@m3ui-vue/m3ui-vue 1.0.1 → 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.
- package/dist/API.md +636 -20
- package/dist/MMenuItem-DFyXflk9.js +707 -0
- package/dist/MMenuItem-DFyXflk9.js.map +1 -0
- package/dist/MSlider-CdNIH7jc.js +1376 -0
- package/dist/MSlider-CdNIH7jc.js.map +1 -0
- package/dist/MTextField-B4X92vH_.js +671 -0
- package/dist/MTextField-B4X92vH_.js.map +1 -0
- package/dist/api.json +1 -1
- package/dist/chart.js +1 -1
- package/dist/chart.js.map +1 -1
- package/dist/code-editor.js +1 -1
- package/dist/components/MIconButton.vue.d.ts +1 -1
- package/dist/components/MMap.vue.d.ts +74 -0
- package/dist/components/MMapBaseLayers.vue.d.ts +15 -0
- package/dist/components/MMapControl.vue.d.ts +23 -0
- package/dist/components/MMapFeatureInfo.vue.d.ts +25 -0
- package/dist/components/MMapFilter.vue.d.ts +19 -0
- package/dist/components/MMapGeoJson.vue.d.ts +34 -0
- package/dist/components/MMapHover.vue.d.ts +17 -0
- package/dist/components/MMapIdentify.vue.d.ts +37 -0
- package/dist/components/MMapLayers.vue.d.ts +31 -0
- package/dist/components/MMapMarker.vue.d.ts +42 -0
- package/dist/components/MMapMeasure.vue.d.ts +43 -0
- package/dist/components/MMapPopup.vue.d.ts +43 -0
- package/dist/components/MMapSearch.vue.d.ts +28 -0
- package/dist/components/MShader.vue.d.ts +9 -3
- package/dist/components/_MMapLayerItem.vue.d.ts +25 -0
- package/dist/composables/_hydration.d.ts +4 -0
- package/dist/composables/_mapGeometry.d.ts +13 -0
- package/dist/composables/_ssrState.d.ts +30 -0
- package/dist/composables/_storageKeys.d.ts +3 -0
- package/dist/composables/_useThemeTokens.d.ts +7 -0
- package/dist/composables/mapAdapters.d.ts +111 -0
- package/dist/composables/mapSearch.d.ts +31 -0
- package/dist/composables/themeInitScript.d.ts +22 -0
- package/dist/composables/useColorPalette.d.ts +176 -6
- package/dist/composables/useLocale.d.ts +30 -0
- package/dist/composables/useMap.d.ts +47 -0
- package/dist/composables/useMapFilter.d.ts +10 -0
- package/dist/composables/useMapLayers.d.ts +30 -0
- package/dist/composables/useTheme.d.ts +2 -0
- package/dist/index.d.ts +4 -1
- package/dist/locales/index.js +217 -7
- package/dist/locales/index.js.map +1 -1
- package/dist/m3ui-vue.css +1 -1
- package/dist/m3ui.js +6742 -7961
- package/dist/m3ui.js.map +1 -1
- package/dist/map.d.ts +24 -0
- package/dist/map.js +1931 -0
- package/dist/map.js.map +1 -0
- package/dist/plugin.d.ts +25 -2
- package/dist/rich-text-editor.js +27 -26
- package/dist/rich-text-editor.js.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/{useLocale-CuvWRZ1h.js → useLocale-b5-hzsL3.js} +32 -2
- package/dist/useLocale-b5-hzsL3.js.map +1 -0
- package/package.json +11 -2
- package/src/__tests__/MFab.test.ts +52 -6
- package/src/__tests__/MMap.test.ts +292 -0
- package/src/__tests__/MMapLayers.test.ts +257 -0
- package/src/__tests__/MMapTools.test.ts +233 -0
- package/src/__tests__/MShader.test.ts +16 -0
- package/src/__tests__/_fakeMaplibre.ts +158 -0
- package/src/__tests__/hydration.test.ts +119 -0
- package/src/__tests__/ssr.test.ts +171 -0
- package/src/__tests__/ssrState.test.ts +155 -0
- package/src/__tests__/themeInitScript.test.ts +122 -0
- package/src/components/MChart.vue +3 -2
- package/src/components/MFab.vue +29 -7
- package/src/components/MIconButton.vue +1 -1
- package/src/components/MLightbox.vue +10 -1
- package/src/components/MMap.vue +522 -0
- package/src/components/MMapBaseLayers.vue +67 -0
- package/src/components/MMapControl.vue +61 -0
- package/src/components/MMapFeatureInfo.vue +41 -0
- package/src/components/MMapFilter.vue +80 -0
- package/src/components/MMapGeoJson.vue +136 -0
- package/src/components/MMapHover.vue +131 -0
- package/src/components/MMapIdentify.vue +103 -0
- package/src/components/MMapLayers.vue +111 -0
- package/src/components/MMapMarker.vue +102 -0
- package/src/components/MMapMeasure.vue +452 -0
- package/src/components/MMapPopup.vue +99 -0
- package/src/components/MMapSearch.vue +162 -0
- package/src/components/MSearchBar.vue +4 -1
- package/src/components/MShader.vue +11 -3
- package/src/components/_MMapLayerItem.vue +77 -0
- package/src/composables/_hydration.ts +10 -0
- package/src/composables/_mapGeometry.ts +75 -0
- package/src/composables/_ssrState.ts +80 -0
- package/src/composables/_storageKeys.ts +6 -0
- package/src/composables/_useThemeTokens.ts +42 -0
- package/src/composables/mapAdapters.ts +208 -0
- package/src/composables/mapSearch.ts +56 -0
- package/src/composables/themeInitScript.ts +51 -0
- package/src/composables/useColorPalette.ts +32 -14
- package/src/composables/useLocale.ts +62 -0
- package/src/composables/useMap.ts +98 -0
- package/src/composables/useMapFilter.ts +45 -0
- package/src/composables/useMapLayers.ts +124 -0
- package/src/composables/useTheme.ts +18 -7
- package/src/composables/useWindowSizeClass.ts +23 -4
- package/src/index.ts +4 -1
- package/src/locales/de.ts +31 -1
- package/src/locales/es.ts +31 -1
- package/src/locales/fr.ts +31 -1
- package/src/locales/ja.ts +31 -1
- package/src/locales/ko.ts +31 -1
- package/src/locales/pt.ts +31 -1
- package/src/locales/zh.ts +31 -1
- package/src/map.ts +32 -0
- package/src/plugin.ts +77 -13
- package/dist/MTextField-BPbFeI9M.js +0 -1368
- package/dist/MTextField-BPbFeI9M.js.map +0 -1
- package/dist/useLocale-CuvWRZ1h.js.map +0 -1
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { THEME_KEY } from './useTheme'
|
|
2
|
+
import { CONTRAST_KEY, CSS_KEY, PALETTE_KEY, STYLE_ID, type ContrastLevel, type PaletteId } from './useColorPalette'
|
|
3
|
+
|
|
4
|
+
export interface ThemeInitOptions {
|
|
5
|
+
/** `createM3UI`'s `palette`: the first-visit default, or forced with `persistPalette: false`. */
|
|
6
|
+
palette?: PaletteId | (string & {})
|
|
7
|
+
/** `createM3UI`'s `contrast`, with the same rules as `palette`. */
|
|
8
|
+
contrast?: ContrastLevel
|
|
9
|
+
/** `createM3UI`'s `persistPalette`. */
|
|
10
|
+
persistPalette?: boolean
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A script to inline in `<head>` of a server-rendered page (Nuxt, Vite SSR), so dark mode, the palette and the
|
|
15
|
+
* contrast level are on `<html>` before the first paint instead of when the app's JS loads. It does what
|
|
16
|
+
* `useTheme` and `useColorPalette` do when they load in the browser (the stored choice, or the given
|
|
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
|
|
19
|
+
* early: its first visit still shows the baseline until the app loads (later visits use the cached CSS).
|
|
20
|
+
*
|
|
21
|
+
* ```ts
|
|
22
|
+
* useHead({ script: [{ innerHTML: themeInitScript({ palette: 'red' }) }] })
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
export function themeInitScript(options: ThemeInitOptions = {}): string {
|
|
26
|
+
const config = JSON.stringify({
|
|
27
|
+
keys: { theme: THEME_KEY, palette: PALETTE_KEY, contrast: CONTRAST_KEY, css: CSS_KEY },
|
|
28
|
+
styleId: STYLE_ID,
|
|
29
|
+
palette: options.palette ?? null,
|
|
30
|
+
contrast: options.contrast ?? null,
|
|
31
|
+
force: options.persistPalette === false,
|
|
32
|
+
}).replace(/</g, '\\u003c')
|
|
33
|
+
// Plain ES5, no dependencies: it runs before anything else. Storage can throw (blocked site data).
|
|
34
|
+
return `(function(o){
|
|
35
|
+
var d=document.documentElement;
|
|
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)}
|
|
38
|
+
function mq(q){return !!(window.matchMedia&&window.matchMedia(q).matches)}
|
|
39
|
+
var t=get(o.keys.theme)||'system';
|
|
40
|
+
d.classList.toggle('dark',t==='dark'||(t==='system'&&mq('(prefers-color-scheme: dark)')));
|
|
41
|
+
var saved=get(o.keys.palette);
|
|
42
|
+
var p=o.force&&o.palette?o.palette:(saved||o.palette);
|
|
43
|
+
if(p&&p===saved){try{var c=JSON.parse(get(o.keys.css));if(c&&c.id===p){var s=document.createElement('style');s.id=o.styleId;s.textContent=c.css;document.head.appendChild(s)}}catch(e){}}
|
|
44
|
+
if(p&&p!=='purple')d.setAttribute('data-palette',p);
|
|
45
|
+
var levels=['standard','medium','high','system'];
|
|
46
|
+
var stored=get(o.keys.contrast);
|
|
47
|
+
var l=o.force&&o.contrast?o.contrast:stored!=null?(levels.indexOf(stored)>-1?stored:'standard'):(o.contrast||'standard');
|
|
48
|
+
if(l==='system')l=mq('(prefers-contrast: more)')?'high':'standard';
|
|
49
|
+
if(l!=='standard')d.setAttribute('data-contrast',l);
|
|
50
|
+
})(${config})`
|
|
51
|
+
}
|
|
@@ -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
|
-
|
|
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))
|
|
@@ -65,21 +73,24 @@ export interface ActiveSeed extends SeedOptions {
|
|
|
65
73
|
seed: string
|
|
66
74
|
}
|
|
67
75
|
|
|
68
|
-
const PALETTE_KEY = 'm3-palette'
|
|
76
|
+
export const PALETTE_KEY = 'm3-palette'
|
|
69
77
|
const SEED_KEY = 'm3-seed'
|
|
70
|
-
const CONTRAST_KEY = 'm3-contrast'
|
|
78
|
+
export const CONTRAST_KEY = 'm3-contrast'
|
|
71
79
|
// The generated CSS of the active palette, so a reload applies it before the generator has loaded
|
|
72
|
-
const CSS_KEY = 'm3-palette-css'
|
|
80
|
+
export const CSS_KEY = 'm3-palette-css'
|
|
73
81
|
|
|
74
82
|
function read<T>(key: string): T | null {
|
|
75
83
|
try {
|
|
76
|
-
|
|
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))
|
|
@@ -126,6 +137,7 @@ function applyContrast(level: Exclude<ContrastLevel, 'system'>) {
|
|
|
126
137
|
const persistEnabled = ref(true)
|
|
127
138
|
|
|
128
139
|
function applyAttribute(id: string) {
|
|
140
|
+
if (typeof document === 'undefined') return
|
|
129
141
|
if (id === 'purple') document.documentElement.removeAttribute('data-palette')
|
|
130
142
|
else document.documentElement.setAttribute('data-palette', id)
|
|
131
143
|
}
|
|
@@ -134,9 +146,10 @@ function applyAttribute(id: string) {
|
|
|
134
146
|
// One <style> element holds the generated CSS of the active palette (a seed, or a custom palette
|
|
135
147
|
// without CSS of its own).
|
|
136
148
|
|
|
137
|
-
|
|
149
|
+
export { STYLE_ID }
|
|
138
150
|
|
|
139
151
|
function injectCss(css: string) {
|
|
152
|
+
if (typeof document === 'undefined') return
|
|
140
153
|
let el = document.getElementById(STYLE_ID) as HTMLStyleElement | null
|
|
141
154
|
if (!el) {
|
|
142
155
|
el = document.createElement('style')
|
|
@@ -148,6 +161,7 @@ function injectCss(css: string) {
|
|
|
148
161
|
|
|
149
162
|
/** Whether a stylesheet (other than our generated one) already styles `[data-palette='<id>']`. */
|
|
150
163
|
function hasPaletteCss(id: string): boolean {
|
|
164
|
+
if (typeof document === 'undefined') return false
|
|
151
165
|
const needles = [`[data-palette="${id}"]`, `[data-palette='${id}']`, `[data-palette=${id}]`]
|
|
152
166
|
const scan = (rules: CSSRuleList): boolean => {
|
|
153
167
|
for (const rule of Array.from(rules)) {
|
|
@@ -248,7 +262,7 @@ export function useColorPalette() {
|
|
|
248
262
|
})
|
|
249
263
|
|
|
250
264
|
/** Switches to a palette by id. */
|
|
251
|
-
function set(id: string) {
|
|
265
|
+
function set(id: PaletteId | (string & {})) {
|
|
252
266
|
void selectPalette(id)
|
|
253
267
|
}
|
|
254
268
|
|
|
@@ -275,22 +289,26 @@ export function useColorPalette() {
|
|
|
275
289
|
void selectContrast(level)
|
|
276
290
|
}
|
|
277
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()
|
|
278
295
|
return {
|
|
279
|
-
palette: current,
|
|
296
|
+
palette: ssrValue(current, initial?.palette),
|
|
280
297
|
palettes,
|
|
281
298
|
set,
|
|
282
299
|
seed: readonly(activeSeed),
|
|
283
300
|
setSeed,
|
|
284
|
-
contrast: readonly(contrast)
|
|
285
|
-
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),
|
|
286
303
|
setContrast,
|
|
287
304
|
persistPalette: persistEnabled,
|
|
288
305
|
setPersistPalette,
|
|
289
306
|
}
|
|
290
307
|
}
|
|
291
308
|
|
|
292
|
-
// Apply on module load so the palette is visible before any component mounts, a generated one included
|
|
293
|
-
|
|
309
|
+
// Apply on module load so the palette is visible before any component mounts, a generated one included (not on
|
|
310
|
+
// the server: the client does it when the module loads there)
|
|
311
|
+
if (typeof document !== 'undefined') {
|
|
294
312
|
const saved = read<string>(PALETTE_KEY)
|
|
295
313
|
const cached = read<{ id: string; css: string }>(CSS_KEY)
|
|
296
314
|
if (saved && cached && cached.id === saved) injectCss(cached.css)
|
|
@@ -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
|
+
}
|