sv5ui 1.5.1 → 1.7.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 (60) hide show
  1. package/dist/Calendar/Calendar.svelte +48 -6
  2. package/dist/Calendar/calendar.types.d.ts +19 -0
  3. package/dist/Calendar/calendar.variants.js +2 -1
  4. package/dist/Carousel/Carousel.svelte +279 -0
  5. package/dist/Carousel/Carousel.svelte.d.ts +26 -0
  6. package/dist/Carousel/carousel.types.d.ts +242 -0
  7. package/dist/Carousel/carousel.types.js +1 -0
  8. package/dist/Carousel/carousel.variants.d.ts +408 -0
  9. package/dist/Carousel/carousel.variants.js +88 -0
  10. package/dist/Carousel/index.d.ts +2 -0
  11. package/dist/Carousel/index.js +1 -0
  12. package/dist/Checkbox/Checkbox.svelte +8 -2
  13. package/dist/CheckboxGroup/CheckboxGroup.svelte +15 -2
  14. package/dist/FileUpload/FileUpload.svelte +81 -10
  15. package/dist/FileUpload/file-upload.types.d.ts +39 -0
  16. package/dist/FileUpload/index.d.ts +1 -1
  17. package/dist/Form/Form.svelte +203 -0
  18. package/dist/Form/Form.svelte.d.ts +26 -0
  19. package/dist/Form/form.context.svelte.d.ts +64 -0
  20. package/dist/Form/form.context.svelte.js +478 -0
  21. package/dist/Form/form.types.d.ts +164 -0
  22. package/dist/Form/form.types.js +12 -0
  23. package/dist/Form/form.variants.d.ts +39 -0
  24. package/dist/Form/form.variants.js +17 -0
  25. package/dist/Form/index.d.ts +4 -0
  26. package/dist/Form/index.js +6 -0
  27. package/dist/Form/validate-schema.d.ts +13 -0
  28. package/dist/Form/validate-schema.js +113 -0
  29. package/dist/FormField/FormField.svelte +71 -8
  30. package/dist/FormField/form-field.types.d.ts +15 -0
  31. package/dist/Input/Input.svelte +31 -5
  32. package/dist/Input/Input.svelte.d.ts +25 -4
  33. package/dist/Input/input.types.d.ts +24 -3
  34. package/dist/Modal/Modal.svelte +14 -3
  35. package/dist/Modal/modal.types.d.ts +15 -4
  36. package/dist/Modal/modal.variants.d.ts +110 -20
  37. package/dist/Modal/modal.variants.js +27 -9
  38. package/dist/PinInput/PinInput.svelte +27 -6
  39. package/dist/PinInput/pin-input.types.d.ts +11 -0
  40. package/dist/RadioGroup/RadioGroup.svelte +17 -3
  41. package/dist/Select/Select.svelte +100 -19
  42. package/dist/Select/select.types.d.ts +44 -2
  43. package/dist/SelectMenu/SelectMenu.svelte +215 -23
  44. package/dist/SelectMenu/select-menu.types.d.ts +62 -1
  45. package/dist/SelectMenu/select-menu.variants.d.ts +26 -0
  46. package/dist/SelectMenu/select-menu.variants.js +34 -6
  47. package/dist/Slideover/Slideover.svelte +13 -2
  48. package/dist/Slideover/slideover.types.d.ts +14 -3
  49. package/dist/Slideover/slideover.variants.d.ts +85 -5
  50. package/dist/Slideover/slideover.variants.js +42 -12
  51. package/dist/Slider/Slider.svelte +4 -1
  52. package/dist/Switch/Switch.svelte +8 -2
  53. package/dist/Textarea/Textarea.svelte +27 -1
  54. package/dist/hooks/index.d.ts +1 -1
  55. package/dist/hooks/index.js +1 -1
  56. package/dist/hooks/useFormField.svelte.d.ts +64 -0
  57. package/dist/hooks/useFormField.svelte.js +70 -1
  58. package/dist/index.d.ts +2 -0
  59. package/dist/index.js +2 -0
  60. package/package.json +31 -3
