@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,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,
@@ -187,6 +187,37 @@ export interface M3Locale {
187
187
  nextPage: string
188
188
  carousel: string
189
189
  carouselItem: string
190
+ // MMap (maplibre controls)
191
+ mapTitle: string
192
+ mapMarker: string
193
+ mapZoomIn: string
194
+ mapZoomOut: string
195
+ mapResetBearing: string
196
+ mapFindMyLocation: string
197
+ mapLocationNotAvailable: string
198
+ mapEnterFullscreen: string
199
+ mapExitFullscreen: string
200
+ mapToggleAttribution: string
201
+ mapFeedback: string
202
+ mapCtrlScroll: string
203
+ mapCmdScroll: string
204
+ mapTwoFingers: string
205
+ mapLayers: string
206
+ mapSearchLayers: string
207
+ mapNoLayers: string
208
+ mapShowLayer: string
209
+ mapHideLayer: string
210
+ mapOpacity: string
211
+ mapDownload: string
212
+ mapNoBaseLayer: string
213
+ mapHoverInfo: string
214
+ mapNoValue: string
215
+ mapMeasureDistance: string
216
+ mapMeasureArea: string
217
+ mapClearMeasurements: string
218
+ mapDeleteMeasurement: string
219
+ mapTotal: string
220
+ mapSearchPlaces: string
190
221
  }
191
222
 
