@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.
Files changed (197) hide show
  1. package/README.md +10 -10
  2. package/dist/components/amount-input.d.ts +23 -1
  3. package/dist/components/amount-input.js +78 -13
  4. package/dist/components/amount-input.js.map +1 -1
  5. package/dist/components/bulk-action-bar.d.ts +10 -2
  6. package/dist/components/bulk-action-bar.js.map +1 -1
  7. package/dist/components/button-group.d.ts +1 -1
  8. package/dist/components/calculator.d.ts +1 -1
  9. package/dist/components/chart.js +14 -8
  10. package/dist/components/chart.js.map +1 -1
  11. package/dist/components/chip.js +20 -15
  12. package/dist/components/chip.js.map +1 -1
  13. package/dist/components/combobox-core.d.ts +3 -1
  14. package/dist/components/combobox-core.js +16 -5
  15. package/dist/components/combobox-core.js.map +1 -1
  16. package/dist/components/combobox.js.map +1 -1
  17. package/dist/components/copy-button.d.ts +1 -1
  18. package/dist/components/data-table-filter-popover.js +8 -1
  19. package/dist/components/data-table-filter-popover.js.map +1 -1
  20. package/dist/components/data-table.js +28 -20
  21. package/dist/components/data-table.js.map +1 -1
  22. package/dist/components/entity-combobox.js +22 -17
  23. package/dist/components/entity-combobox.js.map +1 -1
  24. package/dist/components/error-boundary.d.ts +202 -13
  25. package/dist/components/error-boundary.js +225 -21
  26. package/dist/components/error-boundary.js.map +1 -1
  27. package/dist/components/field-sync.js +90 -83
  28. package/dist/components/field-sync.js.map +1 -1
  29. package/dist/components/file-button.d.ts +1 -1
  30. package/dist/components/file-dropzone.d.ts +1 -1
  31. package/dist/components/form-actions.d.ts +1 -1
  32. package/dist/components/full-bleed-dialog.js +4 -0
  33. package/dist/components/full-bleed-dialog.js.map +1 -1
  34. package/dist/components/hover-menu.js +64 -56
  35. package/dist/components/hover-menu.js.map +1 -1
  36. package/dist/components/list.d.ts +14 -2
  37. package/dist/components/list.js +3 -1
  38. package/dist/components/list.js.map +1 -1
  39. package/dist/components/modal.js.map +1 -1
  40. package/dist/components/multi-entity-combobox.js +23 -17
  41. package/dist/components/multi-entity-combobox.js.map +1 -1
  42. package/dist/components/number-field.d.ts +1 -1
  43. package/dist/components/number-input.d.ts +1 -1
  44. package/dist/components/number-input.js.map +1 -1
  45. package/dist/components/numpad-sheet.d.ts +10 -2
  46. package/dist/components/numpad-sheet.js +6 -4
  47. package/dist/components/numpad-sheet.js.map +1 -1
  48. package/dist/components/page-header.d.ts +35 -6
  49. package/dist/components/page-header.js +7 -1
  50. package/dist/components/page-header.js.map +1 -1
  51. package/dist/components/picker-sheet.js +3 -0
  52. package/dist/components/picker-sheet.js.map +1 -1
  53. package/dist/components/popover.js +3 -0
  54. package/dist/components/popover.js.map +1 -1
  55. package/dist/components/settings-fields.d.ts +1 -1
  56. package/dist/components/signed-amount.d.ts +2 -1
  57. package/dist/components/signed-amount.js +1 -1
  58. package/dist/components/signed-amount.js.map +1 -1
  59. package/dist/components/stat-tile.js +1 -1
  60. package/dist/components/stat-tile.js.map +1 -1
  61. package/dist/components/swipeable-row.js +4 -3
  62. package/dist/components/swipeable-row.js.map +1 -1
  63. package/dist/components/text-link.d.ts +73 -11
  64. package/dist/components/text-link.js +45 -10
  65. package/dist/components/text-link.js.map +1 -1
  66. package/dist/components/text.d.ts +26 -2
  67. package/dist/components/text.js +16 -2
  68. package/dist/components/text.js.map +1 -1
  69. package/dist/components/time-input.d.ts +1 -1
  70. package/dist/components/toggle-group.d.ts +22 -0
  71. package/dist/components/toggle-group.js +8 -8
  72. package/dist/components/toggle-group.js.map +1 -1
  73. package/dist/components/toggle-legend.d.ts +17 -0
  74. package/dist/components/toggle-legend.js +6 -2
  75. package/dist/components/toggle-legend.js.map +1 -1
  76. package/dist/components/tooltip.d.ts +51 -1
  77. package/dist/components/tooltip.js +59 -35
  78. package/dist/components/tooltip.js.map +1 -1
  79. package/dist/components/ui.d.ts +1 -1
  80. package/dist/components/ui.js +166 -28
  81. package/dist/components/ui.js.map +1 -1
  82. package/dist/feedback/feedback-attachment.js +4 -6
  83. package/dist/feedback/feedback-attachment.js.map +1 -1
  84. package/dist/feedback/feedback-dialog.js +5 -3
  85. package/dist/feedback/feedback-dialog.js.map +1 -1
  86. package/dist/feedback/feedback-inbox.js +86 -75
  87. package/dist/feedback/feedback-inbox.js.map +1 -1
  88. package/dist/feedback/feedback-thread.d.ts +43 -3
  89. package/dist/feedback/feedback-thread.js +53 -26
  90. package/dist/feedback/feedback-thread.js.map +1 -1
  91. package/dist/feedback.d.ts +1 -1
  92. package/dist/hooks/use-file-drop.d.ts +1 -1
  93. package/dist/i18n/defaults.d.ts +1 -1
  94. package/dist/i18n/kit-labels.d.ts +1 -1
  95. package/dist/i18n/kit-labels.js.map +1 -1
  96. package/dist/i18n/locales/de-CH-informal.d.ts +1 -1
  97. package/dist/i18n/locales/de-CH.d.ts +1 -1
  98. package/dist/i18n/locales/de-informal.d.ts +1 -1
  99. package/dist/i18n/locales/de.d.ts +1 -1
  100. package/dist/i18n/locales/de.js +9 -1
  101. package/dist/i18n/locales/de.js.map +1 -1
  102. package/dist/i18n/locales/es.d.ts +1 -1
  103. package/dist/i18n/locales/es.js +9 -1
  104. package/dist/i18n/locales/es.js.map +1 -1
  105. package/dist/i18n/locales/fr.d.ts +1 -1
  106. package/dist/i18n/locales/fr.js +9 -1
  107. package/dist/i18n/locales/fr.js.map +1 -1
  108. package/dist/i18n/locales/hu.d.ts +1 -1
  109. package/dist/i18n/locales/hu.js +9 -1
  110. package/dist/i18n/locales/hu.js.map +1 -1
  111. package/dist/i18n/locales/it.d.ts +1 -1
  112. package/dist/i18n/locales/it.js +9 -1
  113. package/dist/i18n/locales/it.js.map +1 -1
  114. package/dist/i18n/locales/zh.d.ts +1 -1
  115. package/dist/i18n/locales/zh.js +9 -1
  116. package/dist/i18n/locales/zh.js.map +1 -1
  117. package/dist/index.d.ts +6 -6
  118. package/dist/{kit-labels-v3biUF1L.d.ts → kit-labels-Mz8zZHIF.d.ts} +102 -3
  119. package/dist/lib/format.d.ts +23 -5
  120. package/dist/lib/format.js +4 -2
  121. package/dist/lib/format.js.map +1 -1
  122. package/dist/rhf/fields.d.ts +59 -15
  123. package/dist/rhf/fields.js +41 -11
  124. package/dist/rhf/fields.js.map +1 -1
  125. package/dist/rhf/form.d.ts +1 -1
  126. package/dist/rhf.d.ts +2 -2
  127. package/dist/rhf.js.map +1 -1
  128. package/dist/search/command-palette.js +20 -14
  129. package/dist/search/command-palette.js.map +1 -1
  130. package/dist/shell/app-shell.d.ts +1 -1
  131. package/dist/shell/app-shell.js +62 -54
  132. package/dist/shell/app-shell.js.map +1 -1
  133. package/dist/shell/top-bar-brand.d.ts +1 -1
  134. package/dist/shell/topbar-action-menu.d.ts +9 -3
  135. package/dist/shell/topbar-action-menu.js +2 -1
  136. package/dist/shell/topbar-action-menu.js.map +1 -1
  137. package/dist/shell.d.ts +1 -1
  138. package/dist/tour/tour.js +10 -4
  139. package/dist/tour/tour.js.map +1 -1
  140. package/dist/wizard/stepper-nav.d.ts +1 -1
  141. package/dist/wizard/use-wizard.js +4 -2
  142. package/dist/wizard/use-wizard.js.map +1 -1
  143. package/dist/wizard/wizard-step.d.ts +11 -1
  144. package/dist/wizard/wizard-step.js +24 -6
  145. package/dist/wizard/wizard-step.js.map +1 -1
  146. package/dist/wizard.d.ts +1 -1
  147. package/package.json +6 -6
  148. package/src/components/amount-input.tsx +165 -12
  149. package/src/components/bulk-action-bar.tsx +16 -3
  150. package/src/components/chart.tsx +19 -8
  151. package/src/components/chip.tsx +6 -0
  152. package/src/components/combobox-core.tsx +28 -9
  153. package/src/components/combobox.tsx +2 -0
  154. package/src/components/data-table-filter-popover.tsx +13 -5
  155. package/src/components/data-table.tsx +6 -0
  156. package/src/components/entity-combobox.tsx +7 -4
  157. package/src/components/error-boundary.tsx +470 -30
  158. package/src/components/field-sync.tsx +48 -40
  159. package/src/components/full-bleed-dialog.tsx +4 -0
  160. package/src/components/hover-menu.tsx +26 -17
  161. package/src/components/list.tsx +17 -3
  162. package/src/components/modal.tsx +4 -0
  163. package/src/components/multi-entity-combobox.tsx +8 -4
  164. package/src/components/number-input.tsx +1 -0
  165. package/src/components/numpad-sheet.tsx +17 -3
  166. package/src/components/page-header.tsx +42 -5
  167. package/src/components/picker-sheet.tsx +3 -0
  168. package/src/components/popover.tsx +3 -0
  169. package/src/components/signed-amount.tsx +12 -3
  170. package/src/components/stat-tile.tsx +3 -1
  171. package/src/components/swipeable-row.tsx +7 -7
  172. package/src/components/text-link.tsx +126 -18
  173. package/src/components/text.tsx +47 -2
  174. package/src/components/toggle-group.tsx +35 -10
  175. package/src/components/toggle-legend.tsx +22 -1
  176. package/src/components/tooltip.tsx +79 -8
  177. package/src/components/ui.tsx +307 -39
  178. package/src/feedback/feedback-attachment.tsx +10 -7
  179. package/src/feedback/feedback-dialog.tsx +7 -4
  180. package/src/feedback/feedback-inbox.tsx +7 -0
  181. package/src/feedback/feedback-thread.tsx +109 -33
  182. package/src/i18n/kit-labels.tsx +16 -0
  183. package/src/i18n/locales/de.ts +8 -0
  184. package/src/i18n/locales/es.ts +8 -0
  185. package/src/i18n/locales/fr.ts +8 -0
  186. package/src/i18n/locales/hu.ts +8 -0
  187. package/src/i18n/locales/it.ts +8 -0
  188. package/src/i18n/locales/zh.ts +8 -0
  189. package/src/lib/format.ts +32 -7
  190. package/src/rhf/fields.tsx +99 -16
  191. package/src/rhf.ts +1 -1
  192. package/src/search/command-palette.tsx +29 -19
  193. package/src/shell/app-shell.tsx +6 -1
  194. package/src/shell/topbar-action-menu.tsx +11 -4
  195. package/src/tour/tour.tsx +16 -5
  196. package/src/wizard/use-wizard.ts +8 -4
  197. package/src/wizard/wizard-step.tsx +38 -6
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/components/field-sync.tsx"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { AlertCircle, Check, Loader2, Pencil, PencilLine } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport { Tooltip } from \"./tooltip\";\nimport { useKitLabels } from \"../i18n/kit-labels\";\n\n/**\n * Sync state for a field backed by a database row.\n *\n * The four states a value can be in between the keyboard and the server:\n *\n * synced the draft equals what was last persisted\n * edited the draft differs and nothing has been sent yet\n * pending a save is in flight\n * error the last save was rejected; `error` carries why\n *\n * `useFieldSync` is the engine and holds no opinion about markup;\n * `FieldSyncIndicator` is the affordance and holds no state. They are separate\n * because the state is useful without the dot — a form can disable its submit\n * button while any field is `pending`, and a router can block navigation while\n * any field is `edited`.\n */\nexport type FieldSyncState = \"synced\" | \"edited\" | \"pending\" | \"error\";\n\nexport interface FieldSyncLabels {\n synced: string;\n edited: string;\n pending: string;\n /** Shown when the failure carries no message of its own. */\n error: string;\n retry: string;\n}\n\nexport const DEFAULT_FIELD_SYNC_LABELS: FieldSyncLabels = {\n synced: \"Saved\",\n edited: \"Unsaved changes\",\n pending: \"Saving…\",\n error: \"Could not save\",\n retry: \"Retry\",\n};\n\nexport function resolveFieldSyncLabels(labels?: Partial<FieldSyncLabels>): FieldSyncLabels {\n return labels ? { ...DEFAULT_FIELD_SYNC_LABELS, ...labels } : DEFAULT_FIELD_SYNC_LABELS;\n}\n\nexport interface UseFieldSyncOptions<T> {\n /** What the database currently holds. Changing it re-seeds a CLEAN field. */\n value: T;\n /** Persist `next`. Reject — or throw — to put the field in `error`. */\n onSave: (next: T) => Promise<void> | void;\n /**\n * Quiet period before an edit saves itself, in ms. Default `0`: no auto-save at\n * all, so `save()` is the only way to persist — called on blur by `FieldSyncRow`,\n * and on Enter by the caller. Saving after a pause in typing wrote half-finished\n * values to the database whenever somebody stopped to think; pass a positive\n * number only for a field where that is genuinely wanted.\n */\n debounceMs?: number;\n /** How to tell two values apart. Defaults to `Object.is`. */\n equals?: (a: T, b: T) => boolean;\n /** Called once per rejected save, with whatever `onSave` threw. */\n onError?: (error: Error) => void;\n}\n\nexport interface UseFieldSyncReturn<T> {\n /** The draft — bind this to the input, not the `value` option. */\n value: T;\n setValue: (next: T) => void;\n state: FieldSyncState;\n /** Non-null exactly when `state === \"error\"`. */\n error: Error | null;\n /** True whenever the draft differs from the last persisted value. */\n dirty: boolean;\n /** Persist now, cancelling any pending debounce. A no-op on a clean field. */\n save: () => void;\n /** Send the current draft again after a failure. */\n retry: () => void;\n /** Throw the draft away and go back to the last persisted value. */\n reset: () => void;\n}\n\nfunction toError(cause: unknown): Error {\n if (cause instanceof Error) return cause;\n // An EMPTY message for a rejection that carried none, not an English one: the\n // indicator shows `error.message` when there is one and the translated\n // `fieldSync.error` otherwise, so a fallback message here was an English sentence\n // that outranked the app's own translation. The original value stays on `cause`\n // for whoever logs it from `onError`.\n return new Error(typeof cause === \"string\" ? cause : \"\", { cause });\n}\n\n/**\n * Track one database-backed field: a local draft, a debounced save, and the state\n * of the round trip.\n *\n * Four things this handles that a `useState` + `useEffect` in a page does not:\n *\n * 1. **An edit during a save is never lost.** A save in flight is not cancelled\n * and not raced — when it settles, the draft is compared again and sent once\n * more if it moved. Cancelling instead would drop a keystroke that arrived\n * mid-flight; firing immediately would let two writes land out of order.\n * 2. **The server value is only adopted when the field is clean.** An external\n * refresh that overwrote what somebody was typing would be a data-loss bug, so\n * a dirty draft wins and keeps winning until it is saved or reset.\n * 3. **Nothing is set after unmount.** The save resolves into a component that\n * may be gone — a row scrolled out of a virtualised table, a closed dialog.\n * 4. **`onSave` is read through a ref**, so an inline arrow — which every call\n * site will pass — does not restart the debounce on every render.\n */\nexport function useFieldSync<T>({\n value,\n onSave,\n debounceMs = 0,\n equals = Object.is,\n onError,\n}: UseFieldSyncOptions<T>): UseFieldSyncReturn<T> {\n const [draft, setDraft] = useState<T>(value);\n const [state, setState] = useState<FieldSyncState>(\"synced\");\n const [error, setError] = useState<Error | null>(null);\n\n // The last value known to be on the server. Not state: it changes together with\n // `state` inside the save, and a second render for it would be a wasted one.\n const savedRef = useRef<T>(value);\n const draftRef = useRef<T>(value);\n const inFlightRef = useRef(false);\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const mountedRef = useRef(true);\n\n // Latest-ref for the callbacks and comparators, so a caller passing inline\n // functions (all of them) does not invalidate the timer on every render.\n const onSaveRef = useRef(onSave);\n const onErrorRef = useRef(onError);\n const equalsRef = useRef(equals);\n useEffect(() => {\n onSaveRef.current = onSave;\n onErrorRef.current = onError;\n equalsRef.current = equals;\n });\n\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n if (timerRef.current) clearTimeout(timerRef.current);\n };\n }, []);\n\n const flush = useCallback(async () => {\n if (inFlightRef.current) return; // the settle path below picks the new draft up\n const next = draftRef.current;\n if (equalsRef.current(next, savedRef.current)) return;\n\n inFlightRef.current = true;\n setState(\"pending\");\n setError(null);\n try {\n await onSaveRef.current(next);\n savedRef.current = next;\n inFlightRef.current = false;\n if (!mountedRef.current) return;\n // The draft may have moved while this was in the air. Compare against what is\n // on screen NOW, not against what was sent.\n if (equalsRef.current(draftRef.current, next)) {\n setState(\"synced\");\n } else {\n setState(\"edited\");\n void flush();\n }\n } catch (cause) {\n inFlightRef.current = false;\n const err = toError(cause);\n onErrorRef.current?.(err);\n if (!mountedRef.current) return;\n setState(\"error\");\n setError(err);\n }\n }, []);\n\n const setValue = useCallback(\n (next: T) => {\n draftRef.current = next;\n setDraft(next);\n if (timerRef.current) clearTimeout(timerRef.current);\n\n if (equalsRef.current(next, savedRef.current)) {\n // Typed back to what the server already has. Nothing to send, and an error\n // from the previous attempt no longer describes anything.\n setState(inFlightRef.current ? \"pending\" : \"synced\");\n setError(null);\n return;\n }\n\n setState(\"edited\");\n setError(null);\n if (debounceMs > 0) timerRef.current = setTimeout(() => void flush(), debounceMs);\n },\n [debounceMs, flush],\n );\n\n const save = useCallback(() => {\n if (timerRef.current) clearTimeout(timerRef.current);\n void flush();\n }, [flush]);\n\n const retry = save;\n\n const reset = useCallback(() => {\n if (timerRef.current) clearTimeout(timerRef.current);\n draftRef.current = savedRef.current;\n setDraft(savedRef.current);\n setState(inFlightRef.current ? \"pending\" : \"synced\");\n setError(null);\n }, []);\n\n // Anything that is not `synced` has something not yet on the server: `edited` and\n // `error` obviously, and `pending` too — the write is in the air, not landed.\n // Derived from state rather than by comparing against `savedRef` during render,\n // because a ref read here would not re-render when the comparison's answer changes.\n const dirty = state !== \"synced\";\n\n // Adopt a new server value ONLY when there is nothing local to lose.\n useEffect(() => {\n if (inFlightRef.current) return;\n if (!equalsRef.current(draftRef.current, savedRef.current)) return; // dirty: keep it\n if (equalsRef.current(value, savedRef.current)) return; // unchanged\n savedRef.current = value;\n draftRef.current = value;\n setDraft(value);\n setState(\"synced\");\n setError(null);\n }, [value]);\n\n return { value: draft, setValue, state, error, dirty, save, retry, reset };\n}\n\nconst STATE_STYLE: Record<FieldSyncState, { color: string; Icon: typeof Check }> = {\n synced: { color: \"var(--status-synced)\", Icon: Check },\n edited: { color: \"var(--status-edited)\", Icon: Pencil },\n pending: { color: \"var(--status-pending)\", Icon: Loader2 },\n error: { color: \"var(--status-error)\", Icon: AlertCircle },\n};\n\nexport interface FieldSyncIndicatorProps {\n state: FieldSyncState;\n /** The failure. Its message becomes the tooltip when `state === \"error\"`. */\n error?: Error | null;\n /** Override any of the five English defaults. */\n labels?: Partial<FieldSyncLabels>;\n /** Render the label beside the icon instead of only in the tooltip. */\n showLabel?: boolean;\n /** When given, the error state renders a retry button after the icon. */\n onRetry?: () => void;\n className?: string;\n}\n\n/**\n * The affordance for {@link useFieldSync}: a coloured icon, and the reason on hover.\n *\n * **Every state has its own icon, and that is not decoration.** The four colours\n * include the green/red pair, which is the one combination this package's palette\n * otherwise refuses (see the note in `tokens.css`) because red-green colour blindness\n * affects roughly one man in twelve. The icon is what carries the meaning for them,\n * and what carries it into a greyscale print or a screenshot. WCAG 1.4.1 is the same\n * requirement stated formally.\n *\n * The state is also announced: the wrapper is a polite live region, so a screen\n * reader hears \"Saving…\" then \"Saved\" without the user going looking. `error` is\n * assertive instead — a failed write is worth interrupting for.\n */\nexport function FieldSyncIndicator({\n state,\n error,\n labels,\n showLabel = false,\n onRetry,\n className,\n}: FieldSyncIndicatorProps) {\n const l = useKitLabels(\"fieldSync\", DEFAULT_FIELD_SYNC_LABELS, labels);\n const { color, Icon } = STATE_STYLE[state];\n const text =\n state === \"error\" ? (error?.message?.trim() ? error.message : l.error) : l[state];\n\n return (\n <span\n // The ICON carries the status colour; the words are `--text-secondary`, because\n // the amber of `edited` is a graphic colour (3:1), not a text colour (4.5:1).\n className={cn(\"inline-flex items-center gap-1.5 text-xs text-[var(--text-secondary)]\", className)}\n // Polite for the three ordinary states so save chatter does not interrupt\n // typing; assertive for a failure, which the user has to know about now.\n role={state === \"error\" ? \"alert\" : \"status\"}\n aria-live={state === \"error\" ? \"assertive\" : \"polite\"}\n >\n <Tooltip label={showLabel ? undefined : text} redact={state === \"error\"}>\n <span className=\"inline-flex items-center gap-1.5\">\n <Icon\n aria-hidden\n style={{ color }}\n className={cn(\"size-3.5 shrink-0\", state === \"pending\" && \"animate-spin\")}\n />\n {/* Always in the DOM, so the live region has something to announce even\n when the label is visually a tooltip. */}\n <span className={showLabel ? undefined : \"sr-only\"}>{text}</span>\n </span>\n </Tooltip>\n {state === \"error\" && onRetry && (\n <button\n type=\"button\"\n onClick={onRetry}\n className=\"rounded underline underline-offset-2 hover:no-underline focus-visible:outline-2 focus-visible:outline-offset-2\"\n style={{ color }}\n >\n {l.retry}\n </button>\n )}\n </span>\n );\n}\n\n/**\n * The field's own frame, coloured by state — applied from the WRAPPER to whatever\n * native control sits inside it, so {@link FieldSyncRow} works with any of the kit's\n * inputs (and a caller's own) without each one growing a `syncState` prop.\n *\n * Border AND a 1px ring, for the reason {@link FIELD_INVALID} gives: a lone 1px\n * border loses a vertical edge to sub-pixel spread at 125% display scaling. The\n * `:focus` twins are what keep the state visible while the reader is typing —\n * the base field class's `focus:` brand colour is `(0,2,0)` and would otherwise win\n * over a descendant selector exactly when the field is in use.\n *\n * `synced` is green, but {@link FieldSyncRow} paints it only for a moment after a\n * save lands — a form of eight permanently green boxes says nothing the absence of\n * colour does not.\n *\n * Every class is a literal so Tailwind's scanner can see it.\n */\nexport const FIELD_SYNC_FRAME: Record<FieldSyncState, string> = {\n synced:\n \"[&_:is(input,select,textarea)]:border-[var(--status-synced)] [&_:is(input,select,textarea)]:ring-1 [&_:is(input,select,textarea)]:ring-[var(--status-synced)] [&_:is(input,select,textarea):focus]:border-[var(--status-synced)] [&_:is(input,select,textarea):focus]:ring-[var(--status-synced)]\",\n edited:\n \"[&_:is(input,select,textarea)]:border-[var(--status-edited)] [&_:is(input,select,textarea)]:ring-1 [&_:is(input,select,textarea)]:ring-[var(--status-edited)] [&_:is(input,select,textarea):focus]:border-[var(--status-edited)] [&_:is(input,select,textarea):focus]:ring-[var(--status-edited)]\",\n pending:\n \"[&_:is(input,select,textarea)]:border-[var(--status-pending)] [&_:is(input,select,textarea)]:ring-1 [&_:is(input,select,textarea)]:ring-[var(--status-pending)] [&_:is(input,select,textarea):focus]:border-[var(--status-pending)] [&_:is(input,select,textarea):focus]:ring-[var(--status-pending)]\",\n error:\n \"[&_:is(input,select,textarea)]:border-[var(--status-error)] [&_:is(input,select,textarea)]:ring-1 [&_:is(input,select,textarea)]:ring-[var(--status-error)] [&_:is(input,select,textarea):focus]:border-[var(--status-error)] [&_:is(input,select,textarea):focus]:ring-[var(--status-error)]\",\n};\n\n/** How long the green \"saved\" frame and check stay after a save lands, in ms. */\nexport const FIELD_SYNC_SAVED_MS = 1500;\n\nexport interface FieldSyncRowProps<T> extends Omit<FieldSyncIndicatorProps, \"state\" | \"error\" | \"showLabel\"> {\n sync: UseFieldSyncReturn<T>;\n children: ReactNode;\n /** Call `sync.save()` when focus leaves the field. Default true — together with the\n * hook's default `debounceMs: 0` this is \"save on blur\": nothing is written while\n * the reader is still typing, however long they pause. */\n saveOnBlur?: boolean;\n /** How long the saved confirmation shows. Default {@link FIELD_SYNC_SAVED_MS}. */\n savedMs?: number;\n}\n\n/**\n * A field wearing its sync state — as its FRAME COLOUR and an ICON AT THE END OF THE\n * FIELD, so the field never changes size (a helper line appearing under it moved\n * everything below it on every save):\n *\n * edited amber frame, pencil — changed, not yet saved\n * pending blue frame, spinning circle — for as long as the save is in flight\n * synced green frame, check — for {@link FIELD_SYNC_SAVED_MS} after a\n * save lands, then an ordinary field again\n * error red frame, alert mark — hover or focus the mark for the reason;\n * click it to retry\n *\n * It saves when focus LEAVES the field (`saveOnBlur`), not after a pause in typing: a\n * database write in the middle of a word is a write nobody asked for. Enter in a\n * single-line field is the caller's to wire to `sync.save`.\n *\n * Colour is never the only signal: every state has its own icon, and the state text is\n * always in the DOM as a live region — polite for the ordinary states, assertive for\n * a failure. The input gets end padding for the icon whether or not one is showing,\n * so the text never reflows when the state changes.\n */\nexport function FieldSyncRow<T>({\n sync,\n children,\n className,\n labels,\n onRetry,\n saveOnBlur = true,\n savedMs = FIELD_SYNC_SAVED_MS,\n}: FieldSyncRowProps<T>) {\n const l = useKitLabels(\"fieldSync\", DEFAULT_FIELD_SYNC_LABELS, labels);\n const { state, error } = sync;\n const isError = state === \"error\";\n const text = isError ? (error?.message?.trim() ? error.message : l.error) : l[state];\n const retry = onRetry ?? sync.retry;\n\n // The saved confirmation: on only for the moment after a save lands. Keyed on the\n // TRANSITION pending → synced, so a field that starts synced shows nothing.\n const previous = useRef(state);\n const [justSaved, setJustSaved] = useState(false);\n useEffect(() => {\n const was = previous.current;\n previous.current = state;\n if (state === \"synced\" && was === \"pending\") {\n // eslint-disable-next-line react-hooks/set-state-in-effect -- reacts to the save landing\n setJustSaved(true);\n const t = setTimeout(() => setJustSaved(false), savedMs);\n return () => clearTimeout(t);\n }\n if (state !== \"synced\") setJustSaved(false);\n }, [state, savedMs]);\n const shown: FieldSyncState | null = state === \"synced\" ? (justSaved ? \"synced\" : null) : state;\n\n return (\n <div\n data-field-sync={state}\n className={cn(\n // `relative` for the icon and for the sr-only live region's containing block.\n \"relative [&_:is(input,select,textarea)]:pe-9\",\n shown && FIELD_SYNC_FRAME[shown],\n className,\n )}\n onBlur={\n saveOnBlur\n ? (e) => {\n // Focus moving between two controls INSIDE the row is not leaving it.\n if (!e.currentTarget.contains(e.relatedTarget as Node | null)) sync.save();\n }\n : undefined\n }\n >\n {children}\n <span className=\"pointer-events-none absolute inset-y-0 end-0 flex items-center pe-3\">\n {state === \"edited\" && (\n <PencilLine aria-hidden className=\"size-4 text-[var(--status-edited)]\" />\n )}\n {state === \"pending\" && (\n <Loader2 aria-hidden className=\"size-4 animate-spin text-[var(--status-pending)] motion-reduce:animate-none\" />\n )}\n {state === \"synced\" && (\n <Check\n aria-hidden\n className={cn(\n \"size-4 text-[var(--status-synced)] transition-opacity duration-500 motion-reduce:transition-none\",\n justSaved ? \"opacity-100\" : \"opacity-0\",\n )}\n />\n )}\n {isError && (\n <Tooltip label={text} portal redact>\n <button\n type=\"button\"\n onClick={retry}\n aria-label={l.retry}\n className=\"pointer-events-auto flex rounded-full text-[var(--status-error)] focus-visible:outline-2 focus-visible:outline-offset-2\"\n >\n <AlertCircle aria-hidden className=\"size-4\" />\n </button>\n </Tooltip>\n )}\n </span>\n <span\n role={isError ? \"alert\" : \"status\"}\n aria-live={isError ? \"assertive\" : \"polite\"}\n className=\"sr-only\"\n >\n {shown === null ? \"\" : text}\n </span>\n </div>\n );\n}\n"],"mappings":";AAsSQ,SACE,KADF;AAtSR,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAEzD,SAAS,aAAa,OAAO,SAAS,QAAQ,kBAAkB;AAChE,SAAS,UAAU;AACnB,SAAS,eAAe;AACxB,SAAS,oBAAoB;AA6BtB,MAAM,4BAA6C;AAAA,EACxD,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,OAAO;AAAA,EACP,OAAO;AACT;AAEO,SAAS,uBAAuB,QAAoD;AACzF,SAAO,SAAS,EAAE,GAAG,2BAA2B,GAAG,OAAO,IAAI;AAChE;AAsCA,SAAS,QAAQ,OAAuB;AACtC,MAAI,iBAAiB,MAAO,QAAO;AAMnC,S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AA;AAAA,QACD,qBAAC,UAAK,WAAU,uEACb;AAAA,oBAAU,YACT,oBAAC,cAAW,eAAW,MAAC,WAAU,sCAAqC;AAAA,UAExE,UAAU,aACT,oBAAC,WAAQ,eAAW,MAAC,WAAU,+EAA8E;AAAA,UAE9G,UAAU,YACT;AAAA,YAAC;AAAA;AAAA,cACC,eAAW;AAAA,cACX,WAAW;AAAA,gBACT;AAAA,gBACA,YAAY,gBAAgB;AAAA,cAC9B;AAAA;AAAA,UACF;AAAA,UAED,WACC,oBAAC,WAAQ,OAAO,MAAM,QAAM,MAAC,QAAM,MACjC;AAAA,YAAC;AAAA;AAAA,cACC,MAAK;AAAA,cACL,SAAS;AAAA,cACT,cAAY,EAAE;AAAA,cACd,WAAU;AAAA,cAEV,8BAAC,eAAY,eAAW,MAAC,WAAU,UAAS;AAAA;AAAA,UAC9C,GACF;AAAA,WAEJ;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YACC,MAAM,UAAU,UAAU;AAAA,YAC1B,aAAW,UAAU,cAAc;AAAA,YACnC,WAAU;AAAA,YAET,oBAAU,OAAO,KAAK;AAAA;AAAA,QACzB;AAAA;AAAA;AAAA,EACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../../src/components/field-sync.tsx"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { AlertCircle, Check, Loader2, Pencil, PencilLine } from \"lucide-react\";\nimport { cn } from \"../lib/cn\";\nimport { Tooltip } from \"./tooltip\";\nimport { useKitLabels } from \"../i18n/kit-labels\";\n\n/**\n * Sync state for a field backed by a database row.\n *\n * The four states a value can be in between the keyboard and the server:\n *\n * synced the draft equals what was last persisted\n * edited the draft differs and nothing has been sent yet\n * pending a save is in flight\n * error the last save was rejected; `error` carries why\n *\n * `useFieldSync` is the engine and holds no opinion about markup;\n * `FieldSyncIndicator` is the affordance and holds no state. They are separate\n * because the state is useful without the dot — a form can disable its submit\n * button while any field is `pending`, and a router can block navigation while\n * any field is `edited`.\n */\nexport type FieldSyncState = \"synced\" | \"edited\" | \"pending\" | \"error\";\n\nexport interface FieldSyncLabels {\n synced: string;\n edited: string;\n pending: string;\n /** Shown when the failure carries no message of its own. */\n error: string;\n retry: string;\n}\n\nexport const DEFAULT_FIELD_SYNC_LABELS: FieldSyncLabels = {\n synced: \"Saved\",\n edited: \"Unsaved changes\",\n pending: \"Saving…\",\n error: \"Could not save\",\n retry: \"Retry\",\n};\n\nexport function resolveFieldSyncLabels(labels?: Partial<FieldSyncLabels>): FieldSyncLabels {\n return labels ? { ...DEFAULT_FIELD_SYNC_LABELS, ...labels } : DEFAULT_FIELD_SYNC_LABELS;\n}\n\nexport interface UseFieldSyncOptions<T> {\n /** What the database currently holds. Changing it re-seeds a CLEAN field. */\n value: T;\n /** Persist `next`. Reject — or throw — to put the field in `error`. */\n onSave: (next: T) => Promise<void> | void;\n /**\n * Quiet period before an edit saves itself, in ms. Default `0`: no auto-save at\n * all, so `save()` is the only way to persist — called on blur by `FieldSyncRow`,\n * and on Enter by the caller. Saving after a pause in typing wrote half-finished\n * values to the database whenever somebody stopped to think; pass a positive\n * number only for a field where that is genuinely wanted.\n */\n debounceMs?: number;\n /** How to tell two values apart. Defaults to `Object.is`. */\n equals?: (a: T, b: T) => boolean;\n /** Called once per rejected save, with whatever `onSave` threw. */\n onError?: (error: Error) => void;\n}\n\nexport interface UseFieldSyncReturn<T> {\n /** The draft — bind this to the input, not the `value` option. */\n value: T;\n setValue: (next: T) => void;\n state: FieldSyncState;\n /** Non-null exactly when `state === \"error\"`. */\n error: Error | null;\n /** True whenever the draft differs from the last persisted value. */\n dirty: boolean;\n /** Persist now, cancelling any pending debounce. A no-op on a clean field. */\n save: () => void;\n /** Send the current draft again after a failure. */\n retry: () => void;\n /** Throw the draft away and go back to the last persisted value. */\n reset: () => void;\n}\n\nfunction toError(cause: unknown): Error {\n if (cause instanceof Error) return cause;\n // An EMPTY message for a rejection that carried none, not an English one: the\n // indicator shows `error.message` when there is one and the translated\n // `fieldSync.error` otherwise, so a fallback message here was an English sentence\n // that outranked the app's own translation. The original value stays on `cause`\n // for whoever logs it from `onError`.\n return new Error(typeof cause === \"string\" ? cause : \"\", { cause });\n}\n\n/**\n * Track one database-backed field: a local draft, a debounced save, and the state\n * of the round trip.\n *\n * Four things this handles that a `useState` + `useEffect` in a page does not:\n *\n * 1. **An edit during a save is never lost.** A save in flight is not cancelled\n * and not raced — when it settles, the draft is compared again and sent once\n * more if it moved. Cancelling instead would drop a keystroke that arrived\n * mid-flight; firing immediately would let two writes land out of order.\n * 2. **The server value is only adopted when the field is clean.** An external\n * refresh that overwrote what somebody was typing would be a data-loss bug, so\n * a dirty draft wins and keeps winning until it is saved or reset.\n * 3. **Nothing is set after unmount.** The save resolves into a component that\n * may be gone — a row scrolled out of a virtualised table, a closed dialog.\n * 4. **`onSave` is read through a ref**, so an inline arrow — which every call\n * site will pass — does not restart the debounce on every render.\n */\nexport function useFieldSync<T>({\n value,\n onSave,\n debounceMs = 0,\n equals = Object.is,\n onError,\n}: UseFieldSyncOptions<T>): UseFieldSyncReturn<T> {\n const [draft, setDraft] = useState<T>(value);\n const [state, setState] = useState<FieldSyncState>(\"synced\");\n const [error, setError] = useState<Error | null>(null);\n\n // The last value known to be on the server. Not state: it changes together with\n // `state` inside the save, and a second render for it would be a wasted one.\n const savedRef = useRef<T>(value);\n const draftRef = useRef<T>(value);\n const inFlightRef = useRef(false);\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const mountedRef = useRef(true);\n\n // Latest-ref for the callbacks and comparators, so a caller passing inline\n // functions (all of them) does not invalidate the timer on every render.\n const onSaveRef = useRef(onSave);\n const onErrorRef = useRef(onError);\n const equalsRef = useRef(equals);\n useEffect(() => {\n onSaveRef.current = onSave;\n onErrorRef.current = onError;\n equalsRef.current = equals;\n });\n\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n if (timerRef.current) clearTimeout(timerRef.current);\n };\n }, []);\n\n // A named inner function so the settle path can start the next round by calling it\n // again; a `useCallback` cannot refer to its own binding while it is being built.\n const flush = useCallback(() => {\n const run = async (): Promise<void> => {\n if (inFlightRef.current) return; // the settle path below picks the new draft up\n const next = draftRef.current;\n if (equalsRef.current(next, savedRef.current)) return;\n\n inFlightRef.current = true;\n setState(\"pending\");\n setError(null);\n try {\n await onSaveRef.current(next);\n savedRef.current = next;\n inFlightRef.current = false;\n if (!mountedRef.current) return;\n // The draft may have moved while this was in the air. Compare against what is\n // on screen NOW, not against what was sent.\n if (equalsRef.current(draftRef.current, next)) {\n setState(\"synced\");\n } else {\n setState(\"edited\");\n void run();\n }\n } catch (cause) {\n inFlightRef.current = false;\n const err = toError(cause);\n onErrorRef.current?.(err);\n if (!mountedRef.current) return;\n setState(\"error\");\n setError(err);\n }\n };\n return run();\n }, []);\n\n const setValue = useCallback(\n (next: T) => {\n draftRef.current = next;\n setDraft(next);\n if (timerRef.current) clearTimeout(timerRef.current);\n\n if (equalsRef.current(next, savedRef.current)) {\n // Typed back to what the server already has. Nothing to send, and an error\n // from the previous attempt no longer describes anything.\n setState(inFlightRef.current ? \"pending\" : \"synced\");\n setError(null);\n return;\n }\n\n setState(\"edited\");\n setError(null);\n if (debounceMs > 0) timerRef.current = setTimeout(() => void flush(), debounceMs);\n },\n [debounceMs, flush],\n );\n\n const save = useCallback(() => {\n if (timerRef.current) clearTimeout(timerRef.current);\n void flush();\n }, [flush]);\n\n const retry = save;\n\n const reset = useCallback(() => {\n if (timerRef.current) clearTimeout(timerRef.current);\n draftRef.current = savedRef.current;\n setDraft(savedRef.current);\n setState(inFlightRef.current ? \"pending\" : \"synced\");\n setError(null);\n }, []);\n\n // Anything that is not `synced` has something not yet on the server: `edited` and\n // `error` obviously, and `pending` too — the write is in the air, not landed.\n // Derived from state rather than by comparing against `savedRef` during render,\n // because a ref read here would not re-render when the comparison's answer changes.\n const dirty = state !== \"synced\";\n\n // Adopt a new server value ONLY when there is nothing local to lose.\n useEffect(() => {\n if (inFlightRef.current) return;\n if (!equalsRef.current(draftRef.current, savedRef.current)) return; // dirty: keep it\n if (equalsRef.current(value, savedRef.current)) return; // unchanged\n savedRef.current = value;\n draftRef.current = value;\n setDraft(value);\n setState(\"synced\");\n setError(null);\n }, [value]);\n\n return { value: draft, setValue, state, error, dirty, save, retry, reset };\n}\n\nconst STATE_STYLE: Record<FieldSyncState, { color: string; Icon: typeof Check }> = {\n synced: { color: \"var(--status-synced)\", Icon: Check },\n edited: { color: \"var(--status-edited)\", Icon: Pencil },\n pending: { color: \"var(--status-pending)\", Icon: Loader2 },\n error: { color: \"var(--status-error)\", Icon: AlertCircle },\n};\n\nexport interface FieldSyncIndicatorProps {\n state: FieldSyncState;\n /** The failure. Its message becomes the tooltip when `state === \"error\"`. */\n error?: Error | null;\n /** Override any of the five English defaults. */\n labels?: Partial<FieldSyncLabels>;\n /** Render the label beside the icon instead of only in the tooltip. */\n showLabel?: boolean;\n /** When given, the error state renders a retry button after the icon. */\n onRetry?: () => void;\n className?: string;\n}\n\n/**\n * The affordance for {@link useFieldSync}: a coloured icon, and the reason on hover.\n *\n * **Every state has its own icon, and that is not decoration.** The four colours\n * include the green/red pair, which is the one combination this package's palette\n * otherwise refuses (see the note in `tokens.css`) because red-green colour blindness\n * affects roughly one man in twelve. The icon is what carries the meaning for them,\n * and what carries it into a greyscale print or a screenshot. WCAG 1.4.1 is the same\n * requirement stated formally.\n *\n * The state is also announced: the wrapper is a polite live region, so a screen\n * reader hears \"Saving…\" then \"Saved\" without the user going looking. `error` is\n * assertive instead — a failed write is worth interrupting for.\n */\nexport function FieldSyncIndicator({\n state,\n error,\n labels,\n showLabel = false,\n onRetry,\n className,\n}: FieldSyncIndicatorProps) {\n const l = useKitLabels(\"fieldSync\", DEFAULT_FIELD_SYNC_LABELS, labels);\n const { color, Icon } = STATE_STYLE[state];\n const text =\n state === \"error\" ? (error?.message?.trim() ? error.message : l.error) : l[state];\n\n return (\n <span\n // The ICON carries the status colour; the words are `--text-secondary`, because\n // the amber of `edited` is a graphic colour (3:1), not a text colour (4.5:1).\n className={cn(\"inline-flex items-center gap-1.5 text-xs text-[var(--text-secondary)]\", className)}\n // Polite for the three ordinary states so save chatter does not interrupt\n // typing; assertive for a failure, which the user has to know about now.\n role={state === \"error\" ? \"alert\" : \"status\"}\n aria-live={state === \"error\" ? \"assertive\" : \"polite\"}\n >\n <Tooltip label={showLabel ? undefined : text} redact={state === \"error\"}>\n <span className=\"inline-flex items-center gap-1.5\">\n <Icon\n aria-hidden\n style={{ color }}\n className={cn(\"size-3.5 shrink-0\", state === \"pending\" && \"animate-spin\")}\n />\n {/* Always in the DOM, so the live region has something to announce even\n when the label is visually a tooltip. */}\n <span className={showLabel ? undefined : \"sr-only\"}>{text}</span>\n </span>\n </Tooltip>\n {state === \"error\" && onRetry && (\n <button\n type=\"button\"\n onClick={onRetry}\n className=\"rounded underline underline-offset-2 hover:no-underline focus-visible:outline-2 focus-visible:outline-offset-2\"\n style={{ color }}\n >\n {l.retry}\n </button>\n )}\n </span>\n );\n}\n\n/**\n * The field's own frame, coloured by state — applied from the WRAPPER to whatever\n * native control sits inside it, so {@link FieldSyncRow} works with any of the kit's\n * inputs (and a caller's own) without each one growing a `syncState` prop.\n *\n * Border AND a 1px ring, for the reason {@link FIELD_INVALID} gives: a lone 1px\n * border loses a vertical edge to sub-pixel spread at 125% display scaling. The\n * `:focus` twins are what keep the state visible while the reader is typing —\n * the base field class's `focus:` brand colour is `(0,2,0)` and would otherwise win\n * over a descendant selector exactly when the field is in use.\n *\n * `synced` is green, but {@link FieldSyncRow} paints it only for a moment after a\n * save lands — a form of eight permanently green boxes says nothing the absence of\n * colour does not.\n *\n * Every class is a literal so Tailwind's scanner can see it.\n */\nexport const FIELD_SYNC_FRAME: Record<FieldSyncState, string> = {\n synced:\n \"[&_:is(input,select,textarea)]:border-[var(--status-synced)] [&_:is(input,select,textarea)]:ring-1 [&_:is(input,select,textarea)]:ring-[var(--status-synced)] [&_:is(input,select,textarea):focus]:border-[var(--status-synced)] [&_:is(input,select,textarea):focus]:ring-[var(--status-synced)]\",\n edited:\n \"[&_:is(input,select,textarea)]:border-[var(--status-edited)] [&_:is(input,select,textarea)]:ring-1 [&_:is(input,select,textarea)]:ring-[var(--status-edited)] [&_:is(input,select,textarea):focus]:border-[var(--status-edited)] [&_:is(input,select,textarea):focus]:ring-[var(--status-edited)]\",\n pending:\n \"[&_:is(input,select,textarea)]:border-[var(--status-pending)] [&_:is(input,select,textarea)]:ring-1 [&_:is(input,select,textarea)]:ring-[var(--status-pending)] [&_:is(input,select,textarea):focus]:border-[var(--status-pending)] [&_:is(input,select,textarea):focus]:ring-[var(--status-pending)]\",\n error:\n \"[&_:is(input,select,textarea)]:border-[var(--status-error)] [&_:is(input,select,textarea)]:ring-1 [&_:is(input,select,textarea)]:ring-[var(--status-error)] [&_:is(input,select,textarea):focus]:border-[var(--status-error)] [&_:is(input,select,textarea):focus]:ring-[var(--status-error)]\",\n};\n\n/** How long the green \"saved\" frame and check stay after a save lands, in ms. */\nexport const FIELD_SYNC_SAVED_MS = 1500;\n\nexport interface FieldSyncRowProps<T> extends Omit<FieldSyncIndicatorProps, \"state\" | \"error\" | \"showLabel\"> {\n sync: UseFieldSyncReturn<T>;\n children: ReactNode;\n /** Call `sync.save()` when focus leaves the field. Default true — together with the\n * hook's default `debounceMs: 0` this is \"save on blur\": nothing is written while\n * the reader is still typing, however long they pause. */\n saveOnBlur?: boolean;\n /** How long the saved confirmation shows. Default {@link FIELD_SYNC_SAVED_MS}. */\n savedMs?: number;\n}\n\n/**\n * A field wearing its sync state — as its FRAME COLOUR and an ICON AT THE END OF THE\n * FIELD, so the field never changes size (a helper line appearing under it moved\n * everything below it on every save):\n *\n * edited amber frame, pencil — changed, not yet saved\n * pending blue frame, spinning circle — for as long as the save is in flight\n * synced green frame, check — for {@link FIELD_SYNC_SAVED_MS} after a\n * save lands, then an ordinary field again\n * error red frame, alert mark — hover or focus the mark for the reason;\n * click it to retry\n *\n * It saves when focus LEAVES the field (`saveOnBlur`), not after a pause in typing: a\n * database write in the middle of a word is a write nobody asked for. Enter in a\n * single-line field is the caller's to wire to `sync.save`.\n *\n * Colour is never the only signal: every state has its own icon, and the state text is\n * always in the DOM as a live region — polite for the ordinary states, assertive for\n * a failure. The input gets end padding for the icon whether or not one is showing,\n * so the text never reflows when the state changes.\n */\nexport function FieldSyncRow<T>({\n sync,\n children,\n className,\n labels,\n onRetry,\n saveOnBlur = true,\n savedMs = FIELD_SYNC_SAVED_MS,\n}: FieldSyncRowProps<T>) {\n const l = useKitLabels(\"fieldSync\", DEFAULT_FIELD_SYNC_LABELS, labels);\n const { state, error } = sync;\n const isError = state === \"error\";\n const text = isError ? (error?.message?.trim() ? error.message : l.error) : l[state];\n const retry = onRetry ?? sync.retry;\n\n // The saved confirmation: on only for the moment after a save lands. Keyed on the\n // TRANSITION pending → synced, so a field that starts synced shows nothing. The\n // transition is seen while rendering, against the previous state; the effect only\n // owns the timer that turns it off again.\n const [previous, setPrevious] = useState(state);\n const [justSaved, setJustSaved] = useState(false);\n if (state !== previous) {\n setPrevious(state);\n setJustSaved(state === \"synced\" && previous === \"pending\");\n }\n useEffect(() => {\n if (!justSaved) return;\n const t = setTimeout(() => setJustSaved(false), savedMs);\n return () => clearTimeout(t);\n }, [justSaved, savedMs]);\n const shown: FieldSyncState | null = state === \"synced\" ? (justSaved ? \"synced\" : null) : state;\n\n return (\n /* eslint-disable-next-line jsx-a11y/no-static-element-interactions -- not an interaction:\n `onBlur` listens for focus leaving the row's own controls (which are the\n interactive elements) to save; the wrapper itself is never focused. */\n <div\n data-field-sync={state}\n className={cn(\n // `relative` for the icon and for the sr-only live region's containing block.\n \"relative [&_:is(input,select,textarea)]:pe-9\",\n shown && FIELD_SYNC_FRAME[shown],\n className,\n )}\n onBlur={\n saveOnBlur\n ? (e) => {\n // Focus moving between two controls INSIDE the row is not leaving it.\n if (!e.currentTarget.contains(e.relatedTarget as Node | null)) sync.save();\n }\n : undefined\n }\n >\n {children}\n <span className=\"pointer-events-none absolute inset-y-0 end-0 flex items-center pe-3\">\n {state === \"edited\" && (\n <PencilLine aria-hidden className=\"size-4 text-[var(--status-edited)]\" />\n )}\n {state === \"pending\" && (\n <Loader2 aria-hidden className=\"size-4 animate-spin text-[var(--status-pending)] motion-reduce:animate-none\" />\n )}\n {state === \"synced\" && (\n <Check\n aria-hidden\n className={cn(\n \"size-4 text-[var(--status-synced)] transition-opacity duration-500 motion-reduce:transition-none\",\n justSaved ? \"opacity-100\" : \"opacity-0\",\n )}\n />\n )}\n {isError && (\n <Tooltip label={text} portal redact>\n <button\n type=\"button\"\n onClick={retry}\n aria-label={l.retry}\n className=\"pointer-events-auto flex rounded-full text-[var(--status-error)] focus-visible:outline-2 focus-visible:outline-offset-2\"\n >\n <AlertCircle aria-hidden className=\"size-4\" />\n </button>\n </Tooltip>\n )}\n </span>\n <span\n role={isError ? \"alert\" : \"status\"}\n aria-live={isError ? \"assertive\" : \"polite\"}\n className=\"sr-only\"\n >\n {shown === null ? \"\" : text}\n </span>\n </div>\n );\n}\n"],"mappings":";AA2SQ,SACE,KADF;AA3SR,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAEzD,SAAS,aAAa,OAAO,SAAS,QAAQ,kBAAkB;AAChE,SAAS,UAAU;AACnB,SAAS,eAAe;AACxB,SAAS,oBAAoB;AA6BtB,MAAM,4BAA6C;AAAA,EACxD,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,OAAO;AAAA,EACP,OAAO;AACT;AAEO,SAAS,uBAAuB,QAAoD;AACzF,SAAO,SAAS,EAAE,GAAG,2BAA2B,GAAG,OAAO,IAAI;AAChE;AAsCA,SAAS,QAAQ,OAAuB;AACtC,MAAI,iBAAiB,MAAO,QAAO;AAMnC,SAAO,IAAI,MAAM,OAAO,UAAU,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC;AACpE;AAoBO,SAAS,aAAgB;AAAA,EAC9B;AAAA,EACA;AAAA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,YACT,oBAAC,cAAW,eAAW,MAAC,WAAU,sCAAqC;AAAA,YAExE,UAAU,aACT,oBAAC,WAAQ,eAAW,MAAC,WAAU,+EAA8E;AAAA,YAE9G,UAAU,YACT;AAAA,cAAC;AAAA;AAAA,gBACC,eAAW;AAAA,gBACX,WAAW;AAAA,kBACT;AAAA,kBACA,YAAY,gBAAgB;AAAA,gBAC9B;AAAA;AAAA,YACF;AAAA,YAED,WACC,oBAAC,WAAQ,OAAO,MAAM,QAAM,MAAC,QAAM,MACjC;AAAA,cAAC;AAAA;AAAA,gBACC,MAAK;AAAA,gBACL,SAAS;AAAA,gBACT,cAAY,EAAE;AAAA,gBACd,WAAU;AAAA,gBAEV,8BAAC,eAAY,eAAW,MAAC,WAAU,UAAS;AAAA;AAAA,YAC9C,GACF;AAAA,aAEJ;AAAA,UACA;AAAA,YAAC;AAAA;AAAA,cACC,MAAM,UAAU,UAAU;AAAA,cAC1B,aAAW,UAAU,cAAc;AAAA,cACnC,WAAU;AAAA,cAET,oBAAU,OAAO,KAAK;AAAA;AAAA,UACzB;AAAA;AAAA;AAAA,IACF;AAAA;AAEJ;","names":[]}
@@ -1,5 +1,5 @@
1
1
  import 'react';
