@m3ui-vue/m3ui-vue 1.0.2 → 1.0.3

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 (106) hide show
  1. package/dist/API.md +599 -9
  2. package/dist/MMenuItem-DFyXflk9.js +707 -0
  3. package/dist/MMenuItem-DFyXflk9.js.map +1 -0
  4. package/dist/MSlider-CdNIH7jc.js +1376 -0
  5. package/dist/MSlider-CdNIH7jc.js.map +1 -0
  6. package/dist/MTextField-B4X92vH_.js +671 -0
  7. package/dist/MTextField-B4X92vH_.js.map +1 -0
  8. package/dist/api.json +1 -1
  9. package/dist/code-editor.js +1 -1
  10. package/dist/components/MIconButton.vue.d.ts +1 -1
  11. package/dist/components/MMap.vue.d.ts +74 -0
  12. package/dist/components/MMapBaseLayers.vue.d.ts +15 -0
  13. package/dist/components/MMapControl.vue.d.ts +23 -0
  14. package/dist/components/MMapFeatureInfo.vue.d.ts +25 -0
  15. package/dist/components/MMapFilter.vue.d.ts +19 -0
  16. package/dist/components/MMapGeoJson.vue.d.ts +34 -0
  17. package/dist/components/MMapHover.vue.d.ts +17 -0
  18. package/dist/components/MMapIdentify.vue.d.ts +37 -0
  19. package/dist/components/MMapLayers.vue.d.ts +31 -0
  20. package/dist/components/MMapMarker.vue.d.ts +42 -0
  21. package/dist/components/MMapMeasure.vue.d.ts +43 -0
  22. package/dist/components/MMapPopup.vue.d.ts +43 -0
  23. package/dist/components/MMapSearch.vue.d.ts +28 -0
  24. package/dist/components/_MMapLayerItem.vue.d.ts +25 -0
  25. package/dist/composables/_mapGeometry.d.ts +13 -0
  26. package/dist/composables/_ssrState.d.ts +30 -0
  27. package/dist/composables/_storageKeys.d.ts +3 -0
  28. package/dist/composables/_useThemeTokens.d.ts +7 -0
  29. package/dist/composables/mapAdapters.d.ts +111 -0
  30. package/dist/composables/mapSearch.d.ts +31 -0
  31. package/dist/composables/themeInitScript.d.ts +4 -3
  32. package/dist/composables/useColorPalette.d.ts +173 -7
  33. package/dist/composables/useLocale.d.ts +30 -0
  34. package/dist/composables/useMap.d.ts +47 -0
  35. package/dist/composables/useMapFilter.d.ts +10 -0
  36. package/dist/composables/useMapLayers.d.ts +30 -0
  37. package/dist/composables/useTheme.d.ts +2 -1
  38. package/dist/index.d.ts +2 -1
  39. package/dist/locales/index.js +217 -7
  40. package/dist/locales/index.js.map +1 -1
  41. package/dist/m3ui-vue.css +1 -1
  42. package/dist/m3ui.js +6709 -7976
  43. package/dist/m3ui.js.map +1 -1
  44. package/dist/map.d.ts +24 -0
  45. package/dist/map.js +1931 -0
  46. package/dist/map.js.map +1 -0
  47. package/dist/plugin.d.ts +18 -2
  48. package/dist/rich-text-editor.js +27 -26
  49. package/dist/rich-text-editor.js.map +1 -1
  50. package/dist/styles.css +1 -1
  51. package/dist/{useLocale-CuvWRZ1h.js → useLocale-b5-hzsL3.js} +32 -2
  52. package/dist/useLocale-b5-hzsL3.js.map +1 -0
  53. package/package.json +11 -2
  54. package/src/__tests__/MFab.test.ts +52 -6
  55. package/src/__tests__/MMap.test.ts +292 -0
  56. package/src/__tests__/MMapLayers.test.ts +257 -0
  57. package/src/__tests__/MMapTools.test.ts +233 -0
  58. package/src/__tests__/_fakeMaplibre.ts +158 -0
  59. package/src/__tests__/hydration.test.ts +33 -0
  60. package/src/__tests__/ssr.test.ts +63 -1
  61. package/src/__tests__/ssrState.test.ts +155 -0
  62. package/src/__tests__/themeInitScript.test.ts +18 -0
  63. package/src/components/MFab.vue +29 -7
  64. package/src/components/MIconButton.vue +1 -1
  65. package/src/components/MLightbox.vue +6 -2
  66. package/src/components/MMap.vue +522 -0
  67. package/src/components/MMapBaseLayers.vue +67 -0
  68. package/src/components/MMapControl.vue +61 -0
  69. package/src/components/MMapFeatureInfo.vue +41 -0
  70. package/src/components/MMapFilter.vue +80 -0
  71. package/src/components/MMapGeoJson.vue +136 -0
  72. package/src/components/MMapHover.vue +131 -0
  73. package/src/components/MMapIdentify.vue +103 -0
  74. package/src/components/MMapLayers.vue +111 -0
  75. package/src/components/MMapMarker.vue +102 -0
  76. package/src/components/MMapMeasure.vue +452 -0
  77. package/src/components/MMapPopup.vue +99 -0
  78. package/src/components/MMapSearch.vue +162 -0
  79. package/src/components/_MMapLayerItem.vue +77 -0
  80. package/src/composables/_mapGeometry.ts +75 -0
  81. package/src/composables/_ssrState.ts +80 -0
  82. package/src/composables/_storageKeys.ts +6 -0
  83. package/src/composables/_useThemeTokens.ts +42 -0
  84. package/src/composables/mapAdapters.ts +208 -0
  85. package/src/composables/mapSearch.ts +56 -0
  86. package/src/composables/themeInitScript.ts +6 -4
  87. package/src/composables/useColorPalette.ts +23 -9
  88. package/src/composables/useLocale.ts +62 -0
  89. package/src/composables/useMap.ts +98 -0
  90. package/src/composables/useMapFilter.ts +45 -0
  91. package/src/composables/useMapLayers.ts +124 -0
  92. package/src/composables/useTheme.ts +8 -3
  93. package/src/composables/useWindowSizeClass.ts +14 -5
  94. package/src/index.ts +2 -1
  95. package/src/locales/de.ts +31 -1
  96. package/src/locales/es.ts +31 -1
  97. package/src/locales/fr.ts +31 -1
  98. package/src/locales/ja.ts +31 -1
  99. package/src/locales/ko.ts +31 -1
  100. package/src/locales/pt.ts +31 -1
  101. package/src/locales/zh.ts +31 -1
  102. package/src/map.ts +32 -0
  103. package/src/plugin.ts +54 -3
  104. package/dist/MTextField-BPbFeI9M.js +0 -1368
  105. package/dist/MTextField-BPbFeI9M.js.map +0 -1
  106. package/dist/useLocale-CuvWRZ1h.js.map +0 -1
