Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

chore(i18n): add CommandPalette screenshot coverage (#6348)

nynexman446410dd6839aa91
diff --git a/apps/storybook/stories/CommandPalette.stories.tsx b/apps/storybook/stories/CommandPalette.stories.tsx
index ade86f3f8e..63204f3a09 100644
--- a/apps/storybook/stories/CommandPalette.stories.tsx
+++ b/apps/storybook/stories/CommandPalette.stories.tsx
@@ -275,6 +275,53 @@ export const AsyncSearch: Story = {
},
};
+// ─── Built-in strings ────────────────────────────────────────────────────────
+
+/**
+ * Nothing overridden, so every built-in string renders. `bootstrap()` returns
+ * nothing so first open shows the bootstrap empty state, and the async
+ * `search()` keeps the pending state observable.
+ */
+export const BuiltInStrings: Story = {
+ render: function Render() {
+ const [isOpen, setIsOpen] = useState(false);
+ const source = useMemo<SearchSource>(() => {
+ let controller: AbortController | null = null;
+ return {
+ cancel() {
+ controller?.abort();
+ },
+ async search(query: string) {
+ controller?.abort();
+ controller = new AbortController();
+ await new Promise(r => setTimeout(r, 600));
+ const all = [
+ {id: 'home', label: 'Home'},
+ {id: 'settings', label: 'Settings'},
+ {id: 'profile', label: 'Profile'},
+ ];
+ return all.filter(c =>
+ c.label.toLowerCase().includes(query.toLowerCase()),
+ );
+ },
+ bootstrap() {
+ return [];
+ },
+ };
+ }, []);
+ return (
+ <>
+ <Button label="Open" onClick={() => setIsOpen(true)} />
+ <CommandPalette
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ searchSource={source}
+ />
+ </>
+ );
+ },
+};
+
// ─── Keywords ────────────────────────────────────────────────────────────────
/** Type "theme" or "appearance" to find "Toggle Dark Mode". */
diff --git a/internal/scripts/README.md b/internal/scripts/README.md
index 5b5290bfe0..0dae67aec7 100644
--- a/internal/scripts/README.md
+++ b/internal/scripts/README.md
@@ -4,10 +4,10 @@ Internal build-time scripts. Not shipped, not part of any package.
<!-- SYNC: When files in this directory change, update this document. -->
-| File | Purpose |
-| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `upload-crowdin-screenshots.mjs` | Build storybook, capture in-context screenshots for i18n catalog keys, upload to Crowdin, and POST tag positions so each screenshot pixel-links to the matching source string. |
-| `lib/crowdin-strategies.mjs` | Declarative measurement strategies (visibleText, option, placeholder, ariaLabel, chipOperator, filterInput, footerButton, srOnlyLabel, srOnlyReveal) used by the upload script to resolve tag coordinates. |
+| File | Purpose |
+| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `upload-crowdin-screenshots.mjs` | Build storybook, capture in-context screenshots for i18n catalog keys, upload to Crowdin, and POST tag positions so each screenshot pixel-links to the matching source string. |
+| `lib/crowdin-strategies.mjs` | Declarative measurement strategies (visibleText, textRun, option, placeholder, ariaLabel, chipOperator, filterInput, footerButton, srOnlyLabel, srOnlyReveal, liveRegionReveal) used by the upload script to resolve tag coordinates. |
The file-level context Crowdin shows beside every string in the catalog is a
field on the file record, not something `crowdin.yml` can declare; a step in
@@ -58,6 +58,10 @@ Each screenshot is an entry in the `targets` array with:
`t(key, strategyName, ...args)` declares one tag. The strategy is a small function that returns pixel coordinates given the rendered page — see `lib/crowdin-strategies.mjs` for the taxonomy. New strategies are added there when a new measurement pattern comes up.
+### Strings sharing an element with other content
+
+`visibleText` matches an element whose whole text is the string, so it cannot reach a CommandPalette footer hint — `<span><Kbd/>Navigate</span>` reads `↑↓Navigate`. `textRun` matches the bare text node and measures it with a `Range`, tagging the word without the key badge.
+
### Screen-reader-only labels
Some catalog strings are aria-labels on widgets that render no visible text (bare checkboxes, unlabelled comboboxes). Two strategies handle this:
@@ -67,6 +71,12 @@ Some catalog strings are aria-labels on widgets that render no visible text (bar
Reveal bubbles only exist inside the screenshot pipeline — they are never rendered in production. A bubble beside a widget at the edge of the viewport slides along that edge until it fits.
+### Live-region announcements
+
+Strings announced through `useAnnounce()` land in a 1×1 clipped region on `<body>` and clear themselves seconds later, so they have no pixels and no useful position. `liveRegionReveal(text, anchorSelector, placement?)` checks that a region is announcing `text`, then reveals a bubble beside `anchorSelector` — the widget the announcement is about.
+
+Timing matters: the pre-screenshot pass (every strategy in `MUTATING_STRATEGIES`) has to run while the text is still live, and the measurement pass then reads back the rect recorded at injection. A target's `interact` must therefore leave the page inside that window.
+
### A tag has to fit the screenshot
Crowdin rejects a tag rectangle that leaves the uploaded image, so every strategy requires the viewport to contain a candidate's rect. A match below the fold is reported unresolved rather than trimmed or scrolled into view — widen the target's `viewport` if a string you want tagged sits outside it.
diff --git a/internal/scripts/lib/crowdin-strategies.mjs b/internal/scripts/lib/crowdin-strategies.mjs
index d95f1b4db1..d77cc68fa4 100644
--- a/internal/scripts/lib/crowdin-strategies.mjs
+++ b/internal/scripts/lib/crowdin-strategies.mjs
@@ -24,8 +24,14 @@ export const STRATEGY_NAMES = [
'footerButton',
'srOnlyLabel',
'srOnlyReveal',
+ 'textRun',
+ 'liveRegionReveal',
];
+// Strategies that inject a reveal bubble, so they also run before the
+// screenshot. Idempotent: measuring returns the rect recorded at injection.
+export const MUTATING_STRATEGIES = ['srOnlyReveal', 'liveRegionReveal'];
+
// Gap in CSS px between a reveal bubble and the widget it labels — a little
// wider beside the widget than above or below it.
export const REVEAL_BUBBLE_GAP = {block: 4, inline: 6};
@@ -230,6 +236,108 @@ export function browserSideMeasure() {
if (!best) return null;
return {x: best.x, y: best.y, width: best.w, height: best.h};
}
+ // Reveal bubbles — shared by srOnlyReveal and liveRegionReveal. -----------
+
+ // Idempotent: a bubble injected by the pre-screenshot pass reports the
+ // rect recorded when it was placed. That recorded rect is the authority —
+ // re-deriving it from the DOM would have to redo positionBubble's
+ // containing-block correction.
+ function readCachedRect(el) {
+ if (!el) return null;
+ const cx = parseFloat(el.getAttribute('data-crowdin-vx') || '');
+ const cy = parseFloat(el.getAttribute('data-crowdin-vy') || '');
+ const cw = parseFloat(el.getAttribute('data-crowdin-vw') || '');
+ const ch = parseFloat(el.getAttribute('data-crowdin-vh') || '');
+ if (Number.isFinite(cx) && Number.isFinite(cy) &&
+ Number.isFinite(cw) && Number.isFinite(ch)) {
+ return {x: cx, y: cy, width: cw, height: ch};
+ }
+ return null;
+ }
+ function cacheRect(bubble, rect) {
+ bubble.setAttribute('data-crowdin-vx', String(rect.x));
+ bubble.setAttribute('data-crowdin-vy', String(rect.y));
+ bubble.setAttribute('data-crowdin-vw', String(rect.width));
+ bubble.setAttribute('data-crowdin-vh', String(rect.height));
+ }
+ function existingBubbleRect(text) {
+ const existing = document.querySelector(
+ `[data-crowdin-reveal-text="${CSS.escape(text)}"]`,
+ );
+ if (!existing) return undefined;
+ const cached = readCachedRect(existing);
+ if (!cached) return undefined;
+ return inViewport(cached) ? cached : null;
+ }
+ function applyBubbleStyle(bubble, t) {
+ bubble.setAttribute('data-crowdin-reveal', '1');
+ bubble.setAttribute('data-crowdin-reveal-text', t);
+ bubble.textContent = t;
+ const S = bubble.style;
+ S.position = 'fixed';
+ S.background = '#ffe680';
+ S.border = '1px solid #b8860b';
+ S.borderRadius = '4px';
+ S.padding = '2px 6px';
+ S.font =
+ '600 11px system-ui, -apple-system, BlinkMacSystemFont, sans-serif';
+ S.color = '#654200';
+ S.zIndex = '99999';
+ S.whiteSpace = 'nowrap';
+ S.pointerEvents = 'none';
+ S.lineHeight = '14px';
+ }
+ // Place the bubble at `place`, clamped inside the viewport, and return the
+ // rect it occupies in the screenshot. `position: fixed` resolves against a
+ // transformed ancestor or the top layer, not always the viewport, so write
+ // viewport coordinates, read back where the browser painted, and correct
+ // by the difference.
+ function positionBubble(bubble, widgetRect, place) {
+ const b = bubble.getBoundingClientRect();
+ const target = placeRevealBubble(
+ widgetRect,
+ {width: b.width, height: b.height},
+ place,
+ {width: window.innerWidth, height: window.innerHeight},
+ );
+ bubble.style.left = `${target.x}px`;
+ bubble.style.top = `${target.y}px`;
+ const painted = bubble.getBoundingClientRect();
+ const dx = target.x - painted.x;
+ const dy = target.y - painted.y;
+ if (Math.abs(dx) >= 0.5 || Math.abs(dy) >= 0.5) {
+ bubble.style.left = `${target.x + dx}px`;
+ bubble.style.top = `${target.y + dy}px`;
+ }
+ return target;
+ }
+ // Inject one bubble reading `text` beside each widget in `anchors`, and
+ // return the last placed rect. A widget outside the capture gets no
+ // bubble: clamping one into view would park a tag on whatever is at the
+ // edge.
+ function injectRevealBubbles(text, anchors, place) {
+ let lastRect = null;
+ for (const anc of anchors) {
+ const pr = anc.getBoundingClientRect();
+ if (!inViewport(pr)) continue;
+ const bubble = document.createElement('div');
+ applyBubbleStyle(bubble, text);
+ // Native <dialog>.showModal() renders inside the browser's "top
+ // layer" above all other content. Elements in the normal DOM tree are
+ // painted UNDER the dialog regardless of z-index. If the widget is
+ // inside a modal dialog, attach the bubble to that dialog so it also
+ // renders in the top layer.
+ const modalHost =
+ anc.closest('dialog[open]') || anc.closest('[popover]');
+ (modalHost || document.body).appendChild(bubble);
+ const rect = positionBubble(bubble, pr, place);
+ cacheRect(bubble, rect);
+ lastRect = rect;
+ }
+ // A bubble larger than the viewport cannot be placed legally.
+ return inViewport(lastRect) ? lastRect : null;
+ }
+
// Returns true if `el` is the topmost element at its own center — i.e.
// NOT covered by an overlapping popover/dropdown. Guards against
// tagging positions of buttons that are hidden behind an open
@@ -440,37 +548,8 @@ export function browserSideMeasure() {
function srOnlyReveal(text, placement) {
const place = placement || 'right';
- // Idempotent: if a reveal bubble for this text already exists (from
- // a pre-screenshot pass), return the rect recorded when it was
- // placed. That recorded rect is the authority — re-deriving it from
- // the DOM would have to redo positionBubble's containing-block
- // correction.
- function readCachedRect(el) {
- if (!el) return null;
- const cx = parseFloat(el.getAttribute('data-crowdin-vx') || '');
- const cy = parseFloat(el.getAttribute('data-crowdin-vy') || '');
- const cw = parseFloat(el.getAttribute('data-crowdin-vw') || '');
- const ch = parseFloat(el.getAttribute('data-crowdin-vh') || '');
- if (Number.isFinite(cx) && Number.isFinite(cy) &&
- Number.isFinite(cw) && Number.isFinite(ch)) {
- return {x: cx, y: cy, width: cw, height: ch};
- }
- return null;
- }
- function cacheRect(bubble, rect) {
- bubble.setAttribute('data-crowdin-vx', String(rect.x));
- bubble.setAttribute('data-crowdin-vy', String(rect.y));
- bubble.setAttribute('data-crowdin-vw', String(rect.width));
- bubble.setAttribute('data-crowdin-vh', String(rect.height));
- }
-
- const existing = document.querySelector(
- `[data-crowdin-reveal-text="${CSS.escape(text)}"]`,
- );
- if (existing) {
- const cached = readCachedRect(existing);
- if (cached) return inViewport(cached) ? cached : null;
- }
+ const cached = existingBubbleRect(text);
+ if (cached !== undefined) return cached;
// Two match paths (deduped):
// (1) sr-only label/span/aria-hidden element whose textContent is `text`
@@ -526,78 +605,63 @@ export function browserSideMeasure() {
return unique;
}
- function applyBubbleStyle(bubble, t) {
- bubble.setAttribute('data-crowdin-reveal', '1');
- bubble.setAttribute('data-crowdin-reveal-text', t);
- bubble.textContent = t;
- const S = bubble.style;
- S.position = 'fixed';
- S.background = '#ffe680';
- S.border = '1px solid #b8860b';
- S.borderRadius = '4px';
- S.padding = '2px 6px';
- S.font =
- '600 11px system-ui, -apple-system, BlinkMacSystemFont, sans-serif';
- S.color = '#654200';
- S.zIndex = '99999';
- S.whiteSpace = 'nowrap';
- S.pointerEvents = 'none';
- S.lineHeight = '14px';
- }
+ const uniqueWidgets = findWidgetsForRevealText(text);
+ if (uniqueWidgets.length === 0) return null;
- // Place the bubble at `place`, clamped inside the viewport, and
- // return the rect it occupies in the screenshot. `position: fixed`
- // resolves against a transformed ancestor or the top layer, not
- // always the viewport, so write viewport coordinates, read back where
- // the browser painted, and correct by the difference.
- function positionBubble(bubble, widgetRect, place) {
- const b = bubble.getBoundingClientRect();
- const target = placeRevealBubble(
- widgetRect,
- {width: b.width, height: b.height},
- place,
- {width: window.innerWidth, height: window.innerHeight},
- );
- bubble.style.left = `${target.x}px`;
- bubble.style.top = `${target.y}px`;
- const painted = bubble.getBoundingClientRect();
- const dx = target.x - painted.x;
- const dy = target.y - painted.y;
- if (Math.abs(dx) >= 0.5 || Math.abs(dy) >= 0.5) {
- bubble.style.left = `${target.x + dx}px`;
- bubble.style.top = `${target.y + dy}px`;
+ // One bubble per widget, so translators see the reveal for every
+ // occurrence (e.g. "Expand row" on multiple rows).
+ return injectRevealBubbles(text, uniqueWidgets, place);
+ }
+
+ // textRun(text) — Range-measure a bare text node reading `text`, for a
+ // string sharing its element with other content ("↑↓" + "Navigate").
+ function textRun(text) {
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
+ let node;
+ let best = null;
+ while ((node = walker.nextNode())) {
+ const value = node.nodeValue || '';
+ if (value.trim() !== text) continue;
+ const parent = node.parentElement;
+ if (!visible(parent)) continue;
+ const range = document.createRange();
+ // Skip surrounding whitespace so the rect hugs the words.
+ const start = value.indexOf(text);
+ range.setStart(node, start);
+ range.setEnd(node, start + text.length);
+ const r = range.getBoundingClientRect();
+ if (r.width <= 0 || r.height <= 0) continue;
+ if (!inViewport(r)) continue;
+ // Smallest wins, matching findByExactText — the most specific match.
+ if (!best || r.width * r.height < best.width * best.height) {
+ best = {x: r.x, y: r.y, width: r.width, height: r.height};
}
- return target;
}
+ return best;
+ }
- const uniqueWidgets = findWidgetsForRevealText(text);
- if (uniqueWidgets.length === 0) return null;
+ // liveRegionReveal(text, anchorSelector, placement?) — reveal a live
+ // region announcement, which has no pixels, beside the widget it is about.
+ // The announcement is transient, so injection has to happen while it lives.
+ function liveRegionReveal(text, anchorSelector, placement) {
+ const place = placement || 'below';
- // Inject one bubble per widget so translators see the reveal for
- // every occurrence (e.g. "Expand row" on multiple rows).
- let lastRect = null;
- for (const anc of uniqueWidgets) {
- const pr = anc.getBoundingClientRect();
- // A widget outside the capture gets no bubble: clamping one into
- // view would park a tag on whatever is at the edge.
- if (!inViewport(pr)) continue;
- const bubble = document.createElement('div');
- applyBubbleStyle(bubble, text);
- // Native <dialog>.showModal() renders inside the browser's "top
- // layer" above all other content. Elements in the normal DOM tree
- // are painted UNDER the dialog regardless of z-index. If the
- // widget is inside a modal dialog, attach the bubble to that
- // dialog so it also renders in the top layer.
- const modalHost =
- anc.closest('dialog[open]') || anc.closest('[popover]');
- const host = modalHost || document.body;
- host.appendChild(bubble);
- const rect = positionBubble(bubble, pr, place);
- cacheRect(bubble, rect);
- lastRect = rect;
- }
- // A bubble larger than the viewport cannot be placed legally.
- return inViewport(lastRect) ? lastRect : null;
+ const cached = existingBubbleRect(text);
+ if (cached !== undefined) return cached;
+
+ const regions = Array.from(
+ document.querySelectorAll('[aria-live], [role="status"], [role="alert"]'),
+ );
+ if (!regions.some(el => (el.textContent || '').trim() === text)) return null;
+
+ const anchor = anchorSelector
+ ? document.querySelector(anchorSelector)
+ : null;
+ if (!anchor) return null;
+ const widget = expandToMeasurableSelf(anchor, 6);
+ if (!widget) return null;
+
+ return injectRevealBubbles(text, [widget], place);
}
// Dispatcher --------------------------------------------------------------
@@ -611,6 +675,8 @@ export function browserSideMeasure() {
case 'footerButton': return footerButton(args[0]);
case 'srOnlyLabel': return srOnlyLabel(args[0]);
case 'srOnlyReveal': return srOnlyReveal(args[0], args[1]);
+ case 'textRun': return textRun(args[0]);
+ case 'liveRegionReveal': return liveRegionReveal(args[0], args[1], args[2]);
default: return null;
}
};
diff --git a/internal/scripts/upload-crowdin-screenshots.mjs b/internal/scripts/upload-crowdin-screenshots.mjs
index 2349e28a6f..8492c4c605 100644
--- a/internal/scripts/upload-crowdin-screenshots.mjs
+++ b/internal/scripts/upload-crowdin-screenshots.mjs
@@ -53,6 +53,7 @@ import * as path from 'node:path';
import {fileURLToPath} from 'node:url';
import {
buildMeasureSource,
+ MUTATING_STRATEGIES,
STRATEGY_NAMES,
toDevicePixelRect,
} from './lib/crowdin-strategies.mjs';
@@ -215,7 +216,7 @@ function serveStatic(dir) {
//
// Per-strategy convention for which arg slot is the "text" arg:
// visibleText / option / placeholder / ariaLabel / footerButton /
-// srOnlyLabel / srOnlyReveal → args[0]
+// srOnlyLabel / srOnlyReveal / textRun / liveRegionReveal → args[0]
// chipOperator → args[1] (args[0] = field name)
// filterInput → no text arg (kind string only)
const TEXT_ARG_INDEX = {
@@ -228,6 +229,8 @@ const TEXT_ARG_INDEX = {
footerButton: 0,
srOnlyLabel: 0,
srOnlyReveal: 0,
+ textRun: 0,
+ liveRegionReveal: 0,
};
function t(key, strategy, ...args) {
@@ -239,6 +242,13 @@ function t(key, strategy, ...args) {
return {key, strategy, args};
}
+// Every palette capture starts by opening the modal behind the trigger.
+async function openCommandPalette(page) {
+ await page.getByRole('button', {name: 'Open'}).click();
+ await page.waitForSelector('dialog[open]', {timeout: 3000});
+ await page.waitForTimeout(400);
+}
+
const TARGETS = [
// ==========================================================================
// Static (non-popover) targets
@@ -1381,6 +1391,95 @@ const TARGETS = [
t('astryx.typeahead.searchPlaceholder', 'placeholder'),
],
},
+
+ // ==========================================================================
+ // CommandPalette
+ // ==========================================================================
+ // Four moments of one flow on the BuiltInStrings story, which overrides no
+ // string. Each announcement replaces the one before it, so each needs its
+ // own capture.
+ {
+ name: 'commandpalette-bootstrap-empty',
+ storyId: 'core-commandpalette--built-in-strings',
+ viewport: {width: 900, height: 700},
+ interact: openCommandPalette,
+ selector: null,
+ manualTags: [
+ t('astryx.commandPalette.input.placeholder', 'placeholder'),
+ t('astryx.commandPalette.emptyBootstrap', 'visibleText'),
+ // Each hint is `<span><Kbd/>Navigate</span>`, so tag the text node.
+ t('astryx.commandPalette.footer.navigate', 'textRun'),
+ t('astryx.commandPalette.footer.select', 'textRun'),
+ t('astryx.commandPalette.footer.close', 'textRun'),
+ // aria-label only, but on surfaces a translator can see and identify.
+ t('astryx.commandPalette.label', 'ariaLabel'),
+ t('astryx.commandPalette.list.label', 'ariaLabel'),
+ ],
+ },
+ {
+ name: 'commandpalette-no-results',
+ storyId: 'core-commandpalette--built-in-strings',
+ viewport: {width: 900, height: 700},
+ interact: async page => {
+ await openCommandPalette(page);
+ await page.locator('dialog[open] input').first().fill('zzz');
+ await page.waitForTimeout(1100);
+ },
+ selector: null,
+ manualTags: [
+ t('astryx.commandPalette.emptySearch', 'visibleText'),
+ // "No results for {query}" — the story's query is "zzz".
+ t(
+ 'astryx.commandPalette.noResultsFor',
+ 'liveRegionReveal',
+ 'No results for zzz',
+ '.astryx-command-palette-input',
+ 'below',
+ ),
+ ],
+ },
+ {
+ name: 'commandpalette-result-count',
+ storyId: 'core-commandpalette--built-in-strings',
+ viewport: {width: 900, height: 700},
+ interact: async page => {
+ await openCommandPalette(page);
+ await page.locator('dialog[open] input').first().fill('e');
+ await page.waitForTimeout(1100);
+ },
+ selector: null,
+ manualTags: [
+ // All three of the story's commands match "e".
+ t(
+ 'astryx.commandPalette.resultCount',
+ 'liveRegionReveal',
+ '3 results',
+ '.astryx-command-palette-input',
+ 'below',
+ ),
+ ],
+ },
+ {
+ name: 'commandpalette-loading',
+ storyId: 'core-commandpalette--built-in-strings',
+ viewport: {width: 900, height: 700},
+ interact: async page => {
+ await openCommandPalette(page);
+ // Capture inside the story's 600ms in-flight window.
+ await page.locator('dialog[open] input').first().fill('e');
+ await page.waitForTimeout(120);
+ },
+ selector: null,
+ manualTags: [
+ t(
+ 'astryx.commandPalette.loading',
+ 'liveRegionReveal',
+ undefined,
+ '.astryx-command-palette-input',
+ 'below',
+ ),
+ ],
+ },
];
// ---------- validation ----------
@@ -1479,8 +1578,9 @@ async function main() {
// screenshot is captured. Strategies are idempotent: the same call
// during the measurement pass below returns the already-injected
// rect instead of duplicating.
- const revealTags =
- (target.manualTags || []).filter(t => t.strategy === 'srOnlyReveal');
+ const revealTags = (target.manualTags || []).filter(t =>
+ MUTATING_STRATEGIES.includes(t.strategy),
+ );
if (revealTags.length) {
for (const tag of revealTags) {
await page.evaluate(