@trackunit/react-components 3.8.4 → 3.8.5-alpha-4acfba00274.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs.js +359 -804
- package/index.esm.js +360 -803
- package/package.json +6 -6
- package/src/hooks/persistence/usePersistedState.d.ts +35 -44
- package/src/hooks/persistence/useSearchParamSync.d.ts +7 -26
- package/src/hooks/persistence/useUrlParamSync.d.ts +71 -0
- package/src/index.d.ts +0 -1
- package/src/hooks/persistence/useHashParamSync.d.ts +0 -55
- package/src/hooks/persistence/useMigrateLegacySearchParam.d.ts +0 -62
package/index.esm.js
CHANGED
|
@@ -13477,6 +13477,90 @@ const useSessionStorage = (options) => useWebStorage(globalThis.sessionStorage,
|
|
|
13477
13477
|
*/
|
|
13478
13478
|
const useSessionStorageReducer = (options) => useWebStorageReducer(globalThis.sessionStorage, options);
|
|
13479
13479
|
|
|
13480
|
+
/**
|
|
13481
|
+
* Pure utilities for stamping a URL-persisted value with the identity that
|
|
13482
|
+
* wrote it.
|
|
13483
|
+
*
|
|
13484
|
+
* A URL (hash or search param) is shared by every account that uses the same
|
|
13485
|
+
* browser: it survives login redirects, history and bookmarks, and it takes
|
|
13486
|
+
* precedence over per-user localStorage when a page loads. Without a stamp
|
|
13487
|
+
* there is no way to tell "a colleague shared this link" from "the previous
|
|
13488
|
+
* account on this PC left its layout in the address bar" — and the second
|
|
13489
|
+
* case silently replaces the current user's saved state (GLU-2396).
|
|
13490
|
+
*
|
|
13491
|
+
* The stamp is a short, non-reversible fingerprint of `clientSideUserId`.
|
|
13492
|
+
* It is not a secret and not a security boundary; it only lets a reader
|
|
13493
|
+
* recognise a value written by a *different* identity on the same device.
|
|
13494
|
+
*/
|
|
13495
|
+
/**
|
|
13496
|
+
* Wire shape of a stamped URL value: `{ o: <fingerprint>, v: <payload> }`.
|
|
13497
|
+
* Values written before stamping existed are bare payloads and decode as
|
|
13498
|
+
* unowned (see {@link unwrapUrlOwner}).
|
|
13499
|
+
*/
|
|
13500
|
+
const stampedUrlValueSchema = z.object({
|
|
13501
|
+
o: z.string(),
|
|
13502
|
+
v: z.unknown(),
|
|
13503
|
+
});
|
|
13504
|
+
const FNV_OFFSET_BASIS = 0x811c9dc5;
|
|
13505
|
+
const FNV_PRIME = 0x01000193;
|
|
13506
|
+
/**
|
|
13507
|
+
* 32-bit FNV-1a of `identity`, rendered in base36 (≤ 7 chars).
|
|
13508
|
+
*
|
|
13509
|
+
* Synchronous and dependency-free so it can run inside a `useState`
|
|
13510
|
+
* initializer. Collisions are possible in theory but irrelevant here: a
|
|
13511
|
+
* collision can only make a foreign value look like the reader's own, which
|
|
13512
|
+
* is today's behaviour for every value.
|
|
13513
|
+
*
|
|
13514
|
+
* @param identity - The client-side user id to fingerprint.
|
|
13515
|
+
* @returns {string} A short stable fingerprint of `identity`.
|
|
13516
|
+
*/
|
|
13517
|
+
const identityFingerprint = (identity) => {
|
|
13518
|
+
let hash = FNV_OFFSET_BASIS;
|
|
13519
|
+
for (let index = 0; index < identity.length; index++) {
|
|
13520
|
+
hash ^= identity.charCodeAt(index);
|
|
13521
|
+
hash = Math.imul(hash, FNV_PRIME) >>> 0;
|
|
13522
|
+
}
|
|
13523
|
+
return hash.toString(36);
|
|
13524
|
+
};
|
|
13525
|
+
/**
|
|
13526
|
+
* Wraps a URL payload with the fingerprint of the identity writing it.
|
|
13527
|
+
*
|
|
13528
|
+
* @param value - The payload that would otherwise be encoded into the URL.
|
|
13529
|
+
* @param owner - Fingerprint of the writing identity (see {@link identityFingerprint}).
|
|
13530
|
+
* @returns {StampedUrlValue} The payload wrapped in its ownership envelope.
|
|
13531
|
+
*/
|
|
13532
|
+
const wrapUrlOwner = (value, owner) => ({ o: owner, v: value });
|
|
13533
|
+
/**
|
|
13534
|
+
* Splits a decoded URL value into its owner fingerprint and payload.
|
|
13535
|
+
* Bare (pre-stamping) payloads come back with `owner: undefined`.
|
|
13536
|
+
*
|
|
13537
|
+
* @param decoded - The decoded URL value, stamped or bare.
|
|
13538
|
+
* @returns {{ owner: string | undefined; value: unknown }} The owner fingerprint (if any) and the payload.
|
|
13539
|
+
*/
|
|
13540
|
+
const unwrapUrlOwner = (decoded) => {
|
|
13541
|
+
const stamped = stampedUrlValueSchema.safeParse(decoded);
|
|
13542
|
+
// `z.unknown()` accepts a missing key, so `{ o: "x" }` parses without `v`.
|
|
13543
|
+
// Such an object is a payload of its own, not an envelope; the `in` check
|
|
13544
|
+
// is what keeps it unowned. Do not remove it as redundant.
|
|
13545
|
+
return stamped.success && "v" in stamped.data
|
|
13546
|
+
? { owner: stamped.data.o, value: stamped.data.v }
|
|
13547
|
+
: { owner: undefined, value: decoded };
|
|
13548
|
+
};
|
|
13549
|
+
|
|
13550
|
+
/**
|
|
13551
|
+
* Generates a localStorage key, optionally scoped to a specific user.
|
|
13552
|
+
*
|
|
13553
|
+
* When `userId` is provided the key is `"key-userId"`.
|
|
13554
|
+
* When omitted the key is returned as-is (unscoped).
|
|
13555
|
+
*
|
|
13556
|
+
* @param key - Unique persistence identifier.
|
|
13557
|
+
* @param userId - Client-side user id to scope storage per user.
|
|
13558
|
+
* @returns {string} The combined storage key.
|
|
13559
|
+
*/
|
|
13560
|
+
const useStorageKey = (key, userId) => {
|
|
13561
|
+
return useMemo(() => (userId ? `${key}-${userId}` : key), [key, userId]);
|
|
13562
|
+
};
|
|
13563
|
+
|
|
13480
13564
|
/**
|
|
13481
13565
|
* Pure utilities for reading and writing single named entries inside a URL
|
|
13482
13566
|
* fragment (the part after `#`).
|
|
@@ -13605,183 +13689,6 @@ const writeHashKey = (hash, key, value) => {
|
|
|
13605
13689
|
return formatHash(next.join(TOKEN_SEPARATOR));
|
|
13606
13690
|
};
|
|
13607
13691
|
|
|
13608
|
-
/**
|
|
13609
|
-
* Default maximum length of the resulting URL fragment after adding one
|
|
13610
|
-
* persisted entry. Oversized new entries are skipped; oversized replacements
|
|
13611
|
-
* remove the stale entry so localStorage remains authoritative.
|
|
13612
|
-
*
|
|
13613
|
-
* The fragment is never sent to the server, so it is not subject to the
|
|
13614
|
-
* AWS WAF managed-rule `SizeRestrictions_QUERYSTRING` cap that applies to
|
|
13615
|
-
* search params (5000 bytes). 64 KB stays well below typical browser URL
|
|
13616
|
-
* limits (Chromium ≳ 100 KB, Firefox ≳ 64 KB on the address bar) while
|
|
13617
|
-
* still leaving generous headroom for any realistic table state.
|
|
13618
|
-
*/
|
|
13619
|
-
const MAX_HASH_LENGTH = 64 * 1024;
|
|
13620
|
-
/**
|
|
13621
|
-
* Syncs an encoded string value with a single named entry inside the URL
|
|
13622
|
-
* fragment (`location.hash`) via Tanstack Router.
|
|
13623
|
-
*
|
|
13624
|
-
* Behaviour mirrors `useSearchParamSync`, with two differences:
|
|
13625
|
-
* - Reads from and writes to `location.hash` instead of `location.search`.
|
|
13626
|
-
* - Oversized replacements remove stale values using
|
|
13627
|
-
* {@link MAX_HASH_LENGTH}, rather than the AWS-WAF-driven search-param cap.
|
|
13628
|
-
*
|
|
13629
|
-
* The fragment is treated as a sequence of `&`-separated tokens via the
|
|
13630
|
-
* pure utilities in `./hashFragment`. Foreign tokens (bare anchors, other
|
|
13631
|
-
* named entries) are preserved byte-for-byte on every write.
|
|
13632
|
-
*
|
|
13633
|
-
* @param options - Configuration for the hash entry sync.
|
|
13634
|
-
* @param options.key - The named entry inside the fragment.
|
|
13635
|
-
* @param options.enabled - Set to `false` to disable all URL interaction (default `true`).
|
|
13636
|
-
* @param options.onExternalChange - Called when the entry changes externally
|
|
13637
|
-
* (e.g. browser back/forward, pasted link, foreign router push).
|
|
13638
|
-
* @param options.replace - `true` to always use `replaceState` instead of pushState.
|
|
13639
|
-
*/
|
|
13640
|
-
const useHashParamSync = ({ key, enabled = true, onExternalChange, replace: replaceOption, }) => {
|
|
13641
|
-
const navigate = useNavigate();
|
|
13642
|
-
const location = useLocation();
|
|
13643
|
-
const router = useRouter();
|
|
13644
|
-
const lastWrittenRef = useRef(undefined);
|
|
13645
|
-
const pendingWriteRef = useRef(null);
|
|
13646
|
-
const onExternalChangeRef = useRef(onExternalChange);
|
|
13647
|
-
useEffect(() => {
|
|
13648
|
-
onExternalChangeRef.current = onExternalChange;
|
|
13649
|
-
}, [onExternalChange]);
|
|
13650
|
-
const currentHashValue = useMemo(() => {
|
|
13651
|
-
if (!enabled) {
|
|
13652
|
-
return undefined;
|
|
13653
|
-
}
|
|
13654
|
-
return readHashKey(location.hash, key);
|
|
13655
|
-
}, [enabled, location.hash, key]);
|
|
13656
|
-
useEffect(() => {
|
|
13657
|
-
if (!enabled) {
|
|
13658
|
-
return;
|
|
13659
|
-
}
|
|
13660
|
-
if (currentHashValue === undefined) {
|
|
13661
|
-
return;
|
|
13662
|
-
}
|
|
13663
|
-
if (currentHashValue === lastWrittenRef.current) {
|
|
13664
|
-
return;
|
|
13665
|
-
}
|
|
13666
|
-
if (lastWrittenRef.current === undefined) {
|
|
13667
|
-
return;
|
|
13668
|
-
}
|
|
13669
|
-
// A caller may have primed `lastWrittenRef` via `updateHashParam` while the
|
|
13670
|
-
// URL still carries the previous value (queued rAF / router pending). Treating
|
|
13671
|
-
// that stale URL as an external change reloads filter state from persistence
|
|
13672
|
-
// and can clear in-progress search input before the write lands.
|
|
13673
|
-
if (pendingWriteRef.current !== null) {
|
|
13674
|
-
return;
|
|
13675
|
-
}
|
|
13676
|
-
requestAnimationFrame(() => {
|
|
13677
|
-
onExternalChangeRef.current?.();
|
|
13678
|
-
});
|
|
13679
|
-
}, [currentHashValue, enabled]);
|
|
13680
|
-
// Writes are dispatched via a "pending write" queue rather than calling
|
|
13681
|
-
// `navigate` directly from inside the rAF callback. Tanstack Router's
|
|
13682
|
-
// `router.state.status === "pending"` is common during the first paint
|
|
13683
|
-
// of a route (loaders, suspense), and an earlier implementation that
|
|
13684
|
-
// simply returned in that case lost the write outright. A one-shot write
|
|
13685
|
-
// (a legacy search-param migrated into the hash, or the first edit)
|
|
13686
|
-
// would otherwise never land.
|
|
13687
|
-
//
|
|
13688
|
-
// The queue + retry pattern below makes writes reliable:
|
|
13689
|
-
// - `updateHashParam` stores the latest attempted write in
|
|
13690
|
-
// `pendingWriteRef` and schedules an rAF flush.
|
|
13691
|
-
// - `flushPendingWrite` only navigates when the router is idle; while
|
|
13692
|
-
// pending it leaves the write queued so it can fire later.
|
|
13693
|
-
// - A dedicated effect watches `router.state.status` and re-attempts
|
|
13694
|
-
// the flush whenever the router settles, draining the queue.
|
|
13695
|
-
const flushPendingWrite = useCallback(() => {
|
|
13696
|
-
const pending = pendingWriteRef.current;
|
|
13697
|
-
if (pending === null) {
|
|
13698
|
-
return;
|
|
13699
|
-
}
|
|
13700
|
-
if (router.state.status === "pending") {
|
|
13701
|
-
// Keep the write queued; the status-watcher effect below will retry
|
|
13702
|
-
// when the router transitions back to idle.
|
|
13703
|
-
return;
|
|
13704
|
-
}
|
|
13705
|
-
pendingWriteRef.current = null;
|
|
13706
|
-
const { encodedValue, options } = pending;
|
|
13707
|
-
let nextHash = writeHashKey(location.hash, key, encodedValue);
|
|
13708
|
-
let removedOversizedValue = false;
|
|
13709
|
-
if (nextHash.length > MAX_HASH_LENGTH) {
|
|
13710
|
-
if (currentHashValue === undefined) {
|
|
13711
|
-
return;
|
|
13712
|
-
}
|
|
13713
|
-
nextHash = writeHashKey(location.hash, key, undefined);
|
|
13714
|
-
removedOversizedValue = true;
|
|
13715
|
-
}
|
|
13716
|
-
const shouldReplace = removedOversizedValue
|
|
13717
|
-
? true
|
|
13718
|
-
: (options?.replace ?? replaceOption ?? !Boolean(currentHashValue));
|
|
13719
|
-
// Tanstack Router's `navigate({ hash })` expects the fragment body
|
|
13720
|
-
// *without* the leading `#` — the router adds the delimiter itself
|
|
13721
|
-
// when serialising the URL. Forwarding the `#`-prefixed value from
|
|
13722
|
-
// `writeHashKey` produces a doubled `##` in the address bar
|
|
13723
|
-
// (visually broken, even though browsers still parse the fragment
|
|
13724
|
-
// correctly because URL fragments start at the *first* `#`).
|
|
13725
|
-
const navigateHash = nextHash.startsWith("#") ? nextHash.slice(1) : nextHash;
|
|
13726
|
-
void navigate({
|
|
13727
|
-
to: ".",
|
|
13728
|
-
// Returning the same `prev` reference leaves the search params
|
|
13729
|
-
// unchanged. We must still pass `search` so router types are happy.
|
|
13730
|
-
search: (prev) => prev,
|
|
13731
|
-
hash: navigateHash,
|
|
13732
|
-
replace: shouldReplace,
|
|
13733
|
-
});
|
|
13734
|
-
}, [router.state.status, location.hash, key, currentHashValue, navigate, replaceOption]);
|
|
13735
|
-
useEffect(() => {
|
|
13736
|
-
if (router.state.status === "pending") {
|
|
13737
|
-
return;
|
|
13738
|
-
}
|
|
13739
|
-
if (pendingWriteRef.current === null) {
|
|
13740
|
-
return;
|
|
13741
|
-
}
|
|
13742
|
-
flushPendingWrite();
|
|
13743
|
-
}, [router.state.status, flushPendingWrite]);
|
|
13744
|
-
// Drop any queued write when the consumer unmounts. The queue + retry
|
|
13745
|
-
// pattern above keeps writes pending across a `router.state.status ===
|
|
13746
|
-
// "pending"` phase, which means a write scheduled just before a route
|
|
13747
|
-
// change could otherwise drain onto the *next* route once it settles.
|
|
13748
|
-
// Cancelling here preserves the original "writes are scoped to the
|
|
13749
|
-
// owning route" contract that the pre-queue implementation got for
|
|
13750
|
-
// free by dropping the write outright.
|
|
13751
|
-
useEffect(() => () => {
|
|
13752
|
-
pendingWriteRef.current = null;
|
|
13753
|
-
}, []);
|
|
13754
|
-
const updateHashParam = useCallback((encodedValue, options) => {
|
|
13755
|
-
if (!enabled) {
|
|
13756
|
-
return;
|
|
13757
|
-
}
|
|
13758
|
-
// Dedupe against either the last *committed* write or the value
|
|
13759
|
-
// currently queued for the next rAF. Both represent the caller's
|
|
13760
|
-
// intent so we don't schedule redundant rAF callbacks for identical
|
|
13761
|
-
// requests.
|
|
13762
|
-
const inFlightOrLastWritten = pendingWriteRef.current?.encodedValue ?? lastWrittenRef.current;
|
|
13763
|
-
if (encodedValue !== undefined && encodedValue === inFlightOrLastWritten) {
|
|
13764
|
-
return;
|
|
13765
|
-
}
|
|
13766
|
-
// Prime `lastWrittenRef` here (not inside `flushPendingWrite`) so
|
|
13767
|
-
// the external-change detector treats this value as the caller's
|
|
13768
|
-
// authoritative state even when the flush is a no-op (URL already
|
|
13769
|
-
// matches) or stays queued during a pending router phase. Without
|
|
13770
|
-
// priming, the next "external" change would look identical to the
|
|
13771
|
-
// initial render (`lastWrittenRef === undefined`) and the callback
|
|
13772
|
-
// would be skipped.
|
|
13773
|
-
lastWrittenRef.current = encodedValue;
|
|
13774
|
-
if (currentHashValue === encodedValue) {
|
|
13775
|
-
return;
|
|
13776
|
-
}
|
|
13777
|
-
pendingWriteRef.current = { encodedValue, options };
|
|
13778
|
-
requestAnimationFrame(() => {
|
|
13779
|
-
flushPendingWrite();
|
|
13780
|
-
});
|
|
13781
|
-
}, [enabled, currentHashValue, flushPendingWrite]);
|
|
13782
|
-
return useMemo(() => ({ searchValue: currentHashValue, updateSearchParam: updateHashParam }), [currentHashValue, updateHashParam]);
|
|
13783
|
-
};
|
|
13784
|
-
|
|
13785
13692
|
const searchRecordSchema = z.record(z.string(), z.unknown());
|
|
13786
13693
|
const primitiveSearchValueSchema = z.union([z.string(), z.number(), z.boolean()]);
|
|
13787
13694
|
/**
|
|
@@ -13804,373 +13711,187 @@ const readPrimitiveSearchParam = (search, key) => {
|
|
|
13804
13711
|
};
|
|
13805
13712
|
|
|
13806
13713
|
/**
|
|
13807
|
-
*
|
|
13808
|
-
*
|
|
13809
|
-
*
|
|
13810
|
-
* A URL (hash or search param) is shared by every account that uses the same
|
|
13811
|
-
* browser: it survives login redirects, history and bookmarks, and it takes
|
|
13812
|
-
* precedence over per-user localStorage when a page loads. Without a stamp
|
|
13813
|
-
* there is no way to tell "a colleague shared this link" from "the previous
|
|
13814
|
-
* account on this PC left its layout in the address bar" — and the second
|
|
13815
|
-
* case silently replaces the current user's saved state (GLU-2396).
|
|
13816
|
-
*
|
|
13817
|
-
* The stamp is a short, non-reversible fingerprint of `clientSideUserId`.
|
|
13818
|
-
* It is not a secret and not a security boundary; it only lets a reader
|
|
13819
|
-
* recognise a value written by a *different* identity on the same device.
|
|
13820
|
-
*/
|
|
13821
|
-
/**
|
|
13822
|
-
* Wire shape of a stamped URL value: `{ o: <fingerprint>, v: <payload> }`.
|
|
13823
|
-
* Values written before stamping existed are bare payloads and decode as
|
|
13824
|
-
* unowned (see {@link unwrapUrlOwner}).
|
|
13825
|
-
*/
|
|
13826
|
-
const stampedUrlValueSchema = z.object({
|
|
13827
|
-
o: z.string(),
|
|
13828
|
-
v: z.unknown(),
|
|
13829
|
-
});
|
|
13830
|
-
const FNV_OFFSET_BASIS = 0x811c9dc5;
|
|
13831
|
-
const FNV_PRIME = 0x01000193;
|
|
13832
|
-
/**
|
|
13833
|
-
* 32-bit FNV-1a of `identity`, rendered in base36 (≤ 7 chars).
|
|
13834
|
-
*
|
|
13835
|
-
* Synchronous and dependency-free so it can run inside a `useState`
|
|
13836
|
-
* initializer. Collisions are possible in theory but irrelevant here: a
|
|
13837
|
-
* collision can only make a foreign value look like the reader's own, which
|
|
13838
|
-
* is today's behaviour for every value.
|
|
13839
|
-
*
|
|
13840
|
-
* @param identity - The client-side user id to fingerprint.
|
|
13841
|
-
* @returns {string} A short stable fingerprint of `identity`.
|
|
13842
|
-
*/
|
|
13843
|
-
const identityFingerprint = (identity) => {
|
|
13844
|
-
let hash = FNV_OFFSET_BASIS;
|
|
13845
|
-
for (let index = 0; index < identity.length; index++) {
|
|
13846
|
-
hash ^= identity.charCodeAt(index);
|
|
13847
|
-
hash = Math.imul(hash, FNV_PRIME) >>> 0;
|
|
13848
|
-
}
|
|
13849
|
-
return hash.toString(36);
|
|
13850
|
-
};
|
|
13851
|
-
/**
|
|
13852
|
-
* Wraps a URL payload with the fingerprint of the identity writing it.
|
|
13853
|
-
*
|
|
13854
|
-
* @param value - The payload that would otherwise be encoded into the URL.
|
|
13855
|
-
* @param owner - Fingerprint of the writing identity (see {@link identityFingerprint}).
|
|
13856
|
-
* @returns {StampedUrlValue} The payload wrapped in its ownership envelope.
|
|
13857
|
-
*/
|
|
13858
|
-
const wrapUrlOwner = (value, owner) => ({ o: owner, v: value });
|
|
13859
|
-
/**
|
|
13860
|
-
* Splits a decoded URL value into its owner fingerprint and payload.
|
|
13861
|
-
* Bare (pre-stamping) payloads come back with `owner: undefined`.
|
|
13862
|
-
*
|
|
13863
|
-
* @param decoded - The decoded URL value, stamped or bare.
|
|
13864
|
-
* @returns {{ owner: string | undefined; value: unknown }} The owner fingerprint (if any) and the payload.
|
|
13865
|
-
*/
|
|
13866
|
-
const unwrapUrlOwner = (decoded) => {
|
|
13867
|
-
const stamped = stampedUrlValueSchema.safeParse(decoded);
|
|
13868
|
-
// `z.unknown()` accepts a missing key, so `{ o: "x" }` parses without `v`.
|
|
13869
|
-
// Such an object is a payload of its own, not an envelope; the `in` check
|
|
13870
|
-
// is what keeps it unowned. Do not remove it as redundant.
|
|
13871
|
-
return stamped.success && "v" in stamped.data
|
|
13872
|
-
? { owner: stamped.data.o, value: stamped.data.v }
|
|
13873
|
-
: { owner: undefined, value: decoded };
|
|
13874
|
-
};
|
|
13875
|
-
|
|
13876
|
-
/**
|
|
13877
|
-
* One-shot migration: if the URL still carries a legacy `?<key>=...`
|
|
13878
|
-
* search param from before this hook moved table-style state to the
|
|
13879
|
-
* fragment, decode it, hand it to the caller via `onMigrated`, then strip
|
|
13880
|
-
* the search param via a `replace` navigation so back/forward history
|
|
13881
|
-
* isn't polluted.
|
|
13882
|
-
*
|
|
13883
|
-
* Invariants:
|
|
13884
|
-
* - The strip navigation fires at most once per mount (guarded by
|
|
13885
|
-
* `hasStrippedRef`) so we don't loop on the navigation we ourselves
|
|
13886
|
-
* triggered.
|
|
13887
|
-
* - `onMigrated` is also fired at most once per mount (guarded by
|
|
13888
|
-
* `hasMigratedRef`), but its gating is independent of the strip:
|
|
13889
|
-
* if `hashAlreadyHasValue` flips `true → false` after the strip
|
|
13890
|
-
* (e.g. an external actor clears the canonical hash mid-mount), the
|
|
13891
|
-
* next render still gets a chance to migrate the legacy value into
|
|
13892
|
-
* the hash. Conflating the two flags would have permanently lost
|
|
13893
|
-
* the legacy state in that race.
|
|
13894
|
-
* - Never throws — a decode/validate failure silently drops the value
|
|
13895
|
-
* and still strips the search param. The legacy key is owned by this
|
|
13896
|
-
* codebase's persistence convention (camelCase + `Tp` suffix), so
|
|
13897
|
-
* stripping unparseable values cannot destroy third-party data.
|
|
13898
|
-
* - When `hashAlreadyHasValue` is `true` the hash wins: the search
|
|
13899
|
-
* param is stripped but `onMigrated` is not fired.
|
|
13900
|
-
* - The `location.hash` is preserved verbatim across the strip
|
|
13901
|
-
* navigation so any concurrent hash content (including a freshly
|
|
13902
|
-
* written value) survives the cleanup.
|
|
13903
|
-
*/
|
|
13904
|
-
const useMigrateLegacySearchParam = ({ key, enabled, decode, fromUrlValue, validate, hashAlreadyHasValue, onMigrated, }) => {
|
|
13905
|
-
const navigate = useNavigate();
|
|
13906
|
-
const location = useLocation();
|
|
13907
|
-
const search = useSearch({ strict: false, shouldThrow: false });
|
|
13908
|
-
// The three flags are tracked independently because they describe
|
|
13909
|
-
// distinct side effects with distinct lifetimes:
|
|
13910
|
-
//
|
|
13911
|
-
// - `hasStrippedRef` guards the cleanup navigation against looping
|
|
13912
|
-
// on the navigation we ourselves triggered.
|
|
13913
|
-
// - `hasMigratedRef` guards `onMigrated` against being called twice
|
|
13914
|
-
// with the same legacy value.
|
|
13915
|
-
// - `cachedRawValueRef` snapshots the legacy raw string the first
|
|
13916
|
-
// time we observe it. The strip navigation below removes the
|
|
13917
|
-
// value from `search` on the next render, so without a cache we
|
|
13918
|
-
// can never migrate it later. This matters in one specific edge
|
|
13919
|
-
// case: `hashAlreadyHasValue` is `true` on the first render (so
|
|
13920
|
-
// we skip `onMigrated` and just strip), then later flips to
|
|
13921
|
-
// `false` because another actor cleared the canonical hash. With
|
|
13922
|
-
// the cache the next render can still surface the legacy value.
|
|
13923
|
-
//
|
|
13924
|
-
// The previous implementation conflated all of this into a single
|
|
13925
|
-
// `hasRunRef`, which permanently lost the legacy state in that race.
|
|
13926
|
-
const hasStrippedRef = useRef(false);
|
|
13927
|
-
const hasMigratedRef = useRef(false);
|
|
13928
|
-
const cachedRawValueRef = useRef(undefined);
|
|
13929
|
-
const decodeRef = useRef(decode);
|
|
13930
|
-
const fromUrlValueRef = useRef(fromUrlValue);
|
|
13931
|
-
const validateRef = useRef(validate);
|
|
13932
|
-
const onMigratedRef = useRef(onMigrated);
|
|
13933
|
-
useEffect(() => {
|
|
13934
|
-
decodeRef.current = decode;
|
|
13935
|
-
fromUrlValueRef.current = fromUrlValue;
|
|
13936
|
-
validateRef.current = validate;
|
|
13937
|
-
onMigratedRef.current = onMigrated;
|
|
13938
|
-
}, [decode, fromUrlValue, validate, onMigrated]);
|
|
13939
|
-
useEffect(() => {
|
|
13940
|
-
if (!enabled) {
|
|
13941
|
-
return;
|
|
13942
|
-
}
|
|
13943
|
-
if (hasStrippedRef.current && hasMigratedRef.current) {
|
|
13944
|
-
return;
|
|
13945
|
-
}
|
|
13946
|
-
// Snapshot the raw value the first time we see it. After the strip
|
|
13947
|
-
// navigation below, `search?.[key]` is undefined, but a later
|
|
13948
|
-
// render that flips `hashAlreadyHasValue` back to `false` still
|
|
13949
|
-
// needs the original value to migrate.
|
|
13950
|
-
if (cachedRawValueRef.current === undefined) {
|
|
13951
|
-
cachedRawValueRef.current = readPrimitiveSearchParam(search, key);
|
|
13952
|
-
}
|
|
13953
|
-
const rawString = cachedRawValueRef.current;
|
|
13954
|
-
if (rawString === undefined) {
|
|
13955
|
-
// Nothing legacy to migrate yet. Don't flip either flag — the
|
|
13956
|
-
// param may appear on a later render (e.g. router still hydrating).
|
|
13957
|
-
return;
|
|
13958
|
-
}
|
|
13959
|
-
if (!hasMigratedRef.current && !hashAlreadyHasValue) {
|
|
13960
|
-
let migratedState;
|
|
13961
|
-
try {
|
|
13962
|
-
const decoded = decodeRef.current(rawString);
|
|
13963
|
-
const transformed = fromUrlValueRef.current ? fromUrlValueRef.current(decoded) : decoded;
|
|
13964
|
-
migratedState = validateRef.current(transformed);
|
|
13965
|
-
}
|
|
13966
|
-
catch {
|
|
13967
|
-
migratedState = undefined;
|
|
13968
|
-
}
|
|
13969
|
-
// Invalid legacy data is silently dropped: the search param is
|
|
13970
|
-
// still stripped below, so the URL stays clean. Surfacing a
|
|
13971
|
-
// console warning here would require disabling a lint rule, and
|
|
13972
|
-
// the data loss is bounded — localStorage holds the working state
|
|
13973
|
-
// for the current session, and the user's next interaction
|
|
13974
|
-
// repopulates the hash. We still flip the flag in the invalid
|
|
13975
|
-
// case so we don't burn cycles re-decoding the same bad string
|
|
13976
|
-
// on every render.
|
|
13977
|
-
hasMigratedRef.current = true;
|
|
13978
|
-
if (migratedState !== undefined) {
|
|
13979
|
-
onMigratedRef.current(migratedState);
|
|
13980
|
-
}
|
|
13981
|
-
}
|
|
13982
|
-
if (!hasStrippedRef.current) {
|
|
13983
|
-
hasStrippedRef.current = true;
|
|
13984
|
-
void navigate({
|
|
13985
|
-
to: ".",
|
|
13986
|
-
search: (prev) => ({ ...prev, [key]: undefined }),
|
|
13987
|
-
hash: location.hash,
|
|
13988
|
-
replace: true,
|
|
13989
|
-
});
|
|
13990
|
-
}
|
|
13991
|
-
}, [enabled, key, hashAlreadyHasValue, search, navigate, location.hash]);
|
|
13992
|
-
};
|
|
13993
|
-
|
|
13994
|
-
/**
|
|
13995
|
-
* Default maximum full URL length after adding one persisted search param
|
|
13996
|
-
* before the URL write is skipped (localStorage still persists the full state).
|
|
13714
|
+
* Maximum full URL length after adding one persisted search param before the
|
|
13715
|
+
* URL write is skipped (localStorage still persists the full state).
|
|
13997
13716
|
*
|
|
13998
13717
|
* Sized to stay safely below the AWS WAF managed-rule default
|
|
13999
|
-
* `SizeRestrictions_QUERYSTRING` cap of 5000 bytes for the entire
|
|
13718
|
+
* `SizeRestrictions_QUERYSTRING` cap of 5000 bytes for the entire
|
|
13719
|
+
* host + path + query + hash string.
|
|
14000
13720
|
*/
|
|
14001
13721
|
const MAX_URL_LENGTH = 5000;
|
|
14002
13722
|
/**
|
|
14003
|
-
*
|
|
13723
|
+
* Maximum length of the URL fragment after adding one persisted entry.
|
|
13724
|
+
* Oversized new entries are skipped; oversized replacements remove the stale
|
|
13725
|
+
* entry so localStorage remains authoritative.
|
|
14004
13726
|
*
|
|
14005
|
-
*
|
|
14006
|
-
*
|
|
14007
|
-
*
|
|
14008
|
-
*
|
|
14009
|
-
|
|
14010
|
-
|
|
14011
|
-
|
|
13727
|
+
* The fragment is never sent to the server, so the WAF cap above does not
|
|
13728
|
+
* apply. 64 KB stays well below typical browser URL limits (Chromium ≳ 100 KB,
|
|
13729
|
+
* Firefox ≳ 64 KB on the address bar) while leaving generous headroom for any
|
|
13730
|
+
* realistic table state.
|
|
13731
|
+
*/
|
|
13732
|
+
const MAX_HASH_LENGTH = 64 * 1024;
|
|
13733
|
+
/**
|
|
13734
|
+
* Syncs an encoded string value with a single named entry in the URL — either
|
|
13735
|
+
* a search param or an entry inside the hash fragment — via Tanstack Router.
|
|
13736
|
+
*
|
|
13737
|
+
* Writes go through the application router so other search params and
|
|
13738
|
+
* foreign fragment content are preserved. Each slot has a size guard
|
|
13739
|
+
* ({@link MAX_URL_LENGTH} for search, {@link MAX_HASH_LENGTH} for hash); an
|
|
13740
|
+
* oversized value is dropped from the URL and localStorage stays
|
|
13741
|
+
* authoritative. External changes to the entry (browser back/forward, a
|
|
13742
|
+
* pasted link, a foreign router push) fire `onExternalChange`.
|
|
13743
|
+
*
|
|
13744
|
+
* Writes are dispatched via a pending-write queue rather than calling
|
|
13745
|
+
* `navigate` directly. Tanstack Router's `router.state.status === "pending"`
|
|
13746
|
+
* is common during the first paint of a route (loaders, suspense), and an
|
|
13747
|
+
* implementation that simply returned in that case lost the write outright.
|
|
13748
|
+
* `updateSearchParam` stores the latest attempted write and schedules an rAF
|
|
13749
|
+
* flush; the flush only navigates when the router is idle, and an effect
|
|
13750
|
+
* retries whenever the router settles. A queued write is dropped on unmount so
|
|
13751
|
+
* it cannot drain onto the next route.
|
|
13752
|
+
*
|
|
13753
|
+
* @param options - Configuration for the URL entry sync.
|
|
13754
|
+
* @param options.key - The search param name or fragment entry name.
|
|
13755
|
+
* @param options.location - `"search"` or `"hash"`.
|
|
14012
13756
|
* @param options.enabled - Set to `false` to disable all URL interaction (default `true`).
|
|
14013
|
-
* @param options.onExternalChange - Called when the
|
|
14014
|
-
* @param options.replace - `true` to always use `replaceState
|
|
13757
|
+
* @param options.onExternalChange - Called when the entry changes externally.
|
|
13758
|
+
* @param options.replace - `true` to always use `replaceState`; `false` to always push.
|
|
13759
|
+
* Default: replace when the entry is being added, push when it already has a value.
|
|
14015
13760
|
*/
|
|
14016
|
-
const
|
|
13761
|
+
const useUrlParamSync = ({ key, location: urlLocation, enabled = true, onExternalChange, replace: replaceOption, }) => {
|
|
14017
13762
|
const navigate = useNavigate();
|
|
14018
13763
|
const location = useLocation();
|
|
14019
13764
|
const router = useRouter();
|
|
14020
13765
|
const search = useSearch({ strict: false, shouldThrow: false });
|
|
13766
|
+
const isHash = urlLocation === "hash";
|
|
14021
13767
|
const lastWrittenRef = useRef(undefined);
|
|
14022
13768
|
const pendingWriteRef = useRef(null);
|
|
14023
13769
|
const onExternalChangeRef = useRef(onExternalChange);
|
|
14024
13770
|
useEffect(() => {
|
|
14025
13771
|
onExternalChangeRef.current = onExternalChange;
|
|
14026
13772
|
}, [onExternalChange]);
|
|
14027
|
-
const
|
|
13773
|
+
const currentValue = useMemo(() => {
|
|
14028
13774
|
if (!enabled) {
|
|
14029
13775
|
return undefined;
|
|
14030
13776
|
}
|
|
14031
|
-
return readPrimitiveSearchParam(search, key);
|
|
14032
|
-
}, [enabled, search, key]);
|
|
13777
|
+
return isHash ? readHashKey(location.hash, key) : readPrimitiveSearchParam(search, key);
|
|
13778
|
+
}, [enabled, isHash, location.hash, search, key]);
|
|
14033
13779
|
useEffect(() => {
|
|
14034
|
-
if (!enabled) {
|
|
13780
|
+
if (!enabled || currentValue === undefined) {
|
|
14035
13781
|
return;
|
|
14036
13782
|
}
|
|
14037
|
-
if (
|
|
13783
|
+
if (currentValue === lastWrittenRef.current || lastWrittenRef.current === undefined) {
|
|
14038
13784
|
return;
|
|
14039
13785
|
}
|
|
14040
|
-
|
|
14041
|
-
|
|
14042
|
-
|
|
14043
|
-
|
|
14044
|
-
return;
|
|
14045
|
-
}
|
|
14046
|
-
// A caller may have primed `lastWrittenRef` via `updateSearchParam` while the
|
|
14047
|
-
// URL still carries the previous value (queued rAF / router pending). Treating
|
|
14048
|
-
// that stale URL as an external change reloads filter state from persistence
|
|
14049
|
-
// and can clear in-progress search input before the write lands.
|
|
13786
|
+
// A caller may have primed `lastWrittenRef` via `updateSearchParam` while
|
|
13787
|
+
// the URL still carries the previous value (queued rAF / router pending).
|
|
13788
|
+
// Treating that stale URL as an external change would reload state from
|
|
13789
|
+
// persistence before the write lands.
|
|
14050
13790
|
if (pendingWriteRef.current !== null) {
|
|
14051
13791
|
return;
|
|
14052
13792
|
}
|
|
14053
13793
|
requestAnimationFrame(() => {
|
|
14054
13794
|
onExternalChangeRef.current?.();
|
|
14055
13795
|
});
|
|
14056
|
-
}, [
|
|
14057
|
-
|
|
13796
|
+
}, [currentValue, enabled]);
|
|
13797
|
+
// Read through refs so the write path does not change identity on every
|
|
13798
|
+
// navigation; it only needs the location and current value at the moment it
|
|
13799
|
+
// flushes, which may be an animation frame after it was queued.
|
|
13800
|
+
const locationRef = useRef(location);
|
|
13801
|
+
const currentValueRef = useRef(currentValue);
|
|
13802
|
+
useEffect(() => {
|
|
13803
|
+
locationRef.current = location;
|
|
13804
|
+
currentValueRef.current = currentValue;
|
|
13805
|
+
}, [location, currentValue]);
|
|
13806
|
+
const getUrlLengthWithSearchParam = useCallback((paramValue, params) => {
|
|
13807
|
+
const { href, searchStr, hash } = locationRef.current;
|
|
14058
13808
|
const otherParamsLength = objectKeys(params)
|
|
14059
|
-
.filter(k => k !==
|
|
13809
|
+
.filter(k => k !== key)
|
|
14060
13810
|
.reduce((totalLength, k) => {
|
|
14061
13811
|
const kLen = encodeURIComponent(String(k)).length;
|
|
14062
13812
|
const v = params[k];
|
|
14063
13813
|
const vLen = v !== null && v !== undefined ? encodeURIComponent(String(v)).length : 0;
|
|
14064
13814
|
return totalLength + kLen + vLen + (totalLength > 0 ? 2 : 1);
|
|
14065
13815
|
}, 0);
|
|
14066
|
-
const urlBase =
|
|
14067
|
-
return urlBase + otherParamsLength + 1 +
|
|
14068
|
-
}, [
|
|
14069
|
-
// Writes are dispatched via a "pending write" queue rather than calling
|
|
14070
|
-
// `navigate` directly from inside the rAF callback. See the matching
|
|
14071
|
-
// comment block in `useHashParamSync` for the full rationale — in short,
|
|
14072
|
-
// navigating while `router.state.status === "pending"` was previously
|
|
14073
|
-
// dropped silently, which lost a one-shot write (a legacy search param
|
|
14074
|
-
// migrated into the URL, or the first edit) on routes that mount during
|
|
14075
|
-
// a loader-driven pending phase.
|
|
13816
|
+
const urlBase = href.length - (searchStr.length || 0) + (hash.length || 0);
|
|
13817
|
+
return urlBase + otherParamsLength + 1 + key.length + 1 + paramValue.length;
|
|
13818
|
+
}, [key]);
|
|
14076
13819
|
const flushPendingWrite = useCallback(() => {
|
|
14077
13820
|
const pending = pendingWriteRef.current;
|
|
14078
13821
|
if (pending === null) {
|
|
14079
13822
|
return;
|
|
14080
13823
|
}
|
|
14081
13824
|
if (router.state.status === "pending") {
|
|
14082
|
-
// Keep the write queued; the status-watcher effect
|
|
14083
|
-
// the next idle transition.
|
|
13825
|
+
// Keep the write queued; the status-watcher effect retries once idle.
|
|
14084
13826
|
return;
|
|
14085
13827
|
}
|
|
14086
13828
|
pendingWriteRef.current = null;
|
|
14087
|
-
const { encodedValue
|
|
14088
|
-
const
|
|
13829
|
+
const { encodedValue } = pending;
|
|
13830
|
+
const { hash } = locationRef.current;
|
|
13831
|
+
const valueInUrl = currentValueRef.current;
|
|
13832
|
+
const shouldReplace = replaceOption ?? !Boolean(valueInUrl);
|
|
13833
|
+
if (!isHash) {
|
|
13834
|
+
void navigate({
|
|
13835
|
+
to: ".",
|
|
13836
|
+
search: (prev) => getUrlLengthWithSearchParam(encodedValue ?? "", prev) <= MAX_URL_LENGTH
|
|
13837
|
+
? { ...prev, [key]: encodedValue }
|
|
13838
|
+
: { ...prev, [key]: undefined },
|
|
13839
|
+
hash,
|
|
13840
|
+
replace: shouldReplace,
|
|
13841
|
+
});
|
|
13842
|
+
return;
|
|
13843
|
+
}
|
|
13844
|
+
let nextHash = writeHashKey(hash, key, encodedValue);
|
|
13845
|
+
let removedOversizedValue = false;
|
|
13846
|
+
if (nextHash.length > MAX_HASH_LENGTH) {
|
|
13847
|
+
if (valueInUrl === undefined) {
|
|
13848
|
+
return;
|
|
13849
|
+
}
|
|
13850
|
+
nextHash = writeHashKey(hash, key, undefined);
|
|
13851
|
+
removedOversizedValue = true;
|
|
13852
|
+
}
|
|
14089
13853
|
void navigate({
|
|
14090
13854
|
to: ".",
|
|
14091
|
-
|
|
14092
|
-
|
|
14093
|
-
|
|
14094
|
-
|
|
14095
|
-
|
|
14096
|
-
|
|
14097
|
-
}
|
|
14098
|
-
},
|
|
14099
|
-
hash: location.hash,
|
|
14100
|
-
replace: shouldReplace,
|
|
13855
|
+
// Returning the same `prev` reference leaves the search params
|
|
13856
|
+
// unchanged; `search` must still be passed for the router types.
|
|
13857
|
+
search: (prev) => prev,
|
|
13858
|
+
// The router adds the `#` itself; forwarding it would double it.
|
|
13859
|
+
hash: nextHash.startsWith("#") ? nextHash.slice(1) : nextHash,
|
|
13860
|
+
replace: removedOversizedValue ? true : shouldReplace,
|
|
14101
13861
|
});
|
|
14102
|
-
}, [
|
|
14103
|
-
router.state.status,
|
|
14104
|
-
location.hash,
|
|
14105
|
-
key,
|
|
14106
|
-
currentSearchValue,
|
|
14107
|
-
navigate,
|
|
14108
|
-
replaceOption,
|
|
14109
|
-
getUrlLengthWithSearchParam,
|
|
14110
|
-
]);
|
|
13862
|
+
}, [router.state.status, replaceOption, isHash, navigate, getUrlLengthWithSearchParam, key]);
|
|
14111
13863
|
useEffect(() => {
|
|
14112
|
-
if (router.state.status === "pending") {
|
|
14113
|
-
return;
|
|
14114
|
-
}
|
|
14115
|
-
if (pendingWriteRef.current === null) {
|
|
13864
|
+
if (router.state.status === "pending" || pendingWriteRef.current === null) {
|
|
14116
13865
|
return;
|
|
14117
13866
|
}
|
|
14118
13867
|
flushPendingWrite();
|
|
14119
13868
|
}, [router.state.status, flushPendingWrite]);
|
|
14120
|
-
// Drop any queued write when the consumer unmounts. The queue + retry
|
|
14121
|
-
// pattern above keeps writes pending across a `router.state.status ===
|
|
14122
|
-
// "pending"` phase, which means a write scheduled just before a route
|
|
14123
|
-
// change could otherwise drain onto the *next* route once it settles
|
|
14124
|
-
// (e.g. a debounced filter write leaking into the destination route).
|
|
14125
|
-
// Cancelling here preserves the original "writes are scoped to the
|
|
14126
|
-
// owning route" contract that the pre-queue implementation got for
|
|
14127
|
-
// free by dropping the write outright.
|
|
14128
13869
|
useEffect(() => () => {
|
|
14129
13870
|
pendingWriteRef.current = null;
|
|
14130
13871
|
}, []);
|
|
14131
|
-
const updateSearchParam = useCallback((encodedValue
|
|
13872
|
+
const updateSearchParam = useCallback((encodedValue) => {
|
|
14132
13873
|
if (!enabled) {
|
|
14133
13874
|
return;
|
|
14134
13875
|
}
|
|
14135
|
-
// Dedupe against
|
|
14136
|
-
//
|
|
14137
|
-
// intent so we don't schedule redundant rAF callbacks for identical
|
|
14138
|
-
// requests.
|
|
13876
|
+
// Dedupe against the last committed write or the value already queued;
|
|
13877
|
+
// both represent the caller's intent.
|
|
14139
13878
|
const inFlightOrLastWritten = pendingWriteRef.current?.encodedValue ?? lastWrittenRef.current;
|
|
14140
13879
|
if (encodedValue !== undefined && encodedValue === inFlightOrLastWritten) {
|
|
14141
13880
|
return;
|
|
14142
13881
|
}
|
|
14143
|
-
// Prime
|
|
14144
|
-
//
|
|
14145
|
-
//
|
|
14146
|
-
// matches) or stays queued during a pending router phase. Without
|
|
14147
|
-
// priming, the next "external" change would look identical to the
|
|
14148
|
-
// initial render (`lastWrittenRef === undefined`) and the callback
|
|
14149
|
-
// would be skipped.
|
|
13882
|
+
// Prime here (not in the flush) so the external-change detector treats
|
|
13883
|
+
// this value as the caller's state even when the flush is a no-op or
|
|
13884
|
+
// stays queued during a pending router phase.
|
|
14150
13885
|
lastWrittenRef.current = encodedValue;
|
|
14151
|
-
if (
|
|
13886
|
+
if (currentValueRef.current === encodedValue) {
|
|
14152
13887
|
return;
|
|
14153
13888
|
}
|
|
14154
|
-
pendingWriteRef.current = { encodedValue
|
|
13889
|
+
pendingWriteRef.current = { encodedValue };
|
|
14155
13890
|
requestAnimationFrame(() => {
|
|
14156
13891
|
flushPendingWrite();
|
|
14157
13892
|
});
|
|
14158
|
-
}, [enabled,
|
|
14159
|
-
return useMemo(() => ({ searchValue:
|
|
14160
|
-
};
|
|
14161
|
-
|
|
14162
|
-
/**
|
|
14163
|
-
* Generates a localStorage key, optionally scoped to a specific user.
|
|
14164
|
-
*
|
|
14165
|
-
* When `userId` is provided the key is `"key-userId"`.
|
|
14166
|
-
* When omitted the key is returned as-is (unscoped).
|
|
14167
|
-
*
|
|
14168
|
-
* @param key - Unique persistence identifier.
|
|
14169
|
-
* @param userId - Client-side user id to scope storage per user.
|
|
14170
|
-
* @returns {string} The combined storage key.
|
|
14171
|
-
*/
|
|
14172
|
-
const useStorageKey = (key, userId) => {
|
|
14173
|
-
return useMemo(() => (userId ? `${key}-${userId}` : key), [key, userId]);
|
|
13893
|
+
}, [enabled, flushPendingWrite]);
|
|
13894
|
+
return useMemo(() => ({ searchValue: currentValue, updateSearchParam }), [currentValue, updateSearchParam]);
|
|
14174
13895
|
};
|
|
14175
13896
|
|
|
14176
13897
|
/**
|
|
@@ -14192,47 +13913,43 @@ const rawLocalStorage = {
|
|
|
14192
13913
|
* and writes changes to both.
|
|
14193
13914
|
*
|
|
14194
13915
|
* On mount the hook resolves the initial state as follows:
|
|
14195
|
-
* - If the
|
|
14196
|
-
* value, decode it and pass through `validate`.
|
|
14197
|
-
* - In `urlLocation: "hash"` mode, if the canonical hash slot has no valid
|
|
14198
|
-
* value but a **legacy** `?<key>=...` search param is present, decode and
|
|
14199
|
-
* validate that as a one-shot fallback. The value is copied into the hash
|
|
14200
|
-
* and the search param is stripped via a `replace` navigation.
|
|
14201
|
-
* - A value that comes only from localStorage is not written to the URL.
|
|
14202
|
-
* Copying it on load left a layout in history, bookmarks, and login
|
|
14203
|
-
* redirects, which then replayed an older layout over the saved one
|
|
14204
|
-
* (GLU-2396). The URL is written when the user changes the state.
|
|
13916
|
+
* - If the URL slot holds a value, decode it and pass through `validate`.
|
|
14205
13917
|
* - If localStorage is enabled, read and validate its value.
|
|
14206
13918
|
* - When `mergeWithStorageOnRead` is `false` (default): URL state wins
|
|
14207
13919
|
* entirely when present, otherwise fall back to localStorage.
|
|
14208
13920
|
* - When `mergeWithStorageOnRead` is `true`: shallow-merge URL fields over
|
|
14209
13921
|
* localStorage so fields stripped by `toUrlValue` survive via storage.
|
|
14210
13922
|
*
|
|
14211
|
-
*
|
|
14212
|
-
*
|
|
14213
|
-
*
|
|
14214
|
-
*
|
|
14215
|
-
*
|
|
14216
|
-
* `
|
|
14217
|
-
*
|
|
14218
|
-
*
|
|
14219
|
-
*
|
|
14220
|
-
*
|
|
14221
|
-
*
|
|
14222
|
-
*
|
|
14223
|
-
*
|
|
14224
|
-
*
|
|
14225
|
-
*
|
|
13923
|
+
* A value that comes only from localStorage is never written to the URL on
|
|
13924
|
+
* load. Copying it left a layout in history, bookmarks, and login redirects,
|
|
13925
|
+
* which then replayed an older layout over the saved one (GLU-2396). The URL
|
|
13926
|
+
* is written when the consumer persists a change.
|
|
13927
|
+
*
|
|
13928
|
+
* `persistState` writes to localStorage (`storageSerializer`) and to the URL
|
|
13929
|
+
* (via `toUrlValue` + encoding).
|
|
13930
|
+
* Each slot skips a value equal to its last write. The URL side compares what
|
|
13931
|
+
* would land in the URL (the `toUrlValue` projection and the identity stamp),
|
|
13932
|
+
* starting from the projection of the hydrated state and the stamp the URL
|
|
13933
|
+
* carries: echoing `initialState`, or changing only a field the projection
|
|
13934
|
+
* strips, writes no URL entry, while an equal state persisted after the
|
|
13935
|
+
* identity resolves rewrites the URL with its stamp. The storage side starts
|
|
13936
|
+
* from what localStorage held, so a consumer that persists `initialState`
|
|
13937
|
+
* after opening a link saves that link's state for the account that opened
|
|
13938
|
+
* it, and a reload of the account's own link writes nothing.
|
|
13939
|
+
* `persistToStorage` and `persistToUrl` are the same two halves exposed
|
|
13940
|
+
* separately for consumers that schedule them differently; passing `undefined`
|
|
13941
|
+
* removes the entry rather than writing an empty value.
|
|
13942
|
+
*
|
|
13943
|
+
* The snapshot is re-read when the storage key or the storage/merge options
|
|
13944
|
+
* change, in the same render, so a write in that commit already sees the
|
|
13945
|
+
* state for the new key.
|
|
14226
13946
|
*
|
|
14227
13947
|
* @param options - Configuration for the persisted state.
|
|
14228
13948
|
* @param options.key - Unique identifier used for both the URL slot and the localStorage key.
|
|
14229
13949
|
* @param options.validate - Called with the decoded/parsed value; must return `TState` or `undefined`.
|
|
14230
|
-
* @param options.serialize - Custom localStorage serialiser (default `storageSerializer.serialize`).
|
|
14231
13950
|
* @param options.toUrlValue - Transform applied before URL encoding (default: encode state as-is).
|
|
14232
13951
|
* @param options.fromUrlValue - Transform applied after URL decoding, before validation (default: identity).
|
|
14233
|
-
* @param options.enabled - When `false` the URL is neither read nor written (default `true`).
|
|
14234
13952
|
* @param options.localStorageEnabled - When `false` localStorage is neither read nor written (default `true`).
|
|
14235
|
-
* @param options.onExternalChange - Fired when the URL value changes externally (e.g. browser back).
|
|
14236
13953
|
* @param options.replace - Forwarded to the underlying URL sync hook.
|
|
14237
13954
|
* @param options.clientSideUserId - The user ID to use for the localStorage key.
|
|
14238
13955
|
* @param options.mergeWithStorageOnRead - Merge URL state on top of localStorage
|
|
@@ -14242,344 +13959,182 @@ const rawLocalStorage = {
|
|
|
14242
13959
|
* @param options.stampUrlWithIdentity - Stamp URL writes with the current identity so the login
|
|
14243
13960
|
* redirect can drop entries left by another account on this browser. Default `false`.
|
|
14244
13961
|
*/
|
|
14245
|
-
const usePersistedState = ({ key, validate,
|
|
13962
|
+
const usePersistedState = ({ key, validate, toUrlValue, fromUrlValue, localStorageEnabled = true, replace, clientSideUserId, mergeWithStorageOnRead = false, urlLocation = "search", stampUrlWithIdentity = false, }) => {
|
|
14246
13963
|
const { encode, decode } = useCustomEncoding();
|
|
14247
13964
|
// Fingerprint of the identity this hook writes URL values for. `undefined`
|
|
14248
13965
|
// while the identity is unresolved (or when stamping is off): writes are
|
|
14249
13966
|
// then unstamped.
|
|
14250
13967
|
const currentUrlOwner = useMemo(() => (stampUrlWithIdentity && clientSideUserId !== undefined ? identityFingerprint(clientSideUserId) : undefined), [stampUrlWithIdentity, clientSideUserId]);
|
|
14251
|
-
const
|
|
14252
|
-
const hashActive = enabled && urlLocation === "hash";
|
|
14253
|
-
// Both URL-sync hooks are mounted unconditionally to satisfy the Rules of
|
|
14254
|
-
// Hooks; the inactive one is gated off via `enabled: false` and is a
|
|
14255
|
-
// no-op at runtime.
|
|
14256
|
-
const searchSync = useSearchParamSync({
|
|
14257
|
-
key,
|
|
14258
|
-
enabled: searchActive,
|
|
14259
|
-
onExternalChange,
|
|
14260
|
-
replace,
|
|
14261
|
-
});
|
|
14262
|
-
const hashSync = useHashParamSync({
|
|
13968
|
+
const { searchValue: urlValue, updateSearchParam: updateUrlValue } = useUrlParamSync({
|
|
14263
13969
|
key,
|
|
14264
|
-
|
|
14265
|
-
onExternalChange,
|
|
13970
|
+
location: urlLocation,
|
|
14266
13971
|
replace,
|
|
14267
13972
|
});
|
|
14268
|
-
const { searchValue, updateSearchParam } = hashActive ? hashSync : searchSync;
|
|
14269
|
-
// In hash mode, also read the raw search params so a legacy `?<key>=...`
|
|
14270
|
-
// value can hydrate the initial state once, before the migration effect
|
|
14271
|
-
// strips it. In search mode this stays `undefined` so the legacy fallback
|
|
14272
|
-
// is inert.
|
|
14273
|
-
const rawSearch = useSearch({ strict: false, shouldThrow: false });
|
|
14274
|
-
const legacySearchValue = useMemo(() => {
|
|
14275
|
-
if (!hashActive) {
|
|
14276
|
-
return undefined;
|
|
14277
|
-
}
|
|
14278
|
-
return readPrimitiveSearchParam(rawSearch, key);
|
|
14279
|
-
}, [hashActive, rawSearch, key]);
|
|
14280
13973
|
const storageKey = useStorageKey(key, clientSideUserId);
|
|
13974
|
+
// `toUrlValue` is read through a ref so the write callbacks stay stable
|
|
13975
|
+
// when a consumer passes an inline function.
|
|
14281
13976
|
const toUrlValueRef = useRef(toUrlValue);
|
|
14282
13977
|
useEffect(() => {
|
|
14283
13978
|
toUrlValueRef.current = toUrlValue;
|
|
14284
13979
|
}, [toUrlValue]);
|
|
14285
|
-
const
|
|
14286
|
-
|
|
14287
|
-
|
|
14288
|
-
|
|
14289
|
-
|
|
14290
|
-
|
|
14291
|
-
|
|
14292
|
-
}, [validate]);
|
|
14293
|
-
const fromUrlValueRef = useRef(fromUrlValue);
|
|
14294
|
-
useEffect(() => {
|
|
14295
|
-
fromUrlValueRef.current = fromUrlValue;
|
|
14296
|
-
}, [fromUrlValue]);
|
|
14297
|
-
const searchValueRef = useRef(searchValue);
|
|
14298
|
-
useEffect(() => {
|
|
14299
|
-
searchValueRef.current = searchValue;
|
|
14300
|
-
}, [searchValue]);
|
|
14301
|
-
const legacySearchValueRef = useRef(legacySearchValue);
|
|
14302
|
-
useEffect(() => {
|
|
14303
|
-
legacySearchValueRef.current = legacySearchValue;
|
|
14304
|
-
}, [legacySearchValue]);
|
|
14305
|
-
const readPersistedState = useCallback(({ valueFromUrl, legacyValueFromUrl, validateState, transformFromUrlValue, }) => {
|
|
14306
|
-
// The ownership stamp is only read at the login redirect (see
|
|
14307
|
-
// `useStripForeignIdentityHash`); here it is unwrapped and discarded.
|
|
14308
|
-
const tryDecode = (raw) => {
|
|
14309
|
-
try {
|
|
14310
|
-
const { value } = unwrapUrlOwner(decode(raw));
|
|
14311
|
-
const transformed = transformFromUrlValue ? transformFromUrlValue(value) : value;
|
|
14312
|
-
const state = validateState(transformed);
|
|
14313
|
-
if (state === undefined) {
|
|
14314
|
-
return undefined;
|
|
14315
|
-
}
|
|
14316
|
-
return { state, payload: value };
|
|
14317
|
-
}
|
|
14318
|
-
catch {
|
|
14319
|
-
return undefined;
|
|
14320
|
-
}
|
|
14321
|
-
};
|
|
14322
|
-
const readStoredState = () => {
|
|
14323
|
-
if (!localStorageEnabled) {
|
|
13980
|
+
const readStoredState = useCallback((validateState) => {
|
|
13981
|
+
if (!localStorageEnabled) {
|
|
13982
|
+
return undefined;
|
|
13983
|
+
}
|
|
13984
|
+
try {
|
|
13985
|
+
const raw = rawLocalStorage.read(storageKey);
|
|
13986
|
+
if (!raw) {
|
|
14324
13987
|
return undefined;
|
|
14325
13988
|
}
|
|
13989
|
+
return validateState(storageSerializer.deserialize(raw));
|
|
13990
|
+
}
|
|
13991
|
+
catch {
|
|
13992
|
+
return undefined;
|
|
13993
|
+
}
|
|
13994
|
+
}, [localStorageEnabled, storageKey]);
|
|
13995
|
+
const readPersistedState = useCallback(({ valueFromUrl, validateState, transformFromUrlValue, }) => {
|
|
13996
|
+
let urlState;
|
|
13997
|
+
let urlStamp;
|
|
13998
|
+
if (valueFromUrl) {
|
|
14326
13999
|
try {
|
|
14327
|
-
|
|
14328
|
-
|
|
14329
|
-
|
|
14330
|
-
}
|
|
14331
|
-
|
|
14000
|
+
// The ownership stamp decides nothing on read (the login redirect
|
|
14001
|
+
// does that, see `useStripForeignIdentityHash`); it is kept only to
|
|
14002
|
+
// seed the URL dedupe with what the URL is currently stamped with.
|
|
14003
|
+
const { value, owner } = unwrapUrlOwner(decode(valueFromUrl));
|
|
14004
|
+
urlState = validateState(transformFromUrlValue ? transformFromUrlValue(value) : value);
|
|
14005
|
+
urlStamp = urlState === undefined ? undefined : { owner };
|
|
14332
14006
|
}
|
|
14333
14007
|
catch {
|
|
14334
|
-
|
|
14008
|
+
urlState = undefined;
|
|
14335
14009
|
}
|
|
14336
|
-
};
|
|
14337
|
-
let urlState;
|
|
14338
|
-
let decodedPayload;
|
|
14339
|
-
let canonicalUrlValid = false;
|
|
14340
|
-
let usedLegacyUrl = false;
|
|
14341
|
-
if (enabled && valueFromUrl) {
|
|
14342
|
-
const decoded = tryDecode(valueFromUrl);
|
|
14343
|
-
if (decoded !== undefined) {
|
|
14344
|
-
urlState = decoded.state;
|
|
14345
|
-
decodedPayload = decoded.payload;
|
|
14346
|
-
canonicalUrlValid = true;
|
|
14347
|
-
}
|
|
14348
|
-
}
|
|
14349
|
-
if (urlState === undefined && enabled && legacyValueFromUrl) {
|
|
14350
|
-
const decoded = tryDecode(legacyValueFromUrl);
|
|
14351
|
-
if (decoded !== undefined) {
|
|
14352
|
-
urlState = decoded.state;
|
|
14353
|
-
usedLegacyUrl = true;
|
|
14354
|
-
}
|
|
14355
|
-
}
|
|
14356
|
-
// Without the merge option, URL state wins entirely when present —
|
|
14357
|
-
// this preserves the original "URL > localStorage" priority.
|
|
14358
|
-
if (urlState !== undefined && !mergeWithStorageOnRead) {
|
|
14359
|
-
return {
|
|
14360
|
-
initialState: urlState,
|
|
14361
|
-
canonicalUrlHasValidState: canonicalUrlValid,
|
|
14362
|
-
canonicalUrlPayload: decodedPayload,
|
|
14363
|
-
needsUrlRestore: usedLegacyUrl,
|
|
14364
|
-
};
|
|
14365
14010
|
}
|
|
14366
|
-
|
|
14367
|
-
|
|
14368
|
-
|
|
14369
|
-
|
|
14370
|
-
|
|
14371
|
-
|
|
14372
|
-
|
|
14373
|
-
canonicalUrlPayload: decodedPayload,
|
|
14374
|
-
needsUrlRestore: usedLegacyUrl,
|
|
14375
|
-
};
|
|
14011
|
+
// Storage is read even when the URL wins outright: it seeds the storage
|
|
14012
|
+
// dedupe, so persisting the hydrated state writes only when the URL
|
|
14013
|
+
// changed something.
|
|
14014
|
+
const stored = readStoredState(validateState);
|
|
14015
|
+
let hydrated;
|
|
14016
|
+
if (urlState === undefined) {
|
|
14017
|
+
hydrated = stored;
|
|
14376
14018
|
}
|
|
14377
|
-
if (
|
|
14378
|
-
|
|
14379
|
-
|
|
14380
|
-
|
|
14381
|
-
canonicalUrlPayload: decodedPayload,
|
|
14382
|
-
needsUrlRestore: usedLegacyUrl,
|
|
14383
|
-
};
|
|
14019
|
+
else if (mergeWithStorageOnRead && stored !== undefined) {
|
|
14020
|
+
// URL fields take precedence; storage fills in whatever the URL
|
|
14021
|
+
// omits (e.g. fields stripped by `toUrlValue`).
|
|
14022
|
+
hydrated = { ...stored, ...urlState };
|
|
14384
14023
|
}
|
|
14385
|
-
|
|
14386
|
-
|
|
14387
|
-
|
|
14388
|
-
|
|
14389
|
-
|
|
14390
|
-
|
|
14391
|
-
|
|
14392
|
-
|
|
14393
|
-
|
|
14394
|
-
|
|
14395
|
-
|
|
14396
|
-
|
|
14397
|
-
|
|
14398
|
-
|
|
14399
|
-
|
|
14400
|
-
|
|
14401
|
-
|
|
14402
|
-
|
|
14403
|
-
|
|
14404
|
-
|
|
14405
|
-
|
|
14406
|
-
|
|
14407
|
-
|
|
14408
|
-
|
|
14409
|
-
|
|
14410
|
-
|
|
14411
|
-
|
|
14412
|
-
|
|
14413
|
-
|
|
14414
|
-
|
|
14415
|
-
|
|
14416
|
-
|
|
14417
|
-
|
|
14418
|
-
|
|
14419
|
-
|
|
14420
|
-
|
|
14421
|
-
|
|
14422
|
-
|
|
14423
|
-
|
|
14424
|
-
|
|
14425
|
-
|
|
14426
|
-
|
|
14427
|
-
|
|
14428
|
-
|
|
14429
|
-
|
|
14430
|
-
|
|
14431
|
-
|
|
14432
|
-
|
|
14433
|
-
|
|
14434
|
-
const { initialState, canonicalUrlHasValidState, canonicalUrlPayload, needsUrlRestore } = persistedStateSnapshot;
|
|
14435
|
-
// Late-hydration recovery: TanStack Router's `useSearch` can return an
|
|
14436
|
-
// empty object on the very first render of a route that's still in a
|
|
14437
|
-
// loader-driven pending phase. The `useState` initializer above runs
|
|
14438
|
-
// exactly once, so a legacy `?<key>=...` value that only becomes
|
|
14439
|
-
// visible on a later render would otherwise be missed entirely —
|
|
14440
|
-
// `initialState` would resolve to `undefined`, and the migration
|
|
14441
|
-
// effect would strip the legacy param without ever piping it through
|
|
14442
|
-
// `onMigrated`. We re-read here when:
|
|
14443
|
-
// - the snapshot has nothing usable yet (`initialState === undefined`
|
|
14444
|
-
// AND the canonical URL slot has no valid value), and
|
|
14445
|
-
// - a legacy value has just appeared.
|
|
14446
|
-
// Once `initialState` is populated, this effect's guard short-circuits
|
|
14447
|
-
// and the rest of the lifecycle (restore + migration) takes over.
|
|
14448
|
-
useEffect(() => {
|
|
14449
|
-
if (initialState !== undefined || canonicalUrlHasValidState) {
|
|
14450
|
-
return;
|
|
14451
|
-
}
|
|
14452
|
-
if (legacySearchValue === undefined) {
|
|
14453
|
-
return;
|
|
14454
|
-
}
|
|
14455
|
-
setPersistedStateSnapshot({
|
|
14456
|
-
...readPersistedState({
|
|
14457
|
-
valueFromUrl: searchValueRef.current,
|
|
14458
|
-
legacyValueFromUrl: legacySearchValue,
|
|
14459
|
-
validateState: validateRef.current,
|
|
14460
|
-
transformFromUrlValue: fromUrlValueRef.current,
|
|
14461
|
-
}),
|
|
14462
|
-
readKey: persistedStateReadKey,
|
|
14463
|
-
});
|
|
14464
|
-
}, [legacySearchValue, initialState, canonicalUrlHasValidState, persistedStateReadKey, readPersistedState]);
|
|
14465
|
-
const lastPersistedRef = useRef(initialState);
|
|
14466
|
-
useEffect(() => {
|
|
14467
|
-
lastPersistedRef.current = initialState;
|
|
14468
|
-
}, [initialState, localStorageEnabled, storageKey]);
|
|
14469
|
-
const hasRestoredUrlRef = useRef(false);
|
|
14470
|
-
useEffect(() => {
|
|
14471
|
-
hasRestoredUrlRef.current = false;
|
|
14472
|
-
}, [enabled, localStorageEnabled, storageKey, urlLocation]);
|
|
14024
|
+
else {
|
|
14025
|
+
hydrated = urlState;
|
|
14026
|
+
}
|
|
14027
|
+
return { initialState: hydrated, storedState: stored, urlValue: urlStamp };
|
|
14028
|
+
}, [decode, mergeWithStorageOnRead, readStoredState]);
|
|
14029
|
+
// The shareable projection of `state`: what a URL write carries before
|
|
14030
|
+
// encoding. The URL dedupe compares this, not the whole state, so a change
|
|
14031
|
+
// confined to a field `toUrlValue` strips is not a URL change.
|
|
14032
|
+
const projectForUrl = useCallback((state) => (toUrlValueRef.current ? toUrlValueRef.current(state) : state), []);
|
|
14033
|
+
// Every URL write goes through here so the ownership stamp is applied uniformly.
|
|
14034
|
+
const encodeUrlWrite = useCallback(({ projected, owner }) => encode(owner === undefined ? projected : wrapUrlOwner(projected, owner)), [encode]);
|
|
14035
|
+
// `readPersistedState` changes identity exactly when an input that changes
|
|
14036
|
+
// what a read returns does (storage key, storage/merge options), so the
|
|
14037
|
+
// snapshot is re-read then and only then — synchronously, in the render
|
|
14038
|
+
// where the input changed, by deriving state from the changed input. A URL
|
|
14039
|
+
// change after mount or an inline `validate` deliberately does not
|
|
14040
|
+
// re-hydrate `initialState`: `useUrlParamSync` owns URL changes.
|
|
14041
|
+
const readSnapshot = () => ({
|
|
14042
|
+
readWith: readPersistedState,
|
|
14043
|
+
...readPersistedState({ valueFromUrl: urlValue, validateState: validate, transformFromUrlValue: fromUrlValue }),
|
|
14044
|
+
});
|
|
14045
|
+
const [snapshot, setSnapshot] = useState(readSnapshot);
|
|
14046
|
+
if (snapshot.readWith !== readPersistedState) {
|
|
14047
|
+
setSnapshot(readSnapshot());
|
|
14048
|
+
}
|
|
14049
|
+
const { initialState, storedState } = snapshot;
|
|
14050
|
+
// Last value written to each slot, for deduping. Two refs, not one, because
|
|
14051
|
+
// a consumer may schedule the two writes differently (storage at once, URL
|
|
14052
|
+
// debounced). Both are re-seeded whenever the snapshot is re-read so the
|
|
14053
|
+
// first write to a newly scoped key is never skipped.
|
|
14054
|
+
//
|
|
14055
|
+
// The storage side starts as what storage held, so persisting the hydrated
|
|
14056
|
+
// state after opening a link writes only when the URL changed something.
|
|
14057
|
+
//
|
|
14058
|
+
// The URL side holds what a write would put in the URL: the shareable
|
|
14059
|
+
// projection plus the owner stamp. It starts as the projection of the
|
|
14060
|
+
// hydrated value, so a consumer that echoes `initialState` on mount, or
|
|
14061
|
+
// changes only a field the projection strips, writes nothing: a layout read
|
|
14062
|
+
// from storage must not grow a URL entry (GLU-2396). Its owner starts as the
|
|
14063
|
+
// stamp the URL carries (or the current owner when the URL is empty), so an
|
|
14064
|
+
// equal state persisted after the identity resolves still rewrites the URL
|
|
14065
|
+
// with its stamp.
|
|
14066
|
+
const urlOwnerSeed = snapshot.urlValue ? snapshot.urlValue.owner : currentUrlOwner;
|
|
14067
|
+
const seedUrlWrite = useCallback((project) => initialState === undefined ? undefined : { projected: project(initialState), owner: urlOwnerSeed }, [initialState, urlOwnerSeed]);
|
|
14068
|
+
const lastStoredRef = useRef(storedState);
|
|
14069
|
+
// The first seed is computed during render, so it projects with the
|
|
14070
|
+
// `toUrlValue` prop rather than reading `toUrlValueRef` (refs are not read
|
|
14071
|
+
// in render); the projection is cheap, and later seeds come from the effect.
|
|
14072
|
+
const lastUrlRef = useRef(seedUrlWrite(state => (toUrlValue ? toUrlValue(state) : state)));
|
|
14473
14073
|
useEffect(() => {
|
|
14474
|
-
|
|
14074
|
+
lastStoredRef.current = storedState;
|
|
14075
|
+
lastUrlRef.current = seedUrlWrite(projectForUrl);
|
|
14076
|
+
}, [seedUrlWrite, projectForUrl, storedState]);
|
|
14077
|
+
const persistToStorage = useCallback((state) => {
|
|
14078
|
+
if (!localStorageEnabled) {
|
|
14475
14079
|
return;
|
|
14476
14080
|
}
|
|
14477
|
-
|
|
14478
|
-
|
|
14479
|
-
|
|
14480
|
-
// `searchValue`: an undecodable string in the hash slot must not block
|
|
14481
|
-
// the legacy copy, or the migration strips the search param and the
|
|
14482
|
-
// bad string is the only state left on the next reload.
|
|
14483
|
-
if (!enabled || !needsUrlRestore || initialState === undefined || canonicalUrlHasValidState) {
|
|
14081
|
+
if (state === undefined) {
|
|
14082
|
+
lastStoredRef.current = undefined;
|
|
14083
|
+
rawLocalStorage.remove(storageKey);
|
|
14484
14084
|
return;
|
|
14485
14085
|
}
|
|
14486
|
-
|
|
14487
|
-
updateSearchParam(encodeForUrl(initialState), { replace: true });
|
|
14488
|
-
}, [enabled, needsUrlRestore, initialState, canonicalUrlHasValidState, updateSearchParam, encodeForUrl]);
|
|
14489
|
-
// Strip the legacy search param so reloads come from the canonical hash
|
|
14490
|
-
// slot and the URL stays tidy. The hook is a no-op outside hash mode.
|
|
14491
|
-
// `hashAlreadyHasValue` is `true` only when the canonical hash slot
|
|
14492
|
-
// already holds *valid* state — a raw but undecodable string must not
|
|
14493
|
-
// suppress `onMigrated`, otherwise a valid legacy value would be lost
|
|
14494
|
-
// on the next reload (see `canonicalUrlHasValidState` for the same
|
|
14495
|
-
// reasoning in the restore effect above).
|
|
14496
|
-
useMigrateLegacySearchParam({
|
|
14497
|
-
key,
|
|
14498
|
-
enabled: hashActive,
|
|
14499
|
-
decode,
|
|
14500
|
-
fromUrlValue,
|
|
14501
|
-
validate,
|
|
14502
|
-
hashAlreadyHasValue: canonicalUrlHasValidState,
|
|
14503
|
-
onMigrated: useCallback((migrated) => {
|
|
14504
|
-
if (dequal(lastPersistedRef.current, migrated)) {
|
|
14505
|
-
return;
|
|
14506
|
-
}
|
|
14507
|
-
lastPersistedRef.current = migrated;
|
|
14508
|
-
if (localStorageEnabled) {
|
|
14509
|
-
const serialized = serializeRef.current
|
|
14510
|
-
? serializeRef.current(migrated)
|
|
14511
|
-
: storageSerializer.serialize(migrated);
|
|
14512
|
-
rawLocalStorage.write(storageKey, serialized);
|
|
14513
|
-
}
|
|
14514
|
-
updateSearchParam(encodeForUrl(migrated), { replace: true });
|
|
14515
|
-
}, [encodeForUrl, localStorageEnabled, storageKey, updateSearchParam]),
|
|
14516
|
-
});
|
|
14517
|
-
const persistState = useCallback((state) => {
|
|
14518
|
-
if (dequal(lastPersistedRef.current, state)) {
|
|
14086
|
+
if (dequal(lastStoredRef.current, state)) {
|
|
14519
14087
|
return;
|
|
14520
14088
|
}
|
|
14521
|
-
lastPersistedRef.current = state;
|
|
14522
|
-
if (localStorageEnabled) {
|
|
14523
|
-
const serialized = serializeRef.current ? serializeRef.current(state) : storageSerializer.serialize(state);
|
|
14524
|
-
rawLocalStorage.write(storageKey, serialized);
|
|
14525
|
-
}
|
|
14526
|
-
updateSearchParam(encodeForUrl(state));
|
|
14527
|
-
}, [storageKey, encodeForUrl, localStorageEnabled, updateSearchParam]);
|
|
14528
|
-
const clearState = useCallback(() => {
|
|
14529
|
-
lastPersistedRef.current = undefined;
|
|
14530
|
-
if (localStorageEnabled) {
|
|
14531
|
-
rawLocalStorage.remove(storageKey);
|
|
14532
|
-
}
|
|
14533
|
-
updateSearchParam(undefined);
|
|
14534
|
-
}, [localStorageEnabled, storageKey, updateSearchParam]);
|
|
14535
|
-
const snapshotIsCurrent = persistedStateSnapshot.readKey === persistedStateReadKey;
|
|
14536
|
-
// Opening a shared URL should become this identity's saved layout. The
|
|
14537
|
-
// caller decides which identity is allowed to commit: this only writes
|
|
14538
|
-
// when the snapshot was read for the current storage key, so a late
|
|
14539
|
-
// identity resolution cannot persist the pre-merge value and drop fields
|
|
14540
|
-
// that live only in localStorage. A hash that is only the shareable
|
|
14541
|
-
// projection of what is already stored is left alone, so reloading this
|
|
14542
|
-
// account's own link does not replace hidden columns with the shorter URL form.
|
|
14543
|
-
const commitHydratedState = useCallback(() => {
|
|
14544
|
-
if (!snapshotIsCurrent || !localStorageEnabled) {
|
|
14545
|
-
return false;
|
|
14546
|
-
}
|
|
14547
|
-
if (!canonicalUrlHasValidState || initialState === undefined) {
|
|
14548
|
-
return true;
|
|
14549
|
-
}
|
|
14550
|
-
let stored;
|
|
14551
14089
|
try {
|
|
14552
|
-
|
|
14553
|
-
|
|
14554
|
-
stored = validateRef.current(storageSerializer.deserialize(raw));
|
|
14555
|
-
}
|
|
14090
|
+
rawLocalStorage.write(storageKey, storageSerializer.serialize(state));
|
|
14091
|
+
lastStoredRef.current = state;
|
|
14556
14092
|
}
|
|
14557
14093
|
catch {
|
|
14558
|
-
|
|
14094
|
+
// Quota or a disabled store: the next write retries; the URL is unaffected.
|
|
14559
14095
|
}
|
|
14560
|
-
|
|
14561
|
-
|
|
14562
|
-
|
|
14563
|
-
|
|
14564
|
-
|
|
14096
|
+
}, [localStorageEnabled, storageKey]);
|
|
14097
|
+
const persistToUrl = useCallback((state) => {
|
|
14098
|
+
if (state === undefined) {
|
|
14099
|
+
lastUrlRef.current = undefined;
|
|
14100
|
+
updateUrlValue(undefined);
|
|
14101
|
+
return;
|
|
14565
14102
|
}
|
|
14566
|
-
const
|
|
14567
|
-
|
|
14568
|
-
|
|
14569
|
-
|
|
14570
|
-
|
|
14571
|
-
|
|
14572
|
-
|
|
14573
|
-
|
|
14574
|
-
|
|
14575
|
-
|
|
14576
|
-
|
|
14577
|
-
|
|
14578
|
-
|
|
14579
|
-
|
|
14580
|
-
|
|
14103
|
+
const write = { projected: projectForUrl(state), owner: currentUrlOwner };
|
|
14104
|
+
const last = lastUrlRef.current;
|
|
14105
|
+
// Same projection: write only to add or change a stamp. An unresolved
|
|
14106
|
+
// identity never rewrites a stamped URL just to strip the stamp; it is
|
|
14107
|
+
// re-stamped once the identity resolves.
|
|
14108
|
+
if (last !== undefined &&
|
|
14109
|
+
dequal(last.projected, write.projected) &&
|
|
14110
|
+
(last.owner === write.owner || write.owner === undefined)) {
|
|
14111
|
+
return;
|
|
14112
|
+
}
|
|
14113
|
+
lastUrlRef.current = write;
|
|
14114
|
+
updateUrlValue(encodeUrlWrite(write));
|
|
14115
|
+
}, [currentUrlOwner, encodeUrlWrite, projectForUrl, updateUrlValue]);
|
|
14116
|
+
const persistState = useCallback((state) => {
|
|
14117
|
+
persistToStorage(state);
|
|
14118
|
+
persistToUrl(state);
|
|
14119
|
+
}, [persistToStorage, persistToUrl]);
|
|
14120
|
+
return useMemo(() => ({ initialState, persistState, persistToStorage, persistToUrl }), [initialState, persistState, persistToStorage, persistToUrl]);
|
|
14581
14121
|
};
|
|
14582
14122
|
|
|
14123
|
+
/**
|
|
14124
|
+
* Syncs an encoded string value with a URL search parameter via Tanstack Router.
|
|
14125
|
+
*
|
|
14126
|
+
* Thin wrapper over {@link useUrlParamSync} with `location: "search"`; see it
|
|
14127
|
+
* for the write queue, the size guard (`MAX_URL_LENGTH`), and external-change
|
|
14128
|
+
* detection.
|
|
14129
|
+
*
|
|
14130
|
+
* @param options - Configuration for the search param sync.
|
|
14131
|
+
* @param options.key - The URL search parameter name.
|
|
14132
|
+
* @param options.enabled - Set to `false` to disable all URL interaction (default `true`).
|
|
14133
|
+
* @param options.onExternalChange - Called when the param changes externally.
|
|
14134
|
+
* @param options.replace - `true` to always use `replaceState`.
|
|
14135
|
+
*/
|
|
14136
|
+
const useSearchParamSync = (options) => useUrlParamSync({ ...options, location: "search" });
|
|
14137
|
+
|
|
14583
14138
|
/**
|
|
14584
14139
|
* Enumerates localStorage keys. Kept local so this file's exemption from the
|
|
14585
14140
|
* no-direct-storage-access rule is centralised, as in `usePersistedState`.
|
|
@@ -15029,6 +14584,8 @@ const useCursorUrlSync = ({ paramName = DEFAULT_PARAM_NAME, debounceMs = DEFAULT
|
|
|
15029
14584
|
...prev,
|
|
15030
14585
|
[paramNameRef.current]: cursor,
|
|
15031
14586
|
}),
|
|
14587
|
+
// Without this the router drops the fragment, and with it the table layout.
|
|
14588
|
+
hash: true,
|
|
15032
14589
|
replace: true,
|
|
15033
14590
|
});
|
|
15034
14591
|
}, debounceMs);
|
|
@@ -15905,4 +15462,4 @@ const useWindowActivity = ({ onFocus, onBlur, skip = false } = { onBlur: undefin
|
|
|
15905
15462
|
*/
|
|
15906
15463
|
setupLibraryTranslations();
|
|
15907
15464
|
|
|
15908
|
-
export { Alert, Badge, Breadcrumb, Button, Card, CardBody, CardFooter, CardHeader, Collapse, CompletionStatusIndicator, CopyButton, CopyableValue, DEFAULT_SKELETON_PREFERENCE_CARD_PROPS, DetailsList, EmptyState, EmptyValue, ExternalLink, GridAreas, Heading, Highlight, HorizontalOverflowScroller, Icon, IconButton, IdentityCard, IdentityCardSkeleton, Indicator, KPI, KPICard, KPICardSkeleton, KPISkeleton, LabeledValue, LabeledValueList, List, ListItem,
|
|
15465
|
+
export { Alert, Badge, Breadcrumb, Button, Card, CardBody, CardFooter, CardHeader, Collapse, CompletionStatusIndicator, CopyButton, CopyableValue, DEFAULT_SKELETON_PREFERENCE_CARD_PROPS, DetailsList, EmptyState, EmptyValue, ExternalLink, GridAreas, Heading, Highlight, HorizontalOverflowScroller, Icon, IconButton, IdentityCard, IdentityCardSkeleton, Indicator, KPI, KPICard, KPICardSkeleton, KPISkeleton, LabeledValue, LabeledValueList, List, ListItem, MAX_URL_LENGTH, MenuContent, MenuDivider, MenuItem, MenuTree, MoreMenu, Notice, PackageNameStoryComponent, Page, PageContent, PageHeader, PageHeaderKpiMetrics, PageHeaderSecondaryActions, PageHeaderTitle, Pagination, Polygon, Popover, PopoverContent, PopoverTitle, PopoverTrigger, Portal, PreferenceCard, PreferenceCardSkeleton, Prompt, ROLE_CARD, SHEET_TRANSITION_DURATION, SHEET_TRANSITION_DURATION_MS, SHEET_TRANSITION_EASING, SectionHeader, SegmentedValueBar, Sheet, Sidebar, SidebarContentLayout, SkeletonBlock, SkeletonLabel, SkeletonLines, Spacer, Spinner, StarButton, Tab, TabContent, TabList, Tabs, Tag, Text, ToggleGroup, Tooltip, TrendIndicator, TrendIndicators, ValueBar, ZStack, createGrid, cvaButton, cvaButtonPrefixSuffix, cvaButtonSpinner, cvaButtonSpinnerContainer, cvaClickable, cvaContainerStyles, cvaContentContainer, cvaContentWrapper, cvaDescriptionCard, cvaIconBackground, cvaIconButton, cvaImgStyles, cvaIndicator, cvaIndicatorIcon, cvaIndicatorIconBackground, cvaIndicatorLabel, cvaIndicatorPing, cvaInputContainer, cvaInteractableItem, cvaList, cvaListContainer, cvaListItem$1 as cvaListItem, cvaMenu, cvaMenuItem, cvaMenuItemLabel, cvaMenuItemPrefix, cvaMenuItemStyle, cvaMenuItemSuffix, cvaMenuList, cvaMenuListDivider, cvaMenuListItem, cvaMenuListMultiSelect, cvaPageHeader, cvaPageHeaderContainer, cvaPageHeaderHeading, cvaPreferenceCard, cvaTitleCard, cvaToggleGroup, cvaToggleGroupWithSlidingBackground, cvaToggleItem, cvaToggleItemContent, cvaToggleItemText, cvaZStackContainer, cvaZStackItem, defaultPageSize, docs, getDevicePixelRatio, getValueBarColorByValue, iconColorNames, iconPalette, noPagination, preferenceCardGrid, useBidirectionalScroll, useClickOutside, useContainerBreakpoints, useContinuousTimeout, useCopyToClipboard, useCursorUrlSync, useCustomEncoding, useDebounce, useDevicePixelRatio, useElevatedReducer, useElevatedState, useGridAreas, useHold, useHover, useInfiniteScroll, useIsFirstRender, useIsFullscreen, useIsTextTruncated, useKeyboardShortcut, useList, useListItemHeight, useLocalStorage, useLocalStorageReducer, useMeasure, useMenuSearchField, useMenuTree, useMergeRefs, useModifierKey, useOptionalPopoverContext, useOverflowBorder, useOverflowItems, usePersistedState, usePopoverContext, usePrevious, usePrompt, useRandomCSSLengths, useRelayPagination, useResize, useScrollBlock, useScrollDetection, useSearchParamSync, useSelfUpdatingRef, useSessionStorage, useSessionStorageReducer, useSheet, useSheetSnap, useStorageKey, useStripForeignIdentityHash, useTextSearch, useTimeout, useViewportBreakpoints, useWatch, useWindowActivity };
|