Files
hyperframes/packages/studio/src/components/editor/InlineTextToolbar.tsx
T
Miguel Ángel 896bc336a2 feat(studio): show every colour of a mixed selection in the swatch (#3144)
* feat(studio): show every colour of a mixed selection in the text swatch

Selecting text painted in more than one colour showed a white swatch. The
toolbar reads a property only when the whole selection agrees on it, which is
right for bold and italic (a toggle is on or off) but wrong for a swatch: with
nothing to report it fell back to the default, so a red-and-green selection
claimed to be white.

The swatch now reads the colours as they run through the selection and draws
one band per run, sized by how many characters carry it. Hard stops, not a
fade — it reports the colours that are there, and a blend would draw colours
that are not. A single-colour selection is a plain swatch, as before, and
picking a colour still applies it to everything selected.

* feat(studio): blend the mixed-colour text swatch instead of banding it

Bands read as two separate swatches sitting next to each other. Each colour
now sits at the middle of its share and the browser fills between them, so the
control looks like one swatch holding a mixed selection.

* fix(studio): keep whitespace out of the text colour swatch

Colouring a whole element and then recolouring one word inside it leaves the
spaces around that word carrying the first colour. The swatch counted them, so
a red word inside green text drew a sliver of green, then red, then green —
the element's colour appearing at an edge where no glyph is painted in it.

Whitespace paints nothing, so it no longer contributes a colour. The swatch
shows the colours the glyphs are actually drawn in, in the order they appear.

* fix(studio): stop the colour swatch repeating its gradient under the border

The swatch grew a green edge on its red side and a red edge on its green side.
`background` maps a gradient to the padding box and then repeats it to fill the
border box, so the 1px ring showed the strip either side of the tile: the
gradient's end colour along the leading edge, its start colour along the
trailing one, both read as a mirrored copy of the swatch.

Painting from the border box instead gives the ring the colour the glyphs next
to it are actually drawn in.

* fix(studio): drop the highlight when a text edit closes

Picking a word with a double press and then clicking away left the word
painted grey. The element was no longer being edited, but the text still read
as selected.

Ending the edit removed contenteditable and blurred the element, and neither
of those drops the browser's own selection. It now clears the selection as
part of the teardown, and only when the selection lives inside the element
being closed — one somewhere else in the preview belongs to whatever put it
there.

* feat(studio): match the mixed-colour swatch to the one in the design tool

The swatch drew a proportional blend along the horizontal: each colour took
the share of the sweep that its characters took of the selection. At 16px that
reads as one muddy smear, and a colour used by a single character is almost
invisible — the opposite of what the control is for, which is answering "which
colours are in here".

It now sweeps diagonally through each distinct colour, evenly spaced, the way
the mixed-colour swatch works in the design tool this sits alongside. A colour
appears once however much text carries it, and the dot itself matches that
reference too: 16px, a 2px ring, and a small lift on hover.

The character counts had no other consumer, so the reader hands back the
distinct colours in document order rather than counting.

* fix(studio): harden mixed-colour text swatches

* refactor(studio): split inline text style readers
2026-08-11 04:26:31 -04:00

282 lines
10 KiB
TypeScript

import { useCallback, useEffect, useState } from "react";
import { applyInlineStyle } from "./inlineTextStyleRange";
import { readInlineStyle, readInlineStyleSpread } from "./inlineTextStyleRead";
import { parseCssColor, toHexColor } from "./colorValue";
import type { InlineTextEditSession } from "../../hooks/useInlineTextEdit";
/**
* The controls for styling the characters selected inside an open text edit.
*
* It lives in Studio's document rather than the composition's, positioned over
* the selection: putting it in the preview would mean injecting Studio's chrome
* into the user's composition, where it would be captured by a render and
* inherit the composition's own styling.
*
* `position: fixed` and viewport coordinates, so it does not have to know which
* of the canvas' several nested coordinate systems it was mounted into.
*/
const READ_PROPERTIES = ["color", "font-weight", "font-style", "text-decoration-line"];
/** Enough above the text to clear it, without leaving the element behind. */
const GAP_PX = 10;
/** h-6 controls + p-1 + the border. Used only to keep an above-toolbar onscreen. */
const TOOLBAR_HEIGHT_PX = 34;
const DEFAULT_COLOR = "#ffffff";
interface ToolbarPlacement {
left: number;
top: number;
placeBelow: boolean;
styles: Record<string, string>;
colours: string[];
pickerColour: string;
}
export function InlineTextToolbar({
session,
iframe,
}: {
session: InlineTextEditSession | null;
iframe: HTMLIFrameElement | null;
}) {
const [placement, setPlacement] = useState<ToolbarPlacement | null>(null);
const refresh = useCallback(() => {
setPlacement(session && iframe ? placeOverSelection(session.element, iframe) : null);
}, [session, iframe]);
// The selection lives in the preview's document, so the event does too.
useEffect(() => {
const doc = session?.element.ownerDocument;
if (!doc) {
setPlacement(null);
return;
}
doc.addEventListener("selectionchange", refresh);
return () => doc.removeEventListener("selectionchange", refresh);
}, [session, refresh]);
const apply = useCallback(
(delta: Record<string, string | null>) => {
const doc = session?.element.ownerDocument;
const selection = doc?.defaultView?.getSelection();
if (!selection || selection.rangeCount === 0) return;
const range = selection.getRangeAt(0);
applyInlineStyle(range, delta);
refresh();
},
[session, refresh],
);
if (!placement) return null;
const styles = placement.styles;
return (
<div
data-inline-text-toolbar="true"
role="toolbar"
aria-label="Text formatting"
className="pointer-events-auto fixed z-[200] flex items-center gap-1 rounded-lg border border-white/10 bg-[#15171c] p-1 shadow-[0_8px_24px_rgba(0,0,0,0.55)]"
style={{
left: placement.left,
top: placement.top,
transform: `translate(-50%, ${placement.placeBelow ? "0" : "-100%"})`,
}}
// Two different things have to be stopped here, and missing either one
// loses the edit the toolbar exists to act on.
//
// The default, because a press anywhere in Studio moves the focus, and
// moving it out of the text collapses the selection being styled.
//
// The propagation, because this renders inside the canvas overlay: a
// press that reaches the canvas is read as a click on the composition,
// which deselects the element and commits the edit out from under the
// button that was just pressed.
onPointerDown={swallow}
onMouseDown={swallow}
onClick={(event) => event.stopPropagation()}
>
<label
className="group relative flex h-6 w-6 cursor-pointer items-center justify-center rounded-md hover:bg-white/10"
title="Text colour"
>
<span
aria-hidden="true"
className="h-4 w-4 rounded-full border-2 border-white/25 transition-transform duration-150 group-hover:scale-110 group-active:scale-95"
// `background` maps a gradient to the PADDING box and then repeats it
// to fill the border box, so the 1px border shows the strip either
// side of the tile: the end colour on the left, the start colour on
// the right. A red-to-green swatch grew a green edge and a red one.
// Set after the shorthand, which resets it.
style={{
background: swatchBackground(placement.colours, styles.color),
backgroundOrigin: "border-box",
}}
/>
{/* `inset-0` is not enough on its own: a colour input carries a
user-agent minimum width, which wins over the right edge and lets
the invisible input spill across the buttons beside it. Hovering
bold then opened the colour picker. The size is pinned instead. */}
<input
type="color"
aria-label="Text colour"
className="absolute inset-0 h-full w-full min-w-0 cursor-pointer opacity-0"
value={placement.pickerColour}
onChange={(event) => apply({ color: event.target.value })}
/>
</label>
<ToolbarToggle
label="Bold"
glyph="B"
bold
on={isBold(styles["font-weight"])}
onToggle={(on) => apply({ "font-weight": on ? "700" : null })}
/>
<ToolbarToggle
label="Italic"
glyph="I"
italic
on={styles["font-style"] === "italic"}
onToggle={(on) => apply({ "font-style": on ? "italic" : null })}
/>
<ToolbarToggle
label="Underline"
glyph="U"
underline
on={styles["text-decoration-line"] === "underline"}
onToggle={(on) => apply({ "text-decoration-line": on ? "underline" : null })}
/>
</div>
);
}
/**
* The selection's colours as one swatch: a diagonal sweep through each distinct
* colour, evenly spaced. A selection with one colour is a plain swatch.
*
* Distinct rather than weighted, and evenly spaced rather than proportional,
* matching the mixed-colour swatch in the design tool this sits alongside. The
* swatch answers "which colours are in here", and at 16px a colour used by one
* character has to be as visible as one used by thirty or it may as well not be
* drawn.
*/
export function swatchBackground(
distinctColours: readonly string[],
agreed: string | undefined,
): string {
if (distinctColours.length === 0) return agreed || DEFAULT_COLOR;
if (distinctColours.length === 1) return distinctColours[0]!;
const stops = distinctColours.map(
(colour, index) => `${colour} ${((index / (distinctColours.length - 1)) * 100).toFixed(2)}%`,
);
return `linear-gradient(135deg, ${stops.join(", ")})`;
}
function swallow(event: { preventDefault: () => void; stopPropagation: () => void }): void {
event.preventDefault();
event.stopPropagation();
}
function ToolbarToggle({
label,
glyph,
on,
onToggle,
bold,
italic,
underline,
}: {
label: string;
glyph: string;
on: boolean;
onToggle: (on: boolean) => void;
bold?: boolean;
italic?: boolean;
underline?: boolean;
}) {
return (
<button
type="button"
title={label}
aria-label={label}
aria-pressed={on}
className={`flex h-6 w-6 items-center justify-center rounded-md text-xs ${
on ? "bg-studio-accent/20 text-studio-accent" : "text-white/70 hover:bg-white/10"
}`}
style={{
fontWeight: bold ? 700 : 400,
fontStyle: italic ? "italic" : "normal",
textDecoration: underline ? "underline" : "none",
}}
onClick={() => onToggle(!on)}
>
{glyph}
</button>
);
}
/** Where the selection is on screen, or null when there is nothing selected. */
function placeOverSelection(
element: HTMLElement,
iframe: HTMLIFrameElement,
): ToolbarPlacement | null {
const doc = element.ownerDocument;
const view = doc.defaultView;
const selection = view?.getSelection();
if (!view || !selection || selection.rangeCount === 0 || selection.isCollapsed) return null;
const range = selection.getRangeAt(0);
if (!element.contains(range.commonAncestorContainer)) return null;
const rect = range.getBoundingClientRect();
// The composition is drawn scaled into the iframe's box, so a point inside it
// is that scale away from a point on Studio's screen. This is the inverse of
// the mapping the canvas uses to turn a press into a caret position.
const box = iframe.getBoundingClientRect();
const scale = view.innerWidth ? box.width / view.innerWidth : 1;
const above = box.top + rect.top * scale - GAP_PX;
const placeBelow = above < TOOLBAR_HEIGHT_PX;
const styles = readInlineStyle(range, READ_PROPERTIES);
const colours = readInlineStyleSpread(range, "color");
return {
left: box.left + (rect.left + rect.width / 2) * scale,
top: placeBelow ? box.top + (rect.top + rect.height) * scale + GAP_PX : above,
placeBelow,
styles,
colours,
pickerColour: toPickerColour(styles.color ?? colours[0], doc),
};
}
function isBold(weight: string | undefined): boolean {
if (!weight) return false;
if (weight === "bold" || weight === "bolder") return true;
return Number.parseInt(weight, 10) >= 600;
}
/** A colour input accepts only `#rrggbb`; normalise any valid CSS colour to it. */
function toPickerColour(value: string | undefined, doc: Document): string {
if (!value) return DEFAULT_COLOR;
const parsed = parseCssColor(value);
if (parsed) return toHexColor(parsed);
// Canvas delegates the full CSS colour grammar to the browser, including
// named colours that the small serialisation parser intentionally omits.
// DOM-only test environments can lack a canvas implementation, in which
// case the picker degrades to its explicit default while the swatch remains
// truthful because CSS still paints the original value.
try {
const context = doc.createElement("canvas").getContext("2d");
if (!context) return DEFAULT_COLOR;
context.fillStyle = DEFAULT_COLOR;
context.fillStyle = value;
const normalised =
typeof context.fillStyle === "string" ? parseCssColor(context.fillStyle) : null;
return normalised ? toHexColor(normalised) : DEFAULT_COLOR;
} catch {
return DEFAULT_COLOR;
}
}