@m3ui-vue/m3ui-vue 1.6.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 (171) hide show
  1. package/dist/API.md +649 -28
  2. package/dist/{MButton-OQ4wIERQ.js → MButton-CN3wYwIG.js} +2 -2
  3. package/dist/{MButton-OQ4wIERQ.js.map → MButton-CN3wYwIG.js.map} +1 -1
  4. package/dist/MColorPickerModal-BKM1CHxr.js +577 -0
  5. package/dist/MColorPickerModal-BKM1CHxr.js.map +1 -0
  6. package/dist/{MDialog-DYMnaBlt.js → MDialog-1LAk9WAO.js} +2 -2
  7. package/dist/{MDialog-DYMnaBlt.js.map → MDialog-1LAk9WAO.js.map} +1 -1
  8. package/dist/{MListItem-D2cNUyzP.js → MListItem-BU5KDRCB.js} +376 -270
  9. package/dist/MListItem-BU5KDRCB.js.map +1 -0
  10. package/dist/{MLoadingIndicator-DWUj0BAB.js → MLoadingIndicator-RykOo5tf.js} +2 -2
  11. package/dist/{MLoadingIndicator-DWUj0BAB.js.map → MLoadingIndicator-RykOo5tf.js.map} +1 -1
  12. package/dist/{MSeekBar-C4cn9RIF.js → MSeekBar-B_Y3MpVz.js} +2 -2
  13. package/dist/{MSeekBar-C4cn9RIF.js.map → MSeekBar-B_Y3MpVz.js.map} +1 -1
  14. package/dist/MSegmentedButton-CiOOY1-N.js +105 -0
  15. package/dist/MSegmentedButton-CiOOY1-N.js.map +1 -0
  16. package/dist/MSlider-BCeVIxcq.js +739 -0
  17. package/dist/MSlider-BCeVIxcq.js.map +1 -0
  18. package/dist/{MSpinner-DZkXZJpc.js → MSpinner-Cs03qoqE.js} +2 -2
  19. package/dist/{MSpinner-DZkXZJpc.js.map → MSpinner-Cs03qoqE.js.map} +1 -1
  20. package/dist/{MTextField-CNH-byir.js → MTextField-NaFbMkjv.js} +162 -115
  21. package/dist/MTextField-NaFbMkjv.js.map +1 -0
  22. package/dist/MTooltip-CK39Zon4.js +183 -0
  23. package/dist/MTooltip-CK39Zon4.js.map +1 -0
  24. package/dist/_useFieldValidation-Bz34IAQY.js +191 -0
  25. package/dist/_useFieldValidation-Bz34IAQY.js.map +1 -0
  26. package/dist/api.json +1 -1
  27. package/dist/code-editor.js +184 -103
  28. package/dist/code-editor.js.map +1 -1
  29. package/dist/components/MAddressField.vue.d.ts +18 -3
  30. package/dist/components/MAppBarWithSearch.vue.d.ts +1 -1
  31. package/dist/components/MAudioRecorder.vue.d.ts +2 -2
  32. package/dist/components/MAutocomplete.vue.d.ts +22 -3
  33. package/dist/components/MCheckbox.vue.d.ts +23 -1
  34. package/dist/components/MCodeEditor.vue.d.ts +23 -1
  35. package/dist/components/MColorPicker.vue.d.ts +24 -3
  36. package/dist/components/MConfirmDialog.vue.d.ts +2 -2
  37. package/dist/components/MCountrySelect.vue.d.ts +13 -2
  38. package/dist/components/MCreditCardInput.vue.d.ts +33 -0
  39. package/dist/components/MCronField.vue.d.ts +23 -1
  40. package/dist/components/MDataTable.vue.d.ts +1 -1
  41. package/dist/components/MDatePicker.vue.d.ts +24 -3
  42. package/dist/components/MDateRangePicker.vue.d.ts +24 -3
  43. package/dist/components/MFileUpload.vue.d.ts +23 -2
  44. package/dist/components/MForm.vue.d.ts +61 -0
  45. package/dist/components/MJsonEditor.vue.d.ts +23 -1
  46. package/dist/components/MMapRoute.vue.d.ts +168 -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/MPhoneInput.vue.d.ts +19 -4
  55. package/dist/components/MPinInput.vue.d.ts +24 -3
  56. package/dist/components/MPosKeypad.vue.d.ts +2 -2
  57. package/dist/components/MRadioGroup.vue.d.ts +23 -1
  58. package/dist/components/MRating.vue.d.ts +23 -1
  59. package/dist/components/MRichTextEditor.vue.d.ts +23 -1
  60. package/dist/components/MSearchBar.vue.d.ts +1 -1
  61. package/dist/components/MSegmentedButton.vue.d.ts +23 -2
  62. package/dist/components/MSelect.vue.d.ts +22 -3
  63. package/dist/components/MSignaturePad.vue.d.ts +19 -0
  64. package/dist/components/MSlider.vue.d.ts +23 -1
  65. package/dist/components/MSwitch.vue.d.ts +23 -1
  66. package/dist/components/MTable.vue.d.ts +1 -1
  67. package/dist/components/MTagInput.vue.d.ts +20 -2
  68. package/dist/components/MText.vue.d.ts +1 -1
  69. package/dist/components/MTextField.vue.d.ts +26 -3
  70. package/dist/components/MTimePicker.vue.d.ts +24 -3
  71. package/dist/components/MTimezoneSelect.vue.d.ts +13 -2
  72. package/dist/components/MTour.vue.d.ts +2 -2
  73. package/dist/components/MTrackingTimeline.vue.d.ts +75 -0
  74. package/dist/components/MWindow.vue.d.ts +2 -2
  75. package/dist/composables/_routeGeometry.d.ts +26 -0
  76. package/dist/composables/_useFieldValidation.d.ts +91 -0
  77. package/dist/composables/mapRouting.d.ts +35 -0
  78. package/dist/composables/useLocale.d.ts +23 -0
  79. package/dist/composables/validation.d.ts +82 -0
  80. package/dist/draw.js +27 -26
  81. package/dist/draw.js.map +1 -1
  82. package/dist/flow.js +1 -1
  83. package/dist/gantt.js +2 -2
  84. package/dist/index.d.ts +5 -0
  85. package/dist/locales/index.js +154 -7
  86. package/dist/locales/index.js.map +1 -1
  87. package/dist/m3ui-vue.css +1 -1
  88. package/dist/m3ui.js +7350 -6183
  89. package/dist/m3ui.js.map +1 -1
  90. package/dist/map.d.ts +4 -0
  91. package/dist/map.js +1319 -867
  92. package/dist/map.js.map +1 -1
  93. package/dist/media.js +4 -4
  94. package/dist/pdf.js +4 -4
  95. package/dist/rich-text-editor.js +189 -146
  96. package/dist/rich-text-editor.js.map +1 -1
  97. package/dist/styles.css +1 -1
  98. package/dist/{useLocale-DaVSTdm0.js → useLocale-Dh1xZZ8i.js} +22 -1
  99. package/dist/useLocale-Dh1xZZ8i.js.map +1 -0
  100. package/package.json +1 -1
  101. package/src/__tests__/MForm.test.ts +325 -0
  102. package/src/__tests__/MMapRoute.test.ts +384 -0
  103. package/src/__tests__/MPhoneInput.test.ts +5 -2
  104. package/src/__tests__/MRichTextEditor.test.ts +2 -1
  105. package/src/__tests__/MTrackingTimeline.test.ts +66 -0
  106. package/src/__tests__/_fakeMaplibre.ts +4 -1
  107. package/src/__tests__/_osrmRoutes.ts +10 -0
  108. package/src/__tests__/attrsFallthrough.test.ts +11 -0
  109. package/src/__tests__/fieldsValidation.test.ts +229 -0
  110. package/src/__tests__/ssr.test.ts +1 -0
  111. package/src/__tests__/validation.test.ts +77 -0
  112. package/src/components/MAddressField.vue +45 -8
  113. package/src/components/MAudioRecorder.vue +9 -9
  114. package/src/components/MAutocomplete.vue +69 -23
  115. package/src/components/MCheckbox.vue +80 -17
  116. package/src/components/MCodeEditor.vue +59 -2
  117. package/src/components/MColorPicker.vue +65 -16
  118. package/src/components/MCountrySelect.vue +17 -3
  119. package/src/components/MCreditCardInput.vue +76 -7
  120. package/src/components/MCronField.vue +60 -10
  121. package/src/components/MDatePicker.vue +65 -16
  122. package/src/components/MDateRangePicker.vue +66 -16
  123. package/src/components/MFileUpload.vue +71 -8
  124. package/src/components/MForm.vue +208 -0
  125. package/src/components/MJsonEditor.vue +57 -3
  126. package/src/components/MMapBaseLayers.vue +29 -28
  127. package/src/components/MMapMeasure.vue +1 -1
  128. package/src/components/MMapRoute.vue +470 -0
  129. package/src/components/MMaskField.vue +55 -13
  130. package/src/components/MMentionField.vue +17 -2
  131. package/src/components/MMultiAutocomplete.vue +70 -23
  132. package/src/components/MMultiSelect.vue +70 -23
  133. package/src/components/MNumberField.vue +58 -16
  134. package/src/components/MPhoneInput.vue +60 -18
  135. package/src/components/MPinInput.vue +58 -10
  136. package/src/components/MRadioGroup.vue +65 -4
  137. package/src/components/MRating.vue +62 -6
  138. package/src/components/MRichTextEditor.vue +64 -4
  139. package/src/components/MSegmentedButton.vue +59 -2
  140. package/src/components/MSelect.vue +72 -26
  141. package/src/components/MSignaturePad.vue +71 -6
  142. package/src/components/MSlider.vue +61 -10
  143. package/src/components/MSwitch.vue +63 -8
  144. package/src/components/MTagInput.vue +67 -25
  145. package/src/components/MTextField.vue +68 -14
  146. package/src/components/MTimePicker.vue +65 -16
  147. package/src/components/MTimezoneSelect.vue +17 -3
  148. package/src/components/MTrackingTimeline.vue +257 -0
  149. package/src/composables/_routeGeometry.ts +140 -0
  150. package/src/composables/_useFieldValidation.ts +287 -0
  151. package/src/composables/mapRouting.ts +55 -0
  152. package/src/composables/useLocale.ts +46 -0
  153. package/src/composables/validation.ts +178 -0
  154. package/src/index.ts +5 -0
  155. package/src/locales/de.ts +21 -0
  156. package/src/locales/es.ts +28 -7
  157. package/src/locales/fr.ts +21 -0
  158. package/src/locales/ja.ts +21 -0
  159. package/src/locales/ko.ts +21 -0
  160. package/src/locales/pt.ts +21 -0
  161. package/src/locales/zh.ts +21 -0
  162. package/src/map.ts +4 -0
  163. package/dist/MListItem-D2cNUyzP.js.map +0 -1
  164. package/dist/MSegmentedButton-BEB4gXLA.js +0 -64
  165. package/dist/MSegmentedButton-BEB4gXLA.js.map +0 -1
  166. package/dist/MSlider-BIkA6DiE.js +0 -690
  167. package/dist/MSlider-BIkA6DiE.js.map +0 -1
  168. package/dist/MTextField-CNH-byir.js.map +0 -1
  169. package/dist/MTooltip-Dd5g2zhh.js +0 -754
  170. package/dist/MTooltip-Dd5g2zhh.js.map +0 -1
  171. package/dist/useLocale-DaVSTdm0.js.map +0 -1
