@m3ui-vue/m3ui-vue 1.6.2 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/dist/API.md +1224 -28
  2. package/dist/{MColorPickerModal-NtkihoK6.js → MColorPickerModal-H8nuX0Wu.js} +3 -4
  3. package/dist/{MColorPickerModal-NtkihoK6.js.map → MColorPickerModal-H8nuX0Wu.js.map} +1 -1
  4. package/dist/MDialog-B42Mhn8W.js +331 -0
  5. package/dist/MDialog-B42Mhn8W.js.map +1 -0
  6. package/dist/{MListItem-D2cNUyzP.js → MListItem-DiOAxaN7.js} +431 -325
  7. package/dist/MListItem-DiOAxaN7.js.map +1 -0
  8. package/dist/{MLoadingIndicator-DWUj0BAB.js → MLoadingIndicator-CuTZYFFj.js} +2 -2
  9. package/dist/{MLoadingIndicator-DWUj0BAB.js.map → MLoadingIndicator-CuTZYFFj.js.map} +1 -1
  10. package/dist/{MSeekBar-C4cn9RIF.js → MSeekBar-BCDQTx2t.js} +2 -2
  11. package/dist/{MSeekBar-C4cn9RIF.js.map → MSeekBar-BCDQTx2t.js.map} +1 -1
  12. package/dist/MSegmentedButton-BXzRsg1S.js +105 -0
  13. package/dist/MSegmentedButton-BXzRsg1S.js.map +1 -0
  14. package/dist/MSignaturePad-BTqGaPXA.js +313 -0
  15. package/dist/MSignaturePad-BTqGaPXA.js.map +1 -0
  16. package/dist/MSlider-D_O8J9YH.js +739 -0
  17. package/dist/MSlider-D_O8J9YH.js.map +1 -0
  18. package/dist/{MSpinner-DZkXZJpc.js → MSpinner-UCdtSOHP.js} +2 -2
  19. package/dist/{MSpinner-DZkXZJpc.js.map → MSpinner-UCdtSOHP.js.map} +1 -1
  20. package/dist/{MTextField-CNH-byir.js → MTextField-CYk9yFvi.js} +162 -115
  21. package/dist/MTextField-CYk9yFvi.js.map +1 -0
  22. package/dist/_useFieldValidation-B0B44M_t.js +191 -0
  23. package/dist/_useFieldValidation-B0B44M_t.js.map +1 -0
  24. package/dist/api.json +1 -1
  25. package/dist/code-editor.js +184 -103
  26. package/dist/code-editor.js.map +1 -1
  27. package/dist/components/MAddressField.vue.d.ts +18 -3
  28. package/dist/components/MAppBarWithSearch.vue.d.ts +1 -1
  29. package/dist/components/MAudioRecorder.vue.d.ts +2 -2
  30. package/dist/components/MAutocomplete.vue.d.ts +22 -3
  31. package/dist/components/MCheckbox.vue.d.ts +23 -1
  32. package/dist/components/MCodeEditor.vue.d.ts +23 -1
  33. package/dist/components/MColorPicker.vue.d.ts +24 -3
  34. package/dist/components/MConfirmDialog.vue.d.ts +2 -2
  35. package/dist/components/MCountrySelect.vue.d.ts +13 -2
  36. package/dist/components/MCreditCardInput.vue.d.ts +33 -0
  37. package/dist/components/MCronField.vue.d.ts +23 -1
  38. package/dist/components/MDataTable.vue.d.ts +1 -1
  39. package/dist/components/MDatePicker.vue.d.ts +24 -3
  40. package/dist/components/MDateRangePicker.vue.d.ts +24 -3
  41. package/dist/components/MFileUpload.vue.d.ts +23 -2
  42. package/dist/components/MForm.vue.d.ts +61 -0
  43. package/dist/components/MFormBuilder.vue.d.ts +22 -0
  44. package/dist/components/MFormRenderer.vue.d.ts +151 -0
  45. package/dist/components/MJsonEditor.vue.d.ts +23 -1
  46. package/dist/components/MMapRoute.vue.d.ts +176 -0
  47. package/dist/components/MMaskField.vue.d.ts +20 -2
  48. package/dist/components/MMentionField.vue.d.ts +13 -2
  49. package/dist/components/MMultiAutocomplete.vue.d.ts +22 -3
  50. package/dist/components/MMultiSelect.vue.d.ts +22 -3
  51. package/dist/components/MNavigationRail.vue.d.ts +1 -1
  52. package/dist/components/MNotificationCenter.vue.d.ts +2 -2
  53. package/dist/components/MNumberField.vue.d.ts +20 -2
  54. package/dist/components/MPdfSigner.vue.d.ts +499 -0
  55. package/dist/components/MPdfViewer.vue.d.ts +12 -0
  56. package/dist/components/MPhoneInput.vue.d.ts +19 -4
  57. package/dist/components/MPinInput.vue.d.ts +24 -3
  58. package/dist/components/MPosKeypad.vue.d.ts +3 -3
  59. package/dist/components/MRadioGroup.vue.d.ts +23 -1
  60. package/dist/components/MRating.vue.d.ts +23 -1
  61. package/dist/components/MRichTextEditor.vue.d.ts +23 -1
  62. package/dist/components/MSearchBar.vue.d.ts +1 -1
  63. package/dist/components/MSegmentedButton.vue.d.ts +23 -2
  64. package/dist/components/MSelect.vue.d.ts +22 -3
  65. package/dist/components/MSignaturePad.vue.d.ts +19 -0
  66. package/dist/components/MSlider.vue.d.ts +23 -1
  67. package/dist/components/MSpreadsheet.vue.d.ts +137 -0
  68. package/dist/components/MStack.vue.d.ts +1 -1
  69. package/dist/components/MSwitch.vue.d.ts +23 -1
  70. package/dist/components/MTable.vue.d.ts +1 -1
  71. package/dist/components/MTagInput.vue.d.ts +20 -2
  72. package/dist/components/MText.vue.d.ts +1 -1
  73. package/dist/components/MTextField.vue.d.ts +26 -3
  74. package/dist/components/MTimePicker.vue.d.ts +24 -3
  75. package/dist/components/MTimezoneSelect.vue.d.ts +13 -2
  76. package/dist/components/MTour.vue.d.ts +2 -2
  77. package/dist/components/MTrackingTimeline.vue.d.ts +75 -0
  78. package/dist/components/MWindow.vue.d.ts +2 -2
  79. package/dist/composables/_routeGeometry.d.ts +26 -0
  80. package/dist/composables/_useFieldValidation.d.ts +91 -0
  81. package/dist/composables/mapRouting.d.ts +35 -0
  82. package/dist/composables/pdfSign.d.ts +52 -0
  83. package/dist/composables/spreadsheetFormula.d.ts +55 -0
  84. package/dist/composables/useLocale.d.ts +177 -0
  85. package/dist/composables/validation.d.ts +82 -0
  86. package/dist/draw.js +2 -2
  87. package/dist/flow.js +1 -1
  88. package/dist/gantt.js +2 -2
  89. package/dist/index.d.ts +12 -0
  90. package/dist/locales/index.js +693 -7
  91. package/dist/locales/index.js.map +1 -1
  92. package/dist/m3ui-vue.css +1 -1
  93. package/dist/m3ui.js +15507 -12417
  94. package/dist/m3ui.js.map +1 -1
  95. package/dist/map.d.ts +4 -0
  96. package/dist/map.js +1207 -745
  97. package/dist/map.js.map +1 -1
  98. package/dist/media.js +4 -4
  99. package/dist/pdf.d.ts +3 -0
  100. package/dist/pdf.js +1228 -687
  101. package/dist/pdf.js.map +1 -1
  102. package/dist/rich-text-editor.js +188 -146
  103. package/dist/rich-text-editor.js.map +1 -1
  104. package/dist/styles.css +1 -1
  105. package/dist/{useLocale-DaVSTdm0.js → useLocale-DL96OFgr.js} +99 -1
  106. package/dist/useLocale-DL96OFgr.js.map +1 -0
  107. package/package.json +5 -1
  108. package/src/__tests__/MForm.test.ts +325 -0
  109. package/src/__tests__/MFormRenderer.test.ts +157 -0
  110. package/src/__tests__/MMapRoute.test.ts +418 -0
  111. package/src/__tests__/MPdfSigner.test.ts +175 -0
  112. package/src/__tests__/MPhoneInput.test.ts +5 -2
  113. package/src/__tests__/MRichTextEditor.test.ts +2 -1
  114. package/src/__tests__/MSpreadsheet.test.ts +223 -0
  115. package/src/__tests__/MTrackingTimeline.test.ts +66 -0
  116. package/src/__tests__/_fakeMaplibre.ts +4 -1
  117. package/src/__tests__/_osrmRoutes.ts +10 -0
  118. package/src/__tests__/attrsFallthrough.test.ts +11 -0
  119. package/src/__tests__/fieldsValidation.test.ts +229 -0
  120. package/src/__tests__/spreadsheetFormula.test.ts +77 -0
  121. package/src/__tests__/ssr.test.ts +4 -0
  122. package/src/__tests__/validation.test.ts +77 -0
  123. package/src/components/MAddressField.vue +45 -8
  124. package/src/components/MAutocomplete.vue +69 -23
  125. package/src/components/MCheckbox.vue +80 -17
  126. package/src/components/MCodeEditor.vue +59 -2
  127. package/src/components/MColorPicker.vue +65 -16
  128. package/src/components/MCountrySelect.vue +17 -3
  129. package/src/components/MCreditCardInput.vue +76 -7
  130. package/src/components/MCronField.vue +60 -10
  131. package/src/components/MDatePicker.vue +65 -16
  132. package/src/components/MDateRangePicker.vue +66 -16
  133. package/src/components/MFileUpload.vue +71 -8
  134. package/src/components/MForm.vue +208 -0
  135. package/src/components/MFormBuilder.vue +417 -0
  136. package/src/components/MFormRenderer.vue +324 -0
  137. package/src/components/MJsonEditor.vue +57 -3
  138. package/src/components/MMapRoute.vue +523 -0
  139. package/src/components/MMaskField.vue +55 -13
  140. package/src/components/MMentionField.vue +17 -2
  141. package/src/components/MMultiAutocomplete.vue +70 -23
  142. package/src/components/MMultiSelect.vue +70 -23
  143. package/src/components/MNumberField.vue +58 -16
  144. package/src/components/MPdfSigner.vue +433 -0
  145. package/src/components/MPdfViewer.vue +12 -0
  146. package/src/components/MPhoneInput.vue +60 -18
  147. package/src/components/MPinInput.vue +58 -10
  148. package/src/components/MRadioGroup.vue +65 -4
  149. package/src/components/MRating.vue +62 -6
  150. package/src/components/MRichTextEditor.vue +64 -4
  151. package/src/components/MSegmentedButton.vue +59 -2
  152. package/src/components/MSelect.vue +72 -26
  153. package/src/components/MSignaturePad.vue +71 -6
  154. package/src/components/MSlider.vue +61 -10
  155. package/src/components/MSpreadsheet.vue +992 -0
  156. package/src/components/MSwitch.vue +63 -8
  157. package/src/components/MTagInput.vue +67 -25
  158. package/src/components/MTextField.vue +68 -14
  159. package/src/components/MTimePicker.vue +65 -16
  160. package/src/components/MTimezoneSelect.vue +17 -3
  161. package/src/components/MTrackingTimeline.vue +257 -0
  162. package/src/composables/_routeGeometry.ts +140 -0
  163. package/src/composables/_useFieldValidation.ts +287 -0
  164. package/src/composables/mapRouting.ts +55 -0
  165. package/src/composables/pdfSign.ts +141 -0
  166. package/src/composables/spreadsheetFormula.ts +459 -0
  167. package/src/composables/useLocale.ts +277 -0
  168. package/src/composables/validation.ts +178 -0
  169. package/src/index.ts +12 -0
  170. package/src/locales/de.ts +98 -0
  171. package/src/locales/es.ts +105 -7
  172. package/src/locales/fr.ts +98 -0
  173. package/src/locales/ja.ts +98 -0
  174. package/src/locales/ko.ts +98 -0
  175. package/src/locales/pt.ts +98 -0
  176. package/src/locales/zh.ts +98 -0
  177. package/src/map.ts +4 -0
  178. package/src/pdf.ts +3 -0
  179. package/dist/MButton-OQ4wIERQ.js +0 -171
  180. package/dist/MButton-OQ4wIERQ.js.map +0 -1
  181. package/dist/MDialog-DYMnaBlt.js +0 -167
  182. package/dist/MDialog-DYMnaBlt.js.map +0 -1
  183. package/dist/MListItem-D2cNUyzP.js.map +0 -1
  184. package/dist/MProgressBar-BWly1UKN.js +0 -179
  185. package/dist/MProgressBar-BWly1UKN.js.map +0 -1
  186. package/dist/MSegmentedButton-BEB4gXLA.js +0 -64
  187. package/dist/MSegmentedButton-BEB4gXLA.js.map +0 -1
  188. package/dist/MSlider-BIkA6DiE.js +0 -690
  189. package/dist/MSlider-BIkA6DiE.js.map +0 -1
  190. package/dist/MTextField-CNH-byir.js.map +0 -1
  191. package/dist/useLocale-DaVSTdm0.js.map +0 -1
