@cognitap/radiant 0.0.67 → 0.0.69

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/src/Form.tsx ADDED
@@ -0,0 +1,260 @@
1
+ 'use client'
2
+
3
+ import { createContext, useContext, useCallback, useEffect, useRef, useState } from 'react'
4
+ import type { ComponentProps, ReactNode } from 'react'
5
+ import { Field, type FieldProps } from './Field.js'
6
+ import { Alert, type AlertProps } from './Alert.js'
7
+ import { cn } from './cn.js'
8
+ import { joinIds } from './internal/ids.js'
9
+ import { useControllableState } from './react/useControllableState.js'
10
+ import type { StateOwner } from './react/useNativeOwner.js'
11
+ import { useComposedRefs } from './react/useComposedRefs.js'
12
+ import type { DistributiveOmit } from './internal/types.js'
13
+ import type { AccessibleName } from './internal/accessibleName.js'
14
+ import { requireAccessibleName } from './internal/accessibleName.js'
15
+ import type { ThemeStyle } from './themes/defineTheme.js'
16
+
17
+ export type FormErrors = { fields?: Record<string, string | undefined>; form?: string }
18
+ export type FormSubmitContext = {
19
+ form: HTMLFormElement
20
+ submitter: HTMLElement | null
21
+ signal: AbortSignal
22
+ }
23
+ export type FormState = {
24
+ errors: FormErrors
25
+ pending: boolean
26
+ focusInvalid: () => void
27
+ }
28
+ export type FormProps = Omit<ComponentProps<'form'>, 'children' | 'style' | 'noValidate'> &
29
+ StateOwner<'errors', FormErrors> &
30
+ AccessibleName & {
31
+ children?: ReactNode | ((state: Pick<FormState, 'errors' | 'pending'>) => ReactNode)
32
+ style?: ThemeStyle
33
+ 'data-slot'?: string
34
+ onErrorsChange?: (errors: FormErrors) => void
35
+ validate?: (data: FormData) => FormErrors | void
36
+ onSubmitValues?: (
37
+ data: FormData,
38
+ context: FormSubmitContext
39
+ ) => FormErrors | void | Promise<FormErrors | void>
40
+ submitErrorText?: string
41
+ }
42
+ const emptyErrors: FormErrors = {}
43
+ const FormContext = createContext<FormState | null>(null)
44
+ export function useForm(): FormState | null {
45
+ return useContext(FormContext)
46
+ }
47
+ function requiredForm() {
48
+ const state = useForm()
49
+ if (!state) throw new Error('Form parts must be inside Form.')
50
+ return state
51
+ }
52
+ function namedError(errors: FormErrors, name: string) {
53
+ const fields = errors.fields
54
+ return fields && Object.hasOwn(fields, name) ? fields[name] : undefined
55
+ }
56
+ function hasErrors(errors: FormErrors) {
57
+ return Boolean(errors.form || Object.values(errors.fields ?? {}).some(Boolean))
58
+ }
59
+ function eventName(target: EventTarget | null) {
60
+ return target && 'name' in target && typeof target.name === 'string' ? target.name : ''
61
+ }
62
+ function equalErrors(left: FormErrors, right: FormErrors) {
63
+ const entries = (errors: FormErrors) =>
64
+ Object.entries(errors.fields ?? {})
65
+ .filter(([, value]) => value)
66
+ .sort(([a], [b]) => a.localeCompare(b))
67
+ return (
68
+ (left.form || '') === (right.form || '') &&
69
+ JSON.stringify(entries(left)) === JSON.stringify(entries(right))
70
+ )
71
+ }
72
+ function controls(form: HTMLFormElement) {
73
+ return Array.from(form.elements).filter(
74
+ (element): element is HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement =>
75
+ /^(INPUT|SELECT|TEXTAREA)$/.test(element.tagName)
76
+ )
77
+ }
78
+ /** Native values stay in the browser or the application's form library. */
79
+ export function Form({
80
+ children,
81
+ errors: errorsProp,
82
+ defaultErrors,
83
+ onErrorsChange,
84
+ validate,
85
+ onSubmitValues,
86
+ submitErrorText = 'Unable to save. Try again.',
87
+ ref,
88
+ className,
89
+ onSubmit,
90
+ onReset,
91
+ onInput,
92
+ onChange,
93
+ ...props
94
+ }: FormProps) {
95
+ requireAccessibleName('Form', props)
96
+ const localRef = useRef<HTMLFormElement>(null)
97
+ const composedRef = useComposedRefs(localRef, ref)
98
+ const { value: errors, request: setErrors } = useControllableState({
99
+ name: 'Form errors',
100
+ value: errorsProp,
101
+ defaultValue: defaultErrors,
102
+ initialValue: emptyErrors,
103
+ onChange: onErrorsChange,
104
+ equal: equalErrors
105
+ })
106
+ const [pending, setPending] = useState(false)
107
+ const operation = useRef<AbortController | null>(null)
108
+ const revision = useRef(0)
109
+ useEffect(() => () => operation.current?.abort(), [])
110
+ const focusInvalid = useCallback(
111
+ (next: FormErrors = errors) => {
112
+ const form = localRef.current
113
+ if (!form) return
114
+ const target = controls(form).find(
115
+ control =>
116
+ !control.disabled &&
117
+ control.type !== 'hidden' &&
118
+ Boolean(
119
+ namedError(next, control.name) ||
120
+ (control.willValidate && !control.validity.valid) ||
121
+ control.getAttribute('aria-invalid') === 'true'
122
+ )
123
+ )
124
+ if (target) {
125
+ const field = target.closest('[data-slot~="field"]')
126
+ const replacement = field?.querySelector<HTMLElement>(
127
+ 'input:not([type="hidden"]):not([disabled]),textarea:not([disabled]),select:not([hidden]):not([disabled]),button[aria-haspopup]:not([disabled])'
128
+ )
129
+ ;(target.getClientRects().length ? target : replacement)?.focus()
130
+ } else if (next.form) form.querySelector<HTMLElement>('[data-slot~="form-error"]')?.focus()
131
+ },
132
+ [errors]
133
+ )
134
+ const state: FormState = { errors, pending, focusInvalid: () => focusInvalid() }
135
+ function edited(name: string) {
136
+ revision.current++
137
+ const old = errors
138
+ if (old.form || namedError(old, name)) {
139
+ const fields = { ...old.fields }
140
+ delete fields[name]
141
+ setErrors({ fields })
142
+ }
143
+ }
144
+ return (
145
+ <FormContext.Provider value={state}>
146
+ <form
147
+ {...props}
148
+ ref={composedRef}
149
+ noValidate
150
+ aria-busy={pending || props['aria-busy'] || undefined}
151
+ data-slot={joinIds('form', props['data-slot'])}
152
+ data-pending={pending ? '' : undefined}
153
+ data-invalid={hasErrors(errors) ? '' : undefined}
154
+ className={cn(
155
+ 'grid min-w-0 gap-[var(--rad-form-gap,var(--rad-spacing-group-gap,1rem))]',
156
+ className
157
+ )}
158
+ onInput={event => {
159
+ onInput?.(event)
160
+ edited(eventName(event.target))
161
+ }}
162
+ onChange={event => {
163
+ onChange?.(event)
164
+ edited(eventName(event.target))
165
+ }}
166
+ onReset={event => {
167
+ onReset?.(event)
168
+ if (event.defaultPrevented) return
169
+ operation.current?.abort()
170
+ operation.current = null
171
+ revision.current++
172
+ setPending(false)
173
+ setErrors(emptyErrors)
174
+ }}
175
+ onSubmit={event => {
176
+ if (operation.current) {
177
+ event.preventDefault()
178
+ return
179
+ }
180
+ onSubmit?.(event)
181
+ if (event.defaultPrevented) return
182
+ const form = event.currentTarget
183
+ const submitter = (event.nativeEvent as SubmitEvent).submitter
184
+ const data = new FormData(form, submitter)
185
+ const nativeErrors: Record<string, string> = Object.create(null)
186
+ let unnamedError: string | undefined
187
+ if (!(submitter as HTMLButtonElement | null)?.formNoValidate) {
188
+ for (const control of controls(form)) {
189
+ if (control.willValidate && !control.validity.valid) {
190
+ if (control.name) nativeErrors[control.name] ??= control.validationMessage
191
+ else unnamedError ??= control.validationMessage
192
+ }
193
+ }
194
+ }
195
+ const custom = validate?.(data) ?? emptyErrors
196
+ const next = {
197
+ form: custom.form || unnamedError,
198
+ fields: { ...custom.fields, ...nativeErrors }
199
+ }
200
+ setErrors(next)
201
+ if (hasErrors(next)) {
202
+ event.preventDefault()
203
+ form.ownerDocument.defaultView?.requestAnimationFrame(() => focusInvalid(next))
204
+ return
205
+ }
206
+ if (!onSubmitValues) return
207
+ event.preventDefault()
208
+ const controller = new AbortController()
209
+ operation.current = controller
210
+ const submittedRevision = revision.current
211
+ setPending(true)
212
+ void Promise.resolve()
213
+ .then(() => onSubmitValues(data, { form, submitter, signal: controller.signal }))
214
+ .catch(() => ({ form: submitErrorText }))
215
+ .then(result => {
216
+ if (controller.signal.aborted || submittedRevision !== revision.current) return
217
+ const next = result ?? emptyErrors
218
+ setErrors(next)
219
+ if (hasErrors(next))
220
+ form.ownerDocument.defaultView?.requestAnimationFrame(() => focusInvalid(next))
221
+ })
222
+ .finally(() => {
223
+ if (operation.current !== controller) return
224
+ operation.current = null
225
+ if (!controller.signal.aborted) setPending(false)
226
+ })
227
+ }}
228
+ >
229
+ {typeof children === 'function' ? children({ errors, pending }) : children}
230
+ </form>
231
+ </FormContext.Provider>
232
+ )
233
+ }
234
+ export type FormFieldProps = DistributiveOmit<FieldProps, 'name'> & { name: string }
235
+ /** Name matches the real input's name; Field retains label and error relationships. */
236
+ export function FormField({ name, error, ...props }: FormFieldProps) {
237
+ const { errors } = requiredForm()
238
+ return (
239
+ <Field
240
+ {...props}
241
+ error={error ?? namedError(errors, name)}
242
+ data-slot={joinIds('form-field', props['data-slot'])}
243
+ />
244
+ )
245
+ }
246
+ export type FormErrorProps = Omit<AlertProps, 'children' | 'tabIndex'>
247
+ export function FormError(props: FormErrorProps) {
248
+ const { errors } = requiredForm()
249
+ return errors.form ? (
250
+ <Alert
251
+ {...props}
252
+ tone={props.tone ?? 'danger'}
253
+ announce={props.announce ?? 'assertive'}
254
+ tabIndex={-1}
255
+ data-slot={joinIds('form-error', props['data-slot'])}
256
+ >
257
+ {errors.form}
258
+ </Alert>
259
+ ) : null
260
+ }
package/src/cn.ts CHANGED
@@ -118,6 +118,9 @@ export const cn: CnFunction = createCn({
118
118
  ],
119
119
  mb: ['mb-(--rad-multi-select-gap)', 'mb-(--rad-fieldset-gap)'],
120
120
  gap: [
121
+ 'gap-(--rad-carousel-gap)',
122
+ 'gap-(--rad-carousel-slide-gap)',
123
+ 'gap-(--rad-form-gap)',
121
124
  'gap-(--rad-sidebar-gap)',
122
125
  'gap-(--rad-navigation-menu-gap)',
123
126
  'gap-(--rad-code-block-header-gap)',
@@ -198,6 +201,7 @@ export const cn: CnFunction = createCn({
198
201
  'p-(--rad-tabs-content-padding)'
199
202
  ],
200
203
  rounded: [
204
+ 'rounded-(--rad-carousel-radius)',
201
205
  'rounded-(--rad-navigation-menu-radius)',
202
206
  'rounded-(--rad-code-block-radius)',
203
207
  'rounded-(--rad-inline-code-radius)',
package/src/index.ts CHANGED
@@ -738,3 +738,32 @@ export type {
738
738
  SidebarLabelProps,
739
739
  SidebarContentProps
740
740
  } from './AppShell.js'
741
+
742
+ export {
743
+ Form,
744
+ FormField,
745
+ FormError,
746
+ useForm,
747
+ type FormProps,
748
+ type FormFieldProps,
749
+ type FormErrorProps,
750
+ type FormErrors,
751
+ type FormState,
752
+ type FormSubmitContext
753
+ } from './Form.js'
754
+
755
+ export {
756
+ Carousel,
757
+ CarouselViewport,
758
+ CarouselPrevious,
759
+ CarouselNext,
760
+ CarouselIndicators,
761
+ CarouselAutoPlay,
762
+ useCarousel,
763
+ type CarouselProps,
764
+ type CarouselItem,
765
+ type CarouselState,
766
+ type CarouselViewportProps,
767
+ type CarouselActionProps,
768
+ type CarouselIndicatorsProps
769
+ } from './Carousel.js'
@@ -162,6 +162,8 @@ export const componentRegistry = {
162
162
  shadow: 'css',
163
163
  gap: 'css'
164
164
  },
165
+ form: { gap: 'css' },
166
+ carousel: { gap: 'css', slideGap: 'css', radius: 'css' },
165
167
  buttonGroup: { radius: 'css' },
166
168
  otpField: { gap: 'css', slotSize: 'css' },
167
169
  tag: { gap: 'css' },