@eifi1/ui-kit 0.12.0 → 0.13.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 +10 -10
- package/dist/components/amount-input.d.ts +23 -1
- package/dist/components/amount-input.js +78 -13
- package/dist/components/amount-input.js.map +1 -1
- package/dist/components/bulk-action-bar.d.ts +10 -2
- package/dist/components/bulk-action-bar.js.map +1 -1
- package/dist/components/button-group.d.ts +1 -1
- package/dist/components/calculator.d.ts +1 -1
- package/dist/components/chart.js +14 -8
- package/dist/components/chart.js.map +1 -1
- package/dist/components/chip.js +20 -15
- package/dist/components/chip.js.map +1 -1
- package/dist/components/combobox-core.d.ts +3 -1
- package/dist/components/combobox-core.js +16 -5
- package/dist/components/combobox-core.js.map +1 -1
- package/dist/components/combobox.js.map +1 -1
- package/dist/components/copy-button.d.ts +1 -1
- package/dist/components/data-table-filter-popover.js +8 -1
- package/dist/components/data-table-filter-popover.js.map +1 -1
- package/dist/components/data-table.js +28 -20
- package/dist/components/data-table.js.map +1 -1
- package/dist/components/entity-combobox.js +22 -17
- package/dist/components/entity-combobox.js.map +1 -1
- package/dist/components/error-boundary.d.ts +202 -13
- package/dist/components/error-boundary.js +225 -21
- package/dist/components/error-boundary.js.map +1 -1
- package/dist/components/field-sync.js +90 -83
- package/dist/components/field-sync.js.map +1 -1
- package/dist/components/file-button.d.ts +1 -1
- package/dist/components/file-dropzone.d.ts +1 -1
- package/dist/components/form-actions.d.ts +1 -1
- package/dist/components/full-bleed-dialog.js +4 -0
- package/dist/components/full-bleed-dialog.js.map +1 -1
- package/dist/components/hover-menu.js +64 -56
- package/dist/components/hover-menu.js.map +1 -1
- package/dist/components/list.d.ts +14 -2
- package/dist/components/list.js +3 -1
- package/dist/components/list.js.map +1 -1
- package/dist/components/modal.js.map +1 -1
- package/dist/components/multi-entity-combobox.js +23 -17
- package/dist/components/multi-entity-combobox.js.map +1 -1
- package/dist/components/number-field.d.ts +1 -1
- package/dist/components/number-input.d.ts +1 -1
- package/dist/components/number-input.js.map +1 -1
- package/dist/components/numpad-sheet.d.ts +10 -2
- package/dist/components/numpad-sheet.js +6 -4
- package/dist/components/numpad-sheet.js.map +1 -1
- package/dist/components/page-header.d.ts +35 -6
- package/dist/components/page-header.js +7 -1
- package/dist/components/page-header.js.map +1 -1
- package/dist/components/picker-sheet.js +3 -0
- package/dist/components/picker-sheet.js.map +1 -1
- package/dist/components/popover.js +3 -0
- package/dist/components/popover.js.map +1 -1
- package/dist/components/settings-fields.d.ts +1 -1
- package/dist/components/signed-amount.d.ts +2 -1
- package/dist/components/signed-amount.js +1 -1
- package/dist/components/signed-amount.js.map +1 -1
- package/dist/components/stat-tile.js +1 -1
- package/dist/components/stat-tile.js.map +1 -1
- package/dist/components/swipeable-row.js +4 -3
- package/dist/components/swipeable-row.js.map +1 -1
- package/dist/components/text-link.d.ts +73 -11
- package/dist/components/text-link.js +45 -10
- package/dist/components/text-link.js.map +1 -1
- package/dist/components/text.d.ts +26 -2
- package/dist/components/text.js +16 -2
- package/dist/components/text.js.map +1 -1
- package/dist/components/time-input.d.ts +1 -1
- package/dist/components/toggle-group.d.ts +22 -0
- package/dist/components/toggle-group.js +8 -8
- package/dist/components/toggle-group.js.map +1 -1
- package/dist/components/toggle-legend.d.ts +17 -0
- package/dist/components/toggle-legend.js +6 -2
- package/dist/components/toggle-legend.js.map +1 -1
- package/dist/components/tooltip.d.ts +51 -1
- package/dist/components/tooltip.js +59 -35
- package/dist/components/tooltip.js.map +1 -1
- package/dist/components/ui.d.ts +1 -1
- package/dist/components/ui.js +166 -28
- package/dist/components/ui.js.map +1 -1
- package/dist/feedback/feedback-attachment.js +4 -6
- package/dist/feedback/feedback-attachment.js.map +1 -1
- package/dist/feedback/feedback-dialog.js +5 -3
- package/dist/feedback/feedback-dialog.js.map +1 -1
- package/dist/feedback/feedback-inbox.js +86 -75
- package/dist/feedback/feedback-inbox.js.map +1 -1
- package/dist/feedback/feedback-thread.d.ts +43 -3
- package/dist/feedback/feedback-thread.js +53 -26
- package/dist/feedback/feedback-thread.js.map +1 -1
- package/dist/feedback.d.ts +1 -1
- package/dist/hooks/use-file-drop.d.ts +1 -1
- package/dist/i18n/defaults.d.ts +1 -1
- package/dist/i18n/kit-labels.d.ts +1 -1
- package/dist/i18n/kit-labels.js.map +1 -1
- package/dist/i18n/locales/de-CH-informal.d.ts +1 -1
- package/dist/i18n/locales/de-CH.d.ts +1 -1
- package/dist/i18n/locales/de-informal.d.ts +1 -1
- package/dist/i18n/locales/de.d.ts +1 -1
- package/dist/i18n/locales/de.js +9 -1
- package/dist/i18n/locales/de.js.map +1 -1
- package/dist/i18n/locales/es.d.ts +1 -1
- package/dist/i18n/locales/es.js +9 -1
- package/dist/i18n/locales/es.js.map +1 -1
- package/dist/i18n/locales/fr.d.ts +1 -1
- package/dist/i18n/locales/fr.js +9 -1
- package/dist/i18n/locales/fr.js.map +1 -1
- package/dist/i18n/locales/hu.d.ts +1 -1
- package/dist/i18n/locales/hu.js +9 -1
- package/dist/i18n/locales/hu.js.map +1 -1
- package/dist/i18n/locales/it.d.ts +1 -1
- package/dist/i18n/locales/it.js +9 -1
- package/dist/i18n/locales/it.js.map +1 -1
- package/dist/i18n/locales/zh.d.ts +1 -1
- package/dist/i18n/locales/zh.js +9 -1
- package/dist/i18n/locales/zh.js.map +1 -1
- package/dist/index.d.ts +6 -6
- package/dist/{kit-labels-v3biUF1L.d.ts → kit-labels-Mz8zZHIF.d.ts} +102 -3
- package/dist/lib/format.d.ts +23 -5
- package/dist/lib/format.js +4 -2
- package/dist/lib/format.js.map +1 -1
- package/dist/rhf/fields.d.ts +59 -15
- package/dist/rhf/fields.js +41 -11
- package/dist/rhf/fields.js.map +1 -1
- package/dist/rhf/form.d.ts +1 -1
- package/dist/rhf.d.ts +2 -2
- package/dist/rhf.js.map +1 -1
- package/dist/search/command-palette.js +20 -14
- package/dist/search/command-palette.js.map +1 -1
- package/dist/shell/app-shell.d.ts +1 -1
- package/dist/shell/app-shell.js +62 -54
- package/dist/shell/app-shell.js.map +1 -1
- package/dist/shell/top-bar-brand.d.ts +1 -1
- package/dist/shell/topbar-action-menu.d.ts +9 -3
- package/dist/shell/topbar-action-menu.js +2 -1
- package/dist/shell/topbar-action-menu.js.map +1 -1
- package/dist/shell.d.ts +1 -1
- package/dist/tour/tour.js +10 -4
- package/dist/tour/tour.js.map +1 -1
- package/dist/wizard/stepper-nav.d.ts +1 -1
- package/dist/wizard/use-wizard.js +4 -2
- package/dist/wizard/use-wizard.js.map +1 -1
- package/dist/wizard/wizard-step.d.ts +11 -1
- package/dist/wizard/wizard-step.js +24 -6
- package/dist/wizard/wizard-step.js.map +1 -1
- package/dist/wizard.d.ts +1 -1
- package/package.json +6 -6
- package/src/components/amount-input.tsx +165 -12
- package/src/components/bulk-action-bar.tsx +16 -3
- package/src/components/chart.tsx +19 -8
- package/src/components/chip.tsx +6 -0
- package/src/components/combobox-core.tsx +28 -9
- package/src/components/combobox.tsx +2 -0
- package/src/components/data-table-filter-popover.tsx +13 -5
- package/src/components/data-table.tsx +6 -0
- package/src/components/entity-combobox.tsx +7 -4
- package/src/components/error-boundary.tsx +470 -30
- package/src/components/field-sync.tsx +48 -40
- package/src/components/full-bleed-dialog.tsx +4 -0
- package/src/components/hover-menu.tsx +26 -17
- package/src/components/list.tsx +17 -3
- package/src/components/modal.tsx +4 -0
- package/src/components/multi-entity-combobox.tsx +8 -4
- package/src/components/number-input.tsx +1 -0
- package/src/components/numpad-sheet.tsx +17 -3
- package/src/components/page-header.tsx +42 -5
- package/src/components/picker-sheet.tsx +3 -0
- package/src/components/popover.tsx +3 -0
- package/src/components/signed-amount.tsx +12 -3
- package/src/components/stat-tile.tsx +3 -1
- package/src/components/swipeable-row.tsx +7 -7
- package/src/components/text-link.tsx +126 -18
- package/src/components/text.tsx +47 -2
- package/src/components/toggle-group.tsx +35 -10
- package/src/components/toggle-legend.tsx +22 -1
- package/src/components/tooltip.tsx +79 -8
- package/src/components/ui.tsx +307 -39
- package/src/feedback/feedback-attachment.tsx +10 -7
- package/src/feedback/feedback-dialog.tsx +7 -4
- package/src/feedback/feedback-inbox.tsx +7 -0
- package/src/feedback/feedback-thread.tsx +109 -33
- package/src/i18n/kit-labels.tsx +16 -0
- package/src/i18n/locales/de.ts +8 -0
- package/src/i18n/locales/es.ts +8 -0
- package/src/i18n/locales/fr.ts +8 -0
- package/src/i18n/locales/hu.ts +8 -0
- package/src/i18n/locales/it.ts +8 -0
- package/src/i18n/locales/zh.ts +8 -0
- package/src/lib/format.ts +32 -7
- package/src/rhf/fields.tsx +99 -16
- package/src/rhf.ts +1 -1
- package/src/search/command-palette.tsx +29 -19
- package/src/shell/app-shell.tsx +6 -1
- package/src/shell/topbar-action-menu.tsx +11 -4
- package/src/tour/tour.tsx +16 -5
- package/src/wizard/use-wizard.ts +8 -4
- package/src/wizard/wizard-step.tsx +38 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/list.tsx"],"sourcesContent":["import { createContext, forwardRef, useContext, useId } from \"react\";\nimport type { ComponentPropsWithoutRef, HTMLAttributes, MouseEvent, ReactElement, ReactNode, Ref } from \"react\";\nimport { ExternalLink } from \"lucide-react\";\nimport type { LucideIcon } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport { Spinner } from \"./ui\";\nimport { StatusDot } from \"./status-dot\";\nimport { useKitLabels, useKitLink } from \"../i18n/kit-labels\";\nimport { pickLinkRenderer } from \"./text-link\";\n\n/* ── Labels ───────────────────────────────────────────────────────────────── */\n\nexport interface ListLabels {\n /** Read after an unread row's title — the dot alone says nothing to a screen reader. */\n unread: string;\n /** Read after an external row's title: the row leaves the app in a new tab. */\n opensInNewTab: string;\n}\n\nexport const DEFAULT_LIST_LABELS: ListLabels = {\n unread: \"Unread\",\n opensInNewTab: \"opens in a new tab\",\n};\n\n/* ── List ─────────────────────────────────────────────────────────────────── */\n\n/**\n * `compact` 36px-ish rows for a dense panel (an inbox in a menu), `default` the ~44px\n * row every site draws with `py-2.5`, `comfortable` for a list that is the page.\n */\nexport type ListDensity = \"compact\" | \"default\" | \"comfortable\";\n/** `divider`: a rule between rows (kastlan's `divide-y` lists); `gap`: a small space\n * between rows (lenkbank's `space-y-2`, kastlan's `space-y-1`); `none`: flush. */\nexport type ListSeparator = \"divider\" | \"gap\" | \"none\";\n\nconst ListContext = createContext<{ density: ListDensity; separator: ListSeparator }>({\n density: \"default\",\n separator: \"gap\",\n});\n\nexport interface ListProps extends Omit<ComponentPropsWithoutRef<\"ul\">, \"role\"> {\n /** `ol` when the order means something (a ranked list, numbered segments). */\n as?: \"ul\" | \"ol\";\n /** Every row's density, unless a row says otherwise. Default `default`. */\n density?: ListDensity;\n /** Default `gap`. */\n separator?: ListSeparator;\n}\n\n/**\n * The list of {@link ListItem}s.\n *\n * A `<ul>` with an explicit `role=\"list\"`: Safari drops a list's semantics once its\n * bullets are styled away, and \"list, 7 items\" is exactly what a screen-reader user\n * wants to hear before the first row.\n */\nexport const List = forwardRef<HTMLUListElement, ListProps>(function List(\n { as = \"ul\", density = \"default\", separator = \"gap\", className, children, ...rest },\n ref,\n) {\n const Tag = as;\n return (\n <ListContext.Provider value={{ density, separator }}>\n <Tag\n {...rest}\n ref={ref as Ref<HTMLUListElement & HTMLOListElement>}\n role=\"list\"\n className={cn(\n \"m-0 flex list-none flex-col p-0\",\n separator === \"gap\" && (density === \"compact\" ? \"gap-0.5\" : \"gap-1\"),\n className,\n )}\n >\n {children}\n </Tag>\n </ListContext.Provider>\n );\n});\n\n/* ── ListItem ─────────────────────────────────────────────────────────────── */\n\n/** What {@link ListItemProps.renderLink} is handed. Spread it onto your router's link,\n * mapping `href` to what it calls it — `({ href, ...p }) => <Link to={href} {...p} />`. */\nexport interface ListItemLinkProps {\n href: string;\n /** The row's target look — keep it, or the row's padding and focus ring go. */\n className: string;\n children: ReactNode;\n ref?: Ref<HTMLAnchorElement>;\n onClick?: (event: MouseEvent<HTMLAnchorElement>) => void;\n onAuxClick?: (event: MouseEvent<HTMLAnchorElement>) => void;\n \"aria-current\"?: \"true\";\n \"aria-busy\"?: true;\n id?: string;\n [key: `aria-${string}`]: string | boolean | number | undefined;\n [key: `data-${string}`]: unknown;\n}\n\nconst PAD: Record<ListDensity, { target: string; actions: string; gap: string; body: string }> = {\n compact: { target: \"gap-2 px-2 py-1.5\", actions: \"pe-1.5\", gap: \"gap-0.5\", body: \"px-2 pb-1.5\" },\n default: { target: \"gap-3 px-3 py-2.5\", actions: \"pe-2\", gap: \"gap-1\", body: \"px-3 pb-2.5\" },\n comfortable: { target: \"gap-3 px-4 py-3\", actions: \"pe-3\", gap: \"gap-1\", body: \"px-4 pb-3\" },\n};\n\nconst TARGET_RING =\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--brand)]\";\n\ninterface ListItemBaseProps {\n /** The row's name: one line, truncated. */\n title: ReactNode;\n /** The line under it: one line, truncated — or two, with `subtitleLines={2}`. */\n subtitle?: ReactNode;\n /** `2` for a line that is a body rather than a label (keksdose's notification text). */\n subtitleLines?: 1 | 2;\n /** A third line in the caption type: a timestamp, \"Updated …\" (lenkbank's projects). */\n meta?: ReactNode;\n /** A Lucide icon before the text, muted, at 16px. */\n icon?: LucideIcon;\n /** Anything else before the text — an avatar, a file-type badge, a drag handle. */\n leading?: ReactNode;\n /**\n * Inside the main target, at its end: a status chip, a file size, a count. It is part\n * of what the row's click does and part of its accessible name — so never a control.\n * Controls go in {@link actions}.\n */\n trailing?: ReactNode;\n /**\n * Controls BESIDE the main target, never inside it: copy, delete, \"Open\".\n *\n * A button inside a button (or a link) is invalid HTML, and a screen reader folds the\n * inner one into the outer one's name where it cannot be reached. lenkbank found this\n * three times (profile-bar.tsx:110, projects-page.tsx:61, segment-list.tsx:165) and\n * solved it the same way each time: the row's target and its actions are siblings in\n * one bordered box. That is this slot — and being siblings is also what stops a click\n * on \"Copy\" from selecting the row.\n */\n actions?: ReactNode;\n /**\n * Rich content UNDER the title row and outside its target: photos, per-row buttons,\n * form fields — kastlan's handover room inspector (room-inspector.tsx), the handover\n * detail page and the wizard's defects step (wizard/defects-step.tsx), which draw\n * each room or defect as a `Card variant=\"inset\"` because a row could not hold a\n * photo strip with its own buttons.\n *\n * The same rule as {@link actions}, one row down: the title area stays ONE named\n * target (the button or link, with the title and subtitle as its name), and the body\n * is its sibling, never nested in it — a thumbnail's \"Remove\" inside the row's button\n * would be invalid HTML and unreachable by a screen reader. The body is a\n * `role=\"group\"` named by the row's title (`aria-labelledby`), so tabbing into the\n * third photo's button of the second room is heard as \"Kitchen, group\" first rather\n * than as a button floating free of any row. Inside the row's box, so a `selected`\n * border and a `divider` hold both; the hover fill stays on the target alone, since\n * the body is not what a click on the row does.\n */\n children?: ReactNode;\n /** Classes on the {@link children} body. */\n bodyClassName?: string;\n /**\n * The unread mark: a brand dot at the row's end, the title in semibold, and \"Unread\"\n * read after the title (keksdose notification-inbox.tsx:215). For another status,\n * pass your own mark in {@link status}.\n */\n unread?: boolean;\n /** A mark in the unread dot's place — a `StatusDot` of another tone, a count. */\n status?: ReactNode;\n /**\n * The row is the chosen one — a brand border on the raised surface (lenkbank's\n * profile bar and segment list). `aria-current=\"true\"` on the target: the row is the\n * current one of a set, which is what those lists mean, not a pressed toggle.\n */\n selected?: boolean;\n disabled?: boolean;\n /**\n * Work under way on the row — keksdose's attachment download (support-attachments\n * .tsx:91). A spinner takes the trailing edge, the target is `aria-busy`, and a\n * second click is ignored. The row keeps focus: `aria-disabled`, not `disabled`, so\n * a keyboard user is not dropped back to the top of the page mid-download.\n */\n loading?: boolean;\n /** Overrides the {@link List}'s density for this row. */\n density?: ListDensity;\n /** `start` for rows whose text runs to two or three lines, so the icon sits by the\n * title rather than the middle of the paragraph. Default `center`. */\n align?: \"center\" | \"start\";\n /** Classes on the visible row (the bordered box). */\n className?: string;\n /** Classes on the main target (the button, link or static block). */\n targetClassName?: string;\n /**\n * Extra attributes and handlers for the main target — e.g. HTML5 drag-and-drop\n * (`draggable`, `onDragStart`, `onDragEnd`): lenkbank's segment list drags the WHOLE\n * 44px row, and a grip inside the button cannot start a drag in Firefox. Spread first,\n * so the row's own role, name, state and click handling always win.\n */\n targetProps?: HTMLAttributes<HTMLElement>;\n /**\n * A visible border while unselected, instead of the transparent one. For rows laid out\n * as a wrapping strip (lenkbank's profile bar), where borderless rows read as loose\n * text. The selected row's brand border is unchanged.\n */\n bordered?: boolean;\n /** `div` for a single row outside a {@link List}; an `<li>` must sit in a list. */\n as?: \"li\" | \"div\";\n /** Reaches the main target — the element with the row's name and action. */\n id?: string;\n [key: `aria-${string}`]: string | boolean | number | undefined;\n [key: `data-${string}`]: unknown;\n}\n\n/**\n * The row is ONE thing to activate, so the types allow one: a button, an in-app link,\n * an external link, or nothing (a static row, like kastlan's passkey and user lists).\n */\nexport type ListItemProps = ListItemBaseProps &\n (\n | {\n /** Makes the row a button — select, open, mark read. */\n onClick: (event: MouseEvent<HTMLButtonElement>) => void;\n href?: never;\n renderLink?: never;\n external?: never;\n onAuxClick?: never;\n }\n | {\n /**\n * Makes the row a link. A real `<a href>`, so a middle click opens it in a\n * background tab (keksdose feedback #451) — which a button calling `navigate`\n * cannot do.\n */\n href: string;\n /** Your router's link for an in-app `href`. Default: the `<UiKitProvider\n * linkComponent>`, then `<a>`. The API `Chip`, `StatTile` and `MenuItem`\n * share. Ignored for an `external` row. */\n renderLink?: (props: ListItemLinkProps) => ReactElement;\n /**\n * The link leaves the app: a plain `<a target=\"_blank\" rel=\"noopener\n * noreferrer\">` with an external-link mark, and \"opens in a new tab\" read\n * after the title. keksdose's inbox rows whose URL is absolute.\n */\n external?: boolean;\n /** Runs on a click, before the navigation (mark the row read). */\n onClick?: (event: MouseEvent<HTMLAnchorElement>) => void;\n /** Runs on a middle click, which fires no `click` — keksdose marks a\n * notification read here too, so a row opened into a background tab does not\n * stay unread. */\n onAuxClick?: (event: MouseEvent<HTMLAnchorElement>) => void;\n }\n | {\n onClick?: never;\n href?: never;\n renderLink?: never;\n external?: never;\n onAuxClick?: never;\n }\n );\n\n/**\n * One row of a {@link List}: leading icon or avatar, title and subtitle (both\n * truncating), a trailing slot, and — beside the row, not inside it — its actions.\n *\n * All three apps draw this row by hand, a dozen times: kastlan's units\n * (building-detail-page.tsx:402), open tickets (group-overview-page.tsx:160), activity\n * feed (activity-feed.tsx:53), company users (platform-company-detail-page.tsx:140)\n * and passkeys (passkeys-card.tsx:75); keksdose's notification inbox and attachment\n * downloads; lenkbank's profiles, projects and segments. The copies differ in the\n * details that are easy to get wrong — which of them truncate, whether the actions\n * are nested in the button, whether a link row is a link at all.\n */\nexport const ListItem = forwardRef<HTMLElement, ListItemProps>(function ListItem(\n {\n title,\n subtitle,\n subtitleLines = 1,\n meta,\n icon: Icon,\n leading,\n trailing,\n actions,\n unread = false,\n status,\n selected = false,\n disabled = false,\n loading = false,\n density: densityProp,\n align = \"center\",\n className,\n targetClassName,\n targetProps,\n bordered = false,\n as = \"li\",\n children,\n bodyClassName,\n href,\n renderLink,\n external = false,\n onClick,\n onAuxClick,\n ...rest\n },\n ref,\n) {\n const list = useContext(ListContext);\n const labels = useKitLabels(\"list\", DEFAULT_LIST_LABELS);\n const kitLink = useKitLink();\n const density = densityProp ?? list.density;\n const pad = PAD[density];\n const isLink = href !== undefined && !disabled;\n const isButton = !isLink && onClick !== undefined && href === undefined;\n const interactive = isLink || isButton;\n const inert = disabled || loading;\n const hasBody = children !== undefined && children !== null && children !== false;\n const titleId = useId();\n\n const mark =\n status ??\n (unread ? <StatusDot tone=\"brand\" size=\"sm\" className={align === \"start\" ? \"mt-1.5\" : undefined} /> : null);\n\n const body = (\n <>\n {Icon && (\n <Icon\n className={cn(\"size-4 shrink-0 text-[var(--text-muted)]\", align === \"start\" && \"mt-0.5\")}\n aria-hidden\n />\n )}\n {leading}\n <span className=\"flex min-w-0 flex-1 flex-col\">\n <span\n // Names the body's group; harmless without one.\n id={hasBody ? titleId : undefined}\n className={cn(\n \"block truncate text-sm text-[var(--text-primary)]\",\n unread ? \"font-semibold\" : \"font-medium\",\n )}\n >\n {title}\n {unread && <span className=\"sr-only\"> ({labels.unread})</span>}\n {external && href !== undefined && <span className=\"sr-only\"> ({labels.opensInNewTab})</span>}\n </span>\n {subtitle != null && (\n <span\n className={cn(\n \"block text-xs text-[var(--text-muted)]\",\n subtitleLines === 2 ? \"line-clamp-2\" : \"truncate\",\n )}\n >\n {subtitle}\n </span>\n )}\n {meta != null && <span className=\"mt-0.5 block truncate text-[11px] leading-snug text-[var(--text-muted)]\">{meta}</span>}\n </span>\n {trailing != null && <span className=\"flex shrink-0 items-center gap-2 text-xs text-[var(--text-muted)]\">{trailing}</span>}\n {loading ? (\n <Spinner label={null} className=\"size-3.5 shrink-0\" />\n ) : (\n external && href !== undefined && (\n <ExternalLink className=\"size-3.5 shrink-0 text-[var(--text-muted)] rtl:-scale-x-100\" aria-hidden />\n )\n )}\n {mark}\n </>\n );\n\n const target = cn(\n \"flex min-w-0 flex-1 text-start\",\n align === \"start\" ? \"items-start\" : \"items-center\",\n pad.target,\n // With a body the target is the top of the box, not all of it, so it takes its\n // own corners and its own hover fill (see `children`).\n hasBody ? \"rounded-md\" : \"rounded-[inherit]\",\n hasBody && interactive && !inert && !selected && \"transition-colors hover:bg-[var(--bg-hover)]\",\n interactive && TARGET_RING,\n interactive && !inert && \"cursor-pointer\",\n loading && \"cursor-progress\",\n targetClassName,\n );\n\n // `role` is the row's own (a button, a link, or nothing on a static block): a\n // targetProps role would silently turn the row into something else.\n const { role: _ignoredRole, ...targetExtras } = targetProps ?? {};\n\n let main: ReactNode;\n if (isLink) {\n const linkProps: ListItemLinkProps = {\n ...(targetExtras as Partial<ListItemLinkProps>),\n ...rest,\n ref: ref as Ref<HTMLAnchorElement>,\n href,\n className: target,\n \"aria-current\": selected ? \"true\" : undefined,\n \"aria-busy\": loading || undefined,\n onClick: loading\n ? (e) => e.preventDefault()\n : (onClick as ListItemLinkProps[\"onClick\"]),\n onAuxClick,\n children: body,\n };\n const { children: linkBody, ...anchorProps } = linkProps;\n const render = external ? undefined : pickLinkRenderer(renderLink, kitLink, href);\n main = render ? (\n <RenderedLink render={render} {...linkProps} />\n ) : (\n <a {...anchorProps} {...(external ? { target: \"_blank\", rel: \"noopener noreferrer\" } : null)}>\n {linkBody}\n </a>\n );\n } else if (isButton) {\n main = (\n <button\n {...(targetExtras as HTMLAttributes<HTMLButtonElement>)}\n {...rest}\n ref={ref as Ref<HTMLButtonElement>}\n type=\"button\"\n // A disabled row is `disabled`: nothing to do there, and nothing to reach. A\n // loading row is only `aria-disabled` — see `loading`.\n disabled={disabled}\n aria-disabled={loading || undefined}\n aria-busy={loading || undefined}\n aria-current={selected ? \"true\" : undefined}\n onClick={loading ? undefined : (onClick as (event: MouseEvent<HTMLButtonElement>) => void)}\n className={target}\n >\n {body}\n </button>\n );\n } else {\n main = (\n <div\n {...(targetExtras as HTMLAttributes<HTMLDivElement>)}\n {...rest}\n ref={ref as Ref<HTMLDivElement>}\n aria-disabled={disabled || undefined}\n aria-busy={loading || undefined}\n className={target}\n >\n {body}\n </div>\n );\n }\n\n const actionsEl =\n actions != null ? <div className={cn(\"flex shrink-0 items-center\", pad.gap, pad.actions)}>{actions}</div> : null;\n\n const Tag = as;\n return (\n <Tag\n className={cn(\n list.separator === \"divider\" && \"border-b border-[var(--border)] last:border-b-0\",\n list.separator === \"divider\" && as === \"li\" && \"py-0.5\",\n )}\n >\n <div\n className={cn(\n \"flex min-w-0 rounded-md border transition-colors\",\n hasBody ? \"flex-col\" : \"items-center\",\n selected\n ? \"border-[var(--brand)] bg-[var(--bg-surface-2)]\"\n : bordered\n ? \"border-[var(--border)]\"\n : \"border-transparent\",\n !hasBody && interactive && !inert && !selected && \"hover:bg-[var(--bg-hover)]\",\n disabled && \"opacity-50\",\n className,\n )}\n >\n {hasBody ? (\n <>\n <div className=\"flex min-w-0 items-center\">\n {main}\n {actionsEl}\n </div>\n <div role=\"group\" aria-labelledby={titleId} className={cn(\"min-w-0\", pad.body, bodyClassName)}>\n {children}\n </div>\n </>\n ) : (\n <>\n {main}\n {actionsEl}\n </>\n )}\n </div>\n </Tag>\n );\n});\n\nfunction RenderedLink({\n render,\n ...props\n}: ListItemLinkProps & { render: (props: ListItemLinkProps) => ReactElement }) {\n return render(props);\n}\n"],"mappings":";AA+DM,SA+PF,UA/PE,KAiRe,YAjRf;AA/DN,SAAS,eAAe,YAAY,YAAY,aAAa;AAE7D,SAAS,oBAAoB;AAE7B,SAAS,UAAU;AACnB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,cAAc,kBAAkB;AACzC,SAAS,wBAAwB;AAW1B,MAAM,sBAAkC;AAAA,EAC7C,QAAQ;AAAA,EACR,eAAe;AACjB;AAaA,MAAM,cAAc,cAAkE;AAAA,EACpF,SAAS;AAAA,EACT,WAAW;AACb,CAAC;AAkBM,MAAM,OAAO,WAAwC,SAASA,MACnE,EAAE,KAAK,MAAM,UAAU,WAAW,YAAY,OAAO,WAAW,UAAU,GAAG,KAAK,GAClF,KACA;AACA,QAAM,MAAM;AACZ,SACE,oBAAC,YAAY,UAAZ,EAAqB,OAAO,EAAE,SAAS,UAAU,GAChD;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ;AAAA,MACA,MAAK;AAAA,MACL,WAAW;AAAA,QACT;AAAA,QACA,cAAc,UAAU,YAAY,YAAY,YAAY;AAAA,QAC5D;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH,GACF;AAEJ,CAAC;AAqBD,MAAM,MAA2F;AAAA,EAC/F,SAAS,EAAE,QAAQ,qBAAqB,SAAS,UAAU,KAAK,WAAW,MAAM,cAAc;AAAA,EAC/F,SAAS,EAAE,QAAQ,qBAAqB,SAAS,QAAQ,KAAK,SAAS,MAAM,cAAc;AAAA,EAC3F,aAAa,EAAE,QAAQ,mBAAmB,SAAS,QAAQ,KAAK,SAAS,MAAM,YAAY;AAC7F;AAEA,MAAM,cACJ;AAmKK,MAAM,WAAW,WAAuC,SAASC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cACA;AAAA,eACH;AAAA,YACA,oBAAC,SAAI,MAAK,SAAQ,mBAAiB,SAAS,WAAW,GAAG,WAAW,IAAI,MAAM,aAAa,GACzF,UACH;AAAA,aACF,IAEA,iCACG;AAAA;AAAA,YACA;AAAA,aACH;AAAA;AAAA,MAEJ;AAAA;AAAA,EACF;AAEJ,CAAC;AAED,SAAS,aAAa;AAAA,EACpB;AAAA,EACA,GAAG;AACL,GAA+E;AAC7E,SAAO,OAAO,KAAK;AACrB;","names":["List","ListItem"]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/list.tsx"],"sourcesContent":["import { createContext, forwardRef, useContext, useId } from \"react\";\nimport type { ComponentPropsWithoutRef, HTMLAttributes, MouseEvent, ReactElement, ReactNode, Ref } from \"react\";\nimport { ExternalLink } from \"lucide-react\";\nimport type { LucideIcon } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport { Spinner } from \"./ui\";\nimport { StatusDot } from \"./status-dot\";\nimport { useKitLabels, useKitLink } from \"../i18n/kit-labels\";\nimport { pickLinkRenderer } from \"./text-link\";\n\n/* ── Labels ───────────────────────────────────────────────────────────────── */\n\nexport interface ListLabels {\n /** Read after an unread row's title — the dot alone says nothing to a screen reader. */\n unread: string;\n /** Read after an external row's title: the row leaves the app in a new tab. */\n opensInNewTab: string;\n}\n\nexport const DEFAULT_LIST_LABELS: ListLabels = {\n unread: \"Unread\",\n opensInNewTab: \"opens in a new tab\",\n};\n\n/* ── List ─────────────────────────────────────────────────────────────────── */\n\n/**\n * `compact` 36px-ish rows for a dense panel (an inbox in a menu), `default` the ~44px\n * row every site draws with `py-2.5`, `comfortable` for a list that is the page.\n */\nexport type ListDensity = \"compact\" | \"default\" | \"comfortable\";\n/** `divider`: a rule between rows (kastlan's `divide-y` lists); `gap`: a small space\n * between rows (lenkbank's `space-y-2`, kastlan's `space-y-1`); `none`: flush. */\nexport type ListSeparator = \"divider\" | \"gap\" | \"none\";\n\nconst ListContext = createContext<{ density: ListDensity; separator: ListSeparator }>({\n density: \"default\",\n separator: \"gap\",\n});\n\nexport interface ListProps extends Omit<ComponentPropsWithoutRef<\"ul\">, \"role\"> {\n /** `ol` when the order means something (a ranked list, numbered segments). */\n as?: \"ul\" | \"ol\";\n /** Every row's density, unless a row says otherwise. Default `default`. */\n density?: ListDensity;\n /** Default `gap`. */\n separator?: ListSeparator;\n}\n\n/**\n * The list of {@link ListItem}s.\n *\n * A `<ul>` with an explicit `role=\"list\"`: Safari drops a list's semantics once its\n * bullets are styled away, and \"list, 7 items\" is exactly what a screen-reader user\n * wants to hear before the first row.\n */\nexport const List = forwardRef<HTMLUListElement, ListProps>(function List(\n { as = \"ul\", density = \"default\", separator = \"gap\", className, children, ...rest },\n ref,\n) {\n const Tag = as;\n return (\n <ListContext.Provider value={{ density, separator }}>\n <Tag\n {...rest}\n ref={ref as Ref<HTMLUListElement & HTMLOListElement>}\n role=\"list\"\n className={cn(\n \"m-0 flex list-none flex-col p-0\",\n separator === \"gap\" && (density === \"compact\" ? \"gap-0.5\" : \"gap-1\"),\n className,\n )}\n >\n {children}\n </Tag>\n </ListContext.Provider>\n );\n});\n\n/* ── ListItem ─────────────────────────────────────────────────────────────── */\n\n/** What {@link ListItemProps.renderLink} is handed. Spread it onto your router's link,\n * mapping `href` to what it calls it — `({ href, ...p }) => <Link to={href} {...p} />`. */\nexport interface ListItemLinkProps {\n href: string;\n /** The row's target look — keep it, or the row's padding and focus ring go. */\n className: string;\n children: ReactNode;\n ref?: Ref<HTMLAnchorElement>;\n onClick?: (event: MouseEvent<HTMLAnchorElement>) => void;\n onAuxClick?: (event: MouseEvent<HTMLAnchorElement>) => void;\n \"aria-current\"?: \"true\";\n \"aria-busy\"?: true;\n id?: string;\n [key: `aria-${string}`]: string | boolean | number | undefined;\n [key: `data-${string}`]: unknown;\n}\n\nconst PAD: Record<ListDensity, { target: string; actions: string; gap: string; body: string }> = {\n compact: { target: \"gap-2 px-2 py-1.5\", actions: \"pe-1.5\", gap: \"gap-0.5\", body: \"px-2 pb-1.5\" },\n default: { target: \"gap-3 px-3 py-2.5\", actions: \"pe-2\", gap: \"gap-1\", body: \"px-3 pb-2.5\" },\n comfortable: { target: \"gap-3 px-4 py-3\", actions: \"pe-3\", gap: \"gap-1\", body: \"px-4 pb-3\" },\n};\n\nconst TARGET_RING =\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--brand)]\";\n\ninterface ListItemBaseProps {\n /** The row's name: one line, truncated — unless {@link titleLines} says otherwise. */\n title: ReactNode;\n /**\n * How many lines the title may take. `1` (default) truncates with an ellipsis, which\n * is right for a name the app chose — a unit number, a user, a file — where the\n * cut-off end is still recognisable and every row keeps one height.\n *\n * `2` clamps at two lines; `\"all\"` shows every line, breaking inside a long word\n * rather than overflowing. For rows whose only name is free text a person typed\n * (kastlan 44): a defect or a note titled by its description, where the first 30\n * characters on a phone say nothing and there is no other field to tell two rows\n * apart. Pair it with `align=\"start\"` so the icon stays by the first line.\n */\n titleLines?: 1 | 2 | \"all\";\n /** The line under it: one line, truncated — or two, with `subtitleLines={2}`. */\n subtitle?: ReactNode;\n /** `2` for a line that is a body rather than a label (keksdose's notification text). */\n subtitleLines?: 1 | 2;\n /** A third line in the caption type: a timestamp, \"Updated …\" (lenkbank's projects). */\n meta?: ReactNode;\n /** A Lucide icon before the text, muted, at 16px. */\n icon?: LucideIcon;\n /** Anything else before the text — an avatar, a file-type badge, a drag handle. */\n leading?: ReactNode;\n /**\n * Inside the main target, at its end: a status chip, a file size, a count. It is part\n * of what the row's click does and part of its accessible name — so never a control.\n * Controls go in {@link actions}.\n */\n trailing?: ReactNode;\n /**\n * Controls BESIDE the main target, never inside it: copy, delete, \"Open\".\n *\n * A button inside a button (or a link) is invalid HTML, and a screen reader folds the\n * inner one into the outer one's name where it cannot be reached. lenkbank found this\n * three times (profile-bar.tsx:110, projects-page.tsx:61, segment-list.tsx:165) and\n * solved it the same way each time: the row's target and its actions are siblings in\n * one bordered box. That is this slot — and being siblings is also what stops a click\n * on \"Copy\" from selecting the row.\n */\n actions?: ReactNode;\n /**\n * Rich content UNDER the title row and outside its target: photos, per-row buttons,\n * form fields — kastlan's handover room inspector (room-inspector.tsx), the handover\n * detail page and the wizard's defects step (wizard/defects-step.tsx), which draw\n * each room or defect as a `Card variant=\"inset\"` because a row could not hold a\n * photo strip with its own buttons.\n *\n * The same rule as {@link actions}, one row down: the title area stays ONE named\n * target (the button or link, with the title and subtitle as its name), and the body\n * is its sibling, never nested in it — a thumbnail's \"Remove\" inside the row's button\n * would be invalid HTML and unreachable by a screen reader. The body is a\n * `role=\"group\"` named by the row's title (`aria-labelledby`), so tabbing into the\n * third photo's button of the second room is heard as \"Kitchen, group\" first rather\n * than as a button floating free of any row. Inside the row's box, so a `selected`\n * border and a `divider` hold both; the hover fill stays on the target alone, since\n * the body is not what a click on the row does.\n */\n children?: ReactNode;\n /** Classes on the {@link children} body. */\n bodyClassName?: string;\n /**\n * The unread mark: a brand dot at the row's end, the title in semibold, and \"Unread\"\n * read after the title (keksdose notification-inbox.tsx:215). For another status,\n * pass your own mark in {@link status}.\n */\n unread?: boolean;\n /** A mark in the unread dot's place — a `StatusDot` of another tone, a count. */\n status?: ReactNode;\n /**\n * The row is the chosen one — a brand border on the raised surface (lenkbank's\n * profile bar and segment list). `aria-current=\"true\"` on the target: the row is the\n * current one of a set, which is what those lists mean, not a pressed toggle.\n */\n selected?: boolean;\n disabled?: boolean;\n /**\n * Work under way on the row — keksdose's attachment download (support-attachments\n * .tsx:91). A spinner takes the trailing edge, the target is `aria-busy`, and a\n * second click is ignored. The row keeps focus: `aria-disabled`, not `disabled`, so\n * a keyboard user is not dropped back to the top of the page mid-download.\n */\n loading?: boolean;\n /** Overrides the {@link List}'s density for this row. */\n density?: ListDensity;\n /** `start` for rows whose text runs to two or three lines, so the icon sits by the\n * title rather than the middle of the paragraph. Default `center`. */\n align?: \"center\" | \"start\";\n /** Classes on the visible row (the bordered box). */\n className?: string;\n /** Classes on the main target (the button, link or static block). */\n targetClassName?: string;\n /**\n * Extra attributes and handlers for the main target — e.g. HTML5 drag-and-drop\n * (`draggable`, `onDragStart`, `onDragEnd`): lenkbank's segment list drags the WHOLE\n * 44px row, and a grip inside the button cannot start a drag in Firefox. Spread first,\n * so the row's own role, name, state and click handling always win.\n */\n targetProps?: HTMLAttributes<HTMLElement>;\n /**\n * A visible border while unselected, instead of the transparent one. For rows laid out\n * as a wrapping strip (lenkbank's profile bar), where borderless rows read as loose\n * text. The selected row's brand border is unchanged.\n */\n bordered?: boolean;\n /** `div` for a single row outside a {@link List}; an `<li>` must sit in a list. */\n as?: \"li\" | \"div\";\n /** Reaches the main target — the element with the row's name and action. */\n id?: string;\n [key: `aria-${string}`]: string | boolean | number | undefined;\n [key: `data-${string}`]: unknown;\n}\n\n/**\n * The row is ONE thing to activate, so the types allow one: a button, an in-app link,\n * an external link, or nothing (a static row, like kastlan's passkey and user lists).\n */\nexport type ListItemProps = ListItemBaseProps &\n (\n | {\n /** Makes the row a button — select, open, mark read. */\n onClick: (event: MouseEvent<HTMLButtonElement>) => void;\n href?: never;\n renderLink?: never;\n external?: never;\n onAuxClick?: never;\n }\n | {\n /**\n * Makes the row a link. A real `<a href>`, so a middle click opens it in a\n * background tab (keksdose feedback #451) — which a button calling `navigate`\n * cannot do.\n */\n href: string;\n /** Your router's link for an in-app `href`. Default: the `<UiKitProvider\n * linkComponent>`, then `<a>`. The API `Chip`, `StatTile` and `MenuItem`\n * share. Ignored for an `external` row. */\n renderLink?: (props: ListItemLinkProps) => ReactElement;\n /**\n * The link leaves the app: a plain `<a target=\"_blank\" rel=\"noopener\n * noreferrer\">` with an external-link mark, and \"opens in a new tab\" read\n * after the title. keksdose's inbox rows whose URL is absolute.\n */\n external?: boolean;\n /** Runs on a click, before the navigation (mark the row read). */\n onClick?: (event: MouseEvent<HTMLAnchorElement>) => void;\n /** Runs on a middle click, which fires no `click` — keksdose marks a\n * notification read here too, so a row opened into a background tab does not\n * stay unread. */\n onAuxClick?: (event: MouseEvent<HTMLAnchorElement>) => void;\n }\n | {\n onClick?: never;\n href?: never;\n renderLink?: never;\n external?: never;\n onAuxClick?: never;\n }\n );\n\n/**\n * One row of a {@link List}: leading icon or avatar, title and subtitle (both\n * truncating by default), a trailing slot, and — beside the row, not inside it — its actions.\n *\n * All three apps draw this row by hand, a dozen times: kastlan's units\n * (building-detail-page.tsx:402), open tickets (group-overview-page.tsx:160), activity\n * feed (activity-feed.tsx:53), company users (platform-company-detail-page.tsx:140)\n * and passkeys (passkeys-card.tsx:75); keksdose's notification inbox and attachment\n * downloads; lenkbank's profiles, projects and segments. The copies differ in the\n * details that are easy to get wrong — which of them truncate, whether the actions\n * are nested in the button, whether a link row is a link at all.\n */\nexport const ListItem = forwardRef<HTMLElement, ListItemProps>(function ListItem(\n {\n title,\n titleLines = 1,\n subtitle,\n subtitleLines = 1,\n meta,\n icon: Icon,\n leading,\n trailing,\n actions,\n unread = false,\n status,\n selected = false,\n disabled = false,\n loading = false,\n density: densityProp,\n align = \"center\",\n className,\n targetClassName,\n targetProps,\n bordered = false,\n as = \"li\",\n children,\n bodyClassName,\n href,\n renderLink,\n external = false,\n onClick,\n onAuxClick,\n ...rest\n },\n ref,\n) {\n const list = useContext(ListContext);\n const labels = useKitLabels(\"list\", DEFAULT_LIST_LABELS);\n const kitLink = useKitLink();\n const density = densityProp ?? list.density;\n const pad = PAD[density];\n const isLink = href !== undefined && !disabled;\n const isButton = !isLink && onClick !== undefined && href === undefined;\n const interactive = isLink || isButton;\n const inert = disabled || loading;\n const hasBody = children !== undefined && children !== null && children !== false;\n const titleId = useId();\n\n const mark =\n status ??\n (unread ? <StatusDot tone=\"brand\" size=\"sm\" className={align === \"start\" ? \"mt-1.5\" : undefined} /> : null);\n\n const body = (\n <>\n {Icon && (\n <Icon\n className={cn(\"size-4 shrink-0 text-[var(--text-muted)]\", align === \"start\" && \"mt-0.5\")}\n aria-hidden\n />\n )}\n {leading}\n <span className=\"flex min-w-0 flex-1 flex-col\">\n <span\n // Names the body's group; harmless without one.\n id={hasBody ? titleId : undefined}\n className={cn(\n \"block text-sm text-[var(--text-primary)]\",\n titleLines === 1 ? \"truncate\" : titleLines === 2 ? \"line-clamp-2 break-words\" : \"break-words\",\n unread ? \"font-semibold\" : \"font-medium\",\n )}\n >\n {title}\n {unread && <span className=\"sr-only\"> ({labels.unread})</span>}\n {external && href !== undefined && <span className=\"sr-only\"> ({labels.opensInNewTab})</span>}\n </span>\n {subtitle != null && (\n <span\n className={cn(\n \"block text-xs text-[var(--text-muted)]\",\n subtitleLines === 2 ? \"line-clamp-2\" : \"truncate\",\n )}\n >\n {subtitle}\n </span>\n )}\n {meta != null && <span className=\"mt-0.5 block truncate text-[11px] leading-snug text-[var(--text-muted)]\">{meta}</span>}\n </span>\n {trailing != null && <span className=\"flex shrink-0 items-center gap-2 text-xs text-[var(--text-muted)]\">{trailing}</span>}\n {loading ? (\n <Spinner label={null} className=\"size-3.5 shrink-0\" />\n ) : (\n external && href !== undefined && (\n <ExternalLink className=\"size-3.5 shrink-0 text-[var(--text-muted)] rtl:-scale-x-100\" aria-hidden />\n )\n )}\n {mark}\n </>\n );\n\n const target = cn(\n \"flex min-w-0 flex-1 text-start\",\n align === \"start\" ? \"items-start\" : \"items-center\",\n pad.target,\n // With a body the target is the top of the box, not all of it, so it takes its\n // own corners and its own hover fill (see `children`).\n hasBody ? \"rounded-md\" : \"rounded-[inherit]\",\n hasBody && interactive && !inert && !selected && \"transition-colors hover:bg-[var(--bg-hover)]\",\n interactive && TARGET_RING,\n interactive && !inert && \"cursor-pointer\",\n loading && \"cursor-progress\",\n targetClassName,\n );\n\n // `role` is the row's own (a button, a link, or nothing on a static block): a\n // targetProps role would silently turn the row into something else.\n const { role: _ignoredRole, ...targetExtras } = targetProps ?? {};\n\n let main: ReactNode;\n if (isLink) {\n const linkProps: ListItemLinkProps = {\n ...(targetExtras as Partial<ListItemLinkProps>),\n ...rest,\n ref: ref as Ref<HTMLAnchorElement>,\n href,\n className: target,\n \"aria-current\": selected ? \"true\" : undefined,\n \"aria-busy\": loading || undefined,\n onClick: loading\n ? (e) => e.preventDefault()\n : (onClick as ListItemLinkProps[\"onClick\"]),\n onAuxClick,\n children: body,\n };\n const { children: linkBody, ...anchorProps } = linkProps;\n const render = external ? undefined : pickLinkRenderer(renderLink, kitLink, href);\n main = render ? (\n <RenderedLink render={render} {...linkProps} />\n ) : (\n <a {...anchorProps} {...(external ? { target: \"_blank\", rel: \"noopener noreferrer\" } : null)}>\n {linkBody}\n </a>\n );\n } else if (isButton) {\n main = (\n <button\n {...(targetExtras as HTMLAttributes<HTMLButtonElement>)}\n {...rest}\n ref={ref as Ref<HTMLButtonElement>}\n type=\"button\"\n // A disabled row is `disabled`: nothing to do there, and nothing to reach. A\n // loading row is only `aria-disabled` — see `loading`.\n disabled={disabled}\n aria-disabled={loading || undefined}\n aria-busy={loading || undefined}\n aria-current={selected ? \"true\" : undefined}\n onClick={loading ? undefined : (onClick as (event: MouseEvent<HTMLButtonElement>) => void)}\n className={target}\n >\n {body}\n </button>\n );\n } else {\n main = (\n <div\n {...(targetExtras as HTMLAttributes<HTMLDivElement>)}\n {...rest}\n ref={ref as Ref<HTMLDivElement>}\n aria-disabled={disabled || undefined}\n aria-busy={loading || undefined}\n className={target}\n >\n {body}\n </div>\n );\n }\n\n const actionsEl =\n actions != null ? <div className={cn(\"flex shrink-0 items-center\", pad.gap, pad.actions)}>{actions}</div> : null;\n\n const Tag = as;\n return (\n <Tag\n className={cn(\n list.separator === \"divider\" && \"border-b border-[var(--border)] last:border-b-0\",\n list.separator === \"divider\" && as === \"li\" && \"py-0.5\",\n )}\n >\n <div\n className={cn(\n \"flex min-w-0 rounded-md border transition-colors\",\n hasBody ? \"flex-col\" : \"items-center\",\n selected\n ? \"border-[var(--brand)] bg-[var(--bg-surface-2)]\"\n : bordered\n ? \"border-[var(--border)]\"\n : \"border-transparent\",\n !hasBody && interactive && !inert && !selected && \"hover:bg-[var(--bg-hover)]\",\n disabled && \"opacity-50\",\n className,\n )}\n >\n {hasBody ? (\n <>\n <div className=\"flex min-w-0 items-center\">\n {main}\n {actionsEl}\n </div>\n <div role=\"group\" aria-labelledby={titleId} className={cn(\"min-w-0\", pad.body, bodyClassName)}>\n {children}\n </div>\n </>\n ) : (\n <>\n {main}\n {actionsEl}\n </>\n )}\n </div>\n </Tag>\n );\n});\n\nfunction RenderedLink({\n render,\n ...props\n}: ListItemLinkProps & { render: (props: ListItemLinkProps) => ReactElement }) {\n return render(props);\n}\n"],"mappings":";AA+DM,SA4QF,UA5QE,KA+Re,YA/Rf;AA/DN,SAAS,eAAe,YAAY,YAAY,aAAa;AAE7D,SAAS,oBAAoB;AAE7B,SAAS,UAAU;AACnB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,cAAc,kBAAkB;AACzC,SAAS,wBAAwB;AAW1B,MAAM,sBAAkC;AAAA,EAC7C,QAAQ;AAAA,EACR,eAAe;AACjB;AAaA,MAAM,cAAc,cAAkE;AAAA,EACpF,SAAS;AAAA,EACT,WAAW;AACb,CAAC;AAkBM,MAAM,OAAO,WAAwC,SAASA,MACnE,EAAE,KAAK,MAAM,UAAU,WAAW,YAAY,OAAO,WAAW,UAAU,GAAG,KAAK,GAClF,KACA;AACA,QAAM,MAAM;AACZ,SACE,oBAAC,YAAY,UAAZ,EAAqB,OAAO,EAAE,SAAS,UAAU,GAChD;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ;AAAA,MACA,MAAK;AAAA,MACL,WAAW;AAAA,QACT;AAAA,QACA,cAAc,UAAU,YAAY,YAAY,YAAY;AAAA,QAC5D;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH,GACF;AAEJ,CAAC;AAqBD,MAAM,MAA2F;AAAA,EAC/F,SAAS,EAAE,QAAQ,qBAAqB,SAAS,UAAU,KAAK,WAAW,MAAM,cAAc;AAAA,EAC/F,SAAS,EAAE,QAAQ,qBAAqB,SAAS,QAAQ,KAAK,SAAS,MA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ACA,UAAU,aAAa;AAAA,YACvB,WACI,mDACA,WACE,2BACA;AAAA,YACN,CAAC,WAAW,eAAe,CAAC,SAAS,CAAC,YAAY;AAAA,YAClD,YAAY;AAAA,YACZ;AAAA,UACF;AAAA,UAEC,oBACC,iCACE;AAAA,iCAAC,SAAI,WAAU,6BACZ;AAAA;AAAA,cACA;AAAA,eACH;AAAA,YACA,oBAAC,SAAI,MAAK,SAAQ,mBAAiB,SAAS,WAAW,GAAG,WAAW,IAAI,MAAM,aAAa,GACzF,UACH;AAAA,aACF,IAEA,iCACG;AAAA;AAAA,YACA;AAAA,aACH;AAAA;AAAA,MAEJ;AAAA;AAAA,EACF;AAEJ,CAAC;AAED,SAAS,aAAa;AAAA,EACpB;AAAA,EACA,GAAG;AACL,GAA+E;AAC7E,SAAO,OAAO,KAAK;AACrB;","names":["List","ListItem"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/modal.tsx"],"sourcesContent":["import { createContext, useEffect, useRef, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport type {\n ComponentPropsWithoutRef,\n KeyboardEvent,\n MouseEvent as ReactMouseEvent,\n PointerEvent as ReactPointerEvent,\n ReactNode,\n} from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { useFocusTrap } from \"../hooks/use-focus-trap\";\nimport { useBodyScrollLock } from \"../hooks/use-body-scroll-lock\";\nimport { useOverlayHistory } from \"../hooks/use-overlay-history\";\nimport { useDialogParam, type DialogParam } from \"../hooks/use-search-param-state\";\nimport { OVERLAY_EXIT_MS, prefersReducedMotion, useCloseTransition } from \"../hooks/use-close-transition\";\n\n/**\n * Drag the panel by its top strip, in pointer space (dev#460).\n *\n * Deliberately not a library and not persisted: the offset is component state that\n * dies with the dialog. It starts only on a press that lands on the panel's own\n * chrome — never on a field, a button or a link, which is what keeps \"drag to select\n * text in the textarea\" working. Above `md` only: below it the panel is a\n * full-width bottom sheet with nothing beside it to uncover.\n *\n * The whole gesture stays on the PANEL — captured pointer, React handlers — rather than\n * on `window`. The first shape of this added `pointermove`/`pointerup` to `window` from\n * inside the `pointerdown` handler and took them off again from the `pointerup` handler,\n * so the teardown ran only if the gesture ended: React never sees a listener added from\n * an event handler, and an unmount mid-drag left a live `pointermove` on `window` for\n * the life of the page, pinning this hook's state with it. The one caller that enables\n * dragging is the feedback composer, which closes ITSELF on submit — a Ctrl+Enter sent\n * with the pointer still down is exactly that order of events, once per drag.\n */\nfunction useDragOffset(enabled: boolean) {\n const [offset, setOffset] = useState<{ x: number; y: number } | null>(null);\n const from = useRef<{ x: number; y: number; ox: number; oy: number } | null>(null);\n\n const endDrag = () => {\n from.current = null;\n };\n\n return {\n /** Back to where the panel opens. A `Modal` with an `open` prop outlives its own\n * closes, so \"the position resets when the dialog closes\" needs saying. */\n reset: () => setOffset(null),\n style: offset ? { transform: `translate(${offset.x}px, ${offset.y}px)` } : undefined,\n handlers: !enabled\n ? undefined\n : {\n onPointerDown: (e: ReactPointerEvent<HTMLDivElement>) => {\n if (e.button !== 0 || window.innerWidth < 768) return;\n const target = e.target as HTMLElement;\n // Only the panel itself and its non-interactive chrome start a drag; a\n // press inside any control belongs to that control.\n if (target.closest(\"input,textarea,select,button,a,[role='button']\")) return;\n from.current = { x: e.clientX, y: e.clientY, ox: offset?.x ?? 0, oy: offset?.y ?? 0 };\n try {\n // Capture is what lets the handlers live on the panel: every later\n // pointer event for this pointer retargets here, so the drag keeps\n // working once the pointer outruns the panel's own box — which it always\n // does, since the panel moves out from under it.\n e.currentTarget.setPointerCapture(e.pointerId);\n } catch {\n // jsdom implements no pointer capture, and a browser throws\n // NotFoundError for a pointerId that is already gone. Neither is worth\n // refusing the drag: uncaptured, the panel still gets the moves that\n // land on it.\n }\n },\n onPointerMove: (e: ReactPointerEvent<HTMLDivElement>) => {\n const start = from.current;\n if (!start) return;\n setOffset({ x: start.ox + e.clientX - start.x, y: start.oy + e.clientY - start.y });\n },\n onPointerUp: endDrag,\n // A cancel (the browser taking the pointer for a scroll or a gesture) and a\n // lost capture both mean no `pointerup` is coming. Without them the drag would\n // stay \"live\" and the next move over the panel would jump it.\n onPointerCancel: endDrag,\n onLostPointerCapture: endDrag,\n },\n };\n}\n\n/**\n * The panel's own ANIMATED dismissal, for chrome rendered inside it. `DialogFrame`'s X\n * and its `actions(close)` read this, so a Cancel or an X lowers the panel exactly the\n * way Escape does — calling `onClose` from inside unmounts with no exit, which is the\n * documented limit of {@link useCloseTransition}. `null` outside a `Modal`.\n */\nexport const ModalCloseContext = createContext<(() => void) | null>(null);\n\n/**\n * Backdrop handlers that close only when a press starts AND ends on the\n * backdrop itself. A plain onClick fires on mouseup, so dragging a text\n * selection that starts inside the panel and releases over the backdrop would\n * dismiss the dialog (feedback #254) — and the reverse drag would too, since\n * click targets the common ancestor of the down/up elements.\n */\nexport function useBackdropClose(onClose: () => void) {\n const pressStartedOnBackdrop = useRef(false);\n return {\n onMouseDown: (e: ReactMouseEvent<HTMLDivElement>) => {\n pressStartedOnBackdrop.current = e.target === e.currentTarget;\n },\n onMouseUp: (e: ReactMouseEvent<HTMLDivElement>) => {\n const started = pressStartedOnBackdrop.current;\n pressStartedOnBackdrop.current = false;\n if (started && e.target === e.currentTarget) onClose();\n },\n };\n}\n\n// Tab-cycle target set: the interactive descendants the focus trap rotates\n// through. Querying live (per keystroke) means dynamically rendered fields are\n// included automatically.\n/**\n * `extends ComponentPropsWithoutRef<\"div\">` so anything a `<div>` takes reaches the\n * PANEL — the element with `role=\"dialog\"`, which is the one a consumer means. That is\n * where a `data-tour` anchor, a test id, an `aria-describedby` or an `aria-label` has\n * to land; before this, a closed prop list dropped all four silently (audit §api-design).\n */\nexport interface ModalProps extends Omit<ComponentPropsWithoutRef<\"div\">, \"role\"> {\n /** Invoked on backdrop click and on Escape. */\n onClose: () => void;\n /**\n * Who decides whether the dialog is up, when the caller wants to keep it MOUNTED.\n *\n * Left out, the dialog is open for as long as it is mounted — `{open && <Modal/>}`,\n * which is every caller before this prop and stays exactly as it was. That idiom has\n * one blind spot: a close the CALLER decides on (a save that succeeded, a\n * `setOpen(false)` from outside) unmounts the panel on the spot, with no exit,\n * because there is nothing left to animate. kastlan's `FormModal` was nothing but an\n * `if (!open) return null` gate in front of this.\n *\n * Passed, the component stays mounted while closed and renders nothing, and a flip\n * to `false` plays the same exit a dismissal does before the panel goes. The focus\n * trap, the scroll lock and the Back-gesture history entry are held only while\n * `open` is true — they are released the moment it turns false, so focus is back on\n * the trigger while the panel is still lowering. A dismissal (Escape, the backdrop,\n * Back, the frame's X) animates first and then calls `onClose`; the `false` that\n * comes back from it is not animated a second time.\n *\n * The body is unmounted once the exit has finished, as it is today, so a form inside\n * still starts fresh on the next open.\n */\n open?: boolean;\n /** `\"alertdialog\"` for a dialog that interrupts to ask a question the user must\n * answer (a confirmation) — screen readers announce it with more urgency. Only the\n * two dialog roles are allowed: the panel stays modal either way. */\n role?: \"dialog\" | \"alertdialog\";\n children: ReactNode;\n /**\n * Panel max-width: `md` (28rem), `lg` (32rem), `xl` (48rem).\n *\n * `xl` exists because two callers had already written `className=\"max-w-3xl\"` to\n * reach it — the payee backfill's preview table and the price-merge dialog, both\n * of which hold a list and several fields rather than one question. A caller\n * patching a missing size IS the signal that the size is missing, and a\n * hand-written width in a `className` is a width nothing else can line up with.\n *\n * The panel is `w-full` under every one of them, so the cap only bites once the\n * viewport is wider than it: on a phone all three are the same full-width bottom\n * sheet. Nothing here may introduce a `min-w-*`, which is what would break that.\n */\n size?: \"md\" | \"lg\" | \"xl\";\n /** Extra classes for the panel (e.g. `space-y-3` for form content spacing). */\n className?: string;\n /** id of the heading element, wired to `aria-labelledby`. */\n labelledBy?: string;\n /**\n * Extra key handling on the panel (e.g. Ctrl/Cmd+Enter to submit). Runs first;\n * if it calls `preventDefault()` the built-in Escape/Tab handling is skipped\n * for that event.\n */\n onKeyDown?: (e: KeyboardEvent<HTMLDivElement>) => void;\n /**\n * Drop the backdrop's mobile margin so the panel can reach the screen edges\n * (a full-screen sheet on phones). The panel still needs its own\n * `h-[100dvh] max-w-full rounded-none` classes via `className` to fill it; the\n * desktop `md:p-4` margin is kept. Defaults to false (padded on all sizes).\n */\n fullBleed?: boolean;\n /**\n * Let the user drag the panel out of the way by its top edge (Keksdose feedback\n * dev#460: *\"Make the feedback dialog draggable so I can see behind it if it\n * blocks something.\"*).\n *\n * Opt-in, because it only makes sense for a dialog whose content is ABOUT the page\n * behind it — the feedback composer is the case, an ordinary form is not, and a\n * draggable panel that has nothing to reveal is a control that can only get lost.\n *\n * Pointer-only by design: it is a \"move this out of the way\" gesture, not a layout\n * choice worth persisting, and the position resets when the dialog closes. On a\n * phone the panel is a bottom sheet the width of the screen, so dragging is\n * suppressed there — there is nothing beside it to see.\n */\n draggable?: boolean;\n /**\n * Bind the open state to a URL search param (0.12.0): `\"edit\"` is open while\n * `?edit` is in the query, `{ key: \"dialog\", value: \"create-lease\" }` while\n * `?dialog=create-lease` is. The URL is then the only state — `open` is ignored —\n * and the dialog opens from anywhere that sets the param: {@link useDialogParam}'s\n * setter, a `<Link>`, a shared link, a reload.\n *\n * kastlan's `useDialogParam` did this beside the dialog, so its open state could be\n * deep-linked and captured in a feedback report. Here it also owns the history:\n * opening through `useDialogParam` pushes an entry, so the Back gesture closes the\n * dialog by leaving it, and a close (Escape, the backdrop, the X) goes back over\n * that entry rather than stacking a second one. The dialog's own Back handling\n * ({@link useOverlayHistory}'s throwaway entry) stays off in this mode — the param's\n * entry already is one, and two would take two Back presses to close one dialog.\n *\n * `onClose` still runs, after the param is cleared. Requires a react-router Router.\n */\n urlParam?: DialogParam;\n}\n\n/**\n * The URL-bound dialog: the param is the open state, and closing clears it. A\n * component of its own so the router hook is only called by a `Modal` that asked for\n * it — a plain `Modal` must keep working with no Router above it.\n */\nfunction UrlParamModal({ urlParam, onClose, ...rest }: ModalProps & { urlParam: DialogParam }) {\n const [open, setOpen] = useDialogParam(urlParam);\n // Closed from here the moment the dismissal is decided. Going back is a traversal\n // the browser lands a task later, and between the two the param still says \"open\":\n // without this the panel, already lowered, would pop back up for that task.\n const [leaving, setLeaving] = useState(false);\n if (leaving && !open) setLeaving(false);\n return (\n <ModalPanel\n {...rest}\n open={open && !leaving}\n ownHistoryEntry={false}\n onClose={() => {\n setLeaving(true);\n setOpen(false);\n onClose();\n }}\n />\n );\n}\n\n/**\n * Centered (bottom-sheet on mobile) modal dialog: dimmed backdrop, single\n * rounded panel. Owns the overlay mechanics that the hand-rolled dialogs each\n * re-implemented or lacked — backdrop-click + Escape to close, the platform Back\n * gesture (Keksdose feedback #172), background scroll lock (feedback #204), focus\n * into the panel on open and back to the trigger on close, a Tab focus trap, and\n * `role=\"dialog\"`/`aria-modal`.\n */\nexport function Modal(props: ModalProps) {\n return props.urlParam !== undefined ? (\n <UrlParamModal {...props} urlParam={props.urlParam} />\n ) : (\n <ModalPanel {...props} />\n );\n}\n\nfunction ModalPanel({\n onClose,\n open,\n children,\n size = \"md\",\n className,\n labelledBy,\n onKeyDown,\n fullBleed,\n draggable,\n style,\n role = \"dialog\",\n urlParam: _urlParam,\n ownHistoryEntry = true,\n ...rest\n}: ModalProps & {\n /** False when the URL already holds an entry for this dialog — see `urlParam`. */\n ownHistoryEntry?: boolean;\n}) {\n const panelRef = useRef<HTMLDivElement>(null);\n const drag = useDragOffset(Boolean(draggable));\n // Without `open`, mounted means open — the constant `true` every hook below used to\n // be given. With it, `open` itself.\n const active = open ?? true;\n\n // Whether the last close came through `requestClose`, i.e. has ALREADY been\n // animated. Set in the same batch as the caller's `onClose`, so the render that sees\n // `open` turn false also sees this and does not lower the panel a second time.\n const [dismissed, setDismissed] = useState(false);\n // The exit of a close the caller decided on (only reachable with `open`). Adjusted\n // during render when `open` flips — `Collapse`'s pattern — so the very render that\n // closes it already paints the `-out` classes rather than a frame of nothing.\n const [exiting, setExiting] = useState(false);\n const [prevOpen, setPrevOpen] = useState(open);\n if (open !== prevOpen) {\n setPrevOpen(open);\n setDismissed(false);\n setExiting(open === false && prevOpen === true && !dismissed && !prefersReducedMotion());\n if (open) drag.reset();\n }\n useEffect(() => {\n if (!exiting) return;\n const timer = setTimeout(() => setExiting(false), OVERLAY_EXIT_MS);\n return () => clearTimeout(timer);\n }, [exiting]);\n\n // The panel lowers itself before the caller unmounts it (live #320 rework). Every\n // dismissal below goes through `requestClose`; `onClose` still does the closing, one\n // animation later. A caller that closes the dialog ITSELF — after a save, say —\n // unmounts with no exit unless it passes `open`, which is what that prop is for.\n const { closing, requestClose } = useCloseTransition(() => {\n setDismissed(true);\n onClose();\n });\n // A panel on its way out after `open` turned false is already closed: a press on\n // its fading backdrop must not report a second close.\n const backdropClose = useBackdropClose(active ? requestClose : () => {});\n // Back means the same as Escape here. On a phone Escape doesn't exist, so without\n // this the only way out of a dialog is finding its close button — and Back, the\n // gesture everyone reaches for, navigated the page underneath instead (#172).\n // Held only while open: a closed `open={false}` dialog must not own a history entry.\n useOverlayHistory(active && ownHistoryEntry, requestClose);\n\n // Through the shared hook and not by hand: this component's own save/restore copy\n // was one half of the pair that left the page permanently unscrollable when a dialog\n // containing an open sheet was closed — see the note in use-body-scroll-lock.ts.\n useBodyScrollLock(active);\n\n // Focus the panel itself (not the first field) so opening doesn't pop the mobile\n // keyboard, while still moving focus into the dialog for keyboard and screen-reader\n // users. Through the shared hook since this component is where it came from — the\n // hook adds per-keystroke recomputation, a guard on restoring to a detached node,\n // and nesting, none of which this copy had. Released when `open` turns false, which\n // hands focus back to the trigger while the panel is still on its way out.\n useFocusTrap(panelRef, { active, initialFocus: \"container\" });\n const leaving = closing || exiting;\n\n const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n onKeyDown?.(e);\n if (e.defaultPrevented) return;\n if (e.key === \"Escape\") {\n e.stopPropagation();\n if (active) requestClose();\n return;\n }\n // Tab containment lives in useFocusTrap, which listens on the panel itself.\n };\n\n // Portal to <body> so the `fixed inset-0 z-50` overlay escapes whatever stacking\n // context its caller sits in. Rendered inline, a modal opened from e.g. the top\n // bar (a z-30 context) could paint BELOW a sibling z-30 sticky element like the\n // expanded transaction editor (feedback #320). The tour/command-palette overlays\n // already portal for the same reason.\n if (!active && !exiting) return null;\n return createPortal(\n <div\n // Out of the accessibility tree for the length of a caller-driven exit: focus is\n // already back on the page, and an `aria-modal` panel that is leaving would hide\n // that page from a screen reader for 220ms. Not `inert` — that would let a tap\n // fall through the fading backdrop to the row underneath.\n aria-hidden={exiting || undefined}\n className={cn(\n // Live #320. The panel below rises only where it is bottom-anchored: from md up\n // it is centred, and a centred box sliding up from off-screen reads as a\n // different component arriving rather than as the same one settling.\n leaving ? \"animate-overlay-out\" : \"animate-overlay\",\n \"fixed inset-0 z-50 flex items-end justify-center bg-black/40 md:items-center\",\n fullBleed ? \"p-0 md:p-4\" : \"p-4\",\n )}\n {...backdropClose}\n >\n <div\n // `...rest` FIRST, everything the dialog needs to be a dialog after it. A\n // wrapper that spreads its own props through to this one cannot then take away\n // the role, the modality or the `tabIndex={-1}` that `useFocusTrap` needs —\n // losing any of the three is silent, and the symptom (a dialog a screen reader\n // walks straight out of) shows up nowhere near the call site that caused it.\n {...rest}\n ref={panelRef}\n // Normalised at runtime too: an untyped caller's `role=\"presentation\"` must not\n // take the dialog role away (props-passthrough pins that).\n role={role === \"alertdialog\" ? \"alertdialog\" : \"dialog\"}\n aria-modal=\"true\"\n aria-labelledby={labelledBy}\n tabIndex={-1}\n onKeyDown={handleKeyDown}\n {...drag.handlers}\n // MERGED, not replaced: `drag.style` is undefined until a drag starts, so\n // assigning it outright would drop a caller's own `style` on every render but\n // the ones where the panel is being dragged.\n style={{ ...style, ...drag.style }}\n className={cn(\n leaving ? \"animate-sheet-out md:animate-none\" : \"animate-sheet md:animate-none\",\n \"w-full rounded-lg border border-[var(--border)] bg-[var(--bg-surface)] shadow-sm outline-none\",\n { md: \"max-w-md\", lg: \"max-w-lg\", xl: \"max-w-3xl\" }[size],\n // A panel taller than the screen has to scroll ITSELF. The backdrop is\n // `fixed inset-0` and the body is scroll-locked while a dialog is open, so\n // without this the overflow simply had nowhere to go: on a phone the panel\n // is bottom-anchored, so it grew UPWARD past the top edge and the part that\n // went past it could not be reached by any gesture (Keksdose live #254, on\n // the price-merge dialog — but it was every dialog with more than a screen\n // of content). `max-h-full` resolves against the backdrop's content box,\n // which is the viewport minus its own padding, so the panel stops exactly\n // where the screen does; `overscroll-contain` keeps the fling inside it.\n //\n // Three callers had already patched themselves with `max-h-[90vh]` +\n // an inner scroller. Those still win — `cn` is tailwind-merge — and this is\n // the default they should not have needed.\n \"max-h-full overflow-y-auto overscroll-contain\",\n \"p-4\",\n // The grab affordance sits on the panel's own top strip: a drag handle of\n // its own would be one more control in a dialog that is mostly one field.\n draggable && \"md:[&>*:first-child]:cursor-grab\",\n className,\n )}\n >\n <ModalCloseContext.Provider value={requestClose}>{children}</ModalCloseContext.Provider>\n </div>\n </div>,\n document.body,\n );\n}\n"],"mappings":";AAwOI;AAxOJ,SAAS,eAAe,WAAW,QAAQ,gBAAgB;AAC3D,SAAS,oBAAoB;AAQ7B,SAAS,UAAU;AACnB,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAClC,SAAS,yBAAyB;AAClC,SAAS,sBAAwC;AACjD,SAAS,iBAAiB,sBAAsB,0BAA0B;AAoB1E,SAAS,cAAc,SAAkB;AACvC,QAAM,CAAC,QAAQ,SAAS,IAAI,SAA0C,IAAI;AAC1E,QAAM,OAAO,OAAgE,IAAI;AAEjF,QAAM,UAAU,MAAM;AACpB,SAAK,UAAU;AAAA,EACjB;AAEA,SAAO;AAAA;AAAA;AAAA,IAGL,OAAO,MAAM,UAAU,IAAI;AAAA,IAC3B,OAAO,SAAS,EAAE,WAAW,aAAa,OAAO,CAAC,OAAO,OAAO,CAAC,MAAM,IAAI;AAAA,IAC3E,UAAU,CAAC,UACP,SACA;AAAA,MACE,eAAe,CAAC,MAAyC;AACvD,YAAI,EAAE,WAAW,KAAK,OAAO,aAAa,IAAK;AAC/C,cAAM,SAAS,EAAE;AAGjB,YAAI,OAAO,QAAQ,gDAAgD,EAAG;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CAAC;AAC5D,QAAM,UAAU,WAAW;AAE3B,QAAM,gBAAgB,CAAC,MAAqC;AAC1D,gBAAY,CAAC;AACb,QAAI,EAAE,iBAAkB;AACxB,QAAI,EAAE,QAAQ,UAAU;AACtB,QAAE,gBAAgB;AAClB,UAAI,OAAQ,cAAa;AACzB;AAAA,IACF;AAAA,EAEF;AAOA,MAAI,CAAC,UAAU,CAAC,QAAS,QAAO;AAChC,SAAO;AAAA,IACL;AAAA,MAAC;AAAA;AAAA,QAKC,eAAa,WAAW;AAAA,QACxB,WAAW;AAAA;AAAA;AAAA;AAAA,UAIT,UAAU,wBAAwB;AAAA,UAClC;AAAA,UACA,YAAY,eAAe;AAAA,QAC7B;AAAA,QACC,GAAG;AAAA,QAEJ;AAAA,UAAC;AAAA;AAAA,YAME,GAAG;AAAA,YACJ,KAAK;AAAA,YAGL,MAAM,SAAS,gBAAgB,gBAAgB;AAAA,YAC/C,cAAW;AAAA,YACX,mBAAiB;AAAA,YACjB,UAAU;AAAA,YACV,WAAW;AAAA,YACV,GAAG,KAAK;AAAA,YAIT,OAAO,EAAE,GAAG,OAAO,GAAG,KAAK,MAAM;AAAA,YACjC,WAAW;AAAA,cACT,UAAU,sCAAsC;AAAA,cAChD;AAAA,cACA,EAAE,IAAI,YAAY,IAAI,YAAY,IAAI,YAAY,EAAE,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,cAcxD;AAAA,cACA;AAAA;AAAA;AAAA,cAGA,aAAa;AAAA,cACb;AAAA,YACF;AAAA,YAEA,8BAAC,kBAAkB,UAAlB,EAA2B,OAAO,cAAe,UAAS;AAAA;AAAA,QAC7D;AAAA;AAAA,IACF;AAAA,IACA,SAAS;AAAA,EACX;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/modal.tsx"],"sourcesContent":["import { createContext, useEffect, useRef, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport type {\n ComponentPropsWithoutRef,\n KeyboardEvent,\n MouseEvent as ReactMouseEvent,\n PointerEvent as ReactPointerEvent,\n ReactNode,\n} from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { useFocusTrap } from \"../hooks/use-focus-trap\";\nimport { useBodyScrollLock } from \"../hooks/use-body-scroll-lock\";\nimport { useOverlayHistory } from \"../hooks/use-overlay-history\";\nimport { useDialogParam, type DialogParam } from \"../hooks/use-search-param-state\";\nimport { OVERLAY_EXIT_MS, prefersReducedMotion, useCloseTransition } from \"../hooks/use-close-transition\";\n\n/**\n * Drag the panel by its top strip, in pointer space (dev#460).\n *\n * Deliberately not a library and not persisted: the offset is component state that\n * dies with the dialog. It starts only on a press that lands on the panel's own\n * chrome — never on a field, a button or a link, which is what keeps \"drag to select\n * text in the textarea\" working. Above `md` only: below it the panel is a\n * full-width bottom sheet with nothing beside it to uncover.\n *\n * The whole gesture stays on the PANEL — captured pointer, React handlers — rather than\n * on `window`. The first shape of this added `pointermove`/`pointerup` to `window` from\n * inside the `pointerdown` handler and took them off again from the `pointerup` handler,\n * so the teardown ran only if the gesture ended: React never sees a listener added from\n * an event handler, and an unmount mid-drag left a live `pointermove` on `window` for\n * the life of the page, pinning this hook's state with it. The one caller that enables\n * dragging is the feedback composer, which closes ITSELF on submit — a Ctrl+Enter sent\n * with the pointer still down is exactly that order of events, once per drag.\n */\nfunction useDragOffset(enabled: boolean) {\n const [offset, setOffset] = useState<{ x: number; y: number } | null>(null);\n const from = useRef<{ x: number; y: number; ox: number; oy: number } | null>(null);\n\n const endDrag = () => {\n from.current = null;\n };\n\n return {\n /** Back to where the panel opens. A `Modal` with an `open` prop outlives its own\n * closes, so \"the position resets when the dialog closes\" needs saying. */\n reset: () => setOffset(null),\n style: offset ? { transform: `translate(${offset.x}px, ${offset.y}px)` } : undefined,\n handlers: !enabled\n ? undefined\n : {\n onPointerDown: (e: ReactPointerEvent<HTMLDivElement>) => {\n if (e.button !== 0 || window.innerWidth < 768) return;\n const target = e.target as HTMLElement;\n // Only the panel itself and its non-interactive chrome start a drag; a\n // press inside any control belongs to that control.\n if (target.closest(\"input,textarea,select,button,a,[role='button']\")) return;\n from.current = { x: e.clientX, y: e.clientY, ox: offset?.x ?? 0, oy: offset?.y ?? 0 };\n try {\n // Capture is what lets the handlers live on the panel: every later\n // pointer event for this pointer retargets here, so the drag keeps\n // working once the pointer outruns the panel's own box — which it always\n // does, since the panel moves out from under it.\n e.currentTarget.setPointerCapture(e.pointerId);\n } catch {\n // jsdom implements no pointer capture, and a browser throws\n // NotFoundError for a pointerId that is already gone. Neither is worth\n // refusing the drag: uncaptured, the panel still gets the moves that\n // land on it.\n }\n },\n onPointerMove: (e: ReactPointerEvent<HTMLDivElement>) => {\n const start = from.current;\n if (!start) return;\n setOffset({ x: start.ox + e.clientX - start.x, y: start.oy + e.clientY - start.y });\n },\n onPointerUp: endDrag,\n // A cancel (the browser taking the pointer for a scroll or a gesture) and a\n // lost capture both mean no `pointerup` is coming. Without them the drag would\n // stay \"live\" and the next move over the panel would jump it.\n onPointerCancel: endDrag,\n onLostPointerCapture: endDrag,\n },\n };\n}\n\n/**\n * The panel's own ANIMATED dismissal, for chrome rendered inside it. `DialogFrame`'s X\n * and its `actions(close)` read this, so a Cancel or an X lowers the panel exactly the\n * way Escape does — calling `onClose` from inside unmounts with no exit, which is the\n * documented limit of {@link useCloseTransition}. `null` outside a `Modal`.\n */\nexport const ModalCloseContext = createContext<(() => void) | null>(null);\n\n/**\n * Backdrop handlers that close only when a press starts AND ends on the\n * backdrop itself. A plain onClick fires on mouseup, so dragging a text\n * selection that starts inside the panel and releases over the backdrop would\n * dismiss the dialog (feedback #254) — and the reverse drag would too, since\n * click targets the common ancestor of the down/up elements.\n */\nexport function useBackdropClose(onClose: () => void) {\n const pressStartedOnBackdrop = useRef(false);\n return {\n onMouseDown: (e: ReactMouseEvent<HTMLDivElement>) => {\n pressStartedOnBackdrop.current = e.target === e.currentTarget;\n },\n onMouseUp: (e: ReactMouseEvent<HTMLDivElement>) => {\n const started = pressStartedOnBackdrop.current;\n pressStartedOnBackdrop.current = false;\n if (started && e.target === e.currentTarget) onClose();\n },\n };\n}\n\n// Tab-cycle target set: the interactive descendants the focus trap rotates\n// through. Querying live (per keystroke) means dynamically rendered fields are\n// included automatically.\n/**\n * `extends ComponentPropsWithoutRef<\"div\">` so anything a `<div>` takes reaches the\n * PANEL — the element with `role=\"dialog\"`, which is the one a consumer means. That is\n * where a `data-tour` anchor, a test id, an `aria-describedby` or an `aria-label` has\n * to land; before this, a closed prop list dropped all four silently (audit §api-design).\n */\nexport interface ModalProps extends Omit<ComponentPropsWithoutRef<\"div\">, \"role\"> {\n /** Invoked on backdrop click and on Escape. */\n onClose: () => void;\n /**\n * Who decides whether the dialog is up, when the caller wants to keep it MOUNTED.\n *\n * Left out, the dialog is open for as long as it is mounted — `{open && <Modal/>}`,\n * which is every caller before this prop and stays exactly as it was. That idiom has\n * one blind spot: a close the CALLER decides on (a save that succeeded, a\n * `setOpen(false)` from outside) unmounts the panel on the spot, with no exit,\n * because there is nothing left to animate. kastlan's `FormModal` was nothing but an\n * `if (!open) return null` gate in front of this.\n *\n * Passed, the component stays mounted while closed and renders nothing, and a flip\n * to `false` plays the same exit a dismissal does before the panel goes. The focus\n * trap, the scroll lock and the Back-gesture history entry are held only while\n * `open` is true — they are released the moment it turns false, so focus is back on\n * the trigger while the panel is still lowering. A dismissal (Escape, the backdrop,\n * Back, the frame's X) animates first and then calls `onClose`; the `false` that\n * comes back from it is not animated a second time.\n *\n * The body is unmounted once the exit has finished, as it is today, so a form inside\n * still starts fresh on the next open.\n */\n open?: boolean;\n /** `\"alertdialog\"` for a dialog that interrupts to ask a question the user must\n * answer (a confirmation) — screen readers announce it with more urgency. Only the\n * two dialog roles are allowed: the panel stays modal either way. */\n role?: \"dialog\" | \"alertdialog\";\n children: ReactNode;\n /**\n * Panel max-width: `md` (28rem), `lg` (32rem), `xl` (48rem).\n *\n * `xl` exists because two callers had already written `className=\"max-w-3xl\"` to\n * reach it — the payee backfill's preview table and the price-merge dialog, both\n * of which hold a list and several fields rather than one question. A caller\n * patching a missing size IS the signal that the size is missing, and a\n * hand-written width in a `className` is a width nothing else can line up with.\n *\n * The panel is `w-full` under every one of them, so the cap only bites once the\n * viewport is wider than it: on a phone all three are the same full-width bottom\n * sheet. Nothing here may introduce a `min-w-*`, which is what would break that.\n */\n size?: \"md\" | \"lg\" | \"xl\";\n /** Extra classes for the panel (e.g. `space-y-3` for form content spacing). */\n className?: string;\n /** id of the heading element, wired to `aria-labelledby`. */\n labelledBy?: string;\n /**\n * Extra key handling on the panel (e.g. Ctrl/Cmd+Enter to submit). Runs first;\n * if it calls `preventDefault()` the built-in Escape/Tab handling is skipped\n * for that event.\n */\n onKeyDown?: (e: KeyboardEvent<HTMLDivElement>) => void;\n /**\n * Drop the backdrop's mobile margin so the panel can reach the screen edges\n * (a full-screen sheet on phones). The panel still needs its own\n * `h-[100dvh] max-w-full rounded-none` classes via `className` to fill it; the\n * desktop `md:p-4` margin is kept. Defaults to false (padded on all sizes).\n */\n fullBleed?: boolean;\n /**\n * Let the user drag the panel out of the way by its top edge (Keksdose feedback\n * dev#460: *\"Make the feedback dialog draggable so I can see behind it if it\n * blocks something.\"*).\n *\n * Opt-in, because it only makes sense for a dialog whose content is ABOUT the page\n * behind it — the feedback composer is the case, an ordinary form is not, and a\n * draggable panel that has nothing to reveal is a control that can only get lost.\n *\n * Pointer-only by design: it is a \"move this out of the way\" gesture, not a layout\n * choice worth persisting, and the position resets when the dialog closes. On a\n * phone the panel is a bottom sheet the width of the screen, so dragging is\n * suppressed there — there is nothing beside it to see.\n */\n draggable?: boolean;\n /**\n * Bind the open state to a URL search param (0.12.0): `\"edit\"` is open while\n * `?edit` is in the query, `{ key: \"dialog\", value: \"create-lease\" }` while\n * `?dialog=create-lease` is. The URL is then the only state — `open` is ignored —\n * and the dialog opens from anywhere that sets the param: {@link useDialogParam}'s\n * setter, a `<Link>`, a shared link, a reload.\n *\n * kastlan's `useDialogParam` did this beside the dialog, so its open state could be\n * deep-linked and captured in a feedback report. Here it also owns the history:\n * opening through `useDialogParam` pushes an entry, so the Back gesture closes the\n * dialog by leaving it, and a close (Escape, the backdrop, the X) goes back over\n * that entry rather than stacking a second one. The dialog's own Back handling\n * ({@link useOverlayHistory}'s throwaway entry) stays off in this mode — the param's\n * entry already is one, and two would take two Back presses to close one dialog.\n *\n * `onClose` still runs, after the param is cleared. Requires a react-router Router.\n */\n urlParam?: DialogParam;\n}\n\n/**\n * The URL-bound dialog: the param is the open state, and closing clears it. A\n * component of its own so the router hook is only called by a `Modal` that asked for\n * it — a plain `Modal` must keep working with no Router above it.\n */\nfunction UrlParamModal({ urlParam, onClose, ...rest }: ModalProps & { urlParam: DialogParam }) {\n const [open, setOpen] = useDialogParam(urlParam);\n // Closed from here the moment the dismissal is decided. Going back is a traversal\n // the browser lands a task later, and between the two the param still says \"open\":\n // without this the panel, already lowered, would pop back up for that task.\n const [leaving, setLeaving] = useState(false);\n if (leaving && !open) setLeaving(false);\n return (\n <ModalPanel\n {...rest}\n open={open && !leaving}\n ownHistoryEntry={false}\n onClose={() => {\n setLeaving(true);\n setOpen(false);\n onClose();\n }}\n />\n );\n}\n\n/**\n * Centered (bottom-sheet on mobile) modal dialog: dimmed backdrop, single\n * rounded panel. Owns the overlay mechanics that the hand-rolled dialogs each\n * re-implemented or lacked — backdrop-click + Escape to close, the platform Back\n * gesture (Keksdose feedback #172), background scroll lock (feedback #204), focus\n * into the panel on open and back to the trigger on close, a Tab focus trap, and\n * `role=\"dialog\"`/`aria-modal`.\n */\nexport function Modal(props: ModalProps) {\n return props.urlParam !== undefined ? (\n <UrlParamModal {...props} urlParam={props.urlParam} />\n ) : (\n <ModalPanel {...props} />\n );\n}\n\nfunction ModalPanel({\n onClose,\n open,\n children,\n size = \"md\",\n className,\n labelledBy,\n onKeyDown,\n fullBleed,\n draggable,\n style,\n role = \"dialog\",\n urlParam: _urlParam,\n ownHistoryEntry = true,\n ...rest\n}: ModalProps & {\n /** False when the URL already holds an entry for this dialog — see `urlParam`. */\n ownHistoryEntry?: boolean;\n}) {\n const panelRef = useRef<HTMLDivElement>(null);\n const drag = useDragOffset(Boolean(draggable));\n // Without `open`, mounted means open — the constant `true` every hook below used to\n // be given. With it, `open` itself.\n const active = open ?? true;\n\n // Whether the last close came through `requestClose`, i.e. has ALREADY been\n // animated. Set in the same batch as the caller's `onClose`, so the render that sees\n // `open` turn false also sees this and does not lower the panel a second time.\n const [dismissed, setDismissed] = useState(false);\n // The exit of a close the caller decided on (only reachable with `open`). Adjusted\n // during render when `open` flips — `Collapse`'s pattern — so the very render that\n // closes it already paints the `-out` classes rather than a frame of nothing.\n const [exiting, setExiting] = useState(false);\n const [prevOpen, setPrevOpen] = useState(open);\n if (open !== prevOpen) {\n setPrevOpen(open);\n setDismissed(false);\n setExiting(open === false && prevOpen === true && !dismissed && !prefersReducedMotion());\n if (open) drag.reset();\n }\n useEffect(() => {\n if (!exiting) return;\n const timer = setTimeout(() => setExiting(false), OVERLAY_EXIT_MS);\n return () => clearTimeout(timer);\n }, [exiting]);\n\n // The panel lowers itself before the caller unmounts it (live #320 rework). Every\n // dismissal below goes through `requestClose`; `onClose` still does the closing, one\n // animation later. A caller that closes the dialog ITSELF — after a save, say —\n // unmounts with no exit unless it passes `open`, which is what that prop is for.\n const { closing, requestClose } = useCloseTransition(() => {\n setDismissed(true);\n onClose();\n });\n // A panel on its way out after `open` turned false is already closed: a press on\n // its fading backdrop must not report a second close.\n const backdropClose = useBackdropClose(active ? requestClose : () => {});\n // Back means the same as Escape here. On a phone Escape doesn't exist, so without\n // this the only way out of a dialog is finding its close button — and Back, the\n // gesture everyone reaches for, navigated the page underneath instead (#172).\n // Held only while open: a closed `open={false}` dialog must not own a history entry.\n useOverlayHistory(active && ownHistoryEntry, requestClose);\n\n // Through the shared hook and not by hand: this component's own save/restore copy\n // was one half of the pair that left the page permanently unscrollable when a dialog\n // containing an open sheet was closed — see the note in use-body-scroll-lock.ts.\n useBodyScrollLock(active);\n\n // Focus the panel itself (not the first field) so opening doesn't pop the mobile\n // keyboard, while still moving focus into the dialog for keyboard and screen-reader\n // users. Through the shared hook since this component is where it came from — the\n // hook adds per-keystroke recomputation, a guard on restoring to a detached node,\n // and nesting, none of which this copy had. Released when `open` turns false, which\n // hands focus back to the trigger while the panel is still on its way out.\n useFocusTrap(panelRef, { active, initialFocus: \"container\" });\n const leaving = closing || exiting;\n\n const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n onKeyDown?.(e);\n if (e.defaultPrevented) return;\n if (e.key === \"Escape\") {\n e.stopPropagation();\n if (active) requestClose();\n return;\n }\n // Tab containment lives in useFocusTrap, which listens on the panel itself.\n };\n\n // Portal to <body> so the `fixed inset-0 z-50` overlay escapes whatever stacking\n // context its caller sits in. Rendered inline, a modal opened from e.g. the top\n // bar (a z-30 context) could paint BELOW a sibling z-30 sticky element like the\n // expanded transaction editor (feedback #320). The tour/command-palette overlays\n // already portal for the same reason.\n if (!active && !exiting) return null;\n return createPortal(\n <div\n // Out of the accessibility tree for the length of a caller-driven exit: focus is\n // already back on the page, and an `aria-modal` panel that is leaving would hide\n // that page from a screen reader for 220ms. Not `inert` — that would let a tap\n // fall through the fading backdrop to the row underneath.\n aria-hidden={exiting || undefined}\n className={cn(\n // Live #320. The panel below rises only where it is bottom-anchored: from md up\n // it is centred, and a centred box sliding up from off-screen reads as a\n // different component arriving rather than as the same one settling.\n leaving ? \"animate-overlay-out\" : \"animate-overlay\",\n \"fixed inset-0 z-50 flex items-end justify-center bg-black/40 md:items-center\",\n fullBleed ? \"p-0 md:p-4\" : \"p-4\",\n )}\n {...backdropClose}\n >\n {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions -- always\n role=\"dialog\" or \"alertdialog\" (the ternary hides that from the rule): `onKeyDown`\n is Escape-to-close per the APG dialog pattern, and the drag handlers are\n swipe-to-dismiss, whose keyboard path is that same Escape. */}\n <div\n // `...rest` FIRST, everything the dialog needs to be a dialog after it. A\n // wrapper that spreads its own props through to this one cannot then take away\n // the role, the modality or the `tabIndex={-1}` that `useFocusTrap` needs —\n // losing any of the three is silent, and the symptom (a dialog a screen reader\n // walks straight out of) shows up nowhere near the call site that caused it.\n {...rest}\n ref={panelRef}\n // Normalised at runtime too: an untyped caller's `role=\"presentation\"` must not\n // take the dialog role away (props-passthrough pins that).\n role={role === \"alertdialog\" ? \"alertdialog\" : \"dialog\"}\n aria-modal=\"true\"\n aria-labelledby={labelledBy}\n tabIndex={-1}\n onKeyDown={handleKeyDown}\n {...drag.handlers}\n // MERGED, not replaced: `drag.style` is undefined until a drag starts, so\n // assigning it outright would drop a caller's own `style` on every render but\n // the ones where the panel is being dragged.\n style={{ ...style, ...drag.style }}\n className={cn(\n leaving ? \"animate-sheet-out md:animate-none\" : \"animate-sheet md:animate-none\",\n \"w-full rounded-lg border border-[var(--border)] bg-[var(--bg-surface)] shadow-sm outline-none\",\n { md: \"max-w-md\", lg: \"max-w-lg\", xl: \"max-w-3xl\" }[size],\n // A panel taller than the screen has to scroll ITSELF. The backdrop is\n // `fixed inset-0` and the body is scroll-locked while a dialog is open, so\n // without this the overflow simply had nowhere to go: on a phone the panel\n // is bottom-anchored, so it grew UPWARD past the top edge and the part that\n // went past it could not be reached by any gesture (Keksdose live #254, on\n // the price-merge dialog — but it was every dialog with more than a screen\n // of content). `max-h-full` resolves against the backdrop's content box,\n // which is the viewport minus its own padding, so the panel stops exactly\n // where the screen does; `overscroll-contain` keeps the fling inside it.\n //\n // Three callers had already patched themselves with `max-h-[90vh]` +\n // an inner scroller. Those still win — `cn` is tailwind-merge — and this is\n // the default they should not have needed.\n \"max-h-full overflow-y-auto overscroll-contain\",\n \"p-4\",\n // The grab affordance sits on the panel's own top strip: a drag handle of\n // its own would be one more control in a dialog that is mostly one field.\n draggable && \"md:[&>*:first-child]:cursor-grab\",\n className,\n )}\n >\n <ModalCloseContext.Provider value={requestClose}>{children}</ModalCloseContext.Provider>\n </div>\n </div>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AAA,YACJ,KAAK;AAAA,YAGL,MAAM,SAAS,gBAAgB,gBAAgB;AAAA,YAC/C,cAAW;AAAA,YACX,mBAAiB;AAAA,YACjB,UAAU;AAAA,YACV,WAAW;AAAA,YACV,GAAG,KAAK;AAAA,YAIT,OAAO,EAAE,GAAG,OAAO,GAAG,KAAK,MAAM;AAAA,YACjC,WAAW;AAAA,cACT,UAAU,sCAAsC;AAAA,cAChD;AAAA,cACA,EAAE,IAAI,YAAY,IAAI,YAAY,IAAI,YAAY,EAAE,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,cAcxD;AAAA,cACA;AAAA;AAAA;AAAA,cAGA,aAAa;AAAA,cACb;AAAA,YACF;AAAA,YAEA,8BAAC,kBAAkB,UAAlB,EAA2B,OAAO,cAAe,UAAS;AAAA;AAAA,QAC7D;AAAA;AAAA,IACF;AAAA,IACA,SAAS;AAAA,EACX;AACF;","names":[]}
|
|
@@ -71,7 +71,7 @@ function MultiEntityCombobox({
|
|
|
71
71
|
create: createLabel
|
|
72
72
|
});
|
|
73
73
|
const common = useKitLabels("common", DEFAULT_COMMON_LABELS);
|
|
74
|
-
const { open, results, resolve, setOpen } = core;
|
|
74
|
+
const { open, results, resolve, setOpen, query, triggerRef } = core;
|
|
75
75
|
const listboxId = useId();
|
|
76
76
|
const valueSet = useMemo(() => new Set(value), [value]);
|
|
77
77
|
const locale = useKitLocale();
|
|
@@ -85,11 +85,11 @@ function MultiEntityCombobox({
|
|
|
85
85
|
const chosen = value.map(resolve);
|
|
86
86
|
return chosen.every(Boolean) ? listFormat.format(chosen.map((o) => o.label)) : labels.selectedCount(value.length);
|
|
87
87
|
})();
|
|
88
|
-
const q =
|
|
88
|
+
const q = query.trim();
|
|
89
89
|
const showCreate = Boolean(onCreate) && q.length > 0 && !results.some((o) => o.label.toLowerCase() === q.toLowerCase());
|
|
90
90
|
const showClear = Boolean(clearable && value.length > 0 && !disabled);
|
|
91
91
|
const toggle = (o) => {
|
|
92
|
-
core.
|
|
92
|
+
core.rememberOption(o);
|
|
93
93
|
if (valueSet.has(o.value)) onChange(value.filter((v) => v !== o.value));
|
|
94
94
|
else onChange([...value, o.value]);
|
|
95
95
|
};
|
|
@@ -103,7 +103,7 @@ function MultiEntityCombobox({
|
|
|
103
103
|
/* @__PURE__ */ jsxs(
|
|
104
104
|
"button",
|
|
105
105
|
{
|
|
106
|
-
ref:
|
|
106
|
+
ref: triggerRef,
|
|
107
107
|
id,
|
|
108
108
|
type: "button",
|
|
109
109
|
role: "combobox",
|
|
@@ -144,19 +144,25 @@ function MultiEntityCombobox({
|
|
|
144
144
|
children: summary
|
|
145
145
|
}
|
|
146
146
|
),
|
|
147
|
-
showClear ?
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
147
|
+
showClear ? (
|
|
148
|
+
/* eslint-disable-next-line jsx-a11y/click-events-have-key-events -- tabIndex -1 inside
|
|
149
|
+
the trigger <button>, so it never holds focus and a key handler here could
|
|
150
|
+
never fire. A pointer shortcut; the keyboard path is unticking the options
|
|
151
|
+
in the open list. */
|
|
152
|
+
/* @__PURE__ */ jsx(
|
|
153
|
+
"span",
|
|
154
|
+
{
|
|
155
|
+
role: "button",
|
|
156
|
+
tabIndex: -1,
|
|
157
|
+
"aria-label": labels.clear,
|
|
158
|
+
onClick: (e) => {
|
|
159
|
+
e.stopPropagation();
|
|
160
|
+
onChange([]);
|
|
161
|
+
},
|
|
162
|
+
className: "absolute end-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-[var(--text-placeholder)] hover:text-[var(--text-secondary)]",
|
|
163
|
+
children: /* @__PURE__ */ jsx(X, { className: "size-4" })
|
|
164
|
+
}
|
|
165
|
+
)
|
|
160
166
|
) : /* @__PURE__ */ jsx(FieldChevron, {})
|
|
161
167
|
]
|
|
162
168
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/multi-entity-combobox.tsx"],"sourcesContent":["import { useId, useMemo, type ComponentPropsWithoutRef, type ReactNode } from \"react\";\nimport { X } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport { FieldChevron, FieldLabel, FIELD_TRIGGER, FIELD_FLOATING_PAD, FIELD_INVALID } from \"./ui\";\nimport {\n ComboboxPanel,\n useComboboxCore,\n useComboboxFieldError,\n type ComboOption,\n} from \"./combobox-core\";\nimport {\n DEFAULT_COMBOBOX_LABELS,\n DEFAULT_COMMON_LABELS,\n useKitLabels,\n useKitLocale,\n} from \"../i18n/kit-labels\";\n\n/** `onChange` is the kit's — \"a selection was made\", carrying values — rather\n * than the div's form event, so the DOM's spelling of it is omitted. */\nexport interface MultiEntityComboboxProps<V extends string | number>\n extends Omit<ComponentPropsWithoutRef<\"div\">, \"onChange\"> {\n /** Selected ids. */\n value: V[];\n onChange: (value: V[]) => void;\n /** Already-loaded options (client-side filtered); also resolves selected labels. */\n options?: ComboOption<V>[];\n /** Async option source, debounced + race-safe; a rejection shows\n * `loadErrorLabel`. When set, `options` resolves labels only. */\n loadOptions?: (query: string) => Promise<ComboOption<V>[]>;\n loading?: boolean;\n label?: ReactNode;\n placeholder?: string;\n searchPlaceholder?: string;\n emptyLabel?: string;\n /** Trigger summary when 1+ selected (default: the labels as a locale-formatted\n * list, or `combobox.selectedCount` when a label can't be resolved). */\n itemLabel?: (count: number) => string;\n clearable?: boolean;\n clearLabel?: string;\n /** The phone sheet's close button. Its own prop rather than a reuse of\n * `clearLabel`: \"clear the selection\" and \"close this screen\" are different\n * actions, and on a full-screen sheet the close button is the only way out —\n * so it is the one control here that MUST be in the reader's language. */\n closeLabel?: string;\n disabled?: boolean;\n /** When set, a \"create\" row appears for a non-empty query with no exact match.\n * The panel stays open (adding the new entity to `value` is the caller's job). */\n onCreate?: (query: string) => void;\n createLabel?: (query: string) => string;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\n /** What is wrong with the value, as {@link Input}'s `error`: rendered under the\n * field, on the trigger's `aria-describedby`, and implies `invalid`. */\n error?: ReactNode;\n /** Narrow `options` client-side by the query. Default `true`; `false` shows them\n * as given (a server-ranked list). */\n filter?: boolean;\n /** Offer nothing, and call no `loadOptions`, below this many characters. Default\n * `0`, i.e. the list loads as the panel opens. */\n minChars?: number;\n /** `loadOptions` debounce. Default 150 ms. */\n debounceMs?: number;\n /** Shown when `loadOptions` rejects. Default: `combobox.loadError`. */\n loadErrorLabel?: string;\n}\n\n/**\n * Multi-value sibling of {@link EntityCombobox}: pick several entities by search,\n * with the same async `loadOptions`/`onCreate` support. Rows show a checkbox and\n * toggle without closing the panel; the trigger summarises the selection.\n */\nexport function MultiEntityCombobox<V extends string | number>({\n value,\n onChange,\n options,\n loadOptions,\n loading,\n label,\n placeholder,\n searchPlaceholder,\n emptyLabel,\n itemLabel,\n clearable,\n clearLabel,\n closeLabel,\n disabled,\n onCreate,\n createLabel,\n className,\n invalid,\n error,\n filter,\n minChars,\n debounceMs,\n loadErrorLabel,\n \"aria-label\": ariaLabel,\n // The control's own wiring, taken off `rest` so it lands on the TRIGGER rather than\n // the wrapper: `Field`'s render-prop spreads `{ id, aria-describedby, aria-invalid,\n // aria-required }`, and on the role-less wrapper div the label's `htmlFor` named\n // nothing and the hint and required state described nothing — kastlan's\n // communication-page To/Cc/Bcc and lease-tenants-step.tsx read as unnamed pickers.\n id,\n \"aria-describedby\": ariaDescribedBy,\n \"aria-invalid\": ariaInvalid,\n \"aria-required\": ariaRequired,\n ...rest\n}: MultiEntityComboboxProps<V>) {\n const core = useComboboxCore<V>({\n options,\n loadOptions,\n loading,\n filter,\n minChars,\n debounceMs,\n });\n const field = useComboboxFieldError(\n error,\n invalid || ariaInvalid === true || ariaInvalid === \"true\",\n ariaDescribedBy,\n );\n // The props are the per-instance overrides, the provider the app-wide ones; a\n // prop left `undefined` falls through to the provider rather than masking it.\n const labels = useKitLabels(\"combobox\", DEFAULT_COMBOBOX_LABELS, {\n search: searchPlaceholder,\n noResults: emptyLabel,\n clear: clearLabel,\n create: createLabel,\n });\n const common = useKitLabels(\"common\", DEFAULT_COMMON_LABELS);\n const { open, results, resolve, setOpen } = core;\n // One id per instance, generated here rather than in the core: `aria-controls` on\n // the trigger has to name the list while the list is still closed, so the id\n // belongs to whoever renders both ends of it.\n const listboxId = useId();\n\n const valueSet = useMemo(() => new Set(value), [value]);\n // A list of NAMES, not a sentence, so the narrow conjunction: English gets\n // \"Food, Rent, Travel\" (no \"and\" squeezed into a truncating trigger), German and\n // French still get their \"und\"/\"et\" where the language insists on it, and Japanese\n // and Chinese get the ideographic comma \"、\". The `unit` type looked like the\n // natural fit for a summary, but in ja/zh it concatenates the names with nothing\n // between them at all.\n const locale = useKitLocale();\n const listFormat = useMemo(\n () => new Intl.ListFormat(locale, { type: \"conjunction\", style: \"narrow\" }),\n [locale],\n );\n const summary = (() => {\n if (value.length === 0) return placeholder ?? \"\";\n if (itemLabel) return itemLabel(value.length);\n const chosen = value.map(resolve);\n return chosen.every(Boolean)\n ? listFormat.format(chosen.map((o) => o!.label))\n : labels.selectedCount(value.length);\n })();\n\n const q = core.query.trim();\n const showCreate =\n Boolean(onCreate) && q.length > 0 && !results.some((o) => o.label.toLowerCase() === q.toLowerCase());\n const showClear = Boolean(clearable && value.length > 0 && !disabled);\n\n const toggle = (o: ComboOption<V>) => {\n core.cacheRef.current.set(o.value, o);\n if (valueSet.has(o.value)) onChange(value.filter((v) => v !== o.value));\n else onChange([...value, o.value]);\n // Stay open — multi-select keeps adding.\n };\n\n return (\n // `rest` dresses the wrapper, which has no role; the accessible NAME — and the\n // id, description, invalid and required state above — go on the trigger, which\n // 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 id={id}\n type=\"button\"\n // A combobox, not a button. The distinction is not pedantry: this control\n // carried `aria-invalid`, which `button` does not support, so a required\n // field left empty painted a rose border and told a reader nothing at all —\n // and ESLint flagged it as exactly that (`role-supports-aria-props`). The\n // fix the audit asked for is the role that describes what this IS: a closed\n // choice that expands into the list named below. `combobox` supports\n // `aria-invalid`, so the border and the announcement finally agree.\n role=\"combobox\"\n aria-expanded={open}\n aria-controls={listboxId}\n aria-haspopup=\"listbox\"\n // The label is a floating <span>, not a <label for>, so without this the\n // trigger's accessible name is whatever value happens to be selected —\n // \"Checking\" with nothing saying it is the account. The label AND the\n // value, because `aria-label` replaces the content rather than adding to\n // it, and a control that announces only its name has lost the answer.\n // A caller's own name wins over the composition: two fields labelled\n // \"Account\" on a transfer form are the from and the to, and only the\n // caller knows which is which.\n aria-label={\n ariaLabel ??\n (typeof label === \"string\" ? common.fieldValue(label, summary) : undefined)\n }\n disabled={disabled}\n aria-invalid={field.isInvalid || undefined}\n aria-describedby={field.describedBy}\n aria-required={ariaRequired}\n onClick={() => !disabled && setOpen((o) => !o)}\n // Down/Up opens the list from the closed trigger, per the APG. Enter and\n // Space already do it through the button's own click.\n onKeyDown={(e) => {\n if (disabled) return;\n if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n e.preventDefault();\n setOpen(true);\n }\n }}\n className={cn(\n FIELD_TRIGGER,\n \"pe-9\",\n label !== undefined && FIELD_FLOATING_PAD,\n disabled && \"cursor-not-allowed opacity-50\",\n field.isInvalid && FIELD_INVALID,\n )}\n >\n <span\n className={cn(\n \"min-w-0 truncate\",\n // Inherit FIELD_BASE's ink for a value, keep the placeholder tone\n // (`--text-placeholder`) — the same rule every field on a form row\n // follows (Keksdose dev#477).\n !value.length && \"text-[var(--text-placeholder)]\",\n )}\n >\n {summary}\n </span>\n {showClear ? (\n <span\n role=\"button\"\n tabIndex={-1}\n aria-label={labels.clear}\n onClick={(e) => {\n e.stopPropagation();\n onChange([]);\n }}\n className=\"absolute end-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-[var(--text-placeholder)] hover:text-[var(--text-secondary)]\"\n >\n <X className=\"size-4\" />\n </span>\n ) : (\n <FieldChevron />\n )}\n </button>\n <ComboboxPanel\n core={core}\n listboxId={listboxId}\n multi\n // On a phone the panel becomes a full-screen sheet, which needs the field's\n // own label to say what it is asking for (live #200).\n sheetTitle={label ?? placeholder}\n searchPlaceholder={labels.search}\n emptyLabel={labels.noResults}\n closeLabel={closeLabel}\n loadErrorLabel={loadErrorLabel}\n isSelected={(v) => valueSet.has(v)}\n onChoose={toggle}\n showCreate={showCreate}\n onCreate={() => {\n onCreate?.(q);\n core.setQuery(\"\");\n }}\n createContent={labels.create(q)}\n />\n {field.errorEl}\n </div>\n );\n}\n"],"mappings":";AA8K8B,cACxB,YADwB;AA9K9B,SAAS,OAAO,eAA8D;AAC9E,SAAS,SAAS;AAClB,SAAS,UAAU;AACnB,SAAS,cAAc,YAAY,eAAe,oBAAoB,qBAAqB;AAC3F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAwDA,SAAS,oBAA+C;AAAA,EAC7D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMd;AAAA,EACA,oBAAoB;AAAA,EACpB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,GAAG;AACL,GAAgC;AAC9B,QAAM,OAAO,gBAAmB;AAAA,IAC9B;AAAA,IACA;AA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AACd,oBAAE,gBAAgB;AAClB,2BAAS,CAAC,CAAC;AAAA,gBACb;AAAA,gBACA,WAAU;AAAA,gBAEV,8BAAC,KAAE,WAAU,UAAS;AAAA;AAAA,YACxB,IAEA,oBAAC,gBAAa;AAAA;AAAA;AAAA,MAElB;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC;AAAA,UACA;AAAA,UACA,OAAK;AAAA,UAGL,YAAY,SAAS;AAAA,UACrB,mBAAmB,OAAO;AAAA,UAC1B,YAAY,OAAO;AAAA,UACnB;AAAA,UACA;AAAA,UACA,YAAY,CAAC,MAAM,SAAS,IAAI,CAAC;AAAA,UACjC,UAAU;AAAA,UACV;AAAA,UACA,UAAU,MAAM;AACd,uBAAW,CAAC;AACZ,iBAAK,SAAS,EAAE;AAAA,UAClB;AAAA,UACA,eAAe,OAAO,OAAO,CAAC;AAAA;AAAA,MAChC;AAAA,MACC,MAAM;AAAA,OACT;AAAA;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/multi-entity-combobox.tsx"],"sourcesContent":["import { useId, useMemo, type ComponentPropsWithoutRef, type ReactNode } from \"react\";\nimport { X } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport { FieldChevron, FieldLabel, FIELD_TRIGGER, FIELD_FLOATING_PAD, FIELD_INVALID } from \"./ui\";\nimport {\n ComboboxPanel,\n useComboboxCore,\n useComboboxFieldError,\n type ComboOption,\n} from \"./combobox-core\";\nimport {\n DEFAULT_COMBOBOX_LABELS,\n DEFAULT_COMMON_LABELS,\n useKitLabels,\n useKitLocale,\n} from \"../i18n/kit-labels\";\n\n/** `onChange` is the kit's — \"a selection was made\", carrying values — rather\n * than the div's form event, so the DOM's spelling of it is omitted. */\nexport interface MultiEntityComboboxProps<V extends string | number>\n extends Omit<ComponentPropsWithoutRef<\"div\">, \"onChange\"> {\n /** Selected ids. */\n value: V[];\n onChange: (value: V[]) => void;\n /** Already-loaded options (client-side filtered); also resolves selected labels. */\n options?: ComboOption<V>[];\n /** Async option source, debounced + race-safe; a rejection shows\n * `loadErrorLabel`. When set, `options` resolves labels only. */\n loadOptions?: (query: string) => Promise<ComboOption<V>[]>;\n loading?: boolean;\n label?: ReactNode;\n placeholder?: string;\n searchPlaceholder?: string;\n emptyLabel?: string;\n /** Trigger summary when 1+ selected (default: the labels as a locale-formatted\n * list, or `combobox.selectedCount` when a label can't be resolved). */\n itemLabel?: (count: number) => string;\n clearable?: boolean;\n clearLabel?: string;\n /** The phone sheet's close button. Its own prop rather than a reuse of\n * `clearLabel`: \"clear the selection\" and \"close this screen\" are different\n * actions, and on a full-screen sheet the close button is the only way out —\n * so it is the one control here that MUST be in the reader's language. */\n closeLabel?: string;\n disabled?: boolean;\n /** When set, a \"create\" row appears for a non-empty query with no exact match.\n * The panel stays open (adding the new entity to `value` is the caller's job). */\n onCreate?: (query: string) => void;\n createLabel?: (query: string) => string;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\n /** What is wrong with the value, as {@link Input}'s `error`: rendered under the\n * field, on the trigger's `aria-describedby`, and implies `invalid`. */\n error?: ReactNode;\n /** Narrow `options` client-side by the query. Default `true`; `false` shows them\n * as given (a server-ranked list). */\n filter?: boolean;\n /** Offer nothing, and call no `loadOptions`, below this many characters. Default\n * `0`, i.e. the list loads as the panel opens. */\n minChars?: number;\n /** `loadOptions` debounce. Default 150 ms. */\n debounceMs?: number;\n /** Shown when `loadOptions` rejects. Default: `combobox.loadError`. */\n loadErrorLabel?: string;\n}\n\n/**\n * Multi-value sibling of {@link EntityCombobox}: pick several entities by search,\n * with the same async `loadOptions`/`onCreate` support. Rows show a checkbox and\n * toggle without closing the panel; the trigger summarises the selection.\n */\nexport function MultiEntityCombobox<V extends string | number>({\n value,\n onChange,\n options,\n loadOptions,\n loading,\n label,\n placeholder,\n searchPlaceholder,\n emptyLabel,\n itemLabel,\n clearable,\n clearLabel,\n closeLabel,\n disabled,\n onCreate,\n createLabel,\n className,\n invalid,\n error,\n filter,\n minChars,\n debounceMs,\n loadErrorLabel,\n \"aria-label\": ariaLabel,\n // The control's own wiring, taken off `rest` so it lands on the TRIGGER rather than\n // the wrapper: `Field`'s render-prop spreads `{ id, aria-describedby, aria-invalid,\n // aria-required }`, and on the role-less wrapper div the label's `htmlFor` named\n // nothing and the hint and required state described nothing — kastlan's\n // communication-page To/Cc/Bcc and lease-tenants-step.tsx read as unnamed pickers.\n id,\n \"aria-describedby\": ariaDescribedBy,\n \"aria-invalid\": ariaInvalid,\n \"aria-required\": ariaRequired,\n ...rest\n}: MultiEntityComboboxProps<V>) {\n const core = useComboboxCore<V>({\n options,\n loadOptions,\n loading,\n filter,\n minChars,\n debounceMs,\n });\n const field = useComboboxFieldError(\n error,\n invalid || ariaInvalid === true || ariaInvalid === \"true\",\n ariaDescribedBy,\n );\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, query, triggerRef } = core;\n // One id per instance, generated here rather than in the core: `aria-controls` on\n // the trigger has to name the list while the list is still closed, so the id\n // belongs to whoever renders both ends of it.\n const listboxId = useId();\n\n const valueSet = useMemo(() => new Set(value), [value]);\n // A list of NAMES, not a sentence, so the narrow conjunction: English gets\n // \"Food, Rent, Travel\" (no \"and\" squeezed into a truncating trigger), German and\n // French still get their \"und\"/\"et\" where the language insists on it, and Japanese\n // and Chinese get the ideographic comma \"、\". The `unit` type looked like the\n // natural fit for a summary, but in ja/zh it concatenates the names with nothing\n // between them at all.\n const locale = useKitLocale();\n const listFormat = useMemo(\n () => new Intl.ListFormat(locale, { type: \"conjunction\", style: \"narrow\" }),\n [locale],\n );\n const summary = (() => {\n if (value.length === 0) return placeholder ?? \"\";\n if (itemLabel) return itemLabel(value.length);\n const chosen = value.map(resolve);\n return chosen.every(Boolean)\n ? listFormat.format(chosen.map((o) => o!.label))\n : labels.selectedCount(value.length);\n })();\n\n const q = query.trim();\n const showCreate =\n Boolean(onCreate) && q.length > 0 && !results.some((o) => o.label.toLowerCase() === q.toLowerCase());\n const showClear = Boolean(clearable && value.length > 0 && !disabled);\n\n const toggle = (o: ComboOption<V>) => {\n core.rememberOption(o);\n if (valueSet.has(o.value)) onChange(value.filter((v) => v !== o.value));\n else onChange([...value, o.value]);\n // Stay open — multi-select keeps adding.\n };\n\n return (\n // `rest` dresses the wrapper, which has no role; the accessible NAME — and the\n // id, description, invalid and required state above — go on the trigger, which\n // 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={triggerRef}\n id={id}\n type=\"button\"\n // A combobox, not a button. The distinction is not pedantry: this control\n // carried `aria-invalid`, which `button` does not support, so a required\n // field left empty painted a rose border and told a reader nothing at all —\n // and ESLint flagged it as exactly that (`role-supports-aria-props`). The\n // fix the audit asked for is the role that describes what this IS: a closed\n // choice that expands into the list named below. `combobox` supports\n // `aria-invalid`, so the border and the announcement finally agree.\n role=\"combobox\"\n aria-expanded={open}\n aria-controls={listboxId}\n aria-haspopup=\"listbox\"\n // The label is a floating <span>, not a <label for>, so without this the\n // trigger's accessible name is whatever value happens to be selected —\n // \"Checking\" with nothing saying it is the account. The label AND the\n // value, because `aria-label` replaces the content rather than adding to\n // it, and a control that announces only its name has lost the answer.\n // A caller's own name wins over the composition: two fields labelled\n // \"Account\" on a transfer form are the from and the to, and only the\n // caller knows which is which.\n aria-label={\n ariaLabel ??\n (typeof label === \"string\" ? common.fieldValue(label, summary) : undefined)\n }\n disabled={disabled}\n aria-invalid={field.isInvalid || undefined}\n aria-describedby={field.describedBy}\n aria-required={ariaRequired}\n onClick={() => !disabled && setOpen((o) => !o)}\n // Down/Up opens the list from the closed trigger, per the APG. Enter and\n // Space already do it through the button's own click.\n onKeyDown={(e) => {\n if (disabled) return;\n if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n e.preventDefault();\n setOpen(true);\n }\n }}\n className={cn(\n FIELD_TRIGGER,\n \"pe-9\",\n label !== undefined && FIELD_FLOATING_PAD,\n disabled && \"cursor-not-allowed opacity-50\",\n field.isInvalid && FIELD_INVALID,\n )}\n >\n <span\n className={cn(\n \"min-w-0 truncate\",\n // Inherit FIELD_BASE's ink for a value, keep the placeholder tone\n // (`--text-placeholder`) — the same rule every field on a form row\n // follows (Keksdose dev#477).\n !value.length && \"text-[var(--text-placeholder)]\",\n )}\n >\n {summary}\n </span>\n {showClear ? (\n /* eslint-disable-next-line jsx-a11y/click-events-have-key-events -- tabIndex -1 inside\n the trigger <button>, so it never holds focus and a key handler here could\n never fire. A pointer shortcut; the keyboard path is unticking the options\n in the open list. */\n <span\n role=\"button\"\n tabIndex={-1}\n aria-label={labels.clear}\n onClick={(e) => {\n e.stopPropagation();\n onChange([]);\n }}\n className=\"absolute end-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-[var(--text-placeholder)] hover:text-[var(--text-secondary)]\"\n >\n <X className=\"size-4\" />\n </span>\n ) : (\n <FieldChevron />\n )}\n </button>\n <ComboboxPanel\n core={core}\n listboxId={listboxId}\n multi\n // On a phone the panel becomes a full-screen sheet, which needs the field's\n // own label to say what it is asking for (live #200).\n sheetTitle={label ?? placeholder}\n searchPlaceholder={labels.search}\n emptyLabel={labels.noResults}\n closeLabel={closeLabel}\n loadErrorLabel={loadErrorLabel}\n isSelected={(v) => valueSet.has(v)}\n onChoose={toggle}\n showCreate={showCreate}\n onCreate={() => {\n onCreate?.(q);\n core.setQuery(\"\");\n }}\n createContent={labels.create(q)}\n />\n {field.errorEl}\n </div>\n );\n}\n"],"mappings":";AA8K8B,cACxB,YADwB;AA9K9B,SAAS,OAAO,eAA8D;AAC9E,SAAS,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AAM;AAAA,OACT;AAAA;AAEJ;","names":[]}
|
|
@@ -2,7 +2,7 @@ import * as react from 'react';
|
|
|
2
2
|
import { ComponentProps, ReactNode } from 'react';
|
|
3
3
|
import { NumberInput } from './number-input.js';
|
|
4
4
|
import './calculator.js';
|
|
5
|
-
import '../kit-labels-
|
|
5
|
+
import '../kit-labels-Mz8zZHIF.js';
|
|
6
6
|
import './data-table-labels.js';
|
|
7
7
|
import './mini-calendar.js';
|
|
8
8
|
import './calendar-heatmap.js';
|
|
@@ -2,7 +2,7 @@ import * as react from 'react';
|
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
3
|
import { CalculatorButtonLabels } from './calculator.js';
|
|
4
4
|
import { NumberPadSheetLabels } from './numpad-sheet.js';
|
|
5
|
-
import '../kit-labels-
|
|
5
|
+
import '../kit-labels-Mz8zZHIF.js';
|
|
6
6
|
import './data-table-labels.js';
|
|
7
7
|
import './mini-calendar.js';
|
|
8
8
|
import './calendar-heatmap.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/number-input.tsx"],"sourcesContent":["import { useId, useRef, useState } from \"react\";\nimport type { KeyboardEvent, ReactNode } from \"react\";\nimport { CalculatorButton, type CalculatorButtonLabels } from \"./calculator\";\nimport { NumberPadSheet, type NumberPadSheetLabels } from \"./numpad-sheet\";\nimport { FIELD_BASE, FIELD_DISPLAY, FIELD_INVALID, FLOATING_INPUT_CLASS, FloatingField, PHONE_QUERY } from \"./ui\";\nimport { cn } from \"../lib/cn\";\nimport { commitExpression, formatResult, sanitizeLive } from \"../lib/calc\";\nimport { useMediaQuery } from \"../hooks/use-media-query\";\n\ninterface NumberInputProps {\n value: string;\n /** Fired on every keystroke with the raw text (comma → dot, operators kept so\n * a typed expression survives). */\n onChange: (value: string) => void;\n /** Fired on blur/Enter with the *evaluated* value — use this for save-on-blur\n * fields so the save always sees the resolved number, never \"10+5\". */\n onCommit?: (value: string) => void;\n label?: ReactNode;\n ariaLabel?: string;\n /** Names for the calculator this field renders — its trigger, and the controls\n * inside the popover — and for the numpad sheet it opens on a phone. Overrides\n * for THIS field only: both resolve the `calculator` namespace of\n * `<UiKitProvider labels>` themselves, then fall back to English.\n *\n * `pad` is not optional plumbing: this field renders a {@link NumberPadSheet}\n * exactly as {@link AmountInput} does, but had no way to pass it anything, so\n * the SAME keypad announced itself in German when a money field opened it and in\n * English when a goal target did. */\n labels?: {\n calculatorTrigger?: string;\n calculator?: CalculatorButtonLabels;\n pad?: NumberPadSheetLabels;\n };\n placeholder?: string;\n disabled?: boolean;\n autoFocus?: boolean;\n /** Wrapper class. */\n className?: string;\n /** Overrides the input's own styling (merged after the field base). */\n inputClassName?: string;\n id?: string;\n /** Show the calculator-popover trigger (default true). Set false for fields in\n * an ephemeral close-on-blur editor, where clicking the icon would blur away\n * and tear the editor down before the popover could open — inline typing\n * (e.g. \"200+50\" → Enter) still evaluates there. */\n calculator?: boolean;\n /** {@link FIELD_DISPLAY} — on a phone, the figure at display size with the field\n * chrome dropped. The currency-free half of the same treatment `AmountInput`\n * carries, for a dialog whose whole point is the one number (a budget goal's\n * target); not for a field among many, and never for the compact inline\n * editors this control also serves. */\n variant?: \"field\" | \"display\";\n /** A {@link FieldHint} \"?\" on the label's own line, beside the label rather\n * than at the far end of the strip — the far end is where the calculator\n * lives, and a hint placed there landed on top of it (steering-design\n * feedback #48). */\n hint?: ReactNode;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\n /**\n * Set on the `<input>`, with `id` above. Declared so `Field`'s render-prop spread —\n * `{(ids) => <NumberInput {...ids} … />}` — is typed and reaches the input: the hint\n * and error are described, a required number is announced as required, and\n * `aria-invalid` paints {@link FIELD_INVALID} the way `invalid` does.\n */\n \"aria-describedby\"?: string;\n \"aria-invalid\"?: boolean | \"true\" | \"false\";\n \"aria-required\"?: boolean | \"true\" | \"false\";\n /**\n * A static unit shown at the field's right edge — \"%\", \"kg\", \"km/h\".\n *\n * The read-out half of {@link AmountInput}'s currency chip, and it exists for the\n * same reason that one does: a unit belongs to the FIELD, not to the text, so\n * typing it is a way to get it into the value. Keksdose had a percentage spelled\n * three different ways across three screens — `<Input type=\"number\" step=\"0.01\">`\n * for a loan rate, `step=\"0.1\"` for a tax rate, `inputMode=\"decimal\"` for a VAT\n * rate — and none of the three showed a \"%\" anywhere near the box, so what the\n * digits meant was a question the label alone had to answer.\n *\n * `aria-hidden`, like the currency read-out: it is a property of the field that\n * the label already names (\"Interest rate (%)\"), and announcing it again after\n * every value reads as part of the number.\n */\n suffix?: ReactNode;\n /**\n * Turns on the step keys: ArrowUp / ArrowDown add or subtract `step`, PageUp /\n * PageDown ten of them. The result lands on the grid `min + k × step` (or `0 + k ×\n * step` without a `min`), so 3.1 with `step={0.25}` goes up to 3.25, not 3.35 —\n * what a native number input does. Decimal-exact: `0.1 + 0.2` steps to \"0.3\".\n *\n * A step changes the text through `onChange` like a keystroke would; `onCommit`\n * still fires on blur/Enter. Without `step` the arrow keys move the caret as before.\n */\n step?: number;\n /** Bounds for the step keys only — a step never leaves `[min, max]`. This field's\n * value is a STRING, so typed text is not clamped: {@link NumberField} is the\n * numeric field that clamps what is typed as well. */\n min?: number;\n max?: number;\n}\n\n/** Decimal places of `n` as written (\"0.25\" → 2, \"1e-7\" → 7), for decimal-exact\n * stepping. */\nfunction decimalsOf(n: number): number {\n const text = formatResult(n);\n const dot = text.indexOf(\".\");\n return dot === -1 ? 0 : text.length - dot - 1;\n}\n\n/**\n * `current` moved by `count` steps (negative = down), on the grid `origin + k × step`\n * and clamped into `[min, max]`. An off-grid value moves to the NEXT grid point in\n * that direction first, so one press is never more than one step.\n *\n * The grid index is found by division and the result rebuilt as `origin + k × step`,\n * then cut to the decimals `step` and `origin` are written with — which is where\n * binary noise goes: `0.1 × 3` is 0.30000000000000004, and `toFixed(1)` of it is\n * \"0.3\". Summing steps would accumulate that noise press by press instead.\n */\nexport function stepNumber(\n current: number | null,\n count: number,\n step: number,\n min?: number,\n max?: number,\n): number {\n const clamp = (n: number) => Math.min(max ?? Infinity, Math.max(min ?? -Infinity, n));\n // Nothing to step from: land on the value nearest zero the bounds allow, rather\n // than on ±step — a room count with `min={1}` goes to 1, a rate to 0.\n if (current === null || !Number.isFinite(current)) return clamp(0);\n const origin = min !== undefined && Number.isFinite(min) ? min : 0;\n const raw = (current - origin) / step;\n const nearest = Math.round(raw);\n // \"On the grid\" within float tolerance: (0.3 - 0) / 0.1 is 2.9999999999999996.\n const onGrid = Math.abs(raw - nearest) < 1e-9;\n const k = onGrid\n ? nearest + count\n : count > 0\n ? Math.ceil(raw) + count - 1\n : Math.floor(raw) + count + 1;\n const places = Math.min(Math.max(decimalsOf(step), decimalsOf(origin)), 20);\n return clamp(Number((origin + k * step).toFixed(places)));\n}\n\n/**\n * A numeric text field with a built-in calculator: type a calculation straight\n * in (e.g. \"12+5\", evaluated on blur/Enter) or click the trailing calculator\n * icon for a keypad. String `value`/`onChange` contract, mirroring\n * {@link AmountInput} — the currency-free counterpart for budgets, goals,\n * invoice totals and split lines.\n */\nexport function NumberInput({\n value,\n onChange,\n onCommit,\n label,\n ariaLabel,\n labels,\n placeholder,\n disabled,\n autoFocus,\n className,\n inputClassName,\n id,\n calculator = true,\n variant = \"field\",\n hint,\n invalid: invalidProp,\n \"aria-describedby\": ariaDescribedBy,\n \"aria-invalid\": ariaInvalid,\n \"aria-required\": ariaRequired,\n suffix,\n step,\n min,\n max,\n}: NumberInputProps) {\n const generatedId = useId();\n const fieldId = id ?? generatedId;\n const invalid = Boolean(invalidProp) || ariaInvalid === true || ariaInvalid === \"true\";\n const labelled = label !== undefined;\n // On phones we suppress the OS keyboard (inputMode=\"none\" below) for our own\n // calculator numpad, so the desktop popover trigger is hidden (feedback #334).\n const isMobile = useMediaQuery(PHONE_QUERY, false);\n const asDisplay = isMobile && variant === \"display\";\n const showCalc = calculator && !disabled && !isMobile;\n const [focused, setFocused] = useState(false);\n // On mobile, focusing opens the numpad bottom sheet instead of the native\n // keyboard (#334); the ref lets its \"Done\" blur → commit + close.\n const showNumpad = isMobile && !disabled && focused;\n const inputRef = useRef<HTMLInputElement>(null);\n\n const commit = () => {\n const next = commitExpression(value);\n if (next !== value) onChange(next);\n onCommit?.(next);\n };\n\n const stepBy = (count: number) => {\n // The step starts from the text as a commit would read it, so \"12+5\" steps from 17.\n const resolved = commitExpression(value).trim();\n const n = resolved === \"\" ? NaN : Number(resolved);\n const next = formatResult(stepNumber(Number.isFinite(n) ? n : null, count, step as number, min, max));\n if (next !== value) onChange(next);\n };\n\n const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n if (e.key === \"Enter\") return commit();\n // A zero, negative or non-finite step is no step: the keys stay the caret's.\n if (!step || !(step > 0) || !Number.isFinite(step) || e.altKey || e.ctrlKey || e.metaKey) return;\n const count =\n e.key === \"ArrowUp\" ? 1 : e.key === \"ArrowDown\" ? -1 : e.key === \"PageUp\" ? 10 : e.key === \"PageDown\" ? -10 : 0;\n if (count === 0) return;\n // Otherwise ArrowUp/Down also jump the caret to the start/end of the text.\n e.preventDefault();\n stepBy(count);\n };\n\n return (\n <FloatingField\n className={cn(\"w-full\", className)}\n htmlFor={fieldId}\n label={label}\n srOnlyLabel={asDisplay}\n hint={hint}\n >\n <input\n ref={inputRef}\n id={fieldId}\n aria-label={ariaLabel}\n type=\"text\"\n // Mobile: suppress the OS keyboard so the numpad sheet owns entry (field\n // keeps focus/caret); desktop keeps the native decimal keypad.\n inputMode={isMobile ? \"none\" : \"decimal\"}\n autoComplete=\"off\"\n autoFocus={autoFocus}\n disabled={disabled}\n // Display mode has no floating label to feed the blank-placeholder trick,\n // and an empty borderless figure shows nothing — so it keeps whatever\n // placeholder the caller gave, falling back to a zero to aim at.\n placeholder={asDisplay ? (placeholder ?? \"0\") : labelled ? \" \" : placeholder}\n value={value}\n onChange={(e) => onChange(sanitizeLive(e.target.value))}\n onFocus={() => setFocused(true)}\n onBlur={() => {\n commit();\n setFocused(false);\n }}\n onKeyDown={onKeyDown}\n aria-invalid={invalid || undefined}\n aria-describedby={ariaDescribedBy}\n aria-required={ariaRequired}\n // The end padding sits last so it always wins over an inputClassName that\n // sets its own px. Both trailing controls can be on at once, so the room\n // they need is reserved together rather than by whichever happens to render:\n // the calculator is ~36px and a short unit ~24px, and a field that reserved\n // only one of them would let the digits run under the other.\n className={cn(\n asDisplay\n ? cn(FIELD_DISPLAY, \"text-4xl font-semibold leading-tight tracking-tight tabular-nums\")\n : labelled\n ? FLOATING_INPUT_CLASS\n : FIELD_BASE,\n inputClassName,\n showCalc && suffix !== undefined ? \"pe-16\" : showCalc ? \"pe-9\" : suffix !== undefined ? \"pe-8\" : undefined,\n invalid && FIELD_INVALID,\n )}\n />\n {(showCalc || suffix !== undefined) && (\n // One flex track for both, so the unit and the calculator sit side by side\n // instead of stacking on the same corner — AmountInput's arrangement, which\n // has carried a chip and a calculator together since #430.\n <div className=\"absolute inset-y-0 end-0 flex items-center\">\n {showCalc && (\n <CalculatorButton\n value={value}\n onChange={onChange}\n className=\"self-stretch px-2.5\"\n ariaLabel={labels?.calculatorTrigger}\n labels={labels?.calculator}\n />\n )}\n {suffix !== undefined && (\n <span\n aria-hidden\n className=\"pointer-events-none pe-3 text-xs font-medium text-[var(--text-muted)]\"\n >\n {suffix}\n </span>\n )}\n </div>\n )}\n {showNumpad && (\n <NumberPadSheet\n value={value}\n onChange={onChange}\n onDone={() => inputRef.current?.blur()}\n label={label}\n labels={labels?.pad}\n />\n )}\n </FloatingField>\n );\n}\n"],"mappings":";AAiOM,cA8CE,YA9CF;AAjON,SAAS,OAAO,QAAQ,gBAAgB;AAExC,SAAS,wBAAqD;AAC9D,SAAS,sBAAiD;AAC1D,SAAS,YAAY,eAAe,eAAe,sBAAsB,eAAe,mBAAmB;AAC3G,SAAS,UAAU;AACnB,SAAS,kBAAkB,cAAc,oBAAoB;AAC7D,SAAS,qBAAqB;AAgG9B,SAAS,WAAW,GAAmB;AACrC,QAAM,OAAO,aAAa,CAAC;AAC3B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,WAAW,SAAS;AAAA,YAC/B,cAAa;AAAA,YACb;AAAA,YACA;AAAA,YAIA,aAAa,YAAa,eAAe,MAAO,WAAW,MAAM;AAAA,YACjE;AAAA,YACA,UAAU,CAAC,MAAM,SAAS,aAAa,EAAE,OAAO,KAAK,CAAC;AAAA,YACtD,SAAS,MAAM,WAAW,IAAI;AAAA,YAC9B,QAAQ,MAAM;AACZ,qBAAO;AACP,yBAAW,KAAK;AAAA,YAClB;AAAA,YACA;AAAA,YACA,gBAAc,WAAW;AAAA,YACzB,oBAAkB;AAAA,YAClB,iBAAe;AAAA,YAMf,WAAW;AAAA,cACT,YACI,GAAG,eAAe,kEAAkE,IACpF,WACE,uBACA;AAAA,cACN;AAAA,cACA,YAAY,WAAW,SAAY,UAAU,WAAW,SAAS,WAAW,SAAY,SAAS;AAAA,cACjG,WAAW;AAAA,YACb;AAAA;AAAA,QACF;AAAA,SACE,YAAY,WAAW;AAAA;AAAA;AAAA,QAIvB,qBAAC,SAAI,WAAU,8CACZ;AAAA,sBACC;AAAA,YAAC;AAAA;AAAA,cACC;AAAA,cACA;AAAA,cACA,WAAU;AAAA,cACV,WAAW,QAAQ;AAAA,cACnB,QAAQ,QAAQ;AAAA;AAAA,UAClB;AAAA,UAED,WAAW,UACV;AAAA,YAAC;AAAA;AAAA,cACC,eAAW;AAAA,cACX,WAAU;AAAA,cAET;AAAA;AAAA,UACH;AAAA,WAEJ;AAAA,QAED,cACC;AAAA,UAAC;AAAA;AAAA,YACC;AAAA,YACA;AAAA,YACA,QAAQ,MAAM,SAAS,SAAS,KAAK;AAAA,YACrC;AAAA,YACA,QAAQ,QAAQ;AAAA;AAAA,QAClB;AAAA;AAAA;AAAA,EAEJ;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/number-input.tsx"],"sourcesContent":["import { useId, useRef, useState } from \"react\";\nimport type { KeyboardEvent, ReactNode } from \"react\";\nimport { CalculatorButton, type CalculatorButtonLabels } from \"./calculator\";\nimport { NumberPadSheet, type NumberPadSheetLabels } from \"./numpad-sheet\";\nimport { FIELD_BASE, FIELD_DISPLAY, FIELD_INVALID, FLOATING_INPUT_CLASS, FloatingField, PHONE_QUERY } from \"./ui\";\nimport { cn } from \"../lib/cn\";\nimport { commitExpression, formatResult, sanitizeLive } from \"../lib/calc\";\nimport { useMediaQuery } from \"../hooks/use-media-query\";\n\ninterface NumberInputProps {\n value: string;\n /** Fired on every keystroke with the raw text (comma → dot, operators kept so\n * a typed expression survives). */\n onChange: (value: string) => void;\n /** Fired on blur/Enter with the *evaluated* value — use this for save-on-blur\n * fields so the save always sees the resolved number, never \"10+5\". */\n onCommit?: (value: string) => void;\n label?: ReactNode;\n ariaLabel?: string;\n /** Names for the calculator this field renders — its trigger, and the controls\n * inside the popover — and for the numpad sheet it opens on a phone. Overrides\n * for THIS field only: both resolve the `calculator` namespace of\n * `<UiKitProvider labels>` themselves, then fall back to English.\n *\n * `pad` is not optional plumbing: this field renders a {@link NumberPadSheet}\n * exactly as {@link AmountInput} does, but had no way to pass it anything, so\n * the SAME keypad announced itself in German when a money field opened it and in\n * English when a goal target did. */\n labels?: {\n calculatorTrigger?: string;\n calculator?: CalculatorButtonLabels;\n pad?: NumberPadSheetLabels;\n };\n placeholder?: string;\n disabled?: boolean;\n autoFocus?: boolean;\n /** Wrapper class. */\n className?: string;\n /** Overrides the input's own styling (merged after the field base). */\n inputClassName?: string;\n id?: string;\n /** Show the calculator-popover trigger (default true). Set false for fields in\n * an ephemeral close-on-blur editor, where clicking the icon would blur away\n * and tear the editor down before the popover could open — inline typing\n * (e.g. \"200+50\" → Enter) still evaluates there. */\n calculator?: boolean;\n /** {@link FIELD_DISPLAY} — on a phone, the figure at display size with the field\n * chrome dropped. The currency-free half of the same treatment `AmountInput`\n * carries, for a dialog whose whole point is the one number (a budget goal's\n * target); not for a field among many, and never for the compact inline\n * editors this control also serves. */\n variant?: \"field\" | \"display\";\n /** A {@link FieldHint} \"?\" on the label's own line, beside the label rather\n * than at the far end of the strip — the far end is where the calculator\n * lives, and a hint placed there landed on top of it (steering-design\n * feedback #48). */\n hint?: ReactNode;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\n /**\n * Set on the `<input>`, with `id` above. Declared so `Field`'s render-prop spread —\n * `{(ids) => <NumberInput {...ids} … />}` — is typed and reaches the input: the hint\n * and error are described, a required number is announced as required, and\n * `aria-invalid` paints {@link FIELD_INVALID} the way `invalid` does.\n */\n \"aria-describedby\"?: string;\n \"aria-invalid\"?: boolean | \"true\" | \"false\";\n \"aria-required\"?: boolean | \"true\" | \"false\";\n /**\n * A static unit shown at the field's right edge — \"%\", \"kg\", \"km/h\".\n *\n * The read-out half of {@link AmountInput}'s currency chip, and it exists for the\n * same reason that one does: a unit belongs to the FIELD, not to the text, so\n * typing it is a way to get it into the value. Keksdose had a percentage spelled\n * three different ways across three screens — `<Input type=\"number\" step=\"0.01\">`\n * for a loan rate, `step=\"0.1\"` for a tax rate, `inputMode=\"decimal\"` for a VAT\n * rate — and none of the three showed a \"%\" anywhere near the box, so what the\n * digits meant was a question the label alone had to answer.\n *\n * `aria-hidden`, like the currency read-out: it is a property of the field that\n * the label already names (\"Interest rate (%)\"), and announcing it again after\n * every value reads as part of the number.\n */\n suffix?: ReactNode;\n /**\n * Turns on the step keys: ArrowUp / ArrowDown add or subtract `step`, PageUp /\n * PageDown ten of them. The result lands on the grid `min + k × step` (or `0 + k ×\n * step` without a `min`), so 3.1 with `step={0.25}` goes up to 3.25, not 3.35 —\n * what a native number input does. Decimal-exact: `0.1 + 0.2` steps to \"0.3\".\n *\n * A step changes the text through `onChange` like a keystroke would; `onCommit`\n * still fires on blur/Enter. Without `step` the arrow keys move the caret as before.\n */\n step?: number;\n /** Bounds for the step keys only — a step never leaves `[min, max]`. This field's\n * value is a STRING, so typed text is not clamped: {@link NumberField} is the\n * numeric field that clamps what is typed as well. */\n min?: number;\n max?: number;\n}\n\n/** Decimal places of `n` as written (\"0.25\" → 2, \"1e-7\" → 7), for decimal-exact\n * stepping. */\nfunction decimalsOf(n: number): number {\n const text = formatResult(n);\n const dot = text.indexOf(\".\");\n return dot === -1 ? 0 : text.length - dot - 1;\n}\n\n/**\n * `current` moved by `count` steps (negative = down), on the grid `origin + k × step`\n * and clamped into `[min, max]`. An off-grid value moves to the NEXT grid point in\n * that direction first, so one press is never more than one step.\n *\n * The grid index is found by division and the result rebuilt as `origin + k × step`,\n * then cut to the decimals `step` and `origin` are written with — which is where\n * binary noise goes: `0.1 × 3` is 0.30000000000000004, and `toFixed(1)` of it is\n * \"0.3\". Summing steps would accumulate that noise press by press instead.\n */\nexport function stepNumber(\n current: number | null,\n count: number,\n step: number,\n min?: number,\n max?: number,\n): number {\n const clamp = (n: number) => Math.min(max ?? Infinity, Math.max(min ?? -Infinity, n));\n // Nothing to step from: land on the value nearest zero the bounds allow, rather\n // than on ±step — a room count with `min={1}` goes to 1, a rate to 0.\n if (current === null || !Number.isFinite(current)) return clamp(0);\n const origin = min !== undefined && Number.isFinite(min) ? min : 0;\n const raw = (current - origin) / step;\n const nearest = Math.round(raw);\n // \"On the grid\" within float tolerance: (0.3 - 0) / 0.1 is 2.9999999999999996.\n const onGrid = Math.abs(raw - nearest) < 1e-9;\n const k = onGrid\n ? nearest + count\n : count > 0\n ? Math.ceil(raw) + count - 1\n : Math.floor(raw) + count + 1;\n const places = Math.min(Math.max(decimalsOf(step), decimalsOf(origin)), 20);\n return clamp(Number((origin + k * step).toFixed(places)));\n}\n\n/**\n * A numeric text field with a built-in calculator: type a calculation straight\n * in (e.g. \"12+5\", evaluated on blur/Enter) or click the trailing calculator\n * icon for a keypad. String `value`/`onChange` contract, mirroring\n * {@link AmountInput} — the currency-free counterpart for budgets, goals,\n * invoice totals and split lines.\n */\nexport function NumberInput({\n value,\n onChange,\n onCommit,\n label,\n ariaLabel,\n labels,\n placeholder,\n disabled,\n autoFocus,\n className,\n inputClassName,\n id,\n calculator = true,\n variant = \"field\",\n hint,\n invalid: invalidProp,\n \"aria-describedby\": ariaDescribedBy,\n \"aria-invalid\": ariaInvalid,\n \"aria-required\": ariaRequired,\n suffix,\n step,\n min,\n max,\n}: NumberInputProps) {\n const generatedId = useId();\n const fieldId = id ?? generatedId;\n const invalid = Boolean(invalidProp) || ariaInvalid === true || ariaInvalid === \"true\";\n const labelled = label !== undefined;\n // On phones we suppress the OS keyboard (inputMode=\"none\" below) for our own\n // calculator numpad, so the desktop popover trigger is hidden (feedback #334).\n const isMobile = useMediaQuery(PHONE_QUERY, false);\n const asDisplay = isMobile && variant === \"display\";\n const showCalc = calculator && !disabled && !isMobile;\n const [focused, setFocused] = useState(false);\n // On mobile, focusing opens the numpad bottom sheet instead of the native\n // keyboard (#334); the ref lets its \"Done\" blur → commit + close.\n const showNumpad = isMobile && !disabled && focused;\n const inputRef = useRef<HTMLInputElement>(null);\n\n const commit = () => {\n const next = commitExpression(value);\n if (next !== value) onChange(next);\n onCommit?.(next);\n };\n\n const stepBy = (count: number) => {\n // The step starts from the text as a commit would read it, so \"12+5\" steps from 17.\n const resolved = commitExpression(value).trim();\n const n = resolved === \"\" ? NaN : Number(resolved);\n const next = formatResult(stepNumber(Number.isFinite(n) ? n : null, count, step as number, min, max));\n if (next !== value) onChange(next);\n };\n\n const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {\n if (e.key === \"Enter\") return commit();\n // A zero, negative or non-finite step is no step: the keys stay the caret's.\n if (!step || !(step > 0) || !Number.isFinite(step) || e.altKey || e.ctrlKey || e.metaKey) return;\n const count =\n e.key === \"ArrowUp\" ? 1 : e.key === \"ArrowDown\" ? -1 : e.key === \"PageUp\" ? 10 : e.key === \"PageDown\" ? -10 : 0;\n if (count === 0) return;\n // Otherwise ArrowUp/Down also jump the caret to the start/end of the text.\n e.preventDefault();\n stepBy(count);\n };\n\n return (\n <FloatingField\n className={cn(\"w-full\", className)}\n htmlFor={fieldId}\n label={label}\n srOnlyLabel={asDisplay}\n hint={hint}\n >\n <input\n ref={inputRef}\n id={fieldId}\n aria-label={ariaLabel}\n type=\"text\"\n // Mobile: suppress the OS keyboard so the numpad sheet owns entry (field\n // keeps focus/caret); desktop keeps the native decimal keypad.\n inputMode={isMobile ? \"none\" : \"decimal\"}\n autoComplete=\"off\"\n // eslint-disable-next-line jsx-a11y/no-autofocus -- a documented prop the caller opts into (off by default); the field never takes focus on its own.\n autoFocus={autoFocus}\n disabled={disabled}\n // Display mode has no floating label to feed the blank-placeholder trick,\n // and an empty borderless figure shows nothing — so it keeps whatever\n // placeholder the caller gave, falling back to a zero to aim at.\n placeholder={asDisplay ? (placeholder ?? \"0\") : labelled ? \" \" : placeholder}\n value={value}\n onChange={(e) => onChange(sanitizeLive(e.target.value))}\n onFocus={() => setFocused(true)}\n onBlur={() => {\n commit();\n setFocused(false);\n }}\n onKeyDown={onKeyDown}\n aria-invalid={invalid || undefined}\n aria-describedby={ariaDescribedBy}\n aria-required={ariaRequired}\n // The end padding sits last so it always wins over an inputClassName that\n // sets its own px. Both trailing controls can be on at once, so the room\n // they need is reserved together rather than by whichever happens to render:\n // the calculator is ~36px and a short unit ~24px, and a field that reserved\n // only one of them would let the digits run under the other.\n className={cn(\n asDisplay\n ? cn(FIELD_DISPLAY, \"text-4xl font-semibold leading-tight tracking-tight tabular-nums\")\n : labelled\n ? FLOATING_INPUT_CLASS\n : FIELD_BASE,\n inputClassName,\n showCalc && suffix !== undefined ? \"pe-16\" : showCalc ? \"pe-9\" : suffix !== undefined ? \"pe-8\" : undefined,\n invalid && FIELD_INVALID,\n )}\n />\n {(showCalc || suffix !== undefined) && (\n // One flex track for both, so the unit and the calculator sit side by side\n // instead of stacking on the same corner — AmountInput's arrangement, which\n // has carried a chip and a calculator together since #430.\n <div className=\"absolute inset-y-0 end-0 flex items-center\">\n {showCalc && (\n <CalculatorButton\n value={value}\n onChange={onChange}\n className=\"self-stretch px-2.5\"\n ariaLabel={labels?.calculatorTrigger}\n labels={labels?.calculator}\n />\n )}\n {suffix !== undefined && (\n <span\n aria-hidden\n className=\"pointer-events-none pe-3 text-xs font-medium text-[var(--text-muted)]\"\n >\n {suffix}\n </span>\n )}\n </div>\n )}\n {showNumpad && (\n <NumberPadSheet\n value={value}\n onChange={onChange}\n onDone={() => inputRef.current?.blur()}\n label={label}\n labels={labels?.pad}\n />\n )}\n </FloatingField>\n );\n}\n"],"mappings":";AAiOM,cA+CE,YA/CF;AAjON,SAAS,OAAO,QAAQ,gBAAgB;AAExC,SAAS,wBAAqD;AAC9D,SAAS,sBAAiD;AAC1D,SAAS,YAAY,eAAe,eAAe,sBAAsB,eAAe,mBAAmB;AAC3G,SAAS,UAAU;AACnB,SAAS,kBAAkB,cAAc,oBAAoB;AAC7D,SAAS,qBAAqB;AAgG9B,SAAS,WAAW,GAAmB;AACrC,QAAM,OAAO,aAAa,CAAC;AAC3B,QAAM,MAAM,KAAK,QAAQ,GAAG;AAC5B,SAAO,QAAQ,KAAK,IAAI,KAAK,SAAS,MAAM;AAC9C;AAYO,SAAS,WACd,SACA,OACA,MACA,KACA,KACQ;AACR,QAAM,QAAQ,CAAC,MAAc,KAAK,IAAI,OAAO,UAAU,KAAK,IAAI,OAAO,WAAW,CAAC,CAAC;AAGpF,MAAI,YAAY,QAAQ,CAAC,OAAO,SAAS,OAAO,EAAG,QAAO,MAAM,CAAC;AACjE,QAAM,SAAS,QAAQ,UAAa,OAAO,SAAS,GAAG,IAAI,MAAM;AACjE,QAAM,OAAO,UAAU,UAAU;AACjC,QAAM,UAAU,KAAK,MAAM,GAAG;AAE9B,QAAM,SAAS,KAAK,IAAI,MAAM,OAAO,IAAI;AACzC,QAAM,IAAI,SACN,UAAU,QACV,QAAQ,IACN,KAAK,KAAK,GAAG,IAAI,QAAQ,IACzB,KAAK,MAAM,GAAG,IAAI,QAAQ;AAChC,QAAM,SAAS,KAAK,IAAI,KAAK,IAAI,WAAW,IAAI,GAAG,WAAW,MAAM,CAAC,GAAG,EAAE;AAC1E,SAAO,MAAM,QAAQ,SAAS,IAAI,MAAM,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AA,cACnB,QAAQ,QAAQ;AAAA;AAAA,UAClB;AAAA,UAED,WAAW,UACV;AAAA,YAAC;AAAA;AAAA,cACC,eAAW;AAAA,cACX,WAAU;AAAA,cAET;AAAA;AAAA,UACH;AAAA,WAEJ;AAAA,QAED,cACC;AAAA,UAAC;AAAA;AAAA,YACC;AAAA,YACA;AAAA,YACA,QAAQ,MAAM,SAAS,SAAS,KAAK;AAAA,YACrC;AAAA,YACA,QAAQ,QAAQ;AAAA;AAAA,QAClB;AAAA;AAAA;AAAA,EAEJ;AAEJ;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
|
-
import { C as CalculatorLabels } from '../kit-labels-
|
|
3
|
+
import { C as CalculatorLabels } from '../kit-labels-Mz8zZHIF.js';
|
|
4
4
|
import './data-table-labels.js';
|
|
5
5
|
import './mini-calendar.js';
|
|
6
6
|
import './calendar-heatmap.js';
|
|
@@ -85,11 +85,19 @@ interface NumberPadSheetLabels extends Partial<CalculatorLabels> {
|
|
|
85
85
|
/** Visible text on the primary key, not an `aria-label`. */
|
|
86
86
|
done?: string;
|
|
87
87
|
}
|
|
88
|
-
declare function NumberPadSheet({ value, onChange, onDone, label, labels, }: {
|
|
88
|
+
declare function NumberPadSheet({ value, onChange, onDone, label, labels, decimalMark, onResult, }: {
|
|
89
89
|
value: string;
|
|
90
90
|
/** Fired with the raw (sanitised) field text on every key — same contract as
|
|
91
91
|
* the host field's own `onChange`. */
|
|
92
92
|
onChange: (value: string) => void;
|
|
93
|
+
/** The glyph on the decimal key — "," where the host shows a comma (AmountInput
|
|
94
|
+
* in fr-CH, kastlan 40). With "," the key inserts a comma and the text is handed
|
|
95
|
+
* back unsanitized, for the host to read by its locale (keksdose G1). */
|
|
96
|
+
decimalMark?: "." | ",";
|
|
97
|
+
/** "=": the evaluated result, dot-decimal. Default `onChange`. A host that reads
|
|
98
|
+
* typed text by the locale's marks takes it apart from keystrokes, since a result
|
|
99
|
+
* like "1.234" is a decimal and never a grouped thousand. */
|
|
100
|
+
onResult?: (value: string) => void;
|
|
93
101
|
/** Fired on "Done": the host blurs the input, which commits (evaluates) and
|
|
94
102
|
* unmounts the sheet via its existing blur handler. */
|
|
95
103
|
onDone: () => void;
|
|
@@ -36,7 +36,9 @@ function NumberPadSheet({
|
|
|
36
36
|
onChange,
|
|
37
37
|
onDone,
|
|
38
38
|
label,
|
|
39
|
-
labels
|
|
39
|
+
labels,
|
|
40
|
+
decimalMark = ".",
|
|
41
|
+
onResult
|
|
40
42
|
}) {
|
|
41
43
|
const fromProps = useMemo(() => {
|
|
42
44
|
if (!labels) return void 0;
|
|
@@ -47,11 +49,11 @@ function NumberPadSheet({
|
|
|
47
49
|
useEscapeKey(onDone);
|
|
48
50
|
const result = evaluateExpression(value);
|
|
49
51
|
const preview = result !== null && formatResult(result) !== value.trim() ? `= ${formatResult(result)}` : "";
|
|
50
|
-
const insert = (ch) => onChange(sanitizeLive(value + ch));
|
|
52
|
+
const insert = (ch) => onChange(decimalMark === "," ? value + (ch === "." ? "," : ch) : sanitizeLive(value + ch));
|
|
51
53
|
const backspace = () => onChange(value.slice(0, -1));
|
|
52
54
|
const clearAll = () => onChange("");
|
|
53
55
|
const equals = () => {
|
|
54
|
-
if (result !== null) onChange(formatResult(result));
|
|
56
|
+
if (result !== null) (onResult ?? onChange)(formatResult(result));
|
|
55
57
|
};
|
|
56
58
|
const sheet = /* @__PURE__ */ jsxs(
|
|
57
59
|
"div",
|
|
@@ -87,7 +89,7 @@ function NumberPadSheet({
|
|
|
87
89
|
"aria-label": key.name ? text[key.name] : key.label,
|
|
88
90
|
onClick: () => insert(key.ins),
|
|
89
91
|
className: cn(PAD_BTN, key.accent ? PAD_ACCENT : PAD_DIGIT),
|
|
90
|
-
children: key.label
|
|
92
|
+
children: key.kind === "ins" && key.name === "decimal" ? decimalMark : key.label
|
|
91
93
|
},
|
|
92
94
|
`${key.ins}-${i}`
|
|
93
95
|
)
|