@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
@@ -4,10 +4,14 @@
4
4
  *
5
5
  * @slot default Custom label content — overrides the label prop when provided
6
6
  * @event update:modelValue Emitted with the new checked state.
7
+ * @event blur Emitted when the checkbox loses focus
7
8
  */
9
+ import { ref } from "vue";
8
10
  import MIcon from "./MIcon.vue";
11
+ import { useFieldValidation } from "../composables/_useFieldValidation";
12
+ import type { ValidateOn, ValidationRule } from "../composables/validation";
9
13
 
10
- withDefaults(
14
+ const props = withDefaults(
11
15
  defineProps<{
12
16
  /** Checked state (v-model) */
13
17
  modelValue: boolean;
@@ -21,11 +25,45 @@ withDefaults(
21
25
  color?: "primary" | "secondary" | "tertiary" | "error";
22
26
  /** Accessible name for the input when there's no visible label (e.g. a list row's checkbox). */
23
27
  ariaLabel?: string;
28
+ /** Error state. A string is also the message */
29
+ error?: boolean | string;
30
+ /** Error message shown when `error` is true */
31
+ errorLabel?: string;
32
+ /** Must be ticked, inside an `MForm` or with `rules` */
33
+ required?: boolean;
34
+ /** Validation rules (functions or a Standard Schema); see `MForm` */
35
+ rules?: ValidationRule | ValidationRule[];
36
+ /** When the rules are checked and shown: on leaving it (default), on change, or only on submit */
37
+ validateOn?: ValidateOn;
38
+ /** 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 */
39
+ validateDebounce?: number;
40
+ /** The key of this field in its `MForm` */
41
+ name?: string;
24
42
  }>(),
25
43
  { indeterminate: false, disabled: false, color: "primary" },
26
44
  );
27
45
 
28
- const emit = defineEmits<{ "update:modelValue": [boolean] }>();
46
+ const emit = defineEmits<{ "update:modelValue": [boolean]; blur: [FocusEvent] }>();
47
+
48
+ const inputEl = ref<HTMLInputElement | null>(null);
49
+
50
+ const validation = useFieldValidation({
51
+ value: () => props.modelValue,
52
+ rules: () => props.rules,
53
+ required: () => props.required,
54
+ error: () => props.error,
55
+ errorLabel: () => props.errorLabel,
56
+ name: () => props.name,
57
+ validateOn: () => props.validateOn,
58
+ validateDebounce: () => props.validateDebounce,
59
+ disabled: () => props.disabled,
60
+ focus: () => { inputEl.value?.focus() },
61
+ el: () => inputEl.value,
62
+ setValue: (v) => emit("update:modelValue", v as boolean),
63
+ });
64
+ /** Its own `disabled` or its MForm's */
65
+ const isDisabled = validation.disabled;
66
+ const { hasError, message: errorMessage, messageId } = validation;
29
67
 
30
68
  // Same 4 named colors + fallback shape as MRadio's checkedColor map. M3's real
31
69
  // CheckboxTokens only define Primary (SelectedContainerColor) and Error (as an error
@@ -45,19 +83,33 @@ const checkedBgClasses: Record<string, string> = {
45
83
  tertiary: "bg-tertiary",
46
84
  error: "bg-error",
47
85
  };
86
+
87
+ // CheckboxTokens' error state: Error container / OnError icon when ticked, Error outline when not
88
+ const errorCheckedClasses = "border-error bg-error text-on-error";
89
+
90
+ defineExpose({
91
+ /** Checks its rules and shows the result; resolves to whether they pass */
92
+ validate: validation.validate,
93
+ /** Hides its validation error (until the next check) */
94
+ resetValidation: validation.resetValidation,
95
+ });
48
96
  </script>
49
97
 
50
98
  <template>
51
99
  <label
52
- class="group inline-flex items-center gap-2 select-none"
53
- :class="disabled ? 'cursor-not-allowed' : 'cursor-pointer'"
100
+ class="group inline-flex gap-2 select-none"
101
+ :class="[isDisabled ? 'cursor-not-allowed' : 'cursor-pointer', errorMessage ? 'items-start' : 'items-center']"
54
102
  >
55
103
  <!--
56
104
  CheckboxTokens.StateLayerSize = 40dp (was 48px), StateLayerShape = CornerFull. The
57
105
  negative margin cancels the touch target's own overhang past the visible 18px box
58
106
  (40-18)/2 = 11px per side, so it doesn't push the label text over.
59
107
  -->
60
- <span class="relative -m-[11px] inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-full">
108
+ <!-- With a message under the text, the box lines up with the text's first line instead of the middle -->
109
+ <span
110
+ class="relative -m-[11px] inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-full"
111
+ :style="errorMessage ? { marginTop: '-8px' } : undefined"
112
+ >
61
113
  <!--
62
114
  Input must stay nested INSIDE this `relative` span (a true sibling of the state-layer
63
115
  /focus-ring spans below, satisfying `peer-*`'s sibling-combinator requirement, but not
@@ -72,9 +124,15 @@ const checkedBgClasses: Record<string, string> = {
72
124
  type="checkbox"
73
125
  class="peer sr-only"
74
126
  :checked="modelValue"
75
- :disabled="disabled"
127
+ :disabled="isDisabled"
128
+ ref="inputEl"
129
+ :name="name"
130
+ :required="required"
76
131
  :aria-label="ariaLabel"
132
+ :aria-invalid="hasError || undefined"
133
+ :aria-describedby="errorMessage ? messageId : undefined"
77
134
  @change="emit('update:modelValue', !modelValue)"
135
+ @blur="validation.onBlur(); emit('blur', $event)"
78
136
  />
79
137
  <!--
80
138
  Hover/press state layer (8%/12%), tinted with the checkbox's own indicator color
@@ -85,22 +143,24 @@ const checkedBgClasses: Record<string, string> = {
85
143
  the small 18px glyph itself.
86
144
  -->
87
145
  <span
88
- v-if="!disabled"
146
+ v-if="!isDisabled"
89
147
  class="pointer-events-none absolute inset-0 rounded-full opacity-0 transition-opacity duration-150 group-hover:opacity-[0.08] group-active:opacity-[0.12]"
90
- :class="modelValue || indeterminate ? checkedBgClasses[color] : 'bg-on-surface'"
148
+ :class="hasError ? 'bg-error' : modelValue || indeterminate ? checkedBgClasses[color] : 'bg-on-surface'"
91
149
  />
92
150
  <!-- Keyboard-focus ring (FocusIndicatorColor = secondary) -->
93
151
  <span
94
- v-if="!disabled"
152
+ v-if="!isDisabled"
95
153
  class="pointer-events-none absolute inset-0 rounded-full ring-0 ring-secondary transition-[box-shadow] duration-150 peer-focus-visible:ring-2"
96
154
  />
97
155
 
98
156
  <span
99
157
  class="relative inline-flex h-4.5 w-4.5 items-center justify-center rounded-[2px] border-2 transition-colors"
100
158
  :class="
101
- disabled
159
+ isDisabled
102
160
  ? (modelValue || indeterminate ? 'border-on-surface/38 bg-on-surface/38 text-surface' : 'border-on-surface/38 text-transparent')
103
- : (modelValue || indeterminate ? checkedClasses[color] : 'border-on-surface-variant text-transparent group-hover:border-on-surface group-active:border-on-surface')
161
+ : hasError
162
+ ? (modelValue || indeterminate ? errorCheckedClasses : 'border-error text-transparent')
163
+ : (modelValue || indeterminate ? checkedClasses[color] : 'border-on-surface-variant text-transparent group-hover:border-on-surface group-active:border-on-surface')
104
164
  "
105
165
  >
106
166
  <MIcon
@@ -111,12 +171,15 @@ const checkedBgClasses: Record<string, string> = {
111
171
  />
112
172
  </span>
113
173
  </span>
114
- <span
115
- v-if="label || $slots.default"
116
- class="text-body-large"
117
- :class="disabled ? 'text-on-surface/38' : 'text-on-surface'"
118
- >
119
- <slot>{{ label }}</slot>
174
+ <span v-if="label || $slots.default || errorMessage" class="flex flex-col">
175
+ <span
176
+ v-if="label || $slots.default"
177
+ class="text-body-large"
178
+ :class="isDisabled ? 'text-on-surface/38' : 'text-on-surface'"
179
+ >
180
+ <slot>{{ label }}</slot><span v-if="required" class="text-error">&nbsp;*</span>
181
+ </span>
182
+ <span v-if="errorMessage" :id="messageId" role="alert" class="text-body-small text-error">{{ errorMessage }}</span>
120
183
  </span>
121
184
  </label>
122
185
  </template>
@@ -4,8 +4,11 @@
4
4
  *
5
5
  * @slot actions Extra controls rendered in the header bar, before the built-in copy button
6
6
  * @event update:modelValue Emitted on every document change — powers v-model
7
+ * @event blur Emitted when focus leaves the editor
7
8
  */
8
9
  import { ref, watch, onMounted, onBeforeUnmount, computed } from 'vue'
10
+ import { useFieldValidation, useFocusLeave } from '../composables/_useFieldValidation'
11
+ import type { ValidateOn, ValidationRule } from '../composables/validation'
9
12
  import MIcon from './MIcon.vue'
10
13
 
11
14
  type Language = 'javascript' | 'typescript' | 'json' | 'html' | 'css' | 'python' | 'vue' | 'c' | 'cpp' | 'rust' | 'asm' | 'plain'
@@ -28,6 +31,20 @@ const props = withDefaults(
28
31
  maxHeight?: string
29
32
  /** Placeholder text shown via CodeMirror when the editor is empty */
30
33
  placeholder?: string
34
+ /** Error state. A string is also the message */
35
+ error?: boolean | string
36
+ /** Error message shown when `error` is true */
37
+ errorLabel?: string
38
+ /** Inside an `MForm` or with `rules`, the code can't be blank */
39
+ required?: boolean
40
+ /** Validation rules (functions or a Standard Schema); see `MForm` */
41
+ rules?: ValidationRule | ValidationRule[]
42
+ /** When the rules are checked and shown: on leaving it (default), on change, or only on submit */
43
+ validateOn?: ValidateOn
44
+ /** 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 */
45
+ validateDebounce?: number
46
+ /** The key of this field in its `MForm` */
47
+ name?: string
31
48
  /** Word wrap */
32
49
  wrap?: boolean
33
50
  }>(),
@@ -42,10 +59,34 @@ const props = withDefaults(
42
59
  },
43
60
  )
44
61
 
45
- const emit = defineEmits<{ 'update:modelValue': [string] }>()
62
+ // Editor + its message: attributes go on the editor
63
+ defineOptions({ inheritAttrs: false })
64
+
65
+ const emit = defineEmits<{ 'update:modelValue': [string]; blur: [] }>()
46
66
 
47
67
  const containerRef = ref<HTMLElement | null>(null)
48
68
  let view: any = null
69
+ const rootEl = ref<HTMLElement | null>(null)
70
+
71
+ const validation = useFieldValidation({
72
+ value: () => props.modelValue,
73
+ rules: () => props.rules,
74
+ required: () => props.required,
75
+ error: () => props.error,
76
+ errorLabel: () => props.errorLabel,
77
+ name: () => props.name,
78
+ validateOn: () => props.validateOn,
79
+ validateDebounce: () => props.validateDebounce,
80
+ disabled: () => props.readonly,
81
+ focus: () => { view?.focus() },
82
+ el: () => rootEl.value,
83
+ setValue: (v) => emit('update:modelValue', v as string),
84
+ })
85
+ const { hasError, message: errorMessage, messageId } = validation
86
+ const onFocusOut = useFocusLeave(() => rootEl.value, () => {
87
+ validation.onBlur()
88
+ emit('blur')
89
+ })
49
90
  let cmModules: any = null
50
91
  const copied = ref(false)
51
92
 
@@ -218,10 +259,25 @@ watch(() => props.modelValue, (val) => {
218
259
  watch([() => props.language, () => props.theme, () => props.readonly, () => props.lineNumbers, () => props.wrap, () => props.placeholder], createEditor)
219
260
 
220
261
  onBeforeUnmount(() => view?.destroy())
262
+
263
+ defineExpose({
264
+ /** Checks its rules and shows the result; resolves to whether they pass */
265
+ validate: validation.validate,
266
+ /** Hides its validation error (until the next check) */
267
+ resetValidation: validation.resetValidation,
268
+ })
221
269
  </script>
222
270
 
223
271
  <template>
224
- <div class="flex flex-col overflow-hidden rounded-lg border border-outline-variant">
272
+ <div
273
+ ref="rootEl"
274
+ v-bind="$attrs"
275
+ class="flex flex-col overflow-hidden rounded-lg border"
276
+ :class="hasError ? 'border-error' : 'border-outline-variant'"
277
+ :aria-invalid="hasError || undefined"
278
+ :aria-describedby="errorMessage ? messageId : undefined"
279
+ @focusout="onFocusOut"
280
+ >
225
281
  <!-- Header bar -->
226
282
  <div class="flex items-center justify-between border-b border-outline-variant bg-surface-container px-4 py-2">
227
283
  <span class="text-label-medium text-on-surface-variant">{{ langLabel }}</span>
@@ -246,6 +302,7 @@ onBeforeUnmount(() => view?.destroy())
246
302
  :style="{ minHeight, maxHeight }"
247
303
  />
248
304
  </div>
305
+ <p v-if="errorMessage" :id="messageId" role="alert" class="mt-1 px-4 text-body-small text-error">{{ errorMessage }}</p>
249
306
  </template>
250
307
 
251
308
  <style scoped>
@@ -7,6 +7,8 @@
7
7
  * @event update:modelValue Emitted with the picked color, live while dragging or typing.
8
8
  */
9
9
  import { nextTick, onUnmounted, ref, watch } from 'vue'
10
+ import { useFieldValidation, useFocusLeave } from '../composables/_useFieldValidation'
11
+ import type { ValidateOn, ValidationRule } from '../composables/validation'
10
12
  import MIcon from './MIcon.vue'
11
13
  import MColorPanel from './_MColorPanel.vue'
12
14
  import { useFieldBg } from '../composables/useFieldBg'
@@ -32,10 +34,23 @@ const props = withDefaults(defineProps<{
32
34
  eyedropper?: boolean
33
35
  /** Disables the picker */
34
36
  disabled?: boolean
35
- /** Error state */
36
- error?: boolean
37
+ /** Error state. A string is also the message (`:error="errors.x"`) */
38
+ error?: boolean | string
37
39
  /** Error message shown when error is true */
38
40
  errorLabel?: string
41
+ /** Marks as required — adds a red asterisk after the label; inside an `MForm` or with `rules`, also validates it */
42
+ required?: boolean
43
+ /**
44
+ * Validation rules: functions `(value, ctx) => true | 'message'` (may be async; see the built-in `required`,
45
+ * `email`, `minLength`…) or a Standard Schema (zod, valibot…). Checked in order; the first failure is shown
46
+ */
47
+ rules?: ValidationRule | ValidationRule[]
48
+ /** When the rules are checked and shown: on leaving the field (default; live after that), while typing, or only on submit (`MForm`) */
49
+ validateOn?: ValidateOn
50
+ /** 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 */
51
+ validateDebounce?: number
52
+ /** The key of this field in its `MForm`'s values, errors and schema */
53
+ name?: string
39
54
  /** Hint text below the field */
40
55
  hint?: string
41
56
  /** Overrides the auto-detected background color used to cut the floating label out of the border */
@@ -48,7 +63,26 @@ const props = withDefaults(defineProps<{
48
63
  eyedropper: true,
49
64
  })
50
65
 
51
- const emit = defineEmits<{ 'update:modelValue': [string] }>()
66
+ const emit = defineEmits<{ blur: []; 'update:modelValue': [string] }>()
67
+
68
+ const rootEl = ref<HTMLElement | null>(null)
69
+ const validation = useFieldValidation({
70
+ value: () => props.modelValue,
71
+ rules: () => props.rules,
72
+ required: () => props.required,
73
+ error: () => props.error,
74
+ errorLabel: () => props.errorLabel,
75
+ name: () => props.name,
76
+ validateOn: () => props.validateOn,
77
+ validateDebounce: () => props.validateDebounce,
78
+ disabled: () => props.disabled,
79
+ focus: () => { buttonEl.value?.focus() },
80
+ el: () => buttonEl.value,
81
+ setValue: (v) => emit('update:modelValue', v as string),
82
+ })
83
+ /** Its own `disabled` or its MForm's */
84
+ const isDisabled = validation.disabled
85
+ const { hasError, message: errorMessage, messageId } = validation
52
86
  const t = useLocale()
53
87
 
54
88
  const open = ref(false)
@@ -126,23 +160,38 @@ watch(open, async (v) => {
126
160
  onUnmounted(() => {
127
161
  document.removeEventListener('mousedown', onOut)
128
162
  })
163
+
164
+ defineExpose({
165
+ /** Checks its rules and shows the result; resolves to whether they pass */
166
+ validate: validation.validate,
167
+ /** Hides its validation error (until the next check) */
168
+ resetValidation: validation.resetValidation,
169
+ })
170
+
171
+ // Last: it watches `open`, declared above
172
+ const onFocusOut = useFocusLeave(() => rootEl.value, () => {
173
+ validation.onBlur()
174
+ emit('blur')
175
+ }, () => open.value)
129
176
  </script>
130
177
 
131
178
  <template>
132
- <div class="flex flex-col gap-1">
179
+ <div ref="rootEl" class="flex flex-col gap-1" @focusout="onFocusOut">
133
180
  <div ref="triggerEl" class="relative mt-2" :style="{ '--field-bg': resolvedFieldBg }">
134
181
  <button
135
182
  ref="buttonEl"
183
+ :aria-invalid="hasError || undefined"
184
+ :aria-describedby="errorMessage || hint ? messageId : undefined"
136
185
  type="button"
137
186
  aria-haspopup="dialog"
138
187
  :aria-expanded="open"
139
- :disabled="disabled"
188
+ :disabled="isDisabled"
140
189
  class="flex h-14 w-full items-center gap-3 rounded-xs border bg-transparent px-4 text-left text-body-large outline-none transition-[border-color,border-width] duration-150"
141
190
  :class="[
142
- disabled ? 'cursor-not-allowed border-on-surface/12' : 'cursor-pointer',
143
- !disabled && (open
144
- ? error ? 'border-2 border-error' : 'border-2 border-primary'
145
- : error
191
+ isDisabled ? 'cursor-not-allowed border-on-surface/12' : 'cursor-pointer',
192
+ !isDisabled && (open
193
+ ? hasError ? 'border-2 border-error' : 'border-2 border-primary'
194
+ : hasError
146
195
  ? 'border-error focus-visible:border-2'
147
196
  : 'border-outline hover:border-on-surface focus-visible:border-2 focus-visible:border-primary'),
148
197
  ]"
@@ -150,27 +199,27 @@ onUnmounted(() => {
150
199
  >
151
200
  <span
152
201
  class="m3-cp-swatch h-6 w-6 shrink-0 rounded-full"
153
- :class="disabled ? 'opacity-38' : ''"
202
+ :class="isDisabled ? 'opacity-38' : ''"
154
203
  :style="{ background: `linear-gradient(${modelValue}, ${modelValue}), repeating-conic-gradient(#d4d4d4 0 25%, #fff 0 50%) 0 0 / 8px 8px` }"
155
204
  />
156
- <span v-overflow-title class="min-w-0 truncate flex-1 font-mono" :class="disabled ? 'text-on-surface/38' : 'text-on-surface'">{{ modelValue }}</span>
205
+ <span v-overflow-title class="min-w-0 truncate flex-1 font-mono" :class="isDisabled ? 'text-on-surface/38' : 'text-on-surface'">{{ modelValue }}</span>
157
206
  <MIcon
158
207
  name="palette"
159
208
  :size="24"
160
209
  class="shrink-0 transition-colors"
161
- :class="disabled ? 'text-on-surface/38' : open ? (error ? 'text-error' : 'text-primary') : 'text-on-surface-variant'"
210
+ :class="isDisabled ? 'text-on-surface/38' : open ? (hasError ? 'text-error' : 'text-primary') : 'text-on-surface-variant'"
162
211
  />
163
212
  </button>
164
213
  <label
165
214
  v-if="label"
166
- :class="[OUTLINED_FLOATED_LABEL, 'transition-colors', disabled ? 'text-on-surface/38' : open ? (error ? 'text-error' : 'text-primary') : error ? 'text-error' : 'text-on-surface-variant']"
215
+ :class="[OUTLINED_FLOATED_LABEL, 'transition-colors', isDisabled ? 'text-on-surface/38' : open ? (hasError ? 'text-error' : 'text-primary') : hasError ? 'text-error' : 'text-on-surface-variant']"
167
216
  >
168
- {{ label }}
217
+ {{ label }}<span v-if="required" class="text-error">&nbsp;*</span>
169
218
  </label>
170
219
  </div>
171
220
 
172
- <p v-if="error && errorLabel" class="px-4 text-body-small text-error">{{ errorLabel }}</p>
173
- <p v-else-if="hint" class="px-4 text-body-small text-on-surface-variant">{{ hint }}</p>
221
+ <p v-if="errorMessage" :id="messageId" role="alert" class="px-4 text-body-small text-error">{{ errorMessage }}</p>
222
+ <p v-else-if="hint" :id="messageId" class="px-4 text-body-small text-on-surface-variant">{{ hint }}</p>
174
223
 
175
224
  <Teleport to="body">
176
225
  <Transition name="m3-cp-drop">
@@ -7,6 +7,7 @@
7
7
  * @event update:modelValue A country was picked (its code), or cleared (null)
8
8
  */
9
9
  import { computed } from 'vue'
10
+ import type { ValidateOn, ValidationRule } from '../composables/validation'
10
11
  import MAutocomplete from './MAutocomplete.vue'
11
12
  import { useLocale } from '../composables/useLocale'
12
13
  import { flagEmoji } from '../composables/phoneNumber'
@@ -32,10 +33,18 @@ const props = withDefaults(
32
33
  clearable?: boolean
33
34
  /** Helper text below the field */
34
35
  hint?: string
35
- /** Error state */
36
- error?: boolean
36
+ /** Error state. A string is also the message */
37
+ error?: boolean | string
37
38
  /** Error message shown when `error` is true */
38
39
  errorLabel?: string
40
+ /** Validation rules (functions or a Standard Schema); see `MForm` */
41
+ rules?: ValidationRule | ValidationRule[]
42
+ /** When the rules are checked and shown: on leaving the field (default), while typing, or only on submit */
43
+ validateOn?: ValidateOn
44
+ /** 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 */
45
+ validateDebounce?: number
46
+ /** The key of this field in its `MForm` */
47
+ name?: string
39
48
  /** Marks it as required */
40
49
  required?: boolean
41
50
  /** Disables the field */
@@ -44,7 +53,7 @@ const props = withDefaults(
44
53
  { modelValue: null, flags: true, variant: 'filled', mode: 'docked', clearable: false },
45
54
  )
46
55
 
47
- const emit = defineEmits<{ 'update:modelValue': [code: string | null] }>()
56
+ const emit = defineEmits<{ blur: []; 'update:modelValue': [code: string | null] }>()
48
57
 
49
58
  const t = useLocale()
50
59
 
@@ -81,6 +90,11 @@ const options = computed(() => {
81
90
  :hint="hint"
82
91
  :error="error"
83
92
  :error-label="errorLabel"
93
+ :rules="rules"
94
+ :validate-on="validateOn"
95
+ :validate-debounce="validateDebounce"
96
+ :name="name"
97
+ @blur="emit('blur')"
84
98
  :required="required"
85
99
  :disabled="disabled"
86
100
  leading-icon="public"
@@ -24,8 +24,11 @@ export type CreditCardField = 'number' | 'expiry' | 'cvc' | 'name'
24
24
  * @event update:modelValue Emitted on every change — powers v-model
25
25
  * @event complete Emitted when every field becomes valid, with the value
26
26
  * @event brand Emitted when the detected network changes
27
+ * @event blur Emitted when focus leaves the card fields
27
28
  */
28
- import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
29
+ import { computed, nextTick, onMounted, provide, reactive, ref, watch } from 'vue'
30
+ import { FORM_KEY, useFieldValidation, useFocusLeave, type FormContext } from '../composables/_useFieldValidation'
31
+ import type { ValidateOn, ValidationRule } from '../composables/validation'
29
32
  import MTextField from './MTextField.vue'
30
33
  import { useLocale } from '../composables/useLocale'
31
34
  import {
@@ -54,6 +57,20 @@ const props = withDefaults(
54
57
  errors?: Partial<Record<CreditCardField, string>>
55
58
  /** Disables every field */
56
59
  disabled?: boolean
60
+ /** Error state for the whole card (e.g. a decline). A string is also the message */
61
+ error?: boolean | string
62
+ /** Error message shown when `error` is true */
63
+ errorLabel?: string
64
+ /** Inside an `MForm` or with `rules`, an empty card fails (an empty optional card passes; a half-typed one never does) */
65
+ required?: boolean
66
+ /** More validation rules on the whole value (functions or a Standard Schema); see `MForm` */
67
+ rules?: ValidationRule | ValidationRule[]
68
+ /** When the rules are checked and shown: on leaving the card fields (default), while typing, or only on submit */
69
+ validateOn?: ValidateOn
70
+ /** 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 */
71
+ validateDebounce?: number
72
+ /** The key of the card value in its `MForm` */
73
+ name?: string
57
74
  }>(),
58
75
  {
59
76
  preview: true,
@@ -68,6 +85,7 @@ const emit = defineEmits<{
68
85
  'update:modelValue': [CreditCardValue]
69
86
  complete: [CreditCardValue]
70
87
  brand: [CardBrand]
88
+ blur: []
71
89
  }>()
72
90
 
73
91
  const numberField = ref<InstanceType<typeof MTextField> | null>(null)
@@ -101,6 +119,50 @@ const messages: Record<CreditCardField, () => string> = {
101
119
  name: () => '',
102
120
  }
103
121
 
122
+ const isBlank = (v: CreditCardValue) => !v.number && !v.expiry && !v.cvc && !v.name?.trim()
123
+ // The card's own checks are one more rule: an empty card passes unless required, anything typed must be valid
124
+ const cardRule: ValidationRule<CreditCardValue> = (v) => {
125
+ if (isBlank(v ?? ({} as CreditCardValue)) || valid.value) return true
126
+ const bad = (['number', 'expiry', 'cvc', 'name'] as const).find((f) => !validity.value[f])!
127
+ return messages[bad]() || locale.validationRequired
128
+ }
129
+ const rootEl = ref<HTMLElement | null>(null)
130
+ const touchAll = () => { touched.number = touched.expiry = touched.cvc = touched.name = true }
131
+ const validation = useFieldValidation({
132
+ value: () => props.modelValue,
133
+ rules: () => [...(props.rules ? (Array.isArray(props.rules) ? props.rules : [props.rules]) : []), cardRule],
134
+ required: () => props.required,
135
+ error: () => props.error,
136
+ errorLabel: () => props.errorLabel,
137
+ name: () => props.name,
138
+ validateOn: () => props.validateOn,
139
+ validateDebounce: () => props.validateDebounce,
140
+ disabled: () => props.disabled,
141
+ focus: () => {
142
+ const bad = (['number', 'name', 'expiry', 'cvc'] as const).find((f) => !!errorFor(f)) ?? 'number'
143
+ ;({ number: numberField, expiry: expiryField, cvc: cvcField, name: nameField })[bad].value?.focus()
144
+ },
145
+ el: () => rootEl.value,
146
+ setValue: (v) => emit('update:modelValue', v as CreditCardValue),
147
+ isEmpty: (v) => isBlank(v as CreditCardValue),
148
+ onValidate: touchAll,
149
+ })
150
+ /** Its own `disabled` or its MForm's */
151
+ const isDisabled = validation.disabled
152
+ const { message: cardMessage, messageId } = validation
153
+ // Leaving the card (not moving between its fields) shows every field's error, like a submit
154
+ const onCardLeave = useFocusLeave(() => rootEl.value, () => {
155
+ touchAll()
156
+ validation.onBlur()
157
+ emit('blur')
158
+ })
159
+ // Its MTextFields are its own: the form sees one field, the card
160
+ provide(FORM_KEY, null as unknown as FormContext)
161
+ /** A message for the whole card (from outside or the consumer's rules), when no field already shows one */
162
+ const cardError = computed(() =>
163
+ cardMessage.value && !(['number', 'expiry', 'cvc', 'name'] as const).some((f) => errorFor(f)) ? cardMessage.value : null,
164
+ )
165
+
104
166
  function errorFor(field: CreditCardField): string | undefined {
105
167
  if (props.errors?.[field]) return props.errors[field]
106
168
  if (!touched[field] || validity.value[field]) return undefined
@@ -222,9 +284,15 @@ defineExpose({
222
284
  valid,
223
285
  /** Shows the errors of every field (as if each had been visited) and returns whether all are valid */
224
286
  validate: () => {
225
- touched.number = touched.expiry = touched.cvc = touched.name = true
287
+ touchAll()
288
+ void validation.validate()
226
289
  return valid.value
227
290
  },
291
+ /** Hides every error until the fields are left again */
292
+ resetValidation: () => {
293
+ touched.number = touched.expiry = touched.cvc = touched.name = false
294
+ validation.resetValidation()
295
+ },
228
296
  /** Focuses a field (the number by default) */
229
297
  focus: (field: CreditCardField = 'number') =>
230
298
  ({ number: numberField, expiry: expiryField, cvc: cvcField, name: nameField })[field].value?.focus(),
@@ -232,7 +300,7 @@ defineExpose({
232
300
  </script>
233
301
 
234
302
  <template>
235
- <div class="flex flex-col gap-4">
303
+ <div ref="rootEl" class="flex flex-col gap-4" @focusout="onCardLeave">
236
304
  <div v-if="preview" class="m3-cc-preview mx-auto w-full max-w-[340px]" aria-hidden="true">
237
305
  <div class="m3-cc-preview__inner relative aspect-[1.586]" :class="{ 'is-flipped': cvcFocused }">
238
306
  <!-- Front -->
@@ -269,7 +337,7 @@ defineExpose({
269
337
  :model-value="formattedNumber"
270
338
  :label="locale.cardNumber"
271
339
  :variant="variant"
272
- :disabled="disabled"
340
+ :disabled="isDisabled"
273
341
  autocomplete="cc-number"
274
342
  leading-icon="credit_card"
275
343
  :error="!!errorFor('number')"
@@ -283,7 +351,7 @@ defineExpose({
283
351
  :model-value="modelValue.name ?? ''"
284
352
  :label="locale.cardName"
285
353
  :variant="variant"
286
- :disabled="disabled"
354
+ :disabled="isDisabled"
287
355
  autocomplete="cc-name"
288
356
  :error="!!errors?.name"
289
357
  :error-label="errors?.name"
@@ -297,7 +365,7 @@ defineExpose({
297
365
  :model-value="modelValue.expiry ?? ''"
298
366
  :label="locale.cardExpiry"
299
367
  :variant="variant"
300
- :disabled="disabled"
368
+ :disabled="isDisabled"
301
369
  autocomplete="cc-exp"
302
370
  :error="!!errorFor('expiry')"
303
371
  :error-label="errorFor('expiry')"
@@ -310,7 +378,7 @@ defineExpose({
310
378
  :model-value="modelValue.cvc ?? ''"
311
379
  :label="locale.cardCvc"
312
380
  :variant="variant"
313
- :disabled="disabled"
381
+ :disabled="isDisabled"
314
382
  autocomplete="cc-csc"
315
383
  :error="!!errorFor('cvc')"
316
384
  :error-label="errorFor('cvc')"
@@ -319,6 +387,7 @@ defineExpose({
319
387
  </div>
320
388
  </div>
321
389
  </div>
390
+ <p v-if="cardError" :id="messageId" role="alert" class="px-4 text-body-small text-error">{{ cardError }}</p>
322
391
  </div>
323
392
  </template>
324
393