@m3ui-vue/m3ui-vue 1.6.2 → 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 (163) 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-NtkihoK6.js → MColorPickerModal-BKM1CHxr.js} +4 -4
  5. package/dist/{MColorPickerModal-NtkihoK6.js.map → MColorPickerModal-BKM1CHxr.js.map} +1 -1
  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/_useFieldValidation-Bz34IAQY.js +191 -0
  23. package/dist/_useFieldValidation-Bz34IAQY.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/MJsonEditor.vue.d.ts +23 -1
  44. package/dist/components/MMapRoute.vue.d.ts +168 -0
  45. package/dist/components/MMaskField.vue.d.ts +20 -2
  46. package/dist/components/MMentionField.vue.d.ts +13 -2
  47. package/dist/components/MMultiAutocomplete.vue.d.ts +22 -3
  48. package/dist/components/MMultiSelect.vue.d.ts +22 -3
  49. package/dist/components/MNavigationRail.vue.d.ts +1 -1
  50. package/dist/components/MNotificationCenter.vue.d.ts +2 -2
  51. package/dist/components/MNumberField.vue.d.ts +20 -2
  52. package/dist/components/MPhoneInput.vue.d.ts +19 -4
  53. package/dist/components/MPinInput.vue.d.ts +24 -3
  54. package/dist/components/MPosKeypad.vue.d.ts +2 -2
  55. package/dist/components/MRadioGroup.vue.d.ts +23 -1
  56. package/dist/components/MRating.vue.d.ts +23 -1
  57. package/dist/components/MRichTextEditor.vue.d.ts +23 -1
  58. package/dist/components/MSearchBar.vue.d.ts +1 -1
  59. package/dist/components/MSegmentedButton.vue.d.ts +23 -2
  60. package/dist/components/MSelect.vue.d.ts +22 -3
  61. package/dist/components/MSignaturePad.vue.d.ts +19 -0
  62. package/dist/components/MSlider.vue.d.ts +23 -1
  63. package/dist/components/MSwitch.vue.d.ts +23 -1
  64. package/dist/components/MTable.vue.d.ts +1 -1
  65. package/dist/components/MTagInput.vue.d.ts +20 -2
  66. package/dist/components/MText.vue.d.ts +1 -1
  67. package/dist/components/MTextField.vue.d.ts +26 -3
  68. package/dist/components/MTimePicker.vue.d.ts +24 -3
  69. package/dist/components/MTimezoneSelect.vue.d.ts +13 -2
  70. package/dist/components/MTour.vue.d.ts +2 -2
  71. package/dist/components/MTrackingTimeline.vue.d.ts +75 -0
  72. package/dist/components/MWindow.vue.d.ts +2 -2
  73. package/dist/composables/_routeGeometry.d.ts +26 -0
  74. package/dist/composables/_useFieldValidation.d.ts +91 -0
  75. package/dist/composables/mapRouting.d.ts +35 -0
  76. package/dist/composables/useLocale.d.ts +23 -0
  77. package/dist/composables/validation.d.ts +82 -0
  78. package/dist/draw.js +2 -2
  79. package/dist/flow.js +1 -1
  80. package/dist/gantt.js +2 -2
  81. package/dist/index.d.ts +5 -0
  82. package/dist/locales/index.js +154 -7
  83. package/dist/locales/index.js.map +1 -1
  84. package/dist/m3ui-vue.css +1 -1
  85. package/dist/m3ui.js +6768 -5602
  86. package/dist/m3ui.js.map +1 -1
  87. package/dist/map.d.ts +4 -0
  88. package/dist/map.js +1230 -784
  89. package/dist/map.js.map +1 -1
  90. package/dist/media.js +4 -4
  91. package/dist/pdf.js +4 -4
  92. package/dist/rich-text-editor.js +189 -146
  93. package/dist/rich-text-editor.js.map +1 -1
  94. package/dist/styles.css +1 -1
  95. package/dist/{useLocale-DaVSTdm0.js → useLocale-Dh1xZZ8i.js} +22 -1
  96. package/dist/useLocale-Dh1xZZ8i.js.map +1 -0
  97. package/package.json +1 -1
  98. package/src/__tests__/MForm.test.ts +325 -0
  99. package/src/__tests__/MMapRoute.test.ts +384 -0
  100. package/src/__tests__/MPhoneInput.test.ts +5 -2
  101. package/src/__tests__/MRichTextEditor.test.ts +2 -1
  102. package/src/__tests__/MTrackingTimeline.test.ts +66 -0
  103. package/src/__tests__/_fakeMaplibre.ts +4 -1
  104. package/src/__tests__/_osrmRoutes.ts +10 -0
  105. package/src/__tests__/attrsFallthrough.test.ts +11 -0
  106. package/src/__tests__/fieldsValidation.test.ts +229 -0
  107. package/src/__tests__/ssr.test.ts +1 -0
  108. package/src/__tests__/validation.test.ts +77 -0
  109. package/src/components/MAddressField.vue +45 -8
  110. package/src/components/MAutocomplete.vue +69 -23
  111. package/src/components/MCheckbox.vue +80 -17
  112. package/src/components/MCodeEditor.vue +59 -2
  113. package/src/components/MColorPicker.vue +65 -16
  114. package/src/components/MCountrySelect.vue +17 -3
  115. package/src/components/MCreditCardInput.vue +76 -7
  116. package/src/components/MCronField.vue +60 -10
  117. package/src/components/MDatePicker.vue +65 -16
  118. package/src/components/MDateRangePicker.vue +66 -16
  119. package/src/components/MFileUpload.vue +71 -8
  120. package/src/components/MForm.vue +208 -0
  121. package/src/components/MJsonEditor.vue +57 -3
  122. package/src/components/MMapRoute.vue +470 -0
  123. package/src/components/MMaskField.vue +55 -13
  124. package/src/components/MMentionField.vue +17 -2
  125. package/src/components/MMultiAutocomplete.vue +70 -23
  126. package/src/components/MMultiSelect.vue +70 -23
  127. package/src/components/MNumberField.vue +58 -16
  128. package/src/components/MPhoneInput.vue +60 -18
  129. package/src/components/MPinInput.vue +58 -10
  130. package/src/components/MRadioGroup.vue +65 -4
  131. package/src/components/MRating.vue +62 -6
  132. package/src/components/MRichTextEditor.vue +64 -4
  133. package/src/components/MSegmentedButton.vue +59 -2
  134. package/src/components/MSelect.vue +72 -26
  135. package/src/components/MSignaturePad.vue +71 -6
  136. package/src/components/MSlider.vue +61 -10
  137. package/src/components/MSwitch.vue +63 -8
  138. package/src/components/MTagInput.vue +67 -25
  139. package/src/components/MTextField.vue +68 -14
  140. package/src/components/MTimePicker.vue +65 -16
  141. package/src/components/MTimezoneSelect.vue +17 -3
  142. package/src/components/MTrackingTimeline.vue +257 -0
  143. package/src/composables/_routeGeometry.ts +140 -0
  144. package/src/composables/_useFieldValidation.ts +287 -0
  145. package/src/composables/mapRouting.ts +55 -0
  146. package/src/composables/useLocale.ts +46 -0
  147. package/src/composables/validation.ts +178 -0
  148. package/src/index.ts +5 -0
  149. package/src/locales/de.ts +21 -0
  150. package/src/locales/es.ts +28 -7
  151. package/src/locales/fr.ts +21 -0
  152. package/src/locales/ja.ts +21 -0
  153. package/src/locales/ko.ts +21 -0
  154. package/src/locales/pt.ts +21 -0
  155. package/src/locales/zh.ts +21 -0
  156. package/src/map.ts +4 -0
  157. package/dist/MListItem-D2cNUyzP.js.map +0 -1
  158. package/dist/MSegmentedButton-BEB4gXLA.js +0 -64
  159. package/dist/MSegmentedButton-BEB4gXLA.js.map +0 -1
  160. package/dist/MSlider-BIkA6DiE.js +0 -690
  161. package/dist/MSlider-BIkA6DiE.js.map +0 -1
  162. package/dist/MTextField-CNH-byir.js.map +0 -1
  163. 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>
