@m3ui-vue/m3ui-vue 1.6.2 → 1.8.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 (191) hide show
  1. package/dist/API.md +1224 -28
  2. package/dist/{MColorPickerModal-NtkihoK6.js → MColorPickerModal-H8nuX0Wu.js} +3 -4
  3. package/dist/{MColorPickerModal-NtkihoK6.js.map → MColorPickerModal-H8nuX0Wu.js.map} +1 -1
  4. package/dist/MDialog-B42Mhn8W.js +331 -0
  5. package/dist/MDialog-B42Mhn8W.js.map +1 -0
  6. package/dist/{MListItem-D2cNUyzP.js → MListItem-DiOAxaN7.js} +431 -325
  7. package/dist/MListItem-DiOAxaN7.js.map +1 -0
  8. package/dist/{MLoadingIndicator-DWUj0BAB.js → MLoadingIndicator-CuTZYFFj.js} +2 -2
  9. package/dist/{MLoadingIndicator-DWUj0BAB.js.map → MLoadingIndicator-CuTZYFFj.js.map} +1 -1
  10. package/dist/{MSeekBar-C4cn9RIF.js → MSeekBar-BCDQTx2t.js} +2 -2
  11. package/dist/{MSeekBar-C4cn9RIF.js.map → MSeekBar-BCDQTx2t.js.map} +1 -1
  12. package/dist/MSegmentedButton-BXzRsg1S.js +105 -0
  13. package/dist/MSegmentedButton-BXzRsg1S.js.map +1 -0
  14. package/dist/MSignaturePad-BTqGaPXA.js +313 -0
  15. package/dist/MSignaturePad-BTqGaPXA.js.map +1 -0
  16. package/dist/MSlider-D_O8J9YH.js +739 -0
  17. package/dist/MSlider-D_O8J9YH.js.map +1 -0
  18. package/dist/{MSpinner-DZkXZJpc.js → MSpinner-UCdtSOHP.js} +2 -2
  19. package/dist/{MSpinner-DZkXZJpc.js.map → MSpinner-UCdtSOHP.js.map} +1 -1
  20. package/dist/{MTextField-CNH-byir.js → MTextField-CYk9yFvi.js} +162 -115
  21. package/dist/MTextField-CYk9yFvi.js.map +1 -0
  22. package/dist/_useFieldValidation-B0B44M_t.js +191 -0
  23. package/dist/_useFieldValidation-B0B44M_t.js.map +1 -0
  24. package/dist/api.json +1 -1
  25. package/dist/code-editor.js +184 -103
  26. package/dist/code-editor.js.map +1 -1
  27. package/dist/components/MAddressField.vue.d.ts +18 -3
  28. package/dist/components/MAppBarWithSearch.vue.d.ts +1 -1
  29. package/dist/components/MAudioRecorder.vue.d.ts +2 -2
  30. package/dist/components/MAutocomplete.vue.d.ts +22 -3
  31. package/dist/components/MCheckbox.vue.d.ts +23 -1
  32. package/dist/components/MCodeEditor.vue.d.ts +23 -1
  33. package/dist/components/MColorPicker.vue.d.ts +24 -3
  34. package/dist/components/MConfirmDialog.vue.d.ts +2 -2
  35. package/dist/components/MCountrySelect.vue.d.ts +13 -2
  36. package/dist/components/MCreditCardInput.vue.d.ts +33 -0
  37. package/dist/components/MCronField.vue.d.ts +23 -1
  38. package/dist/components/MDataTable.vue.d.ts +1 -1
  39. package/dist/components/MDatePicker.vue.d.ts +24 -3
  40. package/dist/components/MDateRangePicker.vue.d.ts +24 -3
  41. package/dist/components/MFileUpload.vue.d.ts +23 -2
  42. package/dist/components/MForm.vue.d.ts +61 -0
  43. package/dist/components/MFormBuilder.vue.d.ts +22 -0
  44. package/dist/components/MFormRenderer.vue.d.ts +151 -0
  45. package/dist/components/MJsonEditor.vue.d.ts +23 -1
  46. package/dist/components/MMapRoute.vue.d.ts +176 -0
  47. package/dist/components/MMaskField.vue.d.ts +20 -2
  48. package/dist/components/MMentionField.vue.d.ts +13 -2
  49. package/dist/components/MMultiAutocomplete.vue.d.ts +22 -3
  50. package/dist/components/MMultiSelect.vue.d.ts +22 -3
  51. package/dist/components/MNavigationRail.vue.d.ts +1 -1
  52. package/dist/components/MNotificationCenter.vue.d.ts +2 -2
  53. package/dist/components/MNumberField.vue.d.ts +20 -2
  54. package/dist/components/MPdfSigner.vue.d.ts +499 -0
  55. package/dist/components/MPdfViewer.vue.d.ts +12 -0
  56. package/dist/components/MPhoneInput.vue.d.ts +19 -4
  57. package/dist/components/MPinInput.vue.d.ts +24 -3
  58. package/dist/components/MPosKeypad.vue.d.ts +3 -3
  59. package/dist/components/MRadioGroup.vue.d.ts +23 -1
  60. package/dist/components/MRating.vue.d.ts +23 -1
  61. package/dist/components/MRichTextEditor.vue.d.ts +23 -1
  62. package/dist/components/MSearchBar.vue.d.ts +1 -1
  63. package/dist/components/MSegmentedButton.vue.d.ts +23 -2
  64. package/dist/components/MSelect.vue.d.ts +22 -3
  65. package/dist/components/MSignaturePad.vue.d.ts +19 -0
  66. package/dist/components/MSlider.vue.d.ts +23 -1
  67. package/dist/components/MSpreadsheet.vue.d.ts +137 -0
  68. package/dist/components/MStack.vue.d.ts +1 -1
  69. package/dist/components/MSwitch.vue.d.ts +23 -1
  70. package/dist/components/MTable.vue.d.ts +1 -1
  71. package/dist/components/MTagInput.vue.d.ts +20 -2
  72. package/dist/components/MText.vue.d.ts +1 -1
  73. package/dist/components/MTextField.vue.d.ts +26 -3
  74. package/dist/components/MTimePicker.vue.d.ts +24 -3
  75. package/dist/components/MTimezoneSelect.vue.d.ts +13 -2
  76. package/dist/components/MTour.vue.d.ts +2 -2
  77. package/dist/components/MTrackingTimeline.vue.d.ts +75 -0
  78. package/dist/components/MWindow.vue.d.ts +2 -2
  79. package/dist/composables/_routeGeometry.d.ts +26 -0
  80. package/dist/composables/_useFieldValidation.d.ts +91 -0
  81. package/dist/composables/mapRouting.d.ts +35 -0
  82. package/dist/composables/pdfSign.d.ts +52 -0
  83. package/dist/composables/spreadsheetFormula.d.ts +55 -0
  84. package/dist/composables/useLocale.d.ts +177 -0
  85. package/dist/composables/validation.d.ts +82 -0
  86. package/dist/draw.js +2 -2
  87. package/dist/flow.js +1 -1
  88. package/dist/gantt.js +2 -2
  89. package/dist/index.d.ts +12 -0
  90. package/dist/locales/index.js +693 -7
  91. package/dist/locales/index.js.map +1 -1
  92. package/dist/m3ui-vue.css +1 -1
  93. package/dist/m3ui.js +15507 -12417
  94. package/dist/m3ui.js.map +1 -1
  95. package/dist/map.d.ts +4 -0
  96. package/dist/map.js +1207 -745
  97. package/dist/map.js.map +1 -1
  98. package/dist/media.js +4 -4
  99. package/dist/pdf.d.ts +3 -0
  100. package/dist/pdf.js +1228 -687
  101. package/dist/pdf.js.map +1 -1
  102. package/dist/rich-text-editor.js +188 -146
  103. package/dist/rich-text-editor.js.map +1 -1
  104. package/dist/styles.css +1 -1
  105. package/dist/{useLocale-DaVSTdm0.js → useLocale-DL96OFgr.js} +99 -1
  106. package/dist/useLocale-DL96OFgr.js.map +1 -0
  107. package/package.json +5 -1
  108. package/src/__tests__/MForm.test.ts +325 -0
  109. package/src/__tests__/MFormRenderer.test.ts +157 -0
  110. package/src/__tests__/MMapRoute.test.ts +418 -0
  111. package/src/__tests__/MPdfSigner.test.ts +175 -0
  112. package/src/__tests__/MPhoneInput.test.ts +5 -2
  113. package/src/__tests__/MRichTextEditor.test.ts +2 -1
  114. package/src/__tests__/MSpreadsheet.test.ts +223 -0
  115. package/src/__tests__/MTrackingTimeline.test.ts +66 -0
  116. package/src/__tests__/_fakeMaplibre.ts +4 -1
  117. package/src/__tests__/_osrmRoutes.ts +10 -0
  118. package/src/__tests__/attrsFallthrough.test.ts +11 -0
  119. package/src/__tests__/fieldsValidation.test.ts +229 -0
  120. package/src/__tests__/spreadsheetFormula.test.ts +77 -0
  121. package/src/__tests__/ssr.test.ts +4 -0
  122. package/src/__tests__/validation.test.ts +77 -0
  123. package/src/components/MAddressField.vue +45 -8
  124. package/src/components/MAutocomplete.vue +69 -23
  125. package/src/components/MCheckbox.vue +80 -17
  126. package/src/components/MCodeEditor.vue +59 -2
  127. package/src/components/MColorPicker.vue +65 -16
  128. package/src/components/MCountrySelect.vue +17 -3
  129. package/src/components/MCreditCardInput.vue +76 -7
  130. package/src/components/MCronField.vue +60 -10
  131. package/src/components/MDatePicker.vue +65 -16
  132. package/src/components/MDateRangePicker.vue +66 -16
  133. package/src/components/MFileUpload.vue +71 -8
  134. package/src/components/MForm.vue +208 -0
  135. package/src/components/MFormBuilder.vue +417 -0
  136. package/src/components/MFormRenderer.vue +324 -0
  137. package/src/components/MJsonEditor.vue +57 -3
  138. package/src/components/MMapRoute.vue +523 -0
  139. package/src/components/MMaskField.vue +55 -13
  140. package/src/components/MMentionField.vue +17 -2
  141. package/src/components/MMultiAutocomplete.vue +70 -23
  142. package/src/components/MMultiSelect.vue +70 -23
  143. package/src/components/MNumberField.vue +58 -16
  144. package/src/components/MPdfSigner.vue +433 -0
  145. package/src/components/MPdfViewer.vue +12 -0
  146. package/src/components/MPhoneInput.vue +60 -18
  147. package/src/components/MPinInput.vue +58 -10
  148. package/src/components/MRadioGroup.vue +65 -4
  149. package/src/components/MRating.vue +62 -6
  150. package/src/components/MRichTextEditor.vue +64 -4
  151. package/src/components/MSegmentedButton.vue +59 -2
  152. package/src/components/MSelect.vue +72 -26
  153. package/src/components/MSignaturePad.vue +71 -6
  154. package/src/components/MSlider.vue +61 -10
  155. package/src/components/MSpreadsheet.vue +992 -0
  156. package/src/components/MSwitch.vue +63 -8
  157. package/src/components/MTagInput.vue +67 -25
  158. package/src/components/MTextField.vue +68 -14
  159. package/src/components/MTimePicker.vue +65 -16
  160. package/src/components/MTimezoneSelect.vue +17 -3
  161. package/src/components/MTrackingTimeline.vue +257 -0
  162. package/src/composables/_routeGeometry.ts +140 -0
  163. package/src/composables/_useFieldValidation.ts +287 -0
  164. package/src/composables/mapRouting.ts +55 -0
  165. package/src/composables/pdfSign.ts +141 -0
  166. package/src/composables/spreadsheetFormula.ts +459 -0
  167. package/src/composables/useLocale.ts +277 -0
  168. package/src/composables/validation.ts +178 -0
  169. package/src/index.ts +12 -0
  170. package/src/locales/de.ts +98 -0
  171. package/src/locales/es.ts +105 -7
  172. package/src/locales/fr.ts +98 -0
  173. package/src/locales/ja.ts +98 -0
  174. package/src/locales/ko.ts +98 -0
  175. package/src/locales/pt.ts +98 -0
  176. package/src/locales/zh.ts +98 -0
  177. package/src/map.ts +4 -0
  178. package/src/pdf.ts +3 -0
  179. package/dist/MButton-OQ4wIERQ.js +0 -171
  180. package/dist/MButton-OQ4wIERQ.js.map +0 -1
  181. package/dist/MDialog-DYMnaBlt.js +0 -167
  182. package/dist/MDialog-DYMnaBlt.js.map +0 -1
  183. package/dist/MListItem-D2cNUyzP.js.map +0 -1
  184. package/dist/MProgressBar-BWly1UKN.js +0 -179
  185. package/dist/MProgressBar-BWly1UKN.js.map +0 -1
  186. package/dist/MSegmentedButton-BEB4gXLA.js +0 -64
  187. package/dist/MSegmentedButton-BEB4gXLA.js.map +0 -1
  188. package/dist/MSlider-BIkA6DiE.js +0 -690
  189. package/dist/MSlider-BIkA6DiE.js.map +0 -1
  190. package/dist/MTextField-CNH-byir.js.map +0 -1
  191. package/dist/useLocale-DaVSTdm0.js.map +0 -1
