An open source design system that's fully customizable and agent ready
TypeScript
fix(Tokenizer): avoid blank trailing input row (#6057)
Xinzi Zhouabbb29358dda
diff --git a/.changeset/quiet-tokens-share.md b/.changeset/quiet-tokens-share.mdnew file mode 100644index 0000000000..b1c2b1f090--- /dev/null+++ b/.changeset/quiet-tokens-share.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Prevent an empty Tokenizer input from creating a blank trailing row.+@imdreamrunnerdiff --git a/.github/scripts/story-play-guard.js b/.github/scripts/story-play-guard.jsindex 01570c2c0d..cab4b09d27 100644--- a/.github/scripts/story-play-guard.js+++ b/.github/scripts/story-play-guard.js@@ -21,13 +21,13 @@* a story that cannot boot must not pass by silence.*/-const { chromium } = require('playwright');+const {chromium} = require('playwright');const fs = require('node:fs');const path = require('node:path');const http = require('node:http');const args = process.argv.slice(2);-const getArg = (name) => {+const getArg = name => {const idx = args.indexOf(`--${name}`);return idx !== -1 ? args[idx + 1] : null;};@@ -66,6 +66,20 @@ const TARGETS = [story: 'core-chattoolcalls--narrow',guards: 'long metadata stays within the 320px narrow-container fixture',},+ {+ component: 'PowerSearch',+ story: 'core-powersearch--near-full-token-row',+ hasTouch: true,+ guards:+ 'on a coarse pointer, an empty trailing combobox stays on the nearly full token row without overlapping the full Clear all hit area',+ },+ {+ component: 'PowerSearch',+ story: 'core-powersearch--near-full-token-row-rtl',+ hasTouch: true,+ guards:+ 'on a coarse pointer, the compact combobox and full Clear all hit area remain separate in RTL as well',+ },{component: 'TabList',story: 'core-tablist--full-bleed-geometry',@@ -85,7 +99,7 @@ const CONTENT_TYPES = {};function createServer(dir, listenPort) {- return new Promise((resolve) => {+ return new Promise(resolve => {const server = http.createServer((req, res) => {const filePath = path.join(dir, req.url === '/' ? 'index.html' : req.url)@@ -105,8 +119,7 @@ function createServer(dir, listenPort) {return;}res.writeHead(200, {- 'Content-Type':- CONTENT_TYPES[path.extname(resolved)] || 'text/plain',+ 'Content-Type': CONTENT_TYPES[path.extname(resolved)] || 'text/plain',});res.end(data);});@@ -120,7 +133,7 @@ function createServer(dir, listenPort) {// is emitted only after the play function resolves; every failure mode has// its own event. Attached before any preview code runs so no event is missed.function recordStoryOutcome() {- window.__storyOutcome = { done: false, errors: [] };+ window.__storyOutcome = {done: false, errors: []};const ERROR_EVENTS = ['playFunctionThrewException','unhandledErrorsWhilePlaying',@@ -128,7 +141,7 @@ function recordStoryOutcome() {'storyErrored','storyMissing',];- const describe = (payload) => {+ const describe = payload => {if (payload == null) return '';if (typeof payload === 'string') return payload;return [payload.name, payload.title, payload.message, payload.description]@@ -145,9 +158,9 @@ function recordStoryOutcome() {window.__storyOutcome.done = true;});for (const event of ERROR_EVENTS) {- channel.on(event, (payload) => {+ channel.on(event, payload => {window.__storyOutcome.errors.push(- `${event}${describe(payload) ? ` — ${describe(payload)}` : ''}`+ `${event}${describe(payload) ? ` — ${describe(payload)}` : ''}`,);window.__storyOutcome.done = true;});@@ -158,14 +171,15 @@ function recordStoryOutcome() {async function probe(page, target) {await page.addInitScript(recordStoryOutcome);+ const pointerQuery = target.hasTouch ? '&storyPlayPointer=coarse' : '';await page.goto(- `http://localhost:${port}/iframe.html?id=${target.story}&viewMode=story`,- { waitUntil: 'domcontentloaded', timeout: 30000 }+ `http://localhost:${port}/iframe.html?id=${target.story}&viewMode=story${pointerQuery}`,+ {waitUntil: 'domcontentloaded', timeout: 30000},);await page.waitForFunction(() => window.__storyOutcome && window.__storyOutcome.done === true,null,- { timeout: 30000 }+ {timeout: 30000},);return page.evaluate(() => window.__storyOutcome);}@@ -182,31 +196,32 @@ async function run() {let failures = 0;try {- const context = await browser.newContext({- viewport: { width: 1280, height: 900 },- });-for (const target of TARGETS) {+ const context = await browser.newContext({+ viewport: {width: 1280, height: 900},+ hasTouch: target.hasTouch === true,+ });const page = await context.newPage();try {const outcome = await probe(page, target);if (outcome.errors.length > 0) {failures++;console.error(- `✗ ${target.component} (${target.story}):\n ${outcome.errors.join('\n ')}`+ `✗ ${target.component} (${target.story}):\n ${outcome.errors.join('\n ')}`,);} else {console.log(- `✓ ${target.component} (${target.story}): play passed — ${target.guards}`+ `✓ ${target.component} (${target.story}): play passed — ${target.guards}`,);}} catch (e) {failures++;console.error(- `✗ ${target.component} (${target.story}): no play outcome — ${e.message}`+ `✗ ${target.component} (${target.story}): no play outcome — ${e.message}`,);} finally {await page.close();+ await context.close();}}} finally {@@ -215,7 +230,9 @@ async function run() {}if (failures > 0) {- console.error(`\nFailing: ${failures} story play function(s) did not pass.`);+ console.error(+ `\nFailing: ${failures} story play function(s) did not pass.`,+ );return 1;}console.log('\nAll story play guards passed.');@@ -223,10 +240,10 @@ async function run() {}run()- .then((code) => {+ .then(code => {process.exitCode = code;})- .catch((e) => {+ .catch(e => {console.error('Story play guard failed:', e);process.exit(1);});diff --git a/apps/storybook/stories/PowerSearch.stories.tsx b/apps/storybook/stories/PowerSearch.stories.tsxindex bad0eb8abd..1c8a709b9b 100644--- a/apps/storybook/stories/PowerSearch.stories.tsx+++ b/apps/storybook/stories/PowerSearch.stories.tsx@@ -540,6 +540,184 @@ export const WithPresetFilters: Story = {name: 'Pre-set Filters',};+/**+ * A nearly full token row keeps its empty combobox on that row instead of+ * growing the field with a blank trailing row. Typing still restores the+ * input's normal editing width and may wrap visibly when space is exhausted.+ */+export const NearFullTokenRow: Story = {+ render: args => {+ const [filters, setFilters] = useState<PowerSearchFilter[]>([+ {field: 'status', operator: 'is', value: {type: 'enum', value: 'open'}},+ {+ field: 'priority',+ operator: 'is',+ value: {type: 'enum', value: 'p1'},+ },+ {+ field: 'title',+ operator: 'contains',+ value: {type: 'string', value: 'aaaaaaaaaaaaaaaaaa'},+ },+ ]);+ return (+ <PowerSearch+ {...args}+ config={basicConfig}+ filters={filters}+ onChange={newFilters => setFilters([...newFilters])}+ />+ );+ },+ args: {+ placeholder: 'Add more filters...',+ },+ name: 'Near-full Token Row',+ play: async ({canvasElement}) => {+ const wrapper =+ canvasElement.querySelector<HTMLElement>('.astryx-tokenizer');+ const input = wrapper?.querySelector<HTMLInputElement>('[role="combobox"]');+ const tokens = wrapper?.querySelectorAll<HTMLElement>(':scope > span');+ const firstToken = tokens?.item(0);+ const finalToken = tokens?.item((tokens?.length ?? 0) - 1);+ const clearButton = wrapper?.querySelector<HTMLButtonElement>(+ 'button[aria-label="Clear all"]',+ );+ if (!wrapper || !input || !firstToken || !finalToken || !clearButton) {+ throw new Error('Near-full token-row fixture did not render as expected');+ }+ const isCoarsePointer = matchMedia('(pointer: coarse)').matches;+ const requiresCoarsePointer =+ new URLSearchParams(window.location.search).get('storyPlayPointer') ===+ 'coarse';+ if (requiresCoarsePointer && !isCoarsePointer) {+ throw new Error('Near-full token-row guard requires a coarse pointer');+ }++ await document.fonts.ready;+ const reserveDeadline = performance.now() + 2000;+ while (+ wrapper.style.getPropertyValue('--_tokenizer-end-lane-reserve') === ''+ ) {+ if (performance.now() >= reserveDeadline) {+ throw new Error('Clear-all lane reserve was not measured');+ }+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => resolve()),+ );+ }+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );++ const inputRect = input.getBoundingClientRect();+ const firstTokenRect = firstToken.getBoundingClientRect();+ const tokenRect = finalToken.getBoundingClientRect();+ const clearRect = clearButton.getBoundingClientRect();+ let clearHitLeft = 0;+ let clearHitRight = 0;+ if (isCoarsePointer) {+ const clearHitStyle = getComputedStyle(clearButton, '::after');+ clearHitLeft = Number.parseFloat(clearHitStyle.left);+ clearHitRight = Number.parseFloat(clearHitStyle.right);+ if (+ clearHitStyle.content === 'none' ||+ !Number.isFinite(clearHitLeft) ||+ !Number.isFinite(clearHitRight)+ ) {+ throw new Error('Clear all did not expose its coarse-pointer hit area');+ }+ }+ const clearHitRect = {+ left: clearRect.left + clearHitLeft,+ right: clearRect.right - clearHitRight,+ };+ if (Math.abs(firstTokenRect.top - tokenRect.top) > 0.5) {+ throw new Error(+ `Fixture tokens wrapped before the empty combobox check: first token top ${firstTokenRect.top.toFixed(2)}, final token top ${tokenRect.top.toFixed(2)}`,+ );+ }+ // Fail closed if token metrics drift: the row is only "nearly full" while+ // the ordinary in-flow editing input (the typed-query layout) cannot fit+ // beside the final token. Without a placeholder the input never matches+ // :placeholder-shown, so it lays out exactly as it does once typing starts.+ const placeholderAttribute = input.getAttribute('placeholder');+ input.removeAttribute('placeholder');+ const inFlowInputTop = input.getBoundingClientRect().top;+ if (placeholderAttribute !== null) {+ input.setAttribute('placeholder', placeholderAttribute);+ }+ if (inFlowInputTop < tokenRect.bottom) {+ throw new Error(+ `Fixture is no longer a nearly full token row: the in-flow editing input still fits beside the final token (input top ${inFlowInputTop.toFixed(2)}, final token bottom ${tokenRect.bottom.toFixed(2)})`,+ );+ }+ if (inputRect.top >= tokenRect.bottom) {+ throw new Error(+ `Empty combobox wrapped onto a blank row: input top ${inputRect.top.toFixed(2)}, final token bottom ${tokenRect.bottom.toFixed(2)}`,+ );+ }+ if (inputRect.width <= 0) {+ throw new Error('Empty combobox has no pointer hit target');+ }+ const overlap =+ Math.min(inputRect.right, clearHitRect.right) -+ Math.max(inputRect.left, clearHitRect.left);+ if (overlap > 0) {+ throw new Error(+ `Empty combobox overlaps the coarse-pointer Clear all hit area by ${overlap.toFixed(2)}px`,+ );+ }+ const clearHitTarget = document.elementFromPoint(+ clearRect.left + clearRect.width / 2,+ clearRect.top + clearRect.height / 2,+ );+ if (!clearHitTarget || !clearButton.contains(clearHitTarget)) {+ throw new Error(+ `Clear all center is hit-tested as ${clearHitTarget?.tagName ?? 'nothing'}`,+ );+ }+ const tokenHitTarget = document.elementFromPoint(+ tokenRect.left + tokenRect.width / 2,+ tokenRect.top + tokenRect.height / 2,+ );+ if (!tokenHitTarget || !finalToken.contains(tokenHitTarget)) {+ throw new Error(+ `Final token center is hit-tested as ${tokenHitTarget?.tagName ?? 'nothing'}`,+ );+ }++ const hitY = inputRect.top + inputRect.height / 2;+ let inputHitTarget: Element | null = null;+ for (let x = Math.ceil(inputRect.left); x < inputRect.right; x += 1) {+ const candidate = document.elementFromPoint(x + 0.5, hitY);+ if (candidate === input) {+ inputHitTarget = candidate;+ break;+ }+ }+ if (!inputHitTarget) {+ throw new Error('Empty combobox has no exposed pointer hit target');+ }+ inputHitTarget.dispatchEvent(new MouseEvent('click', {bubbles: true}));+ if (document.activeElement !== input) {+ throw new Error('Clicking the empty combobox did not focus it');+ }+ },+};++export const NearFullTokenRowRTL: Story = {+ ...NearFullTokenRow,+ decorators: [+ Story => (+ <div dir="rtl">+ <Story />+ </div>+ ),+ ],+ name: 'Near-full Token Row (RTL)',+};+export const FullFeatured: Story = {render: args => {const [filters, setFilters] = useState<PowerSearchFilter[]>([]);diff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsxindex b55a203266..d5cb0cc52b 100644--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx@@ -416,6 +416,29 @@ describe('Tokenizer', () => {expect(input).not.toHaveAttribute('placeholder', 'Search people...');});+ it('uses a non-painting placeholder to collapse only an empty trailing input', () => {+ const onChangeQuery = vi.fn();+ render(+ <Tokenizer+ label="Members"+ searchSource={userSource}+ value={[users[0]]}+ onChange={() => {}}+ onChangeQuery={onChangeQuery}+ hasClear+ />,+ );+ const input = screen.getByRole('combobox');+ expect(input).toHaveAttribute('placeholder', ' ');++ fireEvent.change(input, {target: {value: 'Al'}});+ expect(input).toHaveValue('Al');+ expect(onChangeQuery).toHaveBeenLastCalledWith('Al');++ fireEvent.change(input, {target: {value: ''}});+ expect(onChangeQuery).toHaveBeenLastCalledWith('');+ });+it('shows placeholder when no tokens are present', () => {render(<Tokenizerdiff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsxindex ddf4e8b484..f2d6c767e1 100644--- a/packages/core/src/Tokenizer/Tokenizer.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.tsx@@ -243,6 +243,13 @@ export interface TokenizerProps<T extends SearchableItem> extends Omit<// How far the end lane sits from the field's inline-end border, named once// because the input's reserve is derived from the same value.const END_LANE_INSET = spacingVars['--spacing-2'];+const TOKEN_ROW_INSET = `calc(${spacingVars['--spacing-1']} - 1px)`;+// InputClearButton grows 2px past its visible box under `(pointer: coarse)`.+// Keep this maximum reserve in sync with Field/InputClearButton.tsx.+const INPUT_CLEAR_COARSE_POINTER_OUTSET = '2px';+// Kept in sync with useEndLaneReserve: inputCompact reads the custom property+// directly so its empty-query pseudo-class can suppress the inner reserve.+const END_LANE_RESERVE_VAR = '--_tokenizer-end-lane-reserve';const styles = stylex.create({wrapper: {@@ -260,19 +267,23 @@ const styles = stylex.create({// (radius-1: 4px) sits concentric with wrapper border-radius// (radius-2: 8px) when inset = radius-2 - radius-1 - border// = 8 - 4 - 1 = 3px.- paddingBlock: `calc(${spacingVars['--spacing-1']} - 1px)`,- paddingInline: `calc(${spacingVars['--spacing-1']} - 1px)`,+ paddingBlock: TOKEN_ROW_INSET,+ paddingInline: TOKEN_ROW_INSET,// Row gap must match paddingBlock so wrapped rows look evenly spaced.- rowGap: `calc(${spacingVars['--spacing-1']} - 1px)`,+ rowGap: TOKEN_ROW_INSET,},startIconWithTokens: {// Restore the default 8px inline-start inset when tokens are present,// since wrapperWithTokens reduces padding to 3px for border concentricity.marginInlineStart: `calc(${spacingVars['--spacing-2']} - ${spacingVars['--spacing-1']} + 1px)`,+ position: 'relative',+ zIndex: 1,},token: {display: 'flex',flexShrink: 0,+ position: 'relative',+ zIndex: 1,},endSection: {position: 'absolute',@@ -284,6 +295,7 @@ const styles = stylex.create({alignItems: 'center',gap: spacingVars['--spacing-2'],flexShrink: 0,+ zIndex: 1,},inputAtMax: {width: 0,@@ -294,12 +306,46 @@ const styles = stylex.create({position: 'absolute',},inputCompact: {- minWidth: '40px',- flex: '1 1 40px',- width: 0,- // Restore normal text inset when input follows tokens, since the- // wrapper padding is reduced for border concentricity.- paddingInlineStart: `calc(${spacingVars['--spacing-2']} - ${spacingVars['--spacing-1']} + 1px)`,+ position: {+ default: 'relative',+ ':placeholder-shown': 'absolute',+ },+ boxSizing: 'border-box',+ insetInlineStart: {+ default: 'auto',+ ':placeholder-shown': TOKEN_ROW_INSET,+ },+ zIndex: 0,+ minWidth: {+ default: '40px',+ ':placeholder-shown': '1px',+ },+ flex: {+ default: '1 1 40px',+ ':placeholder-shown': '0 0 auto',+ },+ width: {+ default: 0,+ ':placeholder-shown': `calc(100% - ${TOKEN_ROW_INSET} - var(${END_LANE_RESERVE_VAR}, ${TOKEN_ROW_INSET}) - ${INPUT_CLEAR_COARSE_POINTER_OUTSET} - 1px)`,+ },+ // The empty input is a first-row background hit surface. Taking it out of+ // flex layout means it can neither become a blank final row nor compete+ // with the pills for width. Logical insets stop it before the measured end+ // lane plus InputClearButton's maximum invisible pointer outset; tokens and+ // controls sit above it, leaving only genuine whitespace clickable as+ // search. Typing restores the ordinary in-flow input.+ paddingInlineStart: {+ default: `calc(${spacingVars['--spacing-2']} - ${spacingVars['--spacing-1']} + 1px)`,+ ':placeholder-shown': 0,+ },+ paddingInlineEnd: {+ default: `var(${END_LANE_RESERVE_VAR}, 0px)`,+ ':placeholder-shown': spacingVars['--spacing-1'],+ },+ textAlign: {+ default: 'start',+ ':placeholder-shown': 'end',+ },},truncatedWrapper: {flexWrap: 'nowrap',@@ -341,6 +387,39 @@ const endSectionSizeStyles = stylex.create({},});+const compactInputSizeStyles = stylex.create({+ sm: {+ insetBlockStart: {+ default: 'auto',+ ':placeholder-shown': `calc(${sizeVars['--size-element-sm']} / 2 - 1px)`,+ },+ transform: {+ default: 'none',+ ':placeholder-shown': 'translateY(-50%)',+ },+ },+ md: {+ insetBlockStart: {+ default: 'auto',+ ':placeholder-shown': `calc(${sizeVars['--size-element-md']} / 2 - 1px)`,+ },+ transform: {+ default: 'none',+ ':placeholder-shown': 'translateY(-50%)',+ },+ },+ lg: {+ insetBlockStart: {+ default: 'auto',+ ':placeholder-shown': `calc(${sizeVars['--size-element-lg']} / 2 - 1px)`,+ },+ transform: {+ default: 'none',+ ':placeholder-shown': 'translateY(-50%)',+ },+ },+});+const truncatedSizeStyles = stylex.create({sm: {height: sizeVars['--size-element-sm']},md: {height: sizeVars['--size-element-md']},@@ -527,9 +606,8 @@ export function Tokenizer<T extends SearchableItem>({// 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 hasClearButton = hasClear && value.length > 0 && !isDisabled;+ const hasStaticEndLane = Boolean(endContent || hasClearButton);const [isFocusedWithin, setIsFocusedWithin] = useState(false);const isTruncated =!isFocusedWithin && tokenOverflowBehavior !== 'none' && value.length > 0;@@ -874,7 +952,9 @@ export function Tokenizer<T extends SearchableItem>({value={null}onChange={handleAdd}renderItem={renderItem}- placeholder={value.length === 0 ? placeholder : ''}+ // A space keeps :placeholder-shown available as the CSS-only empty+ // query signal without painting placeholder text beside tokens.+ placeholder={value.length === 0 ? placeholder : ' '}hasEntriesOnFocus={isAtMax ? false : hasEntriesOnFocus}maxMenuItems={maxMenuItems}menuWidth={menuWidth}@@ -895,14 +975,12 @@ export function Tokenizer<T extends SearchableItem>({isAtMax || isTruncated? styles.inputAtMax: value.length > 0- ? styles.inputCompact+ ? [styles.inputCompact, compactInputSizeStyles[size]]: undefined,- // Not for the collapsed states above: those give the input no width- // to pad, and `inputAtMax` zeroes its padding outright.- // 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,+ // The compact-token style owns the same reserve with an empty-query+ // exception. This standalone rule is only for an empty Tokenizer;+ // it still resolves to zero until the lane publishes a width.+ !(isAtMax || isTruncated || value.length > 0) && laneReserve,]}/></BusyIndicatorLaneProvider>@@ -925,7 +1003,7 @@ export function Tokenizer<T extends SearchableItem>({loadingLabel={t('@astryx.typeahead.loading')}hasStaticContent={hasStaticEndLane}>{endContent}- {hasClear && value.length > 0 && !isDisabled && (+ {hasClearButton && (<InputClearButtonlabel={t('@astryx.tokenizer.clearAll')}onClick={e => {diff --git a/packages/core/src/Tokenizer/useEndLaneReserve.ts b/packages/core/src/Tokenizer/useEndLaneReserve.tsindex 4309973650..f61fea9282 100644--- a/packages/core/src/Tokenizer/useEndLaneReserve.ts+++ b/packages/core/src/Tokenizer/useEndLaneReserve.ts@@ -48,9 +48,8 @@ const LANE_RESERVE_VAR = '--_tokenizer-end-lane-reserve';// 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+// That is what lets every input state read the property without knowing whether+// a search is running. The rule stays static either way — it is never// regenerated as the lane changes.const reserveStyles = stylex.create({reserve: {@@ -82,9 +81,10 @@ 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 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.+ * ordinary input reserve style. Tokenizer's compact input reads the same custom+ * property directly so its empty-query hit surface can stop before the lane.+ * With no lane mounted the variable is absent and either rule resolves to its+ * no-lane fallback, so neither path needs to know whether a search is running.*/export function useEndLaneReserve(laneInset: string,