@@ -6,6 +6,8 @@
6
6
  * @event debounced Emitted debounce ms after the user stops typing the search query (only when debounce > 0)
7
7
  */
8
8
  import { computed, ref, useId, onMounted, onUnmounted, watch, nextTick } from 'vue'
9
+ import { useFieldValidation, useFocusLeave } from '../composables/_useFieldValidation'
10
+ import type { ValidateOn, ValidationRule } from '../composables/validation'
9
11
  import MIcon from './MIcon.vue'
10
12
  import MIconButton from './MIconButton.vue'
11
13
  import { useFieldBg } from '../composables/useFieldBg'
@@ -37,10 +39,21 @@ const props = withDefaults(
37
39
  mode?: 'docked' | 'modal'
38
40
  /** Disables the field */
39
41
  disabled?: boolean
40
- /** Error state */
41
- error?: boolean
42
+ /** Error state. A string is also the message (`:error="errors.x"`) */
43
+ error?: boolean | string
42
44
  /** Error message shown when error is true */
43
45
  errorLabel?: string
46
+ /**
47
+ * Validation rules: functions `(value, ctx) => true | 'message'` (may be async; see the built-in `required`,
48
+ * `email`, `minLength`…) or a Standard Schema (zod, valibot…). Checked in order; the first failure is shown
49
+ */
50
+ rules?: ValidationRule | ValidationRule[]
51
+ /** When the rules are checked and shown: on leaving the field (default; live after that), while typing, or only on submit (`MForm`) */
52
+ validateOn?: ValidateOn
53
+ /** 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 */
54
+ validateDebounce?: number
55
+ /** The key of this field in its `MForm`'s values, errors and schema */
56
+ name?: string
44
57
  /** Helper text below field */
45
58
  hint?: string
46
59
  /** Marks as required — adds a red asterisk after the label */
@@ -69,7 +82,26 @@ const props = withDefaults(
69
82
  },
70
83
  )
