@defra/interactive-map 0.0.58-alpha → 0.0.60-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.
Files changed (140) hide show
  1. package/assets/templates/add-polygons.njk +2 -2
  2. package/assets/templates/add-symbols.njk +2 -2
  3. package/dist/css/index.css +1 -1
  4. package/dist/esm/im-core.js +1 -1
  5. package/dist/esm/im-shell.js +1 -1
  6. package/dist/umd/im-core.js +1 -1
  7. package/dist/umd/index.js +1 -1
  8. package/docs/api/panel-definition.md +30 -0
  9. package/docs/api/symbol-config.md +12 -0
  10. package/docs/api.md +21 -2
  11. package/docs/assets/images/slot-map.svg +3 -3
  12. package/docs/plugins/datasets.md +11 -1
  13. package/docs/plugins/draw.md +95 -13
  14. package/package.json +1 -1
  15. package/plugins/datasets/dist/esm/index.js +1 -1
  16. package/plugins/datasets/dist/esm/layerAdapter.js +1 -1
  17. package/plugins/datasets/dist/umd/im-datasets-ml-adapter.js +1 -1
  18. package/plugins/datasets/dist/umd/im-datasets-ol-adapter.js +1 -1
  19. package/plugins/datasets/dist/umd/im-datasets-plugin.js +1 -1
  20. package/plugins/datasets/dist/umd/index.js +1 -1
  21. package/plugins/datasets/src/index.js +0 -1
  22. package/plugins/datasets/src/index.test.js +2 -8
  23. package/plugins/datasets/src/registry/dataset.test.js +9 -0
  24. package/plugins/draw/dist/esm/im-draw-ml-adapter.js +1 -1
  25. package/plugins/draw/dist/esm/im-draw-ol-adapter.js +1 -1
  26. package/plugins/draw/dist/esm/im-draw-plugin.js +1 -1
  27. package/plugins/draw/dist/esm/index.js +1 -1
  28. package/plugins/draw/dist/esm/liveDrawChecks.js +1 -1
  29. package/plugins/draw/dist/umd/im-draw-ml-adapter.js +1 -1
  30. package/plugins/draw/dist/umd/im-draw-ol-adapter.js +1 -1
  31. package/plugins/draw/dist/umd/im-draw-plugin.js +1 -1
  32. package/plugins/draw/dist/umd/index.js +1 -1
  33. package/plugins/draw/src/adapterEvents.js +2 -0
  34. package/plugins/draw/src/adapters/adapterContract.test.js +1 -0
  35. package/plugins/draw/src/adapters/maplibre/MaplibreDrawAdapter.js +15 -3
  36. package/plugins/draw/src/adapters/maplibre/MaplibreDrawAdapter.test.js +27 -0
  37. package/plugins/draw/src/adapters/maplibre/modes/editPointMode/pointerHandlers.js +8 -19
  38. package/plugins/draw/src/adapters/maplibre/modes/editPointMode/pointerHandlers.test.js +20 -0
  39. package/plugins/draw/src/adapters/maplibre/modes/editVertexMode/pointerHandlers.js +6 -17
  40. package/plugins/draw/src/adapters/maplibre/modes/editVertexMode/pointerHandlers.test.js +19 -0
  41. package/plugins/draw/src/adapters/maplibre/utils/editModeEvents.js +29 -1
  42. package/plugins/draw/src/adapters/openlayers/OLDrawAdapter.js +13 -3
  43. package/plugins/draw/src/adapters/openlayers/OLDrawAdapter.test.js +28 -0
  44. package/plugins/draw/src/api/addFeature.js +9 -6
  45. package/plugins/draw/src/api/addFeature.test.js +37 -10
  46. package/plugins/draw/src/api/editFeature.js +1 -1
  47. package/plugins/draw/src/api/recheckGeometry.js +1 -1
  48. package/plugins/draw/src/api/recheckGeometry.test.js +2 -2
  49. package/plugins/draw/src/api/setProperties.js +39 -0
  50. package/plugins/draw/src/api/setProperties.test.js +74 -0
  51. package/plugins/draw/src/api/setStyle.js +16 -19
  52. package/plugins/draw/src/api/setStyle.test.js +17 -2
  53. package/plugins/draw/src/api/split.js +7 -4
  54. package/plugins/draw/src/api/split.test.js +25 -2
  55. package/plugins/draw/src/events.js +95 -53
  56. package/plugins/draw/src/events.test.js +425 -6
  57. package/plugins/draw/src/manifest.js +6 -4
  58. package/plugins/draw/src/manifest.test.js +20 -26
  59. package/plugins/draw/src/reducer.js +7 -0
  60. package/plugins/draw/src/reducer.test.js +11 -0
  61. package/plugins/draw/src/utils/flattenStyleProperties.js +54 -2
  62. package/plugins/draw/src/utils/flattenStyleProperties.test.js +74 -1
  63. package/plugins/draw/src/utils/isPlainObject.js +14 -0
  64. package/plugins/draw/src/utils/isPlainObject.test.js +24 -0
  65. package/plugins/draw/src/utils/mergeFeatureProperties.js +45 -0
  66. package/plugins/draw/src/utils/mergeFeatureProperties.test.js +48 -0
  67. package/plugins/draw/src/utils/stripInternalProperties.js +3 -2
  68. package/plugins/draw/src/validation/commitChecks.js +29 -11
  69. package/plugins/draw/src/validation/commitChecks.test.js +67 -11
  70. package/plugins/draw/src/validation/validateGeometry.js +12 -5
  71. package/plugins/draw/src/validation/validateGeometry.test.js +18 -0
  72. package/plugins/interact/dist/esm/im-interact-plugin.js +1 -1
  73. package/plugins/interact/dist/umd/im-interact-plugin.js +1 -1
  74. package/plugins/map-key/dist/esm/im-map-key-plugin.js +1 -1
  75. package/plugins/map-key/dist/umd/im-map-key-plugin.js +1 -1
  76. package/plugins/search/dist/css/index.css +1 -1
  77. package/plugins/search/src/components/Form/Form.module.scss +1 -0
  78. package/providers/esri/dist/esm/im-esri-provider.js +1 -1
  79. package/providers/esri/src/esriProvider.js +10 -21
  80. package/providers/esri/src/utils/coords.js +37 -7
  81. package/providers/esri/src/utils/coords.test.js +22 -1
  82. package/providers/esri/src/utils/spatial.js +1 -47
  83. package/providers/maplibre/dist/esm/im-maplibre-provider.js +1 -1
  84. package/providers/maplibre/dist/umd/im-maplibre-provider.js +1 -1
  85. package/providers/maplibre/src/maplibreProvider.js +5 -14
  86. package/providers/maplibre/src/maplibreProvider.test.js +143 -146
  87. package/providers/maplibre/src/utils/spatial.js +0 -40
  88. package/providers/maplibre/src/utils/spatial.test.js +0 -35
  89. package/providers/openlayers/dist/esm/im-openlayers-provider.js +1 -1
  90. package/providers/openlayers/dist/umd/im-openlayers-provider.js +1 -1
  91. package/providers/openlayers/src/openlayersProvider.js +5 -14
  92. package/providers/openlayers/src/openlayersProvider.test.js +12 -10
  93. package/providers/openlayers/src/utils/spatial.js +0 -39
  94. package/providers/openlayers/src/utils/spatial.test.js +1 -26
  95. package/src/App/components/Hints/Hints.jsx +9 -21
  96. package/src/App/components/Hints/Hints.test.jsx +20 -33
  97. package/src/App/components/Panel/Panel.jsx +16 -1
  98. package/src/App/components/Panel/Panel.test.jsx +44 -0
  99. package/src/App/hooks/useCrossHairAPI.js +27 -28
  100. package/src/App/hooks/useCrossHairAPI.test.js +64 -7
  101. package/src/App/hooks/useLayoutMeasurements.js +175 -131
  102. package/src/App/hooks/useLayoutMeasurements.test.js +227 -122
  103. package/src/App/hooks/useMapProviderOverrides.js +114 -35
  104. package/src/App/hooks/useMapProviderOverrides.test.js +188 -5
  105. package/src/App/hooks/useModalPanelBehaviour.js +18 -32
  106. package/src/App/hooks/useModalPanelBehaviour.test.js +45 -33
  107. package/src/App/hooks/useVisibleGeometry.js +35 -45
  108. package/src/App/hooks/useVisibleGeometry.test.js +149 -121
  109. package/src/App/layout/Layout.jsx +4 -4
  110. package/src/App/layout/layout.module.scss +124 -61
  111. package/src/App/store/AppProvider.jsx +3 -0
  112. package/src/App/store/MapProvider.jsx +1 -0
  113. package/src/App/store/MapProvider.test.jsx +25 -0
  114. package/src/App/store/appDispatchMiddleware.js +18 -10
  115. package/src/App/store/appDispatchMiddleware.test.js +42 -4
  116. package/src/App/store/mapActionsMap.js +6 -0
  117. package/src/App/store/mapActionsMap.test.js +7 -0
  118. package/src/App/store/mapReducer.js +2 -0
  119. package/src/App/store/mapReducer.test.js +2 -0
  120. package/src/InteractiveMap/InteractiveMap.js +3 -2
  121. package/src/InteractiveMap/InteractiveMap.test.js +2 -2
  122. package/src/config/events.js +1 -1
  123. package/src/config/mapPanelSlots.js +8 -0
  124. package/src/config/symbolConfig.js +1 -1
  125. package/src/services/symbolRegistry.js +1 -1
  126. package/src/services/symbolRegistry.test.js +19 -0
  127. package/src/types.js +29 -8
  128. package/src/utils/getFitMove.js +73 -0
  129. package/src/utils/getFitMove.test.js +114 -0
  130. package/src/utils/getSafeZoneInset.js +122 -77
  131. package/src/utils/getSafeZoneInset.test.js +241 -54
  132. package/src/utils/getValueForStyle.js +10 -5
  133. package/src/utils/getValueForStyle.test.js +13 -2
  134. package/src/utils/renderedBoxes.js +25 -0
  135. package/src/utils/renderedBoxes.test.js +61 -0
  136. package/src/utils/screenBox.js +70 -0
  137. package/src/utils/screenBox.test.js +69 -0
  138. package/src/utils/symbolUtils.js +9 -9
  139. package/src/utils/symbolUtils.test.js +21 -0
  140. package/providers/esri/src/utils/spatial.test.js +0 -58
