diff --git a/packages/overlay/src/inspector/align.ts b/packages/overlay/src/inspector/align.ts index ff37b29..635a04c 100644 --- a/packages/overlay/src/inspector/align.ts +++ b/packages/overlay/src/inspector/align.ts @@ -115,7 +115,7 @@ function tidyPlan(parent: Element): AlignPlan { { property: "gap", value: `${gap}px` }, { property: "align-items", value: "center" }, ], - note: "evens out the grid's spacing", + note: "Evens the grid's spacing", target: "parent", }; } @@ -126,7 +126,7 @@ function tidyPlan(parent: Element): AlignPlan { { property: "gap", value: `${gap}px` }, { property: "align-items", value: "center" }, ], - note: "makes the parent an auto-layout with even spacing", + note: "Makes the parent an auto-layout", target: "parent", }; } @@ -141,7 +141,7 @@ function distributePlan(parent: Element, wantColumn: boolean): AlignPlan { value: "space-between", }, ], - note: "spaces every child in the parent evenly", + note: "Spaces every child evenly", target: "parent", }; } @@ -151,7 +151,7 @@ function distributePlan(parent: Element, wantColumn: boolean): AlignPlan { { property: "flex-direction", value: wantColumn ? "column" : "row" }, { property: "justify-content", value: "space-between" }, ], - note: "spaces every child in the parent evenly", + note: "Spaces every child evenly", target: "parent", }; } @@ -286,7 +286,7 @@ export function planAlign( if (isMainAxis(action, mode)) { return { decls: [{ property: "justify-content", value: JUSTIFY[action] }], - note: "aligns within the parent — moves siblings too", + note: "Moves the siblings too", target: "parent", }; } diff --git a/packages/overlay/src/inspector/controls/num-field.ts b/packages/overlay/src/inspector/controls/num-field.ts index a297438..3064362 100644 --- a/packages/overlay/src/inspector/controls/num-field.ts +++ b/packages/overlay/src/inspector/controls/num-field.ts @@ -531,7 +531,7 @@ export function createNumField( class: scrubbable ? cls("ctl-glyph") : `${cls("ctl-glyph")} ${cls("ctl-glyph-static")}`, - "data-tip": scrubbable ? `${spec.label} — drag to adjust` : spec.label, + "data-tip": scrubbable ? `${spec.label}, drag to adjust` : spec.label, }, glyphText ? [ diff --git a/packages/overlay/src/inspector/descriptors.ts b/packages/overlay/src/inspector/descriptors.ts index c587243..d3ae35a 100644 --- a/packages/overlay/src/inspector/descriptors.ts +++ b/packages/overlay/src/inspector/descriptors.ts @@ -711,9 +711,9 @@ export const MODE_TEXT: Record = { }; export const MODE_NOTE: Record = { - fill: "takes the remaining space", - fixed: "a set length", - hug: "as small as the content allows", + fill: "Takes the remaining space", + fixed: "A set length", + hug: "As small as the content allows", }; /** diff --git a/packages/overlay/src/inspector/sections/appearance.ts b/packages/overlay/src/inspector/sections/appearance.ts index 71309c9..0558c89 100644 --- a/packages/overlay/src/inspector/sections/appearance.ts +++ b/packages/overlay/src/inspector/sections/appearance.ts @@ -52,8 +52,7 @@ export function renderAppearance( // Layer opacity and fill alpha are different things and the panel offers // both, two sections apart. Saying which is which here is cheaper than // letting someone discover it by fading their text along with the box. - cell.dataset.tip = - "Layer opacity — fades children too. Use the fill's % to fade the fill alone"; + cell.dataset.tip = "Layer opacity, children included"; top.append(cell); } // Corner radius is four longhands behind one field with its own mode @@ -101,7 +100,7 @@ export function renderAppearance( { "aria-pressed": String(clipped), class: `${cls("ctl-toggle")}${clipped ? ` ${cls("ctl-toggle-on")}` : ""}`, - "data-tip": "Hide anything that overflows this element's bounds", + "data-tip": "Clip anything outside this element", onClick: () => { const now = readValue(node, "overflow") === "hidden"; ctx.onChange("overflow", now ? "visible" : "hidden"); diff --git a/packages/overlay/src/inspector/sections/auto-layout.ts b/packages/overlay/src/inspector/sections/auto-layout.ts index 73b87f9..e62b792 100644 --- a/packages/overlay/src/inspector/sections/auto-layout.ts +++ b/packages/overlay/src/inspector/sections/auto-layout.ts @@ -279,7 +279,7 @@ function renderGridTracks(ctx: SectionContext, node: Element): HTMLElement { // count-and-size — that would silently destroy it. const custom = createTextField({ glyph, - label: `${kind} — custom track list`, + label: `Custom ${kind} track list`, }); custom.input.value = raw; bindField( diff --git a/packages/overlay/src/inspector/sections/css.ts b/packages/overlay/src/inspector/sections/css.ts index fcc8651..76530e7 100644 --- a/packages/overlay/src/inspector/sections/css.ts +++ b/packages/overlay/src/inspector/sections/css.ts @@ -705,6 +705,6 @@ function computedRow( const BADGE_TIP: Record = { css: "Set by a stylesheet rule", - default: "The value an unstyled element here would have (incl. inherited)", + default: "Browser default, or inherited", inline: "Set inline on the element", }; diff --git a/packages/overlay/src/inspector/sections/media.ts b/packages/overlay/src/inspector/sections/media.ts index 43a891f..176d455 100644 --- a/packages/overlay/src/inspector/sections/media.ts +++ b/packages/overlay/src/inspector/sections/media.ts @@ -323,7 +323,7 @@ function positionRow( }); const field = createTextField({ - label: `${label} — custom`, + label: `Custom ${label.toLowerCase()}`, placeholder: "20% 30%", }); field.input.value = isPreset ? "" : current; diff --git a/packages/overlay/src/inspector/sections/size.ts b/packages/overlay/src/inspector/sections/size.ts index da51785..b0b5861 100644 --- a/packages/overlay/src/inspector/sections/size.ts +++ b/packages/overlay/src/inspector/sections/size.ts @@ -147,8 +147,8 @@ function renderAxisRow( "aria-label": MODE_TEXT[m], class: cls("ctl-seg-btn"), "data-tip": enabled - ? `${MODE_TEXT[m]} — ${MODE_NOTE[m]}` - : `${MODE_TEXT[m]} — needs a parent to fill`, + ? `${MODE_TEXT[m]}. ${MODE_NOTE[m]}` + : `${MODE_TEXT[m]}. Needs a parent to fill`, disabled: enabled ? undefined : "", onClick: enabled ? () => applyMode(m) : undefined, type: "button", @@ -326,7 +326,7 @@ export function renderSize( const open = constrained || state.showBounds; let tip = open ? "Hide min and max" : "Add min and max"; if (constrained) { - tip = "Min and max are set — clear them to hide these"; + tip = "Clear min and max to hide these"; } toggle.replaceChildren(icon(open ? "minus" : "plus", "xs")); toggle.toggleAttribute("disabled", constrained); diff --git a/packages/overlay/src/tooltip.copy.test.ts b/packages/overlay/src/tooltip.copy.test.ts new file mode 100644 index 0000000..92e7e02 --- /dev/null +++ b/packages/overlay/src/tooltip.copy.test.ts @@ -0,0 +1,373 @@ +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { join, sep } from "node:path"; +import { describe, expect, it } from "vitest"; + +/* + * The tooltip copy standard, enforced. + * + * Three rules, and each of them was broken in the tree before this file existed. + * + * **Length.** A tip is a label, not a paragraph. `TIP_MAX_W` is 260px and + * `--ap-font-size-body` is 11px, so one line holds about 44 characters; the + * longest tip in the product was 87 and wrapped to three. + * + * **No em dash.** Roughly thirty tips were built as `X — Y`, where the `Y` was + * usually explaining something the control beside it already showed. The ban is + * on U+2014 only: U+2013 is the right glyph for `lines 12–18` and stays. + * + * **No keyboard marks in the prose.** A tooltip is two spans: `.tip-text` and, + * when `keys.hintFor` finds a binding, a `.tip-key` chip built from `keys.ts`'s + * `DISPLAY` map. Those marks belong in the chip. Two tips spelled them into the + * sentence instead — `"Drag, or ↑↓ to restack"`, and `"Zoom to fit (⇧1)"`, which + * also stopped the real chip resolving, because `hintFor` matches the whole tip + * against a binding's label and no binding is called "Zoom to fit (⇧1)". + * + * **Shortcut chips.** `Tooltips.show` resolves a chord with `keys.hintFor(text)` + * and `keys.hintFor` matches the binding whose *label* equals that string. So a + * tooltip reworded from "Undo" to "Undo the last change" silently loses its ⌘Z — + * nothing throws, nothing renders wrong, the chip is just gone. That is the one + * failure in here that no amount of reading the diff would catch. + * + * Scanned from source rather than asserted against a list, because the point is + * to catch the tip somebody adds next year, not the ones fixed today. + */ + +/** One line at `TIP_MAX_W`, in characters. See the note on the constant. */ +const TIP_MAX_CHARS = 44; + +const EM_DASH = "—"; + +/** + * Marks that belong in the shortcut chip, not in the sentence. + * + * `keys.ts`'s `DISPLAY` map, minus `←` and `→`. Those two are the exception on + * purpose: the change chips build `from → to` readouts, where the arrow is + * notation rather than a key, and banning it would fail seven honest tips to + * catch none. The vertical pair has no such second life. + * + * The middot is not here either, for the same reason. It reads as a key mark in + * `"Drag to move · double-click to rename"` — two sentences wearing punctuation + * from another system, since fixed to a comma — but in `"Button · moved in the + * tree"` it separates a subject from its detail, which is what a middot is for. + * No scan can tell those apart, so this rule does not try. + */ +const KEY_MARKS = /[↑↓⌘⇧⌥⌫⌦↩⏎␣]/u; + +/** + * Binding labels a tooltip can name, and so must keep spelling exactly. + * + * The chip is resolved by string equality between the tip and the binding's + * `label`, so renaming *either* side alone drops it. These are the labels bound + * in `app.ts`, `tools.ts` and `canvas/viewport.ts` that a control also advertises + * as its tip. Renaming one is fine; renaming it here, at the `keys.bind`, and at + * the control in the same commit is the whole requirement. + */ +const CHORD_LABELS = [ + "Undo", + "Redo", + "Delete", + "Duplicate", + "Edit text", + "Add a frame", + "Hand tool", + "Send", + "Move", + "Inspect", + "Zoom in", + "Zoom out", + "Zoom to fit", +]; + +/** + * The subset written out at a `data-tip` site, where this file can see them. + * + * Most controls get their tip through a variable — `iconButton(name, label)`, + * `TOOLS.map(t => t.label)`, `spec.label` — so the string never appears next to + * `data-tip` in the source and a scan cannot check it. These two do appear, and + * they are the ones a copy pass is most likely to reach for and "improve". + */ +const CHORD_TIPS = ["Hand tool", "Send"]; + +/** Everything a comment can hold except the line breaks that keep it aligned. */ +const NON_NEWLINE = /[^\n]/g; + +/** A `label: "…"` literal, wherever it is declared. */ +const LABEL_LITERAL = /label:\s*"([^"]+)"/g; + +/** + * Somewhere a tooltip's text is written, up to and including the assignment. + * + * Several shapes, because `data-tip` is only the last step. Plenty of controls + * build the string first — `const tip = …`, a `tip:` on a `ChangeChip`, a write + * to `dataset.tip` — and those are where the longest and most-interpolated copy + * in the product lives, so scanning only the attribute would miss exactly the + * cases worth catching. `[^=]` on the last alternative keeps `===` out. + * + * `note` is in here for `align.ts`'s `AlignPlan.note`, whose only consumer is the + * tip built in `sections/align-row.ts`. The join site's own literal is just `". "`, + * so without this the note itself — the half that actually carries the words — is + * invisible to both the length and the dash check. + * + * Still outside its reach: `MODE_NOTE` in `descriptors.ts` and `PAINT_NOTE` in + * `vector.ts`, two module constants whose names the lookbehind deliberately + * excludes. Both are interpolated into tips and both are compliant today; a + * regex loose enough to catch them also matches every `NOTE`-suffixed constant + * in the tree, which is a worse trade than auditing two lines by hand. + * + * The `\b` guard is what stops `"data-tip":` matching twice, and a `tip: string` + * in an interface costs nothing: it has no string literal after it to collect. + */ +const TIP_SITE = + /"data-tip"\s*:|\.dataset\.tip\s*=(?!=)|(? existsSync(join(dir, "tooltip.ts"))) as string; + +/** One authored string found in a `data-tip`, and where it was written. */ +interface Tip { + file: string; + line: number; + text: string; +} + +/** + * Ships to a user's page, so the copy standard governs it. + * + * `tsup.config.ts` builds `hook.ts` and `index.ts` and nothing reaches the + * catalogue from either, so `*.stories.ts` and the `stories/` harness beside + * them are development furniture. Their fixtures are deliberately unlike product + * copy — mock page markup, caption prose, specimen strings written *to* be + * overlong — and holding them to a 44-character tooltip rule would either + * fail honestly for no reason or push someone to weaken the rule. + */ +function isProductSource(name: string, path: string): boolean { + return ( + name.endsWith(".ts") && + !( + name.endsWith(".test.ts") || + name.endsWith(".stories.ts") || + path.includes(`${sep}stories${sep}`) + ) + ); +} + +function sourceFiles(dir: string, found: string[] = []): string[] { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isDirectory()) { + sourceFiles(path, found); + } else if (isProductSource(entry.name, path)) { + found.push(path); + } + } + return found; +} + +/** + * Collect the literal text inside one `'…'`, `"…"` or `` `…` ``, from its quote. + * + * Returns the text and the index just past the closing quote. For a template, + * only the chunks *outside* `${ … }` are text — an interpolation contributes + * nothing to review, and the braces may themselves contain nested templates. + */ +function readString(src: string, open: number): { end: number; text: string } { + const quote = src[open]; + let text = ""; + let i = open + 1; + while (i < src.length) { + const ch = src[i]; + if (ch === "\\") { + i += 2; + continue; + } + if (ch === quote) { + return { end: i + 1, text }; + } + if (quote === "`" && ch === "$" && src[i + 1] === "{") { + let depth = 1; + i += 2; + while (i < src.length && depth > 0) { + if (src[i] === "{") { + depth += 1; + } else if (src[i] === "}") { + depth -= 1; + } else if (src[i] === '"' || src[i] === "'" || src[i] === "`") { + i = readString(src, i).end - 1; + } + i += 1; + } + continue; + } + text += ch; + i += 1; + } + return { end: i, text }; +} + +/** + * Collect every string literal in the expression starting at `from`. + * + * Walks to the end of the expression rather than the end of the line: the real + * call sites are ternaries spanning three or four lines (`sections/size.ts`, + * `sections/stroke.ts`, `paint.ts`), and a line-wise regex sees only the first + * branch. Ends at a comma or semicolon outside any bracket, or at the brace that + * closes the object literal the attribute was declared in. + */ +function readExpression(src: string, from: number): string[] { + const literals: string[] = []; + let depth = 0; + let i = from; + while (i < src.length) { + const ch = src[i] as string; + if (ch === '"' || ch === "'" || ch === "`") { + const { end, text } = readString(src, i); + literals.push(text); + i = end; + continue; + } + if (ch === "(" || ch === "[" || ch === "{") { + depth += 1; + } else if (ch === ")" || ch === "]" || ch === "}") { + if (depth === 0) { + return literals; + } + depth -= 1; + } else if (depth === 0 && (ch === "," || ch === ";")) { + return literals; + } + i += 1; + } + return literals; +} + +/** + * Blank every comment, keeping the file the same length. + * + * Without this the scan reads prose. The module comment in `tooltip.ts` explains + * the feature by writing `data-tip="Undo"` in a sentence, which matches a tip + * site and sends `readExpression` off through the rest of the file collecting + * code as copy. Same length in, same length out, and newlines survive inside + * block comments, so the reported line numbers stay true. + */ +function stripComments(src: string): string { + let out = ""; + let i = 0; + while (i < src.length) { + const ch = src[i] as string; + if (ch === '"' || ch === "'" || ch === "`") { + const { end } = readString(src, i); + out += src.slice(i, end); + i = end; + continue; + } + if (ch === "/" && (src[i + 1] === "/" || src[i + 1] === "*")) { + const block = src[i + 1] === "*"; + const close = block ? src.indexOf("*/", i + 2) : src.indexOf("\n", i); + const stop = close === -1 ? src.length : close + (block ? 2 : 0); + out += src.slice(i, stop).replace(NON_NEWLINE, " "); + i = stop; + continue; + } + out += ch; + i += 1; + } + return out; +} + +/** + * Every authored tooltip string in the overlay. + * + * A tip whose value is a bare identifier — `"data-tip": color`, `dataset.tip = + * chip.tip` — contributes nothing and is skipped. That is correct rather than a + * gap: those are exactly the ones carrying a font stack, a stylesheet URL or a + * comment body, which have no length bound anybody can enforce and are why the + * tip wraps in the first place. + */ +function tooltipCopy(): Tip[] { + const tips: Tip[] = []; + for (const path of sourceFiles(SRC)) { + const src = stripComments(readFileSync(path, "utf8")); + const file = path.slice(SRC.length); + for (const match of src.matchAll(TIP_SITE)) { + const at = match.index as number; + const line = src.slice(0, at).split("\n").length; + for (const text of readExpression(src, at + match[0].length)) { + if (text.trim()) { + tips.push({ file, line, text }); + } + } + } + } + return tips; +} + +/** `file:line "text"`, so a failure reads as a worklist. */ +const show = (t: Tip): string => + `${t.file}:${t.line} ${JSON.stringify(t.text)}`; + +const tips = tooltipCopy(); + +describe("tooltip copy", () => { + it("finds the tips to check", () => { + // A scanner that silently matched nothing would make every case below pass. + expect(tips.length).toBeGreaterThan(50); + }); + + it("keeps every tip to one line", () => { + const tooLong = tips + .filter((t) => t.text.length > TIP_MAX_CHARS) + .map(show) + .sort((a, b) => a.localeCompare(b)); + expect(tooLong).toEqual([]); + }); + + it("uses no em dashes", () => { + const dashed = tips + .filter((t) => t.text.includes(EM_DASH)) + .map(show) + .sort((a, b) => a.localeCompare(b)); + expect(dashed).toEqual([]); + }); + + it("keeps keyboard marks out of the prose", () => { + const glyphed = tips + .filter((t) => KEY_MARKS.test(t.text)) + .map(show) + .sort((a, b) => a.localeCompare(b)); + expect(glyphed).toEqual([]); + }); + + it("leaves the tips that name a keybinding alone", () => { + const present = new Set(tips.map((t) => t.text)); + const lost = CHORD_TIPS.filter((label) => !present.has(label)); + expect(lost).toEqual([]); + }); + + it("keeps the keymap spelling those tips the same way", () => { + // The other half of the same contract. `hintFor` compares the tip to the + // binding's `label`, so renaming the binding drops the chip just as surely + // as renaming the tip — and from the keymap side the tooltip looks + // untouched, which is why this is worth its own case. + const declared = new Set(); + for (const path of sourceFiles(SRC)) { + for (const [, label] of readFileSync(path, "utf8").matchAll( + LABEL_LITERAL + )) { + declared.add(label as string); + } + } + const lost = CHORD_LABELS.filter((label) => !declared.has(label)); + expect(lost).toEqual([]); + }); +}); diff --git a/packages/overlay/src/tooltip.stories.ts b/packages/overlay/src/tooltip.stories.ts index 34d455d..806fbbe 100644 --- a/packages/overlay/src/tooltip.stories.ts +++ b/packages/overlay/src/tooltip.stories.ts @@ -77,10 +77,120 @@ function hover(canvasElement: HTMLElement, tip: string): Promise { const instance = new Tooltips(host); onStoryTeardown(() => instance.destroy()); - canvasElement - .querySelector(`[data-tip="${tip}"]`) - ?.dispatchEvent(new PointerEvent("pointerover", { bubbles: true })); - return new Promise((resolve) => setTimeout(resolve, DELAY)); + // Matched against `dataset` rather than through `[data-tip="…"]`, because a + // real tip is not always a safe attribute selector: a font stack carries the + // quotes around `"Segoe UI"`, which closes the selector's own string early and + // throws. Reading the property back is the same lookup without the escaping. + const target = [ + ...canvasElement.querySelectorAll("[data-tip]"), + ].find((node) => node.dataset.tip === tip); + if (!target) { + throw new Error(`No control in this story carries the tip ${tip}`); + } + target.dispatchEvent(new PointerEvent("pointerover", { bubbles: true })); + // `reject`, not a bare `throw`: an exception raised inside the timeout escapes + // the promise entirely, so the story hangs to its 15s timeout and reports that + // instead of the measurement that failed. + return new Promise((resolve, reject) => { + setTimeout(() => { + try { + assertContained(host); + resolve(); + } catch (error) { + reject(error); + } + }, DELAY); + }); +} + +/** The tip node, or a thrown explanation of why there isn't one. */ +function openTip(): { key: HTMLElement | null; node: HTMLElement } { + const host = popoverHost(); + const node = host?.querySelector(`.${cls("tip")}`); + if (!node) { + throw new Error("The tip did not open, so there is nothing to measure."); + } + return { key: node.querySelector(`.${cls("tip-key")}`), node }; +} + +/** + * A tip that runs long stops at three lines rather than growing without bound. + * + * 11px type at `line-height: 1.5` is 16.5px a line, so three lines plus the 4px + * padding and 1px border is around 59px. The unclamped alternative for a comment + * body this size is fourteen lines and 240px of panel — which is the reason the + * clamp is there, and the reason a bare `overflow: hidden` would not do. + */ +function assertClamped(): void { + const { node } = openTip(); + const { height } = node.getBoundingClientRect(); + if (height > 80) { + throw new Error( + `The tip grew to ${Math.round(height)}px; three lines is about 59px, so the line clamp is not applying.` + ); + } +} + +/** + * The chord sits beside the first line of a wrapped tip, not under it. + * + * `flex-wrap: nowrap` on the container is what holds it there and `baseline` is + * what puts it on that first line specifically. Both are easy to lose to a + * well-meaning `align-items: center`, and neither shows up in a width check. + */ +function assertChipOnFirstLine(): void { + const { key, node } = openTip(); + if (!key) { + throw new Error("No chord chip rendered, so `hintFor` found no binding."); + } + const box = node.getBoundingClientRect(); + const chip = key.getBoundingClientRect(); + if (chip.top - box.top > 12) { + throw new Error( + `The chord dropped ${Math.round(chip.top - box.top)}px below the tip's top edge, so it is no longer on the first line.` + ); + } +} + +/** + * The tip's text must sit inside the tip's own background. + * + * The bug this whole module was reworked for, asserted where layout is real: + * `white-space: nowrap` alongside a width cap and no overflow rule let the text + * lay out at its full intrinsic width while the border, background and shadow + * painted at the cap. From about 45 characters up the label hung outside its own + * box, and roughly fifteen tips in the product were over that line. + * + * Checked in `hover`, so it runs for every story in this file rather than only + * the two written about wrapping — and only under `test:browser`, since happy-dom + * has no layout to measure. A pixel of tolerance for subpixel rounding. + */ +function assertContained(host: HTMLElement): void { + const node = host.querySelector(`.${cls("tip")}`); + const text = node?.querySelector(`.${cls("tip-text")}`); + if (!(node && text)) { + throw new Error("The tip did not open, so there is nothing to measure."); + } + const box = node.getBoundingClientRect(); + if (!box.width) { + return; + } + // `scrollWidth` against `clientWidth`, not one rect against the other. The + // rects agree even when this is broken: the span is a flex item, so it takes + // the width the cap allows and the glyphs spill out of it without moving its + // box. Overflowing *content* is the thing that was visible, so it is the thing + // measured. Height is left alone — the line clamp overflows it on purpose. + if (text.scrollWidth > text.clientWidth + 1) { + throw new Error( + `The tip's text runs outside its background: ${text.scrollWidth}px of text in a ${text.clientWidth}px box.` + ); + } + const inner = text.getBoundingClientRect(); + if (inner.right > box.right + 1 || inner.left < box.left - 1) { + throw new Error( + `The tip's text sits outside the tip: text ${Math.round(inner.left)}-${Math.round(inner.right)}, box ${Math.round(box.left)}-${Math.round(box.right)}.` + ); + } } function tipButton(glyph: IconName, tip: string, extra = ""): HTMLElement { @@ -194,6 +304,25 @@ export const InsidePanel: StoryObj = { ), }; +/* + * The four shapes a tooltip's text actually takes. Only the first is copy that + * anyone wrote — the rest are values read off the page, which is why the tip + * wraps instead of ellipsing on one line: for these it *is* the untruncated view + * of a field that already truncated. + */ + +/** Authored copy, at the length the copy standard targets. */ +const SHORT_TIP = "Clip anything outside this element"; +/** A computed font stack, as the Text section shows it. Wraps at its commas. */ +const STACK_TIP = + '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'; +/** A stylesheet URL, as the CSS tab shows it. No spaces anywhere to break at. */ +const URL_TIP = + "https://cdn.example.com/assets/design-system/v4/tokens.generated.css"; +/** A review comment, which is whatever somebody typed into it. */ +const BODY_TIP = + "This card is the only surface in the flow that sets its own radius, and it disagrees with the two beside it. Either pull it back to the token or change all three together, but do not leave it as the odd one out — it reads as a mistake rather than as emphasis, and it is the first thing the eye lands on."; + /** * A control at the right edge of the narrowest dock. * @@ -201,9 +330,15 @@ export const InsidePanel: StoryObj = { * it past the panel's right border — inside the window, outside the panel, and * hanging over nothing. Clamping to the dock first and the viewport second is * what keeps it attached to the thing it names. + * + * The tip is a stylesheet URL rather than a label, and that is the point of the + * case. This story's caption has always said "a long tip", but it used to hover + * `Advanced stroke settings` — 24 characters, comfortably inside the cap — so it + * never once exercised the path it was written to guard. `TIP_MAX_W` and + * `MIN_DOCK_W` are twenty pixels apart, and this is the one place they meet. */ export const AtTheEdge: StoryObj = { - play: ({ canvasElement }) => hover(canvasElement, "Advanced stroke settings"), + play: ({ canvasElement }) => hover(canvasElement, URL_TIP), render: () => plainStage( [ @@ -214,7 +349,7 @@ export const AtTheEdge: StoryObj = { el( "div", { style: "display: flex; justify-content: flex-end;" }, - [tipButton("settings", "Advanced stroke settings")] + [tipButton("settings", URL_TIP)] ) ), ]), @@ -223,7 +358,87 @@ export const AtTheEdge: StoryObj = { ], { try: "the tip must stay inside the dock's rounded border — past it, a label reads as a rendering bug", - what: "A long tip on a control flush with the right edge of a `MIN_DOCK_W` panel.", + what: "A tip wider than the panel, on a control flush with the right edge of a `MIN_DOCK_W` dock.", } ), }; + +/** + * Every length a tip can be, in one panel. + * + * This is the case the old CSS got wrong. It declared `white-space: nowrap` + * beside a width cap and no overflow rule, so the text laid out at its full + * intrinsic width while the border, background and shadow painted at the cap: + * from about 45 characters up, every label sat outside its own box. Roughly + * fifteen tooltips in the product were over that line. + * + * Hover each in turn. The first is one line; the second wraps at its commas; the + * third has nothing to wrap at and leans on `overflow-wrap: anywhere`; the + * fourth runs past three lines and is the only one that ends in an ellipsis. + */ +export const Wrapping: StoryObj = { + play: ({ canvasElement }) => + hover(canvasElement, BODY_TIP).then(assertClamped), + render: () => + plainStage( + [ + dock( + inspectorBody([ + section( + "Appearance", + el("div", { style: "display: grid; gap: 6px;" }, [ + tipButton("crop", SHORT_TIP), + tipButton("style-text", STACK_TIP), + tipButton("code", URL_TIP), + tipButton("comment-message", BODY_TIP), + ]) + ), + ]) + ), + ], + { + try: "compare the font stack with the URL — one wraps at its commas, one has no spaces at all, and both stay inside their own background", + what: "The four text shapes a tip carries. Only the first is copy anyone wrote.", + } + ), +}; + +/** + * A wrapped tip that also carries a chord. + * + * The chip is the one part of a tooltip that is unreadable if it breaks, so it + * is `flex: 0 0 auto` and never wraps, and the text carries `min-width: 0` so the + * text is what gives way instead. The container stays `flex-wrap: nowrap`, which + * is what keeps the chip beside the first line rather than orphaning it onto a + * line of its own under three lines of prose. + */ +export const WrappedWithShortcut: StoryObj = { + play: ({ canvasElement }) => + hover(canvasElement, STACK_TIP).then(assertChipOnFirstLine), + render: () => { + // Bound by label, which is how `hintFor` finds it. The disposer goes to the + // lifecycle registry: `keys` is a singleton, and a story that bound without + // unbinding would leave a live shortcut in every story after it. + onStoryTeardown( + keys.bind({ keys: "mod+alt+f", label: STACK_TIP, run: noop }) + ); + return plainStage( + [ + dock( + inspectorBody([ + section( + "Text", + el("div", { style: "display: grid; gap: 6px;" }, [ + tipButton("style-text", STACK_TIP), + ]) + ), + ]) + ), + ], + { + try: "the chord sits on the first line beside the text, not on a line of its own beneath it, and never breaks after the ⌘", + what: "A tip that wraps *and* carries a shortcut — the two layout rules in the same box.", + } + ); + }, +}; diff --git a/packages/overlay/src/tooltip.test.ts b/packages/overlay/src/tooltip.test.ts new file mode 100644 index 0000000..a528247 --- /dev/null +++ b/packages/overlay/src/tooltip.test.ts @@ -0,0 +1,287 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { cls, el } from "./dom"; +import { sizeOf } from "./inspector/test-support"; +import { keys } from "./keys"; +import { Tooltips } from "./tooltip"; + +/* + * What a tooltip has to get right. + * + * Two of these are regressions rather than features. The tip used to declare + * `white-space: nowrap` next to a width cap, so its text laid out wider than the + * box painted behind it — and `offsetWidth`, which is what the centring and the + * dock clamp are computed from, reported the cap instead of the label. Fixing the + * CSS then exposed a second one: `placePopover` leaves a `left` behind, and a + * box that wraps measures itself inside whatever room that `left` leaves it. The + * cases named "measures" below are those two, and they are the reason this file + * exists at all. + */ + +/** Bind a chord to `label`, undone after the test. `keys` is a singleton. */ +function bindChord(label: string): void { + unbind.push(keys.bind({ keys: "mod+z", label, run: () => undefined })); +} +let unbind: Array<() => void> = []; + +let host: HTMLElement; +let tips: Tooltips; + +/** The shared tip node, as `Tooltips` created it. */ +const tip = (): HTMLElement => + host.querySelector(`.${cls("tip")}`) as HTMLElement; + +const shown = (): boolean => !tip().classList.contains(cls("hidden")); + +/** A control carrying `data-tip`, placed in `parent`. */ +function control(text: string, parent: HTMLElement = document.body) { + const node = el("button", { "data-tip": text, type: "button" }); + parent.append(node); + sizeOf(node, { height: 24, left: 100, top: 400, width: 24 }); + return node; +} + +function hover(node: HTMLElement): void { + node.dispatchEvent(new PointerEvent("pointerover", { bubbles: true })); +} + +/** Report a fixed width, and record the `left` in force when it was read. */ +function stubWidth(node: HTMLElement, width: number): string[] { + const seen: string[] = []; + Object.defineProperty(node, "offsetWidth", { + configurable: true, + get() { + seen.push(node.style.left); + return width; + }, + }); + return seen; +} + +beforeEach(() => { + vi.useFakeTimers(); + // Wide enough that `placePopover`'s viewport clamp never fires: these cases + // are about the dock clamp, and the two are indistinguishable at 1024px. + Object.defineProperty(window, "innerWidth", { + configurable: true, + value: 1440, + }); + Object.defineProperty(window, "innerHeight", { + configurable: true, + value: 900, + }); + host = el("div"); + document.body.append(host); + tips = new Tooltips(host); +}); + +afterEach(() => { + tips.destroy(); + for (const off of unbind) { + off(); + } + unbind = []; + document.body.replaceChildren(); + vi.useRealTimers(); +}); + +describe("opening", () => { + it("waits out the delay before showing", () => { + hover(control("Undo")); + vi.advanceTimersByTime(399); + expect(shown()).toBe(false); + vi.advanceTimersByTime(1); + expect(shown()).toBe(true); + }); + + it("opens the next one instantly while the chain is warm", () => { + hover(control("Undo")); + vi.advanceTimersByTime(400); + + hover(control("Redo")); + // No delay at all: scanning a toolbar should not cost 400ms a button. + vi.advanceTimersByTime(0); + expect(shown()).toBe(true); + expect(tip().textContent).toContain("Redo"); + }); + + it("waits again once the chain has gone cold", () => { + hover(control("Undo")); + vi.advanceTimersByTime(400); + tips.destroy(); + tips = new Tooltips(host); + + vi.advanceTimersByTime(500); + hover(control("Redo")); + vi.advanceTimersByTime(399); + expect(shown()).toBe(false); + }); + + it("ignores a control with no tip", () => { + const bare = el("button", { type: "button" }); + document.body.append(bare); + hover(bare); + vi.advanceTimersByTime(400); + expect(shown()).toBe(false); + }); + + it("declines to show for a control that left the document", () => { + const node = control("Undo"); + hover(node); + node.remove(); + vi.advanceTimersByTime(400); + expect(shown()).toBe(false); + }); +}); + +describe("content", () => { + it("puts the text in the span the line clamp targets", () => { + hover(control("Remove fill")); + vi.advanceTimersByTime(400); + + const text = tip().querySelector(`.${cls("tip-text")}`); + expect(text?.textContent).toBe("Remove fill"); + }); + + it("appends the chord for a tip that names a binding", () => { + bindChord("Undo"); + hover(control("Undo")); + vi.advanceTimersByTime(400); + + expect(tip().querySelector(`.${cls("tip-key")}`)?.textContent).toBeTruthy(); + }); + + it("is text alone when nothing is bound to it", () => { + hover(control("Remove fill")); + vi.advanceTimersByTime(400); + + expect(tip().children).toHaveLength(1); + expect(tip().querySelector(`.${cls("tip-key")}`)).toBeNull(); + }); +}); + +describe("placement", () => { + it("measures from a known origin, not from where it last sat", () => { + // The regression. `placePopover` writes a `left` and never clears it, so a + // tip that wraps would measure itself inside `viewport - previous left`. + const seen = stubWidth(tip(), 260); + + hover(control("Undo")); + vi.advanceTimersByTime(400); + hover(control("Redo")); + vi.advanceTimersByTime(0); + + // Twice per placement, because both modules measure: `Tooltips.place` to + // centre the tip, `placePopover` to clamp it. Each resets `left` first, and + // the count is here so that losing either reset shows up as a failure. + expect(seen).toHaveLength(4); + expect(seen.every((left) => left === "0px")).toBe(true); + }); + + it("stays inside the dock it belongs to", () => { + const dock = el("div", { class: cls("dock") }); + document.body.append(dock); + sizeOf(dock, { height: 600, left: 900, top: 0, width: 280 }); + const node = control("Advanced stroke settings", dock); + sizeOf(node, { height: 24, left: 1150, top: 400, width: 24 }); + stubWidth(tip(), 260); + + hover(node); + vi.advanceTimersByTime(400); + + // Centred on the control would put it at 1032, which hangs past the panel's + // right border with nothing under it. 1180 - 260 - 6 is the last position + // that does not. + expect(tip().style.left).toBe("914px"); + }); + + it("opens below a control in the chrome", () => { + const node = control("Undo"); + stubWidth(tip(), 120); + + hover(node); + vi.advanceTimersByTime(400); + + expect(Number.parseInt(tip().style.top, 10)).toBeGreaterThan(424); + }); + + it("opens above a control in the inspector body", () => { + // Panel rows stack six pixels apart, so a tip below one lands on the row you + // are on your way to. + const body = el("div", { class: cls("insp-body") }); + document.body.append(body); + const node = control("Remove fill", body); + stubWidth(tip(), 120); + + hover(node); + vi.advanceTimersByTime(400); + + expect(Number.parseInt(tip().style.top, 10)).toBeLessThan(400); + }); +}); + +describe("hiding", () => { + const open = (): HTMLElement => { + const node = control("Undo"); + hover(node); + vi.advanceTimersByTime(400); + return node; + }; + + it("hides on a press", () => { + open(); + document.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })); + expect(shown()).toBe(false); + }); + + it("hides when the pointer leaves the window", () => { + const node = open(); + node.dispatchEvent( + new PointerEvent("pointerout", { bubbles: true, relatedTarget: null }) + ); + expect(shown()).toBe(false); + }); + + it("stays up while the pointer moves within the control", () => { + const node = open(); + node.dispatchEvent( + new PointerEvent("pointerout", { bubbles: true, relatedTarget: node }) + ); + expect(shown()).toBe(true); + }); + + it("hides on a scroll rather than following", () => { + open(); + window.dispatchEvent(new Event("scroll")); + expect(shown()).toBe(false); + }); + + it("hides when the pointer reaches something with no tip", () => { + open(); + const bare = el("div"); + document.body.append(bare); + hover(bare); + expect(shown()).toBe(false); + }); +}); + +describe("destroy", () => { + it("takes the node and every listener with it", () => { + const node = tip(); + tips.destroy(); + expect(node.isConnected).toBe(false); + + hover(control("Undo")); + vi.advanceTimersByTime(400); + expect(host.querySelector(`.${cls("tip")}`)).toBeNull(); + }); + + it("cancels a tip that was still counting down", () => { + hover(control("Undo")); + vi.advanceTimersByTime(200); + const node = tip(); + tips.destroy(); + + vi.advanceTimersByTime(400); + expect(node.classList.contains(cls("hidden"))).toBe(true); + }); +}); diff --git a/packages/overlay/src/tooltip.ts b/packages/overlay/src/tooltip.ts index 1f93596..1b54398 100644 --- a/packages/overlay/src/tooltip.ts +++ b/packages/overlay/src/tooltip.ts @@ -128,7 +128,9 @@ export class Tooltips { if (!(text && target.isConnected)) { return; } - this.node.replaceChildren(el("span", { text })); + // The class is a contract, not decoration: it is what the line clamp in + // `pop.css.ts` targets, and a bare span would wrap without ever clamping. + this.node.replaceChildren(el("span", { class: cls("tip-text"), text })); // The shortcut is looked up by the tooltip's own text, so a control and its // binding agree by construction: `data-tip="Undo"` finds the binding @@ -145,6 +147,18 @@ export class Tooltips { /** Centred on the control, kept inside the panel it belongs to. */ private place(anchor: DOMRect): void { + /* + * Measured from a known origin. + * + * `placePopover` writes a `left` and never clears it, and an absolutely + * positioned box with `left` set has only `containing block - left` to lay + * out in. The host is `inset: 0`, so a tip last placed near the right edge + * measures against the sliver beyond it: the text wraps into a narrow column + * and `offsetWidth` reports the column. Under the old `nowrap` this was + * invisible — min-content and max-content were the same number, so the box + * never shrank — which is why it surfaces now and not before. + */ + this.node.style.left = "0px"; const w = this.node.offsetWidth; const bounds = this.bounds(); /*