@eifi1/ui-kit 0.6.0 → 0.6.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/dist/components/autocomplete.d.ts +3 -1
- package/dist/components/autocomplete.js +6 -6
- package/dist/components/autocomplete.js.map +1 -1
- package/dist/components/checkbox.d.ts +9 -0
- package/dist/components/checkbox.js +7 -2
- package/dist/components/checkbox.js.map +1 -1
- package/dist/components/file-button.js +19 -1
- package/dist/components/file-button.js.map +1 -1
- package/dist/components/switch.d.ts +9 -0
- package/dist/components/switch.js +7 -2
- package/dist/components/switch.js.map +1 -1
- package/package.json +1 -1
- package/src/components/autocomplete.tsx +13 -9
- package/src/components/checkbox.tsx +16 -0
- package/src/components/file-button.tsx +28 -1
- package/src/components/switch.tsx +16 -0
|
@@ -87,7 +87,9 @@ interface AutocompleteProps<V extends string | number = string> extends Omit<Com
|
|
|
87
87
|
* row, `aria-controls` the list, and a polite live region says what the list now
|
|
88
88
|
* holds. Keyboard: ↓/↑ move (↓ opens), Enter takes the highlighted row (with none,
|
|
89
89
|
* Enter is left to the form), Escape closes, Tab closes and moves on; Home/End stay
|
|
90
|
-
* with the caret.
|
|
90
|
+
* with the caret. An Escape that closes an open list is consumed and never reaches the
|
|
91
|
+
* caller; with the list closed it does. For every other key a caller's `onKeyDown`
|
|
92
|
+
* runs first and may `preventDefault()` to
|
|
91
93
|
* keep a key for itself.
|
|
92
94
|
*
|
|
93
95
|
* The list is portalled and anchored under the field on every screen size: the
|
|
@@ -129,6 +129,12 @@ function AutocompleteInner({
|
|
|
129
129
|
setActive(-1);
|
|
130
130
|
},
|
|
131
131
|
onKeyDown: (e) => {
|
|
132
|
+
if (e.key === "Escape" && expanded) {
|
|
133
|
+
e.preventDefault();
|
|
134
|
+
e.stopPropagation();
|
|
135
|
+
close();
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
132
138
|
onKeyDown?.(e);
|
|
133
139
|
if (e.defaultPrevented) return;
|
|
134
140
|
const last = results.length - 1;
|
|
@@ -145,12 +151,6 @@ function AutocompleteInner({
|
|
|
145
151
|
e.preventDefault();
|
|
146
152
|
take(results[active]);
|
|
147
153
|
}
|
|
148
|
-
} else if (e.key === "Escape") {
|
|
149
|
-
if (expanded) {
|
|
150
|
-
e.preventDefault();
|
|
151
|
-
e.stopPropagation();
|
|
152
|
-
close();
|
|
153
|
-
}
|
|
154
154
|
} else if (e.key === "Tab") {
|
|
155
155
|
close();
|
|
156
156
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/autocomplete.tsx"],"sourcesContent":["import { Fragment, forwardRef, useId, useRef, useState } from \"react\";\nimport type {\n ComponentPropsWithoutRef,\n ForwardedRef,\n ReactElement,\n ReactNode,\n RefAttributes,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { cn } from \"../lib/cn\";\nimport { FieldLabel, FIELD_BASE, FIELD_FLOATING_PAD, FIELD_INVALID, Spinner } from \"./ui\";\nimport { useAnchoredPanel } from \"../hooks/use-anchored-panel\";\nimport {\n useActiveOptionScroll,\n useComboboxFieldError,\n useOptionSource,\n type ComboOption,\n} from \"./combobox-core\";\nimport { DEFAULT_COMBOBOX_LABELS, useKitLabels } from \"../i18n/kit-labels\";\n\n/**\n * `value`/`onChange` are the TEXT's, and `onSelect` is \"a suggestion was taken\" —\n * not the DOM's text-selection event — so the input's own spellings of those three\n * are omitted. Everything else reaches the `<input>`, the way it does on {@link Input}.\n */\nexport interface AutocompleteProps<V extends string | number = string>\n extends Omit<\n ComponentPropsWithoutRef<\"input\">,\n \"value\" | \"defaultValue\" | \"onChange\" | \"onSelect\" | \"children\" | \"type\"\n > {\n /** What is in the field. Controlled, and never reset by the component: opening,\n * closing and a failed lookup all leave it exactly as typed. */\n value: string;\n /** Every keystroke — and, with `fillOnSelect`, the label of a taken suggestion. */\n onChange: (text: string) => void;\n /** Suggestions the caller already has (e.g. from its own query hook). Narrowed by\n * the text unless `filter={false}`. */\n options?: ComboOption<V>[];\n /** Or: fetch them. Debounced (`debounceMs`), race-safe, only at `minChars` and up,\n * never while the field is idle; a rejection shows `loadErrorLabel` and empties\n * the list rather than leaving the previous text's rows under it. */\n loadOptions?: (query: string) => Promise<ComboOption<V>[]>;\n /** Narrow `options` by label/sublabel substring. Default `true`. Pass `false` for\n * a list a server has already searched and ranked — it is shown as given. */\n filter?: boolean;\n /** External loading flag (a caller-side fetch), OR-ed with `loadOptions`'. */\n loading?: boolean;\n /** Below this many characters nothing is offered or fetched. Default 1: an empty\n * field asks nothing — focusing it is not a search. */\n minChars?: number;\n /** Quiet time before `loadOptions` runs. Default 300 ms — an ordinary typist's\n * inter-key interval is 150–250 ms, so the pickers' 150 fires on nearly every\n * letter, which a rate-limited geocoder cannot afford. */\n debounceMs?: number;\n /** A suggestion was taken (click, or Enter on the highlighted row). */\n onSelect?: (option: ComboOption<V>) => void;\n /**\n * Put the taken suggestion's label into the field (`onChange(label)`). Default\n * `true` — the free-text case, where the text IS the value and a suggestion only\n * completes it (an address field). Pass `false` where taking a row is an ACTION\n * and the field is only the search that found it; the text then stays as typed.\n */\n fillOnSelect?: boolean;\n /** A floating label, as on {@link Combobox}. Names the field (`aria-labelledby`)\n * unless an `aria-label` is given. */\n label?: ReactNode;\n /** Leading decoration inside the field (a pin, a magnifier). Decorative: the\n * label names the field. */\n icon?: ReactNode;\n /** Required and unanswered — {@link FIELD_INVALID}. */\n invalid?: boolean;\n /** What is wrong with the VALUE, as {@link Input}'s `error`: under the field, on\n * its `aria-describedby`, implies `invalid`. Not a failed lookup — that is\n * `loadErrorLabel`, shown in the list. */\n error?: ReactNode;\n /**\n * The caller's own line in the list, replacing the automatic one (loading / failed\n * / no results). For what only the caller knows: \"offline\", \"the address service\n * is switched off\", a privacy note, the hint a caller-fetched list needs below its\n * own minimum. While set, the list opens even with no rows. Announced politely.\n */\n status?: ReactNode;\n /** Default: `combobox.noResults` from the {@link UiKitProvider}, else English. */\n emptyLabel?: string;\n /** Default: `combobox.loadError`. */\n loadErrorLabel?: string;\n /** Classes for the `<input>` itself; `className` styles the wrapper. */\n inputClassName?: string;\n}\n\nfunction AutocompleteInner<V extends string | number = string>(\n {\n value,\n onChange,\n options,\n loadOptions,\n filter,\n loading,\n minChars = 1,\n debounceMs = 300,\n onSelect,\n fillOnSelect = true,\n label,\n icon,\n invalid,\n error,\n status,\n emptyLabel,\n loadErrorLabel,\n className,\n inputClassName,\n id,\n disabled,\n onKeyDown,\n onFocus,\n onBlur,\n \"aria-label\": ariaLabel,\n \"aria-labelledby\": ariaLabelledBy,\n \"aria-describedby\": ariaDescribedBy,\n ...rest\n }: AutocompleteProps<V>,\n ref: ForwardedRef<HTMLInputElement>,\n) {\n const generated = useId();\n const fieldId = id ?? generated;\n // Off the GENERATED id: a caller's `id` is theirs to collide with.\n const listboxId = `${generated}-listbox`;\n const labelId = `${generated}-label`;\n const optionId = (index: number) => `${generated}-option-${index}`;\n const fieldRef = useRef<HTMLDivElement>(null);\n const labels = useKitLabels(\"combobox\", DEFAULT_COMBOBOX_LABELS, {\n noResults: emptyLabel,\n loadError: loadErrorLabel,\n });\n const field = useComboboxFieldError(error, invalid, ariaDescribedBy);\n\n /** The user's intent: the field is focused and the list has not been dismissed.\n * Whether anything SHOWS is decided below, from what there is to show. */\n const [open, setOpen] = useState(false);\n const [active, setActive] = useState(-1);\n const live = open && !disabled;\n const { results, busy, failed, tooShort } = useOptionSource<V>({\n options,\n loadOptions,\n loading,\n filter,\n minChars,\n debounceMs,\n query: value,\n active: live,\n });\n\n const hasStatus = status !== undefined && status !== null && status !== false && status !== \"\";\n // The visible line under the rows. Nothing below `minChars` unless the caller has\n // something to say — an empty field opening a box that says \"type more\" is noise.\n const statusLine: ReactNode = hasStatus\n ? status\n : tooShort\n ? null\n : busy && results.length === 0\n ? labels.loading\n : failed\n ? labels.loadError\n : !busy && results.length === 0\n ? labels.noResults\n : null;\n const expanded = live && (results.length > 0 || statusLine !== null);\n const activeId =\n expanded && active >= 0 && active < results.length ? optionId(active) : undefined;\n useActiveOptionScroll(activeId);\n const { rect, top, maxHeight } = useAnchoredPanel(fieldRef, expanded, { preferredHeight: 256 });\n\n const close = () => {\n setOpen(false);\n setActive(-1);\n };\n const take = (o: ComboOption<V>) => {\n if (fillOnSelect) onChange(o.label);\n onSelect?.(o);\n close();\n };\n\n const hasLabel = label !== undefined;\n // The caller's name wins; else the floating label, by reference so a non-string\n // label still names the field.\n const labelledBy =\n ariaLabel === undefined ? (ariaLabelledBy ?? (hasLabel ? labelId : undefined)) : undefined;\n\n return (\n // `relative`: the floating label and the live region's `sr-only` both need a\n // local containing block.\n <div className={cn(\"relative\", className)}>\n {hasLabel && <FieldLabel id={labelId}>{label}</FieldLabel>}\n <div ref={fieldRef} className=\"relative\">\n {icon && (\n <span\n aria-hidden\n className=\"pointer-events-none absolute start-2.5 top-1/2 flex -translate-y-1/2 text-[var(--text-muted)] [&>svg]:size-4\"\n >\n {icon}\n </span>\n )}\n <input\n {...rest}\n ref={ref}\n id={fieldId}\n type=\"text\"\n value={value}\n disabled={disabled}\n role=\"combobox\"\n aria-autocomplete=\"list\"\n aria-expanded={expanded}\n // Required by the role, and set while closed too, as on the siblings.\n aria-controls={listboxId}\n aria-activedescendant={activeId}\n aria-label={ariaLabel}\n aria-labelledby={labelledBy}\n aria-invalid={field.isInvalid || rest[\"aria-invalid\"] || undefined}\n aria-describedby={field.describedBy}\n autoComplete=\"off\"\n onFocus={(e) => {\n onFocus?.(e);\n // A seeded field (keksdose's `initialQuery`) is looked up as it is\n // focused; an empty one asks nothing, because of `minChars`.\n setOpen(true);\n }}\n onBlur={(e) => {\n onBlur?.(e);\n close();\n }}\n onChange={(e) => {\n onChange(e.target.value);\n setOpen(true);\n setActive(-1);\n }}\n onKeyDown={(e) => {\n onKeyDown?.(e);\n if (e.defaultPrevented) return;\n const last = results.length - 1;\n if (e.key === \"ArrowDown\") {\n e.preventDefault();\n if (!open) setOpen(true);\n else setActive((i) => Math.min(i + 1, last));\n } else if (e.key === \"ArrowUp\") {\n e.preventDefault();\n if (!open) setOpen(true);\n // From \"nothing highlighted\", Up goes to the bottom, as the APG has it.\n else setActive((i) => (i < 0 ? last : Math.max(i - 1, 0)));\n } else if (e.key === \"Enter\") {\n // No row highlighted: the text is the answer, and a form's own submit\n // is left alone.\n if (expanded && activeId) {\n e.preventDefault();\n take(results[active]);\n }\n } else if (e.key === \"Escape\") {\n // Only when there is a list to close — otherwise the Escape belongs to\n // whatever this field sits in (a dialog), and must reach it.\n if (expanded) {\n e.preventDefault();\n e.stopPropagation();\n close();\n }\n } else if (e.key === \"Tab\") {\n close();\n }\n }}\n className={cn(\n FIELD_BASE,\n hasLabel && FIELD_FLOATING_PAD,\n icon ? \"ps-8\" : undefined,\n busy && \"pe-9\",\n field.isInvalid && FIELD_INVALID,\n inputClassName,\n )}\n />\n {busy && live && (\n // Decorative: the live region below already says \"Loading…\".\n <span className=\"pointer-events-none absolute end-2.5 top-1/2 flex -translate-y-1/2\">\n <Spinner label={null} className=\"h-4 w-4\" />\n </span>\n )}\n </div>\n {field.errorEl}\n {/* The live region, kept mounted so a change IS an announcement: focus stays\n in the field, and without it a reader typed into a geocoder and heard only\n their own letters. The panel's visible line is aria-hidden in favour of\n this, which also carries the row count the eye reads off the list. */}\n <div role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n {!live\n ? null\n : statusLine !== null\n ? statusLine\n : results.length > 0\n ? labels.resultCount(results.length)\n : null}\n </div>\n {expanded &&\n rect &&\n typeof document !== \"undefined\" &&\n createPortal(\n <div\n // Every press inside the list keeps focus in the field — rows, the status\n // line, the scrollbar — or the input's blur would close the list first.\n role=\"presentation\"\n onMouseDown={(e) => e.preventDefault()}\n className=\"fixed z-50 flex flex-col overflow-hidden rounded-md border border-[var(--border)] bg-[var(--bg-surface)] shadow-lg\"\n style={{ top, left: rect.left, width: rect.width, maxHeight }}\n >\n {results.length > 0 && (\n <ul\n id={listboxId}\n role=\"listbox\"\n aria-label={ariaLabel}\n aria-labelledby={labelledBy}\n className=\"min-h-0 flex-1 overflow-y-auto py-1\"\n >\n {results.map((o, i) => {\n const startsGroup = o.group != null && o.group !== results[i - 1]?.group;\n return (\n // Keyed by group AND value, as in the core panel: an option may\n // appear once per group.\n <Fragment key={`${o.group ?? \"\"}|${String(o.value)}`}>\n {startsGroup && (\n <li\n role=\"presentation\"\n className=\"px-3 pb-0.5 pt-2 text-[11px] font-semibold uppercase tracking-wide text-[var(--text-muted)] first:pt-1\"\n >\n {o.group}\n </li>\n )}\n <li role=\"presentation\">\n <button\n type=\"button\"\n id={optionId(i)}\n role=\"option\"\n // CHOSEN, never \"highlighted\" — the family's rule. This\n // field holds no value, so the only row that can be chosen\n // is the one whose label the text already is.\n aria-selected={fillOnSelect && o.label === value}\n tabIndex={-1}\n onClick={() => take(o)}\n onMouseEnter={() => setActive(i)}\n className={cn(\n \"flex w-full items-center gap-2 px-3 py-1.5 text-start text-sm\",\n i === active ? \"bg-[var(--bg-active)]\" : \"hover:bg-[var(--bg-hover)]\",\n o.group != null && \"ps-6\",\n )}\n >\n {o.icon && (\n <span aria-hidden className=\"shrink-0 text-[var(--text-muted)]\">\n {o.icon}\n </span>\n )}\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate text-[var(--text-primary)]\">\n {o.label}\n </span>\n {o.sublabel && (\n <span className=\"block truncate text-xs text-[var(--text-placeholder)]\">\n {o.sublabel}\n </span>\n )}\n </span>\n </button>\n </li>\n </Fragment>\n );\n })}\n </ul>\n )}\n {statusLine !== null && (\n // Visible, not live — the region above speaks for it.\n <div\n aria-hidden\n className={cn(\n \"px-3 py-2 text-sm\",\n failed && !hasStatus ? \"text-[var(--danger)]\" : \"text-[var(--text-muted)]\",\n results.length > 0 && \"border-t border-[var(--border)] text-xs\",\n )}\n >\n {statusLine}\n </div>\n )}\n </div>,\n document.body,\n )}\n </div>\n );\n}\n\nconst AutocompleteBase = forwardRef(AutocompleteInner);\nAutocompleteBase.displayName = \"Autocomplete\";\n\n/**\n * An inline, async-capable text field with a suggestion list under it — the\n * WAI-ARIA APG \"editable combobox with list autocomplete\".\n *\n * Two jobs, one control:\n * - **free text** (kastlan's address field): the text is the value, the list only\n * offers completions, and taking one fills the field (`fillOnSelect`, default);\n * - **search-then-act** (keksdose's address search): the text is a query, taking a\n * row calls `onSelect` and nothing is held (`fillOnSelect={false}`).\n *\n * How it differs from its siblings: {@link Combobox} is free text over a STATIC\n * string pool and opens on focus; {@link EntityCombobox} is a trigger holding an id.\n * This one keeps no value of its own, never resets the text, asks nothing below\n * `minChars`, and reports a failed lookup instead of showing stale rows.\n *\n * Focus never leaves the `<input>`: `aria-activedescendant` names the highlighted\n * row, `aria-controls` the list, and a polite live region says what the list now\n * holds. Keyboard: ↓/↑ move (↓ opens), Enter takes the highlighted row (with none,\n * Enter is left to the form), Escape closes, Tab closes and moves on; Home/End stay\n * with the caret. A caller's `onKeyDown` runs first and may `preventDefault()` to\n * keep a key for itself.\n *\n * The list is portalled and anchored under the field on every screen size: the\n * field already carries the keyboard, and `useAnchoredPanel` keeps the list clear\n * of it on a phone. There is no full-screen sheet as {@link Combobox} has.\n\n * Generic over the option value (`ComboOption<V>`); the ref is the `<input>`'s.\n */\nexport const Autocomplete = AutocompleteBase as <V extends string | number = string>(\n props: AutocompleteProps<V> & RefAttributes<HTMLInputElement>,\n) => ReactElement | null;\n"],"mappings":";AAgMmB,cACb,YADa;AAhMnB,SAAS,UAAU,YAAY,OAAO,QAAQ,gBAAgB;AAQ9D,SAAS,oBAAoB;AAC7B,SAAS,UAAU;AACnB,SAAS,YAAY,YAAY,oBAAoB,eAAe,eAAe;AACnF,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,yBAAyB,oBAAoB;AAwEtD,SAAS,kBACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX,aAAa;AAAA,EACb;AAAA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;AAAA,2BA3Ca,GAAG,EAAE,SAAS,EAAE,IAAI,OAAO,EAAE,KAAK,CAAC,EA4ClD;AAAA;AAAA,kBAEJ,CAAC;AAAA;AAAA,cACH;AAAA,cAED,eAAe;AAAA,cAEd;AAAA,gBAAC;AAAA;AAAA,kBACC,eAAW;AAAA,kBACX,WAAW;AAAA,oBACT;AAAA,oBACA,UAAU,CAAC,YAAY,yBAAyB;AAAA,oBAChD,QAAQ,SAAS,KAAK;AAAA,kBACxB;AAAA,kBAEC;AAAA;AAAA,cACH;AAAA;AAAA;AAAA,QAEJ;AAAA,QACA,SAAS;AAAA,MACX;AAAA,OACJ;AAAA;AAEJ;AAEA,MAAM,mBAAmB,WAAW,iBAAiB;AACrD,iBAAiB,cAAc;AA8BxB,MAAM,eAAe;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/autocomplete.tsx"],"sourcesContent":["import { Fragment, forwardRef, useId, useRef, useState } from \"react\";\nimport type {\n ComponentPropsWithoutRef,\n ForwardedRef,\n ReactElement,\n ReactNode,\n RefAttributes,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { cn } from \"../lib/cn\";\nimport { FieldLabel, FIELD_BASE, FIELD_FLOATING_PAD, FIELD_INVALID, Spinner } from \"./ui\";\nimport { useAnchoredPanel } from \"../hooks/use-anchored-panel\";\nimport {\n useActiveOptionScroll,\n useComboboxFieldError,\n useOptionSource,\n type ComboOption,\n} from \"./combobox-core\";\nimport { DEFAULT_COMBOBOX_LABELS, useKitLabels } from \"../i18n/kit-labels\";\n\n/**\n * `value`/`onChange` are the TEXT's, and `onSelect` is \"a suggestion was taken\" —\n * not the DOM's text-selection event — so the input's own spellings of those three\n * are omitted. Everything else reaches the `<input>`, the way it does on {@link Input}.\n */\nexport interface AutocompleteProps<V extends string | number = string>\n extends Omit<\n ComponentPropsWithoutRef<\"input\">,\n \"value\" | \"defaultValue\" | \"onChange\" | \"onSelect\" | \"children\" | \"type\"\n > {\n /** What is in the field. Controlled, and never reset by the component: opening,\n * closing and a failed lookup all leave it exactly as typed. */\n value: string;\n /** Every keystroke — and, with `fillOnSelect`, the label of a taken suggestion. */\n onChange: (text: string) => void;\n /** Suggestions the caller already has (e.g. from its own query hook). Narrowed by\n * the text unless `filter={false}`. */\n options?: ComboOption<V>[];\n /** Or: fetch them. Debounced (`debounceMs`), race-safe, only at `minChars` and up,\n * never while the field is idle; a rejection shows `loadErrorLabel` and empties\n * the list rather than leaving the previous text's rows under it. */\n loadOptions?: (query: string) => Promise<ComboOption<V>[]>;\n /** Narrow `options` by label/sublabel substring. Default `true`. Pass `false` for\n * a list a server has already searched and ranked — it is shown as given. */\n filter?: boolean;\n /** External loading flag (a caller-side fetch), OR-ed with `loadOptions`'. */\n loading?: boolean;\n /** Below this many characters nothing is offered or fetched. Default 1: an empty\n * field asks nothing — focusing it is not a search. */\n minChars?: number;\n /** Quiet time before `loadOptions` runs. Default 300 ms — an ordinary typist's\n * inter-key interval is 150–250 ms, so the pickers' 150 fires on nearly every\n * letter, which a rate-limited geocoder cannot afford. */\n debounceMs?: number;\n /** A suggestion was taken (click, or Enter on the highlighted row). */\n onSelect?: (option: ComboOption<V>) => void;\n /**\n * Put the taken suggestion's label into the field (`onChange(label)`). Default\n * `true` — the free-text case, where the text IS the value and a suggestion only\n * completes it (an address field). Pass `false` where taking a row is an ACTION\n * and the field is only the search that found it; the text then stays as typed.\n */\n fillOnSelect?: boolean;\n /** A floating label, as on {@link Combobox}. Names the field (`aria-labelledby`)\n * unless an `aria-label` is given. */\n label?: ReactNode;\n /** Leading decoration inside the field (a pin, a magnifier). Decorative: the\n * label names the field. */\n icon?: ReactNode;\n /** Required and unanswered — {@link FIELD_INVALID}. */\n invalid?: boolean;\n /** What is wrong with the VALUE, as {@link Input}'s `error`: under the field, on\n * its `aria-describedby`, implies `invalid`. Not a failed lookup — that is\n * `loadErrorLabel`, shown in the list. */\n error?: ReactNode;\n /**\n * The caller's own line in the list, replacing the automatic one (loading / failed\n * / no results). For what only the caller knows: \"offline\", \"the address service\n * is switched off\", a privacy note, the hint a caller-fetched list needs below its\n * own minimum. While set, the list opens even with no rows. Announced politely.\n */\n status?: ReactNode;\n /** Default: `combobox.noResults` from the {@link UiKitProvider}, else English. */\n emptyLabel?: string;\n /** Default: `combobox.loadError`. */\n loadErrorLabel?: string;\n /** Classes for the `<input>` itself; `className` styles the wrapper. */\n inputClassName?: string;\n}\n\nfunction AutocompleteInner<V extends string | number = string>(\n {\n value,\n onChange,\n options,\n loadOptions,\n filter,\n loading,\n minChars = 1,\n debounceMs = 300,\n onSelect,\n fillOnSelect = true,\n label,\n icon,\n invalid,\n error,\n status,\n emptyLabel,\n loadErrorLabel,\n className,\n inputClassName,\n id,\n disabled,\n onKeyDown,\n onFocus,\n onBlur,\n \"aria-label\": ariaLabel,\n \"aria-labelledby\": ariaLabelledBy,\n \"aria-describedby\": ariaDescribedBy,\n ...rest\n }: AutocompleteProps<V>,\n ref: ForwardedRef<HTMLInputElement>,\n) {\n const generated = useId();\n const fieldId = id ?? generated;\n // Off the GENERATED id: a caller's `id` is theirs to collide with.\n const listboxId = `${generated}-listbox`;\n const labelId = `${generated}-label`;\n const optionId = (index: number) => `${generated}-option-${index}`;\n const fieldRef = useRef<HTMLDivElement>(null);\n const labels = useKitLabels(\"combobox\", DEFAULT_COMBOBOX_LABELS, {\n noResults: emptyLabel,\n loadError: loadErrorLabel,\n });\n const field = useComboboxFieldError(error, invalid, ariaDescribedBy);\n\n /** The user's intent: the field is focused and the list has not been dismissed.\n * Whether anything SHOWS is decided below, from what there is to show. */\n const [open, setOpen] = useState(false);\n const [active, setActive] = useState(-1);\n const live = open && !disabled;\n const { results, busy, failed, tooShort } = useOptionSource<V>({\n options,\n loadOptions,\n loading,\n filter,\n minChars,\n debounceMs,\n query: value,\n active: live,\n });\n\n const hasStatus = status !== undefined && status !== null && status !== false && status !== \"\";\n // The visible line under the rows. Nothing below `minChars` unless the caller has\n // something to say — an empty field opening a box that says \"type more\" is noise.\n const statusLine: ReactNode = hasStatus\n ? status\n : tooShort\n ? null\n : busy && results.length === 0\n ? labels.loading\n : failed\n ? labels.loadError\n : !busy && results.length === 0\n ? labels.noResults\n : null;\n const expanded = live && (results.length > 0 || statusLine !== null);\n const activeId =\n expanded && active >= 0 && active < results.length ? optionId(active) : undefined;\n useActiveOptionScroll(activeId);\n const { rect, top, maxHeight } = useAnchoredPanel(fieldRef, expanded, { preferredHeight: 256 });\n\n const close = () => {\n setOpen(false);\n setActive(-1);\n };\n const take = (o: ComboOption<V>) => {\n if (fillOnSelect) onChange(o.label);\n onSelect?.(o);\n close();\n };\n\n const hasLabel = label !== undefined;\n // The caller's name wins; else the floating label, by reference so a non-string\n // label still names the field.\n const labelledBy =\n ariaLabel === undefined ? (ariaLabelledBy ?? (hasLabel ? labelId : undefined)) : undefined;\n\n return (\n // `relative`: the floating label and the live region's `sr-only` both need a\n // local containing block.\n <div className={cn(\"relative\", className)}>\n {hasLabel && <FieldLabel id={labelId}>{label}</FieldLabel>}\n <div ref={fieldRef} className=\"relative\">\n {icon && (\n <span\n aria-hidden\n className=\"pointer-events-none absolute start-2.5 top-1/2 flex -translate-y-1/2 text-[var(--text-muted)] [&>svg]:size-4\"\n >\n {icon}\n </span>\n )}\n <input\n {...rest}\n ref={ref}\n id={fieldId}\n type=\"text\"\n value={value}\n disabled={disabled}\n role=\"combobox\"\n aria-autocomplete=\"list\"\n aria-expanded={expanded}\n // Required by the role, and set while closed too, as on the siblings.\n aria-controls={listboxId}\n aria-activedescendant={activeId}\n aria-label={ariaLabel}\n aria-labelledby={labelledBy}\n aria-invalid={field.isInvalid || rest[\"aria-invalid\"] || undefined}\n aria-describedby={field.describedBy}\n autoComplete=\"off\"\n onFocus={(e) => {\n onFocus?.(e);\n // A seeded field (keksdose's `initialQuery`) is looked up as it is\n // focused; an empty one asks nothing, because of `minChars`.\n setOpen(true);\n }}\n onBlur={(e) => {\n onBlur?.(e);\n close();\n }}\n onChange={(e) => {\n onChange(e.target.value);\n setOpen(true);\n setActive(-1);\n }}\n onKeyDown={(e) => {\n // An Escape that closes the OPEN list is the list's, and is consumed before\n // the caller sees it. A caller whose Escape means \"close the panel\" (keksdose's\n // address search) otherwise closed the whole panel when the user only meant\n // to dismiss the suggestions — the opposite of what the docs promised.\n if (e.key === \"Escape\" && expanded) {\n e.preventDefault();\n e.stopPropagation();\n close();\n return;\n }\n onKeyDown?.(e);\n if (e.defaultPrevented) return;\n const last = results.length - 1;\n if (e.key === \"ArrowDown\") {\n e.preventDefault();\n if (!open) setOpen(true);\n else setActive((i) => Math.min(i + 1, last));\n } else if (e.key === \"ArrowUp\") {\n e.preventDefault();\n if (!open) setOpen(true);\n // From \"nothing highlighted\", Up goes to the bottom, as the APG has it.\n else setActive((i) => (i < 0 ? last : Math.max(i - 1, 0)));\n } else if (e.key === \"Enter\") {\n // No row highlighted: the text is the answer, and a form's own submit\n // is left alone.\n if (expanded && activeId) {\n e.preventDefault();\n take(results[active]);\n }\n } else if (e.key === \"Tab\") {\n close();\n }\n }}\n className={cn(\n FIELD_BASE,\n hasLabel && FIELD_FLOATING_PAD,\n icon ? \"ps-8\" : undefined,\n busy && \"pe-9\",\n field.isInvalid && FIELD_INVALID,\n inputClassName,\n )}\n />\n {busy && live && (\n // Decorative: the live region below already says \"Loading…\".\n <span className=\"pointer-events-none absolute end-2.5 top-1/2 flex -translate-y-1/2\">\n <Spinner label={null} className=\"h-4 w-4\" />\n </span>\n )}\n </div>\n {field.errorEl}\n {/* The live region, kept mounted so a change IS an announcement: focus stays\n in the field, and without it a reader typed into a geocoder and heard only\n their own letters. The panel's visible line is aria-hidden in favour of\n this, which also carries the row count the eye reads off the list. */}\n <div role=\"status\" aria-live=\"polite\" className=\"sr-only\">\n {!live\n ? null\n : statusLine !== null\n ? statusLine\n : results.length > 0\n ? labels.resultCount(results.length)\n : null}\n </div>\n {expanded &&\n rect &&\n typeof document !== \"undefined\" &&\n createPortal(\n <div\n // Every press inside the list keeps focus in the field — rows, the status\n // line, the scrollbar — or the input's blur would close the list first.\n role=\"presentation\"\n onMouseDown={(e) => e.preventDefault()}\n className=\"fixed z-50 flex flex-col overflow-hidden rounded-md border border-[var(--border)] bg-[var(--bg-surface)] shadow-lg\"\n style={{ top, left: rect.left, width: rect.width, maxHeight }}\n >\n {results.length > 0 && (\n <ul\n id={listboxId}\n role=\"listbox\"\n aria-label={ariaLabel}\n aria-labelledby={labelledBy}\n className=\"min-h-0 flex-1 overflow-y-auto py-1\"\n >\n {results.map((o, i) => {\n const startsGroup = o.group != null && o.group !== results[i - 1]?.group;\n return (\n // Keyed by group AND value, as in the core panel: an option may\n // appear once per group.\n <Fragment key={`${o.group ?? \"\"}|${String(o.value)}`}>\n {startsGroup && (\n <li\n role=\"presentation\"\n className=\"px-3 pb-0.5 pt-2 text-[11px] font-semibold uppercase tracking-wide text-[var(--text-muted)] first:pt-1\"\n >\n {o.group}\n </li>\n )}\n <li role=\"presentation\">\n <button\n type=\"button\"\n id={optionId(i)}\n role=\"option\"\n // CHOSEN, never \"highlighted\" — the family's rule. This\n // field holds no value, so the only row that can be chosen\n // is the one whose label the text already is.\n aria-selected={fillOnSelect && o.label === value}\n tabIndex={-1}\n onClick={() => take(o)}\n onMouseEnter={() => setActive(i)}\n className={cn(\n \"flex w-full items-center gap-2 px-3 py-1.5 text-start text-sm\",\n i === active ? \"bg-[var(--bg-active)]\" : \"hover:bg-[var(--bg-hover)]\",\n o.group != null && \"ps-6\",\n )}\n >\n {o.icon && (\n <span aria-hidden className=\"shrink-0 text-[var(--text-muted)]\">\n {o.icon}\n </span>\n )}\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate text-[var(--text-primary)]\">\n {o.label}\n </span>\n {o.sublabel && (\n <span className=\"block truncate text-xs text-[var(--text-placeholder)]\">\n {o.sublabel}\n </span>\n )}\n </span>\n </button>\n </li>\n </Fragment>\n );\n })}\n </ul>\n )}\n {statusLine !== null && (\n // Visible, not live — the region above speaks for it.\n <div\n aria-hidden\n className={cn(\n \"px-3 py-2 text-sm\",\n failed && !hasStatus ? \"text-[var(--danger)]\" : \"text-[var(--text-muted)]\",\n results.length > 0 && \"border-t border-[var(--border)] text-xs\",\n )}\n >\n {statusLine}\n </div>\n )}\n </div>,\n document.body,\n )}\n </div>\n );\n}\n\nconst AutocompleteBase = forwardRef(AutocompleteInner);\nAutocompleteBase.displayName = \"Autocomplete\";\n\n/**\n * An inline, async-capable text field with a suggestion list under it — the\n * WAI-ARIA APG \"editable combobox with list autocomplete\".\n *\n * Two jobs, one control:\n * - **free text** (kastlan's address field): the text is the value, the list only\n * offers completions, and taking one fills the field (`fillOnSelect`, default);\n * - **search-then-act** (keksdose's address search): the text is a query, taking a\n * row calls `onSelect` and nothing is held (`fillOnSelect={false}`).\n *\n * How it differs from its siblings: {@link Combobox} is free text over a STATIC\n * string pool and opens on focus; {@link EntityCombobox} is a trigger holding an id.\n * This one keeps no value of its own, never resets the text, asks nothing below\n * `minChars`, and reports a failed lookup instead of showing stale rows.\n *\n * Focus never leaves the `<input>`: `aria-activedescendant` names the highlighted\n * row, `aria-controls` the list, and a polite live region says what the list now\n * holds. Keyboard: ↓/↑ move (↓ opens), Enter takes the highlighted row (with none,\n * Enter is left to the form), Escape closes, Tab closes and moves on; Home/End stay\n * with the caret. An Escape that closes an open list is consumed and never reaches the\n * caller; with the list closed it does. For every other key a caller's `onKeyDown`\n * runs first and may `preventDefault()` to\n * keep a key for itself.\n *\n * The list is portalled and anchored under the field on every screen size: the\n * field already carries the keyboard, and `useAnchoredPanel` keeps the list clear\n * of it on a phone. There is no full-screen sheet as {@link Combobox} has.\n\n * Generic over the option value (`ComboOption<V>`); the ref is the `<input>`'s.\n */\nexport const Autocomplete = AutocompleteBase as <V extends string | number = string>(\n props: AutocompleteProps<V> & RefAttributes<HTMLInputElement>,\n) => ReactElement | null;\n"],"mappings":";AAgMmB,cACb,YADa;AAhMnB,SAAS,UAAU,YAAY,OAAO,QAAQ,gBAAgB;AAQ9D,SAAS,oBAAoB;AAC7B,SAA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A,4BACrB;AAAA,4BAEC;AAAA,gCAAE,QACD,oBAAC,UAAK,eAAW,MAAC,WAAU,qCACzB,YAAE,MACL;AAAA,8BAEF,qBAAC,UAAK,WAAU,kBACd;AAAA,oDAAC,UAAK,WAAU,6CACb,YAAE,OACL;AAAA,gCACC,EAAE,YACD,oBAAC,UAAK,WAAU,yDACb,YAAE,UACL;AAAA,iCAEJ;AAAA;AAAA;AAAA,wBACF,GACF;AAAA,2BA3Ca,GAAG,EAAE,SAAS,EAAE,IAAI,OAAO,EAAE,KAAK,CAAC,EA4ClD;AAAA;AAAA,kBAEJ,CAAC;AAAA;AAAA,cACH;AAAA,cAED,eAAe;AAAA,cAEd;AAAA,gBAAC;AAAA;AAAA,kBACC,eAAW;AAAA,kBACX,WAAW;AAAA,oBACT;AAAA,oBACA,UAAU,CAAC,YAAY,yBAAyB;AAAA,oBAChD,QAAQ,SAAS,KAAK;AAAA,kBACxB;AAAA,kBAEC;AAAA;AAAA,cACH;AAAA;AAAA;AAAA,QAEJ;AAAA,QACA,SAAS;AAAA,MACX;AAAA,OACJ;AAAA;AAEJ;AAEA,MAAM,mBAAmB,WAAW,iBAAiB;AACrD,iBAAiB,cAAc;AAgCxB,MAAM,eAAe;","names":[]}
|
|
@@ -35,6 +35,15 @@ interface CheckboxProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "typ
|
|
|
35
35
|
* the row when there is a label, the box's own wrapper when there is not — which
|
|
36
36
|
* is where layout (`self-end pb-2` to sit on a field's baseline) belongs. */
|
|
37
37
|
inputClassName?: string;
|
|
38
|
+
/**
|
|
39
|
+
* Must be ticked to submit — a consent, an acceptance before paying. Reaches the
|
|
40
|
+
* `<input>` as the native `required` (so a `<form>` refuses to submit without it and a
|
|
41
|
+
* screen reader announces "required"), and draws the kit's required mark after the
|
|
42
|
+
* label, the same `aria-hidden` star as {@link Label}'s: the word is announced from
|
|
43
|
+
* the control, so a star inside the name would only be read out as noise. Write the
|
|
44
|
+
* label WITHOUT a literal "*". No mark without a label.
|
|
45
|
+
*/
|
|
46
|
+
required?: boolean;
|
|
38
47
|
}
|
|
39
48
|
/**
|
|
40
49
|
* A native checkbox in the kit's tokens, with an optional label, description and
|
|
@@ -20,6 +20,7 @@ const Checkbox = forwardRef(function Checkbox2({
|
|
|
20
20
|
inputClassName,
|
|
21
21
|
id,
|
|
22
22
|
disabled,
|
|
23
|
+
required,
|
|
23
24
|
...rest
|
|
24
25
|
}, ref) {
|
|
25
26
|
const generated = useId();
|
|
@@ -48,6 +49,7 @@ const Checkbox = forwardRef(function Checkbox2({
|
|
|
48
49
|
ref: setRef,
|
|
49
50
|
id: bare ? id : inputId,
|
|
50
51
|
disabled,
|
|
52
|
+
required,
|
|
51
53
|
...rest,
|
|
52
54
|
type: "checkbox",
|
|
53
55
|
"aria-invalid": isInvalid || rest["aria-invalid"] || void 0,
|
|
@@ -96,7 +98,7 @@ const Checkbox = forwardRef(function Checkbox2({
|
|
|
96
98
|
children: [
|
|
97
99
|
/* @__PURE__ */ jsx("span", { className: "flex h-5 shrink-0 items-center", children: box }),
|
|
98
100
|
/* @__PURE__ */ jsxs("span", { className: "min-w-0", children: [
|
|
99
|
-
label !== void 0 && /* @__PURE__ */
|
|
101
|
+
label !== void 0 && /* @__PURE__ */ jsxs(
|
|
100
102
|
"label",
|
|
101
103
|
{
|
|
102
104
|
htmlFor: inputId,
|
|
@@ -106,7 +108,10 @@ const Checkbox = forwardRef(function Checkbox2({
|
|
|
106
108
|
// words, and a drag that starts on them starts a native text drag.
|
|
107
109
|
disabled ? "cursor-not-allowed" : "cursor-pointer select-none"
|
|
108
110
|
),
|
|
109
|
-
children:
|
|
111
|
+
children: [
|
|
112
|
+
label,
|
|
113
|
+
required && /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: "ms-0.5 text-[var(--danger)]", children: "*" })
|
|
114
|
+
]
|
|
110
115
|
}
|
|
111
116
|
),
|
|
112
117
|
showDescription && /* @__PURE__ */ jsx("span", { id: descriptionId, className: "mt-0.5 block text-xs text-[var(--text-muted)]", children: description }),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/checkbox.tsx"],"sourcesContent":["import { forwardRef, useCallback, useEffect, useId, useRef } from \"react\";\nimport { Check, Minus } from \"lucide-react\";\nimport type { ChangeEvent, InputHTMLAttributes, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { assignRef, hasMessage, mergeDescribedBy } from \"./choice-parts\";\n\n/**\n * A checkbox that is still `<input type=\"checkbox\">`.\n *\n * The three consuming apps had three answers: ~30 raw inputs in Keksdose leaning on\n * `tokens.css`'s `accent-color`, a label-plus-box `CheckboxField` in Lenkbank, and a\n * Radix `<button role=\"checkbox\">` in Kastlan. The native element is the one that\n * needs no ARIA to be a checkbox — it submits with its form, answers to `required`,\n * resets with the form and takes a `<label for>` click — so it stays underneath, and\n * only its paint is replaced (`appearance-none`, a token-coloured box, and a glyph\n * laid over it that ignores the pointer so the click still lands on the input).\n *\n * `accent-color` alone was not enough: it tints the native box but cannot change its\n * border, so an INVALID checkbox had no way to say so, and the unchecked box kept the\n * browser's own grey outline in both themes.\n */\n\n// The box. 16px, like every raw checkbox it replaces, so a migration moves nothing.\n//\n// `focus-visible`, with an offset in the surface colour: a --brand ring touching a\n// --brand-filled (checked) box would be a ring painted in the colour it sits on —\n// present in the DOM and invisible on screen. The offset is what separates the two.\nconst BOX =\n \"peer size-4 shrink-0 cursor-pointer appearance-none rounded-[4px] border border-[var(--border-strong)] bg-[var(--bg-surface)] shadow-sm transition-colors \" +\n \"checked:border-[var(--brand)] checked:bg-[var(--brand)] \" +\n \"focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand)] focus-visible:ring-offset-1 focus-visible:ring-offset-[var(--bg-surface)] \" +\n \"disabled:cursor-not-allowed\";\n\n// A mixed box wears the checked fill whether or not the underlying input is checked:\n// `indeterminate` is a property the browser keeps separately from `checked`, and the\n// dash means \"some\", which is neither answer.\nconst BOX_MIXED = \"border-[var(--brand)] bg-[var(--brand)]\";\n\n// The same geometry as FIELD_INVALID — a border plus a 1px ring, so the highlight\n// survives fractional display scaling on every edge (see the note in ui.tsx). The\n// focus ring turns danger too, so focusing a wrong box does not repaint it as fine.\nconst BOX_INVALID =\n \"border-[var(--danger-border)] ring-1 ring-[var(--danger-border)] checked:border-[var(--danger-border)] focus-visible:ring-[var(--danger)]\";\n\nconst ERROR_CLASS = \"mt-1 text-[11px] leading-tight text-[var(--danger)]\";\n\nexport interface CheckboxProps extends Omit<InputHTMLAttributes<HTMLInputElement>, \"type\"> {\n /**\n * The words beside the box. Rendered as a `<label for>` rather than a label that\n * wraps the input, so `description` and `error` can sit under it without becoming\n * part of the accessible NAME — a wrapping label would have the screen reader read\n * the whole paragraph as the checkbox's name.\n */\n label?: ReactNode;\n /** Secondary text under the label (\"Used when no account is chosen\"). Pointed at by\n * `aria-describedby`, merged with any the caller passed. Kastlan's\n * `CheckboxField` `description` variant. */\n description?: ReactNode;\n /**\n * \"Some but not all\" — the header box of a list whose rows are partly selected.\n * A DOM property with no HTML attribute, so it is set on the element after every\n * render; it does not touch `checked`, and a click clears it (the browser's rule,\n * and the caller's `onChange` decides what the click means).\n */\n indeterminate?: boolean;\n /** See {@link Input}'s `invalid`: paints the box and sets `aria-invalid` together,\n * so the two cannot be spelled separately. */\n invalid?: boolean;\n /** What is wrong, in the caller's words (\"Accept the terms to continue\"). Rendered\n * under the label, attached with `aria-describedby`, and implies `invalid`. */\n error?: ReactNode;\n /** The checked state as a boolean — the `(next) => …` shape Lenkbank's\n * `CheckboxField` and Radix's `onCheckedChange` both used, so a migration does not\n * have to unwrap `event.target.checked` at every call site. Fires alongside\n * `onChange`, never instead of it. */\n onCheckedChange?: (checked: boolean) => void;\n /** Classes for the `<input>` itself. `className` styles the OUTERMOST element —\n * the row when there is a label, the box's own wrapper when there is not — which\n * is where layout (`self-end pb-2` to sit on a field's baseline) belongs. */\n inputClassName?: string;\n}\n\n/**\n * A native checkbox in the kit's tokens, with an optional label, description and\n * error.\n *\n * Without `label`, `description` or `error` it renders the box and nothing else, so\n * it drops into a table cell or a caller's own `<label>` exactly as the raw input\n * did — give it an `aria-label` there. Every other prop reaches the `<input>`\n * (`checked`, `defaultChecked`, `name`, `required`, `data-*`, `aria-*`), so it works\n * controlled, uncontrolled, and inside a plain `<form>`.\n */\nexport const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(function Checkbox(\n {\n label,\n description,\n indeterminate = false,\n invalid,\n error,\n onCheckedChange,\n onChange,\n className,\n inputClassName,\n id,\n disabled,\n ...rest\n },\n ref,\n) {\n const generated = useId();\n const inputId = id ?? generated;\n const descriptionId = `${inputId}-description`;\n const errorId = `${inputId}-error`;\n const showError = hasMessage(error);\n const showDescription = hasMessage(description);\n const isInvalid = Boolean(invalid) || showError;\n // Nothing to lay out beside the box: render the box alone, as the raw input was.\n const bare = label === undefined && !showDescription && !showError;\n\n const local = useRef<HTMLInputElement | null>(null);\n const setRef = useCallback(\n (node: HTMLInputElement | null) => {\n local.current = node;\n assignRef(ref, node);\n },\n [ref],\n );\n // After EVERY render, not only when the prop changes: a click clears the property\n // in the DOM, and a controlled caller that keeps `indeterminate` true expects the\n // dash back on the next render even though the prop never changed.\n useEffect(() => {\n if (local.current) local.current.indeterminate = indeterminate;\n });\n\n const box = (\n <span className={cn(\"relative inline-flex shrink-0\", bare && className)}>\n <input\n ref={setRef}\n id={bare ? id : inputId}\n disabled={disabled}\n {...rest}\n // After the spread, like Switch: a props object spread at a checkbox must not\n // be able to turn it into something else.\n type=\"checkbox\"\n // OR-ed with the spread so a caller's own `aria-invalid` survives — Input's rule.\n aria-invalid={isInvalid || rest[\"aria-invalid\"] || undefined}\n aria-describedby={mergeDescribedBy(\n rest[\"aria-describedby\"],\n showDescription && descriptionId,\n showError && errorId,\n )}\n onChange={(e: ChangeEvent<HTMLInputElement>) => {\n onChange?.(e);\n onCheckedChange?.(e.target.checked);\n }}\n className={cn(BOX, indeterminate && BOX_MIXED, isInvalid && BOX_INVALID, inputClassName)}\n />\n {/* The glyph is drawn over the box, not inside it (an input has no children),\n and ignores the pointer so a click on the tick still toggles the input. The\n tick is shown by `peer-checked`, so an UNCONTROLLED box shows it too; the\n dash replaces it outright while `indeterminate` holds. */}\n {indeterminate ? (\n <Minus\n aria-hidden\n strokeWidth={3}\n className=\"pointer-events-none absolute inset-0 m-auto size-3 text-[var(--brand-contrast)]\"\n />\n ) : (\n <Check\n aria-hidden\n strokeWidth={3}\n className=\"pointer-events-none invisible absolute inset-0 m-auto size-3 text-[var(--brand-contrast)] peer-checked:visible\"\n />\n )}\n </span>\n );\n\n if (bare) return box;\n\n return (\n <div\n className={cn(\n // `items-start` + a 20px cell for the box: the box centres on the label's FIRST\n // line (text-sm is 20px tall), so a label that wraps keeps the box at the top\n // rather than floating to the middle of a paragraph.\n \"flex items-start gap-2\",\n // The whole row fades, the way ToggleGroup and the fields do, so the label does\n // not stay at full strength beside a box you cannot change.\n disabled && \"opacity-60\",\n className,\n )}\n >\n <span className=\"flex h-5 shrink-0 items-center\">{box}</span>\n <span className=\"min-w-0\">\n {label !== undefined && (\n <label\n htmlFor={inputId}\n className={cn(\n \"block text-sm leading-5 text-[var(--text-primary)]\",\n // `select-none`: a double-click to toggle twice would otherwise select the\n // words, and a drag that starts on them starts a native text drag.\n disabled ? \"cursor-not-allowed\" : \"cursor-pointer select-none\",\n )}\n >\n {label}\n </label>\n )}\n {showDescription && (\n <span id={descriptionId} className=\"mt-0.5 block text-xs text-[var(--text-muted)]\">\n {description}\n </span>\n )}\n {showError && (\n <span id={errorId} className={cn(\"block\", ERROR_CLASS)}>\n {error}\n </span>\n )}\n </span>\n </div>\n );\n});\nCheckbox.displayName = \"Checkbox\";\n"],"mappings":";AAuII,SACE,KADF;AAvIJ,SAAS,YAAY,aAAa,WAAW,OAAO,cAAc;AAClE,SAAS,OAAO,aAAa;AAE7B,SAAS,UAAU;AACnB,SAAS,WAAW,YAAY,wBAAwB;AAuBxD,MAAM,MACJ;AAQF,MAA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cAAc;AAAA;AAAA,IACzF;AAAA,IAKC,gBACC;AAAA,MAAC;AAAA;AAAA,QACC,eAAW;AAAA,QACX,aAAa;AAAA,QACb,WAAU;AAAA;AAAA,IACZ,IAEA;AAAA,MAAC;AAAA;AAAA,QACC,eAAW;AAAA,QACX,aAAa;AAAA,QACb,WAAU;AAAA;AAAA,IACZ;AAAA,KAEJ;AAGF,MAAI,KAAM,QAAO;AAEjB,SACE;AAAA,IAAC;AAAA;AAAA,MACC,WAAW;AAAA;AAAA;AAAA;AAAA,QAIT;AAAA;AAAA;AAAA,QAGA,YAAY;AAAA,QACZ;AAAA,MACF;AAAA,MAEA;AAAA,4BAAC,UAAK,WAAU,kCAAkC,eAAI;AAAA,QACtD,qBAAC,UAAK,WAAU,WACb;AAAA,oBAAU,UACT;AAAA,YAAC;AAAA;AAAA,cACC,SAAS;AAAA,cACT,WAAW;AAAA,gBACT;AAAA;AAAA;AAAA,gBAGA,WAAW,uBAAuB;AAAA,cACpC;AAAA,cAEC;AAAA;AAAA,UACH;AAAA,UAED,mBACC,oBAAC,UAAK,IAAI,eAAe,WAAU,iDAChC,uBACH;AAAA,UAED,aACC,oBAAC,UAAK,IAAI,SAAS,WAAW,GAAG,SAAS,WAAW,GAClD,iBACH;AAAA,WAEJ;AAAA;AAAA;AAAA,EACF;AAEJ,CAAC;AACD,SAAS,cAAc;","names":["Checkbox"]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/checkbox.tsx"],"sourcesContent":["import { forwardRef, useCallback, useEffect, useId, useRef } from \"react\";\nimport { Check, Minus } from \"lucide-react\";\nimport type { ChangeEvent, InputHTMLAttributes, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { assignRef, hasMessage, mergeDescribedBy } from \"./choice-parts\";\n\n/**\n * A checkbox that is still `<input type=\"checkbox\">`.\n *\n * The three consuming apps had three answers: ~30 raw inputs in Keksdose leaning on\n * `tokens.css`'s `accent-color`, a label-plus-box `CheckboxField` in Lenkbank, and a\n * Radix `<button role=\"checkbox\">` in Kastlan. The native element is the one that\n * needs no ARIA to be a checkbox — it submits with its form, answers to `required`,\n * resets with the form and takes a `<label for>` click — so it stays underneath, and\n * only its paint is replaced (`appearance-none`, a token-coloured box, and a glyph\n * laid over it that ignores the pointer so the click still lands on the input).\n *\n * `accent-color` alone was not enough: it tints the native box but cannot change its\n * border, so an INVALID checkbox had no way to say so, and the unchecked box kept the\n * browser's own grey outline in both themes.\n */\n\n// The box. 16px, like every raw checkbox it replaces, so a migration moves nothing.\n//\n// `focus-visible`, with an offset in the surface colour: a --brand ring touching a\n// --brand-filled (checked) box would be a ring painted in the colour it sits on —\n// present in the DOM and invisible on screen. The offset is what separates the two.\nconst BOX =\n \"peer size-4 shrink-0 cursor-pointer appearance-none rounded-[4px] border border-[var(--border-strong)] bg-[var(--bg-surface)] shadow-sm transition-colors \" +\n \"checked:border-[var(--brand)] checked:bg-[var(--brand)] \" +\n \"focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand)] focus-visible:ring-offset-1 focus-visible:ring-offset-[var(--bg-surface)] \" +\n \"disabled:cursor-not-allowed\";\n\n// A mixed box wears the checked fill whether or not the underlying input is checked:\n// `indeterminate` is a property the browser keeps separately from `checked`, and the\n// dash means \"some\", which is neither answer.\nconst BOX_MIXED = \"border-[var(--brand)] bg-[var(--brand)]\";\n\n// The same geometry as FIELD_INVALID — a border plus a 1px ring, so the highlight\n// survives fractional display scaling on every edge (see the note in ui.tsx). The\n// focus ring turns danger too, so focusing a wrong box does not repaint it as fine.\nconst BOX_INVALID =\n \"border-[var(--danger-border)] ring-1 ring-[var(--danger-border)] checked:border-[var(--danger-border)] focus-visible:ring-[var(--danger)]\";\n\nconst ERROR_CLASS = \"mt-1 text-[11px] leading-tight text-[var(--danger)]\";\n\nexport interface CheckboxProps extends Omit<InputHTMLAttributes<HTMLInputElement>, \"type\"> {\n /**\n * The words beside the box. Rendered as a `<label for>` rather than a label that\n * wraps the input, so `description` and `error` can sit under it without becoming\n * part of the accessible NAME — a wrapping label would have the screen reader read\n * the whole paragraph as the checkbox's name.\n */\n label?: ReactNode;\n /** Secondary text under the label (\"Used when no account is chosen\"). Pointed at by\n * `aria-describedby`, merged with any the caller passed. Kastlan's\n * `CheckboxField` `description` variant. */\n description?: ReactNode;\n /**\n * \"Some but not all\" — the header box of a list whose rows are partly selected.\n * A DOM property with no HTML attribute, so it is set on the element after every\n * render; it does not touch `checked`, and a click clears it (the browser's rule,\n * and the caller's `onChange` decides what the click means).\n */\n indeterminate?: boolean;\n /** See {@link Input}'s `invalid`: paints the box and sets `aria-invalid` together,\n * so the two cannot be spelled separately. */\n invalid?: boolean;\n /** What is wrong, in the caller's words (\"Accept the terms to continue\"). Rendered\n * under the label, attached with `aria-describedby`, and implies `invalid`. */\n error?: ReactNode;\n /** The checked state as a boolean — the `(next) => …` shape Lenkbank's\n * `CheckboxField` and Radix's `onCheckedChange` both used, so a migration does not\n * have to unwrap `event.target.checked` at every call site. Fires alongside\n * `onChange`, never instead of it. */\n onCheckedChange?: (checked: boolean) => void;\n /** Classes for the `<input>` itself. `className` styles the OUTERMOST element —\n * the row when there is a label, the box's own wrapper when there is not — which\n * is where layout (`self-end pb-2` to sit on a field's baseline) belongs. */\n inputClassName?: string;\n /**\n * Must be ticked to submit — a consent, an acceptance before paying. Reaches the\n * `<input>` as the native `required` (so a `<form>` refuses to submit without it and a\n * screen reader announces \"required\"), and draws the kit's required mark after the\n * label, the same `aria-hidden` star as {@link Label}'s: the word is announced from\n * the control, so a star inside the name would only be read out as noise. Write the\n * label WITHOUT a literal \"*\". No mark without a label.\n */\n required?: boolean;\n}\n\n/**\n * A native checkbox in the kit's tokens, with an optional label, description and\n * error.\n *\n * Without `label`, `description` or `error` it renders the box and nothing else, so\n * it drops into a table cell or a caller's own `<label>` exactly as the raw input\n * did — give it an `aria-label` there. Every other prop reaches the `<input>`\n * (`checked`, `defaultChecked`, `name`, `required`, `data-*`, `aria-*`), so it works\n * controlled, uncontrolled, and inside a plain `<form>`.\n */\nexport const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(function Checkbox(\n {\n label,\n description,\n indeterminate = false,\n invalid,\n error,\n onCheckedChange,\n onChange,\n className,\n inputClassName,\n id,\n disabled,\n required,\n ...rest\n },\n ref,\n) {\n const generated = useId();\n const inputId = id ?? generated;\n const descriptionId = `${inputId}-description`;\n const errorId = `${inputId}-error`;\n const showError = hasMessage(error);\n const showDescription = hasMessage(description);\n const isInvalid = Boolean(invalid) || showError;\n // Nothing to lay out beside the box: render the box alone, as the raw input was.\n const bare = label === undefined && !showDescription && !showError;\n\n const local = useRef<HTMLInputElement | null>(null);\n const setRef = useCallback(\n (node: HTMLInputElement | null) => {\n local.current = node;\n assignRef(ref, node);\n },\n [ref],\n );\n // After EVERY render, not only when the prop changes: a click clears the property\n // in the DOM, and a controlled caller that keeps `indeterminate` true expects the\n // dash back on the next render even though the prop never changed.\n useEffect(() => {\n if (local.current) local.current.indeterminate = indeterminate;\n });\n\n const box = (\n <span className={cn(\"relative inline-flex shrink-0\", bare && className)}>\n <input\n ref={setRef}\n id={bare ? id : inputId}\n disabled={disabled}\n required={required}\n {...rest}\n // After the spread, like Switch: a props object spread at a checkbox must not\n // be able to turn it into something else.\n type=\"checkbox\"\n // OR-ed with the spread so a caller's own `aria-invalid` survives — Input's rule.\n aria-invalid={isInvalid || rest[\"aria-invalid\"] || undefined}\n aria-describedby={mergeDescribedBy(\n rest[\"aria-describedby\"],\n showDescription && descriptionId,\n showError && errorId,\n )}\n onChange={(e: ChangeEvent<HTMLInputElement>) => {\n onChange?.(e);\n onCheckedChange?.(e.target.checked);\n }}\n className={cn(BOX, indeterminate && BOX_MIXED, isInvalid && BOX_INVALID, inputClassName)}\n />\n {/* The glyph is drawn over the box, not inside it (an input has no children),\n and ignores the pointer so a click on the tick still toggles the input. The\n tick is shown by `peer-checked`, so an UNCONTROLLED box shows it too; the\n dash replaces it outright while `indeterminate` holds. */}\n {indeterminate ? (\n <Minus\n aria-hidden\n strokeWidth={3}\n className=\"pointer-events-none absolute inset-0 m-auto size-3 text-[var(--brand-contrast)]\"\n />\n ) : (\n <Check\n aria-hidden\n strokeWidth={3}\n className=\"pointer-events-none invisible absolute inset-0 m-auto size-3 text-[var(--brand-contrast)] peer-checked:visible\"\n />\n )}\n </span>\n );\n\n if (bare) return box;\n\n return (\n <div\n className={cn(\n // `items-start` + a 20px cell for the box: the box centres on the label's FIRST\n // line (text-sm is 20px tall), so a label that wraps keeps the box at the top\n // rather than floating to the middle of a paragraph.\n \"flex items-start gap-2\",\n // The whole row fades, the way ToggleGroup and the fields do, so the label does\n // not stay at full strength beside a box you cannot change.\n disabled && \"opacity-60\",\n className,\n )}\n >\n <span className=\"flex h-5 shrink-0 items-center\">{box}</span>\n <span className=\"min-w-0\">\n {label !== undefined && (\n <label\n htmlFor={inputId}\n className={cn(\n \"block text-sm leading-5 text-[var(--text-primary)]\",\n // `select-none`: a double-click to toggle twice would otherwise select the\n // words, and a drag that starts on them starts a native text drag.\n disabled ? \"cursor-not-allowed\" : \"cursor-pointer select-none\",\n )}\n >\n {label}\n {required && (\n <span aria-hidden className=\"ms-0.5 text-[var(--danger)]\">\n *\n </span>\n )}\n </label>\n )}\n {showDescription && (\n <span id={descriptionId} className=\"mt-0.5 block text-xs text-[var(--text-muted)]\">\n {description}\n </span>\n )}\n {showError && (\n <span id={errorId} className={cn(\"block\", ERROR_CLASS)}>\n {error}\n </span>\n )}\n </span>\n </div>\n );\n});\nCheckbox.displayName = \"Checkbox\";\n"],"mappings":";AAiJI,SACE,KADF;AAjJJ,SAAS,YAAY,aAAa,WAAW,OAAO,cAAc;AAClE,SAAS,OAAO,aAAa;AAE7B,SAAS,UAAU;AACnB,SAAS,WAAW,YAAY,wBAAwB;AAuBxD,MAAM,MACJ;AAQF,MAAM,YAAY;AAKlB,MAAM,cACJ;AAEF,MAAM,cAAc;AAyDb,MAAM,WAAW,WAA4C,SAASA,UAC3E;AAAA,EACE;AAAA,EACA;AAAA,EACA,gBA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QACb,WAAU;AAAA;AAAA,IACZ,IAEA;AAAA,MAAC;AAAA;AAAA,QACC,eAAW;AAAA,QACX,aAAa;AAAA,QACb,WAAU;AAAA;AAAA,IACZ;AAAA,KAEJ;AAGF,MAAI,KAAM,QAAO;AAEjB,SACE;AAAA,IAAC;AAAA;AAAA,MACC,WAAW;AAAA;AAAA;AAAA;AAAA,QAIT;AAAA;AAAA;AAAA,QAGA,YAAY;AAAA,QACZ;AAAA,MACF;AAAA,MAEA;AAAA,4BAAC,UAAK,WAAU,kCAAkC,eAAI;AAAA,QACtD,qBAAC,UAAK,WAAU,WACb;AAAA,oBAAU,UACT;AAAA,YAAC;AAAA;AAAA,cACC,SAAS;AAAA,cACT,WAAW;AAAA,gBACT;AAAA;AAAA;AAAA,gBAGA,WAAW,uBAAuB;AAAA,cACpC;AAAA,cAEC;AAAA;AAAA,gBACA,YACC,oBAAC,UAAK,eAAW,MAAC,WAAU,+BAA8B,eAE1D;AAAA;AAAA;AAAA,UAEJ;AAAA,UAED,mBACC,oBAAC,UAAK,IAAI,eAAe,WAAU,iDAChC,uBACH;AAAA,UAED,aACC,oBAAC,UAAK,IAAI,SAAS,WAAW,GAAG,SAAS,WAAW,GAClD,iBACH;AAAA,WAEJ;AAAA;AAAA;AAAA,EACF;AAEJ,CAAC;AACD,SAAS,cAAc;","names":["Checkbox"]}
|
|
@@ -21,7 +21,8 @@ function matchesAccept(file, accept) {
|
|
|
21
21
|
const tokens = (accept ?? "").split(",").map((t) => t.trim().toLowerCase()).filter(Boolean);
|
|
22
22
|
if (tokens.length === 0) return true;
|
|
23
23
|
const name = file.name.toLowerCase();
|
|
24
|
-
const type = (file.type || "").toLowerCase();
|
|
24
|
+
const type = (file.type || typeFromExtension(name) || "").toLowerCase();
|
|
25
|
+
if (!type && !tokens.every((t) => t.startsWith("."))) return true;
|
|
25
26
|
return tokens.some((token) => {
|
|
26
27
|
if (token.startsWith(".")) return name.endsWith(token);
|
|
27
28
|
if (!type) return false;
|
|
@@ -29,6 +30,23 @@ function matchesAccept(file, accept) {
|
|
|
29
30
|
return type === token;
|
|
30
31
|
});
|
|
31
32
|
}
|
|
33
|
+
const EXTENSION_TYPES = {
|
|
34
|
+
heic: "image/heic",
|
|
35
|
+
heif: "image/heif",
|
|
36
|
+
avif: "image/avif",
|
|
37
|
+
webp: "image/webp",
|
|
38
|
+
jpg: "image/jpeg",
|
|
39
|
+
jpeg: "image/jpeg",
|
|
40
|
+
png: "image/png",
|
|
41
|
+
gif: "image/gif",
|
|
42
|
+
pdf: "application/pdf",
|
|
43
|
+
csv: "text/csv",
|
|
44
|
+
txt: "text/plain"
|
|
45
|
+
};
|
|
46
|
+
function typeFromExtension(name) {
|
|
47
|
+
const dot = name.lastIndexOf(".");
|
|
48
|
+
return dot === -1 ? void 0 : EXTENSION_TYPES[name.slice(dot + 1)];
|
|
49
|
+
}
|
|
32
50
|
function screenFiles(files, opts, labels, formatSize) {
|
|
33
51
|
const accepted = [];
|
|
34
52
|
const rejected = [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/file-button.tsx"],"sourcesContent":["import { forwardRef, useRef, useState } from \"react\";\nimport type { ComponentPropsWithoutRef, DragEvent, ReactElement, ReactNode, Ref } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { useAnnounce } from \"../hooks/use-announce\";\nimport { useKitFileLabels, useKitLabels } from \"../i18n/kit-labels\";\nimport { Button, Spinner } from \"./ui\";\n\n/**\n * A button that opens the file picker — the shape all three apps kept writing by hand\n * as a `<Button>` plus a hidden `<input type=\"file\">` plus a ref between them (seven\n * copies in keksdose, two each in kastlan and lenkbank).\n *\n * Every copy had to remember the same four things, and each one forgot at least one:\n *\n * 1. **Reset the input after every pick.** A file input fires `change` only when its\n * value CHANGES, so picking the same file twice in a row — the retry after a failed\n * upload, the second photo of the same receipt — did nothing at all, which reads as\n * a broken button. `value = \"\"` after each pick; always, not per call site.\n * 2. **`type=\"button\"`.** `<Button>` does not set it, and inside a form a bare button\n * submits the form before the picker opens.\n * 3. **Check the file.** `accept` filters the DIALOG, not the result: the dialog's\n * \"All files\" switch, a drop, and a mobile share sheet all hand over whatever the\n * user chose. So `accept` is re-checked here, along with `maxSize`, `maxFiles` and\n * an optional `isValid`.\n * 4. **Say no without a toast.** A rejection is reported through `onReject`, with a\n * translated message per file, and spoken through a live region — the kit does not\n * decide how an app surfaces errors (keksdose's proposal §1 asked for exactly that).\n *\n * The part that is not a button — the hidden input, the check, the announcement — is\n * {@link useFilePicker}, for the case where the thing that opens the picker is someone\n * else's control (a card's \"Add\" action, a menu item, a second button for the camera).\n */\n\n/* ── Labels ──────────────────────────────────────────────────────────────── */\n\n/** Every string the file pickers ({@link FileButton}, `FileDropzone`) render or speak.\n * Messages are functions of the file name so a translation can put it anywhere. */\nexport interface FilePickerLabels {\n /** The file's type is not in `accept`. */\n rejectedType: (name: string) => string;\n /** The file is larger than `maxSize`; `maxSize` arrives formatted (\"5 MB\"). */\n rejectedSize: (name: string, maxSize: string) => string;\n /** The file was one too many for `maxFiles`. */\n rejectedCount: (name: string, maxFiles: number) => string;\n /** `isValid` said no and the caller gave no `invalidMessage`. */\n rejectedInvalid: (name: string) => string;\n /** Spoken instead of the per-file message when more than one file was refused. */\n rejectedMany: (count: number) => string;\n /** Spoken after a pick the component itself echoes (the dropzone). */\n selected: (count: number, firstName: string) => string;\n /** The dropzone's remove button for one file. */\n remove: (name: string) => string;\n /** The dropzone's remove-everything button in `multiple` mode. */\n clearAll: string;\n /** Spoken after a remove / clear, since the button that was pressed is gone. */\n removed: (name: string) => string;\n cleared: string;\n}\n\nexport const DEFAULT_FILE_PICKER_LABELS: FilePickerLabels = {\n rejectedType: (name) => `“${name}” is not a supported file type`,\n rejectedSize: (name, maxSize) => `“${name}” is larger than ${maxSize}`,\n rejectedCount: (name, maxFiles) =>\n `“${name}” was not added: at most ${maxFiles} ${maxFiles === 1 ? \"file\" : \"files\"}`,\n rejectedInvalid: (name) => `“${name}” cannot be used here`,\n rejectedMany: (count) => `${count} files were not added`,\n selected: (count, firstName) => (count === 1 ? `“${firstName}” selected` : `${count} files selected`),\n remove: (name) => `Remove “${name}”`,\n clearAll: \"Remove all files\",\n removed: (name) => `“${name}” removed`,\n cleared: \"All files removed\",\n};\n\n/* ── Screening ───────────────────────────────────────────────────────────── */\n\nexport type FileRejectionReason = \"type\" | \"size\" | \"count\" | \"invalid\";\n\n/** One file the picker refused, and why. `message` is already translated (see\n * {@link FilePickerLabels}, or the caller's `invalidMessage`), so a host that just\n * wants to show it can render `rejections[0].message` as is. */\nexport interface FileRejection {\n file: File;\n reason: FileRejectionReason;\n message: string;\n}\n\n/**\n * Does `file` satisfy an `accept` string, the way the browser's dialog reads it?\n * Comma-separated tokens: `.ext` (case-insensitive suffix of the name), `type/*`\n * (a MIME family) or an exact MIME type. An empty or absent `accept` takes anything.\n *\n * A file with no `type` — common for `.step`, `.dat`, anything the OS has no MIME\n * mapping for — can only match by extension, which is why lenkbank lists `.stp` AND\n * `model/step`: that is how `accept` has to be written for the dialog anyway.\n */\nexport function matchesAccept(file: File, accept: string | undefined): boolean {\n const tokens = (accept ?? \"\")\n .split(\",\")\n .map((t) => t.trim().toLowerCase())\n .filter(Boolean);\n if (tokens.length === 0) return true;\n const name = file.name.toLowerCase();\n const type = (file.type || \"\").toLowerCase();\n return tokens.some((token) => {\n if (token.startsWith(\".\")) return name.endsWith(token);\n if (!type) return false;\n if (token.endsWith(\"/*\")) return type.startsWith(token.slice(0, -1));\n return type === token;\n });\n}\n\n/** What the pickers screen a pick with. All optional; nothing set accepts everything. */\nexport interface FileScreenOptions {\n accept?: string;\n /** Bytes. Larger files are refused with reason `\"size\"`. */\n maxSize?: number;\n /** How many files one pick may deliver. The rest are refused with reason `\"count\"`\n * — first come, first kept. For a running cap (\"at most 5 attachments\") pass what\n * is LEFT: `maxFiles={5 - attachments.length}`. */\n maxFiles?: number;\n /** The caller's own check, after `accept` and `maxSize`. */\n isValid?: (file: File) => boolean;\n /** The message for an `isValid` refusal; `labels.rejectedInvalid` otherwise. */\n invalidMessage?: string;\n}\n\n/** @internal Split a pick into the files that pass and the ones that do not. */\nexport function screenFiles(\n files: readonly File[],\n opts: FileScreenOptions,\n labels: FilePickerLabels,\n formatSize: (bytes: number) => string,\n): { accepted: File[]; rejected: FileRejection[] } {\n const accepted: File[] = [];\n const rejected: FileRejection[] = [];\n for (const file of files) {\n let reason: FileRejectionReason | null = null;\n if (!matchesAccept(file, opts.accept)) reason = \"type\";\n else if (opts.maxSize !== undefined && file.size > opts.maxSize) reason = \"size\";\n else if (opts.isValid && !opts.isValid(file)) reason = \"invalid\";\n // Count last, and only against files that passed everything else: a refused\n // file should not use up one of the slots a good one could have had.\n else if (opts.maxFiles !== undefined && accepted.length >= opts.maxFiles) reason = \"count\";\n if (reason === null) {\n accepted.push(file);\n continue;\n }\n const message =\n reason === \"type\"\n ? labels.rejectedType(file.name)\n : reason === \"size\"\n ? labels.rejectedSize(file.name, formatSize(opts.maxSize ?? 0))\n : reason === \"count\"\n ? labels.rejectedCount(file.name, Math.max(0, opts.maxFiles ?? 0))\n : (opts.invalidMessage ?? labels.rejectedInvalid(file.name));\n rejected.push({ file, reason, message });\n }\n return { accepted, rejected };\n}\n\n/** One sentence for a whole batch of refusals: the file's own message for one, a\n * count for several — reading out five sentences in a row helps nobody. */\nexport function summariseRejections(rejected: readonly FileRejection[], labels: FilePickerLabels): string {\n if (rejected.length === 0) return \"\";\n if (rejected.length === 1) return rejected[0].message;\n return labels.rejectedMany(rejected.length);\n}\n\n/* ── useFilePicker ───────────────────────────────────────────────────────── */\n\nexport interface UseFilePickerOptions extends FileScreenOptions {\n /** Let one pick deliver several files. Without it a drop of several keeps the first. */\n multiple?: boolean;\n /**\n * Ask a phone for its camera instead of the file chooser: `\"environment\"` is the\n * back camera, `\"user\"` the front. A HINT — desktop browsers ignore it, and Chrome\n * drops it when `multiple` is also set (a camera cannot deliver a list), which is why\n * keksdose's camera input has no `multiple`. Pass one or the other.\n */\n capture?: boolean | \"user\" | \"environment\";\n /** The files that passed, in pick order. Never called with an empty array. */\n onFiles: (files: File[]) => void;\n /** The files that did not, with a translated message each. The refusals are also\n * spoken through a live region, so this is for SHOWING them, not for a11y. */\n onReject?: (rejections: FileRejection[]) => void;\n /** `open()` and `take()` do nothing while set. */\n disabled?: boolean;\n /** Per-instance overrides of the `filePicker` label namespace. */\n labels?: Partial<FilePickerLabels>;\n}\n\nexport interface UseFilePickerReturn {\n /** Open the system picker. Call it from a click handler — browsers only open a file\n * dialog in response to a user gesture. */\n open: () => void;\n /** Screen and deliver files that arrived some other way — a drop, a paste. Honours\n * `multiple` (only the first file without it) and every check. */\n take: (files: ArrayLike<File> | null | undefined) => void;\n /** The hidden input and the live region. Render it once, anywhere — it takes no\n * space and needs no positioned ancestor. */\n element: ReactElement;\n}\n\n/**\n * The headless half of {@link FileButton}: a hidden file input you can open from any\n * control, with the reset, the screening and the announcement built in.\n *\n * ```tsx\n * const picker = useFilePicker({ accept: \".pdf\", onFiles: ([f]) => upload(f) });\n * return <>{picker.element}<DetailTableCard onAdd={picker.open} … /></>;\n * ```\n */\nexport function useFilePicker({\n accept,\n multiple,\n capture,\n maxSize,\n maxFiles,\n isValid,\n invalidMessage,\n onFiles,\n onReject,\n disabled,\n labels: labelsProp,\n}: UseFilePickerOptions): UseFilePickerReturn {\n const inputRef = useRef<HTMLInputElement>(null);\n const labels = useKitLabels(\"filePicker\", DEFAULT_FILE_PICKER_LABELS, labelsProp);\n const fileText = useKitFileLabels();\n // Assertive: a refusal is a failure the user has to hear before they move on, and\n // it is the only thing this region ever says.\n const { announce, regionProps } = useAnnounce({ politeness: \"assertive\" });\n\n const take = (list: ArrayLike<File> | null | undefined) => {\n if (disabled || !list || list.length === 0) return;\n const all = Array.from(list);\n const files = multiple ? all : all.slice(0, 1);\n const { accepted, rejected } = screenFiles(\n files,\n // A single-file picker holds one file by definition; `maxFiles` is a multi-mode\n // cap and would only ever say \"0\" there if a caller passed it by mistake.\n { accept, maxSize, maxFiles: multiple ? maxFiles : undefined, isValid, invalidMessage },\n labels,\n fileText.size,\n );\n if (accepted.length > 0) onFiles(accepted);\n if (rejected.length > 0) {\n onReject?.(rejected);\n announce(summariseRejections(rejected, labels));\n }\n };\n\n const element = (\n <>\n <input\n ref={inputRef}\n type=\"file\"\n accept={accept}\n multiple={multiple}\n capture={capture}\n disabled={disabled}\n // `hidden` (display: none), not `sr-only`: the control a user reaches is the\n // button, and a second, nameless tab stop for the same action is noise. A\n // display:none file input still opens on `.click()` in every current browser —\n // and, unlike `sr-only`, it cannot escape to the initial containing block and\n // stretch the page (see the note in `file-dropzone.tsx`).\n className=\"hidden\"\n tabIndex={-1}\n aria-hidden\n onChange={(e) => {\n // Copy BEFORE the reset: `files` is a live view of the input's value, and\n // clearing the value empties it.\n const picked = Array.from(e.currentTarget.files ?? []);\n e.currentTarget.value = \"\";\n take(picked);\n }}\n />\n <span {...regionProps} />\n </>\n );\n\n return {\n open: () => {\n if (!disabled) inputRef.current?.click();\n },\n take,\n element,\n };\n}\n\n/* ── FileButton ──────────────────────────────────────────────────────────── */\n\ntype ButtonOwnProps = ComponentPropsWithoutRef<typeof Button>;\n\nexport interface FileButtonProps\n extends Omit<UseFilePickerOptions, \"disabled\">,\n // `onDrop` & co. stay the caller's own when `droppable` is off; `type` is fixed to\n // \"button\" (see 2. above) — a file trigger never submits a form.\n Omit<ButtonOwnProps, \"type\" | \"children\" | \"accept\" | \"capture\" | \"multiple\"> {\n /** The button's content — usually an icon and a word. It is the accessible name. */\n children: ReactNode;\n /** Busy: disabled, `aria-busy`, and a spinner before the content — for \"uploading\". */\n pending?: boolean;\n /** Also accept files dropped ON the button (lenkbank's \"drop onto the button\").\n * Off by default: a button that silently takes drops is a surprise on a page that\n * has a real drop target elsewhere. */\n droppable?: boolean;\n}\n\n/**\n * {@link useFilePicker} behind a {@link Button}: `variant` and every other button prop\n * pass through, and the ref is the `<button>` (so `ref.current.click()` opens the\n * picker from elsewhere too).\n *\n * ```tsx\n * <FileButton accept=\"image/*,application/pdf\" capture=\"environment\" variant=\"secondary\"\n * maxSize={10_000_000} onFiles={([f]) => upload(f)} onReject={([r]) => setError(r.message)}>\n * <Camera aria-hidden /> Photograph receipt\n * </FileButton>\n * ```\n */\nexport const FileButton = forwardRef<HTMLButtonElement, FileButtonProps>(function FileButton(\n {\n accept,\n multiple,\n capture,\n maxSize,\n maxFiles,\n isValid,\n invalidMessage,\n onFiles,\n onReject,\n labels,\n pending,\n droppable,\n disabled,\n children,\n className,\n onClick,\n onDragEnter,\n onDragOver,\n onDragLeave,\n onDrop,\n ...rest\n },\n ref,\n) {\n const inert = Boolean(disabled || pending);\n const picker = useFilePicker({\n accept,\n multiple,\n capture,\n maxSize,\n maxFiles,\n isValid,\n invalidMessage,\n onFiles,\n onReject,\n labels,\n disabled: inert,\n });\n const [dragOver, setDragOver] = useState(false);\n\n const hasFiles = (e: DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes(\"Files\");\n // Only when `droppable`: otherwise the caller's own handlers are passed untouched.\n const dropHandlers = droppable\n ? {\n onDragEnter: (e: DragEvent<HTMLButtonElement>) => {\n onDragEnter?.(e);\n if (!hasFiles(e)) return;\n e.preventDefault();\n if (!inert) setDragOver(true);\n },\n onDragOver: (e: DragEvent<HTMLButtonElement>) => {\n onDragOver?.(e);\n if (!hasFiles(e)) return;\n // Always cancel for a file drag, busy or not: an uncancelled drop makes the\n // browser NAVIGATE to the file, which loses the page.\n e.preventDefault();\n e.dataTransfer.dropEffect = inert ? \"none\" : \"copy\";\n },\n onDragLeave: (e: DragEvent<HTMLButtonElement>) => {\n onDragLeave?.(e);\n if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;\n setDragOver(false);\n },\n onDrop: (e: DragEvent<HTMLButtonElement>) => {\n onDrop?.(e);\n if (!hasFiles(e)) return;\n e.preventDefault();\n setDragOver(false);\n picker.take(e.dataTransfer.files);\n },\n }\n : { onDragEnter, onDragOver, onDragLeave, onDrop };\n\n // `Button` is a plain function component; under React 19 `ref` is an ordinary prop\n // and reaches the `<button>` through its `...rest`. Its props type just does not\n // declare it, hence the widening here rather than a second button implementation.\n const refProp = { ref } as { ref?: Ref<HTMLButtonElement> };\n\n return (\n <>\n <Button\n {...rest}\n {...refProp}\n {...dropHandlers}\n type=\"button\"\n disabled={inert}\n aria-busy={pending || undefined}\n data-drag-over={dragOver || undefined}\n className={cn(\n // A live drag gets the focus ring's colour as a ring: \"let go here\", in the\n // same vocabulary the button already uses for \"you are here\".\n dragOver && \"ring-2 ring-[var(--brand)]\",\n className,\n )}\n onClick={(e) => {\n onClick?.(e);\n if (!e.defaultPrevented) picker.open();\n }}\n >\n {/* `label={null}`: the spinner is decoration here — `aria-busy` says the same\n thing on the button, and a spoken \"Loading\" would run into its name. */}\n {pending && <Spinner label={null} className=\"size-4\" />}\n {children}\n </Button>\n {picker.element}\n </>\n );\n});\nFileButton.displayName = \"FileButton\";\n"],"mappings":";AA4PI,mBACE,KADF;AA5PJ,SAAS,YAAY,QAAQ,gBAAgB;AAE7C,SAAS,UAAU;AACnB,SAAS,mBAAmB;AAC5B,SAAS,kBAAkB,oBAAoB;AAC/C,SAAS,QAAQ,eAAe;AAsDzB,MAAM,6BAA+C;AAAA,EAC1D,cAAc,CAAC,SAAS,SAAI,IAAI;AAAA,EAChC,cAAc,CAAC,MAAM,YAAY,SAAI,IAAI,yBAAoB,OAAO;AAAA,EACpE,eAAe,CAAC,MAAM,aACpB,SAAI,IAAI,iCAA4B,QAAQ,IAAI,aAAa,IAAI,SAAS,OAAO;AAAA,EACnF,iBAAiB,CAAC,SAAS,SAAI,IAAI;AAAA,EACnC,cAAc,CAAC,UAAU,GAAG,KAAK;AAAA,EACjC,UAAU,CAAC,OAAO,cAAe,UAAU,IAAI,SAAI,SAAS,oBAAe,GAAG,KAAK;AAAA,EACnF,QAAQ,CAAC,SAAS,gBAAW,IAAI;AAAA,EACjC,UAAU;AAAA,EACV,SAAS,CAAC,SAAS,SAAI,IAAI;AAAA,EAC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;AACd,UAAI,CAAC,SAAS,CAAC,EAAG;AAGlB,QAAE,eAAe;AACjB,QAAE,aAAa,aAAa,QAAQ,SAAS;AAAA,IAC/C;AAAA,IACA,aAAa,CAAC,MAAoC;AAChD,oBAAc,CAAC;AACf,UAAI,EAAE,cAAc,SAAS,EAAE,aAA4B,EAAG;AAC9D,kBAAY,KAAK;AAAA,IACnB;AAAA,IACA,QAAQ,CAAC,MAAoC;AAC3C,eAAS,CAAC;AACV,UAAI,CAAC,SAAS,CAAC,EAAG;AAClB,QAAE,eAAe;AACjB,kBAAY,KAAK;AACjB,aAAO,KAAK,EAAE,aAAa,KAAK;AAAA,IAClC;AAAA,EACF,IACA,EAAE,aAAa,YAAY,aAAa,OAAO;AAKnD,QAAM,UAAU,EAAE,IAAI;AAEtB,SACE,iCACE;AAAA;AAAA,MAAC;AAAA;AAAA,QACE,GAAG;AAAA,QACH,GAAG;AAAA,QACH,GAAG;AAAA,QACJ,MAAK;AAAA,QACL,UAAU;AAAA,QACV,aAAW,WAAW;AAAA,QACtB,kBAAgB,YAAY;AAAA,QAC5B,WAAW;AAAA;AAAA;AAAA,UAGT,YAAY;AAAA,UACZ;AAAA,QACF;AAAA,QACA,SAAS,CAAC,MAAM;AACd,oBAAU,CAAC;AACX,cAAI,CAAC,EAAE,iBAAkB,QAAO,KAAK;AAAA,QACvC;AAAA,QAIC;AAAA,qBAAW,oBAAC,WAAQ,OAAO,MAAM,WAAU,UAAS;AAAA,UACpD;AAAA;AAAA;AAAA,IACH;AAAA,IACC,OAAO;AAAA,KACV;AAEJ,CAAC;AACD,WAAW,cAAc;","names":["FileButton"]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/file-button.tsx"],"sourcesContent":["import { forwardRef, useRef, useState } from \"react\";\nimport type { ComponentPropsWithoutRef, DragEvent, ReactElement, ReactNode, Ref } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { useAnnounce } from \"../hooks/use-announce\";\nimport { useKitFileLabels, useKitLabels } from \"../i18n/kit-labels\";\nimport { Button, Spinner } from \"./ui\";\n\n/**\n * A button that opens the file picker — the shape all three apps kept writing by hand\n * as a `<Button>` plus a hidden `<input type=\"file\">` plus a ref between them (seven\n * copies in keksdose, two each in kastlan and lenkbank).\n *\n * Every copy had to remember the same four things, and each one forgot at least one:\n *\n * 1. **Reset the input after every pick.** A file input fires `change` only when its\n * value CHANGES, so picking the same file twice in a row — the retry after a failed\n * upload, the second photo of the same receipt — did nothing at all, which reads as\n * a broken button. `value = \"\"` after each pick; always, not per call site.\n * 2. **`type=\"button\"`.** `<Button>` does not set it, and inside a form a bare button\n * submits the form before the picker opens.\n * 3. **Check the file.** `accept` filters the DIALOG, not the result: the dialog's\n * \"All files\" switch, a drop, and a mobile share sheet all hand over whatever the\n * user chose. So `accept` is re-checked here, along with `maxSize`, `maxFiles` and\n * an optional `isValid`.\n * 4. **Say no without a toast.** A rejection is reported through `onReject`, with a\n * translated message per file, and spoken through a live region — the kit does not\n * decide how an app surfaces errors (keksdose's proposal §1 asked for exactly that).\n *\n * The part that is not a button — the hidden input, the check, the announcement — is\n * {@link useFilePicker}, for the case where the thing that opens the picker is someone\n * else's control (a card's \"Add\" action, a menu item, a second button for the camera).\n */\n\n/* ── Labels ──────────────────────────────────────────────────────────────── */\n\n/** Every string the file pickers ({@link FileButton}, `FileDropzone`) render or speak.\n * Messages are functions of the file name so a translation can put it anywhere. */\nexport interface FilePickerLabels {\n /** The file's type is not in `accept`. */\n rejectedType: (name: string) => string;\n /** The file is larger than `maxSize`; `maxSize` arrives formatted (\"5 MB\"). */\n rejectedSize: (name: string, maxSize: string) => string;\n /** The file was one too many for `maxFiles`. */\n rejectedCount: (name: string, maxFiles: number) => string;\n /** `isValid` said no and the caller gave no `invalidMessage`. */\n rejectedInvalid: (name: string) => string;\n /** Spoken instead of the per-file message when more than one file was refused. */\n rejectedMany: (count: number) => string;\n /** Spoken after a pick the component itself echoes (the dropzone). */\n selected: (count: number, firstName: string) => string;\n /** The dropzone's remove button for one file. */\n remove: (name: string) => string;\n /** The dropzone's remove-everything button in `multiple` mode. */\n clearAll: string;\n /** Spoken after a remove / clear, since the button that was pressed is gone. */\n removed: (name: string) => string;\n cleared: string;\n}\n\nexport const DEFAULT_FILE_PICKER_LABELS: FilePickerLabels = {\n rejectedType: (name) => `“${name}” is not a supported file type`,\n rejectedSize: (name, maxSize) => `“${name}” is larger than ${maxSize}`,\n rejectedCount: (name, maxFiles) =>\n `“${name}” was not added: at most ${maxFiles} ${maxFiles === 1 ? \"file\" : \"files\"}`,\n rejectedInvalid: (name) => `“${name}” cannot be used here`,\n rejectedMany: (count) => `${count} files were not added`,\n selected: (count, firstName) => (count === 1 ? `“${firstName}” selected` : `${count} files selected`),\n remove: (name) => `Remove “${name}”`,\n clearAll: \"Remove all files\",\n removed: (name) => `“${name}” removed`,\n cleared: \"All files removed\",\n};\n\n/* ── Screening ───────────────────────────────────────────────────────────── */\n\nexport type FileRejectionReason = \"type\" | \"size\" | \"count\" | \"invalid\";\n\n/** One file the picker refused, and why. `message` is already translated (see\n * {@link FilePickerLabels}, or the caller's `invalidMessage`), so a host that just\n * wants to show it can render `rejections[0].message` as is. */\nexport interface FileRejection {\n file: File;\n reason: FileRejectionReason;\n message: string;\n}\n\n/**\n * Does `file` satisfy an `accept` string, the way the browser's dialog reads it?\n * Comma-separated tokens: `.ext` (case-insensitive suffix of the name), `type/*`\n * (a MIME family) or an exact MIME type. An empty or absent `accept` takes anything.\n *\n * A file with no `type` — common for `.step`, `.dat`, anything the OS has no MIME\n * mapping for — can only match by extension, which is why lenkbank lists `.stp` AND\n * `model/step`: that is how `accept` has to be written for the dialog anyway.\n */\nexport function matchesAccept(file: File, accept: string | undefined): boolean {\n const tokens = (accept ?? \"\")\n .split(\",\")\n .map((t) => t.trim().toLowerCase())\n .filter(Boolean);\n if (tokens.length === 0) return true;\n const name = file.name.toLowerCase();\n // An EMPTY type is the browser saying \"I don't know\", not \"it's something else\": HEIC\n // photos on Windows without the codec arrive with `type === \"\"`. Refusing them\n // (0.6.0) refused iPhone photos the picker itself had just offered (keksdose). So a\n // missing type is inferred from the extension where that is unambiguous, and a file\n // whose type cannot be known at all is given the benefit of the doubt — nothing here\n // proves it does not match, and the server validates what it receives anyway.\n const type = (file.type || typeFromExtension(name) || \"\").toLowerCase();\n if (!type && !tokens.every((t) => t.startsWith(\".\"))) return true;\n return tokens.some((token) => {\n if (token.startsWith(\".\")) return name.endsWith(token);\n if (!type) return false;\n if (token.endsWith(\"/*\")) return type.startsWith(token.slice(0, -1));\n return type === token;\n });\n}\n\n/** MIME types for the extensions a browser most often leaves untyped. */\nconst EXTENSION_TYPES: Record<string, string> = {\n heic: \"image/heic\",\n heif: \"image/heif\",\n avif: \"image/avif\",\n webp: \"image/webp\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n gif: \"image/gif\",\n pdf: \"application/pdf\",\n csv: \"text/csv\",\n txt: \"text/plain\",\n};\n\nfunction typeFromExtension(name: string): string | undefined {\n const dot = name.lastIndexOf(\".\");\n return dot === -1 ? undefined : EXTENSION_TYPES[name.slice(dot + 1)];\n}\n\n/** What the pickers screen a pick with. All optional; nothing set accepts everything. */\nexport interface FileScreenOptions {\n accept?: string;\n /** Bytes. Larger files are refused with reason `\"size\"`. */\n maxSize?: number;\n /** How many files one pick may deliver. The rest are refused with reason `\"count\"`\n * — first come, first kept. For a running cap (\"at most 5 attachments\") pass what\n * is LEFT: `maxFiles={5 - attachments.length}`. */\n maxFiles?: number;\n /** The caller's own check, after `accept` and `maxSize`. */\n isValid?: (file: File) => boolean;\n /** The message for an `isValid` refusal; `labels.rejectedInvalid` otherwise. */\n invalidMessage?: string;\n}\n\n/** @internal Split a pick into the files that pass and the ones that do not. */\nexport function screenFiles(\n files: readonly File[],\n opts: FileScreenOptions,\n labels: FilePickerLabels,\n formatSize: (bytes: number) => string,\n): { accepted: File[]; rejected: FileRejection[] } {\n const accepted: File[] = [];\n const rejected: FileRejection[] = [];\n for (const file of files) {\n let reason: FileRejectionReason | null = null;\n if (!matchesAccept(file, opts.accept)) reason = \"type\";\n else if (opts.maxSize !== undefined && file.size > opts.maxSize) reason = \"size\";\n else if (opts.isValid && !opts.isValid(file)) reason = \"invalid\";\n // Count last, and only against files that passed everything else: a refused\n // file should not use up one of the slots a good one could have had.\n else if (opts.maxFiles !== undefined && accepted.length >= opts.maxFiles) reason = \"count\";\n if (reason === null) {\n accepted.push(file);\n continue;\n }\n const message =\n reason === \"type\"\n ? labels.rejectedType(file.name)\n : reason === \"size\"\n ? labels.rejectedSize(file.name, formatSize(opts.maxSize ?? 0))\n : reason === \"count\"\n ? labels.rejectedCount(file.name, Math.max(0, opts.maxFiles ?? 0))\n : (opts.invalidMessage ?? labels.rejectedInvalid(file.name));\n rejected.push({ file, reason, message });\n }\n return { accepted, rejected };\n}\n\n/** One sentence for a whole batch of refusals: the file's own message for one, a\n * count for several — reading out five sentences in a row helps nobody. */\nexport function summariseRejections(rejected: readonly FileRejection[], labels: FilePickerLabels): string {\n if (rejected.length === 0) return \"\";\n if (rejected.length === 1) return rejected[0].message;\n return labels.rejectedMany(rejected.length);\n}\n\n/* ── useFilePicker ───────────────────────────────────────────────────────── */\n\nexport interface UseFilePickerOptions extends FileScreenOptions {\n /** Let one pick deliver several files. Without it a drop of several keeps the first. */\n multiple?: boolean;\n /**\n * Ask a phone for its camera instead of the file chooser: `\"environment\"` is the\n * back camera, `\"user\"` the front. A HINT — desktop browsers ignore it, and Chrome\n * drops it when `multiple` is also set (a camera cannot deliver a list), which is why\n * keksdose's camera input has no `multiple`. Pass one or the other.\n */\n capture?: boolean | \"user\" | \"environment\";\n /** The files that passed, in pick order. Never called with an empty array. */\n onFiles: (files: File[]) => void;\n /** The files that did not, with a translated message each. The refusals are also\n * spoken through a live region, so this is for SHOWING them, not for a11y. */\n onReject?: (rejections: FileRejection[]) => void;\n /** `open()` and `take()` do nothing while set. */\n disabled?: boolean;\n /** Per-instance overrides of the `filePicker` label namespace. */\n labels?: Partial<FilePickerLabels>;\n}\n\nexport interface UseFilePickerReturn {\n /** Open the system picker. Call it from a click handler — browsers only open a file\n * dialog in response to a user gesture. */\n open: () => void;\n /** Screen and deliver files that arrived some other way — a drop, a paste. Honours\n * `multiple` (only the first file without it) and every check. */\n take: (files: ArrayLike<File> | null | undefined) => void;\n /** The hidden input and the live region. Render it once, anywhere — it takes no\n * space and needs no positioned ancestor. */\n element: ReactElement;\n}\n\n/**\n * The headless half of {@link FileButton}: a hidden file input you can open from any\n * control, with the reset, the screening and the announcement built in.\n *\n * ```tsx\n * const picker = useFilePicker({ accept: \".pdf\", onFiles: ([f]) => upload(f) });\n * return <>{picker.element}<DetailTableCard onAdd={picker.open} … /></>;\n * ```\n */\nexport function useFilePicker({\n accept,\n multiple,\n capture,\n maxSize,\n maxFiles,\n isValid,\n invalidMessage,\n onFiles,\n onReject,\n disabled,\n labels: labelsProp,\n}: UseFilePickerOptions): UseFilePickerReturn {\n const inputRef = useRef<HTMLInputElement>(null);\n const labels = useKitLabels(\"filePicker\", DEFAULT_FILE_PICKER_LABELS, labelsProp);\n const fileText = useKitFileLabels();\n // Assertive: a refusal is a failure the user has to hear before they move on, and\n // it is the only thing this region ever says.\n const { announce, regionProps } = useAnnounce({ politeness: \"assertive\" });\n\n const take = (list: ArrayLike<File> | null | undefined) => {\n if (disabled || !list || list.length === 0) return;\n const all = Array.from(list);\n const files = multiple ? all : all.slice(0, 1);\n const { accepted, rejected } = screenFiles(\n files,\n // A single-file picker holds one file by definition; `maxFiles` is a multi-mode\n // cap and would only ever say \"0\" there if a caller passed it by mistake.\n { accept, maxSize, maxFiles: multiple ? maxFiles : undefined, isValid, invalidMessage },\n labels,\n fileText.size,\n );\n if (accepted.length > 0) onFiles(accepted);\n if (rejected.length > 0) {\n onReject?.(rejected);\n announce(summariseRejections(rejected, labels));\n }\n };\n\n const element = (\n <>\n <input\n ref={inputRef}\n type=\"file\"\n accept={accept}\n multiple={multiple}\n capture={capture}\n disabled={disabled}\n // `hidden` (display: none), not `sr-only`: the control a user reaches is the\n // button, and a second, nameless tab stop for the same action is noise. A\n // display:none file input still opens on `.click()` in every current browser —\n // and, unlike `sr-only`, it cannot escape to the initial containing block and\n // stretch the page (see the note in `file-dropzone.tsx`).\n className=\"hidden\"\n tabIndex={-1}\n aria-hidden\n onChange={(e) => {\n // Copy BEFORE the reset: `files` is a live view of the input's value, and\n // clearing the value empties it.\n const picked = Array.from(e.currentTarget.files ?? []);\n e.currentTarget.value = \"\";\n take(picked);\n }}\n />\n <span {...regionProps} />\n </>\n );\n\n return {\n open: () => {\n if (!disabled) inputRef.current?.click();\n },\n take,\n element,\n };\n}\n\n/* ── FileButton ──────────────────────────────────────────────────────────── */\n\ntype ButtonOwnProps = ComponentPropsWithoutRef<typeof Button>;\n\nexport interface FileButtonProps\n extends Omit<UseFilePickerOptions, \"disabled\">,\n // `onDrop` & co. stay the caller's own when `droppable` is off; `type` is fixed to\n // \"button\" (see 2. above) — a file trigger never submits a form.\n Omit<ButtonOwnProps, \"type\" | \"children\" | \"accept\" | \"capture\" | \"multiple\"> {\n /** The button's content — usually an icon and a word. It is the accessible name. */\n children: ReactNode;\n /** Busy: disabled, `aria-busy`, and a spinner before the content — for \"uploading\". */\n pending?: boolean;\n /** Also accept files dropped ON the button (lenkbank's \"drop onto the button\").\n * Off by default: a button that silently takes drops is a surprise on a page that\n * has a real drop target elsewhere. */\n droppable?: boolean;\n}\n\n/**\n * {@link useFilePicker} behind a {@link Button}: `variant` and every other button prop\n * pass through, and the ref is the `<button>` (so `ref.current.click()` opens the\n * picker from elsewhere too).\n *\n * ```tsx\n * <FileButton accept=\"image/*,application/pdf\" capture=\"environment\" variant=\"secondary\"\n * maxSize={10_000_000} onFiles={([f]) => upload(f)} onReject={([r]) => setError(r.message)}>\n * <Camera aria-hidden /> Photograph receipt\n * </FileButton>\n * ```\n */\nexport const FileButton = forwardRef<HTMLButtonElement, FileButtonProps>(function FileButton(\n {\n accept,\n multiple,\n capture,\n maxSize,\n maxFiles,\n isValid,\n invalidMessage,\n onFiles,\n onReject,\n labels,\n pending,\n droppable,\n disabled,\n children,\n className,\n onClick,\n onDragEnter,\n onDragOver,\n onDragLeave,\n onDrop,\n ...rest\n },\n ref,\n) {\n const inert = Boolean(disabled || pending);\n const picker = useFilePicker({\n accept,\n multiple,\n capture,\n maxSize,\n maxFiles,\n isValid,\n invalidMessage,\n onFiles,\n onReject,\n labels,\n disabled: inert,\n });\n const [dragOver, setDragOver] = useState(false);\n\n const hasFiles = (e: DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes(\"Files\");\n // Only when `droppable`: otherwise the caller's own handlers are passed untouched.\n const dropHandlers = droppable\n ? {\n onDragEnter: (e: DragEvent<HTMLButtonElement>) => {\n onDragEnter?.(e);\n if (!hasFiles(e)) return;\n e.preventDefault();\n if (!inert) setDragOver(true);\n },\n onDragOver: (e: DragEvent<HTMLButtonElement>) => {\n onDragOver?.(e);\n if (!hasFiles(e)) return;\n // Always cancel for a file drag, busy or not: an uncancelled drop makes the\n // browser NAVIGATE to the file, which loses the page.\n e.preventDefault();\n e.dataTransfer.dropEffect = inert ? \"none\" : \"copy\";\n },\n onDragLeave: (e: DragEvent<HTMLButtonElement>) => {\n onDragLeave?.(e);\n if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;\n setDragOver(false);\n },\n onDrop: (e: DragEvent<HTMLButtonElement>) => {\n onDrop?.(e);\n if (!hasFiles(e)) return;\n e.preventDefault();\n setDragOver(false);\n picker.take(e.dataTransfer.files);\n },\n }\n : { onDragEnter, onDragOver, onDragLeave, onDrop };\n\n // `Button` is a plain function component; under React 19 `ref` is an ordinary prop\n // and reaches the `<button>` through its `...rest`. Its props type just does not\n // declare it, hence the widening here rather than a second button implementation.\n const refProp = { ref } as { ref?: Ref<HTMLButtonElement> };\n\n return (\n <>\n <Button\n {...rest}\n {...refProp}\n {...dropHandlers}\n type=\"button\"\n disabled={inert}\n aria-busy={pending || undefined}\n data-drag-over={dragOver || undefined}\n className={cn(\n // A live drag gets the focus ring's colour as a ring: \"let go here\", in the\n // same vocabulary the button already uses for \"you are here\".\n dragOver && \"ring-2 ring-[var(--brand)]\",\n className,\n )}\n onClick={(e) => {\n onClick?.(e);\n if (!e.defaultPrevented) picker.open();\n }}\n >\n {/* `label={null}`: the spinner is decoration here — `aria-busy` says the same\n thing on the button, and a spoken \"Loading\" would run into its name. */}\n {pending && <Spinner label={null} className=\"size-4\" />}\n {children}\n </Button>\n {picker.element}\n </>\n );\n});\nFileButton.displayName = \"FileButton\";\n"],"mappings":";AAuRI,mBACE,KADF;AAvRJ,SAAS,YAAY,QAAQ,gBAAgB;AAE7C,SAAS,UAAU;AACnB,SAAS,mBAAmB;AAC5B,SAAS,kBAAkB,oBAAoB;AAC/C,SAAS,QAAQ,eAAe;AAsDzB,MAAM,6BAA+C;AAAA,EAC1D,cAAc,CAAC,SAAS,SAAI,IAAI;AAAA,EAChC,cAAc,CAAC,MAAM,YAAY,SAAI,IAAI,yBAAoB,OAAO;AAAA,EACpE,eAAe,CAAC,MAAM,aACpB,SAAI,IAAI,iCAA4B,QAAQ,IAAI,aAAa,IAAI,SAAS,OAAO;AAAA,EACnF,iBAAiB,CAAC,SAAS,SAAI,IAAI;AAAA,EACnC,cAAc,CAAC,UAAU,GAAG,KAAK;AAAA,EACjC,UAAU,CAAC,OAAO,cAAe,UAAU,IAAI,SAAI,SAAS,oBAAe,GAAG,KAAK;AAAA,EACnF,QAAQ,CAAC,SAAS,gBAAW,IAAI;AAAA,EACjC,UAAU;AAAA,EACV,SAAS,CAAC,SAAS,SAAI,IAAI;AAAA,EAC3B,SAAS;AACX;AAwBO,SAAS,cAAc,MAAY,QAAqC;AAC7E,QAAM,UAAU,UAAU,IACvB,MAAM,GAAG,EACT,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,YAAY,CAAC,EACjC,OAAO,OAAO;AACjB,MAAI,OAAO,WAAW,EAAG,QAAO;AAChC,QAAM,OAAO,KAAK,KAAK,YAAY;AAOnC,Q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
|
@@ -47,6 +47,15 @@ interface SwitchProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "type"
|
|
|
47
47
|
/** Classes for the `<input>` (the track). `className` styles the outermost element:
|
|
48
48
|
* the row when there is a label, the switch's own wrapper when there is not. */
|
|
49
49
|
inputClassName?: string;
|
|
50
|
+
/**
|
|
51
|
+
* Must be ticked to submit — a consent, an acceptance before paying. Reaches the
|
|
52
|
+
* `<input>` as the native `required` (so a `<form>` refuses to submit without it and a
|
|
53
|
+
* screen reader announces "required"), and draws the kit's required mark after the
|
|
54
|
+
* label, the same `aria-hidden` star as {@link Label}'s: the word is announced from
|
|
55
|
+
* the control, so a star inside the name would only be read out as noise. Write the
|
|
56
|
+
* label WITHOUT a literal "*". No mark without a label.
|
|
57
|
+
*/
|
|
58
|
+
required?: boolean;
|
|
50
59
|
}
|
|
51
60
|
/**
|
|
52
61
|
* A native checkbox drawn as a track and thumb, announced as a switch.
|
|
@@ -22,6 +22,7 @@ const Switch = forwardRef(function Switch2({
|
|
|
22
22
|
inputClassName,
|
|
23
23
|
id,
|
|
24
24
|
disabled,
|
|
25
|
+
required,
|
|
25
26
|
...rest
|
|
26
27
|
}, ref) {
|
|
27
28
|
const generated = useId();
|
|
@@ -37,6 +38,7 @@ const Switch = forwardRef(function Switch2({
|
|
|
37
38
|
ref,
|
|
38
39
|
id: bare ? id : inputId,
|
|
39
40
|
disabled,
|
|
41
|
+
required,
|
|
40
42
|
...rest,
|
|
41
43
|
type: "checkbox",
|
|
42
44
|
role: "switch",
|
|
@@ -53,7 +55,7 @@ const Switch = forwardRef(function Switch2({
|
|
|
53
55
|
if (bare) return control;
|
|
54
56
|
const cell = /* @__PURE__ */ jsx("span", { className: "flex h-5 shrink-0 items-center", children: control });
|
|
55
57
|
const words = /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
|
|
56
|
-
label !== void 0 && /* @__PURE__ */
|
|
58
|
+
label !== void 0 && /* @__PURE__ */ jsxs(
|
|
57
59
|
"label",
|
|
58
60
|
{
|
|
59
61
|
htmlFor: inputId,
|
|
@@ -61,7 +63,10 @@ const Switch = forwardRef(function Switch2({
|
|
|
61
63
|
"block text-sm leading-5 text-[var(--text-primary)]",
|
|
62
64
|
disabled ? "cursor-not-allowed" : "cursor-pointer select-none"
|
|
63
65
|
),
|
|
64
|
-
children:
|
|
66
|
+
children: [
|
|
67
|
+
label,
|
|
68
|
+
required && /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: "ms-0.5 text-[var(--danger)]", children: "*" })
|
|
69
|
+
]
|
|
65
70
|
}
|
|
66
71
|
),
|
|
67
72
|
showDescription && /* @__PURE__ */ jsx("span", { id: descriptionId, className: "mt-0.5 block text-xs text-[var(--text-muted)]", children: description })
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/switch.tsx"],"sourcesContent":["import { forwardRef, useId } from \"react\";\nimport type { ChangeEvent, InputHTMLAttributes, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { hasMessage, mergeDescribedBy } from \"./choice-parts\";\n\n/**\n * An on/off switch that is still `<input type=\"checkbox\">`, with `role=\"switch\"`.\n *\n * Kastlan's was a Radix `<button>`; this keeps the native element for the reasons\n * `Checkbox` gives (form submission, `required`, reset, `<label for>`), and adds the\n * one thing a checkbox is not: `role=\"switch\"`, which screen readers announce as\n * \"on/off\" rather than \"checked/not checked\". Use it for a setting that takes effect\n * the moment it is flipped; a choice that waits for a Save button is a checkbox.\n */\n\n/** Geometry per size. The thumb sits `2px` in from each end of the track, so its\n * checked offset is `track width − thumb − 2px`. `start-*`, never `left-*` or a\n * `translate-x`: an inline-start offset follows the writing direction, so in a\n * right-to-left form the thumb travels right-to-left with no `rtl:` override to\n * keep in step. */\nconst SIZES = {\n // 28×16 track, 12px thumb: the dense setting rows in Kastlan's tables.\n sm: { track: \"h-4 w-7\", thumb: \"size-3 peer-checked:start-[14px]\" },\n // 36×20 track, 16px thumb.\n md: { track: \"h-5 w-9\", thumb: \"size-4 peer-checked:start-[18px]\" },\n} as const;\n\nexport type SwitchSize = keyof typeof SIZES;\n\n// The track IS the input — `appearance-none` and a pill — so its box is the pointer\n// target and the focus ring lands around the whole control, not the thumb alone.\n//\n// Unchecked it takes `--border-strong`, not `--border`: a hairline-coloured track on\n// a surface-coloured card is a switch you have to look for. Checked it takes the\n// brand fill, which is the only difference in COLOUR; the thumb's position is the\n// difference in SHAPE, so the state never rests on colour alone.\nconst TRACK =\n \"peer block shrink-0 cursor-pointer appearance-none rounded-full bg-[var(--border-strong)] transition-colors \" +\n \"checked:bg-[var(--brand)] \" +\n \"focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--bg-surface)] \" +\n \"disabled:cursor-not-allowed\";\n\n// The thumb, laid over the input and ignoring the pointer so every click still reaches\n// the input. It swaps to `--brand-contrast` on the brand fill: the surface colour would\n// match the fill in some presets, and the contrast token is the one guaranteed to read\n// against --brand.\nconst THUMB =\n \"pointer-events-none absolute start-0.5 top-1/2 -translate-y-1/2 rounded-full bg-[var(--bg-surface)] shadow-sm \" +\n \"transition-[inset-inline-start,background-color] motion-reduce:transition-none \" +\n \"peer-checked:bg-[var(--brand-contrast)]\";\n\nexport interface SwitchProps extends Omit<InputHTMLAttributes<HTMLInputElement>, \"type\" | \"size\" | \"role\"> {\n /** `\"md\"` (36×20, default) or `\"sm\"` (28×16) — Kastlan's `default` and `sm`. */\n size?: SwitchSize;\n /** The words beside the switch, as a `<label for>` — see {@link Checkbox}'s\n * `label` for why it does not wrap the input. Without it, give the switch an\n * `aria-label`. */\n label?: ReactNode;\n /** Secondary text under the label, attached with `aria-describedby` (merged with\n * any the caller passed). */\n description?: ReactNode;\n /** Which end of the row the switch sits at when there is a label. `\"end\"` (the\n * default) is the settings-list shape Kastlan's profile page uses — the words at\n * the start, the control at the far end; `\"start\"` puts it before the words, like\n * a checkbox. Logical, so it follows the writing direction. */\n switchPosition?: \"start\" | \"end\";\n /** The new state as a boolean — Radix's `onCheckedChange`, so Kastlan's call sites\n * move without unwrapping the event. Fires alongside `onChange`. */\n onCheckedChange?: (checked: boolean) => void;\n /** Classes for the `<input>` (the track). `className` styles the outermost element:\n * the row when there is a label, the switch's own wrapper when there is not. */\n inputClassName?: string;\n}\n\n/**\n * A native checkbox drawn as a track and thumb, announced as a switch.\n *\n * Every other prop reaches the `<input>`, so it works controlled (`checked` +\n * `onChange`/`onCheckedChange`), uncontrolled (`defaultChecked`) and in a plain\n * `<form>` (`name`, `value`).\n */\nexport const Switch = forwardRef<HTMLInputElement, SwitchProps>(function Switch(\n {\n size = \"md\",\n label,\n description,\n switchPosition = \"end\",\n onCheckedChange,\n onChange,\n className,\n inputClassName,\n id,\n disabled,\n ...rest\n },\n ref,\n) {\n const generated = useId();\n const inputId = id ?? generated;\n const descriptionId = `${inputId}-description`;\n const showDescription = hasMessage(description);\n const bare = label === undefined && !showDescription;\n const geometry = SIZES[size];\n\n const control = (\n <span className={cn(\"relative inline-flex shrink-0\", bare && className)}>\n <input\n ref={ref}\n id={bare ? id : inputId}\n disabled={disabled}\n {...rest}\n // After the spread: a caller's props object must not be able to turn this\n // back into a plain checkbox, or into a text field.\n type=\"checkbox\"\n role=\"switch\"\n aria-describedby={mergeDescribedBy(rest[\"aria-describedby\"], showDescription && descriptionId)}\n onChange={(e: ChangeEvent<HTMLInputElement>) => {\n onChange?.(e);\n onCheckedChange?.(e.target.checked);\n }}\n className={cn(TRACK, geometry.track, inputClassName)}\n />\n <span aria-hidden className={cn(THUMB, geometry.thumb)} />\n </span>\n );\n\n if (bare) return control;\n\n // The switch's cell is one label line tall (text-sm, 20px) so it centres on the\n // FIRST line of a label that wraps, and a description underneath does not drag it\n // down to the middle of the paragraph.\n const cell = <span className=\"flex h-5 shrink-0 items-center\">{control}</span>;\n const words = (\n <span className=\"min-w-0 flex-1\">\n {label !== undefined && (\n <label\n htmlFor={inputId}\n className={cn(\n \"block text-sm leading-5 text-[var(--text-primary)]\",\n disabled ? \"cursor-not-allowed\" : \"cursor-pointer select-none\",\n )}\n >\n {label}\n </label>\n )}\n {showDescription && (\n <span id={descriptionId} className=\"mt-0.5 block text-xs text-[var(--text-muted)]\">\n {description}\n </span>\n )}\n </span>\n );\n\n return (\n <div className={cn(\"flex items-start gap-3\", disabled && \"opacity-60\", className)}>\n {switchPosition === \"end\" ? (\n <>\n {words}\n {cell}\n </>\n ) : (\n <>\n {cell}\n {words}\n </>\n )}\n </div>\n );\n});\nSwitch.displayName = \"Switch\";\n"],"mappings":";
|
|
1
|
+
{"version":3,"sources":["../../src/components/switch.tsx"],"sourcesContent":["import { forwardRef, useId } from \"react\";\nimport type { ChangeEvent, InputHTMLAttributes, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { hasMessage, mergeDescribedBy } from \"./choice-parts\";\n\n/**\n * An on/off switch that is still `<input type=\"checkbox\">`, with `role=\"switch\"`.\n *\n * Kastlan's was a Radix `<button>`; this keeps the native element for the reasons\n * `Checkbox` gives (form submission, `required`, reset, `<label for>`), and adds the\n * one thing a checkbox is not: `role=\"switch\"`, which screen readers announce as\n * \"on/off\" rather than \"checked/not checked\". Use it for a setting that takes effect\n * the moment it is flipped; a choice that waits for a Save button is a checkbox.\n */\n\n/** Geometry per size. The thumb sits `2px` in from each end of the track, so its\n * checked offset is `track width − thumb − 2px`. `start-*`, never `left-*` or a\n * `translate-x`: an inline-start offset follows the writing direction, so in a\n * right-to-left form the thumb travels right-to-left with no `rtl:` override to\n * keep in step. */\nconst SIZES = {\n // 28×16 track, 12px thumb: the dense setting rows in Kastlan's tables.\n sm: { track: \"h-4 w-7\", thumb: \"size-3 peer-checked:start-[14px]\" },\n // 36×20 track, 16px thumb.\n md: { track: \"h-5 w-9\", thumb: \"size-4 peer-checked:start-[18px]\" },\n} as const;\n\nexport type SwitchSize = keyof typeof SIZES;\n\n// The track IS the input — `appearance-none` and a pill — so its box is the pointer\n// target and the focus ring lands around the whole control, not the thumb alone.\n//\n// Unchecked it takes `--border-strong`, not `--border`: a hairline-coloured track on\n// a surface-coloured card is a switch you have to look for. Checked it takes the\n// brand fill, which is the only difference in COLOUR; the thumb's position is the\n// difference in SHAPE, so the state never rests on colour alone.\nconst TRACK =\n \"peer block shrink-0 cursor-pointer appearance-none rounded-full bg-[var(--border-strong)] transition-colors \" +\n \"checked:bg-[var(--brand)] \" +\n \"focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--bg-surface)] \" +\n \"disabled:cursor-not-allowed\";\n\n// The thumb, laid over the input and ignoring the pointer so every click still reaches\n// the input. It swaps to `--brand-contrast` on the brand fill: the surface colour would\n// match the fill in some presets, and the contrast token is the one guaranteed to read\n// against --brand.\nconst THUMB =\n \"pointer-events-none absolute start-0.5 top-1/2 -translate-y-1/2 rounded-full bg-[var(--bg-surface)] shadow-sm \" +\n \"transition-[inset-inline-start,background-color] motion-reduce:transition-none \" +\n \"peer-checked:bg-[var(--brand-contrast)]\";\n\nexport interface SwitchProps extends Omit<InputHTMLAttributes<HTMLInputElement>, \"type\" | \"size\" | \"role\"> {\n /** `\"md\"` (36×20, default) or `\"sm\"` (28×16) — Kastlan's `default` and `sm`. */\n size?: SwitchSize;\n /** The words beside the switch, as a `<label for>` — see {@link Checkbox}'s\n * `label` for why it does not wrap the input. Without it, give the switch an\n * `aria-label`. */\n label?: ReactNode;\n /** Secondary text under the label, attached with `aria-describedby` (merged with\n * any the caller passed). */\n description?: ReactNode;\n /** Which end of the row the switch sits at when there is a label. `\"end\"` (the\n * default) is the settings-list shape Kastlan's profile page uses — the words at\n * the start, the control at the far end; `\"start\"` puts it before the words, like\n * a checkbox. Logical, so it follows the writing direction. */\n switchPosition?: \"start\" | \"end\";\n /** The new state as a boolean — Radix's `onCheckedChange`, so Kastlan's call sites\n * move without unwrapping the event. Fires alongside `onChange`. */\n onCheckedChange?: (checked: boolean) => void;\n /** Classes for the `<input>` (the track). `className` styles the outermost element:\n * the row when there is a label, the switch's own wrapper when there is not. */\n inputClassName?: string;\n /**\n * Must be ticked to submit — a consent, an acceptance before paying. Reaches the\n * `<input>` as the native `required` (so a `<form>` refuses to submit without it and a\n * screen reader announces \"required\"), and draws the kit's required mark after the\n * label, the same `aria-hidden` star as {@link Label}'s: the word is announced from\n * the control, so a star inside the name would only be read out as noise. Write the\n * label WITHOUT a literal \"*\". No mark without a label.\n */\n required?: boolean;\n}\n\n/**\n * A native checkbox drawn as a track and thumb, announced as a switch.\n *\n * Every other prop reaches the `<input>`, so it works controlled (`checked` +\n * `onChange`/`onCheckedChange`), uncontrolled (`defaultChecked`) and in a plain\n * `<form>` (`name`, `value`).\n */\nexport const Switch = forwardRef<HTMLInputElement, SwitchProps>(function Switch(\n {\n size = \"md\",\n label,\n description,\n switchPosition = \"end\",\n onCheckedChange,\n onChange,\n className,\n inputClassName,\n id,\n disabled,\n required,\n ...rest\n },\n ref,\n) {\n const generated = useId();\n const inputId = id ?? generated;\n const descriptionId = `${inputId}-description`;\n const showDescription = hasMessage(description);\n const bare = label === undefined && !showDescription;\n const geometry = SIZES[size];\n\n const control = (\n <span className={cn(\"relative inline-flex shrink-0\", bare && className)}>\n <input\n ref={ref}\n id={bare ? id : inputId}\n disabled={disabled}\n required={required}\n {...rest}\n // After the spread: a caller's props object must not be able to turn this\n // back into a plain checkbox, or into a text field.\n type=\"checkbox\"\n role=\"switch\"\n aria-describedby={mergeDescribedBy(rest[\"aria-describedby\"], showDescription && descriptionId)}\n onChange={(e: ChangeEvent<HTMLInputElement>) => {\n onChange?.(e);\n onCheckedChange?.(e.target.checked);\n }}\n className={cn(TRACK, geometry.track, inputClassName)}\n />\n <span aria-hidden className={cn(THUMB, geometry.thumb)} />\n </span>\n );\n\n if (bare) return control;\n\n // The switch's cell is one label line tall (text-sm, 20px) so it centres on the\n // FIRST line of a label that wraps, and a description underneath does not drag it\n // down to the middle of the paragraph.\n const cell = <span className=\"flex h-5 shrink-0 items-center\">{control}</span>;\n const words = (\n <span className=\"min-w-0 flex-1\">\n {label !== undefined && (\n <label\n htmlFor={inputId}\n className={cn(\n \"block text-sm leading-5 text-[var(--text-primary)]\",\n disabled ? \"cursor-not-allowed\" : \"cursor-pointer select-none\",\n )}\n >\n {label}\n {required && (\n <span aria-hidden className=\"ms-0.5 text-[var(--danger)]\">\n *\n </span>\n )}\n </label>\n )}\n {showDescription && (\n <span id={descriptionId} className=\"mt-0.5 block text-xs text-[var(--text-muted)]\">\n {description}\n </span>\n )}\n </span>\n );\n\n return (\n <div className={cn(\"flex items-start gap-3\", disabled && \"opacity-60\", className)}>\n {switchPosition === \"end\" ? (\n <>\n {words}\n {cell}\n </>\n ) : (\n <>\n {cell}\n {words}\n </>\n )}\n </div>\n );\n});\nSwitch.displayName = \"Switch\";\n"],"mappings":";AAmHI,SAyDI,UAxDF,KADF;AAnHJ,SAAS,YAAY,aAAa;AAElC,SAAS,UAAU;AACnB,SAAS,YAAY,wBAAwB;AAiB7C,MAAM,QAAQ;AAAA;AAAA,EAEZ,IAAI,EAAE,OAAO,WAAW,OAAO,mCAAmC;AAAA;AAAA,EAElE,IAAI,EAAE,OAAO,WAAW,OAAO,mCAAmC;AACpE;AAWA,MAAM,QACJ;AASF,MAAM,QACJ;AA2CK,MAAM,SAAS,WAA0C,SAASA,QACvE;AAAA,EACE,OAAO;AAAA,EACP;AAAA,EACA;AAAA,EACA,iBAAiB;AAAA,EACjB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GACA,KACA;AACA,QAAM,YAAY,MAAM;AACxB,QAAM,UAAU,MAAM;AACtB,QAAM,gBAAgB,GAAG,OAAO;AAChC,QAAM,kBAAkB,WAAW,WAAW;AAC9C,QAAM,OAAO,UAAU,UAAa,CAAC;AACrC,QAAM,WAAW,MAAM,IAAI;AAE3B,QAAM,UACJ,qBAAC,UAAK,WAAW,GAAG,iCAAiC,QAAQ,SAAS,GACpE;A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
|
|
5
5
|
"description": "App-agnostic shared design system: domain-free React components, theme and tokens.",
|
|
6
6
|
"_sideEffects": "The barrel (src/index.ts) re-exports EVERY component, including components/chart, which statically imports recharts. Without this field a bundler must assume each of those modules has side effects, so it cannot drop the unused ones: importing a Button from '@eifi1/ui-kit' dragged all 433KB of recharts into the consumer's ENTRY chunk, and Keksdose was preloading it on every page load, login included. Nothing in src/ imports for side effects (no bare imports, no CSS imports from JS, no module-level global writes) — the token stylesheet is its own './tokens.css' export — so this is safe. CSS is still listed so any future stylesheet survives. Re-checked when `flag-icons` left `dependencies` and tsup started emitting a `\"use client\"` banner: neither touches this. The flag stylesheet was never imported from JS in the first place (that was the finding), and a directive prologue is a string literal every bundler lifts out before it decides whether a module is inert.",
|
|
@@ -234,6 +234,16 @@ function AutocompleteInner<V extends string | number = string>(
|
|
|
234
234
|
setActive(-1);
|
|
235
235
|
}}
|
|
236
236
|
onKeyDown={(e) => {
|
|
237
|
+
// An Escape that closes the OPEN list is the list's, and is consumed before
|
|
238
|
+
// the caller sees it. A caller whose Escape means "close the panel" (keksdose's
|
|
239
|
+
// address search) otherwise closed the whole panel when the user only meant
|
|
240
|
+
// to dismiss the suggestions — the opposite of what the docs promised.
|
|
241
|
+
if (e.key === "Escape" && expanded) {
|
|
242
|
+
e.preventDefault();
|
|
243
|
+
e.stopPropagation();
|
|
244
|
+
close();
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
237
247
|
onKeyDown?.(e);
|
|
238
248
|
if (e.defaultPrevented) return;
|
|
239
249
|
const last = results.length - 1;
|
|
@@ -253,14 +263,6 @@ function AutocompleteInner<V extends string | number = string>(
|
|
|
253
263
|
e.preventDefault();
|
|
254
264
|
take(results[active]);
|
|
255
265
|
}
|
|
256
|
-
} else if (e.key === "Escape") {
|
|
257
|
-
// Only when there is a list to close — otherwise the Escape belongs to
|
|
258
|
-
// whatever this field sits in (a dialog), and must reach it.
|
|
259
|
-
if (expanded) {
|
|
260
|
-
e.preventDefault();
|
|
261
|
-
e.stopPropagation();
|
|
262
|
-
close();
|
|
263
|
-
}
|
|
264
266
|
} else if (e.key === "Tab") {
|
|
265
267
|
close();
|
|
266
268
|
}
|
|
@@ -411,7 +413,9 @@ AutocompleteBase.displayName = "Autocomplete";
|
|
|
411
413
|
* row, `aria-controls` the list, and a polite live region says what the list now
|
|
412
414
|
* holds. Keyboard: ↓/↑ move (↓ opens), Enter takes the highlighted row (with none,
|
|
413
415
|
* Enter is left to the form), Escape closes, Tab closes and moves on; Home/End stay
|
|
414
|
-
* with the caret.
|
|
416
|
+
* with the caret. An Escape that closes an open list is consumed and never reaches the
|
|
417
|
+
* caller; with the list closed it does. For every other key a caller's `onKeyDown`
|
|
418
|
+
* runs first and may `preventDefault()` to
|
|
415
419
|
* keep a key for itself.
|
|
416
420
|
*
|
|
417
421
|
* The list is portalled and anchored under the field on every screen size: the
|
|
@@ -78,6 +78,15 @@ export interface CheckboxProps extends Omit<InputHTMLAttributes<HTMLInputElement
|
|
|
78
78
|
* the row when there is a label, the box's own wrapper when there is not — which
|
|
79
79
|
* is where layout (`self-end pb-2` to sit on a field's baseline) belongs. */
|
|
80
80
|
inputClassName?: string;
|
|
81
|
+
/**
|
|
82
|
+
* Must be ticked to submit — a consent, an acceptance before paying. Reaches the
|
|
83
|
+
* `<input>` as the native `required` (so a `<form>` refuses to submit without it and a
|
|
84
|
+
* screen reader announces "required"), and draws the kit's required mark after the
|
|
85
|
+
* label, the same `aria-hidden` star as {@link Label}'s: the word is announced from
|
|
86
|
+
* the control, so a star inside the name would only be read out as noise. Write the
|
|
87
|
+
* label WITHOUT a literal "*". No mark without a label.
|
|
88
|
+
*/
|
|
89
|
+
required?: boolean;
|
|
81
90
|
}
|
|
82
91
|
|
|
83
92
|
/**
|
|
@@ -103,6 +112,7 @@ export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(function Che
|
|
|
103
112
|
inputClassName,
|
|
104
113
|
id,
|
|
105
114
|
disabled,
|
|
115
|
+
required,
|
|
106
116
|
...rest
|
|
107
117
|
},
|
|
108
118
|
ref,
|
|
@@ -138,6 +148,7 @@ export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(function Che
|
|
|
138
148
|
ref={setRef}
|
|
139
149
|
id={bare ? id : inputId}
|
|
140
150
|
disabled={disabled}
|
|
151
|
+
required={required}
|
|
141
152
|
{...rest}
|
|
142
153
|
// After the spread, like Switch: a props object spread at a checkbox must not
|
|
143
154
|
// be able to turn it into something else.
|
|
@@ -203,6 +214,11 @@ export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(function Che
|
|
|
203
214
|
)}
|
|
204
215
|
>
|
|
205
216
|
{label}
|
|
217
|
+
{required && (
|
|
218
|
+
<span aria-hidden className="ms-0.5 text-[var(--danger)]">
|
|
219
|
+
*
|
|
220
|
+
</span>
|
|
221
|
+
)}
|
|
206
222
|
</label>
|
|
207
223
|
)}
|
|
208
224
|
{showDescription && (
|
|
@@ -100,7 +100,14 @@ export function matchesAccept(file: File, accept: string | undefined): boolean {
|
|
|
100
100
|
.filter(Boolean);
|
|
101
101
|
if (tokens.length === 0) return true;
|
|
102
102
|
const name = file.name.toLowerCase();
|
|
103
|
-
|
|
103
|
+
// An EMPTY type is the browser saying "I don't know", not "it's something else": HEIC
|
|
104
|
+
// photos on Windows without the codec arrive with `type === ""`. Refusing them
|
|
105
|
+
// (0.6.0) refused iPhone photos the picker itself had just offered (keksdose). So a
|
|
106
|
+
// missing type is inferred from the extension where that is unambiguous, and a file
|
|
107
|
+
// whose type cannot be known at all is given the benefit of the doubt — nothing here
|
|
108
|
+
// proves it does not match, and the server validates what it receives anyway.
|
|
109
|
+
const type = (file.type || typeFromExtension(name) || "").toLowerCase();
|
|
110
|
+
if (!type && !tokens.every((t) => t.startsWith("."))) return true;
|
|
104
111
|
return tokens.some((token) => {
|
|
105
112
|
if (token.startsWith(".")) return name.endsWith(token);
|
|
106
113
|
if (!type) return false;
|
|
@@ -109,6 +116,26 @@ export function matchesAccept(file: File, accept: string | undefined): boolean {
|
|
|
109
116
|
});
|
|
110
117
|
}
|
|
111
118
|
|
|
119
|
+
/** MIME types for the extensions a browser most often leaves untyped. */
|
|
120
|
+
const EXTENSION_TYPES: Record<string, string> = {
|
|
121
|
+
heic: "image/heic",
|
|
122
|
+
heif: "image/heif",
|
|
123
|
+
avif: "image/avif",
|
|
124
|
+
webp: "image/webp",
|
|
125
|
+
jpg: "image/jpeg",
|
|
126
|
+
jpeg: "image/jpeg",
|
|
127
|
+
png: "image/png",
|
|
128
|
+
gif: "image/gif",
|
|
129
|
+
pdf: "application/pdf",
|
|
130
|
+
csv: "text/csv",
|
|
131
|
+
txt: "text/plain",
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
function typeFromExtension(name: string): string | undefined {
|
|
135
|
+
const dot = name.lastIndexOf(".");
|
|
136
|
+
return dot === -1 ? undefined : EXTENSION_TYPES[name.slice(dot + 1)];
|
|
137
|
+
}
|
|
138
|
+
|
|
112
139
|
/** What the pickers screen a pick with. All optional; nothing set accepts everything. */
|
|
113
140
|
export interface FileScreenOptions {
|
|
114
141
|
accept?: string;
|
|
@@ -70,6 +70,15 @@ export interface SwitchProps extends Omit<InputHTMLAttributes<HTMLInputElement>,
|
|
|
70
70
|
/** Classes for the `<input>` (the track). `className` styles the outermost element:
|
|
71
71
|
* the row when there is a label, the switch's own wrapper when there is not. */
|
|
72
72
|
inputClassName?: string;
|
|
73
|
+
/**
|
|
74
|
+
* Must be ticked to submit — a consent, an acceptance before paying. Reaches the
|
|
75
|
+
* `<input>` as the native `required` (so a `<form>` refuses to submit without it and a
|
|
76
|
+
* screen reader announces "required"), and draws the kit's required mark after the
|
|
77
|
+
* label, the same `aria-hidden` star as {@link Label}'s: the word is announced from
|
|
78
|
+
* the control, so a star inside the name would only be read out as noise. Write the
|
|
79
|
+
* label WITHOUT a literal "*". No mark without a label.
|
|
80
|
+
*/
|
|
81
|
+
required?: boolean;
|
|
73
82
|
}
|
|
74
83
|
|
|
75
84
|
/**
|
|
@@ -91,6 +100,7 @@ export const Switch = forwardRef<HTMLInputElement, SwitchProps>(function Switch(
|
|
|
91
100
|
inputClassName,
|
|
92
101
|
id,
|
|
93
102
|
disabled,
|
|
103
|
+
required,
|
|
94
104
|
...rest
|
|
95
105
|
},
|
|
96
106
|
ref,
|
|
@@ -108,6 +118,7 @@ export const Switch = forwardRef<HTMLInputElement, SwitchProps>(function Switch(
|
|
|
108
118
|
ref={ref}
|
|
109
119
|
id={bare ? id : inputId}
|
|
110
120
|
disabled={disabled}
|
|
121
|
+
required={required}
|
|
111
122
|
{...rest}
|
|
112
123
|
// After the spread: a caller's props object must not be able to turn this
|
|
113
124
|
// back into a plain checkbox, or into a text field.
|
|
@@ -141,6 +152,11 @@ export const Switch = forwardRef<HTMLInputElement, SwitchProps>(function Switch(
|
|
|
141
152
|
)}
|
|
142
153
|
>
|
|
143
154
|
{label}
|
|
155
|
+
{required && (
|
|
156
|
+
<span aria-hidden className="ms-0.5 text-[var(--danger)]">
|
|
157
|
+
*
|
|
158
|
+
</span>
|
|
159
|
+
)}
|
|
144
160
|
</label>
|
|
145
161
|
)}
|
|
146
162
|
{showDescription && (
|