Skip to content

[otp field] Compose normalizeValue with validation - #4717

Merged
atomiks merged 6 commits into
mui:masterfrom
atomiks:codex/otp-sanitize-validation-compose
May 18, 2026
Merged

atomiks merged 6 commits into
mui:masterfrom
atomiks:codex/otp-sanitize-validation-compose

Conversation

@atomiks

@atomiks atomiks commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Closes #4608

normalizeValue composes with built-in validation so callers can uppercase alphanumeric recovery codes without opting out of validationType="alphanumeric". OTP Field validates input before and after normalization, then queues focus and updates state with the normalized value.

Changes

  • Rename sanitizeValue to normalizeValue while OTP Field can still take breaking API changes.
  • Compose normalizeValue after whitespace and validationType filtering, then apply validationType again before clamping.
  • Remove the dev warning for combining custom normalization with built-in validation.
  • Update OTP Field docs/types/demo and add regression coverage for uppercase alphanumeric input advancing focus.

@atomiks atomiks added type: bug It doesn't behave as expected. component: otp field labels May 1, 2026
@pkg-pr-new

pkg-pr-new Bot commented May 1, 2026 •

Copy link
Copy Markdown

commit: 85914d3

@code-infra-dashboard

code-infra-dashboard Bot commented May 1, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+111B(+0.02%) 🔺+58B(+0.04%)

Details of bundle changes

Performance

Total duration: 1,177.33 ms +130.57 ms(+12.5%) | Renders: 50 (+0) | Paint: 1,800.63 ms +207.45 ms(+13.0%)

Test Duration Renders
Select mount (200 instances) 162.63 ms 🔺+41.49 ms(+34.2%) 3 (+0)
Select open (500 options) 49.03 ms 🔺+9.50 ms(+24.0%) 14 (+0)

10 tests within noise — details


Check out the code infra dashboard for more information about this PR.

@netlify

netlify Bot commented May 1, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Name Link
🔨 Latest commit 85914d3
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6a0b1c2bb370d400081a7065
😎 Deploy Preview https://deploy-preview-4717--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@atomiks
atomiks force-pushed the codex/otp-sanitize-validation-compose branch 5 times, most recently from e2bdd49 to 691d577 Compare May 4, 2026 04:05
@atomiks
atomiks marked this pull request as ready for review May 4, 2026 04:45

@flaviendelangle flaviendelangle left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

PR Review Summary — #4717 [otp field] Compose sanitizeValue with validation

Four review agents ran against mui/base-ui PR #4717 (small PR: +67 / −43, OTP Field). The PR changes sanitizeValue from a no-op-when-validationType !== 'none' (with dev warning) into a value composed after the built-in regex filter, removes the warning, and updates docs/tests.