2
- export { M as DEFAULT_FILE_PICKER_LABELS, aa as FileButton, ab as FileButtonProps, b8 as FilePickHandler, ad as FilePickerLabels, ae as FileRejection, af as FileRejectionReason, ag as FileScreenOptions, aW as UseFilePickerOptions, aX as UseFilePickerReturn, b9 as formatAccept, ba as judgePick, a_ as matchesAccept, bb as screenFiles, bc as summariseRejections, b1 as useFilePicker } from '../kit-labels-v3biUF1L.js';
2
+ export { M as DEFAULT_FILE_PICKER_LABELS, aa as FileButton, ab as FileButtonProps, ba as FilePickHandler, ad as FilePickerLabels, ae as FileRejection, af as FileRejectionReason, ag as FileScreenOptions, aY as UseFilePickerOptions, aZ as UseFilePickerReturn, bb as formatAccept, bc as judgePick, b0 as matchesAccept, bd as screenFiles, be as summariseRejections, b3 as useFilePicker } from '../kit-labels-Mz8zZHIF.js';
3
3
  import './data-table-labels.js';
4
4
  import './mini-calendar.js';
5
5
  import './calendar-heatmap.js';
@@ -1,6 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { ComponentPropsWithoutRef, ReactNode } from 'react';
3
- import { ae as FileRejection, b8 as FilePickHandler, ad as FilePickerLabels } from '../kit-labels-v3biUF1L.js';
3
+ import { ae as FileRejection, ba as FilePickHandler, ad as FilePickerLabels } from '../kit-labels-Mz8zZHIF.js';
4
4
  import './data-table-labels.js';