@@ -0,0 +1,88 @@
1
+ import { tv } from 'tailwind-variants';
2
+ export const carouselVariants = tv({
3
+ slots: {
4
+ root: 'relative',
5
+ viewport: 'overflow-hidden',
6
+ container: 'flex',
7
+ slide: 'shrink-0 grow-0 basis-[calc(100%/var(--sv-slides))]',
8
+ arrow: 'absolute z-10 shadow-md',
9
+ arrowPrev: '',
10
+ arrowNext: '',
11
+ dots: 'flex items-center justify-center gap-2',
12
+ dot: [
13
+ 'rounded-full bg-on-surface/30 transition-all',
14
+ 'hover:bg-on-surface/50',
15
+ 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2',
16
+ 'data-[selected]:bg-primary'
17
+ ]
18
+ },
19
+ variants: {
20
+ orientation: {
21
+ horizontal: {
22
+ viewport: 'w-full',
23
+ container: 'flex-row touch-pan-y',
24
+ slide: 'min-w-0 h-auto',
25
+ dots: 'flex-row mt-4',
26
+ arrowPrev: 'left-2 top-1/2 -translate-y-1/2',
27
+ arrowNext: 'right-2 top-1/2 -translate-y-1/2'
28
+ },
29
+ vertical: {
30
+ root: 'h-full',
31
+ viewport: 'h-full w-full',
32
+ container: 'flex-col h-full touch-pan-x',
33
+ slide: 'min-h-0 w-auto',
34
+ dots: 'flex-col absolute right-2 top-1/2 -translate-y-1/2',
35
+ arrowPrev: 'top-2 left-1/2 -translate-x-1/2',
36
+ arrowNext: 'bottom-2 left-1/2 -translate-x-1/2'
37
+ }
38
+ },
39
+ size: {
40
+ xs: { dot: 'size-1.5' },
41
+ sm: { dot: 'size-2' },
42
+ md: { dot: 'size-2.5' },
43
+ lg: { dot: 'size-3' },
44
+ xl: { dot: 'size-3.5' }
45
+ },
46
+ color: {
47
+ primary: { dot: 'data-[selected]:bg-primary focus-visible:outline-primary' },
48
+ secondary: { dot: 'data-[selected]:bg-secondary focus-visible:outline-secondary' },
49
+ tertiary: { dot: 'data-[selected]:bg-tertiary focus-visible:outline-tertiary' },
50
+ success: { dot: 'data-[selected]:bg-success focus-visible:outline-success' },
51
+ warning: { dot: 'data-[selected]:bg-warning focus-visible:outline-warning' },
52
+ error: { dot: 'data-[selected]:bg-error focus-visible:outline-error' },
53
+ info: { dot: 'data-[selected]:bg-info focus-visible:outline-info' },
54
+ surface: {
55
+ dot: 'data-[selected]:bg-on-surface focus-visible:outline-on-surface'
56
+ }
57
+ },
58
+ variant: {
59
+ solid: '',
60
+ outline: '',
61
+ soft: '',
62
+ subtle: '',
63
+ ghost: ''
64
+ }
65
+ },
66
+ compoundVariants: [
67
+ { orientation: 'horizontal', size: 'xs', class: { dot: 'data-[selected]:w-4' } },
68
+ { orientation: 'horizontal', size: 'sm', class: { dot: 'data-[selected]:w-5' } },
69
+ { orientation: 'horizontal', size: 'md', class: { dot: 'data-[selected]:w-6' } },
70
+ { orientation: 'horizontal', size: 'lg', class: { dot: 'data-[selected]:w-7' } },
71
+ { orientation: 'horizontal', size: 'xl', class: { dot: 'data-[selected]:w-8' } },
72
+ { orientation: 'vertical', size: 'xs', class: { dot: 'data-[selected]:h-4' } },
73
+ { orientation: 'vertical', size: 'sm', class: { dot: 'data-[selected]:h-5' } },
74
+ { orientation: 'vertical', size: 'md', class: { dot: 'data-[selected]:h-6' } },
75
+ { orientation: 'vertical', size: 'lg', class: { dot: 'data-[selected]:h-7' } },
76
+ { orientation: 'vertical', size: 'xl', class: { dot: 'data-[selected]:h-8' } }
77
+ ],
78
+ defaultVariants: {
79
+ orientation: 'horizontal',
80
+ size: 'md',
81
+ color: 'primary',
82
+ variant: 'soft'
83
+ }
84
+ });
85
+ export const carouselDefaults = {
86
+ defaultVariants: carouselVariants.defaultVariants,
87
+ slots: {}
88
+ };
@@ -0,0 +1,2 @@
1
+ export { default as Carousel } from './Carousel.svelte';
2
+ export type { CarouselProps, CarouselApi, CarouselAutoplayOptions, CarouselSlideSlotProps, CarouselDotSlotProps, CarouselArrowSlotProps } from './carousel.types.js';
@@ -0,0 +1 @@
1
+ export { default as Carousel } from './Carousel.svelte';
@@ -9,7 +9,7 @@
9
9
  import { checkboxVariants, checkboxDefaults } from './checkbox.variants.js'
