@m3ui-vue/m3ui-vue 1.0.2 → 1.1.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 (157) hide show
  1. package/dist/API.md +666 -12
  2. package/dist/MMenuItem-BOkcVtEe.js +809 -0
  3. package/dist/MMenuItem-BOkcVtEe.js.map +1 -0
  4. package/dist/MSlider-BXsBv0ox.js +1402 -0
  5. package/dist/MSlider-BXsBv0ox.js.map +1 -0
  6. package/dist/MTextField-rML9jnXs.js +671 -0
  7. package/dist/MTextField-rML9jnXs.js.map +1 -0
  8. package/dist/api.json +1 -1
  9. package/dist/code-editor.js +1 -1
  10. package/dist/components/MBottomSheet.vue.d.ts +20 -1
  11. package/dist/components/MDialog.vue.d.ts +17 -8
  12. package/dist/components/MDragDropList.vue.d.ts +1 -1
  13. package/dist/components/MIconButton.vue.d.ts +1 -1
  14. package/dist/components/MMap.vue.d.ts +74 -0
  15. package/dist/components/MMapBaseLayers.vue.d.ts +15 -0
  16. package/dist/components/MMapControl.vue.d.ts +40 -0
  17. package/dist/components/MMapFeatureInfo.vue.d.ts +25 -0
  18. package/dist/components/MMapFilter.vue.d.ts +19 -0
  19. package/dist/components/MMapGeoJson.vue.d.ts +34 -0
  20. package/dist/components/MMapHover.vue.d.ts +17 -0
  21. package/dist/components/MMapIdentify.vue.d.ts +37 -0
  22. package/dist/components/MMapLayers.vue.d.ts +31 -0
  23. package/dist/components/MMapMarker.vue.d.ts +45 -0
  24. package/dist/components/MMapMeasure.vue.d.ts +43 -0
  25. package/dist/components/MMapPopup.vue.d.ts +45 -0
  26. package/dist/components/MMapSearch.vue.d.ts +28 -0
  27. package/dist/components/MMenuItem.vue.d.ts +2 -2
  28. package/dist/components/MSeekBar.vue.d.ts +122 -0
  29. package/dist/components/MSplitButton.vue.d.ts +2 -2
  30. package/dist/components/_MMapAttribution.vue.d.ts +7 -0
  31. package/dist/components/_MMapLayerItem.vue.d.ts +25 -0
  32. package/dist/composables/_mapGeometry.d.ts +13 -0
  33. package/dist/composables/_mapPin.d.ts +5 -0
  34. package/dist/composables/_popupPosition.d.ts +12 -0
  35. package/dist/composables/_ssrState.d.ts +30 -0
  36. package/dist/composables/_storageKeys.d.ts +3 -0
  37. package/dist/composables/_useCalendarMonth.d.ts +24 -0
  38. package/dist/composables/_useEscapeStack.d.ts +3 -0
  39. package/dist/composables/_useScrollLock.d.ts +8 -0
  40. package/dist/composables/_useSheetMotion.d.ts +16 -1
  41. package/dist/composables/_useThemeTokens.d.ts +7 -0
  42. package/dist/composables/mapAdapters.d.ts +111 -0
  43. package/dist/composables/mapSearch.d.ts +31 -0
  44. package/dist/composables/themeInitScript.d.ts +4 -3
  45. package/dist/composables/useColorPalette.d.ts +173 -7
  46. package/dist/composables/useLocale.d.ts +38 -0
  47. package/dist/composables/useMap.d.ts +47 -0
  48. package/dist/composables/useMapFilter.d.ts +10 -0
  49. package/dist/composables/useMapLayers.d.ts +30 -0
  50. package/dist/composables/useTheme.d.ts +2 -1
  51. package/dist/index.d.ts +4 -1
  52. package/dist/locales/index.js +273 -7
  53. package/dist/locales/index.js.map +1 -1
  54. package/dist/m3ui-vue.css +1 -1
  55. package/dist/m3ui.js +7913 -8625
  56. package/dist/m3ui.js.map +1 -1
  57. package/dist/map.d.ts +24 -0
  58. package/dist/map.js +2067 -0
  59. package/dist/map.js.map +1 -0
  60. package/dist/plugin.d.ts +18 -2
  61. package/dist/rich-text-editor.js +26 -25
  62. package/dist/rich-text-editor.js.map +1 -1
  63. package/dist/styles.css +1 -1
  64. package/dist/{useLocale-CuvWRZ1h.js → useLocale-CqQrhWFl.js} +40 -2
  65. package/dist/useLocale-CqQrhWFl.js.map +1 -0
  66. package/package.json +11 -2
  67. package/src/__tests__/MDialog.test.ts +30 -0
  68. package/src/__tests__/MFab.test.ts +52 -6
  69. package/src/__tests__/MMap.test.ts +422 -0
  70. package/src/__tests__/MMapLayers.test.ts +257 -0
  71. package/src/__tests__/MMapTools.test.ts +233 -0
  72. package/src/__tests__/MSeekBar.test.ts +170 -0
  73. package/src/__tests__/MTooltip.test.ts +110 -0
  74. package/src/__tests__/_fakeMaplibre.ts +161 -0
  75. package/src/__tests__/calendarMonth.test.ts +59 -0
  76. package/src/__tests__/hydration.test.ts +33 -0
  77. package/src/__tests__/pickerModals.test.ts +128 -0
  78. package/src/__tests__/popupPosition.test.ts +224 -0
  79. package/src/__tests__/scrollLock.test.ts +110 -0
  80. package/src/__tests__/sheets.test.ts +158 -0
  81. package/src/__tests__/ssr.test.ts +63 -1
  82. package/src/__tests__/ssrState.test.ts +155 -0
  83. package/src/__tests__/themeInitScript.test.ts +18 -0
  84. package/src/components/MAutocomplete.vue +2 -4
  85. package/src/components/MBottomSheet.vue +211 -13
  86. package/src/components/MCommandPalette.vue +4 -6
  87. package/src/components/MContextMenu.vue +19 -5
  88. package/src/components/MDatePicker.vue +29 -70
  89. package/src/components/MDatePickerModal.vue +116 -172
  90. package/src/components/MDateRangePicker.vue +29 -51
  91. package/src/components/MDateRangePickerModal.vue +84 -162
  92. package/src/components/MDialog.vue +87 -63
  93. package/src/components/MFab.vue +29 -7
  94. package/src/components/MIconButton.vue +1 -1
  95. package/src/components/MLightbox.vue +12 -5
  96. package/src/components/MMap.vue +568 -0
  97. package/src/components/MMapBaseLayers.vue +67 -0
  98. package/src/components/MMapControl.vue +175 -0
  99. package/src/components/MMapFeatureInfo.vue +41 -0
  100. package/src/components/MMapFilter.vue +80 -0
  101. package/src/components/MMapGeoJson.vue +136 -0
  102. package/src/components/MMapHover.vue +131 -0
  103. package/src/components/MMapIdentify.vue +104 -0
  104. package/src/components/MMapLayers.vue +111 -0
  105. package/src/components/MMapMarker.vue +109 -0
  106. package/src/components/MMapMeasure.vue +452 -0
  107. package/src/components/MMapPopup.vue +103 -0
  108. package/src/components/MMapSearch.vue +162 -0
  109. package/src/components/MMenu.vue +31 -12
  110. package/src/components/MMenuItem.vue +21 -4
  111. package/src/components/MMultiAutocomplete.vue +2 -4
  112. package/src/components/MMultiSelect.vue +2 -4
  113. package/src/components/MNavigationDrawer.vue +2 -8
  114. package/src/components/MNavigationRail.vue +2 -3
  115. package/src/components/MSearchBar.vue +2 -5
  116. package/src/components/MSeekBar.vue +593 -0
  117. package/src/components/MSelect.vue +2 -8
  118. package/src/components/MSplitButton.vue +23 -7
  119. package/src/components/MSpotlightSearch.vue +4 -6
  120. package/src/components/MTimePicker.vue +23 -6
  121. package/src/components/MTimePickerModal.vue +213 -226
  122. package/src/components/MTooltip.vue +99 -3
  123. package/src/components/_MMapAttribution.vue +81 -0
  124. package/src/components/_MMapLayerItem.vue +77 -0
  125. package/src/composables/_mapGeometry.ts +75 -0
  126. package/src/composables/_mapPin.ts +25 -0
  127. package/src/composables/_popupPosition.ts +39 -0
  128. package/src/composables/_ssrState.ts +80 -0
  129. package/src/composables/_storageKeys.ts +6 -0
  130. package/src/composables/_useCalendarMonth.ts +74 -0
  131. package/src/composables/_useEscapeStack.ts +33 -0
  132. package/src/composables/_useScrollLock.ts +41 -0
  133. package/src/composables/_useSheetMotion.ts +82 -20
  134. package/src/composables/_useThemeTokens.ts +42 -0
  135. package/src/composables/mapAdapters.ts +208 -0
  136. package/src/composables/mapSearch.ts +56 -0
  137. package/src/composables/themeInitScript.ts +6 -4
  138. package/src/composables/useColorPalette.ts +23 -9
  139. package/src/composables/useLocale.ts +78 -0
  140. package/src/composables/useMap.ts +98 -0
  141. package/src/composables/useMapFilter.ts +45 -0
  142. package/src/composables/useMapLayers.ts +124 -0
  143. package/src/composables/useTheme.ts +8 -3
  144. package/src/composables/useWindowSizeClass.ts +14 -5
  145. package/src/index.ts +4 -1
  146. package/src/locales/de.ts +39 -1
  147. package/src/locales/es.ts +39 -1
  148. package/src/locales/fr.ts +39 -1
  149. package/src/locales/ja.ts +39 -1
  150. package/src/locales/ko.ts +39 -1
  151. package/src/locales/pt.ts +39 -1
  152. package/src/locales/zh.ts +39 -1
  153. package/src/map.ts +32 -0
  154. package/src/plugin.ts +54 -3
  155. package/dist/MTextField-BPbFeI9M.js +0 -1368
  156. package/dist/MTextField-BPbFeI9M.js.map +0 -1
  157. package/dist/useLocale-CuvWRZ1h.js.map +0 -1
