@m3ui-vue/m3ui-vue 1.7.0 → 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 (88) hide show
  1. package/dist/API.md +578 -3
  2. package/dist/{MColorPickerModal-BKM1CHxr.js → MColorPickerModal-H8nuX0Wu.js} +3 -4
  3. package/dist/{MColorPickerModal-BKM1CHxr.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-BU5KDRCB.js → MListItem-DiOAxaN7.js} +102 -102
  7. package/dist/{MListItem-BU5KDRCB.js.map → MListItem-DiOAxaN7.js.map} +1 -1
  8. package/dist/{MLoadingIndicator-RykOo5tf.js → MLoadingIndicator-CuTZYFFj.js} +2 -2
  9. package/dist/{MLoadingIndicator-RykOo5tf.js.map → MLoadingIndicator-CuTZYFFj.js.map} +1 -1
  10. package/dist/{MSeekBar-B_Y3MpVz.js → MSeekBar-BCDQTx2t.js} +2 -2
  11. package/dist/{MSeekBar-B_Y3MpVz.js.map → MSeekBar-BCDQTx2t.js.map} +1 -1
  12. package/dist/{MSegmentedButton-CiOOY1-N.js → MSegmentedButton-BXzRsg1S.js} +2 -2
  13. package/dist/{MSegmentedButton-CiOOY1-N.js.map → MSegmentedButton-BXzRsg1S.js.map} +1 -1
  14. package/dist/MSignaturePad-BTqGaPXA.js +313 -0
  15. package/dist/MSignaturePad-BTqGaPXA.js.map +1 -0
  16. package/dist/{MSlider-BCeVIxcq.js → MSlider-D_O8J9YH.js} +3 -3
  17. package/dist/{MSlider-BCeVIxcq.js.map → MSlider-D_O8J9YH.js.map} +1 -1
  18. package/dist/{MSpinner-Cs03qoqE.js → MSpinner-UCdtSOHP.js} +2 -2
  19. package/dist/{MSpinner-Cs03qoqE.js.map → MSpinner-UCdtSOHP.js.map} +1 -1
  20. package/dist/{MTextField-NaFbMkjv.js → MTextField-CYk9yFvi.js} +3 -3
  21. package/dist/{MTextField-NaFbMkjv.js.map → MTextField-CYk9yFvi.js.map} +1 -1
  22. package/dist/{_useFieldValidation-Bz34IAQY.js → _useFieldValidation-B0B44M_t.js} +2 -2
  23. package/dist/{_useFieldValidation-Bz34IAQY.js.map → _useFieldValidation-B0B44M_t.js.map} +1 -1
  24. package/dist/api.json +1 -1
  25. package/dist/code-editor.js +2 -2
  26. package/dist/components/MFormBuilder.vue.d.ts +22 -0
  27. package/dist/components/MFormRenderer.vue.d.ts +151 -0
  28. package/dist/components/MMapRoute.vue.d.ts +13 -5
  29. package/dist/components/MPdfSigner.vue.d.ts +499 -0
  30. package/dist/components/MPdfViewer.vue.d.ts +12 -0
  31. package/dist/components/MPosKeypad.vue.d.ts +1 -1
  32. package/dist/components/MSpreadsheet.vue.d.ts +137 -0
  33. package/dist/components/MStack.vue.d.ts +1 -1
  34. package/dist/composables/pdfSign.d.ts +52 -0
  35. package/dist/composables/spreadsheetFormula.d.ts +55 -0
  36. package/dist/composables/useLocale.d.ts +154 -0
  37. package/dist/draw.js +2 -2
  38. package/dist/flow.js +1 -1
  39. package/dist/gantt.js +2 -2
  40. package/dist/index.d.ts +7 -0
  41. package/dist/locales/index.js +539 -0
  42. package/dist/locales/index.js.map +1 -1
  43. package/dist/m3ui-vue.css +1 -1
  44. package/dist/m3ui.js +16988 -15064
  45. package/dist/m3ui.js.map +1 -1
  46. package/dist/map.js +601 -585
  47. package/dist/map.js.map +1 -1
  48. package/dist/media.js +4 -4
  49. package/dist/pdf.d.ts +3 -0
  50. package/dist/pdf.js +1228 -687
  51. package/dist/pdf.js.map +1 -1
  52. package/dist/rich-text-editor.js +12 -13
  53. package/dist/rich-text-editor.js.map +1 -1
  54. package/dist/styles.css +1 -1
  55. package/dist/{useLocale-Dh1xZZ8i.js → useLocale-DL96OFgr.js} +78 -1
  56. package/dist/useLocale-DL96OFgr.js.map +1 -0
  57. package/package.json +5 -1
  58. package/src/__tests__/MFormRenderer.test.ts +157 -0
  59. package/src/__tests__/MMapRoute.test.ts +34 -0
  60. package/src/__tests__/MPdfSigner.test.ts +175 -0
  61. package/src/__tests__/MSpreadsheet.test.ts +223 -0
  62. package/src/__tests__/spreadsheetFormula.test.ts +77 -0
  63. package/src/__tests__/ssr.test.ts +3 -0
  64. package/src/components/MFormBuilder.vue +417 -0
  65. package/src/components/MFormRenderer.vue +324 -0
  66. package/src/components/MMapRoute.vue +64 -11
  67. package/src/components/MPdfSigner.vue +433 -0
  68. package/src/components/MPdfViewer.vue +12 -0
  69. package/src/components/MSpreadsheet.vue +992 -0
  70. package/src/composables/pdfSign.ts +141 -0
  71. package/src/composables/spreadsheetFormula.ts +459 -0
  72. package/src/composables/useLocale.ts +231 -0
  73. package/src/index.ts +7 -0
  74. package/src/locales/de.ts +77 -0
  75. package/src/locales/es.ts +77 -0
  76. package/src/locales/fr.ts +77 -0
  77. package/src/locales/ja.ts +77 -0
  78. package/src/locales/ko.ts +77 -0
  79. package/src/locales/pt.ts +77 -0
  80. package/src/locales/zh.ts +77 -0
  81. package/src/pdf.ts +3 -0
  82. package/dist/MButton-CN3wYwIG.js +0 -171
  83. package/dist/MButton-CN3wYwIG.js.map +0 -1
  84. package/dist/MDialog-1LAk9WAO.js +0 -167
  85. package/dist/MDialog-1LAk9WAO.js.map +0 -1
  86. package/dist/MProgressBar-BWly1UKN.js +0 -179
  87. package/dist/MProgressBar-BWly1UKN.js.map +0 -1
  88. package/dist/useLocale-Dh1xZZ8i.js.map +0 -1