10
10
  import { getComponentConfig, iconsDefaults } from '../config.js'
11
11
  import Icon from '../Icon/Icon.svelte'
12
- import { useFormField } from '../hooks/useFormField.svelte.js'
12
+ import { useFormField, useFormFieldEmit } from '../hooks/useFormField.svelte.js'
13
13
 
14
14
  const config = getComponentConfig('checkbox', checkboxDefaults)
15
15
  const icons = getComponentConfig('icons', iconsDefaults)
@@ -43,6 +43,7 @@
43
43
  }: Props = $props()
44
44
 
45
45
  const formFieldContext = useFormField()
46
+ const emit = useFormFieldEmit()
46
47
 
47
48
  const hasError = $derived(
48
49
  formFieldContext?.error !== undefined && formFieldContext?.error !== false
@@ -107,9 +108,14 @@
107
108
  <div bind:this={containerRef} class={classes.container}>
108
109
  <Checkbox.Root
109
110
  bind:checked
110
- {onCheckedChange}
111
+ onCheckedChange={(val) => {
112
+ emit.onChange()
113
+ onCheckedChange?.(val)
114
+ }}
111
115
  bind:indeterminate
112
116
  {onIndeterminateChange}
117
+ onblur={() => emit.onBlur()}
118
+ onfocus={() => emit.onFocus()}
113
119
  id={resolvedId}
114
120
  name={resolvedName}
115
121
  {value}
@@ -9,7 +9,7 @@
9
9
  import { checkboxGroupVariants, checkboxGroupDefaults } from './checkbox-group.variants.js'
10
10
  import { getComponentConfig, iconsDefaults } from '../config.js'
11
11
  import Icon from '../Icon/Icon.svelte'
12
- import { useFormField } from '../hooks/useFormField.svelte.js'
12
+ import { useFormField, useFormFieldEmit } from '../hooks/useFormField.svelte.js'
13
13
  import type { CheckboxGroupItem } from './checkbox-group.types.js'
14
14
 
15
15
  const config = getComponentConfig('checkboxGroup', checkboxGroupDefaults)
@@ -42,6 +42,7 @@
42
42
  }: Props = $props()
43
43
 
44
44
  const formFieldContext = useFormField()
45
+ const emit = useFormFieldEmit()
45
46
 
46
47
  const hasError = $derived(
47
48
  formFieldContext?.error !== undefined && formFieldContext?.error !== false
@@ -97,6 +98,7 @@
97
98
  } else {
98
99
  value = value.filter((v) => v !== itemValue)
99
100
  }
101
+ emit.onChange()
100
102
  onValueChange?.(value)
101
103
  }
102
104
 
@@ -169,7 +171,18 @@
169
171
  {/snippet}
170
172
 
171
173
  <div {...restProps} bind:this={ref} class={layoutClasses.root}>
