@trackunit/react-map 0.2.291 → 0.2.293
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 +2 -2
- 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/translation10.cjs.js +8 -8
- package/translation10.esm.js +8 -8
package/index.cjs.js
CHANGED
|
@@ -3488,11 +3488,161 @@ const consoleWarnMap = (source, message, ...details) => {
|
|
|
3488
3488
|
console.warn(`[${source}] ${message}`, ...details);
|
|
3489
3489
|
};
|
|
3490
3490
|
|
|
3491
|
+
/**
|
|
3492
|
+
* The controlled form's sync between `value`, the consumer's drawing, and the port, the
|
|
3493
|
+
* map's. Does nothing while `value` is undefined (the uncontrolled form) or the adapter
|
|
3494
|
+
* has no port.
|
|
3495
|
+
*
|
|
3496
|
+
* The prop is the source of truth on every render: `value` is compared with the port's
|
|
3497
|
+
* value by geometry (identity-cached, so the comparison runs only when either side
|
|
3498
|
+
* changed) and pushed when they differ. The consumer's echo of an edit, the same
|
|
3499
|
+
* geometry under its own ids, pushes nothing; the same `value` object rendered again
|
|
3500
|
+
* after an edit the consumer did not take puts it back on the map.
|
|
3501
|
+
*
|
|
3502
|
+
* The port's own changes, a polygon the user finished, edited or deleted, or the Clear
|
|
3503
|
+
* control, are reported through `onChange` inside `flushSync`, as React does for its own
|
|
3504
|
+
* controlled inputs: the consumer's state is committed before any other render (the
|
|
3505
|
+
* hook's own mode or error snapshot, a camera or focus snapshot elsewhere) can see the
|
|
3506
|
+
* old `value` and push it back. Only the map's own changes are reported; a notification
|
|
3507
|
+
* whose geometry the hook itself pushed or already reported is an echo and is not
|
|
3508
|
+
* reported, so the hook's own pushes from effects never reach `flushSync`.
|
|
3509
|
+
*
|
|
3510
|
+
* Nothing here subscribes to the port's value for rendering: the controlled form renders
|
|
3511
|
+
* an edit through the consumer's `onChange` only.
|
|
3512
|
+
*/
|
|
3513
|
+
const useControlledDrawValue = (port, value, onChange, callHandler) => {
|
|
3514
|
+
const isControlled = value !== undefined;
|
|
3515
|
+
// The last port value the hook handled by geometry: what it pushed, or what it
|
|
3516
|
+
// reported. A port notification that differs from it is the map's own change.
|
|
3517
|
+
const lastSeenRef = react.useRef(null);
|
|
3518
|
+
// The pair the push effect last compared, so a render that changed neither side costs
|
|
3519
|
+
// no deep comparison.
|
|
3520
|
+
const comparedRef = react.useRef(null);
|
|
3521
|
+
// A new port, or a hook that turns controlled, has seen nothing yet.
|
|
3522
|
+
react.useEffect(() => {
|
|
3523
|
+
lastSeenRef.current = null;
|
|
3524
|
+
comparedRef.current = null;
|
|
3525
|
+
}, [isControlled, port]);
|
|
3526
|
+
// Reads the latest `onChange` without resubscribing when the consumer passes a new function.
|
|
3527
|
+
const reportChange = react.useEffectEvent((next) => {
|
|
3528
|
+
if (onChange === undefined)
|
|
3529
|
+
return;
|
|
3530
|
+
callHandler("onChange", () => onChange(next));
|
|
3531
|
+
});
|
|
3532
|
+
react.useEffect(() => {
|
|
3533
|
+
if (!isControlled || port === undefined)
|
|
3534
|
+
return;
|
|
3535
|
+
let reported = port.getValue();
|
|
3536
|
+
return port.subscribe(() => {
|
|
3537
|
+
const next = port.getValue();
|
|
3538
|
+
if (next === reported)
|
|
3539
|
+
return;
|
|
3540
|
+
reported = next;
|
|
3541
|
+
const seen = lastSeenRef.current;
|
|
3542
|
+
if (seen !== null && reactMapAdapterShared.drawValuesEqual(next, seen))
|
|
3543
|
+
return;
|
|
3544
|
+
lastSeenRef.current = next;
|
|
3545
|
+
// A user edit, arriving from a map event handler: committed before anything else renders.
|
|
3546
|
+
reactDom.flushSync(() => reportChange(next));
|
|
3547
|
+
});
|
|
3548
|
+
}, [isControlled, port]);
|
|
3549
|
+
// No dependency list on purpose: the prop is checked against the port on every render
|
|
3550
|
+
// of the consumer, which is what reverts an edit the consumer did not take.
|
|
3551
|
+
react.useEffect(() => {
|
|
3552
|
+
if (value === undefined || port === undefined)
|
|
3553
|
+
return;
|
|
3554
|
+
const portValue = port.getValue();
|
|
3555
|
+
const compared = comparedRef.current;
|
|
3556
|
+
if (compared !== null && compared.given === value && compared.port === portValue)
|
|
3557
|
+
return;
|
|
3558
|
+
lastSeenRef.current = value;
|
|
3559
|
+
if (!reactMapAdapterShared.drawValuesEqual(value, portValue))
|
|
3560
|
+
port.setValue(value);
|
|
3561
|
+
comparedRef.current = { given: value, port: port.getValue() };
|
|
3562
|
+
});
|
|
3563
|
+
};
|
|
3564
|
+
|
|
3565
|
+
/**
|
|
3566
|
+
* Error reporting for `useDraw`. Each error slot is reported once per new object: to
|
|
3567
|
+
* `onError` when given, else as a development warning, and to the app's error handler
|
|
3568
|
+
* at most once per code per hook mount (like `useHeatmap`; a rejected stored boundary
|
|
3569
|
+
* would re-report on every reconnect otherwise). A `value-rejected` verdict is reported
|
|
3570
|
+
* too, deliberately: it is the only count of legacy boundaries the engine cannot
|
|
3571
|
+
* render, kept until the Phase 2b pilot has run (ADR 0030).
|
|
3572
|
+
*
|
|
3573
|
+
* Returns `callHandler`, the guard the controlled form wraps `onChange` in.
|
|
3574
|
+
*/
|
|
3575
|
+
const useDrawErrorReporting = (errors, onError) => {
|
|
3576
|
+
const errorHandler = reactCoreHooks.useErrorHandlerOrNull();
|
|
3577
|
+
const reportedKeysRef = react.useRef(new Set());
|
|
3578
|
+
const captureOnce = react.useCallback((key, message, cause) => {
|
|
3579
|
+
if (errorHandler === null || reportedKeysRef.current.has(key))
|
|
3580
|
+
return;
|
|
3581
|
+
reportedKeysRef.current.add(key);
|
|
3582
|
+
errorHandler.captureException(new Error(message, { cause }), {
|
|
3583
|
+
level: "warning",
|
|
3584
|
+
fingerprint: ["react-map", "draw", key],
|
|
3585
|
+
});
|
|
3586
|
+
}, [errorHandler]);
|
|
3587
|
+
const callHandler = react.useCallback((name, run, detail) => {
|
|
3588
|
+
try {
|
|
3589
|
+
run();
|
|
3590
|
+
}
|
|
3591
|
+
catch (handlerError) {
|
|
3592
|
+
consoleWarnMap("useDraw", `${name} threw.`, handlerError, detail);
|
|
3593
|
+
captureOnce(name === "onChange" ? "on-change-threw" : "on-error-threw", `Map drawing ${name} threw`, handlerError);
|
|
3594
|
+
}
|
|
3595
|
+
}, [captureOnce]);
|
|
3596
|
+
// Reads the latest `onError` without making the effect below depend on its identity.
|
|
3597
|
+
const reportError = react.useEffectEvent((next, detail) => {
|
|
3598
|
+
if (onError === undefined) {
|
|
3599
|
+
consoleWarnMap("useDraw", `Drawing failed (${next.code}).`, detail);
|
|
3600
|
+
return;
|
|
3601
|
+
}
|
|
3602
|
+
callHandler("onError", () => onError(next), detail);
|
|
3603
|
+
});
|
|
3604
|
+
// Each slot reports once per new object: an engine error coming and going must not
|
|
3605
|
+
// re-report the value verdict that stayed in place the whole time.
|
|
3606
|
+
const reportedRef = react.useRef(reactMapAdapterShared.NO_DRAW_ERRORS);
|
|
3607
|
+
react.useEffect(() => {
|
|
3608
|
+
const previous = reportedRef.current;
|
|
3609
|
+
reportedRef.current = errors;
|
|
3610
|
+
const fresh = [errors.engine, errors.value].flatMap(slot => slot !== null && slot !== previous.engine && slot !== previous.value ? [slot] : []);
|
|
3611
|
+
for (const next of fresh) {
|
|
3612
|
+
const detail = next.code === "value-rejected" ? next.reasons : next.cause;
|
|
3613
|
+
captureOnce(next.code, `Map drawing failed: ${next.code}`, detail);
|
|
3614
|
+
reportError(next, detail);
|
|
3615
|
+
}
|
|
3616
|
+
}, [captureOnce, errors]);
|
|
3617
|
+
return callHandler;
|
|
3618
|
+
};
|
|
3619
|
+
|
|
3620
|
+
const sameWatched = (a, b) => a.port === b.port && a.condition === b.condition;
|
|
3621
|
+
/**
|
|
3622
|
+
* Forces the port back to `"idle"` whenever `condition` becomes true, at mount included,
|
|
3623
|
+
* and again for a port that arrives or is swapped in while it holds: a disabled hook must
|
|
3624
|
+
* not leave the map in a drawing mode it can no longer exit, and closing the polygon that
|
|
3625
|
+
* reaches the feature limit ends polygon mode so the next click does not start another one.
|
|
3626
|
+
*/
|
|
3627
|
+
const useForceIdleWhen = (port, condition) => {
|
|
3628
|
+
const watched = react.useMemo(() => ({ port, condition }), [condition, port]);
|
|
3629
|
+
reactComponents.useWatch({
|
|
3630
|
+
value: watched,
|
|
3631
|
+
immediate: true,
|
|
3632
|
+
isEqual: sameWatched,
|
|
3633
|
+
onChange: next => {
|
|
3634
|
+
if (next.condition)
|
|
3635
|
+
next.port?.setMode("idle");
|
|
3636
|
+
},
|
|
3637
|
+
});
|
|
3638
|
+
};
|
|
3639
|
+
|
|
3491
3640
|
const noopUnsubscribe$1 = () => undefined;
|
|
3492
3641
|
const subscribeNoop = () => noopUnsubscribe$1;
|
|
3493
3642
|
const getIdle = () => "idle";
|
|
3494
3643
|
const getEmpty = () => reactMapAdapterShared.EMPTY_DRAW_VALUE;
|
|
3495
3644
|
const getNoErrors = () => reactMapAdapterShared.NO_DRAW_ERRORS;
|
|
3645
|
+
const getZero = () => 0;
|
|
3496
3646
|
/**
|
|
3497
3647
|
* Ids of the controls `useDraw` returns, for a consumer that filters or replaces one of them
|
|
3498
3648
|
* (a wizard that confirms before clearing, for instance).
|
|
@@ -3502,87 +3652,32 @@ const DRAW_CONTROL_IDS = {
|
|
|
3502
3652
|
select: "draw-select",
|
|
3503
3653
|
clear: "draw-clear",
|
|
3504
3654
|
};
|
|
3505
|
-
|
|
3506
|
-
* Feature-facing hook for the optional drawing capability (ADR 0030).
|
|
3507
|
-
*
|
|
3508
|
-
* Calling this hook is the consumer's opt-in: a map only offers drawing where a
|
|
3509
|
-
* component renders `controls` (typically appended to the `tools` area through
|
|
3510
|
-
* `useControls`). Feature code sees GeoJSON in and GeoJSON out; the engine behind
|
|
3511
|
-
* the adapter is never exposed.
|
|
3512
|
-
*
|
|
3513
|
-
* @example
|
|
3514
|
-
* ```tsx
|
|
3515
|
-
* const [Map, api] = useMap(adapter);
|
|
3516
|
-
* const draw = useDraw(api);
|
|
3517
|
-
* const controls = useControls(api, { tools: { append: draw.controls } });
|
|
3518
|
-
*
|
|
3519
|
-
* return (
|
|
3520
|
-
* <Map>
|
|
3521
|
-
* <Controls api={api} controls={controls} />
|
|
3522
|
-
* </Map>
|
|
3523
|
-
* );
|
|
3524
|
-
* ```
|
|
3525
|
-
*/
|
|
3526
|
-
const useDraw = (api, options) => {
|
|
3655
|
+
function useDraw(api, options) {
|
|
3527
3656
|
const [t] = useTranslation();
|
|
3528
3657
|
const port = api.actions.draw;
|
|
3529
3658
|
const enabled = options?.enabled ?? true;
|
|
3530
3659
|
const isSupported = port !== undefined;
|
|
3660
|
+
const controlledValue = options?.value;
|
|
3661
|
+
const isControlled = controlledValue !== undefined;
|
|
3531
3662
|
// Call through the port object (never pass its methods around unbound): adapters
|
|
3532
3663
|
// implement DrawPort as a class whose methods read instance state.
|
|
3533
3664
|
const subscribe = react.useMemo(() => (port === undefined ? subscribeNoop : (listener) => port.subscribe(listener)), [port]);
|
|
3534
3665
|
const getMode = react.useMemo(() => (port === undefined ? getIdle : () => port.getMode()), [port]);
|
|
3535
|
-
const getValue = react.useMemo(() => (port === undefined ? getEmpty : () => port.getValue()), [port]);
|
|
3536
3666
|
const getErrors = react.useMemo(() => (port === undefined ? getNoErrors : () => port.getErrors()), [port]);
|
|
3667
|
+
// One value subscription per form. Uncontrolled: the port's value, which the hook returns.
|
|
3668
|
+
// Controlled: never the value (see useControlledDrawValue), only its feature count, a
|
|
3669
|
+
// scalar, so the hook still renders at the one moment the limit matters. The other
|
|
3670
|
+
// getter is constant, so its notifications re-render nothing.
|
|
3671
|
+
const getPortValue = react.useMemo(() => (port === undefined || isControlled ? getEmpty : () => port.getValue()), [isControlled, port]);
|
|
3672
|
+
const getPortFeatureCount = react.useMemo(() => (port === undefined || !isControlled ? getZero : () => port.getValue().features.length), [isControlled, port]);
|
|
3537
3673
|
const mode = react.useSyncExternalStore(subscribe, getMode, getIdle);
|
|
3538
|
-
const value = react.useSyncExternalStore(subscribe, getValue, getEmpty);
|
|
3539
3674
|
const errors = react.useSyncExternalStore(subscribe, getErrors, getNoErrors);
|
|
3675
|
+
const portValue = react.useSyncExternalStore(subscribe, getPortValue, getEmpty);
|
|
3676
|
+
const portFeatureCount = react.useSyncExternalStore(subscribe, getPortFeatureCount, getZero);
|
|
3540
3677
|
const error = errors.engine ?? errors.value;
|
|
3541
|
-
|
|
3542
|
-
|
|
3543
|
-
|
|
3544
|
-
port?.setMode("idle");
|
|
3545
|
-
}, [enabled, port]);
|
|
3546
|
-
const onError = options?.onError;
|
|
3547
|
-
const onErrorRef = react.useRef(onError);
|
|
3548
|
-
react.useEffect(() => {
|
|
3549
|
-
onErrorRef.current = onError;
|
|
3550
|
-
}, [onError]);
|
|
3551
|
-
const errorHandler = reactCoreHooks.useErrorHandlerOrNull();
|
|
3552
|
-
// The app's error handler at most once per code per hook mount, like useHeatmap: a
|
|
3553
|
-
// rejected stored boundary re-reports on every reconnect otherwise. A `value-rejected`
|
|
3554
|
-
// verdict is reported too, deliberately: it is the only count of legacy boundaries
|
|
3555
|
-
// the engine cannot render, kept until the Phase 2b pilot has run (ADR 0030).
|
|
3556
|
-
const reportedCodesRef = react.useRef(new Set());
|
|
3557
|
-
// Each slot reports once per new object: an engine error coming and going must not
|
|
3558
|
-
// re-report the value verdict that stayed in place the whole time.
|
|
3559
|
-
const reportedRef = react.useRef(reactMapAdapterShared.NO_DRAW_ERRORS);
|
|
3560
|
-
react.useEffect(() => {
|
|
3561
|
-
const previous = reportedRef.current;
|
|
3562
|
-
reportedRef.current = errors;
|
|
3563
|
-
const fresh = [errors.engine, errors.value].flatMap(slot => slot !== null && slot !== previous.engine && slot !== previous.value ? [slot] : []);
|
|
3564
|
-
for (const next of fresh) {
|
|
3565
|
-
const detail = next.code === "value-rejected" ? next.reasons : next.cause;
|
|
3566
|
-
if (errorHandler !== null && !reportedCodesRef.current.has(next.code)) {
|
|
3567
|
-
reportedCodesRef.current.add(next.code);
|
|
3568
|
-
errorHandler.captureException(new Error(`Map drawing failed: ${next.code}`, { cause: detail }), {
|
|
3569
|
-
level: "warning",
|
|
3570
|
-
fingerprint: ["react-map", "draw", next.code],
|
|
3571
|
-
});
|
|
3572
|
-
}
|
|
3573
|
-
const handler = onErrorRef.current;
|
|
3574
|
-
if (handler === undefined) {
|
|
3575
|
-
consoleWarnMap("useDraw", `Drawing failed (${next.code}).`, detail);
|
|
3576
|
-
continue;
|
|
3577
|
-
}
|
|
3578
|
-
try {
|
|
3579
|
-
handler(next);
|
|
3580
|
-
}
|
|
3581
|
-
catch (handlerError) {
|
|
3582
|
-
consoleWarnMap("useDraw", "onError threw.", handlerError, detail);
|
|
3583
|
-
}
|
|
3584
|
-
}
|
|
3585
|
-
}, [errors, errorHandler]);
|
|
3678
|
+
const value = controlledValue ?? portValue;
|
|
3679
|
+
const callHandler = useDrawErrorReporting(errors, options?.onError);
|
|
3680
|
+
useControlledDrawValue(port, controlledValue, options?.onChange, callHandler);
|
|
3586
3681
|
const setMode = react.useCallback((nextMode) => {
|
|
3587
3682
|
port?.setMode(nextMode);
|
|
3588
3683
|
}, [port]);
|
|
@@ -3593,20 +3688,28 @@ const useDraw = (api, options) => {
|
|
|
3593
3688
|
port?.setValue(reactMapAdapterShared.EMPTY_DRAW_VALUE);
|
|
3594
3689
|
port?.setMode("idle");
|
|
3595
3690
|
}, [port]);
|
|
3691
|
+
const stopDrawing = react.useCallback(() => {
|
|
3692
|
+
port?.setMode("idle");
|
|
3693
|
+
}, [port]);
|
|
3694
|
+
// The larger of what the map holds and what `value` holds: in the controlled form the
|
|
3695
|
+
// two differ while the consumer has not taken a change, and the limit and the edit
|
|
3696
|
+
// toggle must hold on both sides. Uncontrolled, the count is `value`'s.
|
|
3697
|
+
const featureCount = Math.max(portFeatureCount, value.features.length);
|
|
3596
3698
|
// Rejected features are in the value but not on the map, so there is nothing to
|
|
3597
|
-
// select among them; the edit toggle follows what the map
|
|
3598
|
-
//
|
|
3699
|
+
// select among them; the edit toggle follows what is on the map, whatever the engine
|
|
3700
|
+
// slot says.
|
|
3599
3701
|
const rejectedCount = errors.value?.rejectedFeatureIndices.length ?? 0;
|
|
3600
|
-
const hasPolygons =
|
|
3601
|
-
const
|
|
3702
|
+
const hasPolygons = featureCount - rejectedCount > 0;
|
|
3703
|
+
const maxFeatures = options?.maxFeatures;
|
|
3602
3704
|
// A limit below one would lock the toggle with "clear the drawing" and nothing to clear.
|
|
3603
|
-
const limitReached =
|
|
3604
|
-
// Closing the polygon that reaches the limit ends polygon mode, so the next click
|
|
3605
|
-
// on the map does not start another one.
|
|
3705
|
+
const limitReached = maxFeatures !== undefined && maxFeatures >= 1 && featureCount >= maxFeatures;
|
|
3606
3706
|
react.useEffect(() => {
|
|
3607
|
-
if (
|
|
3608
|
-
|
|
3609
|
-
|
|
3707
|
+
if (maxFeatures === undefined || maxFeatures >= 1)
|
|
3708
|
+
return;
|
|
3709
|
+
consoleWarnMap("useDraw", `maxFeatures must be at least 1; ${maxFeatures} is ignored and the drawing has no limit.`);
|
|
3710
|
+
}, [maxFeatures]);
|
|
3711
|
+
useForceIdleWhen(port, !enabled);
|
|
3712
|
+
useForceIdleWhen(port, limitReached && mode === "polygon");
|
|
3610
3713
|
// A down engine does not disable the toggles: switching one on is the retry. The
|
|
3611
3714
|
// controller loads again on the next mode that needs an engine after a failed load,
|
|
3612
3715
|
// and a mode operation that succeeds clears a failed update. Consumers say drawing
|
|
@@ -3622,8 +3725,8 @@ const useDraw = (api, options) => {
|
|
|
3622
3725
|
section: t("controls.category.tools"),
|
|
3623
3726
|
value: mode === "polygon",
|
|
3624
3727
|
onChange: on => setMode(on ? "polygon" : "idle"),
|
|
3625
|
-
//
|
|
3626
|
-
//
|
|
3728
|
+
// Polygon mode ends as soon as the limit is reached, so the toggle is never
|
|
3729
|
+
// both active and disabled for longer than one render.
|
|
3627
3730
|
disabled: limitReached,
|
|
3628
3731
|
disabledReason: limitReached ? t("draw.limitReached") : undefined,
|
|
3629
3732
|
"data-testid": "map-draw-polygon-toggle",
|
|
@@ -3641,6 +3744,7 @@ const useDraw = (api, options) => {
|
|
|
3641
3744
|
disabledReason: hasPolygons || mode === "select" ? undefined : t("draw.selectDisabled"),
|
|
3642
3745
|
"data-testid": "map-draw-select-toggle",
|
|
3643
3746
|
};
|
|
3747
|
+
// In the controlled form the clear is a change the map makes, reported through `onChange`.
|
|
3644
3748
|
const clearButton = {
|
|
3645
3749
|
type: "button",
|
|
3646
3750
|
id: DRAW_CONTROL_IDS.clear,
|
|
@@ -3652,19 +3756,19 @@ const useDraw = (api, options) => {
|
|
|
3652
3756
|
};
|
|
3653
3757
|
return [polygonToggle, selectToggle, clearButton];
|
|
3654
3758
|
}, [clear, enabled, hasPolygons, isSupported, limitReached, mode, setMode, t]);
|
|
3655
|
-
|
|
3759
|
+
const base = react.useMemo(() => ({
|
|
3656
3760
|
isSupported,
|
|
3657
3761
|
isDrawing: mode !== "idle",
|
|
3658
3762
|
mode,
|
|
3659
|
-
value,
|
|
3660
3763
|
error,
|
|
3661
3764
|
errors,
|
|
3662
3765
|
setMode,
|
|
3663
|
-
setValue,
|
|
3664
|
-
clear,
|
|
3665
3766
|
controls,
|
|
3666
|
-
}), [
|
|
3667
|
-
};
|
|
3767
|
+
}), [controls, error, errors, isSupported, mode, setMode]);
|
|
3768
|
+
const uncontrolled = react.useMemo(() => ({ ...base, value: portValue, setValue, clear }), [base, clear, portValue, setValue]);
|
|
3769
|
+
const controlled = react.useMemo(() => ({ ...base, stopDrawing }), [base, stopDrawing]);
|
|
3770
|
+
return isControlled ? controlled : uncontrolled;
|
|
3771
|
+
}
|
|
3668
3772
|
|
|
3669
3773
|
/**
|
|
3670
3774
|
* Reads the persisted map appearance once (on mount) so it can seed the adapter
|
|
@@ -6077,6 +6181,8 @@ const useRoute = (options) => {
|
|
|
6077
6181
|
}), [id, name, layerReady, getBounds, counts, controls, fitParticipation, features, waypoints, style, interactive]);
|
|
6078
6182
|
};
|
|
6079
6183
|
|
|
6184
|
+
/** No targets. Stable reference for consumers that sometimes have none to pass. */
|
|
6185
|
+
const NO_FIT_TARGETS = [];
|
|
6080
6186
|
// ============================================================================
|
|
6081
6187
|
// Defaults
|
|
6082
6188
|
// ============================================================================
|
|
@@ -6086,25 +6192,39 @@ const DEFAULT_TIMEOUT = 10000;
|
|
|
6086
6192
|
// ============================================================================
|
|
6087
6193
|
// Internal helpers
|
|
6088
6194
|
// ============================================================================
|
|
6089
|
-
const
|
|
6090
|
-
|
|
6091
|
-
|
|
6092
|
-
|
|
6093
|
-
|
|
6195
|
+
const participates = (participation, minParticipation) => minParticipation === "all" ? participation === "all" : participation !== "none";
|
|
6196
|
+
const filterHandles = (handles, minParticipation) => handles.filter(h => participates(h.fitParticipation, minParticipation));
|
|
6197
|
+
const filterTargets = (targets, minParticipation) => targets.filter(t => participates(t.fitParticipation ?? "all", minParticipation));
|
|
6198
|
+
const isLoadingTarget = (target) => target.loading === true;
|
|
6199
|
+
const computeFitBounds = (handles, targets) => mergeBounds([...handles.map(h => h.getBounds()), ...targets.map(t => t.bounds)]);
|
|
6200
|
+
const warnStillLoading = (handles, targets, timeout) => {
|
|
6201
|
+
const names = [
|
|
6202
|
+
...handles.filter(h => h.loadsData && h.loading).map(h => h.name),
|
|
6203
|
+
...targets.filter(isLoadingTarget).map(t => t.name ?? "target"),
|
|
6204
|
+
];
|
|
6205
|
+
if (names.length === 0)
|
|
6206
|
+
return;
|
|
6207
|
+
consoleWarnMap("useFitToContent", `Timeout (${timeout}ms) reached. Fitting with available data. Still loading: ${names.join(", ")}`);
|
|
6094
6208
|
};
|
|
6095
|
-
const computeFitBounds = (handles) => mergeBounds(handles.map(h => h.getBounds()));
|
|
6096
6209
|
// ============================================================================
|
|
6097
6210
|
// Hook
|
|
6098
6211
|
// ============================================================================
|
|
6099
6212
|
/**
|
|
6100
6213
|
* `useFitToContent` -- orchestrates a one-time viewport fit once all
|
|
6101
|
-
* participating layers have loaded their initial data.
|
|
6214
|
+
* participating layers (and targets) have loaded their initial data.
|
|
6102
6215
|
*
|
|
6103
6216
|
* Only layers with `fitParticipation !== "none"` are waited on and included
|
|
6104
6217
|
* in the initial fit. `fitNow()` only includes `fitParticipation: "all"` layers.
|
|
6105
6218
|
*
|
|
6219
|
+
* Content that is not a layer joins through `targets`: a boundary the drawing
|
|
6220
|
+
* engine renders, a server-side extent. A target is filtered by its
|
|
6221
|
+
* `fitParticipation` as a layer is, and waited for while `loading`: the fit is
|
|
6222
|
+
* derived from the map's readiness, the layers' readiness and the targets on every
|
|
6223
|
+
* render until it has run, so a target that starts loading once the map is ready
|
|
6224
|
+
* holds the fit until it settles or the timeout fires.
|
|
6225
|
+
*
|
|
6106
6226
|
* A configurable timeout (default 10s) ensures the map fits to whatever
|
|
6107
|
-
* data is available if some layers are slow.
|
|
6227
|
+
* data is available if some layers or targets are slow.
|
|
6108
6228
|
*
|
|
6109
6229
|
* When using this hook alongside an adapter's `initialViewport`, note that the
|
|
6110
6230
|
* initial viewport serves as a loading-state viewport and will be overridden
|
|
@@ -6116,7 +6236,13 @@ const computeFitBounds = (handles) => mergeBounds(handles.map(h => h.getBounds()
|
|
|
6116
6236
|
* const shapes = useShapes({ id: "zones", ..., fitParticipation: "none" });
|
|
6117
6237
|
* const layers = useLayers(api, [markers, shapes]);
|
|
6118
6238
|
*
|
|
6119
|
-
*
|
|
6239
|
+
* // Memoized: the array is an input of the fit, so a new one per render would
|
|
6240
|
+
* // re-run the fit check and change `fitNow`.
|
|
6241
|
+
* const targets = useMemo(
|
|
6242
|
+
* (): ReadonlyArray<FitTarget> => [{ bounds: storedBoundaryBbox, fitParticipation: "initial" }],
|
|
6243
|
+
* [storedBoundaryBbox]
|
|
6244
|
+
* );
|
|
6245
|
+
* const { hasFitted, isWaiting, fitNow } = useFitToContent(api, layers.handles, { targets });
|
|
6120
6246
|
*
|
|
6121
6247
|
* return (
|
|
6122
6248
|
* <Map>
|
|
@@ -6127,68 +6253,118 @@ const computeFitBounds = (handles) => mergeBounds(handles.map(h => h.getBounds()
|
|
|
6127
6253
|
* ```
|
|
6128
6254
|
*/
|
|
6129
6255
|
const useFitToContent = (api, handles, options) => {
|
|
6130
|
-
const { disabled = false, padding = DEFAULT_PADDING, maxZoom = DEFAULT_MAX_ZOOM, timeout = DEFAULT_TIMEOUT, } = options ?? {};
|
|
6256
|
+
const { disabled = false, padding = DEFAULT_PADDING, maxZoom = DEFAULT_MAX_ZOOM, timeout = DEFAULT_TIMEOUT, targets = NO_FIT_TARGETS, } = options ?? {};
|
|
6131
6257
|
const [hasFitted, setHasFitted] = react.useState(false);
|
|
6258
|
+
// Set the moment the fit runs, ahead of the state: a render whose inputs changed while
|
|
6259
|
+
// `setHasFitted` is still pending must not fit again.
|
|
6260
|
+
const fittedRef = react.useRef(false);
|
|
6261
|
+
// The two inputs the layers and the clock contribute to the fit below: the ids of the
|
|
6262
|
+
// participating layers whose ready promises have resolved (null while none have), and
|
|
6263
|
+
// the timeout. Keyed on the layer id, which is stable, where handle objects are not: a
|
|
6264
|
+
// layer hook recreates its handle on an inline option, and consumers pass fresh arrays.
|
|
6265
|
+
const [readyIds, setReadyIds] = react.useState(null);
|
|
6266
|
+
const [timedOut, setTimedOut] = react.useState(false);
|
|
6132
6267
|
const isWaiting = !disabled && !hasFitted;
|
|
6133
|
-
|
|
6268
|
+
// The current handle objects, read when a wait or a fit runs and by `fitNow`, never
|
|
6269
|
+
// watched: only the participating ids below are an input.
|
|
6134
6270
|
const handlesRef = react.useRef(handles);
|
|
6135
6271
|
react.useEffect(() => {
|
|
6136
6272
|
handlesRef.current = handles;
|
|
6137
6273
|
}, [handles]);
|
|
6138
|
-
|
|
6274
|
+
const participatingKey = react.useMemo(() => filterHandles(handles, "initial")
|
|
6275
|
+
.map(h => h.id)
|
|
6276
|
+
.toSorted()
|
|
6277
|
+
.join("\u0000"), [handles]);
|
|
6278
|
+
const participatingIds = react.useMemo(() => (participatingKey === "" ? [] : participatingKey.split("\u0000")), [participatingKey]);
|
|
6279
|
+
const layersReady = readyIds !== null && participatingIds.every(id => readyIds.has(id));
|
|
6280
|
+
// ---- Layer readiness ----
|
|
6281
|
+
// A recreated map (Google theme switch, Mapbox style reload) drops readiness. Both inputs
|
|
6282
|
+
// reset then, so the wait and the timeout re-arm on the next ready and the new layers'
|
|
6283
|
+
// promises are awaited again before a fit that has not run yet. On a microtask, as the
|
|
6284
|
+
// other state here, so nothing is set synchronously inside an effect.
|
|
6285
|
+
react.useEffect(() => {
|
|
6286
|
+
if (api.state.isReady)
|
|
6287
|
+
return;
|
|
6288
|
+
void Promise.resolve().then(() => {
|
|
6289
|
+
setReadyIds(null);
|
|
6290
|
+
setTimedOut(false);
|
|
6291
|
+
});
|
|
6292
|
+
}, [api.state.isReady]);
|
|
6293
|
+
// Awaited whenever a participating id is not among the ready ones, so a layer that joins
|
|
6294
|
+
// while a target holds the fit is waited for too; a handle replaced by a new object with
|
|
6295
|
+
// the same id, or a new array of the same handles, awaits nothing and cancels nothing.
|
|
6296
|
+
// Promise.all([]) resolves on a microtask, so the state is never set synchronously
|
|
6297
|
+
// inside the effect.
|
|
6139
6298
|
react.useEffect(() => {
|
|
6140
|
-
if (!api.state.isReady ||
|
|
6299
|
+
if (!api.state.isReady || disabled || hasFitted || layersReady)
|
|
6141
6300
|
return;
|
|
6142
|
-
const participating = filterHandles(handlesRef.current, "initial");
|
|
6143
6301
|
let cancelled = false;
|
|
6144
|
-
const
|
|
6145
|
-
|
|
6302
|
+
const pending = filterHandles(handlesRef.current, "initial").filter(h => !(readyIds?.has(h.id) ?? false));
|
|
6303
|
+
const pendingIds = pending.map(h => h.id);
|
|
6304
|
+
void Promise.all(pending.map(h => h.ready)).then(() => {
|
|
6305
|
+
if (cancelled)
|
|
6146
6306
|
return;
|
|
6147
|
-
|
|
6148
|
-
|
|
6307
|
+
setReadyIds(previous => new Set([...(previous ?? []), ...pendingIds]));
|
|
6308
|
+
});
|
|
6309
|
+
return () => {
|
|
6310
|
+
cancelled = true;
|
|
6149
6311
|
};
|
|
6150
|
-
|
|
6151
|
-
|
|
6312
|
+
}, [api.state.isReady, disabled, hasFitted, layersReady, participatingKey, readyIds]);
|
|
6313
|
+
// ---- Timeout: bounds the wait for layers and targets alike ----
|
|
6314
|
+
react.useEffect(() => {
|
|
6315
|
+
if (!api.state.isReady || disabled || hasFitted || timedOut)
|
|
6316
|
+
return;
|
|
6317
|
+
const timeoutId = setTimeout(() => setTimedOut(true), timeout);
|
|
6318
|
+
return () => clearTimeout(timeoutId);
|
|
6319
|
+
}, [api.state.isReady, disabled, hasFitted, timedOut, timeout]);
|
|
6320
|
+
// ---- The initial fit, derived from its inputs ----
|
|
6321
|
+
react.useEffect(() => {
|
|
6322
|
+
if (hasFitted || fittedRef.current || disabled || !api.state.isReady)
|
|
6323
|
+
return;
|
|
6324
|
+
const fitTargets = filterTargets(targets, "initial");
|
|
6325
|
+
const waiting = !layersReady || fitTargets.some(isLoadingTarget);
|
|
6326
|
+
if (waiting && !timedOut)
|
|
6327
|
+
return;
|
|
6328
|
+
let cancelled = false;
|
|
6329
|
+
// On a microtask, as the readiness above, so the state is never set synchronously
|
|
6330
|
+
// inside the effect; a cleanup in between hands the fit to the next run instead of
|
|
6331
|
+
// fitting twice.
|
|
6332
|
+
void Promise.resolve().then(() => {
|
|
6333
|
+
if (cancelled || fittedRef.current)
|
|
6152
6334
|
return;
|
|
6335
|
+
fittedRef.current = true;
|
|
6153
6336
|
const fitHandles = filterHandles(handlesRef.current, "initial");
|
|
6154
|
-
|
|
6337
|
+
if (waiting)
|
|
6338
|
+
warnStillLoading(fitHandles, fitTargets, timeout);
|
|
6339
|
+
const bounds = computeFitBounds(fitHandles, fitTargets);
|
|
6155
6340
|
if (bounds !== null) {
|
|
6156
6341
|
void api.actions.fitBounds(bounds, { padding, maxZoom, animate: false });
|
|
6157
6342
|
}
|
|
6158
|
-
|
|
6159
|
-
};
|
|
6160
|
-
const readyPromises = participating.map(h => h.ready);
|
|
6161
|
-
const timeoutId = setTimeout(() => {
|
|
6162
|
-
if (cancelled)
|
|
6163
|
-
return;
|
|
6164
|
-
const stillPending = filterHandles(handlesRef.current, "initial").filter(h => h.loadsData && h.loading);
|
|
6165
|
-
if (stillPending.length > 0) {
|
|
6166
|
-
const names = stillPending.map(h => h.name).join(", ");
|
|
6167
|
-
consoleWarnMap("useFitToContent", `Timeout (${timeout}ms) reached. Fitting with available data. Still loading: ${names}`);
|
|
6168
|
-
}
|
|
6169
|
-
performFit();
|
|
6170
|
-
}, timeout);
|
|
6171
|
-
// When participating is empty, Promise.all([]) resolves on the next microtask,
|
|
6172
|
-
// which avoids the synchronous-setState-in-effect lint rule.
|
|
6173
|
-
void Promise.all(readyPromises).then(() => {
|
|
6174
|
-
if (cancelled)
|
|
6175
|
-
return;
|
|
6176
|
-
clearTimeout(timeoutId);
|
|
6177
|
-
performFit();
|
|
6343
|
+
setHasFitted(true);
|
|
6178
6344
|
});
|
|
6179
6345
|
return () => {
|
|
6180
6346
|
cancelled = true;
|
|
6181
|
-
clearTimeout(timeoutId);
|
|
6182
6347
|
};
|
|
6183
|
-
}, [
|
|
6348
|
+
}, [
|
|
6349
|
+
api.actions,
|
|
6350
|
+
api.state.isReady,
|
|
6351
|
+
disabled,
|
|
6352
|
+
hasFitted,
|
|
6353
|
+
layersReady,
|
|
6354
|
+
maxZoom,
|
|
6355
|
+
padding,
|
|
6356
|
+
participatingKey,
|
|
6357
|
+
targets,
|
|
6358
|
+
timedOut,
|
|
6359
|
+
timeout,
|
|
6360
|
+
]);
|
|
6184
6361
|
// ---- fitNow: manual re-fit ----
|
|
6185
6362
|
const fitNow = react.useCallback(() => {
|
|
6186
|
-
const
|
|
6187
|
-
const bounds = computeFitBounds(fitHandles);
|
|
6363
|
+
const bounds = computeFitBounds(filterHandles(handlesRef.current, "all"), filterTargets(targets, "all"));
|
|
6188
6364
|
if (bounds !== null) {
|
|
6189
6365
|
void api.actions.fitBounds(bounds, { padding, maxZoom, animate: true });
|
|
6190
6366
|
}
|
|
6191
|
-
}, [api.actions, padding,
|
|
6367
|
+
}, [api.actions, maxZoom, padding, targets]);
|
|
6192
6368
|
return react.useMemo(() => ({ hasFitted, isWaiting, fitNow }), [hasFitted, isWaiting, fitNow]);
|
|
6193
6369
|
};
|
|
6194
6370
|
|
|
@@ -13839,6 +14015,10 @@ Object.defineProperty(exports, "mapTypeSchema", {
|
|
|
13839
14015
|
enumerable: true,
|
|
13840
14016
|
get: function () { return reactMapAdapterShared.mapTypeSchema; }
|
|
13841
14017
|
});
|
|
14018
|
+
Object.defineProperty(exports, "toDrawValue", {
|
|
14019
|
+
enumerable: true,
|
|
14020
|
+
get: function () { return reactMapAdapterShared.toDrawValue; }
|
|
14021
|
+
});
|
|
13842
14022
|
exports.ClusterMarker = ClusterMarker;
|
|
13843
14023
|
exports.ClusterStick = ClusterStick;
|
|
13844
14024
|
exports.Controls = Controls;
|
|
@@ -13856,6 +14036,7 @@ exports.MARKER_TUNING = MARKER_TUNING;
|
|
|
13856
14036
|
exports.MapLoadingState = MapLoadingState;
|
|
13857
14037
|
exports.MapMarker = MapMarker;
|
|
13858
14038
|
exports.MapMarkerIcon = MapMarkerIcon;
|
|
14039
|
+
exports.NO_FIT_TARGETS = NO_FIT_TARGETS;
|
|
13859
14040
|
exports.PanelIconButton = PanelIconButton;
|
|
13860
14041
|
exports.ShapeAnnotationLabel = ShapeAnnotationLabel;
|
|
13861
14042
|
exports.buildExpandedIds = buildExpandedIds;
|