@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,470 @@
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
+ /** How long the vehicle takes to move to a new position, in ms (0 jumps). Reduced motion jumps */
72
+ duration?: number
73
+ /** Fit the map to the whole route when it's shown and when the route changes */
74
+ fit?: boolean
75
+ /** Keep the vehicle in the middle of the map as it moves */
76
+ follow?: boolean
77
+ /** Room around the route when fitting it, in px */
78
+ padding?: number
79
+ /** The route's color: one MapLibre reads (hex, rgb()…), not `var()`. Defaults to the theme's primary, following palette and dark mode */
80
+ color?: string
81
+ /** The dots of the route ahead flow toward the destination (off with reduced motion) */
82
+ flow?: boolean
83
+ /** Line width in px */
84
+ width?: number
85
+ /** Insert the route's lines below this layer id (e.g. under the style's labels) */
86
+ before?: string
87
+ /** The source's id (and the prefix of its layers' ids). Generated when left out */
88
+ id?: string
89
+ /**
90
+ * Fetches the road between the stops when there's no `path` (again when they change): `osrmRouteProvider()`, or
91
+ * your own function. Straight lines meanwhile, and if it fails (`error` event)
92
+ */
93
+ provider?: MapRouteProvider
94
+ /**
95
+ * How a `vehicle` position lands on the route: `forward` (default) only moves ahead from where it was, so a route
96
+ * that passes the same place twice (out and back, a loop, close parallel streets) doesn't jump to the other pass;
97
+ * `nearest` takes the closest point of the whole route every time
98
+ */
99
+ snap?: 'forward' | 'nearest'
100
+ }>(),
101
+ { rotateVehicle: undefined, flow: true, vehicleIcon: 'navigation', showVehicle: true, duration: 1000, fit: true, follow: false, padding: 64, width: 5, snap: 'forward' },
102
+ )
103
+
104
+ const emit = defineEmits<{
105
+ 'stop-click': [stop: MapRouteStop, index: number]
106
+ arrive: []
107
+ /** `provider` returned a road: its path, distance (m) and duration (s) */
108
+ route: [route: MapRouteResult]
109
+ /** `provider` failed (the stops stay joined by straight lines) */
110
+ error: [error: unknown]
111
+ }>()
112
+
113
+ const slots = useSlots()
114
+ const locale = useLocale()
115
+ const sourceId = props.id ?? `m3-route-${useId()}`
116
+ const { onReady, styleVersion } = useMap()
117
+ const theme = useThemeTokens(['primary', 'outline', 'surface'] as const)
118
+
119
+ /** The road `provider` returned */
120
+ const routed = shallowRef<LngLat[] | null>(null)
121
+ const path = computed<LngLat[]>(() =>
122
+ props.path && props.path.length > 1 ? props.path
123
+ : routed.value && routed.value.length > 1 ? routed.value
124
+ : props.stops.map((s) => s.lngLat),
125
+ )
126
+ const pathKey = computed(() => JSON.stringify(path.value))
127
+ const cum = computed(() => cumulative(path.value))
128
+ const total = computed(() => cum.value[cum.value.length - 1] ?? 0)
129
+ /**
130
+ * Where each stop falls along the route, in meters: in order, each from the one before, so on a round trip the last
131
+ * stop (where the first one is) lands at the end, not the start
132
+ */
133
+ const stopAt = computed(() => {
134
+ let from = 0
135
+ return props.stops.map((s) => (from = projectForward(path.value, cum.value, s.lngLat, from, 0)))
136
+ })
137
+
138
+ // The last place a `vehicle` landed on the route (forward snapping goes on from there)
139
+ let snapped: number | null = null
140
+ function computeTarget(): number | null {
141
+ if (props.vehicle) {
142
+ const d = props.snap === 'nearest' || snapped == null
143
+ ? project(path.value, cum.value, props.vehicle)
144
+ : projectForward(path.value, cum.value, props.vehicle, snapped)
145
+ snapped = d
146
+ return d
147
+ }
148
+ snapped = null
149
+ if (props.progress != null && Number.isFinite(props.progress)) return Math.min(Math.max(props.progress, 0), 1) * total.value
150
+ return null
151
+ }
152
+ /** Where the vehicle should be, in meters along the route (null: no vehicle) */
153
+ const target = ref<number | null>(computeTarget())
154
+ // The position by value: an inline `:vehicle="[lng, lat]"` is a new array on every parent render
155
+ watch([() => props.vehicle?.join(','), () => props.progress, () => props.snap], () => (target.value = computeTarget()))
156
+
157
+ // ── provider ──
158
+ let controller: AbortController | undefined
159
+ async function requestRoute() {
160
+ controller?.abort()
161
+ if (!props.provider || (props.path && props.path.length > 1) || props.stops.length < 2) {
162
+ routed.value = null
163
+ return
164
+ }
165
+ const c = (controller = new AbortController())
166
+ try {
167
+ const result = await props.provider(props.stops.map((s) => s.lngLat), { signal: c.signal })
168
+ if (c.signal.aborted) return
169
+ routed.value = result.path
170
+ emit('route', result)
171
+ } catch (e) {
172
+ if (!c.signal.aborted) {
173
+ routed.value = null
174
+ emit('error', e)
175
+ }
176
+ }
177
+ }
178
+ // Client only (no fetch while rendering on the server); stops compared by value
179
+ onMounted(requestRoute)
180
+ watch([() => JSON.stringify(props.stops.map((s) => s.lngLat)), () => props.provider, () => !!(props.path && props.path.length > 1)], () => requestRoute())
181
+
182
+ // The animated position lives outside Vue's reactivity (one rAF loop); only what the template needs is reactive
183
+ let at = 0
184
+ const travelled = ref(0)
185
+ const bearingNow = ref(0)
186
+ let frame = 0
187
+
188
+ const stopDone = (i: number) => props.stops[i]?.done ?? (target.value != null && travelled.value >= stopAt.value[i]! - 1)
189
+
190
+ const lineColor = computed(() => props.color ?? theme.value.primary)
191
+
192
+ let map: Maplibre.Map | undefined
193
+ let vehicleMarker: Maplibre.Marker | undefined
194
+ const vehicleEl = ref<HTMLElement>()
195
+ const layerIds = [`${sourceId}-rest`, `${sourceId}-casing`, `${sourceId}-done`]
196
+
197
+ type LineFeature = { type: 'Feature'; properties: { part: string }; geometry: { type: 'LineString'; coordinates: LngLat[] } }
198
+ function data(d: number): { type: 'FeatureCollection'; features: LineFeature[] } {
199
+ const line = (coordinates: LngLat[], part: string): LineFeature => ({ type: 'Feature', properties: { part }, geometry: { type: 'LineString', coordinates } })
200
+ return {
201
+ type: 'FeatureCollection',
202
+ // Ahead: the whole route, the same every frame, so the dots don't depend on where the vehicle is (a dash pattern
203
+ // is measured from the line's start). The part done is drawn over it, its casing hiding the dots
204
+ features: [line(path.value, 'rest'), line(slicePath(path.value, cum.value, 0, d), 'done')],
205
+ }
206
+ }
207
+
208
+ function layers(): Maplibre.LayerSpecification[] {
209
+ const w = props.width
210
+ const round = { 'line-cap': 'round' as const, 'line-join': 'round' as const }
211
+ return [
212
+ // Ahead: dotted, in the outline color
213
+ { 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)) } },
214
+ // Done: solid, over a surface-colored casing so it reads on any base map
215
+ { id: layerIds[1]!, type: 'line', source: sourceId, filter: ['==', ['get', 'part'], 'done'], layout: round, paint: { 'line-color': theme.value.surface, 'line-width': w + 4 } },
216
+ { id: layerIds[2]!, type: 'line', source: sourceId, filter: ['==', ['get', 'part'], 'done'], layout: round, paint: { 'line-color': lineColor.value, 'line-width': w } },
217
+ ]
218
+ }
219
+
220
+ function add() {
221
+ if (!map) return
222
+ // tolerance 0: MapLibre simplifies GeoJSON lines per zoom by default, which cut across a roundabout's curve (and
223
+ // changed as the part done grew); a route has to keep the road's exact shape
224
+ if (!map.getSource(sourceId)) map.addSource(sourceId, { type: 'geojson', data: data(at), tolerance: 0 })
225
+ for (const layer of layers()) {
226
+ if (map.getLayer(layer.id)) map.removeLayer(layer.id)
227
+ map.addLayer(layer, props.before && map.getLayer(props.before) ? props.before : undefined)
228
+ }
229
+ }
230
+
231
+ /** Puts the vehicle and the split of the line at `d` meters (one frame) */
232
+ function place(d: number) {
233
+ at = d
234
+ const { lngLat } = pointAlong(path.value, cum.value, d)
235
+ const heading = headingAt(d)
236
+ ;(map?.getSource(sourceId) as Maplibre.GeoJSONSource | undefined)?.setData(data(d))
237
+ vehicleMarker?.setLngLat(lngLat)
238
+ if (rotates.value) vehicleMarker?.setRotation(heading)
239
+ bearingNow.value = heading
240
+ // Turn the icon around only when clearly heading west or east: going north or south it keeps the way it faced,
241
+ // instead of flipping back and forth as the heading wobbles around 180° on a real road's short segments
242
+ if (heading > 200 && heading < 340) facingWest.value = true
243
+ else if (heading > 20 && heading < 160) facingWest.value = false
244
+ if (props.follow) map?.jumpTo({ center: lngLat })
245
+ // Stops light up as the vehicle passes them; `travelled` only changes when one is crossed, not every frame
246
+ if (reached(d) !== reached(travelled.value)) travelled.value = d
247
+ }
248
+
249
+ const reached = (d: number) => stopAt.value.filter((s) => d >= s - 1).length
250
+
251
+ const facingWest = ref(false)
252
+
253
+ // ── flow: the dots ahead streaming toward the destination ──
254
+ // The geometry never changes (re-sending it to MapLibre's worker 30 times a second cost a third of the frame rate
255
+ // with a few maps, and the dots only moved in the line's first tile: MapLibre lays dash patterns out tile by tile).
256
+ // The dash pattern itself is shifted instead, through 16 offsets MapLibre caches, the same in every tile. A pattern
257
+ // can't be shifted with round caps (a zero-length dash draws a dot of its own), so the dots are small squares (butt)
258
+ const DOT = 1 // dash length, in line widths
259
+ const GAP = 1.6
260
+ const FLOW_STEPS = 16
261
+ const FLOW_PX_PER_S = 16
262
+ /** The dash pattern shifted by `step` sixteenths of a period: [dash, gap, dash, gap] covering exactly one period */
263
+ function dashAt(step: number): number[] {
264
+ const period = DOT + GAP
265
+ const s = (step / FLOW_STEPS) * period
266
+ // The dot starts `s` into the period; past the gap it wraps around to the period's start
267
+ return s <= GAP ? [0, s, DOT, GAP - s] : [s - GAP, GAP, period - s, 0]
268
+ }
269
+ let flowFrame = 0
270
+ let flowStart = 0
271
+ let flowStepNow = -1
272
+ function flowStep(now: number) {
273
+ const periodPx = (DOT + GAP) * props.width * 0.8
274
+ const step = Math.floor((((now - flowStart) / 1000) * FLOW_PX_PER_S / periodPx) * FLOW_STEPS) % FLOW_STEPS
275
+ // A growing offset moves the dots toward the destination
276
+ if (step !== flowStepNow && map?.getLayer(layerIds[0]!)) {
277
+ flowStepNow = step
278
+ map.setPaintProperty(layerIds[0]!, 'line-dasharray', dashAt(step))
279
+ }
280
+ flowFrame = requestAnimationFrame(flowStep)
281
+ }
282
+ // Each new pattern makes MapLibre redraw the map: only while the map is on screen
283
+ let onScreen = true
284
+ let visibility: IntersectionObserver | undefined
285
+ function watchVisibility() {
286
+ if (visibility || !map || typeof IntersectionObserver === 'undefined') return
287
+ visibility = new IntersectionObserver(([entry]) => {
288
+ const now = !!entry?.isIntersecting
289
+ if (now === onScreen) return
290
+ onScreen = now
291
+ startFlow()
292
+ })
293
+ visibility.observe(map.getContainer())
294
+ }
295
+ function startFlow() {
296
+ cancelAnimationFrame(flowFrame)
297
+ flowStepNow = -1
298
+ watchVisibility()
299
+ if (!onScreen && props.flow) return
300
+ if (props.flow && map && !prefersReducedMotion()) {
301
+ flowStart = performance.now()
302
+ flowFrame = requestAnimationFrame(flowStep)
303
+ } else if (map?.getLayer(layerIds[0]!)) map.setPaintProperty(layerIds[0]!, 'line-dasharray', dashAt(0))
304
+ }
305
+
306
+ /**
307
+ * The heading over a stretch around `d` (10 m behind to 25 m ahead), not the current segment's: a routing service's
308
+ * road is many short segments, and their bearings jitter, which would shake a rotated arrow at every vertex
309
+ */
310
+ function headingAt(d: number): number {
311
+ const behind = pointAlong(path.value, cum.value, Math.max(d - 10, 0)).lngLat
312
+ const ahead = pointAlong(path.value, cum.value, Math.min(d + 25, total.value)).lngLat
313
+ return behind[0] === ahead[0] && behind[1] === ahead[1] ? pointAlong(path.value, cum.value, d).bearing : bearing(behind, ahead)
314
+ }
315
+
316
+ /** An icon that turns with the road (the arrow) vs one drawn facing right, flipped when heading west */
317
+ const rotates = computed(() => props.rotateVehicle ?? (props.vehicleIcon === 'navigation' && !slots.vehicle))
318
+
319
+ function moveTo(d: number) {
320
+ cancelAnimationFrame(frame)
321
+ const from = at
322
+ const ms = prefersReducedMotion() ? 0 : props.duration
323
+ if (ms <= 0 || from === d) {
324
+ place(d)
325
+ travelled.value = d
326
+ arrived()
327
+ return
328
+ }
329
+ const start = performance.now()
330
+ const step = (now: number) => {
331
+ const t = Math.min(1, (now - start) / ms)
332
+ // Constant speed, as a vehicle between two GPS fixes
333
+ place(from + (d - from) * t)
334
+ if (t < 1) frame = requestAnimationFrame(step)
335
+ else {
336
+ travelled.value = d
337
+ arrived()
338
+ }
339
+ }
340
+ frame = requestAnimationFrame(step)
341
+ }
342
+
343
+ let wasArrived = false
344
+ function arrived() {
345
+ const done = total.value > 0 && at >= total.value - 1
346
+ if (done && !wasArrived) emit('arrive')
347
+ wasArrived = done
348
+ }
349
+
350
+ function fitRoute() {
351
+ if (!map || path.value.length < 2) return
352
+ map.fitBounds(bounds(path.value), { padding: props.padding, duration: prefersReducedMotion() ? 0 : 600 })
353
+ }
354
+
355
+ const showVehicle = computed(() => props.showVehicle && target.value != null)
356
+
357
+ onReady((m, ml) => {
358
+ map = m
359
+ at = target.value ?? 0
360
+ travelled.value = at
361
+ add()
362
+ if (vehicleEl.value) {
363
+ // Subpixel positions: whole pixels make a slow vehicle step a pixel every few frames, which reads as shaking
364
+ vehicleMarker = new ml.Marker({ element: vehicleEl.value, rotationAlignment: rotates.value ? 'map' : 'viewport', subpixelPositioning: true })
365
+ if (showVehicle.value) vehicleMarker.setLngLat(pointAlong(path.value, cum.value, at).lngLat).addTo(m)
366
+ }
367
+ place(at)
368
+ wasArrived = total.value > 0 && at >= total.value - 1
369
+ if (props.fit) fitRoute()
370
+ startFlow()
371
+ })
372
+ watch(() => props.flow, startFlow)
373
+
374
+ watch(styleVersion, () => add())
375
+ watch(rotates, (on) => {
376
+ vehicleMarker?.setRotationAlignment(on ? 'map' : 'viewport')
377
+ vehicleMarker?.setRotation(on ? bearingNow.value : 0)
378
+ })
379
+ watch(target, (d) => { if (d != null && map) moveTo(d) })
380
+ watch(showVehicle, (show) => {
381
+ if (!map || !vehicleMarker) return
382
+ if (show) vehicleMarker.setLngLat(pointAlong(path.value, cum.value, at).lngLat).addTo(map)
383
+ else vehicleMarker.remove()
384
+ })
385
+ // A new route (compared by value: an inline array is new on every parent render): redraw, refit
386
+ watch(pathKey, () => {
387
+ snapped = null
388
+ target.value = computeTarget()
389
+ if (!map) return
390
+ at = Math.min(target.value ?? 0, total.value)
391
+ travelled.value = at
392
+ place(at)
393
+ if (props.fit) fitRoute()
394
+ })
395
+ watch(() => [lineColor.value, theme.value.outline, theme.value.surface, props.width, props.before], () => add())
396
+
397
+ onBeforeUnmount(() => {
398
+ controller?.abort()
399
+ cancelAnimationFrame(flowFrame)
400
+ visibility?.disconnect()
401
+ cancelAnimationFrame(frame)
402
+ vehicleMarker?.remove()
403
+ if (map) {
404
+ for (const id of layerIds) if (map.getLayer(id)) map.removeLayer(id)
405
+ if (map.getSource(sourceId)) map.removeSource(sourceId)
406
+ }
407
+ map = undefined
408
+ })
409
+
410
+ const stopIcon = (stop: MapRouteStop, i: number) =>
411
+ stop.icon ?? (i === props.stops.length - 1 ? 'flag' : i === 0 ? 'trip_origin' : undefined)
412
+ const stopName = (stop: MapRouteStop, i: number) => stop.label ?? `${locale.mapRouteStop} ${i + 1}`
413
+
414
+ defineExpose({
415
+ /** Fits the map to the whole route */
416
+ fit: fitRoute,
417
+ /** The route's length, in meters */
418
+ length: total,
419
+ /** How far the vehicle is now, in meters */
420
+ travelled,
421
+ /** The source's id */
422
+ sourceId,
423
+ })
424
+ </script>
425
+
426
+ <template>
427
+ <div class="hidden">
428
+ <MMapMarker
429
+ v-for="(stop, i) in stops"
430
+ :key="i"
431
+ :lng-lat="stop.lngLat"
432
+ @click="emit('stop-click', stop, i)"
433
+ >
434
+ <slot name="stop" :stop="stop" :index="i" :done="stopDone(i)">
435
+ <span
436
+ role="img"
437
+ :aria-label="stopName(stop, i)"
438
+ :title="stopName(stop, i)"
439
+ 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"
440
+ :class="stopDone(i) ? 'border-transparent bg-primary text-on-primary' : 'border-primary bg-surface text-primary'"
441
+ :style="color ? (stopDone(i) ? { background: color } : { borderColor: color, color }) : undefined"
442
+ >
443
+ <MIcon v-if="stopIcon(stop, i)" :name="stopIcon(stop, i)!" :size="16" />
444
+ <template v-else>{{ i }}</template>
445
+ </span>
446
+ </slot>
447
+ <template v-if="$slots['stop-popup']" #popup>
448
+ <slot name="stop-popup" :stop="stop" :index="i" :done="stopDone(i)" />
449
+ </template>
450
+ </MMapMarker>
451
+
452
+ <!-- Moved into the map by MapLibre -->
453
+ <div ref="vehicleEl" class="m3-map-route-vehicle" :aria-label="locale.mapRouteVehicle" role="img">
454
+ <slot name="vehicle" :bearing="bearingNow" :west="facingWest">
455
+ <span
456
+ class="flex h-10 w-10 items-center justify-center rounded-full border-2 border-surface bg-primary text-on-primary shadow-elevation-2"
457
+ :style="color ? { background: color } : undefined"
458
+ >
459
+ <!-- Icons drawn facing right turn around when heading west; the arrow is rotated by the marker itself -->
460
+ <MIcon
461
+ :name="vehicleIcon"
462
+ :size="22"
463
+ :filled="vehicleIcon === 'navigation'"
464
+ :style="!rotates && facingWest ? { transform: 'scaleX(-1)' } : undefined"
465
+ />
466
+ </span>
467
+ </slot>
468
+ </div>
469
+ </div>
470
+ </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>
@@ -14,6 +14,7 @@
14
14
  * @event mention An item was picked: `(item, trigger)`