172
- <fieldset class={layoutClasses.fieldset} aria-describedby={ariaDescribedBy}>
174
+ <fieldset
175
+ class={layoutClasses.fieldset}
176
+ aria-describedby={ariaDescribedBy}
177
+ onfocusin={() => emit.onFocus()}
178
+ onfocusout={(e) => {
179
+ // Only emit blur when focus leaves the fieldset entirely, not when
180
+ // moving between checkboxes within the group.
181
+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
182
+ emit.onBlur()
183
+ }
184
+ }}
185
+ >
173
186
  {#if legend || legendSlot}
174
187
  {#if legendSlot}
175
188
  {@render legendSlot({ legend })}
@@ -1,5 +1,5 @@
1
1
  <script lang="ts" module>
2
- import type { FileUploadProps } from './file-upload.types.js'
2
+ import type { FileUploadProps, FileUploadRejection } from './file-upload.types.js'
3
3
 
4
4
  export type Props = FileUploadProps
5
5
  </script>
@@ -12,6 +12,7 @@
12
12
  import Icon from '../Icon/Icon.svelte'
13
13
  import Button from '../Button/Button.svelte'
14
14
  import Modal from '../Modal/Modal.svelte'
15
+ import { useFormField, useFormFieldEmit } from '../hooks/useFormField.svelte.js'
15
16
 
16
17
  const config = getComponentConfig('fileUpload', fileUploadDefaults)
17
18
  const icons = getComponentConfig('icons', iconsDefaults)
@@ -22,6 +23,9 @@
22
23
  onValueChange,
23
24
  multiple = false,
24
25
  accept,
26
+ maxSize,
27
+ maxFiles,
28
+ onReject,
25
29
  dropzone = true,
26
30
  interactive = true,
27
31
  label = 'Drop files here or click to upload',
@@ -39,6 +43,7 @@
39
43
  required = false,
40
44
  fileIcon = icons.file,
41
45
  imagePreview = true,
46
+ id,
42
47
  name,
43
48
  leadingSlot,
44
49
  labelSlot,
@@ -59,6 +64,9 @@
59
64
  let previewOpen = $state(false)
60
65
  let previewFile = $state<File | null>(null)
61
66
 
67
+ const formFieldContext = useFormField()
68
+ const emit = useFormFieldEmit()
69
+
62
70
  // Stable file identity key with separator to avoid collisions
63
71
  const fileKey = (f: File) => `${f.name}:${f.size}:${f.lastModified}`
64
72
 
@@ -67,8 +75,23 @@
67
75
  // eslint-disable-next-line svelte/prefer-svelte-reactivity
68
76
  const urlCache = new Map<string, string>()
69
77
 
78
+ const hasError = $derived(
79
+ formFieldContext?.error !== undefined && formFieldContext?.error !== false
80
+ )
81
+ const resolvedHighlight = $derived(highlight || hasError)
82
+ const resolvedId = $derived(id ?? formFieldContext?.ariaId)
83
+ const resolvedName = $derived(name ?? formFieldContext?.name)
84
+ const ariaDescribedBy = $derived(
85
+ !formFieldContext
86
+ ? undefined
87
+ : hasError
88
+ ? `${formFieldContext.ariaId}-error`
89
+ : `${formFieldContext.ariaId}-description ${formFieldContext.ariaId}-help`
90
+ )
91
+
70
92
  const isDisabled = $derived(disabled || loading)
71
93
  const isDragging = $derived(dragCounter > 0)
94
+ const isFull = $derived(maxFiles !== undefined && value.length >= maxFiles)
72
95
  const showFilesInside = $derived(
73
96
  layout === 'grid' && !multiple && value.length > 0 && preview && variant === 'area'
74
97
  )
@@ -76,13 +99,13 @@
76
99
  // Pass booleans directly so compound variants with `false` values match correctly
77
100
  const slots = $derived(
78
101
  fileUploadVariants({
79
- color,
102
+ color: hasError ? 'error' : color,
80
103
  size,
81
104
  variant,
82
105
  layout,
83
106
  dropzone,
84
107
  interactive: interactive && !isDisabled,
85
- highlight,
108
+ highlight: resolvedHighlight,
86
109
  multiple,
87
110
  disabled: isDisabled
88
111
  })
@@ -150,17 +173,53 @@
150
173
  })
151
174
  }
152
175
 
176
+ function validateIngress(file: File): FileUploadRejection['reason'] | null {
177
+ if (accept && !isFileAccepted(file)) return 'accept'
178
+ if (maxSize !== undefined && file.size > maxSize) return 'maxSize'
179
+ return null
180
+ }
181
+
182
+ function applyMaxFiles(candidates: File[]): {
183
+ accepted: File[]
184
+ rejected: FileUploadRejection[]
185
+ } {
186
+ if (maxFiles === undefined) return { accepted: candidates, rejected: [] }
187
+ const remaining = Math.max(0, maxFiles - value.length)
188
+ if (candidates.length <= remaining) return { accepted: candidates, rejected: [] }
189
+ return {
190
+ accepted: candidates.slice(0, remaining),
191
+ rejected: candidates.slice(remaining).map((file) => ({ file, reason: 'maxFiles' }))
192
+ }
193
+ }
194
+
153
195
  function addFiles(newFiles: File[]) {
154
196
  if (isDisabled) return
155
- const filtered = accept ? newFiles.filter(isFileAccepted) : newFiles
156
- if (!filtered.length) return
197
+
198
+ const rejected: FileUploadRejection[] = []
199
+ const passed: File[] = []
200
+ for (const file of newFiles) {
201
+ const reason = validateIngress(file)
202
+ if (reason) rejected.push({ file, reason })
203
+ else passed.push(file)
204
+ }
205
+
206
+ let accepted: File[]
157
207
  if (!multiple) {
158
- value = [filtered[0]]
208
+ accepted = passed.slice(0, 1)
159
209
  } else {
160
210
  const existing = new Set(value.map(fileKey))
161
- value = [...value, ...filtered.filter((f) => !existing.has(fileKey(f)))]
211
+ const deduped = passed.filter((f) => !existing.has(fileKey(f)))
212
+ const result = applyMaxFiles(deduped)
213
+ accepted = result.accepted
214
+ rejected.push(...result.rejected)
162
215
  }
163
- onValueChange?.(value)
216
+
217
+ if (accepted.length) {
218
+ value = multiple ? [...value, ...accepted] : accepted
219
+ onValueChange?.(value)
220
+ emit.onChange()
221
+ }
222
+ if (rejected.length) onReject?.(rejected)
164
223
  }