71
84
 
72
- const emit = defineEmits<{ 'update:modelValue': [unknown]; debounced: [string] }>()
85
+ const emit = defineEmits<{ blur: []; 'update:modelValue': [unknown]; debounced: [string] }>()
86
+
87
+ const rootEl = ref<HTMLElement | null>(null)
88
+ const validation = useFieldValidation({
89
+ value: () => props.modelValue,
90
+ rules: () => props.rules,
91
+ required: () => props.required,
92
+ error: () => props.error,
93
+ errorLabel: () => props.errorLabel,
94
+ name: () => props.name,
95
+ validateOn: () => props.validateOn,
96
+ validateDebounce: () => props.validateDebounce,
97
+ disabled: () => props.disabled,
98
+ focus: () => { inputEl.value?.focus() },
99
+ el: () => inputEl.value,
100
+ setValue: (v) => emit('update:modelValue', v as unknown),
101
+ })
102
+ /** Its own `disabled` or its MForm's */
103
+ const isDisabled = validation.disabled
104
+ const { hasError, message: errorMessage, messageId } = validation
73
105
 
74
106
  const locale = useLocale()
75
107
  const id = useId()
@@ -148,7 +180,7 @@ const modalFilteredOptions = computed(() => {
148
180
  })
149
181
 
150
182
  function openDropdown() {
151
- if (props.disabled || open.value) return
183
+ if (isDisabled.value || open.value) return
152
184
  if (props.mode === 'modal') {
153
185
  modalOpen.value = true
154
186
  modalSearch.value = ''
@@ -288,20 +320,20 @@ const triggerClasses = computed(() => {
288
320
  ]
289
321
 
290
322
  if (props.variant === 'outlined') {
291
- const border = props.disabled
323
+ const border = isDisabled.value
292
324
  ? 'border-on-surface/12'
293
325
  : open.value
294
- ? (props.error ? 'border-2 border-error' : 'border-2 border-primary')
295
- : (props.error ? 'border-error' : 'border-outline hover:border-on-surface')
326
+ ? (hasError.value ? 'border-2 border-error' : 'border-2 border-primary')
327
+ : (hasError.value ? 'border-error' : 'border-outline hover:border-on-surface')
296
328
  return [...base, 'h-14 rounded-xs border bg-transparent', border].join(' ')
297
329
  }
298
330
 
299
- const border = props.disabled
331
+ const border = isDisabled.value
300
332
  ? 'border-on-surface/38'
301
333
  : open.value
302
- ? (props.error ? 'border-b-2 border-error' : 'border-b-2 border-primary')
303
- : (props.error ? 'border-error' : 'border-on-surface-variant hover:border-on-surface')
304
- const bg = props.disabled
334
+ ? (hasError.value ? 'border-b-2 border-error' : 'border-b-2 border-primary')
335
+ : (hasError.value ? 'border-error' : 'border-on-surface-variant hover:border-on-surface')
336
+ const bg = isDisabled.value
305
337
  ? 'bg-[color-mix(in_srgb,var(--color-on-surface)_4%,var(--color-surface-container-highest))]'
306
338
  : 'bg-surface-container-highest'
307
339
  return [...base, 'h-14 rounded-t-xs border-b pt-6 pb-2', bg, border].join(' ')
@@ -317,16 +349,29 @@ const labelClasses = computed(() =>
317
349
  floated: isFloated.value,
318
350
  color: [
319
351
  open.value
320
- ? (props.error ? 'text-error' : 'text-primary')
321
- : (props.error ? 'text-error' : 'text-on-surface-variant'),
352
+ ? (hasError.value ? 'text-error' : 'text-primary')
353
+ : (hasError.value ? 'text-error' : 'text-on-surface-variant'),
322
354
  'peer-disabled:text-on-surface/38',
323
355
  ].join(' '),
324
356
  }),
325
357
  )
358
+
359
+ defineExpose({
360
+ /** Checks its rules and shows the result; resolves to whether they pass */
361
+ validate: validation.validate,
362
+ /** Hides its validation error (until the next check) */
363
+ resetValidation: validation.resetValidation,
364
+ })
365
+
366
+ // Last: it watches `open`, declared above
367
+ const onFocusOut = useFocusLeave(() => rootEl.value, () => {
368
+ validation.onBlur()
369
+ emit('blur')
370
+ }, () => open.value)
326
371
  </script>
327
372
 
328
373
  <template>
329
- <div class="flex flex-col gap-1" v-bind="$attrs">
374
+ <div ref="rootEl" class="flex flex-col gap-1" v-bind="$attrs" @focusout="onFocusOut">
330
375
  <div
331
376
  ref="fieldEl"
332
377
  class="relative"
@@ -339,7 +384,7 @@ const labelClasses = computed(() =>
339
384
  class="pointer-events-none absolute left-3.5"
340
385
  :class="[
341
386
  variant === 'filled' ? 'top-4.5' : 'top-4',
342
- disabled ? 'text-on-surface/38' : 'text-on-surface-variant',
387
+ isDisabled ? 'text-on-surface/38' : 'text-on-surface-variant',
343
388
  ]"
344
389
  >
345
390
  <MIcon :name="leadingIcon" :size="24" />
@@ -349,10 +394,11 @@ const labelClasses = computed(() =>
349
394
  <input
350
395
  :id="id"
351
396
  ref="inputEl"
397
+ :aria-describedby="errorMessage || hint ? messageId : undefined"
352
398
  type="text"
353
399
  :value="displayValue"
354
400
  :placeholder="!label ? placeholder : undefined"
355
- :disabled="disabled"
401
+ :disabled="isDisabled"
356
402
  autocomplete="off"
357
403
  role="combobox"
358
404
  aria-autocomplete="list"
@@ -360,13 +406,13 @@ const labelClasses = computed(() =>
360
406
  :aria-controls="open || modalOpen ? listId : undefined"
361
407
  :aria-activedescendant="activeOption"
362
408
  :aria-required="required || undefined"
363
- :aria-invalid="error || undefined"
364
- :aria-disabled="disabled"
409
+ :aria-invalid="hasError || undefined"
410
+ :aria-disabled="isDisabled"
365
411
  v-overflow-title
366
412
  :class="[
367
413
  triggerClasses,
368
414
  'peer outline-none text-on-surface cursor-text',
369
- error ? 'caret-error' : 'caret-primary',
415
+ hasError ? 'caret-error' : 'caret-primary',
370
416
  'disabled:pointer-events-none disabled:cursor-not-allowed disabled:text-on-surface/38',
371
417
  ]"
372
418
  @focus="onInputFocus"
@@ -383,7 +429,7 @@ const labelClasses = computed(() =>
383
429
  <!-- Clear button -->
384
430
  <button
385
431
  :aria-label="locale.clear"
386
- v-if="clearable && hasValue && !disabled"
432
+ v-if="clearable && hasValue && !isDisabled"
387
433
  type="button"
388
434
  class="absolute right-9 top-1/2 -translate-y-1/2 flex h-6 w-6 cursor-pointer items-center justify-center rounded-full text-on-surface-variant transition-colors hover:bg-on-surface/8 hover:text-on-surface"
389
435
  @click.stop="emit('update:modelValue', null); closeDropdown()"
@@ -399,14 +445,14 @@ const labelClasses = computed(() =>
399
445
  class="transition-transform duration-200"
400
446
  :class="[
401
447
  open || modalOpen ? 'rotate-180' : '',
402
- disabled ? 'text-on-surface/38' : 'text-on-surface-variant',
448
+ isDisabled ? 'text-on-surface/38' : 'text-on-surface-variant',
403
449
  ]"
404
450
  />
405
451
  </div>
406
452
  </div>
407
453
 
408
- <p v-if="error && errorLabel" class="px-4 text-body-small text-error">{{ errorLabel }}</p>
409
- <p v-else-if="hint" class="px-4 text-body-small text-on-surface-variant">{{ hint }}</p>
454
+ <p v-if="errorMessage" :id="messageId" role="alert" class="px-4 text-body-small text-error">{{ errorMessage }}</p>
455
+ <p v-else-if="hint" :id="messageId" class="px-4 text-body-small text-on-surface-variant">{{ hint }}</p>
410
456
  </div>
411
457
 
412
458
  <!-- Docked dropdown -->