@@ -12,7 +12,7 @@ import { supportedShortcuts, DEFAULTS } from './defaults.js'
12
12
  import { getViewResolutionConfig, ZOOM_ALIGNMENT } from './utils/zoom.js'
13
13
  import { attachMapEvents } from './mapEvents.js'
14
14
  import { attachAppEvents, createMapStyleLayer } from './appEvents.js'
15
- import { getAreaDimensions, getCardinalMove, getExtentFromGeoJSON, getPaddedExtent, isGeometryObscured } from './utils/spatial.js'
15
+ import { getAreaDimensions, getCardinalMove, getExtentFromGeoJSON, getPaddedExtent } from './utils/spatial.js'
16
16
  import { updateHighlightedFeatures } from './utils/highlightFeatures.js'
17
17
  import { SymbolImageCache } from './utils/symbolImages.js'
18
18
  import { PatternImageCache } from './utils/patternImages.js'
@@ -228,10 +228,12 @@ export default class OpenLayersProvider extends MapProvider {
228
228
  * Fit map view to the specified bounds or GeoJSON geometry.
229
229
  *
230
230
  * @param {[number, number, number, number] | object} bounds - Bounds as [west, south, east, north] (BNG easting/northing), or a GeoJSON Feature, FeatureCollection, or geometry.
231
+ * @param {Object} [options]
232
+ * @param {{ top: number, right: number, bottom: number, left: number }} [options.padding] - Extra space in pixels kept around the bounds, inside the view's padding.
231
233
  */
232
- fitToBounds (bounds) {
234
+ fitToBounds (bounds, { padding } = {}) {
233
235
  const extent = Array.isArray(bounds) ? bounds : getExtentFromGeoJSON(bounds)
234
- this.view.fit(extent, { duration: DEFAULTS.animationDuration })
236
+ this.view.fit(extent, { duration: DEFAULTS.animationDuration, ...(padding && { padding: toPaddingArray(padding) }) })
235
237
  }
236
238
 
237
239
  /**
@@ -516,15 +518,4 @@ export default class OpenLayersProvider extends MapProvider {
516
518
  screenToMap (point) {
517
519
  return this.map.getCoordinateFromPixel([point.x, point.y])
518
520
  }
519
-
520
- /**
521
- * Returns true if the geometry's screen bounding box overlaps the given panel rectangle.
522
- *
523
- * @param {object} geojson - GeoJSON Feature, FeatureCollection, or geometry.
524
- * @param {DOMRect} panelRect - Bounding rect of the panel element (viewport coordinates).
525
- * @returns {boolean}
526
- */
527
- isGeometryObscured (geojson, panelRect) {
528
- return isGeometryObscured(geojson, panelRect, this.map)
529
- }
530
521
  }
@@ -5,7 +5,7 @@ import { SymbolImageCache } from './utils/symbolImages.js'
5
5
  import { PatternImageCache } from './utils/patternImages.js'
6
6
  import { attachMapEvents } from './mapEvents.js'
7
7
  import { attachAppEvents, createMapStyleLayer } from './appEvents.js'
8
- import { getExtentFromGeoJSON, isGeometryObscured } from './utils/spatial.js'
8
+ import { getExtentFromGeoJSON } from './utils/spatial.js'
9
9
  import View from 'ol/View.js'
10
10
 
11
11
  const mockAnimate = jest.fn()
@@ -70,8 +70,7 @@ jest.mock('./utils/spatial.js', () => ({
70
70
  getAreaDimensions: jest.fn(() => '1 mile by 2 miles'),
71
71
  getCardinalMove: jest.fn(() => 'north 100m'),
72
72
  getExtentFromGeoJSON: jest.fn(() => [10, 20, 30, 40]),
73
- getPaddedExtent: jest.fn(() => [0, 0, 800, 600]),
74
- isGeometryObscured: jest.fn(() => false)
73
+ getPaddedExtent: jest.fn(() => [0, 0, 800, 600])
75
74
  }))
76
75
 
77
76
  const events = {
@@ -330,6 +329,16 @@ describe('OpenLayersProvider', () => {
330
329
  expect(mockViewFit).toHaveBeenCalledWith([10, 20, 30, 40], expect.any(Object))
331
330
  })
332
331
 
332
+ it('fitToBounds passes extra padding to view.fit as an OL [top, right, bottom, left] array', () => {
333
+ provider.fitToBounds([1, 2, 3, 4], { padding: { top: 10, right: 20, bottom: 30, left: 40 } })
334
+ expect(mockViewFit).toHaveBeenCalledWith([1, 2, 3, 4], expect.objectContaining({ padding: [10, 20, 30, 40] }))
335
+ })
336
+
337
+ it('fitToBounds passes no padding to view.fit without the option', () => {
338
+ provider.fitToBounds([1, 2, 3, 4])
339
+ expect(mockViewFit.mock.calls.at(-1)[1]).not.toHaveProperty('padding')
340
+ })
341
+
333
342
  it('setPadding converts object to OL [top, right, bottom, left] array', () => {
334
343
  provider.setPadding({ top: 10, right: 20, bottom: 30, left: 40 })
335
344
  expect(mockViewInstance.padding).toEqual([10, 20, 30, 40])
@@ -418,13 +427,6 @@ describe('OpenLayersProvider', () => {
418
427
  expect(provider.screenToMap({ x: 100, y: 200 })).toEqual([400000, 300000])
419
428
  expect(mockMapGetCoord).toHaveBeenCalledWith([100, 200])
420
429
  })
421
-
422
- it('isGeometryObscured delegates to spatial utils with map instance', () => {
423
- const geojson = { type: 'Point', coordinates: [0, 51] }
424
- const panelRect = { left: 0, top: 0, right: 100, bottom: 100 }
425
- provider.isGeometryObscured(geojson, panelRect)
426
- expect(isGeometryObscured).toHaveBeenCalledWith(geojson, panelRect, mockMapInstance)
427
- })
428
430
  })
429
431
 
430
432
  describe('pattern images', () => {
@@ -91,49 +91,10 @@ const getPaddedExtent = (map) => {
91
91
  return [sw[0], sw[1], ne[0], ne[1]]
92
92
  }
93
93
 
94
- /**
95
- * Returns true if the geometry's screen bounding box overlaps the given panel rectangle.
96
- * getPixelFromCoordinate returns layout-space pixels (unscaled canvas), so we convert them
97
- * to screen space using the ratio between the viewport's visual size and the canvas size.
98
- * This accounts for the CSS scale transform applied on medium/large mapSize.
99
- */
100
- const isGeometryObscured = (geojson, panelRect, map) => {
101
- const containerRect = map.getTargetElement().getBoundingClientRect()
102
- if (!containerRect.width || !containerRect.height) {
103
- return false
104
- }
105
- const viewportRect = map.getViewport().getBoundingClientRect()
106
- const scaleX = viewportRect.width / containerRect.width
107
- const scaleY = viewportRect.height / containerRect.height
108
-
109
- const [xmin, ymin, xmax, ymax] = getExtentFromGeoJSON(geojson)
110
-
111
- const corners = [[xmin, ymin], [xmin, ymax], [xmax, ymin], [xmax, ymax]].map(coord => {
112
- return map.getPixelFromCoordinate(coord)
113
- }).filter(Boolean)
114
-
115
- if (!corners.length) {
116
- return false
117
- }
118
-
119
- const screenMinX = containerRect.left + Math.min(...corners.map(c => c[0])) * scaleX
120
- const screenMaxX = containerRect.left + Math.max(...corners.map(c => c[0])) * scaleX
121
- const screenMinY = containerRect.top + Math.min(...corners.map(c => c[1])) * scaleY
122
- const screenMaxY = containerRect.top + Math.max(...corners.map(c => c[1])) * scaleY
123
-
124
- return (
125
- screenMinX < panelRect.right &&
126
- screenMaxX > panelRect.left &&
127
- screenMinY < panelRect.bottom &&
128
- screenMaxY > panelRect.top
129
- )
130
- }
131
-
132
94
  export {
133
95
  getAreaDimensions,
134
96
  getCardinalMove,
135
97
  getExtentFromGeoJSON,
136
98
  getPaddedExtent,
137
- isGeometryObscured,
138
99
  formatDimension
139
100
  }
@@ -3,8 +3,7 @@ import {
3
3
  getAreaDimensions,
4
4
  getCardinalMove,
5
5
  getExtentFromGeoJSON,
6
- getPaddedExtent,
7
- isGeometryObscured
6
+ getPaddedExtent
8
7
  } from './spatial.js'
9
8
 
10
9
  describe('formatDimension', () => {
@@ -91,27 +90,3 @@ describe('getPaddedExtent', () => {
91
90
  expect(getPaddedExtent(map)).toBeNull()
92
91
  })
93
92
  })
94
-
95
- describe('isGeometryObscured', () => {
96
- const point = { type: 'Feature', geometry: { type: 'Point', coordinates: [-1, 51] } }
97
- const panel = { left: 0, top: 0, right: 100, bottom: 100 }
98
-
99
- const containerRect = { left: 0, top: 0, width: 1000, height: 1000 }
100
- const makeMap = (pixelFn, viewportRect = containerRect) => ({
101
- getTargetElement: () => ({ getBoundingClientRect: () => containerRect }),
102
- getViewport: () => ({ getBoundingClientRect: () => viewportRect }),
103
- getPixelFromCoordinate: pixelFn
104
- })
105
-
106
- it('returns false when no corners project to screen pixels', () => {
107
- expect(isGeometryObscured(point, panel, makeMap(() => null))).toBe(false)
108
- })
109
-
110
- it('returns true when geometry overlaps panel', () => {
111
- expect(isGeometryObscured(point, panel, makeMap(() => [50, 50]))).toBe(true)
112
- })
113
-
114
- it('returns false when geometry is outside panel', () => {
115
- expect(isGeometryObscured(point, panel, makeMap(() => [200, 200]))).toBe(false)
116
- })
117
- })
@@ -1,43 +1,32 @@
1
1
  import React, { useState, useEffect } from 'react'
2
- import { createPortal } from 'react-dom'
3
2
  import { useConfig } from '../../store/configContext.js'
4
3
  import { useService } from '../../store/serviceContext.js'
5
- import { useApp } from '../../store/appContext.js'
6
4
  import { htmlToPlainText } from '../../../utils/htmlToPlainText.js'
7
5
 
8
6
  /**
9
- * Renders the active keyboard hint as a toast portaled into im-o-app__main.
10
- * Positioned above the actions bar using --hint-bottom. All visual
11
- * hints pass through here; screen reader announcements are handled internally
12
- * by the hints service so callers only need hints.show().
7
+ * Renders the active keyboard hint as a toast. Layout puts it just before the bottom row, so it's
8
+ * read in the order it's shown, and useLayoutMeasurements keeps it clear of the bottom row and the
9
+ * actions bar (--hint-bottom). All visual hints pass through here; screen reader announcements are
10
+ * handled internally by the hints service so callers only need hints.show().
13
11
  *
14
- * The container element (id="${mapId}-hints") is always in the DOM after mount
15
- * so aria-describedby references remain valid even when no hint is showing.
12
+ * The container element (id="${mapId}-hints") is always in the DOM so aria-describedby references
13
+ * remain valid even when no hint is showing.
16
14
  */
17
15
  // eslint-disable-next-line camelcase, react/jsx-pascal-case
18
16
  // sonarjs/disable-next-line function-name
19
17
  export const Hints = () => {
20
18
  const { id, keyboardHintText, enableMapControls, mapControlsHintText } = useConfig()
21
19
  const { hints } = useService()
22
- const { layoutRefs } = useApp()
23
20
  const [activeHint, setActiveHint] = useState(null)
24
- const [mounted, setMounted] = useState(false)
25
21
 
26
- useEffect(() => {
27
- setMounted(true)
28
- return hints.subscribe(setActiveHint)
29
- }, [hints])
30
-
31
- if (!mounted || !layoutRefs.mainRef?.current) {
32
- return null
33
- }
22
+ useEffect(() => hints.subscribe(setActiveHint), [hints])
34
23
 
35
24
  // Composed at render time so overriding one text doesn't drop the other.
36
25
  const keyboardDescriptionHtml = enableMapControls
37
26
  ? `${keyboardHintText} ${mapControlsHintText}`
38
27
  : keyboardHintText
39
28
 
40
- return createPortal(
29
+ return (
41
30
  <div className='im-o-hints'>
42
31
  <div id={`${id}-hints`} className='im-c-hints'>
43
32
  {activeHint && (
@@ -52,7 +41,6 @@ export const Hints = () => {
52
41
  className='im-u-visually-hidden'
53
42
  dangerouslySetInnerHTML={{ __html: htmlToPlainText(keyboardDescriptionHtml) }}
54
43
  />
55
- </div>,
56
- layoutRefs.mainRef.current
44
+ </div>
57
45
  )
58
46
  }
@@ -3,11 +3,9 @@ import { render, act } from '@testing-library/react'
3
3
  import { Hints } from './Hints.jsx'
4
4
  import { useConfig } from '../../store/configContext.js'
5
5
  import { useService } from '../../store/serviceContext.js'
6
- import { useApp } from '../../store/appContext.js'
7
6
 
8
7
  jest.mock('../../store/configContext.js', () => ({ useConfig: jest.fn() }))
9
8
  jest.mock('../../store/serviceContext.js', () => ({ useService: jest.fn() }))
10
- jest.mock('../../store/appContext.js', () => ({ useApp: jest.fn() }))
11
9
 
12
10
  const CONTAINER_ID = '#test-map-hints'
13
11
  const HINT_CLASS = '.im-c-hints__hint'
@@ -15,7 +13,7 @@ const HINT_CLASS = '.im-c-hints__hint'
15
13
  let capturedSubscriber
16
14
  let mockHints
17
15
 
18
- const setup = ({ mainEl = document.createElement('div') } = {}) => {
16
+ const setup = () => {
19
17
  capturedSubscriber = null
20
18
  mockHints = {
21
19
  subscribe: jest.fn((fn) => {
@@ -25,67 +23,63 @@ const setup = ({ mainEl = document.createElement('div') } = {}) => {
25
23
  }
26
24
  useConfig.mockReturnValue({ id: 'test-map', keyboardHintText: '<kbd>Shift</kbd> + <kbd>?</kbd>' })
27
25
  useService.mockReturnValue({ hints: mockHints })
28
- useApp.mockReturnValue({ layoutRefs: { mainRef: { current: mainEl } } })
29
- if (mainEl) document.body.appendChild(mainEl)
30
- return mainEl
31
26
  }
32
27
 
33
28
  afterEach(() => {
34
- document.body.innerHTML = ''
35
29
  jest.clearAllMocks()
36
30
  })
37
31
 
38
32
  // ─── rendering ───────────────────────────────────────────────────────────────
39
33
 
40
34
  describe('Hints — rendering', () => {
41
- it('renders the container into mainRef after mount', () => {
42
- const mainEl = setup()
43
- render(<Hints />)
44
- expect(mainEl.querySelector(CONTAINER_ID)).toBeTruthy()
35
+ it('renders the container in place', () => {
36
+ setup()
37
+ const { container } = render(<Hints />)
38
+ expect(container.querySelector(CONTAINER_ID)).toBeTruthy()
45
39
  })
46
40
 
47
41
  it('renders a persistent keyboard-desc span with the hint text', () => {
48
- const mainEl = setup()
49
- render(<Hints />)
50
- const desc = mainEl.querySelector('#test-map-keyboard-desc')
42
+ setup()
43
+ const { container } = render(<Hints />)
44
+ const desc = container.querySelector('#test-map-keyboard-desc')
51
45
  expect(desc).toBeTruthy()
52
46
  expect(desc.innerHTML).toBe('Shift + ?')
53
47
  })
54
48
 
55
49
  it('appends the map-controls hint text when enableMapControls is true', () => {
56
- const mainEl = setup()
50
+ setup()
57
51
  useConfig.mockReturnValue({
58
52
  id: 'test-map',
59
53
  keyboardHintText: '<kbd>Shift</kbd> + <kbd>?</kbd>',
60
54
  enableMapControls: true,
61
55
  mapControlsHintText: '<kbd>Arrow keys</kbd> to move'
62
56
  })
63
- render(<Hints />)
64
- const desc = mainEl.querySelector('#test-map-keyboard-desc')
57
+ const { container } = render(<Hints />)
58
+ const desc = container.querySelector('#test-map-keyboard-desc')
65
59
  expect(desc.innerHTML).toBe('Shift + ? Arrow keys to move')
66
60
  })
67
61
 
68
62
  it('renders no hint content when there is no active hint', () => {
69
- const mainEl = setup()
70
- render(<Hints />)
71
- expect(mainEl.querySelector(HINT_CLASS)).toBeNull()
63
+ setup()
64
+ const { container } = render(<Hints />)
65
+ expect(container.querySelector(HINT_CLASS)).toBeNull()
72
66
  })
73
67
 
74
68
  it('renders hint content when subscriber fires with a hint', () => {
75
- const mainEl = setup()
76
- render(<Hints />)
69
+ setup()
70
+ const { container } = render(<Hints />)
77
71
  act(() => capturedSubscriber({ html: '<kbd>Enter</kbd> to select' }))
78
- const hint = mainEl.querySelector(HINT_CLASS)
72
+ const hint = container.querySelector(HINT_CLASS)
79
73
  expect(hint).toBeTruthy()
80
74
  expect(hint.innerHTML).toBe('<kbd>Enter</kbd> to select')
81
75
  })
82
76
 
83
77
  it('removes hint content when subscriber fires with null', () => {
84
- const mainEl = setup()
85
- render(<Hints />)
78
+ setup()
79
+ const { container } = render(<Hints />)
86
80
  act(() => capturedSubscriber({ html: 'hello' }))
87
81
  act(() => capturedSubscriber(null))
88
- expect(mainEl.querySelector(HINT_CLASS)).toBeNull()
82
+ expect(container.querySelector(HINT_CLASS)).toBeNull()
89
83
  })
90
84
  })
91
85
 
@@ -107,11 +101,4 @@ describe('Hints — lifecycle', () => {
107
101
  unmount()
108
102
  expect(unsub).toHaveBeenCalled()
109
103
  })
110
-
111
- it('renders nothing when mainRef is null', () => {
112
- setup({ mainEl: null })
113
- useApp.mockReturnValue({ layoutRefs: { mainRef: { current: null } } })
114
- const { container } = render(<Hints />)
115
- expect(container.innerHTML).toBe('')
116
- })
117
104
  })
@@ -17,6 +17,21 @@ const computePanelState = (bpConfig, triggeringElement, focus, focusOnOpen) => {
17
17
  return { isAside, isDialog, isModal, isDismissible, shouldFocus, buttonContainerEl }
18
18
  }
19
19
 
20
+ // Keyboard users get the browser's own scroll to the focused panel. Others are only scrolled when
21
+ // the top of the panel is off screen, and only as far as needed, so a click never moves a panel
22
+ // they can already see, but never opens one they can't
23
+ const focusOpenedPanel = (panel, interfaceType) => {
24
+ if (interfaceType === 'keyboard') {
25
+ panel.focus()
26
+ return
27
+ }
28
+ panel.focus({ preventScroll: true })
29
+ const { top } = panel.getBoundingClientRect()
30
+ if (top < 0 || top >= window.innerHeight) {
31
+ panel.scrollIntoView({ block: 'nearest' })
32
+ }
33
+ }
34
+
20
35
  const buildPanelClassNames = (slot, showLabel) => [
21
36
  'im-c-panel',
22
37
  `im-c-panel--${slot}`,
@@ -134,7 +149,7 @@ export const Panel = ({ panelId, panelConfig, props, focusOnOpen, WrappedChild,
134
149
  prevIsOpenRef.current = isOpen
135
150
 
136
151
  if (shouldFocus && (justOpened || isOpen)) {
137
- panelRef.current?.focus()
152
+ focusOpenedPanel(panelRef.current, interfaceType)
138
153
  }
139
154
  }, [isOpen])
140
155
 
@@ -153,6 +153,50 @@ describe('Panel', () => {
153
153
  expect(panel).not.toHaveAttribute('tabIndex')
154
154
  expect(document.activeElement).not.toBe(panel)
155
155
  })
156
+
157
+ describe('scrolling to an opened panel', () => {
158
+ let focusSpy, scrollSpy
159
+
160
+ beforeEach(() => {
161
+ focusSpy = jest.spyOn(HTMLElement.prototype, 'focus')
162
+ // jsdom has no scrollIntoView
163
+ HTMLElement.prototype.scrollIntoView = jest.fn()
164
+ scrollSpy = HTMLElement.prototype.scrollIntoView
165
+ })
166
+
167
+ afterEach(() => {
168
+ focusSpy.mockRestore()
169
+ delete HTMLElement.prototype.scrollIntoView
170
+ })
171
+
172
+ const openPanel = (interfaceType, top) => {
173
+ useApp.mockReturnValue({ dispatch, breakpoint: 'desktop', layoutRefs, interfaceType })
174
+ jest.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue({ top })
175
+ renderPanel({ focus: true })
176
+ HTMLElement.prototype.getBoundingClientRect.mockRestore()
177
+ }
178
+
179
+ it('leaves the browser to scroll to the panel for keyboard users', () => {
180
+ openPanel('keyboard', 2000)
181
+ expect(focusSpy).toHaveBeenCalledWith()
182
+ expect(scrollSpy).not.toHaveBeenCalled()
183
+ })
184
+
185
+ it.each(['mouse', 'touch'])('doesn\'t scroll for %s users when the top of the panel is on screen', (interfaceType) => {
186
+ openPanel(interfaceType, 100)
187
+ expect(focusSpy).toHaveBeenCalledWith({ preventScroll: true })
188
+ expect(scrollSpy).not.toHaveBeenCalled()
189
+ })
190
+
191
+ it.each([
192
+ ['below the screen', 2000],
193
+ ['above the screen', -50]
194
+ ])('scrolls only as far as needed for mouse users when the top of the panel is %s', (_name, top) => {
195
+ openPanel('mouse', top)
196
+ expect(focusSpy).toHaveBeenCalledWith({ preventScroll: true })
197
+ expect(scrollSpy).toHaveBeenCalledWith({ block: 'nearest' })
198
+ })
199
+ })
156
200
  })
157
201
 
158
202
  describe('close functionality', () => {
@@ -1,4 +1,4 @@
1
- import { useCallback, useEffect } from 'react'
1
+ import { useCallback, useEffect, useRef } from 'react'
2
2
  import { useConfig } from '../store/configContext.js'
3
3
  import { useApp } from '../store/appContext.js'
4
4
  import { useMap } from '../store/mapContext.js'
@@ -6,15 +6,19 @@ import { useService } from '../store/serviceContext.js'
6
6
  import { scaleFactor } from '../../config/appConfig.js'
7
7
  import { EVENTS as events } from '../../config/events.js'
8
8
 
9
- const assignCrossHairAPI = (crossHair, el, mapProvider, dispatch, updatePosition) => {
9
+ // crossHairHideHeldByMapControls is shared by every copy of the crossHair object, because each
10
+ // UPDATE_CROSS_HAIR replaces the object and a plugin can still call an older copy
11
+ const assignCrossHairAPI = (crossHair, el, mapProvider, dispatch, updatePosition, crossHairHideHeldByMapControls) => {
10
12
  crossHair.pinToMap = (coords, state) => {
11
13
  const { x, y } = mapProvider.mapToScreen(coords)
14
+ crossHairHideHeldByMapControls.isHideWaiting = false
12
15
  crossHair.coords = coords
13
16
  dispatch({ type: 'UPDATE_CROSS_HAIR', payload: { isPinnedToMap: true, isVisible: true, coords, state } })
14
17
  updatePosition(el, x, y)
15
18
  }
16
19
 
17
20
  crossHair.fixAtCenter = () => {
21
+ crossHairHideHeldByMapControls.isHideWaiting = false
18
22
  el.style.left = '50%'
19
23
  el.style.top = '50%'
20
24
  el.style.transform = 'translate(0,0)'
@@ -28,23 +32,21 @@ const assignCrossHairAPI = (crossHair, el, mapProvider, dispatch, updatePosition
28
32
  }
29
33
 
30
34
  crossHair.show = () => {
35
+ crossHairHideHeldByMapControls.isHideWaiting = false
31
36
  el.style.display = 'block'
32
37
  dispatch({ type: 'UPDATE_CROSS_HAIR', payload: { isVisible: true } })
33
38
  }
34
39
 
35
- // Fully hidden — display:none, not just faded — rather than staying in the accessibility
36
- // tree while invisible. An earlier version kept it ax-tree-present here so Voice Control
37
- // could re-summon it by name, but that made "Show Names" put a "Target" label over
38
- // nothing whenever it was genuinely hidden, which is more confusing than helpful. Voice
39
- // Control's real route back is opening MapControls (a normal, always-visible, always-named
40
- // button) — see isMapControlsOpen below — so the crosshair itself doesn't need to stay
41
- // discoverable while it's not actually there. Blocked outright while MapControls is open:
42
- // that panel is a deliberate, explicit "I can't drag/pinch this map" signal from the user,
43
- // which should win over whatever mouse-vs-touch/keyboard inference would otherwise decide.
40
+ // Hides the crosshair completely, so screen readers and Voice Control don't find a "Target"
41
+ // that isn't there. While the map controls are open the crosshair stays visible, because the
42
+ // user has asked for it. A hide asked for then is held back until the controls close, unless
43
+ // something shows the crosshair again first.
44
44
  crossHair.hide = () => {
45
- if (crossHair.isMapControlsOpen) {
45
+ if (crossHairHideHeldByMapControls.isMapControlsOpen) {
46
+ crossHairHideHeldByMapControls.isHideWaiting = true
46
47
  return
47
48
  }
49
+ crossHairHideHeldByMapControls.isHideWaiting = false
48
50
  el.style.display = 'none'
49
51
  dispatch({ type: 'UPDATE_CROSS_HAIR', payload: { isVisible: false } })
50
52
  }
@@ -70,6 +72,7 @@ export const useCrossHair = () => {
70
72
  const { safeZoneInset, expandedButtons } = useApp()
71
73
  const { eventBus } = useService()
72
74
  const { crossHair, dispatch, mapSize } = useMap()
75
+ const crossHairHideHeldByMapControlsRef = useRef({ isMapControlsOpen: false, isHideWaiting: false })
73
76
 
74
77
  const updatePosition = (el, x, y) => {
75
78
  if (!safeZoneInset) {
@@ -87,7 +90,7 @@ export const useCrossHair = () => {
87
90
  return undefined
88
91
  }
89
92
 
90
- assignCrossHairAPI(crossHair, el, mapProvider, dispatch, updatePosition)
93
+ assignCrossHairAPI(crossHair, el, mapProvider, dispatch, updatePosition, crossHairHideHeldByMapControlsRef.current)
91
94
 
92
95
  const handleRender = () => {
93
96
  if (crossHair.coords && crossHair.isPinnedToMap) {
@@ -110,21 +113,17 @@ export const useCrossHair = () => {
110
113
  }
111
114
  }, [mapSize])
112
115
 
113
- // A plain property on the shared crossHair object, not dispatched state — every owner
114
- // (draw's per-adapter modes, interact's useCrossHairVisibility) already holds this same
115
- // object, so mutating it here is all that's needed for hide()'s own guard above to see the
116
- // current value live, however long ago it was last set. This alone never shows or hides
117
- // anything by itself — it only ever blocks a hide() call already in flight — so it's safe to
118
- // run unconditionally even when no plugin that cares about it is loaded at all.
119
- //
120
- // Deliberately NOT a useEffect: this component's own effects and interact's/draw's own
121
- // updateCrossHair effects both react to the same expandedButtons change, and React gives no
122
- // ordering guarantee between two different components' effects — if the consumer's effect
123
- // (which decides to call hide()) ran before this one updated the flag, hide()'s guard would
124
- // read the stale value and incorrectly block itself. Setting it directly in the render body
125
- // (matches DrawInit.jsx's shouldShowCrosshairRef convention) guarantees it's current before
126
- // ANY component's effects run, since React finishes rendering the whole tree first.
127
- crossHair.isMapControlsOpen = expandedButtons?.has('mapControls')
116
+ // Tells hide() whether the map controls are open. It's set while rendering so it's up to date
117
+ // as soon as possible, but a plugin can still call hide() before this component re-renders. So
118
+ // when the controls close, carry out any hide that was held back.
119
+ const isMapControlsOpen = !!expandedButtons?.has('mapControls')
120
+ crossHairHideHeldByMapControlsRef.current.isMapControlsOpen = isMapControlsOpen
121
+
122
+ useEffect(() => {
123
+ if (!isMapControlsOpen && crossHairHideHeldByMapControlsRef.current.isHideWaiting) {
124
+ crossHair.hide()
125
+ }
126
+ }, [isMapControlsOpen])
128
127
 
129
128
  return {
130
129
  crossHair,
@@ -98,20 +98,77 @@ describe('useCrossHair', () => {
98
98
  expect(mockElement.style.display).toBe('none')
99
99
  })
100
100
 
101
- it('hide() is a no-op while isMapControlsOpen is set', () => {
101
+ const withMapControls = (isOpen) => useApp.mockReturnValue({
102
+ safeZoneInset: { left: 10, top: 20 },
103
+ expandedButtons: new Set(isOpen ? ['mapControls'] : [])
104
+ })
105
+
106
+ it('holds back hide() while the map controls are open', () => {
107
+ withMapControls(true)
102
108
  setup()
103
109
  act(() => mockCrossHair.show())
104
- mockCrossHair.isMapControlsOpen = true
105
-
106
110
  act(() => mockCrossHair.hide())
107
111
  expect(mockElement.style.display).toBe('block')
108
112
  expect(mockDispatch).not.toHaveBeenCalledWith({ type: 'UPDATE_CROSS_HAIR', payload: { isVisible: false } })
109
113
  })
110
114
 
111
- it('keeps crossHair.isMapControlsOpen synced with expandedButtons, set synchronously during render (not a useEffect) so it is never stale relative to another component\'s own effect reacting to the same change', () => {
112
- useApp.mockReturnValue({ safeZoneInset: { left: 10, top: 20 }, expandedButtons: new Set(['mapControls']) })
113
- setup()
114
- expect(mockCrossHair.isMapControlsOpen).toBe(true)
115
+ // UPDATE_CROSS_HAIR replaces the crossHair object, and a plugin can still call an older copy
116
+ // (draw's effect cleanup does)
117
+ const replaceCrossHair = (hook) => {
118
+ const olderCopy = mockCrossHair
119
+ mockCrossHair = { ...mockCrossHair }
120
+ useMap.mockReturnValue({ crossHair: mockCrossHair, dispatch: mockDispatch, mapSize: 'medium' })
121
+ hook.rerender()
122
+ act(() => hook.result.current.crossHairRef(mockElement))
123
+ return olderCopy
124
+ }
125
+
126
+ it('hides when an older copy calls hide() after the map controls close', () => {
127
+ withMapControls(true)
128
+ const hook = setup()
129
+ act(() => mockCrossHair.show())
130
+ const olderCopy = replaceCrossHair(hook)
131
+ withMapControls(false)
132
+ hook.rerender()
133
+ act(() => olderCopy.hide())
134
+ expect(mockElement.style.display).toBe('none')
135
+ })
136
+
137
+ it('carries out a hide() held back on an older copy once the map controls close', () => {
138
+ withMapControls(true)
139
+ const hook = setup()
140
+ act(() => mockCrossHair.show())
141
+ const olderCopy = replaceCrossHair(hook)
142
+ act(() => olderCopy.hide())
143
+ expect(mockElement.style.display).toBe('block')
144
+ withMapControls(false)
145
+ hook.rerender()
146
+ expect(mockElement.style.display).toBe('none')
147
+ })
148
+
149
+ // A plugin's updateCrossHair effect can run before this hook re-renders, so its hide() is
150
+ // held back as the map controls close.
151
+ const closeMapControlsAfterBlockedHide = ({ showInBetween } = {}) => {
152
+ withMapControls(true)
153
+ const hook = setup()
154
+ act(() => mockCrossHair.show())
155
+ act(() => mockCrossHair.hide())
156
+ if (showInBetween) {
157
+ act(() => mockCrossHair.fixAtCenter())
158
+ }
159
+ withMapControls(false)
160
+ hook.rerender()
161
+ }
162
+
163
+ it('carries out a hide() blocked by MapControls once it closes', () => {
164
+ closeMapControlsAfterBlockedHide()
165
+ expect(mockElement.style.display).toBe('none')
166
+ expect(mockDispatch).toHaveBeenLastCalledWith({ type: 'UPDATE_CROSS_HAIR', payload: { isVisible: false } })
167
+ })
168
+
169
+ it('drops a blocked hide() when the crosshair is shown again before MapControls closes', () => {
170
+ closeMapControlsAfterBlockedHide({ showInBetween: true })
171
+ expect(mockElement.style.display).toBe('block')
115
172
  })
116
173
 
117
174
  it('setStyle updates state', () => {