@eifi1/ui-kit 0.13.0 → 0.14.0

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 (54) hide show
  1. package/README.md +5 -5
  2. package/dist/components/amount-input.d.ts +6 -0
  3. package/dist/components/amount-input.js +35 -5
  4. package/dist/components/amount-input.js.map +1 -1
  5. package/dist/components/error-boundary.d.ts +8 -1
  6. package/dist/components/error-boundary.js +18 -2
  7. package/dist/components/error-boundary.js.map +1 -1
  8. package/dist/components/numpad-sheet.d.ts +7 -3
  9. package/dist/components/numpad-sheet.js +4 -3
  10. package/dist/components/numpad-sheet.js.map +1 -1
  11. package/dist/components/page-header.d.ts +55 -2
  12. package/dist/components/page-header.js +34 -3
  13. package/dist/components/page-header.js.map +1 -1
  14. package/dist/components/text.js.map +1 -1
  15. package/dist/components/tooltip.d.ts +31 -0
  16. package/dist/components/tooltip.js +33 -0
  17. package/dist/components/tooltip.js.map +1 -1
  18. package/dist/feedback/feedback-thread.d.ts +87 -6
  19. package/dist/feedback/feedback-thread.js +134 -58
  20. package/dist/feedback/feedback-thread.js.map +1 -1
  21. package/dist/feedback.d.ts +1 -1
  22. package/dist/i18n/locales/de.js +3 -1
  23. package/dist/i18n/locales/de.js.map +1 -1
  24. package/dist/i18n/locales/es.js +2 -1
  25. package/dist/i18n/locales/es.js.map +1 -1
  26. package/dist/i18n/locales/fr.js +2 -1
  27. package/dist/i18n/locales/fr.js.map +1 -1
  28. package/dist/i18n/locales/hu.js +2 -1
  29. package/dist/i18n/locales/hu.js.map +1 -1
  30. package/dist/i18n/locales/it.js +2 -1
  31. package/dist/i18n/locales/it.js.map +1 -1
  32. package/dist/i18n/locales/zh.js +2 -1
  33. package/dist/i18n/locales/zh.js.map +1 -1
  34. package/dist/index.d.ts +2 -2
  35. package/dist/lib/format.js +1 -1
  36. package/dist/lib/format.js.map +1 -1
  37. package/dist/rhf/fields.d.ts +3 -1
  38. package/dist/rhf/fields.js.map +1 -1
  39. package/package.json +1 -1
  40. package/src/components/amount-input.tsx +73 -7
  41. package/src/components/error-boundary.tsx +33 -3
  42. package/src/components/numpad-sheet.tsx +13 -4
  43. package/src/components/page-header.tsx +98 -3
  44. package/src/components/text.tsx +2 -1
  45. package/src/components/tooltip.tsx +109 -2
  46. package/src/feedback/feedback-thread.tsx +229 -37
  47. package/src/i18n/locales/de.ts +2 -0
  48. package/src/i18n/locales/es.ts +1 -0
  49. package/src/i18n/locales/fr.ts +1 -0
  50. package/src/i18n/locales/hu.ts +1 -0
  51. package/src/i18n/locales/it.ts +1 -0
  52. package/src/i18n/locales/zh.ts +1 -0
  53. package/src/lib/format.ts +3 -1
  54. package/src/rhf/fields.tsx +3 -1