15
15
  */
16
16
  import { computed, nextTick, onBeforeUnmount, ref, shallowRef, useId, watch, watchEffect } from 'vue'
17
+ import type { ValidateOn, ValidationRule } from '../composables/validation'
17
18
  import MAvatar from './MAvatar.vue'
18
19
  import MIcon from './MIcon.vue'
19
20
  import MSpinner from './MSpinner.vue'
@@ -85,10 +86,18 @@ const props = withDefaults(
85
86
  leadingIcon?: string
86
87
  /** Helper text below the field */
87
88
  hint?: string
88
- /** Error state */
89
- error?: boolean
89
+ /** Error state. A string is also the message */
90
+ error?: boolean | string
90
91
  /** Error message shown when `error` is true */
91
92
  errorLabel?: string
93
+ /** Validation rules (functions or a Standard Schema); see `MForm` */
94
+ rules?: ValidationRule | ValidationRule[]
95
+ /** When the rules are checked and shown: on leaving the field (default), while typing, or only on submit */
96
+ validateOn?: ValidateOn
97
+ /** 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 */
98
+ validateDebounce?: number
99
+ /** The key of this field in its `MForm` */
100
+ name?: string
92
101
  /** Marks it as required */
93
102
  required?: boolean
94
103
  /** Disables the field */
@@ -98,6 +107,7 @@ const props = withDefaults(
98
107
  )
99
108
 
100
109
  const emit = defineEmits<{
110
+ blur: []
101
111
  'update:modelValue': [text: string]
102
112
  'update:mentions': [mentions: MentionRef[]]
103
113
  mention: [item: MentionItem, trigger: string]
@@ -325,6 +335,11 @@ defineExpose({
325
335
  :hint="hint"
326
336
  :error="error"
327
337
  :error-label="errorLabel"
338
+ :rules="rules"
339
+ :validate-on="validateOn"
340
+ :validate-debounce="validateDebounce"
341
+ :name="name"
342
+ @blur="emit('blur')"
328
343
  :required="required"
329
344
  :disabled="disabled"
330
345
  @update:model-value="onText"