@behavioral-agentic-design-system/core 0.21.0 → 0.23.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.
@@ -0,0 +1,323 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+
5
+ import { cn } from "../../lib/utils"
6
+ import { Button } from "./button"
7
+
8
+ type SubmitMode = "blur" | "enter" | "both"
9
+
10
+ interface EditableContextValue {
11
+ editing: boolean
12
+ value: string
13
+ inputRef: React.RefObject<HTMLInputElement | null>
14
+ previewRef: React.RefObject<HTMLDivElement | null>
15
+ startEditing: () => void
16
+ cancelEditing: () => void
17
+ submitEditing: () => void
18
+ disabled: boolean
19
+ submitMode: SubmitMode
20
+ placeholder: string
21
+ }
22
+
23
+ const EditableContext = React.createContext<EditableContextValue | null>(null)
24
+
25
+ function useEditableContext() {
26
+ const ctx = React.useContext(EditableContext)
27
+ if (!ctx) throw new Error("Editable sub-components must be used inside <Editable>")
28
+ return ctx
29
+ }
30
+
31
+ interface EditableProps {
32
+ value?: string
33
+ defaultValue?: string
34
+ onValueChange?: (value: string) => void
35
+ onEditStart?: () => void
36
+ onEditEnd?: (value: string) => void
37
+ disabled?: boolean
38
+ placeholder?: string
39
+ submitMode?: SubmitMode
40
+ /**
41
+ * Accessible name for the edit-mode input (e.g. "Project name"). Falls back
42
+ * to `placeholder` — pass a real label whenever the placeholder is the
43
+ * generic "Click to edit", or screen readers announce a nameless textbox.
44
+ */
45
+ label?: string
46
+ children: React.ReactNode
47
+ className?: string
48
+ }
49
+
50
+ function Editable({
51
+ value: valueProp,
52
+ defaultValue = "",
53
+ onValueChange,
54
+ onEditStart,
55
+ onEditEnd,
56
+ disabled = false,
57
+ placeholder = "Click to edit",
58
+ submitMode = "blur",
59
+ label,
60
+ children,
61
+ className,
62
+ }: EditableProps) {
63
+ const [internalValue, setInternalValue] = React.useState(defaultValue)
64
+ const [editing, setEditing] = React.useState(false)
65
+ const [draft, setDraft] = React.useState(defaultValue)
66
+ const inputRef = React.useRef<HTMLInputElement>(null)
67
+ const previewRef = React.useRef<HTMLDivElement>(null)
68
+ const rootRef = React.useRef<HTMLDivElement>(null)
69
+
70
+ const isControlled = valueProp !== undefined
71
+ const value = isControlled ? valueProp : internalValue
72
+
73
+ const startEditing = React.useCallback(() => {
74
+ if (disabled) return
75
+ setDraft(value)
76
+ setEditing(true)
77
+ onEditStart?.()
78
+ // Focus in a microtask so the input has rendered
79
+ queueMicrotask(() => inputRef.current?.focus())
80
+ }, [disabled, value, onEditStart])
81
+
82
+ // When edit mode ends, DOM focus may still sit on the now aria-hidden,
83
+ // opacity-0 input (Escape/Enter don't blur) or on a Save/Cancel button that
84
+ // is about to unmount — both strand keyboard focus on nothing. Return focus
85
+ // to the preview, but ONLY if focus is still inside this Editable: a
86
+ // blur-submit triggered by clicking elsewhere must not steal focus back.
87
+ const restoreFocusToPreview = React.useCallback(() => {
88
+ const hadFocusInside = rootRef.current?.contains(document.activeElement)
89
+ if (!hadFocusInside) return
90
+ queueMicrotask(() => previewRef.current?.focus())
91
+ }, [])
92
+
93
+ const submitEditing = React.useCallback(() => {
94
+ if (!editing) return
95
+ const trimmed = draft.trim()
96
+ const committed = trimmed || value
97
+ if (!isControlled) setInternalValue(committed)
98
+ onValueChange?.(committed)
99
+ onEditEnd?.(committed)
100
+ restoreFocusToPreview()
101
+ setEditing(false)
102
+ }, [editing, draft, value, isControlled, onValueChange, onEditEnd, restoreFocusToPreview])
103
+
104
+ const cancelEditing = React.useCallback(() => {
105
+ setDraft(value)
106
+ restoreFocusToPreview()
107
+ setEditing(false)
108
+ }, [value, restoreFocusToPreview])
109
+
110
+ return (
111
+ <EditableContext.Provider
112
+ value={{
113
+ editing,
114
+ value,
115
+ inputRef,
116
+ previewRef,
117
+ startEditing,
118
+ cancelEditing,
119
+ submitEditing,
120
+ disabled,
121
+ submitMode,
122
+ placeholder,
123
+ }}
124
+ >
125
+ <div
126
+ ref={rootRef}
127
+ data-slot="editable"
128
+ data-editing={editing || undefined}
129
+ data-disabled={disabled || undefined}
130
+ className={cn("relative w-full", className)}
131
+ >
132
+ {children}
133
+ {/* Hidden input stores draft and handles keyboard events */}
134
+ <input
135
+ ref={inputRef}
136
+ type="text"
137
+ aria-label={label ?? placeholder}
138
+ aria-hidden={!editing}
139
+ tabIndex={editing ? 0 : -1}
140
+ value={draft}
141
+ onChange={(e) => setDraft(e.target.value)}
142
+ onBlur={() => {
143
+ if (submitMode === "blur" || submitMode === "both") {
144
+ submitEditing()
145
+ }
146
+ }}
147
+ onKeyDown={(e) => {
148
+ if (e.key === "Escape") {
149
+ e.preventDefault()
150
+ cancelEditing()
151
+ }
152
+ if (
153
+ e.key === "Enter" &&
154
+ (submitMode === "enter" || submitMode === "both")
155
+ ) {
156
+ e.preventDefault()
157
+ submitEditing()
158
+ }
159
+ }}
160
+ className={cn(
161
+ // Overlay ONLY the preview area (top of the root), not inset-0 — the root
162
+ // also holds EditableControl (Save/Cancel), and inset-0 stretched the input
163
+ // over those controls, hiding them and ballooning the box. min-h-11 + py-2
164
+ // matches the preview's box so the text doesn't jump on the edit crossfade.
165
+ "absolute inset-x-0 top-0 min-h-11 w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-foreground outline-none",
166
+ "focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
167
+ // The overlay input is only ever visible while editing. A disabled
168
+ // Editable can never enter edit mode, so it must NOT get disabled:opacity-50
169
+ // here — that variant beat the opacity-0 below and un-hid the input at
170
+ // 50%, ghosting it over the (also-50%) preview. Dimming when disabled is
171
+ // the preview's job.
172
+ "disabled:cursor-not-allowed",
173
+ !editing && "pointer-events-none opacity-0"
174
+ )}
175
+ style={{
176
+ transitionProperty: "opacity",
177
+ transitionDuration: "var(--duration-fast)",
178
+ transitionTimingFunction: "var(--ease-out)",
179
+ }}
180
+ disabled={disabled}
181
+ />
182
+ </div>
183
+ </EditableContext.Provider>
184
+ )
185
+ }
186
+
187
+ interface EditablePreviewProps extends React.HTMLAttributes<HTMLDivElement> {
188
+ className?: string
189
+ }
190
+
191
+ function EditablePreview({ className, ...props }: EditablePreviewProps) {
192
+ const { editing, value, placeholder, startEditing, disabled, previewRef } =
193
+ useEditableContext()
194
+
195
+ return (
196
+ <div
197
+ ref={previewRef}
198
+ data-slot="editable-preview"
199
+ role="button"
200
+ tabIndex={disabled ? -1 : 0}
201
+ aria-label={`Edit: ${value || placeholder}`}
202
+ // Marks the control disabled for assistive tech AND tells axe to exempt the
203
+ // dimmed (opacity-50) label from the contrast check — disabled controls are
204
+ // WCAG-exempt, but without aria-disabled axe can't know this div is one.
205
+ aria-disabled={disabled || undefined}
206
+ onClick={() => !disabled && startEditing()}
207
+ onKeyDown={(e) => {
208
+ if ((e.key === "Enter" || e.key === " ") && !disabled) {
209
+ e.preventDefault()
210
+ startEditing()
211
+ }
212
+ }}
213
+ className={cn(
214
+ "min-h-11 w-full cursor-text truncate rounded-md px-3 py-2 text-sm",
215
+ "hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50",
216
+ !value && "text-muted-foreground",
217
+ disabled && "cursor-not-allowed opacity-50",
218
+ editing && "pointer-events-none opacity-0",
219
+ className
220
+ )}
221
+ style={{
222
+ transitionProperty: "opacity, background-color",
223
+ transitionDuration: "var(--duration-fast)",
224
+ transitionTimingFunction: "var(--ease-out)",
225
+ }}
226
+ {...props}
227
+ >
228
+ {value || placeholder}
229
+ </div>
230
+ )
231
+ }
232
+
233
+ interface EditableInputProps
234
+ extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "value" | "onChange"> {
235
+ className?: string
236
+ }
237
+
238
+ // EditableInput is a visible companion — the real input is controlled by Editable root.
239
+ // This renders as a styled shell that positions on top of the preview when editing.
240
+ // The actual <input> is rendered inside <Editable> and absolutely positioned.
241
+ // This component is kept for API symmetry and potential slot customization.
242
+ function EditableInput({ className, ...props }: EditableInputProps) {
243
+ return (
244
+ <div
245
+ data-slot="editable-input-slot"
246
+ aria-hidden
247
+ className={cn("sr-only", className)}
248
+ {...(props as React.HTMLAttributes<HTMLDivElement>)}
249
+ />
250
+ )
251
+ }
252
+
253
+ interface EditableControlProps extends React.HTMLAttributes<HTMLDivElement> {
254
+ className?: string
255
+ }
256
+
257
+ function EditableControl({ className, ...props }: EditableControlProps) {
258
+ const { editing } = useEditableContext()
259
+ if (!editing) return null
260
+ return (
261
+ <div
262
+ data-slot="editable-control"
263
+ className={cn("flex items-center gap-2 pt-2.5", className)}
264
+ {...props}
265
+ />
266
+ )
267
+ }
268
+
269
+ interface EditableSubmitProps
270
+ extends React.ButtonHTMLAttributes<HTMLButtonElement> {
271
+ className?: string
272
+ }
273
+
274
+ function EditableSubmit({ className, children, ...props }: EditableSubmitProps) {
275
+ const { submitEditing } = useEditableContext()
276
+ return (
277
+ <Button
278
+ type="button"
279
+ data-slot="editable-submit"
280
+ size="default"
281
+ onClick={submitEditing}
282
+ className={className}
283
+ {...props}
284
+ >
285
+ {children ?? "Save"}
286
+ </Button>
287
+ )
288
+ }
289
+
290
+ interface EditableCancelProps
291
+ extends React.ButtonHTMLAttributes<HTMLButtonElement> {
292
+ className?: string
293
+ }
294
+
295
+ function EditableCancel({
296
+ className,
297
+ children,
298
+ ...props
299
+ }: EditableCancelProps) {
300
+ const { cancelEditing } = useEditableContext()
301
+ return (
302
+ <Button
303
+ type="button"
304
+ data-slot="editable-cancel"
305
+ variant="ghost"
306
+ size="default"
307
+ onClick={cancelEditing}
308
+ className={className}
309
+ {...props}
310
+ >
311
+ {children ?? "Cancel"}
312
+ </Button>
313
+ )
314
+ }
315
+
316
+ export {
317
+ Editable,
318
+ EditablePreview,
319
+ EditableInput,
320
+ EditableControl,
321
+ EditableSubmit,
322
+ EditableCancel,
323
+ }
@@ -0,0 +1,238 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import { cva, type VariantProps } from "class-variance-authority";
5
+
6
+ import { cn } from "../../lib/utils";
7
+
8
+ /**
9
+ * Semantic grouping for related form controls. Renders a native
10
+ * <fieldset> + <legend>, so the group gets a real accessible name (announced
11
+ * when focus enters any nested control) and, critically, native
12
+ * <fieldset disabled> cascade-disables EVERY control inside it, something a
13
+ * <div> group (FieldGroup) cannot do.
14
+ *
15
+ * Use Fieldset when several controls answer one question: a RadioGroup of
16
+ * plan tiers, a set of notification checkboxes, an address block. Use Field
17
+ * for a single labelled input, and FieldGroup for pure column/row layout of
18
+ * unrelated fields.
19
+ *
20
+ * <Fieldset invalid={!!error}>
21
+ * <FieldsetLegend>Notification preferences</FieldsetLegend>
22
+ * <FieldsetHelper>Choose how we reach you.</FieldsetHelper>
23
+ * ...controls...
24
+ * <FieldsetError>{error}</FieldsetError>
25
+ * </Fieldset>
26
+ *
27
+ * Place <FieldsetLegend> FIRST, because the browser requires <legend> to be the
28
+ * fieldset's first child to render and be announced correctly.
29
+ */
30
+
31
+ type FieldsetContextValue = {
32
+ helperId: string;
33
+ errorId: string;
34
+ invalid: boolean;
35
+ disabled: boolean;
36
+ registerHelper: (present: boolean) => void;
37
+ registerError: (present: boolean) => void;
38
+ };
39
+
40
+ const FieldsetContext = React.createContext<FieldsetContextValue | null>(null);
41
+
42
+ function useFieldsetContext() {
43
+ const ctx = React.useContext(FieldsetContext);
44
+ if (!ctx) {
45
+ throw new Error(
46
+ "Fieldset subcomponents must be rendered inside a <Fieldset> parent.",
47
+ );
48
+ }
49
+ return ctx;
50
+ }
51
+
52
+ const fieldsetVariants = cva(
53
+ // Column flow so legend → helper → controls → error stack with rhythm.
54
+ // transition-[color,box-shadow] animates the invalid border shift; the
55
+ // duration/ease come from tokens via the inline style below (Tailwind v4 has
56
+ // no --duration-* namespace, so the class form would silently no-op).
57
+ "flex min-w-0 flex-col transition-[color,box-shadow]",
58
+ {
59
+ variants: {
60
+ variant: {
61
+ default: "rounded-lg border border-border bg-transparent",
62
+ unstyled: "border-0 p-0",
63
+ },
64
+ size: {
65
+ sm: "gap-2",
66
+ default: "gap-3",
67
+ lg: "gap-4",
68
+ },
69
+ },
70
+ compoundVariants: [
71
+ { variant: "default", size: "sm", className: "p-4" },
72
+ { variant: "default", size: "default", className: "p-5" },
73
+ { variant: "default", size: "lg", className: "p-6" },
74
+ ],
75
+ defaultVariants: { variant: "default", size: "default" },
76
+ },
77
+ );
78
+
79
+ export interface FieldsetProps
80
+ extends Omit<React.ComponentProps<"fieldset">, "disabled">,
81
+ VariantProps<typeof fieldsetVariants> {
82
+ /**
83
+ * Native cascade-disable: disables the fieldset AND every form control
84
+ * nested inside it, no per-control wiring needed.
85
+ */
86
+ disabled?: boolean;
87
+ /** Paints the destructive border/legend and switches aria-describedby to the error. */
88
+ invalid?: boolean;
89
+ }
90
+
91
+ function Fieldset({
92
+ className,
93
+ variant,
94
+ size,
95
+ disabled = false,
96
+ invalid = false,
97
+ style,
98
+ children,
99
+ ...props
100
+ }: FieldsetProps) {
101
+ const reactId = React.useId();
102
+ const helperId = `fieldset-${reactId}-helper`;
103
+ const errorId = `fieldset-${reactId}-error`;
104
+
105
+ const [hasHelper, setHasHelper] = React.useState(false);
106
+ const [hasError, setHasError] = React.useState(false);
107
+
108
+ const ctx = React.useMemo<FieldsetContextValue>(
109
+ () => ({
110
+ helperId,
111
+ errorId,
112
+ invalid,
113
+ disabled,
114
+ registerHelper: setHasHelper,
115
+ registerError: setHasError,
116
+ }),
117
+ [helperId, errorId, invalid, disabled],
118
+ );
119
+
120
+ // Only reference ids that are actually in the DOM, so aria-describedby never
121
+ // dangles (axe aria-valid-attr-value). When invalid, the error replaces the
122
+ // helper both visually and for screen readers.
123
+ const describedBy = invalid
124
+ ? hasError
125
+ ? errorId
126
+ : undefined
127
+ : hasHelper
128
+ ? helperId
129
+ : undefined;
130
+
131
+ return (
132
+ <FieldsetContext.Provider value={ctx}>
133
+ <fieldset
134
+ data-slot="fieldset"
135
+ data-invalid={invalid || undefined}
136
+ data-disabled={disabled || undefined}
137
+ disabled={disabled}
138
+ aria-describedby={describedBy}
139
+ className={cn(
140
+ "group",
141
+ fieldsetVariants({ variant, size }),
142
+ invalid && variant === "default" && "border-destructive",
143
+ className,
144
+ )}
145
+ style={{
146
+ transitionDuration: "var(--duration-base)",
147
+ transitionTimingFunction: "var(--ease-out)",
148
+ ...style,
149
+ }}
150
+ {...props}
151
+ >
152
+ {children}
153
+ </fieldset>
154
+ </FieldsetContext.Provider>
155
+ );
156
+ }
157
+
158
+ /** The group's accessible name. Render as the FIRST child of Fieldset. */
159
+ function FieldsetLegend({
160
+ className,
161
+ ...props
162
+ }: React.ComponentProps<"legend">) {
163
+ const { invalid } = useFieldsetContext();
164
+ return (
165
+ <legend
166
+ data-slot="fieldset-legend"
167
+ className={cn(
168
+ // float-none + w-full so it plays nicely as the first flex child
169
+ "float-none w-full text-sm font-semibold text-foreground",
170
+ "group-data-[disabled]:text-muted-foreground",
171
+ invalid && "text-destructive",
172
+ className,
173
+ )}
174
+ {...props}
175
+ />
176
+ );
177
+ }
178
+
179
+ /** Group-level description, wired to the fieldset via aria-describedby. */
180
+ function FieldsetHelper({ className, ...props }: React.ComponentProps<"p">) {
181
+ const { helperId, invalid, registerHelper } = useFieldsetContext();
182
+
183
+ React.useEffect(() => {
184
+ registerHelper(true);
185
+ return () => registerHelper(false);
186
+ }, [registerHelper]);
187
+
188
+ return (
189
+ <p
190
+ data-slot="fieldset-helper"
191
+ id={helperId}
192
+ // Hidden when invalid so the error (below) is the single announced
193
+ // description, matching Field's helper/error handoff.
194
+ className={cn(
195
+ "-mt-1 text-sm text-muted-foreground",
196
+ invalid && "hidden",
197
+ className,
198
+ )}
199
+ {...props}
200
+ />
201
+ );
202
+ }
203
+
204
+ /** Group-level error. Renders only when the Fieldset is invalid and has content. */
205
+ function FieldsetError({
206
+ className,
207
+ children,
208
+ ...props
209
+ }: React.ComponentProps<"p">) {
210
+ const { errorId, invalid, registerError } = useFieldsetContext();
211
+ const shown = invalid && !!children;
212
+
213
+ React.useEffect(() => {
214
+ registerError(shown);
215
+ return () => registerError(false);
216
+ }, [registerError, shown]);
217
+
218
+ if (!shown) return null;
219
+ return (
220
+ <p
221
+ data-slot="fieldset-error"
222
+ id={errorId}
223
+ role="alert"
224
+ className={cn("text-sm font-medium text-destructive", className)}
225
+ {...props}
226
+ >
227
+ {children}
228
+ </p>
229
+ );
230
+ }
231
+
232
+ export {
233
+ Fieldset,
234
+ FieldsetLegend,
235
+ FieldsetHelper,
236
+ FieldsetError,
237
+ fieldsetVariants,
238
+ };
@@ -21,9 +21,11 @@ export * from "./command";
21
21
  export * from "./context-menu";
22
22
  export * from "./dialog";
23
23
  export * from "./dropdown-menu";
24
+ export * from "./fieldset";
24
25
  export * from "./file-upload";
25
26
  export * from "./hover-card";
26
27
  export * from "./input";
28
+ export * from "./input-group";
27
29
  export * from "./kbd";
28
30
  export * from "./label";
29
31
  export * from "./menubar";
@@ -59,3 +61,4 @@ export * from "./toggle-group";
59
61
  export * from "./toolbar";
60
62
  export * from "./tooltip";
61
63
  export * from "./tree-view";
64
+ export * from "./editable";