@defra/interactive-map 0.0.59-alpha → 0.0.61-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 (125) 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/button-definition.md +11 -0
  9. package/docs/api/context.md +2 -0
  10. package/docs/api/panel-definition.md +30 -0
  11. package/docs/api/symbol-config.md +12 -0
  12. package/docs/api.md +21 -2
  13. package/docs/assets/images/slot-map.svg +3 -3
  14. package/docs/plugins/datasets.md +11 -1
  15. package/docs/plugins/draw.md +26 -0
  16. package/package.json +1 -1
  17. package/plugins/datasets/dist/esm/index.js +1 -1
  18. package/plugins/datasets/dist/esm/layerAdapter.js +1 -1
  19. package/plugins/datasets/dist/umd/im-datasets-ml-adapter.js +1 -1
  20. package/plugins/datasets/dist/umd/im-datasets-ol-adapter.js +1 -1
  21. package/plugins/datasets/dist/umd/im-datasets-plugin.js +1 -1
  22. package/plugins/datasets/dist/umd/index.js +1 -1
  23. package/plugins/datasets/src/index.js +0 -1
  24. package/plugins/datasets/src/index.test.js +2 -8
  25. package/plugins/datasets/src/registry/dataset.test.js +9 -0
  26. package/plugins/draw/dist/esm/im-draw-ml-adapter.js +1 -1
  27. package/plugins/draw/dist/esm/im-draw-ol-adapter.js +1 -1
  28. package/plugins/draw/dist/esm/im-draw-plugin.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/DrawInit.jsx +3 -0
  34. package/plugins/draw/src/DrawInit.test.jsx +16 -0
  35. package/plugins/draw/src/adapters/maplibre/MaplibreDrawAdapter.js +19 -3
  36. package/plugins/draw/src/adapters/maplibre/MaplibreDrawAdapter.test.js +27 -0
  37. package/plugins/draw/src/adapters/openlayers/OLDrawAdapter.js +10 -2
  38. package/plugins/draw/src/adapters/openlayers/OLDrawAdapter.test.js +14 -0
  39. package/plugins/draw/src/defaults.js +4 -0
  40. package/plugins/draw/src/hooks/useSnapMinZoom.js +29 -0
  41. package/plugins/draw/src/hooks/useSnapMinZoom.test.js +82 -0
  42. package/plugins/draw/src/manifest.js +4 -1
  43. package/plugins/draw/src/manifest.test.js +15 -2
  44. package/plugins/draw/src/utils/snapMinZoom.js +8 -0
  45. package/plugins/draw/src/utils/snapMinZoom.test.js +22 -0
  46. package/plugins/interact/dist/esm/im-interact-plugin.js +1 -1
  47. package/plugins/interact/dist/umd/im-interact-plugin.js +1 -1
  48. package/plugins/map-key/dist/esm/im-map-key-plugin.js +1 -1
  49. package/plugins/map-key/dist/umd/im-map-key-plugin.js +1 -1
  50. package/plugins/map-key/src/manifest.js +1 -1
  51. package/plugins/search/dist/css/index.css +1 -1
  52. package/plugins/search/src/components/Form/Form.module.scss +1 -0
  53. package/providers/esri/dist/esm/im-esri-provider.js +1 -1
  54. package/providers/esri/src/esriProvider.js +10 -21
  55. package/providers/esri/src/utils/coords.js +37 -7
  56. package/providers/esri/src/utils/coords.test.js +22 -1
  57. package/providers/esri/src/utils/spatial.js +1 -47
  58. package/providers/maplibre/dist/esm/im-maplibre-provider.js +1 -1
  59. package/providers/maplibre/dist/umd/im-maplibre-provider.js +1 -1
  60. package/providers/maplibre/src/maplibreProvider.js +5 -14
  61. package/providers/maplibre/src/maplibreProvider.test.js +143 -146
  62. package/providers/maplibre/src/utils/spatial.js +0 -40
  63. package/providers/maplibre/src/utils/spatial.test.js +0 -35
  64. package/providers/openlayers/dist/esm/im-openlayers-provider.js +1 -1
  65. package/providers/openlayers/dist/umd/im-openlayers-provider.js +1 -1
  66. package/providers/openlayers/src/openlayersProvider.js +5 -14
  67. package/providers/openlayers/src/openlayersProvider.test.js +12 -10
  68. package/providers/openlayers/src/utils/spatial.js +0 -39
  69. package/providers/openlayers/src/utils/spatial.test.js +1 -26
  70. package/src/App/components/Hints/Hints.jsx +9 -21
  71. package/src/App/components/Hints/Hints.test.jsx +20 -33
  72. package/src/App/components/MapButton/MapButton.jsx +20 -2
  73. package/src/App/components/MapButton/MapButton.module.scss +15 -1
  74. package/src/App/components/MapButton/MapButton.test.jsx +21 -3
  75. package/src/App/components/Panel/Panel.jsx +16 -1
  76. package/src/App/components/Panel/Panel.test.jsx +44 -0
  77. package/src/App/components/Tooltip/Tooltip.jsx +29 -11
  78. package/src/App/components/Tooltip/Tooltip.test.jsx +45 -3
  79. package/src/App/components/Viewport/MapController.jsx +2 -0
  80. package/src/App/components/Viewport/MapController.test.jsx +3 -0
  81. package/src/App/hooks/useCrossHairAPI.js +27 -28
  82. package/src/App/hooks/useCrossHairAPI.test.js +64 -7
  83. package/src/App/hooks/useLayoutMeasurements.js +175 -131
  84. package/src/App/hooks/useLayoutMeasurements.test.js +227 -122
  85. package/src/App/hooks/useMapProviderOverrides.js +114 -35
  86. package/src/App/hooks/useMapProviderOverrides.test.js +188 -5
  87. package/src/App/hooks/useModalPanelBehaviour.js +18 -32
  88. package/src/App/hooks/useModalPanelBehaviour.test.js +45 -33
  89. package/src/App/hooks/useUserMoveTracking.js +65 -0
  90. package/src/App/hooks/useUserMoveTracking.test.js +99 -0
  91. package/src/App/hooks/useVisibleGeometry.js +35 -45
  92. package/src/App/hooks/useVisibleGeometry.test.js +149 -121
  93. package/src/App/layout/Layout.jsx +4 -4
  94. package/src/App/layout/layout.module.scss +124 -61
  95. package/src/App/renderer/mapButtons.js +1 -0
  96. package/src/App/renderer/mapButtons.test.js +8 -0
  97. package/src/App/store/AppProvider.jsx +3 -0
  98. package/src/App/store/appDispatchMiddleware.js +18 -10
  99. package/src/App/store/appDispatchMiddleware.test.js +42 -4
  100. package/src/App/store/mapActionsMap.js +2 -1
  101. package/src/App/store/mapActionsMap.test.js +6 -0
  102. package/src/App/store/mapReducer.js +2 -0
  103. package/src/App/store/mapReducer.test.js +1 -0
  104. package/src/InteractiveMap/InteractiveMap.js +3 -2
  105. package/src/InteractiveMap/InteractiveMap.test.js +2 -2
  106. package/src/config/events.js +1 -1
  107. package/src/config/mapPanelSlots.js +8 -0
  108. package/src/config/symbolConfig.js +1 -1
  109. package/src/scss/settings/_colors.scss +4 -0
  110. package/src/services/symbolRegistry.js +1 -1
  111. package/src/services/symbolRegistry.test.js +19 -0
  112. package/src/types.js +33 -8
  113. package/src/utils/getFitMove.js +73 -0
  114. package/src/utils/getFitMove.test.js +114 -0
  115. package/src/utils/getSafeZoneInset.js +122 -77
  116. package/src/utils/getSafeZoneInset.test.js +241 -54
  117. package/src/utils/getValueForStyle.js +10 -5
  118. package/src/utils/getValueForStyle.test.js +13 -2
  119. package/src/utils/renderedBoxes.js +25 -0
  120. package/src/utils/renderedBoxes.test.js +61 -0
  121. package/src/utils/screenBox.js +70 -0
  122. package/src/utils/screenBox.test.js +69 -0
  123. package/src/utils/symbolUtils.js +9 -9
  124. package/src/utils/symbolUtils.test.js +21 -0
  125. 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
  })
