@eifi1/ui-kit 0.15.0 → 0.15.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chart.d.ts +2 -1
- package/dist/components/alert-banner.js +15 -2
- package/dist/components/alert-banner.js.map +1 -1
- package/dist/components/chart.js +10 -3
- package/dist/components/chart.js.map +1 -1
- package/dist/components/facing-pair.d.ts +1 -0
- package/dist/components/series-chart-budget.d.ts +60 -0
- package/dist/components/series-chart-budget.js +56 -0
- package/dist/components/series-chart-budget.js.map +1 -0
- package/dist/components/series-chart.d.ts +54 -2
- package/dist/components/series-chart.js +71 -13
- package/dist/components/series-chart.js.map +1 -1
- package/dist/components/slider.js +6 -2
- package/dist/components/slider.js.map +1 -1
- package/dist/components/table.d.ts +12 -1
- package/dist/components/table.js +38 -0
- package/dist/components/table.js.map +1 -1
- package/dist/components/toggle-group.d.ts +9 -0
- package/dist/components/toggle-group.js +4 -1
- package/dist/components/toggle-group.js.map +1 -1
- package/dist/components/ui.js +26 -22
- package/dist/components/ui.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/package.json +1 -1
- package/src/components/alert-banner.tsx +19 -2
- package/src/components/chart.tsx +10 -3
- package/src/components/series-chart-budget.ts +121 -0
- package/src/components/series-chart.tsx +152 -8
- package/src/components/slider.tsx +6 -2
- package/src/components/table.tsx +59 -0
- package/src/components/toggle-group.tsx +13 -1
- package/src/components/ui.tsx +13 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/slider.tsx"],"sourcesContent":["import { forwardRef, useId } from \"react\";\nimport type { CSSProperties, ChangeEvent, InputHTMLAttributes, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\n\n/**\n * A range control on a native `<input type=\"range\">`.\n *\n * Lenkbank wrote the first one (`shared/ui/slider-field.tsx`) and then the case for\n * moving it here (`docs/ui-kit-slider-proposal.md`). This is that proposal's \"stage 1\"\n * primitive — the track, the thumb, the scale and the accessibility — plus the label\n * line and tick marks its SpeedSlider needed. The four decisions it argues should be\n * made once are made here, and each carries its note below:\n *\n * 1. a logarithmic scale whose far-left stop means exactly zero ({@link SliderProps.zeroStop});\n * 2. `aria-valuetext`, so a log track does not announce its 0–1 position as the value;\n * 3. a 24px pointer target, which needs the track and thumb drawn separately;\n * 4. the number is the truth and the track a view of it: a value outside `min`–`max`\n * is kept and the thumb pins at the end — nothing here clamps what it was given.\n *\n * Controlled only, like `ToggleGroup` and `NumberInput`: there is no uncontrolled mode\n * to get wrong, and neither app wants one. The package does no number formatting and\n * holds no locale — `formatValue` is how the caller's `Intl` result gets in.\n *\n * Not here, deliberately (the proposal's list): two thumbs, vertical orientation, and\n * a number box. A `NumberInput` goes in the `readout` slot when a typed value is\n * wanted beside the track.\n */\n\n/** On a log scale with {@link SliderProps.zeroStop}, the share of the track that is\n * the \"off\" stop. The first position to its right is `min`. */\nconst ZERO_STOP = 0.02;\n\n/** Position resolution on a log track — 1000 stops, fine enough that a drag reads as\n * continuous. PageUp/PageDown still cross a tenth of the track at a time. */\nconst LOG_STEP = 0.001;\n\n/**\n * Where a value sits on a logarithmic track, 0–1.\n *\n * With `zeroStop`, zero and below is 0 and the decades between `min` and `max` are\n * mapped onto the rest; without it, `min` is the far left. A value past either end\n * pins there — that is the DISPLAY clamping, never the value's.\n */\nexport function toLogPosition(value: number, min: number, max: number, zeroStop = true): number {\n if (value <= 0) return 0;\n const share = Math.log(Math.max(value, min) / min) / Math.log(max / min);\n const clamped = Math.min(1, Math.max(0, share));\n return zeroStop ? ZERO_STOP + (1 - ZERO_STOP) * clamped : clamped;\n}\n\n/** The inverse of {@link toLogPosition}: the value at a track position. */\nexport function fromLogPosition(position: number, min: number, max: number, zeroStop = true): number {\n if (zeroStop) {\n if (position < ZERO_STOP) return 0;\n return min * Math.pow(max / min, (position - ZERO_STOP) / (1 - ZERO_STOP));\n }\n return min * Math.pow(max / min, position);\n}\n\n// The input is the pointer target, so its box is `h-6` (24px, WCAG 2.5.8) and the\n// track that LOOKS like a track is a 6px strip drawn inside it. Once the box is taller\n// than the track its background cannot be the track, and with `appearance-none`\n// nothing else draws one — measured in Chromium by Lenkbank, that is a bare thumb\n// floating on nothing, in the browser's blue. Hence the vendor pseudo-elements: the\n// two engines share no selector for either half, so each half is spelt twice.\n//\n// The fill up to the thumb: WebKit has no progress pseudo-element, so its track is a\n// two-stop gradient that breaks at `--slider-fill` (set inline from the position), and\n// the gradient runs the other way in a right-to-left document, where the native range\n// runs the other way too. Firefox draws the fill itself with `::-moz-range-progress`,\n// which follows the direction on its own.\n//\n// The thumb's `-mt-[5px]` centres a 16px thumb on a 6px track: WebKit lays the thumb\n// out from the track's top edge, Firefox centres it, so only one carries the offset.\n//\n// The focus ring goes on the THUMB, not the box: the box is the full width of the\n// row, and a ring round all of it says \"this row is focused\" rather than \"the handle\n// you are about to move is\". Offset in the surface colour, because the thumb is\n// --brand and a --brand ring touching it would be invisible.\nconst TRACK = [\n \"block h-6 w-full cursor-pointer appearance-none bg-transparent focus:outline-none disabled:cursor-not-allowed\",\n // WebKit / Blink\n \"[&::-webkit-slider-runnable-track]:h-1.5 [&::-webkit-slider-runnable-track]:rounded-full\",\n \"[&::-webkit-slider-runnable-track]:bg-[linear-gradient(to_right,var(--brand)_var(--slider-fill),var(--border-strong)_var(--slider-fill))]\",\n \"rtl:[&::-webkit-slider-runnable-track]:bg-[linear-gradient(to_left,var(--brand)_var(--slider-fill),var(--border-strong)_var(--slider-fill))]\",\n \"[&::-webkit-slider-thumb]:-mt-[5px] [&::-webkit-slider-thumb]:size-4 [&::-webkit-slider-thumb]:appearance-none\",\n \"[&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-[var(--brand)] [&::-webkit-slider-thumb]:shadow\",\n \"focus-visible:[&::-webkit-slider-thumb]:ring-2 focus-visible:[&::-webkit-slider-thumb]:ring-[var(--brand)]\",\n \"focus-visible:[&::-webkit-slider-thumb]:ring-offset-2 focus-visible:[&::-webkit-slider-thumb]:ring-offset-[var(--bg-surface)]\",\n // Firefox\n \"[&::-moz-range-track]:h-1.5 [&::-moz-range-track]:rounded-full [&::-moz-range-track]:bg-[var(--border-strong)]\",\n \"[&::-moz-range-progress]:h-1.5 [&::-moz-range-progress]:rounded-full [&::-moz-range-progress]:bg-[var(--brand)]\",\n \"[&::-moz-range-thumb]:size-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0\",\n \"[&::-moz-range-thumb]:bg-[var(--brand)] [&::-moz-range-thumb]:shadow\",\n \"focus-visible:[&::-moz-range-thumb]:ring-2 focus-visible:[&::-moz-range-thumb]:ring-[var(--brand)]\",\n \"focus-visible:[&::-moz-range-thumb]:ring-offset-2 focus-visible:[&::-moz-range-thumb]:ring-offset-[var(--bg-surface)]\",\n].join(\" \");\n\n/** A tick under the track. A bare number is a tick with no words. */\nexport interface SliderMark {\n value: number;\n /** Shown under the tick — \"30 km/h\", \"measured\". Visual only: the value itself is\n * announced through `aria-valuetext`, so the marks row is hidden from assistive\n * technology rather than read out as a list of numbers after the slider. */\n label?: ReactNode;\n}\n\nexport interface SliderProps\n extends Omit<\n InputHTMLAttributes<HTMLInputElement>,\n \"type\" | \"value\" | \"defaultValue\" | \"onChange\" | \"min\" | \"max\" | \"step\" | \"children\"\n > {\n /** The value. On a log scale this is the real value, not the track position. */\n value: number;\n /** The new value — a number, not the DOM event, like `ToggleGroup`. Fired on every\n * movement; debounce at the call site if each one costs a request. */\n onChange: (value: number) => void;\n /** The track's ends. Not a validity range: a `value` outside it is kept and the\n * thumb pins at the end (see the module note). On a log scale `min` must be\n * above zero — zero is what {@link zeroStop} is for. */\n min: number;\n max: number;\n /** Step on a linear scale (the native default is 1). Ignored on a log scale, which\n * steps by track position — a fixed step is wrong at one end of every decade. */\n step?: number;\n /**\n * How the track maps to the value. `\"log\"` for quantities that run over decades — a\n * proportional gain of 0.5 and one of 200 are both ordinary, and on a linear track\n * everything under a tenth of the range is the first pixel. Falls back to linear if\n * `min` is not above zero or `max` not above `min`, where a logarithm has no answer.\n */\n scale?: \"linear\" | \"log\";\n /**\n * Log scale only: the far-left stop means exactly 0 (\"off\"), and the first step to\n * its right is `min`. A logarithm cannot hold zero, and zero is often the question —\n * should there be an integral term at all? Default `true`; turn it off for a scale\n * where zero is meaningless (a zoom factor, a playback rate).\n */\n zeroStop?: boolean;\n /**\n * What a screen reader says for the value — \"12.5 mm\", \"Off\". Sets\n * `aria-valuetext`. Without it a log track would announce its 0–1 POSITION (\"0.63\"\n * for a gain of 12.5), so on a log scale the raw value is announced instead; pass\n * this for anything with a unit or a locale.\n */\n formatValue?: (value: number) => string;\n /** The words above the track, as a `<label for>`. Without it, pass `aria-label`. */\n label?: ReactNode;\n /** Something that belongs to the label rather than the value — in practice a\n * `FieldHint` \"?\". Rendered beside the label, outside the `<label>` element, so it\n * never becomes part of the slider's accessible name. */\n hint?: ReactNode;\n /** The value as the reader sees it, at the end of the label line — a formatted\n * number, or a `NumberInput` for typing one. Rendered as given. */\n readout?: ReactNode;\n /** Ticks under the track, at these values. Marks outside `min`–`max` are dropped. */\n marks?: ReadonlyArray<number | SliderMark>;\n /** Classes for the `<input>`. `className` styles the outer wrapper. */\n inputClassName?: string;\n}\n\n/**\n * A native range input with the kit's track and thumb, an optional label line\n * (`label`, `hint`, `readout`), tick `marks`, and a logarithmic `scale`.\n *\n * Every other prop reaches the `<input>` — `name`, `id`, `aria-*`, `data-*`, `onBlur`,\n * `onPointerUp` for commit-on-release — and `disabled` also fades the label line.\n */\nexport const Slider = forwardRef<HTMLInputElement, SliderProps>(function Slider(\n {\n value,\n onChange,\n min,\n max,\n step,\n scale = \"linear\",\n zeroStop = true,\n formatValue,\n label,\n hint,\n readout,\n marks,\n className,\n inputClassName,\n id,\n disabled,\n style,\n ...rest\n },\n ref,\n) {\n const generated = useId();\n const inputId = id ?? generated;\n const log = scale === \"log\" && min > 0 && max > min;\n\n // Everything the native element sees is a POSITION; everything the caller sees is a\n // value. On a linear track the two are the same number.\n const trackMin = log ? 0 : min;\n const trackMax = log ? 1 : max;\n const position = (v: number) => (log ? toLogPosition(v, min, max, zeroStop) : Math.min(max, Math.max(min, v)));\n const current = position(value);\n // 0–1 share of the track, for the fill and the marks. A zero-width range (min ===\n // max) has no share to speak of; call it empty rather than divide by zero.\n const share = (p: number) => (trackMax > trackMin ? (p - trackMin) / (trackMax - trackMin) : 0);\n const outOfRange = value < min || value > max;\n\n // `aria-valuetext` replaces the announced NUMBER and leaves the announced name\n // alone. The caller's words first (`formatValue`, then a hand-written\n // `aria-valuetext`); failing those, the real value wherever the\n // native one would lie — every log position, and a linear value the thumb is only\n // pinned at. `toPrecision(4)` keeps a log value from being read out to sixteen\n // digits; it is not formatting, and `formatValue` is how to get a locale.\n const valueText = formatValue\n ? formatValue(value)\n : (rest[\"aria-valuetext\"] ??\n (log || outOfRange ? String(Number(value.toPrecision(4))) : undefined));\n\n const handleChange = (e: ChangeEvent<HTMLInputElement>) => {\n const raw = Number(e.target.value);\n if (!log) return onChange(raw);\n // The gap between the zero stop and `min` has to be crossable by keyboard. An\n // arrow key moves one LOG_STEP, which from zero lands inside the gap — and a gap\n // that rounded to the nearer end would send it straight back to zero, trapping\n // a keyboard user at \"off\". So inside the gap, moving up from zero means `min`\n // and anything else means zero.\n if (zeroStop && raw > 0 && raw < ZERO_STOP) return onChange(value <= 0 ? min : 0);\n onChange(fromLogPosition(raw, min, max, zeroStop));\n };\n\n const normalizedMarks = (marks ?? [])\n .map((m) => (typeof m === \"number\" ? { value: m } : m))\n .filter((m) => m.value >= min && m.value <= max);\n const hasMarkLabels = normalizedMarks.some((m) => m.label !== undefined);\n\n const hasHeader = label !== undefined || hint !== undefined || readout !== undefined;\n const plainReadout = typeof readout === \"string\" || typeof readout === \"number\";\n\n return (\n <div className={cn(\"w-full\", disabled && \"opacity-60\", className)}>\n {hasHeader && (\n // `select-none` on the words is not a nicety (Lenkbank feedback #93): a\n // mousedown on text beside a range input starts Chrome's native text drag, the\n // cursor turns to no-drop and the thumb stops following the pointer for the\n // rest of the gesture. The readout is only made unselectable when it is plain\n // text — a NumberInput in that slot has to stay selectable to be editable.\n <div className=\"flex items-center gap-2\">\n {label !== undefined && (\n <label\n htmlFor={inputId}\n className=\"min-w-0 select-none text-xs font-medium text-[var(--text-secondary)]\"\n >\n {label}\n </label>\n )}\n {hint !== undefined && <span className=\"flex shrink-0 items-center\">{hint}</span>}\n {readout !== undefined && (\n <span\n className={cn(\n \"ms-auto shrink-0 text-xs tabular-nums text-[var(--text-primary)]\",\n plainReadout && \"select-none\",\n )}\n >\n {readout}\n </span>\n )}\n </div>\n )}\n <input\n ref={ref}\n id={label !== undefined ? inputId : id}\n disabled={disabled}\n {...rest}\n type=\"range\"\n min={trackMin}\n max={trackMax}\n step={log ? LOG_STEP : step}\n value={current}\n aria-valuetext={valueText}\n onChange={handleChange}\n // The fill's break point, merged under the caller's own style.\n style={{ ...style, \"--slider-fill\": `${share(current) * 100}%` } as CSSProperties}\n className={cn(TRACK, inputClassName)}\n />\n {normalizedMarks.length > 0 && (\n // `mx-2` insets the row by half a thumb on each side, which is exactly the\n // range the thumb's CENTRE travels — so a tick at 0% sits under the thumb at\n // `min`, not under the track's rounded end. Each tick is a zero-width column\n // centred on its point, which centres its label on it in either direction\n // without a `translate` that would need flipping for right-to-left.\n <div\n aria-hidden\n className={cn(\"relative mx-2 -mt-1.5\", hasMarkLabels ? \"h-5\" : \"h-1.5\")}\n >\n {normalizedMarks.map((m) => (\n <span\n key={m.value}\n className=\"absolute top-0 flex w-0 flex-col items-center\"\n style={{ insetInlineStart: `${share(position(m.value)) * 100}%` }}\n >\n <span className=\"h-1.5 w-px shrink-0 bg-[var(--border-strong)]\" />\n {m.label !== undefined && (\n <span className=\"mt-0.5 select-none whitespace-nowrap text-[11px] leading-tight text-[var(--text-muted)]\">\n {m.label}\n </span>\n )}\n </span>\n ))}\n </div>\n )}\n </div>\n );\n});\nSlider.displayName = \"Slider\";\n"],"mappings":";AAqPQ,SAEI,KAFJ;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SAAS,UAAa,oBAAC,UAAK,WAAU,8BAA8B,gBAAK;AAAA,MACzE,YAAY,UACX;AAAA,QAAC;AAAA;AAAA,UACC,WAAW;AAAA,YACT;AAAA,YACA,gBAAgB;AAAA,UAClB;AAAA,UAEC;AAAA;AAAA,MACH;AAAA,OAEJ;AAAA,IAEF;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,QACA,IAAI,UAAU,SAAY,UAAU;AAAA,QACpC;AAAA,QACC,GAAG;AAAA,QACJ,MAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,MAAM,MAAM,WAAW;AAAA,QACvB,OAAO;AAAA,QACP,kBAAgB;AAAA,QAChB,UAAU;AAAA,QAEV,OAAO,EAAE,GAAG,OAAO,iBAAiB,GAAG,MAAM,OAAO,IAAI,GAAG,IAAI;AAAA,QAC/D,WAAW,GAAG,OAAO,cAAc;AAAA;AAAA,IACrC;AAAA,IACC,gBAAgB,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA,IAMxB;AAAA,MAAC;AAAA;AAAA,QACC,eAAW;AAAA,QACX,WAAW,GAAG,yBAAyB,gBAAgB,QAAQ,OAAO;AAAA,QAErE,0BAAgB,IAAI,CAAC,MACpB;AAAA,UAAC;AAAA;AAAA,YAEC,WAAU;AAAA,YACV,OAAO,EAAE,kBAAkB,GAAG,MAAM,SAAS,EAAE,KAAK,CAAC,IAAI,GAAG,IAAI;AAAA,YAEhE;AAAA,kCAAC,UAAK,WAAU,iDAAgD;AAAA,cAC/D,EAAE,UAAU,UACX,oBAAC,UAAK,WAAU,2FACb,YAAE,OACL;AAAA;AAAA;AAAA,UARG,EAAE;AAAA,QAUT,CACD;AAAA;AAAA,IACH;AAAA,KAEJ;AAEJ,CAAC;AACD,OAAO,cAAc;","names":["Slider"]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/slider.tsx"],"sourcesContent":["import { forwardRef, useId } from \"react\";\nimport type { CSSProperties, ChangeEvent, InputHTMLAttributes, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\n\n/**\n * A range control on a native `<input type=\"range\">`.\n *\n * Lenkbank wrote the first one (`shared/ui/slider-field.tsx`) and then the case for\n * moving it here (`docs/ui-kit-slider-proposal.md`). This is that proposal's \"stage 1\"\n * primitive — the track, the thumb, the scale and the accessibility — plus the label\n * line and tick marks its SpeedSlider needed. The four decisions it argues should be\n * made once are made here, and each carries its note below:\n *\n * 1. a logarithmic scale whose far-left stop means exactly zero ({@link SliderProps.zeroStop});\n * 2. `aria-valuetext`, so a log track does not announce its 0–1 position as the value;\n * 3. a 24px pointer target, which needs the track and thumb drawn separately;\n * 4. the number is the truth and the track a view of it: a value outside `min`–`max`\n * is kept and the thumb pins at the end — nothing here clamps what it was given.\n *\n * Controlled only, like `ToggleGroup` and `NumberInput`: there is no uncontrolled mode\n * to get wrong, and neither app wants one. The package does no number formatting and\n * holds no locale — `formatValue` is how the caller's `Intl` result gets in.\n *\n * Not here, deliberately (the proposal's list): two thumbs, vertical orientation, and\n * a number box. A `NumberInput` goes in the `readout` slot when a typed value is\n * wanted beside the track.\n */\n\n/** On a log scale with {@link SliderProps.zeroStop}, the share of the track that is\n * the \"off\" stop. The first position to its right is `min`. */\nconst ZERO_STOP = 0.02;\n\n/** Position resolution on a log track — 1000 stops, fine enough that a drag reads as\n * continuous. PageUp/PageDown still cross a tenth of the track at a time. */\nconst LOG_STEP = 0.001;\n\n/**\n * Where a value sits on a logarithmic track, 0–1.\n *\n * With `zeroStop`, zero and below is 0 and the decades between `min` and `max` are\n * mapped onto the rest; without it, `min` is the far left. A value past either end\n * pins there — that is the DISPLAY clamping, never the value's.\n */\nexport function toLogPosition(value: number, min: number, max: number, zeroStop = true): number {\n if (value <= 0) return 0;\n const share = Math.log(Math.max(value, min) / min) / Math.log(max / min);\n const clamped = Math.min(1, Math.max(0, share));\n return zeroStop ? ZERO_STOP + (1 - ZERO_STOP) * clamped : clamped;\n}\n\n/** The inverse of {@link toLogPosition}: the value at a track position. */\nexport function fromLogPosition(position: number, min: number, max: number, zeroStop = true): number {\n if (zeroStop) {\n if (position < ZERO_STOP) return 0;\n return min * Math.pow(max / min, (position - ZERO_STOP) / (1 - ZERO_STOP));\n }\n return min * Math.pow(max / min, position);\n}\n\n// The input is the pointer target, so its box is `h-6` (24px, WCAG 2.5.8) and the\n// track that LOOKS like a track is a 6px strip drawn inside it. Once the box is taller\n// than the track its background cannot be the track, and with `appearance-none`\n// nothing else draws one — measured in Chromium by Lenkbank, that is a bare thumb\n// floating on nothing, in the browser's blue. Hence the vendor pseudo-elements: the\n// two engines share no selector for either half, so each half is spelt twice.\n//\n// The fill up to the thumb: WebKit has no progress pseudo-element, so its track is a\n// two-stop gradient that breaks at `--slider-fill` (set inline from the position), and\n// the gradient runs the other way in a right-to-left document, where the native range\n// runs the other way too. Firefox draws the fill itself with `::-moz-range-progress`,\n// which follows the direction on its own.\n//\n// The thumb's `-mt-[5px]` centres a 16px thumb on a 6px track: WebKit lays the thumb\n// out from the track's top edge, Firefox centres it, so only one carries the offset.\n//\n// The focus ring goes on the THUMB, not the box: the box is the full width of the\n// row, and a ring round all of it says \"this row is focused\" rather than \"the handle\n// you are about to move is\". Offset in the surface colour, because the thumb is\n// --brand and a --brand ring touching it would be invisible.\nconst TRACK = [\n \"block h-6 w-full cursor-pointer appearance-none bg-transparent focus:outline-none disabled:cursor-not-allowed\",\n // WebKit / Blink\n \"[&::-webkit-slider-runnable-track]:h-1.5 [&::-webkit-slider-runnable-track]:rounded-full\",\n \"[&::-webkit-slider-runnable-track]:bg-[linear-gradient(to_right,var(--brand)_var(--slider-fill),var(--border-strong)_var(--slider-fill))]\",\n \"rtl:[&::-webkit-slider-runnable-track]:bg-[linear-gradient(to_left,var(--brand)_var(--slider-fill),var(--border-strong)_var(--slider-fill))]\",\n \"[&::-webkit-slider-thumb]:-mt-[5px] [&::-webkit-slider-thumb]:size-4 [&::-webkit-slider-thumb]:appearance-none\",\n \"[&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-[var(--brand)] [&::-webkit-slider-thumb]:shadow\",\n \"focus-visible:[&::-webkit-slider-thumb]:ring-2 focus-visible:[&::-webkit-slider-thumb]:ring-[var(--brand)]\",\n \"focus-visible:[&::-webkit-slider-thumb]:ring-offset-2 focus-visible:[&::-webkit-slider-thumb]:ring-offset-[var(--bg-surface)]\",\n // Firefox\n \"[&::-moz-range-track]:h-1.5 [&::-moz-range-track]:rounded-full [&::-moz-range-track]:bg-[var(--border-strong)]\",\n \"[&::-moz-range-progress]:h-1.5 [&::-moz-range-progress]:rounded-full [&::-moz-range-progress]:bg-[var(--brand)]\",\n \"[&::-moz-range-thumb]:size-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0\",\n \"[&::-moz-range-thumb]:bg-[var(--brand)] [&::-moz-range-thumb]:shadow\",\n \"focus-visible:[&::-moz-range-thumb]:ring-2 focus-visible:[&::-moz-range-thumb]:ring-[var(--brand)]\",\n \"focus-visible:[&::-moz-range-thumb]:ring-offset-2 focus-visible:[&::-moz-range-thumb]:ring-offset-[var(--bg-surface)]\",\n].join(\" \");\n\n/** A tick under the track. A bare number is a tick with no words. */\nexport interface SliderMark {\n value: number;\n /** Shown under the tick — \"30 km/h\", \"measured\". Visual only: the value itself is\n * announced through `aria-valuetext`, so the marks row is hidden from assistive\n * technology rather than read out as a list of numbers after the slider. */\n label?: ReactNode;\n}\n\nexport interface SliderProps\n extends Omit<\n InputHTMLAttributes<HTMLInputElement>,\n \"type\" | \"value\" | \"defaultValue\" | \"onChange\" | \"min\" | \"max\" | \"step\" | \"children\"\n > {\n /** The value. On a log scale this is the real value, not the track position. */\n value: number;\n /** The new value — a number, not the DOM event, like `ToggleGroup`. Fired on every\n * movement; debounce at the call site if each one costs a request. */\n onChange: (value: number) => void;\n /** The track's ends. Not a validity range: a `value` outside it is kept and the\n * thumb pins at the end (see the module note). On a log scale `min` must be\n * above zero — zero is what {@link zeroStop} is for. */\n min: number;\n max: number;\n /** Step on a linear scale (the native default is 1). Ignored on a log scale, which\n * steps by track position — a fixed step is wrong at one end of every decade. */\n step?: number;\n /**\n * How the track maps to the value. `\"log\"` for quantities that run over decades — a\n * proportional gain of 0.5 and one of 200 are both ordinary, and on a linear track\n * everything under a tenth of the range is the first pixel. Falls back to linear if\n * `min` is not above zero or `max` not above `min`, where a logarithm has no answer.\n */\n scale?: \"linear\" | \"log\";\n /**\n * Log scale only: the far-left stop means exactly 0 (\"off\"), and the first step to\n * its right is `min`. A logarithm cannot hold zero, and zero is often the question —\n * should there be an integral term at all? Default `true`; turn it off for a scale\n * where zero is meaningless (a zoom factor, a playback rate).\n */\n zeroStop?: boolean;\n /**\n * What a screen reader says for the value — \"12.5 mm\", \"Off\". Sets\n * `aria-valuetext`. Without it a log track would announce its 0–1 POSITION (\"0.63\"\n * for a gain of 12.5), so on a log scale the raw value is announced instead; pass\n * this for anything with a unit or a locale.\n */\n formatValue?: (value: number) => string;\n /** The words above the track, as a `<label for>`. Without it, pass `aria-label`. */\n label?: ReactNode;\n /** Something that belongs to the label rather than the value — in practice a\n * `FieldHint` \"?\". Rendered beside the label, outside the `<label>` element, so it\n * never becomes part of the slider's accessible name. */\n hint?: ReactNode;\n /** The value as the reader sees it, at the end of the label line — a formatted\n * number, or a `NumberInput` for typing one. Rendered as given. */\n readout?: ReactNode;\n /** Ticks under the track, at these values. Marks outside `min`–`max` are dropped. */\n marks?: ReadonlyArray<number | SliderMark>;\n /** Classes for the `<input>`. `className` styles the outer wrapper. */\n inputClassName?: string;\n}\n\n/**\n * A native range input with the kit's track and thumb, an optional label line\n * (`label`, `hint`, `readout`), tick `marks`, and a logarithmic `scale`.\n *\n * Every other prop reaches the `<input>` — `name`, `id`, `aria-*`, `data-*`, `onBlur`,\n * `onPointerUp` for commit-on-release — and `disabled` also fades the label line.\n */\nexport const Slider = forwardRef<HTMLInputElement, SliderProps>(function Slider(\n {\n value,\n onChange,\n min,\n max,\n step,\n scale = \"linear\",\n zeroStop = true,\n formatValue,\n label,\n hint,\n readout,\n marks,\n className,\n inputClassName,\n id,\n disabled,\n style,\n ...rest\n },\n ref,\n) {\n const generated = useId();\n const inputId = id ?? generated;\n const log = scale === \"log\" && min > 0 && max > min;\n\n // Everything the native element sees is a POSITION; everything the caller sees is a\n // value. On a linear track the two are the same number.\n const trackMin = log ? 0 : min;\n const trackMax = log ? 1 : max;\n const position = (v: number) => (log ? toLogPosition(v, min, max, zeroStop) : Math.min(max, Math.max(min, v)));\n const current = position(value);\n // 0–1 share of the track, for the fill and the marks. A zero-width range (min ===\n // max) has no share to speak of; call it empty rather than divide by zero.\n const share = (p: number) => (trackMax > trackMin ? (p - trackMin) / (trackMax - trackMin) : 0);\n const outOfRange = value < min || value > max;\n\n // `aria-valuetext` replaces the announced NUMBER and leaves the announced name\n // alone. The caller's words first (`formatValue`, then a hand-written\n // `aria-valuetext`); failing those, the real value wherever the\n // native one would lie — every log position, and a linear value the thumb is only\n // pinned at. `toPrecision(4)` keeps a log value from being read out to sixteen\n // digits; it is not formatting, and `formatValue` is how to get a locale.\n const valueText = formatValue\n ? formatValue(value)\n : (rest[\"aria-valuetext\"] ??\n (log || outOfRange ? String(Number(value.toPrecision(4))) : undefined));\n\n const handleChange = (e: ChangeEvent<HTMLInputElement>) => {\n const raw = Number(e.target.value);\n if (!log) return onChange(raw);\n // The gap between the zero stop and `min` has to be crossable by keyboard. An\n // arrow key moves one LOG_STEP, which from zero lands inside the gap — and a gap\n // that rounded to the nearer end would send it straight back to zero, trapping\n // a keyboard user at \"off\". So inside the gap, moving up from zero means `min`\n // and anything else means zero.\n if (zeroStop && raw > 0 && raw < ZERO_STOP) return onChange(value <= 0 ? min : 0);\n onChange(fromLogPosition(raw, min, max, zeroStop));\n };\n\n const normalizedMarks = (marks ?? [])\n .map((m) => (typeof m === \"number\" ? { value: m } : m))\n .filter((m) => m.value >= min && m.value <= max);\n const hasMarkLabels = normalizedMarks.some((m) => m.label !== undefined);\n\n const hasHeader = label !== undefined || hint !== undefined || readout !== undefined;\n const plainReadout = typeof readout === \"string\" || typeof readout === \"number\";\n\n return (\n <div className={cn(\"w-full\", disabled && \"opacity-60\", className)}>\n {hasHeader && (\n // `select-none` on the words is not a nicety (Lenkbank feedback #93): a\n // mousedown on text beside a range input starts Chrome's native text drag, the\n // cursor turns to no-drop and the thumb stops following the pointer for the\n // rest of the gesture. The readout is only made unselectable when it is plain\n // text — a NumberInput in that slot has to stay selectable to be editable.\n // `flex-wrap`: a readout wider than the room beside the label (a value plus a\n // link button, \"0 / 60 / 120 km/h · Alle Geschwindigkeiten\") used to print on\n // top of it at 390px (lenkbank L1). Each keeps its own width, so the readout\n // drops to a line of its own, still at the end, only when the two don't fit.\n <div className=\"flex flex-wrap items-center gap-x-2 gap-y-0.5\">\n {label !== undefined && (\n <label\n htmlFor={inputId}\n className=\"min-w-0 select-none text-xs font-medium text-[var(--text-secondary)]\"\n >\n {label}\n </label>\n )}\n {hint !== undefined && <span className=\"flex shrink-0 items-center\">{hint}</span>}\n {readout !== undefined && (\n <span\n className={cn(\n \"ms-auto max-w-full text-xs tabular-nums text-[var(--text-primary)]\",\n plainReadout && \"select-none\",\n )}\n >\n {readout}\n </span>\n )}\n </div>\n )}\n <input\n ref={ref}\n id={label !== undefined ? inputId : id}\n disabled={disabled}\n {...rest}\n type=\"range\"\n min={trackMin}\n max={trackMax}\n step={log ? LOG_STEP : step}\n value={current}\n aria-valuetext={valueText}\n onChange={handleChange}\n // The fill's break point, merged under the caller's own style.\n style={{ ...style, \"--slider-fill\": `${share(current) * 100}%` } as CSSProperties}\n className={cn(TRACK, inputClassName)}\n />\n {normalizedMarks.length > 0 && (\n // `mx-2` insets the row by half a thumb on each side, which is exactly the\n // range the thumb's CENTRE travels — so a tick at 0% sits under the thumb at\n // `min`, not under the track's rounded end. Each tick is a zero-width column\n // centred on its point, which centres its label on it in either direction\n // without a `translate` that would need flipping for right-to-left.\n <div\n aria-hidden\n className={cn(\"relative mx-2 -mt-1.5\", hasMarkLabels ? \"h-5\" : \"h-1.5\")}\n >\n {normalizedMarks.map((m) => (\n <span\n key={m.value}\n className=\"absolute top-0 flex w-0 flex-col items-center\"\n style={{ insetInlineStart: `${share(position(m.value)) * 100}%` }}\n >\n <span className=\"h-1.5 w-px shrink-0 bg-[var(--border-strong)]\" />\n {m.label !== undefined && (\n <span className=\"mt-0.5 select-none whitespace-nowrap text-[11px] leading-tight text-[var(--text-muted)]\">\n {m.label}\n </span>\n )}\n </span>\n ))}\n </div>\n )}\n </div>\n );\n});\nSlider.displayName = \"Slider\";\n"],"mappings":";AAyPQ,SAEI,KAFJ;AAzPR,SAAS,YAAY,aAAa;AAElC,SAAS,UAAU;AA4BnB,MAAM,YAAY;AAIlB,MAAM,WAAW;AASV,SAAS,cAAc,OAAe,KAAa,KAAa,WAAW,MAAc;AAC9F,MAAI,SAAS,EAAG,QAAO;AACvB,QAAM,QAAQ,KAAK,IAAI,KAAK,IAAI,OAAO,GAAG,IAAI,GAAG,IAAI,KAAK,IAAI,MAAM,GAAG;AACvE,QAAM,UAAU,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,KAAK,CAAC;AAC9C,SAAO,WAAW,aAAa,IAAI,aAAa,UAAU;AAC5D;AAGO,SAAS,gBAAgB,UAAkB,KAAa,KAAa,WAAW,MAAc;AACnG,MAAI,UAAU;AACZ,QAAI,WAAW,UAAW,QAAO;AACjC,WAAO,MAAM,KAAK,IAAI,MAAM,MAAM,WAAW,cAAc,IAAI,UAAU;AAAA,EAC3E;AACA,SAAO,MAAM,KAAK,IAAI,MAAM,KAAK,QAAQ;AAC3C;AAsBA,MAAM,QAAQ;AAAA,EACZ;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,EAAE,KAAK,GAAG;AAwEH,MAAM,SAAS,WAA0C,SAASA,QACvE;AAAA,EACE;AAA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AK,CAAC,IAAI,GAAG,IAAI;AAAA,YAEhE;AAAA,kCAAC,UAAK,WAAU,iDAAgD;AAAA,cAC/D,EAAE,UAAU,UACX,oBAAC,UAAK,WAAU,2FACb,YAAE,OACL;AAAA;AAAA;AAAA,UARG,EAAE;AAAA,QAUT,CACD;AAAA;AAAA,IACH;AAAA,KAEJ;AAEJ,CAAC;AACD,OAAO,cAAc;","names":["Slider"]}
|
|
@@ -70,6 +70,17 @@ interface TableProps extends ComponentPropsWithoutRef<"table"> {
|
|
|
70
70
|
* row can still say otherwise with {@link TableRowProps.bordered}.
|
|
71
71
|
*/
|
|
72
72
|
rowDividers?: boolean;
|
|
73
|
+
/**
|
|
74
|
+
* `"phone"`: below `sm` each body row becomes a block — its first cell the row's
|
|
75
|
+
* title, every further cell under its column's header as a small label — and the
|
|
76
|
+
* head row is visually hidden (still read by screen readers). For tables of PROSE,
|
|
77
|
+
* not figures (lenkbank L5: a PID-terms table of three sentence columns wrapped into
|
|
78
|
+
* two-word slivers at 390px and ran its third column off the screen). A table of
|
|
79
|
+
* numbers should keep scrolling sideways, which is why this is opt-in. The labels
|
|
80
|
+
* are the head row's cell texts, read from the DOM; a body cell spanning several
|
|
81
|
+
* columns gets none.
|
|
82
|
+
*/
|
|
83
|
+
stack?: "phone";
|
|
73
84
|
}
|
|
74
85
|
/**
|
|
75
86
|
* A plain, static HTML table in the kit's tokens — for the detail views that need
|
|
@@ -88,7 +99,7 @@ interface TableProps extends ComponentPropsWithoutRef<"table"> {
|
|
|
88
99
|
* Alignment is logical throughout (`text-start` / `text-end`), so a right-to-left
|
|
89
100
|
* page gets its first column on the right without a class changing.
|
|
90
101
|
*/
|
|
91
|
-
declare function Table({ density, zebra, hover, wrapperClassName, layout, framed, rowDividers, className, "aria-label": ariaLabel, ...rest }: TableProps): react.JSX.Element;
|
|
102
|
+
declare function Table({ density, zebra, hover, wrapperClassName, layout, framed, rowDividers, stack, className, "aria-label": ariaLabel, ...rest }: TableProps): react.JSX.Element;
|
|
92
103
|
interface TableHeadProps extends ComponentPropsWithoutRef<"thead"> {
|
|
93
104
|
/** The rule under the head. Default true; `false` for a quiet header over a small
|
|
94
105
|
* table (keksdose's VAT summary wrote `className="border-b-0"` to lose it). */
|
package/dist/components/table.js
CHANGED
|
@@ -52,6 +52,15 @@ const ALIGN = {
|
|
|
52
52
|
end: "text-end"
|
|
53
53
|
};
|
|
54
54
|
const NUMERIC_CELL_CLASS = "text-end tabular-nums";
|
|
55
|
+
const STACK_PHONE_CLASSES = cn(
|
|
56
|
+
"max-sm:block max-sm:[&_tbody]:block max-sm:[&_tfoot]:block",
|
|
57
|
+
"max-sm:[&_thead]:sr-only",
|
|
58
|
+
"max-sm:[&_tbody_tr]:block max-sm:[&_tbody_tr]:py-2 max-sm:[&_tfoot_tr]:block max-sm:[&_tfoot_tr]:py-2",
|
|
59
|
+
"max-sm:[&_tbody_td]:block max-sm:[&_tbody_td]:px-0 max-sm:[&_tbody_td]:py-0.5 max-sm:[&_tbody_td]:text-start",
|
|
60
|
+
"max-sm:[&_tfoot_td]:block max-sm:[&_tfoot_td]:px-0 max-sm:[&_tfoot_td]:py-0.5",
|
|
61
|
+
"max-sm:[&_tbody_td:first-child]:font-medium",
|
|
62
|
+
"max-sm:[&_td[data-label]]:before:block max-sm:[&_td[data-label]]:before:text-[11px] max-sm:[&_td[data-label]]:before:font-medium max-sm:[&_td[data-label]]:before:text-[var(--text-muted)] max-sm:[&_td[data-label]]:before:content-[attr(data-label)]"
|
|
63
|
+
);
|
|
55
64
|
function Table({
|
|
56
65
|
density = "comfortable",
|
|
57
66
|
zebra = false,
|
|
@@ -60,6 +69,7 @@ function Table({
|
|
|
60
69
|
layout,
|
|
61
70
|
framed = false,
|
|
62
71
|
rowDividers = true,
|
|
72
|
+
stack,
|
|
63
73
|
className,
|
|
64
74
|
"aria-label": ariaLabel,
|
|
65
75
|
...rest
|
|
@@ -68,6 +78,32 @@ function Table({
|
|
|
68
78
|
const [captions, setCaptions] = useState(0);
|
|
69
79
|
const wrapper = useRef(null);
|
|
70
80
|
const overflowing = useScrollOverflow(wrapper);
|
|
81
|
+
const tableRef = useRef(null);
|
|
82
|
+
useLayoutEffect(() => {
|
|
83
|
+
const table = tableRef.current;
|
|
84
|
+
if (!stack || !table) return;
|
|
85
|
+
const label = () => {
|
|
86
|
+
const heads = Array.from(table.tHead?.rows[0]?.cells ?? []).map((cell) => cell.textContent?.trim() ?? "");
|
|
87
|
+
table.setAttribute("role", "table");
|
|
88
|
+
for (const row of Array.from(table.rows)) {
|
|
89
|
+
row.setAttribute("role", "row");
|
|
90
|
+
let column = 0;
|
|
91
|
+
for (const cell of Array.from(row.cells)) {
|
|
92
|
+
const span = cell.colSpan || 1;
|
|
93
|
+
if (cell.tagName === "TH") cell.setAttribute("role", cell.closest("thead") ? "columnheader" : "rowheader");
|
|
94
|
+
else cell.setAttribute("role", "cell");
|
|
95
|
+
const text = span === 1 && column > 0 ? heads[column] : void 0;
|
|
96
|
+
if (cell.tagName === "TD" && text) cell.setAttribute("data-label", text);
|
|
97
|
+
else cell.removeAttribute("data-label");
|
|
98
|
+
column += span;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
label();
|
|
103
|
+
const observer = typeof MutationObserver === "undefined" ? null : new MutationObserver(label);
|
|
104
|
+
observer?.observe(table, { childList: true, subtree: true, characterData: true });
|
|
105
|
+
return () => observer?.disconnect();
|
|
106
|
+
}, [stack]);
|
|
71
107
|
const ctx = useMemo(
|
|
72
108
|
() => ({
|
|
73
109
|
density,
|
|
@@ -107,12 +143,14 @@ function Table({
|
|
|
107
143
|
"table",
|
|
108
144
|
{
|
|
109
145
|
...rest,
|
|
146
|
+
ref: tableRef,
|
|
110
147
|
"aria-label": ariaLabel,
|
|
111
148
|
className: cn(
|
|
112
149
|
"w-full caption-bottom border-collapse text-sm text-[var(--text-primary)]",
|
|
113
150
|
density === "compact" && "text-xs",
|
|
114
151
|
layout === "fixed" && "table-fixed",
|
|
115
152
|
layout === "auto" && "table-auto",
|
|
153
|
+
stack === "phone" && STACK_PHONE_CLASSES,
|
|
116
154
|
className
|
|
117
155
|
)
|
|
118
156
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/table.tsx"],"sourcesContent":["import { Children, createContext, useContext, useId, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithoutRef, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { THIN_SCROLLBAR_CLASS, useScrollOverflow } from \"./scroll-area\";\n\n/** `none` (0.10.0): no cell padding at all — keksdose's VAT summary, a table set\n * inside a card's own padding whose columns are spaced by hand (`pl-2` on exactly the\n * columns that need it). Type stays at the body size, as `comfortable`. */\nexport type TableDensity = \"comfortable\" | \"compact\" | \"none\";\n/** CSS `table-layout`. `auto` (the browser default) sizes columns to their content;\n * `fixed` takes widths from the first row and ignores the rest — keksdose's VAT\n * summary switches to it while editing so two inputs stop bidding against the\n * figures for room. */\nexport type TableLayout = \"auto\" | \"fixed\";\nexport type TableAlign = \"start\" | \"center\" | \"end\";\n/**\n * Vertical alignment of a cell's content (0.11.0). The defaults stay as they were — a\n * head cell sits on the `bottom` (a wrapped heading ends on the line above the\n * figures), a body cell at the `top` (a wrapped note starts level with its row). A\n * table whose cells are INPUTS wants `middle`: keksdose's VAT summary\n * (invoices/vat-summary.tsx) sets fields beside derived read-out figures in one row,\n * and a figure at the top of its cell sat above the middle of the field next to it —\n * so it writes `<tr className=\"align-middle\">` over raw `<th>`/`<td>`, because the\n * kit's cells each stated `align-top` and a class on the row could not reach them.\n */\nexport type TableVAlign = \"top\" | \"middle\" | \"bottom\";\n/** The head cell's type size: `xs` (the head's default) or `sm` (the body's). */\nexport type TableHeaderCellSize = \"xs\" | \"sm\";\n/** The header cell's weight. Default `medium`. */\nexport type TableHeaderCellWeight = \"normal\" | \"medium\" | \"semibold\";\n\n/**\n * What a {@link TableRow} is in a statement-style table (0.12.0): an ordinary `row`, a\n * `group` heading (\"Current assets\", a tinted full-width label row), a `subtotal` under\n * a group, or the `total` of the whole table. kastlan's balance sheet, income statement\n * and journal entry each spelled these as `className=\"font-medium\"`, `\"font-bold\n * border-t-2\"` and `bg-muted/50` on the cell — three pages, three sets of classes for\n * the same four kinds of line.\n */\nexport type TableRowVariant = \"row\" | \"group\" | \"subtotal\" | \"total\";\n\ninterface TableContextValue {\n density: TableDensity;\n zebra: boolean;\n hover: boolean;\n rowDividers: boolean;\n captionId: string;\n registerCaption: () => () => void;\n}\n\nconst TableContext = createContext<TableContextValue>({\n density: \"comfortable\",\n zebra: false,\n hover: false,\n rowDividers: true,\n captionId: \"\",\n registerCaption: () => () => {},\n});\n\ntype TableSection = \"head\" | \"body\" | \"foot\";\n\n/** Which section a row sits in — zebra and hover apply to body rows only. `undefined`\n * outside the kit's section parts: a raw `<thead>` / `<tbody>`, which\n * {@link useSection} then reads off the DOM. */\nconst SectionContext = createContext<TableSection | undefined>(undefined);\n\nconst SECTION_OF_TAG: Record<string, TableSection> = { THEAD: \"head\", TBODY: \"body\", TFOOT: \"foot\" };\n\n/**\n * The section a row or cell sits in: the kit part's context where there is one, else the\n * nearest `<thead>` / `<tbody>` / `<tfoot>` in the DOM.\n *\n * keksdose's VAT summary writes a raw `<thead>` round kit cells in places, and a\n * `TableHeaderCell` there took itself for a BODY cell — `scope=\"row\"`, body type — with\n * nothing on the page to say why. React cannot see an ancestor's tag, so the fallback\n * reads it after mount; a layout effect, so the corrected cell is what gets painted.\n */\nfunction useSection<E extends HTMLElement>(): [TableSection, ((el: E | null) => void) | undefined] {\n const fromContext = useContext(SectionContext);\n const [node, setNode] = useState<E | null>(null);\n const [detected, setDetected] = useState<TableSection | undefined>(undefined);\n useLayoutEffect(() => {\n if (fromContext !== undefined || !node) return;\n const section = node.closest(\"thead, tbody, tfoot\");\n const found = section ? SECTION_OF_TAG[section.tagName] : undefined;\n // eslint-disable-next-line react-hooks/set-state-in-effect -- read off the DOM, which only exists after mount\n if (found !== detected) setDetected(found);\n }, [fromContext, node, detected]);\n // No ref at all under a kit section: holding the node would cost every row and cell\n // a second render on mount for an answer the context already gave.\n return [fromContext ?? detected ?? \"body\", fromContext === undefined ? setNode : undefined];\n}\n\n/** A {@link TableRow}'s `valign`, which its cells take unless they set their own. It\n * cannot be left to CSS inheritance: every cell states its own default alignment,\n * and a class on the cell beats one on the row. */\nconst RowVAlignContext = createContext<TableVAlign | undefined>(undefined);\n\nconst VALIGN: Record<TableVAlign, string> = {\n top: \"align-top\",\n middle: \"align-middle\",\n bottom: \"align-bottom\",\n};\n\nconst HEADER_SIZE: Record<TableHeaderCellSize, string> = {\n xs: \"text-xs\",\n sm: \"text-sm\",\n};\n\nconst HEADER_WEIGHT: Record<TableHeaderCellWeight, string> = {\n normal: \"font-normal\",\n medium: \"font-medium\",\n semibold: \"font-semibold\",\n};\n\nconst CELL_PAD: Record<TableDensity, string> = {\n comfortable: \"px-3 py-2\",\n compact: \"px-2 py-1\",\n none: \"p-0\",\n};\n\nconst ALIGN: Record<TableAlign, string> = {\n start: \"text-start\",\n center: \"text-center\",\n end: \"text-end\",\n};\n\n/**\n * The alignment a figure column wants: end-aligned (so the units line up under each\n * other in either reading direction) with tabular digits (so they line up at all).\n * Exported for a cell the kit did not render — a DataTable column, a `<td>` of the\n * app's own.\n */\nexport const NUMERIC_CELL_CLASS = \"text-end tabular-nums\";\n\nexport interface TableProps extends ComponentPropsWithoutRef<\"table\"> {\n /** `compact` for a dense detail view (a ledger, a spec sheet). */\n density?: TableDensity;\n /** Tint every other body row. */\n zebra?: boolean;\n /** Tint the body row under the pointer. Off by default: a static table whose rows\n * light up promises a click that does nothing. */\n hover?: boolean;\n /** Classes for the overflow wrapper around the `<table>` (a max-height, a border). */\n wrapperClassName?: string;\n /** See {@link TableLayout}. Unset leaves the browser's `auto` and adds no class. */\n layout?: TableLayout;\n /**\n * A rounded border round the whole table (0.12.0) — for a table standing on the page\n * or in a dialog rather than inside a card. kastlan wraps six of them in\n * `<div className=\"rounded-md border\">` by hand (payment allocation, the new-budget\n * lines, the meter readings, the deposit transactions, the unit values editor, the\n * maintenance detail), and a hand-made frame outside the scroll wrapper does not clip\n * the rows' tint to its corners.\n */\n framed?: boolean;\n /**\n * The rule between body rows. Default true. `false` for a small table whose rows are\n * spaced by their own content — keksdose's VAT summary, a block of three quiet\n * columns inside a card — which otherwise had to drop to raw `<tr>`s to lose it. One\n * row can still say otherwise with {@link TableRowProps.bordered}.\n */\n rowDividers?: boolean;\n}\n\n/**\n * A plain, static HTML table in the kit's tokens — for the detail views that need\n * rows and columns and none of {@link DataTable}'s sorting, filtering or paging.\n *\n * kastlan renders about twenty of these on shadcn's Table parts; the part names here\n * are the same idea (`TableHead` is the `<thead>`, `TableHeaderCell` the `<th>`), so\n * the move is a rename rather than a rewrite.\n *\n * The table sits in an overflow-x wrapper, because a table cannot shrink below its\n * content and on a phone it would otherwise widen the page. While it overflows that\n * wrapper becomes a tab stop and a `role=\"region\"` named by the `TableCaption` (or the\n * table's own `aria-label`), so a keyboard user can scroll it and a reader can say\n * what it is — the same contract as {@link ScrollArea}.\n *\n * Alignment is logical throughout (`text-start` / `text-end`), so a right-to-left\n * page gets its first column on the right without a class changing.\n */\nexport function Table({\n density = \"comfortable\",\n zebra = false,\n hover = false,\n wrapperClassName,\n layout,\n framed = false,\n rowDividers = true,\n className,\n \"aria-label\": ariaLabel,\n ...rest\n}: TableProps) {\n const captionId = useId();\n const [captions, setCaptions] = useState(0);\n const wrapper = useRef<HTMLDivElement | null>(null);\n const overflowing = useScrollOverflow(wrapper);\n\n const ctx = useMemo<TableContextValue>(\n () => ({\n density,\n zebra,\n hover,\n rowDividers,\n captionId,\n registerCaption: () => {\n setCaptions((n) => n + 1);\n return () => setCaptions((n) => n - 1);\n },\n }),\n [density, zebra, hover, rowDividers, captionId],\n );\n\n const regionName = captions > 0 ? { \"aria-labelledby\": captionId } : ariaLabel ? { \"aria-label\": ariaLabel } : null;\n\n return (\n <TableContext.Provider value={ctx}>\n <div\n ref={wrapper}\n // Only a region when it scrolls AND has a name: a landmark for every short\n // table on a page would bury the real ones.\n role={overflowing && regionName ? \"region\" : undefined}\n {...(overflowing ? regionName : null)}\n tabIndex={overflowing ? 0 : undefined}\n data-overflowing={overflowing || undefined}\n data-clips=\"\"\n data-framed={framed || undefined}\n className={cn(\n // `relative`: the containing block for an `sr-only` caption.\n \"relative w-full overflow-x-auto\",\n // On the scroll wrapper itself, so its clipping keeps the rows inside the\n // rounded corners.\n framed && \"rounded-md border border-[var(--border)]\",\n THIN_SCROLLBAR_CLASS,\n \"focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-[var(--brand)]\",\n wrapperClassName,\n )}\n >\n <table\n {...rest}\n aria-label={ariaLabel}\n className={cn(\n \"w-full caption-bottom border-collapse text-sm text-[var(--text-primary)]\",\n density === \"compact\" && \"text-xs\",\n layout === \"fixed\" && \"table-fixed\",\n layout === \"auto\" && \"table-auto\",\n className,\n )}\n />\n </div>\n </TableContext.Provider>\n );\n}\n\nexport interface TableHeadProps extends ComponentPropsWithoutRef<\"thead\"> {\n /** The rule under the head. Default true; `false` for a quiet header over a small\n * table (keksdose's VAT summary wrote `className=\"border-b-0\"` to lose it). */\n bordered?: boolean;\n}\n\nexport function TableHead({ bordered = true, className, ...rest }: TableHeadProps) {\n return (\n <SectionContext.Provider value=\"head\">\n <thead {...rest} className={cn(bordered && \"border-b border-[var(--border)]\", className)} />\n </SectionContext.Provider>\n );\n}\n\nexport interface TableBodyProps extends ComponentPropsWithoutRef<\"tbody\"> {\n /**\n * Shown as ONE full-width row (a {@link TableEmpty}) when the body has no rows —\n * `children` that render nothing: an empty `.map`, a `false`, `null`. kastlan hand-\n * writes that row with a counted `colSpan` in unit-values-editor, the meeting agenda\n * and invitations tabs, the journal-entry and invoice detail pages, and a column\n * added later leaves every one of those counts one short.\n */\n empty?: ReactNode;\n}\n\nexport function TableBody({ className, empty, children, ...rest }: TableBodyProps) {\n // `toArray` drops null/undefined/booleans and flattens arrays, so `[[], false]` —\n // an empty map beside a conditional row that is off — is no rows.\n const hasRows = Children.toArray(children).length > 0;\n return (\n <SectionContext.Provider value=\"body\">\n <tbody {...rest} className={cn(\"[&>tr:last-child]:border-b-0\", className)}>\n {hasRows || empty === undefined || empty === null || empty === false ? (\n children\n ) : (\n <TableEmpty>{empty}</TableEmpty>\n )}\n </tbody>\n </SectionContext.Provider>\n );\n}\n\nexport interface TableEmptyProps extends Omit<ComponentPropsWithoutRef<\"tr\">, \"children\"> {\n children: ReactNode;\n /** Columns to span. Default: MEASURED — the widest row of the table it renders in,\n * counted after mount, so the row stays full width when a column is added. */\n colSpan?: number;\n /** Classes for the `<td>`. */\n cellClassName?: string;\n}\n\n/**\n * The \"nothing here\" row: one cell across every column, centred, muted. What\n * {@link TableBodyProps.empty} renders, and usable on its own for a body whose rows\n * are not its direct children.\n */\nexport function TableEmpty({ children, colSpan, cellClassName, className, ...rest }: TableEmptyProps) {\n const { density } = useContext(TableContext);\n const cell = useRef<HTMLTableCellElement | null>(null);\n const [measured, setMeasured] = useState(1);\n // Every render, deliberately: a column can appear in the head without anything this\n // row depends on changing. It cannot loop — setting the same count is a bail-out.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useLayoutEffect(() => {\n if (colSpan !== undefined) return;\n const row = cell.current?.parentElement;\n const table = cell.current?.closest(\"table\");\n if (!row || !table) return;\n let widest = 1;\n for (const r of Array.from(table.rows)) {\n if (r === row) continue;\n let n = 0;\n for (const c of Array.from(r.cells)) n += c.colSpan || 1;\n widest = Math.max(widest, n);\n }\n setMeasured(widest);\n });\n return (\n <tr {...rest} data-table-empty=\"\" className={className}>\n <td\n ref={cell}\n colSpan={colSpan ?? measured}\n className={cn(\n // `none` keeps the message off the edges regardless: it is text, not a figure.\n density === \"none\" ? \"py-2\" : CELL_PAD[density],\n \"text-center text-[var(--text-muted)]\",\n cellClassName,\n )}\n >\n {children}\n </td>\n </tr>\n );\n}\n\nexport type TableFootProps = ComponentPropsWithoutRef<\"tfoot\">;\n\n/** The totals row. Not in the brief, but every ledger view has one and a `<tfoot>`\n * is what tells a reader it is a total rather than one more row. */\nexport function TableFoot({ className, ...rest }: TableFootProps) {\n return (\n <SectionContext.Provider value=\"foot\">\n <tfoot {...rest} className={cn(\"border-t border-[var(--border-strong)] font-medium\", className)} />\n </SectionContext.Provider>\n );\n}\n\nconst ROW_VARIANT: Record<TableRowVariant, string | false> = {\n row: false,\n group: \"bg-[var(--bg-surface-2)] font-semibold\",\n subtotal: \"font-medium\",\n // A 2px rule over the 1px divider the row above draws on its bottom: collapsed\n // borders meet on one line, the wider wins, and the heavier rule is what says \"sum\".\n total: \"border-t-2 border-t-[var(--border-strong)] font-semibold\",\n};\n\n/** The deprecated HTML `valign` attribute is replaced by a class-backed one. */\nexport interface TableRowProps extends ComponentPropsWithoutRef<\"tr\"> {\n /** Vertical alignment for every cell of the row that does not set its own. See\n * {@link TableVAlign}. Left out, each cell keeps its default. */\n valign?: TableVAlign;\n /** See {@link TableRowVariant}. Default `row`. Zebra and hover tint ordinary rows\n * only: a group heading or a total is not one more record. */\n variant?: TableRowVariant;\n /** The rule under this body row. Default: the table's `rowDividers`. */\n bordered?: boolean;\n}\n\nexport function TableRow({ valign, variant = \"row\", bordered, className, ...rest }: TableRowProps) {\n const { zebra, hover, rowDividers } = useContext(TableContext);\n const [section, ref] = useSection<HTMLTableRowElement>();\n const body = section === \"body\";\n const record = body && variant === \"row\";\n const row = (\n <tr\n ref={ref}\n {...rest}\n data-variant={variant === \"row\" ? undefined : variant}\n className={cn(\n body && (bordered ?? rowDividers) && \"border-b border-[var(--border)]\",\n record && zebra && \"even:bg-[var(--bg-surface-2)]\",\n record && hover && \"transition-colors hover:bg-[var(--bg-hover)]\",\n ROW_VARIANT[variant],\n // On the row as well, for a raw `<td>` of the caller's, which inherits it.\n valign && VALIGN[valign],\n className,\n )}\n />\n );\n return valign ? <RowVAlignContext.Provider value={valign}>{row}</RowVAlignContext.Provider> : row;\n}\n\ninterface CellAlignProps {\n /** Shorthand for a figure column: end-aligned, tabular digits. */\n numeric?: boolean;\n /** Logical alignment. Default `start` (`end` when `numeric`). */\n align?: TableAlign;\n /** Vertical alignment. Default: the row's `valign`, else `bottom` for a head cell and\n * `top` for a body cell. See {@link TableVAlign}. */\n valign?: TableVAlign;\n}\n\n/** The deprecated HTML `align` and `valign` attributes are replaced by class-backed ones. */\nexport interface TableHeaderCellProps extends Omit<ComponentPropsWithoutRef<\"th\">, \"align\" | \"valign\">, CellAlignProps {\n /**\n * Type size. Left out: `xs` in the head, the table's own size in the body — as\n * before. keksdose's VAT summary heads its columns at the body size and normal weight\n * (vat-summary.tsx:158–168, `font-normal` on each `<th>`), a quiet header over a\n * small table of figures, and could not say so without overriding classes.\n */\n size?: TableHeaderCellSize;\n /** Default `medium`. `normal` for the quiet header above; see {@link size}. */\n weight?: TableHeaderCellWeight;\n}\n\n/**\n * A `<th>`. `scope` defaults to `col` in the head and `row` in the body — a header\n * cell in a body row is the row's label (\"Net rent\" in a key-value table), and a\n * reader needs the scope to read it with each cell beside it.\n */\nexport function TableHeaderCell({\n numeric = false,\n align,\n valign,\n size,\n weight = \"medium\",\n scope,\n className,\n ...rest\n}: TableHeaderCellProps) {\n const { density } = useContext(TableContext);\n const [section, ref] = useSection<HTMLTableCellElement>();\n const rowVAlign = useContext(RowVAlignContext);\n const head = section === \"head\";\n const textSize = size ?? (head ? \"xs\" : undefined);\n return (\n <th\n ref={ref}\n {...rest}\n scope={scope ?? (section === \"head\" ? \"col\" : \"row\")}\n className={cn(\n CELL_PAD[density],\n ALIGN[align ?? (numeric ? \"end\" : \"start\")],\n numeric && \"tabular-nums\",\n VALIGN[valign ?? rowVAlign ?? (head ? \"bottom\" : \"top\")],\n HEADER_WEIGHT[weight],\n head ? \"text-[var(--text-muted)]\" : \"text-[var(--text-secondary)]\",\n textSize && HEADER_SIZE[textSize],\n className,\n )}\n />\n );\n}\n\nexport interface TableCellProps extends Omit<ComponentPropsWithoutRef<\"td\">, \"align\" | \"valign\">, CellAlignProps {}\n\nexport function TableCell({ numeric = false, align, valign, className, ...rest }: TableCellProps) {\n const { density } = useContext(TableContext);\n const rowVAlign = useContext(RowVAlignContext);\n return (\n <td\n {...rest}\n className={cn(\n CELL_PAD[density],\n VALIGN[valign ?? rowVAlign ?? \"top\"],\n ALIGN[align ?? (numeric ? \"end\" : \"start\")],\n numeric && \"tabular-nums whitespace-nowrap\",\n className,\n )}\n />\n );\n}\n\nexport type TableCaptionProps = ComponentPropsWithoutRef<\"caption\">;\n\n/**\n * The table's title. Beneath the table by default (`caption-bottom`, the shadcn\n * convention kastlan's views already follow); `className=\"caption-top\"` moves it.\n * `className=\"sr-only\"` keeps it for readers only — the wrapper is `relative`, so\n * the hidden caption stays inside it.\n *\n * It also names the scroll region when the table overflows: it registers itself\n * with the {@link Table} so the wrapper points at an id that exists, and never at\n * one that does not.\n */\nexport function TableCaption({ className, id, ...rest }: TableCaptionProps) {\n const { captionId, registerCaption } = useContext(TableContext);\n useLayoutEffect(() => (id ? undefined : registerCaption()), [id, registerCaption]);\n return (\n <caption\n {...rest}\n id={id ?? captionId}\n className={cn(\"mt-2 text-start text-sm text-[var(--text-muted)]\", className)}\n />\n );\n}\n"],"mappings":";AA+OQ;AA/OR,SAAS,UAAU,eAAe,YAAY,OAAO,iBAAiB,SAAS,QAAQ,gBAAgB;AAEvG,SAAS,UAAU;AACnB,SAAS,sBAAsB,yBAAyB;AA+CxD,MAAM,eAAe,cAAiC;AAAA,EACpD,SAAS;AAAA,EACT,OAAO;AAAA,EACP,OAAO;AAAA,EACP,aAAa;AAAA,EACb,WAAW;AAAA,EACX,iBAAiB,MAAM,MAAM;AAAA,EAAC;AAChC,CAAC;AAOD,MAAM,iBAAiB,cAAwC,MAAS;AAExE,MAAM,iBAA+C,EAAE,OAAO,QAAQ,OAAO,QAAQ,OAAO,OAAO;AAWnG,SAAS,aAA0F;AACjG,QAAM,cAAc,WAAW,cAAc;AAC7C,QAAM,CAAC,MAAM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MAAM;AAAA,QACvD,cAAc,MAAM;AAAA,QACpB,OAAO,6BAA6B;AAAA,QACpC,YAAY,YAAY,QAAQ;AAAA,QAChC;AAAA,MACF;AAAA;AAAA,EACF;AAEJ;AAIO,SAAS,UAAU,EAAE,UAAU,OAAO,OAAO,QAAQ,WAAW,GAAG,KAAK,GAAmB;AAChG,QAAM,EAAE,QAAQ,IAAI,WAAW,YAAY;AAC3C,QAAM,YAAY,WAAW,gBAAgB;AAC7C,SACE;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,WAAW;AAAA,QACT,SAAS,OAAO;AAAA,QAChB,OAAO,UAAU,aAAa,KAAK;AAAA,QACnC,MAAM,UAAU,UAAU,QAAQ,QAAQ;AAAA,QAC1C,WAAW;AAAA,QACX;AAAA,MACF;AAAA;AAAA,EACF;AAEJ;AAcO,SAAS,aAAa,EAAE,WAAW,IAAI,GAAG,KAAK,GAAsB;AAC1E,QAAM,EAAE,WAAW,gBAAgB,IAAI,WAAW,YAAY;AAC9D,kBAAgB,MAAO,KAAK,SAAY,gBAAgB,GAAI,CAAC,IAAI,eAAe,CAAC;AACjF,SACE;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,IAAI,MAAM;AAAA,MACV,WAAW,GAAG,oDAAoD,SAAS;AAAA;AAAA,EAC7E;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/table.tsx"],"sourcesContent":["import { Children, createContext, useContext, useId, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithoutRef, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { THIN_SCROLLBAR_CLASS, useScrollOverflow } from \"./scroll-area\";\n\n/** `none` (0.10.0): no cell padding at all — keksdose's VAT summary, a table set\n * inside a card's own padding whose columns are spaced by hand (`pl-2` on exactly the\n * columns that need it). Type stays at the body size, as `comfortable`. */\nexport type TableDensity = \"comfortable\" | \"compact\" | \"none\";\n/** CSS `table-layout`. `auto` (the browser default) sizes columns to their content;\n * `fixed` takes widths from the first row and ignores the rest — keksdose's VAT\n * summary switches to it while editing so two inputs stop bidding against the\n * figures for room. */\nexport type TableLayout = \"auto\" | \"fixed\";\nexport type TableAlign = \"start\" | \"center\" | \"end\";\n/**\n * Vertical alignment of a cell's content (0.11.0). The defaults stay as they were — a\n * head cell sits on the `bottom` (a wrapped heading ends on the line above the\n * figures), a body cell at the `top` (a wrapped note starts level with its row). A\n * table whose cells are INPUTS wants `middle`: keksdose's VAT summary\n * (invoices/vat-summary.tsx) sets fields beside derived read-out figures in one row,\n * and a figure at the top of its cell sat above the middle of the field next to it —\n * so it writes `<tr className=\"align-middle\">` over raw `<th>`/`<td>`, because the\n * kit's cells each stated `align-top` and a class on the row could not reach them.\n */\nexport type TableVAlign = \"top\" | \"middle\" | \"bottom\";\n/** The head cell's type size: `xs` (the head's default) or `sm` (the body's). */\nexport type TableHeaderCellSize = \"xs\" | \"sm\";\n/** The header cell's weight. Default `medium`. */\nexport type TableHeaderCellWeight = \"normal\" | \"medium\" | \"semibold\";\n\n/**\n * What a {@link TableRow} is in a statement-style table (0.12.0): an ordinary `row`, a\n * `group` heading (\"Current assets\", a tinted full-width label row), a `subtotal` under\n * a group, or the `total` of the whole table. kastlan's balance sheet, income statement\n * and journal entry each spelled these as `className=\"font-medium\"`, `\"font-bold\n * border-t-2\"` and `bg-muted/50` on the cell — three pages, three sets of classes for\n * the same four kinds of line.\n */\nexport type TableRowVariant = \"row\" | \"group\" | \"subtotal\" | \"total\";\n\ninterface TableContextValue {\n density: TableDensity;\n zebra: boolean;\n hover: boolean;\n rowDividers: boolean;\n captionId: string;\n registerCaption: () => () => void;\n}\n\nconst TableContext = createContext<TableContextValue>({\n density: \"comfortable\",\n zebra: false,\n hover: false,\n rowDividers: true,\n captionId: \"\",\n registerCaption: () => () => {},\n});\n\ntype TableSection = \"head\" | \"body\" | \"foot\";\n\n/** Which section a row sits in — zebra and hover apply to body rows only. `undefined`\n * outside the kit's section parts: a raw `<thead>` / `<tbody>`, which\n * {@link useSection} then reads off the DOM. */\nconst SectionContext = createContext<TableSection | undefined>(undefined);\n\nconst SECTION_OF_TAG: Record<string, TableSection> = { THEAD: \"head\", TBODY: \"body\", TFOOT: \"foot\" };\n\n/**\n * The section a row or cell sits in: the kit part's context where there is one, else the\n * nearest `<thead>` / `<tbody>` / `<tfoot>` in the DOM.\n *\n * keksdose's VAT summary writes a raw `<thead>` round kit cells in places, and a\n * `TableHeaderCell` there took itself for a BODY cell — `scope=\"row\"`, body type — with\n * nothing on the page to say why. React cannot see an ancestor's tag, so the fallback\n * reads it after mount; a layout effect, so the corrected cell is what gets painted.\n */\nfunction useSection<E extends HTMLElement>(): [TableSection, ((el: E | null) => void) | undefined] {\n const fromContext = useContext(SectionContext);\n const [node, setNode] = useState<E | null>(null);\n const [detected, setDetected] = useState<TableSection | undefined>(undefined);\n useLayoutEffect(() => {\n if (fromContext !== undefined || !node) return;\n const section = node.closest(\"thead, tbody, tfoot\");\n const found = section ? SECTION_OF_TAG[section.tagName] : undefined;\n // eslint-disable-next-line react-hooks/set-state-in-effect -- read off the DOM, which only exists after mount\n if (found !== detected) setDetected(found);\n }, [fromContext, node, detected]);\n // No ref at all under a kit section: holding the node would cost every row and cell\n // a second render on mount for an answer the context already gave.\n return [fromContext ?? detected ?? \"body\", fromContext === undefined ? setNode : undefined];\n}\n\n/** A {@link TableRow}'s `valign`, which its cells take unless they set their own. It\n * cannot be left to CSS inheritance: every cell states its own default alignment,\n * and a class on the cell beats one on the row. */\nconst RowVAlignContext = createContext<TableVAlign | undefined>(undefined);\n\nconst VALIGN: Record<TableVAlign, string> = {\n top: \"align-top\",\n middle: \"align-middle\",\n bottom: \"align-bottom\",\n};\n\nconst HEADER_SIZE: Record<TableHeaderCellSize, string> = {\n xs: \"text-xs\",\n sm: \"text-sm\",\n};\n\nconst HEADER_WEIGHT: Record<TableHeaderCellWeight, string> = {\n normal: \"font-normal\",\n medium: \"font-medium\",\n semibold: \"font-semibold\",\n};\n\nconst CELL_PAD: Record<TableDensity, string> = {\n comfortable: \"px-3 py-2\",\n compact: \"px-2 py-1\",\n none: \"p-0\",\n};\n\nconst ALIGN: Record<TableAlign, string> = {\n start: \"text-start\",\n center: \"text-center\",\n end: \"text-end\",\n};\n\n/**\n * The alignment a figure column wants: end-aligned (so the units line up under each\n * other in either reading direction) with tabular digits (so they line up at all).\n * Exported for a cell the kit did not render — a DataTable column, a `<td>` of the\n * app's own.\n */\nexport const NUMERIC_CELL_CLASS = \"text-end tabular-nums\";\n\nexport interface TableProps extends ComponentPropsWithoutRef<\"table\"> {\n /** `compact` for a dense detail view (a ledger, a spec sheet). */\n density?: TableDensity;\n /** Tint every other body row. */\n zebra?: boolean;\n /** Tint the body row under the pointer. Off by default: a static table whose rows\n * light up promises a click that does nothing. */\n hover?: boolean;\n /** Classes for the overflow wrapper around the `<table>` (a max-height, a border). */\n wrapperClassName?: string;\n /** See {@link TableLayout}. Unset leaves the browser's `auto` and adds no class. */\n layout?: TableLayout;\n /**\n * A rounded border round the whole table (0.12.0) — for a table standing on the page\n * or in a dialog rather than inside a card. kastlan wraps six of them in\n * `<div className=\"rounded-md border\">` by hand (payment allocation, the new-budget\n * lines, the meter readings, the deposit transactions, the unit values editor, the\n * maintenance detail), and a hand-made frame outside the scroll wrapper does not clip\n * the rows' tint to its corners.\n */\n framed?: boolean;\n /**\n * The rule between body rows. Default true. `false` for a small table whose rows are\n * spaced by their own content — keksdose's VAT summary, a block of three quiet\n * columns inside a card — which otherwise had to drop to raw `<tr>`s to lose it. One\n * row can still say otherwise with {@link TableRowProps.bordered}.\n */\n rowDividers?: boolean;\n /**\n * `\"phone\"`: below `sm` each body row becomes a block — its first cell the row's\n * title, every further cell under its column's header as a small label — and the\n * head row is visually hidden (still read by screen readers). For tables of PROSE,\n * not figures (lenkbank L5: a PID-terms table of three sentence columns wrapped into\n * two-word slivers at 390px and ran its third column off the screen). A table of\n * numbers should keep scrolling sideways, which is why this is opt-in. The labels\n * are the head row's cell texts, read from the DOM; a body cell spanning several\n * columns gets none.\n */\n stack?: \"phone\";\n}\n\n/**\n * Below `sm` on a `stack=\"phone\"` table: rows as blocks, the head visually hidden,\n * the first cell as a title, the others labelled by `data-label` (set by the table).\n */\nconst STACK_PHONE_CLASSES = cn(\n \"max-sm:block max-sm:[&_tbody]:block max-sm:[&_tfoot]:block\",\n \"max-sm:[&_thead]:sr-only\",\n \"max-sm:[&_tbody_tr]:block max-sm:[&_tbody_tr]:py-2 max-sm:[&_tfoot_tr]:block max-sm:[&_tfoot_tr]:py-2\",\n \"max-sm:[&_tbody_td]:block max-sm:[&_tbody_td]:px-0 max-sm:[&_tbody_td]:py-0.5 max-sm:[&_tbody_td]:text-start\",\n \"max-sm:[&_tfoot_td]:block max-sm:[&_tfoot_td]:px-0 max-sm:[&_tfoot_td]:py-0.5\",\n \"max-sm:[&_tbody_td:first-child]:font-medium\",\n \"max-sm:[&_td[data-label]]:before:block max-sm:[&_td[data-label]]:before:text-[11px] max-sm:[&_td[data-label]]:before:font-medium max-sm:[&_td[data-label]]:before:text-[var(--text-muted)] max-sm:[&_td[data-label]]:before:content-[attr(data-label)]\",\n);\n\n/**\n * A plain, static HTML table in the kit's tokens — for the detail views that need\n * rows and columns and none of {@link DataTable}'s sorting, filtering or paging.\n *\n * kastlan renders about twenty of these on shadcn's Table parts; the part names here\n * are the same idea (`TableHead` is the `<thead>`, `TableHeaderCell` the `<th>`), so\n * the move is a rename rather than a rewrite.\n *\n * The table sits in an overflow-x wrapper, because a table cannot shrink below its\n * content and on a phone it would otherwise widen the page. While it overflows that\n * wrapper becomes a tab stop and a `role=\"region\"` named by the `TableCaption` (or the\n * table's own `aria-label`), so a keyboard user can scroll it and a reader can say\n * what it is — the same contract as {@link ScrollArea}.\n *\n * Alignment is logical throughout (`text-start` / `text-end`), so a right-to-left\n * page gets its first column on the right without a class changing.\n */\nexport function Table({\n density = \"comfortable\",\n zebra = false,\n hover = false,\n wrapperClassName,\n layout,\n framed = false,\n rowDividers = true,\n stack,\n className,\n \"aria-label\": ariaLabel,\n ...rest\n}: TableProps) {\n const captionId = useId();\n const [captions, setCaptions] = useState(0);\n const wrapper = useRef<HTMLDivElement | null>(null);\n const overflowing = useScrollOverflow(wrapper);\n const tableRef = useRef<HTMLTableElement | null>(null);\n\n // `stack=\"phone\"`: label every body cell with its column's header text, and keep the\n // table's roles explicit — `display: block` on table parts drops their table\n // semantics in some engines. Re-run on any change to the rows, which the caller\n // renders and this component never sees.\n useLayoutEffect(() => {\n const table = tableRef.current;\n if (!stack || !table) return;\n const label = () => {\n const heads = Array.from(table.tHead?.rows[0]?.cells ?? []).map((cell) => cell.textContent?.trim() ?? \"\");\n table.setAttribute(\"role\", \"table\");\n for (const row of Array.from(table.rows)) {\n row.setAttribute(\"role\", \"row\");\n let column = 0;\n for (const cell of Array.from(row.cells)) {\n const span = cell.colSpan || 1;\n if (cell.tagName === \"TH\") cell.setAttribute(\"role\", cell.closest(\"thead\") ? \"columnheader\" : \"rowheader\");\n else cell.setAttribute(\"role\", \"cell\");\n const text = span === 1 && column > 0 ? heads[column] : undefined;\n if (cell.tagName === \"TD\" && text) cell.setAttribute(\"data-label\", text);\n else cell.removeAttribute(\"data-label\");\n column += span;\n }\n }\n };\n label();\n const observer = typeof MutationObserver === \"undefined\" ? null : new MutationObserver(label);\n observer?.observe(table, { childList: true, subtree: true, characterData: true });\n return () => observer?.disconnect();\n }, [stack]);\n\n const ctx = useMemo<TableContextValue>(\n () => ({\n density,\n zebra,\n hover,\n rowDividers,\n captionId,\n registerCaption: () => {\n setCaptions((n) => n + 1);\n return () => setCaptions((n) => n - 1);\n },\n }),\n [density, zebra, hover, rowDividers, captionId],\n );\n\n const regionName = captions > 0 ? { \"aria-labelledby\": captionId } : ariaLabel ? { \"aria-label\": ariaLabel } : null;\n\n return (\n <TableContext.Provider value={ctx}>\n <div\n ref={wrapper}\n // Only a region when it scrolls AND has a name: a landmark for every short\n // table on a page would bury the real ones.\n role={overflowing && regionName ? \"region\" : undefined}\n {...(overflowing ? regionName : null)}\n tabIndex={overflowing ? 0 : undefined}\n data-overflowing={overflowing || undefined}\n data-clips=\"\"\n data-framed={framed || undefined}\n className={cn(\n // `relative`: the containing block for an `sr-only` caption.\n \"relative w-full overflow-x-auto\",\n // On the scroll wrapper itself, so its clipping keeps the rows inside the\n // rounded corners.\n framed && \"rounded-md border border-[var(--border)]\",\n THIN_SCROLLBAR_CLASS,\n \"focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-[var(--brand)]\",\n wrapperClassName,\n )}\n >\n <table\n {...rest}\n ref={tableRef}\n aria-label={ariaLabel}\n className={cn(\n \"w-full caption-bottom border-collapse text-sm text-[var(--text-primary)]\",\n density === \"compact\" && \"text-xs\",\n layout === \"fixed\" && \"table-fixed\",\n layout === \"auto\" && \"table-auto\",\n stack === \"phone\" && STACK_PHONE_CLASSES,\n className,\n )}\n />\n </div>\n </TableContext.Provider>\n );\n}\n\nexport interface TableHeadProps extends ComponentPropsWithoutRef<\"thead\"> {\n /** The rule under the head. Default true; `false` for a quiet header over a small\n * table (keksdose's VAT summary wrote `className=\"border-b-0\"` to lose it). */\n bordered?: boolean;\n}\n\nexport function TableHead({ bordered = true, className, ...rest }: TableHeadProps) {\n return (\n <SectionContext.Provider value=\"head\">\n <thead {...rest} className={cn(bordered && \"border-b border-[var(--border)]\", className)} />\n </SectionContext.Provider>\n );\n}\n\nexport interface TableBodyProps extends ComponentPropsWithoutRef<\"tbody\"> {\n /**\n * Shown as ONE full-width row (a {@link TableEmpty}) when the body has no rows —\n * `children` that render nothing: an empty `.map`, a `false`, `null`. kastlan hand-\n * writes that row with a counted `colSpan` in unit-values-editor, the meeting agenda\n * and invitations tabs, the journal-entry and invoice detail pages, and a column\n * added later leaves every one of those counts one short.\n */\n empty?: ReactNode;\n}\n\nexport function TableBody({ className, empty, children, ...rest }: TableBodyProps) {\n // `toArray` drops null/undefined/booleans and flattens arrays, so `[[], false]` —\n // an empty map beside a conditional row that is off — is no rows.\n const hasRows = Children.toArray(children).length > 0;\n return (\n <SectionContext.Provider value=\"body\">\n <tbody {...rest} className={cn(\"[&>tr:last-child]:border-b-0\", className)}>\n {hasRows || empty === undefined || empty === null || empty === false ? (\n children\n ) : (\n <TableEmpty>{empty}</TableEmpty>\n )}\n </tbody>\n </SectionContext.Provider>\n );\n}\n\nexport interface TableEmptyProps extends Omit<ComponentPropsWithoutRef<\"tr\">, \"children\"> {\n children: ReactNode;\n /** Columns to span. Default: MEASURED — the widest row of the table it renders in,\n * counted after mount, so the row stays full width when a column is added. */\n colSpan?: number;\n /** Classes for the `<td>`. */\n cellClassName?: string;\n}\n\n/**\n * The \"nothing here\" row: one cell across every column, centred, muted. What\n * {@link TableBodyProps.empty} renders, and usable on its own for a body whose rows\n * are not its direct children.\n */\nexport function TableEmpty({ children, colSpan, cellClassName, className, ...rest }: TableEmptyProps) {\n const { density } = useContext(TableContext);\n const cell = useRef<HTMLTableCellElement | null>(null);\n const [measured, setMeasured] = useState(1);\n // Every render, deliberately: a column can appear in the head without anything this\n // row depends on changing. It cannot loop — setting the same count is a bail-out.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useLayoutEffect(() => {\n if (colSpan !== undefined) return;\n const row = cell.current?.parentElement;\n const table = cell.current?.closest(\"table\");\n if (!row || !table) return;\n let widest = 1;\n for (const r of Array.from(table.rows)) {\n if (r === row) continue;\n let n = 0;\n for (const c of Array.from(r.cells)) n += c.colSpan || 1;\n widest = Math.max(widest, n);\n }\n setMeasured(widest);\n });\n return (\n <tr {...rest} data-table-empty=\"\" className={className}>\n <td\n ref={cell}\n colSpan={colSpan ?? measured}\n className={cn(\n // `none` keeps the message off the edges regardless: it is text, not a figure.\n density === \"none\" ? \"py-2\" : CELL_PAD[density],\n \"text-center text-[var(--text-muted)]\",\n cellClassName,\n )}\n >\n {children}\n </td>\n </tr>\n );\n}\n\nexport type TableFootProps = ComponentPropsWithoutRef<\"tfoot\">;\n\n/** The totals row. Not in the brief, but every ledger view has one and a `<tfoot>`\n * is what tells a reader it is a total rather than one more row. */\nexport function TableFoot({ className, ...rest }: TableFootProps) {\n return (\n <SectionContext.Provider value=\"foot\">\n <tfoot {...rest} className={cn(\"border-t border-[var(--border-strong)] font-medium\", className)} />\n </SectionContext.Provider>\n );\n}\n\nconst ROW_VARIANT: Record<TableRowVariant, string | false> = {\n row: false,\n group: \"bg-[var(--bg-surface-2)] font-semibold\",\n subtotal: \"font-medium\",\n // A 2px rule over the 1px divider the row above draws on its bottom: collapsed\n // borders meet on one line, the wider wins, and the heavier rule is what says \"sum\".\n total: \"border-t-2 border-t-[var(--border-strong)] font-semibold\",\n};\n\n/** The deprecated HTML `valign` attribute is replaced by a class-backed one. */\nexport interface TableRowProps extends ComponentPropsWithoutRef<\"tr\"> {\n /** Vertical alignment for every cell of the row that does not set its own. See\n * {@link TableVAlign}. Left out, each cell keeps its default. */\n valign?: TableVAlign;\n /** See {@link TableRowVariant}. Default `row`. Zebra and hover tint ordinary rows\n * only: a group heading or a total is not one more record. */\n variant?: TableRowVariant;\n /** The rule under this body row. Default: the table's `rowDividers`. */\n bordered?: boolean;\n}\n\nexport function TableRow({ valign, variant = \"row\", bordered, className, ...rest }: TableRowProps) {\n const { zebra, hover, rowDividers } = useContext(TableContext);\n const [section, ref] = useSection<HTMLTableRowElement>();\n const body = section === \"body\";\n const record = body && variant === \"row\";\n const row = (\n <tr\n ref={ref}\n {...rest}\n data-variant={variant === \"row\" ? undefined : variant}\n className={cn(\n body && (bordered ?? rowDividers) && \"border-b border-[var(--border)]\",\n record && zebra && \"even:bg-[var(--bg-surface-2)]\",\n record && hover && \"transition-colors hover:bg-[var(--bg-hover)]\",\n ROW_VARIANT[variant],\n // On the row as well, for a raw `<td>` of the caller's, which inherits it.\n valign && VALIGN[valign],\n className,\n )}\n />\n );\n return valign ? <RowVAlignContext.Provider value={valign}>{row}</RowVAlignContext.Provider> : row;\n}\n\ninterface CellAlignProps {\n /** Shorthand for a figure column: end-aligned, tabular digits. */\n numeric?: boolean;\n /** Logical alignment. Default `start` (`end` when `numeric`). */\n align?: TableAlign;\n /** Vertical alignment. Default: the row's `valign`, else `bottom` for a head cell and\n * `top` for a body cell. See {@link TableVAlign}. */\n valign?: TableVAlign;\n}\n\n/** The deprecated HTML `align` and `valign` attributes are replaced by class-backed ones. */\nexport interface TableHeaderCellProps extends Omit<ComponentPropsWithoutRef<\"th\">, \"align\" | \"valign\">, CellAlignProps {\n /**\n * Type size. Left out: `xs` in the head, the table's own size in the body — as\n * before. keksdose's VAT summary heads its columns at the body size and normal weight\n * (vat-summary.tsx:158–168, `font-normal` on each `<th>`), a quiet header over a\n * small table of figures, and could not say so without overriding classes.\n */\n size?: TableHeaderCellSize;\n /** Default `medium`. `normal` for the quiet header above; see {@link size}. */\n weight?: TableHeaderCellWeight;\n}\n\n/**\n * A `<th>`. `scope` defaults to `col` in the head and `row` in the body — a header\n * cell in a body row is the row's label (\"Net rent\" in a key-value table), and a\n * reader needs the scope to read it with each cell beside it.\n */\nexport function TableHeaderCell({\n numeric = false,\n align,\n valign,\n size,\n weight = \"medium\",\n scope,\n className,\n ...rest\n}: TableHeaderCellProps) {\n const { density } = useContext(TableContext);\n const [section, ref] = useSection<HTMLTableCellElement>();\n const rowVAlign = useContext(RowVAlignContext);\n const head = section === \"head\";\n const textSize = size ?? (head ? \"xs\" : undefined);\n return (\n <th\n ref={ref}\n {...rest}\n scope={scope ?? (section === \"head\" ? \"col\" : \"row\")}\n className={cn(\n CELL_PAD[density],\n ALIGN[align ?? (numeric ? \"end\" : \"start\")],\n numeric && \"tabular-nums\",\n VALIGN[valign ?? rowVAlign ?? (head ? \"bottom\" : \"top\")],\n HEADER_WEIGHT[weight],\n head ? \"text-[var(--text-muted)]\" : \"text-[var(--text-secondary)]\",\n textSize && HEADER_SIZE[textSize],\n className,\n )}\n />\n );\n}\n\nexport interface TableCellProps extends Omit<ComponentPropsWithoutRef<\"td\">, \"align\" | \"valign\">, CellAlignProps {}\n\nexport function TableCell({ numeric = false, align, valign, className, ...rest }: TableCellProps) {\n const { density } = useContext(TableContext);\n const rowVAlign = useContext(RowVAlignContext);\n return (\n <td\n {...rest}\n className={cn(\n CELL_PAD[density],\n VALIGN[valign ?? rowVAlign ?? \"top\"],\n ALIGN[align ?? (numeric ? \"end\" : \"start\")],\n numeric && \"tabular-nums whitespace-nowrap\",\n className,\n )}\n />\n );\n}\n\nexport type TableCaptionProps = ComponentPropsWithoutRef<\"caption\">;\n\n/**\n * The table's title. Beneath the table by default (`caption-bottom`, the shadcn\n * convention kastlan's views already follow); `className=\"caption-top\"` moves it.\n * `className=\"sr-only\"` keeps it for readers only — the wrapper is `relative`, so\n * the hidden caption stays inside it.\n *\n * It also names the scroll region when the table overflows: it registers itself\n * with the {@link Table} so the wrapper points at an id that exists, and never at\n * one that does not.\n */\nexport function TableCaption({ className, id, ...rest }: TableCaptionProps) {\n const { captionId, registerCaption } = useContext(TableContext);\n useLayoutEffect(() => (id ? undefined : registerCaption()), [id, registerCaption]);\n return (\n <caption\n {...rest}\n id={id ?? captionId}\n className={cn(\"mt-2 text-start text-sm text-[var(--text-muted)]\", className)}\n />\n );\n}\n"],"mappings":";AAwSQ;AAxSR,SAAS,UAAU,eAAe,YAAY,OAAO,iBAAiB,SAAS,QAAQ,gBAAgB;AAEvG,SAAS,UAAU;AACnB,SAAS,sBAAsB,yBAAyB;AA+CxD,MAAM,eAAe,cAAiC;AAAA,EACpD,SAAS;AAAA,EACT,OAAO;AAAA,EACP,OAAO;AAAA,EACP,aAAa;AAAA,EACb,WAAW;AAAA,EACX,iBAAiB,MAAM,MAAM;AAAA,EAAC;AAChC,CAAC;AAOD,MAAM,iBAAiB,cAAwC,MAAS;AAExE,MAAM,iBAA+C,EAAE,OAAO,QAAQ,OAAO,QAAQ,OAAO,OAAO;AAWnG,SAAS,aAA0F;AACjG,QAAM,cAAc,WAAW,cAAc;AAC7C,QAAM,CAAC,MAAM,OAAO,IAAI,SAAmB,IAAI;AAC/C,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,QAAQ;AAAA,QAChC;AAAA,MACF;AAAA;AAAA,EACF;AAEJ;AAIO,SAAS,UAAU,EAAE,UAAU,OAAO,OAAO,QAAQ,WAAW,GAAG,KAAK,GAAmB;AAChG,QAAM,EAAE,QAAQ,IAAI,WAAW,YAAY;AAC3C,QAAM,YAAY,WAAW,gBAAgB;AAC7C,SACE;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,WAAW;AAAA,QACT,SAAS,OAAO;AAAA,QAChB,OAAO,UAAU,aAAa,KAAK;AAAA,QACnC,MAAM,UAAU,UAAU,QAAQ,QAAQ;AAAA,QAC1C,WAAW;AAAA,QACX;AAAA,MACF;AAAA;AAAA,EACF;AAEJ;AAcO,SAAS,aAAa,EAAE,WAAW,IAAI,GAAG,KAAK,GAAsB;AAC1E,QAAM,EAAE,WAAW,gBAAgB,IAAI,WAAW,YAAY;AAC9D,kBAAgB,MAAO,KAAK,SAAY,gBAAgB,GAAI,CAAC,IAAI,eAAe,CAAC;AACjF,SACE;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,IAAI,MAAM;AAAA,MACV,WAAW,GAAG,oDAAoD,SAAS;AAAA;AAAA,EAC7E;AAEJ;","names":[]}
|
|
@@ -20,6 +20,15 @@ interface ToggleGroupBaseProps<T extends string> extends Omit<ComponentPropsWith
|
|
|
20
20
|
/** Applied to every option button (e.g. to tune height/rounding to match
|
|
21
21
|
* adjacent fields). Per-option `className` still wins over this. */
|
|
22
22
|
optionClassName?: string;
|
|
23
|
+
/**
|
|
24
|
+
* What happens when the options do not fit the group's width. `"truncate"`
|
|
25
|
+
* (default): one row, and the labels that do not fit end in an ellipsis — the height
|
|
26
|
+
* never changes. `"wrap"`: the segments flow onto a second row and every label stays
|
|
27
|
+
* whole ("Bewegung", not "Beweg…"), at the price of a taller group on a narrow
|
|
28
|
+
* screen (lenkbank L4: five signal types on a 390px control page). From the width
|
|
29
|
+
* where they fit, both look the same.
|
|
30
|
+
*/
|
|
31
|
+
overflow?: "truncate" | "wrap";
|
|
23
32
|
/**
|
|
24
33
|
* @deprecated Pass `aria-label` instead — the DOM spelling, which every other
|
|
25
34
|
* control in this kit now answers to. Kept working because three applications ship
|
|
@@ -10,6 +10,7 @@ function ToggleGroup(props) {
|
|
|
10
10
|
options,
|
|
11
11
|
className,
|
|
12
12
|
optionClassName,
|
|
13
|
+
overflow = "truncate",
|
|
13
14
|
ariaLabel,
|
|
14
15
|
disabled = false,
|
|
15
16
|
size = "md",
|
|
@@ -78,6 +79,7 @@ function ToggleGroup(props) {
|
|
|
78
79
|
// `hover:` in `@media (hover: hover)`, so a phone never paints it. The half a
|
|
79
80
|
// phone does see is the focus ring — see the segment's own note below.)
|
|
80
81
|
"inline-flex w-full gap-0.5 rounded-md border border-[var(--border-strong)] bg-[var(--bg-surface)] p-0.5 shadow-sm",
|
|
82
|
+
overflow === "wrap" && "flex-wrap",
|
|
81
83
|
// The whole group fades, the way every other disabled control in this
|
|
82
84
|
// package does; `cursor-not-allowed` is on the buttons, which is what a
|
|
83
85
|
// pointer is actually over.
|
|
@@ -125,7 +127,8 @@ function ToggleGroup(props) {
|
|
|
125
127
|
// overlaying the selected segment's boundary. Inset keeps the ring
|
|
126
128
|
// inside the segment it belongs to; focus-visible keeps it for the
|
|
127
129
|
// keyboard, which is the only input that needs it.
|
|
128
|
-
|
|
130
|
+
overflow === "wrap" ? "whitespace-nowrap" : "min-w-0 truncate",
|
|
131
|
+
"flex-1 basis-auto rounded px-3 py-1.5 text-sm font-medium transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--border-strong)]",
|
|
129
132
|
size === "sm" && "px-2 py-1 text-xs",
|
|
130
133
|
// In a field: no vertical padding and a 20px line — a `text-sm` line, the
|
|
131
134
|
// same line a labelled Select holds under its label strip — so the field's
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/components/toggle-group.tsx"],"sourcesContent":["import { useId } from \"react\";\nimport type { ComponentPropsWithoutRef, KeyboardEvent, ReactElement, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { horizontalStep } from \"../lib/direction\";\nimport { FIELD_INVALID, FloatingField, Label } from \"./ui\";\n\nexport interface ToggleOption<T extends string> {\n value: T;\n label: string;\n className?: string;\n}\n\n/**\n * `onChange` is the group's own — the chosen VALUE, not a DOM event — so the div's\n * `onChange` is omitted rather than shadowed: leaving both in scope would give the\n * prop two incompatible meanings depending on which overload TypeScript picked.\n *\n * `children` is omitted too: this renders its `options` and nothing else, so a `children` the type\n * accepted and the component ignored would be a prop that silently does nothing —\n * worse than one that does not compile.\n */\nexport interface ToggleGroupBaseProps<T extends string>\n extends Omit<ComponentPropsWithoutRef<\"div\">, \"onChange\" | \"children\"> {\n options: ToggleOption<T>[];\n className?: string;\n /** Applied to every option button (e.g. to tune height/rounding to match\n * adjacent fields). Per-option `className` still wins over this. */\n optionClassName?: string;\n /**\n * @deprecated Pass `aria-label` instead — the DOM spelling, which every other\n * control in this kit now answers to. Kept working because three applications ship\n * this one today; it names the group only when `aria-label` is absent.\n */\n ariaLabel?: string;\n /**\n * Show, refuse the change (Keksdose live #288: a payment dated in the future has no\n * state to set).\n *\n * Whatever `value` says stays pressed and keeps its own fill rather than going grey\n * with the rest — a reader who cannot see WHICH option is chosen has been told less\n * than before it was disabled. A caller with nothing to show passes no value, and\n * the group renders dimmed with nothing pressed, which is the shape Keksdose's\n * status picker uses for a row whose status does not exist yet.\n *\n * On the whole GROUP, not per option: a segmented control where some segments are\n * live and others are not is a menu with holes in it, and no caller here wants one.\n */\n disabled?: boolean;\n /**\n * `sm`: 12px options with `px-2 py-1` — the compact group keksdose's rule editor\n * (rule-editor:204) writes as `optionClassName=\"px-2 py-1 text-xs\"` beside a small\n * caption. `md` (default) is the size every other group has.\n */\n size?: \"sm\" | \"md\";\n /**\n * Stand in a form row as a FIELD: with a label the group wears the field's chrome —\n * border, surface, the top strip with a small static label in it, a labelled\n * {@link Select}'s height — so beside an Input or a Select it reads as one of them\n * rather than as a control with a caption over it. lenkbank builds exactly this by\n * hand as `ToggleField` (features/gear/common.tsx:97, feedback #69), and its notes\n * are why the chrome STRETCHES to its row as well as matching the select's padding:\n * a native select's height is the browser's, so a toggle a few pixels short of it\n * is levelled up by the row rather than by arithmetic.\n *\n * The label names the group (`aria-labelledby`), so `aria-label` is not needed. With\n * a label, `className` styles the field's wrapper — as on {@link Select} — and the\n * group's own box is dropped: two nested borders read as a control in a control.\n */\n label?: ReactNode;\n /**\n * Where `label` goes. `\"field\"` (default): the field chrome described under `label`.\n * `\"above\"`: the kit's {@link Label} over the bare group — the shape of a {@link Field}\n * — with `hint` beside the label and `error` under the group, for a form that sets\n * its labels above its fields (kastlan's international-rent-calculator.tsx, whose DE\n * cap pair sits in a `Field` column between two labelled-above inputs, where the\n * chrome's inner label would be the only one of its kind).\n *\n * Inside a `Field`, pass no `label` at all and spread the render-prop instead —\n * `{(ids, { labelId }) => <ToggleGroup {...ids} aria-labelledby={labelId} … />}` —\n * so the Field's label names the group and its hint and error describe it.\n */\n labelPlacement?: \"field\" | \"above\";\n /** A {@link FieldHint} on the label line, as on a labelled {@link Select}. Only with\n * `label`. */\n hint?: ReactNode;\n /** The message under the field when it is wrong: paints the field's border with\n * `--danger`, marks the group `aria-invalid` and describes it with the message, as\n * {@link Select}'s `error` does. Only with `label`. */\n error?: ReactNode;\n}\n\n/**\n * A line under the group saying what the CHOSEN option means — lenkbank's ToggleField\n * `hint` (features/gear/common.tsx:97): not help behind a \"?\" but a caption, and one\n * that changes as the choice does. Pass a function of the value for that; it is\n * attached with `aria-describedby`, and a function caption is also a polite live\n * region, because a description is read when the group is entered and not again when\n * an arrow key changes the choice underneath it.\n *\n * In muted 11px text under the field (or the bare group), above an `error`.\n */\ntype ToggleGroupCaption<V> = ReactNode | ((value: V) => ReactNode);\n\n/** The group as it has always been: one option is always the answer. */\nexport interface ToggleGroupRequiredProps<T extends string> extends ToggleGroupBaseProps<T> {\n allowEmpty?: false;\n /**\n * What the options ARE to a screen reader, separately from whether the group can be\n * emptied (kastlan feedback #47).\n *\n * - `\"radio\"` (default) — a `radiogroup` of radios: one Tab stop, arrow keys MOVE the\n * choice. Right for a choice between answers (\"Monthly / Yearly\").\n * - `\"pressed\"` — a `group` of toggle buttons (`aria-pressed`), each its own Tab stop,\n * Space/Enter to press; still one option always pressed. Right for a row that reads\n * as a set of switches — a view mode, a toolbar-like filter — where arrows moving the\n * selection on focus would be a surprise.\n *\n * Before this the only way to `aria-pressed` was `allowEmpty`, which also let a second\n * press clear the choice — so kastlan took the clearable shape and threw the `null`\n * away in `onChange` (`(v) => v && setMode(v)`), a group announcing that a press would\n * unpress what it would not. Here a press on the pressed option re-sends its value, as\n * the radio shape does, and nothing is ever unpressed. A clearable group\n * (`allowEmpty`) is always `\"pressed\"`: a radio cannot be unchecked by activating it.\n */\n semantics?: \"radio\" | \"pressed\";\n value: T;\n onChange: (value: T) => void;\n /** See {@link ToggleGroupCaption}. */\n caption?: ToggleGroupCaption<T>;\n}\n\n/**\n * A group that can be emptied: clicking the active option clears it, and `onChange`\n * receives `null` (Keksdose's support-panel filters, where \"no filter\" is reached by\n * clicking the filter that is on).\n *\n * The options become TOGGLE BUTTONS (`aria-pressed`, in a `role=\"group\"`) rather than\n * radios. A radio cannot be unchecked by activating it — no screen reader user expects\n * a second press on \"Open, radio, checked\" to leave nothing checked, and nothing would\n * tell them it had. \"Open, toggle button, pressed\" says exactly what a press will do.\n */\nexport interface ToggleGroupClearableProps<T extends string> extends ToggleGroupBaseProps<T> {\n allowEmpty: true;\n /** Always toggle buttons — see {@link ToggleGroupRequiredProps.semantics}. Accepted so\n * a wrapper can forward one `semantics` to either shape. */\n semantics?: \"pressed\";\n value: T | null;\n onChange: (value: T | null) => void;\n /** See {@link ToggleGroupCaption}. `null` while nothing is chosen. */\n caption?: ToggleGroupCaption<T | null>;\n}\n\n/** `allowEmpty` picks the shape, so `onChange` is typed `(T) => void` unless the group\n * can actually emit `null` — no existing caller has a `null` to handle. */\nexport type ToggleGroupProps<T extends string> =\n | ToggleGroupRequiredProps<T>\n | ToggleGroupClearableProps<T>;\n\n/**\n * Overloaded rather than typed by the union alone (keksdose, \"Gaps found adopting\n * 0.6.0\" #7). Inferring `T` through a union of prop shapes let TypeScript settle on\n * `string`, so `<ToggleGroup allowEmpty value={filter} onChange={setFilter} />` over a\n * `useState<Status | null>` did not compile unless the caller spelled\n * `<ToggleGroup<Status>>`. One signature per mode lets each infer `T` from its own\n * `value`/`onChange`/`options`; the third keeps a caller that forwards a\n * {@link ToggleGroupProps} union (a wrapper component) compiling.\n */\nexport function ToggleGroup<T extends string>(props: ToggleGroupClearableProps<T>): ReactElement;\nexport function ToggleGroup<T extends string>(props: ToggleGroupRequiredProps<T>): ReactElement;\nexport function ToggleGroup<T extends string>(props: ToggleGroupProps<T>): ReactElement;\nexport function ToggleGroup<T extends string>(props: ToggleGroupProps<T>): ReactElement {\n const {\n value,\n options,\n className,\n optionClassName,\n ariaLabel,\n disabled = false,\n size = \"md\",\n label,\n labelPlacement = \"field\",\n hint,\n error,\n \"aria-label\": ariaLabelAttr,\n ...restWithMode\n } = props;\n const labelId = useId();\n const errorId = useId();\n const labelled = label !== undefined && label !== null && label !== false && label !== \"\";\n // `field` is the chrome; a label placed above keeps the bare group's own box.\n const field = labelled && labelPlacement === \"field\";\n const above = labelled && labelPlacement === \"above\";\n const hasError = labelled && error !== undefined && error !== null && error !== false && error !== \"\";\n // Taken off the rest so neither reaches the DOM; `props` keeps them paired, which is\n // what lets the `onChange` below be called with `null` only in the mode that allows it.\n const { allowEmpty: _allowEmpty, onChange: _onChange, caption, semantics: _semantics, ...rest } = restWithMode;\n // Invalid from outside too: a `Field` hands the bare group `aria-invalid`, and the\n // border has to say what the attribute says.\n const outsideInvalid = rest[\"aria-invalid\"] === true || rest[\"aria-invalid\"] === \"true\";\n const captionId = useId();\n const captionIsLive = typeof caption === \"function\";\n const captionNode = captionIsLive ? (caption as (v: T | null) => ReactNode)(value) : caption;\n const hasCaption = captionNode !== undefined && captionNode !== null && captionNode !== false && captionNode !== \"\";\n const choose = (next: T) => {\n if (props.allowEmpty) props.onChange(next === value ? null : next);\n else props.onChange(next);\n };\n // `pressed`: toggle buttons. Every clearable group is; a required one is when it asks\n // (kastlan #47) — the role, and not whether a second press clears, is what this flag\n // decides from here on, so `choose` above still keys off `allowEmpty` alone.\n const pressed = props.allowEmpty === true || props.semantics === \"pressed\";\n // A radio group is ONE tab stop (the checked radio, else the first) and arrows move\n // the choice — the pattern `role=\"radiogroup\"` promises a screen-reader user. Before\n // 0.7.0 each segment was its own tab stop with no arrow keys. The toggle-button shape\n // is a row of buttons, where separate tab stops are the pattern.\n const tabStop = options.some((o) => o.value === value) ? value : options[0]?.value;\n const onRadioKey = (e: KeyboardEvent<HTMLButtonElement>, index: number) => {\n const last = options.length - 1;\n let next: number | null = null;\n const step = horizontalStep(e.key, e.currentTarget);\n if (step !== 0) next = index + step;\n else if (e.key === \"ArrowDown\") next = index + 1;\n else if (e.key === \"ArrowUp\") next = index - 1;\n else if (e.key === \"Home\") next = 0;\n else if (e.key === \"End\") next = last;\n if (next === null) return;\n e.preventDefault();\n next = next < 0 ? last : next > last ? 0 : next;\n const buttons = e.currentTarget.parentElement?.querySelectorAll<HTMLButtonElement>(\":scope > button\");\n buttons?.[next]?.focus();\n choose(options[next].value);\n };\n const group = (\n <div\n // The audit's named example of a closed prop list (§\"Public API design\"): the\n // tour locates a step by CSS SELECTOR, so a component that drops every attribute\n // it was not expecting cannot be spotlighted at all — and Keksdose's rule editor\n // carries a comment explaining that it wraps this group in a bare <div> for\n // exactly that reason.\n //\n // `...rest` first, then the attributes the group cannot do without: a caller\n // hanging an anchor or a test id on the group must not be able to overwrite the\n // radiogroup role or the disabled state by accident. `className` is destructured\n // out entirely and merged through `cn`, so it is never in here.\n {...rest}\n role={pressed ? \"group\" : \"radiogroup\"}\n // The DOM spelling wins; `ariaLabel` is the fallback for the call sites that\n // have not moved yet.\n aria-label={ariaLabelAttr ?? ariaLabel}\n aria-labelledby={labelled && ariaLabelAttr === undefined && ariaLabel === undefined ? labelId : rest[\"aria-labelledby\"]}\n aria-invalid={hasError || rest[\"aria-invalid\"] || undefined}\n aria-describedby={\n [rest[\"aria-describedby\"], hasCaption && captionId, hasError && errorId].filter(Boolean).join(\" \") || undefined\n }\n // `aria-disabled` on the group as well as `disabled` on each button: a radio\n // group is what the user is being refused, and a screen reader announcing\n // three separately-disabled radios does not say that.\n aria-disabled={disabled || undefined}\n className={cn(\n // `gap-0.5` — the same 2px as the container's own padding, so EVERY segment\n // sits in a uniform 2px moat and no two fills ever touch. Flush segments were\n // Keksdose live #268's rework: the pressed segment wears a saturated fill and\n // an unpressed neighbour wears a pale hover fill, and with a shared edge the\n // two rectangles read as one smeared shape — *\"the boundary of the selected\n // option and hovering next to it overlays the boundary of the selected\n // button\"*. A gap is what makes each segment its own chip; it cannot be\n // undone by a caller's per-option colour, which a hover-only fix could.\n //\n // (The hover fill is the DESKTOP half of that report: Tailwind v4 wraps every\n // `hover:` in `@media (hover: hover)`, so a phone never paints it. The half a\n // phone does see is the focus ring — see the segment's own note below.)\n \"inline-flex w-full gap-0.5 rounded-md border border-[var(--border-strong)] bg-[var(--bg-surface)] p-0.5 shadow-sm\",\n // The whole group fades, the way every other disabled control in this\n // package does; `cursor-not-allowed` is on the buttons, which is what a\n // pointer is actually over.\n disabled && \"opacity-60\",\n // The bare group (no chrome to paint) wears the invalid border itself.\n !field && (outsideInvalid || (above && hasError)) && FIELD_INVALID,\n // Inside the field's chrome the group is only a row of segments: no border, no\n // surface, no padding of its own, and the field (not the group) is what dims.\n field && \"border-0 bg-transparent p-0 shadow-none opacity-100\",\n !labelled && className,\n )}\n >\n {options.map((opt, index) => {\n const active = opt.value === value;\n return (\n <button\n key={opt.value}\n type=\"button\"\n role={pressed ? undefined : \"radio\"}\n aria-checked={pressed ? undefined : active}\n aria-pressed={pressed ? active : undefined}\n disabled={disabled}\n tabIndex={pressed ? undefined : opt.value === tabStop ? 0 : -1}\n onKeyDown={pressed ? undefined : (e) => onRadioKey(e, index)}\n onClick={() => choose(opt.value)}\n className={cn(\n // `truncate` (which carries whitespace-nowrap) rather than letting a\n // label wrap: a segmented control sizes its whole row to the tallest\n // option, so one two-word option — Keksdose feedback #147's \"Where I\n // am\" — silently doubles the height of every segment beside it.\n //\n // `basis-auto` is what keeps that ellipsis a LAST resort rather than\n // the normal state (Keksdose dev#475). With flex-1's `basis-0`, a\n // shrink-to-fit group (`w-auto`) still resolves to the sum of the\n // labels' widths — and then splits it EQUALLY, so the short option\n // got 66px it did not need and \"Where I am\" got 66 of the 81 it did:\n // truncated at 1778px of free screen. Basing each segment on its own\n // content and sharing only the LEFTOVER space keeps a full-width\n // group's segments near-equal and an auto-width group's exact.\n //\n // `focus-visible` + `ring-inset`, not `focus` + an outset ring. A ring\n // is a box-shadow that spreads OUTWARD, so on a flush group it painted\n // 2px of ring over both neighbours and over the container's own border\n // — and on a phone it appeared on every TAP, because a tap focuses the\n // button. That is the other half of what live #268's rework saw\n // overlaying the selected segment's boundary. Inset keeps the ring\n // inside the segment it belongs to; focus-visible keeps it for the\n // keyboard, which is the only input that needs it.\n \"min-w-0 flex-1 basis-auto truncate rounded px-3 py-1.5 text-sm font-medium transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--border-strong)]\",\n size === \"sm\" && \"px-2 py-1 text-xs\",\n // In a field: no vertical padding and a 20px line — a `text-sm` line, the\n // same line a labelled Select holds under its label strip — so the field's\n // own `pt-4 pb-1` decides the height, as it does for the select.\n field && \"py-0 leading-5\",\n active\n ? \"bg-[var(--bg-inverse)] text-[var(--text-inverse)]\"\n : \"text-[var(--text-secondary)] hover:bg-[var(--bg-hover)]\",\n // No hover fill on a group that cannot be changed — a segment that\n // lights up under the pointer is an offer, and there is none here.\n disabled && \"cursor-not-allowed hover:bg-transparent dark:hover:bg-transparent\",\n optionClassName,\n opt.className,\n )}\n >\n {opt.label}\n </button>\n );\n })}\n </div>\n );\n // Rendered whenever the caption is — `aria-live` must be on the element BEFORE its\n // text changes, or the change is not announced — but empty (no height, no margin)\n // when there is nothing to say, so a function caption that returns null for some\n // options leaves no gap. Empty rather than `hidden`: some readers do not announce\n // text that appears inside an element coming back from `display: none`.\n const captionEl =\n hasCaption || captionIsLive ? (\n <p\n id={captionId}\n aria-live={captionIsLive ? \"polite\" : undefined}\n className={cn(\"text-[11px] leading-snug text-[var(--text-muted)]\", hasCaption && \"mt-1\")}\n >\n {hasCaption ? captionNode : null}\n </p>\n ) : null;\n const errorEl = hasError ? (\n <p id={errorId} className=\"mt-1 text-[11px] leading-tight text-[var(--danger)]\">\n {error}\n </p>\n ) : null;\n if (above) {\n // `relative` so a caller's `sr-only` label cannot escape (sr-only-containment).\n return (\n <div className={cn(\"relative grid min-w-0 gap-1.5\", className)}>\n <div className=\"flex items-center gap-1\">\n {/* A `<label>` with no `htmlFor`: a group is not labelable, so it is named\n by `aria-labelledby` on the group; the element keeps the Field look. */}\n <Label\n id={labelId}\n disabled={disabled}\n data-error={hasError || undefined}\n className=\"data-[error=true]:text-[var(--danger)]\"\n >\n {label}\n </Label>\n {hint}\n </div>\n <div className=\"min-w-0\">\n {group}\n {captionEl}\n {errorEl}\n </div>\n </div>\n );\n }\n if (!field) {\n if (!captionEl) return group;\n // The group keeps its `className`, as without a caption; the wrapper only stacks.\n return (\n <div className=\"min-w-0\">\n {group}\n {captionEl}\n </div>\n );\n }\n return (\n // `h-full` + `flex-1`: the chrome fills a grid or stretched flex row, which is what\n // levels it with a select beside it whatever the browser makes of the select.\n <div className={cn(\"flex h-full flex-col\", className)}>\n <FloatingField\n className=\"flex flex-1 flex-col\"\n label={<span id={labelId}>{label}</span>}\n staticLabel\n hint={hint}\n >\n <div\n className={cn(\n \"flex flex-1 flex-col justify-center rounded-md border border-[var(--border)] bg-[var(--bg-surface)] px-1 pt-4 pb-1 shadow-sm\",\n disabled && \"bg-[var(--bg-surface-2)] opacity-60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YACJ;AAAA,YACA,cAAY,YAAY;AAAA,YACxB,WAAU;AAAA,YAET;AAAA;AAAA,QACH;AAAA,QACC;AAAA,SACH;AAAA,MACA,qBAAC,SAAI,WAAU,WACZ;AAAA;AAAA,QACA;AAAA,QACA;AAAA,SACH;AAAA,OACF;AAAA,EAEJ;AACA,MAAI,CAAC,OAAO;AACV,QAAI,CAAC,UAAW,QAAO;AAEvB,WACE,qBAAC,SAAI,WAAU,WACZ;AAAA;AAAA,MACA;AAAA,OACH;AAAA,EAEJ;AACA;AAAA;AAAA;AAAA,IAGE,qBAAC,SAAI,WAAW,GAAG,wBAAwB,SAAS,GAClD;AAAA;AAAA,QAAC;AAAA;AAAA,UACC,WAAU;AAAA,UACV,OAAO,oBAAC,UAAK,IAAI,SAAU,iBAAM;AAAA,UACjC,aAAW;AAAA,UACX;AAAA,UAEA;AAAA,YAAC;AAAA;AAAA,cACC,WAAW;AAAA,gBACT;AAAA,gBACA,YAAY;AAAA,gBACZ,YAAY;AAAA,cACd;AAAA,cAEC;AAAA;AAAA,UACH;AAAA;AAAA,MACF;AAAA,MACC;AAAA,MACA;AAAA,OACH;AAAA;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/components/toggle-group.tsx"],"sourcesContent":["import { useId } from \"react\";\nimport type { ComponentPropsWithoutRef, KeyboardEvent, ReactElement, ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { horizontalStep } from \"../lib/direction\";\nimport { FIELD_INVALID, FloatingField, Label } from \"./ui\";\n\nexport interface ToggleOption<T extends string> {\n value: T;\n label: string;\n className?: string;\n}\n\n/**\n * `onChange` is the group's own — the chosen VALUE, not a DOM event — so the div's\n * `onChange` is omitted rather than shadowed: leaving both in scope would give the\n * prop two incompatible meanings depending on which overload TypeScript picked.\n *\n * `children` is omitted too: this renders its `options` and nothing else, so a `children` the type\n * accepted and the component ignored would be a prop that silently does nothing —\n * worse than one that does not compile.\n */\nexport interface ToggleGroupBaseProps<T extends string>\n extends Omit<ComponentPropsWithoutRef<\"div\">, \"onChange\" | \"children\"> {\n options: ToggleOption<T>[];\n className?: string;\n /** Applied to every option button (e.g. to tune height/rounding to match\n * adjacent fields). Per-option `className` still wins over this. */\n optionClassName?: string;\n /**\n * What happens when the options do not fit the group's width. `\"truncate\"`\n * (default): one row, and the labels that do not fit end in an ellipsis — the height\n * never changes. `\"wrap\"`: the segments flow onto a second row and every label stays\n * whole (\"Bewegung\", not \"Beweg…\"), at the price of a taller group on a narrow\n * screen (lenkbank L4: five signal types on a 390px control page). From the width\n * where they fit, both look the same.\n */\n overflow?: \"truncate\" | \"wrap\";\n /**\n * @deprecated Pass `aria-label` instead — the DOM spelling, which every other\n * control in this kit now answers to. Kept working because three applications ship\n * this one today; it names the group only when `aria-label` is absent.\n */\n ariaLabel?: string;\n /**\n * Show, refuse the change (Keksdose live #288: a payment dated in the future has no\n * state to set).\n *\n * Whatever `value` says stays pressed and keeps its own fill rather than going grey\n * with the rest — a reader who cannot see WHICH option is chosen has been told less\n * than before it was disabled. A caller with nothing to show passes no value, and\n * the group renders dimmed with nothing pressed, which is the shape Keksdose's\n * status picker uses for a row whose status does not exist yet.\n *\n * On the whole GROUP, not per option: a segmented control where some segments are\n * live and others are not is a menu with holes in it, and no caller here wants one.\n */\n disabled?: boolean;\n /**\n * `sm`: 12px options with `px-2 py-1` — the compact group keksdose's rule editor\n * (rule-editor:204) writes as `optionClassName=\"px-2 py-1 text-xs\"` beside a small\n * caption. `md` (default) is the size every other group has.\n */\n size?: \"sm\" | \"md\";\n /**\n * Stand in a form row as a FIELD: with a label the group wears the field's chrome —\n * border, surface, the top strip with a small static label in it, a labelled\n * {@link Select}'s height — so beside an Input or a Select it reads as one of them\n * rather than as a control with a caption over it. lenkbank builds exactly this by\n * hand as `ToggleField` (features/gear/common.tsx:97, feedback #69), and its notes\n * are why the chrome STRETCHES to its row as well as matching the select's padding:\n * a native select's height is the browser's, so a toggle a few pixels short of it\n * is levelled up by the row rather than by arithmetic.\n *\n * The label names the group (`aria-labelledby`), so `aria-label` is not needed. With\n * a label, `className` styles the field's wrapper — as on {@link Select} — and the\n * group's own box is dropped: two nested borders read as a control in a control.\n */\n label?: ReactNode;\n /**\n * Where `label` goes. `\"field\"` (default): the field chrome described under `label`.\n * `\"above\"`: the kit's {@link Label} over the bare group — the shape of a {@link Field}\n * — with `hint` beside the label and `error` under the group, for a form that sets\n * its labels above its fields (kastlan's international-rent-calculator.tsx, whose DE\n * cap pair sits in a `Field` column between two labelled-above inputs, where the\n * chrome's inner label would be the only one of its kind).\n *\n * Inside a `Field`, pass no `label` at all and spread the render-prop instead —\n * `{(ids, { labelId }) => <ToggleGroup {...ids} aria-labelledby={labelId} … />}` —\n * so the Field's label names the group and its hint and error describe it.\n */\n labelPlacement?: \"field\" | \"above\";\n /** A {@link FieldHint} on the label line, as on a labelled {@link Select}. Only with\n * `label`. */\n hint?: ReactNode;\n /** The message under the field when it is wrong: paints the field's border with\n * `--danger`, marks the group `aria-invalid` and describes it with the message, as\n * {@link Select}'s `error` does. Only with `label`. */\n error?: ReactNode;\n}\n\n/**\n * A line under the group saying what the CHOSEN option means — lenkbank's ToggleField\n * `hint` (features/gear/common.tsx:97): not help behind a \"?\" but a caption, and one\n * that changes as the choice does. Pass a function of the value for that; it is\n * attached with `aria-describedby`, and a function caption is also a polite live\n * region, because a description is read when the group is entered and not again when\n * an arrow key changes the choice underneath it.\n *\n * In muted 11px text under the field (or the bare group), above an `error`.\n */\ntype ToggleGroupCaption<V> = ReactNode | ((value: V) => ReactNode);\n\n/** The group as it has always been: one option is always the answer. */\nexport interface ToggleGroupRequiredProps<T extends string> extends ToggleGroupBaseProps<T> {\n allowEmpty?: false;\n /**\n * What the options ARE to a screen reader, separately from whether the group can be\n * emptied (kastlan feedback #47).\n *\n * - `\"radio\"` (default) — a `radiogroup` of radios: one Tab stop, arrow keys MOVE the\n * choice. Right for a choice between answers (\"Monthly / Yearly\").\n * - `\"pressed\"` — a `group` of toggle buttons (`aria-pressed`), each its own Tab stop,\n * Space/Enter to press; still one option always pressed. Right for a row that reads\n * as a set of switches — a view mode, a toolbar-like filter — where arrows moving the\n * selection on focus would be a surprise.\n *\n * Before this the only way to `aria-pressed` was `allowEmpty`, which also let a second\n * press clear the choice — so kastlan took the clearable shape and threw the `null`\n * away in `onChange` (`(v) => v && setMode(v)`), a group announcing that a press would\n * unpress what it would not. Here a press on the pressed option re-sends its value, as\n * the radio shape does, and nothing is ever unpressed. A clearable group\n * (`allowEmpty`) is always `\"pressed\"`: a radio cannot be unchecked by activating it.\n */\n semantics?: \"radio\" | \"pressed\";\n value: T;\n onChange: (value: T) => void;\n /** See {@link ToggleGroupCaption}. */\n caption?: ToggleGroupCaption<T>;\n}\n\n/**\n * A group that can be emptied: clicking the active option clears it, and `onChange`\n * receives `null` (Keksdose's support-panel filters, where \"no filter\" is reached by\n * clicking the filter that is on).\n *\n * The options become TOGGLE BUTTONS (`aria-pressed`, in a `role=\"group\"`) rather than\n * radios. A radio cannot be unchecked by activating it — no screen reader user expects\n * a second press on \"Open, radio, checked\" to leave nothing checked, and nothing would\n * tell them it had. \"Open, toggle button, pressed\" says exactly what a press will do.\n */\nexport interface ToggleGroupClearableProps<T extends string> extends ToggleGroupBaseProps<T> {\n allowEmpty: true;\n /** Always toggle buttons — see {@link ToggleGroupRequiredProps.semantics}. Accepted so\n * a wrapper can forward one `semantics` to either shape. */\n semantics?: \"pressed\";\n value: T | null;\n onChange: (value: T | null) => void;\n /** See {@link ToggleGroupCaption}. `null` while nothing is chosen. */\n caption?: ToggleGroupCaption<T | null>;\n}\n\n/** `allowEmpty` picks the shape, so `onChange` is typed `(T) => void` unless the group\n * can actually emit `null` — no existing caller has a `null` to handle. */\nexport type ToggleGroupProps<T extends string> =\n | ToggleGroupRequiredProps<T>\n | ToggleGroupClearableProps<T>;\n\n/**\n * Overloaded rather than typed by the union alone (keksdose, \"Gaps found adopting\n * 0.6.0\" #7). Inferring `T` through a union of prop shapes let TypeScript settle on\n * `string`, so `<ToggleGroup allowEmpty value={filter} onChange={setFilter} />` over a\n * `useState<Status | null>` did not compile unless the caller spelled\n * `<ToggleGroup<Status>>`. One signature per mode lets each infer `T` from its own\n * `value`/`onChange`/`options`; the third keeps a caller that forwards a\n * {@link ToggleGroupProps} union (a wrapper component) compiling.\n */\nexport function ToggleGroup<T extends string>(props: ToggleGroupClearableProps<T>): ReactElement;\nexport function ToggleGroup<T extends string>(props: ToggleGroupRequiredProps<T>): ReactElement;\nexport function ToggleGroup<T extends string>(props: ToggleGroupProps<T>): ReactElement;\nexport function ToggleGroup<T extends string>(props: ToggleGroupProps<T>): ReactElement {\n const {\n value,\n options,\n className,\n optionClassName,\n overflow = \"truncate\",\n ariaLabel,\n disabled = false,\n size = \"md\",\n label,\n labelPlacement = \"field\",\n hint,\n error,\n \"aria-label\": ariaLabelAttr,\n ...restWithMode\n } = props;\n const labelId = useId();\n const errorId = useId();\n const labelled = label !== undefined && label !== null && label !== false && label !== \"\";\n // `field` is the chrome; a label placed above keeps the bare group's own box.\n const field = labelled && labelPlacement === \"field\";\n const above = labelled && labelPlacement === \"above\";\n const hasError = labelled && error !== undefined && error !== null && error !== false && error !== \"\";\n // Taken off the rest so neither reaches the DOM; `props` keeps them paired, which is\n // what lets the `onChange` below be called with `null` only in the mode that allows it.\n const { allowEmpty: _allowEmpty, onChange: _onChange, caption, semantics: _semantics, ...rest } = restWithMode;\n // Invalid from outside too: a `Field` hands the bare group `aria-invalid`, and the\n // border has to say what the attribute says.\n const outsideInvalid = rest[\"aria-invalid\"] === true || rest[\"aria-invalid\"] === \"true\";\n const captionId = useId();\n const captionIsLive = typeof caption === \"function\";\n const captionNode = captionIsLive ? (caption as (v: T | null) => ReactNode)(value) : caption;\n const hasCaption = captionNode !== undefined && captionNode !== null && captionNode !== false && captionNode !== \"\";\n const choose = (next: T) => {\n if (props.allowEmpty) props.onChange(next === value ? null : next);\n else props.onChange(next);\n };\n // `pressed`: toggle buttons. Every clearable group is; a required one is when it asks\n // (kastlan #47) — the role, and not whether a second press clears, is what this flag\n // decides from here on, so `choose` above still keys off `allowEmpty` alone.\n const pressed = props.allowEmpty === true || props.semantics === \"pressed\";\n // A radio group is ONE tab stop (the checked radio, else the first) and arrows move\n // the choice — the pattern `role=\"radiogroup\"` promises a screen-reader user. Before\n // 0.7.0 each segment was its own tab stop with no arrow keys. The toggle-button shape\n // is a row of buttons, where separate tab stops are the pattern.\n const tabStop = options.some((o) => o.value === value) ? value : options[0]?.value;\n const onRadioKey = (e: KeyboardEvent<HTMLButtonElement>, index: number) => {\n const last = options.length - 1;\n let next: number | null = null;\n const step = horizontalStep(e.key, e.currentTarget);\n if (step !== 0) next = index + step;\n else if (e.key === \"ArrowDown\") next = index + 1;\n else if (e.key === \"ArrowUp\") next = index - 1;\n else if (e.key === \"Home\") next = 0;\n else if (e.key === \"End\") next = last;\n if (next === null) return;\n e.preventDefault();\n next = next < 0 ? last : next > last ? 0 : next;\n const buttons = e.currentTarget.parentElement?.querySelectorAll<HTMLButtonElement>(\":scope > button\");\n buttons?.[next]?.focus();\n choose(options[next].value);\n };\n const group = (\n <div\n // The audit's named example of a closed prop list (§\"Public API design\"): the\n // tour locates a step by CSS SELECTOR, so a component that drops every attribute\n // it was not expecting cannot be spotlighted at all — and Keksdose's rule editor\n // carries a comment explaining that it wraps this group in a bare <div> for\n // exactly that reason.\n //\n // `...rest` first, then the attributes the group cannot do without: a caller\n // hanging an anchor or a test id on the group must not be able to overwrite the\n // radiogroup role or the disabled state by accident. `className` is destructured\n // out entirely and merged through `cn`, so it is never in here.\n {...rest}\n role={pressed ? \"group\" : \"radiogroup\"}\n // The DOM spelling wins; `ariaLabel` is the fallback for the call sites that\n // have not moved yet.\n aria-label={ariaLabelAttr ?? ariaLabel}\n aria-labelledby={labelled && ariaLabelAttr === undefined && ariaLabel === undefined ? labelId : rest[\"aria-labelledby\"]}\n aria-invalid={hasError || rest[\"aria-invalid\"] || undefined}\n aria-describedby={\n [rest[\"aria-describedby\"], hasCaption && captionId, hasError && errorId].filter(Boolean).join(\" \") || undefined\n }\n // `aria-disabled` on the group as well as `disabled` on each button: a radio\n // group is what the user is being refused, and a screen reader announcing\n // three separately-disabled radios does not say that.\n aria-disabled={disabled || undefined}\n className={cn(\n // `gap-0.5` — the same 2px as the container's own padding, so EVERY segment\n // sits in a uniform 2px moat and no two fills ever touch. Flush segments were\n // Keksdose live #268's rework: the pressed segment wears a saturated fill and\n // an unpressed neighbour wears a pale hover fill, and with a shared edge the\n // two rectangles read as one smeared shape — *\"the boundary of the selected\n // option and hovering next to it overlays the boundary of the selected\n // button\"*. A gap is what makes each segment its own chip; it cannot be\n // undone by a caller's per-option colour, which a hover-only fix could.\n //\n // (The hover fill is the DESKTOP half of that report: Tailwind v4 wraps every\n // `hover:` in `@media (hover: hover)`, so a phone never paints it. The half a\n // phone does see is the focus ring — see the segment's own note below.)\n \"inline-flex w-full gap-0.5 rounded-md border border-[var(--border-strong)] bg-[var(--bg-surface)] p-0.5 shadow-sm\",\n overflow === \"wrap\" && \"flex-wrap\",\n // The whole group fades, the way every other disabled control in this\n // package does; `cursor-not-allowed` is on the buttons, which is what a\n // pointer is actually over.\n disabled && \"opacity-60\",\n // The bare group (no chrome to paint) wears the invalid border itself.\n !field && (outsideInvalid || (above && hasError)) && FIELD_INVALID,\n // Inside the field's chrome the group is only a row of segments: no border, no\n // surface, no padding of its own, and the field (not the group) is what dims.\n field && \"border-0 bg-transparent p-0 shadow-none opacity-100\",\n !labelled && className,\n )}\n >\n {options.map((opt, index) => {\n const active = opt.value === value;\n return (\n <button\n key={opt.value}\n type=\"button\"\n role={pressed ? undefined : \"radio\"}\n aria-checked={pressed ? undefined : active}\n aria-pressed={pressed ? active : undefined}\n disabled={disabled}\n tabIndex={pressed ? undefined : opt.value === tabStop ? 0 : -1}\n onKeyDown={pressed ? undefined : (e) => onRadioKey(e, index)}\n onClick={() => choose(opt.value)}\n className={cn(\n // `truncate` (which carries whitespace-nowrap) rather than letting a\n // label wrap: a segmented control sizes its whole row to the tallest\n // option, so one two-word option — Keksdose feedback #147's \"Where I\n // am\" — silently doubles the height of every segment beside it.\n //\n // `basis-auto` is what keeps that ellipsis a LAST resort rather than\n // the normal state (Keksdose dev#475). With flex-1's `basis-0`, a\n // shrink-to-fit group (`w-auto`) still resolves to the sum of the\n // labels' widths — and then splits it EQUALLY, so the short option\n // got 66px it did not need and \"Where I am\" got 66 of the 81 it did:\n // truncated at 1778px of free screen. Basing each segment on its own\n // content and sharing only the LEFTOVER space keeps a full-width\n // group's segments near-equal and an auto-width group's exact.\n //\n // `focus-visible` + `ring-inset`, not `focus` + an outset ring. A ring\n // is a box-shadow that spreads OUTWARD, so on a flush group it painted\n // 2px of ring over both neighbours and over the container's own border\n // — and on a phone it appeared on every TAP, because a tap focuses the\n // button. That is the other half of what live #268's rework saw\n // overlaying the selected segment's boundary. Inset keeps the ring\n // inside the segment it belongs to; focus-visible keeps it for the\n // keyboard, which is the only input that needs it.\n overflow === \"wrap\" ? \"whitespace-nowrap\" : \"min-w-0 truncate\",\n \"flex-1 basis-auto rounded px-3 py-1.5 text-sm font-medium transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--border-strong)]\",\n size === \"sm\" && \"px-2 py-1 text-xs\",\n // In a field: no vertical padding and a 20px line — a `text-sm` line, the\n // same line a labelled Select holds under its label strip — so the field's\n // own `pt-4 pb-1` decides the height, as it does for the select.\n field && \"py-0 leading-5\",\n active\n ? \"bg-[var(--bg-inverse)] text-[var(--text-inverse)]\"\n : \"text-[var(--text-secondary)] hover:bg-[var(--bg-hover)]\",\n // No hover fill on a group that cannot be changed — a segment that\n // lights up under the pointer is an offer, and there is none here.\n disabled && \"cursor-not-allowed hover:bg-transparent dark:hover:bg-transparent\",\n optionClassName,\n opt.className,\n )}\n >\n {opt.label}\n </button>\n );\n })}\n </div>\n );\n // Rendered whenever the caption is — `aria-live` must be on the element BEFORE its\n // text changes, or the change is not announced — but empty (no height, no margin)\n // when there is nothing to say, so a function caption that returns null for some\n // options leaves no gap. Empty rather than `hidden`: some readers do not announce\n // text that appears inside an element coming back from `display: none`.\n const captionEl =\n hasCaption || captionIsLive ? (\n <p\n id={captionId}\n aria-live={captionIsLive ? \"polite\" : undefined}\n className={cn(\"text-[11px] leading-snug text-[var(--text-muted)]\", hasCaption && \"mt-1\")}\n >\n {hasCaption ? captionNode : null}\n </p>\n ) : null;\n const errorEl = hasError ? (\n <p id={errorId} className=\"mt-1 text-[11px] leading-tight text-[var(--danger)]\">\n {error}\n </p>\n ) : null;\n if (above) {\n // `relative` so a caller's `sr-only` label cannot escape (sr-only-containment).\n return (\n <div className={cn(\"relative grid min-w-0 gap-1.5\", className)}>\n <div className=\"flex items-center gap-1\">\n {/* A `<label>` with no `htmlFor`: a group is not labelable, so it is named\n by `aria-labelledby` on the group; the element keeps the Field look. */}\n <Label\n id={labelId}\n disabled={disabled}\n data-error={hasError || undefined}\n className=\"data-[error=true]:text-[var(--danger)]\"\n >\n {label}\n </Label>\n {hint}\n </div>\n <div className=\"min-w-0\">\n {group}\n {captionEl}\n {errorEl}\n </div>\n </div>\n );\n }\n if (!field) {\n if (!captionEl) return group;\n // The group keeps its `className`, as without a caption; the wrapper only stacks.\n return (\n <div className=\"min-w-0\">\n {group}\n {captionEl}\n </div>\n );\n }\n return (\n // `h-full` + `flex-1`: the chrome fills a grid or stretched flex row, which is what\n // levels it with a select beside it whatever the browser makes of the select.\n <div className={cn(\"flex h-full flex-col\", className)}>\n <FloatingField\n className=\"flex flex-1 flex-col\"\n label={<span id={labelId}>{label}</span>}\n staticLabel\n hint={hint}\n >\n <div\n className={cn(\n \"flex flex-1 flex-col justify-center rounded-md border border-[var(--border)] bg-[var(--bg-surface)] px-1 pt-4 pb-1 shadow-sm\",\n disabled && \"bg-[var(--bg-surface-2)] opacity-60\",\n hasError && FIELD_INVALID,\n )}\n >\n {group}\n </div>\n </FloatingField>\n {captionEl}\n {errorEl}\n </div>\n );\n}\n"],"mappings":";AA0SU,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