An open source design system that's fully customizable and agent ready
TypeScript
fix(PowerSearch): Backspace removes no filter of a read-only field (#9648)
Xinzi Zhou7f1bace3c402
diff --git a/.changeset/powersearch-read-only-backspace.md b/.changeset/powersearch-read-only-backspace.mdnew file mode 100644index 0000000000..2fd5391faf--- /dev/null+++ b/.changeset/powersearch-read-only-backspace.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `PowerSearch`: in a read-only field (`isReadOnly`), Backspace on an empty input no longer removes the last filter. A read-only field now removes no filter, as its `isReadOnly` docs promise.++@imdreamrunnerdiff --git a/docs/specs/components/PowerSearch/PowerSearch.spec.md b/docs/specs/components/PowerSearch/PowerSearch.spec.mdindex e665ffa5e6..66f32a37b3 100644--- a/docs/specs/components/PowerSearch/PowerSearch.spec.md+++ b/docs/specs/components/PowerSearch/PowerSearch.spec.md@@ -88,6 +88,13 @@ present-tense implementation gap note.restores the documented contract (only a change after mount is spoken), no`onChange` value, prop, or rendered text changes, and no valid consumermust change. It ships as a `[fix]` patch release of its own.+- A second stable fix, outside the experimental exception: in the `popover`+ presentation, Backspace on an empty input removes no filter of a read-only+ field (FR22). It qualifies as a `[fix]` under `spec:AST-017/FR5`: it+ restores the documented `isReadOnly` contract, "Prevent adding, editing, or+ removing filters", no prop, `onChange` shape, or rendered text changes, and+ no valid consumer relies on a read-only field losing a filter. It ships as a+ `[fix]` patch release.Consumer migration instructions belong in consumer docs and release notes.@@ -173,7 +180,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 govern the `popover` presentation — the tokenizer field and its editor+FR1–FR9 and FR22 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.@@ -201,6 +208,7 @@ FR10–FR21 govern.| FR19 | The result count renders at the end of the field in both presentations and is announced only when it changes after mount; the first render announces nothing, including under StrictMode's effect replay. The announcement takes the route `spec:AST-086/FR14` names for where the field is at that moment: inside the open sheet's dialog while a sheet of the flow is open (AR6), otherwise inside the nearest open native modal that holds the field (a Dialog, a modal Drawer), and the shared polite channel only when no modal does — never a channel the record names itself. | Current popover behavior; `architecture:react-component-runtime/INV3` | Current contract. Implementation gap: the shipped guard announces the initial count under StrictMode. || FR20 | Every string the sheets introduce comes from the `@astryx.powersearch.*` catalog, reusing the existing editor keys where their meaning fits (Cancel, Apply, Operator, Value, Values, Entities, the placeholders, the result count). Content the popover presentation already renders keeps its source — field, operator, and value text from the config and its formatters — except that every label the sheets render for a generated choice comes from the catalog as one ICU message with a plural: the relative-date choice rows (`@astryx.powersearch.sheet.relative{Days,Weeks,Months}{Ago,FromNow}`, the same choices and, in English, the same words as the popover's editor lists) and the value summaries of FR12. | DEC-3; catalog contract | Current contract. Implementation gap: no sheet strings exist. || FR21 | A `string_list` or `entity_list` value inside the value step opens the Tokenizer's sheet above the value step. Escape and 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 |### Allowed variation@@ -463,6 +471,7 @@ mark implementation and focused real-Chromium verification as pending.| FR4–FR6, FR9 | Opening-path tests plus real-Chromium geometry assertions | Add from inner input; edit actual left/right/equidistant token/control; pointer/keyboard; reopen opposite side | Using pointer coordinates, modality, wrapper-only identity, stale identity, or public props fails. | `audit:PowerSearch/interaction` || PR1–PR4 | Instrumented unit tests plus first-frame real-Chromium capture | Open, close, reopen opposite side; hidden placement commit; first painted frame | Render-time reads, repeated reads, observers, pointer tracking, or a default-position flash fails. | `audit:PowerSearch/performance` || 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` || 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) | 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 equal to the popover token's value text (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, a nested filter removed from its step, 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 Remove and announcing the unavailable state in the sheet, Apply and Cancel after a controlled update removed the edited filter focusing the nearest row, else Add filter, 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 and Back glyph mirrored (`design:bidirectionality/DR4`) | A field without `experimental` changes beyond what FR19 states, a value commits before the step confirms, Clear all skips 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/packages/core/src/PowerSearch/PowerSearch.test.tsx b/packages/core/src/PowerSearch/PowerSearch.test.tsxindex b10ce0a355..95a3e7d25e 100644--- a/packages/core/src/PowerSearch/PowerSearch.test.tsx+++ b/packages/core/src/PowerSearch/PowerSearch.test.tsx@@ -250,6 +250,32 @@ describe('PowerSearch', () => {expect(screen.getByText('Open')).toBeInTheDocument();});+ it('a read-only field removes no filter, by control or by Backspace', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <PowerSearch+ config={config}+ filters={[+ {+ field: 'title',+ operator: 'contains',+ value: {type: 'string', value: 'login'},+ },+ ]}+ onChange={onChange}+ isReadOnly+ />,+ );+ expect(+ screen.queryByRole('button', {name: 'Clear all'}),+ ).not.toBeInTheDocument();+ expect(screen.queryAllByRole('button', {name: /^Remove /})).toHaveLength(0);+ await user.click(screen.getByRole('combobox', {name: 'Search'}));+ await user.keyboard('{Backspace}');+ expect(onChange).not.toHaveBeenCalled();+ });+describe('token value truncation (#4759)', () => {it('truncates token values by characters, not code units', () => {const truncConfig: PowerSearchConfig = {diff --git a/packages/core/src/PowerSearch/PowerSearch.tsx b/packages/core/src/PowerSearch/PowerSearch.tsxindex 55a7c57175..2e0eaed55d 100644--- a/packages/core/src/PowerSearch/PowerSearch.tsx+++ b/packages/core/src/PowerSearch/PowerSearch.tsx@@ -31,6 +31,7 @@ import {type TokenizerOverflowBehavior,} from '../Tokenizer';import {TokenizerClearAllMessageContext} from '../Tokenizer/TokenizerClearAllMessageContext';+import {TokenizerItemRemovableContext} from '../Tokenizer/TokenizerItemRemovableContext';import {TypeaheadItem} from '../Typeahead/TypeaheadItem';import {Token} from '../Token';import {Avatar} from '../Avatar';@@ -751,6 +752,10 @@ export function PowerSearch({[config, filters, onChange, setPopoverState],);+ // Tokenizer's Backspace does not go through renderToken. This predicate+ // locks every token of a read-only field.+ const isItemRemovable = useCallback(() => !isReadOnly, [isReadOnly]);+// Handle clicking a token to editconst handleTokenClick = useCallback((index: number) => {@@ -1117,37 +1122,39 @@ export function PowerSearch({{/* The field's Clear all announces PowerSearch's own words(component:PowerSearch; component:Tokenizer AR7). */}<TokenizerClearAllMessageContext value={clearAllMessage}>- <Tokenizer- handleRef={tokenizerRef}- label={label}- isLabelHidden={isLabelHidden}- searchSource={searchSource}- value={tokenizerValue}- onChange={handleTokenizerChange}- renderToken={renderToken}- renderItem={renderItem}- maxMenuItems={MAX_BROWSE_MENU_ITEMS}- menuWidth={menuWidth}- placeholder={filters.length === 0 ? placeholder : ''}- hasAutoFocus={hasAutoFocus}- hasClear={hasClear && !isReadOnly}- startIcon={startIcon}- endContent={combinedEndContent}- isDisabled={isDisabled}- disabledMessage={disabledMessage}- size={size}- tokenOverflowBehavior={tokenOverflowBehavior}- hasEntriesOnFocus- debounceMs={0}- status={status}- statusVariant={statusVariant}- onFocus={onFocus}- onBlur={onBlur}- containerXstyle={xstyle}- containerClassName={className}- containerStyle={style}- data-testid={testId}- />+ <TokenizerItemRemovableContext value={isItemRemovable}>+ <Tokenizer+ handleRef={tokenizerRef}+ label={label}+ isLabelHidden={isLabelHidden}+ searchSource={searchSource}+ value={tokenizerValue}+ onChange={handleTokenizerChange}+ renderToken={renderToken}+ renderItem={renderItem}+ maxMenuItems={MAX_BROWSE_MENU_ITEMS}+ menuWidth={menuWidth}+ placeholder={filters.length === 0 ? placeholder : ''}+ hasAutoFocus={hasAutoFocus}+ hasClear={hasClear && !isReadOnly}+ startIcon={startIcon}+ endContent={combinedEndContent}+ isDisabled={isDisabled}+ disabledMessage={disabledMessage}+ size={size}+ tokenOverflowBehavior={tokenOverflowBehavior}+ hasEntriesOnFocus+ debounceMs={0}+ status={status}+ statusVariant={statusVariant}+ onFocus={onFocus}+ onBlur={onBlur}+ containerXstyle={xstyle}+ containerClassName={className}+ containerStyle={style}+ data-testid={testId}+ />+ </TokenizerItemRemovableContext></TokenizerClearAllMessageContext></div>{popover.render(popoverContent, {diff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsxindex 0c2fe36f5b..1e4a99f85b 100644--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx@@ -23,6 +23,7 @@ import {render, screen, fireEvent, act, waitFor} from '@testing-library/react';import {createRef, Profiler, useState} from 'react';import userEvent from '@testing-library/user-event';import {Tokenizer} from './Tokenizer';+import {TokenizerItemRemovableContext} from './TokenizerItemRemovableContext';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';import type {SearchSource, SearchableItem} from '../Typeahead/types';import {TestIcon} from '../__tests__/TestIcon';@@ -2787,3 +2788,23 @@ describe('Tokenizer incremental results (spec:AST-092)', () => {expect(optionLabels()).toEqual(['Ben', 'Bento', 'Create "ben x"']);});});++describe('Tokenizer locked tokens (internal removable context)', () => {+ it('Backspace on an empty input removes nothing while the last token is locked', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <TokenizerItemRemovableContext value={item => item.id !== '2'}>+ <Tokenizer+ label="Members"+ searchSource={userSource}+ value={[users[0], users[1]]}+ onChange={onChange}+ />+ </TokenizerItemRemovableContext>,+ );+ await user.click(screen.getByRole('combobox'));+ await user.keyboard('{Backspace}');+ expect(onChange).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsxindex a22b621fbd..28605174ea 100644--- a/packages/core/src/Tokenizer/Tokenizer.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.tsx@@ -55,6 +55,7 @@ import {import {inputDisabledFocusStyles} from '../Field/inputDisabledFocus';import {useMergedRefs} from '../hooks/useMergedRefs';import {TokenizerClearAllMessageContext} from './TokenizerClearAllMessageContext';+import {TokenizerItemRemovableContext} from './TokenizerItemRemovableContext';import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';import {useAdaptivePresentation} from '../hooks/useAdaptivePresentation';import {useIsHydrating} from '../hooks/useIsHydrating';@@ -1008,6 +1009,14 @@ export function Tokenizer<T extends SearchableItem>({// `endContent`, a clear button, or all three — so its width is measured// rather than assumed, and the input reserves it.const [laneRef, laneReserve] = useEndLaneReserve(END_LANE_INSET);+ // A composing component can lock tokens (PowerSearch's read-only field).+ // Backspace and the token remove controls skip a locked token. Clear all+ // does not check it.+ const isItemRemovable = use(TokenizerItemRemovableContext);+ const canRemoveItem = useCallback(+ (item: T) => isItemRemovable?.(item) ?? true,+ [isItemRemovable],+ );// The half of the lane's contents this component knows about. The busy half// is the leaf's own business — folding it in here would mean reading the// busy state during this render, which is exactly the re-render the store@@ -1264,7 +1273,7 @@ export function Tokenizer<T extends SearchableItem>({// announcement covers both.const handleRemove = useCallback((item: T, options?: {silent?: boolean}): boolean => {- if (isDisabled) {+ if (isDisabled || !canRemoveItem(item)) {return false;}const newItems = value.filter(v => v.id !== item.id);@@ -1275,7 +1284,7 @@ export function Tokenizer<T extends SearchableItem>({inputRef.current?.focus();return true;},- [value, onChange, isDisabled, announce, t],+ [value, onChange, isDisabled, canRemoveItem, announce, t],);// Handle clearing all itemsdiff --git a/packages/core/src/Tokenizer/TokenizerItemRemovableContext.ts b/packages/core/src/Tokenizer/TokenizerItemRemovableContext.tsnew file mode 100644index 0000000000..e9b08cde36--- /dev/null+++ b/packages/core/src/Tokenizer/TokenizerItemRemovableContext.ts@@ -0,0 +1,22 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file TokenizerItemRemovableContext.ts+ * @input None+ * @output A context carrying a predicate that tells which tokens the user can+ * remove+ * @position Internal to Core: not exported from the Tokenizer barrel. A+ * component that composes Tokenizer and locks some tokens (PowerSearch: every+ * filter of a read-only field) provides it. Backspace then removes nothing+ * while the last token is locked. Without it, every token is removable.+ */++import {createContext} from 'react';+import type {SearchableItem} from '../Typeahead/types';++export const TokenizerItemRemovableContext = createContext<+ ((item: SearchableItem) => boolean) | null+>(null);+TokenizerItemRemovableContext.displayName = 'TokenizerItemRemovableContext';