@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
@@ -0,0 +1,229 @@
1
+ import { describe, expect, it, vi } from 'vitest'
2
+ import { flushPromises, mount } from '@vue/test-utils'
3
+ import { h, type Component } from 'vue'
4
+ import MForm from '../components/MForm.vue'
5
+ import MNumberField from '../components/MNumberField.vue'
6
+ import MMaskField from '../components/MMaskField.vue'
7
+ import MTagInput from '../components/MTagInput.vue'
8
+ import MPinInput from '../components/MPinInput.vue'
9
+ import MSelect from '../components/MSelect.vue'
10
+ import MMultiSelect from '../components/MMultiSelect.vue'
11
+ import MAutocomplete from '../components/MAutocomplete.vue'
12
+ import MMultiAutocomplete from '../components/MMultiAutocomplete.vue'
13
+ import MDatePicker from '../components/MDatePicker.vue'
14
+ import MDateRangePicker from '../components/MDateRangePicker.vue'
15
+ import MTimePicker from '../components/MTimePicker.vue'
16
+ import MColorPicker from '../components/MColorPicker.vue'
17
+ import MPhoneInput from '../components/MPhoneInput.vue'
18
+ import MCountrySelect from '../components/MCountrySelect.vue'
19
+ import MTimezoneSelect from '../components/MTimezoneSelect.vue'
20
+ import MMentionField from '../components/MMentionField.vue'
21
+ import MAddressField from '../components/MAddressField.vue'
22
+ import { defaultLocale } from '../composables/useLocale'
23
+
24
+ const options = [{ value: 'a', label: 'A' }, { value: 'b', label: 'B' }]
25
+
26
+ /** Every form field of phase 2, empty, with what it needs to mount */
27
+ const cases: [string, Component, Record<string, unknown>][] = [
28
+ ['MNumberField', MNumberField, { modelValue: null }],
29
+ ['MMaskField', MMaskField, { modelValue: '', mask: '###' }],
30
+ ['MTagInput', MTagInput, { modelValue: [] }],
31
+ ['MPinInput', MPinInput, { modelValue: '12', length: 4 }], // partly filled counts as empty
32
+ ['MSelect', MSelect, { modelValue: undefined, options }],
33
+ ['MMultiSelect', MMultiSelect, { modelValue: [], options }],
34
+ ['MAutocomplete', MAutocomplete, { modelValue: undefined, options }],
35
+ ['MMultiAutocomplete', MMultiAutocomplete, { modelValue: [], options }],
36
+ ['MDatePicker', MDatePicker, { modelValue: null }],
37
+ ['MDateRangePicker', MDateRangePicker, { modelValue: { start: '2026-01-01', end: null } }], // half a range is empty
38
+ ['MTimePicker', MTimePicker, { modelValue: null }],
39
+ ['MColorPicker', MColorPicker, { modelValue: '' }],
40
+ ['MPhoneInput', MPhoneInput, { modelValue: null, country: 'AR' }],
41
+ ['MCountrySelect', MCountrySelect, { modelValue: null }],
42
+ ['MTimezoneSelect', MTimezoneSelect, { modelValue: null }],
43
+ ['MMentionField', MMentionField, { modelValue: '', sources: [] }],
44
+ ['MAddressField', MAddressField, { modelValue: null }],
45
+ ]
46
+
47
+ async function submit(field: Component, props: Record<string, unknown>) {
48
+ const onSubmit = vi.fn()
49
+ const onInvalid = vi.fn()
50
+ const w = mount(() => h(MForm, { onSubmit, onInvalid }, () => h(field, { label: 'Field', name: 'f', ...props })), { attachTo: document.body })
51
+ await flushPromises()
52
+ await w.find('form').trigger('submit')
53
+ await flushPromises()
54
+ return { w, onSubmit, onInvalid }
55
+ }
56
+
57
+ describe('form fields in an MForm', () => {
58
+ it.each(cases)('%s: required blocks submit, shows the message and takes the focus', async (_, field, props) => {
59
+ const { w, onSubmit, onInvalid } = await submit(field, { ...props, required: true })
60
+ expect(onSubmit).not.toHaveBeenCalled()
61
+ expect(onInvalid).toHaveBeenCalledWith({ f: defaultLocale.validationRequired })
62
+ expect(w.findAll('[role="alert"]').map((p) => p.text())).toEqual([defaultLocale.validationRequired])
63
+ expect(w.element.contains(document.activeElement)).toBe(true)
64
+ w.unmount()
65
+ })
66
+
67
+ it.each(cases)('%s: a string error is the message', async (_, field, props) => {
68
+ const w = mount(field, { props: { label: 'Field', ...props, error: 'From the server' } })
69
+ await flushPromises()
70
+ expect(w.findAll('[role="alert"]').map((p) => p.text())).toEqual(['From the server'])
71
+ })
72
+
73
+ it.each(cases)('%s: required outside an MForm keeps quiet', async (_, field, props) => {
74
+ const w = mount(field, { props: { label: 'Field', ...props, required: true }, attachTo: document.body })
75
+ await flushPromises()
76
+ w.element.dispatchEvent?.(new FocusEvent('focusout', { bubbles: true }))
77
+ await new Promise((r) => setTimeout(r))
78
+ await flushPromises()
79
+ expect(w.findAll('[role="alert"]')).toHaveLength(0)
80
+ w.unmount()
81
+ })
82
+ })
83
+
84
+ describe('leaving a field', () => {
85
+ it("MNumberField: the stepper buttons aren't leaving it", async () => {
86
+ const onBlur = vi.fn()
87
+ const w = mount(MNumberField, { props: { label: 'Qty', modelValue: null, rules: [() => 'Bad'], onBlur }, attachTo: document.body })
88
+ const input = w.find('input').element as HTMLInputElement
89
+ const plus = w.findAll('button')[1].element as HTMLButtonElement
90
+ input.focus()
91
+ plus.focus() // focus moves inside the field
92
+ await new Promise((r) => setTimeout(r))
93
+ await flushPromises()
94
+ expect(onBlur).not.toHaveBeenCalled()
95
+ plus.blur() // now it really leaves
96
+ await new Promise((r) => setTimeout(r))
97
+ await flushPromises()
98
+ expect(onBlur).toHaveBeenCalledTimes(1)
99
+ expect(w.find('[role="alert"]').text()).toBe('Bad')
100
+ w.unmount()
101
+ })
102
+
103
+ it("MDatePicker: opening the calendar isn't leaving it; closing it with focus outside is", async () => {
104
+ const onBlur = vi.fn()
105
+ const w = mount(MDatePicker, { props: { label: 'Date', modelValue: null, rules: [() => 'Pick one'], onBlur }, attachTo: document.body })
106
+ const trigger = w.find('button')
107
+ trigger.element.focus()
108
+ await trigger.trigger('click') // opens the teleported panel
109
+ ;(document.activeElement as HTMLElement | null)?.blur()
110
+ w.element.dispatchEvent(new FocusEvent('focusout', { bubbles: true }))
111
+ await new Promise((r) => setTimeout(r))
112
+ expect(onBlur).not.toHaveBeenCalled()
113
+ document.body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })) // a click outside closes it
114
+ await flushPromises()
115
+ await new Promise((r) => setTimeout(r))
116
+ await flushPromises()
117
+ expect(onBlur).toHaveBeenCalledTimes(1)
118
+ w.unmount()
119
+ })
120
+
121
+ it('MPhoneInput: an incomplete number blocks an MForm submit', async () => {
122
+ const { onSubmit, onInvalid, w } = await submit(MPhoneInput, { modelValue: '+54112', country: 'AR' })
123
+ expect(onSubmit).not.toHaveBeenCalled()
124
+ expect(Object.keys(onInvalid.mock.calls[0][0])).toEqual(['f'])
125
+ w.unmount()
126
+ })
127
+
128
+ it('MAddressField: validates the picked place, and its inner text field stays out of the form', async () => {
129
+ const { onInvalid, w } = await submit(MAddressField, { modelValue: null, required: true })
130
+ // One field in the form (the address), not two
131
+ expect(onInvalid).toHaveBeenCalledWith({ f: defaultLocale.validationRequired })
132
+ expect(w.findAll('[role="alert"]')).toHaveLength(1)
133
+ w.unmount()
134
+ })
135
+ })
136
+
137
+ // ── Phase 3: controls that had no error state ─────────────────────────
138
+ import MCheckbox from '../components/MCheckbox.vue'
139
+ import MSwitch from '../components/MSwitch.vue'
140
+ import MRadioGroup from '../components/MRadioGroup.vue'
141
+ import MRating from '../components/MRating.vue'
142
+ import MSegmentedButton from '../components/MSegmentedButton.vue'
143
+ import MCronField from '../components/MCronField.vue'
144
+ import MFileUpload from '../components/MFileUpload.vue'
145
+ import MSignaturePad from '../components/MSignaturePad.vue'
146
+ import MCreditCardInput from '../components/MCreditCardInput.vue'
147
+ import MJsonEditor from '../components/MJsonEditor.vue'
148
+ import MSlider from '../components/MSlider.vue'
149
+ import { min, required } from '../composables/validation'
150
+
151
+ const blankCard = { number: '', expiry: '', cvc: '' }
152
+ /** [name, component, empty props, can it take focus] */
153
+ const groupB: [string, Component, Record<string, unknown>, boolean][] = [
154
+ ['MCheckbox', MCheckbox, { modelValue: false }, true],
155
+ ['MSwitch', MSwitch, { modelValue: false }, true],
156
+ ['MRadioGroup', MRadioGroup, { modelValue: null, options }, true],
157
+ ['MRating', MRating, { modelValue: 0 }, true],
158
+ ['MSegmentedButton', MSegmentedButton, { modelValue: undefined, options }, true],
159
+ ['MCronField', MCronField, { modelValue: '' }, true],
160
+ ['MFileUpload', MFileUpload, { modelValue: [] }, true],
161
+ ['MSignaturePad', MSignaturePad, {}, false],
162
+ ['MCreditCardInput', MCreditCardInput, { modelValue: blankCard, preview: false }, true],
163
+ ['MJsonEditor', MJsonEditor, { modelValue: null }, false],
164
+ ]
165
+
166
+ describe('group B fields in an MForm', () => {
167
+ it.each(groupB)('%s: required blocks submit and shows the message', async (_, field, props, focusable) => {
168
+ const { w, onSubmit, onInvalid } = await submit(field, { ...props, required: true })
169
+ expect(onSubmit).not.toHaveBeenCalled()
170
+ expect(Object.keys(onInvalid.mock.calls[0][0])).toEqual(['f'])
171
+ const alerts = [...document.body.querySelectorAll('[role="alert"]')].map((p) => p.textContent?.trim())
172
+ // The card shows its fields' own messages instead of a general one
173
+ if (field !== MCreditCardInput) expect(alerts).toEqual([defaultLocale.validationRequired])
174
+ else expect(alerts.length).toBeGreaterThan(0)
175
+ if (focusable) expect(w.element.contains(document.activeElement)).toBe(true)
176
+ w.unmount()
177
+ })
178
+
179
+ it.each(groupB)('%s: a string error is the message', async (_, field, props) => {
180
+ const w = mount(field, { props: { label: 'Field', ...props, error: 'From the server' }, attachTo: document.body })
181
+ await flushPromises()
182
+ expect([...document.body.querySelectorAll('[role="alert"]')].map((p) => p.textContent?.trim())).toEqual(['From the server'])
183
+ w.unmount()
184
+ })
185
+
186
+ it('MCheckbox takes the M3 error colors (Error outline unticked, Error container ticked)', async () => {
187
+ const w = mount(MCheckbox, { props: { modelValue: false, label: 'Terms', error: true } })
188
+ const box = () => w.findAll('span').find((s) => s.classes().includes('h-4.5'))!
189
+ expect(box().classes()).toContain('border-error')
190
+ await w.setProps({ modelValue: true })
191
+ expect(box().classes()).toEqual(expect.arrayContaining(['bg-error', 'text-on-error']))
192
+ })
193
+
194
+ it('MSlider: rules (not required) set its limits', async () => {
195
+ const { onInvalid, w } = await submit(MSlider, { modelValue: 0, rules: [min(10)] })
196
+ expect(onInvalid).toHaveBeenCalledWith({ f: 'Must be at least 10' })
197
+ w.unmount()
198
+ })
199
+
200
+ it('MCreditCardInput: an optional empty card passes, a half-typed one does not', async () => {
201
+ const ok = await submit(MCreditCardInput, { modelValue: blankCard, preview: false })
202
+ expect(ok.onSubmit).toHaveBeenCalled()
203
+ ok.w.unmount()
204
+ const bad = await submit(MCreditCardInput, { modelValue: { number: '4242', expiry: '', cvc: '' }, preview: false })
205
+ expect(bad.onSubmit).not.toHaveBeenCalled()
206
+ expect(bad.onInvalid).toHaveBeenCalledWith({ f: defaultLocale.cardInvalidNumber })
207
+ bad.w.unmount()
208
+ })
209
+
210
+ it("MJsonEditor: required alone (no form, no rules) keeps quiet", async () => {
211
+ const w = mount(MJsonEditor, { props: { modelValue: null, required: true } })
212
+ await flushPromises()
213
+ expect(w.findAll('[role="alert"]')).toHaveLength(0)
214
+ })
215
+
216
+ it('MForm disabled disables div-based fields too (MSelect)', async () => {
217
+ const w = mount(() => h(MForm, { disabled: true }, () => h(MSelect, { label: 'Room', modelValue: undefined, options })))
218
+ await flushPromises()
219
+ expect(w.find('[role="combobox"]').attributes('tabindex')).toBe('-1')
220
+ })
221
+ })
222
+
223
+ describe('required() in rules on a field with its own "empty"', () => {
224
+ it("MDateRangePicker: half a range fails with the rule's message", async () => {
225
+ const { onInvalid, w } = await submit(MDateRangePicker, { modelValue: { start: '2026-01-01', end: null }, required: true, rules: [required('Pick both dates')] })
226
+ expect(onInvalid).toHaveBeenCalledWith({ f: 'Pick both dates' })
227
+ w.unmount()
228
+ })
229
+ })
@@ -26,6 +26,7 @@ const props: Record<string, Record<string, unknown>> = {
26
26
  MVirtualTable: { columns: [{ key: 'a', label: 'A' }], rows: [{ a: 1 }] },
27
27
  MTreeTable: { columns: [{ key: 'a', label: 'A' }], rows: [] },
28
28
  MTree: { nodes: [{ id: 1, label: 'a' }] },
29
+ MTrackingTimeline: { steps: [{ label: 'Placed' }, { label: 'Delivered' }], current: 0, eta: 0 },
29
30
  MKbd: { keys: 'Ctrl+K' },
30
31
  MOrderTicket: { number: 1, createdAt: 0, items: [{ id: 1, name: 'Pizza' }] },
31
32
  MSeatMap: { layout: ['ss_ss', 'ss_ss'], modelValue: ['A1'] },
@@ -0,0 +1,77 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { defaultLocale } from '../composables/useLocale'
3
+ import { email, isEmpty, max, maxLength, min, minLength, pattern, required, runRules, sameAs, url, type StandardSchemaV1 } from '../composables/validation'
4
+
5
+ const ctx = { locale: defaultLocale, values: {} as Record<string, unknown> }
6
+ const check = (rule: ReturnType<typeof required>, value: unknown, values = {}) => runRules([rule], value, { ...ctx, values })
7
+
8
+ /** A minimal Standard Schema, like zod's/valibot's */
9
+ function schema(test: (v: unknown) => string | null): StandardSchemaV1 {
10
+ return { '~standard': { version: 1, vendor: 'test', validate: (v) => { const m = test(v); return m ? { issues: [{ message: m }] } : { value: v } } } }
11
+ }
12
+
13
+ describe('validators', () => {
14
+ it('isEmpty', () => {
15
+ for (const v of [null, undefined, '', ' ', [], false]) expect(isEmpty(v)).toBe(true)
16
+ for (const v of [0, 'a', [1], true]) expect(isEmpty(v)).toBe(false)
17
+ })
18
+
19
+ it('required uses the locale message, or a custom one', async () => {
20
+ expect(await check(required(), '')).toBe(defaultLocale.validationRequired)
21
+ expect(await check(required('Hey'), ' ')).toBe('Hey')
22
+ expect(await check(required(), 'x')).toBeNull()
23
+ expect(await check(required(), 0)).toBeNull()
24
+ })
25
+
26
+ it('every other rule passes on an empty value', async () => {
27
+ for (const rule of [email(), url(), minLength(3), maxLength(1), min(5), max(1), pattern(/x/), sameAs('a')]) {
28
+ expect(await check(rule, '', { a: 'b' })).toBeNull()
29
+ }
30
+ })
31
+
32
+ it('email and url', async () => {
33
+ expect(await check(email(), 'a@b.co')).toBeNull()
34
+ expect(await check(email(), 'a@b')).toBe(defaultLocale.validationEmail)
35
+ expect(await check(url(), 'https://m3ui.dev/x')).toBeNull()
36
+ expect(await check(url(), 'ftp://x.y')).toBe(defaultLocale.validationUrl)
37
+ expect(await check(url(), 'nope')).toBe(defaultLocale.validationUrl)
38
+ })
39
+
40
+ it('lengths fill in {min}/{max}, with item wording for arrays', async () => {
41
+ expect(await check(minLength(3), 'ab')).toBe('Enter at least 3 characters')
42
+ expect(await check(maxLength(2), 'abc')).toBe('Enter at most 2 characters')
43
+ expect(await check(minLength(2), ['a'])).toBe('Choose at least 2')
44
+ expect(await check(maxLength(1), ['a', 'b'])).toBe('Choose at most 1')
45
+ })
46
+
47
+ it('min/max accept numeric strings', async () => {
48
+ expect(await check(min(18), '17')).toBe('Must be at least 18')
49
+ expect(await check(min(18), 18)).toBeNull()
50
+ expect(await check(max(10), '11')).toBe('Must be at most 10')
51
+ })
52
+
53
+ it('pattern resets a global regex between calls', async () => {
54
+ const rule = pattern(/^\d+$/g)
55
+ expect(await check(rule, '12')).toBeNull()
56
+ expect(await check(rule, '12')).toBeNull()
57
+ })
58
+
59
+ it('sameAs reads another field by name, or a getter', async () => {
60
+ expect(await check(sameAs('password'), 'x', { password: 'y' })).toBe(defaultLocale.validationSameAs)
61
+ expect(await check(sameAs('password'), 'x', { password: 'x' })).toBeNull()
62
+ expect(await check(sameAs(() => 'x'), 'x')).toBeNull()
63
+ })
64
+
65
+ it('custom rules: false → generic message, string → that message, async works', async () => {
66
+ expect(await runRules([() => false], 'a', ctx)).toBe(defaultLocale.validationInvalid)
67
+ expect(await runRules([() => 'Nope'], 'a', ctx)).toBe('Nope')
68
+ expect(await runRules([async () => 'Later'], 'a', ctx)).toBe('Later')
69
+ expect(await runRules([() => true, () => 'Second'], 'a', ctx)).toBe('Second')
70
+ })
71
+
72
+ it('a Standard Schema works as a rule', async () => {
73
+ const s = schema((v) => (String(v).length < 2 ? 'Too short' : null))
74
+ expect(await runRules([s], 'a', ctx)).toBe('Too short')
75
+ expect(await runRules([s], 'ab', ctx)).toBeNull()
76
+ })
77
+ })
@@ -9,8 +9,11 @@
9
9
  *
10
10
  * @event update:modelValue A place was picked, or the text changed after picking one (null)
11
11
  * @event select A place was picked
12
+ * @event blur Focus left the field and its list
12
13
  */
13
- import { computed, nextTick, onBeforeUnmount, ref, shallowRef, useId, watch, watchEffect } from 'vue'
14
+ import { computed, nextTick, onBeforeUnmount, provide, ref, shallowRef, useId, watch, watchEffect } from 'vue'
15
+ import { FORM_KEY, useFieldValidation, type FormContext } 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'
@@ -44,11 +47,19 @@ const props = withDefaults(
44
47
  minLength?: number
45
48
  /** Helper text below the field */
46
49
  hint?: string
47
- /** Error state */
48
- error?: boolean
50
+ /** Error state. A string is also the message */
51
+ error?: boolean | string
49
52
  /** Error message shown when `error` is true */
50
53
  errorLabel?: string
51
- /** Marks it as required */
54
+ /** Validation rules (functions or a Standard Schema), run on the picked place (null until one is picked); see `MForm` */
55
+ rules?: ValidationRule | ValidationRule[]
56
+ /** When the rules are checked and shown: on leaving the field (default), while typing, or only on submit */
57
+ validateOn?: ValidateOn
58
+ /** 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 */
59
+ validateDebounce?: number
60
+ /** The key of this field in its `MForm` */
61
+ name?: string
62
+ /** Marks it as required; inside an `MForm` or with `rules`, a place must be picked (typed text alone isn't enough) */
52
63
  required?: boolean
53
64
  /** Disables the field */
54
65
  disabled?: boolean
@@ -59,6 +70,7 @@ const props = withDefaults(
59
70
  const emit = defineEmits<{
60
71
  'update:modelValue': [place: MapSearchResult | null]
61
72
  select: [place: MapSearchResult]
73
+ blur: []
62
74
  }>()
63
75
 
64
76
  const t = useLocale()
@@ -78,6 +90,26 @@ let controller: AbortController | undefined
78
90
  let timer: ReturnType<typeof setTimeout> | undefined
79
91
 
80
92
  const field = ref<InstanceType<typeof MTextField>>()
93
+
94
+ // Validates the picked place, not the text: the inner MTextField is kept out of the MForm
95
+ const validation = useFieldValidation({
96
+ value: () => props.modelValue,
97
+ rules: () => props.rules,
98
+ required: () => props.required,
99
+ error: () => props.error,
100
+ errorLabel: () => props.errorLabel,
101
+ name: () => props.name,
102
+ validateOn: () => props.validateOn,
103
+ validateDebounce: () => props.validateDebounce,
104
+ disabled: () => props.disabled,
105
+ focus: () => field.value?.focus(),
106
+ el: () => wrapEl.value,
107
+ setValue: (v) => emit('update:modelValue', (v as MapSearchResult | null) ?? null),
108
+ })
109
+ /** Its own `disabled` or its MForm's */
110
+ const isDisabled = validation.disabled
111
+ const fieldError = computed(() => validation.message.value || validation.hasError.value)
112
+ provide(FORM_KEY, null as unknown as FormContext)
81
113
  const wrapEl = ref<HTMLElement>()
82
114
  const listEl = ref<HTMLElement>()
83
115
  // The field's box (MTextField's first child), without its hint
@@ -181,6 +213,8 @@ function onFocusOut(e: FocusEvent) {
181
213
  if (next && (wrapEl.value?.contains(next) || listEl.value?.contains(next))) return
182
214
  focused.value = false
183
215
  open.value = false
216
+ validation.onBlur()
217
+ emit('blur')
184
218
  }
185
219
 
186
220
  // Escape closes the list (and only that, inside a dialog)
@@ -231,6 +265,10 @@ defineExpose({
231
265
  clear,
232
266
  /** Focuses the field */
233
267
  focus: () => field.value?.focus(),
268
+ /** Checks its rules and shows the result; resolves to whether they pass */
269
+ validate: validation.validate,
270
+ /** Hides its validation error (until the next check) */
271
+ resetValidation: validation.resetValidation,
234
272
  })
235
273
  </script>
236
274
 
@@ -243,17 +281,16 @@ defineExpose({
243
281
  :variant="variant"
244
282
  :leading-icon="leadingIcon"
245
283
  :hint="hint"
246
- :error="error"
247
- :error-label="errorLabel"
284
+ :error="fieldError"
248
285
  :required="required"
249
- :disabled="disabled"
286
+ :disabled="isDisabled"
250
287
  autocomplete="street-address"
251
288
  @update:model-value="onText"
252
289
  >
253
290
  <!-- Always passed: MTextField reserves the room for #trailing only when the slot exists from the start -->
254
291
  <template #trailing>
255
292
  <MSpinner v-if="loading" :size="20" class="m-2" />
256
- <MIconButton v-else-if="text" icon="close" :label="t.clearSearch" size="sm" :disabled="disabled" @click="clear" />
293
+ <MIconButton v-else-if="text" icon="close" :label="t.clearSearch" size="sm" :disabled="isDisabled" @click="clear" />
257
294
  </template>
258
295
  </MTextField>
259
296
  </div>
@@ -285,16 +285,16 @@ defineExpose({ start, stop, pause, resume, discard })
285
285
  </template>
286
286
  <template v-else-if="modelValue">
287
287
  <MIconButton :icon="playing ? 'pause' : 'play_arrow'" :label="playing ? t.recorderPausePlayback : t.recorderPlay" @click="togglePlay" />
288
- <span class="flex h-8 min-w-0 flex-1 items-center gap-[2px]" aria-hidden="true">
288
+ <span class="mr-1 flex h-8 min-w-0 flex-1 items-center justify-between gap-px overflow-hidden" aria-hidden="true">
289
289
  <span
290
290
  v-for="(p, i) in modelValue.peaks"
291
291
  :key="i"
292
- class="w-[3px] min-w-[2px] flex-1 rounded-full"
292
+ class="min-w-px max-w-[3px] flex-1 rounded-full"
293
293
  :class="i / modelValue.peaks.length < played ? 'bg-primary' : 'bg-on-surface-variant/50'"
294
294
  :style="{ height: `${Math.max(12, p * 100)}%` }"
295
295
  />
296
296
  </span>
297
- <span class="shrink-0 font-mono text-label-medium text-on-surface-variant">{{ fmt(modelValue.duration) }}</span>
297
+ <span class="shrink-0 pl-1 font-mono text-label-medium tabular-nums text-on-surface-variant">{{ fmt(modelValue.duration) }}</span>
298
298
  <MIconButton icon="delete" :label="t.recorderDiscard" @click="discard" />
299
299
  </template>
300
300
  <span v-else class="flex-1 text-body-medium text-on-surface-variant">{{ t.recorderStart }}</span>
@@ -305,10 +305,10 @@ defineExpose({ start, stop, pause, resume, discard })
305
305
  <MIconButton icon="delete" :label="t.recorderDiscard" @click="discard" />
306
306
  <span class="size-2.5 shrink-0 rounded-full bg-error" :class="status === 'recording' ? 'animate-pulse' : 'opacity-40'" />
307
307
  <span class="sr-only" role="status">{{ t.recorderRecording }}</span>
308
- <span class="flex h-8 min-w-0 flex-1 items-center gap-[2px]" aria-hidden="true">
309
- <span v-for="(l, i) in liveBars" :key="i" class="w-[3px] min-w-[2px] flex-1 rounded-full bg-primary transition-[height] duration-75" :style="{ height: `${Math.max(8, l * 100)}%` }" />
308
+ <span class="mr-1 flex h-8 min-w-0 flex-1 items-center justify-between gap-px overflow-hidden" aria-hidden="true">
309
+ <span v-for="(l, i) in liveBars" :key="i" class="min-w-px max-w-[3px] flex-1 rounded-full bg-primary transition-[height] duration-75" :style="{ height: `${Math.max(8, l * 100)}%` }" />
310
310
  </span>
311
- <span class="shrink-0 font-mono text-label-medium text-on-surface" aria-live="off">{{ fmt(elapsed) }}<template v-if="maxDuration"> / {{ fmt(maxDuration) }}</template></span>
311
+ <span class="shrink-0 pl-1 font-mono text-label-medium tabular-nums text-on-surface" aria-live="off">{{ fmt(elapsed) }}<template v-if="maxDuration"> / {{ fmt(maxDuration) }}</template></span>
312
312
  <MIconButton v-if="status === 'recording'" icon="pause" :label="t.recorderPause" @click="pause" />
313
313
  <MIconButton v-else icon="mic" :label="t.recorderResume" @click="resume" />
314
314
  <MIconButton icon="stop" :label="t.recorderStop" variant="filled" @click="stop" />
@@ -318,16 +318,16 @@ defineExpose({ start, stop, pause, resume, discard })
318
318
  <template v-else-if="status === 'review' && result">
319
319
  <MIconButton icon="delete" :label="t.recorderDiscard" @click="discard" />
320
320
  <MIconButton :icon="playing ? 'pause' : 'play_arrow'" :label="playing ? t.recorderPausePlayback : t.recorderPlay" @click="togglePlay" />
321
- <span class="flex h-8 min-w-0 flex-1 items-center gap-[2px]" aria-hidden="true">
321
+ <span class="mr-1 flex h-8 min-w-0 flex-1 items-center justify-between gap-px overflow-hidden" aria-hidden="true">
322
322
  <span
323
323
  v-for="(p, i) in result.peaks"
324
324
  :key="i"
325
- class="w-[3px] min-w-[2px] flex-1 rounded-full"
325
+ class="min-w-px max-w-[3px] flex-1 rounded-full"
326
326
  :class="i / result.peaks.length < played ? 'bg-primary' : 'bg-on-surface-variant/50'"
327
327
  :style="{ height: `${Math.max(12, p * 100)}%` }"
328
328
  />
329
329
  </span>
330
- <span class="shrink-0 font-mono text-label-medium text-on-surface-variant">{{ fmt(result.duration) }}</span>
330
+ <span class="shrink-0 pl-1 font-mono text-label-medium tabular-nums text-on-surface-variant">{{ fmt(result.duration) }}</span>
331
331
  <MIconButton icon="send" :label="t.recorderUse" variant="filled" @click="use" />
332
332
  </template>
333
333
  </div>