@@ -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>
@@ -3,8 +3,11 @@
3
3
  * A JSON-aware editor built on top of MCodeEditor — validates as you type and adds format/minify shortcuts.
4
4
  *
5
5
  * @event update:modelValue Emitted with the parsed value whenever the text is valid JSON — powers v-model
6
+ * @event blur Emitted when focus leaves the editor
6
7
  */
7
- import { ref, computed, watch } from 'vue'
8
+ import { ref, computed, inject, provide, watch } from 'vue'
9
+ import { FORM_KEY, useFieldValidation, useFocusLeave, type FormContext } from '../composables/_useFieldValidation'
10
+ import type { ValidateOn, ValidationRule } from '../composables/validation'
8
11
  import MCodeEditor from './MCodeEditor.vue'
9
12
  import MIcon from './MIcon.vue'
10
13
  import { useLocale } from '../composables/useLocale'
@@ -17,6 +20,8 @@ export interface JsonEditorLabels {
17
20
  }
18
21
 
19
22
  const locale = useLocale()
23
+ // jsonRule is always there: `required` alone (no MForm, no rules) keeps today's behavior
24
+ const inForm = !!inject(FORM_KEY, null)
20
25
 
21
26
  const props = withDefaults(
22
27
  defineProps<{
@@ -24,6 +29,20 @@ const props = withDefaults(
24
29
  modelValue: unknown
25
30
  /** Read-only mode */
26
31
  readonly?: boolean
32
+ /** Error state. A string is also the message */
33
+ error?: boolean | string
34
+ /** Error message shown when `error` is true */
35
+ errorLabel?: string
36
+ /** Inside an `MForm` or with `rules`, it can't be empty (null) */
37
+ required?: boolean
38
+ /** Validation rules (functions or a Standard Schema); see `MForm` */
39
+ rules?: ValidationRule | ValidationRule[]
40
+ /** When the rules are checked and shown: on leaving it (default), on change, or only on submit */
41
+ validateOn?: ValidateOn
42
+ /** 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 */
43
+ validateDebounce?: number
44
+ /** The key of this field in its `MForm` */
45
+ name?: string
27
46
  /** Min height */
28
47
  minHeight?: string
29
48
  /** Max height */
@@ -49,13 +68,38 @@ const l = computed<Required<JsonEditorLabels>>(() => ({
49
68
  ...props.labels,
50
69
  }))
51
70
 
52
- const emit = defineEmits<{ 'update:modelValue': [unknown] }>()
71
+ const emit = defineEmits<{ 'update:modelValue': [unknown]; blur: [] }>()
53
72
 
54
73
  const rawText = ref(JSON.stringify(props.modelValue, null, 2))
55
74
  const parseError = ref<string | null>(null)
56
75
 
57
76
  const isValid = computed(() => !parseError.value)
58
77
 
78
+ // Text that doesn't parse is one more rule: it blocks an MForm submit
79
+ const jsonRule: ValidationRule = () => !parseError.value || l.value.invalid
80
+ const rootEl = ref<HTMLElement | null>(null)
81
+ const validation = useFieldValidation({
82
+ value: () => props.modelValue,
83
+ rules: () => [...(props.rules ? (Array.isArray(props.rules) ? props.rules : [props.rules]) : []), jsonRule],
84
+ required: () => props.required && (inForm || !!props.rules),
85
+ error: () => props.error,
86
+ errorLabel: () => props.errorLabel,
87
+ name: () => props.name,
88
+ validateOn: () => props.validateOn,
89
+ validateDebounce: () => props.validateDebounce,
90
+ disabled: () => props.readonly,
91
+ focus: () => { rootEl.value?.querySelector<HTMLElement>('.cm-content')?.focus() },
92
+ el: () => rootEl.value,
93
+ setValue: (v) => emit('update:modelValue', v),
94
+ })
95
+ const { hasError, message: errorMessage, messageId } = validation
96
+ const onFocusOut = useFocusLeave(() => rootEl.value, () => {
97
+ validation.onBlur()
98
+ emit('blur')
99
+ })
100
+ // The inner MCodeEditor edits text, not this value: keep it out of the form
101
+ provide(FORM_KEY, null as unknown as FormContext)
102
+
59
103
  watch(() => props.modelValue, (val) => {
60
104
  let current: unknown
61
105
  try {
@@ -103,13 +147,21 @@ function minifyJson() {
103
147
  // keep error state
104
148
  }
105
149
  }
150
+
151
+ defineExpose({
152
+ /** Checks its rules and shows the result; resolves to whether they pass */
153
+ validate: validation.validate,
154
+ /** Hides its validation error (until the next check) */
155
+ resetValidation: validation.resetValidation,
156
+ })
106
157
  </script>
107
158
 
108
159
  <template>
109
- <div class="flex flex-col gap-0">
160
+ <div ref="rootEl" class="flex flex-col gap-0" @focusout="onFocusOut">
110
161
  <MCodeEditor
111
162
  :model-value="rawText"
112
163
  language="json"
164
+ :error="hasError && !parseError"
113
165
  :readonly="readonly"
114
166
  :min-height="minHeight"
115
167
  :max-height="maxHeight"
@@ -153,5 +205,7 @@ function minifyJson() {
153
205
  <p v-if="parseError" class="px-3 py-1.5 text-body-small text-error">
154
206
  {{ parseError }}
155
207
  </p>
208
+ <!-- The parse error above already says what's wrong with the text -->
209
+ <p v-else-if="errorMessage" :id="messageId" role="alert" class="px-3 py-1.5 text-body-small text-error">{{ errorMessage }}</p>
156
210
  </div>
157
211
  </template>
@@ -6,6 +6,7 @@
6
6
  * from the `/map` entry point.
7
7
  */
8
8
  import MIcon from './MIcon.vue'
9
+ import MTooltip from './MTooltip.vue'
9
10
  import { useLocale } from '../composables/useLocale'
10
11
  import { useMapLayers } from '../composables/useMapLayers'
11
12
  import type { MapSource } from '../composables/useMap'
@@ -32,34 +33,34 @@ const src = (image: string, base: string) => (/^(https?:|data:|\/\/)/.test(image
32
33
 
33
34
  <template>
34
35
  <div class="flex gap-2" :class="vertical ? 'flex-col' : 'flex-row flex-wrap'" role="radiogroup">
35
- <button
36
- v-for="layer in baseLayers"
37
- :key="layer.id"
38
- type="button"
39
- role="radio"
40
- class="m3-map-base grid size-12 shrink-0 cursor-pointer place-items-center overflow-hidden rounded-full border-2 bg-surface-variant transition-[border-color,transform] duration-150 hover:scale-110"
41
- :class="baseLayer === layer.id ? 'm3-map-base--active border-primary' : 'border-transparent'"
42
- :title="layer.title"
43
- :aria-label="layer.title"
44
- :aria-checked="baseLayer === layer.id"
45
- @click="setBaseLayer(layer.id)"
46
- >
47
- <img v-if="layer.base?.image" :src="src(layer.base.image, imageBase)" alt="" class="size-full object-cover">
48
- <MIcon v-else name="map" :size="22" class="text-on-surface-variant" />
49
- </button>
50
- <button
51
- v-if="none"
52
- type="button"
53
- role="radio"
54
- class="m3-map-base grid size-12 shrink-0 cursor-pointer place-items-center rounded-full border-2 bg-surface-variant transition-[border-color,transform] duration-150 hover:scale-110"
55
- :class="baseLayer === null ? 'm3-map-base--active border-primary' : 'border-transparent'"
56
- :title="t.mapNoBaseLayer"
57
- :aria-label="t.mapNoBaseLayer"
58
- :aria-checked="baseLayer === null"
59
- @click="setBaseLayer(null)"
60
- >
61
- <MIcon name="layers_clear" :size="22" class="text-on-surface-variant" />
62
- </button>
36
+ <!-- The library's tooltip, not the browser's title -->
37
+ <MTooltip v-for="layer in baseLayers" :key="layer.id" :text="layer.title" :placement="vertical ? 'right' : 'top'">
38
+ <button
39
+ type="button"
40
+ role="radio"
41
+ class="m3-map-base grid size-12 shrink-0 cursor-pointer place-items-center overflow-hidden rounded-full border-2 bg-surface-variant transition-[border-color,transform] duration-150 hover:scale-110"
42
+ :class="baseLayer === layer.id ? 'm3-map-base--active border-primary' : 'border-transparent'"
43
+ :aria-label="layer.title"
44
+ :aria-checked="baseLayer === layer.id"
45
+ @click="setBaseLayer(layer.id)"
46
+ >
47
+ <img v-if="layer.base?.image" :src="src(layer.base.image, imageBase)" alt="" class="size-full object-cover">
48
+ <MIcon v-else name="map" :size="22" class="text-on-surface-variant" />
49
+ </button>
50
+ </MTooltip>
51
+ <MTooltip v-if="none" :text="t.mapNoBaseLayer" :placement="vertical ? 'right' : 'top'">
52
+ <button
53
+ type="button"
54
+ role="radio"
55
+ class="m3-map-base grid size-12 shrink-0 cursor-pointer place-items-center rounded-full border-2 bg-surface-variant transition-[border-color,transform] duration-150 hover:scale-110"
56
+ :class="baseLayer === null ? 'm3-map-base--active border-primary' : 'border-transparent'"
57
+ :aria-label="t.mapNoBaseLayer"
58
+ :aria-checked="baseLayer === null"
59
+ @click="setBaseLayer(null)"
60
+ >
61
+ <MIcon name="layers_clear" :size="22" class="text-on-surface-variant" />
62
+ </button>
63
+ </MTooltip>
63
64
  </div>
64
65
  </template>
65
66
 
@@ -413,7 +413,7 @@ defineExpose({ start, finish, clear, remove })
413
413
  <MIcon name="straighten" :size="20" />
414
414
  </button>
415
415
  <button type="button" class="grid place-items-center" :title="t.mapMeasureArea" :aria-pressed="mode === 'area'" @click="start('area')">
416
- <MIcon name="pentagon" :size="20" />
416
+ <MIcon name="square_foot" :size="20" />
417
417
  </button>
418
418
  <button type="button" class="grid place-items-center" :title="t.mapClearMeasurements" :disabled="!count && !mode" @click="clear">
419
419
  <MIcon name="delete" :size="20" />