There are two genuinely cross-cutting themes the agents converged on independently:

  • The new contract has more footguns and fewer guardrails. The deleted dev warning at least caught the old misuse; the new "should be idempotent and only contain characters allowed by validationType" is enforced only by JSDoc — see findings C1, C2, I3, I5.
  • sanitizeValue is invoked more than once per change (via replaceOTPValue's double-normalizeOTPValue), which is the real reason idempotency matters — and the JSDoc justifies idempotency with the wrong reason. See findings C3, I2, I4.

Critical Issues (must address before merge)

  • C1 — Sanitizer can silently inject characters that violate validationType. normalizeOTPValue filters with validation.regexp first, then runs sanitizeValue and uses its output as-is (no re-filter). Disallowed chars flow into valueRef, onValueChange, onValueComplete, and the hidden form input's pattern, causing opaque native form-validation failures with no console message. Suggested fix: in dev mode, re-apply validation.regexp to the sanitized value and warn if anything was stripped. — silent-failure-hunter, also raised by code-reviewer as Suggestion #4. packages/react/src/otp-field/utils/otp.ts:56-62

  • C2 — No guard on sanitizeValue return type. A non-string return (number ⇒ Array.from(123) === [] silently clears state; undefined ⇒ TypeError deep in Array.from with no mention of sanitizeValue). Suggested fix: dev-only Base UI error if typeof sanitized !== 'string'. — silent-failure-hunter. packages/react/src/otp-field/utils/otp.ts:60-65

  • C3 — sanitizeValue runs twice per replaceOTPValue call. replaceOTPValue invokes normalizeOTPValue once on the inserted fragment and again on the assembled prefix+normalized+suffix. Pre-PR this was harmless; post-PR any non-idempotent sanitizer (e.g., v => v + '!') grows on every keystroke. Either document this explicitly and state the real reason for idempotency, or refactor to apply sanitizeValue once on the fully assembled string. — code-reviewer Important #2, comment-analyzer Critical #1. packages/react/src/otp-field/utils/otp.ts:80-89


Important Issues (should address)

  • I1 — onValueInvalid under-reports / mis-reports under composition. The didSanitize check is stripOTPWhitespace(rawValue).length > nextDigits.length against the post-sanitize length at three call sites (OTPFieldRoot.tsx:420, OTPFieldInput.tsx:152, OTPFieldInput.tsx:295). Any sanitizer that adds/expands characters hides regex-stage drops; replacements that change length never trigger the callback even though data was modified. Suggested fix: compute the intermediate post-validation length in otp.ts and compare both legs. — code-reviewer Important #1, silent-failure-hunter Important #3.

  • I2 — JSDoc on sanitizeValue justifies "idempotent" with the wrong reason. The "used as-is before being clamped to length" clause motivates "don't emit disallowed chars / don't exceed length" — not idempotency. The actual cause is the double invocation in replaceOTPValue (see C3). Suggested rewrite splits the two requirements. — comment-analyzer Critical #1. packages/react/src/otp-field/root/OTPFieldRoot.tsx:518-523

  • I3 — Removed warning needs a release-notes entry. Pre-PR <OTPField.Root sanitizeValue={fn} /> (default validationType="numeric") was a warned no-op; post-PR the same callsite silently runs the sanitizer. No type signature changes, but the runtime semantics flip for existing apps. Project convention is to add changelog entries at release time, but the author should explicitly flag this for release notes. — code-reviewer Suggestion #5, silent-failure-hunter Important #4.

  • I4 — Test gap: sanitizer that expands the string. The new JSDoc rules out this misuse but no test pins down what actually happens (slipped chars vs. clamp behavior). One-liner in packages/react/src/otp-field/utils/otp.test.ts: expect(normalizeOTPValue('12', 6, 'numeric', v => v + 'AB')).toBe('12AB'). — pr-test-analyzer Important #1.

  • I5 — Test gap: no negative warning assertion. Old "warns when…" test was deleted but nothing asserts the warning doesn't fire under the new composition — a regression that re-introduces the warning would slip through. Add expect(warnSpy).not.toHaveBeenCalled() inside one of the new composition tests. — pr-test-analyzer Important #4.

  • I6 — Test gap: sanitizer returns empty string after regex passes characters. Lands in the "nextDigits === ''" branch at OTPFieldInput.tsx:152-172 with the slot-revert behavior — currently unverified for the new pipeline. — pr-test-analyzer Important #2.

  • I7 — Test gap: clamp leg of the new composition. The new paste test uses 'ab-12 cd!' ⇒ exactly 6 chars, so clamping never fires alongside sanitizeValue. — pr-test-analyzer Important #3.


Suggestions

  • S1 — Page prose grammar / clarity. "...uppercasing alphanumeric codes, which runs after validationType filtering" attaches the relative clause to the wrong noun; "Use validationType="none" to replace the built-in rule" is cryptic on its own. Both code-reviewer and comment-analyzer flagged this. Suggested rewrite from comment-analyzer reads cleanly. docs/src/app/(docs)/react/components/otp-field/page.mdx:111

  • S2 — JSDoc could mention onValueInvalid interaction. Characters dropped by sanitizeValue count as rejected input and trigger onValueInvalid — useful, non-obvious. — comment-analyzer. packages/react/src/otp-field/root/OTPFieldRoot.tsx:517-524

  • S3 — Hidden-input pattern constraint. Worth one JSDoc line warning that a sanitizer emitting characters outside validationType will pass through user-facing state but break native form validation. — code-reviewer Suggestion #4. packages/react/src/otp-field/root/OTPFieldRoot.tsx:447

  • S4 — Dead CSS in updated demo. .Code class in index.module.css was used only by the old "Digits 0-3 only" description; the new demo doesn't reference it. — comment-analyzer. docs/src/app/(docs)/react/components/otp-field/demos/custom-sanitize/css-modules/index.module.css:75-78

  • S5 — Test gap: paste-path parity for onValueInvalid under composition. Existing paste test only covers built-in regex; mirror the new typing-path inputChange test for inputPaste. — pr-test-analyzer Nice-to-have #5.

  • S6 — Test gap: replaceOTPValue double-application + defaultValue/controlled-value path. Each one-line test, both close real branches in the new pipeline. — pr-test-analyzer Nice-to-have #6, #7.

  • S7 — inputMode removal in demo is not a regression. With validationType="alphanumeric" the default inputMode is 'text' from OTP_VALIDATION_CONFIG.alphanumeric.inputMode, so the demo gets the right virtual-keyboard hint for free. (Confirmed by comment-analyzer.)


Strengths

  • Core change in normalizeOTPValue is minimal, the validation-then-sanitize order is correct for the documented use case, length clamping (incl. multi-byte safety via Array.from) is preserved verbatim, and whitespace-stripping order is unchanged.
  • The new composes built-in validation and custom sanitization typing test correctly verifies single-invocation onValueInvalid semantics with the raw-value first arg — the hardest contract to preserve.
  • Demo refactor (recovery-code uppercasing under alphanumeric) is a strictly better illustration of the new behavior than the old tier-code-only demo.
  • No dead imports or stale type fields left over from the warning removal; repo-wide search for the deleted warning text returned zero hits.
  • Public API surface (props, types, namespaces) is unchanged — pure behavior + docs change, correct scope for closing #4608.
  • JSDoc on normalizeOTPValue itself ("Slice by Unicode code points so multi-byte characters do not split…") is a model for intent-explaining comments.

Recommended Action

  1. Address C1, C2, C3 first — these need either dev-mode warnings/guards or a docs+behavior change. C3 in particular forces a choice: refactor replaceOTPValue to call sanitizeValue once, or commit to the "must be idempotent" contract and surface it loudly.
  2. Fix the onValueInvalid gating (I1) and the JSDoc reasoning (I2) together — both stem from the same composition model.
  3. Add the four small tests (I4, I5, I6, I7) — each is one-liner-sized and pins down newly-reachable branches.
  4. Polish docs (S1, S2, S3) and delete the dead CSS (S4).
  5. Coordinate release notes for the silent semantics flip (I3).
  6. Re-run /pr-review-toolkit:review-pr after fixes to verify.

@atomiks
atomiks force-pushed the codex/otp-sanitize-validation-compose branch 4 times, most recently from a1f7347 to 43ebb9a Compare May 4, 2026 09:03
@atomiks
atomiks requested a review from Copilot May 6, 2026 09:53

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes OTP Field’s inability to compose sanitizeValue with built-in validationType filtering (e.g., uppercasing alphanumeric recovery codes) by ensuring normalization happens before state updates and focus-queueing, preventing controlled-value mismatches that previously broke focus advancement.

Changes:

  • Compose built-in OTP validation with sanitizeValue (apply validation → sanitize → validate again → clamp).
  • Remove the dev warning that discouraged combining sanitizeValue with built-in validation.
  • Add regression tests (utils + component) and update docs to reflect the new sanitization behavior.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated no comments.

Show a summary per file
File Description
packages/react/src/otp-field/utils/otp.ts Updates normalization to compose built-in validation with custom sanitization (and re-filter + clamp).
packages/react/src/otp-field/utils/otp.test.ts Adds unit coverage for sanitize+validation composition, re-filtering, and clamping behavior.
packages/react/src/otp-field/root/OTPFieldRoot.tsx Removes the dev warning and updates prop docs to describe the new sanitize semantics/idempotency.
packages/react/src/otp-field/root/OTPFieldRoot.test.tsx Adds regression coverage ensuring uppercase sanitization with validationType="alphanumeric" advances focus and integrates with invalid reporting.
packages/react/src/otp-field/input/OTPFieldInput.tsx Minor refactor to reuse rawValue while normalizing (behavior unchanged beyond new normalize semantics).
docs/src/app/(docs)/react/components/otp-field/types.md Updates generated API docs for sanitizeValue to match the new behavior/expectations.
docs/src/app/(docs)/react/components/otp-field/page.mdx Updates narrative docs to explain composed sanitization vs validationType="none".
docs/src/app/(docs)/react/components/otp-field/demos/custom-sanitize/css-modules/index.tsx Updates the demo to show uppercasing recovery codes with built-in alphanumeric validation.
docs/src/app/(docs)/react/components/otp-field/demos/custom-sanitize/css-modules/index.module.css Removes unused styling associated with the prior demo content.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label May 13, 2026
@atomiks
atomiks force-pushed the codex/otp-sanitize-validation-compose branch from d7a1653 to 76c873f Compare May 13, 2026 09:34
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label May 13, 2026
@atomiks
atomiks force-pushed the codex/otp-sanitize-validation-compose branch from 76c873f to 4721b91 Compare May 15, 2026 05:34
@atomiks atomiks changed the title [otp field] Compose sanitizeValue with validation [otp field] Compose normalizeValue with validation May 15, 2026
@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label May 18, 2026
# Conflicts:
#	packages/react/src/otp-field/root/OTPFieldRoot.test.tsx
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label May 18, 2026
@oliviertassinari oliviertassinari added the breaking change Introduces changes that are not backward compatible. label May 18, 2026

@flaviendelangle flaviendelangle left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Claude Code is totally obsessed with try/catch these days 🙄


PR #4717 Review Summary — [otp field] Compose normalizeValue with validation

PR: #4717
Author: atomiks
Branch: codex/otp-sanitize-validation-compose → master
Stats: +344 / -132 across 13 files

Critical Issues (2 found)

  • silent-failure-hunter: Untrusted normalizeValue callback runs with no try/catch — and on render. otp.ts:63 is called from OTPFieldRoot.tsx:137 at render time, so a throwing user normalizer destroys the consumer's React tree on mount with no actionable Base UI: error wrapping it. Handler paths (OTPFieldRoot.tsx:230, OTPFieldRoot.tsx:415, OTPFieldInput.tsx:141, 288) swallow into React's synthetic-event boundary with a generic stack.
  • code-reviewer: didRejectCharacters discarded by replaceOTPValue otp.ts:92-110 — both internal flags are thrown away. Callers at OTPFieldInput.tsx:140-153, 288-300 compute didRejectCharacters only from the raw → first-pass step. If the second pass strips characters (combined string overflow or non-idempotent normalizer rejecting more chars), onValueInvalid will not fire but the rendered value silently loses chars.

Important Issues (4 found)

  • code-reviewer: Stale demo folder name docs/.../otp-field/demos/custom-sanitize/ — the feature was renamed everywhere (function OTPFieldCustomNormalizeDemo, export DemoOTPFieldCustomNormalize, MDX heading "Custom normalization", prop normalizeValue) except the directory and the MDX import at page.mdx:118. Use git mv to preserve rename history.
  • silent-failure-hunter / comment-analyzer: Length-clamp now triggers onValueInvalid, undocumented in JSDoc. otp.ts:75 ORs in normalizedCharacters.length > maxLength. The JSDoc at OTPFieldRoot.tsx:570-575 only mentions "validation or normalization" — overflow is omitted. Mirrored docs at types.md:408-414 have the same gap. Suggest: "rejected by validation, normalization, or because the input exceeds length".
  • silent-failure-hunter: No replacement dev warning for new failure modes. The old sanitizeValue + non-none validationType warning was removed (OTPFieldRoot.tsx:684 deleted). No replacement guards: (a) non-idempotent normalizers (JSDoc tells users but nothing checks); (b) non-string return values (would crash .length or silently break didRejectCharacters because undefined > number is false); (c) the empty-output footgun when normalizer's chars get stripped by validationType.
  • comment-analyzer: normalizeOTPValueWithDetails header otp.ts:47-50 omits the second validation pass — the most subtle, load-bearing part of the pipeline. Same for replaceOTPValue header lines 88-91, which understates that the function normalizes twice.

Test Gaps (2 critical, others important)

  • pr-test-analyzer: No test asserts normalizeValue runs on consumer-provided value / defaultValue. JSDoc at OTPFieldRoot.tsx:520-528 promises it; source at OTPFieldRoot.tsx:137 wires it; but no test in OTPFieldRoot.test.tsx verifies <OTPField value="ab-12" normalizeValue={(v) => v.toUpperCase()} validationType="alphanumeric" /> renders AB12. A regression that drops the render-time normalize would silently break a documented contract.
  • pr-test-analyzer: Non-idempotent normalizer behavior untested. New JSDoc warns about compounding across replaceOTPValue's two passes, but otp.test.ts:77-81 only covers a purifying (idempotent) normalizer. Anyone refactoring the second normalizeOTPValue call away (or to a single pass) would silently change semantics the docs now warn about.
  • pr-test-analyzer: Other untested edges: clamp-only onValueInvalid from over-length paste; expanding normalizer at a non-first slot (replaceOTPValue suffix math); Unicode/surrogate pairs through the full pipeline; hidden-input autofill with overflow / empty result; validationType="none" + normalizer that emits forbidden chars (second filter is a no-op there).

Suggestions (4 found)

  • code-reviewer: UTF-16 vs code-point inconsistency between otp.ts:60, 64, 66 (.length, UTF-16 units) and line 75 (Array.from(...), code points). Benign today because all built-in validators strip non-ASCII; worth a one-line comment to document the design choice.
  • code-reviewer: replaceOTPValue UTF-16 slicing at otp.ts:101-102 — prefix/suffix = currentValue.slice(...) uses UTF-16 offsets while index is a slot count. Only reachable with validationType="none" + permissive normalizer.
  • code-reviewer: Whitespace is silently stripped at otp.ts:57 without firing onValueInvalid. Almost certainly intentional (paste UX), but not documented on the public prop or in page.mdx.
  • code-reviewer + pr-test-analyzer: Stray warnSpy in OTPFieldRoot.test.tsx:232-252 — assertion is a noop now that the warning is removed; either drop it or move to a dedicated "does not warn when combining validationType with normalizeValue" regression test.

Strengths

  • Composition pipeline is well designed — normalizeOTPValueWithDetails tuple cleanly eliminates the prior stripOTPWhitespace(rawValue).length > nextDigits.length re-comparison at every call site (verified at OTPFieldRoot.tsx:415-427, OTPFieldInput.tsx:140-153, 288-300).
  • Code-point slicing in the final clamp (otp.ts:71-74) is the correct fix for multi-byte clamping.
  • Type-level rename guard: @ts-expect-error at OTPFieldRoot.spec.tsx:110-112 pins the prop rename and will catch accidental re-introduction.
  • Composition tests are genuinely thorough on the happy paths: built-in→custom order, custom output re-filtered, clamping after expansion, suffix-preserving mid-OTP replacement, paste path, hidden-input autofill, no-warning regression, normalizer-empties-value, all covered.
  • JSDoc earns its keep: "non-idempotent normalizers can compound across those normalization passes" is exactly the kind of "why" comment that wouldn't be derivable from reading the code.
  • All AGENTS.md / CLAUDE.md rules are respected — useStableCallback, useIsoLayoutEffect, ownerDocument, shadow-DOM-safe utilities, Base UI: error-message prefix.
  • Docs prose at page.mdx:109-116 genuinely re-explains the new composition semantics rather than mechanically renaming "sanitize" → "normalize".
  • didRejectCharacters accounting via ||= is monotonic OR — verified safe, no branch can clear a prior true.

Recommended Action

  1. Critical first: wrap normalizeValue calls (especially the render-time one at OTPFieldRoot.tsx:137) and surface a Base UI: error; thread didRejectCharacters through replaceOTPValue to its callers.
  2. Then important: rename the demo folder (git mv custom-sanitize custom-normalize + update page.mdx:118); add length-overflow to the onValueInvalid JSDoc; document the second validation pass in normalizeOTPValueWithDetails / replaceOTPValue headers.
  3. Add the two critical tests: render-time normalization on value/defaultValue; non-idempotent normalizer behavior locked in.
  4. Optional: dev warning for non-idempotent / non-string normalizer output to replace the removed sanitizeValue warning; drop the noop warnSpy.
  5. No blockers from a "code is wrong" standpoint — the composition math is correct. The criticals are about robustness (uncaught user-callback throw) and contract integrity (missing flag wiring through replaceOTPValue).

@atomiks
atomiks merged commit ccb4b30 into mui:master May 18, 2026
6 checks passed
@atomiks
atomiks deleted the codex/otp-sanitize-validation-compose branch May 18, 2026 14:08
mbrookes pushed a commit to mbrookes/base-ui that referenced this pull request May 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking change Introduces changes that are not backward compatible. component: otp field type: bug It doesn't behave as expected.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[otp field] Allow for uppercase-only input

4 participants