@@ -18,17 +18,34 @@ import { sampleSpring, sampleAt, playSamples, prefersReducedMotion } from './_sp
18
18
  *
19
19
  * Wire it to a `<Transition :css="false" @enter @leave>` around a root holding
20
20
  * `[data-sheet-panel]` and `[data-sheet-scrim]`.
21
+ *
22
+ * Resting offsets other than fully open (MBottomSheet's partially expanded state) come from
23
+ * `anchors`: a released drag goes to the next anchor its fling points at, or past
24
+ * DISMISS_DISTANCE (or halfway to the next anchor, if closer) to the anchor nearest where it was
25
+ * dropped on that side, else back to the one it started from; off-screen (1) is always the last
26
+ * one and dismisses.
21
27
  */
22
28
 
23
29
  const DEFAULT_SPATIAL = motionSprings.standard.defaultSpatial
24
30
  const FAST_EFFECTS = motionSprings.standard.fastEffects
25
31
  const DEFAULT_EFFECTS = motionSprings.standard.defaultEffects
26
32
 
27
- /** Past this many px, or this fast (px/s) toward closing, a released drag dismisses. */
33
+ /** Past this many px, or this fast (px/s), a released drag leaves its anchor (off-screen = dismissed). */
28
34
  const DISMISS_DISTANCE = 100
29
35
  const DISMISS_VELOCITY = 1000
30
36
 
31
- export function useSheetMotion(axis: 'x' | 'y', onDismiss: () => void) {
37
+ export interface SheetMotionOptions {
38
+ /** Resting offsets while open, as fractions of the panel's size (0 = fully open). Default [0]. */
39
+ anchors?: (panel: HTMLElement) => number[]
40
+ /** The anchor an open lands on. Default 0. */
41
+ openAt?: (panel: HTMLElement) => number
42
+ /** The sheet is heading for this resting anchor (on open, a drag release or snapTo). */
43
+ onAnchor?: (anchor: number, panel: HTMLElement | null) => void
44
+ /** A drag took over the panel (true) or let go (false). */
45
+ onDrag?: (active: boolean) => void
46
+ }
47
+
48
+ export function useSheetMotion(axis: 'x' | 'y', onDismiss: () => void, opts: SheetMotionOptions = {}) {
32
49
  let panel: HTMLElement | null = null
33
50
  let scrim: HTMLElement | null = null
34
51
  // 0 = open, 1 = off-screen (a fraction of the panel's size); alpha is the scrim's opacity
@@ -43,7 +60,7 @@ export function useSheetMotion(axis: 'x' | 'y', onDismiss: () => void) {
43
60
  let settled: (() => void) | null = null
44
61
 
45
62
  let dragging = false
46
- let dragStart = 0
63
+ let dragStart0 = 0
47
64
  let dragOrigin = 0
48
65
  let size = 1
49
66
  let lastMove = { at: 0, pos: 0 }
@@ -138,7 +155,9 @@ export function useSheetMotion(axis: 'x' | 'y', onDismiss: () => void) {
138
155
  alphaTarget = 0
139
156
  velocity = 0
140
157
  write()
141
- animate(0, DEFAULT_SPATIAL, 1, done)
158
+ const to = panel && opts.openAt ? opts.openAt(panel) : 0
159
+ animate(to, DEFAULT_SPATIAL, 1, done)
160
+ opts.onAnchor?.(to, panel)
142
161
  }
143
162
 
144
163
  function onLeave(el: Element, done: () => void) {
@@ -147,48 +166,91 @@ export function useSheetMotion(axis: 'x' | 'y', onDismiss: () => void) {
147
166
  animate(1, FAST_EFFECTS, 0, done)
148
167
  }
149
168
 
150
- function onDragStart(e: PointerEvent) {
151
- // A sheet mounted already open never ran onEnter: find its elements from the handle.
152
- const root = (e.currentTarget as HTMLElement).closest('[data-sheet-panel]')?.parentElement
169
+ // A drag along the axis, from any element in the panel; positions are clientX/clientY
170
+ function dragStart(from: Element, pos: number) {
171
+ // A sheet mounted already open never ran onEnter: find its elements from the target.
172
+ const root = from.closest('[data-sheet-panel]')?.parentElement
153
173
  if (root) bind(root)
154
174
  stopOffset()
155
175
  dragging = true
156
176
  size = (panel ? (axis === 'y' ? panel.offsetHeight : panel.offsetWidth) : 0) || 1
157
- dragStart = axis === 'y' ? e.clientY : e.clientX
177
+ dragStart0 = pos
158
178
  dragOrigin = offset * size
159
179
  dragVelocity = 0
160
180
  lastMove = { at: performance.now(), pos: dragOrigin }
161
- ;(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId)
181
+ opts.onDrag?.(true)
162
182
  }
163
183
 
164
- function onDragMove(e: PointerEvent) {
165
- if (!dragging) return
184
+ // Returns how far (px) the finger went past fully open, which the panel doesn't follow
185
+ function dragMove(pos: number): number {
186
+ if (!dragging) return 0
166
187
  const now = performance.now()
167
- const pos = Math.max(0, dragOrigin + (axis === 'y' ? e.clientY : e.clientX) - dragStart)
188
+ const raw = dragOrigin + pos - dragStart0
189
+ const p = Math.max(0, raw)
168
190
  const dt = (now - lastMove.at) / 1000
169
- if (dt > 0) dragVelocity = (pos - lastMove.pos) / dt
170
- lastMove = { at: now, pos }
171
- offset = pos / size
191
+ if (dt > 0) dragVelocity = (p - lastMove.pos) / dt
192
+ lastMove = { at: now, pos: p }
193
+ offset = p / size
172
194
  if (panel) panel.style.transform = translate(offset)
195
+ return Math.max(0, -raw)
173
196
  }
174
197
 
175
- function onDragEnd() {
198
+ function dragEnd() {
176
199
  if (!dragging) return
177
200
  dragging = false
201
+ opts.onDrag?.(false)
178
202
  // A pause before lifting the finger means no fling.
179
203
  if (performance.now() - lastMove.at > 100) dragVelocity = 0
180
204
  velocity = dragVelocity / size
181
- if (offset * size > DISMISS_DISTANCE || dragVelocity > DISMISS_VELOCITY) {
182
- onDismiss()
205
+ const stops = [...(panel && opts.anchors ? opts.anchors(panel) : [0]), 1].sort((a, b) => a - b)
206
+ const nearest = (list: number[], x: number) =>
207
+ list.reduce((best, s) => (Math.abs(s - x) < Math.abs(best - x) ? s : best), list[0]!)
208
+ const start = nearest(stops, dragOrigin / size)
209
+ let to = start
210
+ if (Math.abs(dragVelocity) > DISMISS_VELOCITY) {
211
+ const ahead = dragVelocity > 0
212
+ ? stops.filter((s) => s > offset + 1e-3)
213
+ : stops.filter((s) => s < offset - 1e-3).reverse()
214
+ to = ahead[0] ?? (dragVelocity > 0 ? stops[stops.length - 1]! : stops[0]!)
183
215
  } else {
184
- animate(0, DEFAULT_SPATIAL, alphaTarget)
216
+ // Past DISMISS_DISTANCE, or halfway to the next anchor when that's closer
217
+ const side = stops.filter((s) => (offset > start ? s > start : s < start))
218
+ const next = side.length ? nearest(side, start) : start
219
+ if (side.length && Math.abs(offset - start) > Math.min(DISMISS_DISTANCE / size, Math.abs(next - start) / 2)) {
220
+ to = nearest(side, offset)
221
+ }
185
222
  }
223
+ if (to >= 1) return onDismiss()
224
+ animate(to, DEFAULT_SPATIAL, alphaTarget)
225
+ opts.onAnchor?.(to, panel)
226
+ }
227
+
228
+ function onDragStart(e: PointerEvent) {
229
+ const el = e.currentTarget as HTMLElement
230
+ dragStart(el, axis === 'y' ? e.clientY : e.clientX)
231
+ el.setPointerCapture(e.pointerId)
232
+ }
233
+
234
+ function onDragMove(e: PointerEvent) {
235
+ dragMove(axis === 'y' ? e.clientY : e.clientX)
186
236
  }
187
237
 
238
+ const onDragEnd = dragEnd
239
+
240
+ /** Springs an open sheet to a resting anchor (not while a drag holds it). */
241
+ function snapTo(anchor: number) {
242
+ if (!panel || dragging || Math.abs(offset - anchor) < 1e-3) return
243
+ animate(anchor, DEFAULT_SPATIAL, alphaTarget)
244
+ opts.onAnchor?.(anchor, panel)
245
+ }
246
+
247
+ /** Where the panel is headed (or sits), as a fraction of its size. */
248
+ const target = () => offset
249
+
188
250
  onBeforeUnmount(() => {
189
251
  offsetAnim?.cancel()
190
252
  alphaAnim?.cancel()
191
253
  })
192
254
 
193
- return { onEnter, onLeave, onDragStart, onDragMove, onDragEnd }
255
+ return { onEnter, onLeave, onDragStart, onDragMove, onDragEnd, dragStart, dragMove, dragEnd, snapTo, target }
194
256
  }
@@ -0,0 +1,42 @@
1
+ import { onBeforeUnmount, onMounted, ref, type Ref } from 'vue'
2
+ import { STYLE_ID } from './_storageKeys'
3
+
4
+ /**
5
+ * The current values of some color tokens (`['primary', 'surface']` → `--color-primary`…), kept up to date across
6
+ * theme, palette and contrast changes: for what can't use CSS variables (a MapLibre layer's paint, a canvas). Empty
7
+ * strings on the server.
8
+ */
9
+ export function useThemeTokens<T extends string>(names: readonly T[]): Ref<Record<T, string>> {
10
+ const read = () => {
11
+ const style = getComputedStyle(document.documentElement)
12
+ return Object.fromEntries(names.map((n) => [n, style.getPropertyValue(`--color-${n}`).trim()])) as Record<T, string>
13
+ }
14
+ const tokens = ref(typeof document === 'undefined' ? Object.fromEntries(names.map((n) => [n, ''])) as Record<T, string> : read()) as Ref<Record<T, string>>
15
+ let observer: MutationObserver | undefined
16
+ let settle: ReturnType<typeof setTimeout> | undefined
17
+
18
+ onMounted(() => {
19
+ const update = () => {
20
+ const next = read()
21
+ if (names.some((n) => next[n] !== tokens.value[n])) tokens.value = next
22
+ }
23
+ // Dark mode (class), a palette or contrast (attributes), or a generated palette rewriting its <style> in <head>
24
+ const isPaletteStyle = (node: Node | null) => (node instanceof Element ? node : node?.parentElement)?.id === STYLE_ID
25
+ observer = new MutationObserver((records) => {
26
+ if (!records.some((r) => r.target === document.documentElement || isPaletteStyle(r.target)
27
+ || Array.from(r.addedNodes).some(isPaletteStyle))) return
28
+ update()
29
+ // Chromium animates the tokens on a theme switch (_themeTransition, 250ms): read the settled values too
30
+ clearTimeout(settle)
31
+ settle = setTimeout(update, 300)
32
+ })
33
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-palette', 'data-contrast'] })
34
+ observer.observe(document.head, { childList: true, characterData: true, subtree: true })
35
+ })
36
+ onBeforeUnmount(() => {
37
+ observer?.disconnect()
38
+ clearTimeout(settle)
39
+ })
40
+
41
+ return tokens
42
+ }
@@ -0,0 +1,208 @@
1
+ import type * as Maplibre from 'maplibre-gl'
2
+
3
+ /** How to show one property of a feature. */
4
+ export interface MapFieldFormat {
5
+ /** The label (the key, capitalized, by default) */
6
+ label?: string
7
+ /** Text before the value */
8
+ prefix?: string
9
+ /** Text after the value */
10
+ suffix?: string
11
+ /** A number mask: its decimals set the fraction digits (`#.00` → 2) and a comma turns on grouping (`#,###`) */
12
+ mask?: string
13
+ /** Leave it out */
14
+ hidden?: boolean
15
+ }
16
+
17
+ /** One layer of the style, as the map's UI components see it. */
18
+ export interface MapLayerInfo {
19
+ /** The style layer's id */
20
+ id: string
21
+ /** Its name in the UI */
22
+ title: string
23
+ description?: string
24
+ /** The `name` of its group in `MapLayerModel.groups` */
25
+ group?: string
26
+ /** Shown in `MMapLayers` */
27
+ listed: boolean
28
+ /** A base layer: `MMapBaseLayers` shows one of them at a time, with this thumbnail */
29
+ base?: { image?: string }
30
+ /** Layer ids shown, hidden and faded along with it */
31
+ children: string[]
32
+ /** Listed by `MMapIdentify` on click: every property, formatted by `format`, minus `exclude` */
33
+ identify: false | { format: Record<string, MapFieldFormat>; exclude: string[] }
34
+ /** Shown by `MMapHover` under the pointer: these properties, in order */
35
+ hover: false | { fields: (MapFieldFormat & { key: string })[] }
36
+ /** A legend image URL (an SVG, typically) */
37
+ legend?: string
38
+ /** A download URL for its data */
39
+ download?: string
40
+ }
41
+
42
+ /** The style as the map's UI components see it: layers with names, groups, base layers, what to identify. */
43
+ export interface MapLayerModel {
44
+ /** The style's name */
45
+ title?: string
46
+ /** Groups, in order */
47
+ groups: { name: string; title: string }[]
48
+ /** Layers, in the style's order (bottom to top) */
49
+ layers: MapLayerInfo[]
50
+ }
51
+
52
+ /** What an adapter gets besides the style. */
53
+ export interface MapAdapterContext {
54
+ /** The style's URL, when `MMap`'s `mapStyle` is one */
55
+ styleUrl?: string
56
+ }
57
+
58
+ /** Reads a style's conventions (usually its `metadata`) into the model the map's UI components use. */
59
+ export type MapAdapter = (style: Maplibre.StyleSpecification, context: MapAdapterContext) => MapLayerModel
60
+
61
+ type Metadata = Record<string, unknown> | undefined
62
+ const meta = (layer: { metadata?: unknown }) => layer.metadata as Metadata
63
+ const VECTOR = new Set(['fill', 'line', 'circle', 'symbol', 'fill-extrusion', 'heatmap'])
64
+
65
+ /**
66
+ * Any style: every layer but the background is listed under its id (or `metadata.title`), vector layers identify all
67
+ * their properties, and nothing is a base layer or shows on hover.
68
+ */
69
+ export const genericAdapter: MapAdapter = (style) => ({
70
+ title: style.name,
71
+ groups: [],
72
+ layers: style.layers
73
+ .filter((l) => l.type !== 'background')
74
+ .map((l) => ({
75
+ id: l.id,
76
+ title: (meta(l)?.title as string | undefined) ?? l.id,
77
+ listed: true,
78
+ children: [],
79
+ identify: VECTOR.has(l.type) ? { format: {}, exclude: [] } : false,
80
+ hover: false,
81
+ })),
82
+ })
83
+
84
+ export interface OrvianAdapterOptions {
85
+ /**
86
+ * A layer's legend image. By default, for a style served by mvt-rs (`…/services/styles/<style>`), its legend service
87
+ * (`…/services/legends/<style>?layer_id=<id>`), unless the layer's `metadata.legend.show` is false;
88
+ * `metadata.legend.wmslegend` overrides it
89
+ */
90
+ legend?: (layer: Maplibre.LayerSpecification, styleUrl?: string) => string | undefined
91
+ }
92
+
93
+ /**
94
+ * The Orvian viewers' conventions in the style's `metadata`. On each layer: `alias`, `description`, `group`,
95
+ * `show_in_layerlist` (false hides it from the list), `isbaselayer` with `image` (raster base layers), `childs` (layer
96
+ * ids toggled with it), `identify` (true lists its properties on click), `fields` (per property: `alias`, `prefix`,
97
+ * `suffix`, `mask`, `show: false`; plus `exclude`, a list of properties to leave out), `hover` (`enable` and `fields`,
98
+ * a list of `{ <property>: { alias, prefix, suffix, mask } }`), `legend` (`show`, `wmslegend`) and `download`. On the
99
+ * style: `groups` (`{ name, alias }`, in order).
100
+ */
101
+ export function orvianAdapter(options: OrvianAdapterOptions = {}): MapAdapter {
102
+ const legendOf = options.legend ?? ((layer, styleUrl) => {
103
+ const legend = meta(layer)?.legend as { show?: boolean; wmslegend?: string } | undefined
104
+ if (legend?.show === false) return undefined
105
+ if (legend?.wmslegend) return legend.wmslegend
106
+ if (!styleUrl?.includes('/services/styles/')) return undefined
107
+ const url = styleUrl.replace('/services/styles/', '/services/legends/')
108
+ return `${url}${url.includes('?') ? '&' : '?'}has_label=false&include_raster=true&layer_id=${encodeURIComponent(layer.id)}`
109
+ })
110
+
111
+ return (style, { styleUrl }) => {
112
+ const groups = ((style.metadata as Metadata)?.groups as { name: string; alias?: string }[] | undefined) ?? []
113
+ return {
114
+ title: style.name,
115
+ groups: groups.map((g) => ({ name: g.name, title: g.alias ?? g.name })),
116
+ layers: style.layers
117
+ .filter((l) => l.type !== 'background')
118
+ .map((l) => {
119
+ const m = meta(l) ?? {}
120
+ const fields = { ...(m.fields as Record<string, unknown> | undefined) }
121
+ const exclude = (fields.exclude as string[] | undefined) ?? []
122
+ delete fields.exclude
123
+ const format: Record<string, MapFieldFormat> = {}
124
+ for (const [key, f] of Object.entries(fields as Record<string, { alias?: string; prefix?: string; suffix?: string; mask?: string; show?: boolean }>)) {
125
+ format[key] = { label: f.alias, prefix: f.prefix, suffix: f.suffix, mask: f.mask, hidden: f.show === false }
126
+ }
127
+ const hover = m.hover as { enable?: boolean; fields?: Record<string, MapFieldFormat & { alias?: string }>[] } | undefined
128
+ const base = l.type === 'raster' && m.isbaselayer === true
129
+ return {
130
+ id: l.id,
131
+ title: (m.alias as string | undefined) ?? l.id,
132
+ description: m.description as string | undefined,
133
+ group: m.group as string | undefined,
134
+ listed: !base && m.show_in_layerlist !== false,
135
+ base: base && m.show_in_layerlist !== false ? { image: m.image as string | undefined } : undefined,
136
+ children: Array.isArray(m.childs) ? (m.childs as string[]) : [],
137
+ identify: m.identify === true ? { format, exclude } : false,
138
+ hover: hover?.enable
139
+ ? {
140
+ fields: (hover.fields ?? []).flatMap((entry) =>
141
+ Object.entries(entry).map(([key, f]) => ({ key, label: f.alias ?? f.label, prefix: f.prefix, suffix: f.suffix, mask: f.mask }))),
142
+ }
143
+ : false,
144
+ legend: base ? undefined : legendOf(l, styleUrl),
145
+ download: l.type !== 'raster' ? (m.download as string | undefined) : undefined,
146
+ } satisfies MapLayerInfo
147
+ }),
148
+ }
149
+ }
150
+ }
151
+
152
+ /** A property's label: its format's, or the key with a capital first letter. */
153
+ export function fieldLabel(key: string, format?: MapFieldFormat): string {
154
+ return format?.label ?? key.charAt(0).toUpperCase() + key.slice(1)
155
+ }
156
+
157
+ /**
158
+ * A property's value as text: numbers through `mask` (in the page's language, `<html lang>`), then `prefix` and
159
+ * `suffix`. Empty values give ''.
160
+ */
161
+ export function formatFieldValue(raw: unknown, format?: MapFieldFormat): string {
162
+ if (raw === null || raw === undefined || String(raw).trim() === '') return ''
163
+ let value = String(raw)
164
+ const num = typeof raw === 'number' ? raw : Number(raw)
165
+ if (format?.mask && !Number.isNaN(num)) {
166
+ const decimals = format.mask.split('.')[1]?.length ?? 0
167
+ const lang = typeof document !== 'undefined' ? document.documentElement.lang || undefined : undefined
168
+ value = new Intl.NumberFormat(lang, {
169
+ minimumFractionDigits: decimals,
170
+ maximumFractionDigits: decimals,
171
+ useGrouping: format.mask.includes(','),
172
+ }).format(num)
173
+ }
174
+ if (format?.prefix) value = `${format.prefix} ${value}`
175
+ if (format?.suffix) value = `${value} ${format.suffix}`
176
+ return value
177
+ }
178
+
179
+ /** What `MMapIdentify` found on one layer at a point. */
180
+ export interface MapIdentifyResult {
181
+ layer: MapLayerInfo
182
+ feature: Maplibre.MapGeoJSONFeature
183
+ /** Its properties as the layer's `identify` shows them, formatted */
184
+ fields: { key: string; label: string; value: string }[]
185
+ }
186
+
187
+ // Keys MapLibre or a previous identify adds to a feature's properties
188
+ const INTERNAL_KEYS = new Set(['coordinates', 'mapCoordinates', 'layerId', '__layerMetadata'])
189
+
190
+ /**
191
+ * The features of the model's identify layers at a point (topmost first), with their properties formatted: what
192
+ * `MMapIdentify` lists on click, for a UI of your own.
193
+ */
194
+ export function identifyFeatures(map: Maplibre.Map, point: Maplibre.PointLike, model: MapLayerModel | undefined): MapIdentifyResult[] {
195
+ const layers = new Map((model?.layers ?? []).filter((l) => l.identify && map.getLayer(l.id)).map((l) => [l.id, l]))
196
+ if (!layers.size) return []
197
+ const results: MapIdentifyResult[] = []
198
+ for (const feature of map.queryRenderedFeatures(point, { layers: [...layers.keys()] })) {
199
+ const layer = layers.get(feature.layer.id)
200
+ if (!layer || !layer.identify) continue
201
+ const { format, exclude } = layer.identify
202
+ const fields = Object.entries(feature.properties ?? {})
203
+ .filter(([key]) => !INTERNAL_KEYS.has(key) && !exclude.includes(key) && !format[key]?.hidden)
204
+ .map(([key, raw]) => ({ key, label: fieldLabel(key, format[key]), value: formatFieldValue(raw, format[key]) }))
205
+ if (fields.length) results.push({ layer, feature, fields })
206
+ }
207
+ return results
208
+ }
@@ -0,0 +1,56 @@
1
+ /** A place found by a `MapSearchProvider`. */
2
+ export interface MapSearchResult {
3
+ /** What to show */
4
+ label: string
5
+ /** Where it is */
6
+ lngLat: [number, number]
7
+ /** Its extent, `[west, south, east, north]`: the map fits it instead of zooming to the point */
8
+ bbox?: [number, number, number, number]
9
+ /** Its kind (`city`, `road`, `park`, `restaurant`…), for the icon */
10
+ type?: string
11
+ }
12
+
13
+ /** Finds places for `MMapSearch`: the text in, results out. `signal` aborts a search the user replaced. */
14
+ export type MapSearchProvider = (query: string, signal: AbortSignal) => Promise<MapSearchResult[]>
15
+
16
+ export interface NominatimOptions {
17
+ /** The Nominatim server (`https://nominatim.openstreetmap.org` by default; mind its usage policy, or run your own) */
18
+ url?: string
19
+ /** How many results (6) */
20
+ limit?: number
21
+ /** The results' language (`es`, `en`…); by default the page's (`<html lang>`) */
22
+ language?: string
23
+ /** Only these countries (ISO codes: `['ar']`) */
24
+ countryCodes?: string[]
25
+ /** Prefer (or with `bounded`, only) this area: `[west, south, east, north]` */
26
+ viewbox?: [number, number, number, number]
27
+ bounded?: boolean
28
+ }
29
+
30
+ /**
31
+ * OpenStreetMap's Nominatim geocoder. Its public server allows one search per second and no search-as-you-type:
32
+ * `MMapSearch` searches on Enter.
33
+ */
34
+ export function nominatimProvider(options: NominatimOptions = {}): MapSearchProvider {
35
+ return async (query, signal) => {
36
+ const params = new URLSearchParams({ format: 'jsonv2', q: query, limit: String(options.limit ?? 6) })
37
+ const language = options.language ?? (typeof document !== 'undefined' ? document.documentElement.lang : '')
38
+ if (language) params.set('accept-language', language)
39
+ if (options.countryCodes?.length) params.set('countrycodes', options.countryCodes.join(','))
40
+ if (options.viewbox) params.set('viewbox', options.viewbox.join(','))
41
+ if (options.bounded) params.set('bounded', '1')
42
+ const res = await fetch(`${options.url ?? 'https://nominatim.openstreetmap.org'}/search?${params}`, { signal })
43
+ if (!res.ok) throw new Error(`Nominatim: ${res.status}`)
44
+ const data = await res.json() as { display_name: string; lat: string; lon: string; type?: string; boundingbox?: string[] }[]
45
+ return data.map((r) => {
46
+ // Nominatim's boundingbox is [south, north, west, east]
47
+ const b = r.boundingbox?.map(Number)
48
+ return {
49
+ label: r.display_name,
50
+ lngLat: [Number(r.lon), Number(r.lat)] as [number, number],
51
+ bbox: b && b.length === 4 ? [b[2]!, b[0]!, b[3]!, b[1]!] as [number, number, number, number] : undefined,
52
+ type: r.type,
53
+ }
54
+ })
55
+ }
56
+ }
@@ -1,9 +1,9 @@
1
1
  import { THEME_KEY } from './useTheme'
2
- import { CONTRAST_KEY, CSS_KEY, PALETTE_KEY, STYLE_ID, type ContrastLevel } from './useColorPalette'
2
+ import { CONTRAST_KEY, CSS_KEY, PALETTE_KEY, STYLE_ID, type ContrastLevel, type PaletteId } from './useColorPalette'
3
3
 
4
4
  export interface ThemeInitOptions {
5
5
  /** `createM3UI`'s `palette`: the first-visit default, or forced with `persistPalette: false`. */
6
- palette?: string
6
+ palette?: PaletteId | (string & {})
7
7
  /** `createM3UI`'s `contrast`, with the same rules as `palette`. */
8
8
  contrast?: ContrastLevel
9
9
  /** `createM3UI`'s `persistPalette`. */
@@ -14,7 +14,8 @@ export interface ThemeInitOptions {
14
14
  * A script to inline in `<head>` of a server-rendered page (Nuxt, Vite SSR), so dark mode, the palette and the
15
15
  * contrast level are on `<html>` before the first paint instead of when the app's JS loads. It does what
16
16
  * `useTheme` and `useColorPalette` do when they load in the browser (the stored choice, or the given
17
- * `createM3UI` defaults), so pass it the same options as the plugin. A `seed` default can't be generated this
17
+ * `createM3UI` defaults; a choice only in a cookie, from `createM3UI({ cookies })`, counts too), so pass it the same
18
+ * options as the plugin. A `seed` default can't be generated this
18
19
  * early: its first visit still shows the baseline until the app loads (later visits use the cached CSS).
19
20
  *
20
21
  * ```ts
@@ -32,7 +33,8 @@ export function themeInitScript(options: ThemeInitOptions = {}): string {
32
33
  // Plain ES5, no dependencies: it runs before anything else. Storage can throw (blocked site data).
33
34
  return `(function(o){
34
35
  var d=document.documentElement;
35
- function get(k){try{return localStorage.getItem(k)}catch(e){return null}}
36
+ function cookie(k){var m=document.cookie.match(new RegExp('(?:^|; )'+k+'=([^;]*)'));try{return m?decodeURIComponent(m[1]):null}catch(e){return null}}
37
+ function get(k){var v=null;try{v=localStorage.getItem(k)}catch(e){}return v!=null||k===o.keys.css?v:cookie(k)}
36
38
  function mq(q){return !!(window.matchMedia&&window.matchMedia(q).matches)}
37
39
  var t=get(o.keys.theme)||'system';
38
40
  d.classList.toggle('dark',t==='dark'||(t==='system'&&mq('(prefers-color-scheme: dark)')));
@@ -1,6 +1,8 @@
1
- import { computed, readonly, ref, watch, watchEffect } from 'vue'
1
+ import { computed, readonly, ref, watch, watchEffect, type Ref } from 'vue'
2
2
  import { generateScheme, schemeToCss, type SeedOptions } from './dynamicColor'
3
3
  import { themeTransition } from './_themeTransition'
4
+ import { initialState, readCookie, ssrValue, writeCookie } from './_ssrState'
5
+ import { STYLE_ID } from './_storageKeys'
4
6
 
5
7
  export interface Palette {
6
8
  id: string
@@ -12,7 +14,7 @@ export interface Palette {
12
14
  seed: string
13
15
  }
14
16
 
15
- export const palettes: Palette[] = [
17
+ const builtInPalettes = [
16
18
  { id: 'purple', label: 'Purple', seed: '#6750A4' },
17
19
  { id: 'indigo', label: 'Indigo', seed: '#4355B9' },
18
20
  { id: 'navy', label: 'Navy', seed: '#354BA0' },
@@ -53,7 +55,13 @@ export const palettes: Palette[] = [
53
55
  { id: 'amethyst', label: 'Amethyst', seed: '#5953AC' },
54
56
  { id: 'magenta', label: 'Magenta', seed: '#8D3F92' },
55
57
  { id: 'mauve', label: 'Mauve', seed: '#914277' },
56
- ]
58
+ ] as const
59
+
60
+ /** The id of a palette that ships with the library (`palettes.css`, plus the `purple` baseline). */
61
+ export type PaletteId = (typeof builtInPalettes)[number]['id']
62
+
63
+ /** Every palette: the built-in ones, plus `createM3UI({ customPalettes })`. */
64
+ export const palettes: Palette[] = [...builtInPalettes]
57
65
 
58
66
  // Ids whose CSS ships in palettes.css (plus 'purple', the theme.css baseline): never generated
59
67
  const builtInIds = new Set(palettes.map((p) => p.id))
@@ -73,13 +81,16 @@ export const CSS_KEY = 'm3-palette-css'
73
81
 
74
82
  function read<T>(key: string): T | null {
75
83
  try {
76
- const v = localStorage.getItem(key)
84
+ // The palette and the contrast level fall back to their cookies (createM3UI({ cookies })) when storage has none
85
+ const v = localStorage.getItem(key) ?? (key === PALETTE_KEY || key === CONTRAST_KEY ? readCookie(key) : null)
77
86
  return v == null ? null : (key === PALETTE_KEY || key === CONTRAST_KEY ? v : JSON.parse(v)) as T
78
87
  } catch {
79
88
  return null
80
89
  }
81
90
  }
82
91
  function write(key: string, value: unknown) {
92
+ // The palette and the contrast level also go in cookies (createM3UI({ cookies: true })) for a server to read
93
+ if (key === PALETTE_KEY || key === CONTRAST_KEY) writeCookie(key, value == null ? null : String(value))
83
94
  try {
84
95
  if (value == null) localStorage.removeItem(key)
85
96
  else localStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value))
@@ -135,7 +146,7 @@ function applyAttribute(id: string) {
135
146
  // One <style> element holds the generated CSS of the active palette (a seed, or a custom palette
136
147
  // without CSS of its own).
137
148
 
138
- export const STYLE_ID = 'm3-dynamic-palette'
149
+ export { STYLE_ID }
139
150
 
140
151
  function injectCss(css: string) {
141
152
  if (typeof document === 'undefined') return
@@ -251,7 +262,7 @@ export function useColorPalette() {
251
262
  })
252
263
 
253
264
  /** Switches to a palette by id. */
254
- function set(id: string) {
265
+ function set(id: PaletteId | (string & {})) {
255
266
  void selectPalette(id)
256
267
  }
257
268
 
@@ -278,14 +289,17 @@ export function useColorPalette() {
278
289
  void selectContrast(level)
279
290
  }
280
291
 
292
+ // Server-side rendering with `createM3UI({ initialState })`: the user's choice as the server knows it (it can't
293
+ // know the OS's contrast preference, so `system` is standard there)
294
+ const initial = initialState()
281
295
  return {
282
- palette: current,
296
+ palette: ssrValue(current, initial?.palette),
283
297
  palettes,
284
298
  set,
285
299
  seed: readonly(activeSeed),
286
300
  setSeed,
287
- contrast: readonly(contrast),
288
- activeContrast,
301
+ contrast: ssrValue(readonly(contrast) as Ref<ContrastLevel>, initial?.contrast) as Readonly<Ref<ContrastLevel>>,
302
+ activeContrast: ssrValue(activeContrast, initial ? (initial.contrast === 'system' ? 'standard' : initial.contrast) : undefined),
289
303
  setContrast,
290
304
  persistPalette: persistEnabled,
291
305
  setPersistPalette,