Skip to content

Commit 896bc33

Browse files
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
1 parent 4cc46f5 commit 896bc33

7 files changed

Lines changed: 321 additions & 44 deletions

File tree

‎packages/studio/src/components/editor/InlineTextToolbar.test.tsx‎

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import React, { act } from "react";
44
import { createRoot } from "react-dom/client";
55
import { afterEach, describe, expect, it } from "vitest";
6-
import { InlineTextToolbar } from "./InlineTextToolbar";
6+
import { InlineTextToolbar, swatchBackground } from "./InlineTextToolbar";
77
import type { InlineTextEditSession } from "../../hooks/useInlineTextEdit";
88

99
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -219,7 +219,6 @@ describe("InlineTextToolbar", () => {
219219
expect(toolbar.style.left).toBe(`${100 + (20 + 50) * scale}px`);
220220
expect(toolbar.style.top).toBe(`${50 + 40 * scale - 10}px`);
221221
});
222-
223222
it("moves below a selection that leaves no room above the viewport", () => {
224223
const { element, session, iframe } = scene("hello world");
225224
iframe.getBoundingClientRect = () => ({ left: 0, top: 0, width: 400 }) as DOMRect;
@@ -240,4 +239,58 @@ describe("InlineTextToolbar", () => {
240239
expect(toolbar.style.top).toBe(`${10 * scale + 10}px`);
241240
expect(toolbar.style.transform).toBe("translate(-50%, 0)");
242241
});
242+
243+
it("shows the selection's colours in the swatch when they differ", () => {
244+
const { element, session, iframe } = scene(
245+
'<span style="color: red">Hello</span><span style="color: lime">world</span>',
246+
);
247+
const { host } = render(session, iframe);
248+
249+
selectAll(element);
250+
251+
const swatch = toolbarIn(host)!.querySelector<HTMLElement>("span[aria-hidden]")!;
252+
expect(swatch.style.backgroundImage).toBe("linear-gradient(135deg, red 0.00%, lime 100.00%)");
253+
// Without this the gradient repeats under the border, painting the end
254+
// colour along the leading edge and the start colour along the trailing one.
255+
expect(swatch.style.backgroundOrigin).toBe("border-box");
256+
});
257+
258+
it("shows a plain swatch when the whole selection is one colour", () => {
259+
const { element, session, iframe } = scene('<span style="color: red">Hello world</span>');
260+
const { host } = render(session, iframe);
261+
262+
selectAll(element);
263+
264+
const swatch = toolbarIn(host)!.querySelector<HTMLElement>("span[aria-hidden]")!;
265+
expect(swatch.style.backgroundColor).toBe("red");
266+
});
267+
268+
it("opens the colour input on a shorthand hex selection", () => {
269+
const { element, session, iframe } = scene('<span style="color: #f00">Hello world</span>');
270+
const { host } = render(session, iframe);
271+
272+
selectAll(element);
273+
274+
expect(host.querySelector<HTMLInputElement>('input[type="color"]')?.value).toBe("#ff0000");
275+
});
276+
});
277+
278+
describe("swatchBackground", () => {
279+
it("sweeps through each distinct colour, evenly spaced", () => {
280+
expect(swatchBackground(["red", "lime"], undefined)).toBe(
281+
"linear-gradient(135deg, red 0.00%, lime 100.00%)",
282+
);
283+
expect(swatchBackground(["red", "lime", "cyan"], undefined)).toBe(
284+
"linear-gradient(135deg, red 0.00%, lime 50.00%, cyan 100.00%)",
285+
);
286+
});
287+
288+
it("stays a plain swatch when the selection is one colour", () => {
289+
expect(swatchBackground(["red"], "red")).toBe("red");
290+
});
291+
292+
it("falls back to the agreed colour when the characters carry none", () => {
293+
expect(swatchBackground([], "rgb(1, 2, 3)")).toBe("rgb(1, 2, 3)");
294+
expect(swatchBackground([], undefined)).toBe("#ffffff");
295+
});
243296
});

‎packages/studio/src/components/editor/InlineTextToolbar.tsx‎

Lines changed: 65 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { useCallback, useEffect, useState } from "react";
2-
import { applyInlineStyle, readInlineStyle } from "./inlineTextStyleRange";
2+
import { applyInlineStyle } from "./inlineTextStyleRange";
3+
import { readInlineStyle, readInlineStyleSpread } from "./inlineTextStyleRead";
4+
import { parseCssColor, toHexColor } from "./colorValue";
35
import type { InlineTextEditSession } from "../../hooks/useInlineTextEdit";
46

