@seekalfred/primitives 0.7.1 → 0.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +255 -5
- package/dist/alert/alert.d.ts +49 -4
- package/dist/alert/alert.js +66 -38
- package/dist/alert/alert.js.map +1 -1
- package/dist/alert/index.d.ts +2 -2
- package/dist/alert/index.js +2 -2
- package/dist/alert-dialog/alert-dialog.d.ts +31 -4
- package/dist/alert-dialog/alert-dialog.js +75 -26
- package/dist/alert-dialog/alert-dialog.js.map +1 -1
- package/dist/announcement-bar/announcement-bar.d.ts +15 -4
- package/dist/announcement-bar/announcement-bar.js +31 -6
- package/dist/announcement-bar/announcement-bar.js.map +1 -1
- package/dist/avatar/avatar.d.ts +7 -0
- package/dist/avatar/avatar.js +33 -12
- package/dist/avatar/avatar.js.map +1 -1
- package/dist/badge/badge.d.ts +1 -1
- package/dist/bar-chart/bar-chart-series.d.ts +75 -0
- package/dist/bar-chart/bar-chart-series.js +401 -0
- package/dist/bar-chart/bar-chart-series.js.map +1 -0
- package/dist/bar-chart/bar-chart.d.ts +25 -1
- package/dist/bar-chart/bar-chart.js +26 -1
- package/dist/bar-chart/bar-chart.js.map +1 -1
- package/dist/bar-chart/index.d.ts +2 -1
- package/dist/button/button.d.ts +1 -1
- package/dist/calendar/calendar.d.ts +1 -1
- package/dist/card/card.d.ts +22 -1
- package/dist/card/card.js +60 -7
- package/dist/card/card.js.map +1 -1
- package/dist/carousel/carousel.d.ts +21 -0
- package/dist/carousel/carousel.js +34 -8
- package/dist/carousel/carousel.js.map +1 -1
- package/dist/chip-group/chip-group.d.ts +11 -0
- package/dist/chip-group/chip-group.js +50 -34
- package/dist/chip-group/chip-group.js.map +1 -1
- package/dist/chip-group/index.d.ts +2 -2
- package/dist/copy-button/copy-button.d.ts +37 -5
- package/dist/copy-button/copy-button.js +35 -11
- package/dist/copy-button/copy-button.js.map +1 -1
- package/dist/donut-chart/donut-chart.d.ts +22 -0
- package/dist/donut-chart/donut-chart.js +35 -18
- package/dist/donut-chart/donut-chart.js.map +1 -1
- package/dist/donut-chart/index.d.ts +2 -2
- package/dist/empty-state/empty-state.d.ts +21 -0
- package/dist/empty-state/empty-state.js +16 -4
- package/dist/empty-state/empty-state.js.map +1 -1
- package/dist/empty-state/index.d.ts +2 -2
- package/dist/empty-state/index.js +2 -2
- package/dist/file-drop-zone/file-drop-zone.d.ts +29 -3
- package/dist/file-drop-zone/file-drop-zone.js +26 -8
- package/dist/file-drop-zone/file-drop-zone.js.map +1 -1
- package/dist/filter-bar/filter-bar.d.ts +4 -1
- package/dist/filter-bar/filter-bar.js +53 -9
- package/dist/filter-bar/filter-bar.js.map +1 -1
- package/dist/gauge/gauge.d.ts +18 -1
- package/dist/gauge/gauge.js +35 -21
- package/dist/gauge/gauge.js.map +1 -1
- package/dist/gauge/index.d.ts +2 -2
- package/dist/index.d.ts +15 -14
- package/dist/index.js +9 -9
- package/dist/input/input.d.ts +7 -0
- package/dist/input/input.js +7 -5
- package/dist/input/input.js.map +1 -1
- package/dist/lib/field-shell.js +6 -3
- package/dist/lib/field-shell.js.map +1 -1
- package/dist/lib/field-surface.js +22 -1
- package/dist/lib/field-surface.js.map +1 -1
- package/dist/lib/required-marker.js +20 -0
- package/dist/lib/required-marker.js.map +1 -0
- package/dist/lib/use-copy-feedback.js +17 -3
- package/dist/lib/use-copy-feedback.js.map +1 -1
- package/dist/line-chart/index.d.ts +2 -2
- package/dist/line-chart/line-chart.d.ts +144 -2
- package/dist/line-chart/line-chart.js +314 -46
- package/dist/line-chart/line-chart.js.map +1 -1
- package/dist/money-input/index.d.ts +2 -2
- package/dist/money-input/money-input.d.ts +36 -1
- package/dist/money-input/money-input.js +30 -14
- package/dist/money-input/money-input.js.map +1 -1
- package/dist/morph-select/morph-select.d.ts +26 -1
- package/dist/morph-select/morph-select.js +28 -6
- package/dist/morph-select/morph-select.js.map +1 -1
- package/dist/multi-select/index.d.ts +2 -2
- package/dist/multi-select/index.js +2 -2
- package/dist/multi-select/multi-select.d.ts +74 -2
- package/dist/multi-select/multi-select.js +213 -39
- package/dist/multi-select/multi-select.js.map +1 -1
- package/dist/password-field/password-field.d.ts +16 -0
- package/dist/password-field/password-field.js +37 -8
- package/dist/password-field/password-field.js.map +1 -1
- package/dist/popover/index.d.ts +2 -2
- package/dist/popover/index.js +2 -2
- package/dist/popover/popover.d.ts +39 -2
- package/dist/popover/popover.js +29 -2
- package/dist/popover/popover.js.map +1 -1
- package/dist/progress/index.d.ts +2 -2
- package/dist/progress/index.js +2 -2
- package/dist/progress/progress.d.ts +68 -3
- package/dist/progress/progress.js +156 -39
- package/dist/progress/progress.js.map +1 -1
- package/dist/radio-group/index.d.ts +2 -2
- package/dist/radio-group/index.js +2 -2
- package/dist/radio-group/radio-group.d.ts +33 -3
- package/dist/radio-group/radio-group.js +109 -9
- package/dist/radio-group/radio-group.js.map +1 -1
- package/dist/scroll-area/scroll-area.js +4 -3
- package/dist/scroll-area/scroll-area.js.map +1 -1
- package/dist/scrub-input/scrub-input.d.ts +11 -1
- package/dist/scrub-input/scrub-input.js +22 -10
- package/dist/scrub-input/scrub-input.js.map +1 -1
- package/dist/search-field/search-field.d.ts +22 -1
- package/dist/search-field/search-field.js +22 -7
- package/dist/search-field/search-field.js.map +1 -1
- package/dist/select/select.d.ts +10 -1
- package/dist/select/select.js +11 -8
- package/dist/select/select.js.map +1 -1
- package/dist/separator/separator.d.ts +21 -9
- package/dist/separator/separator.js +33 -11
- package/dist/separator/separator.js.map +1 -1
- package/dist/sparkline/sparkline.d.ts +27 -2
- package/dist/sparkline/sparkline.js +115 -18
- package/dist/sparkline/sparkline.js.map +1 -1
- package/dist/stat-card/index.d.ts +2 -2
- package/dist/stat-card/index.js +2 -2
- package/dist/stat-card/stat-card.d.ts +65 -1
- package/dist/stat-card/stat-card.js +98 -25
- package/dist/stat-card/stat-card.js.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/table/index.d.ts +2 -2
- package/dist/table/index.js +2 -2
- package/dist/table/table.d.ts +115 -5
- package/dist/table/table.js +374 -94
- package/dist/table/table.js.map +1 -1
- package/dist/text-shimmer/text-shimmer.d.ts +18 -2
- package/dist/text-shimmer/text-shimmer.js +5 -2
- package/dist/text-shimmer/text-shimmer.js.map +1 -1
- package/dist/textarea/textarea.d.ts +7 -0
- package/dist/textarea/textarea.js +3 -1
- package/dist/textarea/textarea.js.map +1 -1
- package/dist/time-picker/time-picker.d.ts +36 -1
- package/dist/time-picker/time-picker.js +33 -5
- package/dist/time-picker/time-picker.js.map +1 -1
- package/dist/toast/toast.d.ts +2 -2
- package/dist/usage-meter/index.d.ts +2 -2
- package/dist/usage-meter/usage-meter.d.ts +30 -0
- package/dist/usage-meter/usage-meter.js +56 -38
- package/dist/usage-meter/usage-meter.js.map +1 -1
- package/package.json +3 -3
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { cn, cnAll } from "../lib/cn.js";
|
|
3
3
|
import { selectionLabelVariants, selectionRingVariants } from "../lib/selection-control.js";
|
|
4
4
|
import { cva } from "class-variance-authority";
|
|
5
|
-
import { forwardRef } from "react";
|
|
5
|
+
import { createContext, forwardRef, useContext, useId } from "react";
|
|
6
6
|
import { Radio, RadioGroup } from "react-aria-components";
|
|
7
7
|
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
|
|
8
8
|
//#region src/radio-group/radio-group.tsx
|
|
@@ -24,25 +24,79 @@ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
|
|
|
24
24
|
* Checkbox's exact pair -- `bg-primary` with a `primary-strong` boundary --
|
|
25
25
|
* so a radio and a checkbox in the same form agree.
|
|
26
26
|
*/
|
|
27
|
-
const radioGroupVariants = cva(["
|
|
28
|
-
|
|
27
|
+
const radioGroupVariants = cva(["box-border font-sans"], {
|
|
28
|
+
variants: {
|
|
29
|
+
/** `card` lays the choices out as a grid; add `sm:grid-cols-2` and the like. */
|
|
30
|
+
variant: {
|
|
31
|
+
default: "flex flex-col gap-2",
|
|
32
|
+
card: "grid gap-3"
|
|
33
|
+
} },
|
|
34
|
+
defaultVariants: { variant: "default" }
|
|
35
|
+
});
|
|
36
|
+
/**
|
|
37
|
+
* The box and dot, shared by both variants. Only the default variant rings
|
|
38
|
+
* the dot itself: a card rings the whole card, and a second ring on the dot
|
|
39
|
+
* inside it would just be noise.
|
|
40
|
+
*/
|
|
41
|
+
const radioMark = [
|
|
29
42
|
"inline-flex size-4 shrink-0 items-center justify-center",
|
|
30
43
|
"rounded-full border-(length:--border-width) box-border",
|
|
31
44
|
"bg-surface border-control-edge",
|
|
32
45
|
"radio-mark",
|
|
33
46
|
"group-data-[selected]:bg-primary group-data-[selected]:border-primary-strong",
|
|
34
|
-
"group-data-[selected]:text-primary-foreground"
|
|
35
|
-
|
|
47
|
+
"group-data-[selected]:text-primary-foreground"
|
|
48
|
+
];
|
|
49
|
+
const radioVariants = cva([...radioMark, selectionRingVariants()]);
|
|
50
|
+
/**
|
|
51
|
+
* One choice drawn as a selectable card: a bordered surface the whole of
|
|
52
|
+
* which is the hit target, with the title, an optional description and icon.
|
|
53
|
+
*
|
|
54
|
+
* Selection is shown twice, by the border AND by the dot, so it never rests
|
|
55
|
+
* on colour alone (WCAG 1.4.1). The border reuses StatCard's selected filter
|
|
56
|
+
* pair (`border-primary-strong`, hover darkens an unselected edge), so a
|
|
57
|
+
* selected card and a selected stat card read the same.
|
|
58
|
+
*/
|
|
59
|
+
const radioCardVariants = cva([
|
|
60
|
+
"group flex items-start gap-3 p-4",
|
|
61
|
+
"rounded-panel border-(length:--border-width) border-border bg-surface",
|
|
62
|
+
"box-border font-sans text-sm leading-(--leading-normal) text-foreground text-start",
|
|
63
|
+
"cursor-pointer select-none",
|
|
64
|
+
"motion-safe:transition-[border-color] motion-safe:duration-(--duration-quick) motion-safe:ease-settle",
|
|
65
|
+
"data-[hovered]:not-data-[selected]:border-muted-foreground",
|
|
66
|
+
"data-[selected]:border-primary-strong",
|
|
67
|
+
"data-[disabled]:cursor-not-allowed data-[disabled]:opacity-(--opacity-disabled)",
|
|
68
|
+
"outline-none",
|
|
69
|
+
"data-[focus-visible]:outline-solid",
|
|
70
|
+
"data-[focus-visible]:outline-(length:--focus-ring-width)",
|
|
71
|
+
"data-[focus-visible]:outline-offset-(--focus-ring-offset)",
|
|
72
|
+
"data-[focus-visible]:outline-(--color-ring)"
|
|
36
73
|
]);
|
|
37
|
-
const
|
|
74
|
+
const radioCardDotVariants = cva([...radioMark, "mt-0.5"]);
|
|
75
|
+
/** The group hands its variant down, so every Radio inside matches it. */
|
|
76
|
+
const RadioVariantContext = createContext("default");
|
|
77
|
+
const RadioGroup$1 = forwardRef(function RadioGroup$2({ className, variant = "default", children, ...props }, ref) {
|
|
38
78
|
return /* @__PURE__ */ jsx(RadioGroup, {
|
|
39
79
|
ref,
|
|
40
80
|
...props,
|
|
41
81
|
"data-slot": "radio-group",
|
|
42
|
-
|
|
82
|
+
"data-variant": variant === "default" ? void 0 : variant,
|
|
83
|
+
className: cn(radioGroupVariants({ variant }), className),
|
|
84
|
+
children: (renderProps) => /* @__PURE__ */ jsx(RadioVariantContext.Provider, {
|
|
85
|
+
value: variant,
|
|
86
|
+
children: typeof children === "function" ? children(renderProps) : children
|
|
87
|
+
})
|
|
43
88
|
});
|
|
44
89
|
});
|
|
45
|
-
const Radio$1 = forwardRef(function Radio
|
|
90
|
+
const Radio$1 = forwardRef(function Radio(props, ref) {
|
|
91
|
+
return useContext(RadioVariantContext) === "card" ? /* @__PURE__ */ jsx(RadioCard, {
|
|
92
|
+
...props,
|
|
93
|
+
ref
|
|
94
|
+
}) : /* @__PURE__ */ jsx(RadioDefault, {
|
|
95
|
+
...props,
|
|
96
|
+
ref
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
const RadioDefault = forwardRef(function RadioDefault({ className, children, description: _description, icon: _icon, ...props }, ref) {
|
|
46
100
|
return /* @__PURE__ */ jsx(Radio, {
|
|
47
101
|
...props,
|
|
48
102
|
inputRef: ref,
|
|
@@ -63,7 +117,53 @@ const Radio$1 = forwardRef(function Radio$2({ className, children, ...props }, r
|
|
|
63
117
|
})] })
|
|
64
118
|
});
|
|
65
119
|
});
|
|
120
|
+
const RadioCard = forwardRef(function RadioCard({ className, children, description, icon, ...props }, ref) {
|
|
121
|
+
const id = useId();
|
|
122
|
+
const titleId = `${id}-title`;
|
|
123
|
+
const descriptionId = `${id}-description`;
|
|
124
|
+
return /* @__PURE__ */ jsx(Radio, {
|
|
125
|
+
"aria-labelledby": children == null || props["aria-label"] != null ? void 0 : titleId,
|
|
126
|
+
"aria-describedby": description == null ? void 0 : descriptionId,
|
|
127
|
+
...props,
|
|
128
|
+
inputRef: ref,
|
|
129
|
+
"data-slot": "radio",
|
|
130
|
+
"data-variant": "card",
|
|
131
|
+
className: cn(radioCardVariants(), className),
|
|
132
|
+
children: ({ isSelected }) => /* @__PURE__ */ jsxs(Fragment$1, { children: [
|
|
133
|
+
icon == null ? null : /* @__PURE__ */ jsx("span", {
|
|
134
|
+
"aria-hidden": "true",
|
|
135
|
+
"data-slot": "radio-icon",
|
|
136
|
+
className: "mt-0.5 inline-flex shrink-0 text-text-secondary [&_svg]:size-4",
|
|
137
|
+
children: icon
|
|
138
|
+
}),
|
|
139
|
+
/* @__PURE__ */ jsxs("span", {
|
|
140
|
+
className: "flex min-w-0 flex-1 flex-col gap-1",
|
|
141
|
+
children: [children == null ? null : /* @__PURE__ */ jsx("span", {
|
|
142
|
+
id: titleId,
|
|
143
|
+
"data-slot": "radio-label",
|
|
144
|
+
className: "font-medium",
|
|
145
|
+
children
|
|
146
|
+
}), description == null ? null : /* @__PURE__ */ jsx("span", {
|
|
147
|
+
id: descriptionId,
|
|
148
|
+
"data-slot": "radio-description",
|
|
149
|
+
className: "text-text-secondary",
|
|
150
|
+
children: description
|
|
151
|
+
})]
|
|
152
|
+
}),
|
|
153
|
+
/* @__PURE__ */ jsx("span", {
|
|
154
|
+
"aria-hidden": "true",
|
|
155
|
+
"data-slot": "radio-dot",
|
|
156
|
+
className: radioCardDotVariants(),
|
|
157
|
+
children: /* @__PURE__ */ jsx("span", {
|
|
158
|
+
"data-slot": "radio-indicator",
|
|
159
|
+
"data-selected": isSelected || void 0,
|
|
160
|
+
className: "radio-dot size-1.5 rounded-full bg-current"
|
|
161
|
+
})
|
|
162
|
+
})
|
|
163
|
+
] })
|
|
164
|
+
});
|
|
165
|
+
});
|
|
66
166
|
//#endregion
|
|
67
|
-
export { Radio$1 as Radio, RadioGroup$1 as RadioGroup, radioGroupVariants, radioVariants };
|
|
167
|
+
export { Radio$1 as Radio, RadioGroup$1 as RadioGroup, radioCardVariants, radioGroupVariants, radioVariants };
|
|
68
168
|
|
|
69
169
|
//# sourceMappingURL=radio-group.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"radio-group.js","names":["RadioGroup","AriaRadioGroup","Radio","AriaRadio"],"sources":["../../src/radio-group/radio-group.tsx"],"sourcesContent":["\"use client\";\n\nimport { cva } from \"class-variance-authority\";\nimport { forwardRef, type ReactNode } from \"react\";\nimport {\n Radio as AriaRadio,\n RadioGroup as AriaRadioGroup,\n type RadioGroupProps as AriaRadioGroupProps,\n type RadioProps as AriaRadioProps,\n} from \"react-aria-components\";\n\nimport { cn, cnAll } from \"../lib/cn.js\";\nimport { selectionLabelVariants, selectionRingVariants } from \"../lib/selection-control.js\";\n\n/**\n * RadioGroup, ported from the legacy shadcn/Radix component onto React Aria.\n *\n * Census: 1 file, 3 uses -- `RadioGroup` 1, `RadioGroupItem` 2. The\n * smallest real surface in the migration, so the port is deliberately plain.\n *\n * THE LABEL MOVES INSIDE THE ITEM. Radix's `RadioGroupItem` is a bare\n * button and the caller pairs it with a separate `<Label htmlFor>`; React\n * Aria's `Radio` takes its label as `children` and wires the association\n * itself. That is the one rename a call site has to make, and it removes\n * the id bookkeeping.\n *\n * `border-primary` becomes `border-border` for the same reason it did on\n * Checkbox: brand orange is 2.44:1 on white and cannot legally be the only\n * thing describing a control's edge (WCAG 1.4.11). Selected reuses\n * Checkbox's exact pair -- `bg-primary` with a `primary-strong` boundary --\n * so a radio and a checkbox in the same form agree.\n */\nexport const radioGroupVariants = cva([\n \"flex flex-col gap-2\",\n \"box-border font-sans\",\n]);\n\nexport const radioVariants = cva([\n \"inline-flex size-4 shrink-0 items-center justify-center\",\n \"rounded-full border-(length:--border-width) box-border\",\n \"bg-surface border-control-edge\",\n // Colours ease, the mark dips under a press and springs back (see radio-mark).\n \"radio-mark\",\n \"group-data-[selected]:bg-primary group-data-[selected]:border-primary-strong\",\n \"group-data-[selected]:text-primary-foreground\",\n selectionRingVariants(),\n]);\n\n/**\n * A set of mutually exclusive choices.\n *\n * @example\n * <RadioGroup value={plan} onChange={setPlan} aria-label=\"Plan\">\n * <Radio value=\"free\">Free</Radio>\n * <Radio value=\"pro\">Pro</Radio>\n * </RadioGroup>\n */\nexport interface RadioGroupProps extends Omit<AriaRadioGroupProps, \"className\" | \"style\"> {\n /** Extra classes. Merged last, so they win conflicts with ours. */\n className?: string;\n}\n\nexport const RadioGroup = forwardRef<HTMLDivElement, RadioGroupProps>(function RadioGroup(\n { className, ...props },\n ref,\n) {\n return (\n <AriaRadioGroup\n ref={ref}\n {...props}\n data-slot=\"radio-group\"\n className={cn(radioGroupVariants(), className)}\n />\n );\n});\n\n/**\n * One choice.\n *\n * @example\n * <Radio value=\"pro\">Pro</Radio>\n */\nexport interface RadioProps extends Omit<AriaRadioProps, \"className\" | \"style\" | \"children\"> {\n /** The label, and this option's accessible name. */\n children?: ReactNode;\n /** Extra classes for the label. Merged last, so they win conflicts. */\n className?: string;\n}\n\nexport const Radio = forwardRef<HTMLInputElement, RadioProps>(function Radio(\n { className, children, ...props },\n ref,\n) {\n return (\n <AriaRadio\n {...props}\n // inputRef, not ref: AriaRadio's own ref targets the label it renders\n // around a visually-hidden native input, and a label cannot be\n // focused -- ref.current.focus() would silently no-op. inputRef is\n // React Aria's own escape hatch to the real control.\n inputRef={ref}\n data-slot=\"radio\"\n // justify-start, overriding the shared label's centring: a radio sits\n // in a vertical list where every label must start on the same line,\n // not centre itself in a 24px box.\n className={cn(cnAll(selectionLabelVariants(), \"justify-start\"), className)}\n >\n {({ isSelected }) => (\n <>\n <span aria-hidden=\"true\" data-slot=\"radio-dot\" className={radioVariants()}>\n {/*\n Always there: the state decides whether it shows, so the dot can\n spring in and shrink away. data-selected carries the state to a\n test, which can no longer read it from the dot's presence.\n */}\n <span\n data-slot=\"radio-indicator\"\n data-selected={isSelected || undefined}\n className=\"radio-dot size-1.5 rounded-full bg-current\"\n />\n </span>\n {children == null ? null : <span data-slot=\"radio-label\">{children}</span>}\n </>\n )}\n </AriaRadio>\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,qBAAqB,IAAI,CACpC,uBACA,sBACF,CAAC;AAED,MAAa,gBAAgB,IAAI;CAC/B;CACA;CACA;CAEA;CACA;CACA;CACA,sBAAsB;AACxB,CAAC;AAgBD,MAAaA,eAAa,WAA4C,SAASA,aAC7E,EAAE,WAAW,GAAG,SAChB,KACA;CACA,OACE,oBAACC,YAAD;EACO;EACL,GAAI;EACJ,aAAU;EACV,WAAW,GAAG,mBAAmB,GAAG,SAAS;CAC9C,CAAA;AAEL,CAAC;AAeD,MAAaC,UAAQ,WAAyC,SAASA,QACrE,EAAE,WAAW,UAAU,GAAG,SAC1B,KACA;CACA,OACE,oBAACC,OAAD;EACE,GAAI;EAKJ,UAAU;EACV,aAAU;EAIV,WAAW,GAAG,MAAM,uBAAuB,GAAG,eAAe,GAAG,SAAS;EAEvE,WAAA,EAAE,iBACF,qBAAA,YAAA,EAAA,UAAA,CACE,oBAAC,QAAD;GAAM,eAAY;GAAO,aAAU;GAAY,WAAW,cAAc;GAMtE,UAAA,oBAAC,QAAD;IACE,aAAU;IACV,iBAAe,cAAc,KAAA;IAC7B,WAAU;GACX,CAAA;EACG,CAAA,GACL,YAAY,OAAO,OAAO,oBAAC,QAAD;GAAM,aAAU;GAAe;EAAe,CAAA,CACzE,EAAA,CAAA;CAEK,CAAA;AAEf,CAAC"}
|
|
1
|
+
{"version":3,"file":"radio-group.js","names":["RadioGroup","AriaRadioGroup","Radio","AriaRadio"],"sources":["../../src/radio-group/radio-group.tsx"],"sourcesContent":["\"use client\";\n\nimport { cva } from \"class-variance-authority\";\nimport { createContext, forwardRef, useContext, useId, type ReactNode } from \"react\";\nimport {\n Radio as AriaRadio,\n RadioGroup as AriaRadioGroup,\n type RadioGroupProps as AriaRadioGroupProps,\n type RadioProps as AriaRadioProps,\n} from \"react-aria-components\";\n\nimport { cn, cnAll } from \"../lib/cn.js\";\nimport { selectionLabelVariants, selectionRingVariants } from \"../lib/selection-control.js\";\n\n/**\n * RadioGroup, ported from the legacy shadcn/Radix component onto React Aria.\n *\n * Census: 1 file, 3 uses -- `RadioGroup` 1, `RadioGroupItem` 2. The\n * smallest real surface in the migration, so the port is deliberately plain.\n *\n * THE LABEL MOVES INSIDE THE ITEM. Radix's `RadioGroupItem` is a bare\n * button and the caller pairs it with a separate `<Label htmlFor>`; React\n * Aria's `Radio` takes its label as `children` and wires the association\n * itself. That is the one rename a call site has to make, and it removes\n * the id bookkeeping.\n *\n * `border-primary` becomes `border-border` for the same reason it did on\n * Checkbox: brand orange is 2.44:1 on white and cannot legally be the only\n * thing describing a control's edge (WCAG 1.4.11). Selected reuses\n * Checkbox's exact pair -- `bg-primary` with a `primary-strong` boundary --\n * so a radio and a checkbox in the same form agree.\n */\nexport const radioGroupVariants = cva([\"box-border font-sans\"], {\n variants: {\n /** `card` lays the choices out as a grid; add `sm:grid-cols-2` and the like. */\n variant: {\n default: \"flex flex-col gap-2\",\n card: \"grid gap-3\",\n },\n },\n defaultVariants: { variant: \"default\" },\n});\n\n/**\n * The box and dot, shared by both variants. Only the default variant rings\n * the dot itself: a card rings the whole card, and a second ring on the dot\n * inside it would just be noise.\n */\nconst radioMark = [\n \"inline-flex size-4 shrink-0 items-center justify-center\",\n \"rounded-full border-(length:--border-width) box-border\",\n \"bg-surface border-control-edge\",\n // Colours ease, the mark dips under a press and springs back (see radio-mark).\n \"radio-mark\",\n \"group-data-[selected]:bg-primary group-data-[selected]:border-primary-strong\",\n \"group-data-[selected]:text-primary-foreground\",\n];\n\nexport const radioVariants = cva([...radioMark, selectionRingVariants()]);\n\n/**\n * One choice drawn as a selectable card: a bordered surface the whole of\n * which is the hit target, with the title, an optional description and icon.\n *\n * Selection is shown twice, by the border AND by the dot, so it never rests\n * on colour alone (WCAG 1.4.1). The border reuses StatCard's selected filter\n * pair (`border-primary-strong`, hover darkens an unselected edge), so a\n * selected card and a selected stat card read the same.\n */\nexport const radioCardVariants = cva([\n \"group flex items-start gap-3 p-4\",\n \"rounded-panel border-(length:--border-width) border-border bg-surface\",\n \"box-border font-sans text-sm leading-(--leading-normal) text-foreground text-start\",\n \"cursor-pointer select-none\",\n \"motion-safe:transition-[border-color] motion-safe:duration-(--duration-quick) motion-safe:ease-settle\",\n \"data-[hovered]:not-data-[selected]:border-muted-foreground\",\n \"data-[selected]:border-primary-strong\",\n \"data-[disabled]:cursor-not-allowed data-[disabled]:opacity-(--opacity-disabled)\",\n // The same ring as selectionRingVariants, on purpose not reused: that helper\n // reads the state from a `group-data-[focus-visible]:` parent, and here the\n // card IS the group, so its own `data-[focus-visible]:` is the state. Keep\n // the two in step. outline-solid is load-bearing: outline-none sets the\n // style the width utility resolves from (see selectionRingVariants).\n \"outline-none\",\n \"data-[focus-visible]:outline-solid\",\n \"data-[focus-visible]:outline-(length:--focus-ring-width)\",\n \"data-[focus-visible]:outline-offset-(--focus-ring-offset)\",\n \"data-[focus-visible]:outline-(--color-ring)\",\n]);\n\nconst radioCardDotVariants = cva([...radioMark, \"mt-0.5\"]);\n\n/** Which look the group's radios take. */\nexport type RadioGroupVariant = \"default\" | \"card\";\n\n/** The group hands its variant down, so every Radio inside matches it. */\nconst RadioVariantContext = createContext<RadioGroupVariant>(\"default\");\n\n/**\n * A set of mutually exclusive choices.\n *\n * @example\n * <RadioGroup value={plan} onChange={setPlan} aria-label=\"Plan\">\n * <Radio value=\"free\">Free</Radio>\n * <Radio value=\"pro\">Pro</Radio>\n * </RadioGroup>\n */\nexport interface RadioGroupProps extends Omit<AriaRadioGroupProps, \"className\" | \"style\"> {\n /**\n * `card` draws each choice as a selectable card, with a title, an optional\n * `description` and `icon` on each `Radio`. The keyboard model is the same:\n * one tab stop, arrow keys move and select.\n *\n * @default \"default\"\n */\n variant?: RadioGroupVariant;\n /** Extra classes. Merged last, so they win conflicts with ours. */\n className?: string;\n}\n\nexport const RadioGroup = forwardRef<HTMLDivElement, RadioGroupProps>(function RadioGroup(\n { className, variant = \"default\", children, ...props },\n ref,\n) {\n return (\n <AriaRadioGroup\n ref={ref}\n {...props}\n data-slot=\"radio-group\"\n data-variant={variant === \"default\" ? undefined : variant}\n className={cn(radioGroupVariants({ variant }), className)}\n >\n {(renderProps) => (\n <RadioVariantContext.Provider value={variant}>\n {typeof children === \"function\" ? children(renderProps) : children}\n </RadioVariantContext.Provider>\n )}\n </AriaRadioGroup>\n );\n});\n\n/**\n * One choice.\n *\n * @example\n * <Radio value=\"pro\">Pro</Radio>\n */\nexport interface RadioProps extends Omit<AriaRadioProps, \"className\" | \"style\" | \"children\"> {\n /** The label, and this option's accessible name. In a card, the title. */\n children?: ReactNode;\n /**\n * A line under the title, read as the option's description\n * (`aria-describedby`), not as part of its name. Card variant only; the\n * default variant ignores it.\n */\n description?: ReactNode;\n /** A decorative icon before the title. Card variant only; hidden from assistive tech. */\n icon?: ReactNode;\n /** Extra classes for the label (the whole card in the card variant). Merged last, so they win conflicts. */\n className?: string;\n}\n\nexport const Radio = forwardRef<HTMLInputElement, RadioProps>(function Radio(props, ref) {\n const variant = useContext(RadioVariantContext);\n return variant === \"card\" ? <RadioCard {...props} ref={ref} /> : <RadioDefault {...props} ref={ref} />;\n});\n\nconst RadioDefault = forwardRef<HTMLInputElement, RadioProps>(function RadioDefault(\n // description and icon belong to the card; pulled out so they never reach the DOM.\n { className, children, description: _description, icon: _icon, ...props },\n ref,\n) {\n return (\n <AriaRadio\n {...props}\n // inputRef, not ref: AriaRadio's own ref targets the label it renders\n // around a visually-hidden native input, and a label cannot be\n // focused -- ref.current.focus() would silently no-op. inputRef is\n // React Aria's own escape hatch to the real control.\n inputRef={ref}\n data-slot=\"radio\"\n // justify-start, overriding the shared label's centring: a radio sits\n // in a vertical list where every label must start on the same line,\n // not centre itself in a 24px box.\n className={cn(cnAll(selectionLabelVariants(), \"justify-start\"), className)}\n >\n {({ isSelected }) => (\n <>\n <span aria-hidden=\"true\" data-slot=\"radio-dot\" className={radioVariants()}>\n {/*\n Always there: the state decides whether it shows, so the dot can\n spring in and shrink away. data-selected carries the state to a\n test, which can no longer read it from the dot's presence.\n */}\n <span\n data-slot=\"radio-indicator\"\n data-selected={isSelected || undefined}\n className=\"radio-dot size-1.5 rounded-full bg-current\"\n />\n </span>\n {children == null ? null : <span data-slot=\"radio-label\">{children}</span>}\n </>\n )}\n </AriaRadio>\n );\n});\n\nconst RadioCard = forwardRef<HTMLInputElement, RadioProps>(function RadioCard(\n { className, children, description, icon, ...props },\n ref,\n) {\n const id = useId();\n const titleId = `${id}-title`;\n const descriptionId = `${id}-description`;\n return (\n <AriaRadio\n // The title alone names the option; the description describes it. Left\n // to the wrapping <label>, the name would be title and description run\n // together. A caller's own labelling wins: their aria-labelledby or\n // aria-describedby by the spread below, and their aria-label because the\n // title's aria-labelledby is then left off (it would outrank aria-label\n // in the name computation).\n aria-labelledby={children == null || props[\"aria-label\"] != null ? undefined : titleId}\n aria-describedby={description == null ? undefined : descriptionId}\n {...props}\n inputRef={ref}\n data-slot=\"radio\"\n data-variant=\"card\"\n className={cn(radioCardVariants(), className)}\n >\n {({ isSelected }) => (\n <>\n {icon == null ? null : (\n <span\n aria-hidden=\"true\"\n data-slot=\"radio-icon\"\n className=\"mt-0.5 inline-flex shrink-0 text-text-secondary [&_svg]:size-4\"\n >\n {icon}\n </span>\n )}\n <span className=\"flex min-w-0 flex-1 flex-col gap-1\">\n {children == null ? null : (\n <span id={titleId} data-slot=\"radio-label\" className=\"font-medium\">\n {children}\n </span>\n )}\n {description == null ? null : (\n <span id={descriptionId} data-slot=\"radio-description\" className=\"text-text-secondary\">\n {description}\n </span>\n )}\n </span>\n <span aria-hidden=\"true\" data-slot=\"radio-dot\" className={radioCardDotVariants()}>\n <span\n data-slot=\"radio-indicator\"\n data-selected={isSelected || undefined}\n className=\"radio-dot size-1.5 rounded-full bg-current\"\n />\n </span>\n </>\n )}\n </AriaRadio>\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,qBAAqB,IAAI,CAAC,sBAAsB,GAAG;CAC9D,UAAU;;AAER,SAAS;EACP,SAAS;EACT,MAAM;CACR,EACF;CACA,iBAAiB,EAAE,SAAS,UAAU;AACxC,CAAC;;;;;;AAOD,MAAM,YAAY;CAChB;CACA;CACA;CAEA;CACA;CACA;AACF;AAEA,MAAa,gBAAgB,IAAI,CAAC,GAAG,WAAW,sBAAsB,CAAC,CAAC;;;;;;;;;;AAWxE,MAAa,oBAAoB,IAAI;CACnC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAMA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,uBAAuB,IAAI,CAAC,GAAG,WAAW,QAAQ,CAAC;;AAMzD,MAAM,sBAAsB,cAAiC,SAAS;AAwBtE,MAAaA,eAAa,WAA4C,SAASA,aAC7E,EAAE,WAAW,UAAU,WAAW,UAAU,GAAG,SAC/C,KACA;CACA,OACE,oBAACC,YAAD;EACO;EACL,GAAI;EACJ,aAAU;EACV,gBAAc,YAAY,YAAY,KAAA,IAAY;EAClD,WAAW,GAAG,mBAAmB,EAAE,QAAQ,CAAC,GAAG,SAAS;EAEtD,WAAA,gBACA,oBAAC,oBAAoB,UAArB;GAA8B,OAAO;GAClC,UAAA,OAAO,aAAa,aAAa,SAAS,WAAW,IAAI;EAC9B,CAAA;CAElB,CAAA;AAEpB,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AA;GACG,CAAA;GAER,qBAAC,QAAD;IAAM,WAAU;IAAhB,UAAA,CACG,YAAY,OAAO,OAClB,oBAAC,QAAD;KAAM,IAAI;KAAS,aAAU;KAAc,WAAU;KAClD;IACG,CAAA,GAEP,eAAe,OAAO,OACrB,oBAAC,QAAD;KAAM,IAAI;KAAe,aAAU;KAAoB,WAAU;KAC9D,UAAA;IACG,CAAA,CAEJ;;GACN,oBAAC,QAAD;IAAM,eAAY;IAAO,aAAU;IAAY,WAAW,qBAAqB;IAC7E,UAAA,oBAAC,QAAD;KACE,aAAU;KACV,iBAAe,cAAc,KAAA;KAC7B,WAAU;IACX,CAAA;GACG,CAAA;EACN,EAAA,CAAA;CAEK,CAAA;AAEf,CAAC"}
|
|
@@ -46,10 +46,11 @@ framed: {
|
|
|
46
46
|
const scrollAreaVariants = cva([
|
|
47
47
|
"scroll-area-viewport min-h-0 min-w-0 flex-1 overscroll-contain box-border",
|
|
48
48
|
"outline-none",
|
|
49
|
-
"focus-visible:outline-solid",
|
|
49
|
+
"focus-visible:not-data-[fade]:outline-solid",
|
|
50
50
|
"focus-visible:outline-(length:--focus-ring-width)",
|
|
51
|
-
"focus-visible
|
|
52
|
-
"focus-visible:outline-(--color-ring)"
|
|
51
|
+
"focus-visible:-outline-offset-(--focus-ring-width)",
|
|
52
|
+
"focus-visible:outline-(--color-ring)",
|
|
53
|
+
"rounded-[inherit]"
|
|
53
54
|
], {
|
|
54
55
|
variants: { orientation: {
|
|
55
56
|
vertical: "overflow-x-hidden overflow-y-auto",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scroll-area.js","names":[],"sources":["../../src/scroll-area/scroll-area.tsx"],"sourcesContent":["\"use client\";\n\nimport { cva } from \"class-variance-authority\";\nimport {\n forwardRef,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n type ComponentPropsWithoutRef,\n type PointerEvent as ReactPointerEvent,\n type ReactNode,\n} from \"react\";\n\nimport { cn, cnAll } from \"../lib/cn.js\";\nimport { mergeRefs } from \"../lib/merge-refs.js\";\nimport { prefersReducedMotion, useIsomorphicLayoutEffect } from \"../lib/motion.js\";\n\n/**\n * ScrollArea: a native scroll container with thin overlay scrollbars and edge\n * fades. React Aria has no equivalent, so the scrolling stays the browser's --\n * keyboard, touch momentum and scroll snap all behave as the platform expects --\n * and only the scrollbar is drawn here.\n *\n * Census: fourteen paths match, thirteen are counted, ELEVEN render anything,\n * and across them 17 uses. Every one passes `className` and nothing else, and 13\n * of the 17 are a height or flex constraint plus padding. The legacy Radix one\n * cannot be scrolled by keyboard at all.\n *\n * The native scrollbar is hidden and replaced by an overlay pill that appears\n * while scrolling or hovering and fades away at rest (or stays, with\n * `scrollbars=\"always\"`). It is written straight to the DOM on each scroll\n * frame, so scrolling never re-renders React. The pill can be dragged, and\n * pressing its track pages toward the pointer.\n *\n * WHERE THINGS LAND. `className`, `style` and the rest go on the ROOT, the box\n * that carries the height and the optional card. `ref` and `viewportClassName`\n * go on the VIEWPORT, the element that really scrolls -- so a caller can call\n * `ref.current.scrollTo(...)` or `scrollBy(...)` for a \"back to top\" or an\n * arrow button, and put padding on the content without moving the scrollbar\n * inside it.\n *\n * The font is declared here: the reset in @seekalfred/styles is OPT-IN, so a\n * consumer may load none, and a scroll area's content (a list of plain\n * paragraphs) would render in the browser's serif.\n */\nexport const scrollAreaRootVariants = cva(\n [\"scroll-area relative flex min-h-0 min-w-0 flex-col overflow-hidden box-border font-sans\"],\n {\n variants: {\n /** The area is a white card: the panel radius and a hairline border. */\n framed: {\n true: \"rounded-panel border-(length:--border-width) border-border bg-surface\",\n false: \"\",\n },\n },\n defaultVariants: { framed: false },\n },\n);\n\nexport const scrollAreaVariants = cva(\n [\n \"scroll-area-viewport min-h-0 min-w-0 flex-1 overscroll-contain box-border\",\n // A scrollable region must be reachable by keyboard, or its content is\n // unreachable without a pointer -- WCAG 2.1.1, and axe's\n // scrollable-region-focusable rule. The legacy has no tabIndex at all.\n \"outline-none\",\n \"focus-visible:outline-solid\",\n \"focus-visible:outline-(length:--focus-ring-width)\",\n \"focus-visible:outline-offset-(--focus-ring-offset)\",\n \"focus-visible:outline-(--color-ring)\",\n ],\n {\n variants: {\n orientation: {\n vertical: \"overflow-x-hidden overflow-y-auto\",\n horizontal: \"overflow-x-auto overflow-y-hidden\",\n both: \"overflow-auto\",\n },\n },\n defaultVariants: { orientation: \"vertical\" },\n },\n);\n\ntype Axis = \"y\" | \"x\";\n\ninterface Drag {\n axis: Axis;\n start: number;\n scroll: number;\n ratio: number;\n sign: number;\n}\n\n/** The shortest a scrollbar thumb gets, so a very long list still leaves something to grab. */\nconst MIN_THUMB = 28;\n\n/**\n * A scrolling region.\n *\n * @example\n * <ScrollArea label=\"Activity\" className=\"h-64\" framed fade={28}>...</ScrollArea>\n */\nexport interface ScrollAreaProps extends ComponentPropsWithoutRef<\"div\"> {\n children?: ReactNode;\n /**\n * Names the scrolling region.\n *\n * **Required**, and it took a failing test to get here. A focusable\n * element with no role fails axe `focus-order-semantics`, so the\n * keyboard fix cannot ship without a role -- and a role with no\n * accessible name is a violation of its own. Naming it is the only\n * combination that is actually correct.\n *\n * `role=\"region\"` specifically. `group` was the first attempt -- it is\n * lighter, since region is a landmark and seventeen landmarks in one app\n * is noise -- but axe does not accept `group` as an appropriate role for\n * a focusable element, and it is right: a named region is the role the\n * ARIA practices name for a scrollable content area, and being able to\n * jump to it is the point.\n */\n label: string;\n /**\n * Which axes scroll.\n *\n * @default \"vertical\"\n */\n orientation?: \"vertical\" | \"horizontal\" | \"both\";\n /**\n * Fade the content out at an edge by exactly as much as there is content hidden\n * past it, up to this many pixels: the fade grows in with the first pixels of\n * scroll and is gone at the ends, so an edge fades only while content\n * overflows past it. `0` turns it off, and the default leaves the area as it\n * was. Written on each scroll frame straight to the element, so scrolling\n * never re-renders.\n *\n * @default 0\n */\n fade?: number;\n /**\n * `auto` shows the scrollbar while scrolling or hovering and fades it away at\n * rest; `always` keeps it visible whenever the content overflows.\n *\n * @default \"auto\"\n */\n scrollbars?: \"auto\" | \"always\";\n /**\n * How long the scrollbar lingers after scrolling stops, in ms.\n *\n * @default 900\n */\n hideDelay?: number;\n /**\n * Draws the area as a white card: the panel radius and a light border. The\n * content is clipped to it, so an edge fade and the scrollbar sit inside.\n *\n * @default false\n */\n framed?: boolean;\n /**\n * Classes for the viewport, the element that scrolls. Padding for the\n * content goes here.\n */\n viewportClassName?: string;\n /**\n * Change this when the contents change, and the region scrolls back to the\n * top.\n *\n * This stays a declarative prop even though a `ref` exists: reaching\n * for it would mean the caller writes `ref.current.scrollTop = 0` in their\n * own effect on every content change, which is worse ergonomics than a\n * prop that says \"reset when this value changes.\"\n *\n * Sheet forwards its own `scrollResetKey` straight through: going a level\n * deeper in a panel and landing halfway down the new view is disorienting,\n * and it is exactly the thing every call site forgets.\n */\n scrollResetKey?: string | number;\n}\n\n/** The `ref` reaches the VIEWPORT, the element that scrolls. `onScroll` runs on its scroll events. */\nexport const ScrollArea = forwardRef<HTMLDivElement, ScrollAreaProps>(function ScrollArea(\n {\n className,\n children,\n label,\n scrollResetKey,\n orientation = \"vertical\",\n fade = 0,\n scrollbars = \"auto\",\n hideDelay = 900,\n framed = false,\n viewportClassName,\n onScroll,\n ...props\n },\n ref,\n) {\n const root = useRef<HTMLDivElement>(null);\n const viewport = useRef<HTMLDivElement>(null);\n const tracks = useRef<Record<Axis, HTMLDivElement | null>>({ x: null, y: null });\n const thumbs = useRef<Record<Axis, HTMLDivElement | null>>({ x: null, y: null });\n const hideTimer = useRef<number | undefined>(undefined);\n const drag = useRef<Drag | null>(null);\n\n const vertical = orientation !== \"horizontal\";\n const horizontal = orientation !== \"vertical\";\n\n useEffect(() => {\n // Unconditional rather than guarded on scrollResetKey being set: with no\n // key this runs once on mount, where scrollTop is already 0.\n if (viewport.current) viewport.current.scrollTop = 0;\n }, [scrollResetKey]);\n\n // Memoized, not called inline: mergeRefs returns a new callback every call, so\n // an inline call would detach and reattach the DOM ref on every re-render.\n const viewportRef = useMemo(() => mergeRefs(ref, viewport), [ref]);\n\n /*\n * Everything visual is written straight to the DOM: the fade at each edge is\n * how much content is hidden past it (up to `fade`), and a thumb is sized and\n * placed from the scroll position. A track with nothing to scroll is hidden.\n */\n const sync = useCallback(() => {\n const node = viewport.current;\n if (!node) return;\n const { scrollTop, scrollHeight, clientHeight, scrollWidth, clientWidth } = node;\n const maxY = Math.max(0, scrollHeight - clientHeight);\n const maxX = Math.max(0, scrollWidth - clientWidth);\n // scrollLeft runs negative in a right-to-left layout; the distance travelled is what counts.\n const left = Math.abs(node.scrollLeft);\n\n if (fade > 0) {\n node.style.setProperty(\"--fade-top\", `${vertical ? Math.min(fade, scrollTop) : 0}px`);\n node.style.setProperty(\n \"--fade-bottom\",\n `${vertical ? Math.min(fade, Math.max(0, maxY - scrollTop)) : 0}px`,\n );\n node.style.setProperty(\"--fade-left\", `${horizontal ? Math.min(fade, left) : 0}px`);\n node.style.setProperty(\n \"--fade-right\",\n `${horizontal ? Math.min(fade, Math.max(0, maxX - left)) : 0}px`,\n );\n }\n\n const place = (axis: Axis, scroll: number, max: number, client: number, total: number) => {\n const track = tracks.current[axis];\n const thumb = thumbs.current[axis];\n if (!track || !thumb) return;\n const overflowing = max > 0.5;\n track.toggleAttribute(\"data-hidden\", !overflowing);\n if (!overflowing) return;\n const length = axis === \"y\" ? track.clientHeight : track.clientWidth;\n const size = Math.max(MIN_THUMB, (length * client) / total);\n const offset = (length - size) * (scroll / max);\n const sign = axis === \"x\" && getComputedStyle(node).direction === \"rtl\" ? -1 : 1;\n thumb.style[axis === \"y\" ? \"height\" : \"width\"] = `${size}px`;\n thumb.style.transform =\n axis === \"y\" ? `translate3d(0, ${offset}px, 0)` : `translate3d(${offset * sign}px, 0, 0)`;\n };\n if (vertical) place(\"y\", scrollTop, maxY, clientHeight, scrollHeight);\n if (horizontal) place(\"x\", left, maxX, clientWidth, scrollWidth);\n root.current?.toggleAttribute(\"data-overflow\", maxY > 0.5 || maxX > 0.5);\n }, [fade, horizontal, vertical]);\n\n useIsomorphicLayoutEffect(() => {\n const node = viewport.current;\n if (!node) return;\n sync();\n if (typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(() => sync());\n observer.observe(node);\n for (const child of Array.from(node.children)) observer.observe(child);\n return () => observer.disconnect();\n // `children` re-observes when the content's own boxes are replaced.\n }, [sync, children]);\n\n useEffect(() => () => window.clearTimeout(hideTimer.current), []);\n\n const wake = () => {\n const el = root.current;\n if (!el) return;\n el.setAttribute(\"data-scrolling\", \"\");\n window.clearTimeout(hideTimer.current);\n hideTimer.current = window.setTimeout(() => el.removeAttribute(\"data-scrolling\"), hideDelay);\n };\n\n /* Dragging a thumb maps pointer travel to scroll distance. */\n const onThumbDown = (event: ReactPointerEvent<HTMLDivElement>, axis: Axis) => {\n const node = viewport.current;\n const track = tracks.current[axis];\n const thumb = thumbs.current[axis];\n if (!node || !track || !thumb || event.button !== 0) return;\n event.preventDefault();\n event.stopPropagation();\n event.currentTarget.setPointerCapture(event.pointerId);\n const length = axis === \"y\" ? track.clientHeight : track.clientWidth;\n const size = axis === \"y\" ? thumb.offsetHeight : thumb.offsetWidth;\n const max =\n axis === \"y\" ? node.scrollHeight - node.clientHeight : node.scrollWidth - node.clientWidth;\n drag.current = {\n axis,\n start: axis === \"y\" ? event.clientY : event.clientX,\n scroll: axis === \"y\" ? node.scrollTop : node.scrollLeft,\n ratio: max / Math.max(1, length - size),\n sign: axis === \"x\" && getComputedStyle(node).direction === \"rtl\" ? -1 : 1,\n };\n root.current?.setAttribute(\"data-dragging\", axis);\n };\n const onThumbMove = (event: ReactPointerEvent<HTMLDivElement>) => {\n const state = drag.current;\n const node = viewport.current;\n if (!state || !node) return;\n const travel = (state.axis === \"y\" ? event.clientY : event.clientX) - state.start;\n const to = state.scroll + travel * state.ratio * state.sign;\n if (state.axis === \"y\") node.scrollTop = to;\n else node.scrollLeft = to;\n };\n const onThumbUp = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (!drag.current) return;\n drag.current = null;\n if (event.currentTarget.hasPointerCapture(event.pointerId)) {\n event.currentTarget.releasePointerCapture(event.pointerId);\n }\n root.current?.removeAttribute(\"data-dragging\");\n wake();\n };\n /* Pressing the track pages toward the pointer. */\n const onTrackDown = (event: ReactPointerEvent<HTMLDivElement>, axis: Axis) => {\n const node = viewport.current;\n const thumb = thumbs.current[axis];\n if (!node || !thumb || event.button !== 0 || event.target !== event.currentTarget) return;\n const box = thumb.getBoundingClientRect();\n const before = axis === \"y\" ? event.clientY < box.top : event.clientX < box.left;\n const page = (axis === \"y\" ? node.clientHeight : node.clientWidth) * 0.9 * (before ? -1 : 1);\n node.scrollBy({\n [axis === \"y\" ? \"top\" : \"left\"]: page,\n behavior: prefersReducedMotion() ? \"auto\" : \"smooth\",\n });\n };\n\n const bar = (axis: Axis) => (\n <div\n ref={(node) => {\n tracks.current[axis] = node;\n }}\n data-slot=\"scroll-area-track\"\n data-axis={axis}\n data-hidden=\"\"\n aria-hidden=\"true\"\n onPointerDown={(event) => onTrackDown(event, axis)}\n >\n <div\n ref={(node) => {\n thumbs.current[axis] = node;\n }}\n data-slot=\"scroll-area-thumb\"\n onPointerDown={(event) => onThumbDown(event, axis)}\n onPointerMove={onThumbMove}\n onPointerUp={onThumbUp}\n onPointerCancel={onThumbUp}\n />\n </div>\n );\n\n const fadeClass =\n orientation === \"vertical\"\n ? \"scroll-fade-y\"\n : orientation === \"horizontal\"\n ? \"scroll-fade-x\"\n : \"scroll-fade-both\";\n\n return (\n <div\n {...props}\n ref={root}\n data-slot=\"scroll-area-root\"\n data-orientation={orientation}\n data-scrollbars={scrollbars}\n className={cn(scrollAreaRootVariants({ framed }), className)}\n >\n <div\n ref={viewportRef}\n // tabIndex 0 unconditionally: whether the content overflows is a\n // runtime fact that changes as the content does, and a region that\n // becomes scrollable after a fetch would otherwise never gain focus.\n tabIndex={0}\n role=\"region\"\n aria-label={label}\n data-slot=\"scroll-area\"\n data-fade={fade > 0 ? \"\" : undefined}\n onScroll={(event) => {\n sync();\n wake();\n onScroll?.(event);\n }}\n className={cn(\n cnAll(scrollAreaVariants({ orientation }), fade > 0 && fadeClass),\n viewportClassName,\n )}\n >\n {children}\n </div>\n {vertical ? bar(\"y\") : null}\n {horizontal ? bar(\"x\") : null}\n </div>\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,yBAAyB,IACpC,CAAC,yFAAyF,GAC1F;CACE,UAAU;;AAER,QAAQ;EACN,MAAM;EACN,OAAO;CACT,EACF;CACA,iBAAiB,EAAE,QAAQ,MAAM;AACnC,CACF;AAEA,MAAa,qBAAqB,IAChC;CACE;CAIA;CACA;CACA;CACA;CACA;AACF,GACA;CACE,UAAU,EACR,aAAa;EACX,UAAU;EACV,YAAY;EACZ,MAAM;CACR,EACF;CACA,iBAAiB,EAAE,aAAa,WAAW;AAC7C,CACF;;AAaA,MAAM,YAAY;;AAsFlB,MAAa,aAAa,WAA4C,SAAS,WAC7E,EACE,WACA,UACA,OACA,gBACA,cAAc,YACd,OAAO,GACP,aAAa,QACb,YAAY,KACZ,SAAS,OACT,mBACA,UACA,GAAG,SAEL,KACA;CACA,MAAM,OAAO,OAAuB,IAAI;CACxC,MAAM,WAAW,OAAuB,IAAI;CAC5C,MAAM,SAAS,OAA4C;EAAE,GAAG;EAAM,GAAG;CAAK,CAAC;CAC/E,MAAM,SAAS,OAA4C;EAAE,GAAG;EAAM,GAAG;CAAK,CAAC;CAC/E,MAAM,YAAY,OAA2B,KAAA,CAAS;CACtD,MAAM,OAAO,OAAoB,IAAI;CAErC,MAAM,WAAW,gBAAgB;CACjC,MAAM,aAAa,gBAAgB;CAEnC,gBAAgB;EAGd,IAAI,SAAS,SAAS,SAAS,QAAQ,YAAY;CACrD,GAAG,CAAC,cAAc,CAAC;CAInB,MAAM,cAAc,cAAc,UAAU,KAAK,QAAQ,GAAG,CAAC,GAAG,CAAC;CAOjE,MAAM,OAAO,kBAAkB;EAC7B,MAAM,OAAO,SAAS;EACt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AAO,SACX,oBAAC,OAAD;EACE,MAAM,SAAS;GACb,OAAO,QAAQ,QAAQ;EACzB;EACA,aAAU;EACV,aAAW;EACX,eAAY;EACZ,eAAY;EACZ,gBAAgB,UAAU,YAAY,OAAO,IAAI;EAEjD,UAAA,oBAAC,OAAD;GACE,MAAM,SAAS;IACb,OAAO,QAAQ,QAAQ;GACzB;GACA,aAAU;GACV,gBAAgB,UAAU,YAAY,OAAO,IAAI;GACjD,eAAe;GACf,aAAa;GACb,iBAAiB;EAClB,CAAA;CACE,CAAA;CAGP,MAAM,YACJ,gBAAgB,aACZ,kBACA,gBAAgB,eACd,kBACA;CAER,OACE,qBAAC,OAAD;EACE,GAAI;EACJ,KAAK;EACL,aAAU;EACV,oBAAkB;EAClB,mBAAiB;EACjB,WAAW,GAAG,uBAAuB,EAAE,OAAO,CAAC,GAAG,SAAS;EAN7D,UAAA;GAQE,oBAAC,OAAD;IACE,KAAK;IAIL,UAAU;IACV,MAAK;IACL,cAAY;IACZ,aAAU;IACV,aAAW,OAAO,IAAI,KAAK,KAAA;IAC3B,WAAW,UAAU;KACnB,KAAK;KACL,KAAK;KACL,WAAW,KAAK;IAClB;IACA,WAAW,GACT,MAAM,mBAAmB,EAAE,YAAY,CAAC,GAAG,OAAO,KAAK,SAAS,GAChE,iBACF;IAEC;GACE,CAAA;GACJ,WAAW,IAAI,GAAG,IAAI;GACtB,aAAa,IAAI,GAAG,IAAI;EACtB;;AAET,CAAC"}
|
|
1
|
+
{"version":3,"file":"scroll-area.js","names":[],"sources":["../../src/scroll-area/scroll-area.tsx"],"sourcesContent":["\"use client\";\n\nimport { cva } from \"class-variance-authority\";\nimport {\n forwardRef,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n type ComponentPropsWithoutRef,\n type PointerEvent as ReactPointerEvent,\n type ReactNode,\n} from \"react\";\n\nimport { cn, cnAll } from \"../lib/cn.js\";\nimport { mergeRefs } from \"../lib/merge-refs.js\";\nimport { prefersReducedMotion, useIsomorphicLayoutEffect } from \"../lib/motion.js\";\n\n/**\n * ScrollArea: a native scroll container with thin overlay scrollbars and edge\n * fades. React Aria has no equivalent, so the scrolling stays the browser's --\n * keyboard, touch momentum and scroll snap all behave as the platform expects --\n * and only the scrollbar is drawn here.\n *\n * Census: fourteen paths match, thirteen are counted, ELEVEN render anything,\n * and across them 17 uses. Every one passes `className` and nothing else, and 13\n * of the 17 are a height or flex constraint plus padding. The legacy Radix one\n * cannot be scrolled by keyboard at all.\n *\n * The native scrollbar is hidden and replaced by an overlay pill that appears\n * while scrolling or hovering and fades away at rest (or stays, with\n * `scrollbars=\"always\"`). It is written straight to the DOM on each scroll\n * frame, so scrolling never re-renders React. The pill can be dragged, and\n * pressing its track pages toward the pointer.\n *\n * WHERE THINGS LAND. `className`, `style` and the rest go on the ROOT, the box\n * that carries the height and the optional card. `ref` and `viewportClassName`\n * go on the VIEWPORT, the element that really scrolls -- so a caller can call\n * `ref.current.scrollTo(...)` or `scrollBy(...)` for a \"back to top\" or an\n * arrow button, and put padding on the content without moving the scrollbar\n * inside it.\n *\n * The font is declared here: the reset in @seekalfred/styles is OPT-IN, so a\n * consumer may load none, and a scroll area's content (a list of plain\n * paragraphs) would render in the browser's serif.\n */\nexport const scrollAreaRootVariants = cva(\n [\"scroll-area relative flex min-h-0 min-w-0 flex-col overflow-hidden box-border font-sans\"],\n {\n variants: {\n /** The area is a white card: the panel radius and a hairline border. */\n framed: {\n true: \"rounded-panel border-(length:--border-width) border-border bg-surface\",\n false: \"\",\n },\n },\n defaultVariants: { framed: false },\n },\n);\n\nexport const scrollAreaVariants = cva(\n [\n \"scroll-area-viewport min-h-0 min-w-0 flex-1 overscroll-contain box-border\",\n // A scrollable region must be reachable by keyboard, or its content is\n // unreachable without a pointer -- WCAG 2.1.1, and axe's\n // scrollable-region-focusable rule. The legacy has no tabIndex at all.\n \"outline-none\",\n // Inset, not offset outward: the root is overflow-hidden (it clips the\n // overlay scrollbars, the fades and the framed radius), so a ring drawn\n // outside the viewport was cut off on every side and keyboard focus was\n // invisible -- WCAG 2.4.7. Drawn just inside the edge, nothing around the\n // area can clip it, and a caller can still recolour it through\n // `viewportClassName`. The radius is inherited so the ring follows the\n // framed card's corners.\n //\n // With `fade` on (data-fade) the viewport carries the edge-fade mask, which\n // would fade the ring's top and bottom out with the content mid-scroll. The\n // ring's style stays `none` there and the ROOT paints it instead, on an\n // unmasked overlay (`scroll-area` in styles.css).\n \"focus-visible:not-data-[fade]:outline-solid\",\n \"focus-visible:outline-(length:--focus-ring-width)\",\n \"focus-visible:-outline-offset-(--focus-ring-width)\",\n \"focus-visible:outline-(--color-ring)\",\n \"rounded-[inherit]\",\n ],\n {\n variants: {\n orientation: {\n vertical: \"overflow-x-hidden overflow-y-auto\",\n horizontal: \"overflow-x-auto overflow-y-hidden\",\n both: \"overflow-auto\",\n },\n },\n defaultVariants: { orientation: \"vertical\" },\n },\n);\n\ntype Axis = \"y\" | \"x\";\n\ninterface Drag {\n axis: Axis;\n start: number;\n scroll: number;\n ratio: number;\n sign: number;\n}\n\n/** The shortest a scrollbar thumb gets, so a very long list still leaves something to grab. */\nconst MIN_THUMB = 28;\n\n/**\n * A scrolling region.\n *\n * @example\n * <ScrollArea label=\"Activity\" className=\"h-64\" framed fade={28}>...</ScrollArea>\n */\nexport interface ScrollAreaProps extends ComponentPropsWithoutRef<\"div\"> {\n children?: ReactNode;\n /**\n * Names the scrolling region.\n *\n * **Required**, and it took a failing test to get here. A focusable\n * element with no role fails axe `focus-order-semantics`, so the\n * keyboard fix cannot ship without a role -- and a role with no\n * accessible name is a violation of its own. Naming it is the only\n * combination that is actually correct.\n *\n * `role=\"region\"` specifically. `group` was the first attempt -- it is\n * lighter, since region is a landmark and seventeen landmarks in one app\n * is noise -- but axe does not accept `group` as an appropriate role for\n * a focusable element, and it is right: a named region is the role the\n * ARIA practices name for a scrollable content area, and being able to\n * jump to it is the point.\n */\n label: string;\n /**\n * Which axes scroll.\n *\n * @default \"vertical\"\n */\n orientation?: \"vertical\" | \"horizontal\" | \"both\";\n /**\n * Fade the content out at an edge by exactly as much as there is content hidden\n * past it, up to this many pixels: the fade grows in with the first pixels of\n * scroll and is gone at the ends, so an edge fades only while content\n * overflows past it. `0` turns it off, and the default leaves the area as it\n * was. Written on each scroll frame straight to the element, so scrolling\n * never re-renders.\n *\n * @default 0\n */\n fade?: number;\n /**\n * `auto` shows the scrollbar while scrolling or hovering and fades it away at\n * rest; `always` keeps it visible whenever the content overflows.\n *\n * @default \"auto\"\n */\n scrollbars?: \"auto\" | \"always\";\n /**\n * How long the scrollbar lingers after scrolling stops, in ms.\n *\n * @default 900\n */\n hideDelay?: number;\n /**\n * Draws the area as a white card: the panel radius and a light border. The\n * content is clipped to it, so an edge fade and the scrollbar sit inside.\n *\n * @default false\n */\n framed?: boolean;\n /**\n * Classes for the viewport, the element that scrolls. Padding for the\n * content goes here.\n */\n viewportClassName?: string;\n /**\n * Change this when the contents change, and the region scrolls back to the\n * top.\n *\n * This stays a declarative prop even though a `ref` exists: reaching\n * for it would mean the caller writes `ref.current.scrollTop = 0` in their\n * own effect on every content change, which is worse ergonomics than a\n * prop that says \"reset when this value changes.\"\n *\n * Sheet forwards its own `scrollResetKey` straight through: going a level\n * deeper in a panel and landing halfway down the new view is disorienting,\n * and it is exactly the thing every call site forgets.\n */\n scrollResetKey?: string | number;\n}\n\n/** The `ref` reaches the VIEWPORT, the element that scrolls. `onScroll` runs on its scroll events. */\nexport const ScrollArea = forwardRef<HTMLDivElement, ScrollAreaProps>(function ScrollArea(\n {\n className,\n children,\n label,\n scrollResetKey,\n orientation = \"vertical\",\n fade = 0,\n scrollbars = \"auto\",\n hideDelay = 900,\n framed = false,\n viewportClassName,\n onScroll,\n ...props\n },\n ref,\n) {\n const root = useRef<HTMLDivElement>(null);\n const viewport = useRef<HTMLDivElement>(null);\n const tracks = useRef<Record<Axis, HTMLDivElement | null>>({ x: null, y: null });\n const thumbs = useRef<Record<Axis, HTMLDivElement | null>>({ x: null, y: null });\n const hideTimer = useRef<number | undefined>(undefined);\n const drag = useRef<Drag | null>(null);\n\n const vertical = orientation !== \"horizontal\";\n const horizontal = orientation !== \"vertical\";\n\n useEffect(() => {\n // Unconditional rather than guarded on scrollResetKey being set: with no\n // key this runs once on mount, where scrollTop is already 0.\n if (viewport.current) viewport.current.scrollTop = 0;\n }, [scrollResetKey]);\n\n // Memoized, not called inline: mergeRefs returns a new callback every call, so\n // an inline call would detach and reattach the DOM ref on every re-render.\n const viewportRef = useMemo(() => mergeRefs(ref, viewport), [ref]);\n\n /*\n * Everything visual is written straight to the DOM: the fade at each edge is\n * how much content is hidden past it (up to `fade`), and a thumb is sized and\n * placed from the scroll position. A track with nothing to scroll is hidden.\n */\n const sync = useCallback(() => {\n const node = viewport.current;\n if (!node) return;\n const { scrollTop, scrollHeight, clientHeight, scrollWidth, clientWidth } = node;\n const maxY = Math.max(0, scrollHeight - clientHeight);\n const maxX = Math.max(0, scrollWidth - clientWidth);\n // scrollLeft runs negative in a right-to-left layout; the distance travelled is what counts.\n const left = Math.abs(node.scrollLeft);\n\n if (fade > 0) {\n node.style.setProperty(\"--fade-top\", `${vertical ? Math.min(fade, scrollTop) : 0}px`);\n node.style.setProperty(\n \"--fade-bottom\",\n `${vertical ? Math.min(fade, Math.max(0, maxY - scrollTop)) : 0}px`,\n );\n node.style.setProperty(\"--fade-left\", `${horizontal ? Math.min(fade, left) : 0}px`);\n node.style.setProperty(\n \"--fade-right\",\n `${horizontal ? Math.min(fade, Math.max(0, maxX - left)) : 0}px`,\n );\n }\n\n const place = (axis: Axis, scroll: number, max: number, client: number, total: number) => {\n const track = tracks.current[axis];\n const thumb = thumbs.current[axis];\n if (!track || !thumb) return;\n const overflowing = max > 0.5;\n track.toggleAttribute(\"data-hidden\", !overflowing);\n if (!overflowing) return;\n const length = axis === \"y\" ? track.clientHeight : track.clientWidth;\n const size = Math.max(MIN_THUMB, (length * client) / total);\n const offset = (length - size) * (scroll / max);\n const sign = axis === \"x\" && getComputedStyle(node).direction === \"rtl\" ? -1 : 1;\n thumb.style[axis === \"y\" ? \"height\" : \"width\"] = `${size}px`;\n thumb.style.transform =\n axis === \"y\" ? `translate3d(0, ${offset}px, 0)` : `translate3d(${offset * sign}px, 0, 0)`;\n };\n if (vertical) place(\"y\", scrollTop, maxY, clientHeight, scrollHeight);\n if (horizontal) place(\"x\", left, maxX, clientWidth, scrollWidth);\n root.current?.toggleAttribute(\"data-overflow\", maxY > 0.5 || maxX > 0.5);\n }, [fade, horizontal, vertical]);\n\n useIsomorphicLayoutEffect(() => {\n const node = viewport.current;\n if (!node) return;\n sync();\n if (typeof ResizeObserver === \"undefined\") return;\n const observer = new ResizeObserver(() => sync());\n observer.observe(node);\n for (const child of Array.from(node.children)) observer.observe(child);\n return () => observer.disconnect();\n // `children` re-observes when the content's own boxes are replaced.\n }, [sync, children]);\n\n useEffect(() => () => window.clearTimeout(hideTimer.current), []);\n\n const wake = () => {\n const el = root.current;\n if (!el) return;\n el.setAttribute(\"data-scrolling\", \"\");\n window.clearTimeout(hideTimer.current);\n hideTimer.current = window.setTimeout(() => el.removeAttribute(\"data-scrolling\"), hideDelay);\n };\n\n /* Dragging a thumb maps pointer travel to scroll distance. */\n const onThumbDown = (event: ReactPointerEvent<HTMLDivElement>, axis: Axis) => {\n const node = viewport.current;\n const track = tracks.current[axis];\n const thumb = thumbs.current[axis];\n if (!node || !track || !thumb || event.button !== 0) return;\n event.preventDefault();\n event.stopPropagation();\n event.currentTarget.setPointerCapture(event.pointerId);\n const length = axis === \"y\" ? track.clientHeight : track.clientWidth;\n const size = axis === \"y\" ? thumb.offsetHeight : thumb.offsetWidth;\n const max =\n axis === \"y\" ? node.scrollHeight - node.clientHeight : node.scrollWidth - node.clientWidth;\n drag.current = {\n axis,\n start: axis === \"y\" ? event.clientY : event.clientX,\n scroll: axis === \"y\" ? node.scrollTop : node.scrollLeft,\n ratio: max / Math.max(1, length - size),\n sign: axis === \"x\" && getComputedStyle(node).direction === \"rtl\" ? -1 : 1,\n };\n root.current?.setAttribute(\"data-dragging\", axis);\n };\n const onThumbMove = (event: ReactPointerEvent<HTMLDivElement>) => {\n const state = drag.current;\n const node = viewport.current;\n if (!state || !node) return;\n const travel = (state.axis === \"y\" ? event.clientY : event.clientX) - state.start;\n const to = state.scroll + travel * state.ratio * state.sign;\n if (state.axis === \"y\") node.scrollTop = to;\n else node.scrollLeft = to;\n };\n const onThumbUp = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (!drag.current) return;\n drag.current = null;\n if (event.currentTarget.hasPointerCapture(event.pointerId)) {\n event.currentTarget.releasePointerCapture(event.pointerId);\n }\n root.current?.removeAttribute(\"data-dragging\");\n wake();\n };\n /* Pressing the track pages toward the pointer. */\n const onTrackDown = (event: ReactPointerEvent<HTMLDivElement>, axis: Axis) => {\n const node = viewport.current;\n const thumb = thumbs.current[axis];\n if (!node || !thumb || event.button !== 0 || event.target !== event.currentTarget) return;\n const box = thumb.getBoundingClientRect();\n const before = axis === \"y\" ? event.clientY < box.top : event.clientX < box.left;\n const page = (axis === \"y\" ? node.clientHeight : node.clientWidth) * 0.9 * (before ? -1 : 1);\n node.scrollBy({\n [axis === \"y\" ? \"top\" : \"left\"]: page,\n behavior: prefersReducedMotion() ? \"auto\" : \"smooth\",\n });\n };\n\n const bar = (axis: Axis) => (\n <div\n ref={(node) => {\n tracks.current[axis] = node;\n }}\n data-slot=\"scroll-area-track\"\n data-axis={axis}\n data-hidden=\"\"\n aria-hidden=\"true\"\n onPointerDown={(event) => onTrackDown(event, axis)}\n >\n <div\n ref={(node) => {\n thumbs.current[axis] = node;\n }}\n data-slot=\"scroll-area-thumb\"\n onPointerDown={(event) => onThumbDown(event, axis)}\n onPointerMove={onThumbMove}\n onPointerUp={onThumbUp}\n onPointerCancel={onThumbUp}\n />\n </div>\n );\n\n const fadeClass =\n orientation === \"vertical\"\n ? \"scroll-fade-y\"\n : orientation === \"horizontal\"\n ? \"scroll-fade-x\"\n : \"scroll-fade-both\";\n\n return (\n <div\n {...props}\n ref={root}\n data-slot=\"scroll-area-root\"\n data-orientation={orientation}\n data-scrollbars={scrollbars}\n className={cn(scrollAreaRootVariants({ framed }), className)}\n >\n <div\n ref={viewportRef}\n // tabIndex 0 unconditionally: whether the content overflows is a\n // runtime fact that changes as the content does, and a region that\n // becomes scrollable after a fetch would otherwise never gain focus.\n tabIndex={0}\n role=\"region\"\n aria-label={label}\n data-slot=\"scroll-area\"\n data-fade={fade > 0 ? \"\" : undefined}\n onScroll={(event) => {\n sync();\n wake();\n onScroll?.(event);\n }}\n className={cn(\n cnAll(scrollAreaVariants({ orientation }), fade > 0 && fadeClass),\n viewportClassName,\n )}\n >\n {children}\n </div>\n {vertical ? bar(\"y\") : null}\n {horizontal ? bar(\"x\") : null}\n </div>\n );\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAa,yBAAyB,IACpC,CAAC,yFAAyF,GAC1F;CACE,UAAU;;AAER,QAAQ;EACN,MAAM;EACN,OAAO;CACT,EACF;CACA,iBAAiB,EAAE,QAAQ,MAAM;AACnC,CACF;AAEA,MAAa,qBAAqB,IAChC;CACE;CAIA;CAaA;CACA;CACA;CACA;CACA;AACF,GACA;CACE,UAAU,EACR,aAAa;EACX,UAAU;EACV,YAAY;EACZ,MAAM;CACR,EACF;CACA,iBAAiB,EAAE,aAAa,WAAW;AAC7C,CACF;;AAaA,MAAM,YAAY;;AAsFlB,MAAa,aAAa,WAA4C,SAAS,WAC7E,EACE,WACA,UACA,OACA,gBACA,cAAc,YACd,OAAO,GACP,aAAa,QACb,YAAY,KACZ,SAAS,OACT,mBACA,UACA,GAAG,SAEL,KACA;CACA,MAAM,OAAO,OAAuB,IAAI;CACxC,MAAM,WAAW,OAAuB,IAAI;CAC5C,MAAM,SAAS,OAA4C;EAAE,GAAG;EAAM,GAAG;CAAK,CAAC;CAC/E,MAAM,SAAS,OAA4C;EAAE,GAAG;EAAM,GAAG;CAAK,CAAC;CAC/E,MAAM,YAAY,OAA2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48,15 @@ export interface ScrubInputProps extends Omit<InputHTMLAttributes<HTMLInputEleme
|
|
|
48
48
|
size?: "sm" | "md";
|
|
49
49
|
/** Locks the mouse pointer while it scrubs, when the browser allows it, so a long drag never runs out of screen. @default true */
|
|
50
50
|
pointerLock?: boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Shows the value without letting it change: the field stays focusable and its text
|
|
53
|
+
* selectable, but the label does not scrub, the arrow keys do not step, typing and
|
|
54
|
+
* expressions are refused, a double click does not reset, and the unit does not cycle,
|
|
55
|
+
* so `onValueChange`, `onValueCommit` and `onUnitChange` never fire. Sets
|
|
56
|
+
* `aria-readonly` and `data-readonly`. The native attribute, as `disabled` is.
|
|
57
|
+
* @default false
|
|
58
|
+
*/
|
|
59
|
+
readOnly?: boolean;
|
|
51
60
|
/** Extra classes for the field. Merged last, so `w-40` sizes it. */
|
|
52
61
|
className?: string;
|
|
53
62
|
}
|
|
@@ -60,7 +69,8 @@ export interface ScrubInputProps extends Omit<InputHTMLAttributes<HTMLInputEleme
|
|
|
60
69
|
* Keyboard: the arrow keys step (Shift ten times coarser, Alt ten times finer), Enter
|
|
61
70
|
* commits typing, Escape restores the last value (or cancels a scrub back to where it
|
|
62
71
|
* began). A double click on the label restores `resetValue`. The input is a spinbutton, and
|
|
63
|
-
* its value text spells out percent and degrees.
|
|
72
|
+
* its value text spells out percent and degrees. `readOnly` keeps the value visible,
|
|
73
|
+
* focusable and selectable while refusing every change.
|
|
64
74
|
*
|
|
65
75
|
* At a limit the field strains: dragged past `min` or `max` it stretches against
|
|
66
76
|
* rubber-band resistance and springs back on release, and a refused step or an invalid
|
|
@@ -44,7 +44,8 @@ const sizeClass = {
|
|
|
44
44
|
* Keyboard: the arrow keys step (Shift ten times coarser, Alt ten times finer), Enter
|
|
45
45
|
* commits typing, Escape restores the last value (or cancels a scrub back to where it
|
|
46
46
|
* began). A double click on the label restores `resetValue`. The input is a spinbutton, and
|
|
47
|
-
* its value text spells out percent and degrees.
|
|
47
|
+
* its value text spells out percent and degrees. `readOnly` keeps the value visible,
|
|
48
|
+
* focusable and selectable while refusing every change.
|
|
48
49
|
*
|
|
49
50
|
* At a limit the field strains: dragged past `min` or `max` it stretches against
|
|
50
51
|
* rubber-band resistance and springs back on release, and a refused step or an invalid
|
|
@@ -53,7 +54,7 @@ const sizeClass = {
|
|
|
53
54
|
* @example
|
|
54
55
|
* <ScrubInput label="W" value={width} onValueChange={setWidth} min={0} units={["px", "%"]} />
|
|
55
56
|
*/
|
|
56
|
-
const ScrubInput = forwardRef(function ScrubInput({ label, value, defaultValue = 0, onValueChange, onValueCommit, min = -Infinity, max = Infinity, step = 1, fineStep, coarseStep, precision, pixelsPerStep = 2, wrap = false, unit: unitProp, defaultUnit, units, onUnitChange, resetValue, track, size = "md", pointerLock = true, className, disabled, id: idProp, onFocus, onBlur, onKeyDown, "aria-label": ariaLabel, ...rest }, forwarded) {
|
|
57
|
+
const ScrubInput = forwardRef(function ScrubInput({ label, value, defaultValue = 0, onValueChange, onValueCommit, min = -Infinity, max = Infinity, step = 1, fineStep, coarseStep, precision, pixelsPerStep = 2, wrap = false, unit: unitProp, defaultUnit, units, onUnitChange, resetValue, track, size = "md", pointerLock = true, className, disabled, readOnly = false, id: idProp, onFocus, onBlur, onKeyDown, "aria-label": ariaLabel, ...rest }, forwarded) {
|
|
57
58
|
const uid = useId();
|
|
58
59
|
const id = idProp ?? `scrub-${uid.replace(/[^a-zA-Z0-9-]/g, "")}`;
|
|
59
60
|
const inputRef = useRef(null);
|
|
@@ -66,6 +67,8 @@ const ScrubInput = forwardRef(function ScrubInput({ label, value, defaultValue =
|
|
|
66
67
|
const coarse = coarseStep ?? step * 10;
|
|
67
68
|
const places = precision ?? Math.max(decimalsOf(step), decimalsOf(fine));
|
|
68
69
|
const canWrap = wrap && Number.isFinite(min) && Number.isFinite(max) && max > min;
|
|
70
|
+
/** Nothing the person does changes the value: disabled, or read-only. */
|
|
71
|
+
const frozen = Boolean(disabled) || readOnly;
|
|
69
72
|
const showTrack = (track ?? true) && Number.isFinite(min) && Number.isFinite(max) && max > min;
|
|
70
73
|
const [inner, setInner] = useState(defaultValue);
|
|
71
74
|
const current = value ?? inner;
|
|
@@ -171,7 +174,7 @@ const ScrubInput = forwardRef(function ScrubInput({ label, value, defaultValue =
|
|
|
171
174
|
}
|
|
172
175
|
function commitDraft(text = draft) {
|
|
173
176
|
setDraft(null);
|
|
174
|
-
if (text === null) return true;
|
|
177
|
+
if (text === null || readOnly) return true;
|
|
175
178
|
if (text.trim() === format(current, places)) return true;
|
|
176
179
|
const parsed = evaluateScrubExpression(text, unitList);
|
|
177
180
|
if (!parsed) {
|
|
@@ -242,7 +245,7 @@ const ScrubInput = forwardRef(function ScrubInput({ label, value, defaultValue =
|
|
|
242
245
|
if (node) node.style.transform = `translate3d(${cursor.current.x}px, ${cursor.current.y}px, 0)`;
|
|
243
246
|
}
|
|
244
247
|
function onHandleDown(event) {
|
|
245
|
-
if (
|
|
248
|
+
if (frozen || drag.current || event.pointerType === "mouse" && event.button !== 0) return;
|
|
246
249
|
event.preventDefault();
|
|
247
250
|
if (draft !== null) commitDraft();
|
|
248
251
|
try {
|
|
@@ -323,12 +326,16 @@ const ScrubInput = forwardRef(function ScrubInput({ label, value, defaultValue =
|
|
|
323
326
|
inputRef.current?.select();
|
|
324
327
|
}
|
|
325
328
|
function onHandleDoubleClick() {
|
|
326
|
-
if (
|
|
329
|
+
if (frozen || resetValue === void 0) return;
|
|
327
330
|
emit(constrain(resetValue), "reset", true);
|
|
328
331
|
}
|
|
329
332
|
function onInputKeyDown(event) {
|
|
330
333
|
onKeyDown?.(event);
|
|
331
334
|
if (event.defaultPrevented) return;
|
|
335
|
+
if (readOnly) {
|
|
336
|
+
if (event.key === "Enter") event.preventDefault();
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
332
339
|
if (event.key === "ArrowUp" || event.key === "ArrowDown") {
|
|
333
340
|
event.preventDefault();
|
|
334
341
|
if (draft !== null && !commitDraft()) return;
|
|
@@ -358,7 +365,7 @@ const ScrubInput = forwardRef(function ScrubInput({ label, value, defaultValue =
|
|
|
358
365
|
commitDraft();
|
|
359
366
|
}
|
|
360
367
|
function cycleUnit() {
|
|
361
|
-
if (unitList.length < 2) return;
|
|
368
|
+
if (readOnly || unitList.length < 2) return;
|
|
362
369
|
const next = unitList[(unitList.indexOf(unit) + 1) % unitList.length] ?? unit;
|
|
363
370
|
if (unitProp === void 0) setInnerUnit(next);
|
|
364
371
|
onUnitChange?.(next);
|
|
@@ -376,6 +383,7 @@ const ScrubInput = forwardRef(function ScrubInput({ label, value, defaultValue =
|
|
|
376
383
|
"data-slot": "scrub-input",
|
|
377
384
|
"data-size": size,
|
|
378
385
|
"data-disabled": disabled ? "" : void 0,
|
|
386
|
+
"data-readonly": readOnly ? "" : void 0,
|
|
379
387
|
"data-scrubbing": scrubbing ? "" : void 0,
|
|
380
388
|
"data-invalid": invalid ? "" : void 0,
|
|
381
389
|
"data-releasing": releasing ? "" : void 0,
|
|
@@ -403,7 +411,7 @@ const ScrubInput = forwardRef(function ScrubInput({ label, value, defaultValue =
|
|
|
403
411
|
onPointerCancel: onHandleUp,
|
|
404
412
|
onClick: onHandleClick,
|
|
405
413
|
onDoubleClick: onHandleDoubleClick,
|
|
406
|
-
className: "flex min-w-7.5 cursor-ew-resize touch-pan-y items-center justify-center ps-2.5 pe-1 text-text-secondary select-none motion-safe:transition-colors motion-safe:duration-(--duration-quick) data-[text]:font-medium hover:text-foreground group-data-[scrubbing]/scrub:text-foreground group-data-[disabled]/scrub:cursor-not-allowed [&_svg]:size-3.5 [&_svg]:flex-none",
|
|
414
|
+
className: "flex min-w-7.5 cursor-ew-resize touch-pan-y items-center justify-center ps-2.5 pe-1 text-text-secondary select-none motion-safe:transition-colors motion-safe:duration-(--duration-quick) data-[text]:font-medium hover:text-foreground group-data-[scrubbing]/scrub:text-foreground group-data-[readonly]/scrub:cursor-default group-data-[readonly]/scrub:hover:text-text-secondary group-data-[disabled]/scrub:cursor-not-allowed [&_svg]:size-3.5 [&_svg]:flex-none",
|
|
407
415
|
children: label
|
|
408
416
|
}),
|
|
409
417
|
/* @__PURE__ */ jsxs("div", {
|
|
@@ -425,14 +433,18 @@ const ScrubInput = forwardRef(function ScrubInput({ label, value, defaultValue =
|
|
|
425
433
|
"aria-valuemax": Number.isFinite(max) ? max : void 0,
|
|
426
434
|
"aria-valuetext": valueText,
|
|
427
435
|
"aria-invalid": invalid || void 0,
|
|
436
|
+
"aria-readonly": readOnly || void 0,
|
|
428
437
|
disabled,
|
|
438
|
+
readOnly,
|
|
429
439
|
value: text,
|
|
430
|
-
onChange: (event) =>
|
|
440
|
+
onChange: (event) => {
|
|
441
|
+
if (!readOnly) setDraft(event.target.value);
|
|
442
|
+
},
|
|
431
443
|
onFocus: onInputFocus,
|
|
432
444
|
onBlur: onInputBlur,
|
|
433
445
|
onKeyDown: onInputKeyDown,
|
|
434
|
-
className: cnAll("m-0 h-full w-full min-w-0 flex-1 border-0 bg-transparent p-0 ps-1 font-sans text-foreground tabular-nums outline-none selection:bg-primary selection:text-primary-foreground disabled:cursor-not-allowed", size === "sm" ? "text-xs" : "text-sm")
|
|
435
|
-
}), unit ? unitList.length > 1 ? /* @__PURE__ */ jsx(Button, {
|
|
446
|
+
className: cnAll("m-0 h-full w-full min-w-0 flex-1 border-0 bg-transparent p-0 ps-1 font-sans text-foreground tabular-nums outline-none selection:bg-primary selection:text-primary-foreground read-only:caret-transparent disabled:cursor-not-allowed", size === "sm" ? "text-xs" : "text-sm")
|
|
447
|
+
}), unit ? unitList.length > 1 && !readOnly ? /* @__PURE__ */ jsx(Button, {
|
|
436
448
|
"data-slot": "scrub-input-unit",
|
|
437
449
|
isDisabled: disabled,
|
|
438
450
|
onPress: cycleUnit,
|