@cognitap/radiant 0.0.66 → 0.0.68

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 (45) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/library/AppShell.d.ts +71 -0
  3. package/dist/library/AppShell.d.ts.map +1 -0
  4. package/dist/library/AppShell.js +189 -0
  5. package/dist/library/AppShell.js.map +1 -0
  6. package/dist/library/Form.d.ts +41 -0
  7. package/dist/library/Form.d.ts.map +1 -0
  8. package/dist/library/Form.js +171 -0
  9. package/dist/library/Form.js.map +1 -0
  10. package/dist/library/cn.d.ts.map +1 -1
  11. package/dist/library/cn.js +11 -0
  12. package/dist/library/cn.js.map +1 -1
  13. package/dist/library/index.d.ts +3 -0
  14. package/dist/library/index.d.ts.map +1 -1
  15. package/dist/library/index.js +2 -0
  16. package/dist/library/index.js.map +1 -1
  17. package/dist/library/motion/host.d.ts +2 -1
  18. package/dist/library/motion/host.d.ts.map +1 -1
  19. package/dist/library/motion/host.js.map +1 -1
  20. package/dist/library/motion/layoutHost.d.ts +5 -0
  21. package/dist/library/motion/layoutHost.d.ts.map +1 -0
  22. package/dist/library/motion/layoutHost.js +24 -0
  23. package/dist/library/motion/layoutHost.js.map +1 -0
  24. package/dist/library/motion/press.d.ts.map +1 -1
  25. package/dist/library/motion/press.js +6 -5
  26. package/dist/library/motion/press.js.map +1 -1
  27. package/dist/library/motion/react.d.ts.map +1 -1
  28. package/dist/library/motion/react.js +3 -1
  29. package/dist/library/motion/react.js.map +1 -1
  30. package/dist/library/styles.css +1 -1
  31. package/dist/library/themes/components.d.ts +25 -0
  32. package/dist/library/themes/components.d.ts.map +1 -1
  33. package/dist/library/themes/components.js +23 -0
  34. package/dist/library/themes/components.js.map +1 -1
  35. package/docs/architecture.md +15 -11
  36. package/package.json +1 -1
  37. package/src/AppShell.tsx +517 -0
  38. package/src/Form.tsx +260 -0
  39. package/src/cn.ts +11 -0
  40. package/src/index.ts +39 -0
  41. package/src/motion/host.ts +2 -1
  42. package/src/motion/layoutHost.ts +25 -0
  43. package/src/motion/press.ts +6 -5
  44. package/src/motion/react.ts +3 -1
  45. package/src/themes/components.ts +23 -0
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
@@ -9,7 +9,9 @@ const roleClasses = (prefix: string, leaf: string) =>
9
9
  export const cn: CnFunction = createCn({
10
10
  extend: {
11
11
  classGroups: {
12
+ 'border-w-e': ['border-e-(--rad-sidebar-border-width)'],
12
13
  'border-w-b': [
14
+ 'border-b-(--rad-app-shell-header-border-width)',
13
15
  'border-b-(--rad-code-block-border-width)',
14
16
  'border-b-(--rad-table-border-width)'
15
17
  ],
@@ -43,6 +45,7 @@ export const cn: CnFunction = createCn({
43
45
  'font-(--rad-tabs-font-weight)'
44
46
  ],
45
47
  'font-size': [
48
+ 'text-(--rad-sidebar-label-size)',
46
49
  'text-(--rad-inline-code-font-size)',
47
50
  'text-(--rad-code-block-font-size)',
48
51
  'text-(--rad-empty-state-title-size)',
@@ -83,6 +86,8 @@ export const cn: CnFunction = createCn({
83
86
  'h-(--rad-slider-length)'
84
87
  ],
85
88
  w: [
89
+ 'w-(--rad-sidebar-width)',
90
+ 'w-(--rad-sidebar-collapsed-width)',
86
91
  'w-(--rad-resizable-handle-size)',
87
92
  'w-(--rad-otp-field-slot-size)',
88
93
  'w-(--rad-drawer-size)',
@@ -113,6 +118,8 @@ export const cn: CnFunction = createCn({
113
118
  ],
114
119
  mb: ['mb-(--rad-multi-select-gap)', 'mb-(--rad-fieldset-gap)'],
115
120
  gap: [
121
+ 'gap-(--rad-form-gap)',
122
+ 'gap-(--rad-sidebar-gap)',
116
123
  'gap-(--rad-navigation-menu-gap)',
117
124
  'gap-(--rad-code-block-header-gap)',
118
125
  'gap-(--rad-empty-state-gap)',
@@ -141,6 +148,7 @@ export const cn: CnFunction = createCn({
141
148
  'gap-(--rad-tabs-list-gap)'
142
149
  ],
143
150
  'min-h': [
151
+ 'min-h-(--rad-app-shell-header-min-height)',
144
152
  'min-h-(--rad-native-select-height)',
145
153
  'min-h-(--rad-textarea-min-height)',
146
154
  'min-h-(--rad-tabs-trigger-height)'
@@ -169,6 +177,9 @@ export const cn: CnFunction = createCn({
169
177
  'px-(--rad-tabs-trigger-padding)'
170
178
  ],
171
179
  p: [
180
+ 'p-(--rad-app-shell-header-padding)',
181
+ 'p-(--rad-app-shell-main-padding)',
182
+ 'p-(--rad-sidebar-padding)',
172
183
  'p-(--rad-navigation-menu-padding)',
173
184
  'p-(--rad-code-block-padding)',
174
185
  'p-(--rad-code-block-header-padding)',
package/src/index.ts CHANGED
@@ -712,3 +712,42 @@ export type {
712
712
  NavigationMenuRenderProps,
713
713
  NavigationMenuLinkRenderProps
714
714
  } from './NavigationMenu.js'
715
+
716
+ export {
717
+ AppShell,
718
+ AppShellHeader,
719
+ AppShellMain,
720
+ AppShellSkipLink,
721
+ Sidebar,
722
+ SidebarTrigger,
723
+ SidebarLabel,
724
+ SidebarContent,
725
+ useAppShell,
726
+ useSidebar
727
+ } from './AppShell.js'
728
+ export type {
729
+ AppShellProps,
730
+ AppShellState,
731
+ AppShellHeaderProps,
732
+ AppShellMainProps,
733
+ AppShellSkipLinkProps,
734
+ AppShellRenderProps,
735
+ SidebarProps,
736
+ SidebarTriggerProps,
737
+ SidebarRenderProps,
738
+ SidebarLabelProps,
739
+ SidebarContentProps
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'
@@ -21,6 +21,7 @@ export interface MotionHostRuntime {
21
21
  disclosure?(node: HTMLElement, profile: MotionProfile): MotionHostBinding
22
22
  dialog?(node: HTMLElement, profile: MotionProfile): MotionHostBinding
23
23
  popup?(node: HTMLElement, profile: MotionProfile): MotionHostBinding
24
+ layout?(node: HTMLElement, profile: MotionProfile): MotionHostBinding
24
25
  indicator?(node: HTMLElement, profile: MotionProfile): MotionHostBinding
25
26
  }
26
27
  export const MotionHostContext = createContext<MotionHostRuntime | null>(null)
@@ -104,7 +105,7 @@ export function usePressHost<Node extends HTMLElement>(
104
105
 
105
106
  /** Shared lifecycle for native presentation adapters; no engine enters the root path. */
106
107
  export function useTransitionHost<Node extends HTMLElement>(
107
- kind: 'disclosure' | 'dialog' | 'popup' | 'indicator',
108
+ kind: 'disclosure' | 'dialog' | 'popup' | 'indicator' | 'layout',
108
109
  ref: Ref<Node> | undefined,
109
110
  disabled: boolean
110
111
  ) {
@@ -0,0 +1,25 @@
1
+ import { bindSpringLayout } from './layoutDom.js'
2
+ import { resolveMotion, type MotionProfile } from './config.js'
3
+ import type { MotionHostBinding } from './host.js'
4
+ /** The optional host bridge shares the public layout adapter and its property leases. */
5
+ export function bindLayoutMotion(node: HTMLElement, initial: MotionProfile): MotionHostBinding {
6
+ const view = node.ownerDocument.defaultView!,
7
+ query = view.matchMedia('(prefers-reduced-motion: reduce)')
8
+ let profile = initial
9
+ const controller = bindSpringLayout(node, resolveMotion(profile, 'layout', query.matches))
10
+ const sync = () => {
11
+ controller.configure(resolveMotion(profile, 'layout', query.matches))
12
+ controller.measure()
13
+ }
14
+ query.addEventListener('change', sync)
15
+ return {
16
+ update(next) {
17
+ profile = next
18
+ sync()
19
+ },
20
+ destroy() {
21
+ query.removeEventListener('change', sync)
22
+ controller.destroy()
23
+ }
24
+ }
25
+ }
@@ -9,7 +9,8 @@ export function bindPressMotion(
9
9
  initialProfile: MotionProfile
10
10
  ): MotionHostBinding {
11
11
  let profile = initialProfile
12
- const query = node.ownerDocument.defaultView!.matchMedia('(prefers-reduced-motion: reduce)')
12
+ const view = node.ownerDocument.defaultView!
13
+ const query = view.matchMedia('(prefers-reduced-motion: reduce)')
13
14
  const spring = createSpring(1, {
14
15
  ...resolveMotion(profile, 'press', query.matches),
15
16
  reducedValue: 1
@@ -43,7 +44,7 @@ export function bindPressMotion(
43
44
  }
44
45
  const changed = () => update(profile)
45
46
  query.addEventListener('change', changed)
46
- const observer = new MutationObserver(() => {
47
+ const observer = new view.MutationObserver(() => {
47
48
  if (blocked()) reset()
48
49
  })
49
50
  observer.observe(node, {
@@ -59,7 +60,7 @@ export function bindPressMotion(
59
60
  document.addEventListener('pointercancel', release)
60
61
  document.addEventListener('keyup', release)
61
62
  const blur = () => release()
62
- document.defaultView!.addEventListener('blur', blur)
63
+ view.addEventListener('blur', blur)
63
64
  return {
64
65
  update,
65
66
  press(event) {
@@ -78,7 +79,7 @@ export function bindPressMotion(
78
79
  pressed = { pointerId: event.pointerId }
79
80
  }
80
81
  const scale = Number(
81
- getComputedStyle(node).getPropertyValue('--rad-button-press-scale').trim() || '.97'
82
+ view.getComputedStyle(node).getPropertyValue('--rad-button-press-scale').trim() || '.97'
82
83
  )
83
84
  spring.to(Number.isFinite(scale) && scale >= 0.5 && scale <= 1 ? scale : 0.97)
84
85
  },
@@ -89,7 +90,7 @@ export function bindPressMotion(
89
90
  document.removeEventListener('pointerup', release)
90
91
  document.removeEventListener('pointercancel', release)
91
92
  document.removeEventListener('keyup', release)
92
- document.defaultView!.removeEventListener('blur', blur)
93
+ view.removeEventListener('blur', blur)
93
94
  spring.destroy()
94
95
  unbind()
95
96
  }
@@ -14,6 +14,7 @@ import { bindDisclosureMotion, bindDialogMotion } from './transitions.js'
14
14
  import { bindPressMotion } from './press.js'
15
15
  import { bindPopupMotion } from './popup.js'
16
16
  import { bindIndicatorMotion } from './indicator.js'
17
+ import { bindLayoutMotion } from './layoutHost.js'
17
18
  import { bindDrawerMotion } from './drawer.js'
18
19
  import { MotionProfileContext } from './context.js'
19
20
  import { resolveMotion, type MotionInteraction } from './config.js'
@@ -140,7 +141,8 @@ const hostRuntime = {
140
141
  disclosure: bindDisclosureMotion,
141
142
  dialog: bindDialogMotion,
142
143
  popup: bindPopupMotion,
143
- indicator: bindIndicatorMotion
144
+ indicator: bindIndicatorMotion,
145
+ layout: bindLayoutMotion
144
146
  }
145
147
  /** Opt into native Radiant spring interactions without adding a DOM wrapper. */
146
148
  export function MotionProvider({ children }: { children?: ReactNode }) {
@@ -73,6 +73,28 @@ export const componentRegistry = {
73
73
  color: 'css',
74
74
  shadow: 'css'
75
75
  },
76
+ appShell: {
77
+ background: 'css',
78
+ color: 'css',
79
+ headerBackground: 'css',
80
+ headerColor: 'css',
81
+ headerPadding: 'css',
82
+ headerMinHeight: 'css',
83
+ headerBorderColor: 'css',
84
+ headerBorderWidth: 'css',
85
+ mainPadding: 'css'
86
+ },
87
+ sidebar: {
88
+ width: 'css',
89
+ collapsedWidth: 'css',
90
+ background: 'css',
91
+ color: 'css',
92
+ padding: 'css',
93
+ gap: 'css',
94
+ borderColor: 'css',
95
+ borderWidth: 'css',
96
+ labelSize: 'css'
97
+ },
76
98
  resizable: {
77
99
  handleSize: 'css',
78
100
  handleColor: 'css',
@@ -140,6 +162,7 @@ export const componentRegistry = {
140
162
  shadow: 'css',
141
163
  gap: 'css'
142
164
  },
165
+ form: { gap: 'css' },
143
166
  buttonGroup: { radius: 'css' },
144
167
  otpField: { gap: 'css', slotSize: 'css' },
145
168
  tag: { gap: 'css' },