57
/**
@@ -27,6 +29,8 @@ interface ToolbarPlacement {
2729
top: number;
2830
placeBelow: boolean;
2931
styles: Record<string, string>;
32+
colours: string[];
33+
pickerColour: string;
3034
}
3135

3236
export function InlineTextToolbar({
@@ -94,13 +98,21 @@ export function InlineTextToolbar({
9498
onClick={(event) => event.stopPropagation()}
9599
>
96100
<label
97-
className="relative flex h-6 w-6 cursor-pointer items-center justify-center rounded-md hover:bg-white/10"
101+
className="group relative flex h-6 w-6 cursor-pointer items-center justify-center rounded-md hover:bg-white/10"
98102
title="Text colour"
99103
>
100104
<span
101105
aria-hidden="true"
102-
className="h-3.5 w-3.5 rounded-full border border-white/25"
103-
style={{ background: styles.color || DEFAULT_COLOR }}
106+
className="h-4 w-4 rounded-full border-2 border-white/25 transition-transform duration-150 group-hover:scale-110 group-active:scale-95"
107+
// `background` maps a gradient to the PADDING box and then repeats it
108+
// to fill the border box, so the 1px border shows the strip either
109+
// side of the tile: the end colour on the left, the start colour on
110+
// the right. A red-to-green swatch grew a green edge and a red one.
111+
// Set after the shorthand, which resets it.
112+
style={{
113+
background: swatchBackground(placement.colours, styles.color),
114+
backgroundOrigin: "border-box",
115+
}}
104116
/>
105117
{/* `inset-0` is not enough on its own: a colour input carries a
106118
user-agent minimum width, which wins over the right edge and lets
@@ -110,7 +122,7 @@ export function InlineTextToolbar({
110122
type="color"
111123
aria-label="Text colour"
112124
className="absolute inset-0 h-full w-full min-w-0 cursor-pointer opacity-0"
113-
value={toHexColor(styles.color)}
125+
value={placement.pickerColour}
114126
onChange={(event) => apply({ color: event.target.value })}
115127
/>
116128
</label>
@@ -139,6 +151,28 @@ export function InlineTextToolbar({
139151
);
140152
}
141153

154+
/**
155+
* The selection's colours as one swatch: a diagonal sweep through each distinct
156+
* colour, evenly spaced. A selection with one colour is a plain swatch.
157+
*
158+
* Distinct rather than weighted, and evenly spaced rather than proportional,
159+
* matching the mixed-colour swatch in the design tool this sits alongside. The
160+
* swatch answers "which colours are in here", and at 16px a colour used by one
161+
* character has to be as visible as one used by thirty or it may as well not be
162+
* drawn.
163+
*/
164+
export function swatchBackground(
165+
distinctColours: readonly string[],
166+
agreed: string | undefined,
167+
): string {
168+
if (distinctColours.length === 0) return agreed || DEFAULT_COLOR;
169+
if (distinctColours.length === 1) return distinctColours[0]!;
170+
const stops = distinctColours.map(
171+
(colour, index) => `${colour} ${((index / (distinctColours.length - 1)) * 100).toFixed(2)}%`,
172+
);
173+
return `linear-gradient(135deg, ${stops.join(", ")})`;
174+
}
175+
142176
function swallow(event: { preventDefault: () => void; stopPropagation: () => void }): void {
143177
event.preventDefault();
144178
event.stopPropagation();
@@ -204,11 +238,15 @@ function placeOverSelection(
204238
const above = box.top + rect.top * scale - GAP_PX;
205239
const placeBelow = above < TOOLBAR_HEIGHT_PX;
206240

241+
const styles = readInlineStyle(range, READ_PROPERTIES);
242+
const colours = readInlineStyleSpread(range, "color");
207243
return {
208244
left: box.left + (rect.left + rect.width / 2) * scale,
209245
top: placeBelow ? box.top + (rect.top + rect.height) * scale + GAP_PX : above,
210246
placeBelow,
211-
styles: readInlineStyle(range, READ_PROPERTIES),
247+
styles,
248+
colours,
249+
pickerColour: toPickerColour(styles.color ?? colours[0], doc),
212250
};
213251
}
214252

@@ -218,18 +256,26 @@ function isBold(weight: string | undefined): boolean {
218256
return Number.parseInt(weight, 10) >= 600;
219257
}
220258

221-
/**
222-
* A colour input only accepts `#rrggbb`, and what the page reports is whatever
223-
* the stylesheet said. An unreadable value opens the picker on white rather
224-
* than refusing to open.
225-
*/
226-
function toHexColor(value: string | undefined): string {
259+
/** A colour input accepts only `#rrggbb`; normalise any valid CSS colour to it. */
260+
function toPickerColour(value: string | undefined, doc: Document): string {
227261
if (!value) return DEFAULT_COLOR;
228-
if (/^#[0-9a-f]{6}$/i.test(value)) return value;
229-
const channels = value.match(/\d+(\.\d+)?/g);
230-
if (!channels || channels.length < 3) return DEFAULT_COLOR;
231-
return `#${channels
232-
.slice(0, 3)
233-
.map((channel) => Number(channel).toString(16).padStart(2, "0"))
234-
.join("")}`;
262+
const parsed = parseCssColor(value);
263+
if (parsed) return toHexColor(parsed);
264+
265+
// Canvas delegates the full CSS colour grammar to the browser, including
266+
// named colours that the small serialisation parser intentionally omits.
267+
// DOM-only test environments can lack a canvas implementation, in which
268+
// case the picker degrades to its explicit default while the swatch remains
269+
// truthful because CSS still paints the original value.
270+
try {
271+
const context = doc.createElement("canvas").getContext("2d");
272+
if (!context) return DEFAULT_COLOR;
273+
context.fillStyle = DEFAULT_COLOR;
274+
context.fillStyle = value;
275+
const normalised =
276+
typeof context.fillStyle === "string" ? parseCssColor(context.fillStyle) : null;
277+
return normalised ? toHexColor(normalised) : DEFAULT_COLOR;
278+
} catch {
279+
return DEFAULT_COLOR;
280+
}
235281
}

‎packages/studio/src/components/editor/inlineTextStyleRange.test.ts‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
// @vitest-environment happy-dom
22

33
import { afterEach, describe, expect, it, vi } from "vitest";
4-
import { applyInlineStyle, readInlineStyle } from "./inlineTextStyleRange";
4+
import { applyInlineStyle } from "./inlineTextStyleRange";
5+
import { readInlineStyle, readInlineStyleSpread } from "./inlineTextStyleRead";
56

67
afterEach(() => {
78
vi.restoreAllMocks();
@@ -697,3 +698,46 @@ describe("applyInlineStyle when something else is painting the glyphs", () => {
697698
expect(host.innerHTML).not.toContain("-webkit-text-fill-color");
698699
});
699700
});
701+
702+
describe("readInlineStyleSpread", () => {
703+
it("reports every distinct colour in the selection, in order", () => {
704+
const host = mount(
705+
'<span style="color: red">Hello</span><span style="color: lime">world</span>',
706+
);
707+
708+
expect(readInlineStyleSpread(rangeOver(host, 0, 10), "color")).toEqual(["red", "lime"]);
709+
});
710+
711+
it("reports a colour once, however many characters carry it", () => {
712+
const host = mount('<span style="color: red">He</span><span style="color: red">llo</span>');
713+
714+
expect(readInlineStyleSpread(rangeOver(host, 0, 5), "color")).toEqual(["red"]);
715+
});
716+
717+
it("reports only what the selection covers", () => {
718+
const host = mount(
719+
'<span style="color: red">Hello</span><span style="color: lime">world</span>',
720+
);
721+
722+
expect(readInlineStyleSpread(rangeOver(host, 6, 10), "color")).toEqual(["lime"]);
723+
});
724+
725+
it("ignores whitespace, which shows no colour at all", () => {
726+
// Colour the whole element, then recolour one word: the whitespace around it
727+
// keeps the first colour. It paints no glyph, so counting it puts a band of a
728+
// colour nothing on screen is painted in at the edge of the swatch.
729+
const host = mount(
730+
'<span style="color: lime"> </span>' +
731+
'<span style="color: red">Hello</span>' +
732+
'<span style="color: lime"> world</span>',
733+
);
734+
735+
expect(readInlineStyleSpread(rangeOver(host, 0, 12), "color")).toEqual(["red", "lime"]);
736+
});
737+
738+
it("is empty when the characters carry no colour of their own", () => {
739+
const host = mount("Hello world");
740+
741+
expect(readInlineStyleSpread(rangeOver(host, 0, 5), "color")).toEqual([]);
742+
});
743+
});

‎packages/studio/src/components/editor/inlineTextStyleRange.ts‎

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -182,31 +182,23 @@ function holdsBothEnds(host: Element, range: Range): boolean {
182182
return host.contains(range.startContainer) && host.contains(range.endContainer);
183183
}
184184

185-
/**
186-
* What the range is styled with, for a toolbar that has to open showing the
187-
* truth rather than a default. Reports a property only when the whole range
188-
* agrees about it, which is what a control can honestly display.
189-
*/
190-
export function readInlineStyle(range: Range, properties: string[]): Record<string, string> {
185+
export interface InlineStyleChar {
186+
char: string;
187+
style: Readonly<Record<string, string>>;
188+
}
189+
190+
/** Every character the range covers with its style, or null when it covers none. */
191+
export function readCoveredInlineStyleChars(range: Range): readonly InlineStyleChar[] | null {
191192
const host = editingHost(range.startContainer);
192-
if (!host || !holdsBothEnds(host, range)) return {};
193+
if (!host || !holdsBothEnds(host, range)) return null;
193194
const start = offsetOf(host, range.startContainer, range.startOffset);
194195
const end = offsetOf(host, range.endContainer, range.endOffset);
195-
if (start === null || end === null) return {};
196-
196+
if (start === null || end === null) return null;
197197
const collapsed = start === end;
198198
const covered = charRuns(readRuns(host))
199199
.slice(collapsed ? Math.max(0, start - 1) : start, collapsed ? Math.max(1, start) : end)
200-
.map((entry) => entry.style);
201-
if (covered.length === 0) return {};
202-
203-
const styles: Record<string, string> = {};
204-
for (const property of properties) {
205-
const first = covered[0]?.[property];
206-
if (first === undefined) continue;
207-
if (covered.every((style) => style[property] === first)) styles[property] = first;
208-
}
209-
return styles;
200+
.map((entry) => ({ char: entry.char, style: entry.style }));
201+
return covered.length > 0 ? covered : null;
210202
}
211203

212204
/**
@@ -309,11 +301,18 @@ function ownStyle(element: HTMLElement): Record<string, string> {
309301
}
310302

311303
/** One entry per character, which is the easiest thing to slice and compare. */
312-
function charRuns(runs: StyledRun[]): Array<Omit<StyledRun, "text">> {
313-
const perChar: Array<Omit<StyledRun, "text">> = [];
304+
function charRuns(runs: StyledRun[]): Array<Omit<StyledRun, "text"> & { char: string }> {
305+
const perChar: Array<Omit<StyledRun, "text"> & { char: string }> = [];
314306
for (const run of runs) {
307+
// By UTF-16 unit, not code point: `restyle` indexes this list with selection
308+
// offsets, which count units, so an emoji has to stay two entries long.
315309
for (let index = 0; index < run.text.length; index += 1) {
316-
perChar.push({ style: run.style, origin: run.origin, identity: run.identity });
310+
perChar.push({
311+
char: run.text[index] ?? "",
312+
style: run.style,
313+
origin: run.origin,
314+
identity: run.identity,
315+
});
317316
}
318317
}
319318
return perChar;
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { readCoveredInlineStyleChars } from "./inlineTextStyleRange";
2+
3+
/**
4+
* What the range is styled with, for a toolbar that has to open showing the
5+
* truth rather than a default. Reports a property only when the whole range
6+
* agrees about it, which is what a control can honestly display.
7+
*/
8+
export function readInlineStyle(range: Range, properties: string[]): Record<string, string> {
9+
const chars = readCoveredInlineStyleChars(range);
10+
if (!chars) return {};
11+
12+
const styles: Record<string, string> = {};
13+
for (const property of properties) {
14+
const first: string | undefined = chars[0]?.style[property];
15+
if (first === undefined) continue;
16+
if (chars.every(({ style }) => style[property] === first)) styles[property] = first;
17+
}
18+
return styles;
19+
}
20+
21+
/**
22+
* The distinct values one property takes across the range, in document order:
23+
* `["red", "lime"]`.
24+
*
25+
* `readInlineStyle` above answers "what is this range" and reports nothing when
26+
* the range disagrees with itself — right for a toggle, which can only be on or
27+
* off. A swatch can show more than one value at once, and showing the default
28+
* instead reads as "this text is white" when none of it is.
29+
*/
30+
export function readInlineStyleSpread(range: Range, property: string): string[] {
31+
const covered = readCoveredInlineStyleChars(range);
32+
if (!covered) return [];
33+
const seen = new Set<string>();
34+
const spread: string[] = [];
35+
for (const { char, style } of covered) {
36+
// A space paints nothing, so the colour it inherits is not a colour anyone
37+
// can see. Counting it puts the element's own colour in the swatch for text
38+
// that shows none of it — the stray band on a selection that happens to
39+
// start or end next to a space.
40+
if (!char.trim()) continue;
41+
const value = style[property];
42+
if (value === undefined || seen.has(value)) continue;
43+
seen.add(value);
44+
spread.push(value);
45+
}
46+
return spread;
47+
}

0 commit comments

Comments
 (0)