An open source design system that's fully customizable and agent ready
TypeScript
fix(PowerSearch): a filter token's field, operator and value come from catalog messages (#10437)
Cindy Zhangb47b33a43571
diff --git a/.changeset/powersearch-token-field-operator-message.md b/.changeset/powersearch-token-field-operator-message.mdnew file mode 100644index 0000000000..3fe5eb6a45--- /dev/null+++ b/.changeset/powersearch-token-field-operator-message.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `PowerSearch`: a filter token's field and operator now come from one catalog message (`@astryx.powersearch.token.fieldOperator`, "{field}: {operator}" in English), and its full text, which also names its remove button and editor, joins that label and the value with another (`@astryx.powersearch.token.labelValue`, "{label} {value}"). A locale can reorder the parts and change the punctuation. `PowerSearchToken` uses the same message. English tokens read as before, except that a filter with no operator text no longer shows a trailing colon.++@cixzhangdiff --git a/docs/specs/components/PowerSearch/PowerSearch.spec.md b/docs/specs/components/PowerSearch/PowerSearch.spec.mdindex 0c5978a422..b1e6517d98 100644--- a/docs/specs/components/PowerSearch/PowerSearch.spec.md+++ b/docs/specs/components/PowerSearch/PowerSearch.spec.md@@ -276,7 +276,7 @@ FR10–FR21 govern. FR25 governs a date-only value in both, and FR26 a date-and-| FR21 | A `string_list` or `entity_list` value inside the value step opens the Tokenizer's sheet above the value step, one more sheet of the same stack (FR15a). Escape, a scrim tap, and a swipe dismiss only that topmost sheet; closing it returns focus to its trigger inside the value step; the value step keeps its staged state. | DEC-3; `family:overlay-dismissal`; `component:Tokenizer/FR18` | Current contract; verified by focused sheet tests and real-engine touch evidence. || FR22 | In the `popover` presentation, a read-only field (`isReadOnly`) MUST NOT remove a filter: it shows no Clear all, no token has a remove control, and Backspace on an empty input removes nothing. | The `isReadOnly` prop docs: "Prevent adding, editing, or removing filters." | Current contract || FR23 | In the `popover` presentation, Clear all MUST remove every editable filter and keep every read-only filter: it commits `onChange(<the read-only filters>, 'remove', <index of the first removed filter>)` and announces "Editable filters removed" while a read-only filter remains, otherwise "All filters removed". The clear control MUST render only while `hasClear` is set, the field is neither read-only nor disabled, and at least one editable filter exists. Backspace on an empty input MUST NOT remove a read-only filter; its token has no remove control. | DEC-4; a read-only filter's token has no remove control (current source) | Current contract |-| FR24 | In the popover presentation, a built-in filter token (no `components` Token override) that opens its editor is named by its visible text (field, operator and value); `aria-haspopup="dialog"`, `aria-expanded` is true while its editor is open, and the editor is a dialog named by the token's visible text. Its remove button is named by the remove word and the same visible text. | `spec:AST-020` FR1; WCAG 2.5.3 and 4.1.2; `component:Token/FR10` | Current contract. |+| FR24 | In the popover presentation, a built-in filter token (no `components` Token override) that opens its editor is named by its visible text (field, operator and value); `aria-haspopup="dialog"`, `aria-expanded` is true while its editor is open, and the editor is a dialog named by the token's visible text. Its remove button is named by the remove word and the same visible text. The token's full text is one catalog message; a locale whose full token text is not the label, a space, then the value shows that text in one weight, and the accessible name and the visible text stay the same. A filter whose field the config lacks shows the field key. | `spec:AST-020` FR1; WCAG 2.5.3 and 4.1.2; `component:Token/FR10` | Current contract. || FR25 | In both presentations a `date_absolute` value whose operator has `isDateOnly` unset or `true`, and each `ABSOLUTE` part of a `date_range` value, is a calendar day: the day its `unixSeconds` falls on in `timezoneID` when the prop is set, else the UTC day. The built-in token's text, the filter's accessible label and every announcement that names the value, the Filters row of the sheet presentation, and the date editor of either presentation all read that one day, with no time of day, so one value is never two days in one field; a `components[type].Token` override formats its own value (FR11) and receives `timezoneID` in its props, as the exported `PowerSearchToken` (the default token) does and reads, and a `components[type].Editor` override and `PowerSearchFilterEditor` receive `timezoneID` in their props so they can read the same day. A day picked in an editor is stored as that day's midnight in the same zone — `timezoneID`'s midnight, else UTC midnight — and the editor reopens on the day it stored, so an edit that keeps the day keeps the instant. Nothing about a value is rewritten by rendering or reopening: a value stored before `timezoneID` was given reads as its day in the zone now given. A `date_range` whose part is `NOW` or `RELATIVE` reads that part resolved to an instant first, then as its day. A value whose operator sets `isDateOnly: false` is an instant, not a calendar day: FR26 governs it. | DEC-5; `timezoneID` prop contract; `component:DateInput` (a calendar-day control) | Current contract. || FR26 | A `date_absolute` value whose operator has `isDateOnly: false` is an instant with a time of day. In both presentations its token shows its date and time and the sheet's Filters row shows the same, and its editor reads the stored instant's wall-clock time and stores the wall-clock time entered as the instant it names, both in `timezoneID` when the prop is set, else the viewer's zone — the zone the viewer reads a clock in — so the time typed is the time shown. In the popover presentation that editor is a date picker beside a time field; the sheet presentation's control is FR17's. A `components[type].Editor` override and `PowerSearchFilterEditor` receive `timezoneID` in their props so they can read the same time. A `date_absolute` whose operator has `isDateOnly` unset or `true` keeps its date-only picker and shows no time (FR25). | DEC-6; `OperatorValue.isDateOnly` contract; `component:DateInput`; `component:TimeInput` | Current contract. |diff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 33463386fa..cf0a69cd9f 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -387,6 +387,14 @@"defaultMessage": "{label} {value}","description": "A Filters row's \"field operator\" text joined with its value, as the removal announcement reads it (for example \"Status is Open\"). Translators may reorder the two parts."},+ "@astryx.powersearch.token.fieldOperator": {+ "defaultMessage": "{field}: {operator}",+ "description": "A filter token's field label joined with its operator label, before the token's value (for example \"Status: is\" in \"Status: is Open\"). Both parts are inserted text; translators may reorder them and change the punctuation."+ },+ "@astryx.powersearch.token.labelValue": {+ "defaultMessage": "{label} {value}",+ "description": "A filter token's \"field: operator\" text joined with its value, as the token's full text and the name of its controls read it (for example \"Status: is Open\"). Translators may reorder the two parts."+ },"@astryx.alertDialog.cancel": {"defaultMessage": "Cancel","description": "Button label on the secondary/dismiss button of an AlertDialog (modal confirmation). Imperative verb; consumers usually override with task-specific text."diff --git a/packages/core/src/PowerSearch/PowerSearch.tsx b/packages/core/src/PowerSearch/PowerSearch.tsxindex 22ebd7f13a..6896bd8da5 100644--- a/packages/core/src/PowerSearch/PowerSearch.tsx+++ b/packages/core/src/PowerSearch/PowerSearch.tsx@@ -106,7 +106,12 @@ import type {PowerSearchBottomSheetProps,PowerSearchSheetEditors,} from './PowerSearchBottomSheet';-import {formatTokenValueText} from './formatTokenValue';+import {+ formatTokenLabel,+ formatTokenText,+ formatTokenValueText,+ tokenTextKeepsParts,+} from './formatTokenValue';import {useMergedRefs} from '../hooks/useMergedRefs';import type {FieldStatusPlacement} from '../Field/fieldStatusPlacement';@@ -713,9 +718,11 @@ export function PowerSearch({(filter: PowerSearchFilter) => {const field = config.getField(filter.field);const operator = config.getOperator(filter.field, filter.operator);- const fieldLabel = field?.label ?? '';+ // A field the config no longer has shows its key, so the token keeps+ // a visible text and a name.+ const fieldLabel = field?.label ?? filter.field;const operatorLabel = operator ? resolveOperatorLabel(operator, t) : '';- const label = `${fieldLabel}: ${operatorLabel}`.trim();+ const label = formatTokenLabel(t, fieldLabel, operatorLabel);const value = operator? formatTokenValueText(operator.value,@@ -731,7 +738,11 @@ export function PowerSearch({timezoneID,): null;- return {label, value, full: value != null ? `${label} ${value}` : label};+ return {+ label,+ value,+ full: value != null ? formatTokenText(t, label, value) : label,+ };},[config, maxTokenLength, t, locale, timezoneID, calendar],);@@ -877,7 +888,11 @@ export function PowerSearch({const field = config.getField(filter.field);const operator = config.getOperator(filter.field, filter.operator);const resolvedOp = operator ? resolveOperatorLabel(operator, t) : '';- const operatorLabel = resolvedOp ? `: ${resolvedOp}` : '';+ const label = formatTokenLabel(+ t,+ field?.label ?? filter.field,+ resolvedOp,+ );const valueStr = operator? formatFilterValue(config,@@ -892,8 +907,8 @@ export function PowerSearch({: '';const displayLabel = valueStr- ? `${field?.label ?? filter.field}${operatorLabel} ${valueStr}`- : `${field?.label ?? filter.field}${operatorLabel}`;+ ? formatTokenText(t, label, valueStr)+ : label;return {id: `filter-${index}-${filter.field}-${filter.operator}`,@@ -1121,12 +1136,20 @@ export function PowerSearch({const text =filter != null? tokenText(filter)- : {label: `${fieldLabel}: ${operatorLabel}`.trim(), value: null};- const tokenLabel = text.label;+ : {+ label: formatTokenLabel(t, fieldLabel, operatorLabel),+ value: null,+ };const fullText =- text.value != null ? `${text.label} ${text.value}` : text.label;+ text.value != null+ ? formatTokenText(t, text.label, text.value)+ : text.label;+ // The pill shows the text that names it. A locale that writes the full+ // text in another shape than "label value" gets it as one text.+ const showsParts = text.value == null || tokenTextKeepsParts(t);+ const tokenLabel = showsParts ? text.label : fullText;const valueContent =- text.value != null ? (+ showsParts && text.value != null ? (<PowerSearchTokenValue text={text.value} />) : undefined;diff --git a/packages/core/src/PowerSearch/PowerSearchToken.tsx b/packages/core/src/PowerSearch/PowerSearchToken.tsxindex a16f944040..b9ad6c737d 100644--- a/packages/core/src/PowerSearch/PowerSearchToken.tsx+++ b/packages/core/src/PowerSearch/PowerSearchToken.tsx@@ -20,6 +20,7 @@ import {resolveOperatorLabel} from './resolveOperatorLabel';import {useInternalConfig} from './useInternalConfig';import type {PowerSearchTokenProps} from './types';import {useComponentTranslator} from '../i18n/useComponentTranslator';+import {formatTokenLabel} from './formatTokenValue';const tokenValueStyles = stylex.create({value: {@@ -52,10 +53,7 @@ export function PowerSearchToken({const fieldLabel = field.label;const resolvedOperatorLabel = resolveOperatorLabel(operator, t);- const operatorLabel = resolvedOperatorLabel- ? `: ${resolvedOperatorLabel}`- : '';- const tokenLabel = `${fieldLabel}${operatorLabel}`;+ const tokenLabel = formatTokenLabel(t, fieldLabel, resolvedOperatorLabel);const adjustedMaxLength = Math.max(maxLength - fieldLabel.length - resolvedOperatorLabel.length,diff --git a/packages/core/src/PowerSearch/PowerSearchTokenNaming.test.tsx b/packages/core/src/PowerSearch/PowerSearchTokenNaming.test.tsxindex 63a8110139..f240b6e229 100644--- a/packages/core/src/PowerSearch/PowerSearchTokenNaming.test.tsx+++ b/packages/core/src/PowerSearch/PowerSearchTokenNaming.test.tsx@@ -166,6 +166,31 @@ describe('a PowerSearch filter token', () => {);});+ it('names a token whose field the config lacks by its field key', async () => {+ const user = userEvent.setup();+ render(+ <PowerSearch+ config={config}+ filters={[{...openFilter, field: 'priority'}]}+ onChange={() => {}}+ />,+ );++ const token = screen+ .getAllByRole('button', {name: 'priority'})+ .find(button => button.getAttribute('aria-haspopup') === 'dialog');+ expect(token).toBeDefined();+ expect(token).toHaveTextContent(/^priority$/);+ expect(+ screen.getByRole('button', {name: 'Remove priority'}),+ ).toBeInTheDocument();+ await user.click(token!);++ expect(+ await screen.findByRole('dialog', {name: 'priority', hidden: true}),+ ).toBeInTheDocument();+ });+it('keeps the plain popover for a token from a components override', async () => {const user = userEvent.setup();function CustomToken({onClick}: PowerSearchTokenProps) {@@ -232,6 +257,60 @@ describe('a PowerSearch filter token', () => {expect(document.querySelector('[aria-haspopup]')).toBeNull();});+ it("joins the field and operator in the locale's order", () => {+ render(+ <InternationalizationProvider+ locale="ja"+ messages={{+ ja: {+ '@astryx.powersearch.token.fieldOperator': {+ defaultMessage: '{operator}({field})',+ },+ },+ }}>+ <PowerSearch+ config={config}+ filters={[openFilter]}+ onChange={() => {}}+ />+ </InternationalizationProvider>,+ );+ expect(screen.getByText('is(Status)')).toBeInTheDocument();+ });++ it("names the token, its editor and its pill by one text in the locale's order", async () => {+ const user = userEvent.setup();+ render(+ <InternationalizationProvider+ locale="ja"+ messages={{+ ja: {+ '@astryx.powersearch.token.labelValue': {+ defaultMessage: '{value}({label})',+ },+ },+ }}>+ <PowerSearch+ config={config}+ filters={[openFilter]}+ onChange={() => {}}+ />+ </InternationalizationProvider>,+ );+ const token = screen.getByRole('button', {name: 'Open(Status: is)'});+ // The pill shows the same text it is named by.+ expect(token).toHaveTextContent(/^Open(Status: is)$/);++ await user.click(token);++ expect(+ await screen.findByRole('dialog', {+ name: 'Open(Status: is)',+ hidden: true,+ }),+ ).toBeInTheDocument();+ });+it('keeps a verb-last locale order in the remove button name', () => {render(<InternationalizationProviderdiff --git a/packages/core/src/PowerSearch/formatTokenValue.ts b/packages/core/src/PowerSearch/formatTokenValue.tsindex 96e4450678..4099243d46 100644--- a/packages/core/src/PowerSearch/formatTokenValue.ts+++ b/packages/core/src/PowerSearch/formatTokenValue.ts@@ -5,7 +5,10 @@** @input `OperatorValue`, `FilterValue`, a width budget, the locale, and the* calendar.- * @output `formatTokenValueText` — one string, or null for an empty value.+ * @output `formatTokenValueText` — one string, or null for an empty value;+ * `formatTokenLabel` and `formatTokenText` — the token's "field: operator"+ * label and its full text, each one catalog message; `tokenTextKeepsParts` —+ * whether the full text is the label, a space, then the value.* @position Shared by the token itself (`PowerSearch.tsx`) and the sheet* presentation's Filters rows and removal announcement* (`PowerSearchBottomSheet.tsx`), so every reading of a value on the field@@ -24,6 +27,48 @@ registerEnglishFallback(english);type ListFormatFn = (items: ReadonlyArray<string>) => string;+/**+ * A filter token's label: its field and operator, joined by one catalog+ * message so a locale can reorder them. A filter with no operator text shows+ * its field alone.+ */+export function formatTokenLabel(+ t: TranslatorFn,+ fieldLabel: string,+ operatorLabel: string,+): string {+ if (operatorLabel === '') {+ return fieldLabel;+ }+ return t('@astryx.powersearch.token.fieldOperator', {+ field: fieldLabel,+ operator: operatorLabel,+ });+}++/** A filter token's full text: its label and its value, in one message. */+export function formatTokenText(+ t: TranslatorFn,+ label: string,+ value: string,+): string {+ return t('@astryx.powersearch.token.labelValue', {label, value});+}++// Characters no message text uses, to find where the catalog puts each part.+const LABEL_MARK = '\uE000';+const VALUE_MARK = '\uE001';++/**+ * Whether the locale writes a token's full text as its label, a space, then+ * its value. Only then can the pill show the label and the styled value as+ * two parts and still read as the full text that names it.+ */+export function tokenTextKeepsParts(t: TranslatorFn): boolean {+ const pattern = formatTokenText(t, LABEL_MARK, VALUE_MARK);+ return new RegExp(`^${LABEL_MARK}\\s+${VALUE_MARK}$`).test(pattern);+}+function truncateString(value: string, limit: number): string {// Same semantics as before — strings within limit + 3 pass through, longer// ones cut to limit + '...' — but counted in characters, not code units.