@@ -0,0 +1,162 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * A place search on an `MMap`: a search card in a corner. Enter searches through `provider` (OpenStreetMap's
4
+ * Nominatim by default, or any function returning places); picking a result flies there (or fits its extent) and
5
+ * marks it. Available from the `/map` entry point.
6
+ *
7
+ * @event select A result was picked
8
+ */
9
+ import { computed, onBeforeUnmount, ref, shallowRef } from 'vue'
10
+ import type * as Maplibre from 'maplibre-gl'
11
+ import MCard from './MCard.vue'
12
+ import MIcon from './MIcon.vue'
13
+ import MIconButton from './MIconButton.vue'
14
+ import MList from './MList.vue'
15
+ import MListItem from './MListItem.vue'
16
+ import MSpinner from './MSpinner.vue'
17
+ import MMapControl from './MMapControl.vue'
18
+ import MMapMarker from './MMapMarker.vue'
19
+ import { useLocale } from '../composables/useLocale'
20
+ import { useMap } from '../composables/useMap'
21
+ import { nominatimProvider, type MapSearchProvider, type MapSearchResult } from '../composables/mapSearch'
22
+ import type { MapControlPosition } from './MMap.vue'
23
+
24
+ const props = withDefaults(
25
+ defineProps<{
26
+ /** Where to search: `nominatimProvider(options)` by default, or your own function */
27
+ provider?: MapSearchProvider
28
+ /** The corner */
29
+ position?: MapControlPosition
30
+ /** The field's placeholder (the locale's "Search places" by default) */
31
+ placeholder?: string
32
+ /** The zoom to fly to for a result without an extent */
33
+ zoom?: number
34
+ /** Mark the picked result */
35
+ marker?: boolean
36
+ /** Search while typing (debounced), for providers that allow it; Nominatim's public server doesn't */
37
+ instant?: boolean
38
+ }>(),
39
+ { position: 'top-left', zoom: 17, marker: true, instant: false },
40
+ )
41
+
42
+ const emit = defineEmits<{ select: [result: MapSearchResult] }>()
43
+
44
+ const t = useLocale()
45
+ const { map } = useMap()
46
+ const provider = computed(() => props.provider ?? nominatimProvider())
47
+
48
+ const query = ref('')
49
+ const results = shallowRef<MapSearchResult[]>([])
50
+ const loading = ref(false)
51
+ const searched = ref(false)
52
+ const open = ref(false)
53
+ const picked = shallowRef<MapSearchResult | null>(null)
54
+ let controller: AbortController | undefined
55
+ let debounce: ReturnType<typeof setTimeout> | undefined
56
+
57
+ async function search() {
58
+ const q = query.value.trim()
59
+ if (!q) return
60
+ controller?.abort()
61
+ controller = new AbortController()
62
+ const mine = controller
63
+ loading.value = true
64
+ open.value = true
65
+ try {
66
+ results.value = await provider.value(q, mine.signal)
67
+ } catch {
68
+ if (mine.signal.aborted) return
69
+ results.value = []
70
+ } finally {
71
+ if (controller === mine) {
72
+ loading.value = false
73
+ searched.value = true
74
+ }
75
+ }
76
+ }
77
+
78
+ function onInput(value: string) {
79
+ query.value = value
80
+ if (!value) return clear()
81
+ if (props.instant) {
82
+ clearTimeout(debounce)
83
+ debounce = setTimeout(search, 350)
84
+ }
85
+ }
86
+
87
+ function select(result: MapSearchResult) {
88
+ picked.value = result
89
+ open.value = false
90
+ const m = map.value as Maplibre.Map | undefined
91
+ if (result.bbox && result.bbox[0] !== result.bbox[2]) m?.fitBounds([[result.bbox[0], result.bbox[1]], [result.bbox[2], result.bbox[3]]], { padding: 48, maxZoom: props.zoom })
92
+ else m?.flyTo({ center: result.lngLat, zoom: props.zoom })
93
+ emit('select', result)
94
+ }
95
+
96
+ function clear() {
97
+ controller?.abort()
98
+ clearTimeout(debounce)
99
+ query.value = ''
100
+ results.value = []
101
+ searched.value = false
102
+ loading.value = false
103
+ open.value = false
104
+ picked.value = null
105
+ }
106
+
107
+ onBeforeUnmount(() => {
108
+ controller?.abort()
109
+ clearTimeout(debounce)
110
+ })
111
+
112
+ const ICONS: Record<string, string> = {
113
+ city: 'location_city', town: 'location_city', village: 'holiday_village', hamlet: 'cottage', suburb: 'apartment',
114
+ neighbourhood: 'maps_home_work', road: 'road', residential: 'home', house: 'home', building: 'domain',
115
+ shop: 'storefront', park: 'park', water: 'water', river: 'water', lake: 'water', school: 'school',
116
+ university: 'school', hospital: 'local_hospital', restaurant: 'restaurant', cafe: 'local_cafe', hotel: 'hotel',
117
+ station: 'train', bus_stop: 'directions_bus', administrative: 'map', country: 'public', state: 'map',
118
+ }
119
+ const iconOf = (type?: string) => (type && ICONS[type]) || 'location_on'
120
+ </script>
121
+
122
+ <template>
123
+ <div class="hidden">
124
+ <MMapControl :position="position" :group="false">
125
+ <MCard variant="elevated" class="w-80 max-w-[calc(100vw-5rem)] overflow-hidden">
126
+ <form class="flex items-center gap-2 py-1 pr-1 pl-3" role="search" @submit.prevent="search">
127
+ <MIcon name="search" :size="20" class="shrink-0 text-on-surface-variant" />
128
+ <input
129
+ :value="query"
130
+ type="search"
131
+ enterkeyhint="search"
132
+ :placeholder="placeholder ?? t.mapSearchPlaces"
133
+ :aria-label="placeholder ?? t.mapSearchPlaces"
134
+ class="min-w-0 flex-1 bg-transparent py-2 text-body-medium text-on-surface outline-none placeholder:text-on-surface-variant [&::-webkit-search-cancel-button]:hidden"
135
+ @input="onInput(($event.target as HTMLInputElement).value)"
136
+ @focus="open = searched && !picked"
137
+ >
138
+ <MSpinner v-if="loading" :size="20" class="mr-2 shrink-0" />
139
+ <MIconButton v-else-if="query" icon="close" :label="t.clearSearch" size="sm" @click="clear" />
140
+ </form>
141
+ <div v-if="open && searched && !loading" class="border-t border-outline-variant">
142
+ <MList v-if="results.length" class="max-h-72 overflow-y-auto">
143
+ <MListItem
144
+ v-for="(r, i) in results"
145
+ :key="i"
146
+ :title="r.label"
147
+ :icon="iconOf(r.type)"
148
+ leading="icon"
149
+ clickable
150
+ @click="select(r)"
151
+ />
152
+ </MList>
153
+ <div v-else class="flex flex-col items-center gap-2 py-6">
154
+ <MIcon name="search_off" :size="28" class="text-on-surface-variant" />
155
+ <span class="text-body-small text-on-surface-variant">{{ t.noResults }}</span>
156
+ </div>
157
+ </div>
158
+ </MCard>
159
+ </MMapControl>
160
+ <MMapMarker v-if="marker && picked" :lng-lat="picked.lngLat" />
161
+ </div>
162
+ </template>
@@ -0,0 +1,77 @@
1
+ <script setup lang="ts">
2
+ // Internal: one layer of MMapLayers (visibility, title, and expanded: description, opacity, legend, download)
3
+ import MIcon from './MIcon.vue'
4
+ import MSlider from './MSlider.vue'
5
+ import { useLocale } from '../composables/useLocale'
6
+ import { useMapLayers } from '../composables/useMapLayers'
7
+ import type { MapLayerInfo } from '../composables/mapAdapters'
8
+
9
+ defineProps<{ layer: MapLayerInfo; expanded: boolean }>()
10
+ const emit = defineEmits<{ 'toggle-expanded': [] }>()
11
+
12
+ const t = useLocale()
13
+ const { isVisible, toggle, opacityOf, setOpacity } = useMapLayers()
14
+ </script>
15
+
16
+ <template>
17
+ <div class="flex overflow-hidden rounded-2xl bg-surface-container" :class="isVisible(layer.id) ? '' : 'opacity-75'">
18
+ <div class="w-1 shrink-0 transition-colors duration-200" :class="isVisible(layer.id) ? 'bg-primary' : 'bg-outline-variant'" />
19
+ <div class="flex min-w-0 flex-1 flex-col">
20
+ <div class="flex cursor-pointer items-center gap-2 px-3 py-2" @click="emit('toggle-expanded')">
21
+ <button
22
+ type="button"
23
+ class="grid size-8 shrink-0 cursor-pointer place-items-center rounded-full transition-colors duration-200"
24
+ :class="isVisible(layer.id) ? 'bg-primary/12 text-primary' : 'bg-on-surface/5 text-on-surface-variant'"
25
+ :aria-label="isVisible(layer.id) ? t.mapHideLayer : t.mapShowLayer"
26
+ :aria-pressed="isVisible(layer.id)"
27
+ @click.stop="toggle(layer.id)"
28
+ >
29
+ <MIcon :name="isVisible(layer.id) ? 'visibility' : 'visibility_off'" :size="18" />
30
+ </button>
31
+ <div class="flex min-w-0 flex-1 flex-col">
32
+ <span class="truncate text-body-medium" :class="isVisible(layer.id) ? 'text-on-surface' : 'text-on-surface-variant'">{{ layer.title }}</span>
33
+ <span v-if="layer.description && !expanded" class="truncate text-label-small text-on-surface-variant">{{ layer.description }}</span>
34
+ </div>
35
+ <span v-if="isVisible(layer.id) && opacityOf(layer.id) < 1" class="rounded-full bg-primary/8 px-2 py-0.5 text-label-small tabular-nums text-primary">
36
+ {{ Math.round(opacityOf(layer.id) * 100) }}%
37
+ </span>
38
+ <MIcon name="expand_more" :size="18" class="shrink-0 text-on-surface-variant transition-transform duration-300" :class="expanded ? 'rotate-180' : ''" />
39
+ </div>
40
+ <!-- Expands with grid rows 0fr → 1fr, so the height animates without measuring it -->
41
+ <div class="grid transition-[grid-template-rows] duration-300 ease-[cubic-bezier(0.2,0,0,1)]" :style="{ gridTemplateRows: expanded ? '1fr' : '0fr' }">
42
+ <div class="min-h-0 overflow-hidden">
43
+ <div class="flex flex-col gap-3 px-3 pb-3">
44
+ <p v-if="layer.description" class="text-body-small text-on-surface-variant">{{ layer.description }}</p>
45
+ <div class="flex items-center gap-2 rounded-2xl bg-surface-container-highest/60 px-3 py-1">
46
+ <MIcon name="opacity" :size="16" class="shrink-0 text-on-surface-variant" />
47
+ <MSlider
48
+ :model-value="opacityOf(layer.id)"
49
+ :min="0"
50
+ :max="1"
51
+ :step="0.01"
52
+ :label="t.mapOpacity"
53
+ class="flex-1"
54
+ @update:model-value="setOpacity(layer.id, Number($event))"
55
+ />
56
+ </div>
57
+ <img v-if="layer.legend" :src="layer.legend" alt="" class="max-w-full self-start" loading="lazy">
58
+ <div v-if="layer.download || $slots.actions" class="flex flex-wrap items-center gap-2">
59
+ <a
60
+ v-if="layer.download"
61
+ :href="layer.download"
62
+ target="_blank"
63
+ rel="noopener"
64
+ download
65
+ class="inline-flex items-center gap-1 rounded-full px-3 py-1.5 text-label-large text-primary hover:bg-primary/8"
66
+ >
67
+ <MIcon name="download" :size="18" />
68
+ {{ t.mapDownload }}
69
+ </a>
70
+ <slot name="actions" :layer="layer" :visible="isVisible(layer.id)" />
71
+ </div>
72
+ </div>
73
+ </div>
74
+ </div>
75
+ </div>
76
+ </div>
77
+ </template>
@@ -0,0 +1,75 @@
1
+ // Internal: the geodesy MMapMeasure needs, on a sphere of the Earth's mean radius (as @turf/length and @turf/area do,
2
+ // so the numbers match what the Orvian viewers measured with turf)
3
+
4
+ export type LngLat = [number, number]
5
+
6
+ const R = 6371008.8 // meters
7
+ const RAD = Math.PI / 180
8
+
9
+ /** Great-circle distance between two points, in meters (haversine). */
10
+ export function distance(a: LngLat, b: LngLat): number {
11
+ const dLat = (b[1] - a[1]) * RAD
12
+ const dLng = (b[0] - a[0]) * RAD
13
+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(a[1] * RAD) * Math.cos(b[1] * RAD) * Math.sin(dLng / 2) ** 2
14
+ return 2 * R * Math.asin(Math.min(1, Math.sqrt(h)))
15
+ }
16
+
17
+ /** The length of a path, in meters. */
18
+ export function pathLength(points: LngLat[]): number {
19
+ let total = 0
20
+ for (let i = 1; i < points.length; i++) total += distance(points[i - 1]!, points[i]!)
21
+ return total
22
+ }
23
+
24
+ /** The point halfway along the great circle between two points. */
25
+ export function midpoint(a: LngLat, b: LngLat): LngLat {
26
+ const [l1, p1, l2, p2] = [a[0] * RAD, a[1] * RAD, b[0] * RAD, b[1] * RAD]
27
+ const bx = Math.cos(p2) * Math.cos(l2 - l1)
28
+ const by = Math.cos(p2) * Math.sin(l2 - l1)
29
+ const lat = Math.atan2(Math.sin(p1) + Math.sin(p2), Math.sqrt((Math.cos(p1) + bx) ** 2 + by ** 2))
30
+ const lng = l1 + Math.atan2(by, Math.cos(p1) + bx)
31
+ return [lng / RAD, lat / RAD]
32
+ }
33
+
34
+ /** The area of a ring (closed or not), in square meters, on the sphere (@turf/area's formula). */
35
+ export function ringArea(points: LngLat[]): number {
36
+ const ring = closeRing(points)
37
+ const n = ring.length - 1
38
+ if (n <= 2) return 0
39
+ let total = 0
40
+ for (let i = 0; i < n; i++) {
41
+ const lower = ring[i]!
42
+ const middle = ring[i + 1 === n ? 0 : i + 1]!
43
+ const upper = ring[i + 2 >= n ? (i + 2) % n : i + 2]!
44
+ total += (upper[0] - lower[0]) * RAD * Math.sin(middle[1] * RAD)
45
+ }
46
+ return Math.abs((total * R * R) / 2)
47
+ }
48
+
49
+ /** The ring with its first point repeated at the end. */
50
+ export function closeRing(points: LngLat[]): LngLat[] {
51
+ const first = points[0]
52
+ const last = points[points.length - 1]
53
+ return first && last && (first[0] !== last[0] || first[1] !== last[1]) ? [...points, first] : points
54
+ }
55
+
56
+ /** Where to label a polygon: its area centroid (in degrees, fine at a measuring scale), or the vertices' mean. */
57
+ export function centroid(points: LngLat[]): LngLat {
58
+ const ring = closeRing(points)
59
+ let a = 0
60
+ let x = 0
61
+ let y = 0
62
+ for (let i = 0; i < ring.length - 1; i++) {
63
+ const [x0, y0] = ring[i]!
64
+ const [x1, y1] = ring[i + 1]!
65
+ const f = x0 * y1 - x1 * y0
66
+ a += f
67
+ x += (x0 + x1) * f
68
+ y += (y0 + y1) * f
69
+ }
70
+ if (Math.abs(a) < 1e-12) {
71
+ const pts = ring.slice(0, -1)
72
+ return [pts.reduce((s, p) => s + p[0], 0) / pts.length, pts.reduce((s, p) => s + p[1], 0) / pts.length]
73
+ }
74
+ return [x / (3 * a), y / (3 * a)]
75
+ }
@@ -0,0 +1,80 @@
1
+ import { computed, hasInjectionContext, inject, onMounted, ref, type InjectionKey, type Ref } from 'vue'
2
+ import { isHydrating } from './_hydration'
3
+ import { VIEWPORT_KEY } from './_storageKeys'
4
+ import type { Theme } from './useTheme'
5
+ import type { ContrastLevel } from './useColorPalette'
6
+
7
+ /** The user's theme choices as a server knows them (from cookies), for server-side rendering. */
8
+ export interface M3InitialState {
9
+ theme?: Theme
10
+ palette?: string
11
+ contrast?: ContrastLevel
12
+ /** The browser window's size: the adaptive layouts and `useWindowSizeClass()` render for it instead of compact. */
13
+ viewport?: { width: number; height: number }
14
+ }
15
+
16
+ /** `initialState` with the plugin's defaults filled in (the viewport stays optional: there's no default for it). */
17
+ export type ResolvedInitialState = Required<Omit<M3InitialState, 'viewport'>> & Pick<M3InitialState, 'viewport'>
18
+
19
+ // Internal: `createM3UI({ initialState })`, resolved against the plugin's defaults
20
+ export const M3_INITIAL_STATE_KEY: InjectionKey<ResolvedInitialState> = Symbol('m3-initial-state')
21
+
22
+ export function initialState(): ResolvedInitialState | null {
23
+ return hasInjectionContext() ? inject(M3_INITIAL_STATE_KEY, null) : null
24
+ }
25
+
26
+ /**
27
+ * What a composable reports for a stored choice. On the server: the initial state (the module-level refs are shared
28
+ * by every request and hold nothing there). On the client while hydrating: the initial state too, so the first
29
+ * render matches the server's HTML, then the live value once mounted. Otherwise the live ref itself.
30
+ */
31
+ export function ssrValue<T>(live: Ref<T>, initial: T | undefined): Ref<T> {
32
+ if (initial === undefined) return live
33
+ if (typeof window === 'undefined') return ref(initial) as Ref<T>
34
+ if (!isHydrating()) return live
35
+ const mounted = ref(false)
36
+ onMounted(() => { mounted.value = true })
37
+ return computed({
38
+ get: () => (mounted.value ? live.value : initial),
39
+ set: (value) => { live.value = value },
40
+ }) as Ref<T>
41
+ }
42
+
43
+ // ── Cookies ─────────────────────────────────────────────────────────────────────────────────────
44
+ // `createM3UI({ cookies: true })`: the choices are also kept in cookies, which a server can read.
45
+
46
+ let cookiesEnabled = false
47
+
48
+ export function enableCookies() {
49
+ cookiesEnabled = true
50
+ }
51
+
52
+ let trackingViewport = false
53
+
54
+ /** Keeps the window's size in a cookie, for the server to render the adaptive layouts at it. */
55
+ export function trackViewport() {
56
+ if (!cookiesEnabled || trackingViewport || typeof window === 'undefined') return
57
+ trackingViewport = true
58
+ const write = () => writeCookie(VIEWPORT_KEY, `${window.innerWidth}x${window.innerHeight}`)
59
+ let timer: ReturnType<typeof setTimeout> | undefined
60
+ write()
61
+ window.addEventListener('resize', () => {
62
+ clearTimeout(timer)
63
+ timer = setTimeout(write, 300)
64
+ })
65
+ }
66
+
67
+ /** A cookie's value: the stored choice when localStorage has none (cleared storage, or a server that set it). */
68
+ export function readCookie(key: string): string | null {
69
+ if (typeof document === 'undefined') return null
70
+ const match = document.cookie.match(new RegExp(`(?:^|; )${key}=([^;]*)`))
71
+ if (!match) return null
72
+ try { return decodeURIComponent(match[1]!) } catch { return null }
73
+ }
74
+
75
+ export function writeCookie(key: string, value: string | null) {
76
+ if (!cookiesEnabled || typeof document === 'undefined') return
77
+ document.cookie = value == null
78
+ ? `${key}=; Max-Age=0; Path=/; SameSite=Lax`
79
+ : `${key}=${encodeURIComponent(value)}; Max-Age=31536000; Path=/; SameSite=Lax`
80
+ }
@@ -0,0 +1,6 @@
1
+ // Storage keys shared with modules that must not load useTheme (it applies the theme to <html> when it loads)
2
+ export const THEME_KEY = 'm3-theme'
3
+ // The <style> useColorPalette writes a generated palette's CSS into
4
+ export const STYLE_ID = 'm3-dynamic-palette'
5
+ // The window's size, a cookie only (createM3UI({ cookies: true })): `<width>x<height>`
6
+ export const VIEWPORT_KEY = 'm3-viewport'
@@ -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
+ }