package/README.md CHANGED
@@ -377,20 +377,20 @@ columns, strings and permissions (see the note at the top of `src/feedback/feedb
377
377
 
378
378
  <!-- BEGIN GENERATED: exports — node scripts/gen-export-inventory.mjs -->
379
379
 
380
- **1002 names from 159 modules** — 474 values and 528 types. _Italic_ is a type-only export.
380
+ **1005 names from 159 modules** — 474 values and 531 types. _Italic_ is a type-only export.
381
381
 
382
382
  Generated from `dist/index.d.ts` by `node scripts/gen-export-inventory.mjs`; the count
383
383
  is pinned by `src/__tests__/public-surface.test.ts`. Do not edit between the markers.
384
384
 
385
385
  | Entry point | Names |
386
386
  |---|---|
387
- | `@eifi1/ui-kit` | 1002 |
387
+ | `@eifi1/ui-kit` | 1005 |
388
388
  | `@eifi1/ui-kit/chart` | 100 |
389
389
  | `@eifi1/ui-kit/shell` | 24 |
390
390
  | `@eifi1/ui-kit/data-table` | 49 |
391
391
  | `@eifi1/ui-kit/wizard` | 25 |
392
392
  | `@eifi1/ui-kit/tour` | 7 |
393
- | `@eifi1/ui-kit/feedback` | 43 |
393
+ | `@eifi1/ui-kit/feedback` | 45 |
394
394
  | `@eifi1/ui-kit/search` | 22 |
395
395
  | `@eifi1/ui-kit/dates` | 22 |
396
396
  | `@eifi1/ui-kit/table-text` | 8 |
@@ -544,7 +544,7 @@ re-slicing of it, never a second API.
544
544
  | `components/menu-item` | `MenuItem`, _`MenuItemLinkProps`_, _`MenuItemProps`_, _`MenuItemTone`_ |
545
545
  | `components/text` | `Caption`, `CAPTION_CLASS`, `SECTION_LABEL_CLASS`, `SectionLabel`, _`CaptionProps`_, _`SectionLabelProps`_, _`SectionLabelSize`_, _`SectionLabelVariant`_ |
546
546
  | `components/status-dot` | `StatusDot`, _`StatusDotProps`_, _`StatusDotSize`_, _`StatusDotTone`_ |
547
- | `components/page-header` | `PageHeader`, _`PageHeaderMobileLayout`_, _`PageHeaderProps`_, _`PageHeaderSize`_ |
547
+ | `components/page-header` | `PageHeader`, _`PageHeaderActionsAlign`_, _`PageHeaderMobileLayout`_, _`PageHeaderProps`_, _`PageHeaderSize`_ |
548
548
  | `components/breadcrumbs` | `Breadcrumbs`, `DEFAULT_BREADCRUMBS_LABELS`, _`BreadcrumbItem`_, _`BreadcrumbLinkProps`_, _`BreadcrumbsLabels`_, _`BreadcrumbsProps`_ |
549
549
  | `components/text-link` | `TextLink`, _`TextLinkCurrent`_, _`TextLinkProps`_, _`TextLinkRenderProps`_, _`TextLinkTone`_, _`TextLinkUnderline`_ |
550
550
  | `components/toast` | `DEFAULT_TOAST_LABELS`, `toast`, `TOAST_ACTION_DURATION`, `Toaster`, _`ToastAction`_, _`ToasterOffset`_, _`ToasterProps`_, _`ToastId`_, _`ToastLabels`_, _`ToastOptions`_, _`ToastPosition`_, _`ToastPromiseOptions`_, _`ToastRedoOptions`_, _`ToastSwipeDirection`_, _`ToastUndoOptions`_ |
@@ -580,7 +580,7 @@ re-slicing of it, never a second API.
580
580
  | `feedback/feedback-attachment` | `DEFAULT_ATTACHMENT_ACCEPT`, `DEFAULT_FEEDBACK_ATTACHMENT_LABELS`, `DEFAULT_MAX_ATTACHMENT_BYTES`, `FeedbackAttachmentField`, `pastedName`, _`FeedbackAttachmentFieldLabels`_ |
581
581
  | `feedback/feedback-dialog` | `DEFAULT_FEEDBACK_DIALOG_LABELS`, `FeedbackDialog`, _`FeedbackAttachmentLabels`_, _`FeedbackCategoryOption`_, _`FeedbackDialogLabels`_, _`FeedbackDialogTextLabels`_, _`FeedbackSubmission`_ |
582
582
  | `feedback/feedback-inbox` | `FEEDBACK_CATEGORY_META`, `FEEDBACK_CATEGORY_ORDER`, `FEEDBACK_STATUS_META`, `FEEDBACK_STATUS_ORDER`, `FeedbackCategoryBadge`, `feedbackCategoryRank`, `FeedbackDetail`, `FeedbackDetailSection`, `FeedbackNoteEditor`, `FeedbackProse`, `FeedbackStatusBadge`, `FeedbackStatusTransitions`, `nextFeedbackStatus`, `selectableFeedbackStatuses`, `visibleFeedbackStatuses`, _`FeedbackCategory`_, _`FeedbackNoteAttachment`_, _`FeedbackStatus`_ |
583
- | `feedback/feedback-thread` | `DEFAULT_FEEDBACK_COMPOSER_LABELS`, `DEFAULT_FEEDBACK_THREAD_LABELS`, `FeedbackComposer`, `FeedbackThread`, _`FeedbackComposerAttachment`_, _`FeedbackComposerHandle`_, _`FeedbackComposerLabels`_, _`FeedbackComposerProps`_, _`FeedbackThreadAttachment`_, _`FeedbackThreadLabels`_, _`FeedbackThreadMessage`_, _`FeedbackThreadProps`_ |
583
+ | `feedback/feedback-thread` | `DEFAULT_FEEDBACK_COMPOSER_LABELS`, `DEFAULT_FEEDBACK_THREAD_LABELS`, `FeedbackComposer`, `FeedbackThread`, _`FeedbackComposerAttachment`_, _`FeedbackComposerHandle`_, _`FeedbackComposerLabels`_, _`FeedbackComposerProps`_, _`FeedbackThreadAttachment`_, _`FeedbackThreadEvent`_, _`FeedbackThreadItem`_, _`FeedbackThreadLabels`_, _`FeedbackThreadMessage`_, _`FeedbackThreadProps`_ |
584
584
 
585
585
  ### wizard
586
586
 
@@ -188,6 +188,12 @@ interface AmountInputProps {
188
188
  * zero (12.345 → 12.35, -12.345 → -12.35) and happens when the figure settles: on
189
189
  * blur, on Enter, and on every result the calculator writes back. Keystrokes are left
190
190
  * alone, so "12.3" can still become "12.34".
191
+ *
192
+ * ⚠️ **A unit price or a rate needs `digits`.** The default is right for an amount of
193
+ * money and silently wrong for a price per unit: a fund's NAV of 123.4567 or fuel at
194
+ * 1.789 €/l is stored as 123.46 / 1.79, and no test fails (keksdose G2, a
195
+ * `Numeric(18,6)` holding price and a `Numeric(18,4)` unit price). Pass the column's
196
+ * scale: `digits={4}`, `digits={6}`.
191
197
  */
192
198
  digits?: number;
193
199
  /** The smallest amount the field settles on. A lower figure is raised to it when it
@@ -54,6 +54,16 @@ function decimalMark(locale) {
54
54
  return ".";
55
55
  }
56
56
  }
57
+ function normalizeTypedMarks(raw, mark) {
58
+ const other = mark === "," ? "." : ",";
59
+ return raw.replace(/[0-9.,]+/g, (operand) => {
60
+ const hasMark = operand.includes(mark);
61
+ const count = operand.split(other).length - 1;
62
+ if (count === 0) return operand;
63
+ const grouping = hasMark ? true : count > 1 || mark === "," && /^\d{1,3}(\.\d{3})+$/.test(operand);
64
+ return grouping ? operand.split(other).join("") : operand;
65
+ });
66
+ }
57
67
  const TONE_CLASS = {
58
68
  neutral: "",
59
69
  outflow: "text-money-neg",
@@ -91,7 +101,13 @@ const AmountInput = forwardRef(
91
101
  const shown = signOwned && negative && isBareAmount(value) ? `-${value}` : value;
92
102
  const locale = useKitLocale();
93
103
  const mark = decimalMark(locale);
94
- const display = mark === "," ? shown.replace(/\./g, ",") : shown;
104
+ const [draft, setDraft] = useState(null);
105
+ const derived = mark === "," ? shown.replace(/\./g, ",") : shown;
106
+ const draftAs = draft === null ? "" : sanitizeLive(normalizeTypedMarks(draft, mark));
107
+ const display = draft === null ? derived : draftAs === shown ? draft : (
108
+ // The caller owns the sign: the typed "12" is shown as the "-12" it is.
109
+ signOwned && negative && `-${draftAs}` === shown ? `-${draft}` : derived
110
+ );
95
111
  const digits = digitsProp ?? currencyDigits(currency);
96
112
  const settle = (text) => settleAmount(text, digits, min, max);
97
113
  const handleText = (raw, previous = shown) => {
@@ -108,7 +124,14 @@ const AmountInput = forwardRef(
108
124
  }
109
125
  onChange(sign ? rest : text);
110
126
  };
111
- const commit = () => handleText(settle(commitExpression(shown)));
127
+ const commit = () => {
128
+ setDraft(null);
129
+ handleText(settle(commitExpression(shown)));
130
+ };
131
+ const typed = (raw) => {
132
+ setDraft(raw);
133
+ handleText(normalizeTypedMarks(raw, mark));
134
+ };
112
135
  const { open, setOpen, wrapperRef, panelRef, query, setQuery, inputRef } = useDropdownSearch();
113
136
  const chipRef = useRef(null);
114
137
  const currencyOverrides = useMemo(() => {
@@ -144,7 +167,7 @@ const AmountInput = forwardRef(
144
167
  disabled,
145
168
  placeholder: asDisplay ? placeholder ?? "0" : label !== void 0 ? " " : placeholder,
146
169
  value: display,
147
- onChange: (e) => handleText(e.target.value),
170
+ onChange: (e) => typed(e.target.value),
148
171
  onFocus: () => setFocused(true),
149
172
  onBlur: () => {
150
173
  commit();
@@ -201,7 +224,10 @@ const AmountInput = forwardRef(
201
224
  CalculatorButton,
202
225
  {
203
226
  value: display,
204
- onChange: (result, expression) => handleText(settle(result), expression),
227
+ onChange: (result, expression) => {
228
+ setDraft(null);
229
+ handleText(settle(result), expression);
230
+ },
205
231
  className: "px-1.5",
206
232
  ariaLabel: labels?.calculatorTrigger,
207
233
  labels: labels?.calculator
@@ -288,7 +314,11 @@ const AmountInput = forwardRef(
288
314
  NumberPadSheet,
289
315
  {
290
316
  value: display,
291
- onChange: handleText,
317
+ onChange: typed,
318
+ onResult: (result) => {
319
+ setDraft(null);
320
+ handleText(result);
321
+ },
292
322
  onDone: () => innerRef.current?.blur(),
293
323
  label,
294
324
  labels: labels?.pad,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/components/amount-input.tsx"],"sourcesContent":["import { forwardRef, useCallback, useId, useMemo, useRef, useState } from \"react\";\nimport { ChevronDown } from \"lucide-react\";\nimport type { ReactNode } from \"react\";\nimport { CURRENCIES, CurrencyFlag, currencyName, getCurrency } from \"./currency-select\";\nimport { FIELD_BASE, FIELD_DISPLAY, FIELD_INVALID, FLOATING_INPUT_CLASS, FLOATING_LABEL_CLASS, PHONE_QUERY } from \"./ui\";\nimport { cn } from \"../lib/cn\";\nimport { useMediaQuery } from \"../hooks/use-media-query\";\nimport { CalculatorButton, type CalculatorButtonLabels } from \"./calculator\";\nimport { NumberPadSheet, type NumberPadSheetLabels } from \"./numpad-sheet\";\nimport { DropdownPanel, DropdownSearchHeader, useDropdownSearch } from \"./dropdown\";\nimport {\n DEFAULT_COMMON_LABELS,\n DEFAULT_CURRENCY_LABELS,\n useKitLabels,\n useKitLocale,\n type CurrencyLabels,\n} from \"../i18n/kit-labels\";\nimport {\n commitExpression,\n evaluateExpression,\n formatResult,\n isBareAmount,\n looksLikeExpression,\n sanitizeLive,\n splitLeadingSign,\n} from \"../lib/calc\";\n\ninterface AmountInputProps {\n value: string;\n onChange: (value: string) => void;\n currency?: string;\n onCurrencyChange?: (code: string) => void;\n placeholder?: string;\n label?: ReactNode;\n disabled?: boolean;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\n className?: string;\n id?: string;\n ariaLabel?: string;\n /**\n * Set on the `<input>`, with `id` above. Declared so `Field`'s render-prop spread —\n * `{(ids) => <AmountInput {...ids} … />}` — is typed and reaches the input: the\n * hint and error are described, a required amount is announced as required, and\n * `aria-invalid` paints {@link FIELD_INVALID} the way `invalid` does.\n */\n \"aria-describedby\"?: string;\n \"aria-invalid\"?: boolean | \"true\" | \"false\";\n \"aria-required\"?: boolean | \"true\" | \"false\";\n /** Every user-facing string this component and the two it composes own, so a\n * translating host can supply its own. Each key optional, and each a per-field\n * override of the kit-wide translation in `<UiKitProvider labels>`: `currency`\n * and `currencySearch` of its `currency` namespace, the rest of `calculator`.\n * `currency` names the picker chip, composed with the selected code through\n * `common.fieldValue`; the rest are pass-through. */\n labels?: {\n currency?: string;\n currencySearch?: string;\n /** Names the calculator TRIGGER this component renders. `calculator` below\n * names the controls inside the popover it opens. */\n calculatorTrigger?: string;\n pad?: NumberPadSheetLabels;\n calculator?: CalculatorButtonLabels;\n };\n /** Translated currency names for the chip's picker, keyed by ISO code. The same\n * sparse override `CurrencySelect` takes, and for the same reason: the names in\n * `CURRENCIES` are shipped data, so without this they are the one English word\n * left in a translated row. Not part of `labels` because it is keyed by DATA\n * rather than by a fixed set of slots, and an app passes the same map to both\n * pickers. */\n currencyNames?: Record<string, string>;\n /** Focus the field on mount — on mobile this also opens the numpad sheet, so a\n * new-transaction form can jump straight to amount entry (feedback #70). */\n autoFocus?: boolean;\n /**\n * Tint the typed figure by what it will DO (Keksdose feedback #167).\n *\n * The direction is chosen with a toggle beside the field rather than typed, so\n * the digits alone say nothing about which way the money goes — on the one screen\n * where getting that backwards is the expensive mistake. Colour says it\n * continuously, and it costs no layout. It stays the MAIN indication (live #201\n * rework: *\"The main indication shall still be the color\"*); {@link negative}\n * renders the sign as a second, quieter signal in front of the figure.\n *\n * Never the ONLY signal: the toggle it mirrors is right there, labelled, so this\n * is reinforcement rather than the sole carrier of the meaning.\n */\n tone?: \"neutral\" | \"outflow\" | \"inflow\";\n /**\n * The SIGN of the figure, owned by the caller's direction control (Keksdose live\n * #201 rework: *\"Outflow should be negative and inflow positive … the sign shall\n * be displayed but not necessarily be typed in\"*).\n *\n * `value` stays the MAGNITUDE. The minus is glued on at render time and stripped\n * off again before anything is reported back, so the caller never sees its own\n * prefix echoed and no code path can end up applying it twice. That is the whole\n * cure: there is exactly ONE place the sign lives, and it is not the text.\n *\n * Because it is rendered rather than stored it cannot be deleted (the next render\n * puts it back), a select-all-and-retype keeps the direction, and the caret needs\n * no minding.\n */\n negative?: boolean;\n /**\n * A sign the user TYPED, or a calculation that resolved to a signed number.\n *\n * SET, never flip. A \"-\" means *\"this is an outflow\"*, so typing it twice says the\n * same thing twice — which is exactly what the rework asks for (*\"Subtracting\n * values twice resulting in inflow -> outflow and back to inflow seems not\n * reasonable\"*). \"+\" says the other direction.\n *\n * Its presence is what ARMS the whole sign behaviour. A field with no direction\n * control — an account's starting balance, a loan payment, a holding's cost —\n * passes neither prop and keeps a text that is the whole truth, minus included.\n */\n onNegativeChange?: (negative: boolean) => void;\n /**\n * How the field presents itself ON A PHONE (Keksdose feedback #176).\n *\n * `\"field\"` (default) is the labelled, bordered input used everywhere else.\n *\n * `\"display\"` keeps every mechanic — the same `<input>`, the same numpad sheet,\n * the same currency picker, the same commit/blur contract — and only drops the\n * chrome: no border, no fill, no floating label, the figure set at display size.\n * On a form whose whole point is one number, a bordered `text-sm` box draws the\n * amount at the same weight as the memo beside it; this makes it the headline\n * instead. It stays fully editable — the underline and the caret are what say so.\n *\n * Phone-only by construction: it keys off the same breakpoint as the numpad, so\n * from `md` up the field is byte-for-byte the normal one and a desktop grid keeps\n * its column rhythm.\n */\n variant?: \"field\" | \"display\";\n /**\n * Where the figure sits in its row, for `variant=\"display\"` only (Keksdose\n * feedback #176 rework).\n *\n * `\"start\"` (default) keeps it flush left, in the reading column the fields\n * below it share — and it is what the entry forms use, because a figure that\n * starts at a known edge is legible at any width: when the value outgrows the\n * field, the digits that scroll out of sight are the trailing ones, not the\n * magnitude (Keksdose feedback #430 rework).\n *\n * `\"center\"` makes it a centred headline. It centres in the width that REMAINS\n * after the trailing currency control, not in the whole box: the control is\n * pinned to the right edge, so a plain `text-center` would centre the figure\n * under it and the last digits would sit behind the chip. This used to mirror\n * the control's reservation onto the left instead, which centred correctly but\n * spent twice the control's width on padding — fatal on a 375px screen, where\n * it left a 36px figure 16px to live in.\n */\n align?: \"start\" | \"center\";\n /**\n * Decimals the committed amount is rounded to (kastlan 0.12: \"12.345\" and a\n * calculator's \"100/3\" reached a `Numeric(10,2)` column unrounded and failed with a\n * 422). Default: the currency's minor unit, from `Intl` (CHF and EUR 2, JPY 0). With\n * no `currency`, nothing is rounded unless this is set. Rounding is half away from\n * zero (12.345 → 12.35, -12.345 → -12.35) and happens when the figure settles: on\n * blur, on Enter, and on every result the calculator writes back. Keystrokes are left\n * alone, so \"12.3\" can still become \"12.34\".\n */\n digits?: number;\n /** The smallest amount the field settles on. A lower figure is raised to it when it\n * settles, like `digits`. Compared with the signed figure. */\n min?: number;\n /** The largest amount the field settles on (a deposit release capped at the\n * balance). A higher figure is lowered to it when it settles. */\n max?: number;\n}\n\n/** The currency's minor unit (CHF 2, JPY 0), or `undefined` for no currency or a code\n * `Intl` does not accept. */\nfunction currencyDigits(code: string | undefined): number | undefined {\n if (!code) return undefined;\n try {\n return new Intl.NumberFormat(\"en\", { style: \"currency\", currency: code }).resolvedOptions()\n .maximumFractionDigits;\n } catch {\n return undefined;\n }\n}\n\n/**\n * A settled figure, rounded to `digits` (half away from zero) and clamped to\n * `min`/`max`. Only a plain number is touched. A half-typed draft or an expression\n * comes back as it was. Rounding works in decimal exponent notation, because\n * `Math.round(1.005 * 100)` is 100 (1.005 is 1.00499… in binary).\n */\nfunction settleAmount(text: string, digits: number | undefined, min?: number, max?: number): string {\n const t = text.trim();\n if (!/^-?\\d*\\.?\\d*$/.test(t) || !/\\d/.test(t)) return text;\n let n = Number(t);\n if (!Number.isFinite(n)) return text;\n if (digits !== undefined) {\n const magnitude = Number(`${Math.round(Number(`${Math.abs(n)}e${digits}`))}e-${digits}`);\n n = n < 0 ? -magnitude : magnitude;\n }\n if (min !== undefined && n < min) n = min;\n if (max !== undefined && n > max) n = max;\n const out = formatResult(n);\n // Unchanged figures keep their own spelling (\"12.50\" stays \"12.50\").\n return Number(out) === Number(t) ? text : out;\n}\n\n/**\n * The locale's decimal mark, as far as this field can type it: \",\" or \".\" (kastlan 40).\n * The same answer `NumberField` gives, for the same reason: a mark outside those two\n * (Arabic's \"٫\") is not one {@link sanitizeLive} lets through, so those locales keep\n * the dot rather than get a field that eats the key it shows.\n */\nfunction decimalMark(locale: string | undefined): \",\" | \".\" {\n try {\n const part = new Intl.NumberFormat(locale).formatToParts(1.5).find((p) => p.type === \"decimal\");\n return part?.value === \",\" ? \",\" : \".\";\n } catch {\n // An invalid tag throws a RangeError; a typo in a locale must not take the form down.\n return \".\";\n }\n}\n\n// The consuming app's ONE money palette (`--money-expense` / `--money-income`),\n// not a bespoke rose/emerald pairing: a figure being typed has to wear the same\n// colour the same figure will wear once it is a row in the table behind the form\n// (Keksdose dev#434). The utilities are unlayered and theme-aware, so no `dark:`\n// variant is needed and they win over the field's own text colour regardless of\n// where `cn` puts them.\nconst TONE_CLASS: Record<\"neutral\" | \"outflow\" | \"inflow\", string> = {\n neutral: \"\",\n outflow: \"text-money-neg\",\n inflow: \"text-money-pos\",\n};\n\n// The shared chrome-less treatment at money size. `tabular-nums` so digits don't\n// reflow the figure as they are typed; FIELD_DISPLAY's own muted placeholder\n// colour is what keeps an EMPTY form from painting its zero in the direction tint\n// (`tone` is computed from 0, which reads as an inflow).\nconst DISPLAY_INPUT_CLASS = cn(\n FIELD_DISPLAY,\n \"text-4xl font-semibold leading-tight tracking-tight tabular-nums\",\n);\n\n/**\n * Is `text` the ANSWER to `previous`, or something typed OVER it?\n *\n * \"The old text was a sum and the new one is bare\" cannot tell those apart, and both\n * gestures are ordinary: select-all-and-retype after a typo, or backspacing \"-20+\"\n * back down to a fresh figure. Read as an answer, they move the direction chip — so\n * an outflow of 7 quietly booked +7.00 (live #201 rework).\n *\n * The question that does separate them is arithmetic, not shape: evaluate what the\n * text replaced and see whether this IS that number. \"-12+30\" → \"18\" still is, so a\n * sum that comes out positive still takes the chip with it; \"-20+50\" → \"7\" is not,\n * and \"-20+\" evaluates to nothing at all.\n */\nfunction isResultOf(previous: string, text: string, settle: (text: string) => string): boolean {\n const n = evaluateExpression(previous);\n // Compared settled, since the field rounds what the calculator hands it.\n return n !== null && settle(formatResult(n)) === text.trim();\n}\n\nexport const AmountInput = forwardRef<HTMLInputElement, AmountInputProps>(\n ({ value, onChange, currency, onCurrencyChange, placeholder, label, disabled, invalid: invalidProp, className, id, ariaLabel, \"aria-describedby\": ariaDescribedBy, \"aria-invalid\": ariaInvalid, \"aria-required\": ariaRequired, autoFocus, tone = \"neutral\", negative = false, onNegativeChange, variant = \"field\", align = \"start\", labels, currencyNames, digits: digitsProp, min, max }, ref) => {\n const generatedId = useId();\n const fieldId = id ?? generatedId;\n const invalid = Boolean(invalidProp) || ariaInvalid === true || ariaInvalid === \"true\";\n const editable = !!onCurrencyChange;\n // On phones we suppress the OS keyboard (inputMode=\"none\" below) and show our\n // own calculator numpad, so the desktop popover trigger is hidden. The\n // end padding keys off showCalc, so it tightens up automatically.\n const isMobile = useMediaQuery(PHONE_QUERY, false);\n const showCalc = !disabled && !isMobile;\n const [focused, setFocused] = useState(false);\n // On mobile, focusing the field opens the numpad bottom sheet in place of the\n // native keyboard (feedback #334) — a full calculator keypad, not just the old\n // operator bar. An internal ref lets the sheet's \"Done\" blur the input, which\n // commits + closes via the existing onBlur handler.\n const showNumpad = isMobile && !disabled && focused;\n // Gate the display treatment on the SAME `isMobile` the numpad uses rather than\n // on `max-md:` classes, so the two can never drift apart on the breakpoint —\n // and so the two shapes are separate class strings instead of one string\n // fighting itself through responsive overrides. `useMediaQuery` reads\n // synchronously on mount, so there is no field→figure flash.\n const asDisplay = variant === \"display\" && isMobile;\n const innerRef = useRef<HTMLInputElement>(null);\n const setRefs = useCallback(\n (el: HTMLInputElement | null) => {\n innerRef.current = el;\n if (typeof ref === \"function\") ref(el);\n else if (ref) ref.current = el;\n },\n [ref],\n );\n // The sign is DISPLAYED, not stored (live #201 rework). `value` is the\n // magnitude; the minus is glued on here and taken off again in handleText, so\n // the two can never disagree and the caller can never double-apply it. Only in\n // front of a bare amount: an expression being typed (\"12-30\") owns its own\n // minus and has to survive keystroke-for-keystroke.\n const signOwned = onNegativeChange !== undefined;\n const shown = signOwned && negative && isBareAmount(value) ? `-${value}` : value;\n // What the user SEES is `shown` with the locale's decimal mark (kastlan 40: a\n // fr-CH user typed \"1,5\" and watched it turn into \"1.5\" under their fingers). Display only — `value`, `onChange`, the sign split and the settle all\n // stay dot-decimal, because that string is the contract: RhfMoneyField's\n // `parseAmount`, every app's `Number(value)` and the calculator's evaluator read\n // it. The way back is free: {@link sanitizeLive} already folds a typed \",\" into\n // \".\", so a comma typed, pasted or tapped on the numpad lands as a dot.\n //\n // One character for one character, and no digit grouping: the caret stays where\n // the typist put it, and \"1.000\" cannot be read back as a thousand in one locale\n // and as one in the other. de-CH and it-CH are \".\" — CLDR says so, and this\n // follows `Intl` rather than a guess about a country.\n const locale = useKitLocale();\n const mark = decimalMark(locale);\n const display = mark === \",\" ? shown.replace(/\\./g, \",\") : shown;\n // Every route into the field — typing, the numpad sheet, the desktop\n // calculator, the blur/Enter commit — funnels through here, so the split is\n // written once and the four entry paths cannot drift.\n //\n // `previous` is the text this one REPLACES, and it is what says whether a bare\n // figure arriving here is an answer or a magnitude. For the three paths that\n // edit the field's own text that is simply what the field was showing; the\n // desktop calculator keeps its expression in a popover the field never sees,\n // so it passes it in (see `CalculatorButton`'s `onChange`).\n const digits = digitsProp ?? currencyDigits(currency);\n const settle = (text: string) => settleAmount(text, digits, min, max);\n const handleText = (raw: string, previous: string = shown) => {\n const text = sanitizeLive(raw);\n if (!signOwned) {\n onChange(text);\n return;\n }\n const { sign, rest } = splitLeadingSign(text);\n if (sign) {\n // SET, not flip: re-reporting the same sign on every keystroke is a no-op.\n onNegativeChange(sign === \"-\");\n } else if (looksLikeExpression(previous) && isBareAmount(text) && isResultOf(previous, text, settle)) {\n // A calculation that just RESOLVED states its sign in both directions. The\n // figure it ran on is the SIGNED one the user could see — \"-12+30\" is +18 —\n // so a positive result has to move the chip too, or the field would answer\n // that sum with \"-18\" and contradict the arithmetic it just showed.\n //\n // Only when it really resolved, though: see {@link isResultOf}. A bare figure\n // arriving on top of an expression is far more often a replacement than an\n // answer, and reading it as an answer flips the direction of money.\n onNegativeChange(false);\n }\n onChange(sign ? rest : text);\n };\n const commit = () => handleText(settle(commitExpression(shown)));\n const { open, setOpen, wrapperRef, panelRef, query, setQuery, inputRef } = useDropdownSearch();\n // The chip the currency list hangs off (Keksdose dev#548). It is portalled now, so\n // the panel needs a real trigger rect rather than a relative parent — see\n // `DropdownPanel`'s note for what an `overflow` ancestor did to it before.\n const chipRef = useRef<HTMLButtonElement>(null);\n\n // The currency chip's strings are the `currency` namespace — the same two\n // `CurrencySelect` resolves, under this component's older key names. The\n // calculator and the numpad resolve `calculator` themselves; `labels.calculator`\n // and `labels.pad` are handed straight through to them as overrides.\n const currencyOverrides = useMemo(() => {\n const out: Partial<CurrencyLabels> = {};\n if (labels?.currency !== undefined) out.currency = labels.currency;\n if (labels?.currencySearch !== undefined) out.search = labels.currencySearch;\n return out;\n }, [labels?.currency, labels?.currencySearch]);\n const currencyText = useKitLabels(\"currency\", DEFAULT_CURRENCY_LABELS, currencyOverrides);\n const common = useKitLabels(\"common\", DEFAULT_COMMON_LABELS);\n\n const selected = getCurrency(currency);\n const filtered = useMemo(() => {\n const q = query.trim().toLocaleLowerCase(locale);\n if (!q) return CURRENCIES;\n return CURRENCIES.filter(\n (c) =>\n c.code.toLowerCase().includes(q) ||\n // The name the row SHOWS, so a translated list is searchable in the\n // language it is written in.\n currencyName(c, currencyNames, locale).toLocaleLowerCase(locale).includes(q) ||\n c.symbol.toLowerCase().includes(q),\n );\n }, [query, currencyNames, locale]);\n\n return (\n <div ref={wrapperRef} className={cn(\"w-full\", className)}>\n {/* Inner relative box holds the input + its absolutely-positioned\n trailing controls (calculator / currency), so those stay anchored to\n the INPUT even when the mobile math bar is rendered below (#334). */}\n <div className=\"relative w-full\">\n <input\n ref={setRefs}\n id={fieldId}\n aria-label={ariaLabel}\n type=\"text\"\n // eslint-disable-next-line jsx-a11y/no-autofocus -- opt-in per call site (feedback #70)\n autoFocus={autoFocus}\n // On mobile suppress the OS keyboard so our numpad sheet owns entry; the\n // field keeps focus/caret. Desktop keeps the native decimal keypad.\n inputMode={isMobile ? \"none\" : \"decimal\"}\n autoComplete=\"off\"\n disabled={disabled}\n // The floating-label pattern needs a blank placeholder for its\n // peer-placeholder-shown trick. The display shape has no floating label,\n // so it spends the placeholder on what an empty borderless form actually\n // needs: a zero to aim at, at full size. The caller supplies it because\n // only the app knows the locale's decimal separator.\n placeholder={asDisplay ? (placeholder ?? \"0\") : label !== undefined ? \" \" : placeholder}\n value={display}\n onChange={(e) => handleText(e.target.value)}\n onFocus={() => setFocused(true)}\n onBlur={() => {\n commit();\n setFocused(false);\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") commit();\n }}\n className={cn(\n // With a label, use the floating-input padding (pt-4 pb-1) like every\n // other labelled field so the value sits BELOW the floated label rather\n // than vertically centred where it overlaps the resting label\n // (feedback #314). FLOATING_INPUT_CLASS already bundles the peer +\n // transparent-placeholder bits.\n asDisplay ? DISPLAY_INPUT_CLASS : label !== undefined ? FLOATING_INPUT_CLASS : FIELD_BASE,\n // Room for the trailing controls. showCalc is always false on a phone,\n // so the display shape only ever has to clear the currency chip — and\n // it clears it by the chip's actual width (a text-sm code plus a\n // chevron, ~58px) rather than the 5rem the boxed shape reserves. On a\n // 375px screen those 16px are the difference between a readable figure\n // and a clipped one (feedback #430 rework).\n asDisplay\n ? currency ? (editable ? \"pe-16\" : \"pe-12\") : \"pe-0\"\n : showCalc\n ? currency ? (editable ? \"pe-24\" : \"pe-16\") : \"pe-10\"\n : currency ? (editable ? \"pe-20\" : \"pe-14\") : \"pe-3\",\n // Centred display shape: centre in what is LEFT of the currency chip.\n // `text-center` alone would centre the figure in the whole box, i.e.\n // partly underneath the chip; the padding above is what takes the chip\n // out of the centring, and nothing is added at the start because a\n // mirrored reservation would spend the width twice (see `align`).\n asDisplay && align === \"center\" && \"text-center\",\n // Last, so it wins over the base class's own text colour.\n TONE_CLASS[tone],\n invalid && FIELD_INVALID,\n )}\n aria-invalid={invalid || undefined}\n aria-describedby={ariaDescribedBy}\n aria-required={ariaRequired}\n />\n {label !== undefined && (\n // The display shape drops the label VISUALLY, not from the accessibility\n // tree: a 36px tinted figure at the top of a transaction form is legibly\n // the amount, but a screen reader still needs the name, and callers that\n // pass `label` without `ariaLabel` would otherwise be left with none.\n <label htmlFor={fieldId} className={asDisplay ? \"sr-only\" : FLOATING_LABEL_CLASS}>\n {label}\n </label>\n )}\n {/* Trailing controls share one flex track so the calculator icon and the\n currency suffix/picker sit side by side without overlapping. */}\n {/* The display shape has no box to inset from, so the controls align to the\n figure's own end edge and its baseline strip (`bottom-1`, matching the\n input's pb-1) instead of floating inside a field. */}\n <div\n className={cn(\n \"absolute flex items-center gap-0.5\",\n // Logical `end-*`: the chip and the calculator are the figure's trailing\n // controls, so a right-to-left form carries them on the left.\n asDisplay ? \"bottom-1 end-0\" : \"inset-y-1 end-1\",\n )}\n >\n {showCalc && (\n <CalculatorButton\n // The mark the field shows, as NumberInput hands its calculator; the\n // evaluator reads either, and its result comes back dot-decimal.\n value={display}\n onChange={(result, expression) => handleText(settle(result), expression)}\n className=\"px-1.5\"\n ariaLabel={labels?.calculatorTrigger}\n labels={labels?.calculator}\n />\n )}\n {currency && !editable && (\n <span\n aria-hidden\n className={cn(\n \"pointer-events-none px-1 font-medium text-[var(--text-muted)]\",\n // A text-xs chip next to a 36px figure reads as a stray footnote.\n asDisplay ? \"text-sm\" : \"text-xs\",\n )}\n >\n {currency}\n </span>\n )}\n {currency && editable && (\n <button\n ref={chipRef}\n type=\"button\"\n onClick={() => setOpen((v) => !v)}\n aria-label={\n // \"Currency: EUR\" through `common.fieldValue`, not a template literal:\n // the colon-and-space is punctuation a translation has to own.\n selected ? common.fieldValue(currencyText.currency, selected.code) : currencyText.currency\n }\n className={cn(\n \"flex items-center gap-1 rounded px-2 py-1 font-medium text-[var(--text-secondary)] hover:bg-[var(--bg-hover)]\",\n asDisplay ? \"text-sm\" : \"text-xs\",\n )}\n >\n {currency}\n <ChevronDown className=\"size-3\" />\n </button>\n )}\n </div>\n {editable && open && (\n <DropdownPanel\n anchorRef={chipRef}\n panelRef={panelRef}\n empty={filtered.length === 0}\n header={\n <DropdownSearchHeader\n query={query}\n onQueryChange={setQuery}\n inputRef={inputRef}\n placeholder={currencyText.search}\n />\n }\n >\n {filtered.map((c) => {\n const active = c.code === selected?.code;\n return (\n <li key={c.code}>\n <button\n type=\"button\"\n onClick={() => {\n onCurrencyChange?.(c.code);\n setOpen(false);\n }}\n className={cn(\n \"flex w-full items-center gap-2 px-3 py-1.5 text-sm text-start hover:bg-[var(--bg-hover)]\",\n active && \"bg-[var(--bg-active)]\",\n )}\n >\n <CurrencyFlag country={c.country} />\n <span className=\"font-mono text-[var(--text-muted)] w-8 shrink-0 text-xs\">\n {c.symbol}\n </span>\n <span className=\"font-medium text-[var(--text-primary)]\">{c.code}</span>\n <span className=\"text-[var(--text-muted)] truncate text-xs\">{currencyName(c, currencyNames, locale)}</span>\n </button>\n </li>\n );\n })}\n </DropdownPanel>\n )}\n </div>\n {showNumpad && (\n <NumberPadSheet\n // Localised like the field it mirrors; its keys come back through\n // `sanitizeLive`, so the \".\" key and a \",\" both land as a dot.\n value={display}\n onChange={handleText}\n onDone={() => innerRef.current?.blur()}\n label={label}\n labels={labels?.pad}\n decimalMark={mark}\n />\n )}\n </div>\n );\n },\n);\n\nAmountInput.displayName = \"AmountInput\";\n"],"mappings":";AAmYQ,cA0GI,YA1GJ;AAnYR,SAAS,YAAY,aAAa,OAAO,SAAS,QAAQ,gBAAgB;AAC1E,SAAS,mBAAmB;AAE5B,SAAS,YAAY,cAAc,cAAc,mBAAmB;AACpE,SAAS,YAAY,eAAe,eAAe,sBAAsB,sBAAsB,mBAAmB;AAClH,SAAS,UAAU;AACnB,SAAS,qBAAqB;AAC9B,SAAS,wBAAqD;AAC9D,SAAS,sBAAiD;AAC1D,SAAS,eAAe,sBAAsB,yBAAyB;AACvE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAmJP,SAAS,eAAe,MAA8C;AACpE,MAAI,CAAC,KAAM,QAAO;AAClB,MAAI;AACF,WAAO,IAAI,KAAK,aAAa,MAAM,EAAE,OAAO,YAAY,UAAU,K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wCAAC,gBAAa,SAAS,EAAE,SAAS;AAAA,oBAClC,oBAAC,UAAK,WAAU,2DACb,YAAE,QACL;AAAA,oBACA,oBAAC,UAAK,WAAU,0CAA0C,YAAE,MAAK;AAAA,oBACjE,oBAAC,UAAK,WAAU,6CAA6C,uBAAa,GAAG,eAAe,MAAM,GAAE;AAAA;AAAA;AAAA,cACtG,KAlBO,EAAE,IAmBX;AAAA,YAEJ,CAAC;AAAA;AAAA,QACL;AAAA,SAEF;AAAA,MACC,cACC;AAAA,QAAC;AAAA;AAAA,UAGC,OAAO;AAAA,UACP,UAAU;AAAA,UACV,QAAQ,MAAM,SAAS,SAAS,KAAK;AAAA,UACrC;AAAA,UACA,QAAQ,QAAQ;AAAA,UAChB,aAAa;AAAA;AAAA,MACf;AAAA,OAEJ;AAAA,EAEJ;AACF;AAEA,YAAY,cAAc;","names":[]}
1
+ {"version":3,"sources":["../../src/components/amount-input.tsx"],"sourcesContent":["import { forwardRef, useCallback, useId, useMemo, useRef, useState } from \"react\";\nimport { ChevronDown } from \"lucide-react\";\nimport type { ReactNode } from \"react\";\nimport { CURRENCIES, CurrencyFlag, currencyName, getCurrency } from \"./currency-select\";\nimport { FIELD_BASE, FIELD_DISPLAY, FIELD_INVALID, FLOATING_INPUT_CLASS, FLOATING_LABEL_CLASS, PHONE_QUERY } from \"./ui\";\nimport { cn } from \"../lib/cn\";\nimport { useMediaQuery } from \"../hooks/use-media-query\";\nimport { CalculatorButton, type CalculatorButtonLabels } from \"./calculator\";\nimport { NumberPadSheet, type NumberPadSheetLabels } from \"./numpad-sheet\";\nimport { DropdownPanel, DropdownSearchHeader, useDropdownSearch } from \"./dropdown\";\nimport {\n DEFAULT_COMMON_LABELS,\n DEFAULT_CURRENCY_LABELS,\n useKitLabels,\n useKitLocale,\n type CurrencyLabels,\n} from \"../i18n/kit-labels\";\nimport {\n commitExpression,\n evaluateExpression,\n formatResult,\n isBareAmount,\n looksLikeExpression,\n sanitizeLive,\n splitLeadingSign,\n} from \"../lib/calc\";\n\ninterface AmountInputProps {\n value: string;\n onChange: (value: string) => void;\n currency?: string;\n onCurrencyChange?: (code: string) => void;\n placeholder?: string;\n label?: ReactNode;\n disabled?: boolean;\n /** Required and unanswered — {@link FIELD_INVALID}. See {@link Input}'s `invalid`. */\n invalid?: boolean;\n className?: string;\n id?: string;\n ariaLabel?: string;\n /**\n * Set on the `<input>`, with `id` above. Declared so `Field`'s render-prop spread —\n * `{(ids) => <AmountInput {...ids} … />}` — is typed and reaches the input: the\n * hint and error are described, a required amount is announced as required, and\n * `aria-invalid` paints {@link FIELD_INVALID} the way `invalid` does.\n */\n \"aria-describedby\"?: string;\n \"aria-invalid\"?: boolean | \"true\" | \"false\";\n \"aria-required\"?: boolean | \"true\" | \"false\";\n /** Every user-facing string this component and the two it composes own, so a\n * translating host can supply its own. Each key optional, and each a per-field\n * override of the kit-wide translation in `<UiKitProvider labels>`: `currency`\n * and `currencySearch` of its `currency` namespace, the rest of `calculator`.\n * `currency` names the picker chip, composed with the selected code through\n * `common.fieldValue`; the rest are pass-through. */\n labels?: {\n currency?: string;\n currencySearch?: string;\n /** Names the calculator TRIGGER this component renders. `calculator` below\n * names the controls inside the popover it opens. */\n calculatorTrigger?: string;\n pad?: NumberPadSheetLabels;\n calculator?: CalculatorButtonLabels;\n };\n /** Translated currency names for the chip's picker, keyed by ISO code. The same\n * sparse override `CurrencySelect` takes, and for the same reason: the names in\n * `CURRENCIES` are shipped data, so without this they are the one English word\n * left in a translated row. Not part of `labels` because it is keyed by DATA\n * rather than by a fixed set of slots, and an app passes the same map to both\n * pickers. */\n currencyNames?: Record<string, string>;\n /** Focus the field on mount — on mobile this also opens the numpad sheet, so a\n * new-transaction form can jump straight to amount entry (feedback #70). */\n autoFocus?: boolean;\n /**\n * Tint the typed figure by what it will DO (Keksdose feedback #167).\n *\n * The direction is chosen with a toggle beside the field rather than typed, so\n * the digits alone say nothing about which way the money goes — on the one screen\n * where getting that backwards is the expensive mistake. Colour says it\n * continuously, and it costs no layout. It stays the MAIN indication (live #201\n * rework: *\"The main indication shall still be the color\"*); {@link negative}\n * renders the sign as a second, quieter signal in front of the figure.\n *\n * Never the ONLY signal: the toggle it mirrors is right there, labelled, so this\n * is reinforcement rather than the sole carrier of the meaning.\n */\n tone?: \"neutral\" | \"outflow\" | \"inflow\";\n /**\n * The SIGN of the figure, owned by the caller's direction control (Keksdose live\n * #201 rework: *\"Outflow should be negative and inflow positive … the sign shall\n * be displayed but not necessarily be typed in\"*).\n *\n * `value` stays the MAGNITUDE. The minus is glued on at render time and stripped\n * off again before anything is reported back, so the caller never sees its own\n * prefix echoed and no code path can end up applying it twice. That is the whole\n * cure: there is exactly ONE place the sign lives, and it is not the text.\n *\n * Because it is rendered rather than stored it cannot be deleted (the next render\n * puts it back), a select-all-and-retype keeps the direction, and the caret needs\n * no minding.\n */\n negative?: boolean;\n /**\n * A sign the user TYPED, or a calculation that resolved to a signed number.\n *\n * SET, never flip. A \"-\" means *\"this is an outflow\"*, so typing it twice says the\n * same thing twice — which is exactly what the rework asks for (*\"Subtracting\n * values twice resulting in inflow -> outflow and back to inflow seems not\n * reasonable\"*). \"+\" says the other direction.\n *\n * Its presence is what ARMS the whole sign behaviour. A field with no direction\n * control — an account's starting balance, a loan payment, a holding's cost —\n * passes neither prop and keeps a text that is the whole truth, minus included.\n */\n onNegativeChange?: (negative: boolean) => void;\n /**\n * How the field presents itself ON A PHONE (Keksdose feedback #176).\n *\n * `\"field\"` (default) is the labelled, bordered input used everywhere else.\n *\n * `\"display\"` keeps every mechanic — the same `<input>`, the same numpad sheet,\n * the same currency picker, the same commit/blur contract — and only drops the\n * chrome: no border, no fill, no floating label, the figure set at display size.\n * On a form whose whole point is one number, a bordered `text-sm` box draws the\n * amount at the same weight as the memo beside it; this makes it the headline\n * instead. It stays fully editable — the underline and the caret are what say so.\n *\n * Phone-only by construction: it keys off the same breakpoint as the numpad, so\n * from `md` up the field is byte-for-byte the normal one and a desktop grid keeps\n * its column rhythm.\n */\n variant?: \"field\" | \"display\";\n /**\n * Where the figure sits in its row, for `variant=\"display\"` only (Keksdose\n * feedback #176 rework).\n *\n * `\"start\"` (default) keeps it flush left, in the reading column the fields\n * below it share — and it is what the entry forms use, because a figure that\n * starts at a known edge is legible at any width: when the value outgrows the\n * field, the digits that scroll out of sight are the trailing ones, not the\n * magnitude (Keksdose feedback #430 rework).\n *\n * `\"center\"` makes it a centred headline. It centres in the width that REMAINS\n * after the trailing currency control, not in the whole box: the control is\n * pinned to the right edge, so a plain `text-center` would centre the figure\n * under it and the last digits would sit behind the chip. This used to mirror\n * the control's reservation onto the left instead, which centred correctly but\n * spent twice the control's width on padding — fatal on a 375px screen, where\n * it left a 36px figure 16px to live in.\n */\n align?: \"start\" | \"center\";\n /**\n * Decimals the committed amount is rounded to (kastlan 0.12: \"12.345\" and a\n * calculator's \"100/3\" reached a `Numeric(10,2)` column unrounded and failed with a\n * 422). Default: the currency's minor unit, from `Intl` (CHF and EUR 2, JPY 0). With\n * no `currency`, nothing is rounded unless this is set. Rounding is half away from\n * zero (12.345 → 12.35, -12.345 → -12.35) and happens when the figure settles: on\n * blur, on Enter, and on every result the calculator writes back. Keystrokes are left\n * alone, so \"12.3\" can still become \"12.34\".\n *\n * ⚠️ **A unit price or a rate needs `digits`.** The default is right for an amount of\n * money and silently wrong for a price per unit: a fund's NAV of 123.4567 or fuel at\n * 1.789 €/l is stored as 123.46 / 1.79, and no test fails (keksdose G2, a\n * `Numeric(18,6)` holding price and a `Numeric(18,4)` unit price). Pass the column's\n * scale: `digits={4}`, `digits={6}`.\n */\n digits?: number;\n /** The smallest amount the field settles on. A lower figure is raised to it when it\n * settles, like `digits`. Compared with the signed figure. */\n min?: number;\n /** The largest amount the field settles on (a deposit release capped at the\n * balance). A higher figure is lowered to it when it settles. */\n max?: number;\n}\n\n/** The currency's minor unit (CHF 2, JPY 0), or `undefined` for no currency or a code\n * `Intl` does not accept. */\nfunction currencyDigits(code: string | undefined): number | undefined {\n if (!code) return undefined;\n try {\n return new Intl.NumberFormat(\"en\", { style: \"currency\", currency: code }).resolvedOptions()\n .maximumFractionDigits;\n } catch {\n return undefined;\n }\n}\n\n/**\n * A settled figure, rounded to `digits` (half away from zero) and clamped to\n * `min`/`max`. Only a plain number is touched. A half-typed draft or an expression\n * comes back as it was. Rounding works in decimal exponent notation, because\n * `Math.round(1.005 * 100)` is 100 (1.005 is 1.00499… in binary).\n */\nfunction settleAmount(text: string, digits: number | undefined, min?: number, max?: number): string {\n const t = text.trim();\n if (!/^-?\\d*\\.?\\d*$/.test(t) || !/\\d/.test(t)) return text;\n let n = Number(t);\n if (!Number.isFinite(n)) return text;\n if (digits !== undefined) {\n const magnitude = Number(`${Math.round(Number(`${Math.abs(n)}e${digits}`))}e-${digits}`);\n n = n < 0 ? -magnitude : magnitude;\n }\n if (min !== undefined && n < min) n = min;\n if (max !== undefined && n > max) n = max;\n const out = formatResult(n);\n // Unchanged figures keep their own spelling (\"12.50\" stays \"12.50\").\n return Number(out) === Number(t) ? text : out;\n}\n\n/**\n * The locale's decimal mark, as far as this field can type it: \",\" or \".\" (kastlan 40).\n * The same answer `NumberField` gives, for the same reason: a mark outside those two\n * (Arabic's \"٫\") is not one {@link sanitizeLive} lets through, so those locales keep\n * the dot rather than get a field that eats the key it shows.\n */\nfunction decimalMark(locale: string | undefined): \",\" | \".\" {\n try {\n const part = new Intl.NumberFormat(locale).formatToParts(1.5).find((p) => p.type === \"decimal\");\n return part?.value === \",\" ? \",\" : \".\";\n } catch {\n // An invalid tag throws a RangeError; a typo in a locale must not take the form down.\n return \".\";\n }\n}\n\n/**\n * Which typed mark is the decimal one (keksdose G1). {@link sanitizeLive} folds every\n * \",\" into \".\", so on its own it read the German \"1.234,56\" as 1.23456 — and the\n * settle then made that 1.23, final. This decides per operand, from the typist's own\n * text, before that fold:\n *\n * - both marks present: the one that is not the locale's is grouping, and goes;\n * - in a \",\" locale, only \".\" present: grouping when it cannot be a decimal as a\n * German reader writes it — twice (\"1.234.567\"), or in thousands shape (\"1.234\",\n * \"12.500\") — otherwise a decimal (\"1.5\", typed by a dot-decimal habit);\n * - in a \".\" locale, only \",\" present: grouping when it appears twice (\"1,234,567\");\n * once it stays a decimal, because Swiss and German typists write \"1,5\" in a\n * de-CH form (kastlan 40) and a unit price \"1,789\" is a decimal.\n *\n * Only a keystroke's text comes through here. A calculator result is dot-decimal\n * already, and \"1.234\" from `100/81.03…` is never a thousand.\n */\nfunction normalizeTypedMarks(raw: string, mark: \",\" | \".\"): string {\n const other = mark === \",\" ? \".\" : \",\";\n return raw.replace(/[0-9.,]+/g, (operand) => {\n const hasMark = operand.includes(mark);\n const count = operand.split(other).length - 1;\n if (count === 0) return operand;\n const grouping = hasMark\n ? true\n : count > 1 || (mark === \",\" && /^\\d{1,3}(\\.\\d{3})+$/.test(operand));\n return grouping ? operand.split(other).join(\"\") : operand;\n });\n}\n\n// The consuming app's ONE money palette (`--money-expense` / `--money-income`),\n// not a bespoke rose/emerald pairing: a figure being typed has to wear the same\n// colour the same figure will wear once it is a row in the table behind the form\n// (Keksdose dev#434). The utilities are unlayered and theme-aware, so no `dark:`\n// variant is needed and they win over the field's own text colour regardless of\n// where `cn` puts them.\nconst TONE_CLASS: Record<\"neutral\" | \"outflow\" | \"inflow\", string> = {\n neutral: \"\",\n outflow: \"text-money-neg\",\n inflow: \"text-money-pos\",\n};\n\n// The shared chrome-less treatment at money size. `tabular-nums` so digits don't\n// reflow the figure as they are typed; FIELD_DISPLAY's own muted placeholder\n// colour is what keeps an EMPTY form from painting its zero in the direction tint\n// (`tone` is computed from 0, which reads as an inflow).\nconst DISPLAY_INPUT_CLASS = cn(\n FIELD_DISPLAY,\n \"text-4xl font-semibold leading-tight tracking-tight tabular-nums\",\n);\n\n/**\n * Is `text` the ANSWER to `previous`, or something typed OVER it?\n *\n * \"The old text was a sum and the new one is bare\" cannot tell those apart, and both\n * gestures are ordinary: select-all-and-retype after a typo, or backspacing \"-20+\"\n * back down to a fresh figure. Read as an answer, they move the direction chip — so\n * an outflow of 7 quietly booked +7.00 (live #201 rework).\n *\n * The question that does separate them is arithmetic, not shape: evaluate what the\n * text replaced and see whether this IS that number. \"-12+30\" → \"18\" still is, so a\n * sum that comes out positive still takes the chip with it; \"-20+50\" → \"7\" is not,\n * and \"-20+\" evaluates to nothing at all.\n */\nfunction isResultOf(previous: string, text: string, settle: (text: string) => string): boolean {\n const n = evaluateExpression(previous);\n // Compared settled, since the field rounds what the calculator hands it.\n return n !== null && settle(formatResult(n)) === text.trim();\n}\n\nexport const AmountInput = forwardRef<HTMLInputElement, AmountInputProps>(\n ({ value, onChange, currency, onCurrencyChange, placeholder, label, disabled, invalid: invalidProp, className, id, ariaLabel, \"aria-describedby\": ariaDescribedBy, \"aria-invalid\": ariaInvalid, \"aria-required\": ariaRequired, autoFocus, tone = \"neutral\", negative = false, onNegativeChange, variant = \"field\", align = \"start\", labels, currencyNames, digits: digitsProp, min, max }, ref) => {\n const generatedId = useId();\n const fieldId = id ?? generatedId;\n const invalid = Boolean(invalidProp) || ariaInvalid === true || ariaInvalid === \"true\";\n const editable = !!onCurrencyChange;\n // On phones we suppress the OS keyboard (inputMode=\"none\" below) and show our\n // own calculator numpad, so the desktop popover trigger is hidden. The\n // end padding keys off showCalc, so it tightens up automatically.\n const isMobile = useMediaQuery(PHONE_QUERY, false);\n const showCalc = !disabled && !isMobile;\n const [focused, setFocused] = useState(false);\n // On mobile, focusing the field opens the numpad bottom sheet in place of the\n // native keyboard (feedback #334) — a full calculator keypad, not just the old\n // operator bar. An internal ref lets the sheet's \"Done\" blur the input, which\n // commits + closes via the existing onBlur handler.\n const showNumpad = isMobile && !disabled && focused;\n // Gate the display treatment on the SAME `isMobile` the numpad uses rather than\n // on `max-md:` classes, so the two can never drift apart on the breakpoint —\n // and so the two shapes are separate class strings instead of one string\n // fighting itself through responsive overrides. `useMediaQuery` reads\n // synchronously on mount, so there is no field→figure flash.\n const asDisplay = variant === \"display\" && isMobile;\n const innerRef = useRef<HTMLInputElement>(null);\n const setRefs = useCallback(\n (el: HTMLInputElement | null) => {\n innerRef.current = el;\n if (typeof ref === \"function\") ref(el);\n else if (ref) ref.current = el;\n },\n [ref],\n );\n // The sign is DISPLAYED, not stored (live #201 rework). `value` is the\n // magnitude; the minus is glued on here and taken off again in handleText, so\n // the two can never disagree and the caller can never double-apply it. Only in\n // front of a bare amount: an expression being typed (\"12-30\") owns its own\n // minus and has to survive keystroke-for-keystroke.\n const signOwned = onNegativeChange !== undefined;\n const shown = signOwned && negative && isBareAmount(value) ? `-${value}` : value;\n // What the user SEES is `shown` with the locale's decimal mark (kastlan 40: a\n // fr-CH user typed \"1,5\" and watched it turn into \"1.5\" under their fingers). Display only — `value`, `onChange`, the sign split and the settle all\n // stay dot-decimal, because that string is the contract: RhfMoneyField's\n // `parseAmount`, every app's `Number(value)` and the calculator's evaluator read\n // it. The way back is free: {@link sanitizeLive} already folds a typed \",\" into\n // \".\", so a comma typed, pasted or tapped on the numpad lands as a dot.\n //\n // One character for one character, and no digit grouping: the caret stays where\n // the typist put it, and \"1.000\" cannot be read back as a thousand in one locale\n // and as one in the other. de-CH and it-CH are \".\" — CLDR says so, and this\n // follows `Intl` rather than a guess about a country.\n const locale = useKitLocale();\n const mark = decimalMark(locale);\n // While the typist is typing, the field shows THEIR text (\"1.234,5\" stays exactly\n // that), not the value re-spelt: re-spelling turned a grouping \".\" into a \",\" under\n // their fingers, after which no rule could tell the two apart (keksdose G1). The\n // draft is shown only while it still spells what the field holds; a value set from\n // outside, a calculator result or a commit falls back to the derived spelling.\n const [draft, setDraft] = useState<string | null>(null);\n const derived = mark === \",\" ? shown.replace(/\\./g, \",\") : shown;\n const draftAs = draft === null ? \"\" : sanitizeLive(normalizeTypedMarks(draft, mark));\n const display =\n draft === null\n ? derived\n : draftAs === shown\n ? draft\n : // The caller owns the sign: the typed \"12\" is shown as the \"-12\" it is.\n signOwned && negative && `-${draftAs}` === shown\n ? `-${draft}`\n : derived;\n // Every route into the field — typing, the numpad sheet, the desktop\n // calculator, the blur/Enter commit — funnels through here, so the split is\n // written once and the four entry paths cannot drift.\n //\n // `previous` is the text this one REPLACES, and it is what says whether a bare\n // figure arriving here is an answer or a magnitude. For the three paths that\n // edit the field's own text that is simply what the field was showing; the\n // desktop calculator keeps its expression in a popover the field never sees,\n // so it passes it in (see `CalculatorButton`'s `onChange`).\n const digits = digitsProp ?? currencyDigits(currency);\n const settle = (text: string) => settleAmount(text, digits, min, max);\n const handleText = (raw: string, previous: string = shown) => {\n const text = sanitizeLive(raw);\n if (!signOwned) {\n onChange(text);\n return;\n }\n const { sign, rest } = splitLeadingSign(text);\n if (sign) {\n // SET, not flip: re-reporting the same sign on every keystroke is a no-op.\n onNegativeChange(sign === \"-\");\n } else if (looksLikeExpression(previous) && isBareAmount(text) && isResultOf(previous, text, settle)) {\n // A calculation that just RESOLVED states its sign in both directions. The\n // figure it ran on is the SIGNED one the user could see — \"-12+30\" is +18 —\n // so a positive result has to move the chip too, or the field would answer\n // that sum with \"-18\" and contradict the arithmetic it just showed.\n //\n // Only when it really resolved, though: see {@link isResultOf}. A bare figure\n // arriving on top of an expression is far more often a replacement than an\n // answer, and reading it as an answer flips the direction of money.\n onNegativeChange(false);\n }\n onChange(sign ? rest : text);\n };\n const commit = () => {\n setDraft(null);\n handleText(settle(commitExpression(shown)));\n };\n const typed = (raw: string) => {\n setDraft(raw);\n handleText(normalizeTypedMarks(raw, mark));\n };\n const { open, setOpen, wrapperRef, panelRef, query, setQuery, inputRef } = useDropdownSearch();\n // The chip the currency list hangs off (Keksdose dev#548). It is portalled now, so\n // the panel needs a real trigger rect rather than a relative parent — see\n // `DropdownPanel`'s note for what an `overflow` ancestor did to it before.\n const chipRef = useRef<HTMLButtonElement>(null);\n\n // The currency chip's strings are the `currency` namespace — the same two\n // `CurrencySelect` resolves, under this component's older key names. The\n // calculator and the numpad resolve `calculator` themselves; `labels.calculator`\n // and `labels.pad` are handed straight through to them as overrides.\n const currencyOverrides = useMemo(() => {\n const out: Partial<CurrencyLabels> = {};\n if (labels?.currency !== undefined) out.currency = labels.currency;\n if (labels?.currencySearch !== undefined) out.search = labels.currencySearch;\n return out;\n }, [labels?.currency, labels?.currencySearch]);\n const currencyText = useKitLabels(\"currency\", DEFAULT_CURRENCY_LABELS, currencyOverrides);\n const common = useKitLabels(\"common\", DEFAULT_COMMON_LABELS);\n\n const selected = getCurrency(currency);\n const filtered = useMemo(() => {\n const q = query.trim().toLocaleLowerCase(locale);\n if (!q) return CURRENCIES;\n return CURRENCIES.filter(\n (c) =>\n c.code.toLowerCase().includes(q) ||\n // The name the row SHOWS, so a translated list is searchable in the\n // language it is written in.\n currencyName(c, currencyNames, locale).toLocaleLowerCase(locale).includes(q) ||\n c.symbol.toLowerCase().includes(q),\n );\n }, [query, currencyNames, locale]);\n\n return (\n <div ref={wrapperRef} className={cn(\"w-full\", className)}>\n {/* Inner relative box holds the input + its absolutely-positioned\n trailing controls (calculator / currency), so those stay anchored to\n the INPUT even when the mobile math bar is rendered below (#334). */}\n <div className=\"relative w-full\">\n <input\n ref={setRefs}\n id={fieldId}\n aria-label={ariaLabel}\n type=\"text\"\n // eslint-disable-next-line jsx-a11y/no-autofocus -- opt-in per call site (feedback #70)\n autoFocus={autoFocus}\n // On mobile suppress the OS keyboard so our numpad sheet owns entry; the\n // field keeps focus/caret. Desktop keeps the native decimal keypad.\n inputMode={isMobile ? \"none\" : \"decimal\"}\n autoComplete=\"off\"\n disabled={disabled}\n // The floating-label pattern needs a blank placeholder for its\n // peer-placeholder-shown trick. The display shape has no floating label,\n // so it spends the placeholder on what an empty borderless form actually\n // needs: a zero to aim at, at full size. The caller supplies it because\n // only the app knows the locale's decimal separator.\n placeholder={asDisplay ? (placeholder ?? \"0\") : label !== undefined ? \" \" : placeholder}\n value={display}\n onChange={(e) => typed(e.target.value)}\n onFocus={() => setFocused(true)}\n onBlur={() => {\n commit();\n setFocused(false);\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") commit();\n }}\n className={cn(\n // With a label, use the floating-input padding (pt-4 pb-1) like every\n // other labelled field so the value sits BELOW the floated label rather\n // than vertically centred where it overlaps the resting label\n // (feedback #314). FLOATING_INPUT_CLASS already bundles the peer +\n // transparent-placeholder bits.\n asDisplay ? DISPLAY_INPUT_CLASS : label !== undefined ? FLOATING_INPUT_CLASS : FIELD_BASE,\n // Room for the trailing controls. showCalc is always false on a phone,\n // so the display shape only ever has to clear the currency chip — and\n // it clears it by the chip's actual width (a text-sm code plus a\n // chevron, ~58px) rather than the 5rem the boxed shape reserves. On a\n // 375px screen those 16px are the difference between a readable figure\n // and a clipped one (feedback #430 rework).\n asDisplay\n ? currency ? (editable ? \"pe-16\" : \"pe-12\") : \"pe-0\"\n : showCalc\n ? currency ? (editable ? \"pe-24\" : \"pe-16\") : \"pe-10\"\n : currency ? (editable ? \"pe-20\" : \"pe-14\") : \"pe-3\",\n // Centred display shape: centre in what is LEFT of the currency chip.\n // `text-center` alone would centre the figure in the whole box, i.e.\n // partly underneath the chip; the padding above is what takes the chip\n // out of the centring, and nothing is added at the start because a\n // mirrored reservation would spend the width twice (see `align`).\n asDisplay && align === \"center\" && \"text-center\",\n // Last, so it wins over the base class's own text colour.\n TONE_CLASS[tone],\n invalid && FIELD_INVALID,\n )}\n aria-invalid={invalid || undefined}\n aria-describedby={ariaDescribedBy}\n aria-required={ariaRequired}\n />\n {label !== undefined && (\n // The display shape drops the label VISUALLY, not from the accessibility\n // tree: a 36px tinted figure at the top of a transaction form is legibly\n // the amount, but a screen reader still needs the name, and callers that\n // pass `label` without `ariaLabel` would otherwise be left with none.\n <label htmlFor={fieldId} className={asDisplay ? \"sr-only\" : FLOATING_LABEL_CLASS}>\n {label}\n </label>\n )}\n {/* Trailing controls share one flex track so the calculator icon and the\n currency suffix/picker sit side by side without overlapping. */}\n {/* The display shape has no box to inset from, so the controls align to the\n figure's own end edge and its baseline strip (`bottom-1`, matching the\n input's pb-1) instead of floating inside a field. */}\n <div\n className={cn(\n \"absolute flex items-center gap-0.5\",\n // Logical `end-*`: the chip and the calculator are the figure's trailing\n // controls, so a right-to-left form carries them on the left.\n asDisplay ? \"bottom-1 end-0\" : \"inset-y-1 end-1\",\n )}\n >\n {showCalc && (\n <CalculatorButton\n // The mark the field shows, as NumberInput hands its calculator; the\n // evaluator reads either, and its result comes back dot-decimal.\n value={display}\n onChange={(result, expression) => {\n setDraft(null);\n handleText(settle(result), expression);\n }}\n className=\"px-1.5\"\n ariaLabel={labels?.calculatorTrigger}\n labels={labels?.calculator}\n />\n )}\n {currency && !editable && (\n <span\n aria-hidden\n className={cn(\n \"pointer-events-none px-1 font-medium text-[var(--text-muted)]\",\n // A text-xs chip next to a 36px figure reads as a stray footnote.\n asDisplay ? \"text-sm\" : \"text-xs\",\n )}\n >\n {currency}\n </span>\n )}\n {currency && editable && (\n <button\n ref={chipRef}\n type=\"button\"\n onClick={() => setOpen((v) => !v)}\n aria-label={\n // \"Currency: EUR\" through `common.fieldValue`, not a template literal:\n // the colon-and-space is punctuation a translation has to own.\n selected ? common.fieldValue(currencyText.currency, selected.code) : currencyText.currency\n }\n className={cn(\n \"flex items-center gap-1 rounded px-2 py-1 font-medium text-[var(--text-secondary)] hover:bg-[var(--bg-hover)]\",\n asDisplay ? \"text-sm\" : \"text-xs\",\n )}\n >\n {currency}\n <ChevronDown className=\"size-3\" />\n </button>\n )}\n </div>\n {editable && open && (\n <DropdownPanel\n anchorRef={chipRef}\n panelRef={panelRef}\n empty={filtered.length === 0}\n header={\n <DropdownSearchHeader\n query={query}\n onQueryChange={setQuery}\n inputRef={inputRef}\n placeholder={currencyText.search}\n />\n }\n >\n {filtered.map((c) => {\n const active = c.code === selected?.code;\n return (\n <li key={c.code}>\n <button\n type=\"button\"\n onClick={() => {\n onCurrencyChange?.(c.code);\n setOpen(false);\n }}\n className={cn(\n \"flex w-full items-center gap-2 px-3 py-1.5 text-sm text-start hover:bg-[var(--bg-hover)]\",\n active && \"bg-[var(--bg-active)]\",\n )}\n >\n <CurrencyFlag country={c.country} />\n <span className=\"font-mono text-[var(--text-muted)] w-8 shrink-0 text-xs\">\n {c.symbol}\n </span>\n <span className=\"font-medium text-[var(--text-primary)]\">{c.code}</span>\n <span className=\"text-[var(--text-muted)] truncate text-xs\">{currencyName(c, currencyNames, locale)}</span>\n </button>\n </li>\n );\n })}\n </DropdownPanel>\n )}\n </div>\n {showNumpad && (\n <NumberPadSheet\n // Localised like the field it mirrors. Keys are typing, read by the\n // locale's marks like the keyboard's; \"=\" is a result, dot-decimal.\n value={display}\n onChange={typed}\n onResult={(result) => {\n setDraft(null);\n handleText(result);\n }}\n onDone={() => innerRef.current?.blur()}\n label={label}\n labels={labels?.pad}\n decimalMark={mark}\n />\n )}\n </div>\n );\n },\n);\n\nAmountInput.displayName = \"AmountInput\";\n"],"mappings":";AA8bQ,cA6GI,YA7GJ;AA9bR,SAAS,YAAY,aAAa,OAAO,SAAS,QAAQ,gBAAgB;AAC1E,SAAS,mBAAmB;AAE5B,SAAS,YAAY,cAAc,cAAc,mBAAmB;AACpE,SAAS,YAAY,eAAe,eAAe,sBAAsB,sBAAsB,mBAAmB;AAClH,SAAS,UAAU;AACnB,SAAS,qBAAqB;AAC9B,SAAS,wBAAqD;AAC9D,SAAS,sBAAiD;AAC1D,SAAS,eAAe,sBAAsB,yBAAyB;AACvE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAyJP,SAAS,eAAe,MAA8C;AACpE,MAAI,CAAC,KAAM,QAAO;AAClB,MAAI;AACF,WAAO,IAAI,KAAK,aAAa,MAAM,EAAE,OAAO,YAAY,UAAU,KAAK,CAAC,EAAE,gBAAgB,EACvF;AAAA,EACL,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAQA,SAAS,aAAa,MAAc,QAA4B,KAAc,KAAsB;AAClG,QAAM,IAAI,KAAK,KAAK;AACpB,M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EJ;AACF;AAEA,YAAY,cAAc;","names":[]}
@@ -86,6 +86,9 @@ interface CrashReport {
86
86
  userAgent: string;
87
87
  /** The boundary's `appVersion` prop. */
88
88
  appVersion?: string;
89
+ /** The boundary's `placement` prop ("app", "page", "widget"): which boundary caught
90
+ * it, so triage can tell a whole-app crash from one page's (keksdose G3b). */
91
+ placement?: string;
89
92
  /** `navigator.onLine` at the moment of the crash; left out where there is none. */
90
93
  online?: boolean;
91
94
  /** {@link isChunkLoadError} of the thrown value. Such a crash is never handed to
@@ -114,7 +117,7 @@ declare function formatCrashReport(report: CrashReport): string;
114
117
  * times a second. The page and the time are left out on purpose: the same bug on two
115
118
  * routes is still one bug.
116
119
  */
117
- declare function crashFingerprint(report: Pick<CrashReport, "name" | "message" | "stack">): string;
120
+ declare function crashFingerprint(report: Pick<CrashReport, "name" | "message" | "stack"> & Pick<Partial<CrashReport>, "placement">): string;
118
121
  /**
119
122
  * What `onReport` may resolve with. `{ reference }` is shown ("Reported as …");
120
123
  * nothing (or `{}`) means filed without one. `{ filed: false }` says the app decided NOT
@@ -172,6 +175,10 @@ interface ErrorBoundaryProps {
172
175
  copyReport?: boolean;
173
176
  /** The app's version, printed in the report — the first question on every crash. */
174
177
  appVersion?: string;
178
+ /** Which boundary this is — "app" at the root, "page" in the layout — carried into
179
+ * the report (`placement`) and its fingerprint, so `onReport` needs no closure to say
180
+ * where the crash was caught (keksdose G3b). */
181
+ placement?: string;
175
182
  /** More `key: value` lines for the report, read when the boundary catches (a tenant
176
183
  * id, the feature flags). A throw from it is swallowed and the lines are left out. */
177
184
  reportExtras?: () => Record<string, string>;
@@ -28,12 +28,25 @@ function read(get) {
28
28
  return void 0;
29
29
  }
30
30
  }
31
+ function safeJson(value) {
32
+ try {
33
+ const json = JSON.stringify(value);
34
+ if (!json || json === "{}") return "";
35
+ return json.length > 500 ? `${json.slice(0, 499)}\u2026` : json;
36
+ } catch {
37
+ return "";
38
+ }
39
+ }
31
40
  function describeThrown(error) {
32
41
  if (typeof error === "object" && error !== null) {
33
42
  const e = error;
43
+ const message = read(() => e.message) ?? "";
34
44
  return {
35
45
  name: read(() => e.name) ?? "Error",
36
- message: read(() => e.message) ?? "",
46
+ // `throw { code: 500 }` has no message, and an empty line leaves crash triage with
47
+ // nothing (keksdose G3a; its old reporter filed `{"code":500}`). Such a value is
48
+ // quoted as JSON instead, capped, and never at the cost of a throw.
49
+ message: message || (error instanceof Error ? "" : safeJson(error)),
37
50
  stack: read(() => e.stack)
38
51
  };
39
52
  }
@@ -55,6 +68,7 @@ function formatCrashReport(report) {
55
68
  `User agent: ${report.userAgent}`
56
69
  ];
57
70
  if (report.appVersion) lines.push(`App version: ${report.appVersion}`);
71
+ if (report.placement) lines.push(`Placement: ${report.placement}`);
58
72
  if (report.online === false) lines.push("Online: no");
59
73
  for (const [key, value] of Object.entries(report.extras)) lines.push(`${key}: ${value}`);
60
74
  if (report.stack) lines.push("", "Stack:", report.stack.trim());
@@ -63,7 +77,8 @@ function formatCrashReport(report) {
63
77
  }
64
78
  function crashFingerprint(report) {
65
79
  const frames = (report.stack ?? "").split("\n").slice(0, 4).join("|");
66
- return `${report.name}::${report.message}::${frames}`;
80
+ const where = report.placement ? `${report.placement}::` : "";
81
+ return `${where}${report.name}::${report.message}::${frames}`;
67
82
  }
68
83
  const NOT_FILED = { filed: false };
69
84
  const MAX_REPORTS_PER_PAGE_LOAD = 5;
@@ -153,6 +168,7 @@ function buildReport(details, componentStack, props) {
153
168
  time: (/* @__PURE__ */ new Date()).toISOString(),
154
169
  userAgent,
155
170
  appVersion: props.appVersion,
171
+ placement: props.placement,
156
172
  online,
157
173
  chunkLoad: isChunkLoadError(details),
158
174
  extras
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/components/error-boundary.tsx"],"sourcesContent":["import { Component } from \"react\";\nimport type { ErrorInfo, ReactNode } from \"react\";\nimport { AlertTriangle, RefreshCw, WifiOff } from \"lucide-react\";\nimport { useKitLabels } from \"../i18n/kit-labels\";\nimport { Button, EmptyState } from \"./ui\";\nimport { CopyButton } from \"./copy-button\";\nimport { Disclosure } from \"./disclosure\";\n\n/** The words of the default fallback. */\nexport interface ErrorBoundaryLabels {\n /** The fallback's heading. */\n title: string;\n /** The line under it. */\n message: string;\n /** The button that clears the error and renders the children again. */\n retry: string;\n /** The disclosure that opens the full error report (`showDetails`). */\n details: string;\n /** The button that reloads the whole page (0.13). */\n reload: string;\n /** Heading when a lazy chunk failed to load while online — a deploy replaced the\n * files this page was built from (0.13). */\n updateTitle: string;\n updateMessage: string;\n /** Heading when the browser says it is offline (0.13). */\n offlineTitle: string;\n offlineMessage: string;\n /** The copy button's words: what it copies is the plain-text report (0.13). */\n copyReport: string;\n /** Shown once `onReport` has filed the crash and returned no reference (0.13). */\n reported: string;\n /** Shown once `onReport` has filed the crash under a reference — rendered as the\n * app returned it, so return `\"#123\"` if the hash belongs to it (0.13). */\n reportedAs: (reference: string) => string;\n}\n\nexport const DEFAULT_ERROR_BOUNDARY_LABELS: ErrorBoundaryLabels = {\n title: \"Something went wrong\",\n message: \"This part of the page could not be shown. Try again, or reload the page.\",\n retry: \"Try again\",\n details: \"Error details\",\n reload: \"Reload\",\n updateTitle: \"A new version is available\",\n updateMessage: \"Part of the app has changed since this page was loaded. Reload to get the new version.\",\n offlineTitle: \"You’re offline\",\n offlineMessage: \"This page could not be loaded without a connection. Reconnect, then reload the page.\",\n copyReport: \"Copy error report\",\n reported: \"This error has been reported automatically.\",\n reportedAs: (reference) => `Reported as ${reference}`,\n};\n\n/**\n * What was thrown, as flat strings, read ONCE when it arrives.\n *\n * React stores whatever was thrown, hostile or not — `throw { get message() { throw … } }`,\n * `throw { name: Symbol() }`, `throw undefined` — and reading one of those during the\n * fallback's own render would throw INSIDE the boundary, escalating to the next one up\n * (keksdose's error-boundary.tsx learned this as feedback #160: at the app level there is\n * none, and the result is the white screen the boundary exists to prevent).\n */\nexport interface ErrorBoundaryDetails {\n name: string;\n message: string;\n stack?: string;\n}\n\nfunction read(get: () => unknown): string | undefined {\n try {\n const v = get();\n return typeof v === \"string\" ? v : v === undefined || v === null ? undefined : String(v);\n } catch {\n return undefined;\n }\n}\n\n/** {@link ErrorBoundaryDetails} of any thrown value, without ever throwing. */\nexport function describeThrown(error: unknown): ErrorBoundaryDetails {\n if (typeof error === \"object\" && error !== null) {\n const e = error as { name?: unknown; message?: unknown; stack?: unknown };\n return {\n name: read(() => e.name) ?? \"Error\",\n message: read(() => e.message) ?? \"\",\n stack: read(() => e.stack),\n };\n }\n return { name: \"Error\", message: read(() => error) ?? \"\" };\n}\n\n/**\n * Is this a failed lazy import — a route chunk that did not arrive?\n *\n * Two causes, and neither is a bug in the page: the device is offline and the chunk was\n * never cached, or a deploy replaced the hashed files the running page still points at.\n * Both are cured by a reload and by nothing else — `React.lazy` caches the rejected\n * import, so Try again re-throws the same error without fetching. The patterns are\n * keksdose's (crash-report.ts), which covers Vite (\"dynamically imported module\",\n * \"module script failed\"), webpack (\"ChunkLoadError\", \"Loading chunk\") and the bare\n * `fetch` failure a service worker hands back.\n *\n * Never throws: it runs inside the fallback's own render, where a throw is a white\n * screen. An error it cannot read is not a chunk failure.\n */\nexport function isChunkLoadError(\n error: { name?: string | null; message?: string | null } | null | undefined,\n): boolean {\n try {\n const s = `${error?.name ?? \"\"} ${error?.message ?? \"\"}`;\n return /ChunkLoadError|dynamically imported module|module script failed|Loading chunk|Failed to fetch/i.test(s);\n } catch {\n return false;\n }\n}\n\n/**\n * Everything a crash report carries, read once when the boundary catches.\n *\n * Plain strings only, so it survives `JSON.stringify` into an app's crash endpoint as is\n * and {@link formatCrashReport} can print it without a single guard. The wording of the\n * printed report is English on purpose: it is read by whoever fixes the bug, not by the\n * user who copies it, and a report in nine languages cannot be searched.\n */\nexport interface CrashReport {\n /** The thrown value's `name` (\"TypeError\"), \"Error\" for a non-object. */\n name: string;\n message: string;\n stack?: string;\n /** React's component stack from `componentDidCatch` — the part that names the\n * component, which a minified JS stack no longer does. */\n componentStack?: string;\n /** `pathname + search` at the moment of the crash. The search may carry what the\n * user typed — see `redact`. */\n page: string;\n /** ISO 8601, UTC. */\n time: string;\n userAgent: string;\n /** The boundary's `appVersion` prop. */\n appVersion?: string;\n /** `navigator.onLine` at the moment of the crash; left out where there is none. */\n online?: boolean;\n /** {@link isChunkLoadError} of the thrown value. Such a crash is never handed to\n * `onReport` — it is a deploy or a dropped connection, not a defect — but it is\n * still in the copied report. */\n chunkLoad: boolean;\n /** The boundary's `reportExtras()`, stringified. */\n extras: Record<string, string>;\n}\n\n/**\n * The report as one plain-text block — what the copy button puts on the clipboard and\n * the details disclosure shows.\n *\n * lenkbank's layout, because that is the one that was already being pasted into\n * feedback messages: the error line first (it is what a search for the bug matches),\n * then where / when / what, then the two stacks.\n */\nexport function formatCrashReport(report: CrashReport): string {\n const lines = [\n report.message ? `${report.name}: ${report.message}` : report.name,\n `Page: ${report.page}`,\n `Time: ${report.time}`,\n `User agent: ${report.userAgent}`,\n ];\n if (report.appVersion) lines.push(`App version: ${report.appVersion}`);\n if (report.online === false) lines.push(\"Online: no\");\n for (const [key, value] of Object.entries(report.extras)) lines.push(`${key}: ${value}`);\n if (report.stack) lines.push(\"\", \"Stack:\", report.stack.trim());\n if (report.componentStack) lines.push(\"\", \"Component stack:\", report.componentStack.trim());\n return lines.join(\"\\n\");\n}\n\n/**\n * A key for \"the same crash again\": the error's name and message and the first frames\n * of its stack.\n *\n * Page-load local, not a server-side grouping key (keksdose's crash-report.ts draws the\n * same line): its only job is to stop one page load filing one bug twice — React's dev\n * StrictMode, a Try again that crashes again, a render loop that trips the boundary many\n * times a second. The page and the time are left out on purpose: the same bug on two\n * routes is still one bug.\n */\nexport function crashFingerprint(report: Pick<CrashReport, \"name\" | \"message\" | \"stack\">): string {\n const frames = (report.stack ?? \"\").split(\"\\n\").slice(0, 4).join(\"|\");\n return `${report.name}::${report.message}::${frames}`;\n}\n\n/**\n * What `onReport` may resolve with. `{ reference }` is shown (\"Reported as …\");\n * nothing (or `{}`) means filed without one. `{ filed: false }` says the app decided NOT\n * to file (a demo session, a hot-reload artefact, a report buffered for later): the\n * screen then claims nothing and keeps the copy button — claiming a report that was\n * never sent is the same false statement as hiding one that was.\n */\nexport type CrashReportResult = { reference?: string; filed?: boolean } | void;\n\ninterface Filing {\n filed: boolean;\n reference?: string;\n}\n\nconst NOT_FILED: Filing = { filed: false };\n\n/** A render loop can trip a boundary dozens of times a second with a different message\n * each time (a counter in it); without a ceiling the first bad deploy files hundreds of\n * rows. keksdose's number. */\nconst MAX_REPORTS_PER_PAGE_LOAD = 5;\n\n/** Fingerprint → the one filing for it in this page load. Module scope IS the page\n * load: a reload starts it empty. A duplicate gets the first filing's promise, so the\n * second screen shows the same reference instead of claiming nothing. */\nconst filings = new Map<string, Promise<Filing>>();\n\nfunction settle(out: unknown): Filing {\n try {\n if (out && typeof out === \"object\") {\n const o = out as { filed?: unknown; reference?: unknown };\n if (o.filed === false) return NOT_FILED;\n const reference = typeof o.reference === \"string\" && o.reference ? o.reference : undefined;\n return { filed: true, reference };\n }\n return { filed: true };\n } catch {\n return NOT_FILED;\n }\n}\n\n/** Hand the report to the app, once per fingerprint per page load, and never throw —\n * not for a synchronous throw, a rejection, or a hostile thenable. */\nfunction fileOnce(report: CrashReport, onReport: (report: CrashReport) => unknown): Promise<Filing> {\n const key = crashFingerprint(report);\n const known = filings.get(key);\n if (known) return known;\n if (filings.size >= MAX_REPORTS_PER_PAGE_LOAD) return Promise.resolve(NOT_FILED);\n let filing: Promise<Filing>;\n try {\n filing = Promise.resolve(onReport(report)).then(settle, () => NOT_FILED);\n } catch {\n filing = Promise.resolve(NOT_FILED);\n }\n // Claimed before the first await: two catches in the same tick (StrictMode) must not\n // both get past the lookup above.\n filings.set(key, filing);\n return filing;\n}\n\nfunction isOffline(): boolean {\n try {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n } catch {\n return false;\n }\n}\n\nfunction reloadPage(): void {\n try {\n window.location.reload();\n } catch {\n /* nothing left to do from here */\n }\n}\n\n/** What a render-prop `fallback` is handed. */\nexport interface ErrorBoundaryFallbackProps {\n /** The thrown value, as it was thrown. Read it with care — see {@link describeThrown}. */\n error: unknown;\n details: ErrorBoundaryDetails;\n /** Clear the error and render the children again. */\n reset: () => void;\n /** The crash report, once `componentDidCatch` has built it (null on the very first\n * render of the fallback, which happens before it). Already `redact`ed. */\n report: CrashReport | null;\n}\n\nexport interface ErrorBoundaryProps {\n children?: ReactNode;\n /** Replaces the default fallback: a node, or a render function handed the error and\n * a `reset`. The same rule applies to it as to the default: see the component docs. */\n fallback?: ReactNode | ((props: ErrorBoundaryFallbackProps) => ReactNode);\n /** Called once per caught error with the raw value — log it. A throw from it is\n * swallowed: the boundary is the last thing standing. For filing a report, prefer\n * `onReport`, which gets the finished report, dedupe and the reference on screen. */\n onError?: (error: unknown, info: ErrorInfo) => void;\n /** Called when the error is cleared, by Try again, `reset` or a `resetKeys` change —\n * drop a cache, refetch. */\n onReset?: () => void;\n /**\n * When any of these changes (compared with `Object.is`) AFTER an error was caught, the\n * error is cleared and the children render again — a change in the same update that\n * threw does not count (it is what the error was shown under) — pass the route path so leaving a broken page does not\n * carry its fallback to the next one (keksdose's `resetKey`).\n */\n resetKeys?: ReadonlyArray<unknown>;\n /** Quote the error's `name: message` in a monospace box under the hint. Default on\n * (0.13): three sentences true of every crash identify none of them, and the one\n * line that does is what a user can read out or screenshot (lenkbank P7). Not shown\n * for a chunk-load / offline screen, where the message is a URL that explains\n * nothing the title does not. */\n showMessage?: boolean;\n /** A collapsed disclosure holding the full plain-text report. Default on since 0.13\n * (it was an opt-in showing name, message and stack): closed, it costs one line, and\n * it is where a support conversation asks the user to look. */\n showDetails?: boolean;\n /** The copy button for the plain-text report (the kit's CopyButton, which says when\n * the clipboard refused). Default on. Hidden once `onReport` has filed the crash —\n * there is nothing left to paste anywhere — and shown again whenever it did not. */\n copyReport?: boolean;\n /** The app's version, printed in the report — the first question on every crash. */\n appVersion?: string;\n /** More `key: value` lines for the report, read when the boundary catches (a tenant\n * id, the feature flags). A throw from it is swallowed and the lines are left out. */\n reportExtras?: () => Record<string, string>;\n /**\n * Rewrite the report before anything sees it: the screen, the clipboard and\n * `onReport` all get the returned one.\n *\n * THE REPORT IS STRUCTURE, NEVER CONTENT — and only the app knows which of its query\n * params hold content. keksdose's register put the free-text search in `?q=` and payee\n * names in the `f.*` filters, and its crash channel sent them in the clear to a column\n * every admin reads (crash-report.ts `safeUrl`). The cure there is an ALLOW-list, so a\n * param added later is dropped until somebody decides otherwise — rebuild `page`\n * from `new URL(r.page, location.origin)`, keeping only the listed `searchParams`.\n * `extras` are the app's own and need no second pass. A throw from `redact` falls\n * back to the pathname alone and no extras — failing closed.\n *\n * The same holds inside `onReport`, which is the other place to do it: clamp fields\n * to what the endpoint accepts, drop what it must not store. The kit cannot know.\n */\n redact?: (report: CrashReport) => CrashReport;\n /**\n * File the report automatically. Called from `componentDidCatch`, at most once per\n * {@link crashFingerprint} per page load (and at most five times in all), never for a\n * chunk-load error. It can NOT throw into the boundary: a synchronous throw and a\n * rejection both read as \"not filed\", and the copy button stays.\n *\n * Resolve with `{ reference }` and the screen says \"Reported as …\" instead of the copy\n * button; see {@link CrashReportResult} for \"filed without a reference\" and \"decided not\n * to file\". Whatever the app's reporter does, it must do without the router, the query\n * client or the auth store's hooks — a bare `fetch` with `keepalive`, so it survives\n * the reload the user is about to press (keksdose crash-report.ts `post`).\n */\n onReport?: (report: CrashReport) => Promise<CrashReportResult> | CrashReportResult;\n /** The app's own escape hatches, beside Reload / Try again — keksdose's \"Clear local\n * data\" for a poisoned persisted cache that no in-app action could otherwise break.\n * A full-width hint under it: wrap it in `<div className=\"basis-full\">`. */\n actions?: ReactNode;\n /** The default fallback's heading level. Default `h2`: the fallback often IS the page. */\n headingAs?: \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\";\n /** Classes for the default fallback's box (`m-8 min-h-[400px]`, kastlan). */\n className?: string;\n labels?: Partial<ErrorBoundaryLabels>;\n}\n\ntype FilingState = \"none\" | \"pending\" | \"filed\" | \"failed\";\n\ninterface ErrorBoundaryState {\n /** A flag of its own, so `throw undefined` is still an error shown. */\n failed: boolean;\n error: unknown;\n details: ErrorBoundaryDetails | null;\n report: CrashReport | null;\n filing: FilingState;\n reference: string | undefined;\n}\n\nconst CLEAR: ErrorBoundaryState = {\n failed: false,\n error: null,\n details: null,\n report: null,\n filing: \"none\",\n reference: undefined,\n};\n\nfunction keysChanged(a: ReadonlyArray<unknown> | undefined, b: ReadonlyArray<unknown> | undefined): boolean {\n if (a === b) return false;\n if (!a || !b || a.length !== b.length) return true;\n return a.some((v, i) => !Object.is(v, b[i]));\n}\n\nfunction currentPage(): { page: string; path: string } {\n try {\n const { pathname, search } = window.location;\n return { page: `${pathname}${search}`, path: pathname };\n } catch {\n return { page: \"\", path: \"\" };\n }\n}\n\nfunction buildReport(details: ErrorBoundaryDetails, componentStack: string | undefined, props: ErrorBoundaryProps): CrashReport {\n const { page, path } = currentPage();\n const extras: Record<string, string> = {};\n try {\n const more = props.reportExtras?.();\n if (more) for (const [k, v] of Object.entries(more)) extras[k] = String(v);\n } catch {\n /* documented: the lines are left out */\n }\n let userAgent = \"\";\n let online: boolean | undefined;\n try {\n userAgent = navigator.userAgent;\n online = typeof navigator.onLine === \"boolean\" ? navigator.onLine : undefined;\n } catch {\n /* no navigator (SSR, a worker test) */\n }\n const report: CrashReport = {\n name: details.name,\n message: details.message,\n stack: details.stack,\n componentStack: componentStack ?? undefined,\n page,\n time: new Date().toISOString(),\n userAgent,\n appVersion: props.appVersion,\n online,\n chunkLoad: isChunkLoadError(details),\n extras,\n };\n if (!props.redact) return report;\n try {\n return props.redact(report);\n } catch {\n // Fail closed: an app that asked for redaction must not get the unredacted page.\n return { ...report, page: path, extras: {} };\n }\n}\n\n/**\n * Catch a render error below it and show ONE crash screen instead of an empty page.\n *\n * The three apps each built one. kastlan's and keksdose's sat on `EmptyState\n * tone=\"danger\"`; lenkbank's quoted the error and offered a plain-text report to copy;\n * keksdose's filed the crash itself, told a lazy-chunk failure apart as \"offline\", and\n * offered \"clear local data\" when a poisoned cache made Retry useless (feedback #160).\n * This is all of that, so the apps reduce to\n * `<ErrorBoundary resetKeys={[pathname]} appVersion={__VERSION__} />` plus, for an app\n * with a crash endpoint, `onReport` and `actions`:\n *\n * - the error's `name: message`, quoted (`showMessage`);\n * - Try again (reset the boundary) AND Reload (the page) — Try again alone re-renders\n * the same subtree from the same state, which a deterministic crash survives;\n * - a chunk-load error or an offline browser gets its own title and Reload first\n * (\"A new version is available\" / \"You're offline\");\n * - the copy button and the report in a disclosure; `onReport` for filing it, deduped\n * per page load, with its reference on screen.\n *\n * THE RULE for this fallback — and for a `fallback` or `actions` an app passes in: it\n * must not depend on the router, the query client or the auth store. A crash is exactly\n * when those may be what broke, and a fallback that throws escalates to the next\n * boundary up — at the app level there is none, and the user gets the white screen this\n * exists to prevent. So no `useNavigate`, no `useQuery`, no `useAuth()` in it; reload\n * with `window.location`, not the router. The kit's own label hooks are the one context\n * it does read (`errorBoundary.*` from `UiKitProvider`), and they degrade to the English\n * defaults when there is no provider above — which is why the app-level boundary may\n * sit OUTSIDE the provider and still render.\n *\n * The fallback is `role=\"alert\"`: a page replaced by an error is news, and a reader\n * that was on it is told.\n */\nexport class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n state: ErrorBoundaryState = CLEAR;\n\n /** Bumped by every catch and reset, so a filing that settles after the screen moved\n * on (Try again, a route change, a second crash) does not write into it. */\n private generation = 0;\n\n /**\n * Forget which crashes this page load has filed, and the count towards the cap.\n *\n * For tests: the dedupe lives in module scope because a page load is what it spans,\n * and a test file is one page load — so without this, the sixth test that files a\n * report finds the cap reached and `onReport` never called. Call it in `beforeEach`.\n * Never needed in an app: a reload is the reset.\n */\n static forgetReports(): void {\n filings.clear();\n }\n\n static getDerivedStateFromError(error: unknown): Partial<ErrorBoundaryState> {\n return { failed: true, error, details: describeThrown(error), report: null, filing: \"none\", reference: undefined };\n }\n\n componentDidCatch(error: unknown, info: ErrorInfo): void {\n try {\n this.props.onError?.(error, info);\n } catch {\n /* documented: a logger must not take the fallback down */\n }\n const details = this.state.details ?? describeThrown(error);\n const report = buildReport(details, info.componentStack ?? undefined, this.props);\n const { onReport } = this.props;\n const willFile = onReport !== undefined && !report.chunkLoad;\n const generation = ++this.generation;\n this.setState({ report, filing: willFile ? \"pending\" : \"none\", reference: undefined });\n if (!willFile) return;\n void fileOnce(report, onReport).then((filing) => {\n if (generation !== this.generation) return;\n this.setState(\n filing.filed ? { filing: \"filed\", reference: filing.reference } : { filing: \"failed\", reference: undefined },\n );\n });\n }\n\n componentDidUpdate(prev: ErrorBoundaryProps, prevState: ErrorBoundaryState): void {\n // Only a change AFTER the error was caught clears it (react-error-boundary's rule).\n // `prevState.failed` is false in the update that caught it: that update may well be\n // the one that changed the keys too — a navigation to a page that throws, with\n // `resetKeys={[pathname]}` — and resetting then would fire `onReset` for nothing and\n // render the failing child a second time. From then on `prev.resetKeys` are the\n // keys the error was shown under, so any change clears it.\n if (this.state.failed && prevState.failed && keysChanged(prev.resetKeys, this.props.resetKeys)) {\n this.reset();\n }\n }\n\n reset = (): void => {\n this.generation++;\n this.props.onReset?.();\n this.setState(CLEAR);\n };\n\n render(): ReactNode {\n const { failed, error, details, report, filing, reference } = this.state;\n if (!failed || !details) return this.props.children;\n const { fallback } = this.props;\n if (typeof fallback === \"function\") return fallback({ error, details, reset: this.reset, report });\n if (fallback !== undefined) return fallback;\n return (\n <ErrorFallback\n details={details}\n report={report}\n filing={filing}\n reference={reference}\n reset={this.reset}\n showMessage={this.props.showMessage ?? true}\n showDetails={this.props.showDetails ?? true}\n copyReport={this.props.copyReport ?? true}\n actions={this.props.actions}\n headingAs={this.props.headingAs ?? \"h2\"}\n className={this.props.className}\n labels={this.props.labels}\n />\n );\n }\n}\n\nfunction ErrorFallback({\n details,\n report,\n filing,\n reference,\n reset,\n showMessage,\n showDetails,\n copyReport,\n actions,\n headingAs,\n className,\n labels,\n}: {\n details: ErrorBoundaryDetails;\n report: CrashReport | null;\n filing: FilingState;\n reference: string | undefined;\n reset: () => void;\n showMessage: boolean;\n showDetails: boolean;\n copyReport: boolean;\n actions?: ReactNode;\n headingAs: NonNullable<ErrorBoundaryProps[\"headingAs\"]>;\n className?: string;\n labels?: Partial<ErrorBoundaryLabels>;\n}) {\n const text = useKitLabels(\"errorBoundary\", DEFAULT_ERROR_BOUNDARY_LABELS, labels);\n const chunk = isChunkLoadError(details);\n // Offline first, as keksdose has it: offline, a chunk failure is the connection, and\n // any other crash most likely a request that could not be made — either way \"reload\n // once you are back\" is the advice, and \"a new version\" would be a false one.\n const mode = isOffline() ? \"offline\" : chunk ? \"update\" : \"error\";\n const title = mode === \"offline\" ? text.offlineTitle : mode === \"update\" ? text.updateTitle : text.title;\n const hint = mode === \"offline\" ? text.offlineMessage : mode === \"update\" ? text.updateMessage : text.message;\n const Icon = mode === \"offline\" ? WifiOff : mode === \"update\" ? RefreshCw : AlertTriangle;\n const reportText = report ? formatCrashReport(report) : null;\n const errorLine = details.message ? `${details.name}: ${details.message}` : details.name;\n\n const reloadButton = (\n <Button key=\"reload\" variant={mode === \"error\" ? \"secondary\" : \"primary\"} onClick={reloadPage}>\n {text.reload}\n </Button>\n );\n // Not after a chunk failure: `React.lazy` keeps the rejected import, so Try again\n // could only throw the same error again.\n const retryButton = chunk ? null : (\n <Button key=\"retry\" variant={mode === \"error\" ? \"primary\" : \"secondary\"} onClick={reset}>\n {text.retry}\n </Button>\n );\n\n return (\n <EmptyState\n role=\"alert\"\n tone={mode === \"error\" ? \"danger\" : undefined}\n headingAs={headingAs}\n className={className}\n icon={<Icon />}\n title={title}\n hint={hint}\n action={\n <>\n {showMessage && mode === \"error\" && (\n // A quotation, not prose: left-aligned and monospaced, so it reads as the\n // program's words and can be read out or screenshotted verbatim.\n <p\n data-error-message=\"\"\n className=\"-mt-1 mb-1 basis-full whitespace-pre-wrap break-words rounded-md border border-[var(--danger-border)] bg-[var(--danger-bg)] px-3 py-2 text-start font-mono text-xs text-[var(--text-primary)]\"\n >\n {errorLine}\n </p>\n )}\n {filing === \"filed\" && (\n <p className=\"-mt-1 mb-1 basis-full text-xs\">\n {reference ? text.reportedAs(reference) : text.reported}\n </p>\n )}\n {mode === \"error\" ? [retryButton, reloadButton] : [reloadButton, retryButton]}\n {copyReport && reportText !== null && filing !== \"filed\" && (\n <CopyButton variant=\"label\" buttonVariant=\"ghost\" label={text.copyReport} text={reportText} />\n )}\n {actions}\n {showDetails && reportText !== null && (\n <Disclosure variant=\"bare\" title={text.details} className=\"basis-full text-start\">\n <pre className=\"max-h-60 overflow-auto whitespace-pre-wrap break-words text-xs text-[var(--text-secondary)]\">\n {reportText}\n </pre>\n </Disclosure>\n )}\n </>\n }\n />\n );\n}\n"],"mappings":";AA+gBM,SAgFE,UAhFF,KAgFE,YAhFF;AA/gBN,SAAS,iBAAiB;AAE1B,SAAS,eAAe,WAAW,eAAe;AAClD,SAAS,oBAAoB;AAC7B,SAAS,QAAQ,kBAAkB;AACnC,SAAS,kBAAkB;AAC3B,SAAS,kBAAkB;AA8BpB,MAAM,gCAAqD;AAAA,EAChE,OAAO;AAAA,EACP,SAAS;AAAA,EACT,OAAO;AAAA,EACP,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,eAAe;AAAA,EACf,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,YAAY;AAAA,EACZ,UAAU;AAAA,EACV,YAAY,CAAC,cAAc,eAAe,SAAS;AACrD;AAiBA,SAAS,KAAK,KAAwC;AACpD,MAAI;AACF,UAAM,IAAI,IAAI;AACd,WAAO,OAAO,MAAM,WAAW,IAAI,MAAM,UAAa,MAAM,OAAO,SAAY,OAAO,CAAC;AAAA,EACzF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,eAAe,OAAsC;AACnE,MAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAC/C,UAAM,IAAI;AACV,WAAO;AAAA,MACL,MAAM,KAAK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AACxD,QAAM,YAAY,QAAQ,UAAU,GAAG,QAAQ,IAAI,KAAK,QAAQ,OAAO,KAAK,QAAQ;AAEpF,QAAM,eACJ,oBAAC,UAAoB,SAAS,SAAS,UAAU,cAAc,WAAW,SAAS,YAChF,eAAK,UADI,QAEZ;AAIF,QAAM,cAAc,QAAQ,OAC1B,oBAAC,UAAmB,SAAS,SAAS,UAAU,YAAY,aAAa,SAAS,OAC/E,eAAK,SADI,OAEZ;AAGF,SACE;AAAA,IAAC;AAAA;AAAA,MACC,MAAK;AAAA,MACL,MAAM,SAAS,UAAU,WAAW;AAAA,MACpC;AAAA,MACA;AAAA,MACA,MAAM,oBAAC,QAAK;AAAA,MACZ;AAAA,MACA;AAAA,MACA,QACE,iCACG;AAAA,uBAAe,SAAS;AAAA;AAAA,QAGvB;AAAA,UAAC;AAAA;AAAA,YACC,sBAAmB;AAAA,YACnB,WAAU;AAAA,YAET;AAAA;AAAA,QACH;AAAA,QAED,WAAW,WACV,oBAAC,OAAE,WAAU,iCACV,sBAAY,KAAK,WAAW,SAAS,IAAI,KAAK,UACjD;AAAA,QAED,SAAS,UAAU,CAAC,aAAa,YAAY,IAAI,CAAC,cAAc,WAAW;AAAA,QAC3E,cAAc,eAAe,QAAQ,WAAW,WAC/C,oBAAC,cAAW,SAAQ,SAAQ,eAAc,SAAQ,OAAO,KAAK,YAAY,MAAM,YAAY;AAAA,QAE7F;AAAA,QACA,eAAe,eAAe,QAC7B,oBAAC,cAAW,SAAQ,QAAO,OAAO,KAAK,SAAS,WAAU,yBACxD,8BAAC,SAAI,WAAU,+FACZ,sBACH,GACF;AAAA,SAEJ;AAAA;AAAA,EAEJ;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../../src/components/error-boundary.tsx"],"sourcesContent":["import { Component } from \"react\";\nimport type { ErrorInfo, ReactNode } from \"react\";\nimport { AlertTriangle, RefreshCw, WifiOff } from \"lucide-react\";\nimport { useKitLabels } from \"../i18n/kit-labels\";\nimport { Button, EmptyState } from \"./ui\";\nimport { CopyButton } from \"./copy-button\";\nimport { Disclosure } from \"./disclosure\";\n\n/** The words of the default fallback. */\nexport interface ErrorBoundaryLabels {\n /** The fallback's heading. */\n title: string;\n /** The line under it. */\n message: string;\n /** The button that clears the error and renders the children again. */\n retry: string;\n /** The disclosure that opens the full error report (`showDetails`). */\n details: string;\n /** The button that reloads the whole page (0.13). */\n reload: string;\n /** Heading when a lazy chunk failed to load while online — a deploy replaced the\n * files this page was built from (0.13). */\n updateTitle: string;\n updateMessage: string;\n /** Heading when the browser says it is offline (0.13). */\n offlineTitle: string;\n offlineMessage: string;\n /** The copy button's words: what it copies is the plain-text report (0.13). */\n copyReport: string;\n /** Shown once `onReport` has filed the crash and returned no reference (0.13). */\n reported: string;\n /** Shown once `onReport` has filed the crash under a reference — rendered as the\n * app returned it, so return `\"#123\"` if the hash belongs to it (0.13). */\n reportedAs: (reference: string) => string;\n}\n\nexport const DEFAULT_ERROR_BOUNDARY_LABELS: ErrorBoundaryLabels = {\n title: \"Something went wrong\",\n message: \"This part of the page could not be shown. Try again, or reload the page.\",\n retry: \"Try again\",\n details: \"Error details\",\n reload: \"Reload\",\n updateTitle: \"A new version is available\",\n updateMessage: \"Part of the app has changed since this page was loaded. Reload to get the new version.\",\n offlineTitle: \"You’re offline\",\n offlineMessage: \"This page could not be loaded without a connection. Reconnect, then reload the page.\",\n copyReport: \"Copy error report\",\n reported: \"This error has been reported automatically.\",\n reportedAs: (reference) => `Reported as ${reference}`,\n};\n\n/**\n * What was thrown, as flat strings, read ONCE when it arrives.\n *\n * React stores whatever was thrown, hostile or not — `throw { get message() { throw … } }`,\n * `throw { name: Symbol() }`, `throw undefined` — and reading one of those during the\n * fallback's own render would throw INSIDE the boundary, escalating to the next one up\n * (keksdose's error-boundary.tsx learned this as feedback #160: at the app level there is\n * none, and the result is the white screen the boundary exists to prevent).\n */\nexport interface ErrorBoundaryDetails {\n name: string;\n message: string;\n stack?: string;\n}\n\nfunction read(get: () => unknown): string | undefined {\n try {\n const v = get();\n return typeof v === \"string\" ? v : v === undefined || v === null ? undefined : String(v);\n } catch {\n return undefined;\n }\n}\n\n/** `JSON.stringify` that never throws (a cycle, a BigInt, a hostile getter) and never\n * returns more than 500 characters. \"\" when there is nothing to say. */\nfunction safeJson(value: unknown): string {\n try {\n const json = JSON.stringify(value);\n if (!json || json === \"{}\") return \"\";\n return json.length > 500 ? `${json.slice(0, 499)}…` : json;\n } catch {\n return \"\";\n }\n}\n\n/** {@link ErrorBoundaryDetails} of any thrown value, without ever throwing. */\nexport function describeThrown(error: unknown): ErrorBoundaryDetails {\n if (typeof error === \"object\" && error !== null) {\n const e = error as { name?: unknown; message?: unknown; stack?: unknown };\n const message = read(() => e.message) ?? \"\";\n return {\n name: read(() => e.name) ?? \"Error\",\n // `throw { code: 500 }` has no message, and an empty line leaves crash triage with\n // nothing (keksdose G3a; its old reporter filed `{\"code\":500}`). Such a value is\n // quoted as JSON instead, capped, and never at the cost of a throw.\n message: message || (error instanceof Error ? \"\" : safeJson(error)),\n stack: read(() => e.stack),\n };\n }\n return { name: \"Error\", message: read(() => error) ?? \"\" };\n}\n\n/**\n * Is this a failed lazy import — a route chunk that did not arrive?\n *\n * Two causes, and neither is a bug in the page: the device is offline and the chunk was\n * never cached, or a deploy replaced the hashed files the running page still points at.\n * Both are cured by a reload and by nothing else — `React.lazy` caches the rejected\n * import, so Try again re-throws the same error without fetching. The patterns are\n * keksdose's (crash-report.ts), which covers Vite (\"dynamically imported module\",\n * \"module script failed\"), webpack (\"ChunkLoadError\", \"Loading chunk\") and the bare\n * `fetch` failure a service worker hands back.\n *\n * Never throws: it runs inside the fallback's own render, where a throw is a white\n * screen. An error it cannot read is not a chunk failure.\n */\nexport function isChunkLoadError(\n error: { name?: string | null; message?: string | null } | null | undefined,\n): boolean {\n try {\n const s = `${error?.name ?? \"\"} ${error?.message ?? \"\"}`;\n return /ChunkLoadError|dynamically imported module|module script failed|Loading chunk|Failed to fetch/i.test(s);\n } catch {\n return false;\n }\n}\n\n/**\n * Everything a crash report carries, read once when the boundary catches.\n *\n * Plain strings only, so it survives `JSON.stringify` into an app's crash endpoint as is\n * and {@link formatCrashReport} can print it without a single guard. The wording of the\n * printed report is English on purpose: it is read by whoever fixes the bug, not by the\n * user who copies it, and a report in nine languages cannot be searched.\n */\nexport interface CrashReport {\n /** The thrown value's `name` (\"TypeError\"), \"Error\" for a non-object. */\n name: string;\n message: string;\n stack?: string;\n /** React's component stack from `componentDidCatch` — the part that names the\n * component, which a minified JS stack no longer does. */\n componentStack?: string;\n /** `pathname + search` at the moment of the crash. The search may carry what the\n * user typed — see `redact`. */\n page: string;\n /** ISO 8601, UTC. */\n time: string;\n userAgent: string;\n /** The boundary's `appVersion` prop. */\n appVersion?: string;\n /** The boundary's `placement` prop (\"app\", \"page\", \"widget\"): which boundary caught\n * it, so triage can tell a whole-app crash from one page's (keksdose G3b). */\n placement?: string;\n /** `navigator.onLine` at the moment of the crash; left out where there is none. */\n online?: boolean;\n /** {@link isChunkLoadError} of the thrown value. Such a crash is never handed to\n * `onReport` — it is a deploy or a dropped connection, not a defect — but it is\n * still in the copied report. */\n chunkLoad: boolean;\n /** The boundary's `reportExtras()`, stringified. */\n extras: Record<string, string>;\n}\n\n/**\n * The report as one plain-text block — what the copy button puts on the clipboard and\n * the details disclosure shows.\n *\n * lenkbank's layout, because that is the one that was already being pasted into\n * feedback messages: the error line first (it is what a search for the bug matches),\n * then where / when / what, then the two stacks.\n */\nexport function formatCrashReport(report: CrashReport): string {\n const lines = [\n report.message ? `${report.name}: ${report.message}` : report.name,\n `Page: ${report.page}`,\n `Time: ${report.time}`,\n `User agent: ${report.userAgent}`,\n ];\n if (report.appVersion) lines.push(`App version: ${report.appVersion}`);\n if (report.placement) lines.push(`Placement: ${report.placement}`);\n if (report.online === false) lines.push(\"Online: no\");\n for (const [key, value] of Object.entries(report.extras)) lines.push(`${key}: ${value}`);\n if (report.stack) lines.push(\"\", \"Stack:\", report.stack.trim());\n if (report.componentStack) lines.push(\"\", \"Component stack:\", report.componentStack.trim());\n return lines.join(\"\\n\");\n}\n\n/**\n * A key for \"the same crash again\": the error's name and message and the first frames\n * of its stack.\n *\n * Page-load local, not a server-side grouping key (keksdose's crash-report.ts draws the\n * same line): its only job is to stop one page load filing one bug twice — React's dev\n * StrictMode, a Try again that crashes again, a render loop that trips the boundary many\n * times a second. The page and the time are left out on purpose: the same bug on two\n * routes is still one bug.\n */\nexport function crashFingerprint(\n report: Pick<CrashReport, \"name\" | \"message\" | \"stack\"> & Pick<Partial<CrashReport>, \"placement\">,\n): string {\n const frames = (report.stack ?? \"\").split(\"\\n\").slice(0, 4).join(\"|\");\n // The placement is part of it (keksdose G3b): the same error caught by the page\n // boundary and, after Try again fails, by the app boundary is two facts for triage.\n const where = report.placement ? `${report.placement}::` : \"\";\n return `${where}${report.name}::${report.message}::${frames}`;\n}\n\n/**\n * What `onReport` may resolve with. `{ reference }` is shown (\"Reported as …\");\n * nothing (or `{}`) means filed without one. `{ filed: false }` says the app decided NOT\n * to file (a demo session, a hot-reload artefact, a report buffered for later): the\n * screen then claims nothing and keeps the copy button — claiming a report that was\n * never sent is the same false statement as hiding one that was.\n */\nexport type CrashReportResult = { reference?: string; filed?: boolean } | void;\n\ninterface Filing {\n filed: boolean;\n reference?: string;\n}\n\nconst NOT_FILED: Filing = { filed: false };\n\n/** A render loop can trip a boundary dozens of times a second with a different message\n * each time (a counter in it); without a ceiling the first bad deploy files hundreds of\n * rows. keksdose's number. */\nconst MAX_REPORTS_PER_PAGE_LOAD = 5;\n\n/** Fingerprint → the one filing for it in this page load. Module scope IS the page\n * load: a reload starts it empty. A duplicate gets the first filing's promise, so the\n * second screen shows the same reference instead of claiming nothing. */\nconst filings = new Map<string, Promise<Filing>>();\n\nfunction settle(out: unknown): Filing {\n try {\n if (out && typeof out === \"object\") {\n const o = out as { filed?: unknown; reference?: unknown };\n if (o.filed === false) return NOT_FILED;\n const reference = typeof o.reference === \"string\" && o.reference ? o.reference : undefined;\n return { filed: true, reference };\n }\n return { filed: true };\n } catch {\n return NOT_FILED;\n }\n}\n\n/** Hand the report to the app, once per fingerprint per page load, and never throw —\n * not for a synchronous throw, a rejection, or a hostile thenable. */\nfunction fileOnce(report: CrashReport, onReport: (report: CrashReport) => unknown): Promise<Filing> {\n const key = crashFingerprint(report);\n const known = filings.get(key);\n if (known) return known;\n if (filings.size >= MAX_REPORTS_PER_PAGE_LOAD) return Promise.resolve(NOT_FILED);\n let filing: Promise<Filing>;\n try {\n filing = Promise.resolve(onReport(report)).then(settle, () => NOT_FILED);\n } catch {\n filing = Promise.resolve(NOT_FILED);\n }\n // Claimed before the first await: two catches in the same tick (StrictMode) must not\n // both get past the lookup above.\n filings.set(key, filing);\n return filing;\n}\n\nfunction isOffline(): boolean {\n try {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n } catch {\n return false;\n }\n}\n\nfunction reloadPage(): void {\n try {\n window.location.reload();\n } catch {\n /* nothing left to do from here */\n }\n}\n\n/** What a render-prop `fallback` is handed. */\nexport interface ErrorBoundaryFallbackProps {\n /** The thrown value, as it was thrown. Read it with care — see {@link describeThrown}. */\n error: unknown;\n details: ErrorBoundaryDetails;\n /** Clear the error and render the children again. */\n reset: () => void;\n /** The crash report, once `componentDidCatch` has built it (null on the very first\n * render of the fallback, which happens before it). Already `redact`ed. */\n report: CrashReport | null;\n}\n\nexport interface ErrorBoundaryProps {\n children?: ReactNode;\n /** Replaces the default fallback: a node, or a render function handed the error and\n * a `reset`. The same rule applies to it as to the default: see the component docs. */\n fallback?: ReactNode | ((props: ErrorBoundaryFallbackProps) => ReactNode);\n /** Called once per caught error with the raw value — log it. A throw from it is\n * swallowed: the boundary is the last thing standing. For filing a report, prefer\n * `onReport`, which gets the finished report, dedupe and the reference on screen. */\n onError?: (error: unknown, info: ErrorInfo) => void;\n /** Called when the error is cleared, by Try again, `reset` or a `resetKeys` change —\n * drop a cache, refetch. */\n onReset?: () => void;\n /**\n * When any of these changes (compared with `Object.is`) AFTER an error was caught, the\n * error is cleared and the children render again — a change in the same update that\n * threw does not count (it is what the error was shown under) — pass the route path so leaving a broken page does not\n * carry its fallback to the next one (keksdose's `resetKey`).\n */\n resetKeys?: ReadonlyArray<unknown>;\n /** Quote the error's `name: message` in a monospace box under the hint. Default on\n * (0.13): three sentences true of every crash identify none of them, and the one\n * line that does is what a user can read out or screenshot (lenkbank P7). Not shown\n * for a chunk-load / offline screen, where the message is a URL that explains\n * nothing the title does not. */\n showMessage?: boolean;\n /** A collapsed disclosure holding the full plain-text report. Default on since 0.13\n * (it was an opt-in showing name, message and stack): closed, it costs one line, and\n * it is where a support conversation asks the user to look. */\n showDetails?: boolean;\n /** The copy button for the plain-text report (the kit's CopyButton, which says when\n * the clipboard refused). Default on. Hidden once `onReport` has filed the crash —\n * there is nothing left to paste anywhere — and shown again whenever it did not. */\n copyReport?: boolean;\n /** The app's version, printed in the report — the first question on every crash. */\n appVersion?: string;\n /** Which boundary this is — \"app\" at the root, \"page\" in the layout — carried into\n * the report (`placement`) and its fingerprint, so `onReport` needs no closure to say\n * where the crash was caught (keksdose G3b). */\n placement?: string;\n /** More `key: value` lines for the report, read when the boundary catches (a tenant\n * id, the feature flags). A throw from it is swallowed and the lines are left out. */\n reportExtras?: () => Record<string, string>;\n /**\n * Rewrite the report before anything sees it: the screen, the clipboard and\n * `onReport` all get the returned one.\n *\n * THE REPORT IS STRUCTURE, NEVER CONTENT — and only the app knows which of its query\n * params hold content. keksdose's register put the free-text search in `?q=` and payee\n * names in the `f.*` filters, and its crash channel sent them in the clear to a column\n * every admin reads (crash-report.ts `safeUrl`). The cure there is an ALLOW-list, so a\n * param added later is dropped until somebody decides otherwise — rebuild `page`\n * from `new URL(r.page, location.origin)`, keeping only the listed `searchParams`.\n * `extras` are the app's own and need no second pass. A throw from `redact` falls\n * back to the pathname alone and no extras — failing closed.\n *\n * The same holds inside `onReport`, which is the other place to do it: clamp fields\n * to what the endpoint accepts, drop what it must not store. The kit cannot know.\n */\n redact?: (report: CrashReport) => CrashReport;\n /**\n * File the report automatically. Called from `componentDidCatch`, at most once per\n * {@link crashFingerprint} per page load (and at most five times in all), never for a\n * chunk-load error. It can NOT throw into the boundary: a synchronous throw and a\n * rejection both read as \"not filed\", and the copy button stays.\n *\n * Resolve with `{ reference }` and the screen says \"Reported as …\" instead of the copy\n * button; see {@link CrashReportResult} for \"filed without a reference\" and \"decided not\n * to file\". Whatever the app's reporter does, it must do without the router, the query\n * client or the auth store's hooks — a bare `fetch` with `keepalive`, so it survives\n * the reload the user is about to press (keksdose crash-report.ts `post`).\n */\n onReport?: (report: CrashReport) => Promise<CrashReportResult> | CrashReportResult;\n /** The app's own escape hatches, beside Reload / Try again — keksdose's \"Clear local\n * data\" for a poisoned persisted cache that no in-app action could otherwise break.\n * A full-width hint under it: wrap it in `<div className=\"basis-full\">`. */\n actions?: ReactNode;\n /** The default fallback's heading level. Default `h2`: the fallback often IS the page. */\n headingAs?: \"h2\" | \"h3\" | \"h4\" | \"h5\" | \"h6\";\n /** Classes for the default fallback's box (`m-8 min-h-[400px]`, kastlan). */\n className?: string;\n labels?: Partial<ErrorBoundaryLabels>;\n}\n\ntype FilingState = \"none\" | \"pending\" | \"filed\" | \"failed\";\n\ninterface ErrorBoundaryState {\n /** A flag of its own, so `throw undefined` is still an error shown. */\n failed: boolean;\n error: unknown;\n details: ErrorBoundaryDetails | null;\n report: CrashReport | null;\n filing: FilingState;\n reference: string | undefined;\n}\n\nconst CLEAR: ErrorBoundaryState = {\n failed: false,\n error: null,\n details: null,\n report: null,\n filing: \"none\",\n reference: undefined,\n};\n\nfunction keysChanged(a: ReadonlyArray<unknown> | undefined, b: ReadonlyArray<unknown> | undefined): boolean {\n if (a === b) return false;\n if (!a || !b || a.length !== b.length) return true;\n return a.some((v, i) => !Object.is(v, b[i]));\n}\n\nfunction currentPage(): { page: string; path: string } {\n try {\n const { pathname, search } = window.location;\n return { page: `${pathname}${search}`, path: pathname };\n } catch {\n return { page: \"\", path: \"\" };\n }\n}\n\nfunction buildReport(details: ErrorBoundaryDetails, componentStack: string | undefined, props: ErrorBoundaryProps): CrashReport {\n const { page, path } = currentPage();\n const extras: Record<string, string> = {};\n try {\n const more = props.reportExtras?.();\n if (more) for (const [k, v] of Object.entries(more)) extras[k] = String(v);\n } catch {\n /* documented: the lines are left out */\n }\n let userAgent = \"\";\n let online: boolean | undefined;\n try {\n userAgent = navigator.userAgent;\n online = typeof navigator.onLine === \"boolean\" ? navigator.onLine : undefined;\n } catch {\n /* no navigator (SSR, a worker test) */\n }\n const report: CrashReport = {\n name: details.name,\n message: details.message,\n stack: details.stack,\n componentStack: componentStack ?? undefined,\n page,\n time: new Date().toISOString(),\n userAgent,\n appVersion: props.appVersion,\n placement: props.placement,\n online,\n chunkLoad: isChunkLoadError(details),\n extras,\n };\n if (!props.redact) return report;\n try {\n return props.redact(report);\n } catch {\n // Fail closed: an app that asked for redaction must not get the unredacted page.\n return { ...report, page: path, extras: {} };\n }\n}\n\n/**\n * Catch a render error below it and show ONE crash screen instead of an empty page.\n *\n * The three apps each built one. kastlan's and keksdose's sat on `EmptyState\n * tone=\"danger\"`; lenkbank's quoted the error and offered a plain-text report to copy;\n * keksdose's filed the crash itself, told a lazy-chunk failure apart as \"offline\", and\n * offered \"clear local data\" when a poisoned cache made Retry useless (feedback #160).\n * This is all of that, so the apps reduce to\n * `<ErrorBoundary resetKeys={[pathname]} appVersion={__VERSION__} />` plus, for an app\n * with a crash endpoint, `onReport` and `actions`:\n *\n * - the error's `name: message`, quoted (`showMessage`);\n * - Try again (reset the boundary) AND Reload (the page) — Try again alone re-renders\n * the same subtree from the same state, which a deterministic crash survives;\n * - a chunk-load error or an offline browser gets its own title and Reload first\n * (\"A new version is available\" / \"You're offline\");\n * - the copy button and the report in a disclosure; `onReport` for filing it, deduped\n * per page load, with its reference on screen.\n *\n * THE RULE for this fallback — and for a `fallback` or `actions` an app passes in: it\n * must not depend on the router, the query client or the auth store. A crash is exactly\n * when those may be what broke, and a fallback that throws escalates to the next\n * boundary up — at the app level there is none, and the user gets the white screen this\n * exists to prevent. So no `useNavigate`, no `useQuery`, no `useAuth()` in it; reload\n * with `window.location`, not the router. The kit's own label hooks are the one context\n * it does read (`errorBoundary.*` from `UiKitProvider`), and they degrade to the English\n * defaults when there is no provider above — which is why the app-level boundary may\n * sit OUTSIDE the provider and still render.\n *\n * The fallback is `role=\"alert\"`: a page replaced by an error is news, and a reader\n * that was on it is told.\n */\nexport class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n state: ErrorBoundaryState = CLEAR;\n\n /** Bumped by every catch and reset, so a filing that settles after the screen moved\n * on (Try again, a route change, a second crash) does not write into it. */\n private generation = 0;\n\n /**\n * Forget which crashes this page load has filed, and the count towards the cap.\n *\n * For tests: the dedupe lives in module scope because a page load is what it spans,\n * and a test file is one page load — so without this, the sixth test that files a\n * report finds the cap reached and `onReport` never called. Call it in `beforeEach`.\n * Never needed in an app: a reload is the reset.\n */\n static forgetReports(): void {\n filings.clear();\n }\n\n static getDerivedStateFromError(error: unknown): Partial<ErrorBoundaryState> {\n return { failed: true, error, details: describeThrown(error), report: null, filing: \"none\", reference: undefined };\n }\n\n componentDidCatch(error: unknown, info: ErrorInfo): void {\n try {\n this.props.onError?.(error, info);\n } catch {\n /* documented: a logger must not take the fallback down */\n }\n const details = this.state.details ?? describeThrown(error);\n const report = buildReport(details, info.componentStack ?? undefined, this.props);\n const { onReport } = this.props;\n const willFile = onReport !== undefined && !report.chunkLoad;\n const generation = ++this.generation;\n this.setState({ report, filing: willFile ? \"pending\" : \"none\", reference: undefined });\n if (!willFile) return;\n void fileOnce(report, onReport).then((filing) => {\n if (generation !== this.generation) return;\n this.setState(\n filing.filed ? { filing: \"filed\", reference: filing.reference } : { filing: \"failed\", reference: undefined },\n );\n });\n }\n\n componentDidUpdate(prev: ErrorBoundaryProps, prevState: ErrorBoundaryState): void {\n // Only a change AFTER the error was caught clears it (react-error-boundary's rule).\n // `prevState.failed` is false in the update that caught it: that update may well be\n // the one that changed the keys too — a navigation to a page that throws, with\n // `resetKeys={[pathname]}` — and resetting then would fire `onReset` for nothing and\n // render the failing child a second time. From then on `prev.resetKeys` are the\n // keys the error was shown under, so any change clears it.\n if (this.state.failed && prevState.failed && keysChanged(prev.resetKeys, this.props.resetKeys)) {\n this.reset();\n }\n }\n\n reset = (): void => {\n this.generation++;\n this.props.onReset?.();\n this.setState(CLEAR);\n };\n\n render(): ReactNode {\n const { failed, error, details, report, filing, reference } = this.state;\n if (!failed || !details) return this.props.children;\n const { fallback } = this.props;\n if (typeof fallback === \"function\") return fallback({ error, details, reset: this.reset, report });\n if (fallback !== undefined) return fallback;\n return (\n <ErrorFallback\n details={details}\n report={report}\n filing={filing}\n reference={reference}\n reset={this.reset}\n showMessage={this.props.showMessage ?? true}\n showDetails={this.props.showDetails ?? true}\n copyReport={this.props.copyReport ?? true}\n actions={this.props.actions}\n headingAs={this.props.headingAs ?? \"h2\"}\n className={this.props.className}\n labels={this.props.labels}\n />\n );\n }\n}\n\nfunction ErrorFallback({\n details,\n report,\n filing,\n reference,\n reset,\n showMessage,\n showDetails,\n copyReport,\n actions,\n headingAs,\n className,\n labels,\n}: {\n details: ErrorBoundaryDetails;\n report: CrashReport | null;\n filing: FilingState;\n reference: string | undefined;\n reset: () => void;\n showMessage: boolean;\n showDetails: boolean;\n copyReport: boolean;\n actions?: ReactNode;\n headingAs: NonNullable<ErrorBoundaryProps[\"headingAs\"]>;\n className?: string;\n labels?: Partial<ErrorBoundaryLabels>;\n}) {\n const text = useKitLabels(\"errorBoundary\", DEFAULT_ERROR_BOUNDARY_LABELS, labels);\n const chunk = isChunkLoadError(details);\n // Offline first, as keksdose has it: offline, a chunk failure is the connection, and\n // any other crash most likely a request that could not be made — either way \"reload\n // once you are back\" is the advice, and \"a new version\" would be a false one.\n const mode = isOffline() ? \"offline\" : chunk ? \"update\" : \"error\";\n const title = mode === \"offline\" ? text.offlineTitle : mode === \"update\" ? text.updateTitle : text.title;\n const hint = mode === \"offline\" ? text.offlineMessage : mode === \"update\" ? text.updateMessage : text.message;\n const Icon = mode === \"offline\" ? WifiOff : mode === \"update\" ? RefreshCw : AlertTriangle;\n const reportText = report ? formatCrashReport(report) : null;\n const errorLine = details.message ? `${details.name}: ${details.message}` : details.name;\n\n const reloadButton = (\n <Button key=\"reload\" variant={mode === \"error\" ? \"secondary\" : \"primary\"} onClick={reloadPage}>\n {text.reload}\n </Button>\n );\n // Not after a chunk failure: `React.lazy` keeps the rejected import, so Try again\n // could only throw the same error again.\n const retryButton = chunk ? null : (\n <Button key=\"retry\" variant={mode === \"error\" ? \"primary\" : \"secondary\"} onClick={reset}>\n {text.retry}\n </Button>\n );\n\n return (\n <EmptyState\n role=\"alert\"\n tone={mode === \"error\" ? \"danger\" : undefined}\n headingAs={headingAs}\n className={className}\n icon={<Icon />}\n title={title}\n hint={hint}\n action={\n <>\n {showMessage && mode === \"error\" && (\n // A quotation, not prose: left-aligned and monospaced, so it reads as the\n // program's words and can be read out or screenshotted verbatim.\n <p\n data-error-message=\"\"\n className=\"-mt-1 mb-1 basis-full whitespace-pre-wrap break-words rounded-md border border-[var(--danger-border)] bg-[var(--danger-bg)] px-3 py-2 text-start font-mono text-xs text-[var(--text-primary)]\"\n >\n {errorLine}\n </p>\n )}\n {filing === \"filed\" && (\n <p className=\"-mt-1 mb-1 basis-full text-xs\">\n {reference ? text.reportedAs(reference) : text.reported}\n </p>\n )}\n {mode === \"error\" ? [retryButton, reloadButton] : [reloadButton, retryButton]}\n {copyReport && reportText !== null && filing !== \"filed\" && (\n <CopyButton variant=\"label\" buttonVariant=\"ghost\" label={text.copyReport} text={reportText} />\n )}\n {actions}\n {showDetails && reportText !== null && (\n <Disclosure variant=\"bare\" title={text.details} className=\"basis-full text-start\">\n <pre className=\"max-h-60 overflow-auto whitespace-pre-wrap break-words text-xs text-[var(--text-secondary)]\">\n {reportText}\n </pre>\n </Disclosure>\n )}\n </>\n }\n />\n );\n}\n"],"mappings":";AA6iBM,SAg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