@eifi1/ui-kit 0.6.1 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -33
- package/dist/chart.d.ts +1 -0
- package/dist/components/account-settings.js +3 -2
- package/dist/components/account-settings.js.map +1 -1
- package/dist/components/amount-input.d.ts +5 -0
- package/dist/components/amount-input.js +6 -4
- package/dist/components/amount-input.js.map +1 -1
- package/dist/components/autocomplete.d.ts +33 -6
- package/dist/components/autocomplete.js +62 -16
- package/dist/components/autocomplete.js.map +1 -1
- package/dist/components/calculator.d.ts +5 -0
- package/dist/components/calculator.js +2 -1
- package/dist/components/calculator.js.map +1 -1
- package/dist/components/chart-zoom.js +2 -1
- package/dist/components/chart-zoom.js.map +1 -1
- package/dist/components/chart.d.ts +33 -2
- package/dist/components/chart.js +20 -8
- package/dist/components/chart.js.map +1 -1
- package/dist/components/chip.d.ts +34 -14
- package/dist/components/chip.js +63 -28
- package/dist/components/chip.js.map +1 -1
- package/dist/components/choice-card.d.ts +18 -1
- package/dist/components/choice-card.js +21 -8
- package/dist/components/choice-card.js.map +1 -1
- package/dist/components/combobox-core.d.ts +61 -2
- package/dist/components/combobox-core.js +68 -17
- package/dist/components/combobox-core.js.map +1 -1
- package/dist/components/combobox.d.ts +11 -7
- package/dist/components/combobox.js +51 -28
- package/dist/components/combobox.js.map +1 -1
- package/dist/components/currency-select.js +3 -3
- package/dist/components/currency-select.js.map +1 -1
- package/dist/components/danger-confirm.d.ts +30 -6
- package/dist/components/danger-confirm.js +51 -32
- package/dist/components/danger-confirm.js.map +1 -1
- package/dist/components/data-table-filter-popover.d.ts +1 -1
- package/dist/components/data-table-filters.d.ts +1 -1
- package/dist/components/data-table-pagination.d.ts +6 -3
- package/dist/components/data-table-pagination.js +6 -5
- package/dist/components/data-table-pagination.js.map +1 -1
- package/dist/components/data-table.d.ts +1 -1
- package/dist/components/data-table.js +332 -248
- package/dist/components/data-table.js.map +1 -1
- package/dist/components/date-picker.js +17 -7
- package/dist/components/date-picker.js.map +1 -1
- package/dist/components/dialog-frame.d.ts +28 -3
- package/dist/components/dialog-frame.js +47 -11
- package/dist/components/dialog-frame.js.map +1 -1
- package/dist/components/disclosure.d.ts +22 -2
- package/dist/components/disclosure.js +41 -8
- package/dist/components/disclosure.js.map +1 -1
- package/dist/components/dropdown.d.ts +7 -3
- package/dist/components/dropdown.js +6 -2
- package/dist/components/dropdown.js.map +1 -1
- package/dist/components/entity-combobox.d.ts +17 -8
- package/dist/components/entity-combobox.js +7 -5
- package/dist/components/entity-combobox.js.map +1 -1
- package/dist/components/file-button.d.ts +38 -5
- package/dist/components/file-button.js +23 -2
- package/dist/components/file-button.js.map +1 -1
- package/dist/components/file-dropzone.d.ts +11 -5
- package/dist/components/file-dropzone.js +14 -19
- package/dist/components/file-dropzone.js.map +1 -1
- package/dist/components/grouped-picker.js +2 -2
- package/dist/components/grouped-picker.js.map +1 -1
- package/dist/components/hover-menu.d.ts +8 -3
- package/dist/components/hover-menu.js +88 -4
- package/dist/components/hover-menu.js.map +1 -1
- package/dist/components/icon-picker.d.ts +10 -1
- package/dist/components/icon-picker.js +5 -1
- package/dist/components/icon-picker.js.map +1 -1
- package/dist/components/measured-grid.d.ts +165 -0
- package/dist/components/measured-grid.js +559 -0
- package/dist/components/measured-grid.js.map +1 -0
- package/dist/components/mini-calendar.js +7 -8
- package/dist/components/mini-calendar.js.map +1 -1
- package/dist/components/month-picker.js +13 -9
- package/dist/components/month-picker.js.map +1 -1
- package/dist/components/multi-entity-combobox.js +2 -2
- package/dist/components/multi-entity-combobox.js.map +1 -1
- package/dist/components/multi-select.d.ts +9 -1
- package/dist/components/multi-select.js +22 -8
- package/dist/components/multi-select.js.map +1 -1
- package/dist/components/number-field.d.ts +5 -0
- package/dist/components/number-input.d.ts +5 -0
- package/dist/components/number-input.js +3 -3
- package/dist/components/number-input.js.map +1 -1
- package/dist/components/numpad-sheet.d.ts +5 -0
- package/dist/components/numpad-sheet.js +3 -3
- package/dist/components/numpad-sheet.js.map +1 -1
- package/dist/components/picker-sheet.js +1 -1
- package/dist/components/picker-sheet.js.map +1 -1
- package/dist/components/popover.js +11 -2
- package/dist/components/popover.js.map +1 -1
- package/dist/components/series-chart-ticks.d.ts +13 -0
- package/dist/components/series-chart-ticks.js +29 -0
- package/dist/components/series-chart-ticks.js.map +1 -0
- package/dist/components/series-chart.js +33 -27
- package/dist/components/series-chart.js.map +1 -1
- package/dist/components/settings-fields.d.ts +2 -0
- package/dist/components/swatch-picker.d.ts +10 -1
- package/dist/components/swatch-picker.js +2 -0
- package/dist/components/swatch-picker.js.map +1 -1
- package/dist/components/swipeable-row.d.ts +11 -2
- package/dist/components/swipeable-row.js +5 -3
- package/dist/components/swipeable-row.js.map +1 -1
- package/dist/components/tile-radio.js +5 -7
- package/dist/components/tile-radio.js.map +1 -1
- package/dist/components/time-input.d.ts +2 -0
- package/dist/components/toggle-group.d.ts +13 -3
- package/dist/components/toggle-group.js +21 -1
- package/dist/components/toggle-group.js.map +1 -1
- package/dist/components/toggle-legend.js +1 -2
- package/dist/components/toggle-legend.js.map +1 -1
- package/dist/components/tooltip.d.ts +10 -4
- package/dist/components/tooltip.js +23 -6
- package/dist/components/tooltip.js.map +1 -1
- package/dist/components/treemap.d.ts +6 -1
- package/dist/components/treemap.js +16 -6
- package/dist/components/treemap.js.map +1 -1
- package/dist/components/ui.d.ts +36 -8
- package/dist/components/ui.js +27 -19
- package/dist/components/ui.js.map +1 -1
- package/dist/components/use-anchor-dir.d.ts +15 -0
- package/dist/components/use-anchor-dir.js +14 -0
- package/dist/components/use-anchor-dir.js.map +1 -0
- package/dist/components/use-mobile-reveal.d.ts +8 -1
- package/dist/components/use-mobile-reveal.js +3 -2
- package/dist/components/use-mobile-reveal.js.map +1 -1
- package/dist/components/use-table-state.d.ts +4 -4
- package/dist/components/use-table-state.js +12 -5
- package/dist/components/use-table-state.js.map +1 -1
- package/dist/{data-table-filters-DM1auUfH.d.ts → data-table-filters-noy0Abvi.d.ts} +40 -7
- package/dist/data-table.d.ts +1 -1
- package/dist/data-table.js.map +1 -1
- package/dist/feedback/feedback-attachment.d.ts +22 -3
- package/dist/feedback/feedback-attachment.js +15 -7
- package/dist/feedback/feedback-attachment.js.map +1 -1
- package/dist/feedback/feedback-dialog.d.ts +3 -2
- package/dist/feedback/feedback-dialog.js.map +1 -1
- package/dist/feedback.d.ts +1 -1
- package/dist/hooks/use-windowed-rows.d.ts +29 -0
- package/dist/hooks/use-windowed-rows.js +31 -0
- package/dist/hooks/use-windowed-rows.js.map +1 -0
- package/dist/i18n/defaults.d.ts +5 -0
- package/dist/i18n/defaults.js +5 -1
- package/dist/i18n/defaults.js.map +1 -1
- package/dist/i18n/kit-labels.d.ts +7 -0
- package/dist/i18n/kit-labels.js.map +1 -1
- package/dist/i18n/locales/de-CH.d.ts +45 -0
- package/dist/i18n/locales/de-CH.js +21 -0
- package/dist/i18n/locales/de-CH.js.map +1 -0
- package/dist/i18n/locales/de.d.ts +45 -0
- package/dist/i18n/locales/de.js +344 -0
- package/dist/i18n/locales/de.js.map +1 -0
- package/dist/i18n/locales/es.d.ts +45 -0
- package/dist/i18n/locales/es.js +339 -0
- package/dist/i18n/locales/es.js.map +1 -0
- package/dist/i18n/locales/fr.d.ts +45 -0
- package/dist/i18n/locales/fr.js +344 -0
- package/dist/i18n/locales/fr.js.map +1 -0
- package/dist/i18n/locales/hu.d.ts +45 -0
- package/dist/i18n/locales/hu.js +343 -0
- package/dist/i18n/locales/hu.js.map +1 -0
- package/dist/i18n/locales/it.d.ts +45 -0
- package/dist/i18n/locales/it.js +342 -0
- package/dist/i18n/locales/it.js.map +1 -0
- package/dist/i18n/locales/zh.d.ts +45 -0
- package/dist/i18n/locales/zh.js +338 -0
- package/dist/i18n/locales/zh.js.map +1 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/direction.d.ts +24 -0
- package/dist/lib/direction.js +19 -0
- package/dist/lib/direction.js.map +1 -0
- package/dist/rhf/form.d.ts +2 -0
- package/dist/rhf/form.js.map +1 -1
- package/dist/rhf.d.ts +2 -0
- package/dist/search/command-palette.d.ts +5 -0
- package/dist/search/command-palette.js +80 -50
- package/dist/search/command-palette.js.map +1 -1
- package/dist/shell/app-shell.d.ts +13 -1
- package/dist/shell/app-shell.js +134 -85
- package/dist/shell/app-shell.js.map +1 -1
- package/dist/shell/topbar-action-menu.js +1 -1
- package/dist/shell/topbar-action-menu.js.map +1 -1
- package/dist/shell/topbar-controls.d.ts +7 -3
- package/dist/shell/topbar-controls.js +38 -31
- package/dist/shell/topbar-controls.js.map +1 -1
- package/dist/theme/chart-palette.d.ts +7 -1
- package/dist/theme/chart-palette.js +2 -1
- package/dist/theme/chart-palette.js.map +1 -1
- package/dist/tour/tour.d.ts +11 -5
- package/dist/tour/tour.js +124 -58
- package/dist/tour/tour.js.map +1 -1
- package/dist/wizard/use-wizard.js +30 -13
- package/dist/wizard/use-wizard.js.map +1 -1
- package/dist/wizard/wizard-summary.js +1 -1
- package/dist/wizard/wizard-summary.js.map +1 -1
- package/package.json +12 -2
- package/src/components/account-settings.tsx +6 -2
- package/src/components/amount-input.tsx +10 -8
- package/src/components/autocomplete.tsx +110 -24
- package/src/components/calculator.tsx +5 -1
- package/src/components/chart-zoom.tsx +8 -1
- package/src/components/chart.tsx +68 -7
- package/src/components/chip.tsx +131 -49
- package/src/components/choice-card.tsx +77 -36
- package/src/components/combobox-core.tsx +147 -20
- package/src/components/combobox.tsx +100 -44
- package/src/components/currency-select.tsx +6 -6
- package/src/components/danger-confirm.tsx +90 -36
- package/src/components/data-table-pagination.tsx +32 -19
- package/src/components/data-table.tsx +198 -36
- package/src/components/date-picker.tsx +24 -7
- package/src/components/dialog-frame.tsx +97 -22
- package/src/components/disclosure.tsx +75 -13
- package/src/components/dropdown.tsx +17 -5
- package/src/components/entity-combobox.tsx +26 -13
- package/src/components/file-button.tsx +74 -5
- package/src/components/file-dropzone.tsx +44 -35
- package/src/components/grouped-picker.tsx +2 -2
- package/src/components/hover-menu.tsx +139 -10
- package/src/components/icon-picker.tsx +14 -1
- package/src/components/measured-grid.tsx +852 -0
- package/src/components/mini-calendar.tsx +11 -8
- package/src/components/month-picker.tsx +18 -11
- package/src/components/multi-entity-combobox.tsx +2 -2
- package/src/components/multi-select.tsx +34 -7
- package/src/components/number-input.tsx +4 -4
- package/src/components/numpad-sheet.tsx +5 -3
- package/src/components/picker-sheet.tsx +1 -1
- package/src/components/popover.tsx +18 -3
- package/src/components/series-chart-ticks.ts +52 -0
- package/src/components/series-chart.tsx +39 -31
- package/src/components/swatch-picker.tsx +11 -0
- package/src/components/swipeable-row.tsx +21 -6
- package/src/components/tile-radio.tsx +5 -7
- package/src/components/toggle-group.tsx +39 -3
- package/src/components/toggle-legend.tsx +5 -2
- package/src/components/tooltip.tsx +40 -12
- package/src/components/treemap.tsx +28 -5
- package/src/components/ui.tsx +79 -33
- package/src/components/use-anchor-dir.ts +20 -0
- package/src/components/use-mobile-reveal.ts +10 -2
- package/src/components/use-table-state.ts +44 -7
- package/src/data-table.ts +1 -0
- package/src/feedback/feedback-attachment.tsx +36 -9
- package/src/feedback/feedback-dialog.tsx +3 -2
- package/src/hooks/use-windowed-rows.ts +69 -0
- package/src/i18n/defaults.ts +4 -0
- package/src/i18n/kit-labels.tsx +4 -0
- package/src/i18n/locales/de-CH.ts +30 -0
- package/src/i18n/locales/de.ts +365 -0
- package/src/i18n/locales/es.ts +358 -0
- package/src/i18n/locales/fr.ts +371 -0
- package/src/i18n/locales/hu.ts +359 -0
- package/src/i18n/locales/it.ts +360 -0
- package/src/i18n/locales/zh.ts +348 -0
- package/src/index.ts +10 -1
- package/src/lib/direction.ts +37 -0
- package/src/rhf/form.tsx +21 -0
- package/src/search/command-palette.tsx +77 -19
- package/src/shell/app-shell.tsx +201 -130
- package/src/shell/topbar-action-menu.tsx +1 -1
- package/src/shell/topbar-controls.tsx +19 -8
- package/src/theme/chart-palette.ts +9 -2
- package/src/tour/tour.tsx +119 -18
- package/src/wizard/use-wizard.ts +55 -17
- package/src/wizard/wizard-summary.tsx +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/disclosure.tsx"],"sourcesContent":["import { useEffect, useId, useState } from \"react\";\nimport type { ComponentPropsWithoutRef, ReactNode } from \"react\";\nimport { ChevronDown } from \"lucide-react\";\n\nimport { cn } from \"../lib/cn\";\n\n/** How long the fold takes, in ms. The same number as the `duration-200` below and as\n * the unmount timer, because they are the same movement. */\nconst COLLAPSE_MS = 200;\n\n/** Read at the moment of closing, like `useCloseTransition` does: the setting can\n * change under a long-lived page, and jsdom/SSR have no `matchMedia` — where \"no\n * animation\" is also the only correct answer, since nothing is painting. */\nfunction prefersReducedMotion(): boolean {\n return (\n typeof window === \"undefined\" ||\n typeof window.matchMedia !== \"function\" ||\n window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n );\n}\n\n/**\n * `extends` the div's props so an `id` (what a trigger's `aria-controls` points at), a\n * `data-tour` anchor or a test id reaches the element that folds.\n */\nexport interface CollapseProps extends ComponentPropsWithoutRef<\"div\"> {\n open: boolean;\n /**\n * Keep the children mounted while shut (hidden and `inert`) instead of unmounting\n * them once the fold has finished closing.\n *\n * Off by default, and that default is a behaviour contract rather than a\n * performance note: Lenkbank's disclosure bodies FETCH, and a body that only exists\n * while open is what stops a closed card asking — without every caller carrying its\n * own `enabled: open`. On for a body whose state must outlive a close (a half-typed\n * form) or that must be found by the browser's find-in-page.\n */\n keepMounted?: boolean;\n children: ReactNode;\n}\n\n/**\n * The fold on its own: content that opens and shuts in place, animated to a height\n * nobody measured.\n *\n * THE TECHNIQUE is `AppShell`'s sidebar group's, lifted out so there is one copy of it.\n * A `grid-template-rows` transition from `0fr` to `1fr` is the one way to animate to a\n * content-sized height without measuring it — so a chart that resizes inside it, or a\n * translated line that wraps, is still exactly as tall as it needs. `visibility` rides\n * the same transition, so a shut body leaves the accessibility tree only once it has\n * finished closing; `inert` takes it out of the tab order immediately.\n *\n * THE CHILDREN are unmounted once closed (see {@link CollapseProps.keepMounted}), but\n * only once the track has finished closing: the track is what animates, so the\n * children have to survive the movement that hides them. Under reduced motion they\n * go at once — there is no movement to wait for — and the opening half is silenced by\n * `motion-reduce:transition-none`, since tokens.css only silences the overlay\n * animations by name.\n *\n * Padding and margins belong on a child: on this element, or the clipping one inside\n * it, they would hold the row open by that much.\n */\nexport function Collapse({ open, keepMounted = false, children, className, style, ...rest }: CollapseProps) {\n // Whether the children are still on their way out. Adjusted DURING render when\n // `open` flips (React's \"storing information from previous renders\"), so a close\n // under reduced motion unmounts in the same render that shut it — a test, and a\n // screen reader, see the body go on the click — and a re-open mid-fold simply\n // cancels the linger.\n const [lingering, setLingering] = useState(false);\n const [prevOpen, setPrevOpen] = useState(open);\n if (open !== prevOpen) {\n setPrevOpen(open);\n setLingering(!open && !prefersReducedMotion());\n }\n useEffect(() => {\n if (!lingering) return;\n const timer = setTimeout(() => setLingering(false), COLLAPSE_MS);\n return () => clearTimeout(timer);\n }, [lingering]);\n\n const mounted = open || lingering || keepMounted;\n\n return (\n <div\n {...rest}\n inert={!open}\n className={cn(\n \"grid transition-[grid-template-rows,visibility] duration-200 ease-out motion-reduce:transition-none\",\n className,\n )}\n // Inline rather than `grid-rows-[…]` classes: a caller's `className` must not be\n // able to pin the track open, and the two values ARE the state.\n style={{ ...style, gridTemplateRows: open ? \"1fr\" : \"0fr\", visibility: open ? \"visible\" : \"hidden\" }}\n >\n <div\n className={cn(\n \"min-h-0 overflow-hidden transition-opacity duration-200 ease-out motion-reduce:transition-none\",\n open ? \"opacity-100\" : \"opacity-0\",\n )}\n >\n {mounted && children}\n </div>\n </div>\n );\n}\n\n/**\n * `title` is omitted from the div's own props because this component already owns the\n * name: here it is the header's content (and a ReactNode), not the browser's tooltip.\n * Everything else reaches the outer element.\n */\nexport interface DisclosureProps extends Omit<ComponentPropsWithoutRef<\"div\">, \"title\"> {\n /** What the header says. A node, so a status chip or a count can sit in it. */\n title: ReactNode;\n /** The smaller line under the title — what is inside, for a reader deciding whether\n * to open it. */\n hint?: ReactNode;\n /**\n * Who decides whether this one is open. Left out, the disclosure decides for itself,\n * which is what one standing on its own wants. Passed, the caller does — a set of\n * which one is open at a time, or an open state kept in the URL so the view can be\n * linked to. There is no accordion component: \"one open at a time\" is a few lines in\n * the caller and it usually owns a URL parameter, which is app state.\n */\n open?: boolean;\n /** Whether an UNCONTROLLED disclosure starts open. Ignored when `open` is passed. */\n defaultOpen?: boolean;\n /** Called with the next state on every toggle, controlled or not. */\n onOpenChange?: (open: boolean) => void;\n /**\n * `card` (default) draws the kit's `Card` surface round header and body, with the\n * chevron trailing the header and turning over — the \"section that opens\" of a\n * settings or analysis page. `bare` draws nothing: a leading chevron that turns\n * down, for an inline \"Show 3 hidden accounts\" inside something that already has\n * its own surface.\n */\n variant?: \"card\" | \"bare\";\n /**\n * Wrap the header button in a heading of this level. The WAI-ARIA disclosure pattern\n * puts the button INSIDE the heading when the disclosure titles a section, so the\n * page's heading outline still lists it. Off by default: an inline \"show more\" is\n * not a section.\n */\n headingAs?: \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\";\n /** See {@link CollapseProps.keepMounted}. */\n keepMounted?: boolean;\n disabled?: boolean;\n /** Extra classes for the header button. */\n headerClassName?: string;\n /** Extra classes for the body's wrapper — where its padding and spacing live. */\n bodyClassName?: string;\n children: ReactNode;\n}\n\n/**\n * A section that opens in place: a header button with `aria-expanded` and\n * `aria-controls`, and a {@link Collapse} under it.\n *\n * Both apps had written this by hand — Lenkbank as a shared `CollapsibleCard` with ten\n * importers, Keksdose three separate times (accounts, twice; the support panel) — and\n * the copies had drifted: none of Keksdose's animated, and all three swapped a\n * `ChevronRight` for a `ChevronDown` rather than turning one. Here the chevron is one\n * icon that rotates, so the change of state is one element moving rather than two\n * trading places.\n *\n * The body is unmounted while shut; see {@link CollapseProps.keepMounted} for why that\n * is the default and when to opt out.\n */\nexport function Disclosure({\n title,\n hint,\n open: controlled,\n defaultOpen = false,\n onOpenChange,\n variant = \"card\",\n headingAs: Heading,\n keepMounted,\n disabled,\n headerClassName,\n bodyClassName,\n className,\n children,\n ...rest\n}: DisclosureProps) {\n const [own, setOwn] = useState(defaultOpen);\n const open = controlled ?? own;\n const bodyId = useId();\n const card = variant === \"card\";\n\n const toggle = () => {\n const next = !open;\n if (controlled === undefined) setOwn(next);\n onOpenChange?.(next);\n };\n\n const button = (\n <button\n type=\"button\"\n aria-expanded={open}\n aria-controls={bodyId}\n disabled={disabled}\n onClick={toggle}\n className={cn(\n \"flex w-full gap-2 text-start outline-none disabled:cursor-not-allowed disabled:opacity-50\",\n \"focus-visible:ring-2 focus-visible:ring-[var(--brand)]\",\n card\n ? cn(\n \"items-center justify-between rounded-lg p-4 hover:bg-[var(--bg-hover)] focus-visible:ring-inset\",\n open && \"rounded-b-none\",\n )\n : \"items-center rounded-sm text-sm font-medium text-[var(--text-secondary)] hover:text-[var(--text-primary)]\",\n headerClassName,\n )}\n >\n {!card && <Chevron open={open} leading />}\n <span className=\"min-w-0\">\n <span className={cn(\"block\", card && \"text-sm font-semibold text-[var(--text-primary)]\")}>{title}</span>\n {hint !== undefined && (\n <span className=\"mt-0.5 block text-xs font-normal text-[var(--text-muted)]\">{hint}</span>\n )}\n </span>\n {card && <Chevron open={open} />}\n </button>\n );\n\n return (\n <div\n {...rest}\n className={cn(card && \"rounded-lg border border-[var(--border)] bg-[var(--bg-surface)] shadow-sm\", className)}\n >\n {/* Preflight already makes h1–h6 inherit size and weight, so the heading adds\n structure and nothing visible. */}\n {Heading ? <Heading>{button}</Heading> : button}\n <Collapse id={bodyId} open={open} keepMounted={keepMounted}>\n <div className={cn(card ? \"space-y-3 px-4 pb-4\" : \"space-y-2 pt-2\", bodyClassName)}>{children}</div>\n </Collapse>\n </div>\n );\n}\n\n/**\n * One icon for both variants, turned rather than swapped. `leading` (bare) points it\n * along the reading direction while shut — right in LTR, left in RTL — and down when\n * open; trailing (card) points down while shut and up when open, which is the card\n * header's convention. Rotation, not a mirrored glyph, so RTL needs one opposite angle\n * and no `scale` composing with the turn.\n */\nfunction Chevron({ open, leading = false }: { open: boolean; leading?: boolean }) {\n return (\n <ChevronDown\n aria-hidden\n className={cn(\n \"shrink-0 text-[var(--text-muted)] transition-transform duration-200 ease-out motion-reduce:transition-none\",\n leading ? \"size-3.5\" : \"size-4\",\n leading ? !open && \"-rotate-90 rtl:rotate-90\" : open && \"rotate-180\",\n )}\n />\n );\n}\n"],"mappings":";AA8FM,cAyHA,YAzHA;AA9FN,SAAS,WAAW,OAAO,gBAAgB;AAE3C,SAAS,mBAAmB;AAE5B,SAAS,UAAU;AAInB,MAAM,cAAc;AAKpB,SAAS,uBAAgC;AACvC,SACE,OAAO,WAAW,eAClB,OAAO,OAAO,eAAe,cAC7B,OAAO,WAAW,kCAAkC,EAAE;AAE1D;AA2CO,SAAS,SAAS,EAAE,MAAM,cAAc,OAAO,UAAU,WAAW,OAAO,GAAG,KAAK,GAAkB;AAM1G,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,UAAU,WAAW,IAAI,SAAS,IAAI;AAC7C,MAAI,SAAS,UAAU;AACrB,gBAAY,IAAI;AAChB,iBAAa,CAAC,QAAQ,CAAC,qBAAqB,CAAC;AAAA,EAC/C;AACA,YAAU,MAAM;AACd,QAAI,CAAC,UAAW;AAChB,UAAM,QAAQ,WAAW,MAAM,aAAa,KAAK,GAAG,WAAW;AAC/D,WAAO,MAAM,aAAa,KAAK;AAAA,EACjC,GAAG,CAAC,SAAS,CAAC;AAEd,QAAM,UAAU,QAAQ,aAAa;AAErC,SACE;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,OAAO,CAAC;AAAA,MACR,WAAW;AAAA,QACT;AAAA,QACA;AAAA,MACF;AAAA,MAGA,OAAO,EAAE,GAAG,OAAO,kBAAkB,OAAO,QAAQ,OAAO,YAAY,OAAO,YAA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6EAA6E,SAAS;AAAA,MAI3G;AAAA,kBAAU,oBAAC,WAAS,kBAAO,IAAa;AAAA,QACzC,oBAAC,YAAS,IAAI,QAAQ,MAAY,aAChC,8BAAC,SAAI,WAAW,GAAG,OAAO,wBAAwB,kBAAkB,aAAa,GAAI,UAAS,GAChG;AAAA;AAAA;AAAA,EACF;AAEJ;AASA,SAAS,QAAQ,EAAE,MAAM,UAAU,MAAM,GAAyC;AAChF,SACE;AAAA,IAAC;AAAA;AAAA,MACC,eAAW;AAAA,MACX,WAAW;AAAA,QACT;AAAA,QACA,UAAU,aAAa;AAAA,QACvB,UAAU,CAAC,QAAQ,6BAA6B,QAAQ;AAAA,MAC1D;AAAA;AAAA,EACF;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/disclosure.tsx"],"sourcesContent":["import { useEffect, useId, useState } from \"react\";\nimport type { ComponentPropsWithoutRef, ReactNode } from \"react\";\nimport { ChevronDown } from \"lucide-react\";\n\nimport { cn } from \"../lib/cn\";\n\n/** How long the fold takes, in ms. The same number as the `duration-200` below and as\n * the unmount timer, because they are the same movement. */\nconst COLLAPSE_MS = 200;\n\n/** Read at the moment of closing, like `useCloseTransition` does: the setting can\n * change under a long-lived page, and jsdom/SSR have no `matchMedia` — where \"no\n * animation\" is also the only correct answer, since nothing is painting. */\nfunction prefersReducedMotion(): boolean {\n return (\n typeof window === \"undefined\" ||\n typeof window.matchMedia !== \"function\" ||\n window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n );\n}\n\n/**\n * `extends` the div's props so an `id` (what a trigger's `aria-controls` points at), a\n * `data-tour` anchor or a test id reaches the element that folds.\n */\nexport interface CollapseProps extends ComponentPropsWithoutRef<\"div\"> {\n open: boolean;\n /**\n * Keep the children mounted while shut (hidden and `inert`) instead of unmounting\n * them once the fold has finished closing.\n *\n * Off by default, and that default is a behaviour contract rather than a\n * performance note: Lenkbank's disclosure bodies FETCH, and a body that only exists\n * while open is what stops a closed card asking — without every caller carrying its\n * own `enabled: open`. On for a body whose state must outlive a close (a half-typed\n * form) or that must be found by the browser's find-in-page.\n */\n keepMounted?: boolean;\n children: ReactNode;\n}\n\n/**\n * The fold on its own: content that opens and shuts in place, animated to a height\n * nobody measured.\n *\n * THE TECHNIQUE is `AppShell`'s sidebar group's, lifted out so there is one copy of it.\n * A `grid-template-rows` transition from `0fr` to `1fr` is the one way to animate to a\n * content-sized height without measuring it — so a chart that resizes inside it, or a\n * translated line that wraps, is still exactly as tall as it needs. `visibility` rides\n * the same transition, so a shut body leaves the accessibility tree only once it has\n * finished closing; `inert` takes it out of the tab order immediately.\n *\n * THE CHILDREN are unmounted once closed (see {@link CollapseProps.keepMounted}), but\n * only once the track has finished closing: the track is what animates, so the\n * children have to survive the movement that hides them. Under reduced motion they\n * go at once — there is no movement to wait for — and the opening half is silenced by\n * `motion-reduce:transition-none`, since tokens.css only silences the overlay\n * animations by name.\n *\n * Padding and margins belong on a child: on this element, or the clipping one inside\n * it, they would hold the row open by that much.\n */\nexport function Collapse({ open, keepMounted = false, children, className, style, ...rest }: CollapseProps) {\n // Whether the children are still on their way out. Adjusted DURING render when\n // `open` flips (React's \"storing information from previous renders\"), so a close\n // under reduced motion unmounts in the same render that shut it — a test, and a\n // screen reader, see the body go on the click — and a re-open mid-fold simply\n // cancels the linger.\n const [lingering, setLingering] = useState(false);\n const [prevOpen, setPrevOpen] = useState(open);\n if (open !== prevOpen) {\n setPrevOpen(open);\n setLingering(!open && !prefersReducedMotion());\n }\n useEffect(() => {\n if (!lingering) return;\n const timer = setTimeout(() => setLingering(false), COLLAPSE_MS);\n return () => clearTimeout(timer);\n }, [lingering]);\n\n const mounted = open || lingering || keepMounted;\n\n return (\n <div\n {...rest}\n inert={!open}\n className={cn(\n \"grid transition-[grid-template-rows,visibility] duration-200 ease-out motion-reduce:transition-none\",\n className,\n )}\n // Inline rather than `grid-rows-[…]` classes: a caller's `className` must not be\n // able to pin the track open, and the two values ARE the state.\n style={{ ...style, gridTemplateRows: open ? \"1fr\" : \"0fr\", visibility: open ? \"visible\" : \"hidden\" }}\n >\n <div\n className={cn(\n \"min-h-0 overflow-hidden transition-opacity duration-200 ease-out motion-reduce:transition-none\",\n open ? \"opacity-100\" : \"opacity-0\",\n )}\n >\n {mounted && children}\n </div>\n </div>\n );\n}\n\n/**\n * `title` is omitted from the div's own props because this component already owns the\n * name: here it is the header's content (and a ReactNode), not the browser's tooltip.\n * Everything else reaches the outer element.\n */\nexport interface DisclosureProps extends Omit<ComponentPropsWithoutRef<\"div\">, \"title\"> {\n /** What the header says. A node, so a status chip or a count can sit in it. */\n title: ReactNode;\n /** The smaller line under the title — what is inside, for a reader deciding whether\n * to open it. */\n hint?: ReactNode;\n /**\n * Who decides whether this one is open. Left out, the disclosure decides for itself,\n * which is what one standing on its own wants. Passed, the caller does — a set of\n * which one is open at a time, or an open state kept in the URL so the view can be\n * linked to. There is no accordion component: \"one open at a time\" is a few lines in\n * the caller and it usually owns a URL parameter, which is app state.\n */\n open?: boolean;\n /** Whether an UNCONTROLLED disclosure starts open. Ignored when `open` is passed. */\n defaultOpen?: boolean;\n /** Called with the next state on every toggle, controlled or not. */\n onOpenChange?: (open: boolean) => void;\n /**\n * `card` (default) draws the kit's `Card` surface round header and body, with the\n * chevron trailing the header and turning over — the \"section that opens\" of a\n * settings or analysis page. `bare` draws nothing: a leading chevron that turns\n * down, for an inline \"Show 3 hidden accounts\" inside something that already has\n * its own surface.\n */\n variant?: \"card\" | \"bare\";\n /**\n * Wrap the header button in a heading of this level. The WAI-ARIA disclosure pattern\n * puts the button INSIDE the heading when the disclosure titles a section, so the\n * page's heading outline still lists it. Off by default: an inline \"show more\" is\n * not a section.\n */\n headingAs?: \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\";\n /** See {@link CollapseProps.keepMounted}. */\n keepMounted?: boolean;\n disabled?: boolean;\n /** Extra classes for the header button. */\n headerClassName?: string;\n /** Extra classes for the body's wrapper — where its padding and spacing live. */\n bodyClassName?: string;\n /**\n * Content at the far end of the header row, beside the title: a count, a date, a\n * status chip, an action button. It is a SIBLING of the header button, never inside\n * it — a button may not contain another interactive element, and a count inside it\n * would also be read as part of the button's name. The header button still spans\n * the row under it (a stretched hit area), so clicking the empty space or the\n * card's chevron still toggles, while whatever sits in `trailing` gets its own\n * clicks. With `trailing`, the card's chevron moves after it, to the row's end.\n */\n trailing?: ReactNode;\n /**\n * Trigger-only mode: the id of an element the CALLER renders elsewhere — the hidden\n * rows of a table, a panel in another column — which this header shows and hides.\n * The header's `aria-controls` points at it and the disclosure renders no body of\n * its own (`children`, `bodyClassName` and `keepMounted` are ignored). Pair it with\n * `open` / `onOpenChange`: the caller owns the state, since the caller renders what\n * it governs.\n */\n controls?: string;\n /** The body. Not rendered in trigger-only mode ({@link DisclosureProps.controls}). */\n children?: ReactNode;\n}\n\n/**\n * A section that opens in place: a header button with `aria-expanded` and\n * `aria-controls`, and a {@link Collapse} under it.\n *\n * Both apps had written this by hand — Lenkbank as a shared `CollapsibleCard` with ten\n * importers, Keksdose three separate times (accounts, twice; the support panel) — and\n * the copies had drifted: none of Keksdose's animated, and all three swapped a\n * `ChevronRight` for a `ChevronDown` rather than turning one. Here the chevron is one\n * icon that rotates, so the change of state is one element moving rather than two\n * trading places.\n *\n * The body is unmounted while shut; see {@link CollapseProps.keepMounted} for why that\n * is the default and when to opt out.\n */\nexport function Disclosure({\n title,\n hint,\n open: controlled,\n defaultOpen = false,\n onOpenChange,\n variant = \"card\",\n headingAs: Heading,\n keepMounted,\n disabled,\n headerClassName,\n bodyClassName,\n trailing,\n controls,\n className,\n children,\n ...rest\n}: DisclosureProps) {\n const [own, setOwn] = useState(defaultOpen);\n const open = controlled ?? own;\n const bodyId = useId();\n const card = variant === \"card\";\n const triggerOnly = controls !== undefined;\n // The card's header squares its lower corners only when a body opens under it.\n const joined = open && !triggerOnly;\n const hasTrailing = trailing !== undefined && trailing !== null && trailing !== false;\n\n const toggle = () => {\n const next = !open;\n if (controlled === undefined) setOwn(next);\n onOpenChange?.(next);\n };\n\n const button = (\n <button\n type=\"button\"\n aria-expanded={open}\n aria-controls={triggerOnly ? controls : bodyId}\n disabled={disabled}\n onClick={toggle}\n data-disclosure-trigger=\"\"\n className={cn(\n \"flex w-full gap-2 text-start outline-none disabled:cursor-not-allowed disabled:opacity-50\",\n hasTrailing\n ? // Stretched over the whole header row (the row is `relative`), so the space\n // round `trailing` and the card's chevron still toggle; the ring and the\n // card's hover paint on the stretched area / the row, not the text box.\n cn(\n \"min-w-0 flex-1 after:absolute after:inset-0 after:content-['']\",\n \"focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-[var(--brand)]\",\n card ? cn(\"after:rounded-lg\", joined && \"after:rounded-b-none\") : \"after:rounded-sm\",\n )\n : \"focus-visible:ring-2 focus-visible:ring-[var(--brand)]\",\n card\n ? cn(\n \"items-center justify-between rounded-lg p-4\",\n hasTrailing ? \"pe-0\" : \"hover:bg-[var(--bg-hover)] focus-visible:ring-inset\",\n joined && \"rounded-b-none\",\n )\n : \"items-center rounded-sm text-sm font-medium text-[var(--text-secondary)] hover:text-[var(--text-primary)]\",\n headerClassName,\n )}\n >\n {!card && <Chevron open={open} leading />}\n {/* `flex-1`: the title takes the row, so whatever a caller puts at its end sits\n at the header's far edge. */}\n <span className=\"min-w-0 flex-1\">\n <span className={cn(\"block\", card && \"text-sm font-semibold text-[var(--text-primary)]\")}>{title}</span>\n {hint !== undefined && (\n <span className=\"mt-0.5 block text-xs font-normal text-[var(--text-muted)]\">{hint}</span>\n )}\n </span>\n {card && !hasTrailing && <Chevron open={open} />}\n </button>\n );\n\n // Preflight already makes h1–h6 inherit size and weight, so the heading adds\n // structure and nothing visible.\n const header = Heading ? <Heading className={hasTrailing ? \"min-w-0 flex-1\" : undefined}>{button}</Heading> : button;\n\n return (\n <div\n {...rest}\n className={cn(card && \"rounded-lg border border-[var(--border)] bg-[var(--bg-surface)] shadow-sm\", className)}\n >\n {hasTrailing ? (\n <div\n className={cn(\n \"relative flex items-center gap-2\",\n card &&\n cn(\n \"rounded-lg pe-4 has-[[data-disclosure-trigger]:enabled:hover]:bg-[var(--bg-hover)]\",\n joined && \"rounded-b-none\",\n ),\n )}\n >\n {header}\n {/* Positioned, so it paints over the stretched button and takes its own\n clicks; the chevron is not, so a click on it lands on the button. */}\n <div className=\"relative flex shrink-0 items-center gap-2\">{trailing}</div>\n {card && <Chevron open={open} />}\n </div>\n ) : (\n header\n )}\n {!triggerOnly && (\n <Collapse id={bodyId} open={open} keepMounted={keepMounted}>\n <div className={cn(card ? \"space-y-3 px-4 pb-4\" : \"space-y-2 pt-2\", bodyClassName)}>{children}</div>\n </Collapse>\n )}\n </div>\n );\n}\n\n/**\n * One icon for both variants, turned rather than swapped. `leading` (bare) points it\n * along the reading direction while shut — right in LTR, left in RTL — and down when\n * open; trailing (card) points down while shut and up when open, which is the card\n * header's convention. Rotation, not a mirrored glyph, so RTL needs one opposite angle\n * and no `scale` composing with the turn.\n */\nfunction Chevron({ open, leading = false }: { open: boolean; leading?: boolean }) {\n return (\n <ChevronDown\n aria-hidden\n className={cn(\n \"shrink-0 text-[var(--text-muted)] transition-transform duration-200 ease-out motion-reduce:transition-none\",\n leading ? \"size-3.5\" : \"size-4\",\n leading ? !open && \"-rotate-90 rtl:rotate-90\" : open && \"rotate-180\",\n )}\n />\n );\n}\n"],"mappings":";AA8FM,cAgKA,YAhKA;AA9FN,SAAS,WAAW,OAAO,gBAAgB;AAE3C,SAAS,mBAAmB;AAE5B,SAAS,UAAU;AAInB,MAAM,cAAc;AAKpB,SAAS,uBAAgC;AACvC,SACE,OAAO,WAAW,eAClB,OAAO,OAAO,eAAe,cAC7B,OAAO,WAAW,kCAAkC,EAAE;AAE1D;AA2CO,SAAS,SAAS,EAAE,MAAM,cAAc,OAAO,UAAU,WAAW,OAAO,GAAG,KAAK,GAAkB;AAM1G,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,UAAU,WAAW,IAAI,SAAS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S,IAAI,QAAQ,MAAY,aAChC,8BAAC,SAAI,WAAW,GAAG,OAAO,wBAAwB,kBAAkB,aAAa,GAAI,UAAS,GAChG;AAAA;AAAA;AAAA,EAEJ;AAEJ;AASA,SAAS,QAAQ,EAAE,MAAM,UAAU,MAAM,GAAyC;AAChF,SACE;AAAA,IAAC;AAAA;AAAA,MACC,eAAW;AAAA,MACX,WAAW;AAAA,QACT;AAAA,QACA,UAAU,aAAa;AAAA,QACvB,UAAU,CAAC,QAAQ,6BAA6B,QAAQ;AAAA,MAC1D;AAAA;AAAA,EACF;AAEJ;","names":[]}
|
|
@@ -137,8 +137,12 @@ interface DropdownPanelProps extends ComponentPropsWithoutRef<"div"> {
|
|
|
137
137
|
panelRef?: RefObject<HTMLDivElement | null>;
|
|
138
138
|
/** Panel width in px, for the anchored form (the CSS `w-*` cannot be measured). */
|
|
139
139
|
width?: number;
|
|
140
|
-
/** Which of the panel's edges lines up with the trigger's, room permitting.
|
|
141
|
-
|
|
140
|
+
/** Which of the panel's edges lines up with the trigger's, room permitting.
|
|
141
|
+
* `start`/`end` follow the trigger's reading direction — `end` is the right edge
|
|
142
|
+
* in a left-to-right form and the left one in a right-to-left form — and are what
|
|
143
|
+
* the kit's own pickers pass; `left`/`right` stay physical. Default `end`, which
|
|
144
|
+
* is the old `right` in a left-to-right page. */
|
|
145
|
+
align?: "left" | "right" | "start" | "end";
|
|
142
146
|
children: ReactNode;
|
|
143
147
|
}
|
|
144
148
|
/**
|
|
@@ -150,7 +154,7 @@ interface DropdownPanelProps extends ComponentPropsWithoutRef<"div"> {
|
|
|
150
154
|
*
|
|
151
155
|
* Without `anchorRef` the panel is `position: absolute` inside whatever relative box
|
|
152
156
|
* the caller put it in, and the caller places it with `className` (`w-64`,
|
|
153
|
-
* `
|
|
157
|
+
* `end-0 top-full`). That is fine in a page that does not scroll around it, and
|
|
154
158
|
* wrong the moment an ancestor has `overflow` — the panel is then CLIPPED by that
|
|
155
159
|
* ancestor's box, with no error and no scrollbar, just a list with its side sliced
|
|
156
160
|
* off. Keksdose dev#548 is what that looks like in practice: the app's own content
|
|
@@ -7,6 +7,7 @@ import { useAnchoredPanel } from "../hooks/use-anchored-panel.js";
|
|
|
7
7
|
import { useEscapeKey, useOutsideClick } from "../hooks/use-dismiss.js";
|
|
8
8
|
import { useOverlayHistory } from "../hooks/use-overlay-history.js";
|
|
9
9
|
import { cn } from "../lib/cn.js";
|
|
10
|
+
import { useAnchorDir } from "./use-anchor-dir.js";
|
|
10
11
|
function useDropdown({
|
|
11
12
|
backCloses = true,
|
|
12
13
|
panelIsSheet = !backCloses
|
|
@@ -103,12 +104,13 @@ function DropdownPanel({
|
|
|
103
104
|
anchorRef,
|
|
104
105
|
panelRef,
|
|
105
106
|
width = 256,
|
|
106
|
-
align = "
|
|
107
|
+
align = "end",
|
|
107
108
|
children,
|
|
108
109
|
style,
|
|
109
110
|
...rest
|
|
110
111
|
}) {
|
|
111
112
|
const anchored = useAnchoredPanel(anchorRef ?? EMPTY_REF, Boolean(anchorRef));
|
|
113
|
+
const dir = useAnchorDir(anchorRef ?? EMPTY_REF, Boolean(anchorRef));
|
|
112
114
|
const body = /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
113
115
|
header,
|
|
114
116
|
/* @__PURE__ */ jsxs("ul", { ...listProps, className: cn("overflow-y-auto py-1", listProps?.className), children: [
|
|
@@ -134,7 +136,8 @@ function DropdownPanel({
|
|
|
134
136
|
}
|
|
135
137
|
const rect = anchored.rect;
|
|
136
138
|
if (!rect) return null;
|
|
137
|
-
const
|
|
139
|
+
const physical = align === "start" ? dir === "rtl" ? "right" : "left" : align === "end" ? dir === "rtl" ? "left" : "right" : align;
|
|
140
|
+
const wanted = physical === "right" ? rect.right - width : rect.left;
|
|
138
141
|
const left = Math.min(Math.max(8, wanted), window.innerWidth - width - 8);
|
|
139
142
|
return createPortal(
|
|
140
143
|
/* @__PURE__ */ jsx(
|
|
@@ -142,6 +145,7 @@ function DropdownPanel({
|
|
|
142
145
|
{
|
|
143
146
|
...rest,
|
|
144
147
|
ref: panelRef,
|
|
148
|
+
dir,
|
|
145
149
|
style: { ...style, position: "fixed", top: anchored.top, left, width, maxHeight: anchored.maxHeight },
|
|
146
150
|
className: cn(
|
|
147
151
|
"z-50 flex flex-col overflow-hidden rounded-md border border-[var(--border)] bg-[var(--bg-surface)] shadow-lg",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/dropdown.tsx"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport type {\n ComponentPropsWithoutRef,\n KeyboardEvent as ReactKeyboardEvent,\n ReactNode,\n RefObject,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { Search } from \"lucide-react\";\nimport { useAnchoredPanel } from \"../hooks/use-anchored-panel\";\nimport { useEscapeKey, useOutsideClick } from \"../hooks/use-dismiss\";\nimport { useOverlayHistory } from \"../hooks/use-overlay-history\";\nimport { cn } from \"../lib/cn\";\n\n/**\n * Open state + close-on-outside-click for the custom dropdowns (MultiSelect,\n * CurrencySelect, AmountInput's currency picker, Combobox). Attach `wrapperRef`\n * to the relatively-positioned container; the popover lives inside it so a click\n * anywhere else closes it.\n *\n * ## Back closes the list, not the page behind it\n *\n * Keksdose live #309 rework: *\"It shall only close it if it is prior open, and not\n * when I am seeing the dialog.\"* Round one wired {@link PickerSheet} — the shape\n * these lists take on a PHONE — into {@link useOverlayHistory}, and left the pointer\n * shape out. So on a desktop one Back press over an open list still went past it to\n * the dialog underneath: measured on his own budget, the transfer form's account list\n * was showing and Back took the entire add card, amount and all. That is the same\n * loss round one called *\"discarding an edit in progress in order to dismiss a\n * list\"*, in the other shell.\n *\n * Every dropdown built on this hook is dismissible and is the topmost thing on screen\n * while it is up, so the rule is the hook's rather than each caller's. `backCloses`\n * is for the ONE case where a second entry would be wrong: a caller whose panel is\n * itself a `PickerSheet`, which already registers one — both comboboxes swap shape at\n * {@link PHONE_QUERY}, and two entries would cost two Back presses to close one sheet.\n *\n * ## One outside-click rule for the whole package\n *\n * This hand-rolled a second document listener, on `mousedown`, months after\n * {@link useOutsideClick} — the hook the entity pickers dismiss through — was moved to\n * `pointerdown` for a reason that applies here word for word: on a touch platform\n * `mousedown` is SYNTHESISED, the browser emits it for most taps but is not obliged\n * to, and MultiSelect, CurrencySelect, GroupedPicker, AmountInput's currency picker\n * and both comboboxes all dismiss through this. Two copies of one rule is one copy\n * too many; this now delegates, so the package has a single answer to \"what is an\n * outside press\".\n *\n * `panelIsSheet` is what that delegation needs. A {@link PickerSheet} is modal and\n * fills the screen, so it has no outside — and being portalled to `<body>`, it is\n * inside neither `wrapperRef` nor `panelRef`, so a listener left running would read\n * every tap in it as a press outside and close it at finger-down. The sheet's own\n * `onMouseDown` stopPropagation guard used to hide that from this hook; it cannot\n * stop a `pointerdown`. It defaults to `!backCloses` because the two ask the same\n * question — \"is this caller's panel a sheet?\" — and the one caller that answers yes\n * already says so; they are separate props so a future caller can answer them apart.\n *\n * ## Escape, and where focus lands after it\n *\n * This hook had no Escape at all (the audit's §a11y): Back closed these lists, an\n * outside press closed them, and the one key every other dismissible surface in the\n * package answers to did nothing — so a keyboard user who opened a list had no way\n * out of it that did not also choose something. {@link useEscapeKey} is the listener\n * `Modal`, `Popover` and `useComboboxCore` already dismiss through, so the package\n * keeps one answer to \"what does Escape do\" rather than growing a fifth.\n *\n * Escape RESTORES FOCUS; an outside press does not. A press has already put focus\n * where the user pointed, and dragging it back from there would be the bug. Attach\n * `triggerRef` to the control that opens the panel and the keyboard paths — Escape,\n * Tab, a commit — hand focus back to it; leave it unattached and they simply close,\n * which is what the callers written before this get.\n */\nexport function useDropdown<T extends HTMLElement = HTMLDivElement>({\n backCloses = true,\n panelIsSheet = !backCloses,\n}: { backCloses?: boolean; panelIsSheet?: boolean } = {}) {\n const [open, setOpen] = useState(false);\n const wrapperRef = useRef<T>(null);\n // The control that opens the panel — see the note above on why only the keyboard\n // paths read it, and why attaching it is the caller's choice.\n const triggerRef = useRef<HTMLButtonElement>(null);\n // The panel, once it is PORTALLED (see {@link DropdownPanel}'s `anchorRef`): it is\n // then a child of <body> rather than of the wrapper, so \"did the click land inside\n // the wrapper\" answers no for every click on the list itself and the first option a\n // user picked closed the dropdown without picking anything.\n const panelRef = useRef<HTMLDivElement>(null);\n const close = useCallback(() => setOpen(false), []);\n // Closing unmounts whatever held focus — the search box, the row the keyboard was\n // on — and the browser then drops focus on <body>: the caret vanishes and the next\n // Tab restarts at the top of the document. Whoever closed the list with a key gets\n // it handed back to the trigger they opened it from.\n const closeToTrigger = useCallback(() => {\n setOpen(false);\n triggerRef.current?.focus();\n }, []);\n useOutsideClick([wrapperRef, panelRef], close, open && !panelIsSheet);\n useEscapeKey(closeToTrigger, open);\n // Same close path Escape and an outside click take, so a list dismissed by Back\n // cannot end up in a different state from one dismissed any other way.\n useOverlayHistory(open && backCloses, close);\n return { open, setOpen, wrapperRef, panelRef, triggerRef, closeToTrigger };\n}\n\n/**\n * {@link useDropdown} plus a search box: clears the query and focuses the search\n * input each time the panel opens, so typing filters immediately.\n */\nexport function useDropdownSearch<T extends HTMLElement = HTMLDivElement>() {\n const { open, setOpen, wrapperRef, panelRef, triggerRef, closeToTrigger } =\n useDropdown<T>();\n const [query, setQuery] = useState(\"\");\n const inputRef = useRef<HTMLInputElement>(null);\n useEffect(() => {\n if (open) {\n // eslint-disable-next-line react-hooks/set-state-in-effect -- reset the query on open\n setQuery(\"\");\n requestAnimationFrame(() => inputRef.current?.focus());\n }\n }, [open]);\n return {\n open,\n setOpen,\n wrapperRef,\n panelRef,\n triggerRef,\n closeToTrigger,\n query,\n setQuery,\n inputRef,\n };\n}\n\n/** `onKeyDown` is the INPUT's, not the wrapper's — the list's keyboard is handled\n * where the focus is (see the note above), so the div's own handler signature is\n * omitted in favour of it. */\nexport interface DropdownSearchHeaderProps\n extends Omit<ComponentPropsWithoutRef<\"div\">, \"onKeyDown\"> {\n query: string;\n onQueryChange: (v: string) => void;\n inputRef: RefObject<HTMLInputElement | null>;\n placeholder?: string;\n /** The `<ul role=\"listbox\">` this box filters. */\n listboxId?: string;\n /** The id of the option the arrow keys are currently on, if any. */\n activeId?: string;\n /** Arrow/Home/End/Enter/Tab — the list's keyboard, handled where the focus is. */\n onKeyDown?: (e: ReactKeyboardEvent<HTMLInputElement>) => void;\n}\n\n/** The search row (magnifier + text input) shared by the searchable dropdowns.\n *\n * The input had `outline-none` and nothing in its place (the audit's §a11y, the same\n * finding as the numpad's keys). That mattered more here than the bare class suggests:\n * {@link useDropdownSearch} focuses this box the moment a panel opens, so the caret is\n * the ONLY evidence of where the next keystroke goes — and a caret in an empty field\n * showing a placeholder is a single blinking pixel column. The ring is what says \"this\n * list is being typed into\"; it appears whenever the field holds focus, which for a\n * text input is exactly when it is true.\n *\n * ## Why this box is a plain textbox and the TRIGGER is the combobox\n *\n * The panels this header sits in are opened by a field-shaped trigger, and that\n * trigger is what carries `role=\"combobox\"` (see {@link MultiSelect},\n * {@link EntityCombobox}). Two comboboxes for one list would be one too many — a\n * reader tabbing back to the field would meet a second one describing the same\n * choice. So this stays a textbox, which ARIA lets own `aria-activedescendant` and\n * `aria-controls` exactly as a combobox does: focus is HERE while the list is up, so\n * this is what has to say which option the arrow keys are on.\n *\n * Pass `listboxId` and the wiring appears; omit it and the box is what it always\n * was, for the callers that have no listbox to point at. */\nexport function DropdownSearchHeader({\n query,\n onQueryChange,\n inputRef,\n placeholder,\n listboxId,\n activeId,\n onKeyDown,\n \"aria-label\": ariaLabel,\n className,\n ...rest\n}: DropdownSearchHeaderProps) {\n return (\n // `rest` dresses the header row; the NAME goes on the box below it. A search\n // input whose only name is its placeholder has none the moment a character is\n // typed into it — the placeholder disappears — which is why this is worth a prop\n // at all rather than something a caller could add from outside.\n <div\n {...rest}\n className={cn(\n \"flex items-center gap-2 border-b border-[var(--border)] px-2 py-1.5\",\n className,\n )}\n >\n <Search className=\"size-4 text-[var(--text-placeholder)]\" />\n <input\n ref={inputRef}\n type=\"text\"\n value={query}\n onChange={(e) => onQueryChange(e.target.value)}\n onKeyDown={onKeyDown}\n placeholder={placeholder}\n aria-label={ariaLabel}\n aria-controls={listboxId}\n aria-activedescendant={activeId}\n aria-autocomplete={listboxId ? \"list\" : undefined}\n className=\"w-full rounded-sm bg-transparent text-sm outline-none placeholder:text-[var(--text-placeholder)] text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--brand)]\"\n />\n </div>\n );\n}\n\nexport interface DropdownPanelProps extends ComponentPropsWithoutRef<\"div\"> {\n header?: ReactNode;\n empty?: boolean;\n /** Attributes for the `<ul>` itself — how a caller whose children are options\n * gives the list its `role=\"listbox\"`, its id and `aria-multiselectable`. The\n * panel owns the scrolling and the padding, so `className` here is merged rather\n * than replaced. */\n listProps?: ComponentPropsWithoutRef<\"ul\">;\n /** The trigger to hang off. Given, the panel portals and goes `fixed`. */\n anchorRef?: RefObject<HTMLElement | null>;\n /** {@link useDropdown}'s `panelRef`, so an outside-click sees this as inside. */\n panelRef?: RefObject<HTMLDivElement | null>;\n /** Panel width in px, for the anchored form (the CSS `w-*` cannot be measured). */\n width?: number;\n /** Which of the panel's edges lines up with the trigger's, room permitting. */\n align?: \"left\" | \"right\";\n children: ReactNode;\n}\n\n/**\n * The floating popover surface for the searchable dropdowns: bordered/shadowed\n * panel, an optional `header` slot (search box, plus any actions), and a\n * scrollable `<ul>` of `children` with an \"empty\" row when nothing matches.\n *\n * ## Anchored, or merely absolute\n *\n * Without `anchorRef` the panel is `position: absolute` inside whatever relative box\n * the caller put it in, and the caller places it with `className` (`w-64`,\n * `right-0 top-full`). That is fine in a page that does not scroll around it, and\n * wrong the moment an ancestor has `overflow` — the panel is then CLIPPED by that\n * ancestor's box, with no error and no scrollbar, just a list with its side sliced\n * off. Keksdose dev#548 is what that looks like in practice: the app's own content\n * scroller starts 280px from the left, the amount field's currency picker opens\n * right-aligned and 256px wide, and in the transaction row editor its left third —\n * the search box's first letter, and every row's currency symbol — was cut away.\n *\n * With `anchorRef` the panel is PORTALLED to `<body>` and positioned `fixed` against\n * that trigger's rect, so no ancestor can clip it: the same treatment {@link Popover}\n * already gives the calculator, and the same reason. It re-aligns on scroll and\n * resize, flips above the trigger when the room is there instead (a phone keyboard\n * eats the bottom of the screen), and is clamped to the viewport's edges so a trigger\n * near either side cannot push it off-screen.\n *\n * Pass `panelRef` from {@link useDropdown} along with it: once portalled the panel is\n * no longer inside the wrapper, so the outside-click handler has to be told about it\n * or the first click on an option closes the list instead of choosing from it.\n */\nexport function DropdownPanel({\n header,\n empty,\n className,\n listProps,\n anchorRef,\n panelRef,\n width = 256,\n align = \"right\",\n children,\n style,\n ...rest\n}: DropdownPanelProps) {\n const anchored = useAnchoredPanel(anchorRef ?? EMPTY_REF, Boolean(anchorRef));\n const body = (\n <>\n {header}\n {/* The anchored form caps its own height against the VISIBLE viewport and lets\n this list have the rest; the absolute form keeps the fixed `max-h-64` it has\n always had, applied by the wrapper below. */}\n <ul {...listProps} className={cn(\"overflow-y-auto py-1\", listProps?.className)}>\n {children}\n {/* `presentation`, so that a caller who made this list a `listbox` does not\n end up with one child that is not an option. The em dash still reads — it\n is the row's semantics that are dropped, not its text. */}\n {empty && (\n <li role=\"presentation\" className=\"px-3 py-2 text-sm text-[var(--text-muted)]\">\n —\n </li>\n )}\n </ul>\n </>\n );\n\n if (!anchorRef) {\n return (\n <div\n {...rest}\n style={style}\n ref={panelRef}\n className={cn(\n \"absolute z-30 mt-1 rounded-md border border-[var(--border)] bg-[var(--bg-surface)] shadow-lg\",\n \"[&>ul]:max-h-64\",\n className,\n )}\n >\n {body}\n </div>\n );\n }\n\n const rect = anchored.rect;\n if (!rect) return null;\n // Clamped exactly as `Popover` clamps: the panel may leave the trigger's edge to\n // stay on screen, because a list half off the viewport is the bug this exists for.\n const wanted = align === \"right\" ? rect.right - width : rect.left;\n const left = Math.min(Math.max(8, wanted), window.innerWidth - width - 8);\n return createPortal(\n <div\n {...rest}\n ref={panelRef}\n // The caller's `style` is kept underneath, but the placement is measured rather\n // than chosen (dev#548: an `overflow` ancestor clipped a third of this panel\n // away), so those five values are the panel's own.\n style={{ ...style, position: \"fixed\", top: anchored.top, left, width, maxHeight: anchored.maxHeight }}\n className={cn(\n \"z-50 flex flex-col overflow-hidden rounded-md border border-[var(--border)] bg-[var(--bg-surface)] shadow-lg\",\n // The list, not the panel, is what scrolls: the search header has to stay put\n // while the options move under it.\n \"[&>ul]:min-h-0 [&>ul]:flex-1\",\n className,\n )}\n >\n {body}\n </div>,\n document.body,\n );\n}\n\n/** A ref that is always null, for the un-anchored form — hooks may not be conditional. */\nconst EMPTY_REF: RefObject<HTMLElement | null> = { current: null };\n"],"mappings":";AA4LI,SAuFA,UAhFE,KAPF;AA5LJ,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAOzD,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,wBAAwB;AACjC,SAAS,cAAc,uBAAuB;AAC9C,SAAS,yBAAyB;AAClC,SAAS,UAAU;AA4DZ,SAAS,YAAoD;AAAA,EAClE,aAAa;AAAA,EACb,eAAe,CAAC;AAClB,IAAsD,CAAC,GAAG;AACxD,QAAM,CAAC,MAAM,OAAO,IAAI,SAAS,KAAK;AACtC,QAAM,aAAa,OAAU,IAAI;AAGjC,QAAM,aAAa,OAA0B,IAAI;AAKjD,QAAM,WAAW,OAAuB,IAAI;AAC5C,QAAM,QAAQ,YAAY,MAAM,QAAQ,KAAK,GAAG,CAAC,CAAC;AAKlD,QAAM,iBAAiB,YAAY,MAAM;AACvC,YAAQ,KAAK;AACb,eAAW,SAAS,MAAM;AAAA,EAC5B,GAAG,CAAC,CAAC;AACL,kBAAgB,CAAC,YAAY,QAAQ,GAAG,OAAO,QAAQ,CAAC,YAAY;AACpE,eAAa,gBAAgB,IAAI;AAGjC,oBAAkB,QAAQ,YAAY,KAAK;AAC3C,SAAO,EAAE,MAAM,SAAS,YAAY,UAAU,YAAY,eAAe;AAC3E;AAMO,SAAS,oBAA4D;AAC1E,QAAM,EAAE,MAAM,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AAiB,aAAa,WAAW,QAAQ,SAAS,CAAC;AAC5E,QAAM,OACJ,iCACG;AAAA;AAAA,IAID,qBAAC,QAAI,GAAG,WAAW,WAAW,GAAG,wBAAwB,WAAW,SAAS,GAC1E;AAAA;AAAA,MAIA,SACC,oBAAC,QAAG,MAAK,gBAAe,WAAU,8CAA6C,oBAE/E;AAAA,OAEJ;AAAA,KACF;AAGF,MAAI,CAAC,WAAW;AACd,WACE;AAAA,MAAC;AAAA;AAAA,QACE,GAAG;AAAA,QACJ;AAAA,QACA,KAAK;AAAA,QACL,WAAW;AAAA,UACT;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,QAEC;AAAA;AAAA,IACH;AAAA,EAEJ;AAEA,QAAM,OAAO,SAAS;AACtB,MAAI,CAAC,KAAM,QAAO;AAGlB,QAAM,SAAS,UAAU,UAAU,KAAK,QAAQ,QAAQ,KAAK;AAC7D,QAAM,OAAO,KAAK,IAAI,KAAK,IAAI,GAAG,MAAM,GAAG,OAAO,aAAa,QAAQ,CAAC;AACxE,SAAO;AAAA,IACL;AAAA,MAAC;AAAA;AAAA,QACE,GAAG;AAAA,QACJ,KAAK;AAAA,QAIL,OAAO,EAAE,GAAG,OAAO,UAAU,SAAS,KAAK,SAAS,KAAK,MAAM,OAAO,WAAW,SAAS,UAAU;AAAA,QACpG,WAAW;AAAA,UACT;AAAA;AAAA;AAAA,UAGA;AAAA,UACA;AAAA,QACF;AAAA,QAEC;AAAA;AAAA,IACH;AAAA,IACA,SAAS;AAAA,EACX;AACF;AAGA,MAAM,YAA2C,EAAE,SAAS,KAAK;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/dropdown.tsx"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport type {\n ComponentPropsWithoutRef,\n KeyboardEvent as ReactKeyboardEvent,\n ReactNode,\n RefObject,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { Search } from \"lucide-react\";\nimport { useAnchoredPanel } from \"../hooks/use-anchored-panel\";\nimport { useEscapeKey, useOutsideClick } from \"../hooks/use-dismiss\";\nimport { useOverlayHistory } from \"../hooks/use-overlay-history\";\nimport { cn } from \"../lib/cn\";\nimport { useAnchorDir } from \"./use-anchor-dir\";\n\n/**\n * Open state + close-on-outside-click for the custom dropdowns (MultiSelect,\n * CurrencySelect, AmountInput's currency picker, Combobox). Attach `wrapperRef`\n * to the relatively-positioned container; the popover lives inside it so a click\n * anywhere else closes it.\n *\n * ## Back closes the list, not the page behind it\n *\n * Keksdose live #309 rework: *\"It shall only close it if it is prior open, and not\n * when I am seeing the dialog.\"* Round one wired {@link PickerSheet} — the shape\n * these lists take on a PHONE — into {@link useOverlayHistory}, and left the pointer\n * shape out. So on a desktop one Back press over an open list still went past it to\n * the dialog underneath: measured on his own budget, the transfer form's account list\n * was showing and Back took the entire add card, amount and all. That is the same\n * loss round one called *\"discarding an edit in progress in order to dismiss a\n * list\"*, in the other shell.\n *\n * Every dropdown built on this hook is dismissible and is the topmost thing on screen\n * while it is up, so the rule is the hook's rather than each caller's. `backCloses`\n * is for the ONE case where a second entry would be wrong: a caller whose panel is\n * itself a `PickerSheet`, which already registers one — both comboboxes swap shape at\n * {@link PHONE_QUERY}, and two entries would cost two Back presses to close one sheet.\n *\n * ## One outside-click rule for the whole package\n *\n * This hand-rolled a second document listener, on `mousedown`, months after\n * {@link useOutsideClick} — the hook the entity pickers dismiss through — was moved to\n * `pointerdown` for a reason that applies here word for word: on a touch platform\n * `mousedown` is SYNTHESISED, the browser emits it for most taps but is not obliged\n * to, and MultiSelect, CurrencySelect, GroupedPicker, AmountInput's currency picker\n * and both comboboxes all dismiss through this. Two copies of one rule is one copy\n * too many; this now delegates, so the package has a single answer to \"what is an\n * outside press\".\n *\n * `panelIsSheet` is what that delegation needs. A {@link PickerSheet} is modal and\n * fills the screen, so it has no outside — and being portalled to `<body>`, it is\n * inside neither `wrapperRef` nor `panelRef`, so a listener left running would read\n * every tap in it as a press outside and close it at finger-down. The sheet's own\n * `onMouseDown` stopPropagation guard used to hide that from this hook; it cannot\n * stop a `pointerdown`. It defaults to `!backCloses` because the two ask the same\n * question — \"is this caller's panel a sheet?\" — and the one caller that answers yes\n * already says so; they are separate props so a future caller can answer them apart.\n *\n * ## Escape, and where focus lands after it\n *\n * This hook had no Escape at all (the audit's §a11y): Back closed these lists, an\n * outside press closed them, and the one key every other dismissible surface in the\n * package answers to did nothing — so a keyboard user who opened a list had no way\n * out of it that did not also choose something. {@link useEscapeKey} is the listener\n * `Modal`, `Popover` and `useComboboxCore` already dismiss through, so the package\n * keeps one answer to \"what does Escape do\" rather than growing a fifth.\n *\n * Escape RESTORES FOCUS; an outside press does not. A press has already put focus\n * where the user pointed, and dragging it back from there would be the bug. Attach\n * `triggerRef` to the control that opens the panel and the keyboard paths — Escape,\n * Tab, a commit — hand focus back to it; leave it unattached and they simply close,\n * which is what the callers written before this get.\n */\nexport function useDropdown<T extends HTMLElement = HTMLDivElement>({\n backCloses = true,\n panelIsSheet = !backCloses,\n}: { backCloses?: boolean; panelIsSheet?: boolean } = {}) {\n const [open, setOpen] = useState(false);\n const wrapperRef = useRef<T>(null);\n // The control that opens the panel — see the note above on why only the keyboard\n // paths read it, and why attaching it is the caller's choice.\n const triggerRef = useRef<HTMLButtonElement>(null);\n // The panel, once it is PORTALLED (see {@link DropdownPanel}'s `anchorRef`): it is\n // then a child of <body> rather than of the wrapper, so \"did the click land inside\n // the wrapper\" answers no for every click on the list itself and the first option a\n // user picked closed the dropdown without picking anything.\n const panelRef = useRef<HTMLDivElement>(null);\n const close = useCallback(() => setOpen(false), []);\n // Closing unmounts whatever held focus — the search box, the row the keyboard was\n // on — and the browser then drops focus on <body>: the caret vanishes and the next\n // Tab restarts at the top of the document. Whoever closed the list with a key gets\n // it handed back to the trigger they opened it from.\n const closeToTrigger = useCallback(() => {\n setOpen(false);\n triggerRef.current?.focus();\n }, []);\n useOutsideClick([wrapperRef, panelRef], close, open && !panelIsSheet);\n useEscapeKey(closeToTrigger, open);\n // Same close path Escape and an outside click take, so a list dismissed by Back\n // cannot end up in a different state from one dismissed any other way.\n useOverlayHistory(open && backCloses, close);\n return { open, setOpen, wrapperRef, panelRef, triggerRef, closeToTrigger };\n}\n\n/**\n * {@link useDropdown} plus a search box: clears the query and focuses the search\n * input each time the panel opens, so typing filters immediately.\n */\nexport function useDropdownSearch<T extends HTMLElement = HTMLDivElement>() {\n const { open, setOpen, wrapperRef, panelRef, triggerRef, closeToTrigger } =\n useDropdown<T>();\n const [query, setQuery] = useState(\"\");\n const inputRef = useRef<HTMLInputElement>(null);\n useEffect(() => {\n if (open) {\n // eslint-disable-next-line react-hooks/set-state-in-effect -- reset the query on open\n setQuery(\"\");\n requestAnimationFrame(() => inputRef.current?.focus());\n }\n }, [open]);\n return {\n open,\n setOpen,\n wrapperRef,\n panelRef,\n triggerRef,\n closeToTrigger,\n query,\n setQuery,\n inputRef,\n };\n}\n\n/** `onKeyDown` is the INPUT's, not the wrapper's — the list's keyboard is handled\n * where the focus is (see the note above), so the div's own handler signature is\n * omitted in favour of it. */\nexport interface DropdownSearchHeaderProps\n extends Omit<ComponentPropsWithoutRef<\"div\">, \"onKeyDown\"> {\n query: string;\n onQueryChange: (v: string) => void;\n inputRef: RefObject<HTMLInputElement | null>;\n placeholder?: string;\n /** The `<ul role=\"listbox\">` this box filters. */\n listboxId?: string;\n /** The id of the option the arrow keys are currently on, if any. */\n activeId?: string;\n /** Arrow/Home/End/Enter/Tab — the list's keyboard, handled where the focus is. */\n onKeyDown?: (e: ReactKeyboardEvent<HTMLInputElement>) => void;\n}\n\n/** The search row (magnifier + text input) shared by the searchable dropdowns.\n *\n * The input had `outline-none` and nothing in its place (the audit's §a11y, the same\n * finding as the numpad's keys). That mattered more here than the bare class suggests:\n * {@link useDropdownSearch} focuses this box the moment a panel opens, so the caret is\n * the ONLY evidence of where the next keystroke goes — and a caret in an empty field\n * showing a placeholder is a single blinking pixel column. The ring is what says \"this\n * list is being typed into\"; it appears whenever the field holds focus, which for a\n * text input is exactly when it is true.\n *\n * ## Why this box is a plain textbox and the TRIGGER is the combobox\n *\n * The panels this header sits in are opened by a field-shaped trigger, and that\n * trigger is what carries `role=\"combobox\"` (see {@link MultiSelect},\n * {@link EntityCombobox}). Two comboboxes for one list would be one too many — a\n * reader tabbing back to the field would meet a second one describing the same\n * choice. So this stays a textbox, which ARIA lets own `aria-activedescendant` and\n * `aria-controls` exactly as a combobox does: focus is HERE while the list is up, so\n * this is what has to say which option the arrow keys are on.\n *\n * Pass `listboxId` and the wiring appears; omit it and the box is what it always\n * was, for the callers that have no listbox to point at. */\nexport function DropdownSearchHeader({\n query,\n onQueryChange,\n inputRef,\n placeholder,\n listboxId,\n activeId,\n onKeyDown,\n \"aria-label\": ariaLabel,\n className,\n ...rest\n}: DropdownSearchHeaderProps) {\n return (\n // `rest` dresses the header row; the NAME goes on the box below it. A search\n // input whose only name is its placeholder has none the moment a character is\n // typed into it — the placeholder disappears — which is why this is worth a prop\n // at all rather than something a caller could add from outside.\n <div\n {...rest}\n className={cn(\n \"flex items-center gap-2 border-b border-[var(--border)] px-2 py-1.5\",\n className,\n )}\n >\n <Search className=\"size-4 text-[var(--text-placeholder)]\" />\n <input\n ref={inputRef}\n type=\"text\"\n value={query}\n onChange={(e) => onQueryChange(e.target.value)}\n onKeyDown={onKeyDown}\n placeholder={placeholder}\n aria-label={ariaLabel}\n aria-controls={listboxId}\n aria-activedescendant={activeId}\n aria-autocomplete={listboxId ? \"list\" : undefined}\n className=\"w-full rounded-sm bg-transparent text-sm outline-none placeholder:text-[var(--text-placeholder)] text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--brand)]\"\n />\n </div>\n );\n}\n\nexport interface DropdownPanelProps extends ComponentPropsWithoutRef<\"div\"> {\n header?: ReactNode;\n empty?: boolean;\n /** Attributes for the `<ul>` itself — how a caller whose children are options\n * gives the list its `role=\"listbox\"`, its id and `aria-multiselectable`. The\n * panel owns the scrolling and the padding, so `className` here is merged rather\n * than replaced. */\n listProps?: ComponentPropsWithoutRef<\"ul\">;\n /** The trigger to hang off. Given, the panel portals and goes `fixed`. */\n anchorRef?: RefObject<HTMLElement | null>;\n /** {@link useDropdown}'s `panelRef`, so an outside-click sees this as inside. */\n panelRef?: RefObject<HTMLDivElement | null>;\n /** Panel width in px, for the anchored form (the CSS `w-*` cannot be measured). */\n width?: number;\n /** Which of the panel's edges lines up with the trigger's, room permitting.\n * `start`/`end` follow the trigger's reading direction — `end` is the right edge\n * in a left-to-right form and the left one in a right-to-left form — and are what\n * the kit's own pickers pass; `left`/`right` stay physical. Default `end`, which\n * is the old `right` in a left-to-right page. */\n align?: \"left\" | \"right\" | \"start\" | \"end\";\n children: ReactNode;\n}\n\n/**\n * The floating popover surface for the searchable dropdowns: bordered/shadowed\n * panel, an optional `header` slot (search box, plus any actions), and a\n * scrollable `<ul>` of `children` with an \"empty\" row when nothing matches.\n *\n * ## Anchored, or merely absolute\n *\n * Without `anchorRef` the panel is `position: absolute` inside whatever relative box\n * the caller put it in, and the caller places it with `className` (`w-64`,\n * `end-0 top-full`). That is fine in a page that does not scroll around it, and\n * wrong the moment an ancestor has `overflow` — the panel is then CLIPPED by that\n * ancestor's box, with no error and no scrollbar, just a list with its side sliced\n * off. Keksdose dev#548 is what that looks like in practice: the app's own content\n * scroller starts 280px from the left, the amount field's currency picker opens\n * right-aligned and 256px wide, and in the transaction row editor its left third —\n * the search box's first letter, and every row's currency symbol — was cut away.\n *\n * With `anchorRef` the panel is PORTALLED to `<body>` and positioned `fixed` against\n * that trigger's rect, so no ancestor can clip it: the same treatment {@link Popover}\n * already gives the calculator, and the same reason. It re-aligns on scroll and\n * resize, flips above the trigger when the room is there instead (a phone keyboard\n * eats the bottom of the screen), and is clamped to the viewport's edges so a trigger\n * near either side cannot push it off-screen.\n *\n * Pass `panelRef` from {@link useDropdown} along with it: once portalled the panel is\n * no longer inside the wrapper, so the outside-click handler has to be told about it\n * or the first click on an option closes the list instead of choosing from it.\n */\nexport function DropdownPanel({\n header,\n empty,\n className,\n listProps,\n anchorRef,\n panelRef,\n width = 256,\n align = \"end\",\n children,\n style,\n ...rest\n}: DropdownPanelProps) {\n const anchored = useAnchoredPanel(anchorRef ?? EMPTY_REF, Boolean(anchorRef));\n const dir = useAnchorDir(anchorRef ?? EMPTY_REF, Boolean(anchorRef));\n const body = (\n <>\n {header}\n {/* The anchored form caps its own height against the VISIBLE viewport and lets\n this list have the rest; the absolute form keeps the fixed `max-h-64` it has\n always had, applied by the wrapper below. */}\n <ul {...listProps} className={cn(\"overflow-y-auto py-1\", listProps?.className)}>\n {children}\n {/* `presentation`, so that a caller who made this list a `listbox` does not\n end up with one child that is not an option. The em dash still reads — it\n is the row's semantics that are dropped, not its text. */}\n {empty && (\n <li role=\"presentation\" className=\"px-3 py-2 text-sm text-[var(--text-muted)]\">\n —\n </li>\n )}\n </ul>\n </>\n );\n\n if (!anchorRef) {\n return (\n <div\n {...rest}\n style={style}\n ref={panelRef}\n className={cn(\n \"absolute z-30 mt-1 rounded-md border border-[var(--border)] bg-[var(--bg-surface)] shadow-lg\",\n \"[&>ul]:max-h-64\",\n className,\n )}\n >\n {body}\n </div>\n );\n }\n\n const rect = anchored.rect;\n if (!rect) return null;\n // Clamped exactly as `Popover` clamps: the panel may leave the trigger's edge to\n // stay on screen, because a list half off the viewport is the bug this exists for.\n // The portal leaves the subtree the trigger's `dir` came from, so it is read off\n // the trigger — for the alignment here, and for the panel's own `dir` below,\n // without which a right-to-left form got a left-to-right list.\n const physical =\n align === \"start\" ? (dir === \"rtl\" ? \"right\" : \"left\") : align === \"end\" ? (dir === \"rtl\" ? \"left\" : \"right\") : align;\n const wanted = physical === \"right\" ? rect.right - width : rect.left;\n const left = Math.min(Math.max(8, wanted), window.innerWidth - width - 8);\n return createPortal(\n <div\n {...rest}\n ref={panelRef}\n dir={dir}\n // The caller's `style` is kept underneath, but the placement is measured rather\n // than chosen (dev#548: an `overflow` ancestor clipped a third of this panel\n // away), so those five values are the panel's own.\n style={{ ...style, position: \"fixed\", top: anchored.top, left, width, maxHeight: anchored.maxHeight }}\n className={cn(\n \"z-50 flex flex-col overflow-hidden rounded-md border border-[var(--border)] bg-[var(--bg-surface)] shadow-lg\",\n // The list, not the panel, is what scrolls: the search header has to stay put\n // while the options move under it.\n \"[&>ul]:min-h-0 [&>ul]:flex-1\",\n className,\n )}\n >\n {body}\n </div>,\n document.body,\n );\n}\n\n/** A ref that is always null, for the un-anchored form — hooks may not be conditional. */\nconst EMPTY_REF: RefObject<HTMLElement | null> = { current: null };\n"],"mappings":";AA6LI,SA4FA,UArFE,KAPF;AA7LJ,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAOzD,SAAS,oBAAoB;AAC7B,SAAS,cAAc;AACvB,SAAS,wBAAwB;AACjC,SAAS,cAAc,uBAAuB;AAC9C,SAAS,yBAAyB;AAClC,SAAS,UAAU;AACnB,SAAS,oBAAoB;AA4DtB,SAAS,YAAoD;AAAA,EAClE,aAAa;AAAA,EACb,eAAe,CAAC;AAClB,IAAsD,CAAC,GAAG;AACxD,QAAM,CAAC,MAAM,OAAO,IAAI,SAAS,KAAK;AACtC,QAAM,aAAa,OAAU,IAAI;AAGjC,QAAM,aAAa,OAA0B,IAAI;AAKjD,QAAM,WAAW,OAAuB,IAAI;AAC5C,QAAM,QAAQ,YAAY,MAAM,QAAQ,KAAK,GAAG,CAAC,CAAC;AAKlD,QAAM,iBAAiB,YAAY,MAAM;AACvC,YAAQ,KAAK;AACb,eAAW,SAAS,MAAM;AAAA,EAC5B,GAAG,CAAC,CAAC;AACL,kBAAgB,CAAC,YAAY,QAAQ,GAAG,OAAO,QAAQ,CAAC,YAAY;AACpE,eAAa,gBAAgB,IAAI;AAGjC,oBAAkB,QAAQ,YAAY,KAAK;AAC3C,SAAO,EAAE,MAAM,SAAS,YAAY,UAAU,YAAY,eAAe;AAC3E;AAMO,SAAS,oBAA4D;AAC1E,QAAM,EAAE,MAAM,SAAS,YAAY,UAAU,YAAY,eAAe,IACtE,Y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} from './combobox-core.js';
|
|
3
|
+
import { ComboClearValue, ComboOption } from './combobox-core.js';
|
|
4
4
|
import '../hooks/use-anchored-rect.js';
|
|
5
5
|
import '../hooks/use-anchored-panel.js';
|
|
6
6
|
|
|
7
7
|
/** `onChange` is the kit's — "a selection was made", carrying values — rather
|
|
8
8
|
* than the div's form event, so the DOM's spelling of it is omitted. */
|
|
9
|
-
interface EntityComboboxProps<V extends string | number> extends Omit<ComponentPropsWithoutRef<"div">, "onChange"> {
|
|
10
|
-
/** Selected id
|
|
11
|
-
value: V | null | undefined;
|
|
12
|
-
/** Selecting an option emits its value; the clear button emits `
|
|
13
|
-
onChange: (value: V |
|
|
9
|
+
interface EntityComboboxProps<V extends string | number, C extends ComboClearValue = null> extends Omit<ComponentPropsWithoutRef<"div">, "onChange"> {
|
|
10
|
+
/** Selected id; `null`, `undefined` or `clearValue` when nothing is selected. */
|
|
11
|
+
value: V | C | null | undefined;
|
|
12
|
+
/** Selecting an option emits its value; the clear button emits `clearValue`. */
|
|
13
|
+
onChange: (value: V | C) => void;
|
|
14
|
+
/**
|
|
15
|
+
* What the clear button emits. Default `null`. Pass `""` for a form whose schema
|
|
16
|
+
* wants an empty string for "no choice" (a zod `z.string()` field), rather than
|
|
17
|
+
* mapping `null` in every `onChange` — the type of `onChange` follows it, so the
|
|
18
|
+
* mapping cannot be forgotten on one field and not another. The picker also reads
|
|
19
|
+
* the value back as empty, so `value=""` shows the placeholder and no "×".
|
|
20
|
+
* See {@link ComboClearValue} for why the choice is closed.
|
|
21
|
+
*/
|
|
22
|
+
clearValue?: C;
|
|
14
23
|
/** Already-loaded options (client-side filtered). Also used to resolve the
|
|
15
24
|
* trigger label for the current `value`. */
|
|
16
25
|
options?: ComboOption<V>[];
|
|
@@ -59,6 +68,6 @@ interface EntityComboboxProps<V extends string | number> extends Omit<ComponentP
|
|
|
59
68
|
* the shared field/anchor/dismiss/search primitives (no cmdk/Radix). For picking
|
|
60
69
|
* several entities use {@link MultiEntityCombobox}.
|
|
61
70
|
*/
|
|
62
|
-
declare function EntityCombobox<V extends string | number>({ value, onChange, options, loadOptions, loading, label, placeholder, searchPlaceholder, emptyLabel, clearable, clearLabel, closeLabel, disabled, onCreate, createLabel, className, invalid, error, filter, minChars, debounceMs, loadErrorLabel, "aria-label": ariaLabel, ...rest }: EntityComboboxProps<V>): react.JSX.Element;
|
|
71
|
+
declare function EntityCombobox<V extends string | number, C extends ComboClearValue = null>({ value, onChange, clearValue, options, loadOptions, loading, label, placeholder, searchPlaceholder, emptyLabel, clearable, clearLabel, closeLabel, disabled, onCreate, createLabel, className, invalid, error, filter, minChars, debounceMs, loadErrorLabel, "aria-label": ariaLabel, ...rest }: EntityComboboxProps<V, C>): react.JSX.Element;
|
|
63
72
|
|
|
64
|
-
export { ComboOption, EntityCombobox, type EntityComboboxProps };
|
|
73
|
+
export { ComboClearValue, ComboOption, EntityCombobox, type EntityComboboxProps };
|
|
@@ -13,6 +13,7 @@ import { DEFAULT_COMBOBOX_LABELS, DEFAULT_COMMON_LABELS, useKitLabels } from "..
|
|
|
13
13
|
function EntityCombobox({
|
|
14
14
|
value,
|
|
15
15
|
onChange,
|
|
16
|
+
clearValue = null,
|
|
16
17
|
options,
|
|
17
18
|
loadOptions,
|
|
18
19
|
loading,
|
|
@@ -54,10 +55,11 @@ function EntityCombobox({
|
|
|
54
55
|
const common = useKitLabels("common", DEFAULT_COMMON_LABELS);
|
|
55
56
|
const { open, results, resolve, setOpen } = core;
|
|
56
57
|
const listboxId = useId();
|
|
57
|
-
const
|
|
58
|
+
const chosen = value == null || value === clearValue ? null : value;
|
|
59
|
+
const selectedOption = chosen == null ? null : resolve(chosen);
|
|
58
60
|
const q = core.query.trim();
|
|
59
61
|
const showCreate = Boolean(onCreate) && q.length > 0 && !results.some((o) => o.label.toLowerCase() === q.toLowerCase());
|
|
60
|
-
const showClear = Boolean(clearable &&
|
|
62
|
+
const showClear = Boolean(clearable && chosen != null && !disabled);
|
|
61
63
|
const triggerText = selectedOption?.label ?? placeholder ?? "";
|
|
62
64
|
const choose = (o) => {
|
|
63
65
|
core.cacheRef.current.set(o.value, o);
|
|
@@ -93,7 +95,7 @@ function EntityCombobox({
|
|
|
93
95
|
},
|
|
94
96
|
className: cn(
|
|
95
97
|
FIELD_TRIGGER,
|
|
96
|
-
"
|
|
98
|
+
"pe-9",
|
|
97
99
|
label !== void 0 && FIELD_FLOATING_PAD,
|
|
98
100
|
disabled && "cursor-not-allowed opacity-50",
|
|
99
101
|
field.isInvalid && FIELD_INVALID
|
|
@@ -127,9 +129,9 @@ function EntityCombobox({
|
|
|
127
129
|
"aria-label": labels.clear,
|
|
128
130
|
onClick: (e) => {
|
|
129
131
|
e.stopPropagation();
|
|
130
|
-
onChange(
|
|
132
|
+
onChange(clearValue);
|
|
131
133
|
},
|
|
132
|
-
className: "absolute
|
|
134
|
+
className: "absolute end-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-[var(--text-placeholder)] hover:text-[var(--text-secondary)]",
|
|
133
135
|
children: /* @__PURE__ */ jsx(X, { className: "size-4" })
|
|
134
136
|
}
|
|
135
137
|
) : /* @__PURE__ */ jsx(FieldChevron, {})
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/entity-combobox.tsx"],"sourcesContent":["import { useId } from \"react\";\nimport type { ComponentPropsWithoutRef, ReactNode } from \"react\";\nimport { X } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport { FieldChevron, FieldLabel, FIELD_TRIGGER, FIELD_FLOATING_PAD, FIELD_INVALID } from \"./ui\";\nimport {\n ComboboxPanel,\n useComboboxCore,\n useComboboxFieldError,\n type ComboOption,\n} from \"./combobox-core\";\nimport { DEFAULT_COMBOBOX_LABELS, DEFAULT_COMMON_LABELS, useKitLabels } from \"../i18n/kit-labels\";\n\nexport type { ComboOption } from \"./combobox-core\";\n\n/** `onChange` is the kit's — \"a selection was made\", carrying values — rather\n * than the div's form event, so the DOM's spelling of it is omitted. */\nexport interface EntityComboboxProps<V extends string | number>\n extends Omit<ComponentPropsWithoutRef<\"div\">, \"onChange\"> {\n /** Selected id, or null/undefined when nothing is selected. */\n value: V | null | undefined;\n /** Selecting an option emits its value; the clear button emits `null`. */\n onChange: (value: V | null) => void;\n /** Already-loaded options (client-side filtered). Also used to resolve the\n * trigger label for the current `value`. */\n options?: ComboOption<V>[];\n /** Async option source, debounced and called on open + as the query changes\n * (at `minChars` and up). Stale responses are ignored; a rejection empties the\n * list and says `loadErrorLabel` instead of leaving the last query's rows up. When set, `options` is used only for label\n * resolution, not as the result list. */\n loadOptions?: (query: string) => Promise<ComboOption<V>[]>;\n /** External loading flag (OR-ed with the internal async state). */\n loading?: boolean;\n label?: ReactNode;\n placeholder?: string;\n searchPlaceholder?: string;\n emptyLabel?: string;\n clearable?: boolean;\n clearLabel?: string;\n /** The phone sheet's close button. Its own prop rather than a reuse of\n * `clearLabel`: \"clear the selection\" and \"close this screen\" are different\n * actions, and on a full-screen sheet the close button is the only way out —\n * so it is the one control here that MUST be in the reader's language. */\n closeLabel?: string;\n disabled?: boolean;\n /** When set, a \"create\" row appears for a non-empty query with no exact match. */\n onCreate?: (query: string) => void;\n createLabel?: (query: string) => string;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\n /** What is wrong with the value, as {@link Input}'s `error`: rendered under the\n * field, on the trigger's `aria-describedby`, and implies `invalid`. */\n error?: ReactNode;\n /** Narrow `options` client-side by the query. Default `true`; `false` shows them\n * as given (a server-ranked list). */\n filter?: boolean;\n /** Offer nothing, and call no `loadOptions`, below this many characters. Default\n * `0`, i.e. the list loads as the panel opens. */\n minChars?: number;\n /** `loadOptions` debounce. Default 150 ms. */\n debounceMs?: number;\n /** Shown when `loadOptions` rejects. Default: `combobox.loadError`. */\n loadErrorLabel?: string;\n}\n\n/**\n * An id-keyed, searchable entity picker: a field-styled trigger showing the\n * selected item's label, and a portalled dropdown of `{label, sublabel, icon}`\n * options — loaded up front via `options` or lazily via `loadOptions`. Built on\n * the shared field/anchor/dismiss/search primitives (no cmdk/Radix). For picking\n * several entities use {@link MultiEntityCombobox}.\n */\nexport function EntityCombobox<V extends string | number>({\n value,\n onChange,\n options,\n loadOptions,\n loading,\n label,\n placeholder,\n searchPlaceholder,\n emptyLabel,\n clearable,\n clearLabel,\n closeLabel,\n disabled,\n onCreate,\n createLabel,\n className,\n invalid,\n error,\n filter,\n minChars,\n debounceMs,\n loadErrorLabel,\n \"aria-label\": ariaLabel,\n ...rest\n}: EntityComboboxProps<V>) {\n const core = useComboboxCore<V>({\n options,\n loadOptions,\n loading,\n filter,\n minChars,\n debounceMs,\n });\n const field = useComboboxFieldError(error, invalid);\n // The props are the per-instance overrides, the provider the app-wide ones; a\n // prop left `undefined` falls through to the provider rather than masking it.\n const labels = useKitLabels(\"combobox\", DEFAULT_COMBOBOX_LABELS, {\n search: searchPlaceholder,\n noResults: emptyLabel,\n clear: clearLabel,\n create: createLabel,\n });\n const common = useKitLabels(\"common\", DEFAULT_COMMON_LABELS);\n const { open, results, resolve, setOpen } = core;\n // One id per instance, generated here rather than in the core: `aria-controls` on\n // the trigger has to name the list while the list is still closed, so the id\n // belongs to whoever renders both ends of it.\n const listboxId = useId();\n\n const selectedOption = value == null ? null : resolve(value);\n const q = core.query.trim();\n const showCreate =\n Boolean(onCreate) && q.length > 0 && !results.some((o) => o.label.toLowerCase() === q.toLowerCase());\n const showClear = Boolean(clearable && value != null && !disabled);\n /** What the closed control is showing — the second half of its accessible name. */\n const triggerText = selectedOption?.label ?? placeholder ?? \"\";\n\n const choose = (o: ComboOption<V>) => {\n core.cacheRef.current.set(o.value, o);\n onChange(o.value);\n // Back to the trigger, not to <body>: the panel that held focus is about to\n // unmount, and a keyboard user who just answered this field should be standing\n // on it, ready to Tab to the next one.\n core.closeToTrigger();\n };\n\n return (\n // `rest` dresses the wrapper, which has no role; the accessible NAME goes on\n // the trigger, which has one. Spread FIRST so the trigger's ARIA and the\n // handlers that open the panel cannot be clobbered from outside.\n <div {...rest} className={cn(\"relative\", className)}>\n {label !== undefined && <FieldLabel>{label}</FieldLabel>}\n <button\n ref={core.triggerRef}\n type=\"button\"\n // A combobox, not a button. The distinction is not pedantry: this control\n // carried `aria-invalid`, which `button` does not support, so a required\n // field left empty painted a rose border and told a reader nothing at all —\n // and ESLint flagged it as exactly that (`role-supports-aria-props`). The\n // fix the audit asked for is the role that describes what this IS: a closed\n // choice that expands into the list named below. `combobox` supports\n // `aria-invalid`, so the border and the announcement finally agree.\n role=\"combobox\"\n aria-expanded={open}\n aria-controls={listboxId}\n aria-haspopup=\"listbox\"\n // The label is a floating <span>, not a <label for>, so without this the\n // trigger's accessible name is whatever value happens to be selected —\n // \"Checking\" with nothing saying it is the account. The label AND the\n // value, because `aria-label` replaces the content rather than adding to\n // it, and a control that announces only its name has lost the answer.\n // A caller's own name wins over the composition: two fields labelled\n // \"Account\" on a transfer form are the from and the to, and only the\n // caller knows which is which.\n aria-label={\n ariaLabel ??\n (typeof label === \"string\" ? common.fieldValue(label, triggerText) : undefined)\n }\n disabled={disabled}\n aria-invalid={field.isInvalid || undefined}\n aria-describedby={field.describedBy}\n onClick={() => !disabled && setOpen((o) => !o)}\n // Down/Up opens the list from the closed trigger, per the APG. Enter and\n // Space already do it through the button's own click.\n onKeyDown={(e) => {\n if (disabled) return;\n if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n e.preventDefault();\n setOpen(true);\n }\n }}\n className={cn(\n FIELD_TRIGGER,\n \"pr-9\",\n label !== undefined && FIELD_FLOATING_PAD,\n disabled && \"cursor-not-allowed opacity-50\",\n field.isInvalid && FIELD_INVALID,\n )}\n >\n <span className=\"flex min-w-0 items-center gap-2\">\n {selectedOption?.icon && <span className=\"shrink-0\">{selectedOption.icon}</span>}\n <span\n className={cn(\n \"truncate\",\n // A chosen value is the field's VALUE, so it is set in the same ink an\n // <input>'s value is — FIELD_BASE's own text colour, inherited rather\n // than restated (Keksdose dev#477). It used to be one notch lighter\n // than the typeahead fields beside it, which is visible when a picker\n // and a text field share a form row. Nothing selected keeps the\n // placeholder tone (`--text-placeholder`), which every field here\n // agrees on.\n !selectedOption && \"text-[var(--text-placeholder)]\",\n )}\n >\n {selectedOption?.label ?? placeholder ?? \"\"}\n </span>\n </span>\n {showClear ? (\n <span\n role=\"button\"\n tabIndex={-1}\n aria-label={labels.clear}\n onClick={(e) => {\n e.stopPropagation();\n onChange(null);\n }}\n className=\"absolute right-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-[var(--text-placeholder)] hover:text-[var(--text-secondary)]\"\n >\n <X className=\"size-4\" />\n </span>\n ) : (\n <FieldChevron />\n )}\n </button>\n <ComboboxPanel\n core={core}\n listboxId={listboxId}\n // On a phone the panel becomes a full-screen sheet, which needs the field's\n // own label to say what it is asking for (live #200).\n sheetTitle={label ?? placeholder}\n searchPlaceholder={labels.search}\n emptyLabel={labels.noResults}\n closeLabel={closeLabel}\n loadErrorLabel={loadErrorLabel}\n isSelected={(v) => v === value}\n onChoose={choose}\n showCreate={showCreate}\n onCreate={() => {\n onCreate?.(q);\n core.closeToTrigger();\n }}\n createContent={labels.create(q)}\n />\n {field.errorEl}\n </div>\n );\n}\n"],"mappings":";AAgJ8B,cAgDtB,YAhDsB;AAhJ9B,SAAS,aAAa;AAEtB,SAAS,SAAS;AAClB,SAAS,UAAU;AACnB,SAAS,cAAc,YAAY,eAAe,oBAAoB,qBAAqB;AAC3F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,yBAAyB,uBAAuB,oBAAoB;AA6DtE,SAAS,eAA0C;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,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;AAAA,UACA,UAAU,MAAM;AACd,uBAAW,CAAC;AACZ,iBAAK,eAAe;AAAA,UACtB;AAAA,UACA,eAAe,OAAO,OAAO,CAAC;AAAA;AAAA,MAChC;AAAA,MACC,MAAM;AAAA,OACT;AAAA;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/entity-combobox.tsx"],"sourcesContent":["import { useId } from \"react\";\nimport type { ComponentPropsWithoutRef, ReactNode } from \"react\";\nimport { X } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport { FieldChevron, FieldLabel, FIELD_TRIGGER, FIELD_FLOATING_PAD, FIELD_INVALID } from \"./ui\";\nimport {\n ComboboxPanel,\n useComboboxCore,\n useComboboxFieldError,\n type ComboClearValue,\n type ComboOption,\n} from \"./combobox-core\";\nimport { DEFAULT_COMBOBOX_LABELS, DEFAULT_COMMON_LABELS, useKitLabels } from \"../i18n/kit-labels\";\n\nexport type { ComboClearValue, ComboOption } from \"./combobox-core\";\n\n/** `onChange` is the kit's — \"a selection was made\", carrying values — rather\n * than the div's form event, so the DOM's spelling of it is omitted. */\nexport interface EntityComboboxProps<V extends string | number, C extends ComboClearValue = null>\n extends Omit<ComponentPropsWithoutRef<\"div\">, \"onChange\"> {\n /** Selected id; `null`, `undefined` or `clearValue` when nothing is selected. */\n value: V | C | null | undefined;\n /** Selecting an option emits its value; the clear button emits `clearValue`. */\n onChange: (value: V | C) => void;\n /**\n * What the clear button emits. Default `null`. Pass `\"\"` for a form whose schema\n * wants an empty string for \"no choice\" (a zod `z.string()` field), rather than\n * mapping `null` in every `onChange` — the type of `onChange` follows it, so the\n * mapping cannot be forgotten on one field and not another. The picker also reads\n * the value back as empty, so `value=\"\"` shows the placeholder and no \"×\".\n * See {@link ComboClearValue} for why the choice is closed.\n */\n clearValue?: C;\n /** Already-loaded options (client-side filtered). Also used to resolve the\n * trigger label for the current `value`. */\n options?: ComboOption<V>[];\n /** Async option source, debounced and called on open + as the query changes\n * (at `minChars` and up). Stale responses are ignored; a rejection empties the\n * list and says `loadErrorLabel` instead of leaving the last query's rows up. When set, `options` is used only for label\n * resolution, not as the result list. */\n loadOptions?: (query: string) => Promise<ComboOption<V>[]>;\n /** External loading flag (OR-ed with the internal async state). */\n loading?: boolean;\n label?: ReactNode;\n placeholder?: string;\n searchPlaceholder?: string;\n emptyLabel?: string;\n clearable?: boolean;\n clearLabel?: string;\n /** The phone sheet's close button. Its own prop rather than a reuse of\n * `clearLabel`: \"clear the selection\" and \"close this screen\" are different\n * actions, and on a full-screen sheet the close button is the only way out —\n * so it is the one control here that MUST be in the reader's language. */\n closeLabel?: string;\n disabled?: boolean;\n /** When set, a \"create\" row appears for a non-empty query with no exact match. */\n onCreate?: (query: string) => void;\n createLabel?: (query: string) => string;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\n /** What is wrong with the value, as {@link Input}'s `error`: rendered under the\n * field, on the trigger's `aria-describedby`, and implies `invalid`. */\n error?: ReactNode;\n /** Narrow `options` client-side by the query. Default `true`; `false` shows them\n * as given (a server-ranked list). */\n filter?: boolean;\n /** Offer nothing, and call no `loadOptions`, below this many characters. Default\n * `0`, i.e. the list loads as the panel opens. */\n minChars?: number;\n /** `loadOptions` debounce. Default 150 ms. */\n debounceMs?: number;\n /** Shown when `loadOptions` rejects. Default: `combobox.loadError`. */\n loadErrorLabel?: string;\n}\n\n/**\n * An id-keyed, searchable entity picker: a field-styled trigger showing the\n * selected item's label, and a portalled dropdown of `{label, sublabel, icon}`\n * options — loaded up front via `options` or lazily via `loadOptions`. Built on\n * the shared field/anchor/dismiss/search primitives (no cmdk/Radix). For picking\n * several entities use {@link MultiEntityCombobox}.\n */\nexport function EntityCombobox<V extends string | number, C extends ComboClearValue = null>({\n value,\n onChange,\n clearValue = null as C,\n options,\n loadOptions,\n loading,\n label,\n placeholder,\n searchPlaceholder,\n emptyLabel,\n clearable,\n clearLabel,\n closeLabel,\n disabled,\n onCreate,\n createLabel,\n className,\n invalid,\n error,\n filter,\n minChars,\n debounceMs,\n loadErrorLabel,\n \"aria-label\": ariaLabel,\n ...rest\n}: EntityComboboxProps<V, C>) {\n const core = useComboboxCore<V>({\n options,\n loadOptions,\n loading,\n filter,\n minChars,\n debounceMs,\n });\n const field = useComboboxFieldError(error, invalid);\n // The props are the per-instance overrides, the provider the app-wide ones; a\n // prop left `undefined` falls through to the provider rather than masking it.\n const labels = useKitLabels(\"combobox\", DEFAULT_COMBOBOX_LABELS, {\n search: searchPlaceholder,\n noResults: emptyLabel,\n clear: clearLabel,\n create: createLabel,\n });\n const common = useKitLabels(\"common\", DEFAULT_COMMON_LABELS);\n const { open, results, resolve, setOpen } = core;\n // One id per instance, generated here rather than in the core: `aria-controls` on\n // the trigger has to name the list while the list is still closed, so the id\n // belongs to whoever renders both ends of it.\n const listboxId = useId();\n\n // The clear value is \"nothing selected\" too, whichever one the caller picked.\n const chosen: V | null = value == null || value === clearValue ? null : (value as V);\n const selectedOption = chosen == null ? null : resolve(chosen);\n const q = core.query.trim();\n const showCreate =\n Boolean(onCreate) && q.length > 0 && !results.some((o) => o.label.toLowerCase() === q.toLowerCase());\n const showClear = Boolean(clearable && chosen != null && !disabled);\n /** What the closed control is showing — the second half of its accessible name. */\n const triggerText = selectedOption?.label ?? placeholder ?? \"\";\n\n const choose = (o: ComboOption<V>) => {\n core.cacheRef.current.set(o.value, o);\n onChange(o.value);\n // Back to the trigger, not to <body>: the panel that held focus is about to\n // unmount, and a keyboard user who just answered this field should be standing\n // on it, ready to Tab to the next one.\n core.closeToTrigger();\n };\n\n return (\n // `rest` dresses the wrapper, which has no role; the accessible NAME goes on\n // the trigger, which has one. Spread FIRST so the trigger's ARIA and the\n // handlers that open the panel cannot be clobbered from outside.\n <div {...rest} className={cn(\"relative\", className)}>\n {label !== undefined && <FieldLabel>{label}</FieldLabel>}\n <button\n ref={core.triggerRef}\n type=\"button\"\n // A combobox, not a button. The distinction is not pedantry: this control\n // carried `aria-invalid`, which `button` does not support, so a required\n // field left empty painted a rose border and told a reader nothing at all —\n // and ESLint flagged it as exactly that (`role-supports-aria-props`). The\n // fix the audit asked for is the role that describes what this IS: a closed\n // choice that expands into the list named below. `combobox` supports\n // `aria-invalid`, so the border and the announcement finally agree.\n role=\"combobox\"\n aria-expanded={open}\n aria-controls={listboxId}\n aria-haspopup=\"listbox\"\n // The label is a floating <span>, not a <label for>, so without this the\n // trigger's accessible name is whatever value happens to be selected —\n // \"Checking\" with nothing saying it is the account. The label AND the\n // value, because `aria-label` replaces the content rather than adding to\n // it, and a control that announces only its name has lost the answer.\n // A caller's own name wins over the composition: two fields labelled\n // \"Account\" on a transfer form are the from and the to, and only the\n // caller knows which is which.\n aria-label={\n ariaLabel ??\n (typeof label === \"string\" ? common.fieldValue(label, triggerText) : undefined)\n }\n disabled={disabled}\n aria-invalid={field.isInvalid || undefined}\n aria-describedby={field.describedBy}\n onClick={() => !disabled && setOpen((o) => !o)}\n // Down/Up opens the list from the closed trigger, per the APG. Enter and\n // Space already do it through the button's own click.\n onKeyDown={(e) => {\n if (disabled) return;\n if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n e.preventDefault();\n setOpen(true);\n }\n }}\n className={cn(\n FIELD_TRIGGER,\n \"pe-9\",\n label !== undefined && FIELD_FLOATING_PAD,\n disabled && \"cursor-not-allowed opacity-50\",\n field.isInvalid && FIELD_INVALID,\n )}\n >\n <span className=\"flex min-w-0 items-center gap-2\">\n {selectedOption?.icon && <span className=\"shrink-0\">{selectedOption.icon}</span>}\n <span\n className={cn(\n \"truncate\",\n // A chosen value is the field's VALUE, so it is set in the same ink an\n // <input>'s value is — FIELD_BASE's own text colour, inherited rather\n // than restated (Keksdose dev#477). It used to be one notch lighter\n // than the typeahead fields beside it, which is visible when a picker\n // and a text field share a form row. Nothing selected keeps the\n // placeholder tone (`--text-placeholder`), which every field here\n // agrees on.\n !selectedOption && \"text-[var(--text-placeholder)]\",\n )}\n >\n {selectedOption?.label ?? placeholder ?? \"\"}\n </span>\n </span>\n {showClear ? (\n <span\n role=\"button\"\n tabIndex={-1}\n aria-label={labels.clear}\n onClick={(e) => {\n e.stopPropagation();\n onChange(clearValue);\n }}\n className=\"absolute end-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-[var(--text-placeholder)] hover:text-[var(--text-secondary)]\"\n >\n <X className=\"size-4\" />\n </span>\n ) : (\n <FieldChevron />\n )}\n </button>\n <ComboboxPanel\n core={core}\n listboxId={listboxId}\n // On a phone the panel becomes a full-screen sheet, which needs the field's\n // own label to say what it is asking for (live #200).\n sheetTitle={label ?? placeholder}\n searchPlaceholder={labels.search}\n emptyLabel={labels.noResults}\n closeLabel={closeLabel}\n loadErrorLabel={loadErrorLabel}\n isSelected={(v) => v === value}\n onChoose={choose}\n showCreate={showCreate}\n onCreate={() => {\n onCreate?.(q);\n core.closeToTrigger();\n }}\n createContent={labels.create(q)}\n />\n {field.errorEl}\n </div>\n );\n}\n"],"mappings":";AA6J8B,cAgDtB,YAhDsB;AA7J9B,SAAS,aAAa;AAEtB,SAAS,SAAS;AAClB,SAAS,UAAU;AACnB,SAAS,cAAc,YAAY,eAAe,oBAAoB,qBAAqB;AAC3F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,yBAAyB,uBAAuB,oBAAoB;AAsEtE,SAAS,eAA4E;AAAA,EAC1F;AAAA,EACA;AAAA,EACA,aAAa;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA,EACd,GAAG;AACL,GAA8B;AAC5B,QAAM,OAAO,gBAAmB;AAAA,IAC9B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AA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,eAAe,OAAO,OAAO,CAAC;AAAA;AAAA,MAChC;AAAA,MACC,MAAM;AAAA,OACT;AAAA;AAEJ;","names":[]}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ComponentPropsWithoutRef, ReactNode, ReactElement } from 'react';
|
|
3
3
|
import { Button } from './ui.js';
|
|
4
|
+
import './tooltip.js';
|
|
5
|
+
import '../hooks/use-anchored-rect.js';
|
|
4
6
|
|
|
5
7
|
/**
|
|
6
8
|
* A button that opens the file picker — the shape all three apps kept writing by hand
|
|
@@ -30,8 +32,14 @@ import { Button } from './ui.js';
|
|
|
30
32
|
/** Every string the file pickers ({@link FileButton}, `FileDropzone`) render or speak.
|
|
31
33
|
* Messages are functions of the file name so a translation can put it anywhere. */
|
|
32
34
|
interface FilePickerLabels {
|
|
33
|
-
/** The file's type is not in `accept
|
|
35
|
+
/** The file's type is not in `accept`, when no `accept` is known to name (see
|
|
36
|
+
* `rejectedTypeOnly`). */
|
|
34
37
|
rejectedType: (name: string) => string;
|
|
38
|
+
/** The file's type is not in `accept`, naming what IS accepted: `accept`'s tokens,
|
|
39
|
+
* lower-cased and joined with ", " (`".csv"` => "Only .csv files"). Used whenever
|
|
40
|
+
* `accept` is set — kastlan kept a custom `isValid` + `invalidMessage` per form only
|
|
41
|
+
* to say this, and `accept` already knows it. */
|
|
42
|
+
rejectedTypeOnly: (accept: string, name: string) => string;
|
|
35
43
|
/** The file is larger than `maxSize`; `maxSize` arrives formatted ("5 MB"). */
|
|
36
44
|
rejectedSize: (name: string, maxSize: string) => string;
|
|
37
45
|
/** The file was one too many for `maxFiles`. */
|
|
@@ -40,6 +48,9 @@ interface FilePickerLabels {
|
|
|
40
48
|
rejectedInvalid: (name: string) => string;
|
|
41
49
|
/** Spoken instead of the per-file message when more than one file was refused. */
|
|
42
50
|
rejectedMany: (count: number) => string;
|
|
51
|
+
/** Spoken (and shown, on a dropzone) when `onPick` refused the WHOLE pick.
|
|
52
|
+
* Receives the number of files in it. */
|
|
53
|
+
rejectedPick: (count: number) => string;
|
|
43
54
|
/** Spoken after a pick the component itself echoes (the dropzone). */
|
|
44
55
|
selected: (count: number, firstName: string) => string;
|
|
45
56
|
/** The dropzone's remove button for one file. */
|
|
@@ -89,6 +100,25 @@ declare function screenFiles(files: readonly File[], opts: FileScreenOptions, la
|
|
|
89
100
|
accepted: File[];
|
|
90
101
|
rejected: FileRejection[];
|
|
91
102
|
};
|
|
103
|
+
/**
|
|
104
|
+
* Judges a pick as a whole — keksdose's "refuse the pick if any file is bad", which
|
|
105
|
+
* with `onFiles` + `onReject` alone had to be rebuilt from two calls in a microtask.
|
|
106
|
+
*
|
|
107
|
+
* Called ONCE per pick, after screening and before `onFiles` / `onReject`, with both
|
|
108
|
+
* halves (either may be empty). Return `false` to refuse the whole pick: the accepted
|
|
109
|
+
* files are not delivered, `onReject` still receives what screening refused, and one
|
|
110
|
+
* sentence (`labels.rejectedPick`) is spoken for the pick instead of a per-file one.
|
|
111
|
+
* Return nothing to let the pick through as usual.
|
|
112
|
+
*
|
|
113
|
+
* ```tsx
|
|
114
|
+
* onPick={(ok, bad) => bad.length === 0 || false} // all or nothing
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
type FilePickHandler = (accepted: File[], rejected: FileRejection[]) => boolean | void;
|
|
118
|
+
/** @internal The shared tail of both pickers: run `onPick`, and say whether the pick
|
|
119
|
+
* stands. A pick with nothing accepted has nothing to refuse, so `false` there is
|
|
120
|
+
* treated as no verdict and the usual per-file messages are kept. */
|
|
121
|
+
declare function judgePick(onPick: FilePickHandler | undefined, accepted: File[], rejected: FileRejection[]): boolean;
|
|
92
122
|
/** One sentence for a whole batch of refusals: the file's own message for one, a
|
|
93
123
|
* count for several — reading out five sentences in a row helps nobody. */
|
|
94
124
|
declare function summariseRejections(rejected: readonly FileRejection[], labels: FilePickerLabels): string;
|
|
@@ -102,8 +132,11 @@ interface UseFilePickerOptions extends FileScreenOptions {
|
|
|
102
132
|
* keksdose's camera input has no `multiple`. Pass one or the other.
|
|
103
133
|
*/
|
|
104
134
|
capture?: boolean | "user" | "environment";
|
|
105
|
-
/** The files that passed, in pick order. Never called with an empty array.
|
|
106
|
-
|
|
135
|
+
/** The files that passed, in pick order. Never called with an empty array.
|
|
136
|
+
* Optional since 0.7 for a caller that takes the pick through `onPick` alone. */
|
|
137
|
+
onFiles?: (files: File[]) => void;
|
|
138
|
+
/** See {@link FilePickHandler}: the whole pick at once, with the power to refuse it. */
|
|
139
|
+
onPick?: FilePickHandler;
|
|
107
140
|
/** The files that did not, with a translated message each. The refusals are also
|
|
108
141
|
* spoken through a live region, so this is for SHOWING them, not for a11y. */
|
|
109
142
|
onReject?: (rejections: FileRejection[]) => void;
|
|
@@ -132,7 +165,7 @@ interface UseFilePickerReturn {
|
|
|
132
165
|
* return <>{picker.element}<DetailTableCard onAdd={picker.open} … /></>;
|
|
133
166
|
* ```
|
|
134
167
|
*/
|
|
135
|
-
declare function useFilePicker({ accept, multiple, capture, maxSize, maxFiles, isValid, invalidMessage, onFiles, onReject, disabled, labels: labelsProp, }: UseFilePickerOptions): UseFilePickerReturn;
|
|
168
|
+
declare function useFilePicker({ accept, multiple, capture, maxSize, maxFiles, isValid, invalidMessage, onFiles, onPick, onReject, disabled, labels: labelsProp, }: UseFilePickerOptions): UseFilePickerReturn;
|
|
136
169
|
type ButtonOwnProps = ComponentPropsWithoutRef<typeof Button>;
|
|
137
170
|
interface FileButtonProps extends Omit<UseFilePickerOptions, "disabled">, Omit<ButtonOwnProps, "type" | "children" | "accept" | "capture" | "multiple"> {
|
|
138
171
|
/** The button's content — usually an icon and a word. It is the accessible name. */
|
|
@@ -158,4 +191,4 @@ interface FileButtonProps extends Omit<UseFilePickerOptions, "disabled">, Omit<B
|
|
|
158
191
|
*/
|
|
159
192
|
declare const FileButton: react.ForwardRefExoticComponent<FileButtonProps & react.RefAttributes<HTMLButtonElement>>;
|
|
160
193
|
|
|
161
|
-
export { DEFAULT_FILE_PICKER_LABELS, FileButton, type FileButtonProps, type FilePickerLabels, type FileRejection, type FileRejectionReason, type FileScreenOptions, type UseFilePickerOptions, type UseFilePickerReturn, matchesAccept, screenFiles, summariseRejections, useFilePicker };
|
|
194
|
+
export { DEFAULT_FILE_PICKER_LABELS, FileButton, type FileButtonProps, type FilePickHandler, type FilePickerLabels, type FileRejection, type FileRejectionReason, type FileScreenOptions, type UseFilePickerOptions, type UseFilePickerReturn, judgePick, matchesAccept, screenFiles, summariseRejections, useFilePicker };
|
|
@@ -7,10 +7,12 @@ import { useKitFileLabels, useKitLabels } from "../i18n/kit-labels.js";
|
|
|
7
7
|
import { Button, Spinner } from "./ui.js";
|
|
8
8
|
const DEFAULT_FILE_PICKER_LABELS = {
|
|
9
9
|
rejectedType: (name) => `\u201C${name}\u201D is not a supported file type`,
|
|
10
|
+
rejectedTypeOnly: (accept) => `Only ${accept} files`,
|
|
10
11
|
rejectedSize: (name, maxSize) => `\u201C${name}\u201D is larger than ${maxSize}`,
|
|
11
12
|
rejectedCount: (name, maxFiles) => `\u201C${name}\u201D was not added: at most ${maxFiles} ${maxFiles === 1 ? "file" : "files"}`,
|
|
12
13
|
rejectedInvalid: (name) => `\u201C${name}\u201D cannot be used here`,
|
|
13
14
|
rejectedMany: (count) => `${count} files were not added`,
|
|
15
|
+
rejectedPick: (count) => count === 1 ? "The file was not added" : `None of the ${count} files were added`,
|
|
14
16
|
selected: (count, firstName) => count === 1 ? `\u201C${firstName}\u201D selected` : `${count} files selected`,
|
|
15
17
|
remove: (name) => `Remove \u201C${name}\u201D`,
|
|
16
18
|
clearAll: "Remove all files",
|
|
@@ -47,9 +49,15 @@ function typeFromExtension(name) {
|
|
|
47
49
|
const dot = name.lastIndexOf(".");
|
|
48
50
|
return dot === -1 ? void 0 : EXTENSION_TYPES[name.slice(dot + 1)];
|
|
49
51
|
}
|
|
52
|
+
function formatAccept(accept) {
|
|
53
|
+
return accept.split(",").map((t) => t.trim().toLowerCase()).filter(Boolean).join(", ");
|
|
54
|
+
}
|
|
50
55
|
function screenFiles(files, opts, labels, formatSize) {
|
|
51
56
|
const accepted = [];
|
|
52
57
|
const rejected = [];
|
|
58
|
+
const acceptText = opts.accept ? formatAccept(opts.accept) : "";
|
|
59
|
+
const useOnly = acceptText !== "" && (labels.rejectedTypeOnly !== DEFAULT_FILE_PICKER_LABELS.rejectedTypeOnly || labels.rejectedType === DEFAULT_FILE_PICKER_LABELS.rejectedType);
|
|
60
|
+
const typeMessage = (name) => useOnly ? labels.rejectedTypeOnly(acceptText, name) : labels.rejectedType(name);
|
|
53
61
|
for (const file of files) {
|
|
54
62
|
let reason = null;
|
|
55
63
|
if (!matchesAccept(file, opts.accept)) reason = "type";
|
|
@@ -60,11 +68,15 @@ function screenFiles(files, opts, labels, formatSize) {
|
|
|
60
68
|
accepted.push(file);
|
|
61
69
|
continue;
|
|
62
70
|
}
|
|
63
|
-
const message = reason === "type" ?
|
|
71
|
+
const message = reason === "type" ? typeMessage(file.name) : reason === "size" ? labels.rejectedSize(file.name, formatSize(opts.maxSize ?? 0)) : reason === "count" ? labels.rejectedCount(file.name, Math.max(0, opts.maxFiles ?? 0)) : opts.invalidMessage ?? labels.rejectedInvalid(file.name);
|
|
64
72
|
rejected.push({ file, reason, message });
|
|
65
73
|
}
|
|
66
74
|
return { accepted, rejected };
|
|
67
75
|
}
|
|
76
|
+
function judgePick(onPick, accepted, rejected) {
|
|
77
|
+
if (!onPick) return true;
|
|
78
|
+
return onPick(accepted, rejected) !== false || accepted.length === 0;
|
|
79
|
+
}
|
|
68
80
|
function summariseRejections(rejected, labels) {
|
|
69
81
|
if (rejected.length === 0) return "";
|
|
70
82
|
if (rejected.length === 1) return rejected[0].message;
|
|
@@ -79,6 +91,7 @@ function useFilePicker({
|
|
|
79
91
|
isValid,
|
|
80
92
|
invalidMessage,
|
|
81
93
|
onFiles,
|
|
94
|
+
onPick,
|
|
82
95
|
onReject,
|
|
83
96
|
disabled,
|
|
84
97
|
labels: labelsProp
|
|
@@ -99,7 +112,12 @@ function useFilePicker({
|
|
|
99
112
|
labels,
|
|
100
113
|
fileText.size
|
|
101
114
|
);
|
|
102
|
-
if (accepted
|
|
115
|
+
if (!judgePick(onPick, accepted, rejected)) {
|
|
116
|
+
if (rejected.length > 0) onReject?.(rejected);
|
|
117
|
+
announce(labels.rejectedPick(files.length));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (accepted.length > 0) onFiles?.(accepted);
|
|
103
121
|
if (rejected.length > 0) {
|
|
104
122
|
onReject?.(rejected);
|
|
105
123
|
announce(summariseRejections(rejected, labels));
|
|
@@ -144,6 +162,7 @@ const FileButton = forwardRef(function FileButton2({
|
|
|
144
162
|
isValid,
|
|
145
163
|
invalidMessage,
|
|
146
164
|
onFiles,
|
|
165
|
+
onPick,
|
|
147
166
|
onReject,
|
|
148
167
|
labels,
|
|
149
168
|
pending,
|
|
@@ -168,6 +187,7 @@ const FileButton = forwardRef(function FileButton2({
|
|
|
168
187
|
isValid,
|
|
169
188
|
invalidMessage,
|
|
170
189
|
onFiles,
|
|
190
|
+
onPick,
|
|
171
191
|
onReject,
|
|
172
192
|
labels,
|
|
173
193
|
disabled: inert
|
|
@@ -235,6 +255,7 @@ FileButton.displayName = "FileButton";
|
|
|
235
255
|
export {
|
|
236
256
|
DEFAULT_FILE_PICKER_LABELS,
|
|
237
257
|
FileButton,
|
|
258
|
+
judgePick,
|
|
238
259
|
matchesAccept,
|
|
239
260
|
screenFiles,
|
|
240
261
|
summariseRejections,
|