Skip to content

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

TypeScript

feat(ci): add Crowdin screenshot upload script + expand PowerSearchWithTable story (#4215)

nynexman4464d41e590e7034
diff --git a/apps/storybook/stories/PowerSearchWithTable.stories.tsx b/apps/storybook/stories/PowerSearchWithTable.stories.tsx
index 602c04acc4..5aa5edd282 100644
--- a/apps/storybook/stories/PowerSearchWithTable.stories.tsx
+++ b/apps/storybook/stories/PowerSearchWithTable.stories.tsx
@@ -2,10 +2,18 @@
import {useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
-import {PowerSearch, usePowerSearchConfig} from '@astryxdesign/core/PowerSearch';
-import type {PowerSearchFilter} from '@astryxdesign/core/PowerSearch';
+import {
+ PowerSearch,
+ usePowerSearchConfig,
+} from '@astryxdesign/core/PowerSearch';
+import type {
+ PowerSearchConfig,
+ PowerSearchField,
+ PowerSearchFilter,
+} from '@astryxdesign/core/PowerSearch';
import {Table, pixel, proportional} from '@astryxdesign/core/Table';
import type {TableColumn} from '@astryxdesign/core/Table';
+import type {SearchSource, SearchableItem} from '@astryxdesign/core/Typeahead';
// =============================================================================
// Field definitions
@@ -22,13 +30,70 @@ const genreValues = [
{value: 'history', label: 'History'},
];
+const themeValues = [
+ {value: 'coming-of-age', label: 'Coming of Age'},
+ {value: 'dystopia', label: 'Dystopia'},
+ {value: 'love', label: 'Love'},
+ {value: 'war', label: 'War'},
+ {value: 'identity', label: 'Identity'},
+ {value: 'adventure', label: 'Adventure'},
+];
+
const fieldDefs = [
{key: 'title', type: 'string', label: 'Title'},
{key: 'author', type: 'string', label: 'Author'},
{key: 'year', type: 'number', label: 'Publication Year'},
{key: 'genre', type: 'enum', label: 'Genre', enumValues: genreValues},
+ {key: 'published', type: 'date', label: 'Published Date'},
+ {key: 'inStock', type: 'boolean', label: 'In Stock'},
+ {key: 'discontinued', type: 'boolean', label: 'Discontinued'},
+ {key: 'tags', type: 'string_list', label: 'Tags'},
+ {key: 'themes', type: 'enum_list', label: 'Themes', enumValues: themeValues},
] as const;
+// -----------------------------------------------------------------------------
+// Author entity source (entity field must be added manually — the config hook
+// only supports the 7 built-in shorthand types). We build a PowerSearchField
+// manually and merge it into the config below.
+// -----------------------------------------------------------------------------
+
+const authorEntities: SearchableItem[] = [
+ {id: 'author-herbert', label: 'Frank Herbert'},
+ {id: 'author-austen', label: 'Jane Austen'},
+ {id: 'author-fitzgerald', label: 'F. Scott Fitzgerald'},
+ {id: 'author-orwell', label: 'George Orwell'},
+ {id: 'author-lee', label: 'Harper Lee'},
+ {id: 'author-tolkien', label: 'J.R.R. Tolkien'},
+ {id: 'author-harari', label: 'Yuval Noah Harari'},
+ {id: 'author-rothfuss', label: 'Patrick Rothfuss'},
+];
+
+const authorSource: SearchSource = {
+ search: (query: string) =>
+ authorEntities.filter(a =>
+ a.label.toLowerCase().includes(query.toLowerCase()),
+ ),
+ bootstrap: () => authorEntities,
+};
+
+const authorEntityField: PowerSearchField = {
+ key: 'authorEntity',
+ label: 'Author (entity)',
+ defaultOperator: 'is_any_of',
+ operators: [
+ {
+ key: 'is_any_of',
+ i18nKey: '@astryx.powersearch.operator.isAnyOf',
+ value: {type: 'entity_list', searchSource: authorSource},
+ },
+ {
+ key: 'is_none_of',
+ i18nKey: '@astryx.powersearch.operator.isNoneOf',
+ value: {type: 'entity_list', searchSource: authorSource},
+ },
+ ],
+};
+
// =============================================================================
// Sample data
// =============================================================================
@@ -39,8 +104,17 @@ interface Book extends Record<string, unknown> {
author: string;
year: number;
genre: string;
+ published: Date;
+ inStock: boolean;
+ discontinued: boolean;
+ tags: ReadonlyArray<string>;
+ themes: ReadonlyArray<string>;
}
+// Helper to make a Date from a year for the sample data.
+const dateOf = (year: number, month = 1, day = 1) =>
+ new Date(year, month - 1, day);
+
const books: Book[] = [
{
id: '1',
@@ -48,6 +122,11 @@ const books: Book[] = [
author: 'Frank Herbert',
year: 1965,
genre: 'sci-fi',
+ published: dateOf(1965, 8, 1),
+ inStock: true,
+ discontinued: false,
+ tags: ['classic', 'award-winner', 'series'],
+ themes: ['adventure', 'identity'],
},
{
id: '2',
@@ -55,6 +134,11 @@ const books: Book[] = [
author: 'Jane Austen',
year: 1813,
genre: 'romance',
+ published: dateOf(1813, 1, 28),
+ inStock: true,
+ discontinued: true,
+ tags: ['classic', 'bestseller'],
+ themes: ['love', 'identity'],
},
{
id: '3',
@@ -62,6 +146,11 @@ const books: Book[] = [
author: 'F. Scott Fitzgerald',
year: 1925,
genre: 'fiction',
+ published: dateOf(1925, 4, 10),
+ inStock: true,
+ discontinued: false,
+ tags: ['classic', 'staff-pick'],
+ themes: ['love', 'identity'],
},
{
id: '4',
@@ -69,6 +158,11 @@ const books: Book[] = [
author: 'George Orwell',
year: 1949,
genre: 'sci-fi',
+ published: dateOf(1949, 6, 8),
+ inStock: false,
+ discontinued: true,
+ tags: ['classic', 'bestseller'],
+ themes: ['dystopia', 'identity'],
},
{
id: '5',
@@ -76,6 +170,11 @@ const books: Book[] = [
author: 'Harper Lee',
year: 1960,
genre: 'fiction',
+ published: dateOf(1960, 7, 11),
+ inStock: true,
+ discontinued: false,
+ tags: ['classic', 'award-winner'],
+ themes: ['coming-of-age', 'identity'],
},
{
id: '6',
@@ -83,6 +182,11 @@ const books: Book[] = [
author: 'J.R.R. Tolkien',
year: 1937,
genre: 'fantasy',
+ published: dateOf(1937, 9, 21),
+ inStock: true,
+ discontinued: false,
+ tags: ['classic', 'series'],
+ themes: ['adventure'],
},
{
id: '7',
@@ -90,6 +194,11 @@ const books: Book[] = [
author: 'Yuval Noah Harari',
year: 2011,
genre: 'non-fiction',
+ published: dateOf(2011, 1, 1),
+ inStock: true,
+ discontinued: false,
+ tags: ['bestseller', 'staff-pick'],
+ themes: ['identity'],
},
{
id: '8',
@@ -97,6 +206,11 @@ const books: Book[] = [
author: 'Patrick Rothfuss',
year: 2007,
genre: 'fantasy',
+ published: dateOf(2007, 3, 27),
+ inStock: false,
+ discontinued: true,
+ tags: ['series', 'staff-pick'],
+ themes: ['adventure', 'coming-of-age'],
},
{
id: '9',
@@ -104,6 +218,11 @@ const books: Book[] = [
author: 'Gillian Flynn',
year: 2012,
genre: 'mystery',
+ published: dateOf(2012, 6, 5),
+ inStock: true,
+ discontinued: false,
+ tags: ['bestseller'],
+ themes: ['love', 'identity'],
},
{
id: '10',
@@ -111,6 +230,11 @@ const books: Book[] = [
author: 'Walter Isaacson',
year: 2011,
genre: 'biography',
+ published: dateOf(2011, 10, 24),
+ inStock: true,
+ discontinued: true,
+ tags: ['bestseller'],
+ themes: ['identity'],
},
{
id: '11',
@@ -118,6 +242,11 @@ const books: Book[] = [
author: 'Stephen Hawking',
year: 1988,
genre: 'non-fiction',
+ published: dateOf(1988, 4, 1),
+ inStock: false,
+ discontinued: false,
+ tags: ['classic', 'staff-pick'],
+ themes: ['identity'],
},
{
id: '12',
@@ -125,6 +254,11 @@ const books: Book[] = [
author: 'Stephen King',
year: 1977,
genre: 'mystery',
+ published: dateOf(1977, 1, 28),
+ inStock: true,
+ discontinued: false,
+ tags: ['classic'],
+ themes: ['identity'],
},
{
id: '13',
@@ -132,6 +266,11 @@ const books: Book[] = [
author: 'Margaret Atwood',
year: 1985,
genre: 'sci-fi',
+ published: dateOf(1985, 8, 17),
+ inStock: true,
+ discontinued: false,
+ tags: ['award-winner', 'series'],
+ themes: ['dystopia', 'identity'],
},
{
id: '14',
@@ -139,6 +278,11 @@ const books: Book[] = [
author: 'Diana Gabaldon',
year: 1991,
genre: 'romance',
+ published: dateOf(1991, 6, 1),
+ inStock: true,
+ discontinued: true,
+ tags: ['series', 'bestseller'],
+ themes: ['love', 'adventure', 'war'],
},
{
id: '15',
@@ -146,20 +290,37 @@ const books: Book[] = [
author: 'Barbara Tuchman',
year: 1962,
genre: 'history',
+ published: dateOf(1962, 1, 1),
+ inStock: false,
+ discontinued: false,
+ tags: ['classic', 'award-winner'],
+ themes: ['war'],
},
];
const columns: TableColumn<Book>[] = [
{key: 'title', header: 'Title', width: proportional(2)},
{key: 'author', header: 'Author', width: proportional(2)},
- {key: 'year', header: 'Year', width: pixel(100)},
+ {key: 'year', header: 'Year', width: pixel(80)},
{
key: 'genre',
header: 'Genre',
- width: pixel(140),
+ width: pixel(120),
renderCell: (book: Book) =>
genreValues.find(g => g.value === book.genre)?.label ?? book.genre,
},
+ {
+ key: 'published',
+ header: 'Published',
+ width: pixel(120),
+ renderCell: (book: Book) => book.published.toLocaleDateString(),
+ },
+ {
+ key: 'inStock',
+ header: 'In Stock',
+ width: pixel(90),
+ renderCell: (book: Book) => (book.inStock ? 'Yes' : 'No'),
+ },
];
// =============================================================================
@@ -171,7 +332,7 @@ const meta: Meta = {
tags: ['autodocs'],
decorators: [
Story => (
- <div style={{width: 800}}>
+ <div style={{width: 1000}}>
<Story />
</div>
),
@@ -234,3 +395,82 @@ export const WithPresetFilters: Story = {
);
},
};
+
+// -----------------------------------------------------------------------------
+// WithMixedFilters — one preset filter of each new field type.
+//
+// The i18n operator labels come from `usePowerSearchConfig` (built-in). The
+// entity field is added manually (see `authorEntityField` above) because the
+// shorthand config hook doesn't have an entity type — its operators still use
+// the same @astryx.powersearch.operator.* i18n keys as enum_list.
+// -----------------------------------------------------------------------------
+export const WithMixedFilters: Story = {
+ render: () => {
+ const {config: baseConfig, applyFilters} = usePowerSearchConfig(
+ fieldDefs,
+ 'Books',
+ );
+ const config: PowerSearchConfig = {
+ ...baseConfig,
+ fields: [...baseConfig.fields, authorEntityField],
+ };
+ const [filters, setFilters] = useState<PowerSearchFilter[]>([
+ {
+ field: 'published',
+ operator: 'after',
+ value: {
+ type: 'date_absolute',
+ unixSeconds: Math.floor(new Date('1970-01-01').getTime() / 1000),
+ },
+ },
+ {
+ field: 'inStock',
+ operator: 'is_true',
+ value: {type: 'empty'},
+ },
+ {
+ field: 'discontinued',
+ operator: 'is_false',
+ value: {type: 'empty'},
+ },
+ {
+ field: 'tags',
+ operator: 'is_any_of',
+ value: {type: 'string_list', value: ['classic']},
+ },
+ {
+ field: 'themes',
+ operator: 'is_any_of',
+ value: {type: 'enum_list', value: ['identity']},
+ },
+ {
+ field: 'authorEntity',
+ operator: 'is_any_of',
+ value: {
+ type: 'entity_list',
+ value: [{id: 'author-tolkien', label: 'J.R.R. Tolkien'}],
+ },
+ },
+ ]);
+ const filteredBooks = applyFilters(filters, books);
+
+ return (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={newFilters => setFilters([...newFilters])}
+ placeholder="Mixed filters..."
+ resultCount={filteredBooks.length}
+ />
+ <Table
+ data={filteredBooks}
+ columns={columns}
+ idKey="id"
+ hasHover
+ isStriped
+ />
+ </div>
+ );
+ },
+};
diff --git a/internal/README.md b/internal/README.md
index c4c74953e8..5a16cd38c1 100644
--- a/internal/README.md
+++ b/internal/README.md
@@ -4,7 +4,8 @@ Internal tooling packages not published to npm.
<!-- SYNC: When files in this directory change, update this document. -->
-| Directory | Role | Purpose |
-| ------------- | ------- | ------------------------------------------------- |
-| `test-utils/` | Testing | Shared testing utilities and setup for Vitest |
-| `vibe-tests/` | Testing | LLM vibeability test harness for component system |
+| Directory | Role | Purpose |
+| ------------- | ------- | ------------------------------------------------------------ |
+| `scripts/` | Tooling | One-off automation scripts (Crowdin screenshot upload, etc.) |
+| `test-utils/` | Testing | Shared testing utilities and setup for Vitest |
+| `vibe-tests/` | Testing | LLM vibeability test harness for component system |
diff --git a/internal/scripts/.gitignore b/internal/scripts/.gitignore
new file mode 100644
index 0000000000..dc883552a6
--- /dev/null
+++ b/internal/scripts/.gitignore
@@ -0,0 +1,2 @@
+# Local output from upload-crowdin-screenshots.mjs
+output/
diff --git a/internal/scripts/README.md b/internal/scripts/README.md
new file mode 100644
index 0000000000..388420dcac
--- /dev/null
+++ b/internal/scripts/README.md
@@ -0,0 +1,76 @@
+# /internal/scripts
+
+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. |
+
+## upload-crowdin-screenshots.mjs
+
+Automates the "screenshot with in-context tags" flow for [Crowdin](https://crowdin.com/), the translation platform used by astryx.
+
+Translators see each catalog key alongside a real screenshot of where it appears in the UI. Boxes on the screenshot mark exactly which pixels correspond to which key. This dramatically reduces "what does this string mean?" back-and-forth.
+
+### Usage
+
+```bash
+CROWDIN_PERSONAL_TOKEN=xxx CROWDIN_PROJECT_ID=nnn \
+ node internal/scripts/upload-crowdin-screenshots.mjs [flags]
+```
+
+Common flags:
+
+| Flag | Purpose |
+| ---------------- | --------------------------------------------------------------------------------------------------- |
+| `--dry-run` | Capture screenshots + resolve tag coordinates, but skip Crowdin upload. |
+| `--validate` | Verify every declared tag key exists in `packages/core/locales/en.json`, then exit. |
+| `--skip-build` | Reuse existing `apps/storybook/dist/` build. |
+| `--only=<name>` | Comma-separated target names to run (e.g. `--only=dialog-close-button,banner-dismissable`). |
+| `--replace-tags` | For existing Crowdin screenshots, delete previously POSTed tags before uploading fresh coordinates. |
+| `--delete-first` | Delete the entire screenshot record on Crowdin (id + tags) before re-uploading. |
+
+Tokens: personal API token from https://crowdin.com/settings#api-key. Project ID is the numeric ID visible in the Crowdin URL.
+
+### How targets are declared
+
+Each screenshot is an entry in the `targets` array with:
+
+```js
+{
+ name: 'dialog-close-button',
+ storyId: 'core-dialog--default',
+ viewport: {width: 900, height: 700},
+ interact: async page => { /* optional Playwright interaction */ },
+ selector: null, // or CSS selector to crop to
+ manualTags: [
+ t('astryx.dialog.close', 'ariaLabel', 'Close'),
+ ],
+}
+```
+
+`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.
+
+### 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:
+
+- `srOnlyLabel` — tag rect lands on the visible ancestor widget. Best when the widget has some other identifying feature (icon, adjacent text).
+- `srOnlyReveal` — injects a small yellow label bubble next to the widget during screenshot capture, then tags the bubble. Translators see the actual aria-label text pinned to the widget. Best when the widget has no visible cue at all.
+
+Reveal bubbles only exist inside the screenshot pipeline — they are never rendered in production.
+
+### Deterministic tagging, not `--auto-tag`
+
+Crowdin's built-in `--auto-tag` uses fuzzy text matching, which produces false positives (e.g. tagging the wrong "Close"). This script is fully deterministic — every declared tag either resolves to a specific DOM element or the run reports it as unresolved. Catalog keys are validated on every invocation.
+
+### When to re-run
+
+- After adding a new catalog key that has visual context worth showing translators.
+- After a component redesign that changes the pixel position of tagged strings.
+- After adding a new story that better exposes existing keys.
+
+`--replace-tags` handles the "just update the pixel positions" case cleanly.
diff --git a/internal/scripts/lib/crowdin-strategies.mjs b/internal/scripts/lib/crowdin-strategies.mjs
new file mode 100644
index 0000000000..f064c16315
--- /dev/null
+++ b/internal/scripts/lib/crowdin-strategies.mjs
@@ -0,0 +1,512 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+//
+// DOM measurement strategies for Crowdin screenshot manual tagging.
+//
+// Each strategy runs in the PAGE context (via page.evaluate) and returns
+// {x, y, width, height} in CSS pixels, or null if no match was found. The
+// caller multiplies by DPR before POSTing to Crowdin.
+//
+// Strategies are pure DOM lookups — they don't interact with the page.
+// Interactions (open popover, click chip, etc.) happen in the target's
+// `interact()` function before measurement.
+//
+// All strategy code is inlined into a single browserside function
+// (STRATEGY_FN_SOURCE) which is stringified and executed via page.evaluate.
+
+export const STRATEGY_NAMES = [
+ 'visibleText',
+ 'option',
+ 'placeholder',
+ 'ariaLabel',
+ 'chipOperator',
+ 'filterInput',
+ 'footerButton',
+ 'srOnlyLabel',
+ 'srOnlyReveal',
+];
+
+// This function is stringified and evaluated in the browser. Do not import
+// anything from Node.js in here. `strategy` is the strategy name, `args` is
+// an array of positional arguments.
+export function browserSideMeasure() {
+ return function measure(strategy, args) {
+ // Utilities ---------------------------------------------------------------
+ function visible(el) {
+ return !!el && !!el.getClientRects && el.getClientRects().length > 0;
+ }
+ function rectOf(el) {
+ if (!visible(el)) return null;
+ const r = el.getBoundingClientRect();
+ if (r.width <= 0 || r.height <= 0) return null;
+ return {x: r.x, y: r.y, width: r.width, height: r.height};
+ }
+ // Matches when trimmed `actual === want`, or (when tolerance > 0) when
+ // `actual.startsWith(want)` and the extra suffix is <= `tolerance` chars.
+ // Pass tolerance=Infinity to accept any startsWith match.
+ function matchText(actual, want, tolerance) {
+ const t = (actual || '').trim();
+ if (t === want) return true;
+ if (!tolerance) return false;
+ if (!t.startsWith(want)) return false;
+ return t.length <= want.length + tolerance;
+ }
+ function visibleListbox() {
+ const all = Array.from(document.querySelectorAll('[role="listbox"]'));
+ return all.find(el => rectOf(el)) || all[0] || null;
+ }
+ // Shared popover/dialog container selector list, used by strategies that
+ // need to scope their DOM query to the currently-open popover surface.
+ function visibleContainers(opts) {
+ const includeListbox = opts && opts.includeListbox;
+ const sel = includeListbox
+ ? '[role="dialog"], [role="listbox"], [data-radix-popper-content-wrapper], [data-state="open"]'
+ : '[role="dialog"], [data-radix-popper-content-wrapper], [data-state="open"]';
+ return Array.from(document.querySelectorAll(sel));
+ }
+ // Walks up from `el.parentElement` looking for the first ancestor whose
+ // rect is >= minSize × minSize. Used to find the visible widget above a
+ // visually-hidden (sr-only) label.
+ function walkUpToMeasurable(el, minSize) {
+ const min = minSize == null ? 20 : minSize;
+ let anc = el.parentElement;
+ while (anc) {
+ const pr = anc.getBoundingClientRect();
+ if (pr.width >= min && pr.height >= min) return anc;
+ anc = anc.parentElement;
+ }
+ return null;
+ }
+ // Like walkUpToMeasurable but considers `el` itself as the first
+ // candidate. Used when the tagged element (a button/icon) is usually
+ // already the widget but occasionally an inner span too small to
+ // measure.
+ function expandToMeasurableSelf(el, minSize) {
+ const min = minSize == null ? 6 : minSize;
+ let w = el;
+ while (w) {
+ const wr = w.getBoundingClientRect();
+ if (wr.width >= min && wr.height >= min) return w;
+ w = w.parentElement;
+ }
+ return null;
+ }
+ function findByExactText(text, root, candidateSelectors) {
+ const scope = root || document.body;
+ const els = Array.from(
+ scope.querySelectorAll(candidateSelectors || '[role="option"], button, span, div, li, a, p, h1, h2, h3, h4'),
+ );
+ let best = null;
+ for (const el of els) {
+ if (!visible(el)) continue;
+ if ((el.textContent || '').trim() !== text) continue;
+ const r = el.getBoundingClientRect();
+ // Skip essentially-invisible rects — sr-only labels are ~1×1 px.
+ // Callers that specifically want sr-only labels should use
+ // the srOnlyLabel strategy instead.
+ if (r.width < 6 || r.height < 6) continue;
+ // Prefer the SMALLEST matching element — it's the most specific
+ // (avoids picking up giant wrapper divs whose textContent happens
+ // to equal the target text because they contain only that node).
+ if (!best || r.width * r.height < best.w * best.h) {
+ best = {x: r.x, y: r.y, w: r.width, h: r.height};
+ }
+ }
+ if (!best) return null;
+ return {x: best.x, y: best.y, width: best.w, height: best.h};
+ }
+ // 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
+ // value-picker dropdown that Playwright triggered mid-flight.
+ function isVisibleAtCenter(el) {
+ const r = el.getBoundingClientRect();
+ if (r.width <= 0 || r.height <= 0) return false;
+ const cx = r.left + r.width / 2;
+ const cy = r.top + r.height / 2;
+ const top = document.elementFromPoint(cx, cy);
+ if (!top) return false;
+ return top === el || el.contains(top) || top.contains(el);
+ }
+
+ // Strategy implementations -----------------------------------------------
+ // visibleText(text) — find the smallest element whose exact trimmed text
+ // is `text`. Searches the whole document. Good for generic labels.
+ function visibleText(text) {
+ return findByExactText(text);
+ }
+
+ // option(text) — find role=option whose accessible name / text is `text`.
+ // Prefers the currently-visible listbox. Falls back to any role=option
+ // in the document (exact match only for the fallback).
+ function option(text) {
+ const lb = visibleListbox();
+ if (lb) {
+ const opts = Array.from(lb.querySelectorAll('[role="option"]'));
+ for (const el of opts) {
+ if (!visible(el)) continue;
+ // Match exact OR startsWith with tight length bound (guards
+ // against options that include a trailing icon/counter).
+ if (!matchText(el.textContent, text, 4)) continue;
+ const r = rectOf(el);
+ if (r) return r;
+ }
+ }
+ const opts = Array.from(document.querySelectorAll('[role="option"]'));
+ for (const el of opts) {
+ if (!visible(el)) continue;
+ if (!matchText(el.textContent, text, 0)) continue;
+ const r = rectOf(el);
+ if (r) return r;
+ }
+ return null;
+ }
+
+ // placeholder(text) — find an <input>/<textarea> whose placeholder
+ // attribute equals or starts with `text`. Returns the input's rect.
+ // Also matches aria-placeholder / data-placeholder as fallback.
+ function placeholder(text) {
+ const inputs = Array.from(
+ document.querySelectorAll('input[placeholder], textarea[placeholder]'),
+ );
+ for (const el of inputs) {
+ if (!visible(el)) continue;
+ if (!matchText(el.getAttribute('placeholder'), text, Infinity)) continue;
+ const r = rectOf(el);
+ if (r) return r;
+ }
+ const alt = Array.from(
+ document.querySelectorAll('[aria-placeholder], [data-placeholder]'),
+ );
+ for (const el of alt) {
+ if (!visible(el)) continue;
+ const p =
+ el.getAttribute('aria-placeholder') ||
+ el.getAttribute('data-placeholder');
+ if (!matchText(p, text, Infinity)) continue;
+ const r = rectOf(el);
+ if (r) return r;
+ }
+ return null;
+ }
+
+ // ariaLabel(text) — find an element whose aria-label equals `text`.
+ function ariaLabel(text) {
+ const els = Array.from(document.querySelectorAll('[aria-label]'));
+ for (const el of els) {
+ if (!visible(el)) continue;
+ if (!matchText(el.getAttribute('aria-label'), text, 0)) continue;
+ const r = rectOf(el);
+ if (r) return r;
+ }
+ return null;
+ }
+
+ // chipOperator(fieldName, opText) — find a chip labeled
+ // `${fieldName}: ${opText} ...` and return the rect of just the opText
+ // substring (using Range selection on the text node). Chips are
+ // rendered as buttons with visible text like "Created: is after Jan 14".
+ function chipOperator(fieldName, opText) {
+ const buttons = Array.from(document.querySelectorAll('button'));
+ for (const btn of buttons) {
+ if (!visible(btn)) continue;
+ const t = (btn.textContent || '').trim();
+ if (!t.startsWith(`${fieldName}:`)) continue;
+ // Find the text node containing opText and use a Range to measure.
+ const walker = document.createTreeWalker(btn, NodeFilter.SHOW_TEXT);
+ let node;
+ while ((node = walker.nextNode())) {
+ const idx = node.nodeValue.indexOf(opText);
+ if (idx === -1) continue;
+ const range = document.createRange();
+ range.setStart(node, idx);
+ range.setEnd(node, idx + opText.length);
+ const rects = range.getClientRects();
+ if (!rects.length) continue;
+ const r = rects[0];
+ if (r.width <= 0 || r.height <= 0) continue;
+ return {x: r.x, y: r.y, width: r.width, height: r.height};
+ }
+ }
+ return null;
+ }
+
+ // filterInput(kind) — find the value editor input inside the currently
+ // open filter popover. `kind` is 'string' | 'number' | 'search' | 'date'.
+ // string -> input[type=text] or input without type
+ // number -> input[type=number]
+ // date -> input[type=date] or input with role=combobox in date popover
+ // search -> input[placeholder*=Search]
+ function filterInput(kind) {
+ const containers = visibleContainers({includeListbox: true});
+ const scope = containers.length ? containers : [document.body];
+ let selector = 'input, textarea';
+ if (kind === 'number') selector = 'input[type="number"]';
+ else if (kind === 'date') selector = 'input[type="date"], input[type="datetime-local"], input[role="combobox"]';
+ else if (kind === 'search') selector = 'input[placeholder*="Search" i]';
+ for (const root of scope) {
+ const inputs = Array.from(root.querySelectorAll(selector));
+ for (const el of inputs) {
+ if (!visible(el)) continue;
+ const r = rectOf(el);
+ if (r) return r;
+ }
+ }
+ return null;
+ }
+
+ // footerButton(text) — find a <button> whose text is exactly `text`,
+ // scoped to buttons that appear at the bottom of a dialog/popover.
+ // Skips buttons that are covered by an overlapping element (e.g. an
+ // open value-picker dropdown) so we don't tag hidden positions.
+ // Fallback to any matching button in the document (smallest wins).
+ function footerButton(text) {
+ const containers = visibleContainers();
+ for (const root of containers) {
+ const btns = Array.from(root.querySelectorAll('button'));
+ for (const b of btns) {
+ if (!visible(b)) continue;
+ if ((b.textContent || '').trim() !== text) continue;
+ if (!isVisibleAtCenter(b)) continue;
+ const r = rectOf(b);
+ if (r) return r;
+ }
+ }
+ const btns = Array.from(document.querySelectorAll('button'));
+ let best = null;
+ for (const b of btns) {
+ if (!visible(b)) continue;
+ if ((b.textContent || '').trim() !== text) continue;
+ if (!isVisibleAtCenter(b)) continue;
+ const r = b.getBoundingClientRect();
+ if (r.width <= 0 || r.height <= 0) continue;
+ // Pick the smallest — typically the actual footer button (larger
+ // matches would be wrapper divs with the same text).
+ if (!best || r.width * r.height < best.w * best.h) {
+ best = {x: r.x, y: r.y, w: r.width, h: r.height};
+ }
+ }
+ return best ? {x: best.x, y: best.y, width: best.w, height: best.h} : null;
+ }
+
+ // srOnlyLabel(text) — find a <label>/<span>/[aria-hidden] whose exact
+ // text is `text` and return the rect of its nearest visible ancestor.
+ // Useful for `isLabelHidden` controls where the label is in the DOM
+ // (1×1 sr-only) but translators need to see the whole control.
+ function srOnlyLabel(text) {
+ const cands = Array.from(document.querySelectorAll('label, span, [aria-hidden="true"]'));
+ for (const el of cands) {
+ if ((el.textContent || '').trim() !== text) continue;
+ const r = el.getBoundingClientRect();
+ // Only apply when the label itself is visually-hidden (small rect).
+ if (r.width > 20 && r.height > 20) continue;
+ const anc = walkUpToMeasurable(el, 20);
+ if (anc) return rectOf(anc);
+ }
+ return null;
+ }
+
+ // srOnlyReveal(text, placement?) — find a widget labeled `text` (via
+ // either a visually-hidden <label>/<span>/aria-hidden element with
+ // that text content, OR an aria-label / aria-labelledby matching that
+ // text on any interactive element). Injects a small yellow "reveal
+ // bubble" showing the label text next to the widget so translators
+ // can SEE the label in the screenshot. Returns the bubble's rect so
+ // the Crowdin tag lands on readable text, not an icon-only widget.
+ //
+ // placement: 'right' (default), 'below', 'above', 'left'.
+ //
+ // Prefer this over srOnlyLabel / ariaLabel when the tagged widget has
+ // no visible text of its own (bare checkboxes, icon buttons like ×
+ // and chevrons). Reveal bubbles are z-index 99999 so they overlay any
+ // nearby content — pick a placement that doesn't cover the widget.
+ function srOnlyReveal(text, placement) {
+ const place = placement || 'right';
+
+ // Idempotent: if a reveal bubble for this text already exists (from
+ // a pre-screenshot pass), just return its rect instead of injecting
+ // another one. We stash the viewport-relative paint rect at
+ // injection time as data-* attrs, because getBoundingClientRect()
+ // on top-layer descendants can shift between calls
+ // (containing-block vs viewport) in some browsers.
+ 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 cachePaintRect(bubble) {
+ const p = bubble.getBoundingClientRect();
+ bubble.setAttribute('data-crowdin-vx', String(p.x));
+ bubble.setAttribute('data-crowdin-vy', String(p.y));
+ bubble.setAttribute('data-crowdin-vw', String(p.width));
+ bubble.setAttribute('data-crowdin-vh', String(p.height));
+ }
+
+ const existing = document.querySelector(
+ `[data-crowdin-reveal-text="${CSS.escape(text)}"]`,
+ );
+ if (existing) {
+ const cached = readCachedRect(existing);
+ if (cached) return cached;
+ const er = existing.getBoundingClientRect();
+ if (er.width > 0 && er.height > 0) {
+ return {x: er.x, y: er.y, width: er.width, height: er.height};
+ }
+ }
+
+ // Two match paths (deduped):
+ // (1) sr-only label/span/aria-hidden element whose textContent is `text`
+ // → the widget is the nearest visible ancestor.
+ // (2) any element with aria-label === text (or aria-labelledby → text)
+ // → the widget IS that element (or its measurable ancestor if
+ // the element itself is sub-6px).
+ function findWidgetsForRevealText(t) {
+ const widgets = [];
+ // Path 1: sr-only text nodes
+ const textCands = Array.from(
+ document.querySelectorAll('label, span, [aria-hidden="true"]'),
+ );
+ for (const el of textCands) {
+ if ((el.textContent || '').trim() !== t) continue;
+ const r = el.getBoundingClientRect();
+ if (r.width > 20 && r.height > 20) continue;
+ const anc = walkUpToMeasurable(el, 20);
+ if (anc) widgets.push(anc);
+ }
+ // Path 2a: aria-label matches
+ const ariaCands = Array.from(
+ document.querySelectorAll(`[aria-label="${CSS.escape(t)}"]`),
+ );
+ for (const el of ariaCands) {
+ const w = expandToMeasurableSelf(el, 6);
+ if (w) widgets.push(w);
+ }
+ // Path 2b: aria-labelledby matches
+ const labelledByEls = Array.from(
+ document.querySelectorAll('[aria-labelledby]'),
+ );
+ for (const el of labelledByEls) {
+ const ids = (el.getAttribute('aria-labelledby') || '').split(/\s+/);
+ const parts = ids
+ .map(id => document.getElementById(id))
+ .filter(Boolean)
+ .map(n => (n.textContent || '').trim())
+ .join(' ')
+ .trim();
+ if (parts !== t) continue;
+ const w = expandToMeasurableSelf(el, 6);
+ if (w) widgets.push(w);
+ }
+ // Dedup (same widget can be discovered via both paths).
+ const seen = new Set();
+ const unique = [];
+ for (const w of widgets) {
+ if (seen.has(w)) continue;
+ seen.add(w);
+ unique.push(w);
+ }
+ 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';
+ }
+
+ // Compute viewport-space left/top for the bubble at `place`, then
+ // translate to containing-block-space when parented to a top-layer
+ // element (native <dialog>/[popover]) whose `position: fixed`
+ // descendants are scoped to the dialog's origin.
+ function positionBubble(bubble, widgetRect, place, modalHost) {
+ const b = bubble.getBoundingClientRect();
+ let left = 0;
+ let top = 0;
+ switch (place) {
+ case 'below':
+ left = widgetRect.left + widgetRect.width / 2 - b.width / 2;
+ top = widgetRect.bottom + 4;
+ break;
+ case 'above':
+ left = widgetRect.left + widgetRect.width / 2 - b.width / 2;
+ top = widgetRect.top - b.height - 4;
+ break;
+ case 'left':
+ left = widgetRect.left - b.width - 6;
+ top = widgetRect.top + widgetRect.height / 2 - b.height / 2;
+ break;
+ case 'right':
+ default:
+ left = widgetRect.right + 6;
+ top = widgetRect.top + widgetRect.height / 2 - b.height / 2;
+ }
+ if (modalHost) {
+ const mr = modalHost.getBoundingClientRect();
+ left -= mr.left;
+ top -= mr.top;
+ }
+ bubble.style.left = `${Math.max(0, Math.round(left))}px`;
+ bubble.style.top = `${Math.max(0, Math.round(top))}px`;
+ }
+
+ const uniqueWidgets = findWidgetsForRevealText(text);
+ if (uniqueWidgets.length === 0) return null;
+
+ // Inject one bubble per widget so translators see the reveal for
+ // every occurrence (e.g. "Expand row" on multiple rows).
+ let lastBubble = null;
+ for (const anc of uniqueWidgets) {
+ const pr = anc.getBoundingClientRect();
+ 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);
+ positionBubble(bubble, pr, place, modalHost);
+ cachePaintRect(bubble);
+ lastBubble = bubble;
+ }
+ if (!lastBubble) return null;
+ return readCachedRect(lastBubble);
+ }
+
+ // Dispatcher --------------------------------------------------------------
+ switch (strategy) {
+ case 'visibleText': return visibleText(args[0]);
+ case 'option': return option(args[0]);
+ case 'placeholder': return placeholder(args[0]);
+ case 'ariaLabel': return ariaLabel(args[0]);
+ case 'chipOperator': return chipOperator(args[0], args[1]);
+ case 'filterInput': return filterInput(args[0]);
+ case 'footerButton': return footerButton(args[0]);
+ case 'srOnlyLabel': return srOnlyLabel(args[0]);
+ case 'srOnlyReveal': return srOnlyReveal(args[0], args[1]);
+ default: return null;
+ }
+ };
+}
diff --git a/internal/scripts/upload-crowdin-screenshots.mjs b/internal/scripts/upload-crowdin-screenshots.mjs
new file mode 100644
index 0000000000..44abdf5c18
--- /dev/null
+++ b/internal/scripts/upload-crowdin-screenshots.mjs
@@ -0,0 +1,1069 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+//
+// Automate uploading translation-context screenshots to Crowdin.
+//
+// DESIGN: This script uses ONLY declarative, per-target manual tag
+// declarations — never `crowdin screenshot upload --auto-tag`. Every rect
+// that ends up on a Crowdin screenshot originates from a strategy in
+// lib/crowdin-strategies.mjs. This avoids the two main auto-tag failure
+// modes we hit in earlier iterations:
+// 1. Auto-tag matches irrelevant text that happens to render on the
+// screenshot (e.g. "No results", "Search…" in an unrelated dropdown).
+// 2. Auto-tag can't distinguish English text that maps to different
+// catalog keys ("is" -> operator.is for strings, operator.equals for
+// numbers).
+//
+// Pipeline:
+// 1. Ensure a Storybook build exists at apps/storybook/dist (build if
+// missing).
+// 2. Validate every declared manualTag key exists in
+// packages/core/locales/en.json (warn+skip unknowns).
+// 3. Start a local static server, launch chromium.
+// 4. For each target: navigate, interact, screenshot, measure each
+// declared tag's rect using its named strategy.
+// 5. Upload the PNG to Crowdin (WITHOUT --auto-tag), then POST manual
+// tags for the rects we measured.
+//
+// Usage:
+// node internal/scripts/upload-crowdin-screenshots.mjs [flags]
+//
+// Flags:
+// --dry-run Screenshot + measure but do NOT upload or POST tags.
+// --validate Only validate declared keys against en.json (no
+// browser, no network). Exits non-zero if any unknown.
+// --skip-build Reuse existing storybook build.
+// --skip-upload Screenshot + measure but don't call `crowdin` or POST.
+// --rebuild Force storybook rebuild.
+// --only=a,b,c Filter targets by name.
+// --delete-first Delete existing Crowdin screenshot with the same
+// filename before re-uploading (avoids duplicates if
+// the CLI decides to create new IDs). Off by default.
+// --replace-tags Before POSTing new tags, DELETE all existing tags on
+// the (updated-in-place) screenshot. Prevents tag
+// stacking when re-running the script — Crowdin's tag
+// POST doesn't dedupe by key. Off by default.
+
+import {chromium} from '@playwright/test';
+import {execSync, spawnSync} from 'node:child_process';
+import * as http from 'node:http';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {browserSideMeasure, STRATEGY_NAMES} from './lib/crowdin-strategies.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(__dirname, '..', '..');
+const STORYBOOK_DIST = path.join(REPO_ROOT, 'apps/storybook/dist');
+const OUT_DIR = path.join(__dirname, 'output/crowdin-screenshots');
+const EN_JSON = path.join(REPO_ROOT, 'packages/core/locales/en.json');
+const PROJECT_ID = '914513';
+const LABEL = 'i18n-context';
+const DPR = 2;
+
+const argv = process.argv.slice(2);
+const args = new Set(argv);
+const DRY_RUN = args.has('--dry-run');
+const SKIP_BUILD = args.has('--skip-build');
+const SKIP_UPLOAD = args.has('--skip-upload');
+const VALIDATE_ONLY = args.has('--validate');
+const DELETE_FIRST = args.has('--delete-first');
+const REPLACE_TAGS = args.has('--replace-tags');
+let ONLY = null;
+{
+ const idx = argv.findIndex(a => a === '--only' || a.startsWith('--only='));
+ if (idx !== -1) {
+ const val = argv[idx].includes('=') ? argv[idx].split('=', 2)[1] : argv[idx + 1];
+ if (val) ONLY = new Set(val.split(',').map(s => s.trim()).filter(Boolean));
+ }
+}
+
+fs.mkdirSync(OUT_DIR, {recursive: true});
+
+// ---------- helpers ----------
+function log(...a) { console.log('[crowdin-screens]', ...a); }
+function warn(...a) { console.warn('[crowdin-screens]', ...a); }
+function run(cmd, opts = {}) {
+ return execSync(cmd, {stdio: 'inherit', ...opts});
+}
+function getToken() {
+ return execSync(
+ `security find-generic-password -a "$USER" -s CROWDIN_PERSONAL_TOKEN -w`,
+ {encoding: 'utf8'},
+ ).trim();
+}
+
+// ---------- catalog ----------
+function loadCatalogKeys() {
+ const raw = JSON.parse(fs.readFileSync(EN_JSON, 'utf8'));
+ const keys = new Set();
+ for (const k of Object.keys(raw)) {
+ // Catalog keys start with '@'. The stringIdMap uses the un-@ form.
+ keys.add(k.replace(/^@/, ''));
+ }
+ return keys;
+}
+
+// Map of un-@ catalog key → defaultMessage. Loaded once at module scope so
+// t() can fall back to the catalog default when a tag's text arg is omitted.
+function loadCatalogDefaults() {
+ const raw = JSON.parse(fs.readFileSync(EN_JSON, 'utf8'));
+ const out = new Map();
+ for (const k of Object.keys(raw)) {
+ const bare = k.replace(/^@/, '');
+ const msg = raw[k] && typeof raw[k].defaultMessage === 'string'
+ ? raw[k].defaultMessage
+ : null;
+ if (msg != null) out.set(bare, msg);
+ }
+ return out;
+}
+const CATALOG_DEFAULTS = loadCatalogDefaults();
+
+// ---------- Crowdin API ----------
+async function crowdinFetch(pathAndQuery, {token, method = 'GET', body = null} = {}) {
+ const url = `https://api.crowdin.com/api/v2${pathAndQuery}`;
+ const headers = {
+ 'Authorization': `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ };
+ const opts = {method, headers};
+ if (body != null) opts.body = JSON.stringify(body);
+ const res = await fetch(url, opts);
+ const text = await res.text();
+ if (!res.ok) {
+ throw new Error(`Crowdin ${method} ${pathAndQuery} → ${res.status}: ${text.slice(0, 400)}`);
+ }
+ return text ? JSON.parse(text) : null;
+}
+
+// Load identifier → stringId map for every astryx.* string. Cached across
+// runs would be nice but not necessary — the project is small (<1000).
+async function loadStringIdMap(token) {
+ const map = new Map();
+ let offset = 0;
+ const limit = 500;
+ while (true) {
+ // Filter by prefix "astryx." to reduce the payload; we tag nothing else.
+ const q = `/projects/${PROJECT_ID}/strings?filter=${encodeURIComponent('astryx.')}&scope=identifier&limit=${limit}&offset=${offset}`;
+ const data = await crowdinFetch(q, {token});
+ const items = data?.data ?? [];
+ for (const x of items) {
+ const s = x.data;
+ const ident = (s.identifier || '').replace(/^@/, '');
+ map.set(ident, s.id);
+ }
+ if (items.length < limit) break;
+ offset += limit;
+ }
+ return map;
+}
+
+// ---------- static server ----------
+const MIME = {
+ '.html': 'text/html', '.js': 'application/javascript', '.mjs': 'application/javascript',
+ '.css': 'text/css', '.json': 'application/json', '.png': 'image/png',
+ '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.woff': 'font/woff',
+ '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.map': 'application/json',
+};
+function serveStatic(dir) {
+ return new Promise((resolve, reject) => {
+ const server = http.createServer((req, res) => {
+ let urlPath = decodeURIComponent((req.url || '/').split('?')[0]);
+ if (urlPath === '/') urlPath = '/index.html';
+ const filePath = path.join(dir, urlPath);
+ if (!filePath.startsWith(dir) || !fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) {
+ res.writeHead(404); res.end('Not found'); return;
+ }
+ const ct = MIME[path.extname(filePath).toLowerCase()] || 'application/octet-stream';
+ res.writeHead(200, {'Content-Type': ct});
+ fs.createReadStream(filePath).pipe(res);
+ });
+ server.on('error', reject);
+ server.listen(0, '127.0.0.1', () => {
+ const {port} = server.address();
+ resolve({
+ url: `http://127.0.0.1:${port}`,
+ close: () => new Promise(r => server.close(() => r())),
+ });
+ });
+ });
+}
+
+// ---------- targets ----------
+// Every target declares an explicit `manualTags` array. Each entry:
+// { key: 'astryx.foo.bar', strategy: 'option', args: ['Contains'] }
+// The `strategy` is one of STRATEGY_NAMES (see lib/crowdin-strategies.mjs).
+// `args` is a positional-arg array for the strategy.
+//
+// Bare `key` values must NOT include the leading '@' — the strategy map
+// stores identifiers without it.
+//
+// The third+ positional arg is the "text to match" the strategy uses when
+// probing the rendered DOM. For the vast majority of tags this text is
+// identical to `en.json[key].defaultMessage`, so t() defaults it to that
+// catalog value when omitted. Callers still pass an explicit text when it
+// diverges from the catalog default — e.g. ICU-interpolated messages
+// (`Sort by {label}` → `Sort by Name`), or placeholder catalog values that
+// carry trailing ellipses the rendered DOM omits (`Enter value…` vs
+// `Enter value`).
+//
+// Per-strategy convention for which arg slot is the "text" arg:
+// visibleText / option / placeholder / ariaLabel / footerButton /
+// srOnlyLabel / srOnlyReveal → args[0]
+// chipOperator → args[1] (args[0] = field name)
+// filterInput → no text arg (kind string only)
+const TEXT_ARG_INDEX = {
+ visibleText: 0,
+ option: 0,
+ placeholder: 0,
+ ariaLabel: 0,
+ chipOperator: 1,
+ filterInput: null,
+ footerButton: 0,
+ srOnlyLabel: 0,
+ srOnlyReveal: 0,
+};
+
+function t(key, strategy, ...args) {
+ const idx = TEXT_ARG_INDEX[strategy];
+ if (idx != null && args[idx] === undefined) {
+ const def = CATALOG_DEFAULTS.get(key);
+ if (def != null) args[idx] = def;
+ }
+ return {key, strategy, args};
+}
+
+const TARGETS = [
+ // ==========================================================================
+ // Static (non-popover) targets
+ // ==========================================================================
+ {
+ name: 'powersearch-filter-editor',
+ // ManyFilters renders 7 chips whose visible text embeds operator labels.
+ storyId: 'core-powersearch--many-filters',
+ viewport: {width: 900, height: 220},
+ interact: async () => {},
+ selector: null,
+ // Each chip's operator substring gets its own tightly-scoped rect via
+ // chipOperator(fieldName, opText). Story renders 7 chips: Status,
+ // Priority, Title, Assignee, Tags, Line count, Created. "Tags: include"
+ // uses an operator label with no direct catalog key (it's a string_list
+ // isAnyOf render variant), so we skip it here.
+ manualTags: [
+ t('astryx.powersearch.operator.isAnyOf', 'chipOperator', 'Status'),
+ t('astryx.powersearch.operator.is', 'chipOperator', 'Priority'),
+ t('astryx.powersearch.operator.contains', 'chipOperator', 'Title'),
+ t('astryx.powersearch.operator.isAnyOf', 'chipOperator', 'Assignee'),
+ t('astryx.powersearch.operator.greaterThan', 'chipOperator', 'Line count'),
+ t('astryx.powersearch.operator.after', 'chipOperator', 'Created'),
+ ],
+ },
+ {
+ name: 'powersearch-value-editor',
+ // WithDateFilters → open the Created chip and transition to compact editor.
+ storyId: 'core-powersearch--with-date-filters',
+ viewport: {width: 900, height: 400},
+ interact: async page => {
+ const chip = page.getByRole('button', {name: /Created:\s*is after/i}).first();
+ await chip.waitFor({state: 'visible', timeout: 5000});
+ await chip.click();
+ const createdOption = page.getByRole('option', {name: 'Created'}).first();
+ await createdOption.waitFor({state: 'visible', timeout: 5000});
+ await createdOption.click();
+ await page.getByRole('button', {name: 'Apply'}).first().waitFor({timeout: 5000});
+ await page.waitForTimeout(400);
+ },
+ selector: null,
+ manualTags: [
+ // Operator selector in the compact editor shows "is after".
+ t('astryx.powersearch.operator.after', 'visibleText'),
+ // Date value input placeholder (from @astryx/core's DateTimeInput).
+ t('astryx.dateTimeInput.placeholder', 'placeholder'),
+ t('astryx.powersearch.editor.cancel', 'footerButton'),
+ t('astryx.powersearch.editor.apply', 'footerButton'),
+ ],
+ },
+ {
+ name: 'chat-message-with-status',
+ storyId: 'core-chat--message-status',
+ viewport: {width: 700, height: 500},
+ interact: async () => {},
+ selector: null,
+ manualTags: [
+ t('astryx.chat.status.sending', 'visibleText'),
+ t('astryx.chat.status.sent', 'visibleText'),
+ t('astryx.chat.status.delivered', 'visibleText'),
+ t('astryx.chat.status.read', 'visibleText'),
+ t('astryx.chat.status.failed', 'visibleText'),
+ ],
+ },
+ {
+ name: 'powersearch-with-result-count',
+ storyId: 'core-powersearch--with-result-count',
+ viewport: {width: 900, height: 220},
+ interact: async () => {},
+ selector: null,
+ manualTags: [
+ // Story renders "1,234 results" (see WithResultCount fixture).
+ t('astryx.powersearch.resultCount', 'visibleText', '1,234 results'),
+ ],
+ },
+ {
+ name: 'pagination-count',
+ storyId: 'core-pagination--count-variant',
+ viewport: {width: 700, height: 100},
+ interact: async () => {},
+ selector: null,
+ manualTags: [
+ // ICU "{from}–{to} of {total}" — story renders "1–20 of 200".
+ t('astryx.pagination.count', 'visibleText', '1–20 of 200'),
+ ],
+ },
+ {
+ name: 'pagination-compact',
+ storyId: 'core-pagination--compact-variant',
+ viewport: {width: 500, height: 100},
+ interact: async () => {},
+ selector: null,
+ manualTags: [
+ // "Page {n} of {total}"
+ t('astryx.pagination.pageOfTotal', 'visibleText', 'Page 1 of 10'),
+ ],
+ },
+ {
+ name: 'pagination-with-page-size',
+ storyId: 'core-pagination--with-page-size-selector',
+ viewport: {width: 900, height: 100},
+ interact: async () => {},
+ selector: null,
+ manualTags: [
+ t('astryx.pagination.count', 'visibleText', '1–10 of 200'),
+ // "Items per page" is a visually-hidden <label> (isLabelHidden). The
+ // srOnlyReveal strategy injects a small visible label bubble next to
+ // the widget so translators see the actual English label text in the
+ // screenshot instead of just a bare combobox.
+ t('astryx.pagination.itemsPerPage', 'srOnlyReveal', undefined, 'below'),
+ ],
+ },
+
+ // ==========================================================================
+ // Interactive operator-dropdown targets (v3 — WithPresetFilters story)
+ // ==========================================================================
+ {
+ name: 'powersearch-string-operators-open',
+ storyId: 'core-powersearchwithtable--with-preset-filters',
+ viewport: {width: 1000, height: 700},
+ interact: async page => {
+ await page.locator('[role="combobox"]').first().click();
+ await page.waitForTimeout(300);
+ await page.getByRole('option', {name: 'Title'}).first().click();
+ await page.waitForTimeout(400);
+ await page.locator('button[role="combobox"]').nth(1).click();
+ await page.waitForSelector('[role="listbox"]:not(:empty)', {timeout: 3000}).catch(() => {});
+ await page.waitForTimeout(400);
+ },
+ selector: null,
+ manualTags: [
+ t('astryx.powersearch.operator.contains', 'option'),
+ t('astryx.powersearch.operator.notContains', 'option'),
+ t('astryx.powersearch.operator.startsWith', 'option'),
+ t('astryx.powersearch.operator.notStartsWith', 'option'),
+ t('astryx.powersearch.operator.endsWith', 'option'),
+ t('astryx.powersearch.operator.notEndsWith', 'option'),
+ t('astryx.powersearch.operator.is', 'option'),
+ t('astryx.powersearch.operator.isNot', 'option'),
+ t('astryx.powersearch.valueEditor.enterValuePlaceholder', 'placeholder', 'Enter value'),
+ t('astryx.powersearch.editor.cancel', 'footerButton'),
+ t('astryx.powersearch.editor.apply', 'footerButton'),
+ ],
+ },
+ {
+ name: 'powersearch-number-operators-open',
+ storyId: 'core-powersearchwithtable--with-preset-filters',
+ viewport: {width: 1000, height: 700},
+ interact: async page => {
+ await page.locator('[role="combobox"]').first().click();
+ await page.waitForTimeout(300);
+ await page.getByRole('option', {name: 'Publication Year'}).first().click();
+ await page.waitForTimeout(400);
+ await page.locator('button[role="combobox"]').nth(1).click();
+ await page.waitForSelector('[role="listbox"]:not(:empty)', {timeout: 3000}).catch(() => {});
+ await page.waitForTimeout(400);
+ },
+ selector: null,
+ // For number fields: "is" is the label for `equals`, "is not" for
+ // `notEquals`. Different string ids from the string field's is/isNot.
+ manualTags: [
+ t('astryx.powersearch.operator.equals', 'option'),
+ t('astryx.powersearch.operator.notEquals', 'option'),
+ t('astryx.powersearch.operator.greaterThan', 'option'),
+ t('astryx.powersearch.operator.lessThan', 'option'),
+ t('astryx.powersearch.operator.greaterThanOrEqual', 'option'),
+ t('astryx.powersearch.operator.lessThanOrEqual', 'option'),
+ t('astryx.powersearch.editor.cancel', 'footerButton'),
+ t('astryx.powersearch.editor.apply', 'footerButton'),
+ ],
+ },
+ {
+ name: 'powersearch-enum-operators-open',
+ storyId: 'core-powersearchwithtable--with-preset-filters',
+ viewport: {width: 1000, height: 700},
+ interact: async page => {
+ await page.getByRole('button', {name: /^Genre: is/i}).first().click();
+ await page.waitForTimeout(400);
+ await page.getByRole('option', {name: 'Genre'}).first().click();
+ await page.waitForTimeout(400);
+ await page.locator('button[role="combobox"]').nth(1).click();
+ await page.waitForSelector('[role="listbox"]:not(:empty)', {timeout: 3000}).catch(() => {});
+ await page.waitForTimeout(400);
+ },
+ selector: null,
+ manualTags: [
+ t('astryx.powersearch.operator.is', 'option'),
+ t('astryx.powersearch.operator.isNot', 'option'),
+ t('astryx.powersearch.operator.isAnyOf', 'option'),
+ t('astryx.powersearch.operator.isNoneOf', 'option'),
+ t('astryx.powersearch.editor.cancel', 'footerButton'),
+ t('astryx.powersearch.editor.apply', 'footerButton'),
+ ],
+ },
+
+ // ==========================================================================
+ // v4 targets — date / boolean / enum_list operator dropdowns
+ // ==========================================================================
+ {
+ name: 'powersearch-date-operators-open',
+ storyId: 'core-powersearchwithtable--with-mixed-filters',
+ viewport: {width: 1100, height: 750},
+ interact: async page => {
+ await page.getByRole('button', {name: /Published Date:\s*is after/i}).first().click();
+ await page.waitForTimeout(400);
+ await page.getByRole('option', {name: /^Published Date$/}).first().click();
+ await page.waitForTimeout(400);
+ await page.locator('button[role="combobox"]').nth(1).click();
+ await page.waitForSelector('[role="listbox"]:not(:empty)', {timeout: 3000}).catch(() => {});
+ await page.waitForTimeout(400);
+ },
+ selector: null,
+ manualTags: [
+ t('astryx.powersearch.operator.before', 'option'),
+ t('astryx.powersearch.operator.after', 'option'),
+ t('astryx.powersearch.operator.between', 'option'),
+ t('astryx.dateTimeInput.placeholder', 'placeholder'),
+ t('astryx.powersearch.editor.cancel', 'footerButton'),
+ t('astryx.powersearch.editor.apply', 'footerButton'),
+ ],
+ },
+ {
+ name: 'powersearch-boolean-operators-chip',
+ storyId: 'core-powersearchwithtable--with-mixed-filters',
+ viewport: {width: 1100, height: 220},
+ // Boolean filter chips render the operator text directly on the filter
+ // bar (e.g. "In Stock: is true"). Because boolean OperatorValue is
+ // type='empty', PowerSearchEditPopover auto-closes on mount — the
+ // operator dropdown is never user-reachable. Tag isTrue/isFalse against
+ // the chip text on the bar instead, using chipOperator to isolate just
+ // the operator substring inside the chip.
+ interact: async () => {},
+ selector: null,
+ manualTags: [
+ t('astryx.powersearch.operator.isTrue', 'chipOperator', 'In Stock'),
+ t('astryx.powersearch.operator.isFalse', 'chipOperator', 'Discontinued'),
+ ],
+ },
+ {
+ name: 'powersearch-enumlist-operators-open',
+ storyId: 'core-powersearchwithtable--with-mixed-filters',
+ viewport: {width: 1100, height: 750},
+ interact: async page => {
+ await page.getByRole('button', {name: /Themes:\s*is any of/i}).first().click();
+ await page.waitForTimeout(400);
+ await page.getByRole('option', {name: /^Themes$/}).first().click();
+ await page.waitForTimeout(400);
+ await page.locator('button[role="combobox"]').nth(1).click();
+ await page.waitForSelector('[role="listbox"]:not(:empty)', {timeout: 3000}).catch(() => {});
+ await page.waitForTimeout(400);
+ },
+ selector: null,
+ manualTags: [
+ t('astryx.powersearch.operator.isAnyOf', 'option'),
+ t('astryx.powersearch.operator.isNoneOf', 'option'),
+ t('astryx.powersearch.valueEditor.selectValuesPlaceholder', 'placeholder', 'Select values'),
+ t('astryx.powersearch.editor.cancel', 'footerButton'),
+ t('astryx.powersearch.editor.apply', 'footerButton'),
+ ],
+ },
+
+ // ==========================================================================
+ // Value-editor placeholder targets
+ // ==========================================================================
+ {
+ name: 'powersearch-date-value-editor',
+ storyId: 'core-powersearchwithtable--with-mixed-filters',
+ viewport: {width: 1100, height: 750},
+ interact: async page => {
+ await page.getByRole('button', {name: /Published Date:\s*is after/i}).first().click();
+ await page.waitForTimeout(400);
+ await page.getByRole('option', {name: /^Published Date$/}).first().click();
+ await page.waitForTimeout(500);
+ },
+ selector: null,
+ manualTags: [
+ t('astryx.powersearch.operator.after', 'visibleText'),
+ t('astryx.dateTimeInput.placeholder', 'placeholder'),
+ t('astryx.powersearch.editor.cancel', 'footerButton'),
+ t('astryx.powersearch.editor.apply', 'footerButton'),
+ ],
+ },
+ {
+ name: 'powersearch-entity-value-editor',
+ storyId: 'core-powersearchwithtable--with-mixed-filters',
+ viewport: {width: 1100, height: 750},
+ interact: async page => {
+ await page.getByRole('button', {name: /Author \(entity\):\s*is any of/i}).first().click();
+ await page.waitForTimeout(400);
+ await page.getByRole('option', {name: /^Author \(entity\)$/}).first().click();
+ await page.waitForTimeout(500);
+ await page.locator('input[placeholder="Search…"]').first().click({trial: false}).catch(() => {});
+ await page.waitForTimeout(300);
+ },
+ selector: null,
+ manualTags: [
+ t('astryx.powersearch.operator.isAnyOf', 'visibleText'),
+ t('astryx.powersearch.valueEditor.searchPlaceholder', 'placeholder', 'Search'),
+ t('astryx.powersearch.editor.cancel', 'footerButton'),
+ t('astryx.powersearch.editor.apply', 'footerButton'),
+ ],
+ },
+ {
+ name: 'powersearch-string-value-editor',
+ storyId: 'core-powersearchwithtable--with-mixed-filters',
+ viewport: {width: 1100, height: 750},
+ interact: async page => {
+ await page.locator('[role="combobox"]').first().click();
+ await page.waitForTimeout(300);
+ await page.getByRole('option', {name: /^Title$/}).first().click();
+ await page.waitForTimeout(500);
+ },
+ selector: null,
+ manualTags: [
+ t('astryx.powersearch.operator.contains', 'visibleText'),
+ t('astryx.powersearch.valueEditor.enterValuePlaceholder', 'placeholder', 'Enter value'),
+ t('astryx.powersearch.editor.cancel', 'footerButton'),
+ t('astryx.powersearch.editor.apply', 'footerButton'),
+ ],
+ },
+ {
+ name: 'powersearch-number-value-editor',
+ storyId: 'core-powersearchwithtable--with-mixed-filters',
+ viewport: {width: 1100, height: 750},
+ interact: async page => {
+ await page.locator('[role="combobox"]').first().click();
+ await page.waitForTimeout(300);
+ await page.getByRole('option', {name: /^Publication Year$/}).first().click();
+ await page.waitForTimeout(500);
+ },
+ selector: null,
+ manualTags: [
+ // Number-field default operator label is "is" (equals key).
+ t('astryx.powersearch.operator.equals', 'visibleText'),
+ t('astryx.powersearch.valueEditor.enterNumberPlaceholder', 'placeholder', 'Enter number'),
+ t('astryx.powersearch.editor.cancel', 'footerButton'),
+ t('astryx.powersearch.editor.apply', 'footerButton'),
+ ],
+ },
+ {
+ name: 'powersearch-enum-value-editor',
+ storyId: 'core-powersearchwithtable--with-mixed-filters',
+ viewport: {width: 1100, height: 750},
+ interact: async page => {
+ await page.locator('[role="combobox"]').first().click();
+ await page.waitForTimeout(300);
+ await page.getByRole('option', {name: /^Themes$/}).first().click();
+ await page.waitForTimeout(500);
+ },
+ selector: null,
+ manualTags: [
+ t('astryx.powersearch.operator.isAnyOf', 'visibleText'),
+ t('astryx.powersearch.valueEditor.selectValuesPlaceholder', 'placeholder', 'Select values'),
+ t('astryx.powersearch.editor.cancel', 'footerButton'),
+ t('astryx.powersearch.editor.apply', 'footerButton'),
+ ],
+ },
+
+ // ==========================================================================
+ // Dialog / AlertDialog targets
+ // ==========================================================================
+ {
+ name: 'dialog-close-button',
+ // Basic Dialog with a "Close" (×) button in DialogHeader. The story
+ // renders a trigger "Open Modal" that reveals the dialog on click.
+ storyId: 'core-dialog--default',
+ viewport: {width: 900, height: 700},
+ interact: async page => {
+ const btn = page.getByRole('button', {name: /Open Modal/i}).first();
+ await btn.waitFor({state: 'visible', timeout: 5000});
+ await btn.click();
+ // Wait for the Close button inside the dialog header.
+ await page.getByRole('button', {name: 'Close'}).first()
+ .waitFor({state: 'visible', timeout: 5000});
+ await page.waitForTimeout(300);
+ },
+ selector: null,
+ manualTags: [
+ t('astryx.dialog.close', 'srOnlyReveal', undefined, 'left'),
+ ],
+ },
+ {
+ name: 'alertdialog-cancel',
+ // AlertDialog "Delete" variant: trigger is a "Delete item" button; on
+ // click the dialog shows a Cancel + Delete pair.
+ storyId: 'core-alertdialog--delete',
+ viewport: {width: 800, height: 500},
+ interact: async page => {
+ const btn = page.getByRole('button', {name: /Delete item/i}).first();
+ await btn.waitFor({state: 'visible', timeout: 5000});
+ await btn.click();
+ await page.getByRole('button', {name: 'Cancel'}).first()
+ .waitFor({state: 'visible', timeout: 5000});
+ await page.waitForTimeout(300);
+ },
+ selector: null,
+ manualTags: [
+ // Cancel is one of two footer buttons in the alertdialog (Cancel /
+ // Delete). footerButton scopes to dialog/popover containers, avoiding
+ // any stray "Cancel" elsewhere on the page.
+ t('astryx.alertDialog.cancel', 'footerButton'),
+ ],
+ },
+
+ // ==========================================================================
+ // Banner targets
+ // ==========================================================================
+ {
+ name: 'banner-dismissable',
+ // Banner with an × dismiss button (aria-label="Dismiss").
+ storyId: 'core-banner--dismissable',
+ viewport: {width: 900, height: 200},
+ interact: async () => {},
+ selector: null,
+ manualTags: [
+ t('astryx.banner.dismiss', 'srOnlyReveal', undefined, 'below'),
+ ],
+ },
+ {
+ name: 'banner-collapsible',
+ // Collapsible banner starts COLLAPSED — chevron reads "Expand".
+ storyId: 'core-banner--collapsible-content',
+ viewport: {width: 900, height: 250},
+ interact: async () => {},
+ selector: null,
+ manualTags: [
+ t('astryx.banner.expand', 'srOnlyReveal', undefined, 'below'),
+ ],
+ },
+ {
+ name: 'banner-collapsible-expanded',
+ // Same banner but starts EXPANDED — chevron reads "Collapse".
+ storyId: 'core-banner--collapsible-content-expanded',
+ viewport: {width: 900, height: 250},
+ interact: async () => {},
+ selector: null,
+ manualTags: [
+ t('astryx.banner.collapse', 'srOnlyReveal', undefined, 'below'),
+ ],
+ },
+
+ // ==========================================================================
+ // Table sort / selection / filter / row-expansion / grouped-rows targets
+ // ==========================================================================
+ {
+ name: 'table-sort-headers',
+ // The sort-direction strings (`Sort ascending`, `Sort descending`,
+ // `Clear sort`) are NOT the column header aria-labels — those use the
+ // compound `sortBy` / `sortedBy` templates. The three strings we care
+ // about live in the header context menu, which opens on right-click.
+ // Right-clicking the currently-sorted column (Name) reveals all three
+ // options in one popover.
+ storyId: 'core-tablesortable--single-sort',
+ viewport: {width: 1100, height: 500},
+ interact: async page => {
+ const header = page.getByRole('button', {name: /^Sort by Name/}).first();
+ await header.waitFor({state: 'visible', timeout: 5000});
+ await header.click({button: 'right'});
+ // Wait for context menu.
+ await page.locator('[role="menu"], [aria-label="Context menu"]').first()
+ .waitFor({state: 'visible', timeout: 3000}).catch(() => {});
+ await page.waitForTimeout(400);
+ },
+ selector: null,
+ manualTags: [
+ t('astryx.table.sort.ascending', 'visibleText'),
+ t('astryx.table.sort.descending', 'visibleText'),
+ t('astryx.table.sort.clear', 'visibleText'),
+ ],
+ },
+ {
+ name: 'table-selection',
+ // Select-all / select-row labels are sr-only <label> elements
+ // (astryx-field-label at 1×1 px). srOnlyLabel walks up to the nearest
+ // visible ancestor — the checkbox itself — so translators see the
+ // control.
+ storyId: 'core-tableselection--default',
+ viewport: {width: 1100, height: 500},
+ interact: async () => {},
+ selector: null,
+ manualTags: [
+ t('astryx.table.selection.selectAllRows', 'srOnlyReveal', undefined, 'below'),
+ t('astryx.table.selection.selectRow', 'srOnlyReveal', undefined, 'right'),
+ ],
+ },
+ {
+ name: 'table-filter-panel',
+ // Filter popover: click the "Filter Role" header button to open a
+ // panel with an "All" placeholder-ish combobox and Reset / Apply
+ // footer buttons.
+ storyId: 'core-tablefiltering--selector-filter',
+ viewport: {width: 1100, height: 600},
+ interact: async page => {
+ const filterBtn = page.getByRole('button', {name: 'Filter Role'}).first();
+ await filterBtn.waitFor({state: 'visible', timeout: 5000});
+ await filterBtn.click();
+ // "Apply" appears when the panel is open.
+ await page.getByRole('button', {name: 'Apply'}).first()
+ .waitFor({state: 'visible', timeout: 3000}).catch(() => {});
+ await page.waitForTimeout(400);
+ },
+ selector: null,
+ manualTags: [
+ // "All" is rendered as a <span> inside a combobox trigger — no
+ // <input placeholder>, so use visibleText.
+ t('astryx.table.filter.allPlaceholder', 'visibleText'),
+ t('astryx.table.filter.reset', 'footerButton'),
+ t('astryx.table.filter.apply', 'footerButton'),
+ ],
+ },
+ {
+ name: 'table-rowexpansion',
+ // The `inherited-columns` story shows a tree where the first row is
+ // expanded (aria-label="Collapse row") and its siblings are collapsed
+ // (aria-label="Expand row"). The header cell also shows
+ // aria-label="Expand all rows". This gives us three of the four keys
+ // in the four-way expand/collapse set. `collapseAllRows` only appears
+ // when EVERY row is expanded — skip it (would need extra interaction).
+ storyId: 'core-tablerowexpansion--inherited-columns',
+ viewport: {width: 1100, height: 500},
+ interact: async () => {},
+ selector: null,
+ manualTags: [
+ t('astryx.tableRowExpansion.expandRow', 'srOnlyReveal', undefined, 'right'),
+ t('astryx.tableRowExpansion.collapseRow', 'srOnlyReveal', undefined, 'right'),
+ t('astryx.tableRowExpansion.expandAllRows', 'srOnlyReveal', undefined, 'below'),
+ ],
+ },
+ {
+ name: 'table-groupedrows',
+ // The `initially-collapsed` variant has a mix — Design Systems and
+ // Growth start expanded (aria-label "Collapse group X") while Infra
+ // starts collapsed ("Expand group Infra"). Perfect for tagging both
+ // keys on one screenshot. The aria-labels are ICU templates with a
+ // {groupKey} slot, so we must match the fully-rendered text.
+ storyId: 'core-tablegroupedrows--initially-collapsed',
+ viewport: {width: 1100, height: 500},
+ interact: async () => {},
+ selector: null,
+ manualTags: [
+ t('astryx.tableGroupedRows.collapseGroup', 'srOnlyReveal', 'Collapse group Design Systems', 'right'),
+ t('astryx.tableGroupedRows.expandGroup', 'srOnlyReveal', 'Expand group Infra', 'right'),
+ ],
+ },
+];
+
+// ---------- validation ----------
+function validateAllTargets(catalogKeys) {
+ const errors = [];
+ const unknown = new Set();
+ for (const target of TARGETS) {
+ for (const tag of target.manualTags || []) {
+ if (!STRATEGY_NAMES.includes(tag.strategy)) {
+ errors.push(`${target.name}: unknown strategy "${tag.strategy}" for key ${tag.key}`);
+ }
+ if (!catalogKeys.has(tag.key)) {
+ unknown.add(`${target.name} :: ${tag.key}`);
+ }
+ }
+ }
+ return {errors, unknown: [...unknown]};
+}
+
+// ---------- storybook build ----------
+async function ensureStorybookBuild() {
+ if (SKIP_BUILD && fs.existsSync(STORYBOOK_DIST)) {
+ log('Reusing existing storybook build at', STORYBOOK_DIST);
+ return;
+ }
+ if (fs.existsSync(path.join(STORYBOOK_DIST, 'iframe.html')) && !args.has('--rebuild')) {
+ log('Storybook build already exists at', STORYBOOK_DIST, '(skipping)');
+ return;
+ }
+ log('Building Storybook (pnpm --filter @astryxdesign/storybook build)…');
+ const t0 = Date.now();
+ run('pnpm --filter @astryxdesign/storybook build', {cwd: REPO_ROOT});
+ log(`Storybook built in ${((Date.now() - t0) / 1000).toFixed(1)}s`);
+}
+
+// ---------- main ----------
+async function main() {
+ const totalT0 = Date.now();
+
+ // 1. Catalog validation (fast; always runs).
+ const catalogKeys = loadCatalogKeys();
+ const {errors, unknown} = validateAllTargets(catalogKeys);
+ if (errors.length) {
+ for (const e of errors) console.error('[crowdin-screens] ERROR', e);
+ process.exit(2);
+ }
+ if (unknown.length) {
+ warn(`⚠ ${unknown.length} declared key(s) NOT in en.json (will be skipped):`);
+ for (const u of unknown) warn(' ·', u);
+ }
+ if (VALIDATE_ONLY) {
+ log(`Validation complete. ${TARGETS.length} targets checked, ${unknown.length} unknown keys.`);
+ process.exit(unknown.length ? 1 : 0);
+ }
+
+ // 2. Storybook.
+ await ensureStorybookBuild();
+ if (!fs.existsSync(path.join(STORYBOOK_DIST, 'iframe.html'))) {
+ throw new Error(`Missing ${STORYBOOK_DIST}/iframe.html — storybook build failed`);
+ }
+
+ // 3. Browser + measurement.
+ const server = await serveStatic(STORYBOOK_DIST);
+ log('Static server:', server.url);
+ const browser = await chromium.launch({headless: true});
+ const captured = [];
+ const targets = ONLY ? TARGETS.filter(x => ONLY.has(x.name)) : TARGETS;
+ if (ONLY) {
+ log(`--only filter: ${targets.length}/${TARGETS.length}: ${targets.map(x => x.name).join(', ')}`);
+ const missing = [...ONLY].filter(n => !TARGETS.some(x => x.name === n));
+ if (missing.length) warn(`⚠ --only names not found in TARGETS: ${missing.join(', ')}`);
+ }
+
+ const measureFnSource = `(${browserSideMeasure.toString()})()`;
+
+ try {
+ for (const target of targets) {
+ const t0 = Date.now();
+ const ctx = await browser.newContext({viewport: target.viewport, deviceScaleFactor: DPR});
+ const page = await ctx.newPage();
+ const url = `${server.url}/iframe.html?id=${target.storyId}&viewMode=story`;
+ log(`→ ${target.name} :: ${url}`);
+ page.on('pageerror', e => warn(' [page error]', e.message));
+ await page.goto(url, {waitUntil: 'load'});
+ await page.waitForLoadState('networkidle', {timeout: 15000}).catch(() => {});
+ await page.waitForTimeout(500);
+
+ try {
+ await target.interact(page);
+ } catch (err) {
+ warn(` ⚠ interact() failed for ${target.name}: ${err.message} — screenshotting current state anyway`);
+ }
+
+ // Pre-screenshot pass: run any strategies that need to mutate the DOM
+ // (e.g. srOnlyReveal injects visible label bubbles) BEFORE the
+ // 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');
+ if (revealTags.length) {
+ for (const tag of revealTags) {
+ await page.evaluate(
+ ({fnSource, strategy, args}) => {
+ const measure = eval(fnSource);
+ return measure(strategy, args);
+ },
+ {fnSource: measureFnSource, strategy: tag.strategy, args: tag.args},
+ );
+ }
+ }
+
+ const outPath = path.join(OUT_DIR, `${target.name}.png`);
+ if (target.selector) {
+ await page.locator(target.selector).first().screenshot({path: outPath});
+ } else {
+ await page.screenshot({path: outPath, fullPage: false});
+ }
+ const size = fs.statSync(outPath).size;
+ log(` ✓ ${outPath} (${(size / 1024).toFixed(1)} KB, ${((Date.now() - t0) / 1000).toFixed(1)}s)`);
+
+ // Measure each declared tag's rect via its strategy.
+ const measured = [];
+ if (target.manualTags && target.manualTags.length) {
+ for (const tag of target.manualTags) {
+ if (!catalogKeys.has(tag.key)) {
+ measured.push({key: tag.key, position: null, reason: 'not-in-catalog'});
+ continue;
+ }
+ const rect = await page.evaluate(
+ ({fnSource, strategy, args}) => {
+ const measure = eval(fnSource);
+ return measure(strategy, args);
+ },
+ {fnSource: measureFnSource, strategy: tag.strategy, args: tag.args},
+ );
+ if (!rect) {
+ measured.push({key: tag.key, position: null, reason: 'no-rect', strategy: tag.strategy, args: tag.args});
+ } else {
+ measured.push({
+ key: tag.key,
+ strategy: tag.strategy,
+ position: {
+ x: Math.round(rect.x * DPR),
+ y: Math.round(rect.y * DPR),
+ width: Math.round(rect.width * DPR),
+ height: Math.round(rect.height * DPR),
+ },
+ });
+ }
+ }
+ const hit = measured.filter(m => m.position).length;
+ log(` ↳ measured ${hit}/${measured.length} tag positions`);
+ for (const m of measured) {
+ if (!m.position) warn(` · skip ${m.key} (${m.reason}${m.strategy ? ` via ${m.strategy}` : ''})`);
+ }
+ }
+
+ captured.push({name: target.name, path: outPath, size, measured});
+ await ctx.close();
+ }
+ } finally {
+ await browser.close();
+ await server.close();
+ }
+
+ // 4. Upload + tag.
+ if (SKIP_UPLOAD || DRY_RUN) {
+ log(`Skipping upload (${DRY_RUN ? '--dry-run' : '--skip-upload'}). ${captured.length} screenshots captured.`);
+ log(`Total: ${((Date.now() - totalT0) / 1000).toFixed(1)}s`);
+ return;
+ }
+
+ const token = getToken();
+ const env = {...process.env, CROWDIN_PERSONAL_TOKEN: token, CROWDIN_PROJECT_ID: PROJECT_ID};
+
+ log('Fetching Crowdin string-id map…');
+ const stringIdMap = await loadStringIdMap(token);
+ log(` loaded ${stringIdMap.size} astryx.* identifiers`);
+
+ for (const c of captured) {
+ // Optional: delete existing screenshot with the same filename before
+ // re-uploading, to guarantee we don't stack tags on a stale ID.
+ if (DELETE_FIRST) {
+ try {
+ const q = `/projects/${PROJECT_ID}/screenshots?limit=25&search=${encodeURIComponent(c.name)}`;
+ const list = await crowdinFetch(q, {token});
+ for (const x of list?.data ?? []) {
+ if (x?.data?.name === `${c.name}.png`) {
+ log(` ✂ deleting existing screenshot id=${x.data.id} (${c.name}.png)`);
+ await crowdinFetch(`/projects/${PROJECT_ID}/screenshots/${x.data.id}`, {token, method: 'DELETE'});
+ }
+ }
+ } catch (err) {
+ warn(` ⚠ delete-first failed for ${c.name}: ${err.message.slice(0, 300)}`);
+ }
+ }
+
+ const cmdArgs = [
+ 'screenshot', 'upload', c.path,
+ // NOTE: --auto-tag intentionally OMITTED. All tags come from manualTags.
+ // -f / -d / -b would REQUIRE --auto-tag per the CLI's own validation,
+ // so we omit them too.
+ '--project-id', PROJECT_ID,
+ '--label', LABEL,
+ '-o', 'json',
+ ];
+ log(`↑ crowdin screenshot upload ${c.name} (no auto-tag)`);
+ const res = spawnSyncCapture('crowdin', cmdArgs, {env, cwd: REPO_ROOT});
+ const short = (res.stdout || '').slice(0, 800);
+ if (res.status !== 0) {
+ warn(` ✗ exit=${res.status}`);
+ warn(' stdout:', short);
+ warn(' stderr:', (res.stderr || '').slice(0, 600));
+ continue;
+ }
+ log(' ✓ uploaded');
+
+ // POST manual tags.
+ if (!c.measured || !c.measured.length) continue;
+ try {
+ const q = `/projects/${PROJECT_ID}/screenshots?limit=25&search=${encodeURIComponent(c.name)}`;
+ const list = await crowdinFetch(q, {token});
+ const match = (list?.data ?? []).find(x => x?.data?.name === `${c.name}.png`);
+ if (!match) {
+ warn(` ⚠ could not resolve screenshot ID for ${c.name}`);
+ continue;
+ }
+ const screenshotId = match.data.id;
+
+ // Optional: clear existing tags on this screenshot before POSTing new
+ // ones. Tags don't dedupe on POST — running the script twice would
+ // stack duplicates at slightly-different-but-overlapping rects. Use
+ // --replace-tags to guarantee tag-set matches the current declared
+ // measurements exactly.
+ if (REPLACE_TAGS) {
+ try {
+ const existing = await crowdinFetch(
+ `/projects/${PROJECT_ID}/screenshots/${screenshotId}/tags?limit=100`,
+ {token},
+ );
+ const tags = existing?.data ?? [];
+ for (const t of tags) {
+ const tid = t?.data?.id;
+ if (tid == null) continue;
+ await crowdinFetch(
+ `/projects/${PROJECT_ID}/screenshots/${screenshotId}/tags/${tid}`,
+ {token, method: 'DELETE'},
+ );
+ }
+ if (tags.length) {
+ log(` ✗ deleted ${tags.length} existing tag(s) (--replace-tags)`);
+ }
+ } catch (err) {
+ warn(` ⚠ tag-clear failed for ${c.name}: ${err.message.slice(0, 300)}`);
+ }
+ }
+
+ const body = [];
+ const skipped = [];
+ for (const m of c.measured) {
+ if (!m.position) { skipped.push(`${m.key}(${m.reason || 'no-pos'})`); continue; }
+ const sid = stringIdMap.get(m.key);
+ if (!sid) { skipped.push(`${m.key}(no-string-id)`); continue; }
+ body.push({stringId: sid, position: m.position});
+ }
+ if (!body.length) {
+ warn(` ⚠ no manual tags to post; skipped=${skipped.join(',') || 'none'}`);
+ continue;
+ }
+ const postRes = await crowdinFetch(
+ `/projects/${PROJECT_ID}/screenshots/${screenshotId}/tags`,
+ {token, method: 'POST', body},
+ );
+ const postedCount = (postRes?.data ?? []).length;
+ log(` ↑ POSTed ${postedCount} tag(s) → screenshotId=${screenshotId}${skipped.length ? `, skipped=${skipped.join(',')}` : ''}`);
+ } catch (err) {
+ warn(` ✗ manual tagging failed for ${c.name}: ${err.message.slice(0, 300)}`);
+ }
+ }
+
+ log(`Total: ${((Date.now() - totalT0) / 1000).toFixed(1)}s`);
+}
+
+function spawnSyncCapture(cmd, argv, opts) {
+ return spawnSync(cmd, argv, {encoding: 'utf8', ...opts});
+}
+
+main().catch(e => { console.error(e); process.exit(1); });