@@ -0,0 +1,324 @@
1
+ <script lang="ts">
2
+ import type { ValidationRule } from '../composables/validation'
3
+
4
+ /** The kinds of field a form schema can hold. `heading` and `divider` only lay the form out */
5
+ export type FormFieldType =
6
+ | 'text' | 'email' | 'password' | 'tel' | 'url' | 'textarea' | 'number'
7
+ | 'select' | 'autocomplete' | 'radio' | 'checkbox' | 'switch'
8
+ | 'date' | 'time' | 'slider' | 'rating' | 'phone'
9
+ | 'heading' | 'divider'
10
+
11
+ /** A choice of a select, autocomplete or radio group */
12
+ export interface FormFieldOption {
13
+ label: string
14
+ value: string | number | boolean
15
+ }
16
+
17
+ /** Shows a field only while another field's value matches */
18
+ export interface FormFieldCondition {
19
+ /** The other field's name */
20
+ field: string
21
+ /** Its value is this */
22
+ equals?: unknown
23
+ /** Its value isn't this */
24
+ notEquals?: unknown
25
+ /** Its value is one of these */
26
+ in?: unknown[]
27
+ /** It has a value (true) or is empty (false) */
28
+ filled?: boolean
29
+ }
30
+
31
+ /** One field of a form schema: plain JSON, so it can be stored, sent and built with MFormBuilder */
32
+ export interface FormFieldSchema {
33
+ type: FormFieldType
34
+ /** The value's key (required for every type but heading and divider) */
35
+ name?: string
36
+ label?: string
37
+ placeholder?: string
38
+ /** Help under the field */
39
+ hint?: string
40
+ /** A heading's text under its title */
41
+ description?: string
42
+ required?: boolean
43
+ disabled?: boolean
44
+ /** Its value before the user changes it */
45
+ default?: unknown
46
+ /** select, autocomplete, radio: the choices (a plain string is its own label and value) */
47
+ options?: (FormFieldOption | string)[]
48
+ /** number, slider: limits. date: earliest/latest as `YYYY-MM-DD` strings */
49
+ min?: number | string
50
+ max?: number | string
51
+ step?: number
52
+ /** text-like fields: length limits */
53
+ minLength?: number
54
+ maxLength?: number
55
+ /** text-like fields: a regular expression the value must match (as a string, without slashes) */
56
+ pattern?: string
57
+ /** The message when `pattern` doesn't match */
58
+ patternMessage?: string
59
+ /** textarea: visible lines */
60
+ rows?: number
61
+ /** How much of the row it takes on a wide form (stacked on a narrow one). Default `full` */
62
+ width?: 'full' | 'half' | 'third' | 'two-thirds'
63
+ /** A Material Symbol at the start of text-like fields */
64
+ icon?: string
65
+ /** Show it only when this (or all of these) holds */
66
+ visibleWhen?: FormFieldCondition | FormFieldCondition[]
67
+ /** More rules, in code (not JSON): validators, zod/valibot schemas, functions */
68
+ rules?: ValidationRule[]
69
+ }
70
+
71
+ /** A whole form: its fields in order, and its buttons' text */
72
+ export interface FormSchema {
73
+ title?: string
74
+ description?: string
75
+ fields: FormFieldSchema[]
76
+ /** The submit button's text */
77
+ submitLabel?: string
78
+ /** Show a reset button with this text */
79
+ resetLabel?: string
80
+ }
81
+
82
+ /** Whether a field takes a value (headings and dividers don't) */
83
+ export const isValueField = (f: FormFieldSchema) => f.type !== 'heading' && f.type !== 'divider'
84
+
85
+ /** A field's options as `{ label, value }` */
86
+ export const normalizeOptions = (options: FormFieldSchema['options']): FormFieldOption[] =>
87
+ (options ?? []).map((o) => (typeof o === 'string' ? { label: o, value: o } : o))
88
+
89
+ /** What a field holds before anything is typed */
90
+ export function emptyValue(f: FormFieldSchema): unknown {
91
+ if (f.default !== undefined) return f.default
92
+ if (f.type === 'checkbox' || f.type === 'switch') return false
93
+ if (f.type === 'slider') return typeof f.min === 'number' ? f.min : 0
94
+ if (f.type === 'rating') return 0
95
+ if (f.type === 'number' || f.type === 'select' || f.type === 'autocomplete' || f.type === 'radio' || f.type === 'date' || f.type === 'time') return null
96
+ return ''
97
+ }
98
+
99
+ /** Whether a field shows, given the form's values */
100
+ export function fieldVisible(f: FormFieldSchema, values: Record<string, unknown>): boolean {
101
+ if (!f.visibleWhen) return true
102
+ const list = Array.isArray(f.visibleWhen) ? f.visibleWhen : [f.visibleWhen]
103
+ return list.every((c) => {
104
+ const v = values[c.field]
105
+ if (c.filled !== undefined) {
106
+ const filled = !(v == null || v === '' || v === false || (Array.isArray(v) && !v.length))
107
+ if (filled !== c.filled) return false
108
+ }
109
+ if ('equals' in c && c.equals !== undefined && v !== c.equals) return false
110
+ if ('notEquals' in c && c.notEquals !== undefined && v === c.notEquals) return false
111
+ if (c.in && !c.in.includes(v)) return false
112
+ return true
113
+ })
114
+ }
115
+ </script>
116
+
117
+ <script setup lang="ts">
118
+ /**
119
+ * Renders a form from a JSON schema (`FormSchema`): text, number, select, radio, checkbox, switch, date, time,
120
+ * slider, rating and phone fields, headings and dividers, laid out in rows (`width`), with their rules
121
+ * (`required`, lengths, `pattern`, email/url by type) checked by MForm, and fields that show only when another
122
+ * field has some value (`visibleWhen`). Build schemas by hand, from a backend, or with MFormBuilder. A hidden field
123
+ * isn't validated and its value isn't submitted.
124
+ *
125
+ * @slot field-{name} Replaces one field. Scope: `{ field, value, update }` (call `update(value)`)
126
+ * @slot actions Replaces the buttons. Scope: `{ reset }`
127
+ * @event submit The form passed its checks: the values of the fields on show, by name
128
+ * @event invalid Submit was blocked: the messages by field name
129
+ */
130
+ import { computed, ref, watch } from 'vue'
131
+ import MForm from './MForm.vue'
132
+ import MTextField from './MTextField.vue'
133
+ import MNumberField from './MNumberField.vue'
134
+ import MSelect from './MSelect.vue'
135
+ import MAutocomplete from './MAutocomplete.vue'
136
+ import MRadioGroup from './MRadioGroup.vue'
137
+ import MCheckbox from './MCheckbox.vue'
138
+ import MSwitch from './MSwitch.vue'
139
+ import MDatePicker from './MDatePicker.vue'
140
+ import MTimePicker from './MTimePicker.vue'
141
+ import MSlider from './MSlider.vue'
142
+ import MRating from './MRating.vue'
143
+ import MPhoneInput from './MPhoneInput.vue'
144
+ import MDivider from './MDivider.vue'
145
+ import MButton from './MButton.vue'
146
+ import { email, maxLength, minLength, pattern, url } from '../composables/validation'
147
+ import type { ValidateOn } from '../composables/validation'
148
+ import { useLocale } from '../composables/useLocale'
149
+
150
+ const props = withDefaults(
151
+ defineProps<{
152
+ /** The form to render */
153
+ schema: FormSchema
154
+ /** The values by field name (v-model). Missing ones start from each field's `default` */
155
+ modelValue?: Record<string, unknown>
156
+ /** When fields check their rules (MForm's) */
157
+ validateOn?: ValidateOn
158
+ /** Wait this long (ms) after typing stops before re-checking */
159
+ validateDebounce?: number
160
+ /** Errors from outside (a server's), by field name */
161
+ errors?: Record<string, string | string[] | null | undefined>
162
+ /** Disables every field and the buttons */
163
+ disabled?: boolean
164
+ /** Show the submit (and reset) buttons */
165
+ actions?: boolean
166
+ /** The submit button shows a spinner and can't be pressed */
167
+ loading?: boolean
168
+ }>(),
169
+ { modelValue: undefined, actions: true },
170
+ )
171
+
172
+ const emit = defineEmits<{
173
+ 'update:modelValue': [values: Record<string, unknown>]
174
+ submit: [values: Record<string, unknown>]
175
+ invalid: [errors: Record<string, string>]
176
+ }>()
177
+
178
+ const locale = useLocale()
179
+ const form = ref<InstanceType<typeof MForm>>()
180
+
181
+ /** Its own copy, so it works without v-model too */
182
+ const local = ref<Record<string, unknown>>({})
183
+ function seed() {
184
+ const next: Record<string, unknown> = { ...(props.modelValue ?? local.value) }
185
+ for (const f of props.schema.fields) if (f.name && isValueField(f) && !(f.name in next)) next[f.name] = emptyValue(f)
186
+ local.value = next
187
+ return next
188
+ }
189
+ seed()
190
+ watch(() => props.modelValue, (v) => { if (v && v !== local.value) seed() })
191
+ watch(() => props.schema.fields.map((f) => `${f.name}:${f.type}`).join(), () => {
192
+ const before = JSON.stringify(local.value)
193
+ const next = seed()
194
+ if (JSON.stringify(next) !== before) emit('update:modelValue', next)
195
+ })
196
+ // Fields the schema starts with: the parent's v-model gets their defaults
197
+ if (props.modelValue && Object.keys(local.value).some((k) => !(k in props.modelValue!))) emit('update:modelValue', local.value)
198
+
199
+ function set(name: string, value: unknown) {
200
+ local.value = { ...local.value, [name]: value }
201
+ emit('update:modelValue', local.value)
202
+ }
203
+
204
+ const visible = computed(() => props.schema.fields.filter((f) => fieldVisible(f, local.value)))
205
+
206
+ const span: Record<NonNullable<FormFieldSchema['width']>, string> = {
207
+ full: 'col-span-12',
208
+ half: 'col-span-12 @lg:col-span-6',
209
+ third: 'col-span-12 @lg:col-span-4',
210
+ 'two-thirds': 'col-span-12 @lg:col-span-8',
211
+ }
212
+
213
+ function rulesFor(f: FormFieldSchema): ValidationRule[] {
214
+ const out: ValidationRule[] = []
215
+ if (f.type === 'email') out.push(email())
216
+ if (f.type === 'url') out.push(url())
217
+ if (f.minLength != null) out.push(minLength(f.minLength))
218
+ if (f.maxLength != null) out.push(maxLength(f.maxLength))
219
+ if (f.pattern) {
220
+ try { out.push(pattern(new RegExp(f.pattern), f.patternMessage)) } catch { /* a bad expression is ignored */ }
221
+ }
222
+ return [...out, ...(f.rules ?? [])]
223
+ }
224
+
225
+ /** The component and props for each kind of field */
226
+ function control(f: FormFieldSchema): { is: unknown; props: Record<string, unknown> } {
227
+ const common = {
228
+ name: f.name,
229
+ label: f.label,
230
+ required: f.required,
231
+ disabled: f.disabled,
232
+ rules: rulesFor(f),
233
+ hint: f.hint,
234
+ }
235
+ const text = { ...common, placeholder: f.placeholder, leadingIcon: f.icon }
236
+ switch (f.type) {
237
+ case 'textarea': return { is: MTextField, props: { ...text, multiline: true, rows: f.rows ?? 3, autoGrow: true } }
238
+ case 'number': return { is: MNumberField, props: { ...text, min: num(f.min), max: num(f.max), step: f.step } }
239
+ case 'select': return { is: MSelect, props: { ...text, options: normalizeOptions(f.options), clearable: !f.required } }
240
+ case 'autocomplete': return { is: MAutocomplete, props: { ...text, options: normalizeOptions(f.options), clearable: !f.required } }
241
+ case 'radio': return { is: MRadioGroup, props: { ...common, hint: undefined, options: normalizeOptions(f.options) } }
242
+ case 'checkbox': return { is: MCheckbox, props: { ...common, hint: undefined } }
243
+ case 'switch': return { is: MSwitch, props: { ...common, hint: undefined } }
244
+ case 'date': return { is: MDatePicker, props: { ...text, leadingIcon: undefined, min: str(f.min), max: str(f.max) } }
245
+ case 'time': return { is: MTimePicker, props: { ...text, leadingIcon: undefined } }
246
+ case 'slider': return { is: MSlider, props: { ...common, hint: undefined, min: num(f.min) ?? 0, max: num(f.max) ?? 100, step: f.step ?? 1, showValue: true } }
247
+ case 'rating': return { is: MRating, props: { ...common, label: undefined, hint: undefined, max: num(f.max) ?? 5 } }
248
+ case 'phone': return { is: MPhoneInput, props: { ...text, leadingIcon: undefined } }
249
+ default: return { is: MTextField, props: { ...text, type: f.type === 'text' ? undefined : f.type } }
250
+ }
251
+ }
252
+ const num = (v: unknown) => (typeof v === 'number' ? v : typeof v === 'string' && v !== '' && !Number.isNaN(Number(v)) ? Number(v) : undefined)
253
+ const str = (v: unknown) => (typeof v === 'string' ? v : undefined)
254
+
255
+ function onSubmit() {
256
+ // The values of the fields on show, flat by name as the schema names them
257
+ const out: Record<string, unknown> = {}
258
+ for (const f of visible.value) if (f.name && isValueField(f)) out[f.name] = local.value[f.name]
259
+ emit('submit', out)
260
+ }
261
+
262
+ defineExpose({
263
+ /** Checks every field on show (or the named ones) and shows their messages; resolves to whether they pass */
264
+ validate: (...args: Parameters<NonNullable<typeof form.value>['validate']>) => form.value!.validate(...args),
265
+ /** Clears the messages */
266
+ resetValidation: (names?: string[]) => form.value?.resetValidation(names),
267
+ /** The values, defaults included */
268
+ values: computed(() => local.value),
269
+ })
270
+ </script>
271
+
272
+ <template>
273
+ <MForm
274
+ ref="form"
275
+ class="m3-form-renderer @container"
276
+ :validate-on="validateOn"
277
+ :validate-debounce="validateDebounce"
278
+ :errors="errors"
279
+ :disabled="disabled"
280
+ @submit="onSubmit"
281
+ @invalid="emit('invalid', $event)"
282
+ >
283
+ <div v-if="schema.title || schema.description" class="mb-4">
284
+ <h2 v-if="schema.title" class="text-headline-small text-on-surface">{{ schema.title }}</h2>
285
+ <p v-if="schema.description" class="mt-1 text-body-medium text-on-surface-variant">{{ schema.description }}</p>
286
+ </div>
287
+ <div class="grid grid-cols-12 gap-x-4 gap-y-5">
288
+ <template v-for="(f, i) in visible" :key="f.name ?? `${f.type}-${i}`">
289
+ <div v-if="f.type === 'heading'" class="col-span-12 pt-2">
290
+ <h3 class="text-title-medium text-on-surface">{{ f.label }}</h3>
291
+ <p v-if="f.description" class="mt-0.5 text-body-medium text-on-surface-variant">{{ f.description }}</p>
292
+ </div>
293
+ <MDivider v-else-if="f.type === 'divider'" class="col-span-12" />
294
+ <div v-else :class="span[f.width ?? 'full']" :data-field="f.name">
295
+ <slot
296
+ :name="`field-${f.name}`"
297
+ :field="f"
298
+ :value="local[f.name!]"
299
+ :update="(v: unknown) => set(f.name!, v)"
300
+ >
301
+ <div v-if="f.type === 'rating'" class="flex flex-col gap-1">
302
+ <span class="text-body-medium text-on-surface-variant">{{ f.label }}<span v-if="f.required" aria-hidden="true"> *</span></span>
303
+ <component :is="control(f).is" v-bind="control(f).props" :model-value="local[f.name!]" :aria-label="f.label" @update:model-value="set(f.name!, $event)" />
304
+ </div>
305
+ <component
306
+ :is="control(f).is"
307
+ v-else
308
+ v-bind="control(f).props"
309
+ :model-value="local[f.name!]"
310
+ class="w-full"
311
+ @update:model-value="set(f.name!, $event)"
312
+ />
313
+ </slot>
314
+ </div>
315
+ </template>
316
+ </div>
317
+ <div v-if="actions" class="mt-6 flex justify-end gap-2">
318
+ <slot name="actions" :reset="() => form?.reset()">
319
+ <MButton v-if="schema.resetLabel" type="reset" variant="text" :disabled="disabled">{{ schema.resetLabel }}</MButton>
320
+ <MButton type="submit" :loading="loading" :disabled="disabled">{{ schema.submitLabel ?? locale.formSubmit }}</MButton>
321
+ </slot>
322
+ </div>
323
+ </MForm>
324
+ </template>
@@ -68,8 +68,12 @@ const props = withDefaults(
68
68
  rotateVehicle?: boolean
69
69
  /** Show the vehicle (when there's a `progress` or `vehicle`) */
70
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
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'
73
77
  /** Fit the map to the whole route when it's shown and when the route changes */
74
78
  fit?: boolean
75
79
  /** Keep the vehicle in the middle of the map as it moves */
@@ -98,7 +102,7 @@ const props = withDefaults(
98
102
  */
99
103
  snap?: 'forward' | 'nearest'
100
104
  }>(),
101
- { rotateVehicle: undefined, flow: true, vehicleIcon: 'navigation', showVehicle: true, duration: 1000, fit: true, follow: false, padding: 64, width: 5, snap: 'forward' },
105
+ { rotateVehicle: undefined, flow: true, vehicleIcon: 'navigation', showVehicle: true, duration: 'auto', fit: true, follow: false, padding: 64, width: 5, snap: 'forward' },
102
106
  )