@@ -0,0 +1,523 @@
1
+ <script lang="ts">
2
+ import type { LngLat } from '../composables/_mapGeometry'
3
+
4
+ /** A stop on an `MMapRoute`: a pickup, a drop-off, a waypoint. */
5
+ export interface MapRouteStop {
6
+ /** Where it is, `[lng, lat]` */
7
+ lngLat: LngLat
8
+ /** Its name (the marker's accessible name and tooltip) */
9
+ label?: string
10
+ /** A Material Symbol inside its marker. Defaults to a number for the stops in between, a flag for the last one */
11
+ icon?: string
12
+ /** Mark it reached (or not) yourself, instead of by where the vehicle is along the route */
13
+ done?: boolean
14
+ }
15
+ </script>
16
+
17
+ <script setup lang="ts">
18
+ /**
19
+ * A route on an `MMap`, for deliveries and trips: the path (from your routing service, or straight lines between the
20
+ * stops), the part already travelled solid and the rest dotted, a marker per stop, reached ones filled, and a vehicle
21
+ * that moves along the road, not across it, when its position changes. Drive it with `progress` (0–1 of the way) or
22
+ * `vehicle` (a live GPS position, which lands on the nearest point of the route). Theme colors, following palette and
23
+ * dark mode. Available from the `/map` entry point.
24
+ *
25
+ * @slot stop A stop's marker, instead of the round one. Scope: `{ stop, index, done }`
26
+ * @slot stop-popup Content of a popup that opens when a stop is clicked. Scope: `{ stop, index, done }`
27
+ * @slot vehicle The vehicle, instead of the round one (an image, a top-down car, a pin). Scope: `{ bearing, west }`:
28
+ * the heading in degrees, and whether it's heading west (to mirror something drawn facing right). With
29
+ * `rotateVehicle` the marker turns it with the road itself
30
+ * @event stop-click A stop was clicked: the stop and its index
31
+ * @event arrive The vehicle reached the end of the route
32
+ * @event route `provider` returned a road (`{ path, distance, duration }`)
33
+ * @event error `provider` failed
34
+ */
35
+ import { computed, onBeforeUnmount, onMounted, ref, shallowRef, useId, useSlots, watch } from 'vue'
36
+ import type * as Maplibre from 'maplibre-gl'
37
+ import MIcon from './MIcon.vue'
38
+ import MMapMarker from './MMapMarker.vue'
39
+ import { useMap } from '../composables/useMap'
40
+ import { useThemeTokens } from '../composables/useThemeTokens'
41
+ import { useLocale } from '../composables/useLocale'
42
+ import { prefersReducedMotion } from '../composables/_springAnimation'
43
+ import { bearing, bounds, cumulative, pointAlong, project, projectForward, slicePath } from '../composables/_routeGeometry'
44
+ import type { MapRouteProvider, MapRouteResult } from '../composables/mapRouting'
45
+
46
+ // Its markers and vehicle are moved into the map: no element of its own for attributes
47
+ defineOptions({ inheritAttrs: false })
48
+
49
+ const props = withDefaults(
50
+ defineProps<{
51
+ /** The stops, in order: the start, any in between, the destination */
52
+ stops: MapRouteStop[]
53
+ /**
54
+ * The road to follow, `[lng, lat][]`: a routing service's geometry (OSRM, GraphHopper, Mapbox…), with the streets'
55
+ * real shape. Without it, `provider` fetches one, or the stops are joined by straight lines
56
+ */
57
+ path?: LngLat[]
58
+ /** How far the vehicle is, 0–1 of the route's length. Ignored when `vehicle` is set */
59
+ progress?: number
60
+ /** The vehicle's live position, `[lng, lat]`: it's placed on the nearest point of the route */
61
+ vehicle?: LngLat | null
62
+ /** A Material Symbol for the vehicle. The default arrow turns with the road; other icons (`two_wheeler`, `local_shipping`) face the way it goes */
63
+ vehicleIcon?: string
64
+ /**
65
+ * Turn the vehicle with the road (following the map's own rotation too): on for the default arrow, off for other
66
+ * icons (they're mirrored when heading west instead). Set it for `#vehicle` content drawn pointing up (north)
67
+ */
68
+ rotateVehicle?: boolean
69
+ /** Show the vehicle (when there's a `progress` or `vehicle`) */
70
+ showVehicle?: boolean
71
+ /**
72
+ * How long the vehicle takes to move to a new position, in ms (0 jumps). `auto` (default) takes as long as the
73
+ * time between the last two positions, so a vehicle fed every few seconds keeps moving at an even pace instead of
74
+ * stopping between fixes (or slowing down when one arrives early). Reduced motion jumps
75
+ */
76
+ duration?: number | 'auto'
77
+ /** Fit the map to the whole route when it's shown and when the route changes */
78
+ fit?: boolean
79
+ /** Keep the vehicle in the middle of the map as it moves */
80
+ follow?: boolean
81
+ /** Room around the route when fitting it, in px */
82
+ padding?: number
83
+ /** The route's color: one MapLibre reads (hex, rgb()…), not `var()`. Defaults to the theme's primary, following palette and dark mode */
84
+ color?: string
85
+ /** The dots of the route ahead flow toward the destination (off with reduced motion) */
86
+ flow?: boolean
87
+ /** Line width in px */
88
+ width?: number
89
+ /** Insert the route's lines below this layer id (e.g. under the style's labels) */
90
+ before?: string
91
+ /** The source's id (and the prefix of its layers' ids). Generated when left out */
92
+ id?: string
93
+ /**
94
+ * Fetches the road between the stops when there's no `path` (again when they change): `osrmRouteProvider()`, or
95
+ * your own function. Straight lines meanwhile, and if it fails (`error` event)
96
+ */
97
+ provider?: MapRouteProvider
98
+ /**
99
+ * How a `vehicle` position lands on the route: `forward` (default) only moves ahead from where it was, so a route
100
+ * that passes the same place twice (out and back, a loop, close parallel streets) doesn't jump to the other pass;
101
+ * `nearest` takes the closest point of the whole route every time
102
+ */
103
+ snap?: 'forward' | 'nearest'
104
+ }>(),
105
+ { rotateVehicle: undefined, flow: true, vehicleIcon: 'navigation', showVehicle: true, duration: 'auto', fit: true, follow: false, padding: 64, width: 5, snap: 'forward' },
106
+ )
107
+
108
+ const emit = defineEmits<{
109
+ 'stop-click': [stop: MapRouteStop, index: number]
110
+ arrive: []
111
+ /** `provider` returned a road: its path, distance (m) and duration (s) */
112
+ route: [route: MapRouteResult]
113
+ /** `provider` failed (the stops stay joined by straight lines) */
114
+ error: [error: unknown]
115
+ }>()
116
+
117
+ const slots = useSlots()
118
+ const locale = useLocale()
119
+ const sourceId = props.id ?? `m3-route-${useId()}`
120
+ const { onReady, styleVersion } = useMap()
121
+ const theme = useThemeTokens(['primary', 'outline', 'surface'] as const)
122
+
123
+ /** The road `provider` returned */
124
+ const routed = shallowRef<LngLat[] | null>(null)
125
+ const path = computed<LngLat[]>(() =>
126
+ props.path && props.path.length > 1 ? props.path
127
+ : routed.value && routed.value.length > 1 ? routed.value
128
+ : props.stops.map((s) => s.lngLat),
129
+ )
130
+ const pathKey = computed(() => JSON.stringify(path.value))
131
+ const cum = computed(() => cumulative(path.value))
132
+ const total = computed(() => cum.value[cum.value.length - 1] ?? 0)
133
+ /**
134
+ * Where each stop falls along the route, in meters: in order, each from the one before, so on a round trip the last
135
+ * stop (where the first one is) lands at the end, not the start
136
+ */
137
+ const stopAt = computed(() => {
138
+ let from = 0
139
+ return props.stops.map((s) => (from = projectForward(path.value, cum.value, s.lngLat, from, 0)))
140
+ })
141
+
142
+ // The last place a `vehicle` landed on the route (forward snapping goes on from there)
143
+ let snapped: number | null = null
144
+ function computeTarget(): number | null {
145
+ if (props.vehicle) {
146
+ const d = props.snap === 'nearest' || snapped == null
147
+ ? project(path.value, cum.value, props.vehicle)
148
+ : projectForward(path.value, cum.value, props.vehicle, snapped)
149
+ snapped = d
150
+ return d
151
+ }
152
+ snapped = null
153
+ if (props.progress != null && Number.isFinite(props.progress)) return Math.min(Math.max(props.progress, 0), 1) * total.value
154
+ return null
155
+ }
156
+ /** Where the vehicle should be, in meters along the route (null: no vehicle) */
157
+ const target = ref<number | null>(computeTarget())
158
+ // The position by value: an inline `:vehicle="[lng, lat]"` is a new array on every parent render
159
+ watch([() => props.vehicle?.join(','), () => props.progress, () => props.snap], () => (target.value = computeTarget()))
160
+
161
+ // ── provider ──
162
+ let controller: AbortController | undefined
163
+ async function requestRoute() {
164
+ controller?.abort()
165
+ if (!props.provider || (props.path && props.path.length > 1) || props.stops.length < 2) {
166
+ routed.value = null
167
+ return
168
+ }
169
+ const c = (controller = new AbortController())
170
+ try {
171
+ const result = await props.provider(props.stops.map((s) => s.lngLat), { signal: c.signal })
172
+ if (c.signal.aborted) return
173
+ routed.value = result.path
174
+ emit('route', result)
175
+ } catch (e) {
176
+ if (!c.signal.aborted) {
177
+ routed.value = null
178
+ emit('error', e)
179
+ }
180
+ }
181
+ }
182
+ // Client only (no fetch while rendering on the server); stops compared by value
183
+ onMounted(requestRoute)
184
+ watch([() => JSON.stringify(props.stops.map((s) => s.lngLat)), () => props.provider, () => !!(props.path && props.path.length > 1)], () => requestRoute())
185
+
186
+ // The animated position lives outside Vue's reactivity (one rAF loop); only what the template needs is reactive
187
+ let at = 0
188
+ const travelled = ref(0)
189
+ const bearingNow = ref(0)
190
+ let headingNow = 0
191
+ let frame = 0
192
+
193
+ const stopDone = (i: number) => props.stops[i]?.done ?? (target.value != null && travelled.value >= stopAt.value[i]! - 1)
194
+
195
+ const lineColor = computed(() => props.color ?? theme.value.primary)
196
+
197
+ let map: Maplibre.Map | undefined
198
+ let vehicleMarker: Maplibre.Marker | undefined
199
+ const vehicleEl = ref<HTMLElement>()
200
+ const layerIds = [`${sourceId}-rest`, `${sourceId}-casing`, `${sourceId}-done`]
201
+
202
+ type LineFeature = { type: 'Feature'; properties: { part: string }; geometry: { type: 'LineString'; coordinates: LngLat[] } }
203
+ function data(d: number): { type: 'FeatureCollection'; features: LineFeature[] } {
204
+ const line = (coordinates: LngLat[], part: string): LineFeature => ({ type: 'Feature', properties: { part }, geometry: { type: 'LineString', coordinates } })
205
+ return {
206
+ type: 'FeatureCollection',
207
+ // Ahead: the whole route, the same every frame, so the dots don't depend on where the vehicle is (a dash pattern
208
+ // is measured from the line's start). The part done is drawn over it, its casing hiding the dots
209
+ features: [line(path.value, 'rest'), line(slicePath(path.value, cum.value, 0, d), 'done')],
210
+ }
211
+ }
212
+
213
+ function layers(): Maplibre.LayerSpecification[] {
214
+ const w = props.width
215
+ const round = { 'line-cap': 'round' as const, 'line-join': 'round' as const }
216
+ return [
217
+ // Ahead: dotted, in the outline color
218
+ { id: layerIds[0]!, type: 'line', source: sourceId, filter: ['==', ['get', 'part'], 'rest'], layout: { 'line-cap': 'butt', 'line-join': 'round' }, paint: { 'line-color': theme.value.outline, 'line-width': w * 0.8, 'line-dasharray': dashAt(Math.max(flowStepNow, 0)) } },
219
+ // Done: solid, over a surface-colored casing so it reads on any base map
220
+ { id: layerIds[1]!, type: 'line', source: sourceId, filter: ['==', ['get', 'part'], 'done'], layout: round, paint: { 'line-color': theme.value.surface, 'line-width': w + 4 } },
221
+ { id: layerIds[2]!, type: 'line', source: sourceId, filter: ['==', ['get', 'part'], 'done'], layout: round, paint: { 'line-color': lineColor.value, 'line-width': w } },
222
+ ]
223
+ }
224
+
225
+ function add() {
226
+ if (!map) return
227
+ // tolerance 0: MapLibre simplifies GeoJSON lines per zoom by default, which cut across a roundabout's curve (and
228
+ // changed as the part done grew); a route has to keep the road's exact shape
229
+ if (!map.getSource(sourceId)) map.addSource(sourceId, { type: 'geojson', data: data(at), tolerance: 0 })
230
+ for (const layer of layers()) {
231
+ if (map.getLayer(layer.id)) map.removeLayer(layer.id)
232
+ map.addLayer(layer, props.before && map.getLayer(props.before) ? props.before : undefined)
233
+ }
234
+ }
235
+
236
+ /** Where the line's split was last sent to MapLibre (meters), and the vehicle's point then */
237
+ let lineAt = -1
238
+ let linePoint: LngLat | null = null
239
+ /**
240
+ * Re-sending the line goes through MapLibre's worker and re-tiles it: every frame, that cost Firefox a frame in
241
+ * ten (the vehicle stuttered). The split sits under the vehicle, so it's only re-sent once the vehicle has moved
242
+ * 2px on screen, and always at the end of a move (`exact`)
243
+ */
244
+ function lineNeedsUpdate(d: number, lngLat: LngLat, exact: boolean) {
245
+ if (exact || !map || lineAt < 0 || !linePoint) return d !== lineAt || lineAt < 0
246
+ const a = map.project(lngLat)
247
+ const b = map.project(linePoint)
248
+ return Math.hypot(a.x - b.x, a.y - b.y) >= 2
249
+ }
250
+
251
+ /** Puts the vehicle and the split of the line at `d` meters (one frame); `exact` also moves the split exactly there */
252
+ function place(d: number, exact = true) {
253
+ at = d
254
+ const { lngLat } = pointAlong(path.value, cum.value, d)
255
+ const heading = headingAt(d)
256
+ if (lineNeedsUpdate(d, lngLat, exact)) {
257
+ const source = map?.getSource(sourceId) as Maplibre.GeoJSONSource | undefined
258
+ if (source) {
259
+ source.setData(data(d))
260
+ lineAt = d
261
+ linePoint = lngLat
262
+ }
263
+ }
264
+ vehicleMarker?.setLngLat(lngLat)
265
+ if (rotates.value) vehicleMarker?.setRotation(heading)
266
+ headingNow = heading
267
+ // Only `#vehicle` reads it: updating it for the default icon would re-render the component every frame
268
+ if (slots.vehicle) bearingNow.value = heading
269
+ // Turn the icon around only when clearly heading west or east: going north or south it keeps the way it faced,
270
+ // instead of flipping back and forth as the heading wobbles around 180° on a real road's short segments
271
+ if (heading > 200 && heading < 340) facingWest.value = true
272
+ else if (heading > 20 && heading < 160) facingWest.value = false
273
+ if (props.follow) map?.jumpTo({ center: lngLat })
274
+ // Stops light up as the vehicle passes them; `travelled` only changes when one is crossed, not every frame
275
+ if (reached(d) !== reached(travelled.value)) travelled.value = d
276
+ }
277
+
278
+ const reached = (d: number) => stopAt.value.filter((s) => d >= s - 1).length
279
+
280
+ const facingWest = ref(false)
281
+
282
+ // ── flow: the dots ahead streaming toward the destination ──
283
+ // The geometry never changes (re-sending it to MapLibre's worker 30 times a second cost a third of the frame rate
284
+ // with a few maps, and the dots only moved in the line's first tile: MapLibre lays dash patterns out tile by tile).
285
+ // The dash pattern itself is shifted instead, through 16 offsets MapLibre caches, the same in every tile. A pattern
286
+ // can't be shifted with round caps (a zero-length dash draws a dot of its own), so the dots are small squares (butt)
287
+ const DOT = 1 // dash length, in line widths
288
+ const GAP = 1.6
289
+ const FLOW_STEPS = 16
290
+ const FLOW_PX_PER_S = 16
291
+ /** The dash pattern shifted by `step` sixteenths of a period: [dash, gap, dash, gap] covering exactly one period */
292
+ function dashAt(step: number): number[] {
293
+ const period = DOT + GAP
294
+ const s = (step / FLOW_STEPS) * period
295
+ // The dot starts `s` into the period; past the gap it wraps around to the period's start
296
+ return s <= GAP ? [0, s, DOT, GAP - s] : [s - GAP, GAP, period - s, 0]
297
+ }
298
+ let flowFrame = 0
299
+ let flowStart = 0
300
+ let flowStepNow = -1
301
+ function flowStep(now: number) {
302
+ const periodPx = (DOT + GAP) * props.width * 0.8
303
+ const step = Math.floor((((now - flowStart) / 1000) * FLOW_PX_PER_S / periodPx) * FLOW_STEPS) % FLOW_STEPS
304
+ // A growing offset moves the dots toward the destination
305
+ if (step !== flowStepNow && map?.getLayer(layerIds[0]!)) {
306
+ flowStepNow = step
307
+ map.setPaintProperty(layerIds[0]!, 'line-dasharray', dashAt(step))
308
+ }
309
+ flowFrame = requestAnimationFrame(flowStep)
310
+ }
311
+ // Each new pattern makes MapLibre redraw the map: only while the map is on screen
312
+ let onScreen = true
313
+ let visibility: IntersectionObserver | undefined
314
+ function watchVisibility() {
315
+ if (visibility || !map || typeof IntersectionObserver === 'undefined') return
316
+ visibility = new IntersectionObserver(([entry]) => {
317
+ const now = !!entry?.isIntersecting
318
+ if (now === onScreen) return
319
+ onScreen = now
320
+ startFlow()
321
+ })
322
+ visibility.observe(map.getContainer())
323
+ }
324
+ function startFlow() {
325
+ cancelAnimationFrame(flowFrame)
326
+ flowStepNow = -1
327
+ watchVisibility()
328
+ if (!onScreen && props.flow) return
329
+ if (props.flow && map && !prefersReducedMotion()) {
330
+ flowStart = performance.now()
331
+ flowFrame = requestAnimationFrame(flowStep)
332
+ } else if (map?.getLayer(layerIds[0]!)) map.setPaintProperty(layerIds[0]!, 'line-dasharray', dashAt(0))
333
+ }
334
+
335
+ /**
336
+ * The heading over a stretch around `d` (10 m behind to 25 m ahead), not the current segment's: a routing service's
337
+ * road is many short segments, and their bearings jitter, which would shake a rotated arrow at every vertex
338
+ */
339
+ function headingAt(d: number): number {
340
+ const behind = pointAlong(path.value, cum.value, Math.max(d - 10, 0)).lngLat
341
+ const ahead = pointAlong(path.value, cum.value, Math.min(d + 25, total.value)).lngLat
342
+ return behind[0] === ahead[0] && behind[1] === ahead[1] ? pointAlong(path.value, cum.value, d).bearing : bearing(behind, ahead)
343
+ }
344
+
345
+ /** An icon that turns with the road (the arrow) vs one drawn facing right, flipped when heading west */
346
+ const rotates = computed(() => props.rotateVehicle ?? (props.vehicleIcon === 'navigation' && !slots.vehicle))
347
+
348
+ // For `duration: 'auto'`: when the last position came, and the time between positions (smoothed)
349
+ let lastTargetAt = 0
350
+ let interval = 0
351
+ function moveDuration(): number {
352
+ if (prefersReducedMotion()) return 0
353
+ if (props.duration !== 'auto') return props.duration
354
+ const now = performance.now()
355
+ const gap = now - lastTargetAt
356
+ // A gap over 5 s is a pause (the vehicle waiting, the tab hidden), not how often positions come
357
+ if (lastTargetAt && gap <= 5000) interval = interval ? (interval + Math.max(gap, 100)) / 2 : Math.max(gap, 100)
358
+ lastTargetAt = now
359
+ // Until two positions have come, a second
360
+ return interval || 1000
361
+ }
362
+
363
+ function moveTo(d: number) {
364
+ cancelAnimationFrame(frame)
365
+ const from = at
366
+ const ms = moveDuration()
367
+ if (ms <= 0 || from === d) {
368
+ place(d)
369
+ travelled.value = d
370
+ arrived()
371
+ return
372
+ }
373
+ const start = performance.now()
374
+ const step = (now: number) => {
375
+ const t = Math.min(1, (now - start) / ms)
376
+ // Constant speed, as a vehicle between two GPS fixes
377
+ place(from + (d - from) * t, t >= 1)
378
+ if (t < 1) frame = requestAnimationFrame(step)
379
+ else {
380
+ travelled.value = d
381
+ arrived()
382
+ }
383
+ }
384
+ frame = requestAnimationFrame(step)
385
+ }
386
+
387
+ let wasArrived = false
388
+ function arrived() {
389
+ const done = total.value > 0 && at >= total.value - 1
390
+ if (done && !wasArrived) emit('arrive')
391
+ wasArrived = done
392
+ }
393
+
394
+ function fitRoute() {
395
+ if (!map || path.value.length < 2) return
396
+ map.fitBounds(bounds(path.value), { padding: props.padding, duration: prefersReducedMotion() ? 0 : 600 })
397
+ }
398
+
399
+ const showVehicle = computed(() => props.showVehicle && target.value != null)
400
+
401
+ onReady((m, ml) => {
402
+ map = m
403
+ at = target.value ?? 0
404
+ travelled.value = at
405
+ add()
406
+ if (vehicleEl.value) {
407
+ // Subpixel positions: whole pixels make a slow vehicle step a pixel every few frames, which reads as shaking
408
+ vehicleMarker = new ml.Marker({ element: vehicleEl.value, rotationAlignment: rotates.value ? 'map' : 'viewport', subpixelPositioning: true })
409
+ if (showVehicle.value) vehicleMarker.setLngLat(pointAlong(path.value, cum.value, at).lngLat).addTo(m)
410
+ }
411
+ place(at)
412
+ wasArrived = total.value > 0 && at >= total.value - 1
413
+ if (props.fit) fitRoute()
414
+ startFlow()
415
+ })
416
+ watch(() => props.flow, startFlow)
417
+
418
+ watch(styleVersion, () => add())
419
+ watch(rotates, (on) => {
420
+ vehicleMarker?.setRotationAlignment(on ? 'map' : 'viewport')
421
+ vehicleMarker?.setRotation(on ? headingNow : 0)
422
+ })
423
+ watch(target, (d) => {
424
+ // No vehicle any more: the next one starts counting its pace afresh
425
+ if (d == null) lastTargetAt = interval = 0
426
+ else if (map) moveTo(d)
427
+ })
428
+ watch(showVehicle, (show) => {
429
+ if (!map || !vehicleMarker) return
430
+ if (show) vehicleMarker.setLngLat(pointAlong(path.value, cum.value, at).lngLat).addTo(map)
431
+ else vehicleMarker.remove()
432
+ })
433
+ // A new route (compared by value: an inline array is new on every parent render): redraw, refit
434
+ watch(pathKey, () => {
435
+ snapped = null
436
+ lineAt = -1
437
+ target.value = computeTarget()
438
+ if (!map) return
439
+ at = Math.min(target.value ?? 0, total.value)
440
+ travelled.value = at
441
+ place(at)
442
+ if (props.fit) fitRoute()
443
+ })
444
+ watch(() => [lineColor.value, theme.value.outline, theme.value.surface, props.width, props.before], () => add())
445
+
446
+ onBeforeUnmount(() => {
447
+ controller?.abort()
448
+ cancelAnimationFrame(flowFrame)
449
+ visibility?.disconnect()
450
+ cancelAnimationFrame(frame)
451
+ vehicleMarker?.remove()
452
+ if (map) {
453
+ for (const id of layerIds) if (map.getLayer(id)) map.removeLayer(id)
454
+ if (map.getSource(sourceId)) map.removeSource(sourceId)
455
+ }
456
+ map = undefined
457
+ })
458
+
459
+ const stopIcon = (stop: MapRouteStop, i: number) =>
460
+ stop.icon ?? (i === props.stops.length - 1 ? 'flag' : i === 0 ? 'trip_origin' : undefined)
461
+ const stopName = (stop: MapRouteStop, i: number) => stop.label ?? `${locale.mapRouteStop} ${i + 1}`
462
+
463
+ defineExpose({
464
+ /** Fits the map to the whole route */
465
+ fit: fitRoute,
466
+ /** The route's length, in meters */
467
+ length: total,
468
+ /** How far the vehicle is now, in meters */
469
+ travelled,
470
+ /** The source's id */
471
+ sourceId,
472
+ })
473
+ </script>
474
+
475
+ <template>
476
+ <div class="hidden">
477
+ <MMapMarker
478
+ v-for="(stop, i) in stops"
479
+ :key="i"
480
+ :lng-lat="stop.lngLat"
481
+ @click="emit('stop-click', stop, i)"
482
+ >
483
+ <slot name="stop" :stop="stop" :index="i" :done="stopDone(i)">
484
+ <span
485
+ role="img"
486
+ :aria-label="stopName(stop, i)"
487
+ :title="stopName(stop, i)"
488
+ class="m3-map-route-stop flex h-7 w-7 items-center justify-center rounded-full border-2 text-label-medium font-medium shadow-elevation-1 transition-colors duration-300"
489
+ :class="stopDone(i) ? 'border-transparent bg-primary text-on-primary' : 'border-primary bg-surface text-primary'"
490
+ :style="color ? (stopDone(i) ? { background: color } : { borderColor: color, color }) : undefined"
491
+ >
492
+ <MIcon v-if="stopIcon(stop, i)" :name="stopIcon(stop, i)!" :size="16" />
493
+ <template v-else>{{ i }}</template>
494
+ </span>
495
+ </slot>
496
+ <template v-if="$slots['stop-popup']" #popup>
497
+ <slot name="stop-popup" :stop="stop" :index="i" :done="stopDone(i)" />
498
+ </template>
499
+ </MMapMarker>
500
+
501
+ <!-- Moved into the map by MapLibre -->
502
+ <div ref="vehicleEl" class="m3-map-route-vehicle" :aria-label="locale.mapRouteVehicle" role="img">
503
+ <!-- A hint of rotation: Firefox draws an element moved only by translate() at whole pixels (measured), so a
504
+ slow vehicle stepped a pixel every few frames and shook; a rotated one is drawn where it really is -->
505
+ <div style="transform: rotate(0.01deg)">
506
+ <slot name="vehicle" :bearing="bearingNow" :west="facingWest">
507
+ <span
508
+ class="flex h-10 w-10 items-center justify-center rounded-full border-2 border-surface bg-primary text-on-primary shadow-elevation-2"
509
+ :style="color ? { background: color } : undefined"
510
+ >
511
+ <!-- Icons drawn facing right turn around when heading west; the arrow is rotated by the marker itself -->
512
+ <MIcon
513
+ :name="vehicleIcon"
514
+ :size="22"
515
+ :filled="vehicleIcon === 'navigation'"
516
+ :style="!rotates && facingWest ? { transform: 'scaleX(-1)' } : undefined"
517
+ />
518
+ </span>
519
+ </slot>
520
+ </div>
521
+ </div>
522
+ </div>
523
+ </template>
@@ -6,6 +6,8 @@
6
6
  * @event debounced Emitted debounce ms after the user stops typing (only when debounce > 0)