@@ -5,6 +5,8 @@
5
5
  * @event update:modelValue Emitted with the picked date.
6
6
  */
7
7
  import { computed, onUnmounted, ref, watch } from 'vue'
8
+ import { useFieldValidation, useFocusLeave } from '../composables/_useFieldValidation'
9
+ import type { ValidateOn, ValidationRule } from '../composables/validation'
8
10
  import MIcon from './MIcon.vue'
9
11
  import MIconButton from './MIconButton.vue'
10
12
  import MMonthYearButton from './_MMonthYearButton.vue'
@@ -34,10 +36,23 @@ const props = defineProps<{
34
36
  yearRange?: [number, number]
35
37
  /** Disables the picker */
36
38
  disabled?: boolean
37
- /** Error state */
38
- error?: boolean
39
+ /** Error state. A string is also the message (`:error="errors.x"`) */
40
+ error?: boolean | string
39
41
  /** Error message shown when error is true */
40
42
  errorLabel?: string
43
+ /** Marks as required — adds a red asterisk after the label; inside an `MForm` or with `rules`, also validates it */
44
+ required?: boolean
45
+ /**
46
+ * Validation rules: functions `(value, ctx) => true | 'message'` (may be async; see the built-in `required`,
47
+ * `email`, `minLength`…) or a Standard Schema (zod, valibot…). Checked in order; the first failure is shown
48
+ */
49
+ rules?: ValidationRule | ValidationRule[]
50
+ /** When the rules are checked and shown: on leaving the field (default; live after that), while typing, or only on submit (`MForm`) */
51
+ validateOn?: ValidateOn
52
+ /** Wait this long (ms) after the value stops changing before re-checking (one request for an async rule, not one per key). Defaults to its `MForm`'s */
53
+ validateDebounce?: number
54
+ /** The key of this field in its `MForm`'s values, errors and schema */
55
+ name?: string
41
56
  /** Hint text below the field */
42
57
  hint?: string
43
58
  /**
@@ -60,7 +75,26 @@ const localeStrings = useLocale()
60
75
  // to a hardcoded 'es-ES' regardless of what locale the app actually provided.
61
76
  const resolvedLocale = computed(() => props.locale ?? localeStrings.lang)
62
77
 
63
- const emit = defineEmits<{ 'update:modelValue': [string | null] }>()
78
+ const emit = defineEmits<{ blur: []; 'update:modelValue': [string | null] }>()
79
+
80
+ const rootEl = ref<HTMLElement | null>(null)
81
+ const validation = useFieldValidation({
82
+ value: () => props.modelValue,
83
+ rules: () => props.rules,
84
+ required: () => props.required,
85
+ error: () => props.error,
86
+ errorLabel: () => props.errorLabel,
87
+ name: () => props.name,
88
+ validateOn: () => props.validateOn,
89
+ validateDebounce: () => props.validateDebounce,
90
+ disabled: () => props.disabled,
91
+ focus: () => { triggerEl.value?.querySelector('button')?.focus() },
92
+ el: () => triggerEl.value,
93
+ setValue: (v) => emit('update:modelValue', v as string | null),
94
+ })
95
+ /** Its own `disabled` or its MForm's */
96
+ const isDisabled = validation.disabled
97
+ const { hasError, message: errorMessage, messageId } = validation
64
98
 
65
99
  const open = ref(false)
66
100
  const triggerEl = ref<HTMLElement | null>(null)
@@ -165,26 +199,41 @@ watch(open, (v) => {
165
199
  onUnmounted(() => {
166
200
  document.removeEventListener('mousedown', onClickOutside)
167
201
  })
202
+
203
+ defineExpose({
204
+ /** Checks its rules and shows the result; resolves to whether they pass */
205
+ validate: validation.validate,
206
+ /** Hides its validation error (until the next check) */
207
+ resetValidation: validation.resetValidation,
208
+ })
209
+
210
+ // Last: it watches `open`, declared above
211
+ const onFocusOut = useFocusLeave(() => rootEl.value, () => {
212
+ validation.onBlur()
213
+ emit('blur')
214
+ }, () => open.value)
168
215
  </script>
169
216
 
170
217
  <template>
171
- <div class="flex flex-col gap-1">
218
+ <div ref="rootEl" class="flex flex-col gap-1" @focusout="onFocusOut">
172
219
  <!-- Trigger -->
173
220
  <div ref="triggerEl" class="relative mt-2" :style="{ '--field-bg': resolvedFieldBg }">
174
221
  <button
222
+ :aria-invalid="hasError || undefined"
223
+ :aria-describedby="errorMessage || hint ? messageId : undefined"
175
224
  type="button"
176
225
  class="flex h-14 w-full items-center gap-2 rounded-xs border bg-transparent px-4 text-left text-body-large transition-[border-color,border-width] duration-150"
177
226
  :class="[
178
- disabled ? 'pointer-events-none cursor-not-allowed border-on-surface/12' : 'cursor-pointer',
179
- !disabled && (open
180
- ? error ? 'border-2 border-error' : 'border-2 border-primary'
181
- : error ? 'border-error' : 'border-outline hover:border-on-surface'),
227
+ isDisabled ? 'pointer-events-none cursor-not-allowed border-on-surface/12' : 'cursor-pointer',
228
+ !isDisabled && (open
229
+ ? hasError ? 'border-2 border-error' : 'border-2 border-primary'
230
+ : hasError ? 'border-error' : 'border-outline hover:border-on-surface'),
182
231
  ]"
183
- @click="!disabled && (open = !open)"
232
+ @click="!isDisabled && (open = !open)"
184
233
  >
185
- <MIcon name="calendar_today" :size="24" class="shrink-0" :class="disabled ? 'text-on-surface/38' : 'text-on-surface-variant'" />
186
- <span v-overflow-title v-if="displayValue" class="min-w-0 truncate flex-1" :class="disabled ? 'text-on-surface/38' : 'text-on-surface'">{{ displayValue }}</span>
187
- <span v-overflow-title v-else class="min-w-0 truncate flex-1" :class="disabled ? 'text-on-surface/38' : 'text-on-surface-variant'">{{ placeholder || label || localeStrings.selectDate }}</span>
234
+ <MIcon name="calendar_today" :size="24" class="shrink-0" :class="isDisabled ? 'text-on-surface/38' : 'text-on-surface-variant'" />
235
+ <span v-overflow-title v-if="displayValue" class="min-w-0 truncate flex-1" :class="isDisabled ? 'text-on-surface/38' : 'text-on-surface'">{{ displayValue }}</span>
236
+ <span v-overflow-title v-else class="min-w-0 truncate flex-1" :class="isDisabled ? 'text-on-surface/38' : 'text-on-surface-variant'">{{ placeholder || label || localeStrings.selectDate }}</span>
188
237
  <MIcon
189
238
  v-if="modelValue"
190
239
  name="close"
@@ -195,14 +244,14 @@ onUnmounted(() => {
195
244
  </button>
196
245
  <label
197
246
  v-if="label"
198
- :class="[OUTLINED_FLOATED_LABEL, 'transition-colors', disabled ? 'text-on-surface/38' : open ? (error ? 'text-error' : 'text-primary') : error ? 'text-error' : 'text-on-surface-variant']"
247
+ :class="[OUTLINED_FLOATED_LABEL, 'transition-colors', isDisabled ? 'text-on-surface/38' : open ? (hasError ? 'text-error' : 'text-primary') : hasError ? 'text-error' : 'text-on-surface-variant']"
199
248
  >
200
- {{ label }}
249
+ {{ label }}<span v-if="required" class="text-error">&nbsp;*</span>
201
250
  </label>
202
251
  </div>
203
252
 
204
- <p v-if="error && errorLabel" class="px-4 text-body-small text-error">{{ errorLabel }}</p>
205
- <p v-else-if="hint" class="px-4 text-body-small text-on-surface-variant">{{ hint }}</p>
253
+ <p v-if="errorMessage" :id="messageId" role="alert" class="px-4 text-body-small text-error">{{ errorMessage }}</p>
254
+ <p v-else-if="hint" :id="messageId" class="px-4 text-body-small text-on-surface-variant">{{ hint }}</p>
206
255
 
207
256
  <!-- Calendar dropdown -->
208
257
  <Teleport to="body">
@@ -5,6 +5,8 @@
5
5
  * @event update:modelValue Emitted with the picked range.
6
6
  */
7
7
  import { computed, onUnmounted, ref, watch } from 'vue'
8
+ import { useFieldValidation, useFocusLeave } from '../composables/_useFieldValidation'
9
+ import type { ValidateOn, ValidationRule } from '../composables/validation'
8
10
  import MIcon from './MIcon.vue'
9
11
  import MIconButton from './MIconButton.vue'
10
12
  import MMonthYearButton from './_MMonthYearButton.vue'
@@ -39,10 +41,23 @@ const props = defineProps<{
39
41
  yearRange?: [number, number]
40
42
  /** Disables the picker */
41
43
  disabled?: boolean
42
- /** Error state */
43
- error?: boolean
44
+ /** Error state. A string is also the message (`:error="errors.x"`) */
45
+ error?: boolean | string
44
46
  /** Error message shown when error is true */
45
47
  errorLabel?: string
48
+ /** Marks as required — adds a red asterisk after the label; inside an `MForm` or with `rules`, also validates it */
49
+ required?: boolean
50
+ /**
51
+ * Validation rules: functions `(value, ctx) => true | 'message'` (may be async; see the built-in `required`,
52
+ * `email`, `minLength`…) or a Standard Schema (zod, valibot…). Checked in order; the first failure is shown
53
+ */
54
+ rules?: ValidationRule | ValidationRule[]
55
+ /** When the rules are checked and shown: on leaving the field (default; live after that), while typing, or only on submit (`MForm`) */
56
+ validateOn?: ValidateOn
57
+ /** Wait this long (ms) after the value stops changing before re-checking (one request for an async rule, not one per key). Defaults to its `MForm`'s */
58
+ validateDebounce?: number
59
+ /** The key of this field in its `MForm`'s values, errors and schema */
60
+ name?: string
46
61
  /** Hint text below the field */
47
62
  hint?: string
48
63
  /**
@@ -69,7 +84,27 @@ const localeStrings = useLocale()
69
84
  // to a hardcoded 'es-ES' regardless of what locale the app actually provided.
70
85
  const resolvedLocale = computed(() => props.locale ?? localeStrings.lang)
71
86
 
72
- const emit = defineEmits<{ 'update:modelValue': [DateRange] }>()
87
+ const emit = defineEmits<{ blur: []; 'update:modelValue': [DateRange] }>()
88
+
89
+ const rootEl = ref<HTMLElement | null>(null)
90
+ const validation = useFieldValidation({
91
+ value: () => props.modelValue,
92
+ rules: () => props.rules,
93
+ required: () => props.required,
94
+ error: () => props.error,
95
+ errorLabel: () => props.errorLabel,
96
+ name: () => props.name,
97
+ validateOn: () => props.validateOn,
98
+ validateDebounce: () => props.validateDebounce,
99
+ disabled: () => props.disabled,
100
+ focus: () => { triggerEl.value?.querySelector('button')?.focus() },
101
+ el: () => triggerEl.value,
102
+ setValue: (v) => emit('update:modelValue', v as DateRange),
103
+ isEmpty: (v) => !(v as DateRange | null)?.start || !(v as DateRange | null)?.end,
104
+ })
105
+ /** Its own `disabled` or its MForm's */
106
+ const isDisabled = validation.disabled
107
+ const { hasError, message: errorMessage, messageId } = validation
73
108
 
74
109
  const open = ref(false)
75
110
  const triggerEl = ref<HTMLElement | null>(null)
@@ -201,25 +236,40 @@ watch(open, (v) => {
201
236
  onUnmounted(() => {
202
237
  document.removeEventListener('mousedown', onOut)
203
238
  })
239
+
240
+ defineExpose({
241
+ /** Checks its rules and shows the result; resolves to whether they pass */
242
+ validate: validation.validate,
243
+ /** Hides its validation error (until the next check) */
244
+ resetValidation: validation.resetValidation,
245
+ })
246
+
247
+ // Last: it watches `open`, declared above
248
+ const onFocusOut = useFocusLeave(() => rootEl.value, () => {
249
+ validation.onBlur()
250
+ emit('blur')
251
+ }, () => open.value)
204
252
  </script>
205
253
 
206
254
  <template>
207
- <div class="flex flex-col gap-1">
255
+ <div ref="rootEl" class="flex flex-col gap-1" @focusout="onFocusOut">
208
256
  <div ref="triggerEl" class="relative mt-2" :style="{ '--field-bg': resolvedFieldBg }">
209
257
  <button
258
+ :aria-invalid="hasError || undefined"
259
+ :aria-describedby="errorMessage || hint ? messageId : undefined"
210
260
  type="button"
211
261
  class="flex h-14 w-full items-center gap-2 rounded-xs border bg-transparent px-4 text-left text-body-large transition-[border-color,border-width] duration-150"
212
262
  :class="[
213
- disabled ? 'pointer-events-none cursor-not-allowed border-on-surface/12' : 'cursor-pointer',
214
- !disabled && (open
215
- ? error ? 'border-2 border-error' : 'border-2 border-primary'
216
- : error ? 'border-error' : 'border-outline hover:border-on-surface'),
263
+ isDisabled ? 'pointer-events-none cursor-not-allowed border-on-surface/12' : 'cursor-pointer',
264
+ !isDisabled && (open
265
+ ? hasError ? 'border-2 border-error' : 'border-2 border-primary'
266
+ : hasError ? 'border-error' : 'border-outline hover:border-on-surface'),
217
267
  ]"
218
- @click="!disabled && (open = !open)"
268
+ @click="!isDisabled && (open = !open)"
219
269
  >
220
- <MIcon name="date_range" :size="24" class="shrink-0" :class="disabled ? 'text-on-surface/38' : 'text-on-surface-variant'" />
221
- <span v-overflow-title v-if="displayValue" class="min-w-0 truncate flex-1" :class="disabled ? 'text-on-surface/38' : 'text-on-surface'">{{ displayValue }}</span>
222
- <span v-overflow-title v-else class="min-w-0 truncate flex-1" :class="disabled ? 'text-on-surface/38' : 'text-on-surface-variant'">{{ label || placeholder || localeStrings.selectRange }}</span>
270
+ <MIcon name="date_range" :size="24" class="shrink-0" :class="isDisabled ? 'text-on-surface/38' : 'text-on-surface-variant'" />
271
+ <span v-overflow-title v-if="displayValue" class="min-w-0 truncate flex-1" :class="isDisabled ? 'text-on-surface/38' : 'text-on-surface'">{{ displayValue }}</span>
272
+ <span v-overflow-title v-else class="min-w-0 truncate flex-1" :class="isDisabled ? 'text-on-surface/38' : 'text-on-surface-variant'">{{ label || placeholder || localeStrings.selectRange }}</span>
223
273
  <MIcon
224
274
  v-if="modelValue.start || modelValue.end"
225
275
  name="close"
@@ -230,14 +280,14 @@ onUnmounted(() => {
230
280
  </button>
231
281
  <label
232
282
  v-if="label"
233
- :class="[OUTLINED_FLOATED_LABEL, 'transition-colors', disabled ? 'text-on-surface/38' : open ? (error ? 'text-error' : 'text-primary') : error ? 'text-error' : 'text-on-surface-variant']"
283
+ :class="[OUTLINED_FLOATED_LABEL, 'transition-colors', isDisabled ? 'text-on-surface/38' : open ? (hasError ? 'text-error' : 'text-primary') : hasError ? 'text-error' : 'text-on-surface-variant']"
234
284
  >
235
- {{ label }}
285
+ {{ label }}<span v-if="required" class="text-error">&nbsp;*</span>
236
286
  </label>
237
287
  </div>
238
288
 
239
- <p v-if="error && errorLabel" class="px-4 text-body-small text-error">{{ errorLabel }}</p>
240
- <p v-else-if="hint" class="px-4 text-body-small text-on-surface-variant">{{ hint }}</p>
289
+ <p v-if="errorMessage" :id="messageId" role="alert" class="px-4 text-body-small text-error">{{ errorMessage }}</p>
290
+ <p v-else-if="hint" :id="messageId" class="px-4 text-body-small text-on-surface-variant">{{ hint }}</p>
241
291
 
242
292
  <Teleport to="body">
243
293
  <Transition
@@ -9,8 +9,11 @@
9
9
  * @event update:modelValue Emitted with the new list whenever files are added, removed or cleared (v-model)
10
10
  * @event select Emitted with the newly accepted files whenever files are added (drop or picker)
11
11
  * @event remove Emitted when a file is removed from the list with its remove button
12
+ * @event blur Emitted when focus leaves the drop zone
12
13
  */
13
14
  import { ref, computed, reactive, watch, onBeforeUnmount } from 'vue'
15
+ import { useFieldValidation, useFocusLeave } from '../composables/_useFieldValidation'
16
+ import type { ValidateOn, ValidationRule } from '../composables/validation'
14
17
  import MIcon from './MIcon.vue'
15
18
  import MIconButton from './MIconButton.vue'
16
19
  import MSpinner from './MSpinner.vue'
@@ -46,6 +49,20 @@ const props = withDefaults(
46
49
  removeLabel?: string
47
50
  /** Optional v-model. Bind it to own the list: clear it, or update each entry's status/progress. Unbound, the component keeps the list itself. */
48
51
  modelValue?: UploadFile[]
52
+ /** Error state. A string is also the message */
53
+ error?: boolean | string
54
+ /** Error message shown when `error` is true */
55
+ errorLabel?: string
56
+ /** Inside an `MForm` or with `rules`, at least one file must be chosen */
57
+ required?: boolean
58
+ /** Validation rules on the file list (functions or a Standard Schema); `minLength`/`maxLength` count files. See `MForm` */
59
+ rules?: ValidationRule | ValidationRule[]
60
+ /** When the rules are checked and shown: on leaving it (default), on change, or only on submit */
61
+ validateOn?: ValidateOn
62
+ /** Wait this long (ms) after the value stops changing before re-checking (one request for an async rule, not one per key). Defaults to its `MForm`'s */
63
+ validateDebounce?: number
64
+ /** The key of this field in its `MForm` */
65
+ name?: string
49
66
  }>(),
50
67
  {
51
68
  multiple: false,
@@ -57,6 +74,7 @@ const emit = defineEmits<{
57
74
  select: [UploadFile[]]
58
75
  remove: [UploadFile]
59
76
  'update:modelValue': [UploadFile[]]
77
+ blur: []
60
78
  }>()
61
79
 
62
80
  defineSlots<{
@@ -91,6 +109,29 @@ onBeforeUnmount(() => {
91
109
  })
92
110
  const dragging = ref(false)
93
111
  const inputRef = ref<HTMLInputElement | null>(null)
112
+ const zoneEl = ref<HTMLElement | null>(null)
113
+
114
+ const validation = useFieldValidation({
115
+ value: () => files.value,
116
+ rules: () => props.rules,
117
+ required: () => props.required,
118
+ error: () => props.error,
119
+ errorLabel: () => props.errorLabel,
120
+ name: () => props.name,
121
+ validateOn: () => props.validateOn,
122
+ validateDebounce: () => props.validateDebounce,
123
+ disabled: () => props.disabled,
124
+ focus: () => { zoneEl.value?.focus() },
125
+ el: () => zoneEl.value,
126
+ setValue: (v) => setFiles((v as UploadFile[] | undefined) ?? []),
127
+ })
128
+ /** Its own `disabled` or its MForm's */
129
+ const isDisabled = validation.disabled
130
+ const { hasError, message: errorMessage, messageId } = validation
131
+ const onFocusOut = useFocusLeave(() => zoneEl.value, () => {
132
+ validation.onBlur()
133
+ emit('blur')
134
+ })
94
135
 
95
136
  const acceptList = computed(() =>
96
137
  props.accept ? props.accept.split(',').map((s) => s.trim()) : null,
@@ -139,7 +180,7 @@ function processFiles(fileList: FileList | File[]) {
139
180
 
140
181
  function onDrop(e: DragEvent) {
141
182
  dragging.value = false
142
- if (props.disabled || !e.dataTransfer?.files.length) return
183
+ if (isDisabled.value || !e.dataTransfer?.files.length) return
143
184
  processFiles(e.dataTransfer.files)
144
185
  }
145
186
 
@@ -158,26 +199,45 @@ function clear() {
158
199
  if (files.value.length) setFiles([])
159
200
  }
160
201
 
161
- defineExpose({ clear, files })
162
-
163
202
  function openPicker() {
164
- if (!props.disabled) inputRef.value?.click()
203
+ if (!isDisabled.value) inputRef.value?.click()
165
204
  }
205
+
206
+ defineExpose({
207
+ clear,
208
+ files,
209
+ /** Checks its rules and shows the result; resolves to whether they pass */
210
+ validate: validation.validate,
211
+ /** Hides its validation error (until the next check) */
212
+ resetValidation: validation.resetValidation,
213
+ })
166
214
  </script>
167
215
 
168
216
  <template>
169
217
  <div class="flex flex-col gap-3">
170
218
  <!-- Drop zone -->
219
+ <!-- A button for the keyboard too: Enter/Space open the picker, and a form can focus it on an error -->
171
220
  <div
172
- class="relative flex min-h-[160px] cursor-pointer flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed p-6 transition-colors duration-150"
221
+ ref="zoneEl"
222
+ role="button"
223
+ :tabindex="isDisabled ? -1 : 0"
224
+ :aria-disabled="isDisabled || undefined"
225
+ :aria-invalid="hasError || undefined"
226
+ :aria-describedby="errorMessage ? messageId : undefined"
227
+ class="relative flex min-h-[160px] cursor-pointer flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed p-6 outline-none transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-secondary"
173
228
  :class="[
174
- disabled
229
+ isDisabled
175
230
  ? 'cursor-not-allowed border-outline-variant/50 bg-surface-container/30 opacity-60'
176
231
  : dragging
177
232
  ? 'border-primary bg-primary-container/20'
178
- : 'border-outline-variant bg-surface-container-lowest hover:border-primary/60 hover:bg-surface-container',
233
+ : hasError
234
+ ? 'border-error bg-surface-container-lowest hover:bg-surface-container'
235
+ : 'border-outline-variant bg-surface-container-lowest hover:border-primary/60 hover:bg-surface-container',
179
236
  ]"
180
237
  @click="openPicker"
238
+ @keydown.enter.prevent="openPicker"
239
+ @keydown.space.prevent="openPicker"
240
+ @focusout="onFocusOut"
181
241
  @dragenter.prevent="dragging = true"
182
242
  @dragover.prevent="dragging = true"
183
243
  @dragleave.prevent="dragging = false"
@@ -208,10 +268,13 @@ function openPicker() {
208
268
  class="hidden"
209
269
  :accept="accept"
210
270
  :multiple="multiple"
211
- :disabled="disabled"
271
+ :disabled="isDisabled"
272
+ :name="name"
212
273
  @change="onFileInput"
213
274
  />
214
275
 
276
+ <p v-if="errorMessage" :id="messageId" role="alert" class="-mt-1 px-1 text-body-small text-error">{{ errorMessage }}</p>
277
+
215
278
  <!-- File list -->
216
279
  <TransitionGroup
217
280
  name="m3-file"
@@ -0,0 +1,208 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * A `<form>` that validates the fields inside it. Each field registers itself (by its `name`) and checks its
4
+ * own `rules`; the form adds a whole-form `schema` (zod, valibot… any Standard Schema), errors from outside
5
+ * (`errors`: a server's 422, vee-validate's `errors`), and on submit validates everything, emitting `submit`
6
+ * only when it all passes, or `invalid` and focusing the first field in error.
7
+ *
8
+ * @slot default The fields and buttons (a `<MButton type="submit">` submits it, as does Enter in a text field)
9
+ * @event submit Emitted when every field is valid, with the values by name (dotted names nest:
10
+ * `address.city` → `{ address: { city } }`), or the schema's output when there's a `schema`
11
+ * @event invalid Emitted when a submit fails validation, with the error messages by name
12
+ * @event reset Emitted after `reset()` (or a `type="reset"` button) put every field back to its first value
13
+ */
14
+ import { computed, provide, shallowReactive } from 'vue'
15
+ import { FORM_KEY, type FormField } from '../composables/_useFieldValidation'
16
+ import { issueKey, type StandardSchemaIssue, type StandardSchemaResult, type StandardSchemaV1, type ValidateOn } from '../composables/validation'
17
+
18
+ const props = defineProps<{
19
+ /** Errors from outside, by field name (a string or the first of an array): a server's response, vee-validate's `errors`. Shown over the fields' own rules */
20
+ errors?: Record<string, string | string[] | null | undefined>
21
+ /** A schema for the whole form (zod, valibot, arktype… any Standard Schema), run against the values by name */
22
+ schema?: StandardSchemaV1
23
+ /** When the fields check and show their rules, unless a field sets its own: on leaving it (default), while typing, or only on submit */
24
+ validateOn?: ValidateOn
25
+ /** Default for every field: wait this long (ms) after a value stops changing before re-checking it, so an async rule makes one request, not one per key */
26
+ validateDebounce?: number
27
+ /** Keep an `errors` message after its field changes. By default it hides as soon as the user edits that field, until a new `errors` object comes */
28
+ keepErrors?: boolean
29
+ /** Disables every control inside (through a native `<fieldset disabled>`) and skips their validation */
30
+ disabled?: boolean
31
+ }>()
32
+
33
+ const emit = defineEmits<{
34
+ submit: [values: any, event: SubmitEvent]
35
+ invalid: [errors: Record<string, string>]
36
+ reset: []
37
+ }>()
38
+
39
+ const fields = shallowReactive(new Set<FormField>())
40
+
41
+ /** Flat values by name, as the fields' rules see them (`ctx.values`) */
42
+ const values = computed(() => {
43
+ const out: Record<string, unknown> = {}
44
+ for (const f of fields) {
45
+ const name = f.name()
46
+ if (name) out[name] = f.value()
47
+ }
48
+ return out
49
+ })
50
+
51
+ function nest(flat: Record<string, unknown>) {
52
+ const out: Record<string, any> = {}
53
+ for (const [name, value] of Object.entries(flat)) {
54
+ const keys = name.split('.')
55
+ let node = out
56
+ const last = keys.pop()!
57
+ keys.forEach((k) => (node = node[k] ??= {}))
58
+ node[last] = value
59
+ }
60
+ return out
61
+ }
62
+
63
+ // One schema run per set of values, however many fields ask for their part of it
64
+ let schemaCache: { values: object; result: Promise<StandardSchemaResult<unknown>> } | null = null
65
+ function runSchema() {
66
+ if (schemaCache?.values !== values.value) {
67
+ schemaCache = { values: values.value, result: Promise.resolve(props.schema!['~standard'].validate(nest(values.value))) }
68
+ }
69
+ return schemaCache.result
70
+ }
71
+
72
+ const issuePath = (issue: StandardSchemaIssue) => (issue.path ?? []).map((s) => String(issueKey(s))).join('.')
73
+ const belongsTo = (path: string, name: string) => path === name || path.startsWith(name + '.')
74
+
75
+ provide(FORM_KEY, {
76
+ register(field) {
77
+ fields.add(field)
78
+ return () => fields.delete(field)
79
+ },
80
+ values: () => values.value,
81
+ externalError(name) {
82
+ const e = props.errors?.[name]
83
+ return (Array.isArray(e) ? e[0] : e) || null
84
+ },
85
+ hasSchema: () => !!props.schema,
86
+ async schemaError(name) {
87
+ if (!props.schema) return null
88
+ const result = await runSchema()
89
+ return result.issues?.find((i) => belongsTo(issuePath(i), name))?.message ?? null
90
+ },
91
+ validateOn: () => props.validateOn,
92
+ validateDebounce: () => props.validateDebounce,
93
+ externalErrorsKey: () => props.errors,
94
+ keepErrors: () => !!props.keepErrors,
95
+ disabled: () => !!props.disabled,
96
+ })
97
+
98
+ /** Schema issues no field owns, by path ('' for the form itself) */
99
+ async function orphanIssues(): Promise<Record<string, string>> {
100
+ if (!props.schema) return {}
101
+ const result = await runSchema()
102
+ const names = [...fields].map((f) => f.name()).filter((n): n is string => !!n)
103
+ const out: Record<string, string> = {}
104
+ for (const issue of result.issues ?? []) {
105
+ const path = issuePath(issue)
106
+ if (!names.some((n) => belongsTo(path, n)) && !(path in out)) out[path] = issue.message
107
+ }
108
+ return out
109
+ }
110
+
111
+ const errors = computed(() => {
112
+ const out: Record<string, string> = {}
113
+ for (const f of fields) {
114
+ const name = f.name()
115
+ const error = f.error()
116
+ if (name && error !== null) out[name] = error
117
+ }
118
+ return out
119
+ })
120
+
121
+ /** Fields in page order */
122
+ function ordered() {
123
+ return [...fields].sort((a, b) => {
124
+ const ea = a.el(), eb = b.el()
125
+ if (!ea || !eb) return 0
126
+ return ea.compareDocumentPosition(eb) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1
127
+ })
128
+ }
129
+
130
+ /** Validates every field (showing their errors); resolves to whether all pass */
131
+ /** The fields a list of names picks (a name also picks its nested ones: 'address' → 'address.city'), or all */
132
+ function pick(names?: string[]) {
133
+ if (!names) return [...fields]
134
+ return [...fields].filter((f) => {
135
+ const name = f.name()
136
+ return !!name && names.some((n) => belongsTo(name, n))
137
+ })
138
+ }
139
+
140
+ /**
141
+ * Validates every field, or only the ones named (a step of a wizard), showing their errors; resolves to whether
142
+ * they all pass. `focus` moves the focus to the first one in error, as a submit does.
143
+ */
144
+ async function validate(names?: string[], options: { focus?: boolean } = {}): Promise<boolean> {
145
+ const picked = pick(names)
146
+ const results = await Promise.all(picked.map((f) => f.validate()))
147
+ const orphans = Object.keys(await orphanIssues()).filter((path) => !names || names.some((n) => belongsTo(path, n)))
148
+ const ok = results.every(Boolean) && orphans.length === 0
149
+ if (!ok && options.focus) ordered().find((f) => picked.includes(f) && f.error() !== null)?.focus()
150
+ return ok
151
+ }
152
+
153
+ async function onSubmit(event: SubmitEvent) {
154
+ event.preventDefault()
155
+ if (props.disabled) return
156
+ if (await validate()) {
157
+ const nested = nest(values.value)
158
+ let output: unknown = nested
159
+ if (props.schema) {
160
+ const result = await runSchema()
161
+ if (!result.issues) output = result.value
162
+ }
163
+ emit('submit', output, event)
164
+ } else {
165
+ emit('invalid', { ...errors.value, ...(await orphanIssues()) })
166
+ ordered().find((f) => f.error() !== null)?.focus()
167
+ }
168
+ }
169
+
170
+ /** Puts every field back to the value it had when it mounted and clears their errors */
171
+ async function reset() {
172
+ await Promise.all([...fields].map((f) => f.reset()))
173
+ emit('reset')
174
+ }
175
+
176
+ function onReset(event: Event) {
177
+ event.preventDefault()
178
+ reset()
179
+ }
180
+
181
+ /** Hides every error (or the named fields' ones) without touching the values */
182
+ function resetValidation(names?: string[]) {
183
+ pick(names).forEach((f) => f.resetValidation())
184
+ }
185
+
186
+ defineExpose({
187
+ validate,
188
+ reset,
189
+ resetValidation,
190
+ /** Whether every field's rules pass right now (checked silently, shown or not) */
191
+ valid: computed(() => [...fields].every((f) => f.valid())),
192
+ /** Whether async rules are still running */
193
+ pending: computed(() => [...fields].some((f) => f.pending())),
194
+ /** The messages on display, by field name */
195
+ errors,
196
+ /** The values by name (dotted names nested) */
197
+ values: computed(() => nest(values.value)),
198
+ })
199
+ </script>
200
+
201
+ <template>
202
+ <form novalidate @submit="onSubmit" @reset="onReset">
203
+ <!-- display: contents keeps the fieldset out of the layout; it's only here for its native `disabled` -->
204
+ <fieldset :disabled="disabled" class="contents">
205
+ <slot />
206
+ </fieldset>
207
+ </form>
208
+ </template>