192
223
  export const defaultLocale: M3Locale = {
@@ -359,6 +390,37 @@ export const defaultLocale: M3Locale = {
359
390
  nextPage: 'Next page',
360
391
  carousel: 'Carousel',
361
392
  carouselItem: '{index} of {count}',
393
+ // MMap (maplibre controls)
394
+ mapTitle: 'Map',
395
+ mapMarker: 'Map marker',
396
+ mapZoomIn: 'Zoom in',
397
+ mapZoomOut: 'Zoom out',
398
+ mapResetBearing: 'Reset bearing to north',
399
+ mapFindMyLocation: 'Find my location',
400
+ mapLocationNotAvailable: 'Location not available',
401
+ mapEnterFullscreen: 'Enter fullscreen',
402
+ mapExitFullscreen: 'Exit fullscreen',
403
+ mapToggleAttribution: 'Toggle attribution',
404
+ mapFeedback: 'Map feedback',
405
+ mapCtrlScroll: 'Use Ctrl + scroll to zoom the map',
406
+ mapCmdScroll: 'Use ⌘ + scroll to zoom the map',
407
+ mapTwoFingers: 'Use two fingers to move the map',
408
+ mapLayers: 'Layers',
409
+ mapSearchLayers: 'Search layers',
410
+ mapNoLayers: 'No layers',
411
+ mapShowLayer: 'Show layer',
412
+ mapHideLayer: 'Hide layer',
413
+ mapOpacity: 'Opacity',
414
+ mapDownload: 'Download',
415
+ mapNoBaseLayer: 'No base layer',
416
+ mapHoverInfo: 'Info on hover',
417
+ mapNoValue: 'Not available',
418
+ mapMeasureDistance: 'Measure distance',
419
+ mapMeasureArea: 'Measure area',
420
+ mapClearMeasurements: 'Clear measurements',
421
+ mapDeleteMeasurement: 'Delete measurement',
422
+ mapTotal: 'Total',
423
+ mapSearchPlaces: 'Search places',
362
424
  }
363
425
 
364
426
  export const M3_LOCALE_KEY: InjectionKey<MaybeRef<Partial<M3Locale>>> = Symbol('m3-locale')
@@ -0,0 +1,98 @@
1
+ import { computed, getCurrentInstance, inject, onBeforeUnmount, onMounted, watch, type ComputedRef, type InjectionKey, type Ref, type ShallowRef } from 'vue'
2
+ import type * as Maplibre from 'maplibre-gl'
3
+ import type { MapLayerModel } from './mapAdapters'
4
+ import type { MapLayerState } from './useMapLayers'
5
+
6
+ /** The `maplibre-gl` module (its classes: `Map`, `Marker`, `Popup`…) */
7
+ export type MaplibreModule = typeof import('maplibre-gl')
8
+
9
+ /** What `MMap` provides to everything inside it. */
10
+ export interface MapContext {
11
+ /** The MapLibre map, once created (never on the server) */
12
+ map: ShallowRef<Maplibre.Map | undefined>
13
+ /** The `maplibre-gl` module, loaded with the map (so nothing imports it on the server) */
14
+ maplibre: ShallowRef<MaplibreModule | undefined>
15
+ /** Bumped on every `style.load`: sources and layers added by components are re-added after a style change */
16
+ styleVersion: Ref<number>
17
+ /** The style as `MMap`'s `adapter` reads it (undefined without one) */
18
+ model: ShallowRef<MapLayerModel | undefined>
19
+ /** Visibility and opacity of the model's layers */
20
+ layerState: MapLayerState
21
+ /**
22
+ * The tool that owns the map's clicks right now (`'measure'` while measuring), or null: `MMapIdentify` stays quiet
23
+ * meanwhile. Set it from tools of your own the same way
24
+ */
25
+ activeTool: Ref<string | null>
26
+ }
27
+
28
+ // Internal: provided by MMap
29
+ export const MAP_KEY: InjectionKey<MapContext> = Symbol('m3-map')
30
+
31
+ type MapEventType = keyof Maplibre.MapEventType
32
+ type LayerEventType = keyof Maplibre.MapLayerEventType
33
+
34
+ /**
35
+ * The map of the enclosing `MMap`, for your own controls, layers and handlers (call it in a component inside
36
+ * `MMap`). Listeners added through it are removed when the component unmounts.
37
+ *
38
+ * ```ts
39
+ * const { map, onLayer } = useMap()
40
+ * onLayer('click', 'parcels-fill', (e) => console.log(e.features?.[0]?.properties))
41
+ * ```
42
+ */
43
+ export function useMap() {
44
+ const ctx = inject(MAP_KEY, null)
45
+ if (!ctx) throw new Error('useMap() must be called in a component inside <MMap>')
46
+ const cleanups: (() => void)[] = []
47
+ if (getCurrentInstance()) onBeforeUnmount(() => cleanups.splice(0).forEach((fn) => fn()))
48
+
49
+ /**
50
+ * Runs `fn` with the map as soon as it exists (right away if it already does), and in a component not before it's
51
+ * mounted, so its template refs are there.
52
+ */
53
+ function onReady(fn: (map: Maplibre.Map, maplibre: MaplibreModule) => void) {
54
+ const run = () => {
55
+ if (ctx!.map.value && ctx!.maplibre.value) return fn(ctx!.map.value, ctx!.maplibre.value)
56
+ const stop = watch(ctx!.map, (map) => {
57
+ if (!map || !ctx!.maplibre.value) return
58
+ stop()
59
+ fn(map, ctx!.maplibre.value)
60
+ })
61
+ cleanups.push(stop)
62
+ }
63
+ const instance = getCurrentInstance()
64
+ if (instance && !instance.isMounted) onMounted(run)
65
+ else run()
66
+ }
67
+
68
+ /** A map event listener (`click`, `moveend`, `style.load`…), removed on unmount. */
69
+ function on<T extends MapEventType>(type: T, listener: (e: Maplibre.MapEventType[T] & object) => void) {
70
+ onReady((map) => {
71
+ map.on(type, listener)
72
+ cleanups.push(() => map.off(type, listener))
73
+ })
74
+ }
75
+
76
+ /**
77
+ * A listener for one layer's features (`click`, `mouseenter`, `mousemove`…: `e.features` holds the features under
78
+ * the pointer), removed on unmount. It survives style changes, being keyed by the layer id.
79
+ */
80
+ function onLayer<T extends LayerEventType>(type: T, layerId: string, listener: (e: Maplibre.MapLayerEventType[T] & object) => void) {
81
+ onReady((map) => {
82
+ map.on(type, layerId, listener)
83
+ cleanups.push(() => map.off(type, layerId, listener))
84
+ })
85
+ }
86
+
87
+ // computed, not readonly(): readonly() is deep, and a proxied maplibre Map breaks
88
+ return {
89
+ map: computed(() => ctx.map.value) as ComputedRef<Maplibre.Map | undefined>,
90
+ maplibre: computed(() => ctx.maplibre.value) as ComputedRef<MaplibreModule | undefined>,
91
+ styleVersion: computed(() => ctx.styleVersion.value),
92
+ /** The tool that owns the map's clicks (null: none): set it while yours does, and leave it alone otherwise */
93
+ activeTool: ctx.activeTool,
94
+ onReady,
95
+ on,
96
+ onLayer,
97
+ }
98
+ }
@@ -0,0 +1,45 @@
1
+ import { inject } from 'vue'
2
+ import type * as Maplibre from 'maplibre-gl'
3
+ import { MAP_KEY } from './useMap'
4
+
5
+ // The style's own filter of each layer we filter (undefined: none), per map
6
+ const originals = new WeakMap<Maplibre.Map, Map<string, Maplibre.FilterSpecification | undefined>>()
7
+
8
+ /**
9
+ * Filters for the layers of the enclosing `MMap`, on top of the filters their style already has (a layer that only
10
+ * draws parks keeps doing so): `setFilter(layer, expression)` combines both, `setFilter(layer, null)` brings the
11
+ * style's back. `MMapFilter` is built on it; use it for filters of your own (a range slider, a date, a search…).
12
+ */
13
+ export function useMapFilter() {
14
+ const ctx = inject(MAP_KEY, null)
15
+ if (!ctx) throw new Error('useMapFilter() must be called in a component inside <MMap>')
16
+
17
+ function setFilter(layerId: string, filter: Maplibre.FilterSpecification | null) {
18
+ const map = ctx!.map.value
19
+ if (!map?.getLayer(layerId)) return
20
+ let saved = originals.get(map)
21
+ if (!saved) originals.set(map, (saved = new Map()))
22
+ if (!saved.has(layerId)) saved.set(layerId, map.getFilter(layerId) ?? undefined)
23
+ const original = saved.get(layerId)
24
+ map.setFilter(layerId, filter ? (original ? ['all', original, filter] : filter) as Maplibre.FilterSpecification : original ?? null)
25
+ }
26
+
27
+ /**
28
+ * The distinct values of a property among a layer's features loaded in the map (for vector tiles, the tiles in
29
+ * view), sorted.
30
+ */
31
+ function valuesOf(layerId: string, property: string): (string | number)[] {
32
+ const map = ctx!.map.value
33
+ const layer = map?.getLayer(layerId) as (Maplibre.StyleLayer & { source?: string; sourceLayer?: string }) | undefined
34
+ if (!map || !layer?.source) return []
35
+ const features = map.querySourceFeatures(layer.source, layer.sourceLayer ? { sourceLayer: layer.sourceLayer } : undefined)
36
+ const values = new Set<string | number>()
37
+ for (const f of features) {
38
+ const v = f.properties?.[property]
39
+ if (typeof v === 'string' || typeof v === 'number') values.add(v)
40
+ }
41
+ return [...values].sort((a, b) => (typeof a === 'number' && typeof b === 'number' ? a - b : String(a).localeCompare(String(b))))
42
+ }
43
+
44
+ return { setFilter, valuesOf }
45
+ }
@@ -0,0 +1,124 @@
1
+ import { computed, inject, reactive } from 'vue'
2
+ import type * as Maplibre from 'maplibre-gl'
3
+ import { MAP_KEY } from './useMap'
4
+ import type { MapLayerInfo, MapLayerModel } from './mapAdapters'
5
+
6
+ /** The paint properties that make each layer type transparent. */
7
+ const OPACITY: Record<string, string[]> = {
8
+ fill: ['fill-opacity'],
9
+ line: ['line-opacity'],
10
+ circle: ['circle-opacity', 'circle-stroke-opacity'],
11
+ symbol: ['icon-opacity', 'text-opacity'],
12
+ raster: ['raster-opacity'],
13
+ heatmap: ['heatmap-opacity'],
14
+ 'fill-extrusion': ['fill-extrusion-opacity'],
15
+ }
16
+
17
+ /** Visibility and opacity of the model's layers, shared by everything inside one `MMap`. */
18
+ export interface MapLayerState {
19
+ visible: Record<string, boolean>
20
+ opacity: Record<string, number>
21
+ }
22
+
23
+ // Internal: MMap's shared state, filled from the map on every style load
24
+ export function createLayerState(): MapLayerState {
25
+ return reactive({ visible: {}, opacity: {} })
26
+ }
27
+
28
+ export function readLayerState(state: MapLayerState, map: Maplibre.Map, model: MapLayerModel | undefined) {
29
+ const visible: Record<string, boolean> = {}
30
+ const opacity: Record<string, number> = {}
31
+ for (const layer of model?.layers ?? []) {
32
+ const style = map.getLayer(layer.id)
33
+ if (!style) continue
34
+ visible[layer.id] = map.getLayoutProperty(layer.id, 'visibility') !== 'none'
35
+ const prop = OPACITY[style.type]?.[0]
36
+ const value = prop ? map.getPaintProperty(layer.id, prop) : undefined
37
+ opacity[layer.id] = typeof value === 'number' ? value : 1
38
+ }
39
+ state.visible = visible
40
+ state.opacity = opacity
41
+ }
42
+
43
+ /**
44
+ * The layers of the enclosing `MMap`'s style as its `adapter` describes them, with their visibility and opacity, for a
45
+ * layer panel or a base layer switcher of your own (`MMapLayers` and `MMapBaseLayers` are built on it). Changes go to
46
+ * the map and to every component using it; a layer's `children` follow it.
47
+ */
48
+ export function useMapLayers() {
49
+ const ctx = inject(MAP_KEY, null)
50
+ if (!ctx) throw new Error('useMapLayers() must be called in a component inside <MMap>')
51
+ const { map, model, layerState: state } = ctx
52
+
53
+ const layers = computed(() => model.value?.layers ?? [])
54
+ const byId = computed(() => new Map(layers.value.map((l) => [l.id, l])))
55
+
56
+ function isVisible(id: string) {
57
+ return state.visible[id] ?? true
58
+ }
59
+
60
+ function setVisible(id: string, visible: boolean) {
61
+ const m = map.value
62
+ if (m?.getLayer(id)) m.setLayoutProperty(id, 'visibility', visible ? 'visible' : 'none')
63
+ state.visible[id] = visible
64
+ for (const child of byId.value.get(id)?.children ?? []) setVisible(child, visible)
65
+ }
66
+
67
+ function toggle(id: string) {
68
+ setVisible(id, !isVisible(id))
69
+ }
70
+
71
+ function opacityOf(id: string) {
72
+ return state.opacity[id] ?? 1
73
+ }
74
+
75
+ function setOpacity(id: string, opacity: number) {
76
+ const m = map.value
77
+ const layer = m?.getLayer(id)
78
+ if (layer) for (const prop of OPACITY[layer.type] ?? []) m!.setPaintProperty(id, prop, opacity)
79
+ state.opacity[id] = opacity
80
+ for (const child of byId.value.get(id)?.children ?? []) setOpacity(child, opacity)
81
+ }
82
+
83
+ /** The layers of a group (listed ones), or the ungrouped ones with `null`. */
84
+ function layersOf(group: string | null): MapLayerInfo[] {
85
+ return layers.value.filter((l) => l.listed && (group === null ? !l.group || !model.value?.groups.some((g) => g.name === l.group) : l.group === group))
86
+ }
87
+
88
+ function groupState(group: string): 'visible' | 'hidden' | 'partial' {
89
+ const visible = layersOf(group).map((l) => isVisible(l.id))
90
+ if (visible.length && visible.every(Boolean)) return 'visible'
91
+ if (visible.some(Boolean)) return 'partial'
92
+ return 'hidden'
93
+ }
94
+
95
+ function setGroupVisible(group: string, visible: boolean) {
96
+ for (const layer of layersOf(group)) setVisible(layer.id, visible)
97
+ }
98
+
99
+ const baseLayers = computed(() => layers.value.filter((l) => l.base))
100
+ /** The visible base layer's id, or null */
101
+ const baseLayer = computed(() => baseLayers.value.find((l) => isVisible(l.id))?.id ?? null)
102
+
103
+ /** Shows this base layer only (null: none). */
104
+ function setBaseLayer(id: string | null) {
105
+ for (const layer of baseLayers.value) setVisible(layer.id, layer.id === id)
106
+ }
107
+
108
+ return {
109
+ /** The adapter's model (undefined without an `adapter`) */
110
+ model: computed(() => model.value),
111
+ layers,
112
+ isVisible,
113
+ setVisible,
114
+ toggle,
115
+ opacityOf,
116
+ setOpacity,
117
+ layersOf,
118
+ groupState,
119
+ setGroupVisible,
120
+ baseLayers,
121
+ baseLayer,
122
+ setBaseLayer,
123
+ }
124
+ }
@@ -1,14 +1,17 @@
1
1
  import { ref, watchEffect, onMounted, onUnmounted } from 'vue'
2
2
  import { themeTransition } from './_themeTransition'
3
+ import { initialState, readCookie, ssrValue, writeCookie } from './_ssrState'
4
+ import { THEME_KEY } from './_storageKeys'
3
5
 
4
6
  export type Theme = 'light' | 'dark' | 'system'
5
7
 
6
- export const THEME_KEY = 'm3-theme'
8
+ export { THEME_KEY }
7
9
 
8
10
  // No DOM on the server (SSR): nothing is read or applied there, the client does it when the module loads.
9
11
  const inBrowser = typeof window !== 'undefined'
10
12
 
11
- const theme = ref<Theme>((inBrowser ? localStorage.getItem(THEME_KEY) as Theme : null) ?? 'system')
13
+ // localStorage, else the cookie createM3UI({ cookies }) keeps (cleared storage, or a theme a server set)
14
+ const theme = ref<Theme>((inBrowser ? (localStorage.getItem(THEME_KEY) ?? readCookie(THEME_KEY)) as Theme : null) ?? 'system')
12
15
 
13
16
  let _appliedDark: boolean | null = null
14
17
 
@@ -37,6 +40,7 @@ export function useTheme() {
37
40
  watchEffect(() => {
38
41
  if (!inBrowser) return
39
42
  localStorage.setItem(THEME_KEY, theme.value)
43
+ writeCookie(THEME_KEY, theme.value)
40
44
  applyTheme(theme.value)
41
45
  })
42
46
 
@@ -49,5 +53,6 @@ export function useTheme() {
49
53
  theme.value = order[(idx + 1) % order.length]!
50
54
  }
51
55
 
52
- return { theme, cycle }
56
+ // Server-side rendering with `createM3UI({ initialState })`: the user's theme as the server knows it
57
+ return { theme: ssrValue(theme, initialState()?.theme), cycle }
53
58
  }
@@ -1,5 +1,6 @@
1
1
  import { computed, onMounted, onUnmounted, ref, toValue, watch, type MaybeRefOrGetter, type Ref } from 'vue'
2
2
  import { isHydrating } from './_hydration'
3
+ import { initialState } from './_ssrState'
3
4
 
4
5
  /*
5
6
  * M3 window size classes, with the breakpoints from androidx `WindowSizeClass`
@@ -49,15 +50,23 @@ function updateWindow() {
49
50
  export function useWindowSizeClass(target?: MaybeRefOrGetter<HTMLElement | null | undefined>): WindowSizeClassInfo {
50
51
  let width: Ref<number>
51
52
  let height: Ref<number>
52
- // Hydrating server-rendered HTML: start from the server's size (none, so compact) to match it, then measure
53
+ // Server rendering, and hydrating its HTML: the size the server rendered at, so both match, then measure. That's
54
+ // the window size it was given (createM3UI({ initialState: { viewport } }), from a cookie), or none (compact).
53
55
  const hydrating = isHydrating()
56
+ const server = typeof window === 'undefined'
57
+ const start = server || hydrating ? initialState()?.viewport : undefined
58
+ const startWidth = start?.width ?? 0
59
+ const startHeight = start?.height ?? 0
54
60
 
55
61
  if (target === undefined) {
56
62
  if (hydrating) {
57
63
  const mounted = ref(false)
58
64
  onMounted(() => { mounted.value = true })
59
- width = computed(() => (mounted.value ? winWidth.value : 0)) as Ref<number>
60
- height = computed(() => (mounted.value ? winHeight.value : 0)) as Ref<number>
65
+ width = computed(() => (mounted.value ? winWidth.value : startWidth)) as Ref<number>
66
+ height = computed(() => (mounted.value ? winHeight.value : startHeight)) as Ref<number>
67
+ } else if (server) {
68
+ width = ref(startWidth)
69
+ height = ref(startHeight)
61
70
  } else {
62
71
  width = winWidth
63
72
  height = winHeight
@@ -73,8 +82,8 @@ export function useWindowSizeClass(target?: MaybeRefOrGetter<HTMLElement | null
73
82
  })
74
83
  } else {
75
84
  // Until the element is measured, guess from the window so the first paint is usually right.
76
- width = ref(hydrating ? 0 : winWidth.value)
77
- height = ref(hydrating ? 0 : winHeight.value)
85
+ width = ref(server || hydrating ? startWidth : winWidth.value)
86
+ height = ref(server || hydrating ? startHeight : winHeight.value)
78
87
  let observer: ResizeObserver | undefined
79
88
  const observe = (el: HTMLElement | null | undefined) => {
80
89
  observer?.disconnect()
package/src/index.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  // Plugin
2
2
  export { createM3UI } from './plugin'
3
3
  export type { M3UIOptions } from './plugin'
4
+ export type { M3InitialState } from './composables/_ssrState'
4
5
 
5
6
  // Composables
6
7
  export { useTheme } from './composables/useTheme'
7
8
  export type { Theme } from './composables/useTheme'
8
9
  export { useColorPalette, palettes } from './composables/useColorPalette'
9
- export type { Palette, ActiveSeed, ContrastLevel } from './composables/useColorPalette'
10
+ export type { Palette, PaletteId, ActiveSeed, ContrastLevel } from './composables/useColorPalette'
10
11
  export { SEED_PALETTE } from './composables/useColorPalette'
11
12
  export { themeInitScript } from './composables/themeInitScript'
12
13
  export type { ThemeInitOptions } from './composables/themeInitScript'
package/src/locales/de.ts CHANGED
@@ -182,5 +182,35 @@ export const deLocale: M3Locale = {
182
182
  previousPage: 'Vorherige Seite',
183
183
  nextPage: 'Nächste Seite',
184
184
  carousel: 'Karussell',
185
- carouselItem: '{index} von {count}',
185
+ carouselItem: '{index} von {count}', // MMap (maplibre controls)
186
+ mapTitle: 'Karte',
187
+ mapMarker: 'Kartenmarkierung',
188
+ mapZoomIn: 'Vergrößern',
189
+ mapZoomOut: 'Verkleinern',
190
+ mapResetBearing: 'Nach Norden ausrichten',
191
+ mapFindMyLocation: 'Meinen Standort finden',
192
+ mapLocationNotAvailable: 'Standort nicht verfügbar',
193
+ mapEnterFullscreen: 'Vollbild aktivieren',
194
+ mapExitFullscreen: 'Vollbild beenden',
195
+ mapToggleAttribution: 'Quellenangabe ein- oder ausblenden',
196
+ mapFeedback: 'Feedback zur Karte',
197
+ mapCtrlScroll: 'Strg + Scrollen zum Zoomen der Karte',
198
+ mapCmdScroll: '⌘ + Scrollen zum Zoomen der Karte',
199
+ mapTwoFingers: 'Mit zwei Fingern die Karte bewegen',
200
+ mapLayers: 'Ebenen',
201
+ mapSearchLayers: 'Ebenen suchen',
202
+ mapNoLayers: 'Keine Ebenen',
203
+ mapShowLayer: 'Ebene einblenden',
204
+ mapHideLayer: 'Ebene ausblenden',
205
+ mapOpacity: 'Deckkraft',
206
+ mapDownload: 'Herunterladen',
207
+ mapNoBaseLayer: 'Keine Grundkarte',
208
+ mapHoverInfo: 'Infos beim Überfahren',
209
+ mapNoValue: 'Nicht verfügbar',
210
+ mapMeasureDistance: 'Entfernung messen',
211
+ mapMeasureArea: 'Fläche messen',
212
+ mapClearMeasurements: 'Messungen löschen',
213
+ mapDeleteMeasurement: 'Messung löschen',
214
+ mapTotal: 'Gesamt',
215
+ mapSearchPlaces: 'Orte suchen',
186
216
  }