@trackunit/react-map 0.2.290 → 0.2.292
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs.js +314 -133
- package/index.esm.js +314 -138
- package/migrations/entry.js.map +1 -0
- package/package.json +10 -10
- package/src/draw/__testHelpers.d.ts +43 -0
- package/src/draw/internal/useControlledDrawValue.d.ts +25 -0
- package/src/draw/internal/useDrawErrorReporting.d.ts +18 -0
- package/src/draw/internal/useForceIdleWhen.d.ts +8 -0
- package/src/draw/useDraw.d.ts +75 -16
- package/src/index.d.ts +4 -4
- package/src/layers/useFitToContent.d.ts +49 -5
package/index.esm.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
|
|
2
2
|
import { useNamespaceTranslation, registerTranslations } from '@trackunit/i18n-library-translation';
|
|
3
|
-
import { INITIAL_CAMERA_STATE, INITIAL_MAP_STATUS, KEYBOARD_PAN_AMOUNT, KEYBOARD_ZOOM_AMOUNT, mapAppearanceSchema, DEFAULT_MAP_APPEARANCE,
|
|
4
|
-
export { ANCHOR_SELECTOR, DEFAULT_MAP_APPEARANCE, EMPTY_DRAW_VALUE, HIT_SURFACE_SELECTOR, INITIAL_CAMERA_STATE, INITIAL_INTERACTION_STATE, INITIAL_MAP_STATE, INITIAL_MAP_STATUS, computeMarkerDomPortalZIndex, defineAdapter, geometryTypeToShapeType, mapAppearanceSchema, mapThemeSchema, mapTypeSchema } from '@trackunit/react-map-adapter-shared';
|
|
5
|
-
import { useSyncExternalStore, useMemo, useState, useRef, useCallback, useLayoutEffect, useEffect, useReducer, createContext, useContext, memo, Suspense, useId, Fragment as Fragment$1, forwardRef } from 'react';
|
|
3
|
+
import { INITIAL_CAMERA_STATE, INITIAL_MAP_STATUS, KEYBOARD_PAN_AMOUNT, KEYBOARD_ZOOM_AMOUNT, mapAppearanceSchema, DEFAULT_MAP_APPEARANCE, drawValuesEqual, NO_DRAW_ERRORS, EMPTY_DRAW_VALUE, WORLD_BBOX, INITIAL_INTERACTION_STATE, mapThemeSchema, mergeAntimeridianFeatures, extractSourceData, computeMarkerDomPortalZIndex, densifyGeodesicFeatures, angularDistance, intermediatePoint, GEODESIC_MAX_SEGMENT_KM, geometryTypeToShapeType, resolveStrokeColors } from '@trackunit/react-map-adapter-shared';
|
|
4
|
+
export { ANCHOR_SELECTOR, DEFAULT_MAP_APPEARANCE, EMPTY_DRAW_VALUE, HIT_SURFACE_SELECTOR, INITIAL_CAMERA_STATE, INITIAL_INTERACTION_STATE, INITIAL_MAP_STATE, INITIAL_MAP_STATUS, computeMarkerDomPortalZIndex, defineAdapter, geometryTypeToShapeType, mapAppearanceSchema, mapThemeSchema, mapTypeSchema, toDrawValue } from '@trackunit/react-map-adapter-shared';
|
|
5
|
+
import { useSyncExternalStore, useMemo, useState, useRef, useCallback, useLayoutEffect, useEffect, useReducer, createContext, useContext, memo, Suspense, useId, Fragment as Fragment$1, useEffectEvent, forwardRef } from 'react';
|
|
6
6
|
import { cva, cx } from '@trackunit/css-class-variance-utilities';
|
|
7
7
|
import { Tooltip, useMergeRefs, Icon, Spinner, Text, useMeasure, useContainerBreakpoints, useDebounce, useWatch, useKeyboardShortcut, IconButton, ToggleGroup as ToggleGroup$1, useIsFullscreen, Popover, PopoverTrigger, PopoverContent, MoreMenu, useHover as useHover$1, cvaInteractableItem, useLocalStorageReducer } from '@trackunit/react-components';
|
|
8
8
|
import { twMerge } from 'tailwind-merge';
|
|
9
9
|
import { useFloating, autoUpdate, offset, flip, useHover, safePolygon, useInteractions, shift, hide, useDismiss, useRole } from '@floating-ui/react';
|
|
10
|
-
import { createPortal } from 'react-dom';
|
|
10
|
+
import { createPortal, flushSync } from 'react-dom';
|
|
11
11
|
import { isEqual } from 'es-toolkit';
|
|
12
12
|
import { useGeolocation, useErrorHandlerOrNull } from '@trackunit/react-core-hooks';
|
|
13
13
|
import { Checkbox, ToggleSwitch, RadioGroup as RadioGroup$1, RadioItem, FormGroup, Search as Search$1, SelectField, BaseSelect } from '@trackunit/react-form-components';
|
|
@@ -3487,11 +3487,161 @@ const consoleWarnMap = (source, message, ...details) => {
|
|
|
3487
3487
|
console.warn(`[${source}] ${message}`, ...details);
|
|
3488
3488
|
};
|
|
3489
3489
|
|
|
3490
|
+
/**
|
|
3491
|
+
* The controlled form's sync between `value`, the consumer's drawing, and the port, the
|
|
3492
|
+
* map's. Does nothing while `value` is undefined (the uncontrolled form) or the adapter
|
|
3493
|
+
* has no port.
|
|
3494
|
+
*
|
|
3495
|
+
* The prop is the source of truth on every render: `value` is compared with the port's
|
|
3496
|
+
* value by geometry (identity-cached, so the comparison runs only when either side
|
|
3497
|
+
* changed) and pushed when they differ. The consumer's echo of an edit, the same
|
|
3498
|
+
* geometry under its own ids, pushes nothing; the same `value` object rendered again
|
|
3499
|
+
* after an edit the consumer did not take puts it back on the map.
|
|
3500
|
+
*
|
|
3501
|
+
* The port's own changes, a polygon the user finished, edited or deleted, or the Clear
|
|
3502
|
+
* control, are reported through `onChange` inside `flushSync`, as React does for its own
|
|
3503
|
+
* controlled inputs: the consumer's state is committed before any other render (the
|
|
3504
|
+
* hook's own mode or error snapshot, a camera or focus snapshot elsewhere) can see the
|
|
3505
|
+
* old `value` and push it back. Only the map's own changes are reported; a notification
|
|
3506
|
+
* whose geometry the hook itself pushed or already reported is an echo and is not
|
|
3507
|
+
* reported, so the hook's own pushes from effects never reach `flushSync`.
|
|
3508
|
+
*
|
|
3509
|
+
* Nothing here subscribes to the port's value for rendering: the controlled form renders
|
|
3510
|
+
* an edit through the consumer's `onChange` only.
|
|
3511
|
+
*/
|
|
3512
|
+
const useControlledDrawValue = (port, value, onChange, callHandler) => {
|
|
3513
|
+
const isControlled = value !== undefined;
|
|
3514
|
+
// The last port value the hook handled by geometry: what it pushed, or what it
|
|
3515
|
+
// reported. A port notification that differs from it is the map's own change.
|
|
3516
|
+
const lastSeenRef = useRef(null);
|
|
3517
|
+
// The pair the push effect last compared, so a render that changed neither side costs
|
|
3518
|
+
// no deep comparison.
|
|
3519
|
+
const comparedRef = useRef(null);
|
|
3520
|
+
// A new port, or a hook that turns controlled, has seen nothing yet.
|
|
3521
|
+
useEffect(() => {
|
|
3522
|
+
lastSeenRef.current = null;
|
|
3523
|
+
comparedRef.current = null;
|
|
3524
|
+
}, [isControlled, port]);
|
|
3525
|
+
// Reads the latest `onChange` without resubscribing when the consumer passes a new function.
|
|
3526
|
+
const reportChange = useEffectEvent((next) => {
|
|
3527
|
+
if (onChange === undefined)
|
|
3528
|
+
return;
|
|
3529
|
+
callHandler("onChange", () => onChange(next));
|
|
3530
|
+
});
|
|
3531
|
+
useEffect(() => {
|
|
3532
|
+
if (!isControlled || port === undefined)
|
|
3533
|
+
return;
|
|
3534
|
+
let reported = port.getValue();
|
|
3535
|
+
return port.subscribe(() => {
|
|
3536
|
+
const next = port.getValue();
|
|
3537
|
+
if (next === reported)
|
|
3538
|
+
return;
|
|
3539
|
+
reported = next;
|
|
3540
|
+
const seen = lastSeenRef.current;
|
|
3541
|
+
if (seen !== null && drawValuesEqual(next, seen))
|
|
3542
|
+
return;
|
|
3543
|
+
lastSeenRef.current = next;
|
|
3544
|
+
// A user edit, arriving from a map event handler: committed before anything else renders.
|
|
3545
|
+
flushSync(() => reportChange(next));
|
|
3546
|
+
});
|
|
3547
|
+
}, [isControlled, port]);
|
|
3548
|
+
// No dependency list on purpose: the prop is checked against the port on every render
|
|
3549
|
+
// of the consumer, which is what reverts an edit the consumer did not take.
|
|
3550
|
+
useEffect(() => {
|
|
3551
|
+
if (value === undefined || port === undefined)
|
|
3552
|
+
return;
|
|
3553
|
+
const portValue = port.getValue();
|
|
3554
|
+
const compared = comparedRef.current;
|
|
3555
|
+
if (compared !== null && compared.given === value && compared.port === portValue)
|
|
3556
|
+
return;
|
|
3557
|
+
lastSeenRef.current = value;
|
|
3558
|
+
if (!drawValuesEqual(value, portValue))
|
|
3559
|
+
port.setValue(value);
|
|
3560
|
+
comparedRef.current = { given: value, port: port.getValue() };
|
|
3561
|
+
});
|
|
3562
|
+
};
|
|
3563
|
+
|
|
3564
|
+
/**
|
|
3565
|
+
* Error reporting for `useDraw`. Each error slot is reported once per new object: to
|
|
3566
|
+
* `onError` when given, else as a development warning, and to the app's error handler
|
|
3567
|
+
* at most once per code per hook mount (like `useHeatmap`; a rejected stored boundary
|
|
3568
|
+
* would re-report on every reconnect otherwise). A `value-rejected` verdict is reported
|
|
3569
|
+
* too, deliberately: it is the only count of legacy boundaries the engine cannot
|
|
3570
|
+
* render, kept until the Phase 2b pilot has run (ADR 0030).
|
|
3571
|
+
*
|
|
3572
|
+
* Returns `callHandler`, the guard the controlled form wraps `onChange` in.
|
|
3573
|
+
*/
|
|
3574
|
+
const useDrawErrorReporting = (errors, onError) => {
|
|
3575
|
+
const errorHandler = useErrorHandlerOrNull();
|
|
3576
|
+
const reportedKeysRef = useRef(new Set());
|
|
3577
|
+
const captureOnce = useCallback((key, message, cause) => {
|
|
3578
|
+
if (errorHandler === null || reportedKeysRef.current.has(key))
|
|
3579
|
+
return;
|
|
3580
|
+
reportedKeysRef.current.add(key);
|
|
3581
|
+
errorHandler.captureException(new Error(message, { cause }), {
|
|
3582
|
+
level: "warning",
|
|
3583
|
+
fingerprint: ["react-map", "draw", key],
|
|
3584
|
+
});
|
|
3585
|
+
}, [errorHandler]);
|
|
3586
|
+
const callHandler = useCallback((name, run, detail) => {
|
|
3587
|
+
try {
|
|
3588
|
+
run();
|
|
3589
|
+
}
|
|
3590
|
+
catch (handlerError) {
|
|
3591
|
+
consoleWarnMap("useDraw", `${name} threw.`, handlerError, detail);
|
|
3592
|
+
captureOnce(name === "onChange" ? "on-change-threw" : "on-error-threw", `Map drawing ${name} threw`, handlerError);
|
|
3593
|
+
}
|
|
3594
|
+
}, [captureOnce]);
|
|
3595
|
+
// Reads the latest `onError` without making the effect below depend on its identity.
|
|
3596
|
+
const reportError = useEffectEvent((next, detail) => {
|
|
3597
|
+
if (onError === undefined) {
|
|
3598
|
+
consoleWarnMap("useDraw", `Drawing failed (${next.code}).`, detail);
|
|
3599
|
+
return;
|
|
3600
|
+
}
|
|
3601
|
+
callHandler("onError", () => onError(next), detail);
|
|
3602
|
+
});
|
|
3603
|
+
// Each slot reports once per new object: an engine error coming and going must not
|
|
3604
|
+
// re-report the value verdict that stayed in place the whole time.
|
|
3605
|
+
const reportedRef = useRef(NO_DRAW_ERRORS);
|
|
3606
|
+
useEffect(() => {
|
|
3607
|
+
const previous = reportedRef.current;
|
|
3608
|
+
reportedRef.current = errors;
|
|
3609
|
+
const fresh = [errors.engine, errors.value].flatMap(slot => slot !== null && slot !== previous.engine && slot !== previous.value ? [slot] : []);
|
|
3610
|
+
for (const next of fresh) {
|
|
3611
|
+
const detail = next.code === "value-rejected" ? next.reasons : next.cause;
|
|
3612
|
+
captureOnce(next.code, `Map drawing failed: ${next.code}`, detail);
|
|
3613
|
+
reportError(next, detail);
|
|
3614
|
+
}
|
|
3615
|
+
}, [captureOnce, errors]);
|
|
3616
|
+
return callHandler;
|
|
3617
|
+
};
|
|
3618
|
+
|
|
3619
|
+
const sameWatched = (a, b) => a.port === b.port && a.condition === b.condition;
|
|
3620
|
+
/**
|
|
3621
|
+
* Forces the port back to `"idle"` whenever `condition` becomes true, at mount included,
|
|
3622
|
+
* and again for a port that arrives or is swapped in while it holds: a disabled hook must
|
|
3623
|
+
* not leave the map in a drawing mode it can no longer exit, and closing the polygon that
|
|
3624
|
+
* reaches the feature limit ends polygon mode so the next click does not start another one.
|
|
3625
|
+
*/
|
|
3626
|
+
const useForceIdleWhen = (port, condition) => {
|
|
3627
|
+
const watched = useMemo(() => ({ port, condition }), [condition, port]);
|
|
3628
|
+
useWatch({
|
|
3629
|
+
value: watched,
|
|
3630
|
+
immediate: true,
|
|
3631
|
+
isEqual: sameWatched,
|
|
3632
|
+
onChange: next => {
|
|
3633
|
+
if (next.condition)
|
|
3634
|
+
next.port?.setMode("idle");
|
|
3635
|
+
},
|
|
3636
|
+
});
|
|
3637
|
+
};
|
|
3638
|
+
|
|
3490
3639
|
const noopUnsubscribe$1 = () => undefined;
|
|
3491
3640
|
const subscribeNoop = () => noopUnsubscribe$1;
|
|
3492
3641
|
const getIdle = () => "idle";
|
|
3493
3642
|
const getEmpty = () => EMPTY_DRAW_VALUE;
|
|
3494
3643
|
const getNoErrors = () => NO_DRAW_ERRORS;
|
|
3644
|
+
const getZero = () => 0;
|
|
3495
3645
|
/**
|
|
3496
3646
|
* Ids of the controls `useDraw` returns, for a consumer that filters or replaces one of them
|
|
3497
3647
|
* (a wizard that confirms before clearing, for instance).
|
|
@@ -3501,87 +3651,32 @@ const DRAW_CONTROL_IDS = {
|
|
|
3501
3651
|
select: "draw-select",
|
|
3502
3652
|
clear: "draw-clear",
|
|
3503
3653
|
};
|
|
3504
|
-
|
|
3505
|
-
* Feature-facing hook for the optional drawing capability (ADR 0030).
|
|
3506
|
-
*
|
|
3507
|
-
* Calling this hook is the consumer's opt-in: a map only offers drawing where a
|
|
3508
|
-
* component renders `controls` (typically appended to the `tools` area through
|
|
3509
|
-
* `useControls`). Feature code sees GeoJSON in and GeoJSON out; the engine behind
|
|
3510
|
-
* the adapter is never exposed.
|
|
3511
|
-
*
|
|
3512
|
-
* @example
|
|
3513
|
-
* ```tsx
|
|
3514
|
-
* const [Map, api] = useMap(adapter);
|
|
3515
|
-
* const draw = useDraw(api);
|
|
3516
|
-
* const controls = useControls(api, { tools: { append: draw.controls } });
|
|
3517
|
-
*
|
|
3518
|
-
* return (
|
|
3519
|
-
* <Map>
|
|
3520
|
-
* <Controls api={api} controls={controls} />
|
|
3521
|
-
* </Map>
|
|
3522
|
-
* );
|
|
3523
|
-
* ```
|
|
3524
|
-
*/
|
|
3525
|
-
const useDraw = (api, options) => {
|
|
3654
|
+
function useDraw(api, options) {
|
|
3526
3655
|
const [t] = useTranslation();
|
|
3527
3656
|
const port = api.actions.draw;
|
|
3528
3657
|
const enabled = options?.enabled ?? true;
|
|
3529
3658
|
const isSupported = port !== undefined;
|
|
3659
|
+
const controlledValue = options?.value;
|
|
3660
|
+
const isControlled = controlledValue !== undefined;
|
|
3530
3661
|
// Call through the port object (never pass its methods around unbound): adapters
|
|
3531
3662
|
// implement DrawPort as a class whose methods read instance state.
|
|
3532
3663
|
const subscribe = useMemo(() => (port === undefined ? subscribeNoop : (listener) => port.subscribe(listener)), [port]);
|
|
3533
3664
|
const getMode = useMemo(() => (port === undefined ? getIdle : () => port.getMode()), [port]);
|
|
3534
|
-
const getValue = useMemo(() => (port === undefined ? getEmpty : () => port.getValue()), [port]);
|
|
3535
3665
|
const getErrors = useMemo(() => (port === undefined ? getNoErrors : () => port.getErrors()), [port]);
|
|
3666
|
+
// One value subscription per form. Uncontrolled: the port's value, which the hook returns.
|
|
3667
|
+
// Controlled: never the value (see useControlledDrawValue), only its feature count, a
|
|
3668
|
+
// scalar, so the hook still renders at the one moment the limit matters. The other
|
|
3669
|
+
// getter is constant, so its notifications re-render nothing.
|
|
3670
|
+
const getPortValue = useMemo(() => (port === undefined || isControlled ? getEmpty : () => port.getValue()), [isControlled, port]);
|
|
3671
|
+
const getPortFeatureCount = useMemo(() => (port === undefined || !isControlled ? getZero : () => port.getValue().features.length), [isControlled, port]);
|
|
3536
3672
|
const mode = useSyncExternalStore(subscribe, getMode, getIdle);
|
|
3537
|
-
const value = useSyncExternalStore(subscribe, getValue, getEmpty);
|
|
3538
3673
|
const errors = useSyncExternalStore(subscribe, getErrors, getNoErrors);
|
|
3674
|
+
const portValue = useSyncExternalStore(subscribe, getPortValue, getEmpty);
|
|
3675
|
+
const portFeatureCount = useSyncExternalStore(subscribe, getPortFeatureCount, getZero);
|
|
3539
3676
|
const error = errors.engine ?? errors.value;
|
|
3540
|
-
|
|
3541
|
-
|
|
3542
|
-
|
|
3543
|
-
port?.setMode("idle");
|
|
3544
|
-
}, [enabled, port]);
|
|
3545
|
-
const onError = options?.onError;
|
|
3546
|
-
const onErrorRef = useRef(onError);
|
|
3547
|
-
useEffect(() => {
|
|
3548
|
-
onErrorRef.current = onError;
|
|
3549
|
-
}, [onError]);
|
|
3550
|
-
const errorHandler = useErrorHandlerOrNull();
|
|
3551
|
-
// The app's error handler at most once per code per hook mount, like useHeatmap: a
|
|
3552
|
-
// rejected stored boundary re-reports on every reconnect otherwise. A `value-rejected`
|
|
3553
|
-
// verdict is reported too, deliberately: it is the only count of legacy boundaries
|
|
3554
|
-
// the engine cannot render, kept until the Phase 2b pilot has run (ADR 0030).
|
|
3555
|
-
const reportedCodesRef = useRef(new Set());
|
|
3556
|
-
// Each slot reports once per new object: an engine error coming and going must not
|
|
3557
|
-
// re-report the value verdict that stayed in place the whole time.
|
|
3558
|
-
const reportedRef = useRef(NO_DRAW_ERRORS);
|
|
3559
|
-
useEffect(() => {
|
|
3560
|
-
const previous = reportedRef.current;
|
|
3561
|
-
reportedRef.current = errors;
|
|
3562
|
-
const fresh = [errors.engine, errors.value].flatMap(slot => slot !== null && slot !== previous.engine && slot !== previous.value ? [slot] : []);
|
|
3563
|
-
for (const next of fresh) {
|
|
3564
|
-
const detail = next.code === "value-rejected" ? next.reasons : next.cause;
|
|
3565
|
-
if (errorHandler !== null && !reportedCodesRef.current.has(next.code)) {
|
|
3566
|
-
reportedCodesRef.current.add(next.code);
|
|
3567
|
-
errorHandler.captureException(new Error(`Map drawing failed: ${next.code}`, { cause: detail }), {
|
|
3568
|
-
level: "warning",
|
|
3569
|
-
fingerprint: ["react-map", "draw", next.code],
|
|
3570
|
-
});
|
|
3571
|
-
}
|
|
3572
|
-
const handler = onErrorRef.current;
|
|
3573
|
-
if (handler === undefined) {
|
|
3574
|
-
consoleWarnMap("useDraw", `Drawing failed (${next.code}).`, detail);
|
|
3575
|
-
continue;
|
|
3576
|
-
}
|
|
3577
|
-
try {
|
|
3578
|
-
handler(next);
|
|
3579
|
-
}
|
|
3580
|
-
catch (handlerError) {
|
|
3581
|
-
consoleWarnMap("useDraw", "onError threw.", handlerError, detail);
|
|
3582
|
-
}
|
|
3583
|
-
}
|
|
3584
|
-
}, [errors, errorHandler]);
|
|
3677
|
+
const value = controlledValue ?? portValue;
|
|
3678
|
+
const callHandler = useDrawErrorReporting(errors, options?.onError);
|
|
3679
|
+
useControlledDrawValue(port, controlledValue, options?.onChange, callHandler);
|
|
3585
3680
|
const setMode = useCallback((nextMode) => {
|
|
3586
3681
|
port?.setMode(nextMode);
|
|
3587
3682
|
}, [port]);
|
|
@@ -3592,20 +3687,28 @@ const useDraw = (api, options) => {
|
|
|
3592
3687
|
port?.setValue(EMPTY_DRAW_VALUE);
|
|
3593
3688
|
port?.setMode("idle");
|
|
3594
3689
|
}, [port]);
|
|
3690
|
+
const stopDrawing = useCallback(() => {
|
|
3691
|
+
port?.setMode("idle");
|
|
3692
|
+
}, [port]);
|
|
3693
|
+
// The larger of what the map holds and what `value` holds: in the controlled form the
|
|
3694
|
+
// two differ while the consumer has not taken a change, and the limit and the edit
|
|
3695
|
+
// toggle must hold on both sides. Uncontrolled, the count is `value`'s.
|
|
3696
|
+
const featureCount = Math.max(portFeatureCount, value.features.length);
|
|
3595
3697
|
// Rejected features are in the value but not on the map, so there is nothing to
|
|
3596
|
-
// select among them; the edit toggle follows what the map
|
|
3597
|
-
//
|
|
3698
|
+
// select among them; the edit toggle follows what is on the map, whatever the engine
|
|
3699
|
+
// slot says.
|
|
3598
3700
|
const rejectedCount = errors.value?.rejectedFeatureIndices.length ?? 0;
|
|
3599
|
-
const hasPolygons =
|
|
3600
|
-
const
|
|
3701
|
+
const hasPolygons = featureCount - rejectedCount > 0;
|
|
3702
|
+
const maxFeatures = options?.maxFeatures;
|
|
3601
3703
|
// A limit below one would lock the toggle with "clear the drawing" and nothing to clear.
|
|
3602
|
-
const limitReached =
|
|
3603
|
-
// Closing the polygon that reaches the limit ends polygon mode, so the next click
|
|
3604
|
-
// on the map does not start another one.
|
|
3704
|
+
const limitReached = maxFeatures !== undefined && maxFeatures >= 1 && featureCount >= maxFeatures;
|
|
3605
3705
|
useEffect(() => {
|
|
3606
|
-
if (
|
|
3607
|
-
|
|
3608
|
-
|
|
3706
|
+
if (maxFeatures === undefined || maxFeatures >= 1)
|
|
3707
|
+
return;
|
|
3708
|
+
consoleWarnMap("useDraw", `maxFeatures must be at least 1; ${maxFeatures} is ignored and the drawing has no limit.`);
|
|
3709
|
+
}, [maxFeatures]);
|
|
3710
|
+
useForceIdleWhen(port, !enabled);
|
|
3711
|
+
useForceIdleWhen(port, limitReached && mode === "polygon");
|
|
3609
3712
|
// A down engine does not disable the toggles: switching one on is the retry. The
|
|
3610
3713
|
// controller loads again on the next mode that needs an engine after a failed load,
|
|
3611
3714
|
// and a mode operation that succeeds clears a failed update. Consumers say drawing
|
|
@@ -3621,8 +3724,8 @@ const useDraw = (api, options) => {
|
|
|
3621
3724
|
section: t("controls.category.tools"),
|
|
3622
3725
|
value: mode === "polygon",
|
|
3623
3726
|
onChange: on => setMode(on ? "polygon" : "idle"),
|
|
3624
|
-
//
|
|
3625
|
-
//
|
|
3727
|
+
// Polygon mode ends as soon as the limit is reached, so the toggle is never
|
|
3728
|
+
// both active and disabled for longer than one render.
|
|
3626
3729
|
disabled: limitReached,
|
|
3627
3730
|
disabledReason: limitReached ? t("draw.limitReached") : undefined,
|
|
3628
3731
|
"data-testid": "map-draw-polygon-toggle",
|
|
@@ -3640,6 +3743,7 @@ const useDraw = (api, options) => {
|
|
|
3640
3743
|
disabledReason: hasPolygons || mode === "select" ? undefined : t("draw.selectDisabled"),
|
|
3641
3744
|
"data-testid": "map-draw-select-toggle",
|
|
3642
3745
|
};
|
|
3746
|
+
// In the controlled form the clear is a change the map makes, reported through `onChange`.
|
|
3643
3747
|
const clearButton = {
|
|
3644
3748
|
type: "button",
|
|
3645
3749
|
id: DRAW_CONTROL_IDS.clear,
|
|
@@ -3651,19 +3755,19 @@ const useDraw = (api, options) => {
|
|
|
3651
3755
|
};
|
|
3652
3756
|
return [polygonToggle, selectToggle, clearButton];
|
|
3653
3757
|
}, [clear, enabled, hasPolygons, isSupported, limitReached, mode, setMode, t]);
|
|
3654
|
-
|
|
3758
|
+
const base = useMemo(() => ({
|
|
3655
3759
|
isSupported,
|
|
3656
3760
|
isDrawing: mode !== "idle",
|
|
3657
3761
|
mode,
|
|
3658
|
-
value,
|
|
3659
3762
|
error,
|
|
3660
3763
|
errors,
|
|
3661
3764
|
setMode,
|
|
3662
|
-
setValue,
|
|
3663
|
-
clear,
|
|
3664
3765
|
controls,
|
|
3665
|
-
}), [
|
|
3666
|
-
};
|
|
3766
|
+
}), [controls, error, errors, isSupported, mode, setMode]);
|
|
3767
|
+
const uncontrolled = useMemo(() => ({ ...base, value: portValue, setValue, clear }), [base, clear, portValue, setValue]);
|
|
3768
|
+
const controlled = useMemo(() => ({ ...base, stopDrawing }), [base, stopDrawing]);
|
|
3769
|
+
return isControlled ? controlled : uncontrolled;
|
|
3770
|
+
}
|
|
3667
3771
|
|
|
3668
3772
|
/**
|
|
3669
3773
|
* Reads the persisted map appearance once (on mount) so it can seed the adapter
|
|
@@ -6076,6 +6180,8 @@ const useRoute = (options) => {
|
|
|
6076
6180
|
}), [id, name, layerReady, getBounds, counts, controls, fitParticipation, features, waypoints, style, interactive]);
|
|
6077
6181
|
};
|
|
6078
6182
|
|
|
6183
|
+
/** No targets. Stable reference for consumers that sometimes have none to pass. */
|
|
6184
|
+
const NO_FIT_TARGETS = [];
|
|
6079
6185
|
// ============================================================================
|
|
6080
6186
|
// Defaults
|
|
6081
6187
|
// ============================================================================
|
|
@@ -6085,25 +6191,39 @@ const DEFAULT_TIMEOUT = 10000;
|
|
|
6085
6191
|
// ============================================================================
|
|
6086
6192
|
// Internal helpers
|
|
6087
6193
|
// ============================================================================
|
|
6088
|
-
const
|
|
6089
|
-
|
|
6090
|
-
|
|
6091
|
-
|
|
6092
|
-
|
|
6194
|
+
const participates = (participation, minParticipation) => minParticipation === "all" ? participation === "all" : participation !== "none";
|
|
6195
|
+
const filterHandles = (handles, minParticipation) => handles.filter(h => participates(h.fitParticipation, minParticipation));
|
|
6196
|
+
const filterTargets = (targets, minParticipation) => targets.filter(t => participates(t.fitParticipation ?? "all", minParticipation));
|
|
6197
|
+
const isLoadingTarget = (target) => target.loading === true;
|
|
6198
|
+
const computeFitBounds = (handles, targets) => mergeBounds([...handles.map(h => h.getBounds()), ...targets.map(t => t.bounds)]);
|
|
6199
|
+
const warnStillLoading = (handles, targets, timeout) => {
|
|
6200
|
+
const names = [
|
|
6201
|
+
...handles.filter(h => h.loadsData && h.loading).map(h => h.name),
|
|
6202
|
+
...targets.filter(isLoadingTarget).map(t => t.name ?? "target"),
|
|
6203
|
+
];
|
|
6204
|
+
if (names.length === 0)
|
|
6205
|
+
return;
|
|
6206
|
+
consoleWarnMap("useFitToContent", `Timeout (${timeout}ms) reached. Fitting with available data. Still loading: ${names.join(", ")}`);
|
|
6093
6207
|
};
|
|
6094
|
-
const computeFitBounds = (handles) => mergeBounds(handles.map(h => h.getBounds()));
|
|
6095
6208
|
// ============================================================================
|
|
6096
6209
|
// Hook
|
|
6097
6210
|
// ============================================================================
|
|
6098
6211
|
/**
|
|
6099
6212
|
* `useFitToContent` -- orchestrates a one-time viewport fit once all
|
|
6100
|
-
* participating layers have loaded their initial data.
|
|
6213
|
+
* participating layers (and targets) have loaded their initial data.
|
|
6101
6214
|
*
|
|
6102
6215
|
* Only layers with `fitParticipation !== "none"` are waited on and included
|
|
6103
6216
|
* in the initial fit. `fitNow()` only includes `fitParticipation: "all"` layers.
|
|
6104
6217
|
*
|
|
6218
|
+
* Content that is not a layer joins through `targets`: a boundary the drawing
|
|
6219
|
+
* engine renders, a server-side extent. A target is filtered by its
|
|
6220
|
+
* `fitParticipation` as a layer is, and waited for while `loading`: the fit is
|
|
6221
|
+
* derived from the map's readiness, the layers' readiness and the targets on every
|
|
6222
|
+
* render until it has run, so a target that starts loading once the map is ready
|
|
6223
|
+
* holds the fit until it settles or the timeout fires.
|
|
6224
|
+
*
|
|
6105
6225
|
* A configurable timeout (default 10s) ensures the map fits to whatever
|
|
6106
|
-
* data is available if some layers are slow.
|
|
6226
|
+
* data is available if some layers or targets are slow.
|
|
6107
6227
|
*
|
|
6108
6228
|
* When using this hook alongside an adapter's `initialViewport`, note that the
|
|
6109
6229
|
* initial viewport serves as a loading-state viewport and will be overridden
|
|
@@ -6115,7 +6235,13 @@ const computeFitBounds = (handles) => mergeBounds(handles.map(h => h.getBounds()
|
|
|
6115
6235
|
* const shapes = useShapes({ id: "zones", ..., fitParticipation: "none" });
|
|
6116
6236
|
* const layers = useLayers(api, [markers, shapes]);
|
|
6117
6237
|
*
|
|
6118
|
-
*
|
|
6238
|
+
* // Memoized: the array is an input of the fit, so a new one per render would
|
|
6239
|
+
* // re-run the fit check and change `fitNow`.
|
|
6240
|
+
* const targets = useMemo(
|
|
6241
|
+
* (): ReadonlyArray<FitTarget> => [{ bounds: storedBoundaryBbox, fitParticipation: "initial" }],
|
|
6242
|
+
* [storedBoundaryBbox]
|
|
6243
|
+
* );
|
|
6244
|
+
* const { hasFitted, isWaiting, fitNow } = useFitToContent(api, layers.handles, { targets });
|
|
6119
6245
|
*
|
|
6120
6246
|
* return (
|
|
6121
6247
|
* <Map>
|
|
@@ -6126,68 +6252,118 @@ const computeFitBounds = (handles) => mergeBounds(handles.map(h => h.getBounds()
|
|
|
6126
6252
|
* ```
|
|
6127
6253
|
*/
|
|
6128
6254
|
const useFitToContent = (api, handles, options) => {
|
|
6129
|
-
const { disabled = false, padding = DEFAULT_PADDING, maxZoom = DEFAULT_MAX_ZOOM, timeout = DEFAULT_TIMEOUT, } = options ?? {};
|
|
6255
|
+
const { disabled = false, padding = DEFAULT_PADDING, maxZoom = DEFAULT_MAX_ZOOM, timeout = DEFAULT_TIMEOUT, targets = NO_FIT_TARGETS, } = options ?? {};
|
|
6130
6256
|
const [hasFitted, setHasFitted] = useState(false);
|
|
6257
|
+
// Set the moment the fit runs, ahead of the state: a render whose inputs changed while
|
|
6258
|
+
// `setHasFitted` is still pending must not fit again.
|
|
6259
|
+
const fittedRef = useRef(false);
|
|
6260
|
+
// The two inputs the layers and the clock contribute to the fit below: the ids of the
|
|
6261
|
+
// participating layers whose ready promises have resolved (null while none have), and
|
|
6262
|
+
// the timeout. Keyed on the layer id, which is stable, where handle objects are not: a
|
|
6263
|
+
// layer hook recreates its handle on an inline option, and consumers pass fresh arrays.
|
|
6264
|
+
const [readyIds, setReadyIds] = useState(null);
|
|
6265
|
+
const [timedOut, setTimedOut] = useState(false);
|
|
6131
6266
|
const isWaiting = !disabled && !hasFitted;
|
|
6132
|
-
|
|
6267
|
+
// The current handle objects, read when a wait or a fit runs and by `fitNow`, never
|
|
6268
|
+
// watched: only the participating ids below are an input.
|
|
6133
6269
|
const handlesRef = useRef(handles);
|
|
6134
6270
|
useEffect(() => {
|
|
6135
6271
|
handlesRef.current = handles;
|
|
6136
6272
|
}, [handles]);
|
|
6137
|
-
|
|
6273
|
+
const participatingKey = useMemo(() => filterHandles(handles, "initial")
|
|
6274
|
+
.map(h => h.id)
|
|
6275
|
+
.toSorted()
|
|
6276
|
+
.join("\u0000"), [handles]);
|
|
6277
|
+
const participatingIds = useMemo(() => (participatingKey === "" ? [] : participatingKey.split("\u0000")), [participatingKey]);
|
|
6278
|
+
const layersReady = readyIds !== null && participatingIds.every(id => readyIds.has(id));
|
|
6279
|
+
// ---- Layer readiness ----
|
|
6280
|
+
// A recreated map (Google theme switch, Mapbox style reload) drops readiness. Both inputs
|
|
6281
|
+
// reset then, so the wait and the timeout re-arm on the next ready and the new layers'
|
|
6282
|
+
// promises are awaited again before a fit that has not run yet. On a microtask, as the
|
|
6283
|
+
// other state here, so nothing is set synchronously inside an effect.
|
|
6138
6284
|
useEffect(() => {
|
|
6139
|
-
if (
|
|
6285
|
+
if (api.state.isReady)
|
|
6286
|
+
return;
|
|
6287
|
+
void Promise.resolve().then(() => {
|
|
6288
|
+
setReadyIds(null);
|
|
6289
|
+
setTimedOut(false);
|
|
6290
|
+
});
|
|
6291
|
+
}, [api.state.isReady]);
|
|
6292
|
+
// Awaited whenever a participating id is not among the ready ones, so a layer that joins
|
|
6293
|
+
// while a target holds the fit is waited for too; a handle replaced by a new object with
|
|
6294
|
+
// the same id, or a new array of the same handles, awaits nothing and cancels nothing.
|
|
6295
|
+
// Promise.all([]) resolves on a microtask, so the state is never set synchronously
|
|
6296
|
+
// inside the effect.
|
|
6297
|
+
useEffect(() => {
|
|
6298
|
+
if (!api.state.isReady || disabled || hasFitted || layersReady)
|
|
6140
6299
|
return;
|
|
6141
|
-
const participating = filterHandles(handlesRef.current, "initial");
|
|
6142
6300
|
let cancelled = false;
|
|
6143
|
-
const
|
|
6144
|
-
|
|
6301
|
+
const pending = filterHandles(handlesRef.current, "initial").filter(h => !(readyIds?.has(h.id) ?? false));
|
|
6302
|
+
const pendingIds = pending.map(h => h.id);
|
|
6303
|
+
void Promise.all(pending.map(h => h.ready)).then(() => {
|
|
6304
|
+
if (cancelled)
|
|
6145
6305
|
return;
|
|
6146
|
-
|
|
6147
|
-
|
|
6306
|
+
setReadyIds(previous => new Set([...(previous ?? []), ...pendingIds]));
|
|
6307
|
+
});
|
|
6308
|
+
return () => {
|
|
6309
|
+
cancelled = true;
|
|
6148
6310
|
};
|
|
6149
|
-
|
|
6150
|
-
|
|
6311
|
+
}, [api.state.isReady, disabled, hasFitted, layersReady, participatingKey, readyIds]);
|
|
6312
|
+
// ---- Timeout: bounds the wait for layers and targets alike ----
|
|
6313
|
+
useEffect(() => {
|
|
6314
|
+
if (!api.state.isReady || disabled || hasFitted || timedOut)
|
|
6315
|
+
return;
|
|
6316
|
+
const timeoutId = setTimeout(() => setTimedOut(true), timeout);
|
|
6317
|
+
return () => clearTimeout(timeoutId);
|
|
6318
|
+
}, [api.state.isReady, disabled, hasFitted, timedOut, timeout]);
|
|
6319
|
+
// ---- The initial fit, derived from its inputs ----
|
|
6320
|
+
useEffect(() => {
|
|
6321
|
+
if (hasFitted || fittedRef.current || disabled || !api.state.isReady)
|
|
6322
|
+
return;
|
|
6323
|
+
const fitTargets = filterTargets(targets, "initial");
|
|
6324
|
+
const waiting = !layersReady || fitTargets.some(isLoadingTarget);
|
|
6325
|
+
if (waiting && !timedOut)
|
|
6326
|
+
return;
|
|
6327
|
+
let cancelled = false;
|
|
6328
|
+
// On a microtask, as the readiness above, so the state is never set synchronously
|
|
6329
|
+
// inside the effect; a cleanup in between hands the fit to the next run instead of
|
|
6330
|
+
// fitting twice.
|
|
6331
|
+
void Promise.resolve().then(() => {
|
|
6332
|
+
if (cancelled || fittedRef.current)
|
|
6151
6333
|
return;
|
|
6334
|
+
fittedRef.current = true;
|
|
6152
6335
|
const fitHandles = filterHandles(handlesRef.current, "initial");
|
|
6153
|
-
|
|
6336
|
+
if (waiting)
|
|
6337
|
+
warnStillLoading(fitHandles, fitTargets, timeout);
|
|
6338
|
+
const bounds = computeFitBounds(fitHandles, fitTargets);
|
|
6154
6339
|
if (bounds !== null) {
|
|
6155
6340
|
void api.actions.fitBounds(bounds, { padding, maxZoom, animate: false });
|
|
6156
6341
|
}
|
|
6157
|
-
|
|
6158
|
-
};
|
|
6159
|
-
const readyPromises = participating.map(h => h.ready);
|
|
6160
|
-
const timeoutId = setTimeout(() => {
|
|
6161
|
-
if (cancelled)
|
|
6162
|
-
return;
|
|
6163
|
-
const stillPending = filterHandles(handlesRef.current, "initial").filter(h => h.loadsData && h.loading);
|
|
6164
|
-
if (stillPending.length > 0) {
|
|
6165
|
-
const names = stillPending.map(h => h.name).join(", ");
|
|
6166
|
-
consoleWarnMap("useFitToContent", `Timeout (${timeout}ms) reached. Fitting with available data. Still loading: ${names}`);
|
|
6167
|
-
}
|
|
6168
|
-
performFit();
|
|
6169
|
-
}, timeout);
|
|
6170
|
-
// When participating is empty, Promise.all([]) resolves on the next microtask,
|
|
6171
|
-
// which avoids the synchronous-setState-in-effect lint rule.
|
|
6172
|
-
void Promise.all(readyPromises).then(() => {
|
|
6173
|
-
if (cancelled)
|
|
6174
|
-
return;
|
|
6175
|
-
clearTimeout(timeoutId);
|
|
6176
|
-
performFit();
|
|
6342
|
+
setHasFitted(true);
|
|
6177
6343
|
});
|
|
6178
6344
|
return () => {
|
|
6179
6345
|
cancelled = true;
|
|
6180
|
-
clearTimeout(timeoutId);
|
|
6181
6346
|
};
|
|
6182
|
-
}, [
|
|
6347
|
+
}, [
|
|
6348
|
+
api.actions,
|
|
6349
|
+
api.state.isReady,
|
|
6350
|
+
disabled,
|
|
6351
|
+
hasFitted,
|
|
6352
|
+
layersReady,
|
|
6353
|
+
maxZoom,
|
|
6354
|
+
padding,
|
|
6355
|
+
participatingKey,
|
|
6356
|
+
targets,
|
|
6357
|
+
timedOut,
|
|
6358
|
+
timeout,
|
|
6359
|
+
]);
|
|
6183
6360
|
// ---- fitNow: manual re-fit ----
|
|
6184
6361
|
const fitNow = useCallback(() => {
|
|
6185
|
-
const
|
|
6186
|
-
const bounds = computeFitBounds(fitHandles);
|
|
6362
|
+
const bounds = computeFitBounds(filterHandles(handlesRef.current, "all"), filterTargets(targets, "all"));
|
|
6187
6363
|
if (bounds !== null) {
|
|
6188
6364
|
void api.actions.fitBounds(bounds, { padding, maxZoom, animate: true });
|
|
6189
6365
|
}
|
|
6190
|
-
}, [api.actions, padding,
|
|
6366
|
+
}, [api.actions, maxZoom, padding, targets]);
|
|
6191
6367
|
return useMemo(() => ({ hasFitted, isWaiting, fitNow }), [hasFitted, isWaiting, fitNow]);
|
|
6192
6368
|
};
|
|
6193
6369
|
|
|
@@ -13782,4 +13958,4 @@ const mockMapApi = (overrides) => {
|
|
|
13782
13958
|
*/
|
|
13783
13959
|
setupLibraryTranslations();
|
|
13784
13960
|
|
|
13785
|
-
export { ClusterMarker, ClusterStick, Controls, DEFAULT_APPEARANCE_PERSISTENCE_KEY, DEFAULT_MARKER_SIZE_BREAKPOINTS, DRAW_CONTROL_IDS, DefaultControls, Layers, MARKER_DARK_PILL, MARKER_DISC_BORDER_WIDTH_PX, MARKER_LIGHT_PILL, MARKER_PILL_CONTENT_LAYOUT_SIZE, MARKER_SIZE_MAP, MARKER_TUNING, MapLoadingState, MapMarker, MapMarkerIcon, PanelIconButton, ShapeAnnotationLabel, buildExpandedIds, cvaMapMarker, cvaMarkerIndicator, mockMapApi, useAdaptiveMarkerHelpers, useAutoPanResolver, useCameraIdle, useCameraState, useClusterCountFormat, useControlStack, useControls, useDefaultControls, useDirectionIndicator, useDraw, useEntitiesNearCursor, useExpandedIds, useFitFeatureBounds, useFitToContent, useHeatmap, useImageOverlay, useLabelPlacement, useLayers, useMap, useMapAnnotation, useMapAnnotations, useMapAppearanceControls, useMapKeyboardNavigation, useMarkerColors, useMarkerStateResolvers, useMarkers, usePanel, usePanelPreload, usePersistedAppearanceSeed, usePreviewMap, useRoute, useShapeLabelHelpers, useShapes, useViewportContext };
|
|
13961
|
+
export { ClusterMarker, ClusterStick, Controls, DEFAULT_APPEARANCE_PERSISTENCE_KEY, DEFAULT_MARKER_SIZE_BREAKPOINTS, DRAW_CONTROL_IDS, DefaultControls, Layers, MARKER_DARK_PILL, MARKER_DISC_BORDER_WIDTH_PX, MARKER_LIGHT_PILL, MARKER_PILL_CONTENT_LAYOUT_SIZE, MARKER_SIZE_MAP, MARKER_TUNING, MapLoadingState, MapMarker, MapMarkerIcon, NO_FIT_TARGETS, PanelIconButton, ShapeAnnotationLabel, buildExpandedIds, cvaMapMarker, cvaMarkerIndicator, mockMapApi, useAdaptiveMarkerHelpers, useAutoPanResolver, useCameraIdle, useCameraState, useClusterCountFormat, useControlStack, useControls, useDefaultControls, useDirectionIndicator, useDraw, useEntitiesNearCursor, useExpandedIds, useFitFeatureBounds, useFitToContent, useHeatmap, useImageOverlay, useLabelPlacement, useLayers, useMap, useMapAnnotation, useMapAnnotations, useMapAppearanceControls, useMapKeyboardNavigation, useMarkerColors, useMarkerStateResolvers, useMarkers, usePanel, usePanelPreload, usePersistedAppearanceSeed, usePreviewMap, useRoute, useShapeLabelHelpers, useShapes, useViewportContext };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entry.js","sourceRoot":"","sources":["../../../../../libs/react/map/migrations/entry.ts"],"names":[],"mappings":"","sourcesContent":["export {};\n"]}
|
package/package.json
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trackunit/react-map",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.292",
|
|
4
4
|
"repository": "https://github.com/Trackunit/manager",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.txt",
|
|
6
6
|
"engines": {
|
|
7
7
|
"node": ">=24.x"
|
|
8
8
|
},
|
|
9
9
|
"dependencies": {
|
|
10
|
-
"@trackunit/react-components": "6.0.
|
|
11
|
-
"@trackunit/css-class-variance-utilities": "2.6.
|
|
12
|
-
"@trackunit/react-form-components": "2.17.
|
|
13
|
-
"@trackunit/react-core-hooks": "1.31.
|
|
14
|
-
"@trackunit/geo-json-utils": "1.21.
|
|
15
|
-
"@trackunit/i18n-library-translation": "2.14.
|
|
10
|
+
"@trackunit/react-components": "6.0.35",
|
|
11
|
+
"@trackunit/css-class-variance-utilities": "2.6.41",
|
|
12
|
+
"@trackunit/react-form-components": "2.17.37",
|
|
13
|
+
"@trackunit/react-core-hooks": "1.31.33",
|
|
14
|
+
"@trackunit/geo-json-utils": "1.21.41",
|
|
15
|
+
"@trackunit/i18n-library-translation": "2.14.33",
|
|
16
16
|
"react-minimal-pie-chart": "^8.4.0",
|
|
17
|
-
"@trackunit/react-map-adapter-shared": "0.0.
|
|
18
|
-
"@trackunit/react-map-color-utils": "0.0.
|
|
19
|
-
"@trackunit/shared-utils": "1.22.
|
|
17
|
+
"@trackunit/react-map-adapter-shared": "0.0.209",
|
|
18
|
+
"@trackunit/react-map-color-utils": "0.0.182",
|
|
19
|
+
"@trackunit/shared-utils": "1.22.41",
|
|
20
20
|
"@trackunit/ui-design-tokens": "1.21.39",
|
|
21
21
|
"@floating-ui/react": "^0.26.25",
|
|
22
22
|
"es-toolkit": "^1.52.0",
|