Repository navigation
[otp field] Compose normalizeValue with validation - #4717
Conversation
commit: |
Bundle size
PerformanceTotal duration: 1,177.33 ms +130.57 ms(+12.5%) | Renders: 50 (+0) | Paint: 1,800.63 ms +207.45 ms(+13.0%)
10 tests within noise — details Check out the code infra dashboard for more information about this PR. |
✅ Deploy Preview for base-ui ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
e2bdd49 to
691d577
Compare
flaviendelangle
left a comment
There was a problem hiding this comment.
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. sanitizeValueis invoked more than once per change (viareplaceOTPValue'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.normalizeOTPValuefilters withvalidation.regexpfirst, then runssanitizeValueand uses its output as-is (no re-filter). Disallowed chars flow intovalueRef,onValueChange,onValueComplete, and the hidden form input'spattern, causing opaque native form-validation failures with no console message. Suggested fix: in dev mode, re-applyvalidation.regexpto the sanitized value andwarnif anything was stripped. —silent-failure-hunter, also raised bycode-revieweras Suggestion #4.packages/react/src/otp-field/utils/otp.ts:56-62 -
C2 — No guard on
sanitizeValuereturn type. A non-string return (number ⇒Array.from(123) === []silently clears state;undefined⇒TypeErrordeep inArray.fromwith no mention ofsanitizeValue). Suggested fix: dev-only Base UI error iftypeof sanitized !== 'string'. —silent-failure-hunter.packages/react/src/otp-field/utils/otp.ts:60-65 -
C3 —
sanitizeValueruns twice perreplaceOTPValuecall.replaceOTPValueinvokesnormalizeOTPValueonce on the inserted fragment and again on the assembledprefix+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 applysanitizeValueonce on the fully assembled string. —code-reviewerImportant #2,comment-analyzerCritical #1.packages/react/src/otp-field/utils/otp.ts:80-89
Important Issues (should address)
-
I1 —
onValueInvalidunder-reports / mis-reports under composition. ThedidSanitizecheck isstripOTPWhitespace(rawValue).length > nextDigits.lengthagainst 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 inotp.tsand compare both legs. —code-reviewerImportant #1,silent-failure-hunterImportant #3. -
I2 — JSDoc on
sanitizeValuejustifies "idempotent" with the wrong reason. The "used as-is before being clamped tolength" clause motivates "don't emit disallowed chars / don't exceedlength" — not idempotency. The actual cause is the double invocation inreplaceOTPValue(see C3). Suggested rewrite splits the two requirements. —comment-analyzerCritical #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} />(defaultvalidationType="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-reviewerSuggestion #5,silent-failure-hunterImportant #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-analyzerImportant #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-analyzerImportant #4. -
I6 — Test gap: sanitizer returns empty string after regex passes characters. Lands in the "nextDigits === ''" branch at
OTPFieldInput.tsx:152-172with the slot-revert behavior — currently unverified for the new pipeline. —pr-test-analyzerImportant #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 alongsidesanitizeValue. —pr-test-analyzerImportant #3.
Suggestions
-
S1 — Page prose grammar / clarity.
"...uppercasing alphanumeric codes, which runs aftervalidationTypefiltering"attaches the relative clause to the wrong noun;"UsevalidationType="none"to replace the built-in rule"is cryptic on its own. Bothcode-reviewerandcomment-analyzerflagged this. Suggested rewrite fromcomment-analyzerreads cleanly.docs/src/app/(docs)/react/components/otp-field/page.mdx:111 -
S2 — JSDoc could mention
onValueInvalidinteraction. Characters dropped bysanitizeValuecount as rejected input and triggeronValueInvalid— useful, non-obvious. —comment-analyzer.packages/react/src/otp-field/root/OTPFieldRoot.tsx:517-524 -
S3 — Hidden-input
patternconstraint. Worth one JSDoc line warning that a sanitizer emitting characters outsidevalidationTypewill pass through user-facing state but break native form validation. —code-reviewerSuggestion #4.packages/react/src/otp-field/root/OTPFieldRoot.tsx:447 -
S4 — Dead CSS in updated demo.
.Codeclass inindex.module.csswas 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
onValueInvalidunder composition. Existing paste test only covers built-in regex; mirror the new typing-pathinputChangetest forinputPaste. —pr-test-analyzerNice-to-have #5. -
S6 — Test gap:
replaceOTPValuedouble-application +defaultValue/controlled-value path. Each one-line test, both close real branches in the new pipeline. —pr-test-analyzerNice-to-have #6, #7. -
S7 —
inputModeremoval in demo is not a regression. WithvalidationType="alphanumeric"the defaultinputModeis'text'fromOTP_VALIDATION_CONFIG.alphanumeric.inputMode, so the demo gets the right virtual-keyboard hint for free. (Confirmed bycomment-analyzer.)
Strengths
- Core change in
normalizeOTPValueis minimal, the validation-then-sanitize order is correct for the documented use case, length clamping (incl. multi-byte safety viaArray.from) is preserved verbatim, and whitespace-stripping order is unchanged. - The new
composes built-in validation and custom sanitizationtyping test correctly verifies single-invocationonValueInvalidsemantics 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
normalizeOTPValueitself ("Slice by Unicode code points so multi-byte characters do not split…") is a model for intent-explaining comments.
Recommended Action
- Address C1, C2, C3 first — these need either dev-mode warnings/guards or a docs+behavior change. C3 in particular forces a choice: refactor
replaceOTPValueto callsanitizeValueonce, or commit to the "must be idempotent" contract and surface it loudly. - Fix the
onValueInvalidgating (I1) and the JSDoc reasoning (I2) together — both stem from the same composition model. - Add the four small tests (I4, I5, I6, I7) — each is one-liner-sized and pins down newly-reachable branches.
- Polish docs (S1, S2, S3) and delete the dead CSS (S4).
- Coordinate release notes for the silent semantics flip (I3).
- Re-run
/pr-review-toolkit:review-prafter fixes to verify.
a1f7347 to
43ebb9a
Compare
There was a problem hiding this comment.
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
sanitizeValuewith 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.
d7a1653 to
76c873f
Compare
76c873f to
4721b91
Compare
# Conflicts: # packages/react/src/otp-field/root/OTPFieldRoot.test.tsx
flaviendelangle
left a comment
There was a problem hiding this comment.
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
normalizeValuecallback 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 actionableBase 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:
didRejectCharactersdiscarded byreplaceOTPValueotp.ts:92-110 — both internal flags are thrown away. Callers at OTPFieldInput.tsx:140-153, 288-300 computedidRejectCharactersonly from the raw → first-pass step. If the second pass strips characters (combined string overflow or non-idempotent normalizer rejecting more chars),onValueInvalidwill 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, exportDemoOTPFieldCustomNormalize, MDX heading "Custom normalization", propnormalizeValue) except the directory and the MDX import at page.mdx:118. Usegit mvto preserve rename history. - silent-failure-hunter / comment-analyzer: Length-clamp now triggers
onValueInvalid, undocumented in JSDoc. otp.ts:75 ORs innormalizedCharacters.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 exceedslength". - silent-failure-hunter: No replacement dev warning for new failure modes. The old
sanitizeValue+ non-nonevalidationTypewarning 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.lengthor silently breakdidRejectCharactersbecauseundefined > numberisfalse); (c) the empty-output footgun when normalizer's chars get stripped byvalidationType. - comment-analyzer:
normalizeOTPValueWithDetailsheader otp.ts:47-50 omits the second validation pass — the most subtle, load-bearing part of the pipeline. Same forreplaceOTPValueheader lines 88-91, which understates that the function normalizes twice.
Test Gaps (2 critical, others important)
- pr-test-analyzer: No test asserts
normalizeValueruns on consumer-providedvalue/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" />rendersAB12. 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 secondnormalizeOTPValuecall away (or to a single pass) would silently change semantics the docs now warn about. - pr-test-analyzer: Other untested edges: clamp-only
onValueInvalidfrom over-length paste; expanding normalizer at a non-first slot (replaceOTPValuesuffix 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:
replaceOTPValueUTF-16 slicing at otp.ts:101-102 —prefix/suffix = currentValue.slice(...)uses UTF-16 offsets whileindexis a slot count. Only reachable withvalidationType="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
warnSpyin 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 —
normalizeOTPValueWithDetailstuple cleanly eliminates the priorstripOTPWhitespace(rawValue).length > nextDigits.lengthre-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-errorat 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".
didRejectCharactersaccounting via||=is monotonic OR — verified safe, no branch can clear a priortrue.
Recommended Action
- Critical first: wrap
normalizeValuecalls (especially the render-time one at OTPFieldRoot.tsx:137) and surface aBase UI:error; threaddidRejectCharactersthroughreplaceOTPValueto its callers. - Then important: rename the demo folder (
git mv custom-sanitize custom-normalize+ update page.mdx:118); add length-overflow to theonValueInvalidJSDoc; document the second validation pass innormalizeOTPValueWithDetails/replaceOTPValueheaders. - Add the two critical tests: render-time normalization on
value/defaultValue; non-idempotent normalizer behavior locked in. - Optional: dev warning for non-idempotent / non-string normalizer output to replace the removed
sanitizeValuewarning; drop the noopwarnSpy. - 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).
Closes #4608
normalizeValuecomposes with built-in validation so callers can uppercase alphanumeric recovery codes without opting out ofvalidationType="alphanumeric". OTP Field validates input before and after normalization, then queues focus and updates state with the normalized value.Changes
sanitizeValuetonormalizeValuewhile OTP Field can still take breaking API changes.normalizeValueafter whitespace andvalidationTypefiltering, then applyvalidationTypeagain before clamping.