7
7
  */
8
8
  import { computed, ref, useId, watch } 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 { useFieldBg } from '../composables/useFieldBg'
11
13
  import { useDebounce } from '../composables/useDebounce'
@@ -35,10 +37,21 @@ const props = withDefaults(
35
37
  mask: string | MaskPreset
36
38
  /** Visual style */
37
39
  variant?: 'filled' | 'outlined'
38
- /** Error state */
39
- error?: boolean
40
+ /** Error state. A string is also the message (`:error="errors.x"`) */
41
+ error?: boolean | string
40
42
  /** Error message shown when error is true */
41
43
  errorLabel?: string
44
+ /**
45
+ * Validation rules: functions `(value, ctx) => true | 'message'` (may be async; see the built-in `required`,
46
+ * `email`, `minLength`…) or a Standard Schema (zod, valibot…). Checked in order; the first failure is shown
47
+ */
48
+ rules?: ValidationRule | ValidationRule[]
49
+ /** When the rules are checked and shown: on leaving the field (default; live after that), while typing, or only on submit (`MForm`) */
50
+ validateOn?: ValidateOn
51
+ /** 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 */
52
+ validateDebounce?: number
53
+ /** The key of this field in its `MForm`'s values, errors and schema */
54
+ name?: string
42
55
  /** Hint text */
43
56
  hint?: string
44
57
  /** Disables the field */
@@ -63,7 +76,30 @@ const props = withDefaults(
63
76
  },
64
77
  )