165
224
 
166
225
  function removeFile(index: number) {
@@ -176,6 +235,7 @@
176
235
  }
177
236
  value = value.filter((_, i) => i !== index)
178
237
  onValueChange?.(value)
238
+ emit.onChange()
179
239
  }
180
240
 
181
241
  export function clearAll() {
@@ -185,6 +245,7 @@
185
245
  urlCache.clear()
186
246
  value = []
187
247
  onValueChange?.(value)
248
+ emit.onChange()
188
249
  }
189
250
 
190
251
  function handleInputChange(e: Event) {
@@ -254,13 +315,13 @@
254
315
  }
255
316
  </script>
256
317
 
257
- <div {...restProps} bind:this={ref} class={classes.root}>
318
+ <div {...restProps} bind:this={ref} class={classes.root} data-full={isFull ? '' : undefined}>
258
319
  <!-- Hidden file input — uses auto-generated id internally -->
259
320
  <input
260
321
  bind:this={inputRef}
261
322
  type="file"
262
323
  id={autoId}
263
- {name}
324
+ name={resolvedName}
264
325
  {accept}
265
326
  {multiple}
266
327
  {required}
@@ -275,18 +336,23 @@
275
336
  <!-- Area / Dropzone -->
276
337
  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
277
338
  <div
339
+ id={resolvedId}
278
340
  class={classes.base}
279
341
  data-dragging={isDragging ? '' : undefined}
280
342
  role={interactive ? 'button' : undefined}
281
343
  tabindex={interactive && !isDisabled ? 0 : undefined}
282
344
  aria-disabled={isDisabled || undefined}
283
345
  aria-label={interactive ? label : undefined}
346
+ aria-invalid={resolvedHighlight ? true : undefined}
347
+ aria-describedby={ariaDescribedBy}
284
348
  onclick={handleAreaClick}
285
349
  ondragenter={handleDragEnter}
286
350
  ondragover={handleDragOver}
287
351
  ondragleave={handleDragLeave}
288
352
  ondrop={handleDrop}
289
353
  onkeydown={handleKeydown}
354
+ onfocus={() => emit.onFocus()}
355
+ onblur={() => emit.onBlur()}
290
356
  >