103
107
 
104
108
  const emit = defineEmits<{
@@ -183,6 +187,7 @@ watch([() => JSON.stringify(props.stops.map((s) => s.lngLat)), () => props.provi
183
187
  let at = 0
184
188
  const travelled = ref(0)
185
189
  const bearingNow = ref(0)
190
+ let headingNow = 0
186
191
  let frame = 0
187
192
 
188
193
  const stopDone = (i: number) => props.stops[i]?.done ?? (target.value != null && travelled.value >= stopAt.value[i]! - 1)
@@ -228,15 +233,39 @@ function add() {
228
233
  }
229
234
  }
230
235
 
231
- /** Puts the vehicle and the split of the line at `d` meters (one frame) */
232
- function place(d: number) {
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) {
233
253
  at = d
234
254
  const { lngLat } = pointAlong(path.value, cum.value, d)
235
255
  const heading = headingAt(d)
236
- ;(map?.getSource(sourceId) as Maplibre.GeoJSONSource | undefined)?.setData(data(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
+ }
237
264
  vehicleMarker?.setLngLat(lngLat)
238
265
  if (rotates.value) vehicleMarker?.setRotation(heading)
239
- bearingNow.value = 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
240
269
  // Turn the icon around only when clearly heading west or east: going north or south it keeps the way it faced,
241
270
  // instead of flipping back and forth as the heading wobbles around 180° on a real road's short segments
242
271
  if (heading > 200 && heading < 340) facingWest.value = true
@@ -316,10 +345,25 @@ function headingAt(d: number): number {
316
345
  /** An icon that turns with the road (the arrow) vs one drawn facing right, flipped when heading west */
317
346
  const rotates = computed(() => props.rotateVehicle ?? (props.vehicleIcon === 'navigation' && !slots.vehicle))
318
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
+
319
363
  function moveTo(d: number) {
320
364
  cancelAnimationFrame(frame)
321
365
  const from = at
322
- const ms = prefersReducedMotion() ? 0 : props.duration
366
+ const ms = moveDuration()
323
367
  if (ms <= 0 || from === d) {
324
368
  place(d)
325
369
  travelled.value = d
@@ -330,7 +374,7 @@ function moveTo(d: number) {
330
374
  const step = (now: number) => {
331
375
  const t = Math.min(1, (now - start) / ms)
332
376
  // Constant speed, as a vehicle between two GPS fixes
333
- place(from + (d - from) * t)
377
+ place(from + (d - from) * t, t >= 1)
334
378
  if (t < 1) frame = requestAnimationFrame(step)
335
379
  else {
336
380
  travelled.value = d
@@ -374,9 +418,13 @@ watch(() => props.flow, startFlow)
374
418
  watch(styleVersion, () => add())
375
419
  watch(rotates, (on) => {
376
420
  vehicleMarker?.setRotationAlignment(on ? 'map' : 'viewport')
377
- vehicleMarker?.setRotation(on ? bearingNow.value : 0)
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)
378
427
  })
379
- watch(target, (d) => { if (d != null && map) moveTo(d) })
380
428
  watch(showVehicle, (show) => {
381
429
  if (!map || !vehicleMarker) return
382
430
  if (show) vehicleMarker.setLngLat(pointAlong(path.value, cum.value, at).lngLat).addTo(map)
@@ -385,6 +433,7 @@ watch(showVehicle, (show) => {
385
433
  // A new route (compared by value: an inline array is new on every parent render): redraw, refit
386
434
  watch(pathKey, () => {
387
435
  snapped = null
436
+ lineAt = -1
388
437
  target.value = computeTarget()
389
438
  if (!map) return
390
439
  at = Math.min(target.value ?? 0, total.value)
@@ -451,6 +500,9 @@ defineExpose({
451
500
 
452
501
  <!-- Moved into the map by MapLibre -->
453
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)">
454
506
  <slot name="vehicle" :bearing="bearingNow" :west="facingWest">
455
507
  <span
456
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"
@@ -465,6 +517,7 @@ defineExpose({
465
517
  />
466
518
  </span>
467
519
  </slot>
520
+ </div>
468
521
  </div>
469
522
  </div>
470
523
  </template>