65
78
 
66
- const emit = defineEmits<{ 'update:modelValue': [string]; debounced: [string] }>()
79
+ const emit = defineEmits<{ blur: []; 'update:modelValue': [string]; debounced: [string] }>()
80
+
81
+ const rootEl = ref<HTMLElement | null>(null)
82
+ const validation = useFieldValidation({
83
+ value: () => props.modelValue,
84
+ rules: () => props.rules,
85
+ required: () => props.required,
86
+ error: () => props.error,
87
+ errorLabel: () => props.errorLabel,
88
+ name: () => props.name,
89
+ validateOn: () => props.validateOn,
90
+ validateDebounce: () => props.validateDebounce,
91
+ disabled: () => props.disabled,
92
+ focus: () => { inputEl.value?.focus() },
93
+ el: () => inputEl.value,
94
+ setValue: (v) => emit('update:modelValue', v as string),
95
+ })
96
+ /** Its own `disabled` or its MForm's */
97
+ const isDisabled = validation.disabled
98
+ const { hasError, message: errorMessage, messageId } = validation
99
+ const onFocusOut = useFocusLeave(() => rootEl.value, () => {
100
+ validation.onBlur()
101
+ emit('blur')
102
+ })
67
103
 
68
104
  const id = useId()
69
105
  const fieldBgEl = ref<HTMLElement | null>(null)
