Skip to content

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

TypeScript

perf(Typeahead,Tokenizer): the busy state is single-owned, and the fields measure under RTL (#5555)

freddymeta95a7219eeb1a
diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.json
index 4c315fab32..547f3a1be3 100644
--- a/apps/storybook/rtl-audit/targets.json
+++ b/apps/storybook/rtl-audit/targets.json
@@ -103,24 +103,24 @@
},
{
"component": "Typeahead",
- "storyId": "core-typeahead--logical-order",
+ "storyId": "core-typeahead--rtl-end-lane",
"dims": [
- "D2"
+ "D4"
],
"selectors": {
- "prev": ".astryx-token",
- "next": ".astryx-input-clear-button"
+ "overlay": "button[aria-label=\"Clear selection\"]",
+ "overlayRoot": ".astryx-typeahead"
}
},
{
"component": "Tokenizer",
- "storyId": "core-tokenizer--logical-order",
+ "storyId": "core-tokenizer--rtl-end-lane",
"dims": [
- "D2"
+ "D4"
],
"selectors": {
- "prev": ".astryx-token",
- "next": ".astryx-input-clear-button"
+ "overlay": "button[aria-label=\"Clear all\"]",
+ "overlayRoot": ".astryx-tokenizer"
}
},
{
diff --git a/apps/storybook/stories/Tokenizer.stories.tsx b/apps/storybook/stories/Tokenizer.stories.tsx
index d9cde7f0c8..f4c4669430 100644
--- a/apps/storybook/stories/Tokenizer.stories.tsx
+++ b/apps/storybook/stories/Tokenizer.stories.tsx
@@ -523,3 +523,29 @@ export const LogicalOrder: Story = {
},
name: 'Logical order',
};
+
+/**
+ * The inline-end lane, populated at rest, for the RTL audit's D4 pass.
+ *
+ * Tokenizer's lane is absolutely positioned — it has to be, so it stays on the
+ * field's first row while tokens wrap below it — which makes its side entirely
+ * a matter of the writing mode. The busy Spinner shares that lane, and busy
+ * only exists mid-search, so a selected token with `hasClear` is what puts the
+ * lane on screen for a measurement that can be held still.
+ */
+export const RtlEndLane: Story = {
+ render: args => (
+ <Tokenizer
+ {...args}
+ searchSource={userSource}
+ value={[users[0]]}
+ onChange={() => {}}
+ hasClear
+ />
+ ),
+ args: {
+ label: 'Team Members',
+ placeholder: 'Search people...',
+ },
+ name: 'RTL end lane (token + clear)',
+};
diff --git a/apps/storybook/stories/Typeahead.stories.tsx b/apps/storybook/stories/Typeahead.stories.tsx
index 2a34d4e791..01f21a7b4c 100644
--- a/apps/storybook/stories/Typeahead.stories.tsx
+++ b/apps/storybook/stories/Typeahead.stories.tsx
@@ -391,3 +391,26 @@ export const LogicalOrder: Story = {
},
name: 'Logical order',
};
+
+/**
+ * The inline-end lane, populated at rest, for the RTL audit's D4 pass.
+ *
+ * The lane holds the busy Spinner, and the busy state only exists between a
+ * keystroke and its response — nothing the audit can hold still. A selected
+ * value with `hasClear` puts the same lane on screen with no interaction, so
+ * the audit measures the geometry the indicator lands in.
+ */
+export const RtlEndLane: Story = {
+ render: () => (
+ <div style={{width: 320}}>
+ <Typeahead
+ label="Fruit"
+ searchSource={fruitSource}
+ value={fruits[0]}
+ onChange={() => {}}
+ hasClear
+ />
+ </div>
+ ),
+ name: 'RTL end lane (selected + clear)',
+};
diff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsx
index 1db25c3dd4..59475f05d6 100644
--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx
+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx
@@ -27,6 +27,24 @@ import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import type {SearchSource, SearchableItem} from '../Typeahead/types';
import {TestIcon} from '../__tests__/TestIcon';
import {InternationalizationProvider} from '../i18n';
+import type * as TokenModule from '../Token';
+
+// Every Token render, in order, by label.
+//
+// A spy that WRAPS the real component rather than replacing it: a stand-in
+// would measure the stand-in, and the number under review is how often the
+// real token subtree re-renders during a search.
+const renderedTokens: string[] = [];
+vi.mock('../Token', async importActual => {
+ const actual = await importActual<typeof TokenModule>();
+ return {
+ ...actual,
+ Token: (props: Parameters<typeof TokenModule.Token>[0]) => {
+ renderedTokens.push(typeof props.label === 'string' ? props.label : '');
+ return actual.Token(props);
+ },
+ };
+});
// Test-supplied announcement strings: the assertions below depend on no
// catalog, and no hardcoded English in the component can satisfy them.
@@ -1469,7 +1487,17 @@ describe('Tokenizer end-lane reserve', () => {
const laneHost = (container: HTMLElement) =>
container.querySelector<HTMLElement>(
- '[style*="--_tokenizer-end-lane-width"]',
+ '[style*="--_tokenizer-end-lane-reserve"]',
+ );
+
+ // The variable carries the whole reserve — the lane's inset plus its
+ // measured width — so its ABSENCE means "no lane", not "a lane of zero
+ // width". That distinction is what lets the input apply the padding rule
+ // unconditionally and still keep its full content box when nothing is in
+ // the lane.
+ const reserveOf = (container: HTMLElement) =>
+ laneHost(container)?.style.getPropertyValue(
+ '--_tokenizer-end-lane-reserve',
);
it('reserves the lane\u2019s untransformed width, not its on-screen width', () => {
@@ -1488,11 +1516,9 @@ describe('Tokenizer end-lane reserve', () => {
hasClear
/>,
);
- expect(
- laneHost(container)?.style.getPropertyValue(
- '--_tokenizer-end-lane-width',
- ),
- ).toBe(`${LANE_LOCAL_WIDTH}px`);
+ expect(reserveOf(container)).toBe(
+ `calc(var(--spacing-2) + ${LANE_LOCAL_WIDTH}px)`,
+ );
});
it('reserves the lane when the spinner is the only thing in it', () => {
@@ -1517,11 +1543,9 @@ describe('Tokenizer end-lane reserve', () => {
});
expect(screen.getByRole('status')).toBeInTheDocument();
- expect(
- laneHost(container)?.style.getPropertyValue(
- '--_tokenizer-end-lane-width',
- ),
- ).toBe(`${LANE_LOCAL_WIDTH}px`);
+ expect(reserveOf(container)).toBe(
+ `calc(var(--spacing-2) + ${LANE_LOCAL_WIDTH}px)`,
+ );
});
it('does not pad the input on the collapsed paths', () => {
@@ -1586,6 +1610,53 @@ describe('Tokenizer end-lane reserve', () => {
expect(commits.length).toBe(2);
});
+ it('re-renders no token when a search starts or settles', async () => {
+ // The regression this guards. The busy state has one owner — the base —
+ // and the field only needs it to decide whether one Spinner is on screen.
+ // Mirrored into the field's own state, every transition re-rendered the
+ // whole field including every selected token: measured at six tokens,
+ // 6 renders at search start and 6 more at settlement, and 20/40 at
+ // twenty. A token contains no part of the indicator, so the correct
+ // number is zero at any count.
+ const {source, settle} = pendingSource();
+ const selected = users.slice(0, 6);
+ renderedTokens.length = 0;
+
+ render(
+ <Tokenizer
+ label="Users"
+ searchSource={source}
+ value={selected}
+ onChange={() => {}}
+ hasClear
+ debounceMs={0}
+ />,
+ );
+ expect(new Set(renderedTokens).size).toBe(selected.length);
+ renderedTokens.length = 0;
+
+ await act(async () => {
+ fireEvent.change(screen.getByRole('combobox'), {target: {value: 'Al'}});
+ });
+ // The indicator is up, so the transition really did happen. Scoped by
+ // name: the announcer for result counts is a role="status" live region
+ // too, and it is not the indicator.
+ expect(screen.getByRole('status', {name: 'Loading'})).toBeInTheDocument();
+ // ...and it cost no token a render.
+ expect(renderedTokens).toEqual([]);
+
+ await act(async () => {
+ settle([]);
+ await Promise.resolve();
+ });
+ await waitFor(() => {
+ expect(
+ screen.queryByRole('status', {name: 'Loading'}),
+ ).not.toBeInTheDocument();
+ });
+ expect(renderedTokens).toEqual([]);
+ });
+
it('shares one observer across every field on the page', () => {
// Browsers batch per observer instance, so one observer per lane meant N
// callback dispatches a frame for N fields.
diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsx
index a82465ab91..ddf4e8b484 100644
--- a/packages/core/src/Tokenizer/Tokenizer.tsx
+++ b/packages/core/src/Tokenizer/Tokenizer.tsx
@@ -25,7 +25,12 @@ import React, {
type ReactNode,
} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {BusyIndicatorLaneProvider} from '../Typeahead/busyIndicatorLane';
+import {
+ BusyIndicatorLaneProvider,
+ createBusyIndicatorLane,
+ useIsBusy,
+ type BusyIndicatorLane,
+} from '../Typeahead/busyIndicatorLane';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
import {BaseTypeahead} from '../Typeahead/BaseTypeahead';
@@ -394,6 +399,45 @@ const CREATABLE_ID_PREFIX = '__xds_create__';
* />
* ```
*/
+/**
+ * The field's inline-end lane: the busy Spinner, then `endContent`, then the
+ * clear button — pinned to the field's first row while tokens wrap below it.
+ *
+ * A separate component so that subscribing to the busy state re-renders THIS
+ * and nothing else. Subscribed from `Tokenizer`, a search transition
+ * re-rendered every selected token twice — twenty tokens meant forty renders
+ * per search for one glyph none of them contain.
+ *
+ * Renders nothing when the lane would be empty, so `useEndLaneReserve` sees no
+ * element, publishes no width, and the input keeps its full content box.
+ */
+function EndLane({
+ lane,
+ laneRef,
+ laneXStyle,
+ loadingLabel,
+ hasStaticContent,
+ children,
+}: {
+ lane: BusyIndicatorLane;
+ laneRef: (node: HTMLElement | null) => void;
+ laneXStyle: stylex.StyleXStyles[];
+ loadingLabel: string;
+ hasStaticContent: boolean;
+ children: ReactNode;
+}) {
+ const isBusy = useIsBusy(lane);
+ if (!isBusy && !hasStaticContent) {
+ return null;
+ }
+ return (
+ <div ref={laneRef} {...stylex.props(laneXStyle)}>
+ {isBusy && <Spinner size="sm" aria-label={loadingLabel} />}
+ {children}
+ </div>
+ );
+}
+
export function Tokenizer<T extends SearchableItem>({
label,
isLabelHidden = false,
@@ -470,16 +514,21 @@ export function Tokenizer<T extends SearchableItem>({
// Focus-within state for overflow truncation
// Reported by BaseTypeahead so the indicator can live in this field's own
// end lane, beside endContent and the clear button.
- const [isLoading, setIsLoading] = useState(false);
- const busyLane = useMemo(() => ({onBusyChange: setIsLoading}), []);
+ // The base owns the busy state; this field only paints it. Held in a store
+ // rather than this component's state — held here, a search transition
+ // re-rendered every selected token twice, for a glyph no token contains.
+ // See busyIndicatorLane.tsx.
+ const busyLane = useMemo(() => createBusyIndicatorLane(), []);
// What sits in the end lane varies most here — a spinner, arbitrary
// `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);
- // Whether a lane renders at all — known from props and state, without
- // measuring anything, which is why the reserve costs no extra commit.
- const hasEndLane = Boolean(
- isLoading || endContent || (hasClear && value.length > 0 && !isDisabled),
+ // 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
+ // exists to avoid.
+ const hasStaticEndLane = Boolean(
+ endContent || (hasClear && value.length > 0 && !isDisabled),
);
const [isFocusedWithin, setIsFocusedWithin] = useState(false);
const isTruncated =
@@ -850,7 +899,10 @@ export function Tokenizer<T extends SearchableItem>({
: undefined,
// Not for the collapsed states above: those give the input no width
// to pad, and `inputAtMax` zeroes its padding outright.
- !(isAtMax || isTruncated) && hasEndLane && laneReserve,
+ // Applied whether or not a lane is up: the reserve resolves to
+ // zero until the lane publishes a width, so this does not need to
+ // know about the busy state.
+ !(isAtMax || isTruncated) && laneReserve,
]}
/>
</BusyIndicatorLaneProvider>
@@ -866,25 +918,23 @@ export function Tokenizer<T extends SearchableItem>({
disabled={isDisabled}
/>
))}
- {hasEndLane && (
- <div
- ref={laneRef}
- {...stylex.props(styles.endSection, endSectionSizeStyles[size])}>
- {isLoading && (
- <Spinner size="sm" aria-label={t('@astryx.typeahead.loading')} />
- )}
- {endContent}
- {hasClear && value.length > 0 && !isDisabled && (
- <InputClearButton
- label={t('@astryx.tokenizer.clearAll')}
- onClick={e => {
- e.stopPropagation();
- handleClearAll();
- }}
- />
- )}
- </div>
- )}
+ <EndLane
+ lane={busyLane}
+ laneRef={laneRef}
+ laneXStyle={[styles.endSection, endSectionSizeStyles[size]]}
+ loadingLabel={t('@astryx.typeahead.loading')}
+ hasStaticContent={hasStaticEndLane}>
+ {endContent}
+ {hasClear && value.length > 0 && !isDisabled && (
+ <InputClearButton
+ label={t('@astryx.tokenizer.clearAll')}
+ onClick={e => {
+ e.stopPropagation();
+ handleClearAll();
+ }}
+ />
+ )}
+ </EndLane>
</div>
);
diff --git a/packages/core/src/Tokenizer/useEndLaneReserve.ts b/packages/core/src/Tokenizer/useEndLaneReserve.ts
index 8a0ee31cc1..4309973650 100644
--- a/packages/core/src/Tokenizer/useEndLaneReserve.ts
+++ b/packages/core/src/Tokenizer/useEndLaneReserve.ts
@@ -35,7 +35,7 @@ import {observeResize} from '../utils/sharedResizeObserver';
* carries a measurement into CSS without carrying it through React, so a lane
* that grows or shrinks repaints without re-rendering the field.
*/
-const LANE_WIDTH_VAR = '--_tokenizer-end-lane-width';
+const LANE_RESERVE_VAR = '--_tokenizer-end-lane-reserve';
// Keep the input's text and caret out from under the lane.
//
@@ -45,13 +45,17 @@ const LANE_WIDTH_VAR = '--_tokenizer-end-lane-width';
// already has, plus a padding's worth of gap so the text does not touch the
// glyph. The two paddings cancel, which is why this reads as inset + width.
//
-// The width arrives as a variable rather than a number, so this rule is
-// static: one class, generated once, never regenerated as the lane changes.
-// The `0px` fallback covers the frame before the lane is first measured.
+// The variable carries the WHOLE reserve, not just the width, so its absence
+// means "no lane" rather than "a lane of zero width": with no lane up, the
+// fallback resolves the padding to 0 and the input keeps its full content box.
+// That is what lets the caller apply this style unconditionally, which in turn
+// is what keeps the field from having to know whether a search is running.
+// The rule stays static either way — one class, generated once, never
+// regenerated as the lane changes.
const reserveStyles = stylex.create({
- reserve: (laneInset: string) => ({
- paddingInlineEnd: `calc(${laneInset} + var(${LANE_WIDTH_VAR}, 0px))`,
- }),
+ reserve: {
+ paddingInlineEnd: `var(${LANE_RESERVE_VAR}, 0px)`,
+ },
});
/**
@@ -78,51 +82,65 @@ const reserveStyles = stylex.create({
*
* Takes the lane's inset from the field's inline-end border, as the CSS
* expression that positions it. Returns a ref callback for the lane, and the
- * style for the input — which the caller applies only when it renders a lane,
- * something it already knows without measuring anything.
+ * style for the input — which the caller applies unconditionally: with no lane
+ * mounted the variable is absent and the padding resolves to zero, so the
+ * caller never has to know whether a search is running.
*/
export function useEndLaneReserve(
laneInset: string,
): [(node: HTMLElement | null) => void, stylex.StyleXStyles] {
- const laneRef = useCallback((node: HTMLElement | null) => {
- if (node == null) {
- return;
- }
- // The lane's parent: the field wrapper in both callers, and an ancestor
- // of the input either way, which is what inheritance needs.
- const host = node.parentElement;
+ const laneRef = useCallback(
+ (node: HTMLElement | null) => {
+ if (node == null) {
+ return;
+ }
+ // The lane's parent: the field wrapper in both callers, and an ancestor
+ // of the input either way, which is what inheritance needs.
+ const host = node.parentElement;
- const unobserve = observeResize(node, () => {
- // `offsetWidth`, not `getBoundingClientRect().width`. The rect is in
- // VIEWPORT space — it carries every CSS transform between this element
- // and the root — while the padding it feeds is in the element's own
- // LOCAL space. Under `scale(.5)` the rect reads half the lane's real
- // width and the input reserves half of what it needs, so the query runs
- // under the controls again; under `scale(2)` it reads double and the
- // caret sits in a gap twice the lane's width. Measured in Chromium on a
- // 123px lane in a 280px field: at `scale(.5)` the rect published 61.48px
- // and the spinner covered 14px of the input's content box; at `scale(2)`
- // it published 245.91px, leaving a 125.95px gap and growing the field
- // from 32px to 55px tall. `offsetWidth` is the untransformed border-box
- // width, so it reports 123 at every scale — the number this padding is
- // actually denominated in.
- //
- // It is already an integer, which is the rounding the old `Math.ceil`
- // was there for: a fractional width left as-is reserves a hair too
- // little and the glyph's last subpixel column lands on the caret.
- host?.style.setProperty(LANE_WIDTH_VAR, `${node.offsetWidth}px`);
- });
+ const unobserve = observeResize(node, () => {
+ // `offsetWidth`, not `getBoundingClientRect().width`. The rect is in
+ // VIEWPORT space — it carries every CSS transform between this element
+ // and the root — while the padding it feeds is in the element's own
+ // LOCAL space. Under `scale(.5)` the rect reads half the lane's real
+ // width and the input reserves half of what it needs, so the query runs
+ // under the controls again; under `scale(2)` it reads double and the
+ // caret sits in a gap twice the lane's width. Measured in Chromium on a
+ // 123px lane in a 280px field: at `scale(.5)` the rect published 61.48px
+ // and the spinner covered 14px of the input's content box; at `scale(2)`
+ // it published 245.91px, leaving a 125.95px gap and growing the field
+ // from 32px to 55px tall. `offsetWidth` is the untransformed border-box
+ // width, so it reports 123 at every scale — the number this padding is
+ // actually denominated in.
+ //
+ // It is already an integer, which is the rounding the old `Math.ceil`
+ // was there for: a fractional width left as-is reserves a hair too
+ // little and the glyph's last subpixel column lands on the caret.
+ const width = node.offsetWidth;
+ if (width > 0) {
+ host?.style.setProperty(
+ LANE_RESERVE_VAR,
+ `calc(${laneInset} + ${width}px)`,
+ );
+ } else {
+ // A mounted but empty lane (no end content, no clear, not searching)
+ // claims nothing.
+ host?.style.removeProperty(LANE_RESERVE_VAR);
+ }
+ });
- // React 19 runs a ref callback's return value as its cleanup, so the
- // observer is released exactly when the lane unmounts.
- return () => {
- unobserve();
- // The room the lane claimed goes back to the input. Removing beats
- // setting 0px: the rule's fallback is already that, and this leaves no
- // stale property behind on the DOM.
- host?.style.removeProperty(LANE_WIDTH_VAR);
- };
- }, []);
+ // React 19 runs a ref callback's return value as its cleanup, so the
+ // observer is released exactly when the lane unmounts.
+ return () => {
+ unobserve();
+ // The room the lane claimed goes back to the input. Removing beats
+ // setting 0px: the rule's fallback is already that, and this leaves no
+ // stale property behind on the DOM.
+ host?.style.removeProperty(LANE_RESERVE_VAR);
+ };
+ },
+ [laneInset],
+ );
- return [laneRef, reserveStyles.reserve(laneInset)];
+ return [laneRef, reserveStyles.reserve];
}
diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsx
index f1497c9869..13c6beaba0 100644
--- a/packages/core/src/Typeahead/Typeahead.test.tsx
+++ b/packages/core/src/Typeahead/Typeahead.test.tsx
@@ -24,7 +24,10 @@ import {Typeahead} from './Typeahead';
import {readFile} from 'node:fs/promises';
import {resolve} from 'node:path';
import {BaseTypeahead} from './BaseTypeahead';
-import {BusyIndicatorLaneProvider} from './busyIndicatorLane';
+import {
+ BusyIndicatorLaneProvider,
+ createBusyIndicatorLane,
+} from './busyIndicatorLane';
import type {SearchSource, SearchableItem} from './types';
import {InternationalizationProvider} from '../i18n';
@@ -1515,9 +1518,13 @@ describe('busy indicator ownership', () => {
// they already own. Two indicators in one field is the defect this PR
// exists to fix, so the base must yield rather than add to it.
const {source, settle} = pendingSource();
- const onLoadingChange = vi.fn();
+ // A real lane with its notify spied, rather than a hand-built object: the
+ // lane is a store now, and the base must drive the store the wrappers use.
+ const lane = createBusyIndicatorLane();
+ const onLoadingChange = vi.fn(lane.onBusyChange);
render(
- <BusyIndicatorLaneProvider value={{onBusyChange: onLoadingChange}}>
+ <BusyIndicatorLaneProvider
+ value={{...lane, onBusyChange: onLoadingChange}}>
<BaseTypeahead
searchSource={source}
value={null}
@@ -1569,9 +1576,13 @@ describe('busy indicator ownership', () => {
// `false` per character — each one a state write, and on a field that is
// re-rendering as the user types.
const {source, settle} = pendingSource();
- const onLoadingChange = vi.fn();
+ // A real lane with its notify spied, rather than a hand-built object: the
+ // lane is a store now, and the base must drive the store the wrappers use.
+ const lane = createBusyIndicatorLane();
+ const onLoadingChange = vi.fn(lane.onBusyChange);
render(
- <BusyIndicatorLaneProvider value={{onBusyChange: onLoadingChange}}>
+ <BusyIndicatorLaneProvider
+ value={{...lane, onBusyChange: onLoadingChange}}>
<BaseTypeahead
searchSource={source}
value={null}
diff --git a/packages/core/src/Typeahead/Typeahead.tsx b/packages/core/src/Typeahead/Typeahead.tsx
index 813de5c2ba..f1ce0cf5c0 100644
--- a/packages/core/src/Typeahead/Typeahead.tsx
+++ b/packages/core/src/Typeahead/Typeahead.tsx
@@ -27,7 +27,12 @@ import React, {
type ReactNode,
} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {BusyIndicatorLaneProvider} from './busyIndicatorLane';
+import {
+ BusyIndicatorLaneProvider,
+ createBusyIndicatorLane,
+ useIsBusy,
+ type BusyIndicatorLane,
+} from './busyIndicatorLane';
import {BaseTypeahead} from './BaseTypeahead';
import {useSize} from '../SizeContext/SizeContext';
import {
@@ -298,6 +303,39 @@ const wrapperSizeStyles = stylex.create({
* />
* ```
*/
+
+/**
+ * The field's inline-end lane: the busy Spinner, then the clear button.
+ *
+ * A separate component so that subscribing to the busy state re-renders THIS
+ * and nothing else. Subscribing from `Typeahead` itself would re-render the
+ * whole field — and, in the Tokenizer that shares this design, every selected
+ * token — twice per search for one glyph.
+ *
+ * Renders nothing when there is neither a spinner nor a clear button, which is
+ * what keeps an empty flex item from taking a gap in the row.
+ */
+function EndLane({
+ lane,
+ loadingLabel,
+ clear,
+}: {
+ lane: BusyIndicatorLane;
+ loadingLabel: string;
+ clear: ReactNode;
+}) {
+ const isBusy = useIsBusy(lane);
+ if (!isBusy && clear == null) {
+ return null;
+ }
+ return (
+ <div {...stylex.props(styles.endLane)}>
+ {isBusy && <Spinner size="sm" aria-label={loadingLabel} />}
+ {clear}
+ </div>
+ );
+}
+
export function Typeahead<T extends SearchableItem>({
ref,
label,
@@ -362,8 +400,11 @@ export function Typeahead<T extends SearchableItem>({
// Edit mode: when the user clicks the token to edit the selected value
// Reported by BaseTypeahead so the indicator can live in this field's own
// end lane, beside the clear button, rather than in the engine's row.
- const [isLoading, setIsLoading] = useState(false);
- const busyLane = useMemo(() => ({onBusyChange: setIsLoading}), []);
+ // The base owns the busy state; this field only paints it. Held in a store
+ // rather than this component's state so a search transition re-renders the
+ // one leaf that shows the Spinner, not the whole field. See
+ // busyIndicatorLane.tsx.
+ const busyLane = useMemo(() => createBusyIndicatorLane(), []);
const [isEditing, setIsEditing] = useState(false);
const [editingValue, setEditingValue] = useState<T | null>(null);
@@ -569,12 +610,11 @@ export function Typeahead<T extends SearchableItem>({
/>
</div>
</BusyIndicatorLaneProvider>
- {(isLoading || (hasClear && value && !isDisabled)) && (
- <div {...stylex.props(styles.endLane)}>
- {isLoading && (
- <Spinner size="sm" aria-label={t('@astryx.typeahead.loading')} />
- )}
- {hasClear && value && !isDisabled && (
+ <EndLane
+ lane={busyLane}
+ loadingLabel={t('@astryx.typeahead.loading')}
+ clear={
+ hasClear && value && !isDisabled ? (
<InputClearButton
label={t('@astryx.typeahead.clearSelection')}
onClick={e => {
@@ -582,9 +622,9 @@ export function Typeahead<T extends SearchableItem>({
handleClear();
}}
/>
- )}
- </div>
- )}
+ ) : null
+ }
+ />
</div>
{showsDisabledMessage &&
disabledMessageTooltip.renderTooltip(disabledMessage)}
diff --git a/packages/core/src/Typeahead/busyIndicatorLane.tsx b/packages/core/src/Typeahead/busyIndicatorLane.tsx
index 7a2041fd6c..231b7514d4 100644
--- a/packages/core/src/Typeahead/busyIndicatorLane.tsx
+++ b/packages/core/src/Typeahead/busyIndicatorLane.tsx
@@ -9,7 +9,7 @@
* @position Package-internal; not exported from the package entry point
*/
-import {createContext, use} from 'react';
+import {createContext, use, useSyncExternalStore} from 'react';
/**
* How the base hands its busy state to a wrapper that owns the inline-end lane.
@@ -31,8 +31,65 @@ import {createContext, use} from 'react';
* boundary instead of by naming convention.
*/
export interface BusyIndicatorLane {
- /** Called when a search starts or settles. */
+ /** Called by the base when a search starts or settles. */
onBusyChange: (isBusy: boolean) => void;
+ /** Subscribe to transitions; returns an unsubscribe. */
+ subscribe: (onStoreChange: () => void) => () => void;
+ /** The current busy state. */
+ getIsBusy: () => boolean;
+}
+
+/**
+ * A store, deliberately, rather than a setState handed down.
+ *
+ * The busy state has exactly one owner — the base, which is the only thing
+ * that knows a search has started — and a wrapper needs it only to decide
+ * whether one Spinner is on screen. Pushing it into the wrapper's own state
+ * made every one of the wrapper's children re-render on each transition:
+ * a Tokenizer holding twenty selected tokens re-rendered all twenty at search
+ * start and again at settlement, for a glyph none of them contain.
+ *
+ * Holding it here instead lets the single leaf that paints the indicator
+ * subscribe on its own, so a transition re-renders that leaf and nothing else.
+ * The wrapper reads the state at no point, so it never re-renders for it.
+ */
+export function createBusyIndicatorLane(): BusyIndicatorLane {
+ let isBusy = false;
+ const listeners = new Set<() => void>();
+ return {
+ onBusyChange(next: boolean) {
+ // Edge-triggered: the base already guards its own redundant reports,
+ // and this keeps a second caller from waking every subscriber for a
+ // state they are already rendering.
+ if (isBusy === next) {
+ return;
+ }
+ isBusy = next;
+ for (const listener of listeners) {
+ listener();
+ }
+ },
+ subscribe(onStoreChange: () => void) {
+ listeners.add(onStoreChange);
+ return () => {
+ listeners.delete(onStoreChange);
+ };
+ },
+ getIsBusy: () => isBusy,
+ };
+}
+
+/**
+ * Subscribe to a lane's busy state.
+ *
+ * Call this ONLY from the leaf that paints the indicator. Calling it from a
+ * wrapper re-introduces the re-render this store exists to remove.
+ *
+ * The server snapshot is the same getter: the store starts idle, and a search
+ * cannot have begun during SSR.
+ */
+export function useIsBusy(lane: BusyIndicatorLane): boolean {
+ return useSyncExternalStore(lane.subscribe, lane.getIsBusy, lane.getIsBusy);
}
const BusyIndicatorLaneContext = createContext<BusyIndicatorLane | null>(null);