@defra/interactive-map 0.0.52-alpha → 0.0.54-alpha
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/css/index.css +1 -1
- package/dist/esm/im-core.js +1 -1
- package/dist/esm/im-shell.js +1 -1
- package/dist/umd/im-core.js +1 -1
- package/dist/umd/index.js +1 -1
- package/docs/api/context.md +30 -12
- package/docs/api/marker-config.md +16 -8
- package/docs/api/symbol-config.md +24 -9
- package/docs/api/symbol-registry.md +49 -14
- package/docs/api.md +11 -3
- package/docs/plugins/datasets.md +6 -10
- package/docs/plugins/draw.md +2 -1
- package/docs/plugins/map-key.md +47 -4
- package/package.json +1 -1
- package/plugins/beta/map-styles/dist/esm/im-map-styles-plugin.js +1 -1
- package/plugins/beta/map-styles/dist/umd/im-map-styles-plugin.js +1 -1
- package/plugins/beta/map-styles/dist/umd/index.js +1 -1
- package/plugins/datasets/dist/esm/im-datasets-ml-adapter.js +1 -1
- package/plugins/datasets/dist/esm/im-datasets-ol-adapter.js +1 -1
- package/plugins/datasets/dist/esm/im-datasets-plugin.js +1 -1
- package/plugins/datasets/dist/esm/mapboxStyleLayerAdapter.js +1 -1
- package/plugins/datasets/dist/umd/im-datasets-ml-adapter.js +1 -1
- package/plugins/datasets/dist/umd/im-datasets-ol-adapter.js +1 -1
- package/plugins/datasets/dist/umd/im-datasets-plugin.js +1 -1
- package/plugins/datasets/src/adapters/esri/esriLayerAdapter.js +6 -6
- package/plugins/datasets/src/adapters/esri/registry/esriDataset.test.js +1 -1
- package/plugins/datasets/src/adapters/maplibre/layerBuilders.js +10 -10
- package/plugins/datasets/src/adapters/maplibre/layerBuilders.test.js +22 -6
- package/plugins/datasets/src/adapters/maplibre/maplibreLayerAdapter.js +9 -3
- package/plugins/datasets/src/adapters/maplibre/maplibreLayerAdapter.test.js +18 -3
- package/plugins/datasets/src/adapters/maplibre/registry/mapLibreDataset.js +3 -3
- package/plugins/datasets/src/adapters/maplibre/registry/mapLibreDataset.test.js +20 -27
- package/plugins/datasets/src/adapters/openlayers/canvasPatternStyle.js +16 -70
- package/plugins/datasets/src/adapters/openlayers/canvasPatternStyle.test.js +30 -115
- package/plugins/datasets/src/adapters/openlayers/layerBuilders.js +11 -13
- package/plugins/datasets/src/adapters/openlayers/layerBuilders.test.js +11 -3
- package/plugins/datasets/src/adapters/openlayers/openlayersLayerAdapter.js +48 -19
- package/plugins/datasets/src/adapters/openlayers/openlayersLayerAdapter.test.js +101 -13
- package/plugins/datasets/src/adapters/openlayers/registry/openLayersDataset.js +27 -28
- package/plugins/datasets/src/adapters/openlayers/registry/openLayersDataset.test.js +51 -32
- package/plugins/datasets/src/fetch/createDynamicSource.js +2 -2
- package/plugins/datasets/src/initialise/DatasetsInit.jsx +2 -2
- package/plugins/datasets/src/initialise/defaults.js +16 -27
- package/plugins/datasets/src/initialise/defaults.test.js +25 -57
- package/plugins/datasets/src/initialise/initialiseDatasets.js +1 -4
- package/plugins/datasets/src/reducers/__data__/demoDatasets.js +1 -3
- package/plugins/datasets/src/reducers/mappedDatasetsReducer.test.js +1 -1
- package/plugins/datasets/src/registry/dataset.js +23 -17
- package/plugins/datasets/src/registry/dataset.test.js +114 -11
- package/plugins/datasets/src/registry/mapboxStyleDataset.js +1 -1
- package/plugins/datasets/src/registry/mapboxStyleDataset.test.js +1 -1
- package/plugins/draw/dist/esm/im-draw-ml-adapter.js +1 -1
- package/plugins/draw/dist/esm/im-draw-ol-adapter.js +1 -1
- package/plugins/draw/dist/esm/im-draw-plugin.js +1 -1
- package/plugins/draw/dist/esm/index.js +1 -1
- package/plugins/draw/dist/esm/liveDrawChecks.js +1 -1
- package/plugins/draw/dist/umd/im-draw-ml-adapter.js +1 -1
- package/plugins/draw/dist/umd/im-draw-ol-adapter.js +1 -1
- package/plugins/draw/dist/umd/im-draw-plugin.js +1 -1
- package/plugins/draw/dist/umd/index.js +1 -1
- package/plugins/draw/src/DrawInit.jsx +7 -5
- package/plugins/draw/src/DrawInit.test.jsx +18 -2
- package/plugins/draw/src/adapters/maplibre/MaplibreDrawAdapter.js +11 -5
- package/plugins/draw/src/adapters/maplibre/MaplibreDrawAdapter.test.js +27 -11
- package/plugins/draw/src/adapters/maplibre/mapboxDraw.js +12 -9
- package/plugins/draw/src/adapters/maplibre/mapboxDraw.test.js +18 -0
- package/plugins/draw/src/adapters/maplibre/pointSymbolImages.js +81 -56
- package/plugins/draw/src/adapters/maplibre/pointSymbolImages.test.js +149 -80
- package/plugins/draw/src/adapters/openlayers/OLDrawAdapter.js +7 -6
- package/plugins/draw/src/adapters/openlayers/OLDrawAdapter.test.js +22 -25
- package/plugins/draw/src/adapters/openlayers/core/OLDrawManager.js +26 -8
- package/plugins/draw/src/adapters/openlayers/core/OLDrawManager.test.js +58 -16
- package/plugins/draw/src/adapters/openlayers/core/styles.js +33 -20
- package/plugins/draw/src/adapters/openlayers/core/styles.test.js +47 -21
- package/plugins/draw/src/adapters/openlayers/olDraw.js +16 -12
- package/plugins/draw/src/adapters/openlayers/olDraw.test.js +27 -32
- package/plugins/draw/src/adapters/openlayers/point/pointSymbolImages.js +44 -49
- package/plugins/draw/src/adapters/openlayers/point/pointSymbolImages.test.js +100 -119
- package/plugins/draw/src/defaults.js +2 -6
- package/plugins/draw/src/utils/stripInternalProperties.test.js +2 -1
- package/plugins/draw/src/utils/symbolKeys.js +3 -4
- package/plugins/interact/dist/esm/im-interact-plugin.js +1 -1
- package/plugins/interact/dist/umd/im-interact-plugin.js +1 -1
- package/plugins/interact/dist/umd/index.js +1 -1
- package/plugins/map-key/dist/css/index.css +1 -1
- package/plugins/map-key/dist/esm/im-map-key-plugin.js +1 -1
- package/plugins/map-key/dist/umd/im-map-key-plugin.js +1 -2
- package/plugins/map-key/dist/umd/index.js +1 -1
- package/plugins/map-key/src/components/Key/Key.jsx +8 -4
- package/plugins/map-key/src/components/Key/Key.module.scss +144 -53
- package/plugins/map-key/src/components/Key/KeyGroupItem.jsx +36 -3
- package/plugins/map-key/src/components/Key/KeyGroupItem.test.jsx +44 -2
- package/plugins/map-key/src/components/Key/KeyItem.jsx +2 -2
- package/plugins/map-key/src/components/Key/KeySvg.jsx +19 -18
- package/plugins/map-key/src/components/Key/KeySvg.test.jsx +25 -18
- package/plugins/map-key/src/components/Key/KeySvgPattern.jsx +1 -2
- package/plugins/map-key/src/components/Key/KeySvgPattern.test.jsx +3 -1
- package/plugins/map-key/src/components/Key/KeySvgRamp.jsx +35 -6
- package/plugins/map-key/src/components/Key/KeySvgRamp.test.jsx +56 -16
- package/plugins/map-key/src/components/Key/KeySvgSymbol.jsx +26 -12
- package/plugins/map-key/src/components/Key/KeySvgSymbol.test.jsx +24 -74
- package/plugins/map-key/src/components/Key/MapKey.jsx +3 -1
- package/plugins/map-key/src/components/Key/svgProperties.js +8 -2
- package/plugins/map-key/src/components/Key/useRampOrientation.js +61 -0
- package/plugins/map-key/src/components/Key/useRampOrientation.test.jsx +155 -0
- package/plugins/map-key/src/index.js +34 -0
- package/plugins/map-key/src/reducers/mergeKeyGroupItems.test.js +15 -0
- package/plugins/map-key/src/registry/index.js +0 -2
- package/plugins/map-key/src/registry/index.test.js +1 -9
- package/plugins/map-key/src/utils/groupStyles.js +5 -2
- package/plugins/menu/src/registry/index.js +0 -2
- package/plugins/menu/src/registry/index.test.js +1 -9
- package/plugins/search/dist/esm/im-search-plugin.js +1 -1
- package/plugins/search/dist/umd/im-search-plugin.js +1 -1
- package/plugins/search/dist/umd/index.js +1 -1
- package/plugins/search/src/Search.jsx +0 -1
- package/plugins/search/src/components/Form/Form.jsx +3 -3
- package/plugins/search/src/components/Suggestions/Suggestions.jsx +2 -0
- package/plugins/search/src/components/Suggestions/Suggestions.test.jsx +6 -0
- package/plugins/search/src/defaults.js +3 -0
- package/plugins/search/src/events/formHandlers.js +3 -9
- package/plugins/search/src/events/formHandlers.test.js +6 -9
- package/plugins/search/src/events/inputHandlers.js +8 -2
- package/plugins/search/src/events/inputHandlers.test.js +20 -0
- package/plugins/search/src/events/suggestionHandlers.js +3 -5
- package/plugins/search/src/events/suggestionHandlers.test.js +5 -8
- package/plugins/search/src/utils/showResult.js +9 -0
- package/plugins/search/src/utils/showResult.test.js +16 -0
- package/providers/beta/esri/dist/esm/im-esri-provider.js +1 -1
- package/providers/beta/openlayers/dist/esm/im-openlayers-provider.js +1 -1
- package/providers/beta/openlayers/dist/umd/im-openlayers-provider.js +1 -1
- package/providers/beta/openlayers/dist/umd/index.js +1 -1
- package/providers/beta/openlayers/src/openlayersProvider.js +102 -2
- package/providers/beta/openlayers/src/openlayersProvider.test.js +95 -0
- package/providers/beta/openlayers/src/utils/highlightFeatures.js +20 -25
- package/providers/beta/openlayers/src/utils/highlightFeatures.test.js +73 -38
- package/providers/beta/openlayers/src/utils/patternImages.js +61 -0
- package/providers/beta/openlayers/src/utils/patternImages.test.js +74 -0
- package/providers/beta/openlayers/src/utils/symbolImages.js +103 -95
- package/providers/beta/openlayers/src/utils/symbolImages.test.js +136 -85
- package/providers/mapProvider.js +53 -1
- package/providers/mapProvider.test.js +6 -0
- package/providers/maplibre/dist/esm/im-maplibre-provider.js +1 -1
- package/providers/maplibre/dist/umd/im-maplibre-provider.js +1 -1
- package/providers/maplibre/dist/umd/index.js +1 -1
- package/providers/maplibre/src/maplibreProvider.js +50 -17
- package/providers/maplibre/src/maplibreProvider.test.js +74 -20
- package/providers/maplibre/src/utils/highlightFeatures.js +19 -14
- package/providers/maplibre/src/utils/highlightFeatures.test.js +20 -14
- package/providers/maplibre/src/utils/patternImages.js +46 -29
- package/providers/maplibre/src/utils/patternImages.test.js +52 -4
- package/providers/maplibre/src/utils/symbolImages.js +80 -39
- package/providers/maplibre/src/utils/symbolImages.test.js +157 -54
- package/src/App/components/Hints/Hints.module.scss +1 -1
- package/src/App/components/Markers/Markers.jsx +16 -25
- package/src/App/components/Markers/Markers.test.jsx +34 -48
- package/src/App/components/Markers/SymbolLabelMarker.jsx +1 -1
- package/src/App/components/Markers/SymbolMarker.jsx +1 -1
- package/src/App/components/Viewport/Viewport.jsx +6 -4
- package/src/App/components/Viewport/Viewport.test.jsx +18 -1
- package/src/App/hooks/useMapAnnouncements.js +7 -2
- package/src/App/hooks/useMapAnnouncements.test.js +13 -2
- package/src/App/hooks/useModalPanelBehaviour.js +3 -1
- package/src/App/initialiseApp.js +1 -1
- package/src/App/store/ServiceProvider.jsx +12 -3
- package/src/App/store/ServiceProvider.test.jsx +39 -0
- package/src/InteractiveMap/InteractiveMap.js +3 -3
- package/src/config/appConfig.js +1 -5
- package/src/config/mapSizeScales.js +8 -0
- package/src/config/symbolConfig.js +101 -25
- package/src/services/mapFocus.js +64 -0
- package/src/services/mapFocus.test.js +76 -0
- package/src/services/patternRegistry.js +97 -76
- package/src/services/patternRegistry.test.js +19 -1
- package/src/services/symbolComposer.js +184 -0
- package/src/services/symbolComposer.test.js +132 -0
- package/src/services/symbolRegistry.js +326 -155
- package/src/services/symbolRegistry.test.js +334 -32
- package/src/types.js +11 -5
- package/src/utils/detectInterfaceType.js +16 -5
- package/src/utils/detectInterfaceType.test.js +32 -0
- package/src/utils/hashString.js +23 -0
- package/src/utils/hashString.test.js +29 -0
- package/src/utils/imageDataCache.js +43 -0
- package/src/utils/imageDataCache.test.js +38 -0
- package/src/utils/pathBounds.js +330 -0
- package/src/utils/pathBounds.test.js +145 -0
- package/src/utils/patternUtils.js +0 -8
- package/src/utils/patternUtils.test.js +0 -25
- package/src/utils/recentImageSets.js +35 -0
- package/src/utils/recentImageSets.test.js +46 -0
- package/src/utils/symbolUtils.js +26 -29
- package/src/utils/symbolUtils.test.js +27 -41
- package/plugins/map-key/dist/umd/im-map-key-plugin.js.LICENSE.txt +0 -1
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { createImageDataCache } from './imageDataCache.js'
|
|
2
|
+
|
|
3
|
+
const imageData = (width) => ({ width, height: width })
|
|
4
|
+
|
|
5
|
+
describe('createImageDataCache', () => {
|
|
6
|
+
it('caches a rasterised image under its id', async () => {
|
|
7
|
+
const cache = createImageDataCache(2)
|
|
8
|
+
const rasterise = jest.fn(async () => imageData(10))
|
|
9
|
+
const first = await cache.rasteriseOnce('a', rasterise)
|
|
10
|
+
expect(cache.get('a')).toBe(first)
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
it('shares one rasterisation between callers asking for the same image at once', async () => {
|
|
14
|
+
const cache = createImageDataCache(2)
|
|
15
|
+
const rasterise = jest.fn(async () => imageData(10))
|
|
16
|
+
const [first, second] = await Promise.all([cache.rasteriseOnce('a', rasterise), cache.rasteriseOnce('a', rasterise)])
|
|
17
|
+
expect(rasterise).toHaveBeenCalledTimes(1)
|
|
18
|
+
expect(second).toBe(first)
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
it('tries again after a failed rasterisation, rather than sharing the failure', async () => {
|
|
22
|
+
const cache = createImageDataCache(2)
|
|
23
|
+
const failure = new Error('image failed to load')
|
|
24
|
+
await expect(cache.rasteriseOnce('a', jest.fn().mockRejectedValue(failure))).rejects.toBe(failure)
|
|
25
|
+
await expect(cache.rasteriseOnce('a', jest.fn(async () => imageData(10)))).resolves.toEqual(imageData(10))
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it('drops the least recently used image once full', async () => {
|
|
29
|
+
const cache = createImageDataCache(2)
|
|
30
|
+
await cache.rasteriseOnce('a', async () => imageData(1))
|
|
31
|
+
await cache.rasteriseOnce('b', async () => imageData(2))
|
|
32
|
+
cache.get('a') // a is now the most recently used
|
|
33
|
+
await cache.rasteriseOnce('c', async () => imageData(3))
|
|
34
|
+
expect(cache.get('a')).toEqual(imageData(1))
|
|
35
|
+
expect(cache.get('b')).toBeUndefined()
|
|
36
|
+
expect(cache.get('c')).toEqual(imageData(3))
|
|
37
|
+
})
|
|
38
|
+
})
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
// Exact bounding box of an SVG path `d` string — the area the path's outline actually covers,
|
|
2
|
+
// including curve and arc extremes (not their control points). Pure, so it behaves the same in
|
|
3
|
+
// the browser and in tests. Supports every path command, absolute and relative, implicit
|
|
4
|
+
// repeats, and arc flags written without separators (e.g. `a3 3 0 011 10`).
|
|
5
|
+
|
|
6
|
+
const COMMAND = /[MmLlHhVvCcSsQqTtAaZz]/
|
|
7
|
+
const NUMBER = /[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/y
|
|
8
|
+
const SEPARATORS = /[\s,]*/y
|
|
9
|
+
const NUMBER_START = /[-+.\d]/
|
|
10
|
+
|
|
11
|
+
// Each command's parameters, in order: 'n' a number, 'f' an arc flag (a single 0 or 1)
|
|
12
|
+
const PARAMETERS = {
|
|
13
|
+
m: 'nn', l: 'nn', h: 'n', v: 'n', c: 'nnnnnn', s: 'nnnn', q: 'nnnn', t: 'nn', a: 'nnnffnn', z: ''
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const NEAR_ZERO = 1e-12
|
|
17
|
+
const ROUNDING = 1e6 // rounds away floating-point noise, so e.g. 26 doesn't become 26.0000000001
|
|
18
|
+
const HALF = 0.5
|
|
19
|
+
const CUBIC_WEIGHT = 3 // the cubic Bézier (Bernstein) coefficient
|
|
20
|
+
const QUADRATIC_WEIGHT = 2 // the quadratic Bézier coefficient, also used in the quadratic formula
|
|
21
|
+
const DISCRIMINANT_FACTOR = 4
|
|
22
|
+
const FULL_TURN = Math.PI * QUADRATIC_WEIGHT
|
|
23
|
+
const DEGREES_PER_HALF_TURN = 180
|
|
24
|
+
const DEGREES_TO_RADIANS = Math.PI / DEGREES_PER_HALF_TURN
|
|
25
|
+
|
|
26
|
+
const round = (value) => Math.round(value * ROUNDING) / ROUNDING
|
|
27
|
+
const isNearZero = (value) => Math.abs(value) < NEAR_ZERO
|
|
28
|
+
const isWithinCurve = (progress) => progress > 0 && progress < 1
|
|
29
|
+
|
|
30
|
+
// ─── Parsing ──────────────────────────────────────────────────────────────────
|
|
31
|
+
|
|
32
|
+
class PathReader {
|
|
33
|
+
position = 0
|
|
34
|
+
|
|
35
|
+
constructor (pathData) {
|
|
36
|
+
this.pathData = pathData
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
fail (expected) {
|
|
40
|
+
throw new Error(`Invalid SVG path: ${expected} at position ${this.position} in "${this.pathData}"`)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
skipSeparators () {
|
|
44
|
+
SEPARATORS.lastIndex = this.position
|
|
45
|
+
SEPARATORS.exec(this.pathData)
|
|
46
|
+
this.position = SEPARATORS.lastIndex
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
atEnd () {
|
|
50
|
+
this.skipSeparators()
|
|
51
|
+
return this.position >= this.pathData.length
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
peek () {
|
|
55
|
+
return this.pathData[this.position]
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
readCommand () {
|
|
59
|
+
if (!COMMAND.test(this.peek())) {
|
|
60
|
+
return null
|
|
61
|
+
}
|
|
62
|
+
const command = this.peek()
|
|
63
|
+
this.position++
|
|
64
|
+
return command
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
readNumber () {
|
|
68
|
+
this.skipSeparators()
|
|
69
|
+
NUMBER.lastIndex = this.position
|
|
70
|
+
const match = NUMBER.exec(this.pathData)
|
|
71
|
+
if (!match) {
|
|
72
|
+
this.fail('expected a number')
|
|
73
|
+
}
|
|
74
|
+
this.position = NUMBER.lastIndex
|
|
75
|
+
return Number.parseFloat(match[0])
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
readFlag () {
|
|
79
|
+
this.skipSeparators()
|
|
80
|
+
const flag = this.peek()
|
|
81
|
+
if (flag !== '0' && flag !== '1') {
|
|
82
|
+
this.fail('expected an arc flag (0 or 1)')
|
|
83
|
+
}
|
|
84
|
+
this.position++
|
|
85
|
+
return Number(flag)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
readParameters (command) {
|
|
89
|
+
return [...PARAMETERS[command.toLowerCase()]].map((kind) => kind === 'f' ? this.readFlag() : this.readNumber())
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Splits path data into [command, ...parameters] segments, repeating a command for each extra
|
|
94
|
+
// parameter set (a repeated moveto becomes a lineto, per the SVG spec).
|
|
95
|
+
const parsePath = (pathData) => {
|
|
96
|
+
const reader = new PathReader(pathData)
|
|
97
|
+
const segments = []
|
|
98
|
+
let command = null
|
|
99
|
+
while (!reader.atEnd()) {
|
|
100
|
+
const explicitCommand = reader.readCommand()
|
|
101
|
+
// Without a command letter, these must be more parameters for the previous command
|
|
102
|
+
if (!explicitCommand && !(command && NUMBER_START.test(reader.peek()))) {
|
|
103
|
+
reader.fail(`unexpected "${reader.peek()}"`)
|
|
104
|
+
}
|
|
105
|
+
command = explicitCommand ?? command
|
|
106
|
+
segments.push([command, ...reader.readParameters(command)])
|
|
107
|
+
// After a moveto, further coordinates are linetos; nothing can follow a closepath's (zero) parameters
|
|
108
|
+
command = { M: 'L', m: 'l', Z: null, z: null }[command] ?? command
|
|
109
|
+
}
|
|
110
|
+
return segments
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ─── Curve and arc extremes ───────────────────────────────────────────────────
|
|
114
|
+
|
|
115
|
+
// Progress values (0–1 along the curve) where a cubic Bézier's coordinate on one axis turns,
|
|
116
|
+
// i.e. where its derivative is zero.
|
|
117
|
+
const cubicTurningPoints = (start, control1, control2, end) => {
|
|
118
|
+
// derivative ÷ 3 = quadratic × t² + linear × t + constant
|
|
119
|
+
const quadratic = -start + CUBIC_WEIGHT * control1 - CUBIC_WEIGHT * control2 + end
|
|
120
|
+
const linear = QUADRATIC_WEIGHT * (start - QUADRATIC_WEIGHT * control1 + control2)
|
|
121
|
+
const constant = control1 - start
|
|
122
|
+
if (isNearZero(quadratic)) {
|
|
123
|
+
return isNearZero(linear) ? [] : [-constant / linear]
|
|
124
|
+
}
|
|
125
|
+
const discriminant = linear * linear - DISCRIMINANT_FACTOR * quadratic * constant
|
|
126
|
+
if (discriminant < 0) {
|
|
127
|
+
return []
|
|
128
|
+
}
|
|
129
|
+
const root = Math.sqrt(discriminant)
|
|
130
|
+
return [(-linear + root) / (QUADRATIC_WEIGHT * quadratic), (-linear - root) / (QUADRATIC_WEIGHT * quadratic)]
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const cubicPointAt = (start, control1, control2, end, progress) => {
|
|
134
|
+
const remaining = 1 - progress
|
|
135
|
+
return remaining ** CUBIC_WEIGHT * start +
|
|
136
|
+
CUBIC_WEIGHT * remaining ** QUADRATIC_WEIGHT * progress * control1 +
|
|
137
|
+
CUBIC_WEIGHT * remaining * progress ** QUADRATIC_WEIGHT * control2 +
|
|
138
|
+
progress ** CUBIC_WEIGHT * end
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const quadTurningPoints = (start, control, end) => {
|
|
142
|
+
const denominator = start - QUADRATIC_WEIGHT * control + end
|
|
143
|
+
return isNearZero(denominator) ? [] : [(start - control) / denominator]
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const quadPointAt = (start, control, end, progress) => {
|
|
147
|
+
const remaining = 1 - progress
|
|
148
|
+
return remaining ** QUADRATIC_WEIGHT * start + QUADRATIC_WEIGHT * remaining * progress * control + progress ** QUADRATIC_WEIGHT * end
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const wrapAngle = (angle) => ((angle % FULL_TURN) + FULL_TURN) % FULL_TURN
|
|
152
|
+
|
|
153
|
+
// An elliptical arc's centre and angles, per the SVG spec's endpoint-to-centre conversion —
|
|
154
|
+
// including scaling up radii too small to span the endpoints.
|
|
155
|
+
const getArcGeometry = ({ startX, startY, endX, endY, radiusX, radiusY, rotation, largeArc, sweep }) => {
|
|
156
|
+
const cosRotation = Math.cos(rotation * DEGREES_TO_RADIANS)
|
|
157
|
+
const sinRotation = Math.sin(rotation * DEGREES_TO_RADIANS)
|
|
158
|
+
const halfDeltaX = (startX - endX) * HALF
|
|
159
|
+
const halfDeltaY = (startY - endY) * HALF
|
|
160
|
+
// The start point in the ellipse's own (unrotated, centred) frame
|
|
161
|
+
const localX = cosRotation * halfDeltaX + sinRotation * halfDeltaY
|
|
162
|
+
const localY = -sinRotation * halfDeltaX + cosRotation * halfDeltaY
|
|
163
|
+
const radiusScale = Math.max(1, Math.sqrt((localX * localX) / (radiusX * radiusX) + (localY * localY) / (radiusY * radiusY)))
|
|
164
|
+
const scaledRadiusX = radiusX * radiusScale
|
|
165
|
+
const scaledRadiusY = radiusY * radiusScale
|
|
166
|
+
const radiiProduct = scaledRadiusX * scaledRadiusX * scaledRadiusY * scaledRadiusY
|
|
167
|
+
const weighted = scaledRadiusX * scaledRadiusX * localY * localY + scaledRadiusY * scaledRadiusY * localX * localX
|
|
168
|
+
const direction = largeArc === sweep ? -1 : 1
|
|
169
|
+
const centreFactor = direction * Math.sqrt(Math.max(0, (radiiProduct - weighted) / weighted))
|
|
170
|
+
const localCentreX = centreFactor * (scaledRadiusX * localY / scaledRadiusY)
|
|
171
|
+
const localCentreY = centreFactor * -(scaledRadiusY * localX / scaledRadiusX)
|
|
172
|
+
|
|
173
|
+
const startAngle = Math.atan2((localY - localCentreY) / scaledRadiusY, (localX - localCentreX) / scaledRadiusX)
|
|
174
|
+
const endAngle = Math.atan2((-localY - localCentreY) / scaledRadiusY, (-localX - localCentreX) / scaledRadiusX)
|
|
175
|
+
let sweepAngle = endAngle - startAngle
|
|
176
|
+
if (sweep && sweepAngle < 0) { sweepAngle += FULL_TURN }
|
|
177
|
+
if (!sweep && sweepAngle > 0) { sweepAngle -= FULL_TURN }
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
centreX: cosRotation * localCentreX - sinRotation * localCentreY + (startX + endX) * HALF,
|
|
181
|
+
centreY: sinRotation * localCentreX + cosRotation * localCentreY + (startY + endY) * HALF,
|
|
182
|
+
radiusX: scaledRadiusX,
|
|
183
|
+
radiusY: scaledRadiusY,
|
|
184
|
+
cosRotation,
|
|
185
|
+
sinRotation,
|
|
186
|
+
startAngle,
|
|
187
|
+
sweepAngle
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Points on an elliptical arc where x or y turns (the endpoints are added by the caller).
|
|
192
|
+
const arcTurningPoints = (arc) => {
|
|
193
|
+
if (isNearZero(arc.radiusX) || isNearZero(arc.radiusY) || (arc.startX === arc.endX && arc.startY === arc.endY)) {
|
|
194
|
+
return [] // a straight line, or nothing at all
|
|
195
|
+
}
|
|
196
|
+
const { centreX, centreY, radiusX, radiusY, cosRotation, sinRotation, startAngle, sweepAngle } = getArcGeometry(arc)
|
|
197
|
+
const isOnArc = (angle) => sweepAngle >= 0
|
|
198
|
+
? wrapAngle(angle - startAngle) <= sweepAngle
|
|
199
|
+
: wrapAngle(startAngle - angle) <= -sweepAngle
|
|
200
|
+
const pointAt = (angle) => [
|
|
201
|
+
centreX + radiusX * cosRotation * Math.cos(angle) - radiusY * sinRotation * Math.sin(angle),
|
|
202
|
+
centreY + radiusX * sinRotation * Math.cos(angle) + radiusY * cosRotation * Math.sin(angle)
|
|
203
|
+
]
|
|
204
|
+
// The angles where x and y turn, each with its opposite
|
|
205
|
+
const xTurn = Math.atan2(-radiusY * sinRotation, radiusX * cosRotation)
|
|
206
|
+
const yTurn = Math.atan2(radiusY * cosRotation, radiusX * sinRotation)
|
|
207
|
+
return [xTurn, xTurn + Math.PI, yTurn, yTurn + Math.PI].filter(isOnArc).map(pointAt)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// ─── Tracing ──────────────────────────────────────────────────────────────────
|
|
211
|
+
|
|
212
|
+
// Follows the path's current point, widening the bounds to cover everything it draws.
|
|
213
|
+
class PathTracer {
|
|
214
|
+
currentX = 0
|
|
215
|
+
currentY = 0
|
|
216
|
+
subpathStartX = 0
|
|
217
|
+
subpathStartY = 0
|
|
218
|
+
lastCubicControl = null // second control point of the previous C/S, for S's reflection
|
|
219
|
+
lastQuadControl = null // control point of the previous Q/T, for T's reflection
|
|
220
|
+
hasPoints = false
|
|
221
|
+
minX = Infinity
|
|
222
|
+
minY = Infinity
|
|
223
|
+
maxX = -Infinity
|
|
224
|
+
maxY = -Infinity
|
|
225
|
+
|
|
226
|
+
include (pointX, pointY) {
|
|
227
|
+
this.hasPoints = true
|
|
228
|
+
this.minX = Math.min(this.minX, pointX)
|
|
229
|
+
this.minY = Math.min(this.minY, pointY)
|
|
230
|
+
this.maxX = Math.max(this.maxX, pointX)
|
|
231
|
+
this.maxY = Math.max(this.maxY, pointY)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
moveCurrentPoint (pointX, pointY) {
|
|
235
|
+
this.currentX = pointX
|
|
236
|
+
this.currentY = pointY
|
|
237
|
+
this.include(pointX, pointY)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
moveTo (pointX, pointY) {
|
|
241
|
+
this.moveCurrentPoint(pointX, pointY)
|
|
242
|
+
this.subpathStartX = pointX
|
|
243
|
+
this.subpathStartY = pointY
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
lineTo (pointX, pointY) {
|
|
247
|
+
this.moveCurrentPoint(pointX, pointY)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// The reflection of the previous control point about the current point, or the current point
|
|
251
|
+
// itself if the previous segment wasn't the same kind of curve.
|
|
252
|
+
reflect (previousControl) {
|
|
253
|
+
return previousControl
|
|
254
|
+
? [QUADRATIC_WEIGHT * this.currentX - previousControl[0], QUADRATIC_WEIGHT * this.currentY - previousControl[1]]
|
|
255
|
+
: [this.currentX, this.currentY]
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
cubicTo (control1X, control1Y, control2X, control2Y, endX, endY) {
|
|
259
|
+
const xs = [this.currentX, control1X, control2X, endX]
|
|
260
|
+
const ys = [this.currentY, control1Y, control2Y, endY]
|
|
261
|
+
const progresses = [...cubicTurningPoints(...xs), ...cubicTurningPoints(...ys)].filter(isWithinCurve)
|
|
262
|
+
progresses.forEach((progress) => this.include(cubicPointAt(...xs, progress), cubicPointAt(...ys, progress)))
|
|
263
|
+
this.moveCurrentPoint(endX, endY)
|
|
264
|
+
this.lastCubicControl = [control2X, control2Y]
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
quadTo (controlX, controlY, endX, endY) {
|
|
268
|
+
const xs = [this.currentX, controlX, endX]
|
|
269
|
+
const ys = [this.currentY, controlY, endY]
|
|
270
|
+
const progresses = [...quadTurningPoints(...xs), ...quadTurningPoints(...ys)].filter(isWithinCurve)
|
|
271
|
+
progresses.forEach((progress) => this.include(quadPointAt(...xs, progress), quadPointAt(...ys, progress)))
|
|
272
|
+
this.moveCurrentPoint(endX, endY)
|
|
273
|
+
this.lastQuadControl = [controlX, controlY]
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
arcTo (arc) {
|
|
277
|
+
arcTurningPoints({ ...arc, startX: this.currentX, startY: this.currentY })
|
|
278
|
+
.forEach(([pointX, pointY]) => this.include(pointX, pointY))
|
|
279
|
+
this.moveCurrentPoint(arc.endX, arc.endY)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
close () {
|
|
283
|
+
this.currentX = this.subpathStartX
|
|
284
|
+
this.currentY = this.subpathStartY
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Draws one segment, given its parameters already offset to absolute coordinates where relative.
|
|
289
|
+
// `params` holds the raw values; `origin` is the current point for a relative command, else 0,0.
|
|
290
|
+
const SEGMENT_TRACERS = {
|
|
291
|
+
m: (tracer, [toX, toY], [originX, originY]) => tracer.moveTo(toX + originX, toY + originY),
|
|
292
|
+
l: (tracer, [toX, toY], [originX, originY]) => tracer.lineTo(toX + originX, toY + originY),
|
|
293
|
+
h: (tracer, [toX], [originX]) => tracer.lineTo(toX + originX, tracer.currentY),
|
|
294
|
+
v: (tracer, [toY], [, originY]) => tracer.lineTo(tracer.currentX, toY + originY),
|
|
295
|
+
c: (tracer, [control1X, control1Y, control2X, control2Y, toX, toY], [originX, originY]) =>
|
|
296
|
+
tracer.cubicTo(control1X + originX, control1Y + originY, control2X + originX, control2Y + originY, toX + originX, toY + originY),
|
|
297
|
+
s: (tracer, [control2X, control2Y, toX, toY], [originX, originY], previous) =>
|
|
298
|
+
tracer.cubicTo(...tracer.reflect(previous.cubic), control2X + originX, control2Y + originY, toX + originX, toY + originY),
|
|
299
|
+
q: (tracer, [controlX, controlY, toX, toY], [originX, originY]) =>
|
|
300
|
+
tracer.quadTo(controlX + originX, controlY + originY, toX + originX, toY + originY),
|
|
301
|
+
t: (tracer, [toX, toY], [originX, originY], previous) =>
|
|
302
|
+
tracer.quadTo(...tracer.reflect(previous.quad), toX + originX, toY + originY),
|
|
303
|
+
a: (tracer, [radiusX, radiusY, rotation, largeArc, sweep, toX, toY], [originX, originY]) =>
|
|
304
|
+
tracer.arcTo({ radiusX: Math.abs(radiusX), radiusY: Math.abs(radiusY), rotation, largeArc, sweep, endX: toX + originX, endY: toY + originY }),
|
|
305
|
+
z: (tracer) => tracer.close()
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Returns the exact bounding box of an SVG path.
|
|
310
|
+
*
|
|
311
|
+
* @param {string} pathData - SVG path data
|
|
312
|
+
* @returns {number[]} [x, y, width, height]
|
|
313
|
+
* @throws {Error} if the path can't be parsed or draws nothing
|
|
314
|
+
*/
|
|
315
|
+
export const getPathBounds = (pathData) => {
|
|
316
|
+
const tracer = new PathTracer()
|
|
317
|
+
for (const [command, ...params] of parsePath(pathData)) {
|
|
318
|
+
const lowerCommand = command.toLowerCase()
|
|
319
|
+
const origin = command === lowerCommand ? [tracer.currentX, tracer.currentY] : [0, 0]
|
|
320
|
+
// Only a segment immediately after a C/S (or Q/T) can reflect its control point
|
|
321
|
+
const previous = { cubic: tracer.lastCubicControl, quad: tracer.lastQuadControl }
|
|
322
|
+
tracer.lastCubicControl = null
|
|
323
|
+
tracer.lastQuadControl = null
|
|
324
|
+
SEGMENT_TRACERS[lowerCommand](tracer, params, origin, previous)
|
|
325
|
+
}
|
|
326
|
+
if (!tracer.hasPoints) {
|
|
327
|
+
throw new Error(`Invalid SVG path: "${pathData}" draws nothing`)
|
|
328
|
+
}
|
|
329
|
+
return [round(tracer.minX), round(tracer.minY), round(tracer.maxX - tracer.minX), round(tracer.maxY - tracer.minY)]
|
|
330
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { getPathBounds } from './pathBounds.js'
|
|
2
|
+
import * as symbolConfig from '../config/symbolConfig.js'
|
|
3
|
+
|
|
4
|
+
const expectBounds = (d, expected) => {
|
|
5
|
+
getPathBounds(d).forEach((value, i) => expect(value).toBeCloseTo(expected[i], 3))
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
describe('getPathBounds — lines', () => {
|
|
9
|
+
it('bounds absolute lines and closepath', () => {
|
|
10
|
+
expectBounds('M2 3L10 3L10 8Z', [2, 3, 8, 5])
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
it('bounds relative, horizontal and vertical commands', () => {
|
|
14
|
+
expectBounds('m2 3h8v5h-8z', [2, 3, 8, 5])
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('treats extra moveto coordinates as linetos (absolute and relative)', () => {
|
|
18
|
+
expectBounds('M0 0 10 0 10 10', [0, 0, 10, 10])
|
|
19
|
+
expectBounds('m1 1 4 0 0 4', [1, 1, 4, 4])
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('continues from the subpath start after closepath', () => {
|
|
23
|
+
expectBounds('M5 5h2v2zl-5 -5', [0, 0, 7, 7])
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it('parses commas, exponents and numbers without separators', () => {
|
|
27
|
+
expectBounds('M1e1,2L-3.5.5', [-3.5, 0.5, 13.5, 1.5])
|
|
28
|
+
})
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
describe('getPathBounds — curves', () => {
|
|
32
|
+
it('includes a cubic curve\'s extreme, not its control points', () => {
|
|
33
|
+
// control points at y=-10, but the curve itself only reaches y=-7.5
|
|
34
|
+
expectBounds('M0 0C0 -10 10 -10 10 0', [0, -7.5, 10, 7.5])
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('reflects the previous control point for S', () => {
|
|
38
|
+
// S mirrors (0,-10)→(10,-10) about (10,0), giving a downward bulge to y=7.5
|
|
39
|
+
expectBounds('M0 0C0 -10 10 -10 10 0S20 10 20 0', [0, -7.5, 20, 15])
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('uses the current point as S\'s first control point when there\'s no previous cubic', () => {
|
|
43
|
+
// control points (0,0) and (10,-10): the curve turns at t = 2/3, y = -40/9
|
|
44
|
+
expectBounds('M0 0S10 -10 10 0', [0, -40 / 9, 10, 40 / 9])
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('adds nothing for a cubic that never turns along an axis', () => {
|
|
48
|
+
// x runs 0→10 without turning back, and y's only turning points are at the endpoints
|
|
49
|
+
expectBounds('M0 0C5 0 5 10 10 10', [0, 0, 10, 10])
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('includes a quadratic curve\'s extreme', () => {
|
|
53
|
+
expectBounds('M0 0Q5 -10 10 0', [0, -5, 10, 5])
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('reflects the previous control point for T', () => {
|
|
57
|
+
expectBounds('M0 0Q5 -10 10 0T20 0', [0, -5, 20, 10])
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it('treats T with no previous quadratic as a straight line', () => {
|
|
61
|
+
expectBounds('M0 0T20 10', [0, 0, 20, 10])
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('handles a cubic whose turning point equation is linear (a cubic that\'s really a quadratic)', () => {
|
|
65
|
+
// y control points 0, 10, 10, 0: the derivative's t² term cancels, leaving one turn at t = 0.5
|
|
66
|
+
expectBounds('M0 0C0 10 10 10 10 0', [0, 0, 10, 7.5])
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it('includes curves\' extremes along x as well as y', () => {
|
|
70
|
+
expectBounds('M0 0C10 0 10 10 0 10', [0, 0, 7.5, 10])
|
|
71
|
+
expectBounds('M0 0Q10 5 0 10', [0, 0, 5, 10])
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it('adds nothing for a straight-line cubic', () => {
|
|
75
|
+
expectBounds('M0 0C10 10 20 20 30 30', [0, 0, 30, 30])
|
|
76
|
+
})
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
describe('getPathBounds — arcs', () => {
|
|
80
|
+
it('includes the points an arc sweeps through', () => {
|
|
81
|
+
// a half circle over the top of (0,0)-(20,0): reaches y=-10
|
|
82
|
+
expectBounds('M0 0A10 10 0 0 1 20 0', [0, -10, 20, 10])
|
|
83
|
+
// the same endpoints swept the other way: the bottom half
|
|
84
|
+
expectBounds('M0 0A10 10 0 0 0 20 0', [0, 0, 20, 10])
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
it('leaves out extremes a short arc doesn\'t reach', () => {
|
|
88
|
+
// a quarter circle from the top to the right of centre (0,10) stays within its endpoints
|
|
89
|
+
expectBounds('M0 0A10 10 0 0 1 10 10', [0, 0, 10, 10])
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
it('includes the far side for a large arc', () => {
|
|
93
|
+
// 270° the long way round from (0,0) to (10,10) about centre (0,10)
|
|
94
|
+
expectBounds('M0 0A10 10 0 1 0 10 10', [-10, 0, 20, 20])
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it('scales up radii too small to span the endpoints', () => {
|
|
98
|
+
// radius 1 can't reach from (0,0) to (20,0), so it's scaled to a radius-10 half circle
|
|
99
|
+
expectBounds('M0 0A1 1 0 0 1 20 0', [0, -10, 20, 10])
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
it('handles rotated ellipses', () => {
|
|
103
|
+
// a full ellipse (two half arcs), rx 10 ry 5, rotated 90° — so 10 tall and 5 wide each side
|
|
104
|
+
expectBounds('M0 -10A10 5 90 0 1 0 10A10 5 90 0 1 0 -10', [-5, -10, 10, 20])
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
it('reads arc flags written without separators', () => {
|
|
108
|
+
expectBounds('M0 0a10 10 0 0120 0', [0, -10, 20, 10])
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
it('treats a zero-radius arc as a straight line', () => {
|
|
112
|
+
expectBounds('M0 0A0 5 0 0 1 20 10', [0, 0, 20, 10])
|
|
113
|
+
})
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
describe('getPathBounds — errors', () => {
|
|
117
|
+
it('throws for an empty path', () => {
|
|
118
|
+
expect(() => getPathBounds('')).toThrow('draws nothing')
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
it('throws for an unknown command', () => {
|
|
122
|
+
expect(() => getPathBounds('M0 0X10 10')).toThrow('unexpected "X"')
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
it('throws for a missing number', () => {
|
|
126
|
+
expect(() => getPathBounds('M0 0L10')).toThrow('expected a number')
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
it('throws for an invalid arc flag', () => {
|
|
130
|
+
expect(() => getPathBounds('M0 0A10 10 0 2 1 20 0')).toThrow('arc flag')
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
it('throws for parameters before any command', () => {
|
|
134
|
+
expect(() => getPathBounds('10 10')).toThrow('unexpected')
|
|
135
|
+
})
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
// The built-in shapes' bounds are typed into symbolConfig.js; they drive each symbol's viewBox,
|
|
139
|
+
// anchor and centring, so they must always match the path they describe.
|
|
140
|
+
describe('built-in symbol bounds', () => {
|
|
141
|
+
it.each(['pin', 'circle', 'square', 'hexagon', 'triangle', 'diamond'])('%s bounds match its path', (id) => {
|
|
142
|
+
const { path, bounds } = symbolConfig[id]
|
|
143
|
+
expectBounds(path, bounds)
|
|
144
|
+
})
|
|
145
|
+
})
|
|
@@ -5,14 +5,6 @@ const PATTERN_MIN_PIXEL_RATIO = 2
|
|
|
5
5
|
|
|
6
6
|
export const getEffectivePixelRatio = (pixelRatio) => Math.max(PATTERN_MIN_PIXEL_RATIO, pixelRatio * 2)
|
|
7
7
|
|
|
8
|
-
export const hashString = (str) => {
|
|
9
|
-
let hash = 0
|
|
10
|
-
for (const ch of str) {
|
|
11
|
-
hash = Math.trunc(((hash << 5) - hash) + ch.codePointAt(0))
|
|
12
|
-
}
|
|
13
|
-
return Math.abs(hash).toString(36) // NOSONAR: base36 encoding for compact alphanumeric hash string
|
|
14
|
-
}
|
|
15
|
-
|
|
16
8
|
/**
|
|
17
9
|
* Replaces {{foregroundColor}} and {{backgroundColor}} tokens in SVG content with resolved colour values.
|
|
18
10
|
*
|
|
@@ -1,33 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
|
-
hashString,
|
|
3
2
|
injectColors,
|
|
4
3
|
hasPattern
|
|
5
4
|
} from './patternUtils.js'
|
|
6
5
|
|
|
7
|
-
describe('hashString', () => {
|
|
8
|
-
test('returns a non-empty string', () => {
|
|
9
|
-
expect(typeof hashString('hello')).toBe('string')
|
|
10
|
-
expect(hashString('hello').length).toBeGreaterThan(0)
|
|
11
|
-
})
|
|
12
|
-
|
|
13
|
-
test('is deterministic', () => {
|
|
14
|
-
expect(hashString('hello')).toBe(hashString('hello'))
|
|
15
|
-
})
|
|
16
|
-
|
|
17
|
-
it('returns the same hash for the same input', () => {
|
|
18
|
-
expect(hashString('https://tiles.example.com/{z}/{x}/{y}'))
|
|
19
|
-
.toBe(hashString('https://tiles.example.com/{z}/{x}/{y}'))
|
|
20
|
-
})
|
|
21
|
-
|
|
22
|
-
test('produces different values for different inputs', () => {
|
|
23
|
-
expect(hashString('a')).not.toBe(hashString('b'))
|
|
24
|
-
})
|
|
25
|
-
|
|
26
|
-
it('handles an empty string without throwing', () => {
|
|
27
|
-
expect(() => hashString('')).not.toThrow()
|
|
28
|
-
})
|
|
29
|
-
})
|
|
30
|
-
|
|
31
6
|
describe('injectColors', () => {
|
|
32
7
|
test('replaces {{foregroundColor}} and {{backgroundColor}} tokens', () => {
|
|
33
8
|
const result = injectColors('fill="{{foregroundColor}}" bg="{{backgroundColor}}"', 'red', 'blue')
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// The current map size and style, and the one before it — layers still show the previous one's
|
|
2
|
+
// images until every plugin has switched over to the current one's
|
|
3
|
+
const KEPT_SETS = 2
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Records which image ids were registered for each map size and style, keeping the most
|
|
7
|
+
* recently registered ones and reporting which ids only older ones used. A map provider drops
|
|
8
|
+
* those images, so its symbol images can't build up as the map size or style changes.
|
|
9
|
+
*/
|
|
10
|
+
export class RecentImageSets {
|
|
11
|
+
sets = new Map() // key → Set of imageIds, least recently registered first
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Records image ids registered for a map size and style.
|
|
15
|
+
*
|
|
16
|
+
* @param {string} key - identifies the map size and style, e.g. `${mapStyle.id}|${pixelRatio}`
|
|
17
|
+
* @param {string[]} imageIds
|
|
18
|
+
* @returns {string[]} ids no longer used by any kept size and style
|
|
19
|
+
*/
|
|
20
|
+
add (key, imageIds) {
|
|
21
|
+
const ids = this.sets.get(key) ?? new Set()
|
|
22
|
+
this.sets.delete(key)
|
|
23
|
+
this.sets.set(key, ids)
|
|
24
|
+
imageIds.forEach((imageId) => ids.add(imageId))
|
|
25
|
+
|
|
26
|
+
const staleIds = new Set()
|
|
27
|
+
while (this.sets.size > KEPT_SETS) {
|
|
28
|
+
const [oldestKey, oldestIds] = this.sets.entries().next().value
|
|
29
|
+
this.sets.delete(oldestKey)
|
|
30
|
+
oldestIds.forEach((imageId) => staleIds.add(imageId))
|
|
31
|
+
}
|
|
32
|
+
this.sets.forEach((keptIds) => keptIds.forEach((imageId) => staleIds.delete(imageId)))
|
|
33
|
+
return Array.from(staleIds)
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { RecentImageSets } from './recentImageSets.js'
|
|
2
|
+
|
|
3
|
+
describe('RecentImageSets', () => {
|
|
4
|
+
it('drops nothing while there are no more than two sizes or styles', () => {
|
|
5
|
+
const sets = new RecentImageSets()
|
|
6
|
+
expect(sets.add('outdoor|2', ['a', 'b'])).toEqual([])
|
|
7
|
+
expect(sets.add('outdoor|3', ['c', 'd'])).toEqual([])
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
it('reports the oldest size or style\'s ids when a third is registered', () => {
|
|
11
|
+
const sets = new RecentImageSets()
|
|
12
|
+
sets.add('outdoor|2', ['a', 'b'])
|
|
13
|
+
sets.add('outdoor|3', ['c'])
|
|
14
|
+
expect(sets.add('outdoor|4', ['d'])).toEqual(['a', 'b'])
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('keeps an id that a kept size or style also uses', () => {
|
|
18
|
+
const sets = new RecentImageSets()
|
|
19
|
+
sets.add('outdoor|2', ['shared', 'a'])
|
|
20
|
+
sets.add('dark|2', ['shared', 'b'])
|
|
21
|
+
expect(sets.add('night|2', ['c'])).toEqual(['a'])
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('collects every registration for the same size and style, from any caller', () => {
|
|
25
|
+
const sets = new RecentImageSets()
|
|
26
|
+
sets.add('outdoor|2', ['dataset'])
|
|
27
|
+
sets.add('outdoor|2', ['draw'])
|
|
28
|
+
sets.add('outdoor|3', [])
|
|
29
|
+
expect(sets.add('outdoor|4', [])).toEqual(['dataset', 'draw'])
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
it('treats registering again as the most recent use, so returning to a size or style keeps it', () => {
|
|
33
|
+
const sets = new RecentImageSets()
|
|
34
|
+
sets.add('outdoor|2', ['a'])
|
|
35
|
+
sets.add('outdoor|3', ['b'])
|
|
36
|
+
sets.add('outdoor|2', ['a'])
|
|
37
|
+
expect(sets.add('outdoor|4', ['c'])).toEqual(['b'])
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
it('has no limit on how many images a size or style can hold', () => {
|
|
41
|
+
const sets = new RecentImageSets()
|
|
42
|
+
const manyIds = Array.from({ length: 5000 }, (_, index) => `image-${index}`)
|
|
43
|
+
sets.add('outdoor|2', manyIds)
|
|
44
|
+
expect(sets.add('outdoor|3', manyIds)).toEqual([])
|
|
45
|
+
})
|
|
46
|
+
})
|