@@ -74,7 +110,7 @@ const resolvedMask = computed(() => PRESETS[props.mask as MaskPreset] ?? props.m
74
110
 
75
111
  const { debounced: emitDebounced, cancel: cancelDebounce } = useDebounce((v: string) => emit('debounced', v), props.debounce)
76
112
 
77
- const showClear = computed(() => props.clearable && props.modelValue.length > 0 && !props.disabled)
113
+ const showClear = computed(() => props.clearable && props.modelValue.length > 0 && !isDisabled.value)
78
114
 
79
115
  function rawToMasked(raw: string, mask: string): string {
80
116
  let result = ''
@@ -139,13 +175,13 @@ const inputClasses = computed(() => {
139
175
  'peer block w-full text-body-large text-on-surface outline-none placeholder:text-transparent',
140
176
  'transition-[border-color,border-width] duration-150',
141
177
  'disabled:cursor-not-allowed disabled:text-on-surface/38',
142
- props.error ? 'caret-error' : 'caret-primary',
178
+ hasError.value ? 'caret-error' : 'caret-primary',
143
179
  'h-14', pl, pr,
144
180
  ]
145
181
  if (props.variant === 'outlined') {
146
182
  return [...base,
147
183
  'rounded-xs border bg-transparent py-4',
148
- props.error
184
+ hasError.value
149
185
  ? 'border-error focus:border-2 focus:border-error'
150
186
  : 'border-outline hover:border-on-surface focus:border-2 focus:border-primary',
151
187
  'disabled:border-on-surface/12',
@@ -153,7 +189,7 @@ const inputClasses = computed(() => {
153
189
  }
154
190
  return [...base,
155
191
  'rounded-t-xs bg-surface-container-highest border-b pt-6 pb-2',
156
- props.error
192
+ hasError.value
157
193
  ? 'border-error focus:border-b-2 focus:border-error'
158
194
  : 'border-on-surface-variant hover:border-on-surface focus:border-b-2 focus:border-primary',
159
195
  'disabled:border-on-surface/38 disabled:bg-[color-mix(in_srgb,var(--color-on-surface)_4%,var(--color-surface-container-highest))]',
@@ -167,13 +203,17 @@ const labelClasses = computed(() =>
167
203
  right: rightInset.value,
168
204
  floated: 'peer',
169
205
  color: [
170
- props.error ? 'text-error peer-focus:text-error' : 'text-on-surface-variant peer-focus:text-primary',
206
+ hasError.value ? 'text-error peer-focus:text-error' : 'text-on-surface-variant peer-focus:text-primary',
171
207
  'peer-disabled:text-on-surface/38',
172
208
  ].join(' '),
173
209
  }),
174
210
  )
175
211
 
176
212
  defineExpose({
213
+ /** Checks its rules and shows the result; resolves to whether they pass */
214
+ validate: validation.validate,
215
+ /** Hides its validation error (until the next check) */
216
+ resetValidation: validation.resetValidation,
177
217
  /** The `<input>` (or `<textarea>`) element */
178
218
  inputEl: inputEl,
179
219
  /** Focuses the field */
@@ -188,7 +228,7 @@ defineExpose({
188
228
  </script>
189
229
 
190
230
  <template>
191
- <div class="flex flex-col gap-1">
231
+ <div ref="rootEl" class="flex flex-col gap-1" @focusout="onFocusOut">
192
232
  <div
193
233
  ref="fieldBgEl"
194
234
  class="relative"
@@ -200,7 +240,7 @@ defineExpose({
200
240
  class="pointer-events-none absolute left-3.5"
201
241
  :class="[
202
242
  variant === 'filled' ? 'top-4.5' : 'top-4',
203
- disabled ? 'text-on-surface/38' : 'text-on-surface-variant',
243
+ isDisabled ? 'text-on-surface/38' : 'text-on-surface-variant',
204
244
  ]"
205
245
  >
206
246
  <MIcon :name="leadingIcon" :size="24" />
@@ -209,10 +249,12 @@ defineExpose({
209
249
  <input
210
250
  :id="id"
211
251
  ref="inputEl"
252
+ :aria-invalid="hasError || undefined"
253
+ :aria-describedby="errorMessage || hint ? messageId : undefined"
212
254
  type="text"
213
255
  inputmode="numeric"
214
256
  :value="modelValue"
215
- :disabled="disabled"
257
+ :disabled="isDisabled"
216
258
  :required="required"
217
259
  placeholder=" "
218
260
  :class="inputClasses"
@@ -236,7 +278,7 @@ defineExpose({
236
278
  </button>
237
279
  </div>
238
280
 
239
- <p v-if="error && errorLabel" class="px-4 text-body-small text-error">{{ errorLabel }}</p>
240
- <p v-else-if="hint" class="px-4 text-body-small text-on-surface-variant">{{ hint }}</p>
281
+ <p v-if="errorMessage" :id="messageId" role="alert" class="px-4 text-body-small text-error">{{ errorMessage }}</p>
282
+ <p v-else-if="hint" :id="messageId" class="px-4 text-body-small text-on-surface-variant">{{ hint }}</p>
241
283
  </div>
242
284
  </template>