Skip to content

feat(Tokenizer): split delimited text into separate tokens on type and paste (#4175) - #4329

Open
AKnassa wants to merge 7 commits into
meta:mainfrom
AKnassa:rocky/issue-4175-tokenizer-delimiters
Open

AKnassa wants to merge 7 commits into
meta:mainfrom
AKnassa:rocky/issue-4175-tokenizer-delimiters

Conversation

@AKnassa

@AKnassa AKnassa commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

What this does

When a Tokenizer lets people create their own tags, they can now add a whole list at once: type a comma, or paste something like [email protected], [email protected], [email protected], and each value becomes its own tag. Before, that whole string became a single messy tag.

Why it matters

Pasting a list of emails, tags, or names is one of the most common things people do with an input like this. Today it quietly does the wrong thing. This makes the expected thing just work, out of the box.

What changed

  • Typing a comma (or newline) now finishes the current tag and starts a fresh one, the same as pressing Enter but mid-typing.
  • Pasting a comma- or newline-separated list creates one tag per value. Blank bits and duplicates are dropped, and any per-field limit is respected. All three newline flavors split (LF, CRLF, and the bare CR that Excel for Mac puts on the clipboard).
  • A paste is read together with what the input already holds: the clipboard is spliced over the selection exactly as the browser would insert it, so typing ur and pasting gent,x yields urgent and x, and pasting over a selection replaces it instead of leaving it behind for a later Enter.
  • Text composed with an IME is never split mid-composition; it is split once the composition ends, which is the only moment Chrome and Safari make the final text observable.
  • A disabled Tokenizer never splits, including the focusable-disabled (disabledMessage) mode whose readOnly input still receives paste events.
  • A new delimiters setting controls what counts as a separator (defaults to comma + newline). Set it to empty when a value might legitimately contain a comma, like a name written "Smith, John".
  • The advanced search filter builder (PowerSearch) keeps its old behaviour, so saved filters with commas in them are never silently split.

How to see it

In Storybook, Tokenizer: the Creatable (Free Text) story now accepts a pasted list; two new stories show the comma-safe opt-out and a custom separator set.


Notes for reviewers

Implements the spec in #4175.

On overlap: @HelloOjasMutreja posted a spec proposal on #4175 shortly before this branch was finished, and offered to open a PR once the shape was confirmed. This PR is a concrete answer to the open question raised there. Their proposal asked whether delimiters?: RegExp | ReadonlyArray<string> would be preferred over an array of string-or-RegExp; that is the shape implemented here. Happy to close this in their favour or fold their feedback in; @cixzhang's call, since it is her issue.

  • Default-on, both channels (typing + paste), comma + newline, matching the acceptance criteria literally. delimiters={[]} opts out; space is deliberately excluded (it would split ordinary multi-word values).

  • Plumbing: the query lives in BaseTypeahead's private state, so a one-argument transformQuery hook rewrites edited text before it becomes the query. Paste routes through the same hook: BaseTypeahead composes the post-paste value (clipboard over selection), runs the rewrite, and replaces the native insertion only when the rewrite changed the text, so a single-line input's CR/LF stripping never eats a spreadsheet column and a plain paste still follows the native path. compositionend runs the same rewrite for IME text.

  • onChange fires exactly once per commit (batching is required; N calls would each close over stale value). change.items carries the batch, change.item stays the last token so single-create consumers are unaffected. items? is an optional field on the existing 'create' member, not a new union member, so the changeset stays patch-level.

  • Splitter is a small pure module: strings match literally (metachars escaped), delimiters sorted longest-first, capture groups ignored (an exec loop, not String.split). A zero-width match never counts as a delimiter, so a pattern like /,*/u behaves like /,+/ instead of tokenizing every keystroke, and the empty-match skip advances whole code points so astral text cannot wedge the loop.

  • Stale searches: clearing the query (which a delimiter commit does) now invalidates any in-flight search, so late results cannot reopen the dropdown and hand Enter a value the user never chose (hasEntriesOnFocus + debounce window).

  • PowerSearch string_list infers hasCreate and persists values into saved queries, so it opts out (delimiters={[]}). The currently-unused OperatorTokenizationConfig looks like the intended per-operator home; left as a follow-up, along with the Table filter-control divergence.

  • Known follow-ups, all pre-existing patterns this PR chose not to expand: the announce strings ("Added 3 items") are plain English like the Tokenizer's existing announce strings rather than routed through t(); drag-and-drop of a newline-separated list still concatenates (no paste event fires); and the default set covers ASCII comma only, so full-width CJK (U+FF0C, U+3001) and Arabic (U+060C) commas need a custom delimiters for now. Happy to file or fold any of these on request.

  • Branch is merged up to current main. On the merged tree: Tokenizer, Typeahead, and PowerSearch suites 303/303 green (covering typed commits, composed pastes at the caret and over a selection, LF/CRLF/CR lists, IME composition, focusable-disabled, maxEntries, stale-search Enter, zero-width and astral regex delimiters), core typecheck, core build, and the strict CLI typecheck all pass.

Open question you raised in the issue: whether this should move to a richer create={{ ... }} shape if more free-text knobs appear, and whether siblings (MultiSelector) should share the behaviour. This keeps it on hasCreate + delimiters as the issue proposed.

With hasCreate, typing a comma or pasting a comma/newline-separated
list now commits one token per trimmed, non-empty, non-duplicate value
(respecting maxEntries) instead of creating a single token from the
whole string. Enter-to-create still works alongside.

New `delimiters` prop configures the split set: defaults to comma +
newline, accepts a string list or a RegExp (strings match literally, no
escaping; a RegExp ignores capture groups). Pass `delimiters={[]}` to
keep Enter as the only way to create when a value may itself contain a
comma, e.g. "Smith, John".

Plumbing: query state is private to BaseTypeahead and only its own
selection path clears it, so a new one-argument `transformQuery` hook
intercepts edited text before it becomes the query — Tokenizer uses it
to lift delimited values out and return '' so the input clears with no
imperative DOM write. Newline-separated pastes (e.g. a spreadsheet
column) are read from clipboardData via onPaste before the single-line
input strips the newlines. A multi-token commit fires exactly one
onChange (batching is required — N calls would each close over stale
value); change.items carries the batch, change.item stays the last
token so single-create consumers are unaffected.

PowerSearch's string_list editor infers hasCreate and its values persist
into saved queries, so it opts out (delimiters={[]}) rather than
silently splitting a stored value like "Acme, Inc." — per-operator paste
splitting is meant to arrive via the (currently unused)
OperatorTokenizationConfig as a follow-up.

Closes meta#4175
@vercel

vercel Bot commented Jul 25, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
astryx Ready Ready Preview Sep 26, 2026 4:30am UTC

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 25, 2026
@github-actions github-actions Bot added community Authored by a community contributor (not on the eng/design team) needs:code-review High-risk change (new package/component/API) — needs human code review before merge needs:design-review Affects visuals — Design should review labels Jul 25, 2026
@github-actions

github-actions Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR

🧪 Sandbox Preview

View Sandbox for this PR

Modified Components

PowerSearch (@astryxdesign/core) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 3853 -
Complexity N/A Very High (335) -

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@astryxdesign/core N/A 4.9KB 1.2KB

Accessibility Audit

Status: 2 accessibility violation(s) found — 2 serious.

PowerSearch - 1 issue(s)
  • 🟠 serious: Ensure the contrast between foreground and background colors meets WCAG 2 AA minimum contrast ratio thresholds
    • Rule: color-contrast · Affects 2/26 stories · Learn more
    • WCAG: 1.4.3 (Level AA)
Tokenizer - 1 issue(s)
  • 🟠 serious: Ensure the contrast between foreground and background colors meets WCAG 2 AA minimum contrast ratio thresholds
    • Rule: color-contrast · Affects 2/26 stories · Learn more
    • WCAG: 1.4.3 (Level AA)

Visual Regression

1 of 420 shot(s) changed.

A change here is a question, not a failure: check whether the after is the
picture you intended. Record that review on the PR. Baseline maintenance is an
explicit dispatch of CI; this report never rewrites the baseline or adds a release gate.

component story theme mode pixels
SideNav Resizable in AppShell probe dark 3,208

Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

@AKnassa
AKnassa marked this pull request as ready for review August 1, 2026 03:22
github-actions Bot added a commit that referenced this pull request Aug 1, 2026
@github-actions github-actions Bot removed the needs:design-review Affects visuals — Design should review label Aug 27, 2026
github-actions Bot added a commit that referenced this pull request Aug 27, 2026

@astracat-bot astracat-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for implementing the delimited-list workflow — the paste/selection, newline-flavour, IME, capacity and PowerSearch opt-out handling is thorough.

One change is needed before approval:

  • The new delimiter-commit announcements in Tokenizer.tsx are hard-coded as Added … / Added … items, while the existing add/create paths announce through t('@astryx.tokenizer.tokenAdded'). Non-English screen-reader users therefore hear English on this new default path, and the batch count has no locale-aware plural handling. Please route the single-token case through the existing catalog message, add an ICU-pluralised catalog message for batches, and cover the delimiter path under a non-English provider in tests.

No redesign of the delimiter parsing or batch onChange shape is needed.

[Automated review]

Resolved conflicts:
- packages/core/src/Tokenizer/Tokenizer.tsx: took upstream's
  BusyIndicatorLaneProvider-wrapped BaseTypeahead (array inputXStyle with
  the lane reserve) and re-added
  `transformQuery={hasCreate ? commitDelimitedText : undefined}`.
- packages/core/src/Tokenizer/Tokenizer.test.tsx: took upstream's
  multi-line vitest import (adds beforeEach) and folded this branch's
  `useState` into upstream's `import {Profiler} from 'react'`.
- packages/core/src/Typeahead/BaseTypeahead.doc.mjs: kept upstream's
  xstyle/inputTabIndex/onKeyDown entries and re-added the transformQuery
  entries (docs, docsZh, docsDense), prettier-formatted like the rest of
  upstream's now-formatted file.

Semantic fallout fixed in packages/core/src/Typeahead/BaseTypeahead.tsx:
- The empty-query branch called `setIsLoading(false)` directly. Upstream
  (meta#5555) routes the busy state through `setLoading`, which also reports
  it to the BusyIndicatorLane and edge-guards on a ref. Bypassing it left
  Tokenizer's end-lane spinner up forever after a delimiter commit
  abandoned an in-flight search. Now `setLoading(false)`. Covered by the
  new Tokenizer test "a delimiter commit clears the busy indicator of an
  in-flight search" (red before: the Loading status span was still in
  the document).
- Upstream's meta#6179 audit spreads `...rest` onto the input, but this
  branch's hard-coded `onCompositionEnd={handleCompositionEnd}` came
  after it and silently dropped a consumer's onCompositionEnd. It is now
  destructured and composed with composeEventHandlers, like
  onFocus/onBlur/onPointerDown. Covered by extending BaseTypeahead's
  "forwards supported DOM, styling, and event props" test (red before:
  onCompositionEnd called 0 times).

Tokenizer, Typeahead and PowerSearch suites: 14 files, 439 tests pass.
Addresses astracat-bot's review (CHANGES_REQUESTED, 2026-09-24) and the
two @astryx/no-hardcoded-i18n-string errors failing `lint`.

- F1: a single-value delimiter commit now announces
  t('@astryx.tokenizer.tokenAdded', {label}), the same message the
  Enter/click create path uses, instead of a hard-coded `Added ${label}`.
  `t` is added to commitDelimitedText's useCallback deps.
- F2: a batch commit announces the new ICU-plural catalog message
  @astryx.tokenizer.tokensAdded ("Added {count, number} {count, plural,
  one {item} other {items}}") instead of `Added ${n} items`. Only en.json
  gets the key (other locales fall back, per meta#6217/meta#6220). English output
  is unchanged, so the existing English announce tests stay green. The
  changeset mentions both keys.
- F3: TOKEN_MESSAGES.fr gains a tokensAdded override, and two tests
  render the delimiter path under <InternationalizationProvider
  locale="fr">: a typed "alice," and a pasted "a, b, c". Before the fix
  they failed with "expected 'Added alice' to be 'Ajouté : alice'" and
  "expected 'Added 3 items' to be '3 éléments ajoutés'"; both pass now.

Checks: Tokenizer/Typeahead/PowerSearch suites (14 files, 441 tests)
and the i18n suite pass; eslint (also ASTRYX_STRICT_LINT=1) is clean on
Tokenizer.tsx; core tsc, prettier, check:i18n-catalog,
check:changesets, check:sync and check:knowledge pass.
The pre-commit hook (lint-staged: eslint --fix + prettier --write) ran on
the upstream/main merge commit dc0e1e4 and rewrote 12 files that this PR
never touched, so they showed up as formatting-only churn in the PR diff.
This restores each of them byte-for-byte from upstream/main (82fb22c,
the merge's second parent):

- apps/storybook/stories/MobileTokenizer.stories.tsx
- internal/vibe-tests/stepper-collapse-naming-test/PLAN.md
- internal/vibe-tests/stepper-collapse-naming-test/docs/arm-{a-collapsed,b-bare,c-summary,d-enum,recall}.md
  (gen-docs.mjs output; PLAN.md relies on the arms staying byte-identical
  outside their substitutions)
- packages/core/src/Carousel/Carousel.test.tsx
- packages/core/src/Chat/__tests__/ChatMessageMetadata.a11y.chromium.spec.ts
- packages/core/src/TextInput/TextInput.test.tsx
- packages/lab/src/MobileTokenizer/MobileTokenizer.{tsx,test.tsx} (meta#6640)

Committed with the hook bypassed, because lint-staged would otherwise
re-prettify exactly these staged files. After this commit,
`git diff --stat upstream/main HEAD` lists only the PR's 16 files.
@AKnassa

AKnassa commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, agreed. When I opened this, the Tokenizer's existing announcements were still plain English. #4920 has since moved them into the catalog, so the delimiter path was the only hard-coded one left, and that is also what was failing lint. Pushed up to e41264f:

I also merged current main. The three conflicts were mechanical. Upstream's BaseTypeahead refactor needed two follow-up fixes in the merge, each with a regression test: the busy state now clears through the lane-aware setLoading, and a consumer's onCompositionEnd gets forwarded instead of dropped. e41264f undoes formatting-only changes the pre-commit hook made to upstream files during the merge, so the diff is just this PR's files again.

Delimiter parsing and the batch onChange shape are unchanged. Still on my side: updating the description to remove the stale "plain English announcements" follow-up note.

@astracat-bot astracat-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the thorough delimited-list implementation — and for fixing the announcement localisation.

Verified at this revision:

  • Single delimiter commits now announce through @astryx.tokenizer.tokenAdded, the same catalog message as the Enter/click create path, and batch commits use the new ICU-plural @astryx.tokenizer.tokensAdded message.
  • New tests cover both the typed and pasted delimiter paths under a French provider, so hard-coded English would fail them.
  • The paste/selection, LF/CRLF/CR, IME, capacity, disabled and PowerSearch opt-out handling remains intact, including the merge follow-ups for busy-state clearing and consumer onCompositionEnd forwarding.

No further changes are needed from this review.

[Automated review]

@astracat-bot astracat-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the careful implementation: pasting or typing a list now creates one token per value, as described. Approval waits on a maintainer, because the current Tokenizer spec does not cover this addition: a maintainer needs to provide or identify the governing spec for the delimiters prop, settling whether splitting is on by default for existing hasCreate fields, the batched TokenizerChange.items shape, and whether BaseTypeahead.transformQuery becomes public API (you don't need to write that spec). Meanwhile, please merge current main, which conflicts in five files, and carry its case-insensitive label check for already-selected tokens (#6367) into the delimiter path so a pasted list cannot add a duplicate that Enter would refuse. If the default stays on after that decision, the Changeset should be [breaking] with delimiters={[]} as the migration, per spec AST-017.

[Automated review]

@@ -0,0 +1,6 @@
---
'@astryxdesign/core': patch

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This turns delimiter splitting on for every existing hasCreate Tokenizer. Under spec AST-017 FR1/FR3, a default that changes functional behavior is breaking when a caller must add configuration to keep working, and the PowerSearch delimiters={[]} pin in this PR is that case. If the default stays on after the maintainer decision, this needs [breaking], the old (Enter-only) and new defaults, and delimiters={[]} as the migration; if it becomes opt-in, patch [feat] is right.

// silently dropping a paste on a field that can accept no more.
return text;
}
const seen = new Set(selectedIds);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When you merge current main: #6367 made the create path also reject a value whose label matches a selected token, ignoring case (selectedLabels). This hunk merges without a conflict, so unless it changes too, pasting Alice, Bob beside a selected {id: 'usr_1', label: 'Alice'} creates a second "Alice" that Enter refuses. Seeding seen with the lowercased selected labels and comparing trimmed.toLowerCase() keeps the two paths in sync, as the comment above asks.

This branch was successfully deployed

1 active deployment
Preview — e41264fb Deployed Sep 26, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot. community Authored by a community contributor (not on the eng/design team) lane:1 Astryx fix-loop lane 1 owns this needs:code-review High-risk change (new package/component/API) — needs human code review before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants