@eifi1/ui-kit 0.6.1 → 0.7.1
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 +69 -33
- package/dist/chart.d.ts +1 -0
- package/dist/components/account-settings.js +3 -2
- package/dist/components/account-settings.js.map +1 -1
- package/dist/components/amount-input.d.ts +5 -0
- package/dist/components/amount-input.js +6 -4
- package/dist/components/amount-input.js.map +1 -1
- package/dist/components/autocomplete.d.ts +33 -6
- package/dist/components/autocomplete.js +62 -16
- package/dist/components/autocomplete.js.map +1 -1
- package/dist/components/calculator.d.ts +5 -0
- package/dist/components/calculator.js +2 -1
- package/dist/components/calculator.js.map +1 -1
- package/dist/components/chart-zoom.js +2 -1
- package/dist/components/chart-zoom.js.map +1 -1
- package/dist/components/chart.d.ts +33 -2
- package/dist/components/chart.js +20 -8
- package/dist/components/chart.js.map +1 -1
- package/dist/components/chip.d.ts +34 -14
- package/dist/components/chip.js +63 -28
- package/dist/components/chip.js.map +1 -1
- package/dist/components/choice-card.d.ts +18 -1
- package/dist/components/choice-card.js +21 -8
- package/dist/components/choice-card.js.map +1 -1
- package/dist/components/combobox-core.d.ts +61 -2
- package/dist/components/combobox-core.js +68 -17
- package/dist/components/combobox-core.js.map +1 -1
- package/dist/components/combobox.d.ts +11 -7
- package/dist/components/combobox.js +51 -28
- package/dist/components/combobox.js.map +1 -1
- package/dist/components/currency-select.js +3 -3
- package/dist/components/currency-select.js.map +1 -1
- package/dist/components/danger-confirm.d.ts +30 -6
- package/dist/components/danger-confirm.js +51 -32
- package/dist/components/danger-confirm.js.map +1 -1
- package/dist/components/data-table-filter-popover.d.ts +1 -1
- package/dist/components/data-table-filters.d.ts +1 -1
- package/dist/components/data-table-pagination.d.ts +6 -3
- package/dist/components/data-table-pagination.js +6 -5
- package/dist/components/data-table-pagination.js.map +1 -1
- package/dist/components/data-table.d.ts +1 -1
- package/dist/components/data-table.js +332 -248
- package/dist/components/data-table.js.map +1 -1
- package/dist/components/date-picker.js +17 -7
- package/dist/components/date-picker.js.map +1 -1
- package/dist/components/dialog-frame.d.ts +28 -3
- package/dist/components/dialog-frame.js +47 -11
- package/dist/components/dialog-frame.js.map +1 -1
- package/dist/components/disclosure.d.ts +22 -2
- package/dist/components/disclosure.js +41 -8
- package/dist/components/disclosure.js.map +1 -1
- package/dist/components/dropdown.d.ts +7 -3
- package/dist/components/dropdown.js +6 -2
- package/dist/components/dropdown.js.map +1 -1
- package/dist/components/entity-combobox.d.ts +17 -8
- package/dist/components/entity-combobox.js +7 -5
- package/dist/components/entity-combobox.js.map +1 -1
- package/dist/components/file-button.d.ts +38 -5
- package/dist/components/file-button.js +23 -2
- package/dist/components/file-button.js.map +1 -1
- package/dist/components/file-dropzone.d.ts +11 -5
- package/dist/components/file-dropzone.js +14 -19
- package/dist/components/file-dropzone.js.map +1 -1
- package/dist/components/grouped-picker.js +2 -2
- package/dist/components/grouped-picker.js.map +1 -1
- package/dist/components/hover-menu.d.ts +8 -3
- package/dist/components/hover-menu.js +88 -4
- package/dist/components/hover-menu.js.map +1 -1
- package/dist/components/icon-picker.d.ts +10 -1
- package/dist/components/icon-picker.js +5 -1
- package/dist/components/icon-picker.js.map +1 -1
- package/dist/components/measured-grid.d.ts +165 -0
- package/dist/components/measured-grid.js +559 -0
- package/dist/components/measured-grid.js.map +1 -0
- package/dist/components/mini-calendar.js +7 -8
- package/dist/components/mini-calendar.js.map +1 -1
- package/dist/components/month-picker.js +13 -9
- package/dist/components/month-picker.js.map +1 -1
- package/dist/components/multi-entity-combobox.js +2 -2
- package/dist/components/multi-entity-combobox.js.map +1 -1
- package/dist/components/multi-select.d.ts +9 -1
- package/dist/components/multi-select.js +22 -8
- package/dist/components/multi-select.js.map +1 -1
- package/dist/components/number-field.d.ts +5 -0
- package/dist/components/number-input.d.ts +5 -0
- package/dist/components/number-input.js +3 -3
- package/dist/components/number-input.js.map +1 -1
- package/dist/components/numpad-sheet.d.ts +5 -0
- package/dist/components/numpad-sheet.js +3 -3
- package/dist/components/numpad-sheet.js.map +1 -1
- package/dist/components/picker-sheet.js +1 -1
- package/dist/components/picker-sheet.js.map +1 -1
- package/dist/components/popover.js +11 -2
- package/dist/components/popover.js.map +1 -1
- package/dist/components/series-chart-ticks.d.ts +13 -0
- package/dist/components/series-chart-ticks.js +29 -0
- package/dist/components/series-chart-ticks.js.map +1 -0
- package/dist/components/series-chart.js +33 -27
- package/dist/components/series-chart.js.map +1 -1
- package/dist/components/settings-fields.d.ts +2 -0
- package/dist/components/swatch-picker.d.ts +10 -1
- package/dist/components/swatch-picker.js +2 -0
- package/dist/components/swatch-picker.js.map +1 -1
- package/dist/components/swipeable-row.d.ts +11 -2
- package/dist/components/swipeable-row.js +5 -3
- package/dist/components/swipeable-row.js.map +1 -1
- package/dist/components/tile-radio.js +5 -7
- package/dist/components/tile-radio.js.map +1 -1
- package/dist/components/time-input.d.ts +2 -0
- package/dist/components/toggle-group.d.ts +13 -3
- package/dist/components/toggle-group.js +21 -1
- package/dist/components/toggle-group.js.map +1 -1
- package/dist/components/toggle-legend.js +1 -2
- package/dist/components/toggle-legend.js.map +1 -1
- package/dist/components/tooltip.d.ts +10 -4
- package/dist/components/tooltip.js +23 -6
- package/dist/components/tooltip.js.map +1 -1
- package/dist/components/treemap.d.ts +6 -1
- package/dist/components/treemap.js +16 -6
- package/dist/components/treemap.js.map +1 -1
- package/dist/components/ui.d.ts +36 -8
- package/dist/components/ui.js +27 -19
- package/dist/components/ui.js.map +1 -1
- package/dist/components/use-anchor-dir.d.ts +15 -0
- package/dist/components/use-anchor-dir.js +14 -0
- package/dist/components/use-anchor-dir.js.map +1 -0
- package/dist/components/use-mobile-reveal.d.ts +8 -1
- package/dist/components/use-mobile-reveal.js +3 -2
- package/dist/components/use-mobile-reveal.js.map +1 -1
- package/dist/components/use-table-state.d.ts +4 -4
- package/dist/components/use-table-state.js +12 -5
- package/dist/components/use-table-state.js.map +1 -1
- package/dist/{data-table-filters-DM1auUfH.d.ts → data-table-filters-noy0Abvi.d.ts} +40 -7
- package/dist/data-table.d.ts +1 -1
- package/dist/data-table.js.map +1 -1
- package/dist/feedback/feedback-attachment.d.ts +22 -3
- package/dist/feedback/feedback-attachment.js +15 -7
- package/dist/feedback/feedback-attachment.js.map +1 -1
- package/dist/feedback/feedback-dialog.d.ts +3 -2
- package/dist/feedback/feedback-dialog.js.map +1 -1
- package/dist/feedback.d.ts +1 -1
- package/dist/hooks/use-windowed-rows.d.ts +29 -0
- package/dist/hooks/use-windowed-rows.js +31 -0
- package/dist/hooks/use-windowed-rows.js.map +1 -0
- package/dist/i18n/defaults.d.ts +5 -0
- package/dist/i18n/defaults.js +5 -1
- package/dist/i18n/defaults.js.map +1 -1
- package/dist/i18n/kit-labels.d.ts +7 -0
- package/dist/i18n/kit-labels.js.map +1 -1
- package/dist/i18n/locales/de-CH.d.ts +45 -0
- package/dist/i18n/locales/de-CH.js +21 -0
- package/dist/i18n/locales/de-CH.js.map +1 -0
- package/dist/i18n/locales/de.d.ts +45 -0
- package/dist/i18n/locales/de.js +344 -0
- package/dist/i18n/locales/de.js.map +1 -0
- package/dist/i18n/locales/es.d.ts +45 -0
- package/dist/i18n/locales/es.js +339 -0
- package/dist/i18n/locales/es.js.map +1 -0
- package/dist/i18n/locales/fr.d.ts +45 -0
- package/dist/i18n/locales/fr.js +344 -0
- package/dist/i18n/locales/fr.js.map +1 -0
- package/dist/i18n/locales/hu.d.ts +45 -0
- package/dist/i18n/locales/hu.js +343 -0
- package/dist/i18n/locales/hu.js.map +1 -0
- package/dist/i18n/locales/it.d.ts +45 -0
- package/dist/i18n/locales/it.js +342 -0
- package/dist/i18n/locales/it.js.map +1 -0
- package/dist/i18n/locales/zh.d.ts +45 -0
- package/dist/i18n/locales/zh.js +338 -0
- package/dist/i18n/locales/zh.js.map +1 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/direction.d.ts +24 -0
- package/dist/lib/direction.js +19 -0
- package/dist/lib/direction.js.map +1 -0
- package/dist/rhf/form.d.ts +2 -0
- package/dist/rhf/form.js.map +1 -1
- package/dist/rhf.d.ts +2 -0
- package/dist/search/command-palette.d.ts +5 -0
- package/dist/search/command-palette.js +80 -50
- package/dist/search/command-palette.js.map +1 -1
- package/dist/shell/app-shell.d.ts +13 -1
- package/dist/shell/app-shell.js +134 -85
- package/dist/shell/app-shell.js.map +1 -1
- package/dist/shell/topbar-action-menu.js +1 -1
- package/dist/shell/topbar-action-menu.js.map +1 -1
- package/dist/shell/topbar-controls.d.ts +7 -3
- package/dist/shell/topbar-controls.js +38 -31
- package/dist/shell/topbar-controls.js.map +1 -1
- package/dist/theme/chart-palette.d.ts +7 -1
- package/dist/theme/chart-palette.js +2 -1
- package/dist/theme/chart-palette.js.map +1 -1
- package/dist/tour/tour.d.ts +11 -5
- package/dist/tour/tour.js +124 -58
- package/dist/tour/tour.js.map +1 -1
- package/dist/wizard/use-wizard.js +30 -13
- package/dist/wizard/use-wizard.js.map +1 -1
- package/dist/wizard/wizard-summary.js +1 -1
- package/dist/wizard/wizard-summary.js.map +1 -1
- package/package.json +12 -2
- package/src/components/account-settings.tsx +6 -2
- package/src/components/amount-input.tsx +10 -8
- package/src/components/autocomplete.tsx +110 -24
- package/src/components/calculator.tsx +5 -1
- package/src/components/chart-zoom.tsx +8 -1
- package/src/components/chart.tsx +68 -7
- package/src/components/chip.tsx +131 -49
- package/src/components/choice-card.tsx +77 -36
- package/src/components/combobox-core.tsx +147 -20
- package/src/components/combobox.tsx +100 -44
- package/src/components/currency-select.tsx +6 -6
- package/src/components/danger-confirm.tsx +90 -36
- package/src/components/data-table-pagination.tsx +32 -19
- package/src/components/data-table.tsx +198 -36
- package/src/components/date-picker.tsx +24 -7
- package/src/components/dialog-frame.tsx +97 -22
- package/src/components/disclosure.tsx +75 -13
- package/src/components/dropdown.tsx +17 -5
- package/src/components/entity-combobox.tsx +26 -13
- package/src/components/file-button.tsx +74 -5
- package/src/components/file-dropzone.tsx +44 -35
- package/src/components/grouped-picker.tsx +2 -2
- package/src/components/hover-menu.tsx +139 -10
- package/src/components/icon-picker.tsx +14 -1
- package/src/components/measured-grid.tsx +852 -0
- package/src/components/mini-calendar.tsx +11 -8
- package/src/components/month-picker.tsx +18 -11
- package/src/components/multi-entity-combobox.tsx +2 -2
- package/src/components/multi-select.tsx +34 -7
- package/src/components/number-input.tsx +4 -4
- package/src/components/numpad-sheet.tsx +5 -3
- package/src/components/picker-sheet.tsx +1 -1
- package/src/components/popover.tsx +18 -3
- package/src/components/series-chart-ticks.ts +52 -0
- package/src/components/series-chart.tsx +39 -31
- package/src/components/swatch-picker.tsx +11 -0
- package/src/components/swipeable-row.tsx +21 -6
- package/src/components/tile-radio.tsx +5 -7
- package/src/components/toggle-group.tsx +39 -3
- package/src/components/toggle-legend.tsx +5 -2
- package/src/components/tooltip.tsx +40 -12
- package/src/components/treemap.tsx +28 -5
- package/src/components/ui.tsx +79 -33
- package/src/components/use-anchor-dir.ts +20 -0
- package/src/components/use-mobile-reveal.ts +10 -2
- package/src/components/use-table-state.ts +44 -7
- package/src/data-table.ts +1 -0
- package/src/feedback/feedback-attachment.tsx +36 -9
- package/src/feedback/feedback-dialog.tsx +3 -2
- package/src/hooks/use-windowed-rows.ts +69 -0
- package/src/i18n/defaults.ts +4 -0
- package/src/i18n/kit-labels.tsx +4 -0
- package/src/i18n/locales/de-CH.ts +30 -0
- package/src/i18n/locales/de.ts +365 -0
- package/src/i18n/locales/es.ts +358 -0
- package/src/i18n/locales/fr.ts +371 -0
- package/src/i18n/locales/hu.ts +359 -0
- package/src/i18n/locales/it.ts +360 -0
- package/src/i18n/locales/zh.ts +348 -0
- package/src/index.ts +10 -1
- package/src/lib/direction.ts +37 -0
- package/src/rhf/form.tsx +21 -0
- package/src/search/command-palette.tsx +77 -19
- package/src/shell/app-shell.tsx +201 -130
- package/src/shell/topbar-action-menu.tsx +1 -1
- package/src/shell/topbar-controls.tsx +19 -8
- package/src/theme/chart-palette.ts +9 -2
- package/src/tour/tour.tsx +119 -18
- package/src/wizard/use-wizard.ts +55 -17
- package/src/wizard/wizard-summary.tsx +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/multi-entity-combobox.tsx"],"sourcesContent":["import { useId, useMemo, type ComponentPropsWithoutRef, type ReactNode } from \"react\";\nimport { X } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport { FieldChevron, FieldLabel, FIELD_TRIGGER, FIELD_FLOATING_PAD, FIELD_INVALID } from \"./ui\";\nimport {\n ComboboxPanel,\n useComboboxCore,\n useComboboxFieldError,\n type ComboOption,\n} from \"./combobox-core\";\nimport {\n DEFAULT_COMBOBOX_LABELS,\n DEFAULT_COMMON_LABELS,\n useKitLabels,\n useKitLocale,\n} from \"../i18n/kit-labels\";\n\n/** `onChange` is the kit's — \"a selection was made\", carrying values — rather\n * than the div's form event, so the DOM's spelling of it is omitted. */\nexport interface MultiEntityComboboxProps<V extends string | number>\n extends Omit<ComponentPropsWithoutRef<\"div\">, \"onChange\"> {\n /** Selected ids. */\n value: V[];\n onChange: (value: V[]) => void;\n /** Already-loaded options (client-side filtered); also resolves selected labels. */\n options?: ComboOption<V>[];\n /** Async option source, debounced + race-safe; a rejection shows\n * `loadErrorLabel`. When set, `options` resolves labels only. */\n loadOptions?: (query: string) => Promise<ComboOption<V>[]>;\n loading?: boolean;\n label?: ReactNode;\n placeholder?: string;\n searchPlaceholder?: string;\n emptyLabel?: string;\n /** Trigger summary when 1+ selected (default: the labels as a locale-formatted\n * list, or `combobox.selectedCount` when a label can't be resolved). */\n itemLabel?: (count: number) => string;\n clearable?: boolean;\n clearLabel?: string;\n /** The phone sheet's close button. Its own prop rather than a reuse of\n * `clearLabel`: \"clear the selection\" and \"close this screen\" are different\n * actions, and on a full-screen sheet the close button is the only way out —\n * so it is the one control here that MUST be in the reader's language. */\n closeLabel?: string;\n disabled?: boolean;\n /** When set, a \"create\" row appears for a non-empty query with no exact match.\n * The panel stays open (adding the new entity to `value` is the caller's job). */\n onCreate?: (query: string) => void;\n createLabel?: (query: string) => string;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\n /** What is wrong with the value, as {@link Input}'s `error`: rendered under the\n * field, on the trigger's `aria-describedby`, and implies `invalid`. */\n error?: ReactNode;\n /** Narrow `options` client-side by the query. Default `true`; `false` shows them\n * as given (a server-ranked list). */\n filter?: boolean;\n /** Offer nothing, and call no `loadOptions`, below this many characters. Default\n * `0`, i.e. the list loads as the panel opens. */\n minChars?: number;\n /** `loadOptions` debounce. Default 150 ms. */\n debounceMs?: number;\n /** Shown when `loadOptions` rejects. Default: `combobox.loadError`. */\n loadErrorLabel?: string;\n}\n\n/**\n * Multi-value sibling of {@link EntityCombobox}: pick several entities by search,\n * with the same async `loadOptions`/`onCreate` support. Rows show a checkbox and\n * toggle without closing the panel; the trigger summarises the selection.\n */\nexport function MultiEntityCombobox<V extends string | number>({\n value,\n onChange,\n options,\n loadOptions,\n loading,\n label,\n placeholder,\n searchPlaceholder,\n emptyLabel,\n itemLabel,\n clearable,\n clearLabel,\n closeLabel,\n disabled,\n onCreate,\n createLabel,\n className,\n invalid,\n error,\n filter,\n minChars,\n debounceMs,\n loadErrorLabel,\n \"aria-label\": ariaLabel,\n ...rest\n}: MultiEntityComboboxProps<V>) {\n const core = useComboboxCore<V>({\n options,\n loadOptions,\n loading,\n filter,\n minChars,\n debounceMs,\n });\n const field = useComboboxFieldError(error, invalid);\n // The props are the per-instance overrides, the provider the app-wide ones; a\n // prop left `undefined` falls through to the provider rather than masking it.\n const labels = useKitLabels(\"combobox\", DEFAULT_COMBOBOX_LABELS, {\n search: searchPlaceholder,\n noResults: emptyLabel,\n clear: clearLabel,\n create: createLabel,\n });\n const common = useKitLabels(\"common\", DEFAULT_COMMON_LABELS);\n const { open, results, resolve, setOpen } = core;\n // One id per instance, generated here rather than in the core: `aria-controls` on\n // the trigger has to name the list while the list is still closed, so the id\n // belongs to whoever renders both ends of it.\n const listboxId = useId();\n\n const valueSet = useMemo(() => new Set(value), [value]);\n // A list of NAMES, not a sentence, so the narrow conjunction: English gets\n // \"Food, Rent, Travel\" (no \"and\" squeezed into a truncating trigger), German and\n // French still get their \"und\"/\"et\" where the language insists on it, and Japanese\n // and Chinese get the ideographic comma \"、\". The `unit` type looked like the\n // natural fit for a summary, but in ja/zh it concatenates the names with nothing\n // between them at all.\n const locale = useKitLocale();\n const listFormat = useMemo(\n () => new Intl.ListFormat(locale, { type: \"conjunction\", style: \"narrow\" }),\n [locale],\n );\n const summary = (() => {\n if (value.length === 0) return placeholder ?? \"\";\n if (itemLabel) return itemLabel(value.length);\n const chosen = value.map(resolve);\n return chosen.every(Boolean)\n ? listFormat.format(chosen.map((o) => o!.label))\n : labels.selectedCount(value.length);\n })();\n\n const q = core.query.trim();\n const showCreate =\n Boolean(onCreate) && q.length > 0 && !results.some((o) => o.label.toLowerCase() === q.toLowerCase());\n const showClear = Boolean(clearable && value.length > 0 && !disabled);\n\n const toggle = (o: ComboOption<V>) => {\n core.cacheRef.current.set(o.value, o);\n if (valueSet.has(o.value)) onChange(value.filter((v) => v !== o.value));\n else onChange([...value, o.value]);\n // Stay open — multi-select keeps adding.\n };\n\n return (\n // `rest` dresses the wrapper, which has no role; the accessible NAME goes on\n // the trigger, which has one. Spread FIRST so the trigger's ARIA and the\n // handlers that open the panel cannot be clobbered from outside.\n <div {...rest} className={cn(\"relative\", className)}>\n {label !== undefined && <FieldLabel>{label}</FieldLabel>}\n <button\n ref={core.triggerRef}\n type=\"button\"\n // A combobox, not a button. The distinction is not pedantry: this control\n // carried `aria-invalid`, which `button` does not support, so a required\n // field left empty painted a rose border and told a reader nothing at all —\n // and ESLint flagged it as exactly that (`role-supports-aria-props`). The\n // fix the audit asked for is the role that describes what this IS: a closed\n // choice that expands into the list named below. `combobox` supports\n // `aria-invalid`, so the border and the announcement finally agree.\n role=\"combobox\"\n aria-expanded={open}\n aria-controls={listboxId}\n aria-haspopup=\"listbox\"\n // The label is a floating <span>, not a <label for>, so without this the\n // trigger's accessible name is whatever value happens to be selected —\n // \"Checking\" with nothing saying it is the account. The label AND the\n // value, because `aria-label` replaces the content rather than adding to\n // it, and a control that announces only its name has lost the answer.\n // A caller's own name wins over the composition: two fields labelled\n // \"Account\" on a transfer form are the from and the to, and only the\n // caller knows which is which.\n aria-label={\n ariaLabel ??\n (typeof label === \"string\" ? common.fieldValue(label, summary) : undefined)\n }\n disabled={disabled}\n aria-invalid={field.isInvalid || undefined}\n aria-describedby={field.describedBy}\n onClick={() => !disabled && setOpen((o) => !o)}\n // Down/Up opens the list from the closed trigger, per the APG. Enter and\n // Space already do it through the button's own click.\n onKeyDown={(e) => {\n if (disabled) return;\n if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n e.preventDefault();\n setOpen(true);\n }\n }}\n className={cn(\n FIELD_TRIGGER,\n \"pr-9\",\n label !== undefined && FIELD_FLOATING_PAD,\n disabled && \"cursor-not-allowed opacity-50\",\n field.isInvalid && FIELD_INVALID,\n )}\n >\n <span\n className={cn(\n \"min-w-0 truncate\",\n // Inherit FIELD_BASE's ink for a value, keep the placeholder tone\n // (`--text-placeholder`) — the same rule every field on a form row\n // follows (Keksdose dev#477).\n !value.length && \"text-[var(--text-placeholder)]\",\n )}\n >\n {summary}\n </span>\n {showClear ? (\n <span\n role=\"button\"\n tabIndex={-1}\n aria-label={labels.clear}\n onClick={(e) => {\n e.stopPropagation();\n onChange([]);\n }}\n className=\"absolute right-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-[var(--text-placeholder)] hover:text-[var(--text-secondary)]\"\n >\n <X className=\"size-4\" />\n </span>\n ) : (\n <FieldChevron />\n )}\n </button>\n <ComboboxPanel\n core={core}\n listboxId={listboxId}\n multi\n // On a phone the panel becomes a full-screen sheet, which needs the field's\n // own label to say what it is asking for (live #200).\n sheetTitle={label ?? placeholder}\n searchPlaceholder={labels.search}\n emptyLabel={labels.noResults}\n closeLabel={closeLabel}\n loadErrorLabel={loadErrorLabel}\n isSelected={(v) => valueSet.has(v)}\n onChoose={toggle}\n showCreate={showCreate}\n onCreate={() => {\n onCreate?.(q);\n core.setQuery(\"\");\n }}\n createContent={labels.create(q)}\n />\n {field.errorEl}\n </div>\n );\n}\n"],"mappings":";AAgK8B,cACxB,YADwB;AAhK9B,SAAS,OAAO,eAA8D;AAC9E,SAAS,SAAS;AAClB,SAAS,UAAU;AACnB,SAAS,cAAc,YAAY,eAAe,oBAAoB,qBAAqB;AAC3F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAwDA,SAAS,oBAA+C;AAAA,EAC7D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd,GAAG;AACL,GAAgC;AAC9B,QAAM,OAAO,gBAAmB;AAAA,IAC9B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACD,QAAM,QAAQ,sBAAsB,OAAO,OAAO;AAGlD,QAAM,SAAS,aAAa,YAAY,yBAAyB;AAAA,IAC/D,QAAQ;AAAA,IACR,WAAW;AAAA,IACX,OAAO;AAAA,IACP,QAAQ;AAAA,EACV,CAAC;AACD,QAAM,SAAS,aAAa,UAAU,qBAAqB;AAC3D,QAAM,EAAE,MAAM,SAAS,SAAS,QAAQ,IAAI;AAI5C,QAAM,YAAY,MAAM;AAExB,QAAM,WAAW,QAAQ,MAAM,IAAI,IAAI,KAAK,GAAG,CAAC,KAAK,CAAC;AAOtD,QA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Ae,OAAO,OAAO,CAAC;AAAA;AAAA,MAChC;AAAA,MACC,MAAM;AAAA,OACT;AAAA;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/multi-entity-combobox.tsx"],"sourcesContent":["import { useId, useMemo, type ComponentPropsWithoutRef, type ReactNode } from \"react\";\nimport { X } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport { FieldChevron, FieldLabel, FIELD_TRIGGER, FIELD_FLOATING_PAD, FIELD_INVALID } from \"./ui\";\nimport {\n ComboboxPanel,\n useComboboxCore,\n useComboboxFieldError,\n type ComboOption,\n} from \"./combobox-core\";\nimport {\n DEFAULT_COMBOBOX_LABELS,\n DEFAULT_COMMON_LABELS,\n useKitLabels,\n useKitLocale,\n} from \"../i18n/kit-labels\";\n\n/** `onChange` is the kit's — \"a selection was made\", carrying values — rather\n * than the div's form event, so the DOM's spelling of it is omitted. */\nexport interface MultiEntityComboboxProps<V extends string | number>\n extends Omit<ComponentPropsWithoutRef<\"div\">, \"onChange\"> {\n /** Selected ids. */\n value: V[];\n onChange: (value: V[]) => void;\n /** Already-loaded options (client-side filtered); also resolves selected labels. */\n options?: ComboOption<V>[];\n /** Async option source, debounced + race-safe; a rejection shows\n * `loadErrorLabel`. When set, `options` resolves labels only. */\n loadOptions?: (query: string) => Promise<ComboOption<V>[]>;\n loading?: boolean;\n label?: ReactNode;\n placeholder?: string;\n searchPlaceholder?: string;\n emptyLabel?: string;\n /** Trigger summary when 1+ selected (default: the labels as a locale-formatted\n * list, or `combobox.selectedCount` when a label can't be resolved). */\n itemLabel?: (count: number) => string;\n clearable?: boolean;\n clearLabel?: string;\n /** The phone sheet's close button. Its own prop rather than a reuse of\n * `clearLabel`: \"clear the selection\" and \"close this screen\" are different\n * actions, and on a full-screen sheet the close button is the only way out —\n * so it is the one control here that MUST be in the reader's language. */\n closeLabel?: string;\n disabled?: boolean;\n /** When set, a \"create\" row appears for a non-empty query with no exact match.\n * The panel stays open (adding the new entity to `value` is the caller's job). */\n onCreate?: (query: string) => void;\n createLabel?: (query: string) => string;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\n /** What is wrong with the value, as {@link Input}'s `error`: rendered under the\n * field, on the trigger's `aria-describedby`, and implies `invalid`. */\n error?: ReactNode;\n /** Narrow `options` client-side by the query. Default `true`; `false` shows them\n * as given (a server-ranked list). */\n filter?: boolean;\n /** Offer nothing, and call no `loadOptions`, below this many characters. Default\n * `0`, i.e. the list loads as the panel opens. */\n minChars?: number;\n /** `loadOptions` debounce. Default 150 ms. */\n debounceMs?: number;\n /** Shown when `loadOptions` rejects. Default: `combobox.loadError`. */\n loadErrorLabel?: string;\n}\n\n/**\n * Multi-value sibling of {@link EntityCombobox}: pick several entities by search,\n * with the same async `loadOptions`/`onCreate` support. Rows show a checkbox and\n * toggle without closing the panel; the trigger summarises the selection.\n */\nexport function MultiEntityCombobox<V extends string | number>({\n value,\n onChange,\n options,\n loadOptions,\n loading,\n label,\n placeholder,\n searchPlaceholder,\n emptyLabel,\n itemLabel,\n clearable,\n clearLabel,\n closeLabel,\n disabled,\n onCreate,\n createLabel,\n className,\n invalid,\n error,\n filter,\n minChars,\n debounceMs,\n loadErrorLabel,\n \"aria-label\": ariaLabel,\n ...rest\n}: MultiEntityComboboxProps<V>) {\n const core = useComboboxCore<V>({\n options,\n loadOptions,\n loading,\n filter,\n minChars,\n debounceMs,\n });\n const field = useComboboxFieldError(error, invalid);\n // The props are the per-instance overrides, the provider the app-wide ones; a\n // prop left `undefined` falls through to the provider rather than masking it.\n const labels = useKitLabels(\"combobox\", DEFAULT_COMBOBOX_LABELS, {\n search: searchPlaceholder,\n noResults: emptyLabel,\n clear: clearLabel,\n create: createLabel,\n });\n const common = useKitLabels(\"common\", DEFAULT_COMMON_LABELS);\n const { open, results, resolve, setOpen } = core;\n // One id per instance, generated here rather than in the core: `aria-controls` on\n // the trigger has to name the list while the list is still closed, so the id\n // belongs to whoever renders both ends of it.\n const listboxId = useId();\n\n const valueSet = useMemo(() => new Set(value), [value]);\n // A list of NAMES, not a sentence, so the narrow conjunction: English gets\n // \"Food, Rent, Travel\" (no \"and\" squeezed into a truncating trigger), German and\n // French still get their \"und\"/\"et\" where the language insists on it, and Japanese\n // and Chinese get the ideographic comma \"、\". The `unit` type looked like the\n // natural fit for a summary, but in ja/zh it concatenates the names with nothing\n // between them at all.\n const locale = useKitLocale();\n const listFormat = useMemo(\n () => new Intl.ListFormat(locale, { type: \"conjunction\", style: \"narrow\" }),\n [locale],\n );\n const summary = (() => {\n if (value.length === 0) return placeholder ?? \"\";\n if (itemLabel) return itemLabel(value.length);\n const chosen = value.map(resolve);\n return chosen.every(Boolean)\n ? listFormat.format(chosen.map((o) => o!.label))\n : labels.selectedCount(value.length);\n })();\n\n const q = core.query.trim();\n const showCreate =\n Boolean(onCreate) && q.length > 0 && !results.some((o) => o.label.toLowerCase() === q.toLowerCase());\n const showClear = Boolean(clearable && value.length > 0 && !disabled);\n\n const toggle = (o: ComboOption<V>) => {\n core.cacheRef.current.set(o.value, o);\n if (valueSet.has(o.value)) onChange(value.filter((v) => v !== o.value));\n else onChange([...value, o.value]);\n // Stay open — multi-select keeps adding.\n };\n\n return (\n // `rest` dresses the wrapper, which has no role; the accessible NAME goes on\n // the trigger, which has one. Spread FIRST so the trigger's ARIA and the\n // handlers that open the panel cannot be clobbered from outside.\n <div {...rest} className={cn(\"relative\", className)}>\n {label !== undefined && <FieldLabel>{label}</FieldLabel>}\n <button\n ref={core.triggerRef}\n type=\"button\"\n // A combobox, not a button. The distinction is not pedantry: this control\n // carried `aria-invalid`, which `button` does not support, so a required\n // field left empty painted a rose border and told a reader nothing at all —\n // and ESLint flagged it as exactly that (`role-supports-aria-props`). The\n // fix the audit asked for is the role that describes what this IS: a closed\n // choice that expands into the list named below. `combobox` supports\n // `aria-invalid`, so the border and the announcement finally agree.\n role=\"combobox\"\n aria-expanded={open}\n aria-controls={listboxId}\n aria-haspopup=\"listbox\"\n // The label is a floating <span>, not a <label for>, so without this the\n // trigger's accessible name is whatever value happens to be selected —\n // \"Checking\" with nothing saying it is the account. The label AND the\n // value, because `aria-label` replaces the content rather than adding to\n // it, and a control that announces only its name has lost the answer.\n // A caller's own name wins over the composition: two fields labelled\n // \"Account\" on a transfer form are the from and the to, and only the\n // caller knows which is which.\n aria-label={\n ariaLabel ??\n (typeof label === \"string\" ? common.fieldValue(label, summary) : undefined)\n }\n disabled={disabled}\n aria-invalid={field.isInvalid || undefined}\n aria-describedby={field.describedBy}\n onClick={() => !disabled && setOpen((o) => !o)}\n // Down/Up opens the list from the closed trigger, per the APG. Enter and\n // Space already do it through the button's own click.\n onKeyDown={(e) => {\n if (disabled) return;\n if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n e.preventDefault();\n setOpen(true);\n }\n }}\n className={cn(\n FIELD_TRIGGER,\n \"pe-9\",\n label !== undefined && FIELD_FLOATING_PAD,\n disabled && \"cursor-not-allowed opacity-50\",\n field.isInvalid && FIELD_INVALID,\n )}\n >\n <span\n className={cn(\n \"min-w-0 truncate\",\n // Inherit FIELD_BASE's ink for a value, keep the placeholder tone\n // (`--text-placeholder`) — the same rule every field on a form row\n // follows (Keksdose dev#477).\n !value.length && \"text-[var(--text-placeholder)]\",\n )}\n >\n {summary}\n </span>\n {showClear ? (\n <span\n role=\"button\"\n tabIndex={-1}\n aria-label={labels.clear}\n onClick={(e) => {\n e.stopPropagation();\n onChange([]);\n }}\n className=\"absolute end-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-[var(--text-placeholder)] hover:text-[var(--text-secondary)]\"\n >\n <X className=\"size-4\" />\n </span>\n ) : (\n <FieldChevron />\n )}\n </button>\n <ComboboxPanel\n core={core}\n listboxId={listboxId}\n multi\n // On a phone the panel becomes a full-screen sheet, which needs the field's\n // own label to say what it is asking for (live #200).\n sheetTitle={label ?? placeholder}\n searchPlaceholder={labels.search}\n emptyLabel={labels.noResults}\n closeLabel={closeLabel}\n loadErrorLabel={loadErrorLabel}\n isSelected={(v) => valueSet.has(v)}\n onChoose={toggle}\n showCreate={showCreate}\n onCreate={() => {\n onCreate?.(q);\n core.setQuery(\"\");\n }}\n createContent={labels.create(q)}\n />\n {field.errorEl}\n </div>\n );\n}\n"],"mappings":";AAgK8B,cACxB,YADwB;AAhK9B,SAAS,OAAO,eAA8D;AAC9E,SAAS,SAAS;AAClB,SAAS,UAAU;AACnB,SAAS,cAAc,YAAY,eAAe,oBAAoB,qBAAqB;AAC3F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAwDA,SAAS,oBAA+C;AAAA,EAC7D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd,GAAG;AACL,GAAgC;AAC9B,QAAM,OAAO,gBAAmB;AAAA,IAC9B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACD,QAAM,QAAQ,sBAAsB,OAAO,OAAO;AAGlD,QAAM,SAAS,aAAa,YAAY,yBAAyB;AAAA,IAC/D,QAAQ;AAAA,IACR,WAAW;AAAA,IACX,OAAO;AAAA,IACP,QAAQ;AAAA,EACV,CAAC;AACD,QAAM,SAAS,aAAa,UAAU,qBAAqB;AAC3D,QAAM,EAAE,MAAM,SAAS,SAAS,QAAQ,IAAI;AAI5C,QAAM,YAAY,MAAM;AAExB,QAAM,WAAW,QAAQ,MAAM,IAAI,IAAI,KAAK,GAAG,CAAC,KAAK,CAAC;AAOtD,QAAM,SAAS,aAAa;AAC5B,QAA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;AAAA,MAChC;AAAA,MACC,MAAM;AAAA,OACT;AAAA;AAEJ;","names":[]}
|
|
@@ -35,7 +35,15 @@ interface MultiSelectProps extends Omit<ComponentPropsWithoutRef<"div">, "onChan
|
|
|
35
35
|
* this package carries it now, so a form can mark any of its fields rather than
|
|
36
36
|
* only the one that happened to have it first. */
|
|
37
37
|
invalid?: boolean;
|
|
38
|
+
/** What is wrong with the selection, in the caller's words. Rendered under the
|
|
39
|
+
* field, pointed at by the trigger's `aria-describedby` (merged with any the
|
|
40
|
+
* caller passed) and implies `invalid` — {@link Input}'s `error`, on the same
|
|
41
|
+
* rules. */
|
|
42
|
+
error?: ReactNode;
|
|
43
|
+
/** The trigger cannot be opened: FIELD_BASE's settled grey, no chevron (as a
|
|
44
|
+
* disabled {@link Select} drops its own), and a dimmed label. */
|
|
45
|
+
disabled?: boolean;
|
|
38
46
|
}
|
|
39
|
-
declare function MultiSelect({ options, values, onChange, allLabel, itemLabel, placeholder, label, searchLabel, selectAllLabel, clearLabel, className, panelClassName, invalid, "aria-label": ariaLabel, ...rest }: MultiSelectProps): react.JSX.Element;
|
|
47
|
+
declare function MultiSelect({ options, values, onChange, allLabel, itemLabel, placeholder, label, searchLabel, selectAllLabel, clearLabel, className, panelClassName, invalid, error, disabled, "aria-label": ariaLabel, "aria-describedby": ariaDescribedBy, ...rest }: MultiSelectProps): react.JSX.Element;
|
|
40
48
|
|
|
41
49
|
export { MultiSelect, type MultiSelectOption, type MultiSelectProps };
|
|
@@ -5,7 +5,7 @@ import { Check } from "lucide-react";
|
|
|
5
5
|
import { FieldChevron, FieldLabel, FIELD_TRIGGER, FIELD_INVALID, FIELD_FLOATING_PAD } from "./ui.js";
|
|
6
6
|
import { cn } from "../lib/cn.js";
|
|
7
7
|
import { DropdownPanel, DropdownSearchHeader, useDropdownSearch } from "./dropdown.js";
|
|
8
|
-
import { useActiveOptionScroll } from "./combobox-core.js";
|
|
8
|
+
import { useActiveOptionScroll, useComboboxFieldError } from "./combobox-core.js";
|
|
9
9
|
import {
|
|
10
10
|
DEFAULT_COMMON_LABELS,
|
|
11
11
|
DEFAULT_MULTI_SELECT_LABELS,
|
|
@@ -25,7 +25,10 @@ function MultiSelect({
|
|
|
25
25
|
className,
|
|
26
26
|
panelClassName,
|
|
27
27
|
invalid,
|
|
28
|
+
error,
|
|
29
|
+
disabled,
|
|
28
30
|
"aria-label": ariaLabel,
|
|
31
|
+
"aria-describedby": ariaDescribedBy,
|
|
29
32
|
...rest
|
|
30
33
|
}) {
|
|
31
34
|
const { open, setOpen, wrapperRef, triggerRef, closeToTrigger, query, setQuery, inputRef } = useDropdownSearch();
|
|
@@ -36,6 +39,7 @@ function MultiSelect({
|
|
|
36
39
|
selectedCount: itemLabel
|
|
37
40
|
});
|
|
38
41
|
const common = useKitLabels("common", DEFAULT_COMMON_LABELS);
|
|
42
|
+
const field = useComboboxFieldError(error, invalid, ariaDescribedBy);
|
|
39
43
|
const uid = useId();
|
|
40
44
|
const listboxId = `${uid}-listbox`;
|
|
41
45
|
const optionId = (index) => `${uid}-option-${index}`;
|
|
@@ -88,12 +92,13 @@ function MultiSelect({
|
|
|
88
92
|
// the thing with a role. Spread FIRST so the ARIA the trigger composes, and the
|
|
89
93
|
// handlers that open the list, cannot be replaced by accident from outside.
|
|
90
94
|
/* @__PURE__ */ jsxs("div", { ...rest, ref: wrapperRef, className: cn("relative", className), children: [
|
|
91
|
-
label !== void 0 && /* @__PURE__ */ jsx(FieldLabel, { children: label }),
|
|
95
|
+
label !== void 0 && /* @__PURE__ */ jsx(FieldLabel, { className: disabled ? "opacity-50" : void 0, children: label }),
|
|
92
96
|
/* @__PURE__ */ jsxs(
|
|
93
97
|
"button",
|
|
94
98
|
{
|
|
95
99
|
ref: triggerRef,
|
|
96
100
|
type: "button",
|
|
101
|
+
disabled,
|
|
97
102
|
role: "combobox",
|
|
98
103
|
"aria-expanded": open,
|
|
99
104
|
"aria-controls": listboxId,
|
|
@@ -110,15 +115,23 @@ function MultiSelect({
|
|
|
110
115
|
setActive(0);
|
|
111
116
|
}
|
|
112
117
|
},
|
|
113
|
-
"aria-invalid":
|
|
114
|
-
|
|
118
|
+
"aria-invalid": field.isInvalid || void 0,
|
|
119
|
+
"aria-describedby": field.describedBy,
|
|
120
|
+
className: cn(
|
|
121
|
+
FIELD_TRIGGER,
|
|
122
|
+
"pe-9",
|
|
123
|
+
label !== void 0 && FIELD_FLOATING_PAD,
|
|
124
|
+
// FIELD_TRIGGER's hover would still light a trigger nothing can open.
|
|
125
|
+
"disabled:hover:bg-[var(--bg-surface-2)]",
|
|
126
|
+
field.isInvalid && FIELD_INVALID
|
|
127
|
+
),
|
|
115
128
|
children: [
|
|
116
129
|
/* @__PURE__ */ jsx("span", { className: "truncate", children: selectedSummary }),
|
|
117
|
-
/* @__PURE__ */ jsx(FieldChevron, {})
|
|
130
|
+
!disabled && /* @__PURE__ */ jsx(FieldChevron, {})
|
|
118
131
|
]
|
|
119
132
|
}
|
|
120
133
|
),
|
|
121
|
-
open && /* @__PURE__ */ jsx(
|
|
134
|
+
open && !disabled && /* @__PURE__ */ jsx(
|
|
122
135
|
DropdownPanel,
|
|
123
136
|
{
|
|
124
137
|
className: cn("w-64", panelClassName),
|
|
@@ -176,7 +189,7 @@ function MultiSelect({
|
|
|
176
189
|
onClick: () => toggle(o.value),
|
|
177
190
|
onMouseEnter: () => setActive(i),
|
|
178
191
|
className: cn(
|
|
179
|
-
"flex w-full items-center justify-between gap-2 px-3 py-1.5 text-sm text-
|
|
192
|
+
"flex w-full items-center justify-between gap-2 px-3 py-1.5 text-sm text-start hover:bg-[var(--bg-hover)]",
|
|
180
193
|
checked && "bg-[var(--bg-active)]",
|
|
181
194
|
i === active && "bg-[var(--bg-hover)]"
|
|
182
195
|
),
|
|
@@ -199,7 +212,8 @@ function MultiSelect({
|
|
|
199
212
|
) }, o.value);
|
|
200
213
|
})
|
|
201
214
|
}
|
|
202
|
-
)
|
|
215
|
+
),
|
|
216
|
+
field.errorEl
|
|
203
217
|
] })
|
|
204
218
|
);
|
|
205
219
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/multi-select.tsx"],"sourcesContent":["import { useId, useMemo, useState } from \"react\";\nimport type {\n ComponentPropsWithoutRef,\n KeyboardEvent as ReactKeyboardEvent,\n ReactNode,\n} from \"react\";\nimport { Check } from \"lucide-react\";\nimport { FieldChevron, FieldLabel, FIELD_TRIGGER, FIELD_INVALID, FIELD_FLOATING_PAD } from \"./ui\";\nimport { cn } from \"../lib/cn\";\nimport { DropdownPanel, DropdownSearchHeader, useDropdownSearch } from \"./dropdown\";\nimport { useActiveOptionScroll } from \"./combobox-core\";\nimport {\n DEFAULT_COMMON_LABELS,\n DEFAULT_MULTI_SELECT_LABELS,\n useKitLabels,\n} from \"../i18n/kit-labels\";\n\nexport interface MultiSelectOption {\n value: string | number;\n label: string;\n hint?: string;\n}\n\n/** `onChange` is the kit's — \"the selection changed\", carrying the new values —\n * rather than the div's form event. */\nexport interface MultiSelectProps extends Omit<ComponentPropsWithoutRef<\"div\">, \"onChange\"> {\n options: MultiSelectOption[];\n values: (string | number)[];\n onChange: (next: (string | number)[]) => void;\n /** Displayed when no value is selected (i.e. \"all\"). Defaults to `placeholder`,\n * then to `multiSelect.all` from the {@link UiKitProvider}, then \"All\". */\n allLabel?: string;\n /** Singular/plural countable label, used when 1+ items are selected. Default:\n * `multiSelect.selectedCount` from the provider — the bare count in English. */\n itemLabel?: (count: number) => string;\n placeholder?: string;\n /** Embedded top-boundary label, matching the native Input/Select fields. */\n label?: ReactNode;\n /** Search-box placeholder. Default: `multiSelect.search` from the provider, else \"Search\". */\n searchLabel?: string;\n /** \"Select all\" action label. Default: `multiSelect.selectAll`, else \"Select all\". */\n selectAllLabel?: string;\n /** \"Clear\" action label. Default: `multiSelect.clear`, else \"Clear\". */\n clearLabel?: string;\n /** Extra classes for the open dropdown PANEL — the way to widen it past its\n * 16rem default when the rows carry more than a label (Keksdose feedback #147). */\n panelClassName?: string;\n /** Required and unanswered — {@link FIELD_INVALID}, the same rose border the\n * native `Select` has worn since feedback #235. Every field-styled control in\n * this package carries it now, so a form can mark any of its fields rather than\n * only the one that happened to have it first. */\n invalid?: boolean;\n}\n\nexport function MultiSelect({\n options,\n values,\n onChange,\n allLabel,\n itemLabel,\n placeholder,\n label,\n searchLabel,\n selectAllLabel,\n clearLabel,\n className,\n panelClassName,\n invalid,\n \"aria-label\": ariaLabel,\n ...rest\n}: MultiSelectProps) {\n const { open, setOpen, wrapperRef, triggerRef, closeToTrigger, query, setQuery, inputRef } =\n useDropdownSearch();\n // `allLabel` is deliberately NOT folded in here: between it and the provider's\n // `all` sits `placeholder`, which has always doubled as the \"nothing picked\" text,\n // and a caller who set it must keep seeing it.\n const labels = useKitLabels(\"multiSelect\", DEFAULT_MULTI_SELECT_LABELS, {\n search: searchLabel,\n selectAll: selectAllLabel,\n clear: clearLabel,\n selectedCount: itemLabel,\n });\n const common = useKitLabels(\"common\", DEFAULT_COMMON_LABELS);\n // One id per instance: `aria-controls` on the trigger names the list while the\n // list is still closed.\n const uid = useId();\n const listboxId = `${uid}-listbox`;\n const optionId = (index: number) => `${uid}-option-${index}`;\n // Which row the arrow keys are on. Reset from the handlers that change what the\n // list contains rather than from an effect — a render pass is not where this\n // decision belongs, and the two callers that move the list are right here.\n const [active, setActive] = useState(0);\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase();\n if (!q) return options;\n return options.filter(\n (o) =>\n o.label.toLowerCase().includes(q) ||\n (o.hint ?? \"\").toLowerCase().includes(q),\n );\n }, [options, query]);\n\n const valueSet = useMemo(() => new Set(values), [values]);\n const allChecked = options.length > 0 && options.every((o) => valueSet.has(o.value));\n const anyChecked = values.length > 0;\n const selectedSummary = (() => {\n if (!anyChecked || allChecked) return allLabel ?? placeholder ?? labels.all;\n return labels.selectedCount(values.length);\n })();\n\n const toggle = (val: string | number) => {\n if (valueSet.has(val)) onChange(values.filter((v) => v !== val));\n else onChange([...values, val]);\n };\n\n const selectAll = () => onChange(options.map((o) => o.value));\n const clearAll = () => onChange([]);\n\n const activeId = active >= 0 && active < filtered.length ? optionId(active) : undefined;\n useActiveOptionScroll(activeId);\n\n // The WAI-ARIA APG's listbox keyboard, handled on the search box because that is\n // where focus is while the panel is up. Escape is `useDropdown`'s, on the document.\n const onListKeyDown = (e: ReactKeyboardEvent<HTMLInputElement>) => {\n if (e.key === \"ArrowDown\") {\n e.preventDefault();\n setActive((i) => Math.min(i + 1, filtered.length - 1));\n } else if (e.key === \"ArrowUp\") {\n e.preventDefault();\n setActive((i) => Math.max(i - 1, 0));\n } else if (e.key === \"Home\") {\n e.preventDefault();\n setActive(0);\n } else if (e.key === \"End\") {\n e.preventDefault();\n setActive(filtered.length - 1);\n } else if (e.key === \"Enter\") {\n e.preventDefault();\n // Toggling keeps the panel open, exactly as clicking a row does: this control\n // exists to answer \"which of these\", which is rarely one of them.\n if (filtered[active]) toggle(filtered[active].value);\n } else if (e.key === \"Tab\") {\n e.preventDefault();\n closeToTrigger();\n }\n };\n\n return (\n // `rest` dresses the wrapper; the name belongs to the trigger below it, which is\n // the thing with a role. Spread FIRST so the ARIA the trigger composes, and the\n // handlers that open the list, cannot be replaced by accident from outside.\n <div {...rest} ref={wrapperRef} className={cn(\"relative\", className)}>\n {label !== undefined && <FieldLabel>{label}</FieldLabel>}\n <button\n ref={triggerRef}\n type=\"button\"\n // A combobox, not a bare button: this trigger carried `aria-invalid`, which\n // `button` does not support, so a required-and-empty filter painted its rose\n // border and announced nothing (ESLint's `role-supports-aria-props`, the\n // audit's §a11y). The role that describes it is the one that also supports\n // the attribute.\n role=\"combobox\"\n aria-expanded={open}\n aria-controls={listboxId}\n aria-haspopup=\"listbox\"\n // The label is a floating <span>, not a <label for>, so without this the\n // trigger announces only its summary — \"3 selected\", with nothing saying\n // three of WHAT. The label AND the summary, because `aria-label` replaces\n // the content rather than adding to it; the same composition its two\n // siblings use, so a form row of pickers reads the same way throughout.\n // A caller's own name wins: two filters labelled \"Accounts\" on one screen have\n // to be told apart, and only the caller knows by what.\n aria-label={\n ariaLabel ?? (typeof label === \"string\" ? common.fieldValue(label, selectedSummary) : undefined)\n }\n onClick={() => {\n setOpen((v) => !v);\n setActive(0);\n }}\n // Down/Up opens the list from the closed trigger, per the APG; Enter and\n // Space already do through the button's own click.\n onKeyDown={(e) => {\n if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n e.preventDefault();\n setOpen(true);\n setActive(0);\n }\n }}\n aria-invalid={invalid || undefined}\n className={cn(FIELD_TRIGGER, \"pr-9\", label !== undefined && FIELD_FLOATING_PAD, invalid && FIELD_INVALID)}\n >\n {/* The summary IS the field's value, so it inherits FIELD_BASE's ink rather\n than restating a lighter one (Keksdose dev#477). */}\n <span className=\"truncate\">{selectedSummary}</span>\n <FieldChevron />\n </button>\n {open && (\n <DropdownPanel\n // 16rem by default; `panelClassName` is how a caller widens it (Keksdose\n // feedback #147: the market picker's rows carry a postcode, a town, a\n // distance and a receipt count, all of which were being truncated). The\n // override used to be applied from the OUTSIDE with a\n // `[&>div]:w-full` descendant selector, which worked and was a hack —\n // \"change the package\" was the right call.\n className={cn(\"w-64\", panelClassName)}\n empty={filtered.length === 0}\n // The rows below are options, so the list around them has to be a listbox\n // — and one that says several answers are allowed, which is the only thing\n // that made the trigger's \"3 selected\" make sense to a reader.\n listProps={{ id: listboxId, role: \"listbox\", \"aria-multiselectable\": true }}\n header={\n <>\n <DropdownSearchHeader\n query={query}\n onQueryChange={(v) => {\n setQuery(v);\n // The list under the highlight just changed; keeping the old index\n // would point `aria-activedescendant` at a different option than\n // the one the user was on.\n setActive(0);\n }}\n inputRef={inputRef}\n placeholder={labels.search}\n listboxId={listboxId}\n activeId={activeId}\n onKeyDown={onListKeyDown}\n />\n <div className=\"flex items-center justify-between gap-2 px-2 py-1.5 text-xs\">\n <button\n type=\"button\"\n onClick={selectAll}\n disabled={allChecked}\n className=\"rounded px-2 py-0.5 text-[var(--text-secondary)] hover:bg-[var(--bg-hover)] disabled:opacity-40\"\n >\n {labels.selectAll}\n </button>\n <button\n type=\"button\"\n onClick={clearAll}\n disabled={!anyChecked}\n className=\"rounded px-2 py-0.5 text-[var(--text-secondary)] hover:bg-[var(--bg-hover)] disabled:opacity-40\"\n >\n {labels.clear}\n </button>\n </div>\n </>\n }\n >\n {filtered.map((o, i) => {\n const checked = valueSet.has(o.value);\n return (\n <li key={o.value} role=\"presentation\">\n <button\n type=\"button\"\n id={optionId(i)}\n // The checked state used to exist ONLY as the decorative span\n // below (the audit's §a11y): the row said its label and nothing\n // else, so \"selected\" was imperceptible without sight. This is\n // the same state, in the one place a reader looks for it.\n role=\"option\"\n aria-selected={checked}\n // Focus stays in the search box — that is what\n // `aria-activedescendant` is for — so the rows are not tab stops.\n tabIndex={-1}\n onClick={() => toggle(o.value)}\n onMouseEnter={() => setActive(i)}\n className={cn(\n \"flex w-full items-center justify-between gap-2 px-3 py-1.5 text-sm text-left hover:bg-[var(--bg-hover)]\",\n checked && \"bg-[var(--bg-active)]\",\n i === active && \"bg-[var(--bg-hover)]\",\n )}\n >\n <span className=\"flex items-center gap-2 min-w-0\">\n <span\n // A picture of `aria-selected` above; a reader that met both\n // would be told twice.\n aria-hidden\n className={cn(\n \"flex size-4 shrink-0 items-center justify-center rounded border\",\n checked\n ? \"border-[var(--bg-inverse)] bg-[var(--bg-inverse)] text-[var(--text-inverse)]\"\n : \"border-[var(--border-strong)] bg-[var(--bg-surface)]\",\n )}\n >\n {checked && <Check className=\"size-3\" />}\n </span>\n <span className=\"truncate text-[var(--text-primary)]\">{o.label}</span>\n {o.hint && (\n <span className=\"truncate text-xs text-[var(--text-placeholder)]\">\n {o.hint}\n </span>\n )}\n </span>\n </button>\n </li>\n );\n })}\n </DropdownPanel>\n )}\n </div>\n );\n}\n"],"mappings":";AAyJ8B,SA2DlB,UA3DkB,KACxB,YADwB;AAzJ9B,SAAS,OAAO,SAAS,gBAAgB;AAMzC,SAAS,aAAa;AACtB,SAAS,cAAc,YAAY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MAAK;AAAA,kBACL,SAAS;AAAA,kBACT,UAAU;AAAA,kBACV,WAAU;AAAA,kBAET,iBAAO;AAAA;AAAA,cACV;AAAA,cACA;AAAA,gBAAC;AAAA;AAAA,kBACC,MAAK;AAAA,kBACL,SAAS;AAAA,kBACT,UAAU,CAAC;AAAA,kBACX,WAAU;AAAA,kBAET,iBAAO;AAAA;AAAA,cACV;AAAA,eACF;AAAA,aACF;AAAA,UAGD,mBAAS,IAAI,CAAC,GAAG,MAAM;AACpB,kBAAM,UAAU,SAAS,IAAI,EAAE,KAAK;AACpC,mBACE,oBAAC,QAAiB,MAAK,gBACrB;AAAA,cAAC;AAAA;AAAA,gBACC,MAAK;AAAA,gBACL,IAAI,SAAS,CAAC;AAAA,gBAKd,MAAK;AAAA,gBACL,iBAAe;AAAA,gBAGf,UAAU;AAAA,gBACV,SAAS,MAAM,OAAO,EAAE,KAAK;AAAA,gBAC7B,cAAc,MAAM,UAAU,CAAC;AAAA,gBAC/B,WAAW;AAAA,kBACT;AAAA,kBACA,WAAW;AAAA,kBACX,MAAM,UAAU;AAAA,gBAClB;AAAA,gBAEA,+BAAC,UAAK,WAAU,mCACd;AAAA;AAAA,oBAAC;AAAA;AAAA,sBAGC,eAAW;AAAA,sBACX,WAAW;AAAA,wBACT;AAAA,wBACA,UACI,iFACA;AAAA,sBACN;AAAA,sBAEC,qBAAW,oBAAC,SAAM,WAAU,UAAS;AAAA;AAAA,kBACxC;AAAA,kBACA,oBAAC,UAAK,WAAU,uCAAuC,YAAE,OAAM;AAAA,kBAC9D,EAAE,QACD,oBAAC,UAAK,WAAU,mDACb,YAAE,MACL;AAAA,mBAEJ;AAAA;AAAA,YACF,KA1CO,EAAE,KA2CX;AAAA,UAEJ,CAAC;AAAA;AAAA,MACL;AAAA,OAEJ;AAAA;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/multi-select.tsx"],"sourcesContent":["import { useId, useMemo, useState } from \"react\";\nimport type {\n ComponentPropsWithoutRef,\n KeyboardEvent as ReactKeyboardEvent,\n ReactNode,\n} from \"react\";\nimport { Check } from \"lucide-react\";\nimport { FieldChevron, FieldLabel, FIELD_TRIGGER, FIELD_INVALID, FIELD_FLOATING_PAD } from \"./ui\";\nimport { cn } from \"../lib/cn\";\nimport { DropdownPanel, DropdownSearchHeader, useDropdownSearch } from \"./dropdown\";\nimport { useActiveOptionScroll, useComboboxFieldError } from \"./combobox-core\";\nimport {\n DEFAULT_COMMON_LABELS,\n DEFAULT_MULTI_SELECT_LABELS,\n useKitLabels,\n} from \"../i18n/kit-labels\";\n\nexport interface MultiSelectOption {\n value: string | number;\n label: string;\n hint?: string;\n}\n\n/** `onChange` is the kit's — \"the selection changed\", carrying the new values —\n * rather than the div's form event. */\nexport interface MultiSelectProps extends Omit<ComponentPropsWithoutRef<\"div\">, \"onChange\"> {\n options: MultiSelectOption[];\n values: (string | number)[];\n onChange: (next: (string | number)[]) => void;\n /** Displayed when no value is selected (i.e. \"all\"). Defaults to `placeholder`,\n * then to `multiSelect.all` from the {@link UiKitProvider}, then \"All\". */\n allLabel?: string;\n /** Singular/plural countable label, used when 1+ items are selected. Default:\n * `multiSelect.selectedCount` from the provider — the bare count in English. */\n itemLabel?: (count: number) => string;\n placeholder?: string;\n /** Embedded top-boundary label, matching the native Input/Select fields. */\n label?: ReactNode;\n /** Search-box placeholder. Default: `multiSelect.search` from the provider, else \"Search\". */\n searchLabel?: string;\n /** \"Select all\" action label. Default: `multiSelect.selectAll`, else \"Select all\". */\n selectAllLabel?: string;\n /** \"Clear\" action label. Default: `multiSelect.clear`, else \"Clear\". */\n clearLabel?: string;\n /** Extra classes for the open dropdown PANEL — the way to widen it past its\n * 16rem default when the rows carry more than a label (Keksdose feedback #147). */\n panelClassName?: string;\n /** Required and unanswered — {@link FIELD_INVALID}, the same rose border the\n * native `Select` has worn since feedback #235. Every field-styled control in\n * this package carries it now, so a form can mark any of its fields rather than\n * only the one that happened to have it first. */\n invalid?: boolean;\n /** What is wrong with the selection, in the caller's words. Rendered under the\n * field, pointed at by the trigger's `aria-describedby` (merged with any the\n * caller passed) and implies `invalid` — {@link Input}'s `error`, on the same\n * rules. */\n error?: ReactNode;\n /** The trigger cannot be opened: FIELD_BASE's settled grey, no chevron (as a\n * disabled {@link Select} drops its own), and a dimmed label. */\n disabled?: boolean;\n}\n\nexport function MultiSelect({\n options,\n values,\n onChange,\n allLabel,\n itemLabel,\n placeholder,\n label,\n searchLabel,\n selectAllLabel,\n clearLabel,\n className,\n panelClassName,\n invalid,\n error,\n disabled,\n \"aria-label\": ariaLabel,\n \"aria-describedby\": ariaDescribedBy,\n ...rest\n}: MultiSelectProps) {\n const { open, setOpen, wrapperRef, triggerRef, closeToTrigger, query, setQuery, inputRef } =\n useDropdownSearch();\n // `allLabel` is deliberately NOT folded in here: between it and the provider's\n // `all` sits `placeholder`, which has always doubled as the \"nothing picked\" text,\n // and a caller who set it must keep seeing it.\n const labels = useKitLabels(\"multiSelect\", DEFAULT_MULTI_SELECT_LABELS, {\n search: searchLabel,\n selectAll: selectAllLabel,\n clear: clearLabel,\n selectedCount: itemLabel,\n });\n const common = useKitLabels(\"common\", DEFAULT_COMMON_LABELS);\n const field = useComboboxFieldError(error, invalid, ariaDescribedBy);\n // One id per instance: `aria-controls` on the trigger names the list while the\n // list is still closed.\n const uid = useId();\n const listboxId = `${uid}-listbox`;\n const optionId = (index: number) => `${uid}-option-${index}`;\n // Which row the arrow keys are on. Reset from the handlers that change what the\n // list contains rather than from an effect — a render pass is not where this\n // decision belongs, and the two callers that move the list are right here.\n const [active, setActive] = useState(0);\n\n const filtered = useMemo(() => {\n const q = query.trim().toLowerCase();\n if (!q) return options;\n return options.filter(\n (o) =>\n o.label.toLowerCase().includes(q) ||\n (o.hint ?? \"\").toLowerCase().includes(q),\n );\n }, [options, query]);\n\n const valueSet = useMemo(() => new Set(values), [values]);\n const allChecked = options.length > 0 && options.every((o) => valueSet.has(o.value));\n const anyChecked = values.length > 0;\n const selectedSummary = (() => {\n if (!anyChecked || allChecked) return allLabel ?? placeholder ?? labels.all;\n return labels.selectedCount(values.length);\n })();\n\n const toggle = (val: string | number) => {\n if (valueSet.has(val)) onChange(values.filter((v) => v !== val));\n else onChange([...values, val]);\n };\n\n const selectAll = () => onChange(options.map((o) => o.value));\n const clearAll = () => onChange([]);\n\n const activeId = active >= 0 && active < filtered.length ? optionId(active) : undefined;\n useActiveOptionScroll(activeId);\n\n // The WAI-ARIA APG's listbox keyboard, handled on the search box because that is\n // where focus is while the panel is up. Escape is `useDropdown`'s, on the document.\n const onListKeyDown = (e: ReactKeyboardEvent<HTMLInputElement>) => {\n if (e.key === \"ArrowDown\") {\n e.preventDefault();\n setActive((i) => Math.min(i + 1, filtered.length - 1));\n } else if (e.key === \"ArrowUp\") {\n e.preventDefault();\n setActive((i) => Math.max(i - 1, 0));\n } else if (e.key === \"Home\") {\n e.preventDefault();\n setActive(0);\n } else if (e.key === \"End\") {\n e.preventDefault();\n setActive(filtered.length - 1);\n } else if (e.key === \"Enter\") {\n e.preventDefault();\n // Toggling keeps the panel open, exactly as clicking a row does: this control\n // exists to answer \"which of these\", which is rarely one of them.\n if (filtered[active]) toggle(filtered[active].value);\n } else if (e.key === \"Tab\") {\n e.preventDefault();\n closeToTrigger();\n }\n };\n\n return (\n // `rest` dresses the wrapper; the name belongs to the trigger below it, which is\n // the thing with a role. Spread FIRST so the ARIA the trigger composes, and the\n // handlers that open the list, cannot be replaced by accident from outside.\n <div {...rest} ref={wrapperRef} className={cn(\"relative\", className)}>\n {label !== undefined && <FieldLabel className={disabled ? \"opacity-50\" : undefined}>{label}</FieldLabel>}\n <button\n ref={triggerRef}\n type=\"button\"\n disabled={disabled}\n // A combobox, not a bare button: this trigger carried `aria-invalid`, which\n // `button` does not support, so a required-and-empty filter painted its rose\n // border and announced nothing (ESLint's `role-supports-aria-props`, the\n // audit's §a11y). The role that describes it is the one that also supports\n // the attribute.\n role=\"combobox\"\n aria-expanded={open}\n aria-controls={listboxId}\n aria-haspopup=\"listbox\"\n // The label is a floating <span>, not a <label for>, so without this the\n // trigger announces only its summary — \"3 selected\", with nothing saying\n // three of WHAT. The label AND the summary, because `aria-label` replaces\n // the content rather than adding to it; the same composition its two\n // siblings use, so a form row of pickers reads the same way throughout.\n // A caller's own name wins: two filters labelled \"Accounts\" on one screen have\n // to be told apart, and only the caller knows by what.\n aria-label={\n ariaLabel ?? (typeof label === \"string\" ? common.fieldValue(label, selectedSummary) : undefined)\n }\n onClick={() => {\n setOpen((v) => !v);\n setActive(0);\n }}\n // Down/Up opens the list from the closed trigger, per the APG; Enter and\n // Space already do through the button's own click.\n onKeyDown={(e) => {\n if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n e.preventDefault();\n setOpen(true);\n setActive(0);\n }\n }}\n aria-invalid={field.isInvalid || undefined}\n // On the TRIGGER, where focus lands — the `aria-describedby` a caller put on\n // the component is taken off the wrapper for the same reason.\n aria-describedby={field.describedBy}\n className={cn(\n FIELD_TRIGGER,\n \"pe-9\",\n label !== undefined && FIELD_FLOATING_PAD,\n // FIELD_TRIGGER's hover would still light a trigger nothing can open.\n \"disabled:hover:bg-[var(--bg-surface-2)]\",\n field.isInvalid && FIELD_INVALID,\n )}\n >\n {/* The summary IS the field's value, so it inherits FIELD_BASE's ink rather\n than restating a lighter one (Keksdose dev#477). */}\n <span className=\"truncate\">{selectedSummary}</span>\n {!disabled && <FieldChevron />}\n </button>\n {open && !disabled && (\n <DropdownPanel\n // 16rem by default; `panelClassName` is how a caller widens it (Keksdose\n // feedback #147: the market picker's rows carry a postcode, a town, a\n // distance and a receipt count, all of which were being truncated). The\n // override used to be applied from the OUTSIDE with a\n // `[&>div]:w-full` descendant selector, which worked and was a hack —\n // \"change the package\" was the right call.\n className={cn(\"w-64\", panelClassName)}\n empty={filtered.length === 0}\n // The rows below are options, so the list around them has to be a listbox\n // — and one that says several answers are allowed, which is the only thing\n // that made the trigger's \"3 selected\" make sense to a reader.\n listProps={{ id: listboxId, role: \"listbox\", \"aria-multiselectable\": true }}\n header={\n <>\n <DropdownSearchHeader\n query={query}\n onQueryChange={(v) => {\n setQuery(v);\n // The list under the highlight just changed; keeping the old index\n // would point `aria-activedescendant` at a different option than\n // the one the user was on.\n setActive(0);\n }}\n inputRef={inputRef}\n placeholder={labels.search}\n listboxId={listboxId}\n activeId={activeId}\n onKeyDown={onListKeyDown}\n />\n <div className=\"flex items-center justify-between gap-2 px-2 py-1.5 text-xs\">\n <button\n type=\"button\"\n onClick={selectAll}\n disabled={allChecked}\n className=\"rounded px-2 py-0.5 text-[var(--text-secondary)] hover:bg-[var(--bg-hover)] disabled:opacity-40\"\n >\n {labels.selectAll}\n </button>\n <button\n type=\"button\"\n onClick={clearAll}\n disabled={!anyChecked}\n className=\"rounded px-2 py-0.5 text-[var(--text-secondary)] hover:bg-[var(--bg-hover)] disabled:opacity-40\"\n >\n {labels.clear}\n </button>\n </div>\n </>\n }\n >\n {filtered.map((o, i) => {\n const checked = valueSet.has(o.value);\n return (\n <li key={o.value} role=\"presentation\">\n <button\n type=\"button\"\n id={optionId(i)}\n // The checked state used to exist ONLY as the decorative span\n // below (the audit's §a11y): the row said its label and nothing\n // else, so \"selected\" was imperceptible without sight. This is\n // the same state, in the one place a reader looks for it.\n role=\"option\"\n aria-selected={checked}\n // Focus stays in the search box — that is what\n // `aria-activedescendant` is for — so the rows are not tab stops.\n tabIndex={-1}\n onClick={() => toggle(o.value)}\n onMouseEnter={() => setActive(i)}\n className={cn(\n \"flex w-full items-center justify-between gap-2 px-3 py-1.5 text-sm text-start hover:bg-[var(--bg-hover)]\",\n checked && \"bg-[var(--bg-active)]\",\n i === active && \"bg-[var(--bg-hover)]\",\n )}\n >\n <span className=\"flex items-center gap-2 min-w-0\">\n <span\n // A picture of `aria-selected` above; a reader that met both\n // would be told twice.\n aria-hidden\n className={cn(\n \"flex size-4 shrink-0 items-center justify-center rounded border\",\n checked\n ? \"border-[var(--bg-inverse)] bg-[var(--bg-inverse)] text-[var(--text-inverse)]\"\n : \"border-[var(--border-strong)] bg-[var(--bg-surface)]\",\n )}\n >\n {checked && <Check className=\"size-3\" />}\n </span>\n <span className=\"truncate text-[var(--text-primary)]\">{o.label}</span>\n {o.hint && (\n <span className=\"truncate text-xs text-[var(--text-placeholder)]\">\n {o.hint}\n </span>\n )}\n </span>\n </button>\n </li>\n );\n })}\n </DropdownPanel>\n )}\n {/* After the panel, not before it: the panel is `absolute` with no `top`, so it\n opens at its place in the flow — under the message, had the message come\n first. */}\n {field.errorEl}\n </div>\n );\n}\n"],"mappings":";AAqK8B,SAsElB,UAtEkB,KACxB,YADwB;AArK9B,SAAS,OAAO,SAAS,gBAAgB;AAMzC,SAAS,aAAa;AACtB,SAAS,cAAc,YAAY,eAAe,eAAe,0BAA0B;AAC3F,SAAS,UAAU;AACnB,SAAS,eAAe,sBAAsB,yBAAyB;AACvE,SAAS,uBAAuB,6BAA6B;AAC7D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA+CA,SAAS,YAAY;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd,oBAAoB;AAAA,EACpB,GAAG;AACL,GAAqB;AACnB,QAAM,EAAE,MAAM,SAAS,YAAY,YAAY,gBAAgB,OAAO,UAAU,SAAS,IACvF,kBAAkB;AAIpB,QAAM,SAAS,aAAa,eAAe,6BAA6B;AAAA,IACtE,QAAQ;AAAA,IACR,WAAW;AAAA,IACX,OAAO;AAAA,IACP,eAAe;AAAA,EACjB,CAAC;AACD,QAAM,SAAS,aAAa,UAAU,qBAAqB;AAC3D,QAAM,QAAQ,sBAAsB,OAAO,SAAS,eAAe;AAGnE,QAAM,MAAM,MAAM;AAClB,QAAM,YAAY,GAAG,GAAG;AACxB,QAAM,WAAW,CAAC,UA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,EAAE,KAAK;AAAA,gBAC7B,cAAc,MAAM,UAAU,CAAC;AAAA,gBAC/B,WAAW;AAAA,kBACT;AAAA,kBACA,WAAW;AAAA,kBACX,MAAM,UAAU;AAAA,gBAClB;AAAA,gBAEA,+BAAC,UAAK,WAAU,mCACd;AAAA;AAAA,oBAAC;AAAA;AAAA,sBAGC,eAAW;AAAA,sBACX,WAAW;AAAA,wBACT;AAAA,wBACA,UACI,iFACA;AAAA,sBACN;AAAA,sBAEC,qBAAW,oBAAC,SAAM,WAAU,UAAS;AAAA;AAAA,kBACxC;AAAA,kBACA,oBAAC,UAAK,WAAU,uCAAuC,YAAE,OAAM;AAAA,kBAC9D,EAAE,QACD,oBAAC,UAAK,WAAU,mDACb,YAAE,MACL;AAAA,mBAEJ;AAAA;AAAA,YACF,KA1CO,EAAE,KA2CX;AAAA,UAEJ,CAAC;AAAA;AAAA,MACL;AAAA,MAKD,MAAM;AAAA,OACT;AAAA;AAEJ;","names":[]}
|
|
@@ -10,6 +10,8 @@ import './chip.js';
|
|
|
10
10
|
import 'lucide-react';
|
|
11
11
|
import './field-sync.js';
|
|
12
12
|
import './ui.js';
|
|
13
|
+
import './tooltip.js';
|
|
14
|
+
import '../hooks/use-anchored-rect.js';
|
|
13
15
|
import '../wizard/types.js';
|
|
14
16
|
import '../tour/tour.js';
|
|
15
17
|
import '../search/command-palette.js';
|
|
@@ -27,6 +29,9 @@ import './icon-picker.js';
|
|
|
27
29
|
import './dialog-frame.js';
|
|
28
30
|
import './modal.js';
|
|
29
31
|
import './file-button.js';
|
|
32
|
+
import './measured-grid.js';
|
|
33
|
+
import '../feedback/feedback-attachment.js';
|
|
34
|
+
import '../feedback/feedback-dialog.js';
|
|
30
35
|
import './numpad-sheet.js';
|
|
31
36
|
|
|
32
37
|
type NumberInputProps = ComponentProps<typeof NumberInput>;
|
|
@@ -10,6 +10,8 @@ import './chip.js';
|
|
|
10
10
|
import 'lucide-react';
|
|
11
11
|
import './field-sync.js';
|
|
12
12
|
import './ui.js';
|
|
13
|
+
import './tooltip.js';
|
|
14
|
+
import '../hooks/use-anchored-rect.js';
|
|
13
15
|
import '../wizard/types.js';
|
|
14
16
|
import '../tour/tour.js';
|
|
15
17
|
import '../search/command-palette.js';
|
|
@@ -27,6 +29,9 @@ import './icon-picker.js';
|
|
|
27
29
|
import './dialog-frame.js';
|
|
28
30
|
import './modal.js';
|
|
29
31
|
import './file-button.js';
|
|
32
|
+
import './measured-grid.js';
|
|
33
|
+
import '../feedback/feedback-attachment.js';
|
|
34
|
+
import '../feedback/feedback-dialog.js';
|
|
30
35
|
|
|
31
36
|
interface NumberInputProps {
|
|
32
37
|
value: string;
|
|
@@ -106,7 +106,7 @@ function NumberInput({
|
|
|
106
106
|
className: cn(
|
|
107
107
|
asDisplay ? cn(FIELD_DISPLAY, "text-4xl font-semibold leading-tight tracking-tight tabular-nums") : labelled ? FLOATING_INPUT_CLASS : FIELD_BASE,
|
|
108
108
|
inputClassName,
|
|
109
|
-
showCalc && suffix !== void 0 ? "
|
|
109
|
+
showCalc && suffix !== void 0 ? "pe-16" : showCalc ? "pe-9" : suffix !== void 0 ? "pe-8" : void 0,
|
|
110
110
|
invalid && FIELD_INVALID
|
|
111
111
|
)
|
|
112
112
|
}
|
|
@@ -114,7 +114,7 @@ function NumberInput({
|
|
|
114
114
|
(showCalc || suffix !== void 0) && // One flex track for both, so the unit and the calculator sit side by side
|
|
115
115
|
// instead of stacking on the same corner — AmountInput's arrangement, which
|
|
116
116
|
// has carried a chip and a calculator together since #430.
|
|
117
|
-
/* @__PURE__ */ jsxs("div", { className: "absolute inset-y-0
|
|
117
|
+
/* @__PURE__ */ jsxs("div", { className: "absolute inset-y-0 end-0 flex items-center", children: [
|
|
118
118
|
showCalc && /* @__PURE__ */ jsx(
|
|
119
119
|
CalculatorButton,
|
|
120
120
|
{
|
|
@@ -129,7 +129,7 @@ function NumberInput({
|
|
|
129
129
|
"span",
|
|
130
130
|
{
|
|
131
131
|
"aria-hidden": true,
|
|
132
|
-
className: "pointer-events-none
|
|
132
|
+
className: "pointer-events-none pe-3 text-xs font-medium text-[var(--text-muted)]",
|
|
133
133
|
children: suffix
|
|
134
134
|
}
|
|
135
135
|
)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/number-input.tsx"],"sourcesContent":["import { useId, useRef, useState } from \"react\";\nimport type { KeyboardEvent, ReactNode } from \"react\";\nimport { CalculatorButton, type CalculatorButtonLabels } from \"./calculator\";\nimport { NumberPadSheet, type NumberPadSheetLabels } from \"./numpad-sheet\";\nimport { FIELD_BASE, FIELD_DISPLAY, FIELD_INVALID, FLOATING_INPUT_CLASS, FloatingField, PHONE_QUERY } from \"./ui\";\nimport { cn } from \"../lib/cn\";\nimport { commitExpression, formatResult, sanitizeLive } from \"../lib/calc\";\nimport { useMediaQuery } from \"../hooks/use-media-query\";\n\ninterface NumberInputProps {\n value: string;\n /** Fired on every keystroke with the raw text (comma → dot, operators kept so\n * 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 ariaLabel?: 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). */\n hint?: ReactNode;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\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\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/**\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 budgets, goals,\n * invoice totals and split lines.\n */\nexport function NumberInput({\n value,\n onChange,\n onCommit,\n label,\n ariaLabel,\n labels,\n placeholder,\n disabled,\n autoFocus,\n className,\n inputClassName,\n id,\n calculator = true,\n variant = \"field\",\n hint,\n invalid,\n suffix,\n step,\n min,\n max,\n}: NumberInputProps) {\n const generatedId = useId();\n const fieldId = id ?? generatedId;\n const labelled = label !== undefined;\n // On phones we suppress the OS keyboard (inputMode=\"none\" below) for our own\n // calculator numpad, so the desktop popover trigger is hidden (feedback #334).\n const isMobile = useMediaQuery(PHONE_QUERY, false);\n const asDisplay = isMobile && variant === \"display\";\n const showCalc = calculator && !disabled && !isMobile;\n const [focused, setFocused] = useState(false);\n // On mobile, focusing opens the numpad bottom sheet instead of the native\n // keyboard (#334); the ref lets its \"Done\" blur → commit + close.\n const showNumpad = isMobile && !disabled && focused;\n const inputRef = useRef<HTMLInputElement>(null);\n\n const commit = () => {\n const next = commitExpression(value);\n if (next !== value) onChange(next);\n onCommit?.(next);\n };\n\n const stepBy = (count: number) => {\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 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 return (\n <FloatingField\n className={cn(\"w-full\", className)}\n htmlFor={fieldId}\n label={label}\n srOnlyLabel={asDisplay}\n hint={hint}\n >\n <input\n ref={inputRef}\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 autoFocus={autoFocus}\n disabled={disabled}\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={value}\n onChange={(e) => onChange(sanitizeLive(e.target.value))}\n onFocus={() => setFocused(true)}\n onBlur={() => {\n commit();\n setFocused(false);\n }}\n onKeyDown={onKeyDown}\n aria-invalid={invalid || undefined}\n // The right-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 ? \"pr-16\" : showCalc ? \"pr-9\" : suffix !== undefined ? \"pr-8\" : undefined,\n invalid && FIELD_INVALID,\n )}\n />\n {(showCalc || suffix !== undefined) && (\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 className=\"absolute inset-y-0 right-0 flex items-center\">\n {showCalc && (\n <CalculatorButton\n value={value}\n onChange={onChange}\n className=\"self-stretch px-2.5\"\n ariaLabel={labels?.calculatorTrigger}\n labels={labels?.calculator}\n />\n )}\n {suffix !== undefined && (\n <span\n aria-hidden\n className=\"pointer-events-none pr-3 text-xs font-medium text-[var(--text-muted)]\"\n >\n {suffix}\n </span>\n )}\n </div>\n )}\n {showNumpad && (\n <NumberPadSheet\n value={value}\n onChange={onChange}\n onDone={() => inputRef.current?.blur()}\n label={label}\n labels={labels?.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":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/number-input.tsx"],"sourcesContent":["import { useId, useRef, useState } from \"react\";\nimport type { KeyboardEvent, ReactNode } from \"react\";\nimport { CalculatorButton, type CalculatorButtonLabels } from \"./calculator\";\nimport { NumberPadSheet, type NumberPadSheetLabels } from \"./numpad-sheet\";\nimport { FIELD_BASE, FIELD_DISPLAY, FIELD_INVALID, FLOATING_INPUT_CLASS, FloatingField, PHONE_QUERY } from \"./ui\";\nimport { cn } from \"../lib/cn\";\nimport { commitExpression, formatResult, sanitizeLive } from \"../lib/calc\";\nimport { useMediaQuery } from \"../hooks/use-media-query\";\n\ninterface NumberInputProps {\n value: string;\n /** Fired on every keystroke with the raw text (comma → dot, operators kept so\n * 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 ariaLabel?: 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). */\n hint?: ReactNode;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\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\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/**\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 budgets, goals,\n * invoice totals and split lines.\n */\nexport function NumberInput({\n value,\n onChange,\n onCommit,\n label,\n ariaLabel,\n labels,\n placeholder,\n disabled,\n autoFocus,\n className,\n inputClassName,\n id,\n calculator = true,\n variant = \"field\",\n hint,\n invalid,\n suffix,\n step,\n min,\n max,\n}: NumberInputProps) {\n const generatedId = useId();\n const fieldId = id ?? generatedId;\n const labelled = label !== undefined;\n // On phones we suppress the OS keyboard (inputMode=\"none\" below) for our own\n // calculator numpad, so the desktop popover trigger is hidden (feedback #334).\n const isMobile = useMediaQuery(PHONE_QUERY, false);\n const asDisplay = isMobile && variant === \"display\";\n const showCalc = calculator && !disabled && !isMobile;\n const [focused, setFocused] = useState(false);\n // On mobile, focusing opens the numpad bottom sheet instead of the native\n // keyboard (#334); the ref lets its \"Done\" blur → commit + close.\n const showNumpad = isMobile && !disabled && focused;\n const inputRef = useRef<HTMLInputElement>(null);\n\n const commit = () => {\n const next = commitExpression(value);\n if (next !== value) onChange(next);\n onCommit?.(next);\n };\n\n const stepBy = (count: number) => {\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 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 return (\n <FloatingField\n className={cn(\"w-full\", className)}\n htmlFor={fieldId}\n label={label}\n srOnlyLabel={asDisplay}\n hint={hint}\n >\n <input\n ref={inputRef}\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 autoFocus={autoFocus}\n disabled={disabled}\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={value}\n onChange={(e) => onChange(sanitizeLive(e.target.value))}\n onFocus={() => setFocused(true)}\n onBlur={() => {\n commit();\n setFocused(false);\n }}\n onKeyDown={onKeyDown}\n aria-invalid={invalid || undefined}\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 )}\n />\n {(showCalc || suffix !== undefined) && (\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 className=\"absolute inset-y-0 end-0 flex items-center\">\n {showCalc && (\n <CalculatorButton\n value={value}\n onChange={onChange}\n className=\"self-stretch px-2.5\"\n ariaLabel={labels?.calculatorTrigger}\n labels={labels?.calculator}\n />\n )}\n {suffix !== undefined && (\n <span\n aria-hidden\n className=\"pointer-events-none pe-3 text-xs font-medium text-[var(--text-muted)]\"\n >\n {suffix}\n </span>\n )}\n </div>\n )}\n {showNumpad && (\n <NumberPadSheet\n value={value}\n onChange={onChange}\n onDone={() => inputRef.current?.blur()}\n label={label}\n labels={labels?.pad}\n />\n )}\n </FloatingField>\n );\n}\n"],"mappings":";AAoNM,cA4CE,YA5CF;AApNN,SAAS,OAAO,QAAQ,gBAAgB;AAExC,SAAS,wBAAqD;AAC9D,SAAS,sBAAiD;AAC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L,IAAI;AAAA,YACJ,cAAY;AAAA,YACZ,MAAK;AAAA,YAGL,WAAW,WAAW,SAAS;AAAA,YAC/B,cAAa;AAAA,YACb;AAAA,YACA;AAAA,YAIA,aAAa,YAAa,eAAe,MAAO,WAAW,MAAM;AAAA,YACjE;AAAA,YACA,UAAU,CAAC,MAAM,SAAS,aAAa,EAAE,OAAO,KAAK,CAAC;AAAA,YACtD,SAAS,MAAM,WAAW,IAAI;AAAA,YAC9B,QAAQ,MAAM;AACZ,qBAAO;AACP,yBAAW,KAAK;AAAA,YAClB;AAAA,YACA;AAAA,YACA,gBAAc,WAAW;AAAA,YAMzB,WAAW;AAAA,cACT,YACI,GAAG,eAAe,kEAAkE,IACpF,WACE,uBACA;AAAA,cACN;AAAA,cACA,YAAY,WAAW,SAAY,UAAU,WAAW,SAAS,WAAW,SAAY,SAAS;AAAA,cACjG,WAAW;AAAA,YACb;AAAA;AAAA,QACF;AAAA,SACE,YAAY,WAAW;AAAA;AAAA;AAAA,QAIvB,qBAAC,SAAI,WAAU,8CACZ;AAAA,sBACC;AAAA,YAAC;AAAA;AAAA,cACC;AAAA,cACA;AAAA,cACA,WAAU;AAAA,cACV,WAAW,QAAQ;AAAA,cACnB,QAAQ,QAAQ;AAAA;AAAA,UAClB;AAAA,UAED,WAAW,UACV;AAAA,YAAC;AAAA;AAAA,cACC,eAAW;AAAA,cACX,WAAU;AAAA,cAET;AAAA;AAAA,UACH;AAAA,WAEJ;AAAA,QAED,cACC;AAAA,UAAC;AAAA;AAAA,YACC;AAAA,YACA;AAAA,YACA,QAAQ,MAAM,SAAS,SAAS,KAAK;AAAA,YACrC;AAAA,YACA,QAAQ,QAAQ;AAAA;AAAA,QAClB;AAAA;AAAA;AAAA,EAEJ;AAEJ;","names":[]}
|
|
@@ -8,6 +8,8 @@ import './chip.js';
|
|
|
8
8
|
import 'lucide-react';
|
|
9
9
|
import './field-sync.js';
|
|
10
10
|
import './ui.js';
|
|
11
|
+
import './tooltip.js';
|
|
12
|
+
import '../hooks/use-anchored-rect.js';
|
|
11
13
|
import '../wizard/types.js';
|
|
12
14
|
import '../tour/tour.js';
|
|
13
15
|
import '../search/command-palette.js';
|
|
@@ -25,6 +27,9 @@ import './icon-picker.js';
|
|
|
25
27
|
import './dialog-frame.js';
|
|
26
28
|
import './modal.js';
|
|
27
29
|
import './file-button.js';
|
|
30
|
+
import './measured-grid.js';
|
|
31
|
+
import '../feedback/feedback-attachment.js';
|
|
32
|
+
import '../feedback/feedback-dialog.js';
|
|
28
33
|
|
|
29
34
|
/**
|
|
30
35
|
* A full calculator keypad rendered as a bottom sheet — the mobile counterpart to
|
|
@@ -64,9 +64,9 @@ function NumberPadSheet({
|
|
|
64
64
|
children: [
|
|
65
65
|
/* @__PURE__ */ jsxs("div", { className: "flex items-end justify-between gap-3 px-2 pb-2", children: [
|
|
66
66
|
label != null && /* @__PURE__ */ jsx("span", { className: "truncate pb-1 text-xs font-medium text-[var(--money-neutral)]", children: label }),
|
|
67
|
-
/* @__PURE__ */ jsxs("div", { className: "
|
|
68
|
-
/* @__PURE__ */ jsx("div", { className: "truncate font-mono text-lg leading-tight text-[var(--text-primary)]", children: value || "0" }),
|
|
69
|
-
/* @__PURE__ */ jsx("div", { className: "h-4 font-mono text-xs text-[var(--money-neutral)]", children: preview })
|
|
67
|
+
/* @__PURE__ */ jsxs("div", { className: "ms-auto min-w-0", children: [
|
|
68
|
+
/* @__PURE__ */ jsx("div", { dir: "ltr", className: "truncate text-right font-mono text-lg leading-tight text-[var(--text-primary)]", children: value || "0" }),
|
|
69
|
+
/* @__PURE__ */ jsx("div", { dir: "ltr", className: "h-4 text-right font-mono text-xs text-[var(--money-neutral)]", children: preview })
|
|
70
70
|
] })
|
|
71
71
|
] }),
|
|
72
72
|
/* @__PURE__ */ jsx("div", { className: "grid grid-cols-4 gap-1.5", children: PAD_KEYS.map(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/numpad-sheet.tsx"],"sourcesContent":["import { createPortal } from \"react-dom\";\nimport { Delete } from \"lucide-react\";\nimport { useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { useEscapeKey } from \"../hooks/use-dismiss\";\nimport { evaluateExpression, formatResult, sanitizeLive } from \"../lib/calc\";\nimport {\n DEFAULT_CALCULATOR_LABELS,\n useKitLabels,\n type CalculatorLabels,\n} from \"../i18n/kit-labels\";\n\n/**\n * A full calculator keypad rendered as a bottom sheet — the mobile counterpart to\n * the desktop {@link CalculatorButton} popover, and the replacement for the old\n * under-the-field operator bar (`MathKeys`, feedback #334).\n *\n * A native app (YNAB) can swap the system keyboard for its own keypad; a PWA\n * cannot — but it CAN suppress the OS keyboard with `inputMode=\"none\"` on the\n * host field and paint its own keypad in the freed space. So the host input keeps\n * real focus/caret/selection + the existing value/commit contract, while this\n * sheet drives it: digits + operators + a live `= …` preview, evaluated through\n * the shared {@link evaluateExpression} engine. Desktop is untouched (it keeps the\n * native keyboard and the calculator popover); the host gates this to mobile.\n *\n * Buttons commit through the host's `onChange`/blur, so the sheet is stateless —\n * the field text is the single source of truth. `onPointerDown` preventDefault on\n * the root keeps the host input focused (caret stays, keyboard stays hidden) as\n * the user taps keys; the buttons' `onClick` still fires.\n */\n/** Names for the pad itself and its four non-digit keys. The first four are\n * screen-reader names; `done` is the one string here that is READ OFF THE SCREEN —\n * the brand-filled primary button — and it was a hardcoded English literal while\n * its three neighbours each took an override, so a German phone showed \"Done\"\n * among German labels with no prop able to change it. */\nexport interface NumberPadSheetLabels extends Partial<CalculatorLabels> {\n /** The pad's own name — the `calculator.panel` key under its older name here. */\n pad?: string;\n backspace?: string;\n clear?: string;\n equals?: string;\n /** Visible text on the primary key, not an `aria-label`. */\n done?: string;\n}\n\ntype PadKey =\n | { kind: \"ins\"; label: string; ins: string; accent?: boolean; name?: PadKeyName }\n | { kind: \"back\" };\n\n/** The {@link CalculatorLabels} key naming a non-digit key; digits are their glyph. */\ntype PadKeyName = \"plus\" | \"minus\" | \"times\" | \"divide\" | \"decimal\";\n\n// Insert chars that survive `sanitizeLive` (it keeps `× ÷` and ASCII `+ - * /`\n// but strips the unicode minus `−`, so minus inserts an ASCII \"-\" while showing\n// the nicer glyph). The evaluator normalises `× ÷` back to `* /`.\nconst PAD_KEYS: PadKey[] = [\n { kind: \"ins\", label: \"7\", ins: \"7\" },\n { kind: \"ins\", label: \"8\", ins: \"8\" },\n { kind: \"ins\", label: \"9\", ins: \"9\" },\n { kind: \"ins\", label: \"÷\", ins: \"÷\", accent: true, name: \"divide\" },\n { kind: \"ins\", label: \"4\", ins: \"4\" },\n { kind: \"ins\", label: \"5\", ins: \"5\" },\n { kind: \"ins\", label: \"6\", ins: \"6\" },\n { kind: \"ins\", label: \"×\", ins: \"×\", accent: true, name: \"times\" },\n { kind: \"ins\", label: \"1\", ins: \"1\" },\n { kind: \"ins\", label: \"2\", ins: \"2\" },\n { kind: \"ins\", label: \"3\", ins: \"3\" },\n { kind: \"ins\", label: \"−\", ins: \"-\", accent: true, name: \"minus\" },\n { kind: \"ins\", label: \".\", ins: \".\", name: \"decimal\" },\n { kind: \"ins\", label: \"0\", ins: \"0\" },\n { kind: \"back\" },\n { kind: \"ins\", label: \"+\", ins: \"+\", accent: true, name: \"plus\" },\n];\n\n/** Every key's shape — including the thing this pad used to delete without replacing.\n *\n * `focus:outline-none` alone is not a style choice, it is the removal of the only\n * signal a keyboard user has; on a 4×4 grid of identical tiles it leaves no way at all\n * to tell which key Enter is about to press (the audit's §a11y, and the same defect as\n * the dropdown search box).\n *\n * `focus-visible` and `ring-inset`, for the two reasons {@link ToggleGroup} already\n * writes down. This is a touch control first, and a plain `focus:` ring paints itself\n * on every TAP, because a tap focuses the button. And the keys sit 6px apart, which is\n * thinner than an outward ring plus the neighbour it would spill onto — inset keeps the\n * ring inside the key it describes.\n *\n * --brand rather than --border-strong: the operator keys are filled with --border, and\n * a ring in the colour of the thing it surrounds is not an indicator. */\nconst PAD_BTN =\n \"flex h-14 items-center justify-center rounded-lg text-lg font-medium transition-transform select-none focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--brand)] active:scale-[0.97]\";\nconst PAD_DIGIT = \"bg-[var(--bg-surface-2)] text-[var(--text-primary)] active:bg-[var(--border)]\";\nconst PAD_ACCENT = \"bg-[var(--border)] text-[var(--text-primary)] active:bg-[var(--bg-surface-2)]\";\n\nexport function NumberPadSheet({\n value,\n onChange,\n onDone,\n label,\n labels,\n}: {\n value: string;\n /** Fired with the raw (sanitised) field text on every key — same contract as\n * the host field's own `onChange`. */\n onChange: (value: string) => void;\n /** Fired on \"Done\": the host blurs the input, which commits (evaluates) and\n * unmounts the sheet via its existing blur handler. */\n onDone: () => void;\n /** Optional field label, echoed in the sheet header so the user still knows\n * which field they're editing when the sheet covers it. */\n label?: ReactNode;\n /** Names for the pad itself and its non-digit keys — screen-reader names, except\n * `done`, which is the visible text on the primary key. Merged over `calculator`\n * from `<UiKitProvider labels>`: this is the same keypad as `CalculatorButton`'s,\n * on a phone, and one translation covers both. Digits need no name — their glyph\n * IS the name; the operators do (see {@link CalculatorLabels.plus}). */\n labels?: NumberPadSheetLabels;\n}) {\n // `pad` is this sheet's older spelling of `panel`, so it is folded in as that.\n const fromProps = useMemo(() => {\n if (!labels) return undefined;\n const { pad, ...rest } = labels;\n return pad === undefined ? rest : { ...rest, panel: pad };\n }, [labels]);\n const text = useKitLabels(\"calculator\", DEFAULT_CALCULATOR_LABELS, fromProps);\n\n // NO `useBodyScrollLock`, and that is the point of the control (Keksdose live\n // #317: *\"Background not scrollable when the amount input calculator field is\n // open\"*).\n //\n // This sheet is a KEYBOARD, not a dialog. It is opened by focusing a field and\n // exists only because a PWA cannot swap the system keyboard for its own — so it\n // suppresses the OS keyboard with `inputMode=\"none\"` and paints itself in the\n // freed space. An OS keyboard does not freeze the page behind it; it takes the\n // bottom of the screen and leaves you free to scroll what is left, which is how\n // you reach the field you are typing into when the keys cover it.\n //\n // Locking here made the page unreachable at exactly the moment it matters most:\n // correcting a receipt total against the running line sum, where the figure you\n // are comparing against sits below the keypad. The other four holders of that\n // hook are all modal — `Modal`, `PickerSheet`, `FullBleedDialog`, the DataTable\n // row dialog — and they stay locked, because for them the page behind is not\n // part of the task.\n //\n // The pad still does not scroll ITSELF away under a stray drag: the root's\n // `onPointerDown` preventDefault (below) keeps the host input focused and eats\n // the gesture on the sheet, so a touch that starts on a key is not a page scroll.\n\n // ── NO focus trap either, and for a harder reason than the scroll lock ────────\n //\n // Wave 3 put `useFocusTrap` on every overlay in this package. This one is the\n // exception, and it is not an oversight to be tidied up later: a trap here would\n // DELETE THE COMPONENT IT WAS PROTECTING. Both hosts render the pad with\n // `showNumpad = isMobile && !disabled && focused`, where `focused` is the host\n // input's own focus state. Moving focus into the pad blurs that input, the host\n // sets `focused` false, and the pad unmounts — on mount, before a single key can be\n // pressed. The blur also COMMITS, so the trap would evaluate a half-typed\n // expression on the way out.\n //\n // That is the contract, not an accident of it. This sheet exists because a PWA\n // cannot swap the system keyboard for its own: the host keeps real focus, caret and\n // selection while `inputMode=\"none\"` suppresses the OS keys, and the root's\n // `onPointerDown` preventDefault below is there for the same reason. The pad is\n // `role=\"group\"`, not a dialog. A keyboard does not trap focus; it is what you type\n // WITH.\n //\n // What was genuinely missing is a way OUT that is not a tap. `useEscapeKey` and not\n // a handler on the sheet, because the sheet never has the focus a keydown would\n // bubble from — the host does, and the host is not this component. Escape does what\n // the Done key does rather than cancelling, because committing on blur is the\n // host's contract and a cancel would have to be the host's to offer.\n //\n // The limit, since it is better written down than discovered: inside a `Modal` the\n // dialog's own Escape handler sits on the focus path and stops the event before a\n // document listener sees it, so there the press closes the dialog — which it did\n // before this line existed too, and which takes the pad with it either way.\n useEscapeKey(onDone);\n\n const result = evaluateExpression(value);\n const preview = result !== null && formatResult(result) !== value.trim() ? `= ${formatResult(result)}` : \"\";\n\n const insert = (ch: string) => onChange(sanitizeLive(value + ch));\n const backspace = () => onChange(value.slice(0, -1));\n const clearAll = () => onChange(\"\");\n const equals = () => {\n if (result !== null) onChange(formatResult(result));\n };\n\n const sheet = (\n <div\n role=\"group\"\n aria-label={text.panel}\n // Keep the host input focused when tapping the pad: preventDefault on\n // pointerdown blocks the focus/blur, while the buttons' click still fires.\n onPointerDown={(e) => e.preventDefault()}\n className=\"fixed inset-x-0 bottom-0 z-50 border-t border-[var(--border)] bg-[var(--bg-surface)] px-2 pt-2 shadow-[0_-4px_24px_rgba(0,0,0,0.12)]\"\n style={{ paddingBottom: \"max(0.5rem, env(safe-area-inset-bottom))\" }}\n >\n {/* Header display: which field + the running expression and live result, so\n the value stays visible even when the sheet covers the field. */}\n <div className=\"flex items-end justify-between gap-3 px-2 pb-2\">\n {label != null && (\n <span className=\"truncate pb-1 text-xs font-medium text-[var(--money-neutral)]\">{label}</span>\n )}\n <div className=\"ml-auto min-w-0 text-right\">\n <div className=\"truncate font-mono text-lg leading-tight text-[var(--text-primary)]\">{value || \"0\"}</div>\n <div className=\"h-4 font-mono text-xs text-[var(--money-neutral)]\">{preview}</div>\n </div>\n </div>\n\n <div className=\"grid grid-cols-4 gap-1.5\">\n {PAD_KEYS.map((key, i) =>\n key.kind === \"back\" ? (\n <button\n key=\"back\"\n type=\"button\"\n aria-label={text.backspace}\n onClick={backspace}\n className={cn(PAD_BTN, PAD_ACCENT)}\n >\n <Delete className=\"size-5\" />\n </button>\n ) : (\n <button\n key={`${key.ins}-${i}`}\n type=\"button\"\n aria-label={key.name ? text[key.name] : key.label}\n onClick={() => insert(key.ins)}\n className={cn(PAD_BTN, key.accent ? PAD_ACCENT : PAD_DIGIT)}\n >\n {key.label}\n </button>\n ),\n )}\n </div>\n\n <div className=\"mt-1.5 grid grid-cols-4 gap-1.5\">\n <button type=\"button\" aria-label={text.clear} onClick={clearAll} className={cn(PAD_BTN, PAD_ACCENT)}>\n C\n </button>\n <button type=\"button\" aria-label={text.equals} onClick={equals} className={cn(PAD_BTN, PAD_ACCENT)}>\n =\n </button>\n <button\n type=\"button\"\n onClick={onDone}\n // The one key whose own fill is --brand, so it rings in the colour that fill\n // was chosen to be legible against instead (tailwind-merge keeps the later\n // ring colour). A --brand ring here would be present in the DOM and invisible\n // on screen, which is the defect this change exists to fix.\n className={cn(\n PAD_BTN,\n \"col-span-2 bg-[var(--brand)] text-[var(--brand-contrast)] focus-visible:ring-[var(--brand-contrast)] active:bg-[var(--brand-hover)]\",\n )}\n >\n {text.done}\n </button>\n </div>\n </div>\n );\n\n return createPortal(sheet, document.body);\n}\n"],"mappings":";AA2MU,cAEF,YAFE;AA3MV,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,eAAe;AAExB,SAAS,UAAU;AACnB,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB,cAAc,oBAAoB;AAC/D;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AA6CP,MAAM,WAAqB;AAAA,EACzB,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,QAAK,KAAK,QAAK,QAAQ,MAAM,MAAM,SAAS;AAAA,EAClE,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,QAAK,KAAK,QAAK,QAAQ,MAAM,MAAM,QAAQ;AAAA,EACjE,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,UAAK,KAAK,KAAK,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ACF;AAGF,SAAO,aAAa,OAAO,SAAS,IAAI;AAC1C;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/numpad-sheet.tsx"],"sourcesContent":["import { createPortal } from \"react-dom\";\nimport { Delete } from \"lucide-react\";\nimport { useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { useEscapeKey } from \"../hooks/use-dismiss\";\nimport { evaluateExpression, formatResult, sanitizeLive } from \"../lib/calc\";\nimport {\n DEFAULT_CALCULATOR_LABELS,\n useKitLabels,\n type CalculatorLabels,\n} from \"../i18n/kit-labels\";\n\n/**\n * A full calculator keypad rendered as a bottom sheet — the mobile counterpart to\n * the desktop {@link CalculatorButton} popover, and the replacement for the old\n * under-the-field operator bar (`MathKeys`, feedback #334).\n *\n * A native app (YNAB) can swap the system keyboard for its own keypad; a PWA\n * cannot — but it CAN suppress the OS keyboard with `inputMode=\"none\"` on the\n * host field and paint its own keypad in the freed space. So the host input keeps\n * real focus/caret/selection + the existing value/commit contract, while this\n * sheet drives it: digits + operators + a live `= …` preview, evaluated through\n * the shared {@link evaluateExpression} engine. Desktop is untouched (it keeps the\n * native keyboard and the calculator popover); the host gates this to mobile.\n *\n * Buttons commit through the host's `onChange`/blur, so the sheet is stateless —\n * the field text is the single source of truth. `onPointerDown` preventDefault on\n * the root keeps the host input focused (caret stays, keyboard stays hidden) as\n * the user taps keys; the buttons' `onClick` still fires.\n */\n/** Names for the pad itself and its four non-digit keys. The first four are\n * screen-reader names; `done` is the one string here that is READ OFF THE SCREEN —\n * the brand-filled primary button — and it was a hardcoded English literal while\n * its three neighbours each took an override, so a German phone showed \"Done\"\n * among German labels with no prop able to change it. */\nexport interface NumberPadSheetLabels extends Partial<CalculatorLabels> {\n /** The pad's own name — the `calculator.panel` key under its older name here. */\n pad?: string;\n backspace?: string;\n clear?: string;\n equals?: string;\n /** Visible text on the primary key, not an `aria-label`. */\n done?: string;\n}\n\ntype PadKey =\n | { kind: \"ins\"; label: string; ins: string; accent?: boolean; name?: PadKeyName }\n | { kind: \"back\" };\n\n/** The {@link CalculatorLabels} key naming a non-digit key; digits are their glyph. */\ntype PadKeyName = \"plus\" | \"minus\" | \"times\" | \"divide\" | \"decimal\";\n\n// Insert chars that survive `sanitizeLive` (it keeps `× ÷` and ASCII `+ - * /`\n// but strips the unicode minus `−`, so minus inserts an ASCII \"-\" while showing\n// the nicer glyph). The evaluator normalises `× ÷` back to `* /`.\nconst PAD_KEYS: PadKey[] = [\n { kind: \"ins\", label: \"7\", ins: \"7\" },\n { kind: \"ins\", label: \"8\", ins: \"8\" },\n { kind: \"ins\", label: \"9\", ins: \"9\" },\n { kind: \"ins\", label: \"÷\", ins: \"÷\", accent: true, name: \"divide\" },\n { kind: \"ins\", label: \"4\", ins: \"4\" },\n { kind: \"ins\", label: \"5\", ins: \"5\" },\n { kind: \"ins\", label: \"6\", ins: \"6\" },\n { kind: \"ins\", label: \"×\", ins: \"×\", accent: true, name: \"times\" },\n { kind: \"ins\", label: \"1\", ins: \"1\" },\n { kind: \"ins\", label: \"2\", ins: \"2\" },\n { kind: \"ins\", label: \"3\", ins: \"3\" },\n { kind: \"ins\", label: \"−\", ins: \"-\", accent: true, name: \"minus\" },\n { kind: \"ins\", label: \".\", ins: \".\", name: \"decimal\" },\n { kind: \"ins\", label: \"0\", ins: \"0\" },\n { kind: \"back\" },\n { kind: \"ins\", label: \"+\", ins: \"+\", accent: true, name: \"plus\" },\n];\n\n/** Every key's shape — including the thing this pad used to delete without replacing.\n *\n * `focus:outline-none` alone is not a style choice, it is the removal of the only\n * signal a keyboard user has; on a 4×4 grid of identical tiles it leaves no way at all\n * to tell which key Enter is about to press (the audit's §a11y, and the same defect as\n * the dropdown search box).\n *\n * `focus-visible` and `ring-inset`, for the two reasons {@link ToggleGroup} already\n * writes down. This is a touch control first, and a plain `focus:` ring paints itself\n * on every TAP, because a tap focuses the button. And the keys sit 6px apart, which is\n * thinner than an outward ring plus the neighbour it would spill onto — inset keeps the\n * ring inside the key it describes.\n *\n * --brand rather than --border-strong: the operator keys are filled with --border, and\n * a ring in the colour of the thing it surrounds is not an indicator. */\nconst PAD_BTN =\n \"flex h-14 items-center justify-center rounded-lg text-lg font-medium transition-transform select-none focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--brand)] active:scale-[0.97]\";\nconst PAD_DIGIT = \"bg-[var(--bg-surface-2)] text-[var(--text-primary)] active:bg-[var(--border)]\";\nconst PAD_ACCENT = \"bg-[var(--border)] text-[var(--text-primary)] active:bg-[var(--bg-surface-2)]\";\n\nexport function NumberPadSheet({\n value,\n onChange,\n onDone,\n label,\n labels,\n}: {\n value: string;\n /** Fired with the raw (sanitised) field text on every key — same contract as\n * the host field's own `onChange`. */\n onChange: (value: string) => void;\n /** Fired on \"Done\": the host blurs the input, which commits (evaluates) and\n * unmounts the sheet via its existing blur handler. */\n onDone: () => void;\n /** Optional field label, echoed in the sheet header so the user still knows\n * which field they're editing when the sheet covers it. */\n label?: ReactNode;\n /** Names for the pad itself and its non-digit keys — screen-reader names, except\n * `done`, which is the visible text on the primary key. Merged over `calculator`\n * from `<UiKitProvider labels>`: this is the same keypad as `CalculatorButton`'s,\n * on a phone, and one translation covers both. Digits need no name — their glyph\n * IS the name; the operators do (see {@link CalculatorLabels.plus}). */\n labels?: NumberPadSheetLabels;\n}) {\n // `pad` is this sheet's older spelling of `panel`, so it is folded in as that.\n const fromProps = useMemo(() => {\n if (!labels) return undefined;\n const { pad, ...rest } = labels;\n return pad === undefined ? rest : { ...rest, panel: pad };\n }, [labels]);\n const text = useKitLabels(\"calculator\", DEFAULT_CALCULATOR_LABELS, fromProps);\n\n // NO `useBodyScrollLock`, and that is the point of the control (Keksdose live\n // #317: *\"Background not scrollable when the amount input calculator field is\n // open\"*).\n //\n // This sheet is a KEYBOARD, not a dialog. It is opened by focusing a field and\n // exists only because a PWA cannot swap the system keyboard for its own — so it\n // suppresses the OS keyboard with `inputMode=\"none\"` and paints itself in the\n // freed space. An OS keyboard does not freeze the page behind it; it takes the\n // bottom of the screen and leaves you free to scroll what is left, which is how\n // you reach the field you are typing into when the keys cover it.\n //\n // Locking here made the page unreachable at exactly the moment it matters most:\n // correcting a receipt total against the running line sum, where the figure you\n // are comparing against sits below the keypad. The other four holders of that\n // hook are all modal — `Modal`, `PickerSheet`, `FullBleedDialog`, the DataTable\n // row dialog — and they stay locked, because for them the page behind is not\n // part of the task.\n //\n // The pad still does not scroll ITSELF away under a stray drag: the root's\n // `onPointerDown` preventDefault (below) keeps the host input focused and eats\n // the gesture on the sheet, so a touch that starts on a key is not a page scroll.\n\n // ── NO focus trap either, and for a harder reason than the scroll lock ────────\n //\n // Wave 3 put `useFocusTrap` on every overlay in this package. This one is the\n // exception, and it is not an oversight to be tidied up later: a trap here would\n // DELETE THE COMPONENT IT WAS PROTECTING. Both hosts render the pad with\n // `showNumpad = isMobile && !disabled && focused`, where `focused` is the host\n // input's own focus state. Moving focus into the pad blurs that input, the host\n // sets `focused` false, and the pad unmounts — on mount, before a single key can be\n // pressed. The blur also COMMITS, so the trap would evaluate a half-typed\n // expression on the way out.\n //\n // That is the contract, not an accident of it. This sheet exists because a PWA\n // cannot swap the system keyboard for its own: the host keeps real focus, caret and\n // selection while `inputMode=\"none\"` suppresses the OS keys, and the root's\n // `onPointerDown` preventDefault below is there for the same reason. The pad is\n // `role=\"group\"`, not a dialog. A keyboard does not trap focus; it is what you type\n // WITH.\n //\n // What was genuinely missing is a way OUT that is not a tap. `useEscapeKey` and not\n // a handler on the sheet, because the sheet never has the focus a keydown would\n // bubble from — the host does, and the host is not this component. Escape does what\n // the Done key does rather than cancelling, because committing on blur is the\n // host's contract and a cancel would have to be the host's to offer.\n //\n // The limit, since it is better written down than discovered: inside a `Modal` the\n // dialog's own Escape handler sits on the focus path and stops the event before a\n // document listener sees it, so there the press closes the dialog — which it did\n // before this line existed too, and which takes the pad with it either way.\n useEscapeKey(onDone);\n\n const result = evaluateExpression(value);\n const preview = result !== null && formatResult(result) !== value.trim() ? `= ${formatResult(result)}` : \"\";\n\n const insert = (ch: string) => onChange(sanitizeLive(value + ch));\n const backspace = () => onChange(value.slice(0, -1));\n const clearAll = () => onChange(\"\");\n const equals = () => {\n if (result !== null) onChange(formatResult(result));\n };\n\n const sheet = (\n <div\n role=\"group\"\n aria-label={text.panel}\n // Keep the host input focused when tapping the pad: preventDefault on\n // pointerdown blocks the focus/blur, while the buttons' click still fires.\n onPointerDown={(e) => e.preventDefault()}\n className=\"fixed inset-x-0 bottom-0 z-50 border-t border-[var(--border)] bg-[var(--bg-surface)] px-2 pt-2 shadow-[0_-4px_24px_rgba(0,0,0,0.12)]\"\n style={{ paddingBottom: \"max(0.5rem, env(safe-area-inset-bottom))\" }}\n >\n {/* Header display: which field + the running expression and live result, so\n the value stays visible even when the sheet covers the field. */}\n <div className=\"flex items-end justify-between gap-3 px-2 pb-2\">\n {label != null && (\n <span className=\"truncate pb-1 text-xs font-medium text-[var(--money-neutral)]\">{label}</span>\n )}\n {/* At the logical end, opposite the label; the figures themselves stay\n left-to-right and right-aligned, like the desktop calculator's. */}\n <div className=\"ms-auto min-w-0\">\n <div dir=\"ltr\" className=\"truncate text-right font-mono text-lg leading-tight text-[var(--text-primary)]\">{value || \"0\"}</div>\n <div dir=\"ltr\" className=\"h-4 text-right font-mono text-xs text-[var(--money-neutral)]\">{preview}</div>\n </div>\n </div>\n\n <div className=\"grid grid-cols-4 gap-1.5\">\n {PAD_KEYS.map((key, i) =>\n key.kind === \"back\" ? (\n <button\n key=\"back\"\n type=\"button\"\n aria-label={text.backspace}\n onClick={backspace}\n className={cn(PAD_BTN, PAD_ACCENT)}\n >\n <Delete className=\"size-5\" />\n </button>\n ) : (\n <button\n key={`${key.ins}-${i}`}\n type=\"button\"\n aria-label={key.name ? text[key.name] : key.label}\n onClick={() => insert(key.ins)}\n className={cn(PAD_BTN, key.accent ? PAD_ACCENT : PAD_DIGIT)}\n >\n {key.label}\n </button>\n ),\n )}\n </div>\n\n <div className=\"mt-1.5 grid grid-cols-4 gap-1.5\">\n <button type=\"button\" aria-label={text.clear} onClick={clearAll} className={cn(PAD_BTN, PAD_ACCENT)}>\n C\n </button>\n <button type=\"button\" aria-label={text.equals} onClick={equals} className={cn(PAD_BTN, PAD_ACCENT)}>\n =\n </button>\n <button\n type=\"button\"\n onClick={onDone}\n // The one key whose own fill is --brand, so it rings in the colour that fill\n // was chosen to be legible against instead (tailwind-merge keeps the later\n // ring colour). A --brand ring here would be present in the DOM and invisible\n // on screen, which is the defect this change exists to fix.\n className={cn(\n PAD_BTN,\n \"col-span-2 bg-[var(--brand)] text-[var(--brand-contrast)] focus-visible:ring-[var(--brand-contrast)] active:bg-[var(--brand-hover)]\",\n )}\n >\n {text.done}\n </button>\n </div>\n </div>\n );\n\n return createPortal(sheet, document.body);\n}\n"],"mappings":";AA2MU,cAIF,YAJE;AA3MV,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,eAAe;AAExB,SAAS,UAAU;AACnB,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB,cAAc,oBAAoB;AAC/D;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AA6CP,MAAM,WAAqB;AAAA,EACzB,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,QAAK,KAAK,QAAK,QAAQ,MAAM,MAAM,SAAS;AAAA,EAClE,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,KAAK,KAAK,IAAI;AAAA,EACpC,EAAE,MAAM,OAAO,OAAO,QAAK,KAAK,QAAK,QAAQ,MAAM,MAAM,QAAQ;AAAA,EACjE,EA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QAAQ,WAAW,GAAG,SAAS,UAAU,GAAG,eAEpG;AAAA,UACA;AAAA,YAAC;AAAA;AAAA,cACC,MAAK;AAAA,cACL,SAAS;AAAA,cAKT,WAAW;AAAA,gBACT;AAAA,gBACA;AAAA,cACF;AAAA,cAEC,eAAK;AAAA;AAAA,UACR;AAAA,WACF;AAAA;AAAA;AAAA,EACF;AAGF,SAAO,aAAa,OAAO,SAAS,IAAI;AAC1C;","names":[]}
|
|
@@ -88,7 +88,7 @@ function PickerSheet({
|
|
|
88
88
|
);
|
|
89
89
|
}
|
|
90
90
|
const SHEET_ROW_CLASS = cn(
|
|
91
|
-
"flex min-h-11 w-full items-center gap-2 px-4 py-2 text-
|
|
91
|
+
"flex min-h-11 w-full items-center gap-2 px-4 py-2 text-start text-base",
|
|
92
92
|
"text-[var(--text-primary)] hover:bg-[var(--bg-hover)]"
|
|
93
93
|
);
|
|
94
94
|
export {
|