@@ -114,6 +114,21 @@ const getControlledElement = ({ idPrefix, panelId, buttonId, hasMenu, panelRole
114
114
  return null
115
115
  }
116
116
 
117
+ /**
118
+ * The button's tooltip: its label when the label isn't shown, and its description when it has one.
119
+ * @param {Object} options - Configuration options
120
+ * @param {string} options.label - The button's label
121
+ * @param {string} [options.description] - The button's description
122
+ * @param {boolean} [options.showLabel] - Whether the label is shown
123
+ * @returns {{ label?: string, description?: string }|null} The tooltip, or null when it would be empty
124
+ */
125
+ const getTooltip = ({ label, description, showLabel }) => {
126
+ if (showLabel && !description) {
127
+ return null
128
+ }
129
+ return { label: showLabel ? undefined : label, description }
130
+ }
131
+
117
132
  /**
118
133
  * Builds the complete props object for a button or anchor element.
119
134
  * Handles ARIA attributes, event handlers, refs, and conditional styling.
@@ -211,6 +226,7 @@ const buildButtonProps = ({
211
226
  * @param {string} [props.href] - URL for anchor element; if provided, renders as <a> instead of <button>
212
227
  * @param {string} [props.ariaControls] - Explicit aria-controls target id for buttons that toggle
213
228
  * inline UI which is neither a panel nor a popup (a panelId/menuItems always takes precedence).
229
+ * @param {string} [props.description] - Extra information shown as the tooltip and read by screen readers after the label
214
230
  * @returns {JSX.Element} The rendered button component
215
231
  */
216
232
  export const MapButton = ({
@@ -232,7 +248,8 @@ export const MapButton = ({
232
248
  menuItems,
233
249
  idPrefix,
234
250
  href,
235
- ariaControls
251
+ ariaControls,
252
+ description
236
253
  }) => {
237
254
  const { id: appId } = useConfig()
238
255
  const { buttonRefs } = useApp()
@@ -254,6 +271,7 @@ export const MapButton = ({
254
271
  const showIcon = iconId || iconSvgContent || hasMenu
255
272
  const buttonSlot = getButtonSlot(panelId, buttonId)
256
273
  const controlledElement = getControlledElement({ idPrefix, panelId, buttonId, hasMenu, panelRole })
274
+ const tooltip = getTooltip({ label, description, showLabel })
257
275
 
258
276
  /**
259
277
  * Handles button click events.
@@ -314,7 +332,7 @@ export const MapButton = ({
314
332
  data-button-slot={buttonSlot}
315
333
  hidden={isHidden}
316
334
  >
317
- {showLabel ? buttonEl : <Tooltip content={label}>{buttonEl}</Tooltip>}
335
+ {tooltip ? <Tooltip label={tooltip.label} description={tooltip.description}>{buttonEl}</Tooltip> : buttonEl}
318
336
  {buttonSlot && <SlotRenderer slot={buttonSlot} />}
319
337
  {/* Mounted permanently, not just while open, so its aria-controls id stays a stable node. */}
320
338
  {controlledElement?.type === 'popup' && (
@@ -184,7 +184,7 @@
184
184
  transform: rotate(180deg);
185
185
  }
186
186
 
187
- .im-c-map-button[aria-disabled="true"]:not(.im-c-map-button--primary):not(.im-c-map-button--tertiary) {
187
+ .im-c-map-button[aria-disabled="true"]:not(.im-c-map-button--primary):not(.im-c-map-button--tertiary):not([aria-pressed="true"]) {
188
188
  svg, span {
189
189
  opacity: var(--disabled-button-opacity);
190
190
  }
@@ -197,6 +197,20 @@
197
197
  background-color: var(--pressed-button-background-color);
198
198
  }
199
199
 
200
+ // Pressed and disabled fades the fill rather than the icon and label, which would leave dim
201
+ // content on a full-strength pressed fill. Doubled class to outrank the slot-specific pressed
202
+ // rules and hover.
203
+ .im-c-map-button.im-c-map-button[aria-pressed="true"][aria-disabled="true"] {
204
+ color: var(--disabled-pressed-button-foreground-color);
205
+ border-color: var(--disabled-pressed-button-background-color);
206
+ background-color: var(--disabled-pressed-button-background-color);
207
+
208
+ @media (-ms-high-contrast:active), screen and (forced-colors: active) {
209
+ color: GrayText;
210
+ border-color: GrayText;
211
+ }
212
+ }
213
+
200
214
  // 5. Responsive tweaks
201
215
 
202
216
  .im-o-app--tablet, .im-o-app--desktop {
@@ -7,8 +7,8 @@ jest.mock('../../../utils/stringToKebab', () => ({
7
7
  }))
8
8
 
9
9
  jest.mock('../Tooltip/Tooltip', () => ({
10
- Tooltip: ({ content, children }) => (
11
- <div data-testid='tooltip' data-content={content}>{children}</div>
10
+ Tooltip: ({ label, description, children }) => (
11
+ <div data-testid='tooltip' data-label={label} data-description={description}>{children}</div>
12
12
  )
13
13
  }))
14
14
 
@@ -68,7 +68,13 @@ describe('MapButton', () => {
68
68
 
69
69
  it('wraps in Tooltip when showLabel is false', () => {
70
70
  renderButton({ showLabel: false })
71
- expect(screen.getByTestId('tooltip')).toHaveAttribute('data-content', 'Label')
71
+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-label', 'Label')
72
+ expect(screen.getByTestId('tooltip')).not.toHaveAttribute('data-description')
73
+ })
74
+
75
+ it('has no Tooltip when the label is shown and there\'s no description', () => {
76
+ renderButton({ showLabel: true })
77
+ expect(screen.queryByTestId('tooltip')).toBeNull()
72
78
  })
73
79
 
74
80
  it('hides wrapper when isHidden', () => {
@@ -309,4 +315,16 @@ describe('MapButton', () => {
309
315
  expect(screen.queryByRole('img', { hidden: true })).toBeNull()
310
316
  expect(screen.queryByTestId('icon')).toBeNull()
311
317
  })
318
+
319
+ it('shows the label and description as the tooltip when the label isn\'t shown', () => {
320
+ renderButton({ showLabel: false, description: 'Zoom in to use snap' })
321
+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-label', 'Label')
322
+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-description', 'Zoom in to use snap')
323
+ })
324
+
325
+ it('shows only the description as the tooltip when the label is shown', () => {
326
+ renderButton({ showLabel: true, description: 'Zoom in to use snap' })
327
+ expect(screen.getByTestId('tooltip')).not.toHaveAttribute('data-label')
328
+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-description', 'Zoom in to use snap')
329
+ })
312
330
  })
@@ -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', () => {
@@ -6,9 +6,19 @@ let tooltipIdCounter = 0
6
6
  const showDelay = 500
7
7
  const hideDelay = 0
8
8
 
9
+ // The label names the trigger (aria-labelledby) and the description describes it (aria-describedby).
10
+ // With both, they're shown together, each in its own element so neither is read twice.
11
+ const TooltipText = ({ tooltipId, label, description }) => (
12
+ <>
13
+ {label && <span id={`${tooltipId}-label`}>{label}</span>}
14
+ {label && description && ': '}
15
+ {description && <span id={`${tooltipId}-description`}>{description}</span>}
16
+ </>
17
+ )
18
+
9
19
  // eslint-disable-next-line camelcase, react/jsx-pascal-case
10
20
  // sonarjs/disable-next-line function-name
11
- export const Tooltip = ({ children, content }) => {
21
+ export const Tooltip = ({ children, label, description }) => {
12
22
  const { interfaceType } = useApp()
13
23
  const triggerRef = useRef(null)
14
24
  const tooltipRef = useRef(null)
@@ -76,23 +86,31 @@ export const Tooltip = ({ children, content }) => {
76
86
  }
77
87
  }
78
88
 
89
+ // Runs the trigger's own handler after the tooltip's, so the trigger keeps its own behaviour
90
+ // (such as a menu button's keyboard handling)
91
+ const withChildHandler = (name, handler) => (event) => {
92
+ handler()
93
+ children.props?.[name]?.(event)
94
+ }
95
+
79
96
  const childWithProps = cloneElement(children, {
80
97
  ref: mergeRefs,
81
- onMouseEnter: show,
82
- onMouseLeave: hide,
83
- onMouseDown: cancel,
84
- onKeyDown: cancel,
85
- onFocus: () => {
98
+ onMouseEnter: withChildHandler('onMouseEnter', show),
99
+ onMouseLeave: withChildHandler('onMouseLeave', hide),
100
+ onMouseDown: withChildHandler('onMouseDown', cancel),
101
+ onKeyDown: withChildHandler('onKeyDown', cancel),
102
+ onFocus: withChildHandler('onFocus', () => {
86
103
  if (interfaceType === 'keyboard') {
87
104
  show()
88
105
  }
89
106
  setFocused(true)
90
- },
91
- onBlur: () => {
107
+ }),
108
+ onBlur: withChildHandler('onBlur', () => {
92
109
  hide()
93
110
  setFocused(false)
94
- },
95
- 'aria-labelledby': tooltipId
111
+ }),
112
+ 'aria-labelledby': label ? `${tooltipId}-label` : undefined,
113
+ 'aria-describedby': description ? `${tooltipId}-description` : undefined
96
114
  })
97
115
 
98
116
  return (
@@ -105,7 +123,7 @@ export const Tooltip = ({ children, content }) => {
105
123
  role='tooltip'
106
124
  aria-hidden={!visible}
107
125
  >
108
- {content}
126
+ <TooltipText tooltipId={tooltipId} label={label} description={description} />
109
127
  </div>
110
128
  </div>
111
129
  )