@eifi1/ui-kit 0.35.0 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -5
- package/dist/admin/role-select.d.ts +3 -2
- package/dist/admin/role-select.js +2 -0
- package/dist/admin/role-select.js.map +1 -1
- package/dist/components/amount-input.d.ts +2 -2
- package/dist/components/amount-input.js.map +1 -1
- package/dist/components/autocomplete.d.ts +2 -2
- package/dist/components/autocomplete.js +2 -1
- package/dist/components/autocomplete.js.map +1 -1
- package/dist/components/button-look.d.ts +1 -1
- package/dist/components/button-look.js +9 -4
- package/dist/components/button-look.js.map +1 -1
- package/dist/components/checkbox-group.d.ts +5 -2
- package/dist/components/checkbox-group.js +15 -4
- package/dist/components/checkbox-group.js.map +1 -1
- package/dist/components/column-mapper.d.ts +5 -3
- package/dist/components/column-mapper.js +2 -0
- package/dist/components/column-mapper.js.map +1 -1
- package/dist/components/combobox.d.ts +2 -2
- package/dist/components/combobox.js +2 -1
- package/dist/components/combobox.js.map +1 -1
- package/dist/components/country-select.d.ts +3 -3
- package/dist/components/country-select.js +3 -0
- package/dist/components/country-select.js.map +1 -1
- package/dist/components/currency-select.d.ts +3 -2
- package/dist/components/currency-select.js +10 -1
- package/dist/components/currency-select.js.map +1 -1
- package/dist/components/date-field.d.ts +2 -1
- package/dist/components/date-field.js.map +1 -1
- package/dist/components/date-picker.js +3 -0
- package/dist/components/date-picker.js.map +1 -1
- package/dist/components/date-range-picker.js +3 -0
- package/dist/components/date-range-picker.js.map +1 -1
- package/dist/components/entity-combobox.d.ts +2 -2
- package/dist/components/entity-combobox.js +2 -1
- package/dist/components/entity-combobox.js.map +1 -1
- package/dist/components/field-parts.d.ts +66 -11
- package/dist/components/field-parts.js +32 -10
- package/dist/components/field-parts.js.map +1 -1
- package/dist/components/field-strip.d.ts +3 -2
- package/dist/components/field-strip.js +2 -1
- package/dist/components/field-strip.js.map +1 -1
- package/dist/components/field.d.ts +3 -2
- package/dist/components/field.js +24 -15
- package/dist/components/field.js.map +1 -1
- package/dist/components/help-popover.d.ts +9 -7
- package/dist/components/help-popover.js.map +1 -1
- package/dist/components/icon-picker.d.ts +3 -2
- package/dist/components/icon-picker.js +3 -0
- package/dist/components/icon-picker.js.map +1 -1
- package/dist/components/inline-entity-combobox.d.ts +2 -2
- package/dist/components/inline-entity-combobox.js +2 -1
- package/dist/components/inline-entity-combobox.js.map +1 -1
- package/dist/components/input.d.ts +2 -2
- package/dist/components/input.js +2 -1
- package/dist/components/input.js.map +1 -1
- package/dist/components/month-picker.d.ts +2 -1
- package/dist/components/month-picker.js +8 -1
- package/dist/components/month-picker.js.map +1 -1
- package/dist/components/multi-entity-combobox.d.ts +2 -2
- package/dist/components/multi-entity-combobox.js +2 -1
- package/dist/components/multi-entity-combobox.js.map +1 -1
- package/dist/components/multi-select.d.ts +2 -2
- package/dist/components/multi-select.js +3 -0
- package/dist/components/multi-select.js.map +1 -1
- package/dist/components/number-input.d.ts +2 -2
- package/dist/components/number-input.js.map +1 -1
- package/dist/components/numeric-field.d.ts +5 -2
- package/dist/components/numeric-field.js +4 -1
- package/dist/components/numeric-field.js.map +1 -1
- package/dist/components/one-time-code-input.d.ts +2 -1
- package/dist/components/one-time-code-input.js +2 -1
- package/dist/components/one-time-code-input.js.map +1 -1
- package/dist/components/phone-input.d.ts +1 -1
- package/dist/components/phone-input.js +4 -0
- package/dist/components/phone-input.js.map +1 -1
- package/dist/components/popover.js +1 -1
- package/dist/components/popover.js.map +1 -1
- package/dist/components/select.d.ts +4 -3
- package/dist/components/select.js +2 -1
- package/dist/components/select.js.map +1 -1
- package/dist/components/slider.d.ts +3 -2
- package/dist/components/slider.js +7 -1
- package/dist/components/slider.js.map +1 -1
- package/dist/components/stat-tile.js +2 -11
- package/dist/components/stat-tile.js.map +1 -1
- package/dist/components/swatch-picker.d.ts +3 -2
- package/dist/components/swatch-picker.js +3 -0
- package/dist/components/swatch-picker.js.map +1 -1
- package/dist/components/text-link.js +3 -1
- package/dist/components/text-link.js.map +1 -1
- package/dist/components/textarea.d.ts +2 -1
- package/dist/components/textarea.js +9 -3
- package/dist/components/textarea.js.map +1 -1
- package/dist/components/toggle-group.d.ts +2 -2
- package/dist/components/toggle-group.js +7 -3
- package/dist/components/toggle-group.js.map +1 -1
- package/dist/eslint/index.js +1 -1
- package/dist/eslint/role-utilities.d.ts +34 -2
- package/dist/eslint/role-utilities.js +30 -9
- package/dist/eslint/role-utilities.js.map +1 -1
- package/dist/i18n/defaults.js +5 -1
- package/dist/i18n/defaults.js.map +1 -1
- package/dist/i18n/german.js +97 -1
- package/dist/i18n/german.js.map +1 -1
- package/dist/i18n/kit-labels.d.ts +16 -0
- package/dist/i18n/kit-labels.js +21 -1
- package/dist/i18n/kit-labels.js.map +1 -1
- package/dist/i18n/locales/en.js +103 -2
- package/dist/i18n/locales/en.js.map +3 -3
- package/dist/i18n/locales/es.js +95 -1
- package/dist/i18n/locales/es.js.map +1 -1
- package/dist/i18n/locales/fr.js +96 -1
- package/dist/i18n/locales/fr.js.map +1 -1
- package/dist/i18n/locales/hu.js +95 -1
- package/dist/i18n/locales/hu.js.map +1 -1
- package/dist/i18n/locales/it.js +96 -1
- package/dist/i18n/locales/it.js.map +1 -1
- package/dist/i18n/locales/zh.js +95 -1
- package/dist/i18n/locales/zh.js.map +1 -1
- package/dist/i18n/review.js +13 -0
- package/dist/i18n/review.js.map +1 -1
- package/dist/i18n/shared-labels.js +3 -1
- package/dist/i18n/shared-labels.js.map +1 -1
- package/dist/index.d.ts +21 -0
- package/dist/index.js +38 -0
- package/dist/index.js.map +1 -1
- package/dist/lib/device-settings.d.ts +72 -0
- package/dist/lib/device-settings.js +64 -0
- package/dist/lib/device-settings.js.map +1 -0
- package/dist/lib/plain-text.d.ts +11 -0
- package/dist/lib/plain-text.js +16 -0
- package/dist/lib/plain-text.js.map +1 -0
- package/dist/lib/safe-storage.d.ts +6 -0
- package/dist/lib/safe-storage.js +11 -0
- package/dist/lib/safe-storage.js.map +1 -1
- package/dist/notifications/notification-parts.d.ts +39 -0
- package/dist/notifications/notification-parts.js +47 -0
- package/dist/notifications/notification-parts.js.map +1 -0
- package/dist/notifications/notification-types-setting.d.ts +62 -0
- package/dist/notifications/notification-types-setting.js +192 -0
- package/dist/notifications/notification-types-setting.js.map +1 -0
- package/dist/notifications/notification-types.d.ts +75 -0
- package/dist/notifications/notification-types.js +2 -0
- package/dist/notifications/notification-types.js.map +1 -0
- package/dist/notifications/notifications-labels.d.ts +131 -0
- package/dist/notifications/notifications-labels.js +83 -0
- package/dist/notifications/notifications-labels.js.map +1 -0
- package/dist/notifications/push-device-setting.d.ts +37 -0
- package/dist/notifications/push-device-setting.js +164 -0
- package/dist/notifications/push-device-setting.js.map +1 -0
- package/dist/notifications/push-devices-setting.d.ts +44 -0
- package/dist/notifications/push-devices-setting.js +203 -0
- package/dist/notifications/push-devices-setting.js.map +1 -0
- package/dist/notifications/quiet-hours-setting.d.ts +47 -0
- package/dist/notifications/quiet-hours-setting.js +131 -0
- package/dist/notifications/quiet-hours-setting.js.map +1 -0
- package/dist/notifications/time-zone-select.d.ts +50 -0
- package/dist/notifications/time-zone-select.js +76 -0
- package/dist/notifications/time-zone-select.js.map +1 -0
- package/dist/notifications/unsubscribe-panel.d.ts +53 -0
- package/dist/notifications/unsubscribe-panel.js +139 -0
- package/dist/notifications/unsubscribe-panel.js.map +1 -0
- package/dist/notifications/use-push-device.d.ts +122 -0
- package/dist/notifications/use-push-device.js +230 -0
- package/dist/notifications/use-push-device.js.map +1 -0
- package/dist/rhf/fields.d.ts +26 -19
- package/dist/rhf/fields.js +51 -22
- package/dist/rhf/fields.js.map +1 -1
- package/dist/settings/device-reset-setting-labels.d.ts +3 -0
- package/dist/settings/device-reset-setting-labels.js +15 -0
- package/dist/settings/device-reset-setting-labels.js.map +1 -0
- package/dist/settings/device-reset-setting.d.ts +58 -0
- package/dist/settings/device-reset-setting.js +51 -0
- package/dist/settings/device-reset-setting.js.map +1 -0
- package/dist/shell/app-shell.js +5 -0
- package/dist/shell/app-shell.js.map +1 -1
- package/dist/theme/contrast-tokens.d.ts +42 -4
- package/dist/theme/contrast-tokens.js +56 -9
- package/dist/theme/contrast-tokens.js.map +1 -1
- package/dist/theme/contrast.d.ts +4 -2
- package/dist/theme/contrast.js +13 -0
- package/dist/theme/contrast.js.map +1 -1
- package/dist/theme/palette-derive.d.ts +15 -1
- package/dist/theme/palette-derive.js +37 -8
- package/dist/theme/palette-derive.js.map +1 -1
- package/dist/theme/palette-presets.d.ts +2 -1
- package/dist/theme/palette-presets.js +5 -5
- package/dist/theme/palette-presets.js.map +1 -1
- package/dist/theme/palette-store.js +6 -0
- package/dist/theme/palette-store.js.map +1 -1
- package/dist/theme/text-size.js +6 -0
- package/dist/theme/text-size.js.map +1 -1
- package/dist/theme/theme-store.js +6 -0
- package/dist/theme/theme-store.js.map +1 -1
- package/package.json +1 -1
- package/src/admin/role-select.tsx +4 -1
- package/src/components/amount-input.tsx +2 -1
- package/src/components/autocomplete.tsx +5 -2
- package/src/components/button-look.ts +15 -5
- package/src/components/checkbox-group.tsx +22 -4
- package/src/components/column-mapper.tsx +6 -2
- package/src/components/combobox.tsx +5 -2
- package/src/components/country-select.tsx +6 -1
- package/src/components/currency-select.tsx +12 -3
- package/src/components/date-field.tsx +2 -2
- package/src/components/date-picker.tsx +3 -0
- package/src/components/date-range-picker.tsx +3 -0
- package/src/components/entity-combobox.tsx +5 -2
- package/src/components/field-parts.tsx +107 -19
- package/src/components/field-strip.tsx +4 -3
- package/src/components/field.tsx +28 -15
- package/src/components/help-popover.tsx +9 -7
- package/src/components/icon-picker.tsx +8 -3
- package/src/components/inline-entity-combobox.tsx +5 -2
- package/src/components/input.tsx +4 -2
- package/src/components/month-picker.tsx +10 -3
- package/src/components/multi-entity-combobox.tsx +5 -2
- package/src/components/multi-select.tsx +6 -1
- package/src/components/number-input.tsx +2 -2
- package/src/components/numeric-field.ts +10 -2
- package/src/components/one-time-code-input.tsx +5 -3
- package/src/components/phone-input.tsx +4 -0
- package/src/components/popover.tsx +3 -1
- package/src/components/select.tsx +6 -3
- package/src/components/slider.tsx +10 -3
- package/src/components/stat-tile.tsx +3 -18
- package/src/components/swatch-picker.tsx +9 -4
- package/src/components/text-link.tsx +3 -1
- package/src/components/textarea.tsx +11 -4
- package/src/components/toggle-group.tsx +21 -5
- package/src/eslint/role-utilities.ts +67 -11
- package/src/i18n/defaults.ts +4 -0
- package/src/i18n/german.ts +113 -0
- package/src/i18n/kit-labels.tsx +52 -1
- package/src/i18n/locales/en.ts +6 -0
- package/src/i18n/locales/es.ts +106 -0
- package/src/i18n/locales/fr.ts +106 -0
- package/src/i18n/locales/hu.ts +104 -0
- package/src/i18n/locales/it.ts +105 -0
- package/src/i18n/locales/zh.ts +96 -0
- package/src/i18n/review.ts +13 -0
- package/src/i18n/shared-labels.ts +2 -0
- package/src/index.ts +50 -0
- package/src/lib/device-settings.ts +146 -0
- package/src/lib/plain-text.ts +22 -0
- package/src/lib/safe-storage.ts +16 -0
- package/src/notifications/notification-parts.tsx +83 -0
- package/src/notifications/notification-types-setting.tsx +309 -0
- package/src/notifications/notification-types.ts +80 -0
- package/src/notifications/notifications-labels.ts +238 -0
- package/src/notifications/push-device-setting.tsx +224 -0
- package/src/notifications/push-devices-setting.tsx +306 -0
- package/src/notifications/quiet-hours-setting.tsx +185 -0
- package/src/notifications/time-zone-select.tsx +126 -0
- package/src/notifications/unsubscribe-panel.tsx +203 -0
- package/src/notifications/use-push-device.ts +392 -0
- package/src/rhf/fields.tsx +77 -29
- package/src/settings/device-reset-setting-labels.ts +20 -0
- package/src/settings/device-reset-setting.tsx +119 -0
- package/src/shell/app-shell.tsx +8 -0
- package/src/theme/contrast-tokens.ts +106 -12
- package/src/theme/contrast.ts +30 -4
- package/src/theme/palette-derive.ts +68 -7
- package/src/theme/palette-presets.ts +9 -6
- package/src/theme/palette-store.ts +12 -0
- package/src/theme/text-size.ts +8 -0
- package/src/theme/theme-store.ts +10 -0
- package/tokens.css +38 -4
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import type { ReactNode, Ref } from "react";
|
|
2
2
|
import { type CalculatorButtonLabels } from "./calculator.js";
|
|
3
3
|
import { type NumberPadSheetLabels } from "./numpad-sheet.js";
|
|
4
|
-
import { type DisabledReasonDisplay } from "./field-parts.js";
|
|
4
|
+
import { type DisabledReasonDisplay, type FieldHelpProps } from "./field-parts.js";
|
|
5
5
|
import type { CommitScope } from "./write-lock.js";
|
|
6
6
|
/** {@link NumberInput}'s props — exported since 0.34 (refactor audit 2026-10, API-9): a
|
|
7
7
|
* wrapper typed itself off `ComponentProps<typeof NumberInput>` until then. */
|
|
8
|
-
export interface NumberInputProps {
|
|
8
|
+
export interface NumberInputProps extends FieldHelpProps {
|
|
9
9
|
/** The text, DOT-decimal ("1234.5", or a calculation being typed: "12+5"), as
|
|
10
10
|
* `onChange` reports it — so a caller's `Number(value)` reads it. The field SHOWS it
|
|
11
11
|
* in the locale's mark (see `locale`). A comma here is read as the decimal mark too,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/number-input.tsx"],"sourcesContent":["import { useEffect, useId, useMemo, useRef } from \"react\";\nimport type { KeyboardEvent, ReactNode, Ref } from \"react\";\nimport { CalculatorButton, type CalculatorButtonLabels } from \"./calculator\";\nimport { NumberPadSheet, type NumberPadSheetLabels } from \"./numpad-sheet\";\nimport {\n FIELD_BASE,\n FIELD_DISPLAY,\n FIELD_INVALID,\n FLOATING_INPUT_CLASS,\n FloatingField,\n} from \"./field-base\";\n// The data alone (0.35): not the picker, which this field does not render.\nimport { CURRENCIES } from \"../currencies\";\nimport { FieldCaption, LockedReason, mergeRefs, type DisabledReasonDisplay } from \"./field-parts\";\nimport { useEndWidth, useNumericField } from \"./numeric-field\";\nimport type { CommitScope } from \"./write-lock\";\nimport { cn } from \"../lib/cn\";\nimport { commitExpression, formatResult } from \"../lib/calc\";\n\n/** {@link NumberInput}'s props — exported since 0.34 (refactor audit 2026-10, API-9): a\n * wrapper typed itself off `ComponentProps<typeof NumberInput>` until then. */\nexport interface NumberInputProps {\n /** The text, DOT-decimal (\"1234.5\", or a calculation being typed: \"12+5\"), as\n * `onChange` reports it — so a caller's `Number(value)` reads it. The field SHOWS it\n * in the locale's mark (see `locale`). A comma here is read as the decimal mark too,\n * never as grouping. */\n value: string;\n /** Fired on every keystroke with the text as a number reads it: grouping marks read\n * off (\"1.234,56\" → \"1234.56\" for a German typist, keksdose K5), the decimal mark\n * folded to a dot, operators kept so a typed expression survives. */\n onChange: (value: string) => void;\n /** Fired on blur/Enter with the *evaluated* value — use this for save-on-blur\n * fields so the save always sees the resolved number, never \"10+5\". */\n onCommit?: (value: string) => void;\n label?: ReactNode;\n /** Names the field when it has no visible `label` (a table cell, a phone's display\n * shape). */\n \"aria-label\"?: string;\n /** Names for the calculator this field renders — its trigger, and the controls\n * inside the popover — and for the numpad sheet it opens on a phone. Overrides\n * for THIS field only: both resolve the `calculator` namespace of\n * `<UiKitProvider labels>` themselves, then fall back to English.\n *\n * `pad` is not optional plumbing: this field renders a {@link NumberPadSheet}\n * exactly as {@link AmountInput} does, but had no way to pass it anything, so\n * the SAME keypad announced itself in German when a money field opened it and in\n * English when a goal target did. */\n labels?: {\n calculatorTrigger?: string;\n calculator?: CalculatorButtonLabels;\n pad?: NumberPadSheetLabels;\n };\n placeholder?: string;\n disabled?: boolean;\n autoFocus?: boolean;\n /** Wrapper class. */\n className?: string;\n /** Overrides the input's own styling (merged after the field base). */\n inputClassName?: string;\n id?: string;\n /** Show the calculator-popover trigger (default true). Set false for fields in\n * an ephemeral close-on-blur editor, where clicking the icon would blur away\n * and tear the editor down before the popover could open — inline typing\n * (e.g. \"200+50\" → Enter) still evaluates there. */\n calculator?: boolean;\n /** {@link FIELD_DISPLAY} — on a phone, the figure at display size with the field\n * chrome dropped. The currency-free half of the same treatment `AmountInput`\n * carries, for a dialog whose whole point is the one number (a budget goal's\n * target); not for a field among many, and never for the compact inline\n * editors this control also serves. */\n variant?: \"field\" | \"display\";\n /** A {@link FieldHint} \"?\" on the label's own line, beside the label rather\n * than at the far end of the strip — the far end is where the calculator\n * lives, and a hint placed there landed on top of it (steering-design\n * feedback #48). Plain TEXT (a string or a number) is a caption instead, UNDER\n * the field and attached through `aria-describedby` after the caller's own —\n * the same rule as {@link Select}'s `hint`: the label line has no room for a\n * sentence, and one placed there ran over the label and into the value.\n * Since 0.32 a FieldHint is that caption too at Large and on a touch screen,\n * where a \"?\" cannot be hovered open (`useInlineHint`). */\n hint?: ReactNode;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\n /**\n * What is wrong with the value, in the caller's own words — {@link Input}'s `error`,\n * the same anatomy (keksdose K5/K4: of the kit's fields only `Input` and\n * `NumberField` had one, so a goal target or a rate field wrote its message as a\n * loose `<p>` that nothing pointed at). Rendered under the field, after a text\n * `hint`; merged into `aria-describedby` after the caller's ids and the hint's; and\n * it implies `invalid`, so the field paints as well as announces. `null`, `false`\n * and `\"\"` — a `touched && errors.x` on the happy path — are no message.\n *\n * Passing the key at all (even `undefined`) keeps the field in a steady wrapper,\n * message or not, so the message coming and going never remounts the `<input>` and\n * takes the caret with it — see `Input`'s `FieldGroup`. A field that never passes\n * `error` renders exactly the DOM it did before the prop existed.\n */\n error?: ReactNode;\n /**\n * BCP 47 tag that decides the decimal mark the field SHOWS; default the\n * `<UiKitProvider locale>`, else the runtime's (keksdose K5). A French or Italian\n * reader sees \"3,5\", a German one too, de-CH and en-US see \"3.5\" — `Intl`\n * decides, not a guess about a country. Display only: `value` and `onChange` stay\n * dot-decimal. {@link NumberField} passes its own `locale` through here.\n */\n locale?: string;\n /**\n * Set on the `<input>`, with `id` above. Declared so `Field`'s render-prop spread —\n * `{(ids) => <NumberInput {...ids} … />}` — is typed and reaches the input: the hint\n * and error are described, a required number is announced as required, and\n * `aria-invalid` paints {@link FIELD_INVALID} the way `invalid` does.\n */\n \"aria-describedby\"?: string;\n \"aria-invalid\"?: boolean | \"true\" | \"false\";\n \"aria-required\"?: boolean | \"true\" | \"false\";\n /**\n * A static unit shown at the field's right edge — \"%\", \"kg\", \"km/h\".\n *\n * The read-out half of {@link AmountInput}'s currency chip, and it exists for the\n * same reason that one does: a unit belongs to the FIELD, not to the text, so\n * typing it is a way to get it into the value. Keksdose had a percentage spelled\n * three different ways across three screens — `<Input type=\"number\" step=\"0.01\">`\n * for a loan rate, `step=\"0.1\"` for a tax rate, `inputMode=\"decimal\"` for a VAT\n * rate — and none of the three showed a \"%\" anywhere near the box, so what the\n * digits meant was a question the label alone had to answer.\n *\n * `aria-hidden`, like the currency read-out: it is a property of the field that\n * the label already names (\"Interest rate (%)\"), and announcing it again after\n * every value reads as part of the number.\n */\n suffix?: ReactNode;\n /**\n * Turns on the step keys: ArrowUp / ArrowDown add or subtract `step`, PageUp /\n * PageDown ten of them. The result lands on the grid `min + k × step` (or `0 + k ×\n * step` without a `min`), so 3.1 with `step={0.25}` goes up to 3.25, not 3.35 —\n * what a native number input does. Decimal-exact: `0.1 + 0.2` steps to \"0.3\".\n *\n * A step changes the text through `onChange` like a keystroke would; `onCommit`\n * still fires on blur/Enter. Without `step` the arrow keys move the caret as before.\n */\n step?: number;\n /** Bounds for the step keys only — a step never leaves `[min, max]`. This field's\n * value is a STRING, so typed text is not clamped: {@link NumberField} is the\n * numeric field that clamps what is typed as well. */\n min?: number;\n max?: number;\n /**\n * Why the value cannot be changed — {@link Button}'s `disabledReason`, for a number\n * that SAVES itself: a setting committed on blur, a figure in a row editor\n * (Kurvenschmiede's session page, 0.33.1). `disabled` takes the field out of the tab\n * order, so the reason never reached a keyboard, and Kurvenschmiede wrote its own\n * `CommitInput` to keep it in.\n *\n * With a reason the field stays in the tab order and shows its value, `readOnly` (the\n * settled grey FIELD_BASE gives a `[readonly]` field) and `aria-disabled`, as the\n * Combobox family's lock is. Nothing changes the value: the step keys do nothing, the\n * calculator and the phone's numpad are not offered, and neither blur nor Enter\n * commits — so `onChange` and `onCommit` are never called. Enter is swallowed, so the\n * field does not submit the form around it. The reason is a line under the field at\n * Large and on a touch screen, else in the kit {@link Tooltip} (`disabledReasonDisplay`),\n * and on the input's `aria-describedby`, between the caption and the error. Wins over\n * `disabled`.\n */\n disabledReason?: ReactNode;\n /**\n * Where the reason shows — {@link Button}'s `disabledReasonDisplay`: by default a line\n * under the field at Large and on a touch screen, the tooltip otherwise (§4 \"No fact\n * only in a tooltip\"; DUP-3, refactor audit 2026-10).\n */\n disabledReasonDisplay?: DisabledReasonDisplay;\n /**\n * This field COMMITS — {@link Button}'s `commit`: under a locked\n * {@link WriteLockProvider} it is locked the `disabledReason` way with the lock's reason\n * (which wins over its own). A field whose value only reaches the server through the\n * form's Save leaves this off and stays editable under the lock; the Save takes\n * `commit`. No provider, or an unlocked one: no effect. {@link NumberField} and\n * {@link IntegerField} pass it on.\n */\n commit?: CommitScope;\n /**\n * The `<input>`, as a React 19 ref prop (0.34, API-3, refactor audit 2026-10): the one\n * focusable field of its family with no ref at all, so react-hook-form's focus-on-error\n * could reach it only through /rhf's id lookup, and an app not at all.\n * {@link NumberField} and {@link IntegerField} pass it on.\n */\n ref?: Ref<HTMLInputElement>;\n}\n\n/** Decimal places of `n` as written (\"0.25\" → 2, \"1e-7\" → 7), for decimal-exact\n * stepping. */\nfunction decimalsOf(n: number): number {\n const text = formatResult(n);\n const dot = text.indexOf(\".\");\n return dot === -1 ? 0 : text.length - dot - 1;\n}\n\n/**\n * `current` moved by `count` steps (negative = down), on the grid `origin + k × step`\n * and clamped into `[min, max]`. An off-grid value moves to the NEXT grid point in\n * that direction first, so one press is never more than one step.\n *\n * The grid index is found by division and the result rebuilt as `origin + k × step`,\n * then cut to the decimals `step` and `origin` are written with — which is where\n * binary noise goes: `0.1 × 3` is 0.30000000000000004, and `toFixed(1)` of it is\n * \"0.3\". Summing steps would accumulate that noise press by press instead.\n */\nexport function stepNumber(\n current: number | null,\n count: number,\n step: number,\n min?: number,\n max?: number,\n): number {\n const clamp = (n: number) => Math.min(max ?? Infinity, Math.max(min ?? -Infinity, n));\n // Nothing to step from: land on the value nearest zero the bounds allow, rather\n // than on ±step — a room count with `min={1}` goes to 1, a rate to 0.\n if (current === null || !Number.isFinite(current)) return clamp(0);\n const origin = min !== undefined && Number.isFinite(min) ? min : 0;\n const raw = (current - origin) / step;\n const nearest = Math.round(raw);\n // \"On the grid\" within float tolerance: (0.3 - 0) / 0.1 is 2.9999999999999996.\n const onGrid = Math.abs(raw - nearest) < 1e-9;\n const k = onGrid\n ? nearest + count\n : count > 0\n ? Math.ceil(raw) + count - 1\n : Math.floor(raw) + count + 1;\n const places = Math.min(Math.max(decimalsOf(step), decimalsOf(origin)), 20);\n return clamp(Number((origin + k * step).toFixed(places)));\n}\n\n/** NumberInput never rounds: what was typed (or calculated) is what it reports. */\nconst asTyped = (text: string) => text;\n\n// ── The money guard (kastlan 5, Kurvenschmiede) ─────────────────────────────────\n\n// The codes the kit's own currency pickers offer, as whole words: \"Amount (CHF)\",\n// \"EUR\", \"Kosten CHF\". Not every ISO 4217 code — \"ALL\", \"TOP\" and \"PEN\" are codes too,\n// and an upper-case label would trip on them.\nconst CURRENCY_CODE = new RegExp(`(?:^|[^A-Za-z])(?:${CURRENCIES.map((c) => c.code).join(\"|\")})(?![A-Za-z])`);\n// Symbols no unit of measure is written with. Not \"kr\", \"R\" or \"Fr\": those are words\n// and units as often as they are money.\nconst CURRENCY_SYMBOL = /[€$£¥₹₺₽₪₩₫฿₴₦₱]/;\n\n/** Text that names a currency and no unit to go with it. A slash makes it a rate or\n * a unit price (\"CHF/m²\", \"€/kWh\") — a figure whose decimals are its column's\n * business, not the currency's — and that is not what the guard is for. */\nfunction namesMoney(node: ReactNode): boolean {\n if (typeof node !== \"string\" && typeof node !== \"number\") return false;\n const text = String(node);\n return (CURRENCY_CODE.test(text) || CURRENCY_SYMBOL.test(text)) && !text.includes(\"/\") && !text.includes(\"%\");\n}\n\n/**\n * Is this field being used for MONEY? A currency in the unit (`suffix=\"CHF\"`), or in\n * the label, `aria-label` or placeholder of a field with no unit at all (\"Estimated\n * cost (CHF)\"). Any other suffix is a unit — \"%\", \"mm\", \"N·m\" — and says what the\n * digits are, whatever the label says. `digits` plays no part: NumberInput has none,\n * and Kurvenschmiede's engineering fields at 2 and 3 decimals are exactly what this\n * must stay quiet about.\n */\nfunction looksLikeMoney(suffix: ReactNode, texts: ReactNode[]): boolean {\n if (suffix !== undefined && suffix !== null && suffix !== \"\") return namesMoney(suffix);\n return texts.some(namesMoney);\n}\n\n/**\n * The kit's dev switch, as `lib/logger.ts` reads it: a development build, never a\n * production one — the consumer's bundler replaces `import.meta.env.DEV` with `false`\n * there, and this branch is dead code — and never under vitest, where every consumer\n * suite would print it once per render of every field it has not migrated yet. Read\n * per call rather than once per module, so a test can switch it on with `vi.stubEnv`.\n * Optional-chained: `import.meta.env` is a Vite injection, absent under plain Node.\n */\nfunction devWarnings(): boolean {\n return Boolean(import.meta.env?.DEV) && !import.meta.env?.VITEST;\n}\n\n/**\n * A numeric text field with a built-in calculator: type a calculation straight\n * in (e.g. \"12+5\", evaluated on blur/Enter) or click the trailing calculator\n * icon for a keypad. String `value`/`onChange` contract, mirroring\n * {@link AmountInput} — the currency-free counterpart for quantities, rates,\n * percentages and measurements.\n *\n * NOT FOR MONEY. This field never rounds: \"12.345\", or a calculator's \"100/3\", is\n * reported exactly as typed. kastlan's journal lines, a payment allocation and a\n * defect's estimated cost were NumberInputs, and a 3-decimal amount reached a\n * 2-decimal Money column and failed the save with a 422 — in one wizard after the\n * record before it had already been created (kastlan 5). Money goes in\n * {@link AmountInput} (string value, like this one) or {@link MoneyField} (number\n * value): both settle to the currency's minor unit on blur, Enter and every calculator\n * result, and take `digits` for a unit price at a finer scale. In development a\n * NumberInput that looks like money — a currency as its unit, or a currency in the\n * label of a field with no unit — says so on the console, once per field. A unit of\n * measure (\"mm\", \"N·m\", \"%\") keeps it quiet, as does any number of decimals.\n *\n * THE LOCALE'S MARK (keksdose K5). The field shows the `locale`'s decimal mark — \"3,5\"\n * to a French, Italian or German reader — and reads what is typed the way\n * {@link AmountInput} does (keksdose G1): \"1.234,56\" from a German typist is 1234.56,\n * \"1,234.56\" from an English one too, and a lone mark that cannot be grouping is the\n * decimal, whichever key typed it. Before, it always showed \"3.5\" and folded\n * \"1.234,56\" into 1.23456. `value` and `onChange` stay dot-decimal, which is the\n * contract every caller's `Number(value)` reads.\n *\n * While a figure is being typed the field shows the typist's OWN text — \"1.234,5\"\n * stays exactly that — rather than the value re-spelt: re-spelling turned a grouping\n * \".\" into a \",\" under their fingers, after which no rule could tell the two apart, and\n * a text that changes length under the caret moves it to the end. It is re-spelt in the\n * locale's mark, without grouping, once the figure settles (blur, Enter, a step or a\n * calculator result) or when the value changes from outside.\n */\nexport function NumberInput(props: NumberInputProps) {\n const {\n ref,\n value,\n onChange,\n onCommit,\n label,\n \"aria-label\": ariaLabel,\n labels,\n placeholder,\n autoFocus,\n className,\n inputClassName,\n id,\n \"aria-required\": ariaRequired,\n suffix,\n step,\n min,\n max,\n disabledReasonDisplay,\n } = props;\n const generatedId = useId();\n const fieldId = id ?? generatedId;\n // The engine AmountInput shares (DUP-10): the lock (focusable, `readOnly`, nothing\n // changes or commits — see `disabledReason`), the hint — a FieldHint is its words at\n // Large and on touch, §4 — the error, the description's order, the typist's draft and\n // the locale's mark (see the component's note), the calculator and the numpad.\n // NumberInput never rounds; it shows the value as it is.\n const numeric = useNumericField(props, { settle: asTyped, display: () => value });\n const { lock, locked, off, isMobile, asDisplay, showCalc, showNumpad, setFocused, mark, setDraft, derived } = numeric;\n const invalid = numeric.isInvalid;\n // Passed at all — even as `undefined` — the field keeps its box; see `error`.\n const reserve = \"error\" in props || \"hint\" in props;\n const labelled = label !== undefined;\n // The unit and the calculator's measured width, reserved as the field's end padding.\n const hasEnd = showCalc || suffix !== undefined;\n const [endRef, endWidth] = useEndWidth(hasEnd);\n // Before the first measurement (and wherever there is no layout), a TEXT unit\n // reserves an estimate from its length — one `ch` a character, in the input's own\n // (larger) font, so it errs wide — plus the span's `pe-2` and the 4px gap, and the\n // calculator's 36px. The class fallback's flat pe-8 gave a \"%\" 32px for a frame and\n // \"km/h\" too little.\n const suffixChars = typeof suffix === \"string\" || typeof suffix === \"number\" ? String(suffix).length : null;\n const estimatedEnd =\n suffixChars !== null ? `calc(${suffixChars}ch + 0.75rem${showCalc ? \" + 2.25rem\" : \"\"})` : undefined;\n // On mobile, focusing opens the numpad bottom sheet instead of the native\n // keyboard (#334); the ref lets its \"Done\" blur → commit + close. The caller's `ref`\n // gets the same element.\n const inputRef = useRef<HTMLInputElement>(null);\n const setInput = useMemo(() => mergeRefs(inputRef, ref), [ref]);\n\n // `derived` is the value in the locale's mark — one character for one, no grouping —\n // and the draft the typist's own text, shown only while it still says what the value\n // says (see `showsTyped`).\n const display = numeric.typedFor(value) ?? derived;\n\n // A keystroke, a paste or a numpad key: the typist's text is kept, the value is what\n // a number reads it as.\n const typed = (raw: string) => onChange(numeric.read(raw));\n // A RESULT — the calculator's, the numpad's \"=\" — is dot-decimal already. It does not\n // go through `typed`: \"1.234\" out of `100/81.03…` is never a thousand.\n const result = (next: string) => {\n setDraft(null);\n onChange(next);\n };\n\n // The money guard: once per field, development only. See `looksLikeMoney`.\n const warnedMoney = useRef(false);\n useEffect(() => {\n if (warnedMoney.current || !devWarnings()) return;\n if (!looksLikeMoney(suffix, [label, ariaLabel, placeholder])) return;\n warnedMoney.current = true;\n const name = [label, ariaLabel, suffix].find((t) => typeof t === \"string\" || typeof t === \"number\");\n console.warn(\n `[ui-kit] NumberInput${name === undefined ? \"\" : ` \"${String(name)}\"`} looks like a money field: a ` +\n `currency, and no unit. NumberInput never rounds, so \"12.345\" or a calculator's \"100/3\" is sent with ` +\n `three or more decimals (kastlan 5: a 422 from a 2-decimal Money column). Use AmountInput (string ` +\n `value) or MoneyField (number value) — both settle to the currency's minor unit. ` +\n `(Development builds only; once per field.)`,\n );\n }, [suffix, label, ariaLabel, placeholder]);\n\n const commit = () => {\n setDraft(null);\n const next = numeric.settle(commitExpression(value));\n if (next !== value) onChange(next);\n onCommit?.(next);\n };\n\n const stepBy = (count: number) => {\n setDraft(null);\n // The step starts from the text as a commit would read it, so \"12+5\" steps from 17.\n const resolved = commitExpression(value).trim();\n const n = resolved === \"\" ? NaN : Number(resolved);\n const next = formatResult(stepNumber(Number.isFinite(n) ? n : null, count, step as number, min, max));\n if (next !== value) onChange(next);\n };\n\n const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n // Locked: Enter submits no form and commits nothing, and no key steps the value.\n // The arrows and Home/End stay the caret's, for a long value someone is reading.\n if (locked) {\n if (e.key === \"Enter\") e.preventDefault();\n return;\n }\n if (e.key === \"Enter\") return commit();\n // A zero, negative or non-finite step is no step: the keys stay the caret's.\n if (!step || !(step > 0) || !Number.isFinite(step) || e.altKey || e.ctrlKey || e.metaKey) return;\n const count =\n e.key === \"ArrowUp\" ? 1 : e.key === \"ArrowDown\" ? -1 : e.key === \"PageUp\" ? 10 : e.key === \"PageDown\" ? -10 : 0;\n if (count === 0) return;\n // Otherwise ArrowUp/Down also jump the caret to the start/end of the text.\n e.preventDefault();\n stepBy(count);\n };\n\n // While locked the field sits in the reason's frame (line or Tooltip), its outermost\n // box — so `className` (a width, a flex or grid cell) moves onto that, and the form\n // keeps its layout, as on Select.\n const field = (\n <FloatingField\n className={cn(\"w-full\", !locked && className)}\n htmlFor={fieldId}\n label={label}\n srOnlyLabel={asDisplay}\n hint={numeric.hint.labelHint}\n >\n <input\n ref={setInput}\n id={fieldId}\n aria-label={ariaLabel}\n type=\"text\"\n // Mobile: suppress the OS keyboard so the numpad sheet owns entry (field\n // keeps focus/caret); desktop keeps the native decimal keypad.\n inputMode={isMobile ? \"none\" : \"decimal\"}\n autoComplete=\"off\"\n // eslint-disable-next-line jsx-a11y/no-autofocus -- a documented prop the caller opts into (off by default); the field never takes focus on its own.\n autoFocus={autoFocus}\n disabled={off}\n // Locked: focusable, `readOnly`, `aria-disabled` — see `disabledReason`.\n readOnly={locked || undefined}\n aria-disabled={locked || undefined}\n // Display mode has no floating label to feed the blank-placeholder trick,\n // and an empty borderless figure shows nothing — so it keeps whatever\n // placeholder the caller gave, falling back to a zero to aim at.\n placeholder={asDisplay ? (placeholder ?? \"0\") : labelled ? \" \" : placeholder}\n value={display}\n onChange={(e) => {\n if (!locked) typed(e.target.value);\n }}\n onFocus={() => setFocused(true)}\n onBlur={() => {\n // Nothing commits under the lock — not even a draft typed before it arrived,\n // which stays in the field for when it lifts.\n if (!locked) commit();\n setFocused(false);\n }}\n onKeyDown={onKeyDown}\n aria-invalid={invalid || undefined}\n aria-describedby={numeric.describedBy}\n aria-required={ariaRequired}\n // The end padding sits last so it always wins over an inputClassName that\n // sets its own px. Both trailing controls can be on at once, so the room\n // they need is reserved together rather than by whichever happens to render:\n // the calculator is ~36px and a short unit ~24px, and a field that reserved\n // only one of them would let the digits run under the other.\n className={cn(\n asDisplay\n ? cn(FIELD_DISPLAY, \"text-4xl font-semibold leading-tight tracking-tight tabular-nums\")\n : labelled\n ? FLOATING_INPUT_CLASS\n : FIELD_BASE,\n inputClassName,\n showCalc && suffix !== undefined ? \"pe-16\" : showCalc ? \"pe-9\" : suffix !== undefined ? \"pe-8\" : undefined,\n invalid && FIELD_INVALID,\n locked && \"cursor-not-allowed\",\n )}\n // The classes above are the fallback; once the end controls are measured the\n // field reserves exactly their width (+4px). A fixed pe-8 for any unit left a\n // \"%\" in a ~78px table cell 32px of padding and the digits ~32px of room\n // (keksdose live #367); a long unit (\"km/h\") got too little.\n style={\n hasEnd && endWidth != null\n ? { paddingInlineEnd: endWidth + 4 }\n : estimatedEnd !== undefined\n ? { paddingInlineEnd: estimatedEnd }\n : undefined\n }\n />\n {hasEnd && (\n // One flex track for both, so the unit and the calculator sit side by side\n // instead of stacking on the same corner — AmountInput's arrangement, which\n // has carried a chip and a calculator together since #430.\n <div ref={endRef} className=\"absolute inset-y-0 end-0 flex items-center\">\n {showCalc && (\n <CalculatorButton\n // Seeded with the value in the field's mark but WITHOUT the typist's\n // grouping: the evaluator reads either mark, but \"1.234,5\" is two of them.\n value={derived}\n onChange={result}\n className=\"self-stretch px-2.5\"\n aria-label={labels?.calculatorTrigger}\n labels={labels?.calculator}\n />\n )}\n {suffix !== undefined && (\n <span\n aria-hidden\n // pe-2, not the input's px-3: the unit is chrome at the box's edge, and\n // with pe-3 plus the 4px gap it took ~26px of a narrow table cell.\n className=\"pointer-events-none pe-2 text-xs font-medium text-muted\"\n >\n {suffix}\n </span>\n )}\n </div>\n )}\n {showNumpad && (\n <NumberPadSheet\n // Localised like the field it mirrors, as AmountInput's is: its keys are\n // typing, read by the locale's marks like the keyboard's; \"=\" is a result.\n value={display}\n onChange={typed}\n onResult={result}\n onDone={() => inputRef.current?.blur()}\n label={label}\n labels={labels?.pad}\n decimalMark={mark}\n />\n )}\n </FloatingField>\n );\n const box = locked ? (\n <LockedReason lock={lock} display={disabledReasonDisplay} className={cn(\"block w-full\", className)}>\n {field}\n </LockedReason>\n ) : (\n field\n );\n if (numeric.hint.captionText === undefined && numeric.errorEl === null && !reserve) return box;\n // Outside the field's own `relative` box, as Select's caption is: the calculator\n // and the unit are `inset-y-0` in it and would stretch down over a second line.\n // `className` stays on the field, so adding a caption cannot change what it styles.\n return (\n <div>\n {box}\n <FieldCaption parts={numeric.hint} />\n {numeric.errorEl}\n </div>\n );\n}\n"],"mappings":";AAubM,cAkEE,YAlEF;AAvbN,SAAS,WAAW,OAAO,SAAS,cAAc;AAElD,SAAS,wBAAqD;AAC9D,SAAS,sBAAiD;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,kBAAkB;AAC3B,SAAS,cAAc,cAAc,iBAA6C;AAClF,SAAS,aAAa,uBAAuB;AAE7C,SAAS,UAAU;AACnB,SAAS,kBAAkB,oBAAoB;AA6K/C,SAAS,WAAW,GAAmB;AACrC,QAAM,OAAO,aAAa,CAAC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AA;AAAA,QAIC,qBAAC,SAAI,KAAK,QAAQ,WAAU,8CACzB;AAAA,sBACC;AAAA,YAAC;AAAA;AAAA,cAGC,OAAO;AAAA,cACP,UAAU;AAAA,cACV,WAAU;AAAA,cACV,cAAY,QAAQ;AAAA,cACpB,QAAQ,QAAQ;AAAA;AAAA,UAClB;AAAA,UAED,WAAW,UACV;AAAA,YAAC;AAAA;AAAA,cACC,eAAW;AAAA,cAGX,WAAU;AAAA,cAET;AAAA;AAAA,UACH;AAAA,WAEJ;AAAA,QAED,cACC;AAAA,UAAC;AAAA;AAAA,YAGC,OAAO;AAAA,YACP,UAAU;AAAA,YACV,UAAU;AAAA,YACV,QAAQ,MAAM,SAAS,SAAS,KAAK;AAAA,YACrC;AAAA,YACA,QAAQ,QAAQ;AAAA,YAChB,aAAa;AAAA;AAAA,QACf;AAAA;AAAA;AAAA,EAEJ;AAEF,QAAM,MAAM,SACV,oBAAC,gBAAa,MAAY,SAAS,uBAAuB,WAAW,GAAG,gBAAgB,SAAS,GAC9F,iBACH,IAEA;AAEF,MAAI,QAAQ,KAAK,gBAAgB,UAAa,QAAQ,YAAY,QAAQ,CAAC,QAAS,QAAO;AAI3F,SACE,qBAAC,SACE;AAAA;AAAA,IACD,oBAAC,gBAAa,OAAO,QAAQ,MAAM;AAAA,IAClC,QAAQ;AAAA,KACX;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/number-input.tsx"],"sourcesContent":["import { useEffect, useId, useMemo, useRef } from \"react\";\nimport type { KeyboardEvent, ReactNode, Ref } from \"react\";\nimport { CalculatorButton, type CalculatorButtonLabels } from \"./calculator\";\nimport { NumberPadSheet, type NumberPadSheetLabels } from \"./numpad-sheet\";\nimport {\n FIELD_BASE,\n FIELD_DISPLAY,\n FIELD_INVALID,\n FLOATING_INPUT_CLASS,\n FloatingField,\n} from \"./field-base\";\n// The data alone (0.35): not the picker, which this field does not render.\nimport { CURRENCIES } from \"../currencies\";\nimport { FieldCaption, LockedReason, mergeRefs, type DisabledReasonDisplay, type FieldHelpProps } from \"./field-parts\";\nimport { useEndWidth, useNumericField } from \"./numeric-field\";\nimport type { CommitScope } from \"./write-lock\";\nimport { cn } from \"../lib/cn\";\nimport { commitExpression, formatResult } from \"../lib/calc\";\n\n/** {@link NumberInput}'s props — exported since 0.34 (refactor audit 2026-10, API-9): a\n * wrapper typed itself off `ComponentProps<typeof NumberInput>` until then. */\nexport interface NumberInputProps extends FieldHelpProps {\n /** The text, DOT-decimal (\"1234.5\", or a calculation being typed: \"12+5\"), as\n * `onChange` reports it — so a caller's `Number(value)` reads it. The field SHOWS it\n * in the locale's mark (see `locale`). A comma here is read as the decimal mark too,\n * never as grouping. */\n value: string;\n /** Fired on every keystroke with the text as a number reads it: grouping marks read\n * off (\"1.234,56\" → \"1234.56\" for a German typist, keksdose K5), the decimal mark\n * folded to a dot, operators kept so a typed expression survives. */\n onChange: (value: string) => void;\n /** Fired on blur/Enter with the *evaluated* value — use this for save-on-blur\n * fields so the save always sees the resolved number, never \"10+5\". */\n onCommit?: (value: string) => void;\n label?: ReactNode;\n /** Names the field when it has no visible `label` (a table cell, a phone's display\n * shape). */\n \"aria-label\"?: string;\n /** Names for the calculator this field renders — its trigger, and the controls\n * inside the popover — and for the numpad sheet it opens on a phone. Overrides\n * for THIS field only: both resolve the `calculator` namespace of\n * `<UiKitProvider labels>` themselves, then fall back to English.\n *\n * `pad` is not optional plumbing: this field renders a {@link NumberPadSheet}\n * exactly as {@link AmountInput} does, but had no way to pass it anything, so\n * the SAME keypad announced itself in German when a money field opened it and in\n * English when a goal target did. */\n labels?: {\n calculatorTrigger?: string;\n calculator?: CalculatorButtonLabels;\n pad?: NumberPadSheetLabels;\n };\n placeholder?: string;\n disabled?: boolean;\n autoFocus?: boolean;\n /** Wrapper class. */\n className?: string;\n /** Overrides the input's own styling (merged after the field base). */\n inputClassName?: string;\n id?: string;\n /** Show the calculator-popover trigger (default true). Set false for fields in\n * an ephemeral close-on-blur editor, where clicking the icon would blur away\n * and tear the editor down before the popover could open — inline typing\n * (e.g. \"200+50\" → Enter) still evaluates there. */\n calculator?: boolean;\n /** {@link FIELD_DISPLAY} — on a phone, the figure at display size with the field\n * chrome dropped. The currency-free half of the same treatment `AmountInput`\n * carries, for a dialog whose whole point is the one number (a budget goal's\n * target); not for a field among many, and never for the compact inline\n * editors this control also serves. */\n variant?: \"field\" | \"display\";\n /** A {@link FieldHint} \"?\" on the label's own line, beside the label rather\n * than at the far end of the strip — the far end is where the calculator\n * lives, and a hint placed there landed on top of it (steering-design\n * feedback #48). Plain TEXT (a string or a number) is a caption instead, UNDER\n * the field and attached through `aria-describedby` after the caller's own —\n * the same rule as {@link Select}'s `hint`: the label line has no room for a\n * sentence, and one placed there ran over the label and into the value.\n * Since 0.32 a FieldHint is that caption too at Large and on a touch screen,\n * where a \"?\" cannot be hovered open (`useInlineHint`). */\n hint?: ReactNode;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\n /**\n * What is wrong with the value, in the caller's own words — {@link Input}'s `error`,\n * the same anatomy (keksdose K5/K4: of the kit's fields only `Input` and\n * `NumberField` had one, so a goal target or a rate field wrote its message as a\n * loose `<p>` that nothing pointed at). Rendered under the field, after a text\n * `hint`; merged into `aria-describedby` after the caller's ids and the hint's; and\n * it implies `invalid`, so the field paints as well as announces. `null`, `false`\n * and `\"\"` — a `touched && errors.x` on the happy path — are no message.\n *\n * Passing the key at all (even `undefined`) keeps the field in a steady wrapper,\n * message or not, so the message coming and going never remounts the `<input>` and\n * takes the caret with it — see `Input`'s `FieldGroup`. A field that never passes\n * `error` renders exactly the DOM it did before the prop existed.\n */\n error?: ReactNode;\n /**\n * BCP 47 tag that decides the decimal mark the field SHOWS; default the\n * `<UiKitProvider locale>`, else the runtime's (keksdose K5). A French or Italian\n * reader sees \"3,5\", a German one too, de-CH and en-US see \"3.5\" — `Intl`\n * decides, not a guess about a country. Display only: `value` and `onChange` stay\n * dot-decimal. {@link NumberField} passes its own `locale` through here.\n */\n locale?: string;\n /**\n * Set on the `<input>`, with `id` above. Declared so `Field`'s render-prop spread —\n * `{(ids) => <NumberInput {...ids} … />}` — is typed and reaches the input: the hint\n * and error are described, a required number is announced as required, and\n * `aria-invalid` paints {@link FIELD_INVALID} the way `invalid` does.\n */\n \"aria-describedby\"?: string;\n \"aria-invalid\"?: boolean | \"true\" | \"false\";\n \"aria-required\"?: boolean | \"true\" | \"false\";\n /**\n * A static unit shown at the field's right edge — \"%\", \"kg\", \"km/h\".\n *\n * The read-out half of {@link AmountInput}'s currency chip, and it exists for the\n * same reason that one does: a unit belongs to the FIELD, not to the text, so\n * typing it is a way to get it into the value. Keksdose had a percentage spelled\n * three different ways across three screens — `<Input type=\"number\" step=\"0.01\">`\n * for a loan rate, `step=\"0.1\"` for a tax rate, `inputMode=\"decimal\"` for a VAT\n * rate — and none of the three showed a \"%\" anywhere near the box, so what the\n * digits meant was a question the label alone had to answer.\n *\n * `aria-hidden`, like the currency read-out: it is a property of the field that\n * the label already names (\"Interest rate (%)\"), and announcing it again after\n * every value reads as part of the number.\n */\n suffix?: ReactNode;\n /**\n * Turns on the step keys: ArrowUp / ArrowDown add or subtract `step`, PageUp /\n * PageDown ten of them. The result lands on the grid `min + k × step` (or `0 + k ×\n * step` without a `min`), so 3.1 with `step={0.25}` goes up to 3.25, not 3.35 —\n * what a native number input does. Decimal-exact: `0.1 + 0.2` steps to \"0.3\".\n *\n * A step changes the text through `onChange` like a keystroke would; `onCommit`\n * still fires on blur/Enter. Without `step` the arrow keys move the caret as before.\n */\n step?: number;\n /** Bounds for the step keys only — a step never leaves `[min, max]`. This field's\n * value is a STRING, so typed text is not clamped: {@link NumberField} is the\n * numeric field that clamps what is typed as well. */\n min?: number;\n max?: number;\n /**\n * Why the value cannot be changed — {@link Button}'s `disabledReason`, for a number\n * that SAVES itself: a setting committed on blur, a figure in a row editor\n * (Kurvenschmiede's session page, 0.33.1). `disabled` takes the field out of the tab\n * order, so the reason never reached a keyboard, and Kurvenschmiede wrote its own\n * `CommitInput` to keep it in.\n *\n * With a reason the field stays in the tab order and shows its value, `readOnly` (the\n * settled grey FIELD_BASE gives a `[readonly]` field) and `aria-disabled`, as the\n * Combobox family's lock is. Nothing changes the value: the step keys do nothing, the\n * calculator and the phone's numpad are not offered, and neither blur nor Enter\n * commits — so `onChange` and `onCommit` are never called. Enter is swallowed, so the\n * field does not submit the form around it. The reason is a line under the field at\n * Large and on a touch screen, else in the kit {@link Tooltip} (`disabledReasonDisplay`),\n * and on the input's `aria-describedby`, between the caption and the error. Wins over\n * `disabled`.\n */\n disabledReason?: ReactNode;\n /**\n * Where the reason shows — {@link Button}'s `disabledReasonDisplay`: by default a line\n * under the field at Large and on a touch screen, the tooltip otherwise (§4 \"No fact\n * only in a tooltip\"; DUP-3, refactor audit 2026-10).\n */\n disabledReasonDisplay?: DisabledReasonDisplay;\n /**\n * This field COMMITS — {@link Button}'s `commit`: under a locked\n * {@link WriteLockProvider} it is locked the `disabledReason` way with the lock's reason\n * (which wins over its own). A field whose value only reaches the server through the\n * form's Save leaves this off and stays editable under the lock; the Save takes\n * `commit`. No provider, or an unlocked one: no effect. {@link NumberField} and\n * {@link IntegerField} pass it on.\n */\n commit?: CommitScope;\n /**\n * The `<input>`, as a React 19 ref prop (0.34, API-3, refactor audit 2026-10): the one\n * focusable field of its family with no ref at all, so react-hook-form's focus-on-error\n * could reach it only through /rhf's id lookup, and an app not at all.\n * {@link NumberField} and {@link IntegerField} pass it on.\n */\n ref?: Ref<HTMLInputElement>;\n}\n\n/** Decimal places of `n` as written (\"0.25\" → 2, \"1e-7\" → 7), for decimal-exact\n * stepping. */\nfunction decimalsOf(n: number): number {\n const text = formatResult(n);\n const dot = text.indexOf(\".\");\n return dot === -1 ? 0 : text.length - dot - 1;\n}\n\n/**\n * `current` moved by `count` steps (negative = down), on the grid `origin + k × step`\n * and clamped into `[min, max]`. An off-grid value moves to the NEXT grid point in\n * that direction first, so one press is never more than one step.\n *\n * The grid index is found by division and the result rebuilt as `origin + k × step`,\n * then cut to the decimals `step` and `origin` are written with — which is where\n * binary noise goes: `0.1 × 3` is 0.30000000000000004, and `toFixed(1)` of it is\n * \"0.3\". Summing steps would accumulate that noise press by press instead.\n */\nexport function stepNumber(\n current: number | null,\n count: number,\n step: number,\n min?: number,\n max?: number,\n): number {\n const clamp = (n: number) => Math.min(max ?? Infinity, Math.max(min ?? -Infinity, n));\n // Nothing to step from: land on the value nearest zero the bounds allow, rather\n // than on ±step — a room count with `min={1}` goes to 1, a rate to 0.\n if (current === null || !Number.isFinite(current)) return clamp(0);\n const origin = min !== undefined && Number.isFinite(min) ? min : 0;\n const raw = (current - origin) / step;\n const nearest = Math.round(raw);\n // \"On the grid\" within float tolerance: (0.3 - 0) / 0.1 is 2.9999999999999996.\n const onGrid = Math.abs(raw - nearest) < 1e-9;\n const k = onGrid\n ? nearest + count\n : count > 0\n ? Math.ceil(raw) + count - 1\n : Math.floor(raw) + count + 1;\n const places = Math.min(Math.max(decimalsOf(step), decimalsOf(origin)), 20);\n return clamp(Number((origin + k * step).toFixed(places)));\n}\n\n/** NumberInput never rounds: what was typed (or calculated) is what it reports. */\nconst asTyped = (text: string) => text;\n\n// ── The money guard (kastlan 5, Kurvenschmiede) ─────────────────────────────────\n\n// The codes the kit's own currency pickers offer, as whole words: \"Amount (CHF)\",\n// \"EUR\", \"Kosten CHF\". Not every ISO 4217 code — \"ALL\", \"TOP\" and \"PEN\" are codes too,\n// and an upper-case label would trip on them.\nconst CURRENCY_CODE = new RegExp(`(?:^|[^A-Za-z])(?:${CURRENCIES.map((c) => c.code).join(\"|\")})(?![A-Za-z])`);\n// Symbols no unit of measure is written with. Not \"kr\", \"R\" or \"Fr\": those are words\n// and units as often as they are money.\nconst CURRENCY_SYMBOL = /[€$£¥₹₺₽₪₩₫฿₴₦₱]/;\n\n/** Text that names a currency and no unit to go with it. A slash makes it a rate or\n * a unit price (\"CHF/m²\", \"€/kWh\") — a figure whose decimals are its column's\n * business, not the currency's — and that is not what the guard is for. */\nfunction namesMoney(node: ReactNode): boolean {\n if (typeof node !== \"string\" && typeof node !== \"number\") return false;\n const text = String(node);\n return (CURRENCY_CODE.test(text) || CURRENCY_SYMBOL.test(text)) && !text.includes(\"/\") && !text.includes(\"%\");\n}\n\n/**\n * Is this field being used for MONEY? A currency in the unit (`suffix=\"CHF\"`), or in\n * the label, `aria-label` or placeholder of a field with no unit at all (\"Estimated\n * cost (CHF)\"). Any other suffix is a unit — \"%\", \"mm\", \"N·m\" — and says what the\n * digits are, whatever the label says. `digits` plays no part: NumberInput has none,\n * and Kurvenschmiede's engineering fields at 2 and 3 decimals are exactly what this\n * must stay quiet about.\n */\nfunction looksLikeMoney(suffix: ReactNode, texts: ReactNode[]): boolean {\n if (suffix !== undefined && suffix !== null && suffix !== \"\") return namesMoney(suffix);\n return texts.some(namesMoney);\n}\n\n/**\n * The kit's dev switch, as `lib/logger.ts` reads it: a development build, never a\n * production one — the consumer's bundler replaces `import.meta.env.DEV` with `false`\n * there, and this branch is dead code — and never under vitest, where every consumer\n * suite would print it once per render of every field it has not migrated yet. Read\n * per call rather than once per module, so a test can switch it on with `vi.stubEnv`.\n * Optional-chained: `import.meta.env` is a Vite injection, absent under plain Node.\n */\nfunction devWarnings(): boolean {\n return Boolean(import.meta.env?.DEV) && !import.meta.env?.VITEST;\n}\n\n/**\n * A numeric text field with a built-in calculator: type a calculation straight\n * in (e.g. \"12+5\", evaluated on blur/Enter) or click the trailing calculator\n * icon for a keypad. String `value`/`onChange` contract, mirroring\n * {@link AmountInput} — the currency-free counterpart for quantities, rates,\n * percentages and measurements.\n *\n * NOT FOR MONEY. This field never rounds: \"12.345\", or a calculator's \"100/3\", is\n * reported exactly as typed. kastlan's journal lines, a payment allocation and a\n * defect's estimated cost were NumberInputs, and a 3-decimal amount reached a\n * 2-decimal Money column and failed the save with a 422 — in one wizard after the\n * record before it had already been created (kastlan 5). Money goes in\n * {@link AmountInput} (string value, like this one) or {@link MoneyField} (number\n * value): both settle to the currency's minor unit on blur, Enter and every calculator\n * result, and take `digits` for a unit price at a finer scale. In development a\n * NumberInput that looks like money — a currency as its unit, or a currency in the\n * label of a field with no unit — says so on the console, once per field. A unit of\n * measure (\"mm\", \"N·m\", \"%\") keeps it quiet, as does any number of decimals.\n *\n * THE LOCALE'S MARK (keksdose K5). The field shows the `locale`'s decimal mark — \"3,5\"\n * to a French, Italian or German reader — and reads what is typed the way\n * {@link AmountInput} does (keksdose G1): \"1.234,56\" from a German typist is 1234.56,\n * \"1,234.56\" from an English one too, and a lone mark that cannot be grouping is the\n * decimal, whichever key typed it. Before, it always showed \"3.5\" and folded\n * \"1.234,56\" into 1.23456. `value` and `onChange` stay dot-decimal, which is the\n * contract every caller's `Number(value)` reads.\n *\n * While a figure is being typed the field shows the typist's OWN text — \"1.234,5\"\n * stays exactly that — rather than the value re-spelt: re-spelling turned a grouping\n * \".\" into a \",\" under their fingers, after which no rule could tell the two apart, and\n * a text that changes length under the caret moves it to the end. It is re-spelt in the\n * locale's mark, without grouping, once the figure settles (blur, Enter, a step or a\n * calculator result) or when the value changes from outside.\n */\nexport function NumberInput(props: NumberInputProps) {\n const {\n ref,\n value,\n onChange,\n onCommit,\n label,\n \"aria-label\": ariaLabel,\n labels,\n placeholder,\n autoFocus,\n className,\n inputClassName,\n id,\n \"aria-required\": ariaRequired,\n suffix,\n step,\n min,\n max,\n disabledReasonDisplay,\n } = props;\n const generatedId = useId();\n const fieldId = id ?? generatedId;\n // The engine AmountInput shares (DUP-10): the lock (focusable, `readOnly`, nothing\n // changes or commits — see `disabledReason`), the hint — a FieldHint is its words at\n // Large and on touch, §4 — the error, the description's order, the typist's draft and\n // the locale's mark (see the component's note), the calculator and the numpad.\n // NumberInput never rounds; it shows the value as it is.\n const numeric = useNumericField(props, { settle: asTyped, display: () => value });\n const { lock, locked, off, isMobile, asDisplay, showCalc, showNumpad, setFocused, mark, setDraft, derived } = numeric;\n const invalid = numeric.isInvalid;\n // Passed at all — even as `undefined` — the field keeps its box; see `error`.\n const reserve = \"error\" in props || \"hint\" in props;\n const labelled = label !== undefined;\n // The unit and the calculator's measured width, reserved as the field's end padding.\n const hasEnd = showCalc || suffix !== undefined;\n const [endRef, endWidth] = useEndWidth(hasEnd);\n // Before the first measurement (and wherever there is no layout), a TEXT unit\n // reserves an estimate from its length — one `ch` a character, in the input's own\n // (larger) font, so it errs wide — plus the span's `pe-2` and the 4px gap, and the\n // calculator's 36px. The class fallback's flat pe-8 gave a \"%\" 32px for a frame and\n // \"km/h\" too little.\n const suffixChars = typeof suffix === \"string\" || typeof suffix === \"number\" ? String(suffix).length : null;\n const estimatedEnd =\n suffixChars !== null ? `calc(${suffixChars}ch + 0.75rem${showCalc ? \" + 2.25rem\" : \"\"})` : undefined;\n // On mobile, focusing opens the numpad bottom sheet instead of the native\n // keyboard (#334); the ref lets its \"Done\" blur → commit + close. The caller's `ref`\n // gets the same element.\n const inputRef = useRef<HTMLInputElement>(null);\n const setInput = useMemo(() => mergeRefs(inputRef, ref), [ref]);\n\n // `derived` is the value in the locale's mark — one character for one, no grouping —\n // and the draft the typist's own text, shown only while it still says what the value\n // says (see `showsTyped`).\n const display = numeric.typedFor(value) ?? derived;\n\n // A keystroke, a paste or a numpad key: the typist's text is kept, the value is what\n // a number reads it as.\n const typed = (raw: string) => onChange(numeric.read(raw));\n // A RESULT — the calculator's, the numpad's \"=\" — is dot-decimal already. It does not\n // go through `typed`: \"1.234\" out of `100/81.03…` is never a thousand.\n const result = (next: string) => {\n setDraft(null);\n onChange(next);\n };\n\n // The money guard: once per field, development only. See `looksLikeMoney`.\n const warnedMoney = useRef(false);\n useEffect(() => {\n if (warnedMoney.current || !devWarnings()) return;\n if (!looksLikeMoney(suffix, [label, ariaLabel, placeholder])) return;\n warnedMoney.current = true;\n const name = [label, ariaLabel, suffix].find((t) => typeof t === \"string\" || typeof t === \"number\");\n console.warn(\n `[ui-kit] NumberInput${name === undefined ? \"\" : ` \"${String(name)}\"`} looks like a money field: a ` +\n `currency, and no unit. NumberInput never rounds, so \"12.345\" or a calculator's \"100/3\" is sent with ` +\n `three or more decimals (kastlan 5: a 422 from a 2-decimal Money column). Use AmountInput (string ` +\n `value) or MoneyField (number value) — both settle to the currency's minor unit. ` +\n `(Development builds only; once per field.)`,\n );\n }, [suffix, label, ariaLabel, placeholder]);\n\n const commit = () => {\n setDraft(null);\n const next = numeric.settle(commitExpression(value));\n if (next !== value) onChange(next);\n onCommit?.(next);\n };\n\n const stepBy = (count: number) => {\n setDraft(null);\n // The step starts from the text as a commit would read it, so \"12+5\" steps from 17.\n const resolved = commitExpression(value).trim();\n const n = resolved === \"\" ? NaN : Number(resolved);\n const next = formatResult(stepNumber(Number.isFinite(n) ? n : null, count, step as number, min, max));\n if (next !== value) onChange(next);\n };\n\n const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n // Locked: Enter submits no form and commits nothing, and no key steps the value.\n // The arrows and Home/End stay the caret's, for a long value someone is reading.\n if (locked) {\n if (e.key === \"Enter\") e.preventDefault();\n return;\n }\n if (e.key === \"Enter\") return commit();\n // A zero, negative or non-finite step is no step: the keys stay the caret's.\n if (!step || !(step > 0) || !Number.isFinite(step) || e.altKey || e.ctrlKey || e.metaKey) return;\n const count =\n e.key === \"ArrowUp\" ? 1 : e.key === \"ArrowDown\" ? -1 : e.key === \"PageUp\" ? 10 : e.key === \"PageDown\" ? -10 : 0;\n if (count === 0) return;\n // Otherwise ArrowUp/Down also jump the caret to the start/end of the text.\n e.preventDefault();\n stepBy(count);\n };\n\n // While locked the field sits in the reason's frame (line or Tooltip), its outermost\n // box — so `className` (a width, a flex or grid cell) moves onto that, and the form\n // keeps its layout, as on Select.\n const field = (\n <FloatingField\n className={cn(\"w-full\", !locked && className)}\n htmlFor={fieldId}\n label={label}\n srOnlyLabel={asDisplay}\n hint={numeric.hint.labelHint}\n >\n <input\n ref={setInput}\n id={fieldId}\n aria-label={ariaLabel}\n type=\"text\"\n // Mobile: suppress the OS keyboard so the numpad sheet owns entry (field\n // keeps focus/caret); desktop keeps the native decimal keypad.\n inputMode={isMobile ? \"none\" : \"decimal\"}\n autoComplete=\"off\"\n // eslint-disable-next-line jsx-a11y/no-autofocus -- a documented prop the caller opts into (off by default); the field never takes focus on its own.\n autoFocus={autoFocus}\n disabled={off}\n // Locked: focusable, `readOnly`, `aria-disabled` — see `disabledReason`.\n readOnly={locked || undefined}\n aria-disabled={locked || undefined}\n // Display mode has no floating label to feed the blank-placeholder trick,\n // and an empty borderless figure shows nothing — so it keeps whatever\n // placeholder the caller gave, falling back to a zero to aim at.\n placeholder={asDisplay ? (placeholder ?? \"0\") : labelled ? \" \" : placeholder}\n value={display}\n onChange={(e) => {\n if (!locked) typed(e.target.value);\n }}\n onFocus={() => setFocused(true)}\n onBlur={() => {\n // Nothing commits under the lock — not even a draft typed before it arrived,\n // which stays in the field for when it lifts.\n if (!locked) commit();\n setFocused(false);\n }}\n onKeyDown={onKeyDown}\n aria-invalid={invalid || undefined}\n aria-describedby={numeric.describedBy}\n aria-required={ariaRequired}\n // The end padding sits last so it always wins over an inputClassName that\n // sets its own px. Both trailing controls can be on at once, so the room\n // they need is reserved together rather than by whichever happens to render:\n // the calculator is ~36px and a short unit ~24px, and a field that reserved\n // only one of them would let the digits run under the other.\n className={cn(\n asDisplay\n ? cn(FIELD_DISPLAY, \"text-4xl font-semibold leading-tight tracking-tight tabular-nums\")\n : labelled\n ? FLOATING_INPUT_CLASS\n : FIELD_BASE,\n inputClassName,\n showCalc && suffix !== undefined ? \"pe-16\" : showCalc ? \"pe-9\" : suffix !== undefined ? \"pe-8\" : undefined,\n invalid && FIELD_INVALID,\n locked && \"cursor-not-allowed\",\n )}\n // The classes above are the fallback; once the end controls are measured the\n // field reserves exactly their width (+4px). A fixed pe-8 for any unit left a\n // \"%\" in a ~78px table cell 32px of padding and the digits ~32px of room\n // (keksdose live #367); a long unit (\"km/h\") got too little.\n style={\n hasEnd && endWidth != null\n ? { paddingInlineEnd: endWidth + 4 }\n : estimatedEnd !== undefined\n ? { paddingInlineEnd: estimatedEnd }\n : undefined\n }\n />\n {hasEnd && (\n // One flex track for both, so the unit and the calculator sit side by side\n // instead of stacking on the same corner — AmountInput's arrangement, which\n // has carried a chip and a calculator together since #430.\n <div ref={endRef} className=\"absolute inset-y-0 end-0 flex items-center\">\n {showCalc && (\n <CalculatorButton\n // Seeded with the value in the field's mark but WITHOUT the typist's\n // grouping: the evaluator reads either mark, but \"1.234,5\" is two of them.\n value={derived}\n onChange={result}\n className=\"self-stretch px-2.5\"\n aria-label={labels?.calculatorTrigger}\n labels={labels?.calculator}\n />\n )}\n {suffix !== undefined && (\n <span\n aria-hidden\n // pe-2, not the input's px-3: the unit is chrome at the box's edge, and\n // with pe-3 plus the 4px gap it took ~26px of a narrow table cell.\n className=\"pointer-events-none pe-2 text-xs font-medium text-muted\"\n >\n {suffix}\n </span>\n )}\n </div>\n )}\n {showNumpad && (\n <NumberPadSheet\n // Localised like the field it mirrors, as AmountInput's is: its keys are\n // typing, read by the locale's marks like the keyboard's; \"=\" is a result.\n value={display}\n onChange={typed}\n onResult={result}\n onDone={() => inputRef.current?.blur()}\n label={label}\n labels={labels?.pad}\n decimalMark={mark}\n />\n )}\n </FloatingField>\n );\n const box = locked ? (\n <LockedReason lock={lock} display={disabledReasonDisplay} className={cn(\"block w-full\", className)}>\n {field}\n </LockedReason>\n ) : (\n field\n );\n if (numeric.hint.captionText === undefined && numeric.errorEl === null && !reserve) return box;\n // Outside the field's own `relative` box, as Select's caption is: the calculator\n // and the unit are `inset-y-0` in it and would stretch down over a second line.\n // `className` stays on the field, so adding a caption cannot change what it styles.\n return (\n <div>\n {box}\n <FieldCaption parts={numeric.hint} />\n {numeric.errorEl}\n </div>\n );\n}\n"],"mappings":";AAubM,cAkEE,YAlEF;AAvbN,SAAS,WAAW,OAAO,SAAS,cAAc;AAElD,SAAS,wBAAqD;AAC9D,SAAS,sBAAiD;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,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S,WAAW,SAAY,SAAS;AAAA,cACjG,WAAW;AAAA,cACX,UAAU;AAAA,YACZ;AAAA,YAKA,OACE,UAAU,YAAY,OAClB,EAAE,kBAAkB,WAAW,EAAE,IACjC,iBAAiB,SACf,EAAE,kBAAkB,aAAa,IACjC;AAAA;AAAA,QAEV;AAAA,QACC;AAAA;AAAA;AAAA,QAIC,qBAAC,SAAI,KAAK,QAAQ,WAAU,8CACzB;AAAA,sBACC;AAAA,YAAC;AAAA;AAAA,cAGC,OAAO;AAAA,cACP,UAAU;AAAA,cACV,WAAU;AAAA,cACV,cAAY,QAAQ;AAAA,cACpB,QAAQ,QAAQ;AAAA;AAAA,UAClB;AAAA,UAED,WAAW,UACV;AAAA,YAAC;AAAA;AAAA,cACC,eAAW;AAAA,cAGX,WAAU;AAAA,cAET;AAAA;AAAA,UACH;AAAA,WAEJ;AAAA,QAED,cACC;AAAA,UAAC;AAAA;AAAA,YAGC,OAAO;AAAA,YACP,UAAU;AAAA,YACV,UAAU;AAAA,YACV,QAAQ,MAAM,SAAS,SAAS,KAAK;AAAA,YACrC;AAAA,YACA,QAAQ,QAAQ;AAAA,YAChB,aAAa;AAAA;AAAA,QACf;AAAA;AAAA;AAAA,EAEJ;AAEF,QAAM,MAAM,SACV,oBAAC,gBAAa,MAAY,SAAS,uBAAuB,WAAW,GAAG,gBAAgB,SAAS,GAC9F,iBACH,IAEA;AAEF,MAAI,QAAQ,KAAK,gBAAgB,UAAa,QAAQ,YAAY,QAAQ,CAAC,QAAS,QAAO;AAI3F,SACE,qBAAC,SACE;AAAA;AAAA,IACD,oBAAC,gBAAa,OAAO,QAAQ,MAAM;AAAA,IAClC,QAAQ;AAAA,KACX;AAEJ;","names":[]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ReactNode, RefObject } from "react";
|
|
2
|
-
import { type FieldHintParts, type LockReason } from "./field-parts.js";
|
|
2
|
+
import { type FieldHelpProps, type FieldHintParts, type LockReason } from "./field-parts.js";
|
|
3
3
|
import type { CommitScope } from "./write-lock.js";
|
|
4
4
|
/**
|
|
5
5
|
* The engine NumberInput and AmountInput share (DUP-10, refactor audit 2026-10): the
|
|
@@ -15,7 +15,9 @@ import type { CommitScope } from "./write-lock.js";
|
|
|
15
15
|
* controls. Package-private — not re-exported from the barrel.
|
|
16
16
|
*/
|
|
17
17
|
/** The props both fields take and this engine reads. */
|
|
18
|
-
export interface NumericFieldProps {
|
|
18
|
+
export interface NumericFieldProps extends FieldHelpProps {
|
|
19
|
+
/** What names the `help` "?" — "About “<label>”" — with the `aria-label`. */
|
|
20
|
+
label?: ReactNode;
|
|
19
21
|
hint?: ReactNode;
|
|
20
22
|
error?: ReactNode;
|
|
21
23
|
invalid?: boolean;
|
|
@@ -26,6 +28,7 @@ export interface NumericFieldProps {
|
|
|
26
28
|
calculator?: boolean;
|
|
27
29
|
variant?: "field" | "display";
|
|
28
30
|
locale?: string;
|
|
31
|
+
"aria-label"?: string;
|
|
29
32
|
"aria-describedby"?: string;
|
|
30
33
|
"aria-invalid"?: boolean | "true" | "false";
|
|
31
34
|
}
|
|
@@ -12,7 +12,10 @@ import {
|
|
|
12
12
|
function useNumericField(props, { settle, display }) {
|
|
13
13
|
const lock = useLockReason(props.commit, props.disabledReason);
|
|
14
14
|
const locked = lock.locked;
|
|
15
|
-
const hint = useFieldHint(props.hint, props["aria-describedby"]
|
|
15
|
+
const hint = useFieldHint(props.hint, props["aria-describedby"], {
|
|
16
|
+
help: props.help,
|
|
17
|
+
name: props.label ?? props["aria-label"]
|
|
18
|
+
});
|
|
16
19
|
const field = useFieldError(
|
|
17
20
|
props.error,
|
|
18
21
|
props.invalid,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/numeric-field.ts"],"sourcesContent":["import { useLayoutEffect, useRef, useState } from \"react\";\nimport type { ReactNode, RefObject } from \"react\";\nimport { usePhoneLayout } from \"../hooks/use-breakpoint\";\nimport { useKitLocale } from \"../i18n/kit-labels\";\nimport { decimalMark, localizeMark, readTyped, showsTyped } from \"../lib/decimal-marks\";\nimport {\n mergeDescribedBy,\n useFieldError,\n useFieldHint,\n useLockReason,\n type FieldHintParts,\n type LockReason,\n} from \"./field-parts\";\nimport type { CommitScope } from \"./write-lock\";\n\n/**\n * The engine NumberInput and AmountInput share (DUP-10, refactor audit 2026-10): the\n * lock, the hint and its caption, the error, the `aria-describedby` order, the typist's\n * draft and what the field shows, the calculator and the phone's numpad, and the room\n * its end controls take. They were two copies of it, and each fix had to be made twice —\n * some reached only one: NumberInput measured its end controls (keksdose live #367) and\n * took a `locale`, AmountInput did neither; the 0.32 FieldHint caption reached\n * AmountInput two releases late.\n *\n * Each field keeps what is its own: the settle (money's minor unit and `min`/`max`\n * against NumberInput's \"what was typed\"), the caller-owned sign, and its trailing\n * controls. Package-private — not re-exported from the barrel.\n */\n\n/** The props both fields take and this engine reads. */\nexport interface NumericFieldProps {\n hint?: ReactNode;\n error?: ReactNode;\n invalid?: boolean;\n disabled?: boolean;\n disabledReason?: ReactNode;\n commit?: CommitScope;\n /** Show the desktop calculator trigger. Default `true`. */\n calculator?: boolean;\n variant?: \"field\" | \"display\";\n locale?: string;\n \"aria-describedby\"?: string;\n \"aria-invalid\"?: boolean | \"true\" | \"false\";\n}\n\nexport interface NumericFieldOptions {\n /** The field's own settle, dot-decimal in and out — AmountInput's minor unit and\n * `min` / `max`; NumberInput's identity (it never rounds). */\n settle: (text: string) => string;\n /** What the field shows while no typed draft stands, dot-decimal, given whether it\n * has focus — spelt in the locale's mark here (`derived`). */\n display: (focused: boolean) => string;\n}\n\nexport interface NumericField {\n /** The write lock: focusable, `readOnly`, nothing changes or commits. */\n lock: LockReason;\n locked: boolean;\n /** Natively `disabled`: `disabled`, and no lock — a reason wins over it. */\n off: boolean;\n /** The hint, split into the caption under the field and the label line's \"?\". */\n hint: FieldHintParts;\n /** `invalid`, a message, or a form library's `aria-invalid`. */\n isInvalid: boolean;\n /** The caller's ids, the caption, a lock's reason, the error — Select's order. */\n describedBy: string | undefined;\n /** The message under the field, or `null`. */\n errorEl: ReactNode;\n /** The phone layout: the numpad sheet replaces the keyboard and the calculator. */\n isMobile: boolean;\n /** `variant=\"display\"`, on a phone. */\n asDisplay: boolean;\n showCalc: boolean;\n showNumpad: boolean;\n focused: boolean;\n setFocused: (focused: boolean) => void;\n /** The locale's decimal mark — the field's `locale`, else the provider's. */\n mark: \",\" | \".\";\n /** The typist's own text while a figure is typed, else `null`. */\n draft: string | null;\n setDraft: (draft: string | null) => void;\n /** `display(focused)` in the locale's mark. */\n derived: string;\n /** The draft, while it still says what `canonical` (dot-decimal) says and holds\n * nothing the field would drop — see `showsTyped`; else `null`. */\n typedFor: (canonical: string) => string | null;\n /** A keystroke's raw text: kept as the draft, and read as a number reads it —\n * grouping off, dot-decimal. */\n read: (raw: string) => string;\n settle: (text: string) => string;\n}\n\nexport function useNumericField(props: NumericFieldProps, { settle, display }: NumericFieldOptions): NumericField {\n const lock = useLockReason(props.commit, props.disabledReason);\n const locked = lock.locked;\n // §4: a FieldHint is the caption at Large and on touch, as on every field.\n const hint = useFieldHint(props.hint, props[\"aria-describedby\"]);\n // The standing advice first, the news second: the caller's ids, the caption, the\n // error — a lock's reason between the last two, as on Select.\n const field = useFieldError(\n props.error,\n props.invalid,\n mergeDescribedBy(hint.describedBy, locked && lock.reasonId),\n props[\"aria-invalid\"],\n );\n // On phones the OS keyboard is suppressed (`inputMode=\"none\"`) for the kit's numpad\n // sheet, so the desktop calculator trigger is hidden (feedback #334). A locked field\n // offers neither: their result would be a value.\n const isMobile = usePhoneLayout();\n const [focused, setFocused] = useState(false);\n const mark = decimalMark(useKitLocale(props.locale));\n const [draft, setDraft] = useState<string | null>(null);\n return {\n lock,\n locked,\n off: Boolean(props.disabled) && !locked,\n hint,\n isInvalid: field.isInvalid,\n describedBy: field.describedBy,\n errorEl: field.errorEl,\n isMobile,\n asDisplay: isMobile && props.variant === \"display\",\n showCalc: (props.calculator ?? true) && !props.disabled && !locked && !isMobile,\n showNumpad: isMobile && !props.disabled && !locked && focused,\n focused,\n setFocused,\n mark,\n draft,\n setDraft,\n derived: localizeMark(display(focused), mark),\n typedFor: (canonical) => (draft !== null && showsTyped(draft, mark, canonical) ? draft : null),\n read: (raw) => {\n setDraft(raw);\n return readTyped(raw, mark);\n },\n settle,\n };\n}\n\n/**\n * The measured width of a field's end controls (keksdose live #367), and the ref for\n * their track: `null` before the first measurement and wherever there is no layout\n * (jsdom), where the field keeps its class fallback. A `ResizeObserver` calls back once\n * on `observe`, and again whenever the controls change size (a chip's code, a translated\n * label, the text size). A pair, so the width reads as the plain number it is.\n */\nexport function useEndWidth(present: boolean): [RefObject<HTMLDivElement | null>, number | null] {\n const ref = useRef<HTMLDivElement>(null);\n const [width, setWidth] = useState<number | null>(null);\n useLayoutEffect(() => {\n const el = ref.current;\n if (!present || !el || typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(() => {\n const measured = el.getBoundingClientRect().width;\n setWidth(measured > 0 ? Math.ceil(measured) : null);\n });\n observer.observe(el);\n return () => observer.disconnect();\n }, [present]);\n return [ref, width];\n}\n"],"mappings":";AAAA,SAAS,iBAAiB,QAAQ,gBAAgB;AAElD,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB;AAC7B,SAAS,aAAa,cAAc,WAAW,kBAAkB;AACjE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,
|
|
1
|
+
{"version":3,"sources":["../../src/components/numeric-field.ts"],"sourcesContent":["import { useLayoutEffect, useRef, useState } from \"react\";\nimport type { ReactNode, RefObject } from \"react\";\nimport { usePhoneLayout } from \"../hooks/use-breakpoint\";\nimport { useKitLocale } from \"../i18n/kit-labels\";\nimport { decimalMark, localizeMark, readTyped, showsTyped } from \"../lib/decimal-marks\";\nimport {\n mergeDescribedBy,\n useFieldError,\n useFieldHint,\n useLockReason,\n type FieldHelpProps,\n type FieldHintParts,\n type LockReason,\n} from \"./field-parts\";\nimport type { CommitScope } from \"./write-lock\";\n\n/**\n * The engine NumberInput and AmountInput share (DUP-10, refactor audit 2026-10): the\n * lock, the hint and its caption, the error, the `aria-describedby` order, the typist's\n * draft and what the field shows, the calculator and the phone's numpad, and the room\n * its end controls take. They were two copies of it, and each fix had to be made twice —\n * some reached only one: NumberInput measured its end controls (keksdose live #367) and\n * took a `locale`, AmountInput did neither; the 0.32 FieldHint caption reached\n * AmountInput two releases late.\n *\n * Each field keeps what is its own: the settle (money's minor unit and `min`/`max`\n * against NumberInput's \"what was typed\"), the caller-owned sign, and its trailing\n * controls. Package-private — not re-exported from the barrel.\n */\n\n/** The props both fields take and this engine reads. */\nexport interface NumericFieldProps extends FieldHelpProps {\n /** What names the `help` \"?\" — \"About “<label>”\" — with the `aria-label`. */\n label?: ReactNode;\n hint?: ReactNode;\n error?: ReactNode;\n invalid?: boolean;\n disabled?: boolean;\n disabledReason?: ReactNode;\n commit?: CommitScope;\n /** Show the desktop calculator trigger. Default `true`. */\n calculator?: boolean;\n variant?: \"field\" | \"display\";\n locale?: string;\n \"aria-label\"?: string;\n \"aria-describedby\"?: string;\n \"aria-invalid\"?: boolean | \"true\" | \"false\";\n}\n\nexport interface NumericFieldOptions {\n /** The field's own settle, dot-decimal in and out — AmountInput's minor unit and\n * `min` / `max`; NumberInput's identity (it never rounds). */\n settle: (text: string) => string;\n /** What the field shows while no typed draft stands, dot-decimal, given whether it\n * has focus — spelt in the locale's mark here (`derived`). */\n display: (focused: boolean) => string;\n}\n\nexport interface NumericField {\n /** The write lock: focusable, `readOnly`, nothing changes or commits. */\n lock: LockReason;\n locked: boolean;\n /** Natively `disabled`: `disabled`, and no lock — a reason wins over it. */\n off: boolean;\n /** The hint, split into the caption under the field and the label line's \"?\". */\n hint: FieldHintParts;\n /** `invalid`, a message, or a form library's `aria-invalid`. */\n isInvalid: boolean;\n /** The caller's ids, the caption, a lock's reason, the error — Select's order. */\n describedBy: string | undefined;\n /** The message under the field, or `null`. */\n errorEl: ReactNode;\n /** The phone layout: the numpad sheet replaces the keyboard and the calculator. */\n isMobile: boolean;\n /** `variant=\"display\"`, on a phone. */\n asDisplay: boolean;\n showCalc: boolean;\n showNumpad: boolean;\n focused: boolean;\n setFocused: (focused: boolean) => void;\n /** The locale's decimal mark — the field's `locale`, else the provider's. */\n mark: \",\" | \".\";\n /** The typist's own text while a figure is typed, else `null`. */\n draft: string | null;\n setDraft: (draft: string | null) => void;\n /** `display(focused)` in the locale's mark. */\n derived: string;\n /** The draft, while it still says what `canonical` (dot-decimal) says and holds\n * nothing the field would drop — see `showsTyped`; else `null`. */\n typedFor: (canonical: string) => string | null;\n /** A keystroke's raw text: kept as the draft, and read as a number reads it —\n * grouping off, dot-decimal. */\n read: (raw: string) => string;\n settle: (text: string) => string;\n}\n\nexport function useNumericField(props: NumericFieldProps, { settle, display }: NumericFieldOptions): NumericField {\n const lock = useLockReason(props.commit, props.disabledReason);\n const locked = lock.locked;\n // §4: a FieldHint is the caption at Large and on touch, as on every field.\n // A `help` is the label line's one \"?\" and turns the hint into the caption (0.36).\n const hint = useFieldHint(props.hint, props[\"aria-describedby\"], {\n help: props.help,\n name: props.label ?? props[\"aria-label\"],\n });\n // The standing advice first, the news second: the caller's ids, the caption, the\n // error — a lock's reason between the last two, as on Select.\n const field = useFieldError(\n props.error,\n props.invalid,\n mergeDescribedBy(hint.describedBy, locked && lock.reasonId),\n props[\"aria-invalid\"],\n );\n // On phones the OS keyboard is suppressed (`inputMode=\"none\"`) for the kit's numpad\n // sheet, so the desktop calculator trigger is hidden (feedback #334). A locked field\n // offers neither: their result would be a value.\n const isMobile = usePhoneLayout();\n const [focused, setFocused] = useState(false);\n const mark = decimalMark(useKitLocale(props.locale));\n const [draft, setDraft] = useState<string | null>(null);\n return {\n lock,\n locked,\n off: Boolean(props.disabled) && !locked,\n hint,\n isInvalid: field.isInvalid,\n describedBy: field.describedBy,\n errorEl: field.errorEl,\n isMobile,\n asDisplay: isMobile && props.variant === \"display\",\n showCalc: (props.calculator ?? true) && !props.disabled && !locked && !isMobile,\n showNumpad: isMobile && !props.disabled && !locked && focused,\n focused,\n setFocused,\n mark,\n draft,\n setDraft,\n derived: localizeMark(display(focused), mark),\n typedFor: (canonical) => (draft !== null && showsTyped(draft, mark, canonical) ? draft : null),\n read: (raw) => {\n setDraft(raw);\n return readTyped(raw, mark);\n },\n settle,\n };\n}\n\n/**\n * The measured width of a field's end controls (keksdose live #367), and the ref for\n * their track: `null` before the first measurement and wherever there is no layout\n * (jsdom), where the field keeps its class fallback. A `ResizeObserver` calls back once\n * on `observe`, and again whenever the controls change size (a chip's code, a translated\n * label, the text size). A pair, so the width reads as the plain number it is.\n */\nexport function useEndWidth(present: boolean): [RefObject<HTMLDivElement | null>, number | null] {\n const ref = useRef<HTMLDivElement>(null);\n const [width, setWidth] = useState<number | null>(null);\n useLayoutEffect(() => {\n const el = ref.current;\n if (!present || !el || typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(() => {\n const measured = el.getBoundingClientRect().width;\n setWidth(measured > 0 ? Math.ceil(measured) : null);\n });\n observer.observe(el);\n return () => observer.disconnect();\n }, [present]);\n return [ref, width];\n}\n"],"mappings":";AAAA,SAAS,iBAAiB,QAAQ,gBAAgB;AAElD,SAAS,sBAAsB;AAC/B,SAAS,oBAAoB;AAC7B,SAAS,aAAa,cAAc,WAAW,kBAAkB;AACjE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAmFA,SAAS,gBAAgB,OAA0B,EAAE,QAAQ,QAAQ,GAAsC;AAChH,QAAM,OAAO,cAAc,MAAM,QAAQ,MAAM,cAAc;AAC7D,QAAM,SAAS,KAAK;AAGpB,QAAM,OAAO,aAAa,MAAM,MAAM,MAAM,kBAAkB,GAAG;AAAA,IAC/D,MAAM,MAAM;AAAA,IACZ,MAAM,MAAM,SAAS,MAAM,YAAY;AAAA,EACzC,CAAC;AAGD,QAAM,QAAQ;AAAA,IACZ,MAAM;AAAA,IACN,MAAM;AAAA,IACN,iBAAiB,KA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AAC;AACD,aAAS,QAAQ,EAAE;AACnB,WAAO,MAAM,SAAS,WAAW;AAAA,EACnC,GAAG,CAAC,OAAO,CAAC;AACZ,SAAO,CAAC,KAAK,KAAK;AACpB;","names":[]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { InputHTMLAttributes, ReactNode, Ref } from "react";
|
|
2
|
+
import { type FieldHelpProps } from "./field-parts.js";
|
|
2
3
|
/**
|
|
3
4
|
* The field for a verification code — the six digits an authenticator app shows, or the
|
|
4
5
|
* ones a sign-in mail or SMS carries.
|
|
@@ -45,7 +46,7 @@ import type { InputHTMLAttributes, ReactNode, Ref } from "react";
|
|
|
45
46
|
* as a caption under the field (a {@link FieldHint} "?" rides the label line instead),
|
|
46
47
|
* the error under that, both attached through `aria-describedby` after the caller's own.
|
|
47
48
|
*/
|
|
48
|
-
export interface OneTimeCodeInputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "value" | "defaultValue" | "onChange" | "type" | "inputMode" | "autoComplete" | "maxLength" | "pattern"
|
|
49
|
+
export interface OneTimeCodeInputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "value" | "defaultValue" | "onChange" | "type" | "inputMode" | "autoComplete" | "maxLength" | "pattern">, FieldHelpProps {
|
|
49
50
|
/** The digits so far — a string, so leading zeros survive. */
|
|
50
51
|
value: string;
|
|
51
52
|
/** The cleaned code after every edit: digits only, never longer than `length`. */
|
|
@@ -23,6 +23,7 @@ function OneTimeCodeInput(props) {
|
|
|
23
23
|
onComplete,
|
|
24
24
|
label,
|
|
25
25
|
hint,
|
|
26
|
+
help,
|
|
26
27
|
error,
|
|
27
28
|
invalid: invalidProp,
|
|
28
29
|
className,
|
|
@@ -40,7 +41,7 @@ function OneTimeCodeInput(props) {
|
|
|
40
41
|
const size = Math.max(1, Math.floor(length) || 1);
|
|
41
42
|
const generatedId = useId();
|
|
42
43
|
const fieldId = id ?? generatedId;
|
|
43
|
-
const hintParts = useFieldHint(hint, ariaDescribedBy);
|
|
44
|
+
const hintParts = useFieldHint(hint, ariaDescribedBy, { help, name: label ?? rest["aria-label"] });
|
|
44
45
|
const {
|
|
45
46
|
isInvalid: invalid,
|
|
46
47
|
describedBy,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/one-time-code-input.tsx"],"sourcesContent":["import { useId, useState } from \"react\";\nimport type { ChangeEvent, ClipboardEvent, FocusEvent, InputHTMLAttributes, ReactNode, Ref } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { EndHintRow, FieldCaption, useFieldError, useFieldHint } from \"./field-parts\";\nimport {\n FIELD_BASE,\n FIELD_INVALID,\n FIELD_WRITABLE_LOOK,\n FLOATING_INPUT_CLASS,\n FloatingField,\n} from \"./field-base\";\n\n/**\n * The field for a verification code — the six digits an authenticator app shows, or the\n * ones a sign-in mail or SMS carries.\n *\n * Asked for by kastlan (input audit, item 3) and keksdose (K8) for the sign-in\n * verification step, and already written twice by hand inside {@link TwoFactorSetting}.\n * The three copies agreed on `inputMode=\"numeric\"` and `autoComplete=\"one-time-code\"`\n * and on nothing else: kastlan's login stripped non-digits and capped at six, keksdose's\n * capped at eight and kept whatever was typed, and the settings card kept everything,\n * spaces included — so \"123 456\" pasted from an authenticator that groups its digits\n * reached the server with the space in it.\n *\n * ONE FIELD, NOT SIX BOXES. The six-box look is the fashionable one, and every part of\n * it works against the two ways a code actually arrives. A paste lands in ONE input,\n * so the boxes need a paste handler that spreads it; the platform's own code autofill\n * (iOS and macOS offer the code from Messages and Mail above the keyboard, Android's\n * keyboards do the same) fills the ONE field marked `one-time-code`, so the boxes need\n * that field to exist anyway, hidden; and a screen reader hears six unlabelled inputs\n * of one character each. One text field gets all three right for free.\n *\n * WHAT IT DOES TO THE TEXT:\n * - **Digits only**, as a STRING. A code may start with 0, and a number field would\n * drop it (\"012345\" → 12345) — kastlan's login says as much in a comment. Every\n * character that is not a digit is dropped as it arrives, so the spaces and dashes\n * of \"123 456\" and \"123-456\" go, whether typed or pasted. Full-width digits (what a\n * Chinese input method types: \"123\") are folded to ASCII first (NFKC).\n * - **No `maxLength` attribute.** The browser applies it BEFORE the change event, so\n * pasting \"123 456\" into a `maxLength={6}` field kept \"123 45\" and the cleaning saw\n * one digit short. The length is enforced here instead, after the cleaning: a field\n * that is full refuses another digit, as `maxLength` would.\n * - **A paste that is a whole code replaces the field**, wherever the caret is: a\n * person pasting six digits means \"this is the code\", not \"insert these into the\n * stale one\".\n * - **The caret stays put** when a character is dropped, rather than jumping to the\n * end as a controlled input does when its value is put back.\n *\n * `onComplete` fires when an edit — a keystroke, a paste, the platform's autofill —\n * makes the code `length` digits long. It is a notification, nothing more: the field\n * never submits a form on its own. Whether a full code verifies at once is the app's\n * call (a sign-in step may; a \"turn off two-factor\" form that also wants a password\n * should not). It does not fire for a value set from outside.\n *\n * `label`, `hint` and `error` read as on every kit field: a floating label, a text hint\n * as a caption under the field (a {@link FieldHint} \"?\" rides the label line instead),\n * the error under that, both attached through `aria-describedby` after the caller's own.\n */\nexport interface OneTimeCodeInputProps\n extends Omit<\n InputHTMLAttributes<HTMLInputElement>,\n \"value\" | \"defaultValue\" | \"onChange\" | \"type\" | \"inputMode\" | \"autoComplete\" | \"maxLength\" | \"pattern\"\n > {\n /** The digits so far — a string, so leading zeros survive. */\n value: string;\n /** The cleaned code after every edit: digits only, never longer than `length`. */\n onChange: (code: string) => void;\n /** How many digits the code has. Default 6. The field refuses digits past it. */\n length?: number;\n /** Called with the code when an edit makes it `length` digits long. Never submits\n * anything itself. */\n onComplete?: (code: string) => void;\n /** The floating label, as on {@link Input}. Without one, name the field with\n * `aria-label` or `aria-labelledby` (kastlan's login points it at its prompt). */\n label?: ReactNode;\n /** Plain text: a caption under the field, attached with `aria-describedby`. Anything\n * else (a {@link FieldHint}): on the label line — or at the field's end edge when\n * there is no label. The rule {@link Select}'s `hint` follows. */\n hint?: ReactNode;\n /** What is wrong (\"That code has expired\"). Rendered under the field, attached with\n * `aria-describedby`, and implies `invalid`. */\n error?: ReactNode;\n /** Paint the field invalid and set `aria-invalid` without a message of its own. */\n invalid?: boolean;\n /** Classes for the `<input>`; `className` styles the field's wrapper once it has a\n * label, the `<input>` itself when it has none — as on {@link Input}. */\n inputClassName?: string;\n /**\n * Keep the field `readOnly` until it first takes focus.\n *\n * A browser that has a login saved for the site fills it in on load — and on a page\n * where the code field is the only text field near a password field, it can take the\n * code field for the username and write the address into it. A read-only field is\n * never autofilled, and focus is the moment a person (or the platform's code\n * suggestion, which needs a focused field anyway) starts to use it. So the field\n * stays read-only until then, and only until then.\n *\n * It keeps the LOOK of an editable field throughout ({@link FIELD_WRITABLE_LOOK}):\n * this is the one place where read-only does not mean \"you may not type here\", and\n * without the opt-out the field would sit there greyed until it is clicked.\n *\n * {@link TwoFactorSetting} has always done this — its code fields share a page with\n * the current-password field of the disable form — and keeps doing it through this\n * prop. Off by default, because it is a trade: a field that is read-only at the\n * moment focus lands can be announced as read-only by a screen reader, and on some\n * mobile browsers it does not raise the keyboard until a second tap. Turn it on where\n * a saved login actually lands in the field.\n */\n readOnlyUntilFocus?: boolean;\n /** The `<input>`. A React 19 ref prop since 0.34 (MOD-4, refactor audit 2026-10); it\n * was `forwardRef`. */\n ref?: Ref<HTMLInputElement>;\n}\n\n// Equal-width digits, spaced a little apart, so a code reads — and compares against the\n// authenticator's screen — digit by digit.\nconst CODE_TYPE = \"tabular-nums tracking-widest\";\n\n/** The ASCII digits in `text`, in order. NFKC folds full-width digits (\"1\") to \"1\". */\nfunction digitsOf(text: string): string {\n return text.normalize(\"NFKC\").replace(/\\D/g, \"\");\n}\n\nexport function OneTimeCodeInput(props: OneTimeCodeInputProps) {\n const {\n ref,\n value,\n onChange,\n length = 6,\n onComplete,\n label,\n hint,\n error,\n invalid: invalidProp,\n className,\n inputClassName,\n readOnlyUntilFocus = false,\n readOnly,\n id,\n placeholder,\n onFocus,\n onPaste,\n \"aria-describedby\": ariaDescribedBy,\n \"aria-invalid\": ariaInvalid,\n ...rest\n } = props;\n // A length below one is no code at all; a fractional one is a typo.\n const size = Math.max(1, Math.floor(length) || 1);\n const generatedId = useId();\n const fieldId = id ?? generatedId;\n // Text is a caption under the field; a FieldHint rides the label line, and is that\n // caption at Large and on touch (§4). See `hint`. Through useFieldHint and\n // useFieldError since 0.34, not copies of their rules (DUP-2, DUP-8).\n const hintParts = useFieldHint(hint, ariaDescribedBy);\n const {\n isInvalid: invalid,\n describedBy,\n errorEl,\n } = useFieldError(error, invalidProp, hintParts.describedBy, ariaInvalid);\n // Passed at all — even as `undefined` — the field keeps its box, so the `<input>` is\n // never re-parented (and never loses focus) when a message comes or goes. See\n // `FieldGroup` in field-base.tsx.\n const reserve = \"error\" in props || \"hint\" in props;\n const labelled = label !== undefined;\n\n // Focused once = in use; the guard is down for good from then on (see the prop).\n const [focusedOnce, setFocusedOnce] = useState(false);\n const guarding = readOnlyUntilFocus && !focusedOnce;\n\n const commit = (next: string) => {\n if (next === value) return;\n onChange(next);\n if (next.length === size) onComplete?.(next);\n };\n\n const handleChange = (e: ChangeEvent<HTMLInputElement>) => {\n const input = e.currentTarget;\n const raw = input.value;\n const cleaned = digitsOf(raw);\n // Past the length: a full field refuses the digit (what `maxLength` does), a\n // partial one keeps the first `size` — a paste longer than the room left.\n const refused = cleaned.length > size && value.length >= size;\n const next = refused ? value : cleaned.slice(0, size);\n if (next !== raw) {\n // Write the cleaned text back NOW, with the caret where the typist left it.\n // React would otherwise put its value back after this handler, and setting an\n // input's value moves the caret to the end — so a space typed mid-code threw\n // the caret to the last digit. React finds the DOM already agreeing and leaves\n // it alone.\n const caret = input.selectionStart ?? raw.length;\n const at = refused\n ? Math.max(0, caret - (raw.length - value.length))\n : Math.min(digitsOf(raw.slice(0, caret)).length, next.length);\n input.value = next;\n try {\n input.setSelectionRange(at, at);\n } catch {\n /* not every input type has a selection; a text field does */\n }\n }\n commit(next);\n };\n\n const handlePaste = (e: ClipboardEvent<HTMLInputElement>) => {\n onPaste?.(e);\n // A read-only field still receives the event; it must not take the code.\n if (e.defaultPrevented || readOnly || guarding || rest.disabled) return;\n const pasted = digitsOf(e.clipboardData.getData(\"text\"));\n // Anything else — a few digits into a partial code — is an ordinary insertion,\n // and the change handler cleans it.\n if (pasted.length !== size) return;\n e.preventDefault();\n commit(pasted);\n };\n\n const handleFocus = (e: FocusEvent<HTMLInputElement>) => {\n if (guarding) setFocusedOnce(true);\n onFocus?.(e);\n };\n\n const input = (\n <input\n ref={ref}\n id={labelled ? fieldId : id}\n {...rest}\n type=\"text\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n // The numeric keypad's older cue, for the browsers that predate `inputMode`.\n // The value is digits only, so it can never fail the pattern.\n pattern=\"[0-9]*\"\n // A labelled field's placeholder is a single space: it drives the floating\n // label's `placeholder-shown` trick. Unlabelled, the caller's (\"000000\") shows.\n placeholder={labelled ? \" \" : placeholder}\n value={value}\n readOnly={readOnly || guarding}\n onChange={handleChange}\n onPaste={handlePaste}\n onFocus={handleFocus}\n aria-invalid={invalid || undefined}\n aria-describedby={describedBy}\n className={cn(\n labelled ? FLOATING_INPUT_CLASS : FIELD_BASE,\n CODE_TYPE,\n // Read-only for the guard's sake only: keep the editable look. A caller's\n // own `readOnly` keeps FIELD_BASE's settled grey, as everywhere else.\n guarding && !readOnly && FIELD_WRITABLE_LOOK,\n !labelled && className,\n inputClassName,\n invalid && FIELD_INVALID,\n )}\n />\n );\n\n const field: ReactNode = labelled ? (\n <FloatingField className={className} htmlFor={fieldId} label={label} hint={hintParts.labelHint}>\n {input}\n </FloatingField>\n ) : (\n // No label line to ride: a \"?\" goes at the field's end edge, outside the box —\n // where an unlabelled Select puts it.\n <EndHintRow hint={hintParts.labelHint}>{input}</EndHintRow>\n );\n\n if (hintParts.captionText === undefined && errorEl === null && !reserve) return field;\n return (\n <div>\n {field}\n <FieldCaption parts={hintParts} />\n {errorEl}\n </div>\n );\n}\n"],"mappings":";AA6NI,cA6CA,YA7CA;AA7NJ,SAAS,OAAO,gBAAgB;AAEhC,SAAS,UAAU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,MACb;AAAA;AAAA,EACF;AAGF,QAAM,QAAmB,WACvB,oBAAC,iBAAc,WAAsB,SAAS,SAAS,OAAc,MAAM,UAAU,WAClF,iBACH;AAAA;AAAA;AAAA,IAIA,oBAAC,cAAW,MAAM,UAAU,WAAY,iBAAM;AAAA;AAGhD,MAAI,UAAU,gBAAgB,UAAa,YAAY,QAAQ,CAAC,QAAS,QAAO;AAChF,SACE,qBAAC,SACE;AAAA;AAAA,IACD,oBAAC,gBAAa,OAAO,WAAW;AAAA,IAC/B;AAAA,KACH;AAEJ;","names":["input"]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/one-time-code-input.tsx"],"sourcesContent":["import { useId, useState } from \"react\";\nimport type { ChangeEvent, ClipboardEvent, FocusEvent, InputHTMLAttributes, ReactNode, Ref } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { EndHintRow, FieldCaption, useFieldError, useFieldHint, type FieldHelpProps } from \"./field-parts\";\nimport {\n FIELD_BASE,\n FIELD_INVALID,\n FIELD_WRITABLE_LOOK,\n FLOATING_INPUT_CLASS,\n FloatingField,\n} from \"./field-base\";\n\n/**\n * The field for a verification code — the six digits an authenticator app shows, or the\n * ones a sign-in mail or SMS carries.\n *\n * Asked for by kastlan (input audit, item 3) and keksdose (K8) for the sign-in\n * verification step, and already written twice by hand inside {@link TwoFactorSetting}.\n * The three copies agreed on `inputMode=\"numeric\"` and `autoComplete=\"one-time-code\"`\n * and on nothing else: kastlan's login stripped non-digits and capped at six, keksdose's\n * capped at eight and kept whatever was typed, and the settings card kept everything,\n * spaces included — so \"123 456\" pasted from an authenticator that groups its digits\n * reached the server with the space in it.\n *\n * ONE FIELD, NOT SIX BOXES. The six-box look is the fashionable one, and every part of\n * it works against the two ways a code actually arrives. A paste lands in ONE input,\n * so the boxes need a paste handler that spreads it; the platform's own code autofill\n * (iOS and macOS offer the code from Messages and Mail above the keyboard, Android's\n * keyboards do the same) fills the ONE field marked `one-time-code`, so the boxes need\n * that field to exist anyway, hidden; and a screen reader hears six unlabelled inputs\n * of one character each. One text field gets all three right for free.\n *\n * WHAT IT DOES TO THE TEXT:\n * - **Digits only**, as a STRING. A code may start with 0, and a number field would\n * drop it (\"012345\" → 12345) — kastlan's login says as much in a comment. Every\n * character that is not a digit is dropped as it arrives, so the spaces and dashes\n * of \"123 456\" and \"123-456\" go, whether typed or pasted. Full-width digits (what a\n * Chinese input method types: \"123\") are folded to ASCII first (NFKC).\n * - **No `maxLength` attribute.** The browser applies it BEFORE the change event, so\n * pasting \"123 456\" into a `maxLength={6}` field kept \"123 45\" and the cleaning saw\n * one digit short. The length is enforced here instead, after the cleaning: a field\n * that is full refuses another digit, as `maxLength` would.\n * - **A paste that is a whole code replaces the field**, wherever the caret is: a\n * person pasting six digits means \"this is the code\", not \"insert these into the\n * stale one\".\n * - **The caret stays put** when a character is dropped, rather than jumping to the\n * end as a controlled input does when its value is put back.\n *\n * `onComplete` fires when an edit — a keystroke, a paste, the platform's autofill —\n * makes the code `length` digits long. It is a notification, nothing more: the field\n * never submits a form on its own. Whether a full code verifies at once is the app's\n * call (a sign-in step may; a \"turn off two-factor\" form that also wants a password\n * should not). It does not fire for a value set from outside.\n *\n * `label`, `hint` and `error` read as on every kit field: a floating label, a text hint\n * as a caption under the field (a {@link FieldHint} \"?\" rides the label line instead),\n * the error under that, both attached through `aria-describedby` after the caller's own.\n */\nexport interface OneTimeCodeInputProps\n extends Omit<\n InputHTMLAttributes<HTMLInputElement>,\n \"value\" | \"defaultValue\" | \"onChange\" | \"type\" | \"inputMode\" | \"autoComplete\" | \"maxLength\" | \"pattern\"\n >,\n FieldHelpProps {\n /** The digits so far — a string, so leading zeros survive. */\n value: string;\n /** The cleaned code after every edit: digits only, never longer than `length`. */\n onChange: (code: string) => void;\n /** How many digits the code has. Default 6. The field refuses digits past it. */\n length?: number;\n /** Called with the code when an edit makes it `length` digits long. Never submits\n * anything itself. */\n onComplete?: (code: string) => void;\n /** The floating label, as on {@link Input}. Without one, name the field with\n * `aria-label` or `aria-labelledby` (kastlan's login points it at its prompt). */\n label?: ReactNode;\n /** Plain text: a caption under the field, attached with `aria-describedby`. Anything\n * else (a {@link FieldHint}): on the label line — or at the field's end edge when\n * there is no label. The rule {@link Select}'s `hint` follows. */\n hint?: ReactNode;\n /** What is wrong (\"That code has expired\"). Rendered under the field, attached with\n * `aria-describedby`, and implies `invalid`. */\n error?: ReactNode;\n /** Paint the field invalid and set `aria-invalid` without a message of its own. */\n invalid?: boolean;\n /** Classes for the `<input>`; `className` styles the field's wrapper once it has a\n * label, the `<input>` itself when it has none — as on {@link Input}. */\n inputClassName?: string;\n /**\n * Keep the field `readOnly` until it first takes focus.\n *\n * A browser that has a login saved for the site fills it in on load — and on a page\n * where the code field is the only text field near a password field, it can take the\n * code field for the username and write the address into it. A read-only field is\n * never autofilled, and focus is the moment a person (or the platform's code\n * suggestion, which needs a focused field anyway) starts to use it. So the field\n * stays read-only until then, and only until then.\n *\n * It keeps the LOOK of an editable field throughout ({@link FIELD_WRITABLE_LOOK}):\n * this is the one place where read-only does not mean \"you may not type here\", and\n * without the opt-out the field would sit there greyed until it is clicked.\n *\n * {@link TwoFactorSetting} has always done this — its code fields share a page with\n * the current-password field of the disable form — and keeps doing it through this\n * prop. Off by default, because it is a trade: a field that is read-only at the\n * moment focus lands can be announced as read-only by a screen reader, and on some\n * mobile browsers it does not raise the keyboard until a second tap. Turn it on where\n * a saved login actually lands in the field.\n */\n readOnlyUntilFocus?: boolean;\n /** The `<input>`. A React 19 ref prop since 0.34 (MOD-4, refactor audit 2026-10); it\n * was `forwardRef`. */\n ref?: Ref<HTMLInputElement>;\n}\n\n// Equal-width digits, spaced a little apart, so a code reads — and compares against the\n// authenticator's screen — digit by digit.\nconst CODE_TYPE = \"tabular-nums tracking-widest\";\n\n/** The ASCII digits in `text`, in order. NFKC folds full-width digits (\"1\") to \"1\". */\nfunction digitsOf(text: string): string {\n return text.normalize(\"NFKC\").replace(/\\D/g, \"\");\n}\n\nexport function OneTimeCodeInput(props: OneTimeCodeInputProps) {\n const {\n ref,\n value,\n onChange,\n length = 6,\n onComplete,\n label,\n hint,\n help,\n error,\n invalid: invalidProp,\n className,\n inputClassName,\n readOnlyUntilFocus = false,\n readOnly,\n id,\n placeholder,\n onFocus,\n onPaste,\n \"aria-describedby\": ariaDescribedBy,\n \"aria-invalid\": ariaInvalid,\n ...rest\n } = props;\n // A length below one is no code at all; a fractional one is a typo.\n const size = Math.max(1, Math.floor(length) || 1);\n const generatedId = useId();\n const fieldId = id ?? generatedId;\n // Text is a caption under the field; a FieldHint rides the label line, and is that\n // caption at Large and on touch (§4). See `hint`. Through useFieldHint and\n // useFieldError since 0.34, not copies of their rules (DUP-2, DUP-8).\n const hintParts = useFieldHint(hint, ariaDescribedBy, { help, name: label ?? rest[\"aria-label\"] });\n const {\n isInvalid: invalid,\n describedBy,\n errorEl,\n } = useFieldError(error, invalidProp, hintParts.describedBy, ariaInvalid);\n // Passed at all — even as `undefined` — the field keeps its box, so the `<input>` is\n // never re-parented (and never loses focus) when a message comes or goes. See\n // `FieldGroup` in field-base.tsx.\n const reserve = \"error\" in props || \"hint\" in props;\n const labelled = label !== undefined;\n\n // Focused once = in use; the guard is down for good from then on (see the prop).\n const [focusedOnce, setFocusedOnce] = useState(false);\n const guarding = readOnlyUntilFocus && !focusedOnce;\n\n const commit = (next: string) => {\n if (next === value) return;\n onChange(next);\n if (next.length === size) onComplete?.(next);\n };\n\n const handleChange = (e: ChangeEvent<HTMLInputElement>) => {\n const input = e.currentTarget;\n const raw = input.value;\n const cleaned = digitsOf(raw);\n // Past the length: a full field refuses the digit (what `maxLength` does), a\n // partial one keeps the first `size` — a paste longer than the room left.\n const refused = cleaned.length > size && value.length >= size;\n const next = refused ? value : cleaned.slice(0, size);\n if (next !== raw) {\n // Write the cleaned text back NOW, with the caret where the typist left it.\n // React would otherwise put its value back after this handler, and setting an\n // input's value moves the caret to the end — so a space typed mid-code threw\n // the caret to the last digit. React finds the DOM already agreeing and leaves\n // it alone.\n const caret = input.selectionStart ?? raw.length;\n const at = refused\n ? Math.max(0, caret - (raw.length - value.length))\n : Math.min(digitsOf(raw.slice(0, caret)).length, next.length);\n input.value = next;\n try {\n input.setSelectionRange(at, at);\n } catch {\n /* not every input type has a selection; a text field does */\n }\n }\n commit(next);\n };\n\n const handlePaste = (e: ClipboardEvent<HTMLInputElement>) => {\n onPaste?.(e);\n // A read-only field still receives the event; it must not take the code.\n if (e.defaultPrevented || readOnly || guarding || rest.disabled) return;\n const pasted = digitsOf(e.clipboardData.getData(\"text\"));\n // Anything else — a few digits into a partial code — is an ordinary insertion,\n // and the change handler cleans it.\n if (pasted.length !== size) return;\n e.preventDefault();\n commit(pasted);\n };\n\n const handleFocus = (e: FocusEvent<HTMLInputElement>) => {\n if (guarding) setFocusedOnce(true);\n onFocus?.(e);\n };\n\n const input = (\n <input\n ref={ref}\n id={labelled ? fieldId : id}\n {...rest}\n type=\"text\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n // The numeric keypad's older cue, for the browsers that predate `inputMode`.\n // The value is digits only, so it can never fail the pattern.\n pattern=\"[0-9]*\"\n // A labelled field's placeholder is a single space: it drives the floating\n // label's `placeholder-shown` trick. Unlabelled, the caller's (\"000000\") shows.\n placeholder={labelled ? \" \" : placeholder}\n value={value}\n readOnly={readOnly || guarding}\n onChange={handleChange}\n onPaste={handlePaste}\n onFocus={handleFocus}\n aria-invalid={invalid || undefined}\n aria-describedby={describedBy}\n className={cn(\n labelled ? FLOATING_INPUT_CLASS : FIELD_BASE,\n CODE_TYPE,\n // Read-only for the guard's sake only: keep the editable look. A caller's\n // own `readOnly` keeps FIELD_BASE's settled grey, as everywhere else.\n guarding && !readOnly && FIELD_WRITABLE_LOOK,\n !labelled && className,\n inputClassName,\n invalid && FIELD_INVALID,\n )}\n />\n );\n\n const field: ReactNode = labelled ? (\n <FloatingField className={className} htmlFor={fieldId} label={label} hint={hintParts.labelHint}>\n {input}\n </FloatingField>\n ) : (\n // No label line to ride: a \"?\" goes at the field's end edge, outside the box —\n // where an unlabelled Select puts it.\n <EndHintRow hint={hintParts.labelHint}>{input}</EndHintRow>\n );\n\n if (hintParts.captionText === undefined && errorEl === null && !reserve) return field;\n return (\n <div>\n {field}\n <FieldCaption parts={hintParts} />\n {errorEl}\n </div>\n );\n}\n"],"mappings":";AA+NI,cA6CA,YA7CA;AA/NJ,SAAS,OAAO,gBAAgB;AAEhC,SAAS,UAAU;AACnB,SAAS,YAAY,cAAc,eAAe,oBAAyC;AAC3F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA2GP,MAAM,YAAY;AAGlB,SAAS,SAAS,MAAsB;AACtC,SAAO,KAAK,UAAU,MAAM,EAAE,QAAQ,OAAO,EAAE;AACjD;AAEO,SAAS,iBAAiB,OAA8B;AAC7D,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT;AAAA,IACA;AAAA,IACA,qBAAqB;AAAA,IACrB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,IACpB,gBAAgB;AAAA,IAChB,GAAG;AAAA,EACL,IAAI;AAEJ,QAAM,OAAO,KAAK,IAAI,GAAG,KAAK,MAAM,MAAM,KAAK,CAAC;AAChD,QAAM,cAAc,MAAM;AAC1B,QAAM,UAAU,MAAM;AAItB,QAAM,YAAY,aAAa,MAAM,iBAAiB,EAAE,MAAM,MAAM,SAAS,KAAK,YAAY,EAAE,CAAC;AACjG,QAAM;AAAA,IACJ,WAAW;AAAA,IACX;AAAA,IACA;AAAA,EACF,IAAI,cAAc,OAAO,aAAa,UAAU,aAAa,WAAW;AAIxE,QAAM,UAAU,WAAW,SAAS,UAAU;AAC9C,QAAM,WAAW,UAAU;AAG3B,QAAM,CAAC,aAAa,cAAc,IAAI,SAAS,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AGb,SAAQ;AAAA,MAGR,aAAa,WAAW,MAAM;AAAA,MAC9B;AAAA,MACA,UAAU,YAAY;AAAA,MACtB,UAAU;AAAA,MACV,SAAS;AAAA,MACT,SAAS;AAAA,MACT,gBAAc,WAAW;AAAA,MACzB,oBAAkB;AAAA,MAClB,WAAW;AAAA,QACT,WAAW,uBAAuB;AAAA,QAClC;AAAA;AAAA;AAAA,QAGA,YAAY,CAAC,YAAY;AAAA,QACzB,CAAC,YAAY;AAAA,QACb;AAAA,QACA,WAAW;AAAA,MACb;AAAA;AAAA,EACF;AAGF,QAAM,QAAmB,WACvB,oBAAC,iBAAc,WAAsB,SAAS,SAAS,OAAc,MAAM,UAAU,WAClF,iBACH;AAAA;AAAA;AAAA,IAIA,oBAAC,cAAW,MAAM,UAAU,WAAY,iBAAM;AAAA;AAGhD,MAAI,UAAU,gBAAgB,UAAa,YAAY,QAAQ,CAAC,QAAS,QAAO;AAChF,SACE,qBAAC,SACE;AAAA;AAAA,IACD,oBAAC,gBAAa,OAAO,WAAW;AAAA,IAC/B;AAAA,KACH;AAEJ;","names":["input"]}
|
|
@@ -72,4 +72,4 @@ export interface PhoneInputProps extends Omit<InputProps, "type" | "value" | "de
|
|
|
72
72
|
* the number with `aria-describedby`. The select is named by `labels.countryCode`, and
|
|
73
73
|
* the pair is a group named by a string `label`.
|
|
74
74
|
*/
|
|
75
|
-
export declare function PhoneInput({ ref, value, onValueChange, onChange, onBlur, defaultCountry, countries, labels, className, inputClassName, label, hint, error, invalid, disabled, "aria-describedby": ariaDescribedBy, ...rest }: PhoneInputProps): import("react").JSX.Element;
|
|
75
|
+
export declare function PhoneInput({ ref, value, onValueChange, onChange, onBlur, defaultCountry, countries, labels, className, inputClassName, label, hint, help, error, invalid, disabled, "aria-describedby": ariaDescribedBy, ...rest }: PhoneInputProps): import("react").JSX.Element;
|
|
@@ -50,6 +50,7 @@ function PhoneInput({
|
|
|
50
50
|
inputClassName,
|
|
51
51
|
label,
|
|
52
52
|
hint,
|
|
53
|
+
help,
|
|
53
54
|
error,
|
|
54
55
|
invalid,
|
|
55
56
|
disabled,
|
|
@@ -105,6 +106,9 @@ function PhoneInput({
|
|
|
105
106
|
if (country !== "other" && !options.includes(country)) options.push(country);
|
|
106
107
|
const messages = useFieldMessages({
|
|
107
108
|
hint,
|
|
109
|
+
// The number's label line takes the help's "?" (0.36); the hint is then the caption.
|
|
110
|
+
help,
|
|
111
|
+
name: label ?? rest["aria-label"],
|
|
108
112
|
error,
|
|
109
113
|
invalid,
|
|
110
114
|
describedBy: ariaDescribedBy,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/phone-input.tsx"],"sourcesContent":["import { useState } from \"react\";\nimport type { ChangeEvent, FocusEvent } from \"react\";\nimport { useKitLabels, type LabelOverride } from \"../i18n/kit-labels\";\nimport { cn } from \"../lib/cn\";\nimport {\n PHONE_COUNTRIES,\n PHONE_DIAL_CODES,\n formatNationalPhone,\n formatPhone,\n isE164,\n parsePhone,\n} from \"../lib/phone\";\nimport type { ParsedPhone, PhoneCountry, PhoneCountryCode } from \"../lib/phone\";\nimport { useFieldMessages } from \"./field-parts\";\nimport { Input, type InputProps } from \"./input\";\nimport { Select } from \"./select\";\nimport { DEFAULT_PHONE_INPUT_LABELS } from \"./phone-input-labels\";\n\n// ── Labels ────────────────────────────────────────────────────────────────────\n\n/** The words {@link PhoneInput} renders on its own behalf. */\nexport interface PhoneInputLabels {\n /** The country-code select's accessible name. */\n countryCode: string;\n /** The select's last option: a number from a country not listed, typed with its\n * own \"+\". */\n other: string;\n}\n\n// Defined in ./phone-input-labels, which holds no component code (0.34, KS U8).\nexport { DEFAULT_PHONE_INPUT_LABELS };\n\n/**\n * The `phoneInput` namespace: prop > `<UiKitProvider labels>` > English (0.22.0).\n */\nfunction usePhoneInputLabels(prop: Partial<PhoneInputLabels> | undefined): PhoneInputLabels {\n const labels: PhoneInputLabels = useKitLabels(\"phoneInput\", DEFAULT_PHONE_INPUT_LABELS, prop);\n return labels;\n}\n\n// ── Helpers ───────────────────────────────────────────────────────────────────\n\n/** A stored value read back: an E.164 number these rules can read, else `null`. */\nfunction storedNumber(value: string): ParsedPhone | null {\n return isE164(value) ? parsePhone(value, \"other\") : null;\n}\n\n/** The select's country for a stored E.164 value, or `null` for free text. */\nfunction countryOf(value: string): PhoneCountry | null {\n const parsed = storedNumber(value);\n return parsed ? (parsed.country ?? \"other\") : null;\n}\n\n/** What the field emits for typed text: E.164 when it reads, the text unchanged when\n * it does not. */\nfunction emitFor(raw: string, country: PhoneCountry): string {\n return parsePhone(raw, country)?.e164 ?? raw;\n}\n\n/**\n * The text a stored value shows, outside of typing. Under its own country: the national\n * number grouped (\"21 000 00 01\" beside \"CH +41\"). Under another (a \"+33\" number while\n * the select says \"Other\"): the whole international number. Free text: as it is.\n */\nfunction displayOf(value: string, country: PhoneCountry): string {\n const parsed = storedNumber(value);\n if (!parsed) return value;\n if (parsed.country !== null && parsed.country === country) {\n return formatNationalPhone(parsed.national, parsed.country);\n }\n return formatPhone(parsed.e164);\n}\n\n// ── Component ─────────────────────────────────────────────────────────────────\n\nexport interface PhoneInputProps extends Omit<InputProps, \"type\" | \"value\" | \"defaultValue\"> {\n /** The number: E.164 (\"+41210000001\") for one the field could read, or free text —\n * a value saved before the field existed is shown exactly as it is. `\"\"` is no\n * number. */\n value: string;\n /** On every change: E.164 when the typed text reads as a number of the selected\n * country (or carries its own \"+\"), otherwise the typed text UNCHANGED. Nothing is\n * refused — see {@link PhoneInput}. Plain `onChange` still fires with the raw event;\n * bind this one to a form. */\n onValueChange?: (value: string) => void;\n /** The country a number typed without \"+\" belongs to, until the value says\n * otherwise. Default `\"CH\"`. */\n defaultCountry?: PhoneCountry;\n /** The countries the select offers, in order; \"Other\" always follows. Default\n * {@link PHONE_COUNTRIES} (CH, LI, DE, AT, FR, IT). A stored number from a country\n * left out still shows under its own code. */\n countries?: readonly PhoneCountryCode[];\n /** See {@link PhoneInputLabels}. */\n labels?: LabelOverride<PhoneInputLabels>;\n /** Classes for the whole field — the select, the input and the lines under them.\n * `inputClassName` reaches the `<input>`. */\n className?: string;\n}\n\n/**\n * A phone number field (kastlan): a country-code select and the number, stored as\n * E.164 and shown grouped.\n *\n * kastlan's contacts kept whatever was typed — \"079 …\", \"+41 (0)79 …\", \"0041 79 …\" —\n * which nobody could dial from the app or match against the next import. This field\n * turns all of those into one stored form, \"+41210000001\", without taking anything\n * away from the person typing:\n *\n * - **A country to type against.** The select (default CH, then LI, DE, AT, FR, IT\n * and \"Other\") says which country a number without \"+\" belongs to; the national\n * trunk 0 may be typed or left out. Typing a \"+\" or \"00\" overrides it, and the\n * select follows the number (\"+49 …\" switches it to DE). Changing the select moves\n * the national number to the new country code.\n * - **E.164 when it reads, the text when it does not.** A number the rules read is\n * emitted as E.164; anything else (\"ask reception\", an extension) is emitted exactly\n * as typed. Never refused, never an error of its own: a contact's number is often\n * known only roughly, and a field that will not save \"079 … (mornings)\" makes\n * people type it into the notes instead. An app that needs a dialable number\n * checks {@link isE164} on submit.\n * - **Existing values untouched.** A free-text value from before is shown exactly as\n * it is, and normalised only when someone edits it — the field never rewrites a\n * record just by being opened.\n * - **Grouped when settled.** While typing the field shows what was typed; on blur a\n * number it read is regrouped by its country (\"21 000 00 01\").\n *\n * **The limitation** — there is no libphonenumber behind this (≈150 kB of metadata in\n * every bundle): the six countries have light rules (the trunk 0, a plausible length)\n * and every other country is any \"+\" with 8–15 digits. A well-formed number that does\n * not exist passes, and German and Austrian landlines, whose area codes vary in length,\n * are grouped only where the split is known (mobile prefixes, the largest cities) and\n * otherwise shown as one block. See `lib/phone.ts`.\n *\n * `label`, `hint`, `error` and `invalid` read as on {@link Input}: the label floats in\n * the number's box, and a text hint and the error go under the whole row, attached to\n * the number with `aria-describedby`. The select is named by `labels.countryCode`, and\n * the pair is a group named by a string `label`.\n */\nexport function PhoneInput({\n ref,\n value,\n onValueChange,\n onChange,\n onBlur,\n defaultCountry = \"CH\",\n countries = PHONE_COUNTRIES,\n labels,\n className,\n inputClassName,\n label,\n hint,\n error,\n invalid,\n disabled,\n \"aria-describedby\": ariaDescribedBy,\n ...rest\n}: PhoneInputProps) {\n const text = usePhoneInputLabels(labels);\n const [country, setCountry] = useState<PhoneCountry>(() => countryOf(value) ?? defaultCountry);\n // What was typed, shown for as long as it still reads as the value (AmountInput's\n // draft): the person's own spacing stays under their fingers, and is regrouped on\n // blur.\n const [draft, setDraft] = useState<string | null>(null);\n // The last value this field emitted, to tell its own echo from a value set outside.\n const [emitted, setEmitted] = useState<string | null>(null);\n const [seen, setSeen] = useState(value);\n if (seen !== value) {\n setSeen(value);\n if (value !== emitted) {\n // Set from outside (a reset, another record): its own country, none of our text.\n const own = countryOf(value);\n if (own) setCountry(own);\n setDraft(null);\n }\n }\n\n const emit = (next: string) => {\n setEmitted(next);\n onValueChange?.(next);\n };\n\n const handleChange = (e: ChangeEvent<HTMLInputElement>) => {\n onChange?.(e);\n const raw = e.target.value;\n setDraft(raw);\n const parsed = parsePhone(raw, country);\n // A number typed with its own \"+\" takes the select with it.\n if (parsed && parsed.country !== country) setCountry(parsed.country ?? \"other\");\n emit(parsed?.e164 ?? raw);\n };\n\n const handleCountry = (next: PhoneCountry) => {\n setCountry(next);\n const stored = storedNumber(value);\n if (stored) {\n // \"Other\", the same country, or a generic number with its own \"+\": the number\n // stays, only the way it is shown changes.\n if (next === \"other\" || stored.country === null || stored.country === next) {\n setDraft(null);\n return;\n }\n // A different listed country: the national number moves to its code. If it does\n // not read there, the digits are kept as text for the person to finish.\n emit(parsePhone(stored.national, next)?.e164 ?? stored.national);\n setDraft(null);\n return;\n }\n // Free text (or a draft): read it again under the new country.\n const source = draft ?? value;\n const parsed = source.trim() === \"\" ? null : parsePhone(source, next);\n if (parsed && parsed.e164 !== value) {\n setDraft(source);\n emit(parsed.e164);\n }\n };\n\n const display = draft !== null && emitFor(draft, country) === value ? draft : displayOf(value, country);\n\n // The select offers the configured countries, plus the stored number's own if it\n // is not among them — a select cannot show a value it has no option for.\n const options: PhoneCountryCode[] = [...countries];\n if (country !== \"other\" && !options.includes(country)) options.push(country);\n\n // A FieldHint \"?\" rides the number's label line; text — and a FieldHint at Large and\n // on touch (§4) — goes under the whole row with the error. Through useFieldMessages\n // since 0.34, not a copy of its rule (DUP-2, DUP-8).\n const messages = useFieldMessages({\n hint,\n error,\n invalid,\n describedBy: ariaDescribedBy,\n ariaInvalid: rest[\"aria-invalid\"],\n });\n const named = typeof label === \"string\" && label !== \"\";\n\n return (\n <div\n className={className}\n role={named ? \"group\" : undefined}\n aria-label={named ? label : undefined}\n >\n {/* On a phone at Large the number takes a line of its own under the country (0.32.1,\n the 360 px Extra-large sweep; docs/text-size-harmonization.md §4 \"nothing\n truncates\"): the 7rem select is 168 px at 150 %, and on a 360 px phone it left\n the number 82 px — \"Ph…\" over \"021 (\". `large:max-sm:`, the scaled phone width,\n so a wider screen at Large and Normal keep the one row. */}\n <div className=\"flex items-stretch gap-2 large:max-sm:flex-wrap\">\n <Select\n aria-label={text.countryCode}\n value={country}\n disabled={disabled}\n onChange={(e) => handleCountry(e.target.value as PhoneCountry)}\n className=\"w-28 shrink-0\"\n // Stretched to the number's height: a labelled field is taller than an\n // unlabelled select, and the pair should read as one row.\n selectClassName=\"h-full tabular-nums\"\n >\n {options.map((code) => (\n <option key={code} value={code}>\n {`${code} +${PHONE_DIAL_CODES[code]}`}\n </option>\n ))}\n <option value=\"other\">{text.other}</option>\n </Select>\n {/* Its own flex item, so nothing Input wraps itself in can take the sizing. */}\n <div className=\"min-w-0 flex-1 large:max-sm:basis-full\">\n <Input\n ref={ref}\n {...rest}\n type=\"tel\"\n autoComplete={rest.autoComplete ?? \"tel\"}\n label={label}\n hint={messages.labelHint}\n invalid={messages.isInvalid}\n aria-describedby={messages.describedBy}\n disabled={disabled}\n value={display}\n onChange={handleChange}\n onBlur={(e: FocusEvent<HTMLInputElement>) => {\n setDraft(null);\n onBlur?.(e);\n }}\n inputClassName={cn(\"tabular-nums\", inputClassName)}\n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AA;AAAA;AAAA,EACZ;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/phone-input.tsx"],"sourcesContent":["import { useState } from \"react\";\nimport type { ChangeEvent, FocusEvent } from \"react\";\nimport { useKitLabels, type LabelOverride } from \"../i18n/kit-labels\";\nimport { cn } from \"../lib/cn\";\nimport {\n PHONE_COUNTRIES,\n PHONE_DIAL_CODES,\n formatNationalPhone,\n formatPhone,\n isE164,\n parsePhone,\n} from \"../lib/phone\";\nimport type { ParsedPhone, PhoneCountry, PhoneCountryCode } from \"../lib/phone\";\nimport { useFieldMessages } from \"./field-parts\";\nimport { Input, type InputProps } from \"./input\";\nimport { Select } from \"./select\";\nimport { DEFAULT_PHONE_INPUT_LABELS } from \"./phone-input-labels\";\n\n// ── Labels ────────────────────────────────────────────────────────────────────\n\n/** The words {@link PhoneInput} renders on its own behalf. */\nexport interface PhoneInputLabels {\n /** The country-code select's accessible name. */\n countryCode: string;\n /** The select's last option: a number from a country not listed, typed with its\n * own \"+\". */\n other: string;\n}\n\n// Defined in ./phone-input-labels, which holds no component code (0.34, KS U8).\nexport { DEFAULT_PHONE_INPUT_LABELS };\n\n/**\n * The `phoneInput` namespace: prop > `<UiKitProvider labels>` > English (0.22.0).\n */\nfunction usePhoneInputLabels(prop: Partial<PhoneInputLabels> | undefined): PhoneInputLabels {\n const labels: PhoneInputLabels = useKitLabels(\"phoneInput\", DEFAULT_PHONE_INPUT_LABELS, prop);\n return labels;\n}\n\n// ── Helpers ───────────────────────────────────────────────────────────────────\n\n/** A stored value read back: an E.164 number these rules can read, else `null`. */\nfunction storedNumber(value: string): ParsedPhone | null {\n return isE164(value) ? parsePhone(value, \"other\") : null;\n}\n\n/** The select's country for a stored E.164 value, or `null` for free text. */\nfunction countryOf(value: string): PhoneCountry | null {\n const parsed = storedNumber(value);\n return parsed ? (parsed.country ?? \"other\") : null;\n}\n\n/** What the field emits for typed text: E.164 when it reads, the text unchanged when\n * it does not. */\nfunction emitFor(raw: string, country: PhoneCountry): string {\n return parsePhone(raw, country)?.e164 ?? raw;\n}\n\n/**\n * The text a stored value shows, outside of typing. Under its own country: the national\n * number grouped (\"21 000 00 01\" beside \"CH +41\"). Under another (a \"+33\" number while\n * the select says \"Other\"): the whole international number. Free text: as it is.\n */\nfunction displayOf(value: string, country: PhoneCountry): string {\n const parsed = storedNumber(value);\n if (!parsed) return value;\n if (parsed.country !== null && parsed.country === country) {\n return formatNationalPhone(parsed.national, parsed.country);\n }\n return formatPhone(parsed.e164);\n}\n\n// ── Component ─────────────────────────────────────────────────────────────────\n\nexport interface PhoneInputProps extends Omit<InputProps, \"type\" | \"value\" | \"defaultValue\"> {\n /** The number: E.164 (\"+41210000001\") for one the field could read, or free text —\n * a value saved before the field existed is shown exactly as it is. `\"\"` is no\n * number. */\n value: string;\n /** On every change: E.164 when the typed text reads as a number of the selected\n * country (or carries its own \"+\"), otherwise the typed text UNCHANGED. Nothing is\n * refused — see {@link PhoneInput}. Plain `onChange` still fires with the raw event;\n * bind this one to a form. */\n onValueChange?: (value: string) => void;\n /** The country a number typed without \"+\" belongs to, until the value says\n * otherwise. Default `\"CH\"`. */\n defaultCountry?: PhoneCountry;\n /** The countries the select offers, in order; \"Other\" always follows. Default\n * {@link PHONE_COUNTRIES} (CH, LI, DE, AT, FR, IT). A stored number from a country\n * left out still shows under its own code. */\n countries?: readonly PhoneCountryCode[];\n /** See {@link PhoneInputLabels}. */\n labels?: LabelOverride<PhoneInputLabels>;\n /** Classes for the whole field — the select, the input and the lines under them.\n * `inputClassName` reaches the `<input>`. */\n className?: string;\n}\n\n/**\n * A phone number field (kastlan): a country-code select and the number, stored as\n * E.164 and shown grouped.\n *\n * kastlan's contacts kept whatever was typed — \"079 …\", \"+41 (0)79 …\", \"0041 79 …\" —\n * which nobody could dial from the app or match against the next import. This field\n * turns all of those into one stored form, \"+41210000001\", without taking anything\n * away from the person typing:\n *\n * - **A country to type against.** The select (default CH, then LI, DE, AT, FR, IT\n * and \"Other\") says which country a number without \"+\" belongs to; the national\n * trunk 0 may be typed or left out. Typing a \"+\" or \"00\" overrides it, and the\n * select follows the number (\"+49 …\" switches it to DE). Changing the select moves\n * the national number to the new country code.\n * - **E.164 when it reads, the text when it does not.** A number the rules read is\n * emitted as E.164; anything else (\"ask reception\", an extension) is emitted exactly\n * as typed. Never refused, never an error of its own: a contact's number is often\n * known only roughly, and a field that will not save \"079 … (mornings)\" makes\n * people type it into the notes instead. An app that needs a dialable number\n * checks {@link isE164} on submit.\n * - **Existing values untouched.** A free-text value from before is shown exactly as\n * it is, and normalised only when someone edits it — the field never rewrites a\n * record just by being opened.\n * - **Grouped when settled.** While typing the field shows what was typed; on blur a\n * number it read is regrouped by its country (\"21 000 00 01\").\n *\n * **The limitation** — there is no libphonenumber behind this (≈150 kB of metadata in\n * every bundle): the six countries have light rules (the trunk 0, a plausible length)\n * and every other country is any \"+\" with 8–15 digits. A well-formed number that does\n * not exist passes, and German and Austrian landlines, whose area codes vary in length,\n * are grouped only where the split is known (mobile prefixes, the largest cities) and\n * otherwise shown as one block. See `lib/phone.ts`.\n *\n * `label`, `hint`, `error` and `invalid` read as on {@link Input}: the label floats in\n * the number's box, and a text hint and the error go under the whole row, attached to\n * the number with `aria-describedby`. The select is named by `labels.countryCode`, and\n * the pair is a group named by a string `label`.\n */\nexport function PhoneInput({\n ref,\n value,\n onValueChange,\n onChange,\n onBlur,\n defaultCountry = \"CH\",\n countries = PHONE_COUNTRIES,\n labels,\n className,\n inputClassName,\n label,\n hint,\n help,\n error,\n invalid,\n disabled,\n \"aria-describedby\": ariaDescribedBy,\n ...rest\n}: PhoneInputProps) {\n const text = usePhoneInputLabels(labels);\n const [country, setCountry] = useState<PhoneCountry>(() => countryOf(value) ?? defaultCountry);\n // What was typed, shown for as long as it still reads as the value (AmountInput's\n // draft): the person's own spacing stays under their fingers, and is regrouped on\n // blur.\n const [draft, setDraft] = useState<string | null>(null);\n // The last value this field emitted, to tell its own echo from a value set outside.\n const [emitted, setEmitted] = useState<string | null>(null);\n const [seen, setSeen] = useState(value);\n if (seen !== value) {\n setSeen(value);\n if (value !== emitted) {\n // Set from outside (a reset, another record): its own country, none of our text.\n const own = countryOf(value);\n if (own) setCountry(own);\n setDraft(null);\n }\n }\n\n const emit = (next: string) => {\n setEmitted(next);\n onValueChange?.(next);\n };\n\n const handleChange = (e: ChangeEvent<HTMLInputElement>) => {\n onChange?.(e);\n const raw = e.target.value;\n setDraft(raw);\n const parsed = parsePhone(raw, country);\n // A number typed with its own \"+\" takes the select with it.\n if (parsed && parsed.country !== country) setCountry(parsed.country ?? \"other\");\n emit(parsed?.e164 ?? raw);\n };\n\n const handleCountry = (next: PhoneCountry) => {\n setCountry(next);\n const stored = storedNumber(value);\n if (stored) {\n // \"Other\", the same country, or a generic number with its own \"+\": the number\n // stays, only the way it is shown changes.\n if (next === \"other\" || stored.country === null || stored.country === next) {\n setDraft(null);\n return;\n }\n // A different listed country: the national number moves to its code. If it does\n // not read there, the digits are kept as text for the person to finish.\n emit(parsePhone(stored.national, next)?.e164 ?? stored.national);\n setDraft(null);\n return;\n }\n // Free text (or a draft): read it again under the new country.\n const source = draft ?? value;\n const parsed = source.trim() === \"\" ? null : parsePhone(source, next);\n if (parsed && parsed.e164 !== value) {\n setDraft(source);\n emit(parsed.e164);\n }\n };\n\n const display = draft !== null && emitFor(draft, country) === value ? draft : displayOf(value, country);\n\n // The select offers the configured countries, plus the stored number's own if it\n // is not among them — a select cannot show a value it has no option for.\n const options: PhoneCountryCode[] = [...countries];\n if (country !== \"other\" && !options.includes(country)) options.push(country);\n\n // A FieldHint \"?\" rides the number's label line; text — and a FieldHint at Large and\n // on touch (§4) — goes under the whole row with the error. Through useFieldMessages\n // since 0.34, not a copy of its rule (DUP-2, DUP-8).\n const messages = useFieldMessages({\n hint,\n // The number's label line takes the help's \"?\" (0.36); the hint is then the caption.\n help,\n name: label ?? rest[\"aria-label\"],\n error,\n invalid,\n describedBy: ariaDescribedBy,\n ariaInvalid: rest[\"aria-invalid\"],\n });\n const named = typeof label === \"string\" && label !== \"\";\n\n return (\n <div\n className={className}\n role={named ? \"group\" : undefined}\n aria-label={named ? label : undefined}\n >\n {/* On a phone at Large the number takes a line of its own under the country (0.32.1,\n the 360 px Extra-large sweep; docs/text-size-harmonization.md §4 \"nothing\n truncates\"): the 7rem select is 168 px at 150 %, and on a 360 px phone it left\n the number 82 px — \"Ph…\" over \"021 (\". `large:max-sm:`, the scaled phone width,\n so a wider screen at Large and Normal keep the one row. */}\n <div className=\"flex items-stretch gap-2 large:max-sm:flex-wrap\">\n <Select\n aria-label={text.countryCode}\n value={country}\n disabled={disabled}\n onChange={(e) => handleCountry(e.target.value as PhoneCountry)}\n className=\"w-28 shrink-0\"\n // Stretched to the number's height: a labelled field is taller than an\n // unlabelled select, and the pair should read as one row.\n selectClassName=\"h-full tabular-nums\"\n >\n {options.map((code) => (\n <option key={code} value={code}>\n {`${code} +${PHONE_DIAL_CODES[code]}`}\n </option>\n ))}\n <option value=\"other\">{text.other}</option>\n </Select>\n {/* Its own flex item, so nothing Input wraps itself in can take the sizing. */}\n <div className=\"min-w-0 flex-1 large:max-sm:basis-full\">\n <Input\n ref={ref}\n {...rest}\n type=\"tel\"\n autoComplete={rest.autoComplete ?? \"tel\"}\n label={label}\n hint={messages.labelHint}\n invalid={messages.isInvalid}\n aria-describedby={messages.describedBy}\n disabled={disabled}\n value={display}\n onChange={handleChange}\n onBlur={(e: FocusEvent<HTMLInputElement>) => {\n setDraft(null);\n onBlur?.(e);\n }}\n inputClassName={cn(\"tabular-nums\", inputClassName)}\n />\n </div>\n </div>\n {messages.below}\n </div>\n );\n}\n"],"mappings":";AA0PQ,SAWI,KAXJ;AA1PR,SAAS,gBAAgB;AAEzB,SAAS,oBAAwC;AACjD,SAAS,UAAU;AACnB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,wBAAwB;AACjC,SAAS,aAA8B;AACvC,SAA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b,aAAa,KAAK,cAAc;AAAA,EAClC,CAAC;AACD,QAAM,QAAQ,OAAO,UAAU,YAAY,UAAU;AAErD,SACE;AAAA,IAAC;AAAA;AAAA,MACC;AAAA,MACA,MAAM,QAAQ,UAAU;AAAA,MACxB,cAAY,QAAQ,QAAQ;AAAA,MAO5B;AAAA,6BAAC,SAAI,WAAU,mDACb;AAAA;AAAA,YAAC;AAAA;AAAA,cACC,cAAY,KAAK;AAAA,cACjB,OAAO;AAAA,cACP;AAAA,cACA,UAAU,CAAC,MAAM,cAAc,EAAE,OAAO,KAAqB;AAAA,cAC7D,WAAU;AAAA,cAGV,iBAAgB;AAAA,cAEf;AAAA,wBAAQ,IAAI,CAAC,SACZ,oBAAC,YAAkB,OAAO,MACvB,aAAG,IAAI,KAAK,iBAAiB,IAAI,CAAC,MADxB,IAEb,CACD;AAAA,gBACD,oBAAC,YAAO,OAAM,SAAS,eAAK,OAAM;AAAA;AAAA;AAAA,UACpC;AAAA,UAEA,oBAAC,SAAI,WAAU,0CACb;AAAA,YAAC;AAAA;AAAA,cACC;AAAA,cACC,GAAG;AAAA,cACJ,MAAK;AAAA,cACL,cAAc,KAAK,gBAAgB;AAAA,cACnC;AAAA,cACA,MAAM,SAAS;AAAA,cACf,SAAS,SAAS;AAAA,cAClB,oBAAkB,SAAS;AAAA,cAC3B;AAAA,cACA,OAAO;AAAA,cACP,UAAU;AAAA,cACV,QAAQ,CAAC,MAAoC;AAC3C,yBAAS,IAAI;AACb,yBAAS,CAAC;AAAA,cACZ;AAAA,cACA,gBAAgB,GAAG,gBAAgB,cAAc;AAAA;AAAA,UACnD,GACF;AAAA,WACF;AAAA,QACC,SAAS;AAAA;AAAA;AAAA,EACZ;AAEJ;","names":[]}
|
|
@@ -10,7 +10,7 @@ import { cn } from "../lib/cn.js";
|
|
|
10
10
|
import { dirOf } from "../lib/direction.js";
|
|
11
11
|
import { useKitLabels } from "../i18n/kit-labels.js";
|
|
12
12
|
import { DEFAULT_POPOVER_LABELS } from "./popover-labels.js";
|
|
13
|
-
import { mergeRefs } from "
|
|
13
|
+
import { mergeRefs } from "../lib/refs.js";
|
|
14
14
|
const POPOVER_WIDTH = "18rem";
|
|
15
15
|
const EDGE = 8;
|
|
16
16
|
function Popover({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/popover.tsx"],"sourcesContent":["import { useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithoutRef, KeyboardEvent, ReactNode, Ref, RefObject } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { anchoredInline, useAnchoredPanel, viewportSize } from \"../hooks/use-anchored-panel\";\nimport { runOwnKeyDown, takeEscape, useDismissLayer, useOutsideClick } from \"../hooks/use-dismiss\";\nimport { useFocusTrap } from \"../hooks/use-focus-trap\";\nimport { lengthPx, useRemPx, type RemLength } from \"../hooks/use-breakpoint\";\nimport { cn } from \"../lib/cn\";\nimport { dirOf } from \"../lib/direction\";\nimport type { Direction } from \"../lib/direction\";\nimport { useKitLabels, type LabelOverride } from \"../i18n/kit-labels\";\nimport { DEFAULT_POPOVER_LABELS } from \"./popover-labels\";\nimport { mergeRefs } from \"./field-parts\";\n\n/** The panel's accessible name. A `role=\"dialog\"` with no name announces as \"dialog\"\n * and nothing else, which is worse than the unlabelled div it replaced — so it is a\n * prop with an English default, like every other string this package renders. Callers\n * should pass the control's own name (\"Filter\", \"Choose a date\"); the default is only\n * there so an unmigrated call site is still named. */\nexport interface PopoverLabels {\n panel: string;\n}\n\n// Defined in ./popover-labels, which holds no component code (0.34, KS U8).\nexport { DEFAULT_POPOVER_LABELS };\n\n/**\n * Exported, and extending the `<div>` attributes, so a consumer wrapping this — which is\n * what `DateField` and `FilterPopover` in this very package do — can hand anything\n * through to the PANEL: a `data-tour` anchor for the kit's own guided tour, a test id,\n * an `aria-describedby`, or an `aria-label` naming this particular popover.\n *\n * `children` is omitted from those attributes rather than inherited: here it is a render\n * prop taking the panel's `close`, not a `ReactNode`, so the two cannot be reconciled.\n */\nexport interface PopoverProps extends Omit<ComponentPropsWithoutRef<\"div\">, \"children\"> {\n trigger: (state: { open: boolean; toggle: () => void; ref: RefObject<HTMLButtonElement | null> }) => ReactNode;\n children: (close: () => void) => ReactNode;\n /**\n * The panel's width: `\"18rem\"` (the default) grows with the text size — the panel\n * holds text, and a 288 px calendar at 150 % cut its own month off (0.32,\n * docs/text-size-harmonization.md §3.2). A plain number is px, fixed, as before.\n * Either way the panel is never wider than the viewport less 8 px a side: 18rem is\n * 432 px at Extra large, more than a 360 px phone has.\n */\n width?: number | RemLength;\n labels?: LabelOverride<PopoverLabels>;\n /** Id for the panel, so a trigger wearing `role=\"combobox\"` can `aria-controls` it.\n * Required by ARIA on that role, and the panel is rendered here rather than by the\n * caller, so the id has to come in from outside. */\n panelId?: string;\n /** Extra classes for the PANEL. The trigger is the caller's own element. */\n className?: string;\n /** The PANEL, while it is open — where the rest of the props go (0.34, API-2, refactor\n * audit 2026-10). Merged with the panel's own ref (focus trap, outside click), so\n * neither loses it. The trigger is the caller's own element, ref and all. */\n ref?: Ref<HTMLDivElement>;\n}\n\n/** 288 px at Normal, in rem so it follows the text size (§3.2). */\nconst POPOVER_WIDTH: RemLength = \"18rem\";\n\n/** The gap the panel keeps from either edge of the viewport, in px. */\nconst EDGE = 8;\n\n/**\n * Portal-rendered popover anchored under its trigger button. The panel is fixed\n * to the viewport (so table/overflow ancestors can't clip it) and re-aligns on\n * scroll/resize; it closes on outside-click and Escape.\n *\n * ## Trapped, not merely focused — and why, because it is the closer call\n *\n * The audit's finding was that this panel *\"portals out of the tab order with no role\n * and no focus move\"*: Tab from the trigger went straight past the panel into the page\n * behind it, so the calendar, the calculator keypad and every column filter in the kit\n * were mouse-only. Two shapes fix that, and a popover is not automatically a dialog, so\n * this was chosen rather than inherited:\n *\n * - **The light one** — move focus in on open, hand it back on close, and let Tab walk\n * OUT of the panel into whatever follows the trigger. That is the right shape for a\n * non-modal popover sitting inline in the document.\n * - **The trap** — Tab cycles inside the panel; Escape and a click outside are the\n * ways out. What is here.\n *\n * The deciding fact is the portal. This panel is rendered to the END of `<body>`, not\n * beside its trigger, so \"let Tab walk out\" does not mean \"carry on from the trigger\" —\n * it means land at the end of the document, several hundred controls from where the\n * user was. Tabbing out of it would be a worse place to arrive than the one the finding\n * complains about, and fixing that properly needs a sentinel-and-return dance that\n * nothing in this package has. The trap gets the user back to the trigger every time,\n * because `useFocusTrap` restores focus on close.\n *\n * And the panels this kit actually opens are self-contained: pick a date, tap out a\n * sum, narrow a column. Each of them commits and closes, and each already has two\n * documented ways out wired above — Escape and an outside press — so containment costs\n * a keyboard user nothing they had.\n *\n * **It stays non-modal in every other respect**, deliberately: no backdrop, no body\n * scroll lock, and no `aria-modal`, so the page behind is still readable by a screen\n * reader, still scrollable, and still clickable — clicking it is what dismisses this.\n * Only Tab is contained. A popover that took the page away as well would be a\n * {@link Modal}, and there is one of those.\n */\nexport function Popover({\n trigger,\n children,\n width = POPOVER_WIDTH,\n labels,\n panelId,\n className,\n style,\n \"aria-label\": ariaLabel,\n onKeyDown: onKeyDownProp,\n ref,\n ...rest\n}: PopoverProps) {\n const triggerRef = useRef<HTMLButtonElement>(null);\n const panelRef = useRef<HTMLDivElement>(null);\n const setPanel = useMemo(() => mergeRefs(panelRef, ref), [ref]);\n const [open, setOpen] = useState(false);\n // The trigger's reading direction, read when it is pressed. The panel is portalled to\n // <body>, out of any `dir=\"rtl\"` subtree the trigger sits in, so without carrying it\n // across a right-to-left calendar or filter rendered left-to-right.\n const [dir, setDir] = useState<Direction>(\"ltr\");\n const close = () => setOpen(false);\n const toggle = () => {\n setDir(dirOf(triggerRef.current));\n setOpen((v) => !v);\n };\n // prop > `<UiKitProvider labels={{ popover }}>` > English. The provider's\n // `popover.panel` is only the last-resort name for a panel no caller named.\n const text = useKitLabels(\"popover\", DEFAULT_POPOVER_LABELS, labels);\n\n // Align the panel's END edge to the trigger's — right in LTR, left in RTL; it was\n // always `rect.right`, so an RTL panel hung off the wrong side — and clamp it\n // horizontally; the\n // hook owns the vertical half — below by default, flipped above (and height-capped)\n // when that is where the room is, e.g. once a mobile keyboard has eaten the bottom\n // of the screen (feedback #135). It re-measures on scroll/resize.\n const placement = useAnchoredPanel(triggerRef, open);\n const rect = placement.rect;\n // In px for the arithmetic below, at the text size in force; capped at the glass — the\n // root's client width, not `innerWidth`, which on a phone is the layout viewport grown\n // by whatever overflows (live #381, Wave 2 DUP-7).\n const remPx = useRemPx();\n const glass = rect ? viewportSize().width : 0;\n const panelWidth = rect ? Math.min(lengthPx(width, remPx), Math.max(0, glass - 2 * EDGE)) : 0;\n const pos = rect\n ? {\n // Flipped above, the panel hangs from its bottom edge, so one shorter than its\n // cap still meets the trigger (keksdose K1); the edge not in use is cleared.\n top: placement.above ? undefined : placement.top,\n bottom: placement.above ? placement.bottom : undefined,\n left: anchoredInline(rect, panelWidth, { dir, align: \"end\", edge: EDGE, viewportWidth: glass }).left,\n }\n : null;\n\n useOutsideClick([triggerRef, panelRef], close, open);\n // A layer on the Escape stack while open (Wave 2, DUP-1): a list opened inside closes\n // first, and the dialog this popover sits in only after it — the calculator on an\n // amount field in a Modal is exactly that.\n const layer = useDismissLayer(open, close);\n\n useFocusTrap(panelRef, {\n active: open && pos !== null,\n // The panel keeps a focus one of its own children has already taken. `FilterPopover`\n // autofocuses its text box on mount — that is what the press on \"Filter\" was FOR,\n // and it is a prop there precisely so the popover keeps it — and a trap that\n // unconditionally focused the container would take it straight back off again,\n // one effect later and invisibly.\n initialFocus: () => {\n const panel = panelRef.current;\n const active = document.activeElement;\n return panel?.contains(active) ? (active as HTMLElement) : panel;\n },\n });\n\n const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n // A caller's own handler first (0.32.2: RowActions stops Enter / Space at the panel);\n // it used to be dropped, overwritten by this one. A `preventDefault()` on Escape\n // there keeps the popover open — the owner's claim, as on the dialogs. And as there,\n // the handler sees Escape only while this popover is the layer on top: a tooltip or a\n // menu open over it takes that press first (round 0.35 R2, the dialogs' rule).\n runOwnKeyDown(e, onKeyDownProp, layer);\n // Focus is in here, the normal case: the key is handed to the top layer and STOPPED,\n // so it does not travel on up the React tree to a dialog around the popover.\n takeEscape(e);\n };\n\n return (\n <>\n {trigger({ open, toggle, ref: triggerRef })}\n {open && pos &&\n createPortal(\n /* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- the\n dialog container, per the APG dialog pattern: `onKeyDown` is Escape-to-close for\n whatever inside it holds focus. */\n <div\n // `...rest` first: the role, the id the trigger's `aria-controls` points at,\n // the `tabIndex` the trap needs and the measured position are what make this\n // a popover, and a caller reaching for a `data-tour` anchor must not be able\n // to remove one of them by accident.\n {...rest}\n ref={setPanel}\n role=\"dialog\"\n id={panelId}\n // The caller's own `aria-label` wins over {@link PopoverLabels.panel}, which\n // is the package's English fallback for an unnamed panel. Both name the same\n // element; the DOM spelling is the one being standardised on, so where both\n // are present it is the one that survives.\n aria-label={ariaLabel ?? text.panel}\n dir={rest.dir ?? dir}\n // Without it the panel cannot take focus at all, and the trap above would\n // silently do nothing on a panel whose children are not yet tabbable.\n tabIndex={-1}\n onKeyDown={handleKeyDown}\n style={{\n // Merged over the caller's, never replaced by it: these are measured\n // against the trigger every scroll and resize, and a panel that dropped\n // them would paint at the top-left of the viewport.\n ...style,\n position: \"fixed\",\n top: pos.top,\n bottom: pos.bottom,\n left: pos.left,\n width: panelWidth,\n maxHeight: placement.maxHeight,\n }}\n className={cn(\n \"z-50 overflow-y-auto rounded-md border border-subtle bg-surface p-3 shadow-lg outline-none\",\n className,\n )}\n >\n {children(close)}\n </div>,\n document.body,\n )}\n </>\n );\n}\n"],"mappings":";AA8LI,mBAOM,KAPN;AA9LJ,SAAS,SAAS,QAAQ,gBAAgB;AAE1C,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB,kBAAkB,oBAAoB;AAC/D,SAAS,eAAe,YAAY,iBAAiB,uBAAuB;AAC5E,SAAS,oBAAoB;AAC7B,SAAS,UAAU,gBAAgC;AACnD,SAA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AAgB,CAAC,YAAY,QAAQ,GAAG,OAAO,IAAI;AAInD,QAAM,QAAQ,gBAAgB,MAAM,KAAK;AAEzC,eAAa,UAAU;AAAA,IACrB,QAAQ,QAAQ,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMxB,cAAc,MAAM;AAClB,YAAM,QAAQ,SAAS;AACvB,YAAM,SAAS,SAAS;AACxB,aAAO,OAAO,SAAS,MAAM,IAAK,SAAyB;AAAA,IAC7D;AAAA,EACF,CAAC;AAED,QAAM,gBAAgB,CAAC,MAAqC;AAM1D,kBAAc,GAAG,eAAe,KAAK;AAGrC,eAAW,CAAC;AAAA,EACd;AAEA,SACE,iCACG;AAAA,YAAQ,EAAE,MAAM,QAAQ,KAAK,WAAW,CAAC;AAAA,IACzC,QAAQ,OACP;AAAA;AAAA;AAAA;AAAA,MAIE;AAAA,QAAC;AAAA;AAAA,UAKE,GAAG;AAAA,UACJ,KAAK;AAAA,UACL,MAAK;AAAA,UACL,IAAI;AAAA,UAKJ,cAAY,aAAa,KAAK;AAAA,UAC9B,KAAK,KAAK,OAAO;AAAA,UAGjB,UAAU;AAAA,UACV,WAAW;AAAA,UACX,OAAO;AAAA;AAAA;AAAA;AAAA,YAIL,GAAG;AAAA,YACH,UAAU;AAAA,YACV,KAAK,IAAI;AAAA,YACT,QAAQ,IAAI;AAAA,YACZ,MAAM,IAAI;AAAA,YACV,OAAO;AAAA,YACP,WAAW,UAAU;AAAA,UACvB;AAAA,UACA,WAAW;AAAA,YACT;AAAA,YACA;AAAA,UACF;AAAA,UAEC,mBAAS,KAAK;AAAA;AAAA,MACjB;AAAA,MACA,SAAS;AAAA,IACX;AAAA,KACJ;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/popover.tsx"],"sourcesContent":["import { useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithoutRef, KeyboardEvent, ReactNode, Ref, RefObject } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { anchoredInline, useAnchoredPanel, viewportSize } from \"../hooks/use-anchored-panel\";\nimport { runOwnKeyDown, takeEscape, useDismissLayer, useOutsideClick } from \"../hooks/use-dismiss\";\nimport { useFocusTrap } from \"../hooks/use-focus-trap\";\nimport { lengthPx, useRemPx, type RemLength } from \"../hooks/use-breakpoint\";\nimport { cn } from \"../lib/cn\";\nimport { dirOf } from \"../lib/direction\";\nimport type { Direction } from \"../lib/direction\";\nimport { useKitLabels, type LabelOverride } from \"../i18n/kit-labels\";\nimport { DEFAULT_POPOVER_LABELS } from \"./popover-labels\";\n// From ../lib/refs, not field-parts (round 0.36): field-parts renders a HelpPopover for a\n// field's `help`, so importing from there would close a cycle, as it did for Tooltip.\nimport { mergeRefs } from \"../lib/refs\";\n\n/** The panel's accessible name. A `role=\"dialog\"` with no name announces as \"dialog\"\n * and nothing else, which is worse than the unlabelled div it replaced — so it is a\n * prop with an English default, like every other string this package renders. Callers\n * should pass the control's own name (\"Filter\", \"Choose a date\"); the default is only\n * there so an unmigrated call site is still named. */\nexport interface PopoverLabels {\n panel: string;\n}\n\n// Defined in ./popover-labels, which holds no component code (0.34, KS U8).\nexport { DEFAULT_POPOVER_LABELS };\n\n/**\n * Exported, and extending the `<div>` attributes, so a consumer wrapping this — which is\n * what `DateField` and `FilterPopover` in this very package do — can hand anything\n * through to the PANEL: a `data-tour` anchor for the kit's own guided tour, a test id,\n * an `aria-describedby`, or an `aria-label` naming this particular popover.\n *\n * `children` is omitted from those attributes rather than inherited: here it is a render\n * prop taking the panel's `close`, not a `ReactNode`, so the two cannot be reconciled.\n */\nexport interface PopoverProps extends Omit<ComponentPropsWithoutRef<\"div\">, \"children\"> {\n trigger: (state: { open: boolean; toggle: () => void; ref: RefObject<HTMLButtonElement | null> }) => ReactNode;\n children: (close: () => void) => ReactNode;\n /**\n * The panel's width: `\"18rem\"` (the default) grows with the text size — the panel\n * holds text, and a 288 px calendar at 150 % cut its own month off (0.32,\n * docs/text-size-harmonization.md §3.2). A plain number is px, fixed, as before.\n * Either way the panel is never wider than the viewport less 8 px a side: 18rem is\n * 432 px at Extra large, more than a 360 px phone has.\n */\n width?: number | RemLength;\n labels?: LabelOverride<PopoverLabels>;\n /** Id for the panel, so a trigger wearing `role=\"combobox\"` can `aria-controls` it.\n * Required by ARIA on that role, and the panel is rendered here rather than by the\n * caller, so the id has to come in from outside. */\n panelId?: string;\n /** Extra classes for the PANEL. The trigger is the caller's own element. */\n className?: string;\n /** The PANEL, while it is open — where the rest of the props go (0.34, API-2, refactor\n * audit 2026-10). Merged with the panel's own ref (focus trap, outside click), so\n * neither loses it. The trigger is the caller's own element, ref and all. */\n ref?: Ref<HTMLDivElement>;\n}\n\n/** 288 px at Normal, in rem so it follows the text size (§3.2). */\nconst POPOVER_WIDTH: RemLength = \"18rem\";\n\n/** The gap the panel keeps from either edge of the viewport, in px. */\nconst EDGE = 8;\n\n/**\n * Portal-rendered popover anchored under its trigger button. The panel is fixed\n * to the viewport (so table/overflow ancestors can't clip it) and re-aligns on\n * scroll/resize; it closes on outside-click and Escape.\n *\n * ## Trapped, not merely focused — and why, because it is the closer call\n *\n * The audit's finding was that this panel *\"portals out of the tab order with no role\n * and no focus move\"*: Tab from the trigger went straight past the panel into the page\n * behind it, so the calendar, the calculator keypad and every column filter in the kit\n * were mouse-only. Two shapes fix that, and a popover is not automatically a dialog, so\n * this was chosen rather than inherited:\n *\n * - **The light one** — move focus in on open, hand it back on close, and let Tab walk\n * OUT of the panel into whatever follows the trigger. That is the right shape for a\n * non-modal popover sitting inline in the document.\n * - **The trap** — Tab cycles inside the panel; Escape and a click outside are the\n * ways out. What is here.\n *\n * The deciding fact is the portal. This panel is rendered to the END of `<body>`, not\n * beside its trigger, so \"let Tab walk out\" does not mean \"carry on from the trigger\" —\n * it means land at the end of the document, several hundred controls from where the\n * user was. Tabbing out of it would be a worse place to arrive than the one the finding\n * complains about, and fixing that properly needs a sentinel-and-return dance that\n * nothing in this package has. The trap gets the user back to the trigger every time,\n * because `useFocusTrap` restores focus on close.\n *\n * And the panels this kit actually opens are self-contained: pick a date, tap out a\n * sum, narrow a column. Each of them commits and closes, and each already has two\n * documented ways out wired above — Escape and an outside press — so containment costs\n * a keyboard user nothing they had.\n *\n * **It stays non-modal in every other respect**, deliberately: no backdrop, no body\n * scroll lock, and no `aria-modal`, so the page behind is still readable by a screen\n * reader, still scrollable, and still clickable — clicking it is what dismisses this.\n * Only Tab is contained. A popover that took the page away as well would be a\n * {@link Modal}, and there is one of those.\n */\nexport function Popover({\n trigger,\n children,\n width = POPOVER_WIDTH,\n labels,\n panelId,\n className,\n style,\n \"aria-label\": ariaLabel,\n onKeyDown: onKeyDownProp,\n ref,\n ...rest\n}: PopoverProps) {\n const triggerRef = useRef<HTMLButtonElement>(null);\n const panelRef = useRef<HTMLDivElement>(null);\n const setPanel = useMemo(() => mergeRefs(panelRef, ref), [ref]);\n const [open, setOpen] = useState(false);\n // The trigger's reading direction, read when it is pressed. The panel is portalled to\n // <body>, out of any `dir=\"rtl\"` subtree the trigger sits in, so without carrying it\n // across a right-to-left calendar or filter rendered left-to-right.\n const [dir, setDir] = useState<Direction>(\"ltr\");\n const close = () => setOpen(false);\n const toggle = () => {\n setDir(dirOf(triggerRef.current));\n setOpen((v) => !v);\n };\n // prop > `<UiKitProvider labels={{ popover }}>` > English. The provider's\n // `popover.panel` is only the last-resort name for a panel no caller named.\n const text = useKitLabels(\"popover\", DEFAULT_POPOVER_LABELS, labels);\n\n // Align the panel's END edge to the trigger's — right in LTR, left in RTL; it was\n // always `rect.right`, so an RTL panel hung off the wrong side — and clamp it\n // horizontally; the\n // hook owns the vertical half — below by default, flipped above (and height-capped)\n // when that is where the room is, e.g. once a mobile keyboard has eaten the bottom\n // of the screen (feedback #135). It re-measures on scroll/resize.\n const placement = useAnchoredPanel(triggerRef, open);\n const rect = placement.rect;\n // In px for the arithmetic below, at the text size in force; capped at the glass — the\n // root's client width, not `innerWidth`, which on a phone is the layout viewport grown\n // by whatever overflows (live #381, Wave 2 DUP-7).\n const remPx = useRemPx();\n const glass = rect ? viewportSize().width : 0;\n const panelWidth = rect ? Math.min(lengthPx(width, remPx), Math.max(0, glass - 2 * EDGE)) : 0;\n const pos = rect\n ? {\n // Flipped above, the panel hangs from its bottom edge, so one shorter than its\n // cap still meets the trigger (keksdose K1); the edge not in use is cleared.\n top: placement.above ? undefined : placement.top,\n bottom: placement.above ? placement.bottom : undefined,\n left: anchoredInline(rect, panelWidth, { dir, align: \"end\", edge: EDGE, viewportWidth: glass }).left,\n }\n : null;\n\n useOutsideClick([triggerRef, panelRef], close, open);\n // A layer on the Escape stack while open (Wave 2, DUP-1): a list opened inside closes\n // first, and the dialog this popover sits in only after it — the calculator on an\n // amount field in a Modal is exactly that.\n const layer = useDismissLayer(open, close);\n\n useFocusTrap(panelRef, {\n active: open && pos !== null,\n // The panel keeps a focus one of its own children has already taken. `FilterPopover`\n // autofocuses its text box on mount — that is what the press on \"Filter\" was FOR,\n // and it is a prop there precisely so the popover keeps it — and a trap that\n // unconditionally focused the container would take it straight back off again,\n // one effect later and invisibly.\n initialFocus: () => {\n const panel = panelRef.current;\n const active = document.activeElement;\n return panel?.contains(active) ? (active as HTMLElement) : panel;\n },\n });\n\n const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n // A caller's own handler first (0.32.2: RowActions stops Enter / Space at the panel);\n // it used to be dropped, overwritten by this one. A `preventDefault()` on Escape\n // there keeps the popover open — the owner's claim, as on the dialogs. And as there,\n // the handler sees Escape only while this popover is the layer on top: a tooltip or a\n // menu open over it takes that press first (round 0.35 R2, the dialogs' rule).\n runOwnKeyDown(e, onKeyDownProp, layer);\n // Focus is in here, the normal case: the key is handed to the top layer and STOPPED,\n // so it does not travel on up the React tree to a dialog around the popover.\n takeEscape(e);\n };\n\n return (\n <>\n {trigger({ open, toggle, ref: triggerRef })}\n {open && pos &&\n createPortal(\n /* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- the\n dialog container, per the APG dialog pattern: `onKeyDown` is Escape-to-close for\n whatever inside it holds focus. */\n <div\n // `...rest` first: the role, the id the trigger's `aria-controls` points at,\n // the `tabIndex` the trap needs and the measured position are what make this\n // a popover, and a caller reaching for a `data-tour` anchor must not be able\n // to remove one of them by accident.\n {...rest}\n ref={setPanel}\n role=\"dialog\"\n id={panelId}\n // The caller's own `aria-label` wins over {@link PopoverLabels.panel}, which\n // is the package's English fallback for an unnamed panel. Both name the same\n // element; the DOM spelling is the one being standardised on, so where both\n // are present it is the one that survives.\n aria-label={ariaLabel ?? text.panel}\n dir={rest.dir ?? dir}\n // Without it the panel cannot take focus at all, and the trap above would\n // silently do nothing on a panel whose children are not yet tabbable.\n tabIndex={-1}\n onKeyDown={handleKeyDown}\n style={{\n // Merged over the caller's, never replaced by it: these are measured\n // against the trigger every scroll and resize, and a panel that dropped\n // them would paint at the top-left of the viewport.\n ...style,\n position: \"fixed\",\n top: pos.top,\n bottom: pos.bottom,\n left: pos.left,\n width: panelWidth,\n maxHeight: placement.maxHeight,\n }}\n className={cn(\n \"z-50 overflow-y-auto rounded-md border border-subtle bg-surface p-3 shadow-lg outline-none\",\n className,\n )}\n >\n {children(close)}\n </div>,\n document.body,\n )}\n </>\n );\n}\n"],"mappings":";AAgMI,mBAOM,KAPN;AAhMJ,SAAS,SAAS,QAAQ,gBAAgB;AAE1C,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB,kBAAkB,oBAAoB;AAC/D,SAAS,eAAe,YAAY,iBAAiB,uBAAuB;AAC5E,SAAS,oBAAoB;AAC7B,SAAS,UAAU,gBAAgC;AACnD,SAAS,UAAU;AACnB,SAAS,aAAa;AAEtB,SAAS,oBAAwC;AACjD,SAAS,8BAA8B;AAGvC,SAAS,iBAAiB;AAgD1B,MAAM,gBAA2B;AAGjC,MAAM,OAAO;AAwCN,SAAS,QAAQ;AAAA,EACtB;AAAA,EACA;AAAA,EACA,QAAQ;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd,WA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