5
5
  import './mini-calendar.js';
6
6
  import './calendar-heatmap.js';
@@ -1,5 +1,5 @@
1
1
  import 'react';
2
- export { N as DEFAULT_FORM_ACTIONS_LABELS, aj as FormActions, ak as FormActionsAlign, al as FormActionsDestructive, am as FormActionsLabels, an as FormActionsPlacement, ao as FormActionsProps } from '../kit-labels-v3biUF1L.js';
2
+ export { N as DEFAULT_FORM_ACTIONS_LABELS, aj as FormActions, ak as FormActionsAlign, al as FormActionsDestructive, am as FormActionsLabels, an as FormActionsPlacement, ao as FormActionsProps } from '../kit-labels-Mz8zZHIF.js';
3
3
  import './data-table-labels.js';
4
4
  import './mini-calendar.js';
5
5
  import './calendar-heatmap.js';
@@ -44,6 +44,10 @@ function FullBleedDialog({
44
44
  };
45
45
  if (!open || typeof document === "undefined") return null;
46
46
  return createPortal(
47
+ /* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- the dialog
48
+ container, per the APG dialog pattern: `onKeyDown` is Escape-to-close for whatever
49
+ inside it holds focus, and the mouse handlers are the backdrop press (Escape and the
50
+ close button are its keyboard path). */
47
51
  /* @__PURE__ */ jsx(
48
52
  "div",
49
53
  {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/components/full-bleed-dialog.tsx"],"sourcesContent":["import { useId, useRef } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport type { ComponentPropsWithoutRef, KeyboardEvent, ReactNode } from \"react\";\nimport { X } from \"lucide-react\";\n\nimport { cn } from \"../lib/cn\";\nimport { useBackdropClose } from \"./modal\";\nimport { useBodyScrollLock } from \"../hooks/use-body-scroll-lock\";\nimport { useOverlayHistory } from \"../hooks/use-overlay-history\";\nimport { useCloseTransition } from \"../hooks/use-close-transition\";\nimport { useFocusTrap } from \"../hooks/use-focus-trap\";\n\n/**\n * Named and exported, because `ComponentProps<typeof FullBleedDialog>` was the only way\n * to say \"the props of this\" and five call sites across keksdose and kastlan had already\n * written one (audit §api-design).\n *\n * It extends the `<div>` attributes so a caller can reach the OUTER element — the one\n * carrying `role=\"dialog\"`, and therefore the one an `aria-label`, an\n * `aria-describedby` or a `data-tour` anchor belongs on. {@link className} keeps going\n * to the panel inside it, which is what it has always meant here.\n */\nexport interface FullBleedDialogProps extends Omit<ComponentPropsWithoutRef<\"div\">, \"title\"> {\n open: boolean;\n /** The X, the backdrop (where one shows) and — unless {@link backCloses} is off —\n * the platform Back gesture all call this. */\n onClose: () => void;\n /**\n * The dialog's HEADING: rendered as a real `h2` (see {@link headingAs}) at the start\n * of the header strip, and wired to the dialog's `aria-labelledby`, so the dialog is\n * announced by name rather than as just \"dialog\".\n *\n * Before this the strip was a styled `div`, and a caller that wanted its full-screen\n * phone editor NAMED had to leave this component for `DialogFrame fullBleed` —\n * keksdose's budget-table phone editor says so in a comment at the call site. A\n * caller's own `aria-label` / `aria-labelledby` still wins.\n */\n title?: ReactNode;\n /** The heading level of {@link title}. `h2` by default, as `DialogFrame`'s. */\n headingAs?: \"h1\" | \"h2\" | \"h3\" | \"h4\";\n /**\n * Free content for the header strip, beside the close button — after the\n * {@link title} when there is one, or on its own (the row editor shows the row's\n * own first cell here). It does not name the dialog; `title` does.\n */\n header?: ReactNode;\n closeLabel: string;\n children: ReactNode;\n /**\n * Push a history entry so Back dismisses this dialog instead of navigating\n * (Keksdose feedback #172). On by default, because a full-screen form that ignores\n * the phone's universal \"go back\" gesture does not merely fail to close — the\n * navigation lands somewhere else with the form still notionally open.\n *\n * **Off for a caller whose open state is already in the URL.** The transactions\n * create card is `?action=new`, so Back already pops it through the router; a\n * sentinel on top of that would cost two presses to close one dialog. One owner of\n * the Back press, always.\n */\n backCloses?: boolean;\n /** Extra classes for the PANEL (not the backdrop). */\n className?: string;\n /**\n * A row pinned under the scrolling body — an Apply, a Save. Keksdose's `RangeSheet`\n * (reports/report-range-field.tsx) is a hand-rolled copy of this dialog for want of\n * exactly this slot: a date range picked on a phone is committed by a sticky Apply,\n * and a button at the end of the body scrolls away with the calendar.\n *\n * Outside the scroller, so it stays put without `position: sticky` (which would\n * need the body to be the scroll container of its own child and paint over the\n * last field); padded for the home indicator, since it is the panel's bottom edge.\n */\n footer?: ReactNode;\n}\n\n/**\n * The phone's full-screen dialog: a panel that covers the viewport edge to edge.\n *\n * Not {@link Modal}, and that is a decision rather than an omission. Keksdose feedback\n * #32: the inset panel #204 shipped left a strip of page showing beside it on a phone,\n * and tapping that strip dismissed a form mid-edit. With no backdrop exposed there is\n * nothing to mis-tap, so the X is the way out — `backdropClose` stays wired for any\n * layout that does leave a backdrop visible, and costs nothing where none is.\n *\n * ## Why it is a component\n *\n * It was markup inside `data-table.tsx`, where it is the phone's row EDITOR. Keksdose\n * live #307's follow-up needed the same shell for the transactions CREATE card —\n * *\"Is the creation window of the tx still different than the edit window? Since the tx\n * list still appears below when scrolling down?\"* — and the two answers to that are\n * either one component or two copies that drift. Every previous convergence in that app\n * drifted the moment a second surface was written beside the first, which is what\n * `field-layer-parity` exists to catch one layer down.\n *\n * So the panel, the header strip, the scrolling body, the body-scroll lock and the Back\n * handling are all here, once.\n *\n * ## What the caller still owns\n *\n * The HEADER's content, because the two callers name themselves differently: the row\n * editor shows the row's own first column, the create card a plain title. A plain\n * title belongs in `title`, which is a real heading and the dialog's name; `header`\n * stays the free slot beside it. And `open`,\n * because who decides is the caller's business — see {@link backCloses}.\n */\nexport function FullBleedDialog({\n open,\n onClose,\n title,\n headingAs: Heading = \"h2\",\n header,\n closeLabel,\n children,\n backCloses = true,\n className,\n footer,\n onMouseDown,\n onMouseUp,\n onKeyDown,\n ...rest\n}: FullBleedDialogProps) {\n // Every way OUT goes through `requestClose`, so the panel lowers itself before the\n // caller unmounts it (live #320 rework). `onClose` is still what finally runs — this\n // only delays it by the length of the animation.\n const { closing, requestClose } = useCloseTransition(onClose);\n const backdropClose = useBackdropClose(requestClose);\n // The page behind must not scroll or jump under the overlay (feedback #204).\n useBodyScrollLock(open);\n useOverlayHistory(open && backCloses, requestClose);\n\n const dialogRef = useRef<HTMLDivElement>(null);\n const titleId = useId();\n const hasTitle = title !== undefined && title !== null && title !== false;\n const hasHeader = header !== undefined && header !== null && header !== false;\n // The half of \"modal\" this dialog was only claiming. It has said\n // `aria-modal=\"true\"` since it was extracted from `data-table.tsx`, which tells\n // assistive technology to hide everything outside it — while the user's focus stayed\n // on the row they tapped, in the part that is now hidden. Tab then walked them\n // through a table the screen reader would not describe, and on a phone this dialog\n // covers the whole screen, so there was nothing on screen to say where they were.\n //\n // `initialFocus` is left at the default — the dialog itself, not the first field.\n // This is the phone's row EDITOR and its first child is usually an input; focusing it\n // would pull the software keyboard up over half the form before the user has said\n // which field they came for. `Modal` made the same call for the same reason.\n useFocusTrap(dialogRef, { active: open });\n\n const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n // The caller's handler first (keksdose's transaction-search keeps its list keys on\n // the dialog); a `preventDefault()` IN THAT HANDLER claims the key, Escape included.\n // Only there: a descendant's preventDefault does not count. A SearchField in the\n // header prevents Escape to stop Chromium clearing a type=search input, and in\n // 0.8.0 that silently stopped Escape from closing the dialog (keksdose).\n const preventedBefore = e.defaultPrevented;\n onKeyDown?.(e);\n const claimedByCaller = !preventedBefore && e.defaultPrevented;\n if (claimedByCaller || e.key !== \"Escape\") return;\n // On the panel, the way `Modal` does it, and NOT through `useEscapeKey`: this\n // dialog is the thing a `PickerSheet` opens on top of, and a document-level\n // listener cannot tell which of the two the user meant. One press would dismiss\n // the sheet AND throw away the edit behind it — Keksdose live #309 (*\"Mouse Back\n // does not only close the select but also the whole edit or create dialog\"*) on a\n // different key. The sheet's own handler stops the event here, so the innermost\n // overlay is the one that closes, which is only true because focus is now in it.\n e.stopPropagation();\n requestClose();\n };\n\n if (!open || typeof document === \"undefined\") return null;\n\n return createPortal(\n <div\n // `animate-overlay` on the backdrop and `animate-sheet` on the panel (live #320):\n // the backdrop fades, the panel rises from the bottom edge it is anchored to.\n // Both are no-ops under prefers-reduced-motion — see tokens.css.\n //\n // …and the same two backwards while `closing`, which is the #320 rework. The\n // backdrop keeps taking pointer events on the way out: a tap during those 220ms\n // is a tap on a dialog that is leaving, and letting it through to the row\n // underneath would open a second one.\n //\n // `...rest` first, the dialog's own contract after it. A caller adding a\n // `data-tour` anchor must not be able to take away the role, the modality or the\n // `tabIndex` below by passing one of them too — this is the element the focus\n // trap holds, and each of those failures is invisible on screen.\n {...rest}\n className={cn(\n \"fixed inset-0 z-50 flex items-stretch justify-center bg-black/40 outline-none\",\n closing ? \"animate-overlay-out\" : \"animate-overlay\",\n )}\n role=\"dialog\"\n aria-modal=\"true\"\n // The heading names the dialog unless the caller named it some other way — an\n // `aria-labelledby` of its own, or an `aria-label` (which a `labelledby` would\n // silently outrank).\n aria-labelledby={rest[\"aria-labelledby\"] ?? (hasTitle && !rest[\"aria-label\"] ? titleId : undefined)}\n // `tabIndex={-1}` is what makes the line above more than a claim: without it the\n // container cannot take focus and `useFocusTrap` silently does nothing.\n tabIndex={-1}\n ref={dialogRef}\n onKeyDown={handleKeyDown}\n // COMPOSED with the backdrop's, not overridden by them. These two used to ride\n // `...rest` and then lose to `{...backdropClose}` spread after it, silently —\n // and the one caller about to pass one is keksdose's RangeSheet, whose\n // `onMouseDown={(e) => e.stopPropagation()}` is its dev#477 fix: a press in a\n // portalled sheet must not reach a document-level \"outside click\" listener,\n // which would unmount the day cell before its `click`. The caller's runs first;\n // the backdrop's still runs after it, since it is the same element.\n onMouseDown={(e) => {\n onMouseDown?.(e);\n backdropClose.onMouseDown(e);\n }}\n onMouseUp={(e) => {\n onMouseUp?.(e);\n backdropClose.onMouseUp(e);\n }}\n >\n <div\n className={cn(\n \"flex h-full w-full flex-col overflow-hidden bg-[var(--bg-surface)] shadow-xl\",\n closing ? \"animate-sheet-out\" : \"animate-sheet\",\n className,\n )}\n >\n <div className=\"flex items-center justify-between gap-2 border-b border-[var(--border)] px-3 py-3\">\n {hasTitle ? (\n <div className=\"flex min-w-0 flex-1 items-center gap-2\">\n <Heading id={titleId} className=\"min-w-0 break-words text-base font-semibold leading-snug text-[var(--text-primary)]\">\n {title}\n </Heading>\n {hasHeader && <div className=\"min-w-0 flex-1 font-medium\">{header}</div>}\n </div>\n ) : (\n <div className=\"min-w-0 flex-1 font-medium\">{header}</div>\n )}\n <button\n type=\"button\"\n onClick={requestClose}\n aria-label={closeLabel}\n className=\"-me-1 shrink-0 rounded p-1.5 text-[var(--text-muted)] hover:bg-[var(--bg-hover)] hover:text-[var(--text-secondary)]\"\n >\n <X className=\"size-5\" />\n </button>\n </div>\n {/* px-3, not px-4: every pixel of chrome here is width the form fields lose\n on a phone (feedback #32). The body is the only thing that scrolls, so the\n header stays put and the page underneath cannot move at all. */}\n {/* `min-h-0` so it is the BODY that gives way to a footer, not the footer that\n is pushed off the bottom edge. */}\n <div className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain px-3 py-3\">{children}</div>\n {footer !== undefined && footer !== null && footer !== false && (\n <div\n data-full-bleed-footer=\"\"\n className=\"flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-[var(--border)] px-3 pt-3\"\n style={{ paddingBottom: \"max(0.75rem, env(safe-area-inset-bottom))\" }}\n >\n {footer}\n </div>\n )}\n </div>\n </div>,\n document.body,\n );\n}\n"],"mappings":";AAkOY,SACE,KADF;AAlOZ,SAAS,OAAO,cAAc;AAC9B,SAAS,oBAAoB;AAE7B,SAAS,SAAS;AAElB,SAAS,UAAU;AACnB,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAClC,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC,S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;AAChB,sBAAY,CAAC;AACb,wBAAc,UAAU,CAAC;AAAA,QAC3B;AAAA,QAEA;AAAA,UAAC;AAAA;AAAA,YACC,WAAW;AAAA,cACT;AAAA,cACA,UAAU,sBAAsB;AAAA,cAChC;AAAA,YACF;AAAA,YAEA;AAAA,mCAAC,SAAI,WAAU,qFACZ;AAAA,2BACC,qBAAC,SAAI,WAAU,0CACb;AAAA,sCAAC,WAAQ,IAAI,SAAS,WAAU,uFAC7B,iBACH;AAAA,kBACC,aAAa,oBAAC,SAAI,WAAU,8BAA8B,kBAAO;AAAA,mBACpE,IAEA,oBAAC,SAAI,WAAU,8BAA8B,kBAAO;AAAA,gBAEtD;AAAA,kBAAC;AAAA;AAAA,oBACC,MAAK;AAAA,oBACL,SAAS;AAAA,oBACT,cAAY;AAAA,oBACZ,WAAU;AAAA,oBAEV,8BAAC,KAAE,WAAU,UAAS;AAAA;AAAA,gBACxB;AAAA,iBACF;AAAA,cAMA,oBAAC,SAAI,WAAU,+DAA+D,UAAS;AAAA,cACtF,WAAW,UAAa,WAAW,QAAQ,WAAW,SACrD;AAAA,gBAAC;AAAA;AAAA,kBACC,0BAAuB;AAAA,kBACvB,WAAU;AAAA,kBACV,OAAO,EAAE,eAAe,4CAA4C;AAAA,kBAEnE;AAAA;AAAA,cACH;AAAA;AAAA;AAAA,QAEJ;AAAA;AAAA,IACF;AAAA,IACA,SAAS;AAAA,EACX;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/components/full-bleed-dialog.tsx"],"sourcesContent":["import { useId, useRef } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport type { ComponentPropsWithoutRef, KeyboardEvent, ReactNode } from \"react\";\nimport { X } from \"lucide-react\";\n\nimport { cn } from \"../lib/cn\";\nimport { useBackdropClose } from \"./modal\";\nimport { useBodyScrollLock } from \"../hooks/use-body-scroll-lock\";\nimport { useOverlayHistory } from \"../hooks/use-overlay-history\";\nimport { useCloseTransition } from \"../hooks/use-close-transition\";\nimport { useFocusTrap } from \"../hooks/use-focus-trap\";\n\n/**\n * Named and exported, because `ComponentProps<typeof FullBleedDialog>` was the only way\n * to say \"the props of this\" and five call sites across keksdose and kastlan had already\n * written one (audit §api-design).\n *\n * It extends the `<div>` attributes so a caller can reach the OUTER element — the one\n * carrying `role=\"dialog\"`, and therefore the one an `aria-label`, an\n * `aria-describedby` or a `data-tour` anchor belongs on. {@link className} keeps going\n * to the panel inside it, which is what it has always meant here.\n */\nexport interface FullBleedDialogProps extends Omit<ComponentPropsWithoutRef<\"div\">, \"title\"> {\n open: boolean;\n /** The X, the backdrop (where one shows) and — unless {@link backCloses} is off —\n * the platform Back gesture all call this. */\n onClose: () => void;\n /**\n * The dialog's HEADING: rendered as a real `h2` (see {@link headingAs}) at the start\n * of the header strip, and wired to the dialog's `aria-labelledby`, so the dialog is\n * announced by name rather than as just \"dialog\".\n *\n * Before this the strip was a styled `div`, and a caller that wanted its full-screen\n * phone editor NAMED had to leave this component for `DialogFrame fullBleed` —\n * keksdose's budget-table phone editor says so in a comment at the call site. A\n * caller's own `aria-label` / `aria-labelledby` still wins.\n */\n title?: ReactNode;\n /** The heading level of {@link title}. `h2` by default, as `DialogFrame`'s. */\n headingAs?: \"h1\" | \"h2\" | \"h3\" | \"h4\";\n /**\n * Free content for the header strip, beside the close button — after the\n * {@link title} when there is one, or on its own (the row editor shows the row's\n * own first cell here). It does not name the dialog; `title` does.\n */\n header?: ReactNode;\n closeLabel: string;\n children: ReactNode;\n /**\n * Push a history entry so Back dismisses this dialog instead of navigating\n * (Keksdose feedback #172). On by default, because a full-screen form that ignores\n * the phone's universal \"go back\" gesture does not merely fail to close — the\n * navigation lands somewhere else with the form still notionally open.\n *\n * **Off for a caller whose open state is already in the URL.** The transactions\n * create card is `?action=new`, so Back already pops it through the router; a\n * sentinel on top of that would cost two presses to close one dialog. One owner of\n * the Back press, always.\n */\n backCloses?: boolean;\n /** Extra classes for the PANEL (not the backdrop). */\n className?: string;\n /**\n * A row pinned under the scrolling body — an Apply, a Save. Keksdose's `RangeSheet`\n * (reports/report-range-field.tsx) is a hand-rolled copy of this dialog for want of\n * exactly this slot: a date range picked on a phone is committed by a sticky Apply,\n * and a button at the end of the body scrolls away with the calendar.\n *\n * Outside the scroller, so it stays put without `position: sticky` (which would\n * need the body to be the scroll container of its own child and paint over the\n * last field); padded for the home indicator, since it is the panel's bottom edge.\n */\n footer?: ReactNode;\n}\n\n/**\n * The phone's full-screen dialog: a panel that covers the viewport edge to edge.\n *\n * Not {@link Modal}, and that is a decision rather than an omission. Keksdose feedback\n * #32: the inset panel #204 shipped left a strip of page showing beside it on a phone,\n * and tapping that strip dismissed a form mid-edit. With no backdrop exposed there is\n * nothing to mis-tap, so the X is the way out — `backdropClose` stays wired for any\n * layout that does leave a backdrop visible, and costs nothing where none is.\n *\n * ## Why it is a component\n *\n * It was markup inside `data-table.tsx`, where it is the phone's row EDITOR. Keksdose\n * live #307's follow-up needed the same shell for the transactions CREATE card —\n * *\"Is the creation window of the tx still different than the edit window? Since the tx\n * list still appears below when scrolling down?\"* — and the two answers to that are\n * either one component or two copies that drift. Every previous convergence in that app\n * drifted the moment a second surface was written beside the first, which is what\n * `field-layer-parity` exists to catch one layer down.\n *\n * So the panel, the header strip, the scrolling body, the body-scroll lock and the Back\n * handling are all here, once.\n *\n * ## What the caller still owns\n *\n * The HEADER's content, because the two callers name themselves differently: the row\n * editor shows the row's own first column, the create card a plain title. A plain\n * title belongs in `title`, which is a real heading and the dialog's name; `header`\n * stays the free slot beside it. And `open`,\n * because who decides is the caller's business — see {@link backCloses}.\n */\nexport function FullBleedDialog({\n open,\n onClose,\n title,\n headingAs: Heading = \"h2\",\n header,\n closeLabel,\n children,\n backCloses = true,\n className,\n footer,\n onMouseDown,\n onMouseUp,\n onKeyDown,\n ...rest\n}: FullBleedDialogProps) {\n // Every way OUT goes through `requestClose`, so the panel lowers itself before the\n // caller unmounts it (live #320 rework). `onClose` is still what finally runs — this\n // only delays it by the length of the animation.\n const { closing, requestClose } = useCloseTransition(onClose);\n const backdropClose = useBackdropClose(requestClose);\n // The page behind must not scroll or jump under the overlay (feedback #204).\n useBodyScrollLock(open);\n useOverlayHistory(open && backCloses, requestClose);\n\n const dialogRef = useRef<HTMLDivElement>(null);\n const titleId = useId();\n const hasTitle = title !== undefined && title !== null && title !== false;\n const hasHeader = header !== undefined && header !== null && header !== false;\n // The half of \"modal\" this dialog was only claiming. It has said\n // `aria-modal=\"true\"` since it was extracted from `data-table.tsx`, which tells\n // assistive technology to hide everything outside it — while the user's focus stayed\n // on the row they tapped, in the part that is now hidden. Tab then walked them\n // through a table the screen reader would not describe, and on a phone this dialog\n // covers the whole screen, so there was nothing on screen to say where they were.\n //\n // `initialFocus` is left at the default — the dialog itself, not the first field.\n // This is the phone's row EDITOR and its first child is usually an input; focusing it\n // would pull the software keyboard up over half the form before the user has said\n // which field they came for. `Modal` made the same call for the same reason.\n useFocusTrap(dialogRef, { active: open });\n\n const handleKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {\n // The caller's handler first (keksdose's transaction-search keeps its list keys on\n // the dialog); a `preventDefault()` IN THAT HANDLER claims the key, Escape included.\n // Only there: a descendant's preventDefault does not count. A SearchField in the\n // header prevents Escape to stop Chromium clearing a type=search input, and in\n // 0.8.0 that silently stopped Escape from closing the dialog (keksdose).\n const preventedBefore = e.defaultPrevented;\n onKeyDown?.(e);\n const claimedByCaller = !preventedBefore && e.defaultPrevented;\n if (claimedByCaller || e.key !== \"Escape\") return;\n // On the panel, the way `Modal` does it, and NOT through `useEscapeKey`: this\n // dialog is the thing a `PickerSheet` opens on top of, and a document-level\n // listener cannot tell which of the two the user meant. One press would dismiss\n // the sheet AND throw away the edit behind it — Keksdose live #309 (*\"Mouse Back\n // does not only close the select but also the whole edit or create dialog\"*) on a\n // different key. The sheet's own handler stops the event here, so the innermost\n // overlay is the one that closes, which is only true because focus is now in it.\n e.stopPropagation();\n requestClose();\n };\n\n if (!open || typeof document === \"undefined\") return null;\n\n return createPortal(\n /* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- the dialog\n container, per the APG dialog pattern: `onKeyDown` is Escape-to-close for whatever\n inside it holds focus, and the mouse handlers are the backdrop press (Escape and the\n close button are its keyboard path). */\n <div\n // `animate-overlay` on the backdrop and `animate-sheet` on the panel (live #320):\n // the backdrop fades, the panel rises from the bottom edge it is anchored to.\n // Both are no-ops under prefers-reduced-motion — see tokens.css.\n //\n // …and the same two backwards while `closing`, which is the #320 rework. The\n // backdrop keeps taking pointer events on the way out: a tap during those 220ms\n // is a tap on a dialog that is leaving, and letting it through to the row\n // underneath would open a second one.\n //\n // `...rest` first, the dialog's own contract after it. A caller adding a\n // `data-tour` anchor must not be able to take away the role, the modality or the\n // `tabIndex` below by passing one of them too — this is the element the focus\n // trap holds, and each of those failures is invisible on screen.\n {...rest}\n className={cn(\n \"fixed inset-0 z-50 flex items-stretch justify-center bg-black/40 outline-none\",\n closing ? \"animate-overlay-out\" : \"animate-overlay\",\n )}\n role=\"dialog\"\n aria-modal=\"true\"\n // The heading names the dialog unless the caller named it some other way — an\n // `aria-labelledby` of its own, or an `aria-label` (which a `labelledby` would\n // silently outrank).\n aria-labelledby={rest[\"aria-labelledby\"] ?? (hasTitle && !rest[\"aria-label\"] ? titleId : undefined)}\n // `tabIndex={-1}` is what makes the line above more than a claim: without it the\n // container cannot take focus and `useFocusTrap` silently does nothing.\n tabIndex={-1}\n ref={dialogRef}\n onKeyDown={handleKeyDown}\n // COMPOSED with the backdrop's, not overridden by them. These two used to ride\n // `...rest` and then lose to `{...backdropClose}` spread after it, silently —\n // and the one caller about to pass one is keksdose's RangeSheet, whose\n // `onMouseDown={(e) => e.stopPropagation()}` is its dev#477 fix: a press in a\n // portalled sheet must not reach a document-level \"outside click\" listener,\n // which would unmount the day cell before its `click`. The caller's runs first;\n // the backdrop's still runs after it, since it is the same element.\n onMouseDown={(e) => {\n onMouseDown?.(e);\n backdropClose.onMouseDown(e);\n }}\n onMouseUp={(e) => {\n onMouseUp?.(e);\n backdropClose.onMouseUp(e);\n }}\n >\n <div\n className={cn(\n \"flex h-full w-full flex-col overflow-hidden bg-[var(--bg-surface)] shadow-xl\",\n closing ? \"animate-sheet-out\" : \"animate-sheet\",\n className,\n )}\n >\n <div className=\"flex items-center justify-between gap-2 border-b border-[var(--border)] px-3 py-3\">\n {hasTitle ? (\n <div className=\"flex min-w-0 flex-1 items-center gap-2\">\n <Heading id={titleId} className=\"min-w-0 break-words text-base font-semibold leading-snug text-[var(--text-primary)]\">\n {title}\n </Heading>\n {hasHeader && <div className=\"min-w-0 flex-1 font-medium\">{header}</div>}\n </div>\n ) : (\n <div className=\"min-w-0 flex-1 font-medium\">{header}</div>\n )}\n <button\n type=\"button\"\n onClick={requestClose}\n aria-label={closeLabel}\n className=\"-me-1 shrink-0 rounded p-1.5 text-[var(--text-muted)] hover:bg-[var(--bg-hover)] hover:text-[var(--text-secondary)]\"\n >\n <X className=\"size-5\" />\n </button>\n </div>\n {/* px-3, not px-4: every pixel of chrome here is width the form fields lose\n on a phone (feedback #32). The body is the only thing that scrolls, so the\n header stays put and the page underneath cannot move at all. */}\n {/* `min-h-0` so it is the BODY that gives way to a footer, not the footer that\n is pushed off the bottom edge. */}\n <div className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain px-3 py-3\">{children}</div>\n {footer !== undefined && footer !== null && footer !== false && (\n <div\n data-full-bleed-footer=\"\"\n className=\"flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-[var(--border)] px-3 pt-3\"\n style={{ paddingBottom: \"max(0.75rem, env(safe-area-inset-bottom))\" }}\n >\n {footer}\n </div>\n )}\n </div>\n </div>,\n document.body,\n );\n}\n"],"mappings":";AAsOY,SACE,KADF;AAtOZ,SAAS,OAAO,cAAc;AAC9B,SAAS,oBAAoB;AAE7B,SAAS,SAAS;AAElB,SAAS,UAAU;AACnB,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAClC,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC,SAAS,oB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,WAAW,CAAC,MAAM;AAChB,sBAAY,CAAC;AACb,wBAAc,UAAU,CAAC;AAAA,QAC3B;AAAA,QAEA;AAAA,UAAC;AAAA;AAAA,YACC,WAAW;AAAA,cACT;AAAA,cACA,UAAU,sBAAsB;AAAA,cAChC;AAAA,YACF;AAAA,YAEA;AAAA,mCAAC,SAAI,WAAU,qFACZ;AAAA,2BACC,qBAAC,SAAI,WAAU,0CACb;AAAA,sCAAC,WAAQ,IAAI,SAAS,WAAU,uFAC7B,iBACH;AAAA,kBACC,aAAa,oBAAC,SAAI,WAAU,8BAA8B,kBAAO;AAAA,mBACpE,IAEA,oBAAC,SAAI,WAAU,8BAA8B,kBAAO;AAAA,gBAEtD;AAAA,kBAAC;AAAA;AAAA,oBACC,MAAK;AAAA,oBACL,SAAS;AAAA,oBACT,cAAY;AAAA,oBACZ,WAAU;AAAA,oBAEV,8BAAC,KAAE,WAAU,UAAS;AAAA;AAAA,gBACxB;AAAA,iBACF;AAAA,cAMA,oBAAC,SAAI,WAAU,+DAA+D,UAAS;AAAA,cACtF,WAAW,UAAa,WAAW,QAAQ,WAAW,SACrD;AAAA,gBAAC;AAAA;AAAA,kBACC,0BAAuB;AAAA,kBACvB,WAAU;AAAA,kBACV,OAAO,EAAE,eAAe,4CAA4C;AAAA,kBAEnE;AAAA;AAAA,cACH;AAAA;AAAA;AAAA,QAEJ;AAAA;AAAA,IACF;AAAA,IACA,SAAS;AAAA,EACX;AACF;","names":[]}
@@ -37,19 +37,19 @@ function HoverMenu({
37
37
  const wrapperRef = useRef(null);
38
38
  const [phase, setPhase] = useState("closed");
39
39
  const open = phase === "open" || phase === "closing";
40
- const openedByHoverRef = useRef(false);
40
+ const [openedByHover, setOpenedByHover] = useState(false);
41
41
  const close = useCallback(() => {
42
- openedByHoverRef.current = false;
42
+ setOpenedByHover(false);
43
43
  setPhase("closed");
44
44
  }, []);
45
- const toggle = useCallback(
46
- () => setPhase((p) => {
47
- if (p === "open" || p === "closing") return openedByHoverRef.current ? p : "closed";
48
- openedByHoverRef.current = false;
49
- return "open";
50
- }),
51
- []
52
- );
45
+ const toggle = useCallback(() => {
46
+ if (open) {
47
+ if (!openedByHover) setPhase("closed");
48
+ return;
49
+ }
50
+ setOpenedByHover(false);
51
+ setPhase("open");
52
+ }, [open, openedByHover]);
53
53
  const handleMouseEnter = useCallback(
54
54
  () => setPhase((p) => p === "closing" ? "open" : p === "closed" ? "opening" : p),
55
55
  []
@@ -61,7 +61,7 @@ function HoverMenu({
61
61
  useEffect(() => {
62
62
  if (phase === "opening") {
63
63
  const id = setTimeout(() => {
64
- openedByHoverRef.current = true;
64
+ setOpenedByHover(true);
65
65
  setPhase("open");
66
66
  }, OPEN_DELAY_MS);
67
67
  return () => clearTimeout(id);
@@ -119,7 +119,7 @@ function HoverMenu({
119
119
  (edge === "last" ? list2[list2.length - 1] : list2[0])?.focus();
120
120
  } else {
121
121
  focusOnOpenRef.current = edge;
122
- openedByHoverRef.current = false;
122
+ setOpenedByHover(false);
123
123
  setPhase("open");
124
124
  }
125
125
  }
@@ -143,11 +143,13 @@ function HoverMenu({
143
143
  };
144
144
  const panelRef = useRef(null);
145
145
  const [shiftX, setShiftX] = useState(0);
146
+ const [wasOpen, setWasOpen] = useState(open);
147
+ if (open !== wasOpen) {
148
+ setWasOpen(open);
149
+ if (!open) setShiftX(0);
150
+ }
146
151
  useLayoutEffect(() => {
147
- if (!open) {
148
- setShiftX(0);
149
- return;
150
- }
152
+ if (!open) return;
151
153
  const el = panelRef.current;
152
154
  if (!el) return;
153
155
  const rect = el.getBoundingClientRect();
@@ -160,46 +162,52 @@ function HoverMenu({
160
162
  if (naturalLeft + next < margin) next = margin - naturalLeft;
161
163
  setShiftX(next);
162
164
  }, [open]);
163
- return /* @__PURE__ */ jsxs(
164
- "div",
165
- {
166
- ...rest,
167
- ref: wrapperRef,
168
- className: cn("relative", className),
169
- onMouseEnter: handleMouseEnter,
170
- onMouseLeave: handleMouseLeave,
171
- onKeyDown: (e) => {
172
- rest.onKeyDown?.(e);
173
- onKeyDown(e);
174
- },
175
- children: [
176
- trigger({ open, toggle }),
177
- open && /* @__PURE__ */ jsx(
178
- "div",
179
- {
180
- ref: panelRef,
181
- className: cn(
182
- "absolute top-full z-40 pt-2",
183
- ALIGN_CLASS[align]
184
- ),
185
- style: shiftX ? { transform: `translateX(${shiftX}px)` } : void 0,
186
- children: /* @__PURE__ */ jsx(
187
- "div",
188
- {
189
- ref: menuRef,
190
- role: "menu",
191
- "aria-label": ariaLabelAttr ?? ariaLabel,
192
- className: cn(
193
- "min-w-44 max-w-[calc(100vw-1rem)] rounded-md border border-[var(--border)] bg-[var(--bg-surface)] shadow-lg",
194
- panelClassName
195
- ),
196
- children: children(close)
197
- }
198
- )
199
- }
200
- )
201
- ]
202
- }
165
+ return (
166
+ /* eslint-disable-next-line jsx-a11y/no-static-element-interactions -- never focused
167
+ itself: the mouse handlers are the hover-to-open convenience, and `onKeyDown`
168
+ catches keys bubbling from the caller's trigger button and the menuitems, which
169
+ are the keyboard path (Enter/Space/arrows open, arrows move, Escape closes). */
170
+ /* @__PURE__ */ jsxs(
171
+ "div",
172
+ {
173
+ ...rest,
174
+ ref: wrapperRef,
175
+ className: cn("relative", className),
176
+ onMouseEnter: handleMouseEnter,
177
+ onMouseLeave: handleMouseLeave,
178
+ onKeyDown: (e) => {
179
+ rest.onKeyDown?.(e);
180
+ onKeyDown(e);
181
+ },
182
+ children: [
183
+ trigger({ open, toggle }),
184
+ open && /* @__PURE__ */ jsx(
185
+ "div",
186
+ {
187
+ ref: panelRef,
188
+ className: cn(
189
+ "absolute top-full z-40 pt-2",
190
+ ALIGN_CLASS[align]
191
+ ),
192
+ style: shiftX ? { transform: `translateX(${shiftX}px)` } : void 0,
193
+ children: /* @__PURE__ */ jsx(
194
+ "div",
195
+ {
196
+ ref: menuRef,
197
+ role: "menu",
198
+ "aria-label": ariaLabelAttr ?? ariaLabel,
199
+ className: cn(
200
+ "min-w-44 max-w-[calc(100vw-1rem)] rounded-md border border-[var(--border)] bg-[var(--bg-surface)] shadow-lg",
201
+ panelClassName
202
+ ),
203
+ children: children(close)
204
+ }
205
+ )
206
+ }
207
+ )
208
+ ]
209
+ }
210
+ )
203
211
  );
204
212
  }
205
213
  export {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/components/hover-menu.tsx"],"sourcesContent":["import { useCallback, useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport type { ComponentPropsWithoutRef, KeyboardEvent as ReactKeyboardEvent, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { useEscapeKey, useOutsideClick } from \"../hooks/use-dismiss\";\n\n/**\n * Exported and `<div>`-shaped: the top bar composes several of these side by side, and\n * telling them apart — in a test, in a guided tour, in an accessibility tree — needs an\n * attribute the kit does not know about. A closed prop list dropped every one of them.\n *\n * `children` is omitted from the div attributes because here it is a render prop taking\n * the panel's `close`, not a `ReactNode`.\n */\nexport interface HoverMenuProps extends Omit<ComponentPropsWithoutRef<\"div\">, \"children\"> {\n trigger: (state: { open: boolean; toggle: () => void }) => ReactNode;\n children: (close: () => void) => ReactNode;\n /**\n * Which edge of the trigger the panel lines up with. `start`/`end` follow the\n * reading direction (`end` is the right edge in LTR, the left in RTL); `left`/`right`\n * are physical and kept for existing callers. Default `end` — the same right-aligned\n * panel as before in LTR, mirrored in RTL.\n */\n align?: \"start\" | \"end\" | \"left\" | \"right\";\n panelClassName?: string;\n /** Extra classes for the WRAPPER (the panel has {@link panelClassName}). */\n className?: string;\n /**\n * @deprecated Use the DOM spelling `aria-label`, which names the `role=\"menu\"` panel. Kept working because keksdose, kastlan and lenkbank all pass\n * this today and a rename to save one line of resolution is not a patch release; it\n * loses to `aria-label` wherever both are given. Removal is a later minor.\n */\n ariaLabel?: string;\n}\n\n// Hovering waits briefly before opening so sweeping the cursor across a row of\n// triggers doesn't flash menus; closing waits so the cursor can travel from\n// trigger to panel. Click/keyboard toggling is instant (no \"opening\" phase).\nconst OPEN_DELAY_MS = 120;\nconst CLOSE_DELAY_MS = 120;\n\ntype Phase = \"closed\" | \"opening\" | \"open\" | \"closing\";\n\nconst ALIGN_CLASS = { start: \"start-0\", end: \"end-0\", left: \"left-0\", right: \"right-0\" } as const;\n\n/** Explicit menu-item roles a caller may already have written. */\nconst ITEM_ROLES = '[role=\"menuitem\"],[role=\"menuitemcheckbox\"],[role=\"menuitemradio\"]';\n/** What the panel promotes to `menuitem` when the caller wrote plain controls. */\nconst PLAIN_ITEMS = \"button:not([role]),a[href]:not([role])\";\n/** The trigger: the first focusable in the wrapper that is not inside the panel. */\nconst FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex=\"-1\"])';\n\n/**\n * Give the caller's markup menu semantics.\n *\n * `children` is arbitrary — every caller in the kit renders a `<ul>` of `<li>`s holding\n * `<button>`s and router `<Link>`s — so the panel was a `role=\"menu\"` whose children\n * were a list, list items and plain buttons: no `menuitem` anywhere, which is a menu\n * with nothing in it as far as a screen reader is concerned. Rather than make every\n * caller rewrite its rows, the panel upgrades them after render: controls become\n * `menuitem`s out of the Tab order (the arrow keys move between them), and the list\n * markup in between becomes `role=\"none\"` so the menu owns its items directly. An\n * element that already carries a role is the caller's decision and is left alone.\n */\nfunction applyMenuSemantics(menu: HTMLElement): HTMLElement[] {\n for (const el of menu.querySelectorAll<HTMLElement>(PLAIN_ITEMS)) el.setAttribute(\"role\", \"menuitem\");\n const items = Array.from(menu.querySelectorAll<HTMLElement>(ITEM_ROLES));\n for (const item of items) {\n item.setAttribute(\"tabindex\", \"-1\");\n for (let el = item.parentElement; el && el !== menu; el = el.parentElement) {\n if (!el.hasAttribute(\"role\")) el.setAttribute(\"role\", \"none\");\n }\n }\n for (const el of menu.querySelectorAll<HTMLElement>(\"ul:not([role]),ol:not([role]),li:not([role])\")) {\n el.setAttribute(\"role\", \"none\");\n }\n return items.filter((el) => !el.hasAttribute(\"disabled\") && el.getAttribute(\"aria-disabled\") !== \"true\");\n}\n\n// Only one hover menu may show its panel at a time across the app — opening\n// one closes whichever was open, so adjacent top-bar menus can't overlap\n// (feedback #251). Module-level is fine: there is one cursor per document.\nlet activeClose: (() => void) | null = null;\n\nexport function HoverMenu({\n trigger,\n children,\n align = \"end\",\n panelClassName,\n className,\n ariaLabel,\n \"aria-label\": ariaLabelAttr,\n ...rest\n}: HoverMenuProps) {\n const wrapperRef = useRef<HTMLDivElement>(null);\n const [phase, setPhase] = useState<Phase>(\"closed\");\n const open = phase === \"open\" || phase === \"closing\";\n\n // Whether the panel is open *because hover opened it*, vs. an explicit\n // click/keyboard toggle. A real mouse click on the trigger is always\n // preceded by a real mouseenter — the cursor has to land on the button\n // before it can be clicked — so once hover has opened the panel, the click\n // that inevitably follows is the same physical gesture, not a request to\n // close what was just opened (feedback #19). Toggling closed on click stays\n // for keyboard/touch activation, which reaches \"open\" without going through\n // the hover path.\n const openedByHoverRef = useRef(false);\n\n const close = useCallback(() => {\n openedByHoverRef.current = false;\n setPhase(\"closed\");\n }, []);\n\n const toggle = useCallback(\n () =>\n setPhase((p) => {\n if (p === \"open\" || p === \"closing\") return openedByHoverRef.current ? p : \"closed\";\n openedByHoverRef.current = false;\n return \"open\";\n }),\n [],\n );\n\n const handleMouseEnter = useCallback(\n () => setPhase((p) => (p === \"closing\" ? \"open\" : p === \"closed\" ? \"opening\" : p)),\n [],\n );\n\n const handleMouseLeave = useCallback(\n () => setPhase((p) => (p === \"opening\" ? \"closed\" : p === \"open\" ? \"closing\" : p)),\n [],\n );\n\n // Drive the delayed transitions; unmount/phase changes cancel the timer.\n useEffect(() => {\n if (phase === \"opening\") {\n const id = setTimeout(() => {\n openedByHoverRef.current = true;\n setPhase(\"open\");\n }, OPEN_DELAY_MS);\n return () => clearTimeout(id);\n }\n if (phase === \"closing\") {\n const id = setTimeout(() => setPhase(\"closed\"), CLOSE_DELAY_MS);\n return () => clearTimeout(id);\n }\n }, [phase]);\n\n // Claim the \"active menu\" slot while our panel is visible, closing the\n // previous holder. Cleanup releases the slot only if we still hold it\n // (a successor that displaced us has already overwritten it).\n useEffect(() => {\n if (!open) return;\n if (activeClose !== close) activeClose?.();\n activeClose = close;\n return () => {\n if (activeClose === close) activeClose = null;\n };\n }, [open, close]);\n\n useOutsideClick(wrapperRef, close, open);\n\n const menuRef = useRef<HTMLDivElement>(null);\n /** Set by a keyboard press on the trigger, so the open that follows moves focus into\n * the menu. A hover or a mouse click opens it without taking focus off the page. */\n const focusOnOpenRef = useRef<\"first\" | \"last\" | null>(null);\n\n const triggerEl = () =>\n Array.from(wrapperRef.current?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? []).find(\n (el) => !menuRef.current?.contains(el),\n ) ?? null;\n const items = () => (menuRef.current ? applyMenuSemantics(menuRef.current) : []);\n\n // Escape closes, from anywhere — it did nothing at all before. Focus goes back to the\n // trigger only when it was inside the menu: a panel opened by hover while the user is\n // typing elsewhere must not yank the caret over here on the way out.\n useEscapeKey(() => {\n const hadFocus = wrapperRef.current?.contains(document.activeElement) ?? false;\n close();\n if (hadFocus) triggerEl()?.focus();\n }, open);\n\n // Upgrade the markup every render while open (the caller's rows can change), then\n // honour a pending keyboard open.\n useLayoutEffect(() => {\n if (!open) return;\n const list = items();\n const want = focusOnOpenRef.current;\n focusOnOpenRef.current = null;\n if (want) (want === \"last\" ? list[list.length - 1] : list[0])?.focus();\n });\n\n // Trigger state for assistive technology, on whatever element the caller rendered.\n // Only where the caller has not said something of its own.\n useLayoutEffect(() => {\n const el = triggerEl();\n if (!el) return;\n if (!el.hasAttribute(\"aria-haspopup\")) el.setAttribute(\"aria-haspopup\", \"menu\");\n if (el.getAttribute(\"aria-haspopup\") === \"menu\") el.setAttribute(\"aria-expanded\", String(open));\n });\n\n /** ↑/↓ roving focus with wrap, Home/End, Tab leaves (and closes); on the trigger,\n * Enter/Space/↓ open onto the first item and ↑ onto the last. */\n const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {\n const target = e.target as HTMLElement;\n const inMenu = menuRef.current?.contains(target) ?? false;\n if (!inMenu) {\n if (target !== triggerEl()) return;\n if (e.key === \"Enter\" || e.key === \" \") {\n // The trigger's own click handler does the toggling; this only records that\n // the press came from a keyboard.\n if (!open) focusOnOpenRef.current = \"first\";\n } else if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n e.preventDefault();\n const edge = e.key === \"ArrowDown\" ? \"first\" : \"last\";\n if (open) {\n const list = items();\n (edge === \"last\" ? list[list.length - 1] : list[0])?.focus();\n } else {\n focusOnOpenRef.current = edge;\n openedByHoverRef.current = false;\n setPhase(\"open\");\n }\n }\n return;\n }\n if (e.key === \"Tab\") {\n close();\n return;\n }\n const list = items();\n if (list.length === 0) return;\n const at = list.indexOf(document.activeElement as HTMLElement);\n let next: number | null = null;\n if (e.key === \"ArrowDown\") next = at < 0 ? 0 : (at + 1) % list.length;\n else if (e.key === \"ArrowUp\") next = at < 0 ? list.length - 1 : (at - 1 + list.length) % list.length;\n else if (e.key === \"Home\") next = 0;\n else if (e.key === \"End\") next = list.length - 1;\n if (next === null) return;\n e.preventDefault();\n list[next].focus();\n };\n\n // Keep the panel inside the viewport (feedback #85): a wide panel anchored to a\n // trigger near a screen edge would otherwise spill off it (on mobile the guided-\n // tours menu ran off the left). Once open, measure and translate it horizontally\n // just enough to sit within an 8px margin. Recomputed on each open; `shiftX` is\n // subtracted first so the measurement is against the natural position.\n const panelRef = useRef<HTMLDivElement>(null);\n const [shiftX, setShiftX] = useState(0);\n useLayoutEffect(() => {\n if (!open) {\n setShiftX(0);\n return;\n }\n const el = panelRef.current;\n if (!el) return;\n const rect = el.getBoundingClientRect();\n if (rect.width === 0) return; // unmeasured (e.g. jsdom) — leave as-is\n const margin = 8;\n const naturalLeft = rect.left - shiftX;\n const naturalRight = rect.right - shiftX;\n let next = 0;\n if (naturalRight > window.innerWidth - margin) next = window.innerWidth - margin - naturalRight;\n if (naturalLeft + next < margin) next = margin - naturalLeft;\n setShiftX(next);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- recompute only on open/close\n }, [open]);\n\n return (\n <div\n // `...rest` first: the hover handlers below are the whole component, and a caller\n // passing one of its own must not silently replace them.\n {...rest}\n ref={wrapperRef}\n className={cn(\"relative\", className)}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n onKeyDown={(e) => {\n rest.onKeyDown?.(e);\n onKeyDown(e);\n }}\n >\n {trigger({ open, toggle })}\n {open && (\n <div\n ref={panelRef}\n className={cn(\n \"absolute top-full z-40 pt-2\",\n ALIGN_CLASS[align],\n )}\n style={shiftX ? { transform: `translateX(${shiftX}px)` } : undefined}\n >\n <div\n ref={menuRef}\n role=\"menu\"\n // On the element with the role. It used to sit on the role-less wrapper,\n // where no screen reader reads a name. The DOM spelling wins;\n // {@link HoverMenuProps.ariaLabel} is the deprecated alias three apps still\n // pass, so it stays as the fallback rather than as the answer.\n aria-label={ariaLabelAttr ?? ariaLabel}\n className={cn(\n \"min-w-44 max-w-[calc(100vw-1rem)] rounded-md border border-[var(--border)] bg-[var(--bg-surface)] shadow-lg\",\n panelClassName,\n )}\n >\n {children(close)}\n </div>\n </div>\n )}\n </div>\n );\n}\n"],"mappings":";AA6QI,SAuBM,KAvBN;AA7QJ,SAAS,aAAa,WAAW,iBAAiB,QAAQ,gBAAgB;AAE1E,SAAS,UAAU;AACnB,SAAS,cAAc,uBAAuB;AAkC9C,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AAIvB,MAAM,cAAc,EAAE,OAAO,WAAW,KAAK,SAAS,MAAM,UAAU,OAAO,UAAU;AAGvF,MAAM,aAAa;AAEnB,MAAM,cAAc;AAEpB,MAAM,YAAY;AAclB,SAAS,mBAAmB,MAAkC;AAC5D,aAAW,MAAM,KAAK,iBAA8B,WAAW,EAAG,IAAG,aAAa,QAAQ,UAAU;AACpG,QAAM,QAAQ,MAAM,KAAK,KAAK,iBAA8B,UAAU,CAAC;AACvE,aAAW,QAAQ,OAAO;AACxB,SAAK,aAAa,YAAY,IAAI;AAClC,aAAS,KAAK,KAAK,eAAe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ACjB;AAAA;AAAA,QACF;AAAA;AAAA;AAAA,EAEJ;AAEJ;","names":["list"]}
1
+ {"version":3,"sources":["../../src/components/hover-menu.tsx"],"sourcesContent":["import { useCallback, useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport type { ComponentPropsWithoutRef, KeyboardEvent as ReactKeyboardEvent, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { useEscapeKey, useOutsideClick } from \"../hooks/use-dismiss\";\n\n/**\n * Exported and `<div>`-shaped: the top bar composes several of these side by side, and\n * telling them apart — in a test, in a guided tour, in an accessibility tree — needs an\n * attribute the kit does not know about. A closed prop list dropped every one of them.\n *\n * `children` is omitted from the div attributes because here it is a render prop taking\n * the panel's `close`, not a `ReactNode`.\n */\nexport interface HoverMenuProps extends Omit<ComponentPropsWithoutRef<\"div\">, \"children\"> {\n trigger: (state: { open: boolean; toggle: () => void }) => ReactNode;\n children: (close: () => void) => ReactNode;\n /**\n * Which edge of the trigger the panel lines up with. `start`/`end` follow the\n * reading direction (`end` is the right edge in LTR, the left in RTL); `left`/`right`\n * are physical and kept for existing callers. Default `end` — the same right-aligned\n * panel as before in LTR, mirrored in RTL.\n */\n align?: \"start\" | \"end\" | \"left\" | \"right\";\n panelClassName?: string;\n /** Extra classes for the WRAPPER (the panel has {@link panelClassName}). */\n className?: string;\n /**\n * @deprecated Use the DOM spelling `aria-label`, which names the `role=\"menu\"` panel. Kept working because keksdose, kastlan and lenkbank all pass\n * this today and a rename to save one line of resolution is not a patch release; it\n * loses to `aria-label` wherever both are given. Removal is a later minor.\n */\n ariaLabel?: string;\n}\n\n// Hovering waits briefly before opening so sweeping the cursor across a row of\n// triggers doesn't flash menus; closing waits so the cursor can travel from\n// trigger to panel. Click/keyboard toggling is instant (no \"opening\" phase).\nconst OPEN_DELAY_MS = 120;\nconst CLOSE_DELAY_MS = 120;\n\ntype Phase = \"closed\" | \"opening\" | \"open\" | \"closing\";\n\nconst ALIGN_CLASS = { start: \"start-0\", end: \"end-0\", left: \"left-0\", right: \"right-0\" } as const;\n\n/** Explicit menu-item roles a caller may already have written. */\nconst ITEM_ROLES = '[role=\"menuitem\"],[role=\"menuitemcheckbox\"],[role=\"menuitemradio\"]';\n/** What the panel promotes to `menuitem` when the caller wrote plain controls. */\nconst PLAIN_ITEMS = \"button:not([role]),a[href]:not([role])\";\n/** The trigger: the first focusable in the wrapper that is not inside the panel. */\nconst FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex=\"-1\"])';\n\n/**\n * Give the caller's markup menu semantics.\n *\n * `children` is arbitrary — every caller in the kit renders a `<ul>` of `<li>`s holding\n * `<button>`s and router `<Link>`s — so the panel was a `role=\"menu\"` whose children\n * were a list, list items and plain buttons: no `menuitem` anywhere, which is a menu\n * with nothing in it as far as a screen reader is concerned. Rather than make every\n * caller rewrite its rows, the panel upgrades them after render: controls become\n * `menuitem`s out of the Tab order (the arrow keys move between them), and the list\n * markup in between becomes `role=\"none\"` so the menu owns its items directly. An\n * element that already carries a role is the caller's decision and is left alone.\n */\nfunction applyMenuSemantics(menu: HTMLElement): HTMLElement[] {\n for (const el of menu.querySelectorAll<HTMLElement>(PLAIN_ITEMS)) el.setAttribute(\"role\", \"menuitem\");\n const items = Array.from(menu.querySelectorAll<HTMLElement>(ITEM_ROLES));\n for (const item of items) {\n item.setAttribute(\"tabindex\", \"-1\");\n for (let el = item.parentElement; el && el !== menu; el = el.parentElement) {\n if (!el.hasAttribute(\"role\")) el.setAttribute(\"role\", \"none\");\n }\n }\n for (const el of menu.querySelectorAll<HTMLElement>(\"ul:not([role]),ol:not([role]),li:not([role])\")) {\n el.setAttribute(\"role\", \"none\");\n }\n return items.filter((el) => !el.hasAttribute(\"disabled\") && el.getAttribute(\"aria-disabled\") !== \"true\");\n}\n\n// Only one hover menu may show its panel at a time across the app — opening\n// one closes whichever was open, so adjacent top-bar menus can't overlap\n// (feedback #251). Module-level is fine: there is one cursor per document.\nlet activeClose: (() => void) | null = null;\n\nexport function HoverMenu({\n trigger,\n children,\n align = \"end\",\n panelClassName,\n className,\n ariaLabel,\n \"aria-label\": ariaLabelAttr,\n ...rest\n}: HoverMenuProps) {\n const wrapperRef = useRef<HTMLDivElement>(null);\n const [phase, setPhase] = useState<Phase>(\"closed\");\n const open = phase === \"open\" || phase === \"closing\";\n\n // Whether the panel is open *because hover opened it*, vs. an explicit\n // click/keyboard toggle. A real mouse click on the trigger is always\n // preceded by a real mouseenter — the cursor has to land on the button\n // before it can be clicked — so once hover has opened the panel, the click\n // that inevitably follows is the same physical gesture, not a request to\n // close what was just opened (feedback #19). Toggling closed on click stays\n // for keyboard/touch activation, which reaches \"open\" without going through\n // the hover path.\n //\n // State rather than a ref: `close` is handed to the caller's render prop, and a\n // function that writes a ref must not be reachable from render.\n const [openedByHover, setOpenedByHover] = useState(false);\n\n const close = useCallback(() => {\n setOpenedByHover(false);\n setPhase(\"closed\");\n }, []);\n\n const toggle = useCallback(() => {\n if (open) {\n if (!openedByHover) setPhase(\"closed\");\n return;\n }\n setOpenedByHover(false);\n setPhase(\"open\");\n }, [open, openedByHover]);\n\n const handleMouseEnter = useCallback(\n () => setPhase((p) => (p === \"closing\" ? \"open\" : p === \"closed\" ? \"opening\" : p)),\n [],\n );\n\n const handleMouseLeave = useCallback(\n () => setPhase((p) => (p === \"opening\" ? \"closed\" : p === \"open\" ? \"closing\" : p)),\n [],\n );\n\n // Drive the delayed transitions; unmount/phase changes cancel the timer.\n useEffect(() => {\n if (phase === \"opening\") {\n const id = setTimeout(() => {\n setOpenedByHover(true);\n setPhase(\"open\");\n }, OPEN_DELAY_MS);\n return () => clearTimeout(id);\n }\n if (phase === \"closing\") {\n const id = setTimeout(() => setPhase(\"closed\"), CLOSE_DELAY_MS);\n return () => clearTimeout(id);\n }\n }, [phase]);\n\n // Claim the \"active menu\" slot while our panel is visible, closing the\n // previous holder. Cleanup releases the slot only if we still hold it\n // (a successor that displaced us has already overwritten it).\n useEffect(() => {\n if (!open) return;\n if (activeClose !== close) activeClose?.();\n activeClose = close;\n return () => {\n if (activeClose === close) activeClose = null;\n };\n }, [open, close]);\n\n useOutsideClick(wrapperRef, close, open);\n\n const menuRef = useRef<HTMLDivElement>(null);\n /** Set by a keyboard press on the trigger, so the open that follows moves focus into\n * the menu. A hover or a mouse click opens it without taking focus off the page. */\n const focusOnOpenRef = useRef<\"first\" | \"last\" | null>(null);\n\n const triggerEl = () =>\n Array.from(wrapperRef.current?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? []).find(\n (el) => !menuRef.current?.contains(el),\n ) ?? null;\n const items = () => (menuRef.current ? applyMenuSemantics(menuRef.current) : []);\n\n // Escape closes, from anywhere — it did nothing at all before. Focus goes back to the\n // trigger only when it was inside the menu: a panel opened by hover while the user is\n // typing elsewhere must not yank the caret over here on the way out.\n useEscapeKey(() => {\n const hadFocus = wrapperRef.current?.contains(document.activeElement) ?? false;\n close();\n if (hadFocus) triggerEl()?.focus();\n }, open);\n\n // Upgrade the markup every render while open (the caller's rows can change), then\n // honour a pending keyboard open.\n useLayoutEffect(() => {\n if (!open) return;\n const list = items();\n const want = focusOnOpenRef.current;\n focusOnOpenRef.current = null;\n if (want) (want === \"last\" ? list[list.length - 1] : list[0])?.focus();\n });\n\n // Trigger state for assistive technology, on whatever element the caller rendered.\n // Only where the caller has not said something of its own.\n useLayoutEffect(() => {\n const el = triggerEl();\n if (!el) return;\n if (!el.hasAttribute(\"aria-haspopup\")) el.setAttribute(\"aria-haspopup\", \"menu\");\n if (el.getAttribute(\"aria-haspopup\") === \"menu\") el.setAttribute(\"aria-expanded\", String(open));\n });\n\n /** ↑/↓ roving focus with wrap, Home/End, Tab leaves (and closes); on the trigger,\n * Enter/Space/↓ open onto the first item and ↑ onto the last. */\n const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {\n const target = e.target as HTMLElement;\n const inMenu = menuRef.current?.contains(target) ?? false;\n if (!inMenu) {\n if (target !== triggerEl()) return;\n if (e.key === \"Enter\" || e.key === \" \") {\n // The trigger's own click handler does the toggling; this only records that\n // the press came from a keyboard.\n if (!open) focusOnOpenRef.current = \"first\";\n } else if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n e.preventDefault();\n const edge = e.key === \"ArrowDown\" ? \"first\" : \"last\";\n if (open) {\n const list = items();\n (edge === \"last\" ? list[list.length - 1] : list[0])?.focus();\n } else {\n focusOnOpenRef.current = edge;\n setOpenedByHover(false);\n setPhase(\"open\");\n }\n }\n return;\n }\n if (e.key === \"Tab\") {\n close();\n return;\n }\n const list = items();\n if (list.length === 0) return;\n const at = list.indexOf(document.activeElement as HTMLElement);\n let next: number | null = null;\n if (e.key === \"ArrowDown\") next = at < 0 ? 0 : (at + 1) % list.length;\n else if (e.key === \"ArrowUp\") next = at < 0 ? list.length - 1 : (at - 1 + list.length) % list.length;\n else if (e.key === \"Home\") next = 0;\n else if (e.key === \"End\") next = list.length - 1;\n if (next === null) return;\n e.preventDefault();\n list[next].focus();\n };\n\n // Keep the panel inside the viewport (feedback #85): a wide panel anchored to a\n // trigger near a screen edge would otherwise spill off it (on mobile the guided-\n // tours menu ran off the left). Once open, measure and translate it horizontally\n // just enough to sit within an 8px margin. Recomputed on each open; `shiftX` is\n // subtracted first so the measurement is against the natural position.\n const panelRef = useRef<HTMLDivElement>(null);\n const [shiftX, setShiftX] = useState(0);\n // Back to 0 on close, adjusted while rendering against the previous `open`.\n const [wasOpen, setWasOpen] = useState(open);\n if (open !== wasOpen) {\n setWasOpen(open);\n if (!open) setShiftX(0);\n }\n useLayoutEffect(() => {\n if (!open) return;\n const el = panelRef.current;\n if (!el) return;\n const rect = el.getBoundingClientRect();\n if (rect.width === 0) return; // unmeasured (e.g. jsdom) — leave as-is\n const margin = 8;\n const naturalLeft = rect.left - shiftX;\n const naturalRight = rect.right - shiftX;\n let next = 0;\n if (naturalRight > window.innerWidth - margin) next = window.innerWidth - margin - naturalRight;\n if (naturalLeft + next < margin) next = margin - naturalLeft;\n setShiftX(next);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- recompute only on open/close\n }, [open]);\n\n return (\n /* eslint-disable-next-line jsx-a11y/no-static-element-interactions -- never focused\n itself: the mouse handlers are the hover-to-open convenience, and `onKeyDown`\n catches keys bubbling from the caller's trigger button and the menuitems, which\n are the keyboard path (Enter/Space/arrows open, arrows move, Escape closes). */\n <div\n // `...rest` first: the hover handlers below are the whole component, and a caller\n // passing one of its own must not silently replace them.\n {...rest}\n ref={wrapperRef}\n className={cn(\"relative\", className)}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n onKeyDown={(e) => {\n rest.onKeyDown?.(e);\n onKeyDown(e);\n }}\n >\n {trigger({ open, toggle })}\n {open && (\n <div\n ref={panelRef}\n className={cn(\n \"absolute top-full z-40 pt-2\",\n ALIGN_CLASS[align],\n )}\n style={shiftX ? { transform: `translateX(${shiftX}px)` } : undefined}\n >\n <div\n ref={menuRef}\n role=\"menu\"\n // On the element with the role. It used to sit on the role-less wrapper,\n // where no screen reader reads a name. The DOM spelling wins;\n // {@link HoverMenuProps.ariaLabel} is the deprecated alias three apps still\n // pass, so it stays as the fallback rather than as the answer.\n aria-label={ariaLabelAttr ?? ariaLabel}\n className={cn(\n \"min-w-44 max-w-[calc(100vw-1rem)] rounded-md border border-[var(--border)] bg-[var(--bg-surface)] shadow-lg\",\n panelClassName,\n )}\n >\n {children(close)}\n </div>\n </div>\n )}\n </div>\n );\n}\n"],"mappings":";AAsRI,SAuBM,KAvBN;AAtRJ,SAAS,aAAa,WAAW,iBAAiB,QAAQ,gBAAgB;AAE1E,SAAS,UAAU;AACnB,SAAS,cAAc,uBAAuB;AAkC9C,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AAIvB,MAAM,cAAc,EAAE,OAAO,WAAW,KAAK,SAAS,MAAM,UAAU,OAAO,UAAU;AAGvF,MAAM,aAAa;AAEnB,MAAM,cAAc;AAEpB,MAAM,YAAY;AAclB,SAAS,mBAAmB,MAAkC;AAC5D,aAAW,MAA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AAAA;AAAA,cACC,KAAK;AAAA,cACL,WAAW;AAAA,gBACT;AAAA,gBACA,YAAY,KAAK;AAAA,cACnB;AAAA,cACA,OAAO,SAAS,EAAE,WAAW,cAAc,MAAM,MAAM,IAAI;AAAA,cAE3D;AAAA,gBAAC;AAAA;AAAA,kBACC,KAAK;AAAA,kBACL,MAAK;AAAA,kBAKL,cAAY,iBAAiB;AAAA,kBAC7B,WAAW;AAAA,oBACT;AAAA,oBACA;AAAA,kBACF;AAAA,kBAEC,mBAAS,KAAK;AAAA;AAAA,cACjB;AAAA;AAAA,UACF;AAAA;AAAA;AAAA,IAEJ;AAAA;AAEJ;","names":["list"]}
@@ -50,8 +50,20 @@ interface ListItemLinkProps {
50
50
  [key: `data-${string}`]: unknown;
51
51
  }
52
52
  interface ListItemBaseProps {
53
- /** The row's name: one line, truncated. */
53
+ /** The row's name: one line, truncated — unless {@link titleLines} says otherwise. */
54
54
  title: ReactNode;
55
+ /**
56
+ * How many lines the title may take. `1` (default) truncates with an ellipsis, which
57
+ * is right for a name the app chose — a unit number, a user, a file — where the
58
+ * cut-off end is still recognisable and every row keeps one height.
59
+ *
60
+ * `2` clamps at two lines; `"all"` shows every line, breaking inside a long word
61
+ * rather than overflowing. For rows whose only name is free text a person typed
62
+ * (kastlan 44): a defect or a note titled by its description, where the first 30
63
+ * characters on a phone say nothing and there is no other field to tell two rows
64
+ * apart. Pair it with `align="start"` so the icon stays by the first line.
65
+ */
66
+ titleLines?: 1 | 2 | "all";
55
67
  /** The line under it: one line, truncated — or two, with `subtitleLines={2}`. */
56
68
  subtitle?: ReactNode;
57
69
  /** `2` for a line that is a body rather than a label (keksdose's notification text). */
@@ -193,7 +205,7 @@ type ListItemProps = ListItemBaseProps & ({
193
205
  });
194
206
  /**
195
207
  * One row of a {@link List}: leading icon or avatar, title and subtitle (both
196
- * truncating), a trailing slot, and — beside the row, not inside it — its actions.
208
+ * truncating by default), a trailing slot, and — beside the row, not inside it — its actions.
197
209
  *
198
210
  * All three apps draw this row by hand, a dozen times: kastlan's units
199
211
  * (building-detail-page.tsx:402), open tickets (group-overview-page.tsx:160), activity
@@ -40,6 +40,7 @@ const PAD = {
40
40
  const TARGET_RING = "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--brand)]";
41
41
  const ListItem = forwardRef(function ListItem2({
42
42
  title,
43
+ titleLines = 1,
43
44
  subtitle,
44
45
  subtitleLines = 1,
45
46
  meta,
@@ -95,7 +96,8 @@ const ListItem = forwardRef(function ListItem2({
95
96
  {
96
97
  id: hasBody ? titleId : void 0,
97
98
  className: cn(
98
- "block truncate text-sm text-[var(--text-primary)]",
99
+ "block text-sm text-[var(--text-primary)]",
100
+ titleLines === 1 ? "truncate" : titleLines === 2 ? "line-clamp-2 break-words" : "break-words",
99
101
  unread ? "font-semibold" : "font-medium"
100
102
  ),
101
103
  children: [