291
357
  {#if showFilesInside}
292
358
  <!-- Grid single: file fills the area as overlay -->
@@ -390,6 +456,7 @@
390
456
  {:else}
391
457
  <!-- Button variant -->
392
458
  <Button
459
+ id={resolvedId}
393
460
  {color}
394
461
  {size}
395
462
  disabled={isDisabled}
@@ -397,7 +464,11 @@
397
464
  {loadingIcon}
398
465
  leadingIcon={loading ? undefined : icon}
399
466
  {label}
467
+ aria-invalid={resolvedHighlight ? true : undefined}
468
+ aria-describedby={ariaDescribedBy}
400
469
  onclick={handleAreaClick}
470
+ onfocus={() => emit.onFocus()}
471
+ onblur={() => emit.onBlur()}
401
472
  />
402
473
  {/if}
403
474
 
@@ -2,6 +2,21 @@ import type { Snippet } from 'svelte';
2
2
  import type { HTMLAttributes } from 'svelte/elements';
3
3
  import type { ClassNameValue } from 'tailwind-merge';
4
4
  import type { FileUploadVariantProps, FileUploadSlots } from './file-upload.variants.js';
5
+ /**
6
+ * Reason a file was rejected by FileUpload.
7
+ *
8
+ * - `accept`: file did not match the `accept` MIME/extension filter
9
+ * - `maxSize`: file exceeded the `maxSize` byte limit
10
+ * - `maxFiles`: file would have pushed the selection past `maxFiles`
11
+ */
12
+ export type FileUploadRejectionReason = 'accept' | 'maxSize' | 'maxFiles';
13
+ /**
14
+ * A single rejected file along with the reason it was rejected.
15
+ */
16
+ export interface FileUploadRejection {
17
+ file: File;
18
+ reason: FileUploadRejectionReason;
19
+ }
5
20
  export type FileUploadProps = Omit<HTMLAttributes<HTMLElement>, 'class' | 'children'> & {
6
21
  /**
7
22
  * Bindable reference to the root DOM element.
@@ -25,6 +40,30 @@ export type FileUploadProps = Omit<HTMLAttributes<HTMLElement>, 'class' | 'child
25
40
  * Accepted file types as MIME types or extensions (e.g. "image/*,.pdf").
26
41
  */
27
42
  accept?: string;
43
+ /**
44
+ * Maximum allowed size per file, in bytes. Files exceeding this are
45
+ * rejected and reported through `onReject`.
46
+ *
47
+ * @example
48
+ * ```svelte
49
+ * <FileUpload maxSize={5 * 1024 * 1024} /> <!-- 5 MB -->
50
+ * ```
51
+ */
52
+ maxSize?: number;
53
+ /**
54
+ * Maximum number of files that can be selected. When the current
55
+ * selection plus the incoming files would exceed this, the excess
56
+ * files are rejected and reported through `onReject`. The root element
57
+ * exposes a `data-full` attribute when the limit is reached, so the
58
+ * upload area can be styled accordingly.
59
+ */
60
+ maxFiles?: number;
61
+ /**
62
+ * Called when one or more incoming files are rejected by `accept`,
63
+ * `maxSize`, or `maxFiles`. Receives the full rejection list for a
64
+ * single user action (one drop or one input change).
65
+ */
66
+ onReject?: (rejected: FileUploadRejection[]) => void;
28
67
  /**
29
68
  * Enable drag-and-drop file upload.
30
69
  * @default true
@@ -1,2 +1,2 @@
1
1
  export { default as FileUpload } from './FileUpload.svelte';
2
- export type { FileUploadProps } from './file-upload.types.js';
2
+ export type { FileUploadProps, FileUploadRejection, FileUploadRejectionReason } from './file-upload.types.js';
@@ -0,0 +1,203 @@
1
+ <script lang="ts" module>
2
+ import type { FormProps, FormSchema } from './form.types.js'
3
+
4
+ export type Props<
5
+ S extends FormSchema | undefined = FormSchema | undefined,
6
+ T extends boolean = true,
7
+ N extends boolean = false
8
+ > = FormProps<S, T, N>
9
+ </script>
10
+
11
+ <script
12
+ lang="ts"
13
+ generics="S extends FormSchema | undefined = FormSchema | undefined, T extends boolean = true, N extends boolean = false"
14
+ >
15
+ import { setContext, onMount, onDestroy, untrack } from 'svelte'
16
+ import type { HTMLAttributes } from 'svelte/elements'
17
+ import { formVariants, formDefaults } from './form.variants.js'
18
+ import { FormContext, FORM_CONTEXT_KEY, getFormContext } from './form.context.svelte.js'
19
+ import { getComponentConfig } from '../config.js'
20
+ import type { FormApi, FormErrorWithId } from './form.types.js'
21
+
22
+ const config = getComponentConfig('form', formDefaults)
23
+
24
+ let {
25
+ ref = $bindable(null),
26
+ api = $bindable<FormApi<unknown> | undefined>(),
27
+ id,
28
+ schema,
29
+ state = $bindable({} as never),
30
+ validate: customValidate,
31
+ validateOn = ['input', 'blur', 'change'],
32
+ validateOnInputDelay = 300,
33
+ disabled = false,
34
+ loadingAuto = true,
35
+ transform = true as T,
36
+ nested = false as N,
37
+ name,
38
+ onsubmit,
39
+ onerror,
40
+ class: className,
41
+ ui,
42
+ children,
43
+ ...restProps
44
+ }: Props<S, T, N> = $props()
45
+
46
+ // Generate a stable form id. Both `id` and `nested` are effectively init-only
47
+ // (they should not change over a form instance's lifetime), so `untrack`
48
+ // silences Svelte's state_referenced_locally warning.
49
+ const formId: string | number = untrack(
50
+ () =>
51
+ (id as string | number | undefined) ??
52
+ (typeof crypto !== 'undefined' && 'randomUUID' in crypto
53
+ ? crypto.randomUUID()
54
+ : `sv5ui-form-${Math.random().toString(36).slice(2)}`)
55
+ )
56
+
57
+ // Parent context captured once at init — `nested` is effectively immutable
58
+ // over a form instance's lifetime. We warn (dev-only) if it's mutated later.
59
+ const parentCtx = untrack(() => (nested ? getFormContext() : undefined))
60
+ const initialNested = untrack(() => nested)
61
+ $effect(() => {
62
+ if (nested !== initialNested) {
63
+ // eslint-disable-next-line no-console
64
+ console.warn(
65
+ '[sv5ui Form] The `nested` prop was changed after mount. This is ' +
66
+ 'not supported — nested/standalone status is fixed at mount time. ' +
67
+ 'Unmount and remount the Form to toggle.'
68
+ )
69
+ }
70
+ })
71
+
72
+ // Create the reactive form context. All config is passed via getter closures
73
+ // so that reactive prop changes are visible inside the class.
74
+ const ctx = new FormContext(
75
+ {
76
+ getState: () => state as unknown,
77
+ getSchema: () => schema as FormSchema | undefined,
78
+ getCustomValidate: () =>
79
+ customValidate as
80
+ | ((s: unknown) => ReturnType<NonNullable<typeof customValidate>>)
81
+ | undefined,
82
+ getValidateOn: () => validateOn,
83
+ getValidateOnInputDelay: () => validateOnInputDelay,
84
+ getDisabled: () => disabled,
85
+ getLoadingAuto: () => loadingAuto,
86
+ getTransform: () => transform,
87
+ getName: () => name as string | undefined,
88
+ getOnSubmit: () =>
89
+ onsubmit as
90
+ | ((
91
+ e: import('./form.types.js').FormSubmitEvent<unknown>
92
+ ) => void | Promise<void>)
93
+ | undefined,
94
+ getOnError: () => onerror
95
+ },
96
+ formId,
97
+ parentCtx
98
+ )
99
+
100
+ setContext(FORM_CONTEXT_KEY, ctx)
101
+
102
+ // Build the bindable API object. Getters ensure reactive state reads stay live.
103
+ const apiObject: FormApi<unknown> = {
104
+ validate: (opts) => ctx.validate(opts) as Promise<unknown | false>,
105
+ submit: () => ctx.submit(),
106
+ clear: (name) => ctx.clear(name),
107
+ getErrors: (name) => ctx.getErrors(name),
108
+ setErrors: (errs, name) => ctx.setErrors(errs, name),
109
+ reset: () => ctx.reset(),
110
+ get errors() {
111
+ return ctx.errors
112
+ },
113
+ get loading() {
114
+ return ctx.loading
115
+ },
116
+ get disabled() {
117
+ return ctx.disabled
118
+ },
119
+ get dirty() {
120
+ return ctx.dirty
121
+ },
122
+ get dirtyFields() {
123
+ return ctx.dirtyFields as ReadonlySet<string>
124
+ },
125
+ get touchedFields() {
126
+ return ctx.touchedFields as ReadonlySet<string>
127
+ },
128
+ get blurredFields() {
129
+ return ctx.blurredFields as ReadonlySet<string>
130
+ },
131
+ get submitCount() {
132
+ return ctx.submitCount
133
+ }
134
+ }
135
+
136
+ // Sync the api object to the bindable prop once at setup time. `apiObject`
137
+ // is a stable reference built from getters, so there's nothing reactive to
138
+ // track — direct assignment is sufficient.
139
+ api = apiObject as typeof api
140
+
141
+ // Nested form attach/detach lifecycle.
142
+ onMount(() => {
143
+ if (parentCtx && nested) {
144
+ parentCtx.attachChild(formId, {
145
+ formId,
146
+ name: name as string | undefined,
147
+ validate: (opts) => ctx.validate(opts) as Promise<unknown | false>,
148
+ clear: (n) => ctx.clear(n),
149
+ reset: () => ctx.reset(),
150
+ setErrors: (errs, n) => ctx.setErrors(errs, n)
151
+ })
152
+ }
153
+ })
154
+
155
+ onDestroy(() => {
156
+ if (parentCtx && nested) parentCtx.detachChild(formId)
157
+ ctx.dispose()
158
+ })
159
+
160
+ async function handleSubmit(event: SubmitEvent) {
161
+ event.preventDefault()
162
+ // Forward the real SubmitEvent so user handlers can read `submitter`,
163
+ // `target`, etc. When `api.submit()` is called programmatically, ctx.submit
164
+ // synthesizes a fresh event instead.
165
+ await ctx.submit(event)
166
+ }
167
+
168
+ // `formVariants` has no variants (only a single `root` slot), so its
169
+ // output is stable — compute once at setup rather than via $derived.
170
+ const variantSlots = formVariants()
171
+ const classes = $derived({
172
+ root: variantSlots.root({
173
+ class: [config.slots.root, className, ui?.root]
174
+ })
175
+ })
176
+
177
+ // Slot props for children
178
+ const slotProps = $derived({
179
+ errors: ctx.errors as FormErrorWithId[],
180
+ loading: ctx.loading
181
+ })
182
+ </script>
183
+
184
+ {#if nested}
185
+ <div
186
+ {...restProps as unknown as HTMLAttributes<HTMLDivElement>}
187
+ bind:this={ref}
188
+ id={typeof id === 'number' ? String(id) : id}
189
+ class={classes.root}
190
+ >
191
+ {@render children?.(slotProps)}
192
+ </div>
193
+ {:else}
194
+ <form
195
+ {...restProps}
196
+ bind:this={ref}
197
+ id={typeof id === 'number' ? String(id) : id}
198
+ class={classes.root}
199
+ onsubmit={handleSubmit}
200
+ >
201
+ {@render children?.(slotProps)}
202
+ </form>
203
+ {/if}
@@ -0,0 +1,26 @@
1
+ import type { FormProps, FormSchema } from './form.types.js';
2
+ export type Props<S extends FormSchema | undefined = FormSchema | undefined, T extends boolean = true, N extends boolean = false> = FormProps<S, T, N>;
3
+ declare function $$render<S extends FormSchema | undefined = FormSchema | undefined, T extends boolean = true, N extends boolean = false>(): {
4
+ props: Props<S, T, N>;
5
+ exports: {};
6
+ bindings: "ref" | "api" | "state";
7
+ slots: {};
8
+ events: {};
9
+ };
10
+ declare class __sveltets_Render<S extends FormSchema | undefined = FormSchema | undefined, T extends boolean = true, N extends boolean = false> {
11
+ props(): ReturnType<typeof $$render<S, T, N>>['props'];
12
+ events(): ReturnType<typeof $$render<S, T, N>>['events'];
13
+ slots(): ReturnType<typeof $$render<S, T, N>>['slots'];
14
+ bindings(): "ref" | "api" | "state";
15
+ exports(): {};
16
+ }
17
+ interface $$IsomorphicComponent {
18
+ new <S extends FormSchema | undefined = FormSchema | undefined, T extends boolean = true, N extends boolean = false>(options: import('svelte').ComponentConstructorOptions<ReturnType<__sveltets_Render<S, T, N>['props']>>): import('svelte').SvelteComponent<ReturnType<__sveltets_Render<S, T, N>['props']>, ReturnType<__sveltets_Render<S, T, N>['events']>, ReturnType<__sveltets_Render<S, T, N>['slots']>> & {
19
+ $$bindings?: ReturnType<__sveltets_Render<S, T, N>['bindings']>;
20
+ } & ReturnType<__sveltets_Render<S, T, N>['exports']>;
21
+ <S extends FormSchema | undefined = FormSchema | undefined, T extends boolean = true, N extends boolean = false>(internal: unknown, props: ReturnType<__sveltets_Render<S, T, N>['props']> & {}): ReturnType<__sveltets_Render<S, T, N>['exports']>;
22
+ z_$$bindings?: ReturnType<__sveltets_Render<any, any, any>['bindings']>;
23
+ }
24
+ declare const Form: $$IsomorphicComponent;
25
+ type Form<S extends FormSchema | undefined = FormSchema | undefined, T extends boolean = true, N extends boolean = false> = InstanceType<typeof Form<S, T, N>>;
26
+ export default Form;