@accelint/map-toolkit 0.1.0 → 0.3.0

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 (77) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/README.md +91 -18
  3. package/catalog-info.yaml +16 -10
  4. package/dist/cursor-coordinates/index.d.ts +3 -0
  5. package/dist/cursor-coordinates/index.js +3 -0
  6. package/dist/cursor-coordinates/index.js.map +1 -0
  7. package/dist/cursor-coordinates/use-cursor-coordinates.d.ts +76 -0
  8. package/dist/cursor-coordinates/use-cursor-coordinates.js +161 -0
  9. package/dist/cursor-coordinates/use-cursor-coordinates.js.map +1 -0
  10. package/dist/deckgl/base-map/events.d.ts +1 -0
  11. package/dist/deckgl/base-map/events.js +2 -1
  12. package/dist/deckgl/base-map/events.js.map +1 -1
  13. package/dist/deckgl/base-map/index.d.ts +91 -8
  14. package/dist/deckgl/base-map/index.js +93 -33
  15. package/dist/deckgl/base-map/index.js.map +1 -1
  16. package/dist/deckgl/base-map/provider.d.ts +129 -0
  17. package/dist/deckgl/base-map/provider.js +18 -0
  18. package/dist/deckgl/base-map/provider.js.map +1 -0
  19. package/dist/deckgl/base-map/types.d.ts +64 -3
  20. package/dist/deckgl/index.d.ts +3 -2
  21. package/dist/deckgl/index.js +1 -1
  22. package/dist/deckgl/text-layer/character-sets.d.ts +27 -0
  23. package/dist/deckgl/text-layer/character-sets.js +36 -0
  24. package/dist/deckgl/text-layer/character-sets.js.map +1 -0
  25. package/dist/deckgl/text-layer/default-settings.d.ts +5 -0
  26. package/dist/deckgl/text-layer/default-settings.js +23 -0
  27. package/dist/deckgl/text-layer/default-settings.js.map +1 -0
  28. package/dist/deckgl/text-layer/fiber.d.ts +31 -0
  29. package/dist/deckgl/text-layer/fiber.js +6 -0
  30. package/dist/deckgl/text-layer/fiber.js.map +1 -0
  31. package/dist/deckgl/text-layer/index.d.ts +43 -0
  32. package/dist/deckgl/text-layer/index.js +33 -0
  33. package/dist/deckgl/text-layer/index.js.map +1 -0
  34. package/dist/decorators/deckgl.d.ts +1 -1
  35. package/dist/decorators/deckgl.js +3 -1
  36. package/dist/decorators/deckgl.js.map +1 -1
  37. package/dist/map-mode/events.d.ts +37 -0
  38. package/dist/map-mode/events.js +15 -0
  39. package/dist/map-mode/events.js.map +1 -0
  40. package/dist/map-mode/index.d.ts +6 -0
  41. package/dist/map-mode/index.js +5 -0
  42. package/dist/map-mode/index.js.map +1 -0
  43. package/dist/map-mode/store.d.ts +48 -0
  44. package/dist/map-mode/store.js +306 -0
  45. package/dist/map-mode/store.js.map +1 -0
  46. package/dist/map-mode/types.d.ts +83 -0
  47. package/dist/map-mode/types.js +3 -0
  48. package/dist/map-mode/types.js.map +1 -0
  49. package/dist/map-mode/use-map-mode.d.ts +52 -0
  50. package/dist/map-mode/use-map-mode.js +29 -0
  51. package/dist/map-mode/use-map-mode.js.map +1 -0
  52. package/dist/maplibre/hooks/use-maplibre.d.ts +34 -0
  53. package/dist/maplibre/hooks/use-maplibre.js +3 -2
  54. package/dist/maplibre/hooks/use-maplibre.js.map +1 -1
  55. package/dist/metafile-esm.json +1 -1
  56. package/dist/viewport/constants.d.ts +9 -0
  57. package/dist/viewport/constants.js +11 -0
  58. package/dist/viewport/constants.js.map +1 -0
  59. package/dist/viewport/index.d.ts +13 -0
  60. package/dist/viewport/index.js +6 -0
  61. package/dist/viewport/index.js.map +1 -0
  62. package/dist/viewport/types.d.ts +22 -0
  63. package/dist/viewport/types.js +3 -0
  64. package/dist/viewport/types.js.map +1 -0
  65. package/dist/viewport/use-viewport-state.d.ts +85 -0
  66. package/dist/viewport/use-viewport-state.js +109 -0
  67. package/dist/viewport/use-viewport-state.js.map +1 -0
  68. package/dist/viewport/utils.d.ts +37 -0
  69. package/dist/viewport/utils.js +46 -0
  70. package/dist/viewport/utils.js.map +1 -0
  71. package/dist/viewport/viewport-size.d.ts +42 -0
  72. package/dist/viewport/viewport-size.js +16 -0
  73. package/dist/viewport/viewport-size.js.map +1 -0
  74. package/package.json +48 -46
  75. package/dist/test/setup.d.ts +0 -2
  76. package/dist/test/setup.js +0 -11
  77. package/dist/test/setup.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,108 @@
1
1
  # @accelint/map-toolkit
2
2
 
3
+ ## 0.3.0
4
+ ### Minor Changes
5
+
6
+ - 7131cc0: Add `useCursorCoordinates`, a hook to retrieve the current coordinates for the mouse hovered position
7
+ - 874edd5: ## Breaking Change: Structured Clone Constraint
8
+
9
+ The event bus payload is now constrained to values that are serializable by the [structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). This constraint aligns the TypeScript types with the actual runtime behavior of the `BroadcastChannel` API.
10
+
11
+ ### What this means
12
+
13
+ You can no longer pass the following types in event payloads:
14
+
15
+ - Functions
16
+ - Symbols
17
+ - DOM nodes
18
+ - Prototype chains (class instances lose their methods)
19
+ - Properties with `undefined` values (they're omitted)
20
+
21
+ ### How to migrate
22
+
23
+ **❌ Before:**
24
+
25
+ ```typescript
26
+ bus.emit('user-action', {
27
+ callback: () => console.log('done'), // ❌ Function
28
+ userData: userClass, // ❌ Class instance with methods
29
+ element: document.getElementById('foo'), // ❌ DOM node
30
+ });
31
+ ```
32
+
33
+ **✅ After:**
34
+
35
+ ```typescript
36
+ // Option 1: Send only data, handle logic separately
37
+ bus.emit('user-action', {
38
+ actionType: 'complete', // ✅ Primitive
39
+ userData: { id: userClass.id, name: userClass.name }, // ✅ Plain object
40
+ elementId: 'foo', // ✅ Reference by ID
41
+ });
42
+
43
+ // Option 2: Use event types to trigger behavior
44
+ bus.on('user-action-complete', () => {
45
+ console.log('done'); // Handle callback logic in listener
46
+ });
47
+ ```
48
+
49
+ ### Supported types
50
+
51
+ - Primitives (string, number, boolean, null, BigInt)
52
+ - Plain objects and arrays
53
+ - Date, RegExp, Map, Set
54
+ - Typed arrays (Uint8Array, etc.)
55
+ - ArrayBuffer, Blob, File
56
+
57
+ ### Finding issues
58
+
59
+ TypeScript will now catch most violations at compile time. Runtime errors from `BroadcastChannel.postMessage()` indicate non-serializable values that slipped through.
60
+ - e8535c4: Adds ViewportSize component that shows the width and height of the viewport and updates with changes.
61
+ Adds useViewportState for more fine-grained control of viewport data (lat/lon/zoom/bounds). Exports `useEffectEvent` ponyfill from `@accelint/bus/react`.
62
+
63
+ ### Patch Changes
64
+
65
+ - 9ab8d72: Convert TextLayer README to Storybook doc and add JSDocs
66
+ - 99f6cd5: Add map-mode/store getCurrentModeOwner method to access the current map mode owner.
67
+ - 80db585: BREAKING CHANGES:
68
+ Design Toolkit no longer exports `tv`, this is now available from Design Foundation
69
+
70
+ Created new package @accelint/design-foundation that houses all of the Tailwind tokens, variants, base styles and utilities for easier reuse without having a dependency on the larger Design Toolkit
71
+
72
+ Updated Map Toolkit Storybook and NextJS demo app styles to import the new Design Foundation
73
+ - f157e42: update picking info to remove more unserializable properties in map-toolkit
74
+ - 7539bbb: update vite config in map-toolkit to re-enable base-map render in storybook preview
75
+ - 86a95cf: refactor map mode to use module useSyncExternalStore pattern instead of class.
76
+
77
+ ## 0.2.0
78
+
79
+ ### Minor Changes
80
+
81
+ - b4d1b9b: Add map mode system with authorization flow for managing interaction modes.
82
+
83
+ **New Features:**
84
+ - `MapProvider` component for managing map mode state with instance isolation
85
+ - `useMapMode()` hook for accessing and requesting mode changes
86
+ - Authorization flow for resolving ownership conflicts when switching modes
87
+ - Event bus integration for decoupled mode change communication
88
+ - Support for multiple independent map instances with isolated state
89
+
90
+ **API:**
91
+ - `MapProvider` component (internal to `BaseMap`)
92
+ - `useMapMode(id)` hook for UI components
93
+ - `BaseMap` now requires `id` prop for instance identification
94
+ - Observable store pattern using React's `useSyncExternalStore`
95
+
96
+ - 998dee6: add deckgl-layer-text for default text styling
97
+
98
+ ### Patch Changes
99
+
100
+ - 303b61f: Pins the dependency version of Deck.gl to 9.1.14. We are not yet able to support 9.2.
101
+ - 0d697fa: Fixed definitions in package files for longhand repository definitions, while disabling the option in syncpack that changed it.
102
+ - a8b8de2: Update README content in map-toolkit
103
+ - f99f294: Updated syncpack and realigned all packages for dependency versions
104
+ - 935b8e5: Updated the package names in the Constellation configuration file.
105
+
3
106
  ## 0.1.0
4
107
 
5
108
  ### Minor Changes
package/README.md CHANGED
@@ -1,35 +1,108 @@
1
1
  # @accelint/map-toolkit
2
2
 
3
+ A collection of components and utilities to simplify visualizing and working with geospatial data. This toolkit provides ready-to-use map components and layers for deck.gl and MapLibre, making it easier to build interactive mapping applications.
4
+
5
+ ## What is Map Toolkit?
6
+
7
+ Map Toolkit is a comprehensive library that provides:
8
+
9
+ - **Deck.gl Components**: Pre-configured layers and components for rendering geospatial data, including symbol layers for military symbology (MIL-STD-2525)
10
+ - **MapLibre Integration**: Components and utilities for working with MapLibre GL JS
11
+ - **React Support**: React-friendly components with hooks and utilities via `@deckgl-fiber-renderer`
12
+ - **Geospatial Utilities**: Helper functions and decorators for common mapping tasks
13
+
14
+ The package is organized by technology (e.g., `deckgl/`, `maplibre/`) with feature-specific exports, allowing you to import only what you need.
15
+
3
16
  ## Installation
4
17
 
5
18
  ```sh
6
19
  npm install @accelint/map-toolkit
7
20
  ```
8
21
 
9
- ## Structure
22
+ ### Optional Dependencies
10
23
 
11
- - standard-toolkit/packages/map-toolkit
12
- - src
13
- - deckgl
14
- - [feature folders]
15
- - index.ts (generated by indexer)
24
+ To minimize bundle size, Map Toolkit uses optional dependencies. Install only the technologies you need:
16
25
 
17
- - [other technology folders, ex: maplibre]
26
+ ```sh
27
+ # For deck.gl features
28
+ pnpm i --save-optional @deck.gl/core @deck.gl/layers @deck.gl/extensions
18
29
 
19
- - ~~index.ts~~ (do not create a root level barrel, there should only be tech level barrels, but also support individual feature exports in package.json)
30
+ # For React/deck.gl features
31
+ pnpm i --save-optional react @deckgl-fiber-renderer/dom
20
32
 
21
- - [misc files, ex: package.json, etc]
33
+ # For MapLibre features
34
+ pnpm i --save-optional maplibre-gl
22
35
 
23
- ## Installing New Packages
24
- Similar to DesignTK, all features within a technology MUST work together, to help guarantee this we will not publish them as individual packages, but as part of a single package.
36
+ # For military symbology
37
+ pnpm i --save-optional milsymbol
38
+ ```
25
39
 
26
- In an effort to reduce the number of unnecessary dependencies being installed by consumers, we are opting to use `optionalDependencies`, instead of `peerDependencies`. This allows us for more flexibility, but also requires us to be more mindful of how these packages are being used.
40
+ ## Usage
27
41
 
28
- ### Example
29
- `pnpm i --save-optional deckgl@latest`
42
+ Import components from their technology-specific paths:
30
43
 
31
- ## Usage
32
- - Under Construction 🚧
44
+ ```ts
45
+ // Deck.gl components
46
+ import { SymbolLayer } from '@accelint/map-toolkit/deckgl';
47
+
48
+ // MapLibre components
49
+ import { /* components */ } from '@accelint/map-toolkit/maplibre';
50
+
51
+ // React/Fiber components
52
+ import { /* components */ } from '@accelint/map-toolkit/deckgl/fiber';
53
+ ```
54
+
55
+ For detailed examples and interactive demos, see the [Storybook documentation](https://map-toolkit.accelint.io/?path=/docs/deckgl-symbol-layer--docs).
56
+
57
+ ## Running Locally
58
+
59
+ To work on Map Toolkit locally:
60
+
61
+ ```bash
62
+ # Install dependencies
63
+ pnpm i
64
+
65
+ # Run Storybook development server
66
+ pnpm --filter=@accelint/map-toolkit preview
67
+
68
+ # Build the package
69
+ pnpm --filter=@accelint/map-toolkit build
70
+ ```
71
+
72
+ If you encounter errors, try running `pnpm build` after installing dependencies, then run the preview command again.
73
+
74
+ ## Testing
75
+
76
+ Run the test suite:
77
+
78
+ ```bash
79
+ # Run tests once
80
+ pnpm --filter=@accelint/map-toolkit test
81
+
82
+ # Run tests in watch mode
83
+ pnpm --filter=@accelint/map-toolkit test:watch
84
+
85
+ # Run benchmarks
86
+ pnpm --filter=@accelint/map-toolkit bench
87
+ ```
88
+
89
+ ## Documentation
90
+
91
+ - **[Storybook](https://map-toolkit.accelint.io/?path=/docs/deckgl-symbol-layer--docs)** - Interactive component documentation and examples
92
+ - **[Changelog](./CHANGELOG.md)** - Release notes and version history
93
+
94
+ ## Package Structure
95
+
96
+ ```
97
+ packages/map-toolkit/
98
+ src/
99
+ deckgl/ # Deck.gl layers and components
100
+ maplibre/ # MapLibre utilities and components
101
+ decorators/ # Shared decorators and utilities
102
+ ```
103
+
104
+ Each technology folder exports its components via barrel files, and individual features are also exported via `package.json` for granular imports.
105
+
106
+ ## License
33
107
 
34
- ## Storybook Preview
35
- - To run storybook, use the command `pnpm preview` to run locally.
108
+ Apache-2.0
package/catalog-info.yaml CHANGED
@@ -2,7 +2,7 @@
2
2
  apiVersion: backstage.io/v1alpha1
3
3
  kind: Component
4
4
  metadata:
5
- name: "@accelint/map-toolkit"
5
+ name: accelint_map-toolkit
6
6
  title: Accelint Map Toolkit
7
7
  description: >-
8
8
  A collection of components and utilities to simplify visualizing and working
@@ -11,13 +11,15 @@ metadata:
11
11
 
12
12
  Dependencies:
13
13
 
14
- @accelint/biome-config@1.0.0, @accelint/constellation-tracker@0.0.0,
15
- @accelint/design-toolkit@5.0.0, @accelint/typescript-config@0.1.2,
16
- @accelint/vitest-config@0.1.3
14
+ accelint_biome-config@1.0.2, accelint_bus@3.0.0,
15
+ accelint_constellation-tracker@1.0.1, accelint_core@0.5.0,
16
+ accelint_design-foundation@1.0.0, accelint_design-toolkit@8.0.0,
17
+ accelint_geo@0.3.0, accelint_typescript-config@0.1.4,
18
+ accelint_vitest-config@0.1.5
17
19
  annotations:
18
20
  backstage.io/edit-url: https://github.com/gohypergiant/standard-toolkit/blob/main/packages/map-toolkit/catalog-info.yaml
19
21
  backstage.io/techdocs-ref: dir:.
20
- package/version: 0.0.2
22
+ package/version: 0.3.0
21
23
  github.com/project-slug: gohypergiant/standard-toolkit
22
24
  links:
23
25
  - url: https://github.com/gohypergiant/standard-toolkit/tree/main/packages/map-toolkit
@@ -34,8 +36,12 @@ spec:
34
36
  lifecycle: production
35
37
  owner: group:default/pathfinder
36
38
  dependsOn:
37
- - component:@accelint/biome-config
38
- - component:@accelint/constellation-tracker
39
- - component:@accelint/design-toolkit
40
- - component:@accelint/typescript-config
41
- - component:@accelint/vitest-config
39
+ - component:accelint_biome-config
40
+ - component:accelint_bus
41
+ - component:accelint_constellation-tracker
42
+ - component:accelint_core
43
+ - component:accelint_design-foundation
44
+ - component:accelint_design-toolkit
45
+ - component:accelint_geo
46
+ - component:accelint_typescript-config
47
+ - component:accelint_vitest-config
@@ -0,0 +1,3 @@
1
+ export { CoordinateFormatTypes, clearCursorCoordinateState, useCursorCoordinates } from './use-cursor-coordinates.js';
2
+ import '@accelint/geo';
3
+ import '@accelint/core';
@@ -0,0 +1,3 @@
1
+ export { clearCursorCoordinateState, useCursorCoordinates } from './use-cursor-coordinates.js';
2
+ //# sourceMappingURL=index.js.map
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js","sourcesContent":[]}
@@ -0,0 +1,76 @@
1
+ import { coordinateSystems } from '@accelint/geo';
2
+ import { UniqueId } from '@accelint/core';
3
+
4
+ /**
5
+ * Supported coordinate format types for displaying map coordinates.
6
+ *
7
+ * @typedef {'dd' | 'ddm' | 'dms' | 'mgrs' | 'utm'} CoordinateFormatTypes
8
+ * @property dd - Decimal Degrees (e.g., "45.50000000 E / 30.25000000 N")
9
+ * @property ddm - Degrees Decimal Minutes (e.g., "45° 30' E / 30° 15' N")
10
+ * @property dms - Degrees Minutes Seconds (e.g., "45° 30' 0\" E / 30° 15' 0\" N")
11
+ * @property mgrs - Military Grid Reference System (e.g., "31U DQ 48251 11932")
12
+ * @property utm - Universal Transverse Mercator (e.g., "31N 448251 5411932")
13
+ */
14
+ type CoordinateFormatTypes = keyof typeof coordinateSystems;
15
+ /**
16
+ * Manually clear cursor coordinate state for a specific instanceId.
17
+ * This is typically not needed as cleanup happens automatically when all subscribers unmount.
18
+ * Use this only in advanced scenarios where manual cleanup is required.
19
+ *
20
+ * @param instanceId - The unique identifier for the map to clear
21
+ *
22
+ * @example
23
+ * ```tsx
24
+ * // Manual cleanup (rarely needed)
25
+ * clearCursorCoordinateState('my-map-instance');
26
+ * ```
27
+ */
28
+ declare function clearCursorCoordinateState(instanceId: UniqueId): void;
29
+ /**
30
+ * React hook that tracks and formats the cursor hover position coordinates on a map.
31
+ *
32
+ * Subscribes to map hover events via the event bus and converts coordinates to various
33
+ * geographic formats (Decimal Degrees, DMS, MGRS, UTM, etc.). The hook automatically
34
+ * filters events to only process those from the specified map instance.
35
+ *
36
+ * Uses `useSyncExternalStore` for concurrent-safe updates and efficient fan-out pattern
37
+ * where multiple components can subscribe to the same map's coordinates with a single
38
+ * bus listener.
39
+ *
40
+ * @param id - Optional map instance ID. If not provided, attempts to use the ID from MapProvider context.
41
+ * @returns Object containing the formatted coordinate string and format setter function
42
+ * @property formattedCoord - The formatted coordinate string (defaults to "--, --" when no position)
43
+ * @property setFormat - Function to change the coordinate format system
44
+ * @throws {Error} When no id is provided and hook is used outside MapProvider context
45
+ *
46
+ * @example
47
+ * ```tsx
48
+ * import { uuid } from '@accelint/core';
49
+ * import { useCursorCoordinates } from '@accelint/map-toolkit/cursor-coordinates';
50
+ *
51
+ * const MAP_ID = uuid();
52
+ *
53
+ * function CoordinateDisplay() {
54
+ * const { formattedCoord, setFormat } = useCursorCoordinates(MAP_ID);
55
+ *
56
+ * return (
57
+ * <div>
58
+ * <select onChange={(e) => setFormat(e.target.value as CoordinateFormatTypes)}>
59
+ * <option value="dd">Decimal Degrees</option>
60
+ * <option value="ddm">Degrees Decimal Minutes</option>
61
+ * <option value="dms">Degrees Minutes Seconds</option>
62
+ * <option value="mgrs">MGRS</option>
63
+ * <option value="utm">UTM</option>
64
+ * </select>
65
+ * <div>{formattedCoord}</div>
66
+ * </div>
67
+ * );
68
+ * }
69
+ * ```
70
+ */
71
+ declare function useCursorCoordinates(id?: UniqueId): {
72
+ formattedCoord: string;
73
+ setFormat: (format: CoordinateFormatTypes) => void;
74
+ };
75
+
76
+ export { type CoordinateFormatTypes, clearCursorCoordinateState, useCursorCoordinates };
@@ -0,0 +1,161 @@
1
+ import 'client-only';
2
+ import { Broadcast } from '@accelint/bus';
3
+ import { createCoordinate, coordinateSystems } from '@accelint/geo';
4
+ import { useContext, useSyncExternalStore, useMemo } from 'react';
5
+ import { MapEvents } from '../deckgl/base-map/events.js';
6
+ import { MapContext } from '../deckgl/base-map/provider.js';
7
+
8
+ const bus = Broadcast.getInstance();
9
+ const create = createCoordinate(coordinateSystems.dd, "LONLAT");
10
+ const MAX_LONGITUDE = 180;
11
+ const LONGITUDE_RANGE = 360;
12
+ const COORDINATE_PRECISION = 8;
13
+ const DEFAULT_COORDINATE = "--, --";
14
+ const prepareCoord = (coord) => {
15
+ let lon = coord[0];
16
+ lon = ((lon + MAX_LONGITUDE) % LONGITUDE_RANGE + LONGITUDE_RANGE) % LONGITUDE_RANGE - MAX_LONGITUDE;
17
+ const lat = coord[1];
18
+ const lonStr = `${Math.abs(lon).toFixed(COORDINATE_PRECISION)} ${lon < 0 ? "W" : "E"}`;
19
+ const latStr = `${Math.abs(lat).toFixed(COORDINATE_PRECISION)} ${lat < 0 ? "S" : "N"}`;
20
+ return `${lonStr} / ${latStr}`;
21
+ };
22
+ function isValidCoordinate(value) {
23
+ return Array.isArray(value) && value.length === 2 && value.every(Number.isFinite);
24
+ }
25
+ const coordinateStore = /* @__PURE__ */ new Map();
26
+ const componentSubscribers = /* @__PURE__ */ new Map();
27
+ const busUnsubscribers = /* @__PURE__ */ new Map();
28
+ const subscriptionCache = /* @__PURE__ */ new Map();
29
+ const snapshotCache = /* @__PURE__ */ new Map();
30
+ function ensureBusListener(instanceId) {
31
+ if (busUnsubscribers.has(instanceId)) {
32
+ return;
33
+ }
34
+ const unsub = bus.on(MapEvents.hover, (data) => {
35
+ const eventId = data.payload.id;
36
+ if (instanceId !== eventId) {
37
+ return;
38
+ }
39
+ const coords = data.payload.info.coordinate;
40
+ const state = coordinateStore.get(instanceId);
41
+ if (state) {
42
+ if (isValidCoordinate(coords)) {
43
+ state.coordinate = coords;
44
+ } else {
45
+ state.coordinate = null;
46
+ }
47
+ const subscribers = componentSubscribers.get(instanceId);
48
+ if (subscribers) {
49
+ for (const onStoreChange of subscribers) {
50
+ onStoreChange();
51
+ }
52
+ }
53
+ }
54
+ });
55
+ busUnsubscribers.set(instanceId, unsub);
56
+ }
57
+ function cleanupBusListenerIfNeeded(instanceId) {
58
+ const subscribers = componentSubscribers.get(instanceId);
59
+ if (!subscribers || subscribers.size === 0) {
60
+ const unsub = busUnsubscribers.get(instanceId);
61
+ if (unsub) {
62
+ unsub();
63
+ busUnsubscribers.delete(instanceId);
64
+ }
65
+ coordinateStore.delete(instanceId);
66
+ componentSubscribers.delete(instanceId);
67
+ subscriptionCache.delete(instanceId);
68
+ snapshotCache.delete(instanceId);
69
+ }
70
+ }
71
+ function getOrCreateSubscription(instanceId) {
72
+ const subscription = subscriptionCache.get(instanceId) ?? ((onStoreChange) => {
73
+ ensureBusListener(instanceId);
74
+ let subscriberSet = componentSubscribers.get(instanceId);
75
+ if (!subscriberSet) {
76
+ subscriberSet = /* @__PURE__ */ new Set();
77
+ componentSubscribers.set(instanceId, subscriberSet);
78
+ }
79
+ subscriberSet.add(onStoreChange);
80
+ return () => {
81
+ const currentSubscriberSet = componentSubscribers.get(instanceId);
82
+ if (currentSubscriberSet) {
83
+ currentSubscriberSet.delete(onStoreChange);
84
+ }
85
+ cleanupBusListenerIfNeeded(instanceId);
86
+ };
87
+ });
88
+ subscriptionCache.set(instanceId, subscription);
89
+ return subscription;
90
+ }
91
+ function getOrCreateSnapshot(instanceId) {
92
+ let cached = snapshotCache.get(instanceId);
93
+ if (!cached) {
94
+ cached = () => {
95
+ const state = coordinateStore.get(instanceId);
96
+ if (!state) {
97
+ return DEFAULT_COORDINATE;
98
+ }
99
+ if (!state.coordinate) {
100
+ return DEFAULT_COORDINATE;
101
+ }
102
+ const coord = create(prepareCoord(state.coordinate));
103
+ return coord[state.format]();
104
+ };
105
+ snapshotCache.set(instanceId, cached);
106
+ }
107
+ return cached;
108
+ }
109
+ function setFormatForInstance(instanceId, format) {
110
+ const state = coordinateStore.get(instanceId);
111
+ if (state) {
112
+ state.format = format;
113
+ const subscribers = componentSubscribers.get(instanceId);
114
+ if (subscribers) {
115
+ for (const onStoreChange of subscribers) {
116
+ onStoreChange();
117
+ }
118
+ }
119
+ }
120
+ }
121
+ function clearCursorCoordinateState(instanceId) {
122
+ const unsub = busUnsubscribers.get(instanceId);
123
+ if (unsub) {
124
+ unsub();
125
+ busUnsubscribers.delete(instanceId);
126
+ }
127
+ coordinateStore.delete(instanceId);
128
+ componentSubscribers.delete(instanceId);
129
+ subscriptionCache.delete(instanceId);
130
+ snapshotCache.delete(instanceId);
131
+ }
132
+ function useCursorCoordinates(id) {
133
+ const contextId = useContext(MapContext);
134
+ const actualId = id ?? contextId;
135
+ if (!actualId) {
136
+ throw new Error(
137
+ "useCursorCoordinates requires either an id parameter or to be used within a MapProvider"
138
+ );
139
+ }
140
+ if (!coordinateStore.has(actualId)) {
141
+ coordinateStore.set(actualId, {
142
+ coordinate: null,
143
+ format: "dd"
144
+ });
145
+ }
146
+ const formattedCoord = useSyncExternalStore(
147
+ getOrCreateSubscription(actualId),
148
+ getOrCreateSnapshot(actualId)
149
+ );
150
+ return useMemo(
151
+ () => ({
152
+ formattedCoord,
153
+ setFormat: (format) => setFormatForInstance(actualId, format)
154
+ }),
155
+ [formattedCoord, actualId]
156
+ );
157
+ }
158
+
159
+ export { clearCursorCoordinateState, useCursorCoordinates };
160
+ //# sourceMappingURL=use-cursor-coordinates.js.map
161
+ //# sourceMappingURL=use-cursor-coordinates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/cursor-coordinates/use-cursor-coordinates.ts"],"names":[],"mappings":";;;;;;;AAkCA,MAAM,GAAA,GAAM,UAAU,WAAA,EAA0B;AAChD,MAAM,MAAA,GAAS,gBAAA,CAAiB,iBAAA,CAAkB,EAAA,EAAI,QAAQ,CAAA;AAE9D,MAAM,aAAA,GAAgB,GAAA;AACtB,MAAM,eAAA,GAAk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ACvC,EAAA,MAAM,WAAW,EAAA,IAAM,SAAA;AAEvB,EAAA,IAAI,CAAC,QAAA,EAAU;AACb,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAIA,EAAA,IAAI,CAAC,eAAA,CAAgB,GAAA,CAAI,QAAQ,CAAA,EAAG;AAClC,IAAA,eAAA,CAAgB,IAAI,QAAA,EAAU;AAAA,MAC5B,UAAA,EAAY,IAAA;AAAA,MACZ,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AAIA,EAAA,MAAM,cAAA,GAAiB,oBAAA;AAAA,IACrB,wBAAwB,QAAQ,CAAA;AAAA,IAChC,oBAAoB,QAAQ;AAAA,GAC9B;AAGA,EAAA,OAAO,OAAA;AAAA,IACL,OAAO;AAAA,MACL,cAAA;AAAA,MACA,SAAA,EAAW,CAAC,MAAA,KACV,oBAAA,CAAqB,UAAU,MAAM;AAAA,KACzC,CAAA;AAAA,IACA,CAAC,gBAAgB,QAAQ;AAAA,GAC3B;AACF","file":"use-cursor-coordinates.js","sourcesContent":["/*\n * Copyright 2025 Hypergiant Galactic Systems Inc. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n'use client';\n\nimport 'client-only';\nimport { Broadcast } from '@accelint/bus';\nimport { coordinateSystems, createCoordinate } from '@accelint/geo';\nimport { useContext, useMemo, useSyncExternalStore } from 'react';\nimport { MapEvents } from '../deckgl/base-map/events';\nimport { MapContext } from '../deckgl/base-map/provider';\nimport type { UniqueId } from '@accelint/core';\nimport type { MapEventType, MapHoverEvent } from '../deckgl/base-map/types';\n\n/**\n * Supported coordinate format types for displaying map coordinates.\n *\n * @typedef {'dd' | 'ddm' | 'dms' | 'mgrs' | 'utm'} CoordinateFormatTypes\n * @property dd - Decimal Degrees (e.g., \"45.50000000 E / 30.25000000 N\")\n * @property ddm - Degrees Decimal Minutes (e.g., \"45° 30' E / 30° 15' N\")\n * @property dms - Degrees Minutes Seconds (e.g., \"45° 30' 0\\\" E / 30° 15' 0\\\" N\")\n * @property mgrs - Military Grid Reference System (e.g., \"31U DQ 48251 11932\")\n * @property utm - Universal Transverse Mercator (e.g., \"31N 448251 5411932\")\n */\nexport type CoordinateFormatTypes = keyof typeof coordinateSystems;\n\nconst bus = Broadcast.getInstance<MapEventType>();\nconst create = createCoordinate(coordinateSystems.dd, 'LONLAT');\n\nconst MAX_LONGITUDE = 180;\nconst LONGITUDE_RANGE = 360;\nconst COORDINATE_PRECISION = 8;\nconst DEFAULT_COORDINATE = '--, --';\n\n/**\n * Prepares coordinates for display by normalizing longitude and formatting with cardinal directions.\n * Normalizes longitude to -180 to 180 range and formats both longitude and latitude with\n * compass directions (E/W for longitude, N/S for latitude).\n *\n * @param coord - Tuple of [longitude, latitude] coordinates\n * @returns Formatted string in the format \"LON.NNNNNNNN E/W / LAT.NNNNNNNN N/S\"\n */\nconst prepareCoord = (coord: [number, number]) => {\n // Normalize longitude to -180 to 180 range (handles wraparound including multi-revolution values)\n let lon = coord[0];\n lon =\n ((((lon + MAX_LONGITUDE) % LONGITUDE_RANGE) + LONGITUDE_RANGE) %\n LONGITUDE_RANGE) -\n MAX_LONGITUDE;\n\n const lat = coord[1];\n const lonStr = `${Math.abs(lon).toFixed(COORDINATE_PRECISION)} ${lon < 0 ? 'W' : 'E'}`;\n const latStr = `${Math.abs(lat).toFixed(COORDINATE_PRECISION)} ${lat < 0 ? 'S' : 'N'}`;\n\n return `${lonStr} / ${latStr}`;\n};\n\n/**\n * Type guard to validate that a value is a proper coordinate tuple.\n * Checks that the value is an array with exactly two finite numbers.\n *\n * @param value - Value to validate as a coordinate\n * @returns True if value is a valid [longitude, latitude] tuple\n */\nfunction isValidCoordinate(value?: number[]): value is [number, number] {\n return (\n Array.isArray(value) && value.length === 2 && value.every(Number.isFinite)\n );\n}\n\n/**\n * State stored for each map instance's cursor coordinates\n */\ntype CursorCoordinateState = {\n coordinate: [number, number] | null;\n format: CoordinateFormatTypes;\n};\n\n/**\n * Store for cursor coordinate state keyed by instanceId\n */\nconst coordinateStore = new Map<UniqueId, CursorCoordinateState>();\n\n/**\n * Track React component subscribers per instanceId (for fan-out notifications).\n * Each Set contains onStoreChange callbacks from useSyncExternalStore.\n */\nconst componentSubscribers = new Map<UniqueId, Set<() => void>>();\n\n/**\n * Cache of bus unsubscribe functions (1 per instanceId).\n * This ensures we only have one bus listener per map, regardless of\n * how many React components subscribe to it.\n */\nconst busUnsubscribers = new Map<UniqueId, () => void>();\n\ntype Subscription = (onStoreChange: () => void) => () => void;\n/**\n * Cache of subscription functions per instanceId to avoid recreating on every render\n */\nconst subscriptionCache = new Map<UniqueId, Subscription>();\n\n/**\n * Cache of snapshot functions per instanceId to maintain referential stability\n */\nconst snapshotCache = new Map<UniqueId, () => string>();\n\n/**\n * Ensures a single bus listener exists for the given instanceId.\n * All React subscribers will be notified via fan-out when the bus event fires.\n * This prevents creating N bus listeners for N React components.\n *\n * @param instanceId - The unique identifier for the map\n */\nfunction ensureBusListener(instanceId: UniqueId): void {\n if (busUnsubscribers.has(instanceId)) {\n return; // Already listening\n }\n\n const unsub = bus.on(MapEvents.hover, (data: MapHoverEvent) => {\n const eventId = data.payload.id;\n\n // Ignore hover events from other possible map instances\n if (instanceId !== eventId) {\n return;\n }\n\n const coords = data.payload.info.coordinate;\n const state = coordinateStore.get(instanceId);\n\n // Update coordinate if valid, or clear if invalid\n if (state) {\n if (isValidCoordinate(coords)) {\n state.coordinate = coords as [number, number];\n } else {\n state.coordinate = null;\n }\n\n // Fan-out: notify all React subscribers\n const subscribers = componentSubscribers.get(instanceId);\n if (subscribers) {\n for (const onStoreChange of subscribers) {\n onStoreChange();\n }\n }\n }\n });\n\n busUnsubscribers.set(instanceId, unsub);\n}\n\n/**\n * Cleans up the bus listener if no React subscribers remain.\n *\n * @param instanceId - The unique identifier for the map\n */\nfunction cleanupBusListenerIfNeeded(instanceId: UniqueId): void {\n const subscribers = componentSubscribers.get(instanceId);\n\n if (!subscribers || subscribers.size === 0) {\n // No more React subscribers - clean up bus listener\n const unsub = busUnsubscribers.get(instanceId);\n if (unsub) {\n unsub();\n busUnsubscribers.delete(instanceId);\n }\n\n // Clean up all state\n coordinateStore.delete(instanceId);\n componentSubscribers.delete(instanceId);\n subscriptionCache.delete(instanceId);\n snapshotCache.delete(instanceId);\n }\n}\n\n/**\n * Creates or retrieves a cached subscription function for a given instanceId.\n * Uses a fan-out pattern: 1 bus listener -> N React subscribers.\n * Automatically cleans up coordinate state when the last subscriber unsubscribes.\n *\n * @param instanceId - The unique identifier for the map\n * @returns A subscription function for useSyncExternalStore\n */\nfunction getOrCreateSubscription(\n instanceId: UniqueId,\n): (onStoreChange: () => void) => () => void {\n const subscription =\n subscriptionCache.get(instanceId) ??\n ((onStoreChange: () => void) => {\n // Ensure single bus listener exists for this instanceId\n ensureBusListener(instanceId);\n\n // Get or create the subscriber set for this map instance, then add this component's callback\n let subscriberSet = componentSubscribers.get(instanceId);\n if (!subscriberSet) {\n subscriberSet = new Set();\n componentSubscribers.set(instanceId, subscriberSet);\n }\n subscriberSet.add(onStoreChange);\n\n // Return cleanup function to remove this component's subscription\n return () => {\n const currentSubscriberSet = componentSubscribers.get(instanceId);\n if (currentSubscriberSet) {\n currentSubscriberSet.delete(onStoreChange);\n }\n\n // Clean up bus listener if this was the last React subscriber\n cleanupBusListenerIfNeeded(instanceId);\n };\n });\n\n subscriptionCache.set(instanceId, subscription);\n\n return subscription;\n}\n\n/**\n * Creates or retrieves a cached snapshot function for a given instanceId.\n * The function must read from the store on every call to get current state.\n *\n * @param instanceId - The unique identifier for the map\n * @returns A snapshot function for useSyncExternalStore that returns formatted coordinate string\n */\nfunction getOrCreateSnapshot(instanceId: UniqueId): () => string {\n let cached = snapshotCache.get(instanceId);\n\n if (!cached) {\n // Create a snapshot function that always reads current state from the store\n cached = () => {\n const state = coordinateStore.get(instanceId);\n\n if (!state) {\n return DEFAULT_COORDINATE;\n }\n\n if (!state.coordinate) {\n return DEFAULT_COORDINATE;\n }\n\n const coord = create(prepareCoord(state.coordinate));\n return coord[state.format]();\n };\n\n snapshotCache.set(instanceId, cached);\n }\n\n return cached;\n}\n\n/**\n * Updates the format for a given map instance and notifies subscribers.\n *\n * @param instanceId - The unique identifier for the map\n * @param format - The new coordinate format to use\n */\nfunction setFormatForInstance(\n instanceId: UniqueId,\n format: CoordinateFormatTypes,\n): void {\n const state = coordinateStore.get(instanceId);\n if (state) {\n state.format = format;\n\n // Notify all subscribers of the format change\n // The coordinate remains unchanged; only the display format changes\n const subscribers = componentSubscribers.get(instanceId);\n if (subscribers) {\n for (const onStoreChange of subscribers) {\n onStoreChange();\n }\n }\n }\n}\n\n/**\n * Manually clear cursor coordinate state for a specific instanceId.\n * This is typically not needed as cleanup happens automatically when all subscribers unmount.\n * Use this only in advanced scenarios where manual cleanup is required.\n *\n * @param instanceId - The unique identifier for the map to clear\n *\n * @example\n * ```tsx\n * // Manual cleanup (rarely needed)\n * clearCursorCoordinateState('my-map-instance');\n * ```\n */\nexport function clearCursorCoordinateState(instanceId: UniqueId): void {\n // Unsubscribe from bus if listening\n const unsub = busUnsubscribers.get(instanceId);\n if (unsub) {\n unsub();\n busUnsubscribers.delete(instanceId);\n }\n\n // Clear all state\n coordinateStore.delete(instanceId);\n componentSubscribers.delete(instanceId);\n subscriptionCache.delete(instanceId);\n snapshotCache.delete(instanceId);\n}\n\n/**\n * React hook that tracks and formats the cursor hover position coordinates on a map.\n *\n * Subscribes to map hover events via the event bus and converts coordinates to various\n * geographic formats (Decimal Degrees, DMS, MGRS, UTM, etc.). The hook automatically\n * filters events to only process those from the specified map instance.\n *\n * Uses `useSyncExternalStore` for concurrent-safe updates and efficient fan-out pattern\n * where multiple components can subscribe to the same map's coordinates with a single\n * bus listener.\n *\n * @param id - Optional map instance ID. If not provided, attempts to use the ID from MapProvider context.\n * @returns Object containing the formatted coordinate string and format setter function\n * @property formattedCoord - The formatted coordinate string (defaults to \"--, --\" when no position)\n * @property setFormat - Function to change the coordinate format system\n * @throws {Error} When no id is provided and hook is used outside MapProvider context\n *\n * @example\n * ```tsx\n * import { uuid } from '@accelint/core';\n * import { useCursorCoordinates } from '@accelint/map-toolkit/cursor-coordinates';\n *\n * const MAP_ID = uuid();\n *\n * function CoordinateDisplay() {\n * const { formattedCoord, setFormat } = useCursorCoordinates(MAP_ID);\n *\n * return (\n * <div>\n * <select onChange={(e) => setFormat(e.target.value as CoordinateFormatTypes)}>\n * <option value=\"dd\">Decimal Degrees</option>\n * <option value=\"ddm\">Degrees Decimal Minutes</option>\n * <option value=\"dms\">Degrees Minutes Seconds</option>\n * <option value=\"mgrs\">MGRS</option>\n * <option value=\"utm\">UTM</option>\n * </select>\n * <div>{formattedCoord}</div>\n * </div>\n * );\n * }\n * ```\n */\nexport function useCursorCoordinates(id?: UniqueId) {\n const contextId = useContext(MapContext);\n const actualId = id ?? contextId;\n\n if (!actualId) {\n throw new Error(\n 'useCursorCoordinates requires either an id parameter or to be used within a MapProvider',\n );\n }\n\n // Initialize state for this map instance BEFORE subscribing\n // This ensures the bus listener has a store to write to\n if (!coordinateStore.has(actualId)) {\n coordinateStore.set(actualId, {\n coordinate: null,\n format: 'dd',\n });\n }\n\n // Subscribe to coordinate changes using useSyncExternalStore\n // This must happen after store initialization\n const formattedCoord = useSyncExternalStore<string>(\n getOrCreateSubscription(actualId),\n getOrCreateSnapshot(actualId),\n );\n\n // Memoize the return value to prevent unnecessary re-renders\n return useMemo(\n () => ({\n formattedCoord,\n setFormat: (format: CoordinateFormatTypes) =>\n setFormatForInstance(actualId, format),\n }),\n [formattedCoord, actualId],\n );\n}\n"]}
@@ -2,6 +2,7 @@ declare const MapEventsNamespace = "map";
2
2
  declare const MapEvents: {
3
3
  readonly click: "map:click";
4
4
  readonly hover: "map:hover";
5
+ readonly viewport: "map:viewport";
5
6
  };
6
7
 
7
8
  export { MapEvents, MapEventsNamespace };
@@ -1,7 +1,8 @@
1
1
  const MapEventsNamespace = "map";
2
2
  const MapEvents = {
3
3
  click: `${MapEventsNamespace}:click`,
4
- hover: `${MapEventsNamespace}:hover`
4
+ hover: `${MapEventsNamespace}:hover`,
5
+ viewport: `${MapEventsNamespace}:viewport`
5
6
  };
6
7
 
7
8
  export { MapEvents, MapEventsNamespace };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/deckgl/base-map/events.ts"],"names":[],"mappings":"AAYO,MAAM,kBAAA,GAAqB;AAE3B,MAAM,SAAA,GAAY;AAAA,EACvB,KAAA,EAAO,GAAG,kBAAkB,CAAA,MAAA,CAAA;AAAA,EAC5B,KAAA,EAAO,GAAG,kBAAkB,CAAA,MAAA;AAC9B","file":"events.js","sourcesContent":["/*\n * Copyright 2025 Hypergiant Galactic Systems Inc. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nexport const MapEventsNamespace = 'map';\n\nexport const MapEvents = {\n click: `${MapEventsNamespace}:click`,\n hover: `${MapEventsNamespace}:hover`,\n} as const;\n"]}
1
+ {"version":3,"sources":["../../../src/deckgl/base-map/events.ts"],"names":[],"mappings":"AAYO,MAAM,kBAAA,GAAqB;AAE3B,MAAM,SAAA,GAAY;AAAA,EACvB,KAAA,EAAO,GAAG,kBAAkB,CAAA,MAAA,CAAA;AAAA,EAC5B,KAAA,EAAO,GAAG,kBAAkB,CAAA,MAAA,CAAA;AAAA,EAC5B,QAAA,EAAU,GAAG,kBAAkB,CAAA,SAAA;AACjC","file":"events.js","sourcesContent":["/*\n * Copyright 2025 Hypergiant Galactic Systems Inc. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nexport const MapEventsNamespace = 'map';\n\nexport const MapEvents = {\n click: `${MapEventsNamespace}:click`,\n hover: `${MapEventsNamespace}:hover`,\n viewport: `${MapEventsNamespace}:viewport`,\n} as const;\n"]}