An open source design system that's fully customizable and agent ready
TypeScript
fix(PowerSearch): name a filter token by its visible text and expose its editor (#9687)
Cindy Zhange68774f5b8aa
diff --git a/.changeset/powersearch-token-name.md b/.changeset/powersearch-token-name.mdnew file mode 100644index 0000000000..474628a294--- /dev/null+++ b/.changeset/powersearch-token-name.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] PowerSearch: in the popover presentation, a built-in filter token's button was named by its field and operator only ("Status: is") and gave no sign that it opens an editor. Two filters on one field sounded the same, and the visible value was missing from the name. Now the token is named by all its visible text ("Status: is Open"), has `aria-haspopup="dialog"` and `aria-expanded`, and opens an editor that is a dialog of the same name. Its remove button is "Remove Status: is Open". Token: `aria-haspopup` and `aria-expanded` now reach a clickable token's inner button, beside `aria-labelledby` and `aria-describedby`.++@cixzhangdiff --git a/docs/specs/components/PowerSearch/PowerSearch.spec.md b/docs/specs/components/PowerSearch/PowerSearch.spec.mdindex ca5d10afff..ce5025b8cf 100644--- a/docs/specs/components/PowerSearch/PowerSearch.spec.md+++ b/docs/specs/components/PowerSearch/PowerSearch.spec.md@@ -199,7 +199,7 @@ Current requirements identify their basis and distinguish accepted contract fromimplementation status. The contract is authoritative; the behavior remains unshippeduntil its implementation and verification complete.-FR1–FR9, FR22, and FR23 govern the `popover` presentation — the tokenizer field and its editor+FR1–FR9 and FR22–FR24 govern the `popover` presentation — the tokenizer field and its editorpopover, rendered when `experimental` is omitted or resolves to `popover`. Theeditor popover does not render in the `bottom-sheet` presentation, whose surfaceFR10–FR21 govern.@@ -230,6 +230,7 @@ FR10–FR21 govern.| 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. Implementation gap: no nested sheet exists. || 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. |### Allowed variation@@ -501,6 +502,7 @@ mark implementation and focused real-Chromium verification as pending.| FR8, AR1–AR3 | Existing PowerSearch/editor suites plus focused browser checks | Pointer and keyboard edit, apply, cancel, Escape, light dismiss, focus return, selection, semantics | Focus, semantics, selection, dismissal, or reachability changes fail. | `audit:PowerSearch/accessibility` || FR22 | PowerSearch and Tokenizer unit tests | A read-only field with a filter: no Clear all, no token remove control, Backspace on the empty input | A read-only field removes a filter through Backspace, Clear all, or a token control. | `audit:PowerSearch/interaction` || FR23 | PowerSearch and Tokenizer unit tests | Clear all with a read-only filter before two editable ones; every filter read-only; Backspace with a read-only last filter; the words with and without a read-only filter left | A read-only filter is removed, Clear all reports an index other than the first removed one, Clear all shows with no editable filter, or its words say every filter went while one remains. | `audit:PowerSearch/interaction` |+| FR24 | `PowerSearchTokenNaming.test.tsx`; real-Chromium accessibility tree of a popover token | Popover token with a value, read-only token, editor open and closed, a verb-last remove word | A token named without its value, a missing or stale `aria-expanded`, an unnamed or non-dialog editor, or a remove name that loses its locale's word order fails. | `audit:PowerSearch/accessibility` || FR10–FR21, AR4–AR6, PR5 | Focused PowerSearch sheet tests with the compact-touch query stubbed both ways, plus real-engine touch evidence (implementation gap: not yet in the tree; the Lab prototype's suite, `packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx`, is the current evidence for the flow the rows describe) | default popover, forced sheet, adaptive both ways (server markup and hydration as the popover field on a coarse-pointer client, then the trigger, no recoverable error, focus on the body; with `hasAutoFocus`, the autofocused input's focus ending on the trigger with no `onBlur` or `onFocus` to the caller), trigger name, Filters/Add filter/value steps, each value type, list value through the Tokenizer sheet, Clear all, read-only, disabled while open, focus after each step, focus after an `adaptive` switch from the trigger, the input, a removed control, an open editor popover, and from outside the field, a field inside an open Dialog announcing the count, Clear all, and in-sheet messages inside that Dialog and never on the page body, StrictMode result count, in-sheet live region while a sheet is open (added, removed, count, empty results), Clear all announced only after the dialog's exit, row, token and Removed text sharing one formatter, a date-only value as its day in `timezoneID`, else the UTC day, and a date-and-time value in `timezoneID`, else the viewer's zone, on all three (UTC, Tokyo, Honolulu, unset), summaries and relative-date labels and values from the catalog, the row and Removed through one reorderable message, an unmatched relative-date value as stored, a filter the config no longer knows listed and removable, a cleared number unstaged, choice rows as radios and checkboxes with `aria-checked`, a stale read-only filter as a plain row, a removal next to a nested row focusing that row's remove action, a list value joined by the locale's narrow conjunction list in English, Simplified Chinese, Japanese, and German, an empty-result message spoken once per query from its rendered element, a controlled update that removes the edited field moving focus from the replaced body to Cancel and announcing the unavailable state in the sheet while the step is open and never from a step beneath another or retained closed, Apply and Cancel after a controlled update removed the edited filter focusing the nearest row, else Add filter, a row's trailing remove action focusing the next row's remove action, a one-tap `empty`-valued filter added from its field row and removed from its row, Clear all behind its confirmation keeping read-only filters and leaving Filters open, a dismissed step revealing the step beneath with focus restored to it, Add filter opening with its search unfocused and a touch drag on the rows blurring a focused search, a stale filter's step titled as its row reads (raw keys for what is gone, the field's label when the field remains), Cancel from creation after the opening field was removed focusing the Add filter sheet's first control, a removed focused Filters row, a removed Clear all, and a dropped focused field row each handing focus to the nearest remaining row or the sheet's first control, element counts at rest and with each of the Filters, Add filter and value sheets open, and with the Tokenizer's list-value sheet stacked above the value step, under fine and coarse pointers, nothing of the flow in the DOM at rest before a press and after the exit, a nested filter edited and created through the built-in nested editor (its sub-filter rows wrapping inside a 390 and a 414 px sheet; its root operator picker absent on a mixed field, the Operator group in its place), a nested-only field and its suggestion offered, a suggestion's operator checked over the field's default, the Operator group outside a caller's Editor override on a mixed field, a count changed during the exit spoken with Clear all's message as one catalog message after the close, a radio group's arrow keys, Home, and End moving and checking, Space and Enter checking a focused radio row and toggling a checkbox row, right-to-left layout with the row chevrons mirrored in RTL (`design:bidirectionality/DR4`) | A field without `experimental` changes beyond what FR19 states, a value commits before the step confirms, Clear all removes a read-only filter, the trigger carries native `disabled`, focus lands elsewhere, an announcement reaches a channel outside the modal that holds the field at that moment, or the popover bundle carries the sheets. | `audit:PowerSearch/sheet` || Record structure | `scripts/check-knowledge.mjs` | Component-contract schema and current-authority dependency | Missing or invalid metadata and sections fail repository validation. | `audit:PowerSearch/knowledge` |diff --git a/docs/specs/components/Token/Token.spec.md b/docs/specs/components/Token/Token.spec.mdindex a7a7c57ca2..9f7a4879cb 100644--- a/docs/specs/components/Token/Token.spec.md+++ b/docs/specs/components/Token/Token.spec.md@@ -130,7 +130,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR7 | The label never wraps: the root is capped at its container's inline size and clips overflow. In the static and link structures the Label ends in an ellipsis; in the clickable and link-and-remove structures the inner control clips the Label without an ellipsis. `isLabelHidden` keeps the Label in the DOM with a visually hidden clip treatment. | Current source and tests || FR8 | `color` defaults to `default`, painting `--color-neutral` with primary text; every other built-in tone paints its tinted background with its matching colored text. The `token` target reflects the resolved `color` and `size` for every value, including a theme-added color, which receives no component fill or text color until a theme paints it. | Current source and tests || FR9 | Clickable and link structures paint the shared hover overlay under a hover-capable pointer and the shared pressed overlay for mouse and touch presses; the static structure paints neither. | Current source |-| FR10 | `ref` reaches the root element of every structure. Supported DOM, ARIA, data, and event props reach the root, except that in the clickable structure `aria-labelledby` and `aria-describedby` reach the inner button, the element that owns the token's action (`architecture:public-component-api` INV5); `data-testid` reaches the root; `xstyle`, `className`, and `style` merge in that order after component styles. | Current source and tests |+| FR10 | `ref` reaches the root element of every structure. Supported DOM, ARIA, data, and event props reach the root, except that in the clickable structure `aria-labelledby`, `aria-describedby`, `aria-haspopup` and `aria-expanded` reach the inner button, the element that owns the token's action (`architecture:public-component-api` INV5); `data-testid` reaches the root; `xstyle`, `className`, and `style` merge in that order after component styles. | Current source and tests |### Allowed variation@@ -142,15 +142,15 @@ Consumer migration instructions belong in consumer docs and release notes.### Representative states-| State | Required invariant | Allowed variation |-| ------------------ | ------------------------------------------------------------------------------------------------------- | --------------------------- |-| Static | `span` root; Token adds no focusable element except a Remove button. | Tone, size, slots. |-| Clickable | One inner button named by the label, or by a caller `aria-labelledby`; container click calls `onClick`. | End content. |-| Link | Root is the link; focus outline on the link itself. | Router link component. |-| Link and remove | Container holds a link and a sibling Remove button; surface click activates the link. | Modified and middle clicks. |-| Removable | Remove button named "Remove {label}" with a 24 by 24 CSS pixel target. | Locale wording. |-| Disabled clickable | Buttons focusable with `aria-disabled="true"`; no callback fires; half opacity. | Tone. |-| Hidden label | Label text visually hidden; the root's `aria-label` equals the label. | Structure. |+| State | Required invariant | Allowed variation |+| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- |+| Static | `span` root; Token adds no focusable element except a Remove button. | Tone, size, slots. |+| Clickable | One inner button named by the label, by a caller `aria-labelledby`, or inside PowerSearch by the filter token's full visible text (AR2); container click calls `onClick`. | End content. |+| Link | Root is the link; focus outline on the link itself. | Router link component. |+| Link and remove | Container holds a link and a sibling Remove button; surface click activates the link. | Modified and middle clicks. |+| Removable | Remove button named "Remove {label}" (inside PowerSearch, over the full visible text, AR2) with a 24 by 24 CSS pixel target. | Locale wording. |+| Disabled clickable | Buttons focusable with `aria-disabled="true"`; no callback fires; half opacity. | Tone. |+| Hidden label | Label text visually hidden; the root's `aria-label` equals the label. | Structure. |### Transformation and precedence order@@ -182,7 +182,10 @@ Consumer migration instructions belong in consumer docs and release notes.from a caller `aria-labelledby` (FR10). In the link structure the linkis the root and takes its name from all of its content, including End content(a label "Inbox" with a count reads "Inbox 12"). The- Remove button is named by the translated "Remove {label}" string.+ Remove button is named by the translated "Remove {label}" string. Inside+ PowerSearch, whose filter tokens show their value after the Label, a filter+ token's inner button is named by its full visible text, and its Remove button+ by the same translated string over that text.- **AR3 — Hidden label.** With `isLabelHidden`, the Label text stays in theaccessibility tree and names the token, and no element with the generic rolecarries a name (WAI-ARIA 1.2). The root carries `aria-label` equal to thediff --git a/packages/core/src/PowerSearch/PowerSearch.test.tsx b/packages/core/src/PowerSearch/PowerSearch.test.tsxindex fa841e83f2..b5f7dcc60e 100644--- a/packages/core/src/PowerSearch/PowerSearch.test.tsx+++ b/packages/core/src/PowerSearch/PowerSearch.test.tsx@@ -218,7 +218,7 @@ describe('PowerSearch', () => {expect(screen.getAllByRole('button', {name: /^Remove /})).toHaveLength(2);await user.click(- screen.getAllByRole('button', {name: 'Remove Status: is'})[0],+ screen.getAllByRole('button', {name: 'Remove Status: is Open'})[0],);expect(screen.getAllByRole('button', {name: /^Remove /})).toHaveLength(1);@@ -757,7 +757,7 @@ describe('filter token focus', () => {await user.tab({shift: true}); // Remove buttonawait user.tab({shift: true}); // Token label- expect(screen.getByRole('button', {name: 'Status: is'})).toHaveFocus();+ expect(screen.getByRole('button', {name: 'Status: is Open'})).toHaveFocus();await user.keyboard('{Enter}');expect(await screen.findByRole('button', {name: 'Apply', hidden: true}),@@ -844,7 +844,7 @@ describe('maxOperatorMenuItems', () => {/>,);- await user.click(screen.getByRole('button', {name: 'Person: is any of'}));+ await user.click(screen.getByRole('button', {name: /^Person: is any of /}));const inputs = screen.getAllByRole('combobox', {hidden: true});const valueInput = inputs[inputs.length - 1];await user.type(valueInput, 'Person');diff --git a/packages/core/src/PowerSearch/PowerSearch.tsx b/packages/core/src/PowerSearch/PowerSearch.tsxindex 0917c28494..697b9f9faa 100644--- a/packages/core/src/PowerSearch/PowerSearch.tsx+++ b/packages/core/src/PowerSearch/PowerSearch.tsx@@ -34,6 +34,7 @@ import {TokenizerClearAllMessageContext} from '../Tokenizer/TokenizerClearAllMesimport {TokenizerItemRemovableContext} from '../Tokenizer/TokenizerItemRemovableContext';import {TypeaheadItem} from '../Typeahead/TypeaheadItem';import {Token} from '../Token';+import {TokenNamingContext} from '../Token/TokenNamingContext';import {Avatar} from '../Avatar';import {layerAnimations} from '../Layer/layerAnimations.stylex';import {Icon} from '../Icon';@@ -75,6 +76,7 @@ import type {OperatorValue,EnumItem,PowerSearchComponents,+ PowerSearchOperator,} from './types';import {useMergedRefs} from '../hooks/useMergedRefs';@@ -158,52 +160,35 @@ function getEnumLabel(values: ReadonlyArray<EnumItem>, value: string): string {return values.find(v => v.value === value)?.label ?? value;}-function PowerSearchTokenValue({- operatorValue,- filterValue,- maxLength,- locale,-}: {- operatorValue: OperatorValue;- filterValue: FilterValue;- maxLength: number;- locale: Locale;-}) {+/**+ * The visible text of a filter token's value. The token renders it, and the+ * token's remove button and editor dialog are named by the same text.+ */+function tokenValueText(+ operatorValue: OperatorValue,+ filterValue: FilterValue,+ maxLength: number,+ locale: Locale,+): string | null {switch (filterValue.type) {case 'empty':return null;case 'string':- return (- <span {...stylex.props(tokenValueStyles.value)}>- {truncateString(filterValue.value, maxLength)}- </span>- );+ return truncateString(filterValue.value, maxLength);case 'integer':case 'float':- return (- <span {...stylex.props(tokenValueStyles.value)}>- {filterValue.value}- </span>- );+ return String(filterValue.value);case 'enum':if (operatorValue.type === 'enum') {- return (- <span {...stylex.props(tokenValueStyles.value)}>- {truncateString(- getEnumLabel(operatorValue.values, filterValue.value),- maxLength,- )}- </span>+ return truncateString(+ getEnumLabel(operatorValue.values, filterValue.value),+ maxLength,);}- return (- <span {...stylex.props(tokenValueStyles.value)}>- {truncateString(filterValue.value, maxLength)}- </span>- );+ return truncateString(filterValue.value, maxLength);case 'string_list': {const items = filterValue.value;@@ -211,25 +196,13 @@ function PowerSearchTokenValue({return null;}if (items.length === 1) {- return (- <span {...stylex.props(tokenValueStyles.value)}>- {truncateString(items[0], maxLength)}- </span>- );+ return truncateString(items[0], maxLength);}const totalLength = items.reduce((sum, s) => sum + s.length, 0);if (totalLength > maxLength) {- return (- <span {...stylex.props(tokenValueStyles.value)}>- {items.length} items- </span>- );+ return `${items.length} items`;}- return (- <span {...stylex.props(tokenValueStyles.value)}>- {items.join(', ')}- </span>- );+ return items.join(', ');}case 'enum_list': {@@ -240,38 +213,18 @@ function PowerSearchTokenValue({if (operatorValue.type === 'enum_list') {const labels = items.map(v => getEnumLabel(operatorValue.values, v));if (labels.length === 1) {- return (- <span {...stylex.props(tokenValueStyles.value)}>- {truncateString(labels[0], maxLength)}- </span>- );+ return truncateString(labels[0], maxLength);}const totalLength = labels.reduce((sum, s) => sum + s.length, 0);if (totalLength > maxLength) {- return (- <span {...stylex.props(tokenValueStyles.value)}>- {labels.length} items- </span>- );+ return `${labels.length} items`;}- return (- <span {...stylex.props(tokenValueStyles.value)}>- {labels.join(', ')}- </span>- );+ return labels.join(', ');}if (items.length === 1) {- return (- <span {...stylex.props(tokenValueStyles.value)}>- {truncateString(items[0], maxLength)}- </span>- );+ return truncateString(items[0], maxLength);}- return (- <span {...stylex.props(tokenValueStyles.value)}>- {items.length} items- </span>- );+ return `${items.length} items`;}case 'entity_list': {@@ -280,80 +233,42 @@ function PowerSearchTokenValue({return null;}if (entities.length === 1) {- return (- <span {...stylex.props(tokenValueStyles.value)}>- {truncateString(entities[0].label, maxLength)}- </span>- );+ return truncateString(entities[0].label, maxLength);}const totalLength = entities.reduce((sum, e) => sum + e.label.length, 0);if (totalLength > maxLength) {- return (- <span {...stylex.props(tokenValueStyles.value)}>- {entities.length} items- </span>- );+ return `${entities.length} items`;}- return (- <span {...stylex.props(tokenValueStyles.value)}>- {entities.map(e => e.label).join(', ')}- </span>- );+ return entities.map(e => e.label).join(', ');}case 'time':- return (- <span {...stylex.props(tokenValueStyles.value)}>- {filterValue.value}- </span>- );+ return filterValue.value;- case 'date_absolute': {- const formatted = formatDateAbsoluteCompact(- filterValue.unixSeconds,- locale,+ case 'date_absolute':+ return truncateString(+ formatDateAbsoluteCompact(filterValue.unixSeconds, locale),+ maxLength,);- return (- <span {...stylex.props(tokenValueStyles.value)}>- {truncateString(formatted, maxLength)}- </span>- );- }case 'date_relative':- return (- <span {...stylex.props(tokenValueStyles.value)}>- {truncateString(filterValue.value, maxLength)}- </span>- );+ return truncateString(filterValue.value, maxLength);case 'date_range':- return <span {...stylex.props(tokenValueStyles.value)}>date range</span>;+ return 'date range';case 'custom':if (operatorValue.type === 'custom') {- return (- <span {...stylex.props(tokenValueStyles.value)}>- {truncateString(- operatorValue.getString(filterValue.value),- maxLength,- )}- </span>+ return truncateString(+ operatorValue.getString(filterValue.value),+ maxLength,);}- return (- <span {...stylex.props(tokenValueStyles.value)}>- {filterValue.value}- </span>- );+ return filterValue.value;case 'nested': {const count = filterValue.value.length;- return (- <span {...stylex.props(tokenValueStyles.value)}>- {count === 1 ? '1 filter' : `${count} filters`}- </span>- );+ return count === 1 ? '1 filter' : `${count} filters`;}default:@@ -361,6 +276,10 @@ function PowerSearchTokenValue({}}+function PowerSearchTokenValue({text}: {text: string}) {+ return <span {...stylex.props(tokenValueStyles.value)}>{text}</span>;+}+// =============================================================================// Types// =============================================================================@@ -491,6 +410,20 @@ type PopoverState =// Component// =============================================================================+/**+ * Whether a press on a token with this operator commits the filter instead of+ * opening its editor: an `empty` operator with no `empty` Editor override.+ */+function commitsWithoutEditor(+ operator: PowerSearchOperator | undefined,+ componentOverrides: PowerSearchComponents | undefined,+): boolean {+ return (+ operator?.value.type === 'empty' &&+ componentOverrides?.empty?.Editor == null+ );+}+/*** Structured filter bar where each token represents a filter (field + operator + value).*@@ -608,6 +541,47 @@ export function PowerSearch({type: 'idle',});+ // A default filter token's visible text: its label (field and operator)+ // and its value. The token's remove button and editor dialog are named by+ // the same text.+ const tokenText = useCallback(+ (filter: PowerSearchFilter) => {+ const field = config.getField(filter.field);+ const operator = config.getOperator(filter.field, filter.operator);+ const fieldLabel = field?.label ?? '';+ const operatorLabel = operator ? resolveOperatorLabel(operator, t) : '';+ const label = `${fieldLabel}: ${operatorLabel}`.trim();+ const value = operator+ ? tokenValueText(+ operator.value,+ filter.value,+ Math.max(+ maxTokenLength - fieldLabel.length - operatorLabel.length,+ 10,+ ),+ locale,+ )+ : null;+ return {label, value, full: value != null ? `${label} ${value}` : label};+ },+ [config, maxTokenLength, t, locale],+ );+ // The built-in token being edited. A token from a `components` override+ // names itself, so its editor keeps the plain popover.+ const editedFilter =+ popoverState.type === 'editing'+ ? filters[popoverState.filterIndex]+ : undefined;+ const editedOperator =+ editedFilter != null+ ? config.getOperator(editedFilter.field, editedFilter.operator)+ : undefined;+ const editedBuiltInFilter =+ editedOperator == null ||+ componentOverrides?.[editedOperator.value.type]?.Token == null+ ? editedFilter+ : undefined;+// Layer for positioning the edit popover anchored to the tokenizerconst handleLayerHide = useCallback(() => {setPopoverStateRaw({type: 'idle'});@@ -618,9 +592,16 @@ export function PowerSearch({hasLightDismiss: true,hasCloseButton: false,hasAutoFocus: false,- // The popup's own listbox/menu content is the exposed semantics; focus- // stays on the tokenizer input, so a modal dialog wrapper is incorrect.- role: 'none',+ // Adding: the popup's own listbox/menu content is the exposed semantics,+ // and focus stays on the tokenizer input, so a dialog wrapper is+ // incorrect. Editing a token: focus moves into the editor's controls, so+ // the editor is a non-modal dialog named by the token's visible text.+ role: editedBuiltInFilter != null ? 'dialog' : 'none',+ isModal: false,+ dialogLabel:+ editedBuiltInFilter != null+ ? tokenText(editedBuiltInFilter).full+ : undefined,});// Wrapper that manages layer visibility and tokenizer focus alongside state@@ -789,10 +770,7 @@ export function PowerSearch({// edit: commit it as that editor's save would, the way adding one does,// instead of opening it. A consumer's `empty` Editor override still opens.const operator = config.getOperator(filter.field, filter.operator);- if (- operator?.value.type === 'empty' &&- componentOverrides?.empty?.Editor == null- ) {+ if (commitsWithoutEditor(operator, componentOverrides)) {const newFilters = [...filters];newFilters[index] = {field: filter.field,@@ -897,20 +875,16 @@ export function PowerSearch({// Default token renderingconst fieldLabel = field?.label ?? '';const operatorLabel = operator ? resolveOperatorLabel(operator, t) : '';- const tokenLabel = `${fieldLabel}: ${operatorLabel}`.trim();- const adjustedMaxLength = Math.max(- maxTokenLength - fieldLabel.length - operatorLabel.length,- 10,- );-+ const text =+ filter != null+ ? tokenText(filter)+ : {label: `${fieldLabel}: ${operatorLabel}`.trim(), value: null};+ const tokenLabel = text.label;+ const fullText =+ text.value != null ? `${text.label} ${text.value}` : text.label;const valueContent =- operator && filter ? (- <PowerSearchTokenValue- operatorValue={operator.value}- filterValue={filter.value}- maxLength={adjustedMaxLength}- locale={locale}- />+ text.value != null ? (+ <PowerSearchTokenValue text={text.value} />) : undefined;// Show entity photo as token icon for single-entity filters@@ -924,32 +898,49 @@ export function PowerSearch({tokenIcon = <Avatar src={entity.photo} name={entity.label} size={16} />;}+ // A token that opens its editor says that it opens a dialog, and the+ // naming context names it by all its visible text.+ const editorProps =+ handleClick != null &&+ !commitsWithoutEditor(operator, componentOverrides)+ ? {+ 'aria-haspopup': 'dialog' as const,+ 'aria-expanded':+ popoverState.type === 'editing' &&+ popoverState.filterIndex === filterIndex,+ }+ : null;+return (- <Token- label={tokenLabel}- size={size}- icon={tokenIcon}- endContent={valueContent}- onMouseDown={- handleClick- ? e => {- // Keep a token press from entering Tokenizer's input-focus- // redirect. Click still edits/removes; Tab entry is unchanged.- e.preventDefault();- }- : undefined- }- onClick={- handleClick- ? (e: React.MouseEvent) => {- e.stopPropagation();- handleClick();- }- : undefined- }- onRemove={handleRemove}- isDisabled={isDisabled}- />+ <TokenNamingContext+ value={{actionName: fullText, removeName: fullText}}>+ <Token+ label={tokenLabel}+ size={size}+ icon={tokenIcon}+ {...editorProps}+ endContent={valueContent}+ onMouseDown={+ handleClick+ ? e => {+ // Keep a token press from entering Tokenizer's input-focus+ // redirect. Click still edits/removes; Tab entry is unchanged.+ e.preventDefault();+ }+ : undefined+ }+ onClick={+ handleClick+ ? (e: React.MouseEvent) => {+ e.stopPropagation();+ handleClick();+ }+ : undefined+ }+ onRemove={handleRemove}+ isDisabled={isDisabled}+ />+ </TokenNamingContext>);},[@@ -957,13 +948,14 @@ export function PowerSearch({config,configProp,maxTokenLength,- locale,size,isReadOnly,isDisabled,handleTokenClick,componentOverrides,t,+ popoverState,+ tokenText,],);diff --git a/packages/core/src/PowerSearch/PowerSearchTokenNaming.test.tsx b/packages/core/src/PowerSearch/PowerSearchTokenNaming.test.tsxnew file mode 100644index 0000000000..63a8110139--- /dev/null+++ b/packages/core/src/PowerSearch/PowerSearchTokenNaming.test.tsx@@ -0,0 +1,253 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file PowerSearchTokenNaming.test.tsx+ * @input Uses vitest, @testing-library/react and PowerSearch+ * @output Tests that a popover filter token's action is named by all its+ * visible text, says it opens a dialog and whether it is open, that the+ * editor is a dialog of that name, and that its remove button is named by+ * the remove word and that text in each locale's word order+ * @position Core testing; validates token naming in PowerSearch.tsx and the+ * ARIA routing in Token.tsx+ */++import {render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {describe, expect, it} from 'vitest';+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';+import {PowerSearch} from './PowerSearch';+import type {+ PowerSearchConfig,+ PowerSearchFilter,+ PowerSearchTokenProps,+} from './types';++const config: PowerSearchConfig = {+ name: 'Issues',+ fields: [+ {+ key: 'status',+ label: 'Status',+ defaultOperator: 'is',+ operators: [+ {+ key: 'is',+ label: 'is',+ value: {+ type: 'enum',+ values: [+ {value: 'open', label: 'Open'},+ {value: 'closed', label: 'Closed'},+ ],+ },+ },+ ],+ },+ ],+};++const openFilter: PowerSearchFilter = {+ field: 'status',+ operator: 'is',+ value: {type: 'enum', value: 'open'},+};++describe('a PowerSearch filter token', () => {+ it('is named by its field, operator and value', () => {+ render(+ <PowerSearch+ config={config}+ filters={[openFilter]}+ onChange={() => {}}+ />,+ );+ expect(+ screen.getByRole('button', {name: 'Status: is Open'}),+ ).toBeInTheDocument();+ expect(+ screen.getByRole('button', {name: 'Remove Status: is Open'}),+ ).toBeInTheDocument();+ });++ it('says it opens a dialog, and whether that dialog is open', async () => {+ const user = userEvent.setup();+ render(+ <PowerSearch+ config={config}+ filters={[openFilter]}+ onChange={() => {}}+ />,+ );+ const token = screen.getByRole('button', {name: 'Status: is Open'});+ expect(token).toHaveAttribute('aria-haspopup', 'dialog');+ expect(token).toHaveAttribute('aria-expanded', 'false');++ await user.click(token);++ expect(token).toHaveAttribute('aria-expanded', 'true');+ expect(+ await screen.findByRole('dialog', {+ name: 'Status: is Open',+ hidden: true,+ }),+ ).toBeInTheDocument();+ });++ it('names the remove button and the editor by the text the token shows', async () => {+ const user = userEvent.setup();+ const sizeConfig: PowerSearchConfig = {+ name: 'Files',+ fields: [+ {+ key: 'lines',+ label: 'Line count',+ defaultOperator: 'gt',+ operators: [+ {+ key: 'gt',+ label: 'is greater than',+ value: {type: 'integer', units: 'lines'},+ },+ ],+ },+ ],+ };+ render(+ <PowerSearch+ config={sizeConfig}+ filters={[+ {+ field: 'lines',+ operator: 'gt',+ value: {type: 'integer', value: 100},+ },+ ]}+ onChange={() => {}}+ />,+ );+ const token = screen.getByRole('button', {+ name: 'Line count: is greater than 100',+ });+ expect(+ screen.getByRole('button', {+ name: 'Remove Line count: is greater than 100',+ }),+ ).toBeInTheDocument();++ await user.click(token);++ expect(+ await screen.findByRole('dialog', {+ name: 'Line count: is greater than 100',+ hidden: true,+ }),+ ).toBeInTheDocument();+ });++ it('opens a named dialog for a token whose operator the config lacks', async () => {+ const user = userEvent.setup();+ render(+ <PowerSearch+ config={config}+ filters={[{...openFilter, operator: 'was'}]}+ onChange={() => {}}+ />,+ );++ const token = screen+ .getAllByRole('button', {name: /^Status/})+ .find(button => button.getAttribute('aria-haspopup') === 'dialog');+ expect(token).toBeDefined();+ await user.click(token!);++ const dialog = await screen.findByRole('dialog', {hidden: true});+ expect(dialog).toHaveAccessibleName(+ token!.getAttribute('aria-label') ?? '',+ );+ });++ it('keeps the plain popover for a token from a components override', async () => {+ const user = userEvent.setup();+ function CustomToken({onClick}: PowerSearchTokenProps) {+ return (+ <button type="button" onClick={onClick}>+ Custom status+ </button>+ );+ }+ render(+ <PowerSearch+ config={config}+ filters={[openFilter]}+ onChange={() => {}}+ components={{enum: {Token: CustomToken}}}+ />,+ );++ await user.click(screen.getByRole('button', {name: 'Custom status'}));++ expect(+ await screen.findByRole('button', {name: 'Apply', hidden: true}),+ ).toBeInTheDocument();+ expect(screen.queryByRole('dialog', {hidden: true})).toBeNull();+ });++ it('offers no editor on a token whose press commits it', () => {+ const emptyConfig: PowerSearchConfig = {+ name: 'Messages',+ fields: [+ {+ key: 'unread',+ label: 'Unread',+ defaultOperator: 'only',+ operators: [{key: 'only', label: 'only', value: {type: 'empty'}}],+ },+ ],+ };+ render(+ <PowerSearch+ config={emptyConfig}+ filters={[{field: 'unread', operator: 'only', value: {type: 'empty'}}]}+ onChange={() => {}}+ />,+ );++ const token = screen+ .getAllByRole('button', {name: /Unread/})+ .find(button => !button.textContent?.startsWith('Remove'));+ expect(token).toBeDefined();+ expect(token).not.toHaveAttribute('aria-haspopup');+ expect(token).not.toHaveAttribute('aria-expanded');+ });++ it('offers no editor on a read-only token', () => {+ render(+ <PowerSearch+ config={config}+ filters={[openFilter]}+ onChange={() => {}}+ isReadOnly+ />,+ );+ expect(document.querySelector('[aria-haspopup]')).toBeNull();+ });++ it('keeps a verb-last locale order in the remove button name', () => {+ render(+ <InternationalizationProvider+ locale="de"+ messages={{+ de: {'@astryx.token.remove': {defaultMessage: '{label} entfernen'}},+ }}>+ <PowerSearch+ config={config}+ filters={[openFilter]}+ onChange={() => {}}+ />+ </InternationalizationProvider>,+ );+ expect(+ screen.getByRole('button', {name: /^Status: .* Open entfernen$/}),+ ).toBeInTheDocument();+ });+});diff --git a/packages/core/src/Token/Token.test.tsx b/packages/core/src/Token/Token.test.tsxindex c44e40666b..328f282a46 100644--- a/packages/core/src/Token/Token.test.tsx+++ b/packages/core/src/Token/Token.test.tsx@@ -837,3 +837,20 @@ describe('Token — owned handlers on the link+remove container', () => {openSpy.mockRestore();});});++describe('popup state on a clickable token (FR10)', () => {+ it('passes aria-haspopup and aria-expanded to the inner button', () => {+ render(+ <Token+ label="Status"+ onClick={() => {}}+ aria-haspopup="dialog"+ aria-expanded={false}+ />,+ );+ const button = screen.getByRole('button', {name: 'Status'});+ expect(button).toHaveAttribute('aria-haspopup', 'dialog');+ expect(button).toHaveAttribute('aria-expanded', 'false');+ expect(button.parentElement).not.toHaveAttribute('aria-haspopup');+ });+});diff --git a/packages/core/src/Token/Token.tsx b/packages/core/src/Token/Token.tsxindex 9cb5b91be4..0b15aba6da 100644--- a/packages/core/src/Token/Token.tsx+++ b/packages/core/src/Token/Token.tsx@@ -17,7 +17,7 @@* - /packages/cli/assets/templates/blocks/components/Token/ (showcase blocks)*/-import type {ReactNode} from 'react';+import {use, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars,@@ -41,6 +41,7 @@ import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';import {usePressFeedback} from '../hooks/usePressFeedback';import type {TokenColorMap} from './index';import {disabledInteractionProps} from '../utils/disabledInteraction';+import {TokenNamingContext} from './TokenNamingContext';import {registerEnglishFallback,useComponentTranslator,@@ -309,6 +310,8 @@ export function Token({'data-testid': testId,'aria-labelledby': ariaLabelledBy,'aria-describedby': ariaDescribedBy,+ 'aria-haspopup': ariaHasPopup,+ 'aria-expanded': ariaExpanded,ref,...rest}: TokenProps) {@@ -319,6 +322,7 @@ export function Token({const t = useComponentTranslator();const LinkComponent = useLinkComponent();const role = useInteractiveRole({href, onClick, isDisabled});+ const naming = use(TokenNamingContext);// When role is 'button' via context (no explicit onClick), treat as// if onClick was provided — the popover attaches its own handler.@@ -327,7 +331,9 @@ export function Token({const removeButton = onRemove != null && (<buttontype="button"- aria-label={t('@astryx.token.remove', {label})}+ aria-label={t('@astryx.token.remove', {+ label: naming?.removeName ?? label,+ })}onClick={e => {e.stopPropagation();onRemove(e);@@ -352,12 +358,14 @@ export function Token({</>);- // Naming inputs reach the element that owns the token's action: the inner- // button of a clickable token, otherwise the root+ // Naming and popup inputs reach the element that owns the token's action:+ // the inner button of a clickable token, otherwise the root// (architecture:public-component-api INV5).const labellingProps = {'aria-labelledby': ariaLabelledBy,'aria-describedby': ariaDescribedBy,+ 'aria-haspopup': ariaHasPopup,+ 'aria-expanded': ariaExpanded,};const sharedProps = {@@ -532,6 +540,7 @@ export function Token({<buttontype="button"onClick={effectiveOnClick}+ aria-label={ariaLabelledBy == null ? naming?.actionName : undefined}{...labellingProps}aria-disabled={isDisabled || undefined}{...(isDisabled ? disabledInteractionProps() : null)}diff --git a/packages/core/src/Token/TokenNamingContext.ts b/packages/core/src/Token/TokenNamingContext.tsnew file mode 100644index 0000000000..07b68e6e42--- /dev/null+++ b/packages/core/src/Token/TokenNamingContext.ts@@ -0,0 +1,28 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file TokenNamingContext.ts+ * @input Naming parts from a caller whose token value renders outside its label+ * @output Internal context: the names of a token's action and remove button+ * @position Internal to Core; not exported from the Token entry point+ */++import {createContext} from 'react';++/**+ * Names for a Token whose visible text runs past its label. PowerSearch+ * provides them: its tokens show the value as `endContent`.+ *+ * - `actionName` names a clickable token's inner button in place of `label`.+ * - `removeName` names the remove button in place of `label`. The remove word+ * still comes from the catalog, so each locale keeps its word order.+ */+export interface TokenNaming {+ actionName?: string;+ removeName?: string;+}++export const TokenNamingContext = createContext<TokenNaming | null>(null);+TokenNamingContext.displayName = 'TokenNamingContext';