@behavioral-agentic-design-system/core 0.40.0 → 0.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +2 -0
  2. package/package.json +41 -9
  3. package/scripts/a11y-lint.cjs +66 -3
  4. package/scripts/check-spec.mjs +73 -0
  5. package/scripts/deal-directions.mjs +186 -0
  6. package/scripts/health-report.mjs +23 -3
  7. package/scripts/lib/counted-lint.mjs +100 -0
  8. package/scripts/lib/marketing-library.mjs +129 -0
  9. package/scripts/lib/on-system.mjs +249 -0
  10. package/scripts/lib/random.mjs +22 -0
  11. package/scripts/lib/spec-parse.d.mts +25 -0
  12. package/scripts/lib/spec-parse.mjs +188 -0
  13. package/scripts/lib/tells.mjs +128 -0
  14. package/scripts/lint-css-vars.mjs +175 -0
  15. package/scripts/lint-html-nesting.mjs +116 -0
  16. package/scripts/lint-live-ctas.mjs +138 -0
  17. package/scripts/lint-slop.mjs +25 -1
  18. package/scripts/on-system-score.mjs +95 -0
  19. package/scripts/slop-rules.mjs +1 -1
  20. package/scripts/source-images.mjs +180 -0
  21. package/scripts/ux-tells.mjs +78 -0
  22. package/scripts/wcag-audit.cjs +72 -5
  23. package/src/api/brand-colors.ts +3 -0
  24. package/src/api/brand-fonts.ts +3 -0
  25. package/src/api/brand-mark.ts +6 -1
  26. package/src/api/dev-write-guard.ts +53 -0
  27. package/src/api/layers/file.ts +7 -4
  28. package/src/api/onboarding-extract.ts +85 -30
  29. package/src/api/onboarding.ts +3 -0
  30. package/src/api/save-tokens.ts +3 -0
  31. package/src/app/layout.tsx +6 -0
  32. package/src/app/opengraph-image.tsx +5 -0
  33. package/src/app/preview/canvas/page.tsx +12 -0
  34. package/src/app/preview/components/page.tsx +2003 -2
  35. package/src/app/preview/studio/blank-screen.tsx +143 -0
  36. package/src/app/preview/studio/page.tsx +7 -0
  37. package/src/app/shell.tsx +168 -49
  38. package/src/components/Foundations/Motion.stories.tsx +1 -0
  39. package/src/components/canvas/canvas.tsx +458 -0
  40. package/src/components/canvas/layout.ts +72 -0
  41. package/src/components/canvas/parse-canvas.ts +32 -0
  42. package/src/components/canvas/sample.ts +90 -0
  43. package/src/components/canvas/spec-frame.tsx +43 -0
  44. package/src/components/canvas/types.ts +33 -0
  45. package/src/components/customize/design-controls.tsx +16 -1
  46. package/src/components/docs-tab.tsx +7 -7
  47. package/src/components/home-recent.tsx +73 -0
  48. package/src/components/home-tab.tsx +13 -13
  49. package/src/components/layers-tab.tsx +2 -2
  50. package/src/components/markdown-preview.tsx +60 -12
  51. package/src/components/studio/control-panel.tsx +299 -0
  52. package/src/components/studio/control-row.tsx +77 -0
  53. package/src/components/studio/preview-frame.tsx +165 -0
  54. package/src/components/studio/preview-pane.tsx +247 -0
  55. package/src/components/studio/studio.tsx +158 -0
  56. package/src/components/studio/types.ts +218 -0
  57. package/src/components/studio/use-studio-tweaks.ts +128 -0
  58. package/src/components/studio/use-studio-view-state.ts +72 -0
  59. package/src/components/ui/anchor.tsx +37 -3
  60. package/src/components/ui/attachment.tsx +211 -0
  61. package/src/components/ui/autocomplete.tsx +1 -1
  62. package/src/components/ui/chart.tsx +3 -0
  63. package/src/components/ui/code.tsx +1 -1
  64. package/src/components/ui/color-picker.tsx +21 -5
  65. package/src/components/ui/data-table.tsx +64 -3
  66. package/src/components/ui/date-field.tsx +1 -1
  67. package/src/components/ui/editable.tsx +1 -0
  68. package/src/components/ui/faceted-filter.tsx +187 -0
  69. package/src/components/ui/gauge-chart.tsx +252 -0
  70. package/src/components/ui/heatmap.tsx +256 -0
  71. package/src/components/ui/index.ts +9 -0
  72. package/src/components/ui/infinite-scroll.tsx +103 -0
  73. package/src/components/ui/inline-edit.tsx +175 -0
  74. package/src/components/ui/json-input.tsx +351 -0
  75. package/src/components/ui/month-picker.tsx +1 -1
  76. package/src/components/ui/navigation-progress.tsx +281 -0
  77. package/src/components/ui/number-input.tsx +27 -7
  78. package/src/components/ui/otp-input.tsx +208 -0
  79. package/src/components/ui/password-input.tsx +2 -1
  80. package/src/components/ui/password-strength-input.tsx +288 -0
  81. package/src/components/ui/phone-input.tsx +274 -0
  82. package/src/components/ui/pill.tsx +140 -0
  83. package/src/components/ui/popover.tsx +27 -4
  84. package/src/components/ui/scroll-progress.tsx +100 -0
  85. package/src/components/ui/search-input.tsx +1 -1
  86. package/src/components/ui/snackbar.tsx +393 -0
  87. package/src/components/ui/sortable-list.tsx +342 -0
  88. package/src/components/ui/squircle.tsx +1 -1
  89. package/src/components/ui/table.tsx +1 -1
  90. package/src/components/ui/tags-input.tsx +1 -1
  91. package/src/components/ui/timer.tsx +1 -0
  92. package/src/components/ui/tour.tsx +1 -3
  93. package/src/components/ui/transfer-list.tsx +13 -26
  94. package/src/components/ui/week-picker.tsx +1 -1
  95. package/src/components/ui/year-picker.tsx +1 -1
  96. package/src/data/component-added.json +958 -0
  97. package/src/data/docs-index.ts +36 -0
  98. package/src/hooks/use-global-mono-font.ts +1 -0
  99. package/src/hooks/use-global-primary-color.ts +1 -0
  100. package/src/hooks/use-global-sans-font.ts +1 -0
  101. package/src/hooks/use-global-serif-font.ts +1 -0
  102. package/src/hooks/use-global-type-scale.ts +17 -2
  103. package/src/hooks/use-mobile.ts +2 -0
  104. package/src/hooks/use-sync-type-scale.ts +7 -11
  105. package/src/lib/clamp.ts +2 -0
  106. package/src/lib/spec-parse.ts +4 -0
  107. package/src/lib/svg-sanitize.ts +19 -9
  108. package/src/stories/Anchor.stories.tsx +54 -0
  109. package/src/stories/Attachment.stories.tsx +189 -0
  110. package/src/stories/Autocomplete.stories.tsx +2 -0
  111. package/src/stories/Canvas.stories.tsx +45 -0
  112. package/src/stories/Chart.stories.tsx +4 -0
  113. package/src/stories/Code.stories.tsx +1 -0
  114. package/src/stories/ColorPicker.stories.tsx +41 -0
  115. package/src/stories/DataTable.stories.tsx +30 -0
  116. package/src/stories/DateField.stories.tsx +21 -0
  117. package/src/stories/Editable.stories.tsx +2 -0
  118. package/src/stories/FacetedFilter.stories.tsx +197 -0
  119. package/src/stories/GaugeChart.stories.tsx +169 -0
  120. package/src/stories/Heatmap.stories.tsx +172 -0
  121. package/src/stories/InfiniteScroll.stories.tsx +225 -0
  122. package/src/stories/InlineEdit.stories.tsx +106 -0
  123. package/src/stories/JsonInput.stories.tsx +212 -0
  124. package/src/stories/MarkdownPreview.stories.tsx +53 -0
  125. package/src/stories/MonthPicker.stories.tsx +21 -0
  126. package/src/stories/NavigationProgress.stories.tsx +159 -0
  127. package/src/stories/NumberInput.stories.tsx +26 -0
  128. package/src/stories/OtpInput.stories.tsx +110 -0
  129. package/src/stories/PasswordInput.stories.tsx +4 -0
  130. package/src/stories/PasswordStrengthInput.stories.tsx +211 -0
  131. package/src/stories/PhoneInput.stories.tsx +127 -0
  132. package/src/stories/Pill.stories.tsx +201 -0
  133. package/src/stories/Popover.stories.tsx +29 -1
  134. package/src/stories/Portal.stories.tsx +3 -1
  135. package/src/stories/ScrollProgress.stories.tsx +117 -0
  136. package/src/stories/SearchInput.stories.tsx +2 -0
  137. package/src/stories/Snackbar.stories.tsx +315 -0
  138. package/src/stories/SortableList.stories.tsx +263 -0
  139. package/src/stories/Squircle.stories.tsx +1 -0
  140. package/src/stories/Table.stories.tsx +1 -0
  141. package/src/stories/TagsInput.stories.tsx +2 -0
  142. package/src/stories/Timer.stories.tsx +26 -0
  143. package/src/stories/Tour.stories.tsx +1 -0
  144. package/src/stories/TransferList.stories.tsx +4 -0
  145. package/src/stories/WeekPicker.stories.tsx +21 -0
  146. package/src/stories/YearPicker.stories.tsx +21 -0
  147. package/src/stories/story-groups.json +33 -16
  148. package/src/tokens.json +82 -54
@@ -0,0 +1,256 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+
5
+ import { cn } from "../../lib/utils"
6
+
7
+ // Heatmap — a matrix of cells whose color intensity encodes a value.
8
+ //
9
+ // The fifth chart primitive, and the first one that is not a Recharts wrapper:
10
+ // Recharts has no heatmap series, and a value matrix does not want an SVG
11
+ // anyway. It wants a <table>. Row and column headers are the axes, each cell
12
+ // is a <td> with a tinted swatch, and the formatted value rides along as
13
+ // screen-reader-only text, so the chart is its own text alternative — a
14
+ // screen reader walks it as "Mon, Week 3, 12 commits" with no separate data
15
+ // table needed (docs/chart-design.md → Accessibility recap).
16
+ //
17
+ // Peer parity: Mantine `@mantine/charts` Heatmap (5 levels, Less→More legend,
18
+ // per-cell tooltip), MUI X Charts Heatmap (x/y axes + continuous color map),
19
+ // AntV Heatmap (xField/yField/colorField + legend ramp). BADS keeps the five
20
+ // levels and the legend, uses a native `title` for the per-cell tooltip, and
21
+ // adds the table semantics none of the three ship.
22
+ //
23
+ // Color (docs/chart-color-palette.md): ONE series color — `--chart-1` by
24
+ // default — and an opacity ramp for intensity. The data is the only saturated
25
+ // thing on the canvas; labels and the legend chrome sit in muted-foreground.
26
+ // Level 0 (the lowest bucket) and "no data" are `--muted`, so a quiet cell
27
+ // reads as surface, not as a faint data mark. Zero new tokens.
28
+ //
29
+ // Motion is pattern (c): the swatch transitions opacity + box-shadow on
30
+ // var(--duration-fast) / var(--ease-out) for the hover ring. Static otherwise.
31
+
32
+ const LEVELS = 5
33
+ /** Opacity for levels 1..4 (level 0 is the muted "lowest" bucket). */
34
+ const LEVEL_OPACITY = [0, 0.3, 0.5, 0.75, 1] as const
35
+
36
+ const sizeClass = {
37
+ sm: "size-3",
38
+ md: "size-4",
39
+ lg: "size-6",
40
+ } as const
41
+
42
+ // Explicit default locale, same reasoning as FormatNumber: an implicit
43
+ // navigator locale formats differently on the server and the client. Pass
44
+ // `formatValue` from your i18n layer to localize.
45
+ const defaultFormatter = new Intl.NumberFormat("en-US")
46
+
47
+ export interface HeatmapProps
48
+ extends Omit<React.ComponentProps<"div">, "children"> {
49
+ /** Row (y-axis) labels, top to bottom. One per row of `data`. */
50
+ rows: string[]
51
+ /** Column (x-axis) labels, left to right. One per entry of each row. */
52
+ columns: string[]
53
+ /**
54
+ * `rows.length` × `columns.length` matrix. `null` / `undefined` is "no data"
55
+ * and renders as a quiet muted cell, announced as "No data".
56
+ */
57
+ data: ReadonlyArray<ReadonlyArray<number | null | undefined>>
58
+ /**
59
+ * Series color — any CSS color, usually a chart token
60
+ * (`var(--chart-2)`). Intensity is an opacity ramp of this one color.
61
+ * Defaults to `var(--chart-1)`.
62
+ */
63
+ color?: string
64
+ /** Cell size: sm 12px, md 16px (default), lg 24px. */
65
+ size?: keyof typeof sizeClass
66
+ /**
67
+ * Fixed `[min, max]` for the intensity scale. Defaults to the data's own
68
+ * range. Pass it when several heatmaps must share one scale (a row of
69
+ * months, one per card) so the same value reads the same shade everywhere.
70
+ */
71
+ domain?: [number, number]
72
+ /**
73
+ * Formats a value for the cell tooltip, the screen-reader text, and the
74
+ * legend. Defaults to `Intl.NumberFormat("en-US")`.
75
+ */
76
+ formatValue?: (value: number) => string
77
+ /** Render the Less → More ramp below the grid. Default `true`. */
78
+ showLegend?: boolean
79
+ /**
80
+ * Accessible name — becomes the scroll region's `aria-label` and the
81
+ * table's caption. Say what the matrix measures: "Commits by weekday,
82
+ * last 12 weeks". Default "Heatmap".
83
+ */
84
+ label?: string
85
+ }
86
+
87
+ function quantize(
88
+ value: number | null | undefined,
89
+ min: number,
90
+ max: number
91
+ ): number | null {
92
+ if (value == null || Number.isNaN(value)) return null
93
+ if (max === min) return value > 0 ? LEVELS - 1 : 0
94
+ if (value <= min) return 0
95
+ const t = (value - min) / (max - min)
96
+ return Math.min(LEVELS - 1, 1 + Math.floor(t * (LEVELS - 1)))
97
+ }
98
+
99
+ function Heatmap({
100
+ rows,
101
+ columns,
102
+ data,
103
+ color = "var(--chart-1)",
104
+ size = "md",
105
+ domain,
106
+ formatValue,
107
+ showLegend = true,
108
+ label = "Heatmap",
109
+ className,
110
+ ...props
111
+ }: HeatmapProps) {
112
+ const format = React.useCallback(
113
+ (v: number) => (formatValue ? formatValue(v) : defaultFormatter.format(v)),
114
+ [formatValue]
115
+ )
116
+
117
+ const [min, max] = React.useMemo<[number, number]>(() => {
118
+ if (domain) return domain
119
+ let lo = Number.POSITIVE_INFINITY
120
+ let hi = Number.NEGATIVE_INFINITY
121
+ for (const row of data) {
122
+ for (const v of row) {
123
+ if (v == null || Number.isNaN(v)) continue
124
+ if (v < lo) lo = v
125
+ if (v > hi) hi = v
126
+ }
127
+ }
128
+ if (lo === Number.POSITIVE_INFINITY) return [0, 0]
129
+ return [lo, hi]
130
+ }, [data, domain])
131
+
132
+ const swatchSize = sizeClass[size]
133
+ const motion: React.CSSProperties = {
134
+ transitionDuration: "var(--duration-fast)",
135
+ transitionTimingFunction: "var(--ease-out)",
136
+ }
137
+
138
+ return (
139
+ <div
140
+ data-slot="heatmap"
141
+ data-size={size}
142
+ // The matrix can be wider than its container (52 weeks, 24 hours), so
143
+ // the root is a scroll region. A scroll container no keyboard user can
144
+ // reach fails axe (scrollable-region-focusable) — hence tabIndex + a
145
+ // landmark role with the chart's name (corrections #019).
146
+ role="region"
147
+ aria-label={label}
148
+ tabIndex={0}
149
+ className={cn(
150
+ "inline-flex max-w-full flex-col gap-3 overflow-x-auto rounded-md outline-none",
151
+ "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
152
+ className
153
+ )}
154
+ {...props}
155
+ >
156
+ <table
157
+ data-slot="heatmap-table"
158
+ className="w-max border-separate border-spacing-0.5 text-xs text-muted-foreground"
159
+ >
160
+ <caption className="sr-only">{label}</caption>
161
+ <thead>
162
+ <tr>
163
+ {/* Empty corner cell above the row labels. */}
164
+ <td aria-hidden="true" />
165
+ {columns.map((column, ci) => (
166
+ <th
167
+ key={`${column}-${ci}`}
168
+ scope="col"
169
+ data-slot="heatmap-column-label"
170
+ className="px-0 pb-1 text-center align-bottom font-normal whitespace-nowrap"
171
+ >
172
+ {column}
173
+ </th>
174
+ ))}
175
+ </tr>
176
+ </thead>
177
+ <tbody>
178
+ {rows.map((row, ri) => (
179
+ <tr key={`${row}-${ri}`}>
180
+ <th
181
+ scope="row"
182
+ data-slot="heatmap-row-label"
183
+ className="pr-2 text-left align-middle font-normal whitespace-nowrap"
184
+ >
185
+ {row}
186
+ </th>
187
+ {columns.map((column, ci) => {
188
+ const value = data[ri]?.[ci]
189
+ const level = quantize(value, min, max)
190
+ const text =
191
+ level == null ? "No data" : format(value as number)
192
+ return (
193
+ <td
194
+ key={`${column}-${ci}`}
195
+ data-slot="heatmap-cell"
196
+ data-level={level ?? undefined}
197
+ title={`${row} · ${column}: ${text}`}
198
+ className="group/cell p-0 align-middle"
199
+ >
200
+ <span
201
+ data-slot="heatmap-swatch"
202
+ aria-hidden="true"
203
+ className={cn(
204
+ "block rounded-sm transition-[opacity,box-shadow]",
205
+ swatchSize,
206
+ level == null && "bg-muted/50",
207
+ level === 0 && "bg-muted",
208
+ "group-hover/cell:ring-2 group-hover/cell:ring-ring group-hover/cell:ring-offset-1 group-hover/cell:ring-offset-background"
209
+ )}
210
+ style={{
211
+ ...motion,
212
+ ...(level != null && level > 0
213
+ ? { backgroundColor: color, opacity: LEVEL_OPACITY[level] }
214
+ : null),
215
+ }}
216
+ />
217
+ <span className="sr-only">{text}</span>
218
+ </td>
219
+ )
220
+ })}
221
+ </tr>
222
+ ))}
223
+ </tbody>
224
+ </table>
225
+ {showLegend && (
226
+ <div
227
+ data-slot="heatmap-legend"
228
+ className="flex items-center justify-end gap-1 text-xs text-muted-foreground"
229
+ >
230
+ <span>Less</span>
231
+ <span className="sr-only">
232
+ {` (${format(min)}) to `}
233
+ </span>
234
+ <span aria-hidden="true" className="flex items-center gap-0.5">
235
+ {Array.from({ length: LEVELS }, (_, level) => (
236
+ <span
237
+ key={level}
238
+ data-level={level}
239
+ className={cn("block rounded-sm", swatchSize, level === 0 && "bg-muted")}
240
+ style={
241
+ level > 0
242
+ ? { backgroundColor: color, opacity: LEVEL_OPACITY[level] }
243
+ : undefined
244
+ }
245
+ />
246
+ ))}
247
+ </span>
248
+ <span>More</span>
249
+ <span className="sr-only">{` (${format(max)})`}</span>
250
+ </div>
251
+ )}
252
+ </div>
253
+ )
254
+ }
255
+
256
+ export { Heatmap }
@@ -152,3 +152,12 @@ export * from "./icon";
152
152
  export * from "./progress-stack";
153
153
  export * from "./callout";
154
154
  export * from "./announcement-bar";
155
+ export * from "./gauge-chart";
156
+ export * from "./password-strength-input";
157
+ export * from "./pill";
158
+ export * from "./snackbar";
159
+ export * from "./json-input";
160
+ export * from "./sortable-list";
161
+ export * from "./heatmap";
162
+ export * from "./navigation-progress";
163
+ export * from "./attachment";
@@ -0,0 +1,103 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { cn } from "../../lib/utils"
5
+ import { Spinner } from "./spinner"
6
+
7
+ export interface InfiniteScrollProps {
8
+ /** Fired when the sentinel enters the viewport and `hasMore` is true. */
9
+ onLoadMore: () => void
10
+ /** Whether more pages are available. When false the sentinel is removed. */
11
+ hasMore: boolean
12
+ /** Override the default spinner. Pass `null` to suppress the loader entirely. */
13
+ loader?: React.ReactNode
14
+ /** Shown below the list when `hasMore` is false. */
15
+ endMessage?: React.ReactNode
16
+ /**
17
+ * IntersectionObserver threshold (0–1). Default 0.
18
+ * Higher values trigger earlier (before the sentinel fully enters view).
19
+ */
20
+ threshold?: number
21
+ /**
22
+ * IntersectionObserver rootMargin. Default "0px 0px 200px 0px" (triggers
23
+ * 200px before the sentinel reaches the viewport bottom).
24
+ */
25
+ rootMargin?: string
26
+ children: React.ReactNode
27
+ className?: string
28
+ }
29
+
30
+ /**
31
+ * Wraps a list with an IntersectionObserver-based load-more trigger.
32
+ * The sentinel sits below `children`; when it enters the viewport and
33
+ * `hasMore` is true, `onLoadMore` fires once per intersection.
34
+ *
35
+ * Sources: Mantine InfiniteScroll (Embla fork), TanStack Query infinite
36
+ * scroll recipe, react-infinite-scroll-component (npm), shadcn community
37
+ * infinite-scroll recipe (2026-Q3).
38
+ */
39
+ function InfiniteScroll({
40
+ onLoadMore,
41
+ hasMore,
42
+ loader,
43
+ endMessage,
44
+ threshold = 0,
45
+ rootMargin = "0px 0px 200px 0px",
46
+ children,
47
+ className,
48
+ }: InfiniteScrollProps) {
49
+ const sentinelRef = React.useRef<HTMLDivElement>(null)
50
+ const loadingRef = React.useRef(false)
51
+
52
+ React.useEffect(() => {
53
+ const sentinel = sentinelRef.current
54
+ if (!sentinel || !hasMore) return
55
+
56
+ const observer = new IntersectionObserver(
57
+ (entries) => {
58
+ const entry = entries[0]
59
+ if (!entry.isIntersecting) {
60
+ // The sentinel left the viewport: re-arm for the next entry. Before
61
+ // this, the guard only reset on a `hasMore` transition, so a list
62
+ // whose `hasMore` stayed true loaded exactly one page and went inert.
63
+ loadingRef.current = false
64
+ return
65
+ }
66
+ if (!loadingRef.current) {
67
+ loadingRef.current = true
68
+ onLoadMore()
69
+ }
70
+ },
71
+ { threshold, rootMargin }
72
+ )
73
+
74
+ observer.observe(sentinel)
75
+ return () => observer.disconnect()
76
+ }, [hasMore, onLoadMore, threshold, rootMargin])
77
+
78
+ // Reset loading guard when hasMore changes (i.e. a new page loaded).
79
+ React.useEffect(() => {
80
+ loadingRef.current = false
81
+ }, [hasMore])
82
+
83
+ const defaultLoader = (
84
+ <div className="flex justify-center py-4" aria-label="Loading more items">
85
+ <Spinner size="sm" />
86
+ </div>
87
+ )
88
+
89
+ return (
90
+ <div data-slot="infinite-scroll" className={cn("w-full", className)}>
91
+ {children}
92
+ {hasMore ? (
93
+ <div ref={sentinelRef} aria-hidden="true">
94
+ {loader === null ? null : loader ?? defaultLoader}
95
+ </div>
96
+ ) : (
97
+ endMessage
98
+ )}
99
+ </div>
100
+ )
101
+ }
102
+
103
+ export { InfiniteScroll }
@@ -0,0 +1,175 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { cva, type VariantProps } from "class-variance-authority"
5
+ import { cn } from "../../lib/utils"
6
+
7
+ const inlineEditViewVariants = cva(
8
+ "inline-flex w-full min-w-0 cursor-text items-center rounded-md outline-none transition-colors select-none",
9
+ {
10
+ variants: {
11
+ variant: {
12
+ ghost:
13
+ "px-0 hover:bg-muted/60 data-[empty=true]:text-muted-foreground",
14
+ outline:
15
+ "border border-transparent px-3 hover:border-input data-[empty=true]:text-muted-foreground",
16
+ },
17
+ size: {
18
+ sm: "h-8 text-sm",
19
+ default: "h-9 text-sm md:text-sm",
20
+ lg: "h-10 text-base",
21
+ },
22
+ },
23
+ defaultVariants: { variant: "ghost", size: "default" },
24
+ }
25
+ )
26
+
27
+ const inlineEditInputVariants = cva(
28
+ "w-full min-w-0 rounded-md border bg-transparent outline-none transition-[color,box-shadow] placeholder:text-muted-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50",
29
+ {
30
+ variants: {
31
+ variant: {
32
+ ghost:
33
+ "rounded-none border-0 border-b border-input focus-visible:border-ring focus-visible:ring-0",
34
+ outline:
35
+ "border-input shadow-xs focus-visible:border-ring dark:bg-input/30",
36
+ },
37
+ size: {
38
+ sm: "h-8 px-2.5 text-sm",
39
+ default: "h-9 px-3 text-sm md:text-sm",
40
+ lg: "h-10 px-4 text-base",
41
+ },
42
+ },
43
+ defaultVariants: { variant: "ghost", size: "default" },
44
+ }
45
+ )
46
+
47
+ export interface InlineEditProps
48
+ extends Omit<React.ComponentProps<"input">, "size" | "onChange">,
49
+ VariantProps<typeof inlineEditViewVariants> {
50
+ /** Controlled value. Use with onConfirm / onCancel. */
51
+ value?: string
52
+ /** Uncontrolled initial value. */
53
+ defaultValue?: string
54
+ /** Called with the new value when the user confirms (Enter or blur). */
55
+ onConfirm?: (value: string) => void
56
+ /** Called when the user cancels with Escape; value reverts to before-edit state. */
57
+ onCancel?: (value: string) => void
58
+ /** Placeholder shown in view mode when value is empty. */
59
+ placeholder?: string
60
+ /** When true the input renders directly without the view-mode toggle. */
61
+ alwaysEditing?: boolean
62
+ /** Wrapper className */
63
+ className?: string
64
+ /** Input element className override */
65
+ inputClassName?: string
66
+ }
67
+
68
+ function InlineEdit({
69
+ value: controlledValue,
70
+ defaultValue = "",
71
+ onConfirm,
72
+ onCancel,
73
+ placeholder = "Click to edit",
74
+ alwaysEditing = false,
75
+ disabled,
76
+ variant,
77
+ size,
78
+ className,
79
+ inputClassName,
80
+ ...inputProps
81
+ }: InlineEditProps) {
82
+ const [editing, setEditing] = React.useState(alwaysEditing)
83
+ const [draft, setDraft] = React.useState(controlledValue ?? defaultValue)
84
+ const [committed, setCommitted] = React.useState(controlledValue ?? defaultValue)
85
+ const inputRef = React.useRef<HTMLInputElement>(null)
86
+
87
+ // Sync when controlled value changes from outside
88
+ React.useEffect(() => {
89
+ if (controlledValue !== undefined) {
90
+ setDraft(controlledValue)
91
+ setCommitted(controlledValue)
92
+ }
93
+ }, [controlledValue])
94
+
95
+ const startEdit = () => {
96
+ if (disabled || alwaysEditing) return
97
+ setEditing(true)
98
+ }
99
+
100
+ const confirm = () => {
101
+ if (!editing) return
102
+ setCommitted(draft)
103
+ setEditing(false)
104
+ onConfirm?.(draft)
105
+ }
106
+
107
+ const cancel = () => {
108
+ if (!editing) return
109
+ setDraft(committed)
110
+ setEditing(false)
111
+ onCancel?.(committed)
112
+ }
113
+
114
+ React.useEffect(() => {
115
+ if (editing) {
116
+ inputRef.current?.focus()
117
+ inputRef.current?.select()
118
+ }
119
+ }, [editing])
120
+
121
+ const displayValue = controlledValue ?? committed
122
+
123
+ if (!editing && !alwaysEditing) {
124
+ return (
125
+ <span
126
+ role="button"
127
+ tabIndex={disabled ? -1 : 0}
128
+ data-slot="inline-edit-view"
129
+ data-empty={!displayValue ? "true" : undefined}
130
+ aria-label={displayValue || placeholder}
131
+ onClick={startEdit}
132
+ onKeyDown={(e) => {
133
+ if (e.key === "Enter" || e.key === " ") {
134
+ e.preventDefault()
135
+ startEdit()
136
+ }
137
+ }}
138
+ className={cn(
139
+ inlineEditViewVariants({ variant, size }),
140
+ disabled && "cursor-not-allowed opacity-50",
141
+ className
142
+ )}
143
+ >
144
+ {displayValue || (
145
+ <span className="text-muted-foreground">{placeholder}</span>
146
+ )}
147
+ </span>
148
+ )
149
+ }
150
+
151
+ return (
152
+ <input
153
+ ref={inputRef}
154
+ data-slot="inline-edit-input"
155
+ value={draft}
156
+ onChange={(e) => setDraft(e.target.value)}
157
+ onBlur={confirm}
158
+ onKeyDown={(e) => {
159
+ if (e.key === "Enter") {
160
+ e.preventDefault()
161
+ confirm()
162
+ } else if (e.key === "Escape") {
163
+ e.preventDefault()
164
+ cancel()
165
+ }
166
+ }}
167
+ disabled={disabled}
168
+ placeholder={placeholder}
169
+ {...inputProps}
170
+ className={cn(inlineEditInputVariants({ variant, size }), inputClassName)}
171
+ />
172
+ )
173
+ }
174
+
175
+ export { InlineEdit, inlineEditViewVariants, inlineEditInputVariants }