@trackunit/react-components 3.8.3-alpha-e1e6a0f33ce.0 → 3.8.4
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 +813 -369
- package/index.esm.js +813 -371
- package/package.json +6 -6
- package/src/components/Tag/Tag.d.ts +16 -9
- package/src/components/Tag/Tag.variants.d.ts +6 -0
- package/src/hooks/persistence/useHashParamSync.d.ts +55 -0
- package/src/hooks/persistence/useMigrateLegacySearchParam.d.ts +62 -0
- package/src/hooks/persistence/usePersistedState.d.ts +44 -35
- package/src/hooks/persistence/useSearchParamSync.d.ts +26 -7
- package/src/index.d.ts +1 -0
- package/src/hooks/persistence/useUrlParamSync.d.ts +0 -71
package/index.cjs.js
CHANGED
|
@@ -2361,6 +2361,7 @@ const cvaTagText = cssClassVarianceUtilities.cva({
|
|
|
2361
2361
|
},
|
|
2362
2362
|
});
|
|
2363
2363
|
const cvaTagIconContainer = cssClassVarianceUtilities.cva({ base: ["shrink-0", "inline-flex", "self-center"] });
|
|
2364
|
+
const cvaTagDismissButton = cssClassVarianceUtilities.cva({ base: ["inline-flex", "rounded-full", "focus-visible:outline-native"] });
|
|
2364
2365
|
const cvaTagIcon = cssClassVarianceUtilities.cva({
|
|
2365
2366
|
base: ["cursor-pointer", "transition-opacity", "hover:opacity-70", "text-neutral-500"],
|
|
2366
2367
|
});
|
|
@@ -2414,9 +2415,11 @@ const TAG_TEXT_MIN_WIDTH_PX = sharedUtils.parseTailwindArbitraryValue(TAG_TEXT_M
|
|
|
2414
2415
|
* @param {TagProps} props - The props for the Tag component.
|
|
2415
2416
|
* @returns {ReactElement} The rendered Tag component.
|
|
2416
2417
|
*/
|
|
2417
|
-
const Tag = ({ className, "data-testid": dataTestId, children, size = "medium", onClickClose, color = "info", disabled = false, ref, icon, onMouseEnter, style, removeTagLabel, }) => {
|
|
2418
|
+
const Tag = ({ className, "data-testid": dataTestId, children, size = "medium", onClickClose, color = "info", disabled = false, ref, icon, onMouseEnter, style, removeTagLabel, removeButtonInTabOrder = true, }) => {
|
|
2418
2419
|
const textRef = react.useRef(null);
|
|
2419
2420
|
const [shouldTruncate, setShouldTruncate] = react.useState(false);
|
|
2421
|
+
const textId = react.useId();
|
|
2422
|
+
const removeButtonId = react.useId();
|
|
2420
2423
|
react.useLayoutEffect(() => {
|
|
2421
2424
|
// Using simple DOM measurements to avoid the complexity of the useMeasure hook.
|
|
2422
2425
|
// Resize observers have some overhead and we don't need the full power of the useMeasure hook here.
|
|
@@ -2428,28 +2431,22 @@ const Tag = ({ className, "data-testid": dataTestId, children, size = "medium",
|
|
|
2428
2431
|
setShouldTruncate(width >= TAG_TEXT_MIN_WIDTH_PX);
|
|
2429
2432
|
}
|
|
2430
2433
|
}, [children]);
|
|
2431
|
-
const isSupportedDismissColor = react.useMemo(() => {
|
|
2432
|
-
if (color === "neutral" || color === "primary" || color === "white" || color === "info") {
|
|
2433
|
-
return true;
|
|
2434
|
-
}
|
|
2435
|
-
return false;
|
|
2436
|
-
}, [color]);
|
|
2437
2434
|
const layout = react.useMemo(() => {
|
|
2438
|
-
if (onClickClose !== undefined &&
|
|
2435
|
+
if (onClickClose !== undefined && !disabled) {
|
|
2439
2436
|
return "containsDismiss";
|
|
2440
2437
|
}
|
|
2441
2438
|
if (icon !== null && icon !== undefined) {
|
|
2442
2439
|
return "containsIcon";
|
|
2443
2440
|
}
|
|
2444
2441
|
return "default";
|
|
2445
|
-
}, [onClickClose,
|
|
2442
|
+
}, [onClickClose, disabled, icon]);
|
|
2446
2443
|
return (jsxRuntime.jsxs("div", { className: cvaTag({
|
|
2447
2444
|
className,
|
|
2448
2445
|
size,
|
|
2449
2446
|
color,
|
|
2450
2447
|
layout,
|
|
2451
2448
|
border: color === "white" ? "default" : "none",
|
|
2452
|
-
}), "data-testid": dataTestId, onMouseEnter: onMouseEnter, ref: ref, style: style, children: [icon !== null && icon !== undefined && size === "medium" ? (jsxRuntime.jsx("div", { className: cvaTagIconContainer(), "data-slot": "icon", children: icon })) : null, jsxRuntime.jsx("span", { className: cvaTagText({ truncate: shouldTruncate }), ref: textRef, children: children }), Boolean(onClickClose) &&
|
|
2449
|
+
}), "data-testid": dataTestId, onMouseEnter: onMouseEnter, ref: ref, style: style, children: [icon !== null && icon !== undefined && size === "medium" ? (jsxRuntime.jsx("div", { className: cvaTagIconContainer(), "data-slot": "icon", children: icon })) : null, jsxRuntime.jsx("span", { className: cvaTagText({ truncate: shouldTruncate }), id: textId, ref: textRef, children: children }), Boolean(onClickClose) && size === "medium" && !disabled ? (jsxRuntime.jsx("div", { className: cvaTagIconContainer(), "data-slot": "dismiss", onClick: onClickClose, children: jsxRuntime.jsx(Tooltip, { disabled: disabled, label: removeTagLabel, placement: "bottom", children: jsxRuntime.jsx("button", { "aria-label": removeTagLabel, "aria-labelledby": `${removeButtonId} ${textId}`, className: cvaTagDismissButton(), id: removeButtonId, tabIndex: removeButtonInTabOrder ? undefined : -1, type: "button", children: jsxRuntime.jsx(Icon, { ariaHidden: true, className: cvaTagIcon(), "data-testid": `${dataTestId}Icon`, name: "XCircle", size: "small", style: { WebkitTransition: "-webkit-transform 0.150s" }, type: "solid" }) }) }) })) : null] }));
|
|
2453
2450
|
};
|
|
2454
2451
|
|
|
2455
2452
|
// Mirrors the slug logic in @trackunit/storybook-docs-components SectionName so anchors line up
|
|
@@ -7136,7 +7133,7 @@ const cvaLabeledValueLabel = cssClassVarianceUtilities.cva({
|
|
|
7136
7133
|
orientation: "horizontal",
|
|
7137
7134
|
},
|
|
7138
7135
|
});
|
|
7139
|
-
const cvaLabeledValueValue = cssClassVarianceUtilities.cva({ base: ["min-w-0", "font-
|
|
7136
|
+
const cvaLabeledValueValue = cssClassVarianceUtilities.cva({ base: ["min-w-0", "font-normal", "text-neutral-900"] });
|
|
7140
7137
|
const cvaLabeledValueList = cssClassVarianceUtilities.cva({ base: ["flex", "flex-col", "gap-4"] });
|
|
7141
7138
|
const cvaLabeledValueTooltip = cssClassVarianceUtilities.cva({ base: ["ml-1", "inline-flex", "align-sub"] });
|
|
7142
7139
|
|
|
@@ -12750,7 +12747,7 @@ const cvaToggleGroup = cssClassVarianceUtilities.cva({
|
|
|
12750
12747
|
base: ["inline-flex", "p-0.5", "bg-neutral-200", "rounded-md", "gap-1", "relative"],
|
|
12751
12748
|
});
|
|
12752
12749
|
const cvaToggleItem = cssClassVarianceUtilities.cva({
|
|
12753
|
-
base: ["z-10", "group"],
|
|
12750
|
+
base: ["z-10", "group", "cursor-pointer", "disabled:cursor-not-allowed"],
|
|
12754
12751
|
variants: {
|
|
12755
12752
|
selected: {
|
|
12756
12753
|
true: [],
|
|
@@ -13481,90 +13478,6 @@ const useSessionStorage = (options) => useWebStorage(globalThis.sessionStorage,
|
|
|
13481
13478
|
*/
|
|
13482
13479
|
const useSessionStorageReducer = (options) => useWebStorageReducer(globalThis.sessionStorage, options);
|
|
13483
13480
|
|
|
13484
|
-
/**
|
|
13485
|
-
* Pure utilities for stamping a URL-persisted value with the identity that
|
|
13486
|
-
* wrote it.
|
|
13487
|
-
*
|
|
13488
|
-
* A URL (hash or search param) is shared by every account that uses the same
|
|
13489
|
-
* browser: it survives login redirects, history and bookmarks, and it takes
|
|
13490
|
-
* precedence over per-user localStorage when a page loads. Without a stamp
|
|
13491
|
-
* there is no way to tell "a colleague shared this link" from "the previous
|
|
13492
|
-
* account on this PC left its layout in the address bar" — and the second
|
|
13493
|
-
* case silently replaces the current user's saved state (GLU-2396).
|
|
13494
|
-
*
|
|
13495
|
-
* The stamp is a short, non-reversible fingerprint of `clientSideUserId`.
|
|
13496
|
-
* It is not a secret and not a security boundary; it only lets a reader
|
|
13497
|
-
* recognise a value written by a *different* identity on the same device.
|
|
13498
|
-
*/
|
|
13499
|
-
/**
|
|
13500
|
-
* Wire shape of a stamped URL value: `{ o: <fingerprint>, v: <payload> }`.
|
|
13501
|
-
* Values written before stamping existed are bare payloads and decode as
|
|
13502
|
-
* unowned (see {@link unwrapUrlOwner}).
|
|
13503
|
-
*/
|
|
13504
|
-
const stampedUrlValueSchema = zod.z.object({
|
|
13505
|
-
o: zod.z.string(),
|
|
13506
|
-
v: zod.z.unknown(),
|
|
13507
|
-
});
|
|
13508
|
-
const FNV_OFFSET_BASIS = 0x811c9dc5;
|
|
13509
|
-
const FNV_PRIME = 0x01000193;
|
|
13510
|
-
/**
|
|
13511
|
-
* 32-bit FNV-1a of `identity`, rendered in base36 (≤ 7 chars).
|
|
13512
|
-
*
|
|
13513
|
-
* Synchronous and dependency-free so it can run inside a `useState`
|
|
13514
|
-
* initializer. Collisions are possible in theory but irrelevant here: a
|
|
13515
|
-
* collision can only make a foreign value look like the reader's own, which
|
|
13516
|
-
* is today's behaviour for every value.
|
|
13517
|
-
*
|
|
13518
|
-
* @param identity - The client-side user id to fingerprint.
|
|
13519
|
-
* @returns {string} A short stable fingerprint of `identity`.
|
|
13520
|
-
*/
|
|
13521
|
-
const identityFingerprint = (identity) => {
|
|
13522
|
-
let hash = FNV_OFFSET_BASIS;
|
|
13523
|
-
for (let index = 0; index < identity.length; index++) {
|
|
13524
|
-
hash ^= identity.charCodeAt(index);
|
|
13525
|
-
hash = Math.imul(hash, FNV_PRIME) >>> 0;
|
|
13526
|
-
}
|
|
13527
|
-
return hash.toString(36);
|
|
13528
|
-
};
|
|
13529
|
-
/**
|
|
13530
|
-
* Wraps a URL payload with the fingerprint of the identity writing it.
|
|
13531
|
-
*
|
|
13532
|
-
* @param value - The payload that would otherwise be encoded into the URL.
|
|
13533
|
-
* @param owner - Fingerprint of the writing identity (see {@link identityFingerprint}).
|
|
13534
|
-
* @returns {StampedUrlValue} The payload wrapped in its ownership envelope.
|
|
13535
|
-
*/
|
|
13536
|
-
const wrapUrlOwner = (value, owner) => ({ o: owner, v: value });
|
|
13537
|
-
/**
|
|
13538
|
-
* Splits a decoded URL value into its owner fingerprint and payload.
|
|
13539
|
-
* Bare (pre-stamping) payloads come back with `owner: undefined`.
|
|
13540
|
-
*
|
|
13541
|
-
* @param decoded - The decoded URL value, stamped or bare.
|
|
13542
|
-
* @returns {{ owner: string | undefined; value: unknown }} The owner fingerprint (if any) and the payload.
|
|
13543
|
-
*/
|
|
13544
|
-
const unwrapUrlOwner = (decoded) => {
|
|
13545
|
-
const stamped = stampedUrlValueSchema.safeParse(decoded);
|
|
13546
|
-
// `z.unknown()` accepts a missing key, so `{ o: "x" }` parses without `v`.
|
|
13547
|
-
// Such an object is a payload of its own, not an envelope; the `in` check
|
|
13548
|
-
// is what keeps it unowned. Do not remove it as redundant.
|
|
13549
|
-
return stamped.success && "v" in stamped.data
|
|
13550
|
-
? { owner: stamped.data.o, value: stamped.data.v }
|
|
13551
|
-
: { owner: undefined, value: decoded };
|
|
13552
|
-
};
|
|
13553
|
-
|
|
13554
|
-
/**
|
|
13555
|
-
* Generates a localStorage key, optionally scoped to a specific user.
|
|
13556
|
-
*
|
|
13557
|
-
* When `userId` is provided the key is `"key-userId"`.
|
|
13558
|
-
* When omitted the key is returned as-is (unscoped).
|
|
13559
|
-
*
|
|
13560
|
-
* @param key - Unique persistence identifier.
|
|
13561
|
-
* @param userId - Client-side user id to scope storage per user.
|
|
13562
|
-
* @returns {string} The combined storage key.
|
|
13563
|
-
*/
|
|
13564
|
-
const useStorageKey = (key, userId) => {
|
|
13565
|
-
return react.useMemo(() => (userId ? `${key}-${userId}` : key), [key, userId]);
|
|
13566
|
-
};
|
|
13567
|
-
|
|
13568
13481
|
/**
|
|
13569
13482
|
* Pure utilities for reading and writing single named entries inside a URL
|
|
13570
13483
|
* fragment (the part after `#`).
|
|
@@ -13693,6 +13606,183 @@ const writeHashKey = (hash, key, value) => {
|
|
|
13693
13606
|
return formatHash(next.join(TOKEN_SEPARATOR));
|
|
13694
13607
|
};
|
|
13695
13608
|
|
|
13609
|
+
/**
|
|
13610
|
+
* Default maximum length of the resulting URL fragment after adding one
|
|
13611
|
+
* persisted entry. Oversized new entries are skipped; oversized replacements
|
|
13612
|
+
* remove the stale entry so localStorage remains authoritative.
|
|
13613
|
+
*
|
|
13614
|
+
* The fragment is never sent to the server, so it is not subject to the
|
|
13615
|
+
* AWS WAF managed-rule `SizeRestrictions_QUERYSTRING` cap that applies to
|
|
13616
|
+
* search params (5000 bytes). 64 KB stays well below typical browser URL
|
|
13617
|
+
* limits (Chromium ≳ 100 KB, Firefox ≳ 64 KB on the address bar) while
|
|
13618
|
+
* still leaving generous headroom for any realistic table state.
|
|
13619
|
+
*/
|
|
13620
|
+
const MAX_HASH_LENGTH = 64 * 1024;
|
|
13621
|
+
/**
|
|
13622
|
+
* Syncs an encoded string value with a single named entry inside the URL
|
|
13623
|
+
* fragment (`location.hash`) via Tanstack Router.
|
|
13624
|
+
*
|
|
13625
|
+
* Behaviour mirrors `useSearchParamSync`, with two differences:
|
|
13626
|
+
* - Reads from and writes to `location.hash` instead of `location.search`.
|
|
13627
|
+
* - Oversized replacements remove stale values using
|
|
13628
|
+
* {@link MAX_HASH_LENGTH}, rather than the AWS-WAF-driven search-param cap.
|
|
13629
|
+
*
|
|
13630
|
+
* The fragment is treated as a sequence of `&`-separated tokens via the
|
|
13631
|
+
* pure utilities in `./hashFragment`. Foreign tokens (bare anchors, other
|
|
13632
|
+
* named entries) are preserved byte-for-byte on every write.
|
|
13633
|
+
*
|
|
13634
|
+
* @param options - Configuration for the hash entry sync.
|
|
13635
|
+
* @param options.key - The named entry inside the fragment.
|
|
13636
|
+
* @param options.enabled - Set to `false` to disable all URL interaction (default `true`).
|
|
13637
|
+
* @param options.onExternalChange - Called when the entry changes externally
|
|
13638
|
+
* (e.g. browser back/forward, pasted link, foreign router push).
|
|
13639
|
+
* @param options.replace - `true` to always use `replaceState` instead of pushState.
|
|
13640
|
+
*/
|
|
13641
|
+
const useHashParamSync = ({ key, enabled = true, onExternalChange, replace: replaceOption, }) => {
|
|
13642
|
+
const navigate = reactRouter.useNavigate();
|
|
13643
|
+
const location = reactRouter.useLocation();
|
|
13644
|
+
const router = reactRouter.useRouter();
|
|
13645
|
+
const lastWrittenRef = react.useRef(undefined);
|
|
13646
|
+
const pendingWriteRef = react.useRef(null);
|
|
13647
|
+
const onExternalChangeRef = react.useRef(onExternalChange);
|
|
13648
|
+
react.useEffect(() => {
|
|
13649
|
+
onExternalChangeRef.current = onExternalChange;
|
|
13650
|
+
}, [onExternalChange]);
|
|
13651
|
+
const currentHashValue = react.useMemo(() => {
|
|
13652
|
+
if (!enabled) {
|
|
13653
|
+
return undefined;
|
|
13654
|
+
}
|
|
13655
|
+
return readHashKey(location.hash, key);
|
|
13656
|
+
}, [enabled, location.hash, key]);
|
|
13657
|
+
react.useEffect(() => {
|
|
13658
|
+
if (!enabled) {
|
|
13659
|
+
return;
|
|
13660
|
+
}
|
|
13661
|
+
if (currentHashValue === undefined) {
|
|
13662
|
+
return;
|
|
13663
|
+
}
|
|
13664
|
+
if (currentHashValue === lastWrittenRef.current) {
|
|
13665
|
+
return;
|
|
13666
|
+
}
|
|
13667
|
+
if (lastWrittenRef.current === undefined) {
|
|
13668
|
+
return;
|
|
13669
|
+
}
|
|
13670
|
+
// A caller may have primed `lastWrittenRef` via `updateHashParam` while the
|
|
13671
|
+
// URL still carries the previous value (queued rAF / router pending). Treating
|
|
13672
|
+
// that stale URL as an external change reloads filter state from persistence
|
|
13673
|
+
// and can clear in-progress search input before the write lands.
|
|
13674
|
+
if (pendingWriteRef.current !== null) {
|
|
13675
|
+
return;
|
|
13676
|
+
}
|
|
13677
|
+
requestAnimationFrame(() => {
|
|
13678
|
+
onExternalChangeRef.current?.();
|
|
13679
|
+
});
|
|
13680
|
+
}, [currentHashValue, enabled]);
|
|
13681
|
+
// Writes are dispatched via a "pending write" queue rather than calling
|
|
13682
|
+
// `navigate` directly from inside the rAF callback. Tanstack Router's
|
|
13683
|
+
// `router.state.status === "pending"` is common during the first paint
|
|
13684
|
+
// of a route (loaders, suspense), and an earlier implementation that
|
|
13685
|
+
// simply returned in that case lost the write outright. A one-shot write
|
|
13686
|
+
// (a legacy search-param migrated into the hash, or the first edit)
|
|
13687
|
+
// would otherwise never land.
|
|
13688
|
+
//
|
|
13689
|
+
// The queue + retry pattern below makes writes reliable:
|
|
13690
|
+
// - `updateHashParam` stores the latest attempted write in
|
|
13691
|
+
// `pendingWriteRef` and schedules an rAF flush.
|
|
13692
|
+
// - `flushPendingWrite` only navigates when the router is idle; while
|
|
13693
|
+
// pending it leaves the write queued so it can fire later.
|
|
13694
|
+
// - A dedicated effect watches `router.state.status` and re-attempts
|
|
13695
|
+
// the flush whenever the router settles, draining the queue.
|
|
13696
|
+
const flushPendingWrite = react.useCallback(() => {
|
|
13697
|
+
const pending = pendingWriteRef.current;
|
|
13698
|
+
if (pending === null) {
|
|
13699
|
+
return;
|
|
13700
|
+
}
|
|
13701
|
+
if (router.state.status === "pending") {
|
|
13702
|
+
// Keep the write queued; the status-watcher effect below will retry
|
|
13703
|
+
// when the router transitions back to idle.
|
|
13704
|
+
return;
|
|
13705
|
+
}
|
|
13706
|
+
pendingWriteRef.current = null;
|
|
13707
|
+
const { encodedValue, options } = pending;
|
|
13708
|
+
let nextHash = writeHashKey(location.hash, key, encodedValue);
|
|
13709
|
+
let removedOversizedValue = false;
|
|
13710
|
+
if (nextHash.length > MAX_HASH_LENGTH) {
|
|
13711
|
+
if (currentHashValue === undefined) {
|
|
13712
|
+
return;
|
|
13713
|
+
}
|
|
13714
|
+
nextHash = writeHashKey(location.hash, key, undefined);
|
|
13715
|
+
removedOversizedValue = true;
|
|
13716
|
+
}
|
|
13717
|
+
const shouldReplace = removedOversizedValue
|
|
13718
|
+
? true
|
|
13719
|
+
: (options?.replace ?? replaceOption ?? !Boolean(currentHashValue));
|
|
13720
|
+
// Tanstack Router's `navigate({ hash })` expects the fragment body
|
|
13721
|
+
// *without* the leading `#` — the router adds the delimiter itself
|
|
13722
|
+
// when serialising the URL. Forwarding the `#`-prefixed value from
|
|
13723
|
+
// `writeHashKey` produces a doubled `##` in the address bar
|
|
13724
|
+
// (visually broken, even though browsers still parse the fragment
|
|
13725
|
+
// correctly because URL fragments start at the *first* `#`).
|
|
13726
|
+
const navigateHash = nextHash.startsWith("#") ? nextHash.slice(1) : nextHash;
|
|
13727
|
+
void navigate({
|
|
13728
|
+
to: ".",
|
|
13729
|
+
// Returning the same `prev` reference leaves the search params
|
|
13730
|
+
// unchanged. We must still pass `search` so router types are happy.
|
|
13731
|
+
search: (prev) => prev,
|
|
13732
|
+
hash: navigateHash,
|
|
13733
|
+
replace: shouldReplace,
|
|
13734
|
+
});
|
|
13735
|
+
}, [router.state.status, location.hash, key, currentHashValue, navigate, replaceOption]);
|
|
13736
|
+
react.useEffect(() => {
|
|
13737
|
+
if (router.state.status === "pending") {
|
|
13738
|
+
return;
|
|
13739
|
+
}
|
|
13740
|
+
if (pendingWriteRef.current === null) {
|
|
13741
|
+
return;
|
|
13742
|
+
}
|
|
13743
|
+
flushPendingWrite();
|
|
13744
|
+
}, [router.state.status, flushPendingWrite]);
|
|
13745
|
+
// Drop any queued write when the consumer unmounts. The queue + retry
|
|
13746
|
+
// pattern above keeps writes pending across a `router.state.status ===
|
|
13747
|
+
// "pending"` phase, which means a write scheduled just before a route
|
|
13748
|
+
// change could otherwise drain onto the *next* route once it settles.
|
|
13749
|
+
// Cancelling here preserves the original "writes are scoped to the
|
|
13750
|
+
// owning route" contract that the pre-queue implementation got for
|
|
13751
|
+
// free by dropping the write outright.
|
|
13752
|
+
react.useEffect(() => () => {
|
|
13753
|
+
pendingWriteRef.current = null;
|
|
13754
|
+
}, []);
|
|
13755
|
+
const updateHashParam = react.useCallback((encodedValue, options) => {
|
|
13756
|
+
if (!enabled) {
|
|
13757
|
+
return;
|
|
13758
|
+
}
|
|
13759
|
+
// Dedupe against either the last *committed* write or the value
|
|
13760
|
+
// currently queued for the next rAF. Both represent the caller's
|
|
13761
|
+
// intent so we don't schedule redundant rAF callbacks for identical
|
|
13762
|
+
// requests.
|
|
13763
|
+
const inFlightOrLastWritten = pendingWriteRef.current?.encodedValue ?? lastWrittenRef.current;
|
|
13764
|
+
if (encodedValue !== undefined && encodedValue === inFlightOrLastWritten) {
|
|
13765
|
+
return;
|
|
13766
|
+
}
|
|
13767
|
+
// Prime `lastWrittenRef` here (not inside `flushPendingWrite`) so
|
|
13768
|
+
// the external-change detector treats this value as the caller's
|
|
13769
|
+
// authoritative state even when the flush is a no-op (URL already
|
|
13770
|
+
// matches) or stays queued during a pending router phase. Without
|
|
13771
|
+
// priming, the next "external" change would look identical to the
|
|
13772
|
+
// initial render (`lastWrittenRef === undefined`) and the callback
|
|
13773
|
+
// would be skipped.
|
|
13774
|
+
lastWrittenRef.current = encodedValue;
|
|
13775
|
+
if (currentHashValue === encodedValue) {
|
|
13776
|
+
return;
|
|
13777
|
+
}
|
|
13778
|
+
pendingWriteRef.current = { encodedValue, options };
|
|
13779
|
+
requestAnimationFrame(() => {
|
|
13780
|
+
flushPendingWrite();
|
|
13781
|
+
});
|
|
13782
|
+
}, [enabled, currentHashValue, flushPendingWrite]);
|
|
13783
|
+
return react.useMemo(() => ({ searchValue: currentHashValue, updateSearchParam: updateHashParam }), [currentHashValue, updateHashParam]);
|
|
13784
|
+
};
|
|
13785
|
+
|
|
13696
13786
|
const searchRecordSchema = zod.z.record(zod.z.string(), zod.z.unknown());
|
|
13697
13787
|
const primitiveSearchValueSchema = zod.z.union([zod.z.string(), zod.z.number(), zod.z.boolean()]);
|
|
13698
13788
|
/**
|
|
@@ -13715,187 +13805,373 @@ const readPrimitiveSearchParam = (search, key) => {
|
|
|
13715
13805
|
};
|
|
13716
13806
|
|
|
13717
13807
|
/**
|
|
13718
|
-
*
|
|
13719
|
-
*
|
|
13808
|
+
* Pure utilities for stamping a URL-persisted value with the identity that
|
|
13809
|
+
* wrote it.
|
|
13720
13810
|
*
|
|
13721
|
-
*
|
|
13722
|
-
*
|
|
13723
|
-
*
|
|
13811
|
+
* A URL (hash or search param) is shared by every account that uses the same
|
|
13812
|
+
* browser: it survives login redirects, history and bookmarks, and it takes
|
|
13813
|
+
* precedence over per-user localStorage when a page loads. Without a stamp
|
|
13814
|
+
* there is no way to tell "a colleague shared this link" from "the previous
|
|
13815
|
+
* account on this PC left its layout in the address bar" — and the second
|
|
13816
|
+
* case silently replaces the current user's saved state (GLU-2396).
|
|
13817
|
+
*
|
|
13818
|
+
* The stamp is a short, non-reversible fingerprint of `clientSideUserId`.
|
|
13819
|
+
* It is not a secret and not a security boundary; it only lets a reader
|
|
13820
|
+
* recognise a value written by a *different* identity on the same device.
|
|
13724
13821
|
*/
|
|
13725
|
-
const MAX_URL_LENGTH = 5000;
|
|
13726
13822
|
/**
|
|
13727
|
-
*
|
|
13728
|
-
*
|
|
13729
|
-
*
|
|
13823
|
+
* Wire shape of a stamped URL value: `{ o: <fingerprint>, v: <payload> }`.
|
|
13824
|
+
* Values written before stamping existed are bare payloads and decode as
|
|
13825
|
+
* unowned (see {@link unwrapUrlOwner}).
|
|
13826
|
+
*/
|
|
13827
|
+
const stampedUrlValueSchema = zod.z.object({
|
|
13828
|
+
o: zod.z.string(),
|
|
13829
|
+
v: zod.z.unknown(),
|
|
13830
|
+
});
|
|
13831
|
+
const FNV_OFFSET_BASIS = 0x811c9dc5;
|
|
13832
|
+
const FNV_PRIME = 0x01000193;
|
|
13833
|
+
/**
|
|
13834
|
+
* 32-bit FNV-1a of `identity`, rendered in base36 (≤ 7 chars).
|
|
13835
|
+
*
|
|
13836
|
+
* Synchronous and dependency-free so it can run inside a `useState`
|
|
13837
|
+
* initializer. Collisions are possible in theory but irrelevant here: a
|
|
13838
|
+
* collision can only make a foreign value look like the reader's own, which
|
|
13839
|
+
* is today's behaviour for every value.
|
|
13730
13840
|
*
|
|
13731
|
-
*
|
|
13732
|
-
*
|
|
13733
|
-
* Firefox ≳ 64 KB on the address bar) while leaving generous headroom for any
|
|
13734
|
-
* realistic table state.
|
|
13841
|
+
* @param identity - The client-side user id to fingerprint.
|
|
13842
|
+
* @returns {string} A short stable fingerprint of `identity`.
|
|
13735
13843
|
*/
|
|
13736
|
-
const
|
|
13844
|
+
const identityFingerprint = (identity) => {
|
|
13845
|
+
let hash = FNV_OFFSET_BASIS;
|
|
13846
|
+
for (let index = 0; index < identity.length; index++) {
|
|
13847
|
+
hash ^= identity.charCodeAt(index);
|
|
13848
|
+
hash = Math.imul(hash, FNV_PRIME) >>> 0;
|
|
13849
|
+
}
|
|
13850
|
+
return hash.toString(36);
|
|
13851
|
+
};
|
|
13852
|
+
/**
|
|
13853
|
+
* Wraps a URL payload with the fingerprint of the identity writing it.
|
|
13854
|
+
*
|
|
13855
|
+
* @param value - The payload that would otherwise be encoded into the URL.
|
|
13856
|
+
* @param owner - Fingerprint of the writing identity (see {@link identityFingerprint}).
|
|
13857
|
+
* @returns {StampedUrlValue} The payload wrapped in its ownership envelope.
|
|
13858
|
+
*/
|
|
13859
|
+
const wrapUrlOwner = (value, owner) => ({ o: owner, v: value });
|
|
13860
|
+
/**
|
|
13861
|
+
* Splits a decoded URL value into its owner fingerprint and payload.
|
|
13862
|
+
* Bare (pre-stamping) payloads come back with `owner: undefined`.
|
|
13863
|
+
*
|
|
13864
|
+
* @param decoded - The decoded URL value, stamped or bare.
|
|
13865
|
+
* @returns {{ owner: string | undefined; value: unknown }} The owner fingerprint (if any) and the payload.
|
|
13866
|
+
*/
|
|
13867
|
+
const unwrapUrlOwner = (decoded) => {
|
|
13868
|
+
const stamped = stampedUrlValueSchema.safeParse(decoded);
|
|
13869
|
+
// `z.unknown()` accepts a missing key, so `{ o: "x" }` parses without `v`.
|
|
13870
|
+
// Such an object is a payload of its own, not an envelope; the `in` check
|
|
13871
|
+
// is what keeps it unowned. Do not remove it as redundant.
|
|
13872
|
+
return stamped.success && "v" in stamped.data
|
|
13873
|
+
? { owner: stamped.data.o, value: stamped.data.v }
|
|
13874
|
+
: { owner: undefined, value: decoded };
|
|
13875
|
+
};
|
|
13876
|
+
|
|
13877
|
+
/**
|
|
13878
|
+
* One-shot migration: if the URL still carries a legacy `?<key>=...`
|
|
13879
|
+
* search param from before this hook moved table-style state to the
|
|
13880
|
+
* fragment, decode it, hand it to the caller via `onMigrated`, then strip
|
|
13881
|
+
* the search param via a `replace` navigation so back/forward history
|
|
13882
|
+
* isn't polluted.
|
|
13883
|
+
*
|
|
13884
|
+
* Invariants:
|
|
13885
|
+
* - The strip navigation fires at most once per mount (guarded by
|
|
13886
|
+
* `hasStrippedRef`) so we don't loop on the navigation we ourselves
|
|
13887
|
+
* triggered.
|
|
13888
|
+
* - `onMigrated` is also fired at most once per mount (guarded by
|
|
13889
|
+
* `hasMigratedRef`), but its gating is independent of the strip:
|
|
13890
|
+
* if `hashAlreadyHasValue` flips `true → false` after the strip
|
|
13891
|
+
* (e.g. an external actor clears the canonical hash mid-mount), the
|
|
13892
|
+
* next render still gets a chance to migrate the legacy value into
|
|
13893
|
+
* the hash. Conflating the two flags would have permanently lost
|
|
13894
|
+
* the legacy state in that race.
|
|
13895
|
+
* - Never throws — a decode/validate failure silently drops the value
|
|
13896
|
+
* and still strips the search param. The legacy key is owned by this
|
|
13897
|
+
* codebase's persistence convention (camelCase + `Tp` suffix), so
|
|
13898
|
+
* stripping unparseable values cannot destroy third-party data.
|
|
13899
|
+
* - When `hashAlreadyHasValue` is `true` the hash wins: the search
|
|
13900
|
+
* param is stripped but `onMigrated` is not fired.
|
|
13901
|
+
* - The `location.hash` is preserved verbatim across the strip
|
|
13902
|
+
* navigation so any concurrent hash content (including a freshly
|
|
13903
|
+
* written value) survives the cleanup.
|
|
13904
|
+
*/
|
|
13905
|
+
const useMigrateLegacySearchParam = ({ key, enabled, decode, fromUrlValue, validate, hashAlreadyHasValue, onMigrated, }) => {
|
|
13906
|
+
const navigate = reactRouter.useNavigate();
|
|
13907
|
+
const location = reactRouter.useLocation();
|
|
13908
|
+
const search = reactRouter.useSearch({ strict: false, shouldThrow: false });
|
|
13909
|
+
// The three flags are tracked independently because they describe
|
|
13910
|
+
// distinct side effects with distinct lifetimes:
|
|
13911
|
+
//
|
|
13912
|
+
// - `hasStrippedRef` guards the cleanup navigation against looping
|
|
13913
|
+
// on the navigation we ourselves triggered.
|
|
13914
|
+
// - `hasMigratedRef` guards `onMigrated` against being called twice
|
|
13915
|
+
// with the same legacy value.
|
|
13916
|
+
// - `cachedRawValueRef` snapshots the legacy raw string the first
|
|
13917
|
+
// time we observe it. The strip navigation below removes the
|
|
13918
|
+
// value from `search` on the next render, so without a cache we
|
|
13919
|
+
// can never migrate it later. This matters in one specific edge
|
|
13920
|
+
// case: `hashAlreadyHasValue` is `true` on the first render (so
|
|
13921
|
+
// we skip `onMigrated` and just strip), then later flips to
|
|
13922
|
+
// `false` because another actor cleared the canonical hash. With
|
|
13923
|
+
// the cache the next render can still surface the legacy value.
|
|
13924
|
+
//
|
|
13925
|
+
// The previous implementation conflated all of this into a single
|
|
13926
|
+
// `hasRunRef`, which permanently lost the legacy state in that race.
|
|
13927
|
+
const hasStrippedRef = react.useRef(false);
|
|
13928
|
+
const hasMigratedRef = react.useRef(false);
|
|
13929
|
+
const cachedRawValueRef = react.useRef(undefined);
|
|
13930
|
+
const decodeRef = react.useRef(decode);
|
|
13931
|
+
const fromUrlValueRef = react.useRef(fromUrlValue);
|
|
13932
|
+
const validateRef = react.useRef(validate);
|
|
13933
|
+
const onMigratedRef = react.useRef(onMigrated);
|
|
13934
|
+
react.useEffect(() => {
|
|
13935
|
+
decodeRef.current = decode;
|
|
13936
|
+
fromUrlValueRef.current = fromUrlValue;
|
|
13937
|
+
validateRef.current = validate;
|
|
13938
|
+
onMigratedRef.current = onMigrated;
|
|
13939
|
+
}, [decode, fromUrlValue, validate, onMigrated]);
|
|
13940
|
+
react.useEffect(() => {
|
|
13941
|
+
if (!enabled) {
|
|
13942
|
+
return;
|
|
13943
|
+
}
|
|
13944
|
+
if (hasStrippedRef.current && hasMigratedRef.current) {
|
|
13945
|
+
return;
|
|
13946
|
+
}
|
|
13947
|
+
// Snapshot the raw value the first time we see it. After the strip
|
|
13948
|
+
// navigation below, `search?.[key]` is undefined, but a later
|
|
13949
|
+
// render that flips `hashAlreadyHasValue` back to `false` still
|
|
13950
|
+
// needs the original value to migrate.
|
|
13951
|
+
if (cachedRawValueRef.current === undefined) {
|
|
13952
|
+
cachedRawValueRef.current = readPrimitiveSearchParam(search, key);
|
|
13953
|
+
}
|
|
13954
|
+
const rawString = cachedRawValueRef.current;
|
|
13955
|
+
if (rawString === undefined) {
|
|
13956
|
+
// Nothing legacy to migrate yet. Don't flip either flag — the
|
|
13957
|
+
// param may appear on a later render (e.g. router still hydrating).
|
|
13958
|
+
return;
|
|
13959
|
+
}
|
|
13960
|
+
if (!hasMigratedRef.current && !hashAlreadyHasValue) {
|
|
13961
|
+
let migratedState;
|
|
13962
|
+
try {
|
|
13963
|
+
const decoded = decodeRef.current(rawString);
|
|
13964
|
+
const transformed = fromUrlValueRef.current ? fromUrlValueRef.current(decoded) : decoded;
|
|
13965
|
+
migratedState = validateRef.current(transformed);
|
|
13966
|
+
}
|
|
13967
|
+
catch {
|
|
13968
|
+
migratedState = undefined;
|
|
13969
|
+
}
|
|
13970
|
+
// Invalid legacy data is silently dropped: the search param is
|
|
13971
|
+
// still stripped below, so the URL stays clean. Surfacing a
|
|
13972
|
+
// console warning here would require disabling a lint rule, and
|
|
13973
|
+
// the data loss is bounded — localStorage holds the working state
|
|
13974
|
+
// for the current session, and the user's next interaction
|
|
13975
|
+
// repopulates the hash. We still flip the flag in the invalid
|
|
13976
|
+
// case so we don't burn cycles re-decoding the same bad string
|
|
13977
|
+
// on every render.
|
|
13978
|
+
hasMigratedRef.current = true;
|
|
13979
|
+
if (migratedState !== undefined) {
|
|
13980
|
+
onMigratedRef.current(migratedState);
|
|
13981
|
+
}
|
|
13982
|
+
}
|
|
13983
|
+
if (!hasStrippedRef.current) {
|
|
13984
|
+
hasStrippedRef.current = true;
|
|
13985
|
+
void navigate({
|
|
13986
|
+
to: ".",
|
|
13987
|
+
search: (prev) => ({ ...prev, [key]: undefined }),
|
|
13988
|
+
hash: location.hash,
|
|
13989
|
+
replace: true,
|
|
13990
|
+
});
|
|
13991
|
+
}
|
|
13992
|
+
}, [enabled, key, hashAlreadyHasValue, search, navigate, location.hash]);
|
|
13993
|
+
};
|
|
13994
|
+
|
|
13995
|
+
/**
|
|
13996
|
+
* Default maximum full URL length after adding one persisted search param
|
|
13997
|
+
* before the URL write is skipped (localStorage still persists the full state).
|
|
13998
|
+
*
|
|
13999
|
+
* Sized to stay safely below the AWS WAF managed-rule default
|
|
14000
|
+
* `SizeRestrictions_QUERYSTRING` cap of 5000 bytes for the entire url host + path + query + hash string
|
|
14001
|
+
*/
|
|
14002
|
+
const MAX_URL_LENGTH = 5000;
|
|
13737
14003
|
/**
|
|
13738
|
-
* Syncs an encoded string value with a
|
|
13739
|
-
*
|
|
13740
|
-
*
|
|
13741
|
-
*
|
|
13742
|
-
*
|
|
13743
|
-
*
|
|
13744
|
-
*
|
|
13745
|
-
*
|
|
13746
|
-
*
|
|
13747
|
-
*
|
|
13748
|
-
* Writes are dispatched via a pending-write queue rather than calling
|
|
13749
|
-
* `navigate` directly. Tanstack Router's `router.state.status === "pending"`
|
|
13750
|
-
* is common during the first paint of a route (loaders, suspense), and an
|
|
13751
|
-
* implementation that simply returned in that case lost the write outright.
|
|
13752
|
-
* `updateSearchParam` stores the latest attempted write and schedules an rAF
|
|
13753
|
-
* flush; the flush only navigates when the router is idle, and an effect
|
|
13754
|
-
* retries whenever the router settles. A queued write is dropped on unmount so
|
|
13755
|
-
* it cannot drain onto the next route.
|
|
13756
|
-
*
|
|
13757
|
-
* @param options - Configuration for the URL entry sync.
|
|
13758
|
-
* @param options.key - The search param name or fragment entry name.
|
|
13759
|
-
* @param options.location - `"search"` or `"hash"`.
|
|
14004
|
+
* Syncs an encoded string value with a URL search parameter via Tanstack Router.
|
|
14005
|
+
*
|
|
14006
|
+
* Provides a write function that updates the URL through the application
|
|
14007
|
+
* router (preserving other search params), guards against exceeding
|
|
14008
|
+
* {@link MAX_URL_LENGTH}, and detects external URL changes (browser
|
|
14009
|
+
* back/forward, shared links) via an optional callback.
|
|
14010
|
+
*
|
|
14011
|
+
* @param options - Configuration for the search param sync.
|
|
14012
|
+
* @param options.key - The URL search parameter name.
|
|
13760
14013
|
* @param options.enabled - Set to `false` to disable all URL interaction (default `true`).
|
|
13761
|
-
* @param options.onExternalChange - Called when the
|
|
13762
|
-
* @param options.replace - `true` to always use `replaceState
|
|
13763
|
-
* Default: replace when the entry is being added, push when it already has a value.
|
|
14014
|
+
* @param options.onExternalChange - Called when the param changes externally.
|
|
14015
|
+
* @param options.replace - `true` to always use `replaceState`.
|
|
13764
14016
|
*/
|
|
13765
|
-
const
|
|
14017
|
+
const useSearchParamSync = ({ key, enabled = true, onExternalChange, replace: replaceOption, }) => {
|
|
13766
14018
|
const navigate = reactRouter.useNavigate();
|
|
13767
14019
|
const location = reactRouter.useLocation();
|
|
13768
14020
|
const router = reactRouter.useRouter();
|
|
13769
14021
|
const search = reactRouter.useSearch({ strict: false, shouldThrow: false });
|
|
13770
|
-
const isHash = urlLocation === "hash";
|
|
13771
14022
|
const lastWrittenRef = react.useRef(undefined);
|
|
13772
14023
|
const pendingWriteRef = react.useRef(null);
|
|
13773
14024
|
const onExternalChangeRef = react.useRef(onExternalChange);
|
|
13774
14025
|
react.useEffect(() => {
|
|
13775
14026
|
onExternalChangeRef.current = onExternalChange;
|
|
13776
14027
|
}, [onExternalChange]);
|
|
13777
|
-
const
|
|
14028
|
+
const currentSearchValue = react.useMemo(() => {
|
|
13778
14029
|
if (!enabled) {
|
|
13779
14030
|
return undefined;
|
|
13780
14031
|
}
|
|
13781
|
-
return
|
|
13782
|
-
}, [enabled,
|
|
14032
|
+
return readPrimitiveSearchParam(search, key);
|
|
14033
|
+
}, [enabled, search, key]);
|
|
13783
14034
|
react.useEffect(() => {
|
|
13784
|
-
if (!enabled
|
|
14035
|
+
if (!enabled) {
|
|
14036
|
+
return;
|
|
14037
|
+
}
|
|
14038
|
+
if (currentSearchValue === undefined) {
|
|
13785
14039
|
return;
|
|
13786
14040
|
}
|
|
13787
|
-
if (
|
|
14041
|
+
if (currentSearchValue === lastWrittenRef.current) {
|
|
13788
14042
|
return;
|
|
13789
14043
|
}
|
|
13790
|
-
|
|
13791
|
-
|
|
13792
|
-
|
|
13793
|
-
//
|
|
14044
|
+
if (lastWrittenRef.current === undefined) {
|
|
14045
|
+
return;
|
|
14046
|
+
}
|
|
14047
|
+
// A caller may have primed `lastWrittenRef` via `updateSearchParam` while the
|
|
14048
|
+
// URL still carries the previous value (queued rAF / router pending). Treating
|
|
14049
|
+
// that stale URL as an external change reloads filter state from persistence
|
|
14050
|
+
// and can clear in-progress search input before the write lands.
|
|
13794
14051
|
if (pendingWriteRef.current !== null) {
|
|
13795
14052
|
return;
|
|
13796
14053
|
}
|
|
13797
14054
|
requestAnimationFrame(() => {
|
|
13798
14055
|
onExternalChangeRef.current?.();
|
|
13799
14056
|
});
|
|
13800
|
-
}, [
|
|
13801
|
-
|
|
13802
|
-
// navigation; it only needs the location and current value at the moment it
|
|
13803
|
-
// flushes, which may be an animation frame after it was queued.
|
|
13804
|
-
const locationRef = react.useRef(location);
|
|
13805
|
-
const currentValueRef = react.useRef(currentValue);
|
|
13806
|
-
react.useEffect(() => {
|
|
13807
|
-
locationRef.current = location;
|
|
13808
|
-
currentValueRef.current = currentValue;
|
|
13809
|
-
}, [location, currentValue]);
|
|
13810
|
-
const getUrlLengthWithSearchParam = react.useCallback((paramValue, params) => {
|
|
13811
|
-
const { href, searchStr, hash } = locationRef.current;
|
|
14057
|
+
}, [currentSearchValue, enabled]);
|
|
14058
|
+
const getUrlLengthWithSearchParam = react.useCallback((paramKey, paramValue, params) => {
|
|
13812
14059
|
const otherParamsLength = sharedUtils.objectKeys(params)
|
|
13813
|
-
.filter(k => k !==
|
|
14060
|
+
.filter(k => k !== paramKey)
|
|
13814
14061
|
.reduce((totalLength, k) => {
|
|
13815
14062
|
const kLen = encodeURIComponent(String(k)).length;
|
|
13816
14063
|
const v = params[k];
|
|
13817
14064
|
const vLen = v !== null && v !== undefined ? encodeURIComponent(String(v)).length : 0;
|
|
13818
14065
|
return totalLength + kLen + vLen + (totalLength > 0 ? 2 : 1);
|
|
13819
14066
|
}, 0);
|
|
13820
|
-
const urlBase = href.length - (searchStr.length || 0) + (hash.length || 0);
|
|
13821
|
-
return urlBase + otherParamsLength + 1 +
|
|
13822
|
-
}, [
|
|
14067
|
+
const urlBase = location.href.length - (location.searchStr.length || 0) + (location.hash.length || 0);
|
|
14068
|
+
return urlBase + otherParamsLength + 1 + paramKey.length + 1 + paramValue.length;
|
|
14069
|
+
}, [location]);
|
|
14070
|
+
// Writes are dispatched via a "pending write" queue rather than calling
|
|
14071
|
+
// `navigate` directly from inside the rAF callback. See the matching
|
|
14072
|
+
// comment block in `useHashParamSync` for the full rationale — in short,
|
|
14073
|
+
// navigating while `router.state.status === "pending"` was previously
|
|
14074
|
+
// dropped silently, which lost a one-shot write (a legacy search param
|
|
14075
|
+
// migrated into the URL, or the first edit) on routes that mount during
|
|
14076
|
+
// a loader-driven pending phase.
|
|
13823
14077
|
const flushPendingWrite = react.useCallback(() => {
|
|
13824
14078
|
const pending = pendingWriteRef.current;
|
|
13825
14079
|
if (pending === null) {
|
|
13826
14080
|
return;
|
|
13827
14081
|
}
|
|
13828
14082
|
if (router.state.status === "pending") {
|
|
13829
|
-
// Keep the write queued; the status-watcher effect retries
|
|
14083
|
+
// Keep the write queued; the status-watcher effect below retries on
|
|
14084
|
+
// the next idle transition.
|
|
13830
14085
|
return;
|
|
13831
14086
|
}
|
|
13832
14087
|
pendingWriteRef.current = null;
|
|
13833
|
-
const { encodedValue } = pending;
|
|
13834
|
-
const
|
|
13835
|
-
const valueInUrl = currentValueRef.current;
|
|
13836
|
-
const shouldReplace = replaceOption ?? !Boolean(valueInUrl);
|
|
13837
|
-
if (!isHash) {
|
|
13838
|
-
void navigate({
|
|
13839
|
-
to: ".",
|
|
13840
|
-
search: (prev) => getUrlLengthWithSearchParam(encodedValue ?? "", prev) <= MAX_URL_LENGTH
|
|
13841
|
-
? { ...prev, [key]: encodedValue }
|
|
13842
|
-
: { ...prev, [key]: undefined },
|
|
13843
|
-
hash,
|
|
13844
|
-
replace: shouldReplace,
|
|
13845
|
-
});
|
|
13846
|
-
return;
|
|
13847
|
-
}
|
|
13848
|
-
let nextHash = writeHashKey(hash, key, encodedValue);
|
|
13849
|
-
let removedOversizedValue = false;
|
|
13850
|
-
if (nextHash.length > MAX_HASH_LENGTH) {
|
|
13851
|
-
if (valueInUrl === undefined) {
|
|
13852
|
-
return;
|
|
13853
|
-
}
|
|
13854
|
-
nextHash = writeHashKey(hash, key, undefined);
|
|
13855
|
-
removedOversizedValue = true;
|
|
13856
|
-
}
|
|
14088
|
+
const { encodedValue, options } = pending;
|
|
14089
|
+
const shouldReplace = options?.replace ?? replaceOption ?? !Boolean(currentSearchValue);
|
|
13857
14090
|
void navigate({
|
|
13858
14091
|
to: ".",
|
|
13859
|
-
|
|
13860
|
-
|
|
13861
|
-
|
|
13862
|
-
|
|
13863
|
-
|
|
13864
|
-
|
|
14092
|
+
search: (prev) => {
|
|
14093
|
+
if (getUrlLengthWithSearchParam(key, encodedValue || "", prev) <= MAX_URL_LENGTH) {
|
|
14094
|
+
return { ...prev, [key]: encodedValue };
|
|
14095
|
+
}
|
|
14096
|
+
else {
|
|
14097
|
+
return { ...prev, [key]: undefined };
|
|
14098
|
+
}
|
|
14099
|
+
},
|
|
14100
|
+
hash: location.hash,
|
|
14101
|
+
replace: shouldReplace,
|
|
13865
14102
|
});
|
|
13866
|
-
}, [
|
|
14103
|
+
}, [
|
|
14104
|
+
router.state.status,
|
|
14105
|
+
location.hash,
|
|
14106
|
+
key,
|
|
14107
|
+
currentSearchValue,
|
|
14108
|
+
navigate,
|
|
14109
|
+
replaceOption,
|
|
14110
|
+
getUrlLengthWithSearchParam,
|
|
14111
|
+
]);
|
|
13867
14112
|
react.useEffect(() => {
|
|
13868
|
-
if (router.state.status === "pending"
|
|
14113
|
+
if (router.state.status === "pending") {
|
|
14114
|
+
return;
|
|
14115
|
+
}
|
|
14116
|
+
if (pendingWriteRef.current === null) {
|
|
13869
14117
|
return;
|
|
13870
14118
|
}
|
|
13871
14119
|
flushPendingWrite();
|
|
13872
14120
|
}, [router.state.status, flushPendingWrite]);
|
|
14121
|
+
// Drop any queued write when the consumer unmounts. The queue + retry
|
|
14122
|
+
// pattern above keeps writes pending across a `router.state.status ===
|
|
14123
|
+
// "pending"` phase, which means a write scheduled just before a route
|
|
14124
|
+
// change could otherwise drain onto the *next* route once it settles
|
|
14125
|
+
// (e.g. a debounced filter write leaking into the destination route).
|
|
14126
|
+
// Cancelling here preserves the original "writes are scoped to the
|
|
14127
|
+
// owning route" contract that the pre-queue implementation got for
|
|
14128
|
+
// free by dropping the write outright.
|
|
13873
14129
|
react.useEffect(() => () => {
|
|
13874
14130
|
pendingWriteRef.current = null;
|
|
13875
14131
|
}, []);
|
|
13876
|
-
const updateSearchParam = react.useCallback((encodedValue) => {
|
|
14132
|
+
const updateSearchParam = react.useCallback((encodedValue, options) => {
|
|
13877
14133
|
if (!enabled) {
|
|
13878
14134
|
return;
|
|
13879
14135
|
}
|
|
13880
|
-
// Dedupe against the last committed write or the value
|
|
13881
|
-
// both represent the caller's
|
|
14136
|
+
// Dedupe against either the last committed write or the value
|
|
14137
|
+
// currently queued for the next rAF — both represent the caller's
|
|
14138
|
+
// intent so we don't schedule redundant rAF callbacks for identical
|
|
14139
|
+
// requests.
|
|
13882
14140
|
const inFlightOrLastWritten = pendingWriteRef.current?.encodedValue ?? lastWrittenRef.current;
|
|
13883
14141
|
if (encodedValue !== undefined && encodedValue === inFlightOrLastWritten) {
|
|
13884
14142
|
return;
|
|
13885
14143
|
}
|
|
13886
|
-
// Prime here (not
|
|
13887
|
-
// this value as the caller's
|
|
13888
|
-
//
|
|
14144
|
+
// Prime `lastWrittenRef` here (not inside `flushPendingWrite`) so
|
|
14145
|
+
// the external-change detector treats this value as the caller's
|
|
14146
|
+
// authoritative state even when the flush is a no-op (URL already
|
|
14147
|
+
// matches) or stays queued during a pending router phase. Without
|
|
14148
|
+
// priming, the next "external" change would look identical to the
|
|
14149
|
+
// initial render (`lastWrittenRef === undefined`) and the callback
|
|
14150
|
+
// would be skipped.
|
|
13889
14151
|
lastWrittenRef.current = encodedValue;
|
|
13890
|
-
if (
|
|
14152
|
+
if (currentSearchValue === encodedValue) {
|
|
13891
14153
|
return;
|
|
13892
14154
|
}
|
|
13893
|
-
pendingWriteRef.current = { encodedValue };
|
|
14155
|
+
pendingWriteRef.current = { encodedValue, options };
|
|
13894
14156
|
requestAnimationFrame(() => {
|
|
13895
14157
|
flushPendingWrite();
|
|
13896
14158
|
});
|
|
13897
|
-
}, [enabled, flushPendingWrite]);
|
|
13898
|
-
return react.useMemo(() => ({ searchValue:
|
|
14159
|
+
}, [enabled, currentSearchValue, flushPendingWrite]);
|
|
14160
|
+
return react.useMemo(() => ({ searchValue: currentSearchValue, updateSearchParam }), [currentSearchValue, updateSearchParam]);
|
|
14161
|
+
};
|
|
14162
|
+
|
|
14163
|
+
/**
|
|
14164
|
+
* Generates a localStorage key, optionally scoped to a specific user.
|
|
14165
|
+
*
|
|
14166
|
+
* When `userId` is provided the key is `"key-userId"`.
|
|
14167
|
+
* When omitted the key is returned as-is (unscoped).
|
|
14168
|
+
*
|
|
14169
|
+
* @param key - Unique persistence identifier.
|
|
14170
|
+
* @param userId - Client-side user id to scope storage per user.
|
|
14171
|
+
* @returns {string} The combined storage key.
|
|
14172
|
+
*/
|
|
14173
|
+
const useStorageKey = (key, userId) => {
|
|
14174
|
+
return react.useMemo(() => (userId ? `${key}-${userId}` : key), [key, userId]);
|
|
13899
14175
|
};
|
|
13900
14176
|
|
|
13901
14177
|
/**
|
|
@@ -13917,43 +14193,47 @@ const rawLocalStorage = {
|
|
|
13917
14193
|
* and writes changes to both.
|
|
13918
14194
|
*
|
|
13919
14195
|
* On mount the hook resolves the initial state as follows:
|
|
13920
|
-
* - If the URL slot
|
|
14196
|
+
* - If the canonical URL slot (search OR hash, per `urlLocation`) holds a
|
|
14197
|
+
* value, decode it and pass through `validate`.
|
|
14198
|
+
* - In `urlLocation: "hash"` mode, if the canonical hash slot has no valid
|
|
14199
|
+
* value but a **legacy** `?<key>=...` search param is present, decode and
|
|
14200
|
+
* validate that as a one-shot fallback. The value is copied into the hash
|
|
14201
|
+
* and the search param is stripped via a `replace` navigation.
|
|
14202
|
+
* - A value that comes only from localStorage is not written to the URL.
|
|
14203
|
+
* Copying it on load left a layout in history, bookmarks, and login
|
|
14204
|
+
* redirects, which then replayed an older layout over the saved one
|
|
14205
|
+
* (GLU-2396). The URL is written when the user changes the state.
|
|
13921
14206
|
* - If localStorage is enabled, read and validate its value.
|
|
13922
14207
|
* - When `mergeWithStorageOnRead` is `false` (default): URL state wins
|
|
13923
14208
|
* entirely when present, otherwise fall back to localStorage.
|
|
13924
14209
|
* - When `mergeWithStorageOnRead` is `true`: shallow-merge URL fields over
|
|
13925
14210
|
* localStorage so fields stripped by `toUrlValue` survive via storage.
|
|
13926
14211
|
*
|
|
13927
|
-
*
|
|
13928
|
-
*
|
|
13929
|
-
*
|
|
13930
|
-
*
|
|
13931
|
-
*
|
|
13932
|
-
* `
|
|
13933
|
-
*
|
|
13934
|
-
*
|
|
13935
|
-
*
|
|
13936
|
-
*
|
|
13937
|
-
*
|
|
13938
|
-
*
|
|
13939
|
-
*
|
|
13940
|
-
*
|
|
13941
|
-
*
|
|
13942
|
-
* it, and a reload of the account's own link writes nothing.
|
|
13943
|
-
* `persistToStorage` and `persistToUrl` are the same two halves exposed
|
|
13944
|
-
* separately for consumers that schedule them differently; passing `undefined`
|
|
13945
|
-
* removes the entry rather than writing an empty value.
|
|
13946
|
-
*
|
|
13947
|
-
* The snapshot is re-read when the storage key or the storage/merge options
|
|
13948
|
-
* change, in the same render, so a write in that commit already sees the
|
|
13949
|
-
* state for the new key.
|
|
14212
|
+
* `persistState` writes the state to localStorage (via `serialize`, default
|
|
14213
|
+
* `storageSerializer.serialize`) and syncs to the canonical URL slot (via
|
|
14214
|
+
* `toUrlValue` + encoding). Duplicate writes where the state has not
|
|
14215
|
+
* changed (deep equality) are skipped.
|
|
14216
|
+
*
|
|
14217
|
+
* `commitHydratedState` writes the hydrated value to localStorage only,
|
|
14218
|
+
* when it came from the URL and differs from what this identity has stored.
|
|
14219
|
+
* It does not update the URL. It returns `false` while the snapshot is
|
|
14220
|
+
* still for a previous read, so the caller can retry after identity
|
|
14221
|
+
* resolution. The caller decides which identity is allowed to commit.
|
|
14222
|
+
*
|
|
14223
|
+
* `clearState` removes the entry from localStorage and from the URL slot,
|
|
14224
|
+
* rather than writing an empty value. Use it when the state a consumer
|
|
14225
|
+
* derives has become empty, so no leftover entry is stored for a value the
|
|
14226
|
+
* user has reset. It is idempotent — clearing an absent entry is a no-op.
|
|
13950
14227
|
*
|
|
13951
14228
|
* @param options - Configuration for the persisted state.
|
|
13952
14229
|
* @param options.key - Unique identifier used for both the URL slot and the localStorage key.
|
|
13953
14230
|
* @param options.validate - Called with the decoded/parsed value; must return `TState` or `undefined`.
|
|
14231
|
+
* @param options.serialize - Custom localStorage serialiser (default `storageSerializer.serialize`).
|
|
13954
14232
|
* @param options.toUrlValue - Transform applied before URL encoding (default: encode state as-is).
|
|
13955
14233
|
* @param options.fromUrlValue - Transform applied after URL decoding, before validation (default: identity).
|
|
14234
|
+
* @param options.enabled - When `false` the URL is neither read nor written (default `true`).
|
|
13956
14235
|
* @param options.localStorageEnabled - When `false` localStorage is neither read nor written (default `true`).
|
|
14236
|
+
* @param options.onExternalChange - Fired when the URL value changes externally (e.g. browser back).
|
|
13957
14237
|
* @param options.replace - Forwarded to the underlying URL sync hook.
|
|
13958
14238
|
* @param options.clientSideUserId - The user ID to use for the localStorage key.
|
|
13959
14239
|
* @param options.mergeWithStorageOnRead - Merge URL state on top of localStorage
|
|
@@ -13963,182 +14243,344 @@ const rawLocalStorage = {
|
|
|
13963
14243
|
* @param options.stampUrlWithIdentity - Stamp URL writes with the current identity so the login
|
|
13964
14244
|
* redirect can drop entries left by another account on this browser. Default `false`.
|
|
13965
14245
|
*/
|
|
13966
|
-
const usePersistedState = ({ key, validate, toUrlValue, fromUrlValue, localStorageEnabled = true, replace, clientSideUserId, mergeWithStorageOnRead = false, urlLocation = "search", stampUrlWithIdentity = false, }) => {
|
|
14246
|
+
const usePersistedState = ({ key, validate, serialize, toUrlValue, fromUrlValue, enabled = true, localStorageEnabled = true, onExternalChange, replace, clientSideUserId, mergeWithStorageOnRead = false, urlLocation = "search", stampUrlWithIdentity = false, }) => {
|
|
13967
14247
|
const { encode, decode } = useCustomEncoding();
|
|
13968
14248
|
// Fingerprint of the identity this hook writes URL values for. `undefined`
|
|
13969
14249
|
// while the identity is unresolved (or when stamping is off): writes are
|
|
13970
14250
|
// then unstamped.
|
|
13971
14251
|
const currentUrlOwner = react.useMemo(() => (stampUrlWithIdentity && clientSideUserId !== undefined ? identityFingerprint(clientSideUserId) : undefined), [stampUrlWithIdentity, clientSideUserId]);
|
|
13972
|
-
const
|
|
14252
|
+
const searchActive = enabled && urlLocation === "search";
|
|
14253
|
+
const hashActive = enabled && urlLocation === "hash";
|
|
14254
|
+
// Both URL-sync hooks are mounted unconditionally to satisfy the Rules of
|
|
14255
|
+
// Hooks; the inactive one is gated off via `enabled: false` and is a
|
|
14256
|
+
// no-op at runtime.
|
|
14257
|
+
const searchSync = useSearchParamSync({
|
|
14258
|
+
key,
|
|
14259
|
+
enabled: searchActive,
|
|
14260
|
+
onExternalChange,
|
|
14261
|
+
replace,
|
|
14262
|
+
});
|
|
14263
|
+
const hashSync = useHashParamSync({
|
|
13973
14264
|
key,
|
|
13974
|
-
|
|
14265
|
+
enabled: hashActive,
|
|
14266
|
+
onExternalChange,
|
|
13975
14267
|
replace,
|
|
13976
14268
|
});
|
|
14269
|
+
const { searchValue, updateSearchParam } = hashActive ? hashSync : searchSync;
|
|
14270
|
+
// In hash mode, also read the raw search params so a legacy `?<key>=...`
|
|
14271
|
+
// value can hydrate the initial state once, before the migration effect
|
|
14272
|
+
// strips it. In search mode this stays `undefined` so the legacy fallback
|
|
14273
|
+
// is inert.
|
|
14274
|
+
const rawSearch = reactRouter.useSearch({ strict: false, shouldThrow: false });
|
|
14275
|
+
const legacySearchValue = react.useMemo(() => {
|
|
14276
|
+
if (!hashActive) {
|
|
14277
|
+
return undefined;
|
|
14278
|
+
}
|
|
14279
|
+
return readPrimitiveSearchParam(rawSearch, key);
|
|
14280
|
+
}, [hashActive, rawSearch, key]);
|
|
13977
14281
|
const storageKey = useStorageKey(key, clientSideUserId);
|
|
13978
|
-
// `toUrlValue` is read through a ref so the write callbacks stay stable
|
|
13979
|
-
// when a consumer passes an inline function.
|
|
13980
14282
|
const toUrlValueRef = react.useRef(toUrlValue);
|
|
13981
14283
|
react.useEffect(() => {
|
|
13982
14284
|
toUrlValueRef.current = toUrlValue;
|
|
13983
14285
|
}, [toUrlValue]);
|
|
13984
|
-
const
|
|
13985
|
-
|
|
13986
|
-
|
|
13987
|
-
|
|
13988
|
-
|
|
13989
|
-
|
|
13990
|
-
|
|
14286
|
+
const serializeRef = react.useRef(serialize);
|
|
14287
|
+
react.useEffect(() => {
|
|
14288
|
+
serializeRef.current = serialize;
|
|
14289
|
+
}, [serialize]);
|
|
14290
|
+
const validateRef = react.useRef(validate);
|
|
14291
|
+
react.useEffect(() => {
|
|
14292
|
+
validateRef.current = validate;
|
|
14293
|
+
}, [validate]);
|
|
14294
|
+
const fromUrlValueRef = react.useRef(fromUrlValue);
|
|
14295
|
+
react.useEffect(() => {
|
|
14296
|
+
fromUrlValueRef.current = fromUrlValue;
|
|
14297
|
+
}, [fromUrlValue]);
|
|
14298
|
+
const searchValueRef = react.useRef(searchValue);
|
|
14299
|
+
react.useEffect(() => {
|
|
14300
|
+
searchValueRef.current = searchValue;
|
|
14301
|
+
}, [searchValue]);
|
|
14302
|
+
const legacySearchValueRef = react.useRef(legacySearchValue);
|
|
14303
|
+
react.useEffect(() => {
|
|
14304
|
+
legacySearchValueRef.current = legacySearchValue;
|
|
14305
|
+
}, [legacySearchValue]);
|
|
14306
|
+
const readPersistedState = react.useCallback(({ valueFromUrl, legacyValueFromUrl, validateState, transformFromUrlValue, }) => {
|
|
14307
|
+
// The ownership stamp is only read at the login redirect (see
|
|
14308
|
+
// `useStripForeignIdentityHash`); here it is unwrapped and discarded.
|
|
14309
|
+
const tryDecode = (raw) => {
|
|
14310
|
+
try {
|
|
14311
|
+
const { value } = unwrapUrlOwner(decode(raw));
|
|
14312
|
+
const transformed = transformFromUrlValue ? transformFromUrlValue(value) : value;
|
|
14313
|
+
const state = validateState(transformed);
|
|
14314
|
+
if (state === undefined) {
|
|
14315
|
+
return undefined;
|
|
14316
|
+
}
|
|
14317
|
+
return { state, payload: value };
|
|
14318
|
+
}
|
|
14319
|
+
catch {
|
|
14320
|
+
return undefined;
|
|
14321
|
+
}
|
|
14322
|
+
};
|
|
14323
|
+
const readStoredState = () => {
|
|
14324
|
+
if (!localStorageEnabled) {
|
|
13991
14325
|
return undefined;
|
|
13992
14326
|
}
|
|
13993
|
-
return validateState(sharedUtils.storageSerializer.deserialize(raw));
|
|
13994
|
-
}
|
|
13995
|
-
catch {
|
|
13996
|
-
return undefined;
|
|
13997
|
-
}
|
|
13998
|
-
}, [localStorageEnabled, storageKey]);
|
|
13999
|
-
const readPersistedState = react.useCallback(({ valueFromUrl, validateState, transformFromUrlValue, }) => {
|
|
14000
|
-
let urlState;
|
|
14001
|
-
let urlStamp;
|
|
14002
|
-
if (valueFromUrl) {
|
|
14003
14327
|
try {
|
|
14004
|
-
|
|
14005
|
-
|
|
14006
|
-
|
|
14007
|
-
|
|
14008
|
-
|
|
14009
|
-
urlStamp = urlState === undefined ? undefined : { owner };
|
|
14328
|
+
const raw = rawLocalStorage.read(storageKey);
|
|
14329
|
+
if (!raw) {
|
|
14330
|
+
return undefined;
|
|
14331
|
+
}
|
|
14332
|
+
return validateState(sharedUtils.storageSerializer.deserialize(raw));
|
|
14010
14333
|
}
|
|
14011
14334
|
catch {
|
|
14012
|
-
|
|
14335
|
+
return undefined;
|
|
14013
14336
|
}
|
|
14337
|
+
};
|
|
14338
|
+
let urlState;
|
|
14339
|
+
let decodedPayload;
|
|
14340
|
+
let canonicalUrlValid = false;
|
|
14341
|
+
let usedLegacyUrl = false;
|
|
14342
|
+
if (enabled && valueFromUrl) {
|
|
14343
|
+
const decoded = tryDecode(valueFromUrl);
|
|
14344
|
+
if (decoded !== undefined) {
|
|
14345
|
+
urlState = decoded.state;
|
|
14346
|
+
decodedPayload = decoded.payload;
|
|
14347
|
+
canonicalUrlValid = true;
|
|
14348
|
+
}
|
|
14349
|
+
}
|
|
14350
|
+
if (urlState === undefined && enabled && legacyValueFromUrl) {
|
|
14351
|
+
const decoded = tryDecode(legacyValueFromUrl);
|
|
14352
|
+
if (decoded !== undefined) {
|
|
14353
|
+
urlState = decoded.state;
|
|
14354
|
+
usedLegacyUrl = true;
|
|
14355
|
+
}
|
|
14356
|
+
}
|
|
14357
|
+
// Without the merge option, URL state wins entirely when present —
|
|
14358
|
+
// this preserves the original "URL > localStorage" priority.
|
|
14359
|
+
if (urlState !== undefined && !mergeWithStorageOnRead) {
|
|
14360
|
+
return {
|
|
14361
|
+
initialState: urlState,
|
|
14362
|
+
canonicalUrlHasValidState: canonicalUrlValid,
|
|
14363
|
+
canonicalUrlPayload: decodedPayload,
|
|
14364
|
+
needsUrlRestore: usedLegacyUrl,
|
|
14365
|
+
};
|
|
14014
14366
|
}
|
|
14015
|
-
|
|
14016
|
-
|
|
14017
|
-
|
|
14018
|
-
|
|
14019
|
-
|
|
14020
|
-
|
|
14021
|
-
|
|
14367
|
+
const storageState = readStoredState();
|
|
14368
|
+
if (urlState !== undefined && storageState !== undefined) {
|
|
14369
|
+
// Shallow merge — URL fields take precedence; storage fills in
|
|
14370
|
+
// whatever the URL omits (e.g. fields stripped by `toUrlValue`).
|
|
14371
|
+
return {
|
|
14372
|
+
initialState: { ...storageState, ...urlState },
|
|
14373
|
+
canonicalUrlHasValidState: canonicalUrlValid,
|
|
14374
|
+
canonicalUrlPayload: decodedPayload,
|
|
14375
|
+
needsUrlRestore: usedLegacyUrl,
|
|
14376
|
+
};
|
|
14022
14377
|
}
|
|
14023
|
-
|
|
14024
|
-
|
|
14025
|
-
|
|
14026
|
-
|
|
14378
|
+
if (urlState !== undefined) {
|
|
14379
|
+
return {
|
|
14380
|
+
initialState: urlState,
|
|
14381
|
+
canonicalUrlHasValidState: canonicalUrlValid,
|
|
14382
|
+
canonicalUrlPayload: decodedPayload,
|
|
14383
|
+
needsUrlRestore: usedLegacyUrl,
|
|
14384
|
+
};
|
|
14027
14385
|
}
|
|
14028
|
-
|
|
14029
|
-
|
|
14030
|
-
|
|
14031
|
-
|
|
14032
|
-
|
|
14033
|
-
|
|
14034
|
-
|
|
14035
|
-
|
|
14036
|
-
|
|
14037
|
-
|
|
14038
|
-
|
|
14039
|
-
|
|
14040
|
-
|
|
14041
|
-
|
|
14042
|
-
|
|
14043
|
-
|
|
14044
|
-
|
|
14045
|
-
|
|
14046
|
-
|
|
14047
|
-
|
|
14048
|
-
|
|
14049
|
-
|
|
14050
|
-
|
|
14051
|
-
|
|
14052
|
-
|
|
14053
|
-
|
|
14054
|
-
|
|
14055
|
-
|
|
14056
|
-
|
|
14057
|
-
|
|
14058
|
-
|
|
14059
|
-
|
|
14060
|
-
|
|
14061
|
-
|
|
14062
|
-
// The URL side holds what a write would put in the URL: the shareable
|
|
14063
|
-
// projection plus the owner stamp. It starts as the projection of the
|
|
14064
|
-
// hydrated value, so a consumer that echoes `initialState` on mount, or
|
|
14065
|
-
// changes only a field the projection strips, writes nothing: a layout read
|
|
14066
|
-
// from storage must not grow a URL entry (GLU-2396). Its owner starts as the
|
|
14067
|
-
// stamp the URL carries (or the current owner when the URL is empty), so an
|
|
14068
|
-
// equal state persisted after the identity resolves still rewrites the URL
|
|
14069
|
-
// with its stamp.
|
|
14070
|
-
const urlOwnerSeed = snapshot.urlValue ? snapshot.urlValue.owner : currentUrlOwner;
|
|
14071
|
-
const seedUrlWrite = react.useCallback((project) => initialState === undefined ? undefined : { projected: project(initialState), owner: urlOwnerSeed }, [initialState, urlOwnerSeed]);
|
|
14072
|
-
const lastStoredRef = react.useRef(storedState);
|
|
14073
|
-
// The first seed is computed during render, so it projects with the
|
|
14074
|
-
// `toUrlValue` prop rather than reading `toUrlValueRef` (refs are not read
|
|
14075
|
-
// in render); the projection is cheap, and later seeds come from the effect.
|
|
14076
|
-
const lastUrlRef = react.useRef(seedUrlWrite(state => (toUrlValue ? toUrlValue(state) : state)));
|
|
14386
|
+
if (storageState !== undefined) {
|
|
14387
|
+
return {
|
|
14388
|
+
initialState: storageState,
|
|
14389
|
+
canonicalUrlHasValidState: false,
|
|
14390
|
+
canonicalUrlPayload: undefined,
|
|
14391
|
+
// Leave the URL alone. A storage-only load must not grow a hash,
|
|
14392
|
+
// or the next history/bookmark/login of this page replays it.
|
|
14393
|
+
needsUrlRestore: false,
|
|
14394
|
+
};
|
|
14395
|
+
}
|
|
14396
|
+
return {
|
|
14397
|
+
initialState: undefined,
|
|
14398
|
+
canonicalUrlHasValidState: false,
|
|
14399
|
+
canonicalUrlPayload: undefined,
|
|
14400
|
+
needsUrlRestore: false,
|
|
14401
|
+
};
|
|
14402
|
+
}, [decode, enabled, localStorageEnabled, storageKey, mergeWithStorageOnRead]);
|
|
14403
|
+
// Every URL write goes through here so the ownership stamp is applied
|
|
14404
|
+
// uniformly (user edits and legacy search-param migration).
|
|
14405
|
+
const encodeForUrl = react.useCallback((state) => {
|
|
14406
|
+
const urlValue = toUrlValueRef.current ? toUrlValueRef.current(state) : state;
|
|
14407
|
+
return encode(currentUrlOwner === undefined ? urlValue : wrapUrlOwner(urlValue, currentUrlOwner));
|
|
14408
|
+
}, [encode, currentUrlOwner]);
|
|
14409
|
+
const persistedStateReadKey = `${enabled}:${localStorageEnabled}:${mergeWithStorageOnRead}:${urlLocation}:${storageKey}`;
|
|
14410
|
+
const [persistedStateSnapshot, setPersistedStateSnapshot] = react.useState(() => ({
|
|
14411
|
+
...readPersistedState({
|
|
14412
|
+
valueFromUrl: searchValue,
|
|
14413
|
+
legacyValueFromUrl: legacySearchValue,
|
|
14414
|
+
validateState: validate,
|
|
14415
|
+
transformFromUrlValue: fromUrlValue,
|
|
14416
|
+
}),
|
|
14417
|
+
readKey: persistedStateReadKey,
|
|
14418
|
+
}));
|
|
14419
|
+
const persistedStateReadKeyRef = react.useRef(persistedStateReadKey);
|
|
14077
14420
|
react.useEffect(() => {
|
|
14078
|
-
|
|
14079
|
-
lastUrlRef.current = seedUrlWrite(projectForUrl);
|
|
14080
|
-
}, [seedUrlWrite, projectForUrl, storedState]);
|
|
14081
|
-
const persistToStorage = react.useCallback((state) => {
|
|
14082
|
-
if (!localStorageEnabled) {
|
|
14421
|
+
if (persistedStateReadKeyRef.current === persistedStateReadKey) {
|
|
14083
14422
|
return;
|
|
14084
14423
|
}
|
|
14085
|
-
|
|
14086
|
-
|
|
14087
|
-
|
|
14424
|
+
persistedStateReadKeyRef.current = persistedStateReadKey;
|
|
14425
|
+
setPersistedStateSnapshot({
|
|
14426
|
+
...readPersistedState({
|
|
14427
|
+
valueFromUrl: searchValueRef.current,
|
|
14428
|
+
legacyValueFromUrl: legacySearchValueRef.current,
|
|
14429
|
+
validateState: validateRef.current,
|
|
14430
|
+
transformFromUrlValue: fromUrlValueRef.current,
|
|
14431
|
+
}),
|
|
14432
|
+
readKey: persistedStateReadKey,
|
|
14433
|
+
});
|
|
14434
|
+
}, [persistedStateReadKey, readPersistedState]);
|
|
14435
|
+
const { initialState, canonicalUrlHasValidState, canonicalUrlPayload, needsUrlRestore } = persistedStateSnapshot;
|
|
14436
|
+
// Late-hydration recovery: TanStack Router's `useSearch` can return an
|
|
14437
|
+
// empty object on the very first render of a route that's still in a
|
|
14438
|
+
// loader-driven pending phase. The `useState` initializer above runs
|
|
14439
|
+
// exactly once, so a legacy `?<key>=...` value that only becomes
|
|
14440
|
+
// visible on a later render would otherwise be missed entirely —
|
|
14441
|
+
// `initialState` would resolve to `undefined`, and the migration
|
|
14442
|
+
// effect would strip the legacy param without ever piping it through
|
|
14443
|
+
// `onMigrated`. We re-read here when:
|
|
14444
|
+
// - the snapshot has nothing usable yet (`initialState === undefined`
|
|
14445
|
+
// AND the canonical URL slot has no valid value), and
|
|
14446
|
+
// - a legacy value has just appeared.
|
|
14447
|
+
// Once `initialState` is populated, this effect's guard short-circuits
|
|
14448
|
+
// and the rest of the lifecycle (restore + migration) takes over.
|
|
14449
|
+
react.useEffect(() => {
|
|
14450
|
+
if (initialState !== undefined || canonicalUrlHasValidState) {
|
|
14088
14451
|
return;
|
|
14089
14452
|
}
|
|
14090
|
-
if (
|
|
14453
|
+
if (legacySearchValue === undefined) {
|
|
14091
14454
|
return;
|
|
14092
14455
|
}
|
|
14093
|
-
|
|
14094
|
-
|
|
14095
|
-
|
|
14096
|
-
|
|
14097
|
-
|
|
14098
|
-
|
|
14099
|
-
|
|
14100
|
-
|
|
14101
|
-
|
|
14102
|
-
|
|
14103
|
-
|
|
14104
|
-
|
|
14456
|
+
setPersistedStateSnapshot({
|
|
14457
|
+
...readPersistedState({
|
|
14458
|
+
valueFromUrl: searchValueRef.current,
|
|
14459
|
+
legacyValueFromUrl: legacySearchValue,
|
|
14460
|
+
validateState: validateRef.current,
|
|
14461
|
+
transformFromUrlValue: fromUrlValueRef.current,
|
|
14462
|
+
}),
|
|
14463
|
+
readKey: persistedStateReadKey,
|
|
14464
|
+
});
|
|
14465
|
+
}, [legacySearchValue, initialState, canonicalUrlHasValidState, persistedStateReadKey, readPersistedState]);
|
|
14466
|
+
const lastPersistedRef = react.useRef(initialState);
|
|
14467
|
+
react.useEffect(() => {
|
|
14468
|
+
lastPersistedRef.current = initialState;
|
|
14469
|
+
}, [initialState, localStorageEnabled, storageKey]);
|
|
14470
|
+
const hasRestoredUrlRef = react.useRef(false);
|
|
14471
|
+
react.useEffect(() => {
|
|
14472
|
+
hasRestoredUrlRef.current = false;
|
|
14473
|
+
}, [enabled, localStorageEnabled, storageKey, urlLocation]);
|
|
14474
|
+
react.useEffect(() => {
|
|
14475
|
+
if (hasRestoredUrlRef.current) {
|
|
14105
14476
|
return;
|
|
14106
14477
|
}
|
|
14107
|
-
|
|
14108
|
-
|
|
14109
|
-
//
|
|
14110
|
-
//
|
|
14111
|
-
//
|
|
14112
|
-
|
|
14113
|
-
|
|
14114
|
-
(last.owner === write.owner || write.owner === undefined)) {
|
|
14478
|
+
// Only a legacy search param is copied into the hash. Storage is not:
|
|
14479
|
+
// mirroring it on load is what put a layout into every history entry
|
|
14480
|
+
// (GLU-2396). Gate on `canonicalUrlHasValidState`, not on the raw
|
|
14481
|
+
// `searchValue`: an undecodable string in the hash slot must not block
|
|
14482
|
+
// the legacy copy, or the migration strips the search param and the
|
|
14483
|
+
// bad string is the only state left on the next reload.
|
|
14484
|
+
if (!enabled || !needsUrlRestore || initialState === undefined || canonicalUrlHasValidState) {
|
|
14115
14485
|
return;
|
|
14116
14486
|
}
|
|
14117
|
-
|
|
14118
|
-
|
|
14119
|
-
}, [
|
|
14487
|
+
hasRestoredUrlRef.current = true;
|
|
14488
|
+
updateSearchParam(encodeForUrl(initialState), { replace: true });
|
|
14489
|
+
}, [enabled, needsUrlRestore, initialState, canonicalUrlHasValidState, updateSearchParam, encodeForUrl]);
|
|
14490
|
+
// Strip the legacy search param so reloads come from the canonical hash
|
|
14491
|
+
// slot and the URL stays tidy. The hook is a no-op outside hash mode.
|
|
14492
|
+
// `hashAlreadyHasValue` is `true` only when the canonical hash slot
|
|
14493
|
+
// already holds *valid* state — a raw but undecodable string must not
|
|
14494
|
+
// suppress `onMigrated`, otherwise a valid legacy value would be lost
|
|
14495
|
+
// on the next reload (see `canonicalUrlHasValidState` for the same
|
|
14496
|
+
// reasoning in the restore effect above).
|
|
14497
|
+
useMigrateLegacySearchParam({
|
|
14498
|
+
key,
|
|
14499
|
+
enabled: hashActive,
|
|
14500
|
+
decode,
|
|
14501
|
+
fromUrlValue,
|
|
14502
|
+
validate,
|
|
14503
|
+
hashAlreadyHasValue: canonicalUrlHasValidState,
|
|
14504
|
+
onMigrated: react.useCallback((migrated) => {
|
|
14505
|
+
if (dequal.dequal(lastPersistedRef.current, migrated)) {
|
|
14506
|
+
return;
|
|
14507
|
+
}
|
|
14508
|
+
lastPersistedRef.current = migrated;
|
|
14509
|
+
if (localStorageEnabled) {
|
|
14510
|
+
const serialized = serializeRef.current
|
|
14511
|
+
? serializeRef.current(migrated)
|
|
14512
|
+
: sharedUtils.storageSerializer.serialize(migrated);
|
|
14513
|
+
rawLocalStorage.write(storageKey, serialized);
|
|
14514
|
+
}
|
|
14515
|
+
updateSearchParam(encodeForUrl(migrated), { replace: true });
|
|
14516
|
+
}, [encodeForUrl, localStorageEnabled, storageKey, updateSearchParam]),
|
|
14517
|
+
});
|
|
14120
14518
|
const persistState = react.useCallback((state) => {
|
|
14121
|
-
|
|
14122
|
-
|
|
14123
|
-
|
|
14124
|
-
|
|
14519
|
+
if (dequal.dequal(lastPersistedRef.current, state)) {
|
|
14520
|
+
return;
|
|
14521
|
+
}
|
|
14522
|
+
lastPersistedRef.current = state;
|
|
14523
|
+
if (localStorageEnabled) {
|
|
14524
|
+
const serialized = serializeRef.current ? serializeRef.current(state) : sharedUtils.storageSerializer.serialize(state);
|
|
14525
|
+
rawLocalStorage.write(storageKey, serialized);
|
|
14526
|
+
}
|
|
14527
|
+
updateSearchParam(encodeForUrl(state));
|
|
14528
|
+
}, [storageKey, encodeForUrl, localStorageEnabled, updateSearchParam]);
|
|
14529
|
+
const clearState = react.useCallback(() => {
|
|
14530
|
+
lastPersistedRef.current = undefined;
|
|
14531
|
+
if (localStorageEnabled) {
|
|
14532
|
+
rawLocalStorage.remove(storageKey);
|
|
14533
|
+
}
|
|
14534
|
+
updateSearchParam(undefined);
|
|
14535
|
+
}, [localStorageEnabled, storageKey, updateSearchParam]);
|
|
14536
|
+
const snapshotIsCurrent = persistedStateSnapshot.readKey === persistedStateReadKey;
|
|
14537
|
+
// Opening a shared URL should become this identity's saved layout. The
|
|
14538
|
+
// caller decides which identity is allowed to commit: this only writes
|
|
14539
|
+
// when the snapshot was read for the current storage key, so a late
|
|
14540
|
+
// identity resolution cannot persist the pre-merge value and drop fields
|
|
14541
|
+
// that live only in localStorage. A hash that is only the shareable
|
|
14542
|
+
// projection of what is already stored is left alone, so reloading this
|
|
14543
|
+
// account's own link does not replace hidden columns with the shorter URL form.
|
|
14544
|
+
const commitHydratedState = react.useCallback(() => {
|
|
14545
|
+
if (!snapshotIsCurrent || !localStorageEnabled) {
|
|
14546
|
+
return false;
|
|
14547
|
+
}
|
|
14548
|
+
if (!canonicalUrlHasValidState || initialState === undefined) {
|
|
14549
|
+
return true;
|
|
14550
|
+
}
|
|
14551
|
+
let stored;
|
|
14552
|
+
try {
|
|
14553
|
+
const raw = rawLocalStorage.read(storageKey);
|
|
14554
|
+
if (raw) {
|
|
14555
|
+
stored = validateRef.current(sharedUtils.storageSerializer.deserialize(raw));
|
|
14556
|
+
}
|
|
14557
|
+
}
|
|
14558
|
+
catch {
|
|
14559
|
+
stored = undefined;
|
|
14560
|
+
}
|
|
14561
|
+
if (stored !== undefined) {
|
|
14562
|
+
const projected = toUrlValueRef.current ? toUrlValueRef.current(stored) : stored;
|
|
14563
|
+
if (dequal.dequal(projected, canonicalUrlPayload)) {
|
|
14564
|
+
return true;
|
|
14565
|
+
}
|
|
14566
|
+
}
|
|
14567
|
+
const serialized = serializeRef.current
|
|
14568
|
+
? serializeRef.current(initialState)
|
|
14569
|
+
: sharedUtils.storageSerializer.serialize(initialState);
|
|
14570
|
+
rawLocalStorage.write(storageKey, serialized);
|
|
14571
|
+
lastPersistedRef.current = initialState;
|
|
14572
|
+
return true;
|
|
14573
|
+
}, [
|
|
14574
|
+
canonicalUrlHasValidState,
|
|
14575
|
+
canonicalUrlPayload,
|
|
14576
|
+
initialState,
|
|
14577
|
+
localStorageEnabled,
|
|
14578
|
+
snapshotIsCurrent,
|
|
14579
|
+
storageKey,
|
|
14580
|
+
]);
|
|
14581
|
+
return react.useMemo(() => ({ initialState, persistState, clearState, commitHydratedState }), [initialState, persistState, clearState, commitHydratedState]);
|
|
14125
14582
|
};
|
|
14126
14583
|
|
|
14127
|
-
/**
|
|
14128
|
-
* Syncs an encoded string value with a URL search parameter via Tanstack Router.
|
|
14129
|
-
*
|
|
14130
|
-
* Thin wrapper over {@link useUrlParamSync} with `location: "search"`; see it
|
|
14131
|
-
* for the write queue, the size guard (`MAX_URL_LENGTH`), and external-change
|
|
14132
|
-
* detection.
|
|
14133
|
-
*
|
|
14134
|
-
* @param options - Configuration for the search param sync.
|
|
14135
|
-
* @param options.key - The URL search parameter name.
|
|
14136
|
-
* @param options.enabled - Set to `false` to disable all URL interaction (default `true`).
|
|
14137
|
-
* @param options.onExternalChange - Called when the param changes externally.
|
|
14138
|
-
* @param options.replace - `true` to always use `replaceState`.
|
|
14139
|
-
*/
|
|
14140
|
-
const useSearchParamSync = (options) => useUrlParamSync({ ...options, location: "search" });
|
|
14141
|
-
|
|
14142
14584
|
/**
|
|
14143
14585
|
* Enumerates localStorage keys. Kept local so this file's exemption from the
|
|
14144
14586
|
* no-direct-storage-access rule is centralised, as in `usePersistedState`.
|
|
@@ -15502,6 +15944,7 @@ exports.LabeledValue = LabeledValue;
|
|
|
15502
15944
|
exports.LabeledValueList = LabeledValueList;
|
|
15503
15945
|
exports.List = List;
|
|
15504
15946
|
exports.ListItem = ListItem;
|
|
15947
|
+
exports.MAX_HASH_LENGTH = MAX_HASH_LENGTH;
|
|
15505
15948
|
exports.MAX_URL_LENGTH = MAX_URL_LENGTH;
|
|
15506
15949
|
exports.MenuContent = MenuContent;
|
|
15507
15950
|
exports.MenuDivider = MenuDivider;
|
|
@@ -15618,6 +16061,7 @@ exports.useDevicePixelRatio = useDevicePixelRatio;
|
|
|
15618
16061
|
exports.useElevatedReducer = useElevatedReducer;
|
|
15619
16062
|
exports.useElevatedState = useElevatedState;
|
|
15620
16063
|
exports.useGridAreas = useGridAreas;
|
|
16064
|
+
exports.useHashParamSync = useHashParamSync;
|
|
15621
16065
|
exports.useHold = useHold;
|
|
15622
16066
|
exports.useHover = useHover;
|
|
15623
16067
|
exports.useInfiniteScroll = useInfiniteScroll;
|