@solidnative-dev/navigation 0.0.0-stage → 0.1.0-alpha.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/dist/index.js ADDED
@@ -0,0 +1,3427 @@
1
+ import { Modal, Screen, ScreenStack, ScrollView, TabsHost, TabsScreen, View, createCausalPlatformEventHandler, createMemoryWarningCount, retainCausalNativeEvent, retainCausalPlatformEvent, } from "@solidnative-dev/core";
2
+ import { createComponent, effect, } from "@solidnative-dev/renderer";
3
+ import { Show, createContext, createMemo, createRoot, createSignal, getOwner, mapArray, onCleanup, onSettled, runWithOwner, untrack, useContext, } from "solid-js";
4
+ import { parseHref as parseTanStackHref, } from "@tanstack/history";
5
+ import { reportIsolatedError } from "./error-reporting.js";
6
+ import { TanStackNativeMatches } from "./tanstack-matches.js";
7
+ import { useTanStackNativeRouter } from "./tanstack-router.js";
8
+ export { createTanStackNativeRouter, getSolidNativeRouterStoreConfig, TanStackNativeLink, TanStackNativeRouterProvider, TanStackNativeRouteView, TanStackRootRoute, TanStackRoute, tanStackRedirect, useTanStackNativeNavigate, useTanStackNativeRouter, } from "./tanstack-router.js";
9
+ export { TanStackNativeMatch, TanStackNativeMatches, TanStackNativeOutlet, useTanStackNativeLoaderData, useTanStackNativeMatch, } from "./tanstack-matches.js";
10
+ export const NATIVE_HISTORY_RESTORATION_VERSION = 0;
11
+ export const NATIVE_HISTORY_MAX_ENTRIES = 512;
12
+ export const NATIVE_HISTORY_MAX_SERIALIZED_LENGTH = 1_048_576;
13
+ const NATIVE_HISTORY_MAX_ENTRY_ID_LENGTH = 256;
14
+ const NATIVE_HISTORY_MAX_HREF_LENGTH = 16_384;
15
+ const NATIVE_HISTORY_MAX_STATE_DEPTH = 64;
16
+ const NATIVE_HISTORY_MAX_STATE_VALUES = 100_000;
17
+ function cloneStateValue(value, path, context, depth) {
18
+ if (depth > NATIVE_HISTORY_MAX_STATE_DEPTH) {
19
+ throw new RangeError(`${path} exceeds the maximum navigation state depth of ${NATIVE_HISTORY_MAX_STATE_DEPTH}.`);
20
+ }
21
+ context.values++;
22
+ if (context.values > NATIVE_HISTORY_MAX_STATE_VALUES) {
23
+ throw new RangeError(`${path} exceeds the maximum navigation state size of ${NATIVE_HISTORY_MAX_STATE_VALUES} values.`);
24
+ }
25
+ if (value === null ||
26
+ typeof value === "string" ||
27
+ typeof value === "boolean") {
28
+ return value;
29
+ }
30
+ if (typeof value === "number") {
31
+ if (!Number.isFinite(value)) {
32
+ throw new TypeError(`${path} must contain only finite numbers.`);
33
+ }
34
+ return value;
35
+ }
36
+ if (typeof value !== "object") {
37
+ throw new TypeError(`${path} is not transport-safe navigation state.`);
38
+ }
39
+ if (context.ancestors.has(value)) {
40
+ throw new TypeError(`${path} contains a circular value.`);
41
+ }
42
+ if (Array.isArray(value)) {
43
+ context.ancestors.add(value);
44
+ const result = value.map((entry, index) => cloneStateValue(entry, `${path}[${String(index)}]`, context, depth + 1));
45
+ context.ancestors.delete(value);
46
+ return result;
47
+ }
48
+ const prototype = Object.getPrototypeOf(value);
49
+ if (prototype !== Object.prototype && prototype !== null) {
50
+ throw new TypeError(`${path} must be a plain transport-safe object.`);
51
+ }
52
+ context.ancestors.add(value);
53
+ const entries = Object.entries(value).map(([key, entry]) => [
54
+ key,
55
+ cloneStateValue(entry, `${path}.${key}`, context, depth + 1),
56
+ ]);
57
+ context.ancestors.delete(value);
58
+ return Object.fromEntries(entries);
59
+ }
60
+ function cloneValue(value, path = "navigation state") {
61
+ return cloneStateValue(value, path, { ancestors: new Set(), values: 0 }, 0);
62
+ }
63
+ function plainRecord(value, path) {
64
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
65
+ throw new TypeError(`${path} must be an object.`);
66
+ }
67
+ const prototype = Object.getPrototypeOf(value);
68
+ if (prototype !== Object.prototype && prototype !== null) {
69
+ throw new TypeError(`${path} must be a plain object.`);
70
+ }
71
+ return value;
72
+ }
73
+ function normalizeEntryId(value, path) {
74
+ if (typeof value !== "string" ||
75
+ value.length === 0 ||
76
+ value.length > NATIVE_HISTORY_MAX_ENTRY_ID_LENGTH ||
77
+ value.includes("\0")) {
78
+ throw new TypeError(`${path} must be a 1-${NATIVE_HISTORY_MAX_ENTRY_ID_LENGTH} character string without null bytes.`);
79
+ }
80
+ return value;
81
+ }
82
+ function normalizeHref(value, path = "navigation href") {
83
+ if (typeof value !== "string" ||
84
+ value.length === 0 ||
85
+ value.length > NATIVE_HISTORY_MAX_HREF_LENGTH ||
86
+ value.includes("\0")) {
87
+ throw new TypeError(`${path} must be a 1-${NATIVE_HISTORY_MAX_HREF_LENGTH} character string without null bytes.`);
88
+ }
89
+ return value;
90
+ }
91
+ function cloneEntry(entry) {
92
+ return {
93
+ id: entry.id,
94
+ href: entry.href,
95
+ state: cloneValue(entry.state),
96
+ };
97
+ }
98
+ function normalizeSnapshot(value) {
99
+ const snapshot = plainRecord(value, "native history snapshot");
100
+ if (!Array.isArray(snapshot.entries)) {
101
+ throw new TypeError("Native history snapshot entries must be an array.");
102
+ }
103
+ if (snapshot.entries.length === 0 ||
104
+ snapshot.entries.length > NATIVE_HISTORY_MAX_ENTRIES) {
105
+ throw new RangeError(`Native history requires 1-${NATIVE_HISTORY_MAX_ENTRIES} entries.`);
106
+ }
107
+ if (!Number.isInteger(snapshot.index) ||
108
+ snapshot.index < 0 ||
109
+ snapshot.index >= snapshot.entries.length) {
110
+ throw new RangeError(`Native history index ${String(snapshot.index)} is out of range.`);
111
+ }
112
+ const ids = new Set();
113
+ const entries = snapshot.entries.map((value, index) => {
114
+ const path = `native history snapshot entry ${String(index)}`;
115
+ const entry = plainRecord(value, path);
116
+ const id = normalizeEntryId(entry.id, `${path} id`);
117
+ if (ids.has(id)) {
118
+ throw new Error(`Duplicate native screen id: ${id}.`);
119
+ }
120
+ ids.add(id);
121
+ return {
122
+ id,
123
+ href: normalizeHref(entry.href, `${path} href`),
124
+ state: cloneValue(entry.state, `${path} state`),
125
+ };
126
+ });
127
+ return {
128
+ entries,
129
+ index: snapshot.index,
130
+ };
131
+ }
132
+ export function serializeNativeHistorySnapshot(snapshot) {
133
+ return serializeNormalizedNativeHistorySnapshot(normalizeSnapshot(snapshot));
134
+ }
135
+ function serializeNormalizedNativeHistorySnapshot(snapshot) {
136
+ const serialized = JSON.stringify({
137
+ version: NATIVE_HISTORY_RESTORATION_VERSION,
138
+ snapshot,
139
+ });
140
+ if (serialized.length > NATIVE_HISTORY_MAX_SERIALIZED_LENGTH) {
141
+ throw new RangeError(`Serialized native history exceeds ${NATIVE_HISTORY_MAX_SERIALIZED_LENGTH} characters.`);
142
+ }
143
+ return serialized;
144
+ }
145
+ export function deserializeNativeHistorySnapshot(serialized) {
146
+ if (typeof serialized !== "string") {
147
+ throw new TypeError("Serialized native history must be a string.");
148
+ }
149
+ if (serialized.length > NATIVE_HISTORY_MAX_SERIALIZED_LENGTH) {
150
+ throw new RangeError(`Serialized native history exceeds ${NATIVE_HISTORY_MAX_SERIALIZED_LENGTH} characters.`);
151
+ }
152
+ let decoded;
153
+ try {
154
+ decoded = JSON.parse(serialized);
155
+ }
156
+ catch {
157
+ throw new SyntaxError("Serialized native history is not valid JSON.");
158
+ }
159
+ const envelope = plainRecord(decoded, "native history restoration");
160
+ if (envelope.version !== NATIVE_HISTORY_RESTORATION_VERSION) {
161
+ throw new Error(`Unsupported native history restoration version: ${String(envelope.version)}.`);
162
+ }
163
+ return normalizeSnapshot(envelope.snapshot);
164
+ }
165
+ export class NativeHistory {
166
+ #listeners = new Set();
167
+ #platformTransitionBlockers = new Set();
168
+ #platformTransitionBlockerListeners = new Set();
169
+ #awaitingApplicationAck = new Set();
170
+ #pendingPlatform = new Map();
171
+ // Generated IDs are monotonic, so only restored IDs need to be reserved.
172
+ // Retaining every screen ID ever visited would turn ordinary push/pop churn
173
+ // into an unbounded history-side memory cost.
174
+ #reservedRestoredEntryIds = new Set();
175
+ #entries;
176
+ #index;
177
+ #nextEntry = 1;
178
+ #nextTransition = 1;
179
+ constructor(options = {}) {
180
+ if (options.snapshot !== undefined) {
181
+ const snapshot = normalizeSnapshot(options.snapshot);
182
+ serializeNormalizedNativeHistorySnapshot(snapshot);
183
+ this.#entries = [...snapshot.entries];
184
+ this.#index = snapshot.index;
185
+ for (const entry of this.#entries) {
186
+ this.#reservedRestoredEntryIds.add(entry.id);
187
+ }
188
+ }
189
+ else {
190
+ this.#entries = [
191
+ this.#createEntry(options.initialHref ?? "/", options.initialState ?? null),
192
+ ];
193
+ this.#index = 0;
194
+ serializeNormalizedNativeHistorySnapshot(this.snapshot);
195
+ }
196
+ }
197
+ get location() {
198
+ return cloneEntry(this.#entries[this.#index]);
199
+ }
200
+ get canGoBack() {
201
+ return this.#index > 0;
202
+ }
203
+ get canGoForward() {
204
+ return this.#index < this.#entries.length - 1;
205
+ }
206
+ get pendingApplicationTransitionCount() {
207
+ return this.#awaitingApplicationAck.size;
208
+ }
209
+ get hasPendingPlatformTransition() {
210
+ return this.#pendingPlatform.size > 0;
211
+ }
212
+ get hasPlatformTransitionBlockers() {
213
+ return this.#platformTransitionBlockers.size > 0;
214
+ }
215
+ get snapshot() {
216
+ return {
217
+ entries: this.#entries.map(cloneEntry),
218
+ index: this.#index,
219
+ };
220
+ }
221
+ subscribe(listener) {
222
+ this.#listeners.add(listener);
223
+ return () => {
224
+ this.#listeners.delete(listener);
225
+ };
226
+ }
227
+ subscribePlatformTransitionBlockers(listener) {
228
+ this.#platformTransitionBlockerListeners.add(listener);
229
+ return () => {
230
+ this.#platformTransitionBlockerListeners.delete(listener);
231
+ };
232
+ }
233
+ blockPlatformTransitions(blocker) {
234
+ const wasEmpty = this.#platformTransitionBlockers.size === 0;
235
+ const registered = (transition) => blocker(transition);
236
+ this.#platformTransitionBlockers.add(registered);
237
+ if (wasEmpty)
238
+ this.#notifyPlatformTransitionBlockers(true);
239
+ let active = true;
240
+ return () => {
241
+ if (!active)
242
+ return;
243
+ active = false;
244
+ if (!this.#platformTransitionBlockers.delete(registered))
245
+ return;
246
+ if (this.#platformTransitionBlockers.size === 0) {
247
+ this.#notifyPlatformTransitionBlockers(false);
248
+ }
249
+ };
250
+ }
251
+ push(href, state = null) {
252
+ if (this.#index + 1 >= NATIVE_HISTORY_MAX_ENTRIES) {
253
+ throw new RangeError(`Native history cannot exceed ${NATIVE_HISTORY_MAX_ENTRIES} active entries.`);
254
+ }
255
+ const from = this.#entries[this.#index];
256
+ const previousNextEntry = this.#nextEntry;
257
+ let to;
258
+ let next;
259
+ try {
260
+ to = this.#createEntry(href, state);
261
+ next = [...this.#entries.slice(0, this.#index + 1), to];
262
+ serializeNormalizedNativeHistorySnapshot({
263
+ entries: next,
264
+ index: this.#index + 1,
265
+ });
266
+ }
267
+ catch (error) {
268
+ this.#nextEntry = previousNextEntry;
269
+ throw error;
270
+ }
271
+ this.#entries = next;
272
+ this.#index++;
273
+ return this.#publish("push", "application", from, to, 1, true);
274
+ }
275
+ replace(href, state = null) {
276
+ const from = this.#entries[this.#index];
277
+ const to = {
278
+ ...from,
279
+ href: normalizeHref(href),
280
+ state: cloneValue(state),
281
+ };
282
+ const next = [...this.#entries];
283
+ next[this.#index] = to;
284
+ serializeNormalizedNativeHistorySnapshot({
285
+ entries: next,
286
+ index: this.#index,
287
+ });
288
+ this.#entries = next;
289
+ return this.#publish("replace", "application", from, to, 0, true);
290
+ }
291
+ back(count = 1) {
292
+ const targetIndex = this.#backIndex(count);
293
+ return this.#moveTo(targetIndex, "pop");
294
+ }
295
+ forward(count = 1) {
296
+ if (!Number.isInteger(count) || count < 1) {
297
+ throw new Error("Forward count must be a positive integer.");
298
+ }
299
+ const targetIndex = Math.min(this.#entries.length - 1, this.#index + count);
300
+ return this.#moveTo(targetIndex, "traverse");
301
+ }
302
+ go(delta) {
303
+ if (!Number.isInteger(delta)) {
304
+ throw new Error("History delta must be an integer.");
305
+ }
306
+ if (delta === 0)
307
+ return undefined;
308
+ const targetIndex = Math.min(this.#entries.length - 1, Math.max(0, this.#index + delta));
309
+ return this.#moveTo(targetIndex, delta < 0 ? "pop" : "traverse");
310
+ }
311
+ reset(entries, index = entries.length - 1) {
312
+ if (entries.length === 0 || entries.length > NATIVE_HISTORY_MAX_ENTRIES) {
313
+ throw new RangeError(`Native history reset requires 1-${NATIVE_HISTORY_MAX_ENTRIES} entries.`);
314
+ }
315
+ if (!Number.isInteger(index) || index < 0 || index >= entries.length) {
316
+ throw new RangeError(`Native history index ${String(index)} is out of range.`);
317
+ }
318
+ const from = this.#entries[this.#index];
319
+ const previousNextEntry = this.#nextEntry;
320
+ let next;
321
+ try {
322
+ next = entries.map((entry) => this.#createEntry(entry.href, entry.state));
323
+ serializeNormalizedNativeHistorySnapshot({ entries: next, index });
324
+ }
325
+ catch (error) {
326
+ this.#nextEntry = previousNextEntry;
327
+ throw error;
328
+ }
329
+ this.#entries = next;
330
+ this.#index = index;
331
+ const to = next[index];
332
+ return this.#publish("reset", "application", from, to, 0, true);
333
+ }
334
+ openDeepLink(href, state = null) {
335
+ if (this.#index + 1 >= NATIVE_HISTORY_MAX_ENTRIES) {
336
+ throw new RangeError(`Native history cannot exceed ${NATIVE_HISTORY_MAX_ENTRIES} active entries.`);
337
+ }
338
+ const from = this.#entries[this.#index];
339
+ const previousNextEntry = this.#nextEntry;
340
+ let to;
341
+ let next;
342
+ try {
343
+ to = this.#createEntry(href, state);
344
+ next = [...this.#entries.slice(0, this.#index + 1), to];
345
+ serializeNormalizedNativeHistorySnapshot({
346
+ entries: next,
347
+ index: this.#index + 1,
348
+ });
349
+ }
350
+ catch (error) {
351
+ this.#nextEntry = previousNextEntry;
352
+ throw error;
353
+ }
354
+ this.#entries = next;
355
+ this.#index++;
356
+ return this.#publish("push", "system", from, to, 1, true);
357
+ }
358
+ requestPlatformBack(count = 1) {
359
+ if (this.#pendingPlatform.size > 0) {
360
+ throw new Error("A platform navigation transition is already pending.");
361
+ }
362
+ const targetIndex = this.#backIndex(count);
363
+ if (targetIndex === this.#index)
364
+ return undefined;
365
+ const transition = this.#transition("pop", "platform", this.#entries[this.#index], this.#entries[targetIndex], targetIndex - this.#index);
366
+ this.#pendingPlatform.set(transition.id, { transition, targetIndex });
367
+ return transition;
368
+ }
369
+ completePlatformTransition(id, completed) {
370
+ const pending = this.#pendingPlatform.get(id);
371
+ if (pending === undefined)
372
+ return false;
373
+ this.#pendingPlatform.delete(id);
374
+ if (!completed)
375
+ return true;
376
+ if (this.#entries[this.#index].id !==
377
+ pending.transition.from.id) {
378
+ return false;
379
+ }
380
+ this.#index = pending.targetIndex;
381
+ this.#notify(pending.transition);
382
+ return true;
383
+ }
384
+ async isPlatformTransitionBlocked(id) {
385
+ const pending = this.#pendingPlatform.get(id);
386
+ if (pending === undefined) {
387
+ throw new Error(`Unknown platform navigation transition ${id}.`);
388
+ }
389
+ for (const blocker of [...this.#platformTransitionBlockers]) {
390
+ const blocked = await blocker({
391
+ ...pending.transition,
392
+ from: cloneEntry(pending.transition.from),
393
+ to: cloneEntry(pending.transition.to),
394
+ });
395
+ if (typeof blocked !== "boolean") {
396
+ throw new TypeError("A native platform transition blocker must return a boolean.");
397
+ }
398
+ if (blocked)
399
+ return true;
400
+ }
401
+ return false;
402
+ }
403
+ acknowledgeTransition(id) {
404
+ return this.#awaitingApplicationAck.delete(id);
405
+ }
406
+ acknowledgeApplicationTransition(id) {
407
+ return this.acknowledgeTransition(id);
408
+ }
409
+ #backIndex(count) {
410
+ if (!Number.isInteger(count) || count < 1) {
411
+ throw new Error("Back count must be a positive integer.");
412
+ }
413
+ return Math.max(0, this.#index - count);
414
+ }
415
+ #moveTo(targetIndex, kind) {
416
+ if (targetIndex === this.#index)
417
+ return undefined;
418
+ const from = this.#entries[this.#index];
419
+ const to = this.#entries[targetIndex];
420
+ const delta = targetIndex - this.#index;
421
+ this.#index = targetIndex;
422
+ return this.#publish(kind, "application", from, to, delta, true);
423
+ }
424
+ #createEntry(href, state) {
425
+ const normalizedHref = normalizeHref(href);
426
+ const normalizedState = cloneValue(state);
427
+ let id;
428
+ do {
429
+ id = `screen-${this.#nextEntry++}`;
430
+ } while (this.#reservedRestoredEntryIds.has(id));
431
+ return {
432
+ id,
433
+ href: normalizedHref,
434
+ state: normalizedState,
435
+ };
436
+ }
437
+ #transition(kind, origin, from, to, delta) {
438
+ return {
439
+ id: `navigation-${this.#nextTransition++}`,
440
+ kind,
441
+ origin,
442
+ from: cloneEntry(from),
443
+ to: cloneEntry(to),
444
+ delta,
445
+ };
446
+ }
447
+ #publish(kind, origin, from, to, delta, requiresAcknowledgement) {
448
+ const transition = this.#transition(kind, origin, from, to, delta);
449
+ if (requiresAcknowledgement) {
450
+ this.#awaitingApplicationAck.add(transition.id);
451
+ }
452
+ this.#notify(transition);
453
+ return transition;
454
+ }
455
+ #notify(transition) {
456
+ const update = {
457
+ transition,
458
+ snapshot: this.snapshot,
459
+ };
460
+ for (const listener of [...this.#listeners])
461
+ listener(update);
462
+ }
463
+ #notifyPlatformTransitionBlockers(hasBlockers) {
464
+ for (const listener of [...this.#platformTransitionBlockerListeners]) {
465
+ try {
466
+ listener(hasBlockers);
467
+ }
468
+ catch {
469
+ // Blocker-presence observers update presentation policy only. One
470
+ // failing observer cannot strand every future platform transition.
471
+ }
472
+ }
473
+ }
474
+ }
475
+ const TANSTACK_NATIVE_STATE_KEY = "__solidNativeState";
476
+ const nativeHistoryByTanStackHistory = new WeakMap();
477
+ function tanStackState(entry, index) {
478
+ const nativeState = entry.state;
479
+ let state;
480
+ if (nativeState !== null &&
481
+ typeof nativeState === "object" &&
482
+ !Array.isArray(nativeState)) {
483
+ state = nativeState;
484
+ }
485
+ else if (nativeState === null) {
486
+ state = {};
487
+ }
488
+ else {
489
+ state = { [TANSTACK_NATIVE_STATE_KEY]: nativeState };
490
+ }
491
+ const legacyKey = typeof state.key === "string" ? state.key : undefined;
492
+ const routerKey = typeof state.__TSR_key === "string"
493
+ ? state.__TSR_key
494
+ : (legacyKey ?? entry.id);
495
+ return {
496
+ ...state,
497
+ key: legacyKey ?? routerKey,
498
+ __TSR_key: routerKey,
499
+ __TSR_index: index,
500
+ };
501
+ }
502
+ function tanStackLocation(history) {
503
+ const snapshot = history.snapshot;
504
+ const entry = snapshot.entries[snapshot.index];
505
+ return parseTanStackHref(entry.href, tanStackState(entry, snapshot.index));
506
+ }
507
+ function tanStackAction(transition) {
508
+ switch (transition.kind) {
509
+ case "push":
510
+ return { type: "PUSH" };
511
+ case "replace":
512
+ case "reset":
513
+ return { type: "REPLACE" };
514
+ case "pop":
515
+ case "traverse":
516
+ if (transition.delta === -1)
517
+ return { type: "BACK" };
518
+ if (transition.delta === 1)
519
+ return { type: "FORWARD" };
520
+ return { type: "GO", index: transition.delta };
521
+ }
522
+ }
523
+ function assignedTanStackState(state, index, key) {
524
+ const source = state ? Object(state) : {};
525
+ return {
526
+ ...source,
527
+ key,
528
+ __TSR_key: key,
529
+ __TSR_index: index,
530
+ };
531
+ }
532
+ /**
533
+ * Adapts the native navigation state machine to TanStack Router's current
534
+ * framework-neutral history contract. Adapter-originated mutations are
535
+ * suppressed at the native subscription boundary and then published exactly
536
+ * once by TanStack history; platform backs and deep links enter through the
537
+ * native subscription and are translated into the matching TanStack action.
538
+ */
539
+ export function createTanStackNativeHistory(nativeHistory = new NativeHistory(), options = {}) {
540
+ let suppressNativeNotification = false;
541
+ let destroyed = false;
542
+ let nextLocationKey = 1;
543
+ let location = tanStackLocation(nativeHistory);
544
+ const subscribers = new Set();
545
+ let blockers = [];
546
+ const createLocationKey = () => {
547
+ const snapshot = nativeHistory.snapshot;
548
+ const activeKeys = new Set(snapshot.entries.map((entry, index) => tanStackState(entry, index).__TSR_key));
549
+ let key;
550
+ do {
551
+ key = `solid-native-${String(nextLocationKey++)}`;
552
+ } while (activeKeys.has(key));
553
+ return key;
554
+ };
555
+ const notify = (action) => {
556
+ location = tanStackLocation(nativeHistory);
557
+ for (const subscriber of [...subscribers]) {
558
+ subscriber({ location, action });
559
+ }
560
+ };
561
+ const mutate = (mutation, action) => {
562
+ suppressNativeNotification = true;
563
+ try {
564
+ mutation();
565
+ }
566
+ finally {
567
+ suppressNativeNotification = false;
568
+ }
569
+ notify(action);
570
+ };
571
+ const reportNavigationError = (error) => {
572
+ if (reportIsolatedError(options.onNavigationError, error))
573
+ return;
574
+ void Promise.resolve().then(() => {
575
+ throw error;
576
+ });
577
+ };
578
+ const isNavigationBlocked = async (action, currentLocation, nextLocation) => {
579
+ for (const blocker of [...blockers]) {
580
+ if (await blocker.blockerFn({
581
+ currentLocation,
582
+ nextLocation,
583
+ action,
584
+ })) {
585
+ try {
586
+ options.onBlocked?.();
587
+ }
588
+ catch {
589
+ // Navigation already stopped; observer failures are isolated.
590
+ }
591
+ return true;
592
+ }
593
+ }
594
+ return false;
595
+ };
596
+ const attemptNavigation = (action, navigateOptions, nextLocation, commit) => {
597
+ const run = async () => {
598
+ const next = nextLocation();
599
+ if (!(navigateOptions?.ignoreBlocker ?? false) &&
600
+ (await isNavigationBlocked(action, location, next))) {
601
+ return;
602
+ }
603
+ commit(next);
604
+ };
605
+ if ((navigateOptions?.ignoreBlocker ?? false) || blockers.length === 0) {
606
+ commit(nextLocation());
607
+ return;
608
+ }
609
+ void run().catch(reportNavigationError);
610
+ };
611
+ let removePlatformTransitionBlocker;
612
+ const syncPlatformTransitionBlocker = () => {
613
+ if (destroyed || blockers.length === 0) {
614
+ removePlatformTransitionBlocker?.();
615
+ removePlatformTransitionBlocker = undefined;
616
+ return;
617
+ }
618
+ if (removePlatformTransitionBlocker !== undefined)
619
+ return;
620
+ removePlatformTransitionBlocker = nativeHistory.blockPlatformTransitions(async (transition) => {
621
+ const snapshot = nativeHistory.snapshot;
622
+ const targetIndex = snapshot.entries.findIndex((entry) => entry.id === transition.to.id);
623
+ if (targetIndex < 0)
624
+ return true;
625
+ const next = parseTanStackHref(transition.to.href, tanStackState(transition.to, targetIndex));
626
+ const action = transition.delta === -1 ? "BACK" : "GO";
627
+ try {
628
+ return await isNavigationBlocked(action, location, next);
629
+ }
630
+ catch (error) {
631
+ reportNavigationError(error);
632
+ // A failed blocker must fail closed while a native dismissal is
633
+ // being held. The current screen remains mounted.
634
+ return true;
635
+ }
636
+ });
637
+ };
638
+ const unsubscribe = nativeHistory.subscribe(({ transition }) => {
639
+ if (destroyed || suppressNativeNotification)
640
+ return;
641
+ notify(tanStackAction(transition));
642
+ });
643
+ const traverse = (action, delta, navigateOptions) => {
644
+ if (!Number.isInteger(delta)) {
645
+ throw new Error("TanStack history delta must be an integer.");
646
+ }
647
+ const subscriberAction = action === "GO" ? { type: "GO", index: delta } : { type: action };
648
+ attemptNavigation(action, navigateOptions, () => {
649
+ const snapshot = nativeHistory.snapshot;
650
+ const target = Math.min(snapshot.entries.length - 1, Math.max(0, snapshot.index + delta));
651
+ const entry = snapshot.entries[target];
652
+ return parseTanStackHref(entry.href, tanStackState(entry, target));
653
+ }, () => {
654
+ mutate(() => nativeHistory.go(delta), subscriberAction);
655
+ });
656
+ };
657
+ const history = {
658
+ get location() {
659
+ return location;
660
+ },
661
+ get length() {
662
+ return nativeHistory.snapshot.entries.length;
663
+ },
664
+ subscribers,
665
+ subscribe(subscriber) {
666
+ subscribers.add(subscriber);
667
+ return () => subscribers.delete(subscriber);
668
+ },
669
+ push(href, state, navigateOptions) {
670
+ const key = createLocationKey();
671
+ attemptNavigation("PUSH", navigateOptions, () => parseTanStackHref(href, assignedTanStackState(state, nativeHistory.snapshot.index + 1, key)), (next) => {
672
+ mutate(() => nativeHistory.push(next.href, next.state), { type: "PUSH" });
673
+ });
674
+ },
675
+ replace(href, state, navigateOptions) {
676
+ const key = createLocationKey();
677
+ attemptNavigation("REPLACE", navigateOptions, () => parseTanStackHref(href, assignedTanStackState(state, nativeHistory.snapshot.index, key)), (next) => {
678
+ mutate(() => nativeHistory.replace(next.href, next.state), { type: "REPLACE" });
679
+ });
680
+ },
681
+ go(delta, navigateOptions) {
682
+ traverse("GO", delta, navigateOptions);
683
+ },
684
+ back(navigateOptions) {
685
+ traverse("BACK", -1, navigateOptions);
686
+ },
687
+ forward(navigateOptions) {
688
+ traverse("FORWARD", 1, navigateOptions);
689
+ },
690
+ canGoBack() {
691
+ return location.state.__TSR_index !== 0;
692
+ },
693
+ createHref: options.createHref ?? ((href) => href),
694
+ block(blocker) {
695
+ // One blocker object may be registered by more than one router owner.
696
+ // Keep each registration independently disposable, matching the native
697
+ // blocker registry and TanStack's subscription-shaped contract.
698
+ const registered = { ...blocker };
699
+ blockers = [...blockers, registered];
700
+ syncPlatformTransitionBlocker();
701
+ let active = true;
702
+ return () => {
703
+ if (!active)
704
+ return;
705
+ active = false;
706
+ blockers = blockers.filter((candidate) => candidate !== registered);
707
+ syncPlatformTransitionBlocker();
708
+ };
709
+ },
710
+ flush() { },
711
+ destroy() {
712
+ if (destroyed)
713
+ return;
714
+ destroyed = true;
715
+ nativeHistoryByTanStackHistory.delete(history);
716
+ removePlatformTransitionBlocker?.();
717
+ removePlatformTransitionBlocker = undefined;
718
+ unsubscribe();
719
+ },
720
+ notify,
721
+ };
722
+ nativeHistoryByTanStackHistory.set(history, nativeHistory);
723
+ return history;
724
+ }
725
+ /**
726
+ * Reconciles untrusted persistence and initial-URL inputs before the first
727
+ * native tree is mounted. An accepted deep link starts a fresh one-entry stack
728
+ * so restored screens cannot unexpectedly appear behind it. Invalid stored
729
+ * state is reported in the result and falls back to the configured initial
730
+ * location instead of making the application unlaunchable.
731
+ */
732
+ export function createNativeHistoryFromLaunch(options = {}) {
733
+ let initialURL;
734
+ if (options.initialURL !== undefined && options.initialURL !== null) {
735
+ initialURL = normalizeHref(options.initialURL, "native initial deep-link URL");
736
+ const target = options.resolveDeepLink === undefined
737
+ ? { href: initialURL, state: null }
738
+ : options.resolveDeepLink(initialURL);
739
+ if (target !== undefined) {
740
+ return {
741
+ history: new NativeHistory({
742
+ initialHref: target.href,
743
+ initialState: target.state ?? null,
744
+ }),
745
+ source: "deep-link",
746
+ initialURL,
747
+ };
748
+ }
749
+ }
750
+ let restorationError;
751
+ if (options.serializedSnapshot !== undefined &&
752
+ options.serializedSnapshot !== null) {
753
+ try {
754
+ return {
755
+ history: new NativeHistory({
756
+ snapshot: deserializeNativeHistorySnapshot(options.serializedSnapshot),
757
+ }),
758
+ source: "restoration",
759
+ ...(initialURL === undefined ? {} : { initialURL }),
760
+ };
761
+ }
762
+ catch (error) {
763
+ restorationError = error;
764
+ }
765
+ }
766
+ return {
767
+ history: new NativeHistory({
768
+ ...(options.initialHref === undefined
769
+ ? {}
770
+ : { initialHref: options.initialHref }),
771
+ ...(options.initialState === undefined
772
+ ? {}
773
+ : { initialState: options.initialState }),
774
+ }),
775
+ source: "initial",
776
+ ...(initialURL === undefined ? {} : { initialURL }),
777
+ ...(restorationError === undefined ? {} : { restorationError }),
778
+ };
779
+ }
780
+ function persistenceKey(value) {
781
+ if (typeof value !== "string" ||
782
+ value.length === 0 ||
783
+ value.length > 1_024 ||
784
+ value.includes("\0")) {
785
+ throw new TypeError("Native persistence storage key must be a 1-1024 character string without null bytes.");
786
+ }
787
+ return value;
788
+ }
789
+ /**
790
+ * Reads and validates the application shell's persisted navigation value
791
+ * before creating history. Corrupt or obsolete data, including a valid stack
792
+ * discarded by an accepted initial URL, is removed before launch returns;
793
+ * native storage availability errors still reject startup so the shell can
794
+ * choose its own recovery policy.
795
+ */
796
+ export async function createNativeHistoryFromStorage(options) {
797
+ const key = persistenceKey(options.storageKey);
798
+ const serializedSnapshot = await options.storage.getItem(key);
799
+ const result = createNativeHistoryFromLaunch({
800
+ ...(options.initialHref === undefined
801
+ ? {}
802
+ : { initialHref: options.initialHref }),
803
+ ...(options.initialState === undefined
804
+ ? {}
805
+ : { initialState: options.initialState }),
806
+ ...(options.initialURL === undefined
807
+ ? {}
808
+ : { initialURL: options.initialURL }),
809
+ ...(options.resolveDeepLink === undefined
810
+ ? {}
811
+ : { resolveDeepLink: options.resolveDeepLink }),
812
+ serializedSnapshot,
813
+ });
814
+ if (result.restorationError !== undefined ||
815
+ (result.source === "deep-link" && serializedSnapshot !== null)) {
816
+ await options.storage.removeItem(key);
817
+ }
818
+ return result;
819
+ }
820
+ /**
821
+ * Persists the initial snapshot and every subsequent navigation update. Writes
822
+ * are serialized so a slow native operation cannot overwrite newer state;
823
+ * updates that arrive while one write is pending coalesce to the newest
824
+ * snapshot. The current Solid owner disposes the subscription automatically.
825
+ */
826
+ export function createNativeHistoryPersistence(history, storage, options) {
827
+ const key = persistenceKey(options.storageKey);
828
+ let pending;
829
+ let draining = false;
830
+ let active = true;
831
+ const waiters = [];
832
+ const settleWaiters = (failed, failure) => {
833
+ const settled = waiters.splice(0);
834
+ for (const waiter of settled) {
835
+ if (failed)
836
+ waiter.reject(failure);
837
+ else
838
+ waiter.resolve();
839
+ }
840
+ };
841
+ const reportError = (error) => {
842
+ reportIsolatedError(options.onError, error);
843
+ };
844
+ const drain = async () => {
845
+ draining = true;
846
+ let failed = false;
847
+ let failure;
848
+ while (pending !== undefined) {
849
+ const serialized = pending;
850
+ pending = undefined;
851
+ try {
852
+ await storage.setItem(key, serialized);
853
+ }
854
+ catch (error) {
855
+ reportError(error);
856
+ // Retain the failed value unless an update that arrived during the
857
+ // native write already supplied a newer snapshot. Do not retry in a
858
+ // tight loop; the next explicit flush or history update owns retry.
859
+ pending ??= serialized;
860
+ failed = true;
861
+ failure = error;
862
+ break;
863
+ }
864
+ }
865
+ draining = false;
866
+ settleWaiters(failed, failure);
867
+ if (!failed && pending !== undefined)
868
+ void drain();
869
+ };
870
+ const schedule = (snapshot) => {
871
+ pending = serializeNativeHistorySnapshot(snapshot);
872
+ if (!draining)
873
+ void drain();
874
+ };
875
+ const unsubscribe = history.subscribe((update) => {
876
+ if (active)
877
+ schedule(update.snapshot);
878
+ });
879
+ schedule(history.snapshot);
880
+ const persistence = Object.freeze({
881
+ async flush() {
882
+ if (!draining && pending === undefined) {
883
+ return;
884
+ }
885
+ await new Promise((resolve, reject) => {
886
+ waiters.push({ resolve, reject });
887
+ if (!draining)
888
+ void drain();
889
+ });
890
+ },
891
+ dispose() {
892
+ if (!active)
893
+ return;
894
+ active = false;
895
+ unsubscribe();
896
+ },
897
+ });
898
+ // Standalone application shells can own the explicit disposable directly;
899
+ // component callers additionally inherit automatic Solid teardown.
900
+ if (getOwner() !== null)
901
+ onCleanup(() => persistence.dispose());
902
+ return persistence;
903
+ }
904
+ /** Portable bound imposed by Android's native BottomNavigationView. */
905
+ export const NATIVE_TABS_MAX_ITEMS = 5;
906
+ export const NATIVE_TABS_STATE_RESTORATION_VERSION = 0;
907
+ export const NATIVE_TABS_STATE_MAX_SERIALIZED_LENGTH = NATIVE_HISTORY_MAX_SERIALIZED_LENGTH * NATIVE_TABS_MAX_ITEMS + 16_384;
908
+ function inheritNativeScreenOptions(defaults, overrides) {
909
+ if (defaults === undefined)
910
+ return (overrides ?? {});
911
+ if (overrides === undefined)
912
+ return defaults;
913
+ // Option inheritance is intentionally shallow: native option values are
914
+ // atomic transport contracts. An explicit override, including `undefined`,
915
+ // owns that key and can therefore clear a navigator-wide default.
916
+ return { ...defaults, ...overrides };
917
+ }
918
+ const HARDWARE_BACK_EVENT_NAME = "platform.hardware-back.press";
919
+ const LIVE_URL_EVENT_NAME = "platform.url.open";
920
+ function requestHardwareBack(history, options) {
921
+ try {
922
+ const target = typeof history === "function" ? history() : history;
923
+ if (target === undefined)
924
+ return false;
925
+ const transition = target.requestPlatformBack();
926
+ if (transition === undefined)
927
+ return false;
928
+ if (target.hasPlatformTransitionBlockers) {
929
+ return {
930
+ history: target,
931
+ transition,
932
+ blocked: target.isPlatformTransitionBlocked(transition.id),
933
+ };
934
+ }
935
+ const completed = target.completePlatformTransition(transition.id, true);
936
+ if (completed)
937
+ options.onTransition?.(transition);
938
+ return completed;
939
+ }
940
+ catch (error) {
941
+ if (!reportIsolatedError(options.onError, error))
942
+ throw error;
943
+ // A navigation invariant failed after the application was offered Back.
944
+ // Consume the event so the Activity cannot exit behind a fatal overlay.
945
+ return true;
946
+ }
947
+ }
948
+ function settleHardwareBack(pending, options, retention) {
949
+ const run = (callback) => retention?.state === "active" ? retention.run(callback) : callback();
950
+ const settlement = pending.blocked
951
+ .then((blocked) => run(() => {
952
+ const completed = pending.history.completePlatformTransition(pending.transition.id, !blocked);
953
+ if (!completed)
954
+ return;
955
+ if (blocked)
956
+ options.onBlocked?.(pending.transition);
957
+ else
958
+ options.onTransition?.(pending.transition);
959
+ }))
960
+ .catch((error) => run(() => {
961
+ pending.history.completePlatformTransition(pending.transition.id, false);
962
+ if (!reportIsolatedError(options.onError, error))
963
+ throw error;
964
+ }));
965
+ if (retention === undefined) {
966
+ void settlement;
967
+ return;
968
+ }
969
+ void settlement.then(() => retention.finish(), (error) => {
970
+ retention.fail(error);
971
+ // Preserve the lower-level handler's global rejection when the
972
+ // application did not install an error callback.
973
+ throw error;
974
+ });
975
+ }
976
+ /**
977
+ * Creates the synchronous callback expected by React Native's Android
978
+ * BackHandler without importing React Native into this package. An accessor
979
+ * selects a retained tab's history at event time; an asynchronous blocker
980
+ * remains attached to that exact history even if selection changes meanwhile.
981
+ */
982
+ export function createHardwareBackHandler(history, options = {}) {
983
+ return () => {
984
+ const result = requestHardwareBack(history, options);
985
+ if (typeof result === "boolean")
986
+ return result;
987
+ settleHardwareBack(result, options);
988
+ return true;
989
+ };
990
+ }
991
+ function createCausalHardwareBackHandler(history, options = {}) {
992
+ return () => {
993
+ const result = requestHardwareBack(history, options);
994
+ if (typeof result === "boolean") {
995
+ return retainCausalPlatformEvent(result, (event) => event.finish());
996
+ }
997
+ return retainCausalPlatformEvent(true, (event) => settleHardwareBack(result, options, event));
998
+ };
999
+ }
1000
+ /**
1001
+ * Converts a React Native-compatible `{ url }` event into a system-originated
1002
+ * history transition without importing its Linking singleton.
1003
+ */
1004
+ export function createDeepLinkHandler(history, options = {}) {
1005
+ return (event) => {
1006
+ try {
1007
+ const payload = plainRecord(event, "native deep-link event");
1008
+ const url = normalizeHref(payload.url, "native deep-link URL");
1009
+ const target = options.resolve === undefined
1010
+ ? { href: url, state: null }
1011
+ : options.resolve(url);
1012
+ if (target === undefined)
1013
+ return undefined;
1014
+ const transition = history.openDeepLink(target.href, target.state ?? null);
1015
+ options.onTransition?.(transition);
1016
+ return transition;
1017
+ }
1018
+ catch (error) {
1019
+ if (!reportIsolatedError(options.onError, error))
1020
+ throw error;
1021
+ return undefined;
1022
+ }
1023
+ };
1024
+ }
1025
+ /**
1026
+ * Owns platform Back and live-link subscriptions for the current Solid owner.
1027
+ * The returned disposer is idempotent for callers that need an earlier stop.
1028
+ */
1029
+ export function createNativeNavigationBindings(history, source, options = {}) {
1030
+ const handleHardwareBack = createCausalPlatformEventHandler(HARDWARE_BACK_EVENT_NAME, createCausalHardwareBackHandler(history, options.hardwareBack), { priority: "discrete" });
1031
+ const handleDeepLink = createCausalPlatformEventHandler(LIVE_URL_EVENT_NAME, createDeepLinkHandler(history, options.deepLinks));
1032
+ const hardwareBack = source.subscribeHardwareBack(handleHardwareBack);
1033
+ let deepLinks;
1034
+ try {
1035
+ deepLinks = source.subscribeURL(handleDeepLink);
1036
+ }
1037
+ catch (error) {
1038
+ hardwareBack.remove();
1039
+ throw error;
1040
+ }
1041
+ let active = true;
1042
+ const bindings = Object.freeze({
1043
+ dispose() {
1044
+ if (!active)
1045
+ return;
1046
+ active = false;
1047
+ let firstError;
1048
+ try {
1049
+ hardwareBack.remove();
1050
+ }
1051
+ catch (error) {
1052
+ firstError = error;
1053
+ }
1054
+ try {
1055
+ deepLinks.remove();
1056
+ }
1057
+ catch (error) {
1058
+ firstError ??= error;
1059
+ }
1060
+ if (firstError !== undefined)
1061
+ throw firstError;
1062
+ },
1063
+ });
1064
+ if (getOwner() !== null)
1065
+ onCleanup(() => bindings.dispose());
1066
+ return bindings;
1067
+ }
1068
+ function dismissCount(event) {
1069
+ const payload = event.payload;
1070
+ if (payload === null ||
1071
+ typeof payload !== "object" ||
1072
+ Array.isArray(payload)) {
1073
+ return 1;
1074
+ }
1075
+ const value = payload.dismissCount;
1076
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0
1077
+ ? value
1078
+ : 1;
1079
+ }
1080
+ function normalizeNativeTabKey(value, path) {
1081
+ if (typeof value !== "string" ||
1082
+ value.length === 0 ||
1083
+ value.length > 128 ||
1084
+ value.includes("\0")) {
1085
+ throw new TypeError(`${path} must be a 1-128 character string without null bytes.`);
1086
+ }
1087
+ return value;
1088
+ }
1089
+ function normalizeNativeTabHistoryDefinitions(value) {
1090
+ if (!Array.isArray(value) || value.length === 0) {
1091
+ throw new TypeError("Native tabs state tabs must be a non-empty array.");
1092
+ }
1093
+ if (value.length > NATIVE_TABS_MAX_ITEMS) {
1094
+ throw new RangeError(`Native tabs state tabs must contain at most ${String(NATIVE_TABS_MAX_ITEMS)} items.`);
1095
+ }
1096
+ const keys = new Set();
1097
+ return value.map((rawDefinition, index) => {
1098
+ const definition = plainRecord(rawDefinition, `native tabs state tabs[${String(index)}]`);
1099
+ const key = normalizeNativeTabKey(definition.key, `native tabs state tabs[${String(index)}].key`);
1100
+ if (keys.has(key)) {
1101
+ throw new TypeError(`Native tabs state tab key ${JSON.stringify(key)} is duplicated.`);
1102
+ }
1103
+ keys.add(key);
1104
+ return {
1105
+ key,
1106
+ ...(definition.initialHref === undefined
1107
+ ? {}
1108
+ : {
1109
+ initialHref: normalizeHref(definition.initialHref, `native tabs state tabs[${String(index)}].initialHref`),
1110
+ }),
1111
+ ...(definition.initialState === undefined
1112
+ ? {}
1113
+ : {
1114
+ initialState: cloneValue(definition.initialState, `native tabs state tabs[${String(index)}].initialState`),
1115
+ }),
1116
+ };
1117
+ });
1118
+ }
1119
+ function normalizeNativeTabsStateSnapshot(value) {
1120
+ const snapshot = plainRecord(value, "native tabs state snapshot");
1121
+ if (!Array.isArray(snapshot.tabs) ||
1122
+ snapshot.tabs.length === 0 ||
1123
+ snapshot.tabs.length > NATIVE_TABS_MAX_ITEMS) {
1124
+ throw new RangeError(`Native tabs state snapshot requires 1-${String(NATIVE_TABS_MAX_ITEMS)} tabs.`);
1125
+ }
1126
+ const keys = new Set();
1127
+ const tabs = snapshot.tabs.map((rawTab, index) => {
1128
+ const tab = plainRecord(rawTab, `native tabs state snapshot tab ${String(index)}`);
1129
+ const key = normalizeNativeTabKey(tab.key, `native tabs state snapshot tab ${String(index)} key`);
1130
+ if (keys.has(key)) {
1131
+ throw new TypeError(`Native tabs state snapshot tab key ${JSON.stringify(key)} is duplicated.`);
1132
+ }
1133
+ keys.add(key);
1134
+ return { key, history: normalizeSnapshot(tab.history) };
1135
+ });
1136
+ const selectedKey = normalizeNativeTabKey(snapshot.selectedKey, "native tabs state snapshot selectedKey");
1137
+ if (!keys.has(selectedKey)) {
1138
+ throw new RangeError(`Native tabs state snapshot selectedKey ${JSON.stringify(selectedKey)} does not identify a tab.`);
1139
+ }
1140
+ return { selectedKey, tabs };
1141
+ }
1142
+ function normalizeNativeTabDeepLinkTarget(value) {
1143
+ const target = plainRecord(value, "native tab deep-link target");
1144
+ return {
1145
+ tabKey: normalizeNativeTabKey(target.tabKey, "native tab deep-link target.tabKey"),
1146
+ href: normalizeHref(target.href, "native tab deep-link target.href"),
1147
+ state: cloneValue(target.state ?? null, "native tab deep-link target.state"),
1148
+ };
1149
+ }
1150
+ function assertNativeTabsStateSnapshotCompatibility(definitions, snapshot) {
1151
+ const restoredKeys = new Set(snapshot.tabs.map((tab) => tab.key));
1152
+ if (restoredKeys.size !== definitions.length ||
1153
+ definitions.some((definition) => !restoredKeys.has(definition.key))) {
1154
+ throw new Error("Native tabs state restoration keys do not match the configured tabs.");
1155
+ }
1156
+ }
1157
+ export function serializeNativeTabsStateSnapshot(snapshot) {
1158
+ const serialized = JSON.stringify({
1159
+ version: NATIVE_TABS_STATE_RESTORATION_VERSION,
1160
+ snapshot: normalizeNativeTabsStateSnapshot(snapshot),
1161
+ });
1162
+ if (serialized.length > NATIVE_TABS_STATE_MAX_SERIALIZED_LENGTH) {
1163
+ throw new RangeError(`Serialized native tabs state exceeds ${String(NATIVE_TABS_STATE_MAX_SERIALIZED_LENGTH)} characters.`);
1164
+ }
1165
+ return serialized;
1166
+ }
1167
+ export function deserializeNativeTabsStateSnapshot(serialized) {
1168
+ if (typeof serialized !== "string") {
1169
+ throw new TypeError("Serialized native tabs state must be a string.");
1170
+ }
1171
+ if (serialized.length > NATIVE_TABS_STATE_MAX_SERIALIZED_LENGTH) {
1172
+ throw new RangeError(`Serialized native tabs state exceeds ${String(NATIVE_TABS_STATE_MAX_SERIALIZED_LENGTH)} characters.`);
1173
+ }
1174
+ let decoded;
1175
+ try {
1176
+ decoded = JSON.parse(serialized);
1177
+ }
1178
+ catch {
1179
+ throw new SyntaxError("Serialized native tabs state is not valid JSON.");
1180
+ }
1181
+ const envelope = plainRecord(decoded, "native tabs state restoration");
1182
+ if (envelope.version !== NATIVE_TABS_STATE_RESTORATION_VERSION) {
1183
+ throw new Error(`Unsupported native tabs state restoration version: ${String(envelope.version)}.`);
1184
+ }
1185
+ return normalizeNativeTabsStateSnapshot(envelope.snapshot);
1186
+ }
1187
+ /**
1188
+ * Owns one history per stable native-tab key and exposes selection as a Solid
1189
+ * accessor. A cross-tab deep link publishes one coherent state update after
1190
+ * both the target history and selected key have changed.
1191
+ */
1192
+ export function createNativeTabsState(options) {
1193
+ const definitions = normalizeNativeTabHistoryDefinitions(options.tabs);
1194
+ const restored = options.snapshot === undefined
1195
+ ? undefined
1196
+ : normalizeNativeTabsStateSnapshot(options.snapshot);
1197
+ if (restored !== undefined) {
1198
+ assertNativeTabsStateSnapshotCompatibility(definitions, restored);
1199
+ }
1200
+ const restoredTabs = new Map(restored?.tabs.map((tab) => [tab.key, tab.history]) ?? []);
1201
+ const histories = new Map(definitions.map((definition) => [
1202
+ definition.key,
1203
+ new NativeHistory(restored === undefined
1204
+ ? {
1205
+ ...(definition.initialHref === undefined
1206
+ ? {}
1207
+ : { initialHref: definition.initialHref }),
1208
+ ...(definition.initialState === undefined
1209
+ ? {}
1210
+ : { initialState: definition.initialState }),
1211
+ }
1212
+ : { snapshot: restoredTabs.get(definition.key) }),
1213
+ ]));
1214
+ const initialSelectedKey = normalizeNativeTabKey(restored?.selectedKey ?? options.selectedKey ?? definitions[0].key, "Native tabs state selectedKey");
1215
+ if (!histories.has(initialSelectedKey)) {
1216
+ throw new RangeError(`Native tabs state selectedKey ${JSON.stringify(initialSelectedKey)} does not identify a tab.`);
1217
+ }
1218
+ let currentSelectedKey = initialSelectedKey;
1219
+ // Solid 2 publishes signal writes at its flush boundary. Keep an immediate
1220
+ // canonical value for imperative snapshots/deep links while still reading
1221
+ // the signal so JSX consumers react in the next native transaction.
1222
+ const [reactiveSelectedKey, setReactiveSelectedKey] = createSignal(initialSelectedKey);
1223
+ const selectedKey = () => {
1224
+ reactiveSelectedKey();
1225
+ return currentSelectedKey;
1226
+ };
1227
+ const selectedHistory = () => histories.get(selectedKey());
1228
+ const listeners = new Set();
1229
+ let active = true;
1230
+ let suppressHistoryUpdate = false;
1231
+ const snapshot = () => ({
1232
+ selectedKey: currentSelectedKey,
1233
+ tabs: definitions.map((definition) => ({
1234
+ key: definition.key,
1235
+ history: histories.get(definition.key).snapshot,
1236
+ })),
1237
+ });
1238
+ const notify = (kind, tabKey, historyUpdate) => {
1239
+ const update = {
1240
+ kind,
1241
+ selectedKey: currentSelectedKey,
1242
+ tabKey,
1243
+ ...(historyUpdate === undefined ? {} : { historyUpdate }),
1244
+ snapshot: snapshot(),
1245
+ };
1246
+ for (const listener of [...listeners])
1247
+ listener(update);
1248
+ };
1249
+ const historySubscriptions = [...histories].map(([tabKey, history]) => history.subscribe((update) => {
1250
+ if (active && !suppressHistoryUpdate) {
1251
+ notify("history", tabKey, update);
1252
+ }
1253
+ }));
1254
+ const resolveHistory = (rawKey, path) => {
1255
+ const key = normalizeNativeTabKey(rawKey, path);
1256
+ const history = histories.get(key);
1257
+ if (history === undefined) {
1258
+ throw new RangeError(`Native tabs state tab key ${JSON.stringify(key)} does not identify a tab.`);
1259
+ }
1260
+ return history;
1261
+ };
1262
+ const assertActive = () => {
1263
+ if (!active)
1264
+ throw new Error("Native tabs state is disposed.");
1265
+ };
1266
+ const state = Object.freeze({
1267
+ selectedKey,
1268
+ selectedHistory,
1269
+ get snapshot() {
1270
+ return snapshot();
1271
+ },
1272
+ history(tabKey) {
1273
+ return resolveHistory(tabKey, "Native tabs state history key");
1274
+ },
1275
+ select(tabKey) {
1276
+ assertActive();
1277
+ const key = normalizeNativeTabKey(tabKey, "Native tabs state selected key");
1278
+ resolveHistory(key, "Native tabs state selected key");
1279
+ if (currentSelectedKey === key)
1280
+ return false;
1281
+ currentSelectedKey = key;
1282
+ setReactiveSelectedKey(key);
1283
+ notify("selection", key);
1284
+ return true;
1285
+ },
1286
+ handleTabSelected(selection) {
1287
+ if (selection === null || typeof selection !== "object") {
1288
+ throw new TypeError("Native tab selection must be an object.");
1289
+ }
1290
+ return state.select(selection.selectedKey);
1291
+ },
1292
+ openDeepLink(rawTarget) {
1293
+ assertActive();
1294
+ const target = normalizeNativeTabDeepLinkTarget(rawTarget);
1295
+ const history = resolveHistory(target.tabKey, "native tab deep-link target.tabKey");
1296
+ suppressHistoryUpdate = true;
1297
+ let transition;
1298
+ try {
1299
+ transition = history.openDeepLink(target.href, target.state ?? null);
1300
+ currentSelectedKey = target.tabKey;
1301
+ setReactiveSelectedKey(target.tabKey);
1302
+ }
1303
+ finally {
1304
+ suppressHistoryUpdate = false;
1305
+ }
1306
+ notify("deep-link", target.tabKey, {
1307
+ transition,
1308
+ snapshot: history.snapshot,
1309
+ });
1310
+ return transition;
1311
+ },
1312
+ subscribe(listener) {
1313
+ assertActive();
1314
+ if (typeof listener !== "function") {
1315
+ throw new TypeError("Native tabs state listener must be a function.");
1316
+ }
1317
+ listeners.add(listener);
1318
+ return () => {
1319
+ listeners.delete(listener);
1320
+ };
1321
+ },
1322
+ dispose() {
1323
+ if (!active)
1324
+ return;
1325
+ active = false;
1326
+ for (const unsubscribe of historySubscriptions)
1327
+ unsubscribe();
1328
+ listeners.clear();
1329
+ },
1330
+ });
1331
+ if (getOwner() !== null)
1332
+ onCleanup(() => state.dispose());
1333
+ return state;
1334
+ }
1335
+ /**
1336
+ * Resolves cold-launch precedence for native tabs. An accepted initial URL
1337
+ * starts the target tab directly at that route and discards restoration, so no
1338
+ * stale screen is exposed behind Back. Unhandled URLs still allow restoration.
1339
+ */
1340
+ export function createNativeTabsStateFromLaunch(options) {
1341
+ const definitions = normalizeNativeTabHistoryDefinitions(options.tabs);
1342
+ let initialURL;
1343
+ if (options.initialURL !== undefined && options.initialURL !== null) {
1344
+ initialURL = normalizeHref(options.initialURL, "native initial URL");
1345
+ const resolved = options.resolveDeepLink?.(initialURL);
1346
+ if (resolved !== undefined) {
1347
+ const target = normalizeNativeTabDeepLinkTarget(resolved);
1348
+ if (!definitions.some((definition) => definition.key === target.tabKey)) {
1349
+ throw new RangeError(`Native tab deep-link target ${JSON.stringify(target.tabKey)} does not identify a configured tab.`);
1350
+ }
1351
+ return {
1352
+ state: createNativeTabsState({
1353
+ tabs: definitions.map((definition) => definition.key === target.tabKey
1354
+ ? {
1355
+ ...definition,
1356
+ initialHref: target.href,
1357
+ initialState: target.state ?? null,
1358
+ }
1359
+ : definition),
1360
+ selectedKey: target.tabKey,
1361
+ }),
1362
+ source: "deep-link",
1363
+ initialURL,
1364
+ };
1365
+ }
1366
+ }
1367
+ let restorationError;
1368
+ if (options.serializedSnapshot !== undefined &&
1369
+ options.serializedSnapshot !== null) {
1370
+ try {
1371
+ return {
1372
+ state: createNativeTabsState({
1373
+ tabs: definitions,
1374
+ snapshot: deserializeNativeTabsStateSnapshot(options.serializedSnapshot),
1375
+ }),
1376
+ source: "restoration",
1377
+ ...(initialURL === undefined ? {} : { initialURL }),
1378
+ };
1379
+ }
1380
+ catch (error) {
1381
+ restorationError = error;
1382
+ }
1383
+ }
1384
+ return {
1385
+ state: createNativeTabsState({
1386
+ tabs: definitions,
1387
+ ...(options.selectedKey === undefined
1388
+ ? {}
1389
+ : { selectedKey: options.selectedKey }),
1390
+ }),
1391
+ source: "initial",
1392
+ ...(initialURL === undefined ? {} : { initialURL }),
1393
+ ...(restorationError === undefined ? {} : { restorationError }),
1394
+ };
1395
+ }
1396
+ /**
1397
+ * Loads a validated multi-history envelope. Corrupt state and valid state
1398
+ * discarded by an accepted initial URL are removed before launch returns, so
1399
+ * a crash before persistence setup cannot resurrect obsolete tab histories.
1400
+ */
1401
+ export async function createNativeTabsStateFromStorage(options) {
1402
+ const key = persistenceKey(options.storageKey);
1403
+ const serializedSnapshot = await options.storage.getItem(key);
1404
+ const result = createNativeTabsStateFromLaunch({
1405
+ tabs: options.tabs,
1406
+ ...(options.selectedKey === undefined
1407
+ ? {}
1408
+ : { selectedKey: options.selectedKey }),
1409
+ ...(options.initialURL === undefined
1410
+ ? {}
1411
+ : { initialURL: options.initialURL }),
1412
+ ...(options.resolveDeepLink === undefined
1413
+ ? {}
1414
+ : { resolveDeepLink: options.resolveDeepLink }),
1415
+ serializedSnapshot,
1416
+ });
1417
+ if (result.restorationError !== undefined ||
1418
+ (result.source === "deep-link" && serializedSnapshot !== null)) {
1419
+ await options.storage.removeItem(key);
1420
+ }
1421
+ return result;
1422
+ }
1423
+ /** Serializes and coalesces selection and child-history persistence writes. */
1424
+ export function createNativeTabsStatePersistence(state, storage, options) {
1425
+ const key = persistenceKey(options.storageKey);
1426
+ let pending;
1427
+ let draining = false;
1428
+ let active = true;
1429
+ const waiters = [];
1430
+ const settleWaiters = (failed, failure) => {
1431
+ const settled = waiters.splice(0);
1432
+ for (const waiter of settled) {
1433
+ if (failed)
1434
+ waiter.reject(failure);
1435
+ else
1436
+ waiter.resolve();
1437
+ }
1438
+ };
1439
+ const reportError = (error) => {
1440
+ reportIsolatedError(options.onError, error);
1441
+ };
1442
+ const drain = async () => {
1443
+ draining = true;
1444
+ let failed = false;
1445
+ let failure;
1446
+ while (pending !== undefined) {
1447
+ const serialized = pending;
1448
+ pending = undefined;
1449
+ try {
1450
+ await storage.setItem(key, serialized);
1451
+ }
1452
+ catch (error) {
1453
+ reportError(error);
1454
+ pending ??= serialized;
1455
+ failed = true;
1456
+ failure = error;
1457
+ break;
1458
+ }
1459
+ }
1460
+ draining = false;
1461
+ settleWaiters(failed, failure);
1462
+ if (!failed && pending !== undefined)
1463
+ void drain();
1464
+ };
1465
+ const schedule = (snapshot) => {
1466
+ pending = serializeNativeTabsStateSnapshot(snapshot);
1467
+ if (!draining)
1468
+ void drain();
1469
+ };
1470
+ const unsubscribe = state.subscribe((update) => {
1471
+ if (active)
1472
+ schedule(update.snapshot);
1473
+ });
1474
+ schedule(state.snapshot);
1475
+ const persistence = Object.freeze({
1476
+ async flush() {
1477
+ if (!draining && pending === undefined) {
1478
+ return;
1479
+ }
1480
+ await new Promise((resolve, reject) => {
1481
+ waiters.push({ resolve, reject });
1482
+ if (!draining)
1483
+ void drain();
1484
+ });
1485
+ },
1486
+ dispose() {
1487
+ if (!active)
1488
+ return;
1489
+ active = false;
1490
+ unsubscribe();
1491
+ },
1492
+ });
1493
+ if (getOwner() !== null)
1494
+ onCleanup(() => persistence.dispose());
1495
+ return persistence;
1496
+ }
1497
+ function nativeTabsProvenance(value, path) {
1498
+ if (typeof value !== "number" ||
1499
+ !Number.isInteger(value) ||
1500
+ value < 0 ||
1501
+ value > 2_147_483_647) {
1502
+ throw new TypeError(`${path} must be a non-negative 32-bit integer.`);
1503
+ }
1504
+ return value;
1505
+ }
1506
+ function nativeTabsBoolean(value, path) {
1507
+ if (typeof value !== "boolean") {
1508
+ throw new TypeError(`${path} must be a boolean.`);
1509
+ }
1510
+ return value;
1511
+ }
1512
+ function parseNativeTabSelection(event) {
1513
+ const payload = plainRecord(event.payload, "native tab selection payload");
1514
+ const actionOrigin = payload.actionOrigin;
1515
+ if (actionOrigin !== "user" &&
1516
+ actionOrigin !== "programmatic-js" &&
1517
+ actionOrigin !== "programmatic-native" &&
1518
+ actionOrigin !== "implicit") {
1519
+ throw new TypeError("native tab selection payload.actionOrigin is invalid.");
1520
+ }
1521
+ return {
1522
+ selectedKey: normalizeNativeTabKey(payload.selectedScreenKey, "native tab selection payload.selectedScreenKey"),
1523
+ provenance: nativeTabsProvenance(payload.provenance, "native tab selection payload.provenance"),
1524
+ repeated: nativeTabsBoolean(payload.isRepeated, "native tab selection payload.isRepeated"),
1525
+ triggeredSpecialEffect: nativeTabsBoolean(payload.hasTriggeredSpecialEffect, "native tab selection payload.hasTriggeredSpecialEffect"),
1526
+ actionOrigin,
1527
+ };
1528
+ }
1529
+ function parseNativeTabSelectionRejection(event) {
1530
+ const payload = plainRecord(event.payload, "native tab selection rejection payload");
1531
+ const reason = payload.rejectionReason;
1532
+ if (reason !== "stale" && reason !== "repeated") {
1533
+ throw new TypeError("native tab selection rejection payload.rejectionReason is invalid.");
1534
+ }
1535
+ return {
1536
+ selectedKey: normalizeNativeTabKey(payload.selectedScreenKey, "native tab selection rejection payload.selectedScreenKey"),
1537
+ provenance: nativeTabsProvenance(payload.provenance, "native tab selection rejection payload.provenance"),
1538
+ rejectedKey: normalizeNativeTabKey(payload.rejectedScreenKey, "native tab selection rejection payload.rejectedScreenKey"),
1539
+ rejectedBaseProvenance: nativeTabsProvenance(payload.rejectedBaseProvenance, "native tab selection rejection payload.rejectedBaseProvenance"),
1540
+ reason,
1541
+ };
1542
+ }
1543
+ function parseNativeTabSelectionPrevention(event) {
1544
+ const payload = plainRecord(event.payload, "native tab selection prevention payload");
1545
+ return {
1546
+ selectedKey: normalizeNativeTabKey(payload.selectedScreenKey, "native tab selection prevention payload.selectedScreenKey"),
1547
+ provenance: nativeTabsProvenance(payload.provenance, "native tab selection prevention payload.provenance"),
1548
+ preventedKey: normalizeNativeTabKey(payload.preventedScreenKey, "native tab selection prevention payload.preventedScreenKey"),
1549
+ };
1550
+ }
1551
+ /**
1552
+ * Retains one keyed Solid owner per native tab and reconciles the pinned
1553
+ * native host's provenance protocol with optional controlled Solid state.
1554
+ * Upstream tabs are stable; this projection remains locally experimental until
1555
+ * each pinned release completes Solid Native's physical promotion matrix.
1556
+ */
1557
+ export function NativeTabs(props) {
1558
+ const tabs = createMemo(() => {
1559
+ if (!Array.isArray(props.tabs) || props.tabs.length === 0) {
1560
+ throw new TypeError("NativeTabs tabs must be a non-empty array.");
1561
+ }
1562
+ if (props.tabs.length > NATIVE_TABS_MAX_ITEMS) {
1563
+ throw new RangeError(`NativeTabs tabs must contain at most ${String(NATIVE_TABS_MAX_ITEMS)} items.`);
1564
+ }
1565
+ const keys = new Set();
1566
+ for (const [index, tab] of props.tabs.entries()) {
1567
+ if (tab === null || typeof tab !== "object") {
1568
+ throw new TypeError(`NativeTabs tabs[${index}] must be an object.`);
1569
+ }
1570
+ const key = normalizeNativeTabKey(tab.key, `NativeTabs tabs[${index}].key`);
1571
+ if (keys.has(key)) {
1572
+ throw new TypeError(`NativeTabs tab key ${JSON.stringify(key)} is duplicated.`);
1573
+ }
1574
+ keys.add(key);
1575
+ }
1576
+ return props.tabs;
1577
+ });
1578
+ const { initialTabs, initialDefaultSelectedKey, initialSelectedKeyProp } = untrack(() => ({
1579
+ initialTabs: tabs(),
1580
+ initialDefaultSelectedKey: props.defaultSelectedKey,
1581
+ initialSelectedKeyProp: props.selectedKey,
1582
+ }));
1583
+ if (initialDefaultSelectedKey !== undefined) {
1584
+ normalizeNativeTabKey(initialDefaultSelectedKey, "NativeTabs defaultSelectedKey");
1585
+ }
1586
+ const initialSelectedKey = normalizeNativeTabKey(initialSelectedKeyProp ?? initialDefaultSelectedKey ?? initialTabs[0].key, "NativeTabs initial selected key");
1587
+ if (!initialTabs.some((tab) => tab.key === initialSelectedKey)) {
1588
+ throw new RangeError(`NativeTabs initial selected key ${JSON.stringify(initialSelectedKey)} does not identify a tab.`);
1589
+ }
1590
+ const [nativeSelectedKey, setNativeSelectedKey] = createSignal(initialSelectedKey);
1591
+ const [nativeProvenance, setNativeProvenance] = createSignal(0);
1592
+ const [navigationRequest, setNavigationRequest] = createSignal({
1593
+ selectedKey: initialSelectedKey,
1594
+ baseProvenance: 0,
1595
+ }, { ownedWrite: true });
1596
+ const desiredSelectedKey = createMemo(() => {
1597
+ const currentTabs = tabs();
1598
+ const available = new Set(currentTabs.map((tab) => tab.key));
1599
+ const desired = props.selectedKey ??
1600
+ (available.has(nativeSelectedKey())
1601
+ ? nativeSelectedKey()
1602
+ : currentTabs[0].key);
1603
+ const selectedKey = normalizeNativeTabKey(desired, "NativeTabs selectedKey");
1604
+ if (!available.has(selectedKey)) {
1605
+ throw new RangeError(`NativeTabs selectedKey ${JSON.stringify(selectedKey)} does not identify a tab.`);
1606
+ }
1607
+ return selectedKey;
1608
+ });
1609
+ effect(() => ({
1610
+ desiredKey: desiredSelectedKey(),
1611
+ nativeKey: nativeSelectedKey(),
1612
+ request: navigationRequest(),
1613
+ provenance: nativeProvenance(),
1614
+ }), ({ desiredKey, nativeKey, request, provenance }) => {
1615
+ if (desiredKey === nativeKey)
1616
+ return;
1617
+ if (request.selectedKey === desiredKey &&
1618
+ request.baseProvenance === provenance) {
1619
+ return;
1620
+ }
1621
+ setNavigationRequest({
1622
+ selectedKey: desiredKey,
1623
+ baseProvenance: provenance,
1624
+ });
1625
+ });
1626
+ const requireCurrentTab = (key) => {
1627
+ if (!tabs().some((tab) => tab.key === key)) {
1628
+ throw new RangeError(`The native tabs host selected unknown tab ${JSON.stringify(key)}.`);
1629
+ }
1630
+ };
1631
+ const reportError = (error) => {
1632
+ if (!reportIsolatedError(props.onError, error))
1633
+ throw error;
1634
+ };
1635
+ const handleSelected = (event) => {
1636
+ try {
1637
+ const selection = parseNativeTabSelection(event);
1638
+ requireCurrentTab(selection.selectedKey);
1639
+ setNativeSelectedKey(selection.selectedKey);
1640
+ setNativeProvenance(selection.provenance);
1641
+ props.onTabSelected?.(selection, event);
1642
+ }
1643
+ catch (error) {
1644
+ reportError(error);
1645
+ }
1646
+ };
1647
+ const handleRejected = (event) => {
1648
+ try {
1649
+ const rejection = parseNativeTabSelectionRejection(event);
1650
+ requireCurrentTab(rejection.selectedKey);
1651
+ setNativeSelectedKey(rejection.selectedKey);
1652
+ setNativeProvenance(rejection.provenance);
1653
+ props.onTabSelectionRejected?.(rejection, event);
1654
+ }
1655
+ catch (error) {
1656
+ reportError(error);
1657
+ }
1658
+ };
1659
+ const handlePrevented = (event) => {
1660
+ try {
1661
+ const prevention = parseNativeTabSelectionPrevention(event);
1662
+ requireCurrentTab(prevention.selectedKey);
1663
+ setNativeSelectedKey(prevention.selectedKey);
1664
+ setNativeProvenance(prevention.provenance);
1665
+ props.onTabSelectionPrevented?.(prevention, event);
1666
+ }
1667
+ catch (error) {
1668
+ reportError(error);
1669
+ }
1670
+ };
1671
+ const screens = mapArray(tabs, (tab, index) => {
1672
+ const tabKey = tab().key;
1673
+ const options = createMemo(() => inheritNativeScreenOptions(props.defaultScreenOptions, props.screenOptions?.(tab(), index())));
1674
+ const isSelected = createMemo(() => nativeSelectedKey() === tabKey);
1675
+ const content = props.children(tab, index, isSelected);
1676
+ return createComponent(TabsScreen, {
1677
+ screenKey: tabKey,
1678
+ get style() {
1679
+ return options().style;
1680
+ },
1681
+ get title() {
1682
+ return options().title;
1683
+ },
1684
+ get badgeValue() {
1685
+ return options().badgeValue;
1686
+ },
1687
+ get icon() {
1688
+ return options().icon;
1689
+ },
1690
+ get selectedIcon() {
1691
+ return options().selectedIcon;
1692
+ },
1693
+ get standardAppearance() {
1694
+ return options().standardAppearance;
1695
+ },
1696
+ get scrollEdgeAppearance() {
1697
+ return options().scrollEdgeAppearance;
1698
+ },
1699
+ get preventNativeSelection() {
1700
+ return options().preventNativeSelection;
1701
+ },
1702
+ get tabBarItemTestID() {
1703
+ return options().tabBarItemTestID;
1704
+ },
1705
+ get tabBarItemAccessibilityLabel() {
1706
+ return options().tabBarItemAccessibilityLabel;
1707
+ },
1708
+ get specialEffects() {
1709
+ return options().specialEffects;
1710
+ },
1711
+ get orientation() {
1712
+ return options().orientation;
1713
+ },
1714
+ ...(props.onTabWillAppear === undefined
1715
+ ? {}
1716
+ : {
1717
+ onWillAppear: (event) => props.onTabWillAppear?.(tab(), event),
1718
+ }),
1719
+ ...(props.onTabDidAppear === undefined
1720
+ ? {}
1721
+ : {
1722
+ onDidAppear: (event) => props.onTabDidAppear?.(tab(), event),
1723
+ }),
1724
+ ...(props.onTabWillDisappear === undefined
1725
+ ? {}
1726
+ : {
1727
+ onWillDisappear: (event) => props.onTabWillDisappear?.(tab(), event),
1728
+ }),
1729
+ ...(props.onTabDidDisappear === undefined
1730
+ ? {}
1731
+ : {
1732
+ onDidDisappear: (event) => props.onTabDidDisappear?.(tab(), event),
1733
+ }),
1734
+ children: content,
1735
+ });
1736
+ }, { keyed: (tab) => tab.key });
1737
+ return createComponent(TabsHost, {
1738
+ get selectedKey() {
1739
+ return navigationRequest().selectedKey;
1740
+ },
1741
+ get baseProvenance() {
1742
+ return navigationRequest().baseProvenance;
1743
+ },
1744
+ rejectStaleNavStateUpdates: true,
1745
+ get tabBarHidden() {
1746
+ return props.tabBarHidden;
1747
+ },
1748
+ get nativeContainerBackgroundColor() {
1749
+ return props.nativeContainerBackgroundColor;
1750
+ },
1751
+ get direction() {
1752
+ return props.direction;
1753
+ },
1754
+ get colorScheme() {
1755
+ return props.colorScheme;
1756
+ },
1757
+ get tabBarRespectsIMEInsets() {
1758
+ return props.tabBarRespectsIMEInsets;
1759
+ },
1760
+ get tabBarTintColor() {
1761
+ return props.tabBarTintColor;
1762
+ },
1763
+ get tabBarMinimizeBehavior() {
1764
+ return props.tabBarMinimizeBehavior;
1765
+ },
1766
+ get tabBarControllerMode() {
1767
+ return props.tabBarControllerMode;
1768
+ },
1769
+ onTabSelected: handleSelected,
1770
+ onTabSelectionRejected: handleRejected,
1771
+ onTabSelectionPrevented: handlePrevented,
1772
+ get children() {
1773
+ return screens();
1774
+ },
1775
+ });
1776
+ }
1777
+ export function NativeStack(props) {
1778
+ const [snapshot, setSnapshot] = createSignal(props.history.snapshot);
1779
+ const [hasPlatformTransitionBlockers, setHasPlatformTransitionBlockers] = createSignal(props.history.hasPlatformTransitionBlockers);
1780
+ const awaitingNativeCompletion = [];
1781
+ const screenFocusSetters = new Map();
1782
+ const unsubscribe = props.history.subscribe((update) => {
1783
+ if (update.transition.origin !== "platform") {
1784
+ if (update.transition.kind === "replace") {
1785
+ // Replace preserves the stable screen identity, so the native stack
1786
+ // receives an ordinary reactive content/prop update rather than a
1787
+ // presentation transition and is not required to emit transitionEnd.
1788
+ props.history.acknowledgeApplicationTransition(update.transition.id);
1789
+ }
1790
+ else {
1791
+ awaitingNativeCompletion.push(update.transition.id);
1792
+ }
1793
+ }
1794
+ setSnapshot(update.snapshot);
1795
+ props.onUpdate?.(update);
1796
+ });
1797
+ onCleanup(unsubscribe);
1798
+ const unsubscribePlatformTransitionBlockers = props.history.subscribePlatformTransitionBlockers(setHasPlatformTransitionBlockers);
1799
+ onCleanup(unsubscribePlatformTransitionBlockers);
1800
+ const completeApplicationTransitions = () => {
1801
+ for (const transition of awaitingNativeCompletion.splice(0)) {
1802
+ props.history.acknowledgeApplicationTransition(transition);
1803
+ }
1804
+ };
1805
+ // A presenter that leaves its Solid owner can no longer observe native
1806
+ // completion. Relinquish every acknowledgement it owns so an externally
1807
+ // retained history cannot accumulate orphaned transition diagnostics.
1808
+ onCleanup(completeApplicationTransitions);
1809
+ const reportPlatformBackError = (error) => {
1810
+ if (!reportIsolatedError(props.onPlatformBackError, error))
1811
+ throw error;
1812
+ };
1813
+ const handleNativeDismiss = (entry, event) => {
1814
+ const currentSnapshot = snapshot();
1815
+ const current = currentSnapshot.entries[currentSnapshot.index];
1816
+ if (currentSnapshot.index === 0 ||
1817
+ current?.id !== entry.id ||
1818
+ props.history.hasPendingPlatformTransition) {
1819
+ return undefined;
1820
+ }
1821
+ let transition;
1822
+ try {
1823
+ transition = props.history.requestPlatformBack(dismissCount(event));
1824
+ }
1825
+ catch (error) {
1826
+ reportPlatformBackError(error);
1827
+ return undefined;
1828
+ }
1829
+ if (transition === undefined)
1830
+ return undefined;
1831
+ // Do not dispose the keyed Solid owner whose native event handler is still
1832
+ // executing. When blockers exist, react-native-screens has kept the native
1833
+ // screen in place and this decision may be asynchronous. An allowed result
1834
+ // removes it through ordinary Solid reconciliation; a blocked result keeps
1835
+ // both native and logical stacks unchanged.
1836
+ return retainCausalNativeEvent(undefined, (retention) => {
1837
+ const run = (callback) => retention.state === "active" ? retention.run(callback) : callback();
1838
+ const settlement = Promise.resolve()
1839
+ .then(async () => {
1840
+ const blocked = props.history.hasPlatformTransitionBlockers
1841
+ ? await props.history.isPlatformTransitionBlocked(transition.id)
1842
+ : false;
1843
+ run(() => {
1844
+ if (!props.history.completePlatformTransition(transition.id, !blocked)) {
1845
+ return;
1846
+ }
1847
+ if (blocked)
1848
+ props.onPlatformBackBlocked?.(entry, event);
1849
+ else
1850
+ props.onPlatformBack?.(transition);
1851
+ });
1852
+ })
1853
+ .catch((error) => {
1854
+ run(() => {
1855
+ props.history.completePlatformTransition(transition.id, false);
1856
+ reportPlatformBackError(error);
1857
+ });
1858
+ });
1859
+ void settlement.then(() => retention.finish(), (error) => {
1860
+ retention.fail(error);
1861
+ throw error;
1862
+ });
1863
+ });
1864
+ };
1865
+ const screens = mapArray(() => {
1866
+ const current = snapshot();
1867
+ return current.entries.slice(0, current.index + 1);
1868
+ }, (entry, index) => {
1869
+ const options = createMemo(() => inheritNativeScreenOptions(props.defaultScreenOptions, props.screenOptions?.(entry(), index())));
1870
+ const [isFocused, setIsFocused] = createSignal(false);
1871
+ const entryId = entry().id;
1872
+ const presentation = untrack(() => options().presentation ?? "push");
1873
+ screenFocusSetters.set(entryId, setIsFocused);
1874
+ onCleanup(() => screenFocusSetters.delete(entryId));
1875
+ // Create route content exactly once for this keyed screen owner. The
1876
+ // entry and index accessors remain reactive across replace/reorder, but a
1877
+ // parent stack reconciliation must not reconstruct the native subtree.
1878
+ const content = props.children(entry, index, isFocused);
1879
+ const header = props.renderHeader?.(entry, index, isFocused);
1880
+ return createComponent(Screen, {
1881
+ get name() {
1882
+ return entry().id;
1883
+ },
1884
+ get style() {
1885
+ return options().style;
1886
+ },
1887
+ get presentation() {
1888
+ return presentation;
1889
+ },
1890
+ get gestureEnabled() {
1891
+ return options().gestureEnabled ?? true;
1892
+ },
1893
+ get nativeBackButtonDismissalEnabled() {
1894
+ return options().nativeBackButtonDismissalEnabled ?? true;
1895
+ },
1896
+ get preventNativeDismiss() {
1897
+ return (hasPlatformTransitionBlockers() ||
1898
+ options().preventNativeDismiss === true);
1899
+ },
1900
+ // Presentation kind is structural for one keyed native screen. Only a
1901
+ // sheet owner subscribes to the corresponding configuration surface.
1902
+ ...(presentation === "sheet"
1903
+ ? {
1904
+ get sheetAllowedDetents() {
1905
+ return options().sheetAllowedDetents;
1906
+ },
1907
+ get sheetInitialDetent() {
1908
+ return options().sheetInitialDetent;
1909
+ },
1910
+ get sheetLargestUndimmedDetent() {
1911
+ return options().sheetLargestUndimmedDetent;
1912
+ },
1913
+ get sheetGrabberVisible() {
1914
+ return options().sheetGrabberVisible;
1915
+ },
1916
+ get sheetCornerRadius() {
1917
+ return options().sheetCornerRadius;
1918
+ },
1919
+ get sheetExpandsWhenScrolledToEdge() {
1920
+ return options().sheetExpandsWhenScrolledToEdge;
1921
+ },
1922
+ get sheetElevation() {
1923
+ return options().sheetElevation;
1924
+ },
1925
+ get sheetShouldOverflowTopInset() {
1926
+ return options().sheetShouldOverflowTopInset;
1927
+ },
1928
+ get sheetDefaultResizeAnimationEnabled() {
1929
+ return options().sheetDefaultResizeAnimationEnabled;
1930
+ },
1931
+ }
1932
+ : {}),
1933
+ activityState: 2,
1934
+ onFocus(event) {
1935
+ // Android screen stacks may emit appear without a paired disappear
1936
+ // for the covered screen. A native stack has one focused owner, so
1937
+ // reconcile the complete keyed set from the positive event.
1938
+ for (const [screenId, setFocused] of screenFocusSetters) {
1939
+ setFocused(screenId === entryId);
1940
+ }
1941
+ props.onScreenFocus?.(entry(), event);
1942
+ },
1943
+ onBlur(event) {
1944
+ setIsFocused(false);
1945
+ props.onScreenBlur?.(entry(), event);
1946
+ },
1947
+ ...(props.onScreenSheetDetentChange === undefined
1948
+ ? {}
1949
+ : {
1950
+ onSheetDetentChange: (event) => props.onScreenSheetDetentChange?.(entry(), event),
1951
+ }),
1952
+ onDismiss(event) {
1953
+ return handleNativeDismiss(entry(), event);
1954
+ },
1955
+ onGestureCancel(event) {
1956
+ // A blocker-protected stack nested under a native tab reports its
1957
+ // prevented dismissal as gestureCancel, while a standalone stack
1958
+ // reports nativeDismissCancel. Both must enter the same history
1959
+ // arbitration path. Without blockers, gestureCancel remains a
1960
+ // natural user cancellation and cannot mutate history.
1961
+ if (hasPlatformTransitionBlockers()) {
1962
+ return handleNativeDismiss(entry(), event);
1963
+ }
1964
+ else {
1965
+ return props.onPlatformBackCancel?.(entry(), event);
1966
+ }
1967
+ },
1968
+ onNativeDismissCancel(event) {
1969
+ if (hasPlatformTransitionBlockers()) {
1970
+ return handleNativeDismiss(entry(), event);
1971
+ }
1972
+ else {
1973
+ return props.onPlatformBackBlocked?.(entry(), event);
1974
+ }
1975
+ },
1976
+ get children() {
1977
+ return header === undefined ? content : [content, header];
1978
+ },
1979
+ });
1980
+ }, { keyed: (entry) => entry.id });
1981
+ return createComponent(ScreenStack, {
1982
+ get style() {
1983
+ return props.style;
1984
+ },
1985
+ onTransitionEnd(event) {
1986
+ completeApplicationTransitions();
1987
+ props.onTransitionEnd?.(event);
1988
+ },
1989
+ get children() {
1990
+ return screens();
1991
+ },
1992
+ });
1993
+ }
1994
+ function activeNativeModalPresentations(snapshot) {
1995
+ return snapshot.entries.slice(1, snapshot.index + 1).map((entry, offset) => ({
1996
+ entry,
1997
+ index: offset + 1,
1998
+ shown: false,
1999
+ visible: true,
2000
+ }));
2001
+ }
2002
+ function reconcileNativeModalPresentations(current, snapshot) {
2003
+ const active = activeNativeModalPresentations(snapshot);
2004
+ const activeById = new Map(active.map((presentation) => [presentation.entry.id, presentation]));
2005
+ const closing = current.some((presentation) => !presentation.visible);
2006
+ if (closing) {
2007
+ // UIKit and Android Dialog dismissal are asynchronous. Do not reactivate a
2008
+ // closing route or mount replacement routes until its native hidden
2009
+ // boundary; doing so can ask one controller to present while it is still
2010
+ // dismissing. Active retained entries may still receive a replace update.
2011
+ return current.map((presentation) => {
2012
+ const target = activeById.get(presentation.entry.id);
2013
+ return target === undefined || !presentation.visible
2014
+ ? presentation
2015
+ : { ...presentation, entry: target.entry, index: target.index };
2016
+ });
2017
+ }
2018
+ const retired = current.filter((presentation) => !activeById.has(presentation.entry.id));
2019
+ if (retired.length > 0) {
2020
+ // A multi-pop or reset dismisses one real native container at a time from
2021
+ // the top. Lower routes retain their Solid owners and presentation until
2022
+ // the route above reports the portable hidden boundary.
2023
+ const topRetired = retired[retired.length - 1];
2024
+ return current.map((presentation) => {
2025
+ const target = activeById.get(presentation.entry.id);
2026
+ if (target !== undefined) {
2027
+ return { ...presentation, entry: target.entry, index: target.index };
2028
+ }
2029
+ return presentation.entry.id === topRetired.entry.id
2030
+ ? { ...presentation, visible: false }
2031
+ : presentation;
2032
+ });
2033
+ }
2034
+ const previousById = new Map(current.map((presentation) => [presentation.entry.id, presentation]));
2035
+ return active.map((presentation) => {
2036
+ const previous = previousById.get(presentation.entry.id);
2037
+ return previous === undefined
2038
+ ? presentation
2039
+ : { ...presentation, shown: previous.shown, visible: true };
2040
+ });
2041
+ }
2042
+ function nativeModalPresentationChanged(previous, next) {
2043
+ const previousIds = new Set(previous.entries.slice(1, previous.index + 1).map((entry) => entry.id));
2044
+ const nextIds = new Set(next.entries.slice(1, next.index + 1).map((entry) => entry.id));
2045
+ return (previousIds.size !== nextIds.size ||
2046
+ [...previousIds].some((entryId) => !nextIds.has(entryId)));
2047
+ }
2048
+ /**
2049
+ * Projects the root NativeHistory entry as retained application content and
2050
+ * every active later entry as a keyed cross-platform Modal route.
2051
+ */
2052
+ export function NativeModalStack(props) {
2053
+ const initialSnapshot = props.history.snapshot;
2054
+ let latestSnapshot = initialSnapshot;
2055
+ const [snapshot, setSnapshot] = createSignal(initialSnapshot, {
2056
+ ownedWrite: true,
2057
+ });
2058
+ const [presentations, setPresentations] = createSignal(activeNativeModalPresentations(initialSnapshot), { ownedWrite: true });
2059
+ const [hasPlatformTransitionBlockers, setHasPlatformTransitionBlockers] = createSignal(props.history.hasPlatformTransitionBlockers);
2060
+ const awaitingNativeCompletion = [];
2061
+ const acknowledgeApplicationTransitions = () => {
2062
+ for (const transition of awaitingNativeCompletion.splice(0)) {
2063
+ props.history.acknowledgeApplicationTransition(transition);
2064
+ }
2065
+ };
2066
+ onCleanup(acknowledgeApplicationTransitions);
2067
+ const completeApplicationTransitions = (current = presentations()) => {
2068
+ if (current.some((presentation) => !presentation.visible || !presentation.shown)) {
2069
+ return;
2070
+ }
2071
+ acknowledgeApplicationTransitions();
2072
+ };
2073
+ const unsubscribe = props.history.subscribe((update) => {
2074
+ const previous = latestSnapshot;
2075
+ latestSnapshot = update.snapshot;
2076
+ if (update.transition.origin !== "platform") {
2077
+ if (nativeModalPresentationChanged(previous, update.snapshot)) {
2078
+ awaitingNativeCompletion.push(update.transition.id);
2079
+ }
2080
+ else {
2081
+ props.history.acknowledgeApplicationTransition(update.transition.id);
2082
+ }
2083
+ }
2084
+ setSnapshot(update.snapshot);
2085
+ setPresentations((current) => reconcileNativeModalPresentations(current, update.snapshot));
2086
+ props.onUpdate?.(update);
2087
+ });
2088
+ onCleanup(unsubscribe);
2089
+ const unsubscribePlatformTransitionBlockers = props.history.subscribePlatformTransitionBlockers(setHasPlatformTransitionBlockers);
2090
+ onCleanup(unsubscribePlatformTransitionBlockers);
2091
+ const reportPlatformBackError = (error) => {
2092
+ if (!reportIsolatedError(props.onPlatformBackError, error))
2093
+ throw error;
2094
+ };
2095
+ const handlePlatformClose = (entry, event) => {
2096
+ const currentSnapshot = latestSnapshot;
2097
+ const current = currentSnapshot.entries[currentSnapshot.index];
2098
+ if (currentSnapshot.index === 0 ||
2099
+ current?.id !== entry.id ||
2100
+ props.history.hasPendingPlatformTransition) {
2101
+ return;
2102
+ }
2103
+ let transition;
2104
+ try {
2105
+ transition = props.history.requestPlatformBack(1);
2106
+ }
2107
+ catch (error) {
2108
+ reportPlatformBackError(error);
2109
+ return;
2110
+ }
2111
+ if (transition === undefined)
2112
+ return;
2113
+ if (!props.history.hasPlatformTransitionBlockers) {
2114
+ if (props.history.completePlatformTransition(transition.id, true)) {
2115
+ props.onPlatformBack?.(transition);
2116
+ }
2117
+ return;
2118
+ }
2119
+ void Promise.resolve()
2120
+ .then(async () => {
2121
+ const blocked = await props.history.isPlatformTransitionBlocked(transition.id);
2122
+ if (!props.history.completePlatformTransition(transition.id, !blocked)) {
2123
+ return;
2124
+ }
2125
+ if (blocked)
2126
+ props.onPlatformBackBlocked?.(entry, event);
2127
+ else
2128
+ props.onPlatformBack?.(transition);
2129
+ })
2130
+ .catch((error) => {
2131
+ props.history.completePlatformTransition(transition.id, false);
2132
+ reportPlatformBackError(error);
2133
+ });
2134
+ };
2135
+ const base = mapArray(() => {
2136
+ const root = snapshot().entries[0];
2137
+ return root === undefined ? [] : [root];
2138
+ }, (entry, index) => {
2139
+ const isFocused = createMemo(() => snapshot().index === 0 && presentations().length === 0);
2140
+ return props.children(entry, index, isFocused);
2141
+ }, { keyed: (entry) => entry.id });
2142
+ const modalRoutes = mapArray(presentations, (presentation) => {
2143
+ const entry = createMemo(() => presentation().entry);
2144
+ const index = createMemo(() => presentation().index);
2145
+ const entryId = entry().id;
2146
+ const [nestedRoute, setNestedRoute] = createSignal(undefined, { ownedWrite: true });
2147
+ const isFocused = createMemo(() => {
2148
+ const current = presentations();
2149
+ return (presentation().visible &&
2150
+ current[current.length - 1]?.entry.id === entryId);
2151
+ });
2152
+ const options = createMemo(() => inheritNativeScreenOptions(props.defaultModalOptions, props.modalOptions?.(entry(), index())));
2153
+ const content = props.children(entry, index, isFocused);
2154
+ const modal = createComponent(Modal, {
2155
+ get visible() {
2156
+ return presentation().visible;
2157
+ },
2158
+ get accessible() {
2159
+ return options().accessible;
2160
+ },
2161
+ get accessibilityHint() {
2162
+ return options().accessibilityHint;
2163
+ },
2164
+ get accessibilityLabel() {
2165
+ return options().accessibilityLabel;
2166
+ },
2167
+ get accessibilityRole() {
2168
+ return options().accessibilityRole;
2169
+ },
2170
+ get accessibilityState() {
2171
+ return options().accessibilityState;
2172
+ },
2173
+ get allowSwipeDismissal() {
2174
+ return (!hasPlatformTransitionBlockers() &&
2175
+ options().allowSwipeDismissal === true);
2176
+ },
2177
+ get animationType() {
2178
+ return options().animationType;
2179
+ },
2180
+ get backdropColor() {
2181
+ return options().backdropColor;
2182
+ },
2183
+ get hardwareAccelerated() {
2184
+ return options().hardwareAccelerated;
2185
+ },
2186
+ get hidden() {
2187
+ return options().hidden;
2188
+ },
2189
+ get nativeID() {
2190
+ return options().nativeID;
2191
+ },
2192
+ get navigationBarTranslucent() {
2193
+ return options().navigationBarTranslucent;
2194
+ },
2195
+ get presentationStyle() {
2196
+ return options().presentationStyle;
2197
+ },
2198
+ get statusBarTranslucent() {
2199
+ return options().statusBarTranslucent;
2200
+ },
2201
+ get style() {
2202
+ return options().style;
2203
+ },
2204
+ get supportedOrientations() {
2205
+ return options().supportedOrientations;
2206
+ },
2207
+ get testID() {
2208
+ return options().testID;
2209
+ },
2210
+ get transparent() {
2211
+ return options().transparent;
2212
+ },
2213
+ onShow(event) {
2214
+ const nextPresentations = presentations().map((candidate) => candidate.entry.id === entryId
2215
+ ? { ...candidate, shown: true }
2216
+ : candidate);
2217
+ setPresentations(nextPresentations);
2218
+ completeApplicationTransitions(nextPresentations);
2219
+ props.onModalShow?.(entry(), event);
2220
+ },
2221
+ onRequestClose(event) {
2222
+ props.onModalRequestClose?.(entry(), event);
2223
+ handlePlatformClose(entry(), event);
2224
+ },
2225
+ onDismiss(event) {
2226
+ // The pinned iOS interactive path emits requestClose before this
2227
+ // normalized completion, which has already marked the presentation
2228
+ // hidden. Retain dismiss-only backend compatibility without turning
2229
+ // an application dismissal (or a back/forward race) into a second
2230
+ // platform pop.
2231
+ if (presentation().visible) {
2232
+ handlePlatformClose(entry(), event);
2233
+ }
2234
+ props.onModalDismiss?.(entry(), event);
2235
+ },
2236
+ onHidden() {
2237
+ const hiddenEntry = entry();
2238
+ const nextPresentations = reconcileNativeModalPresentations(presentations().filter((candidate) => candidate.entry.id !== entryId), latestSnapshot);
2239
+ try {
2240
+ props.onModalHidden?.(hiddenEntry);
2241
+ }
2242
+ finally {
2243
+ setPresentations(nextPresentations);
2244
+ if (nextPresentations.every((candidate) => candidate.visible && candidate.shown)) {
2245
+ acknowledgeApplicationTransitions();
2246
+ }
2247
+ }
2248
+ },
2249
+ ...(props.onModalOrientationChange === undefined
2250
+ ? {}
2251
+ : {
2252
+ onOrientationChange: (event) => props.onModalOrientationChange?.(entry(), event),
2253
+ }),
2254
+ children: () => [content, nestedRoute()],
2255
+ });
2256
+ return { modal, setNestedRoute };
2257
+ }, { keyed: (presentation) => presentation.entry.id });
2258
+ effect(modalRoutes, (routes) => {
2259
+ for (let index = 0; index < routes.length; index++) {
2260
+ routes[index]?.setNestedRoute(routes[index + 1]?.modal);
2261
+ }
2262
+ });
2263
+ return createComponent(View, {
2264
+ get style() {
2265
+ return [{ flex: 1 }, props.style];
2266
+ },
2267
+ get children() {
2268
+ return [...base(), modalRoutes()[0]?.modal];
2269
+ },
2270
+ });
2271
+ }
2272
+ export const NATIVE_SCROLL_RESTORATION_VERSION = 0;
2273
+ export const NATIVE_SCROLL_RESTORATION_MAX_SERIALIZED_LENGTH = 1_048_576;
2274
+ export const NATIVE_SCROLL_RESTORATION_MAX_CONTAINERS_PER_ENTRY = 32;
2275
+ function normalizedNativeScrollOffset(value, path) {
2276
+ const offset = plainRecord(value, path);
2277
+ if (typeof offset.x !== "number" ||
2278
+ !Number.isFinite(offset.x) ||
2279
+ offset.x < 0 ||
2280
+ typeof offset.y !== "number" ||
2281
+ !Number.isFinite(offset.y) ||
2282
+ offset.y < 0) {
2283
+ throw new TypeError(`${path} must contain finite non-negative x and y.`);
2284
+ }
2285
+ return { x: offset.x, y: offset.y };
2286
+ }
2287
+ function normalizeNativeScrollRestorationSnapshot(value) {
2288
+ const snapshot = plainRecord(value, "native scroll restoration snapshot");
2289
+ if (!Array.isArray(snapshot.entries)) {
2290
+ throw new TypeError("Native scroll restoration snapshot entries must be an array.");
2291
+ }
2292
+ if (snapshot.entries.length > NATIVE_HISTORY_MAX_ENTRIES) {
2293
+ throw new RangeError(`Native scroll restoration cannot exceed ${String(NATIVE_HISTORY_MAX_ENTRIES)} entries.`);
2294
+ }
2295
+ const entryIds = new Set();
2296
+ const entries = snapshot.entries.map((value, entryIndex) => {
2297
+ const path = `native scroll restoration entry ${String(entryIndex)}`;
2298
+ const entry = plainRecord(value, path);
2299
+ const entryId = normalizeEntryId(entry.entryId, `${path} id`);
2300
+ if (entryIds.has(entryId)) {
2301
+ throw new Error(`Duplicate native scroll restoration entry: ${entryId}.`);
2302
+ }
2303
+ entryIds.add(entryId);
2304
+ if (!Array.isArray(entry.containers)) {
2305
+ throw new TypeError(`${path} containers must be an array.`);
2306
+ }
2307
+ if (entry.containers.length >
2308
+ NATIVE_SCROLL_RESTORATION_MAX_CONTAINERS_PER_ENTRY) {
2309
+ throw new RangeError(`${path} cannot contain more than ${String(NATIVE_SCROLL_RESTORATION_MAX_CONTAINERS_PER_ENTRY)} containers.`);
2310
+ }
2311
+ const restorationKeys = new Set();
2312
+ const containers = entry.containers.map((value, containerIndex) => {
2313
+ const containerPath = `${path} container ${String(containerIndex)}`;
2314
+ const container = plainRecord(value, containerPath);
2315
+ const restorationKey = normalizeScrollRestorationKey(container.restorationKey);
2316
+ if (restorationKeys.has(restorationKey)) {
2317
+ throw new Error(`Duplicate native scroll restoration container: ${restorationKey}.`);
2318
+ }
2319
+ restorationKeys.add(restorationKey);
2320
+ return {
2321
+ restorationKey,
2322
+ ...normalizedNativeScrollOffset(container, containerPath),
2323
+ };
2324
+ });
2325
+ containers.sort((left, right) => left.restorationKey.localeCompare(right.restorationKey));
2326
+ return { entryId, containers };
2327
+ });
2328
+ entries.sort((left, right) => left.entryId.localeCompare(right.entryId));
2329
+ return { entries };
2330
+ }
2331
+ const EMPTY_NATIVE_SCROLL_RESTORATION_SERIALIZED_LENGTH = JSON.stringify({
2332
+ version: NATIVE_SCROLL_RESTORATION_VERSION,
2333
+ snapshot: { entries: [] },
2334
+ }).length;
2335
+ function nativeScrollContainerSerializedLength(restorationKey, offset) {
2336
+ return JSON.stringify({
2337
+ restorationKey,
2338
+ x: offset.x,
2339
+ y: offset.y,
2340
+ }).length;
2341
+ }
2342
+ function nativeScrollEntrySerializedLength(entryId, offsets) {
2343
+ let length = JSON.stringify({ entryId, containers: [] }).length;
2344
+ let containerCount = 0;
2345
+ for (const [restorationKey, offset] of offsets) {
2346
+ length += nativeScrollContainerSerializedLength(restorationKey, offset);
2347
+ if (containerCount > 0)
2348
+ length++;
2349
+ containerCount++;
2350
+ }
2351
+ return length;
2352
+ }
2353
+ export function serializeNativeScrollRestorationSnapshot(snapshot) {
2354
+ const serialized = JSON.stringify({
2355
+ version: NATIVE_SCROLL_RESTORATION_VERSION,
2356
+ snapshot: normalizeNativeScrollRestorationSnapshot(snapshot),
2357
+ });
2358
+ if (serialized.length > NATIVE_SCROLL_RESTORATION_MAX_SERIALIZED_LENGTH) {
2359
+ throw new RangeError(`Serialized native scroll restoration exceeds ${String(NATIVE_SCROLL_RESTORATION_MAX_SERIALIZED_LENGTH)} characters.`);
2360
+ }
2361
+ return serialized;
2362
+ }
2363
+ export function deserializeNativeScrollRestorationSnapshot(serialized) {
2364
+ if (typeof serialized !== "string") {
2365
+ throw new TypeError("Serialized native scroll restoration must be a string.");
2366
+ }
2367
+ if (serialized.length > NATIVE_SCROLL_RESTORATION_MAX_SERIALIZED_LENGTH) {
2368
+ throw new RangeError(`Serialized native scroll restoration exceeds ${String(NATIVE_SCROLL_RESTORATION_MAX_SERIALIZED_LENGTH)} characters.`);
2369
+ }
2370
+ let decoded;
2371
+ try {
2372
+ decoded = JSON.parse(serialized);
2373
+ }
2374
+ catch {
2375
+ throw new SyntaxError("Serialized native scroll restoration is not valid JSON.");
2376
+ }
2377
+ const envelope = plainRecord(decoded, "native scroll restoration");
2378
+ if (envelope.version !== NATIVE_SCROLL_RESTORATION_VERSION) {
2379
+ throw new Error(`Unsupported native scroll restoration version: ${String(envelope.version)}.`);
2380
+ }
2381
+ return normalizeNativeScrollRestorationSnapshot(envelope.snapshot);
2382
+ }
2383
+ /**
2384
+ * Owns bounded offsets for the live entries of one NativeHistory. A supplied
2385
+ * snapshot is pruned against that history before any route can read it.
2386
+ */
2387
+ export class NativeScrollRestoration {
2388
+ #history;
2389
+ #listeners = new Set();
2390
+ #offsets = new Map();
2391
+ #entrySerializedLengths = new Map();
2392
+ #entryIds = new Set();
2393
+ #serializedLength = EMPTY_NATIVE_SCROLL_RESTORATION_SERIALIZED_LENGTH;
2394
+ #unsubscribeHistory;
2395
+ #active = true;
2396
+ constructor(history, options = {}) {
2397
+ this.#history = history;
2398
+ const snapshot = normalizeNativeScrollRestorationSnapshot(options.snapshot ?? { entries: [] });
2399
+ this.#entryIds = new Set(history.snapshot.entries.map((entry) => entry.id));
2400
+ for (const entry of snapshot.entries) {
2401
+ if (!this.#entryIds.has(entry.entryId))
2402
+ continue;
2403
+ const offsets = new Map(entry.containers.map((container) => [
2404
+ container.restorationKey,
2405
+ { x: container.x, y: container.y },
2406
+ ]));
2407
+ const entryLength = nativeScrollEntrySerializedLength(entry.entryId, offsets);
2408
+ this.#serializedLength +=
2409
+ entryLength + (this.#offsets.size === 0 ? 0 : 1);
2410
+ if (this.#serializedLength > NATIVE_SCROLL_RESTORATION_MAX_SERIALIZED_LENGTH) {
2411
+ throw new RangeError(`Serialized native scroll restoration exceeds ${String(NATIVE_SCROLL_RESTORATION_MAX_SERIALIZED_LENGTH)} characters.`);
2412
+ }
2413
+ this.#offsets.set(entry.entryId, offsets);
2414
+ this.#entrySerializedLengths.set(entry.entryId, entryLength);
2415
+ }
2416
+ this.#unsubscribeHistory = history.subscribe((update) => {
2417
+ this.#entryIds = new Set(update.snapshot.entries.map((entry) => entry.id));
2418
+ let changed = false;
2419
+ for (const entryId of this.#offsets.keys()) {
2420
+ if (this.#entryIds.has(entryId))
2421
+ continue;
2422
+ const entryLength = this.#entrySerializedLengths.get(entryId);
2423
+ this.#serializedLength -=
2424
+ entryLength + (this.#offsets.size > 1 ? 1 : 0);
2425
+ this.#offsets.delete(entryId);
2426
+ this.#entrySerializedLengths.delete(entryId);
2427
+ changed = true;
2428
+ }
2429
+ if (changed)
2430
+ this.#notify();
2431
+ });
2432
+ }
2433
+ get history() {
2434
+ return this.#history;
2435
+ }
2436
+ get snapshot() {
2437
+ return {
2438
+ entries: [...this.#offsets]
2439
+ .map(([entryId, offsets]) => ({
2440
+ entryId,
2441
+ containers: [...offsets]
2442
+ .map(([restorationKey, offset]) => ({
2443
+ restorationKey,
2444
+ x: offset.x,
2445
+ y: offset.y,
2446
+ }))
2447
+ .sort((left, right) => left.restorationKey.localeCompare(right.restorationKey)),
2448
+ }))
2449
+ .sort((left, right) => left.entryId.localeCompare(right.entryId)),
2450
+ };
2451
+ }
2452
+ subscribe(listener) {
2453
+ if (!this.#active) {
2454
+ throw new Error("Native scroll restoration has been disposed.");
2455
+ }
2456
+ this.#listeners.add(listener);
2457
+ let active = true;
2458
+ return () => {
2459
+ if (!active)
2460
+ return;
2461
+ active = false;
2462
+ this.#listeners.delete(listener);
2463
+ };
2464
+ }
2465
+ read(entryId, restorationKey) {
2466
+ const normalizedEntryId = normalizeEntryId(entryId, "native scroll restoration entry id");
2467
+ const normalizedKey = normalizeScrollRestorationKey(restorationKey);
2468
+ const offset = this.#offsets.get(normalizedEntryId)?.get(normalizedKey);
2469
+ return offset === undefined ? undefined : { ...offset };
2470
+ }
2471
+ capture(entryId, restorationKey, offset) {
2472
+ if (!this.#active) {
2473
+ throw new Error("Native scroll restoration has been disposed.");
2474
+ }
2475
+ const normalizedEntryId = normalizeEntryId(entryId, "native scroll restoration entry id");
2476
+ if (!this.#entryIds.has(normalizedEntryId)) {
2477
+ throw new Error(`Native scroll restoration entry is not present in history: ${normalizedEntryId}.`);
2478
+ }
2479
+ const normalizedKey = normalizeScrollRestorationKey(restorationKey);
2480
+ const normalizedOffset = normalizedNativeScrollOffset(offset, "native scroll restoration offset");
2481
+ const existingOffsets = this.#offsets.get(normalizedEntryId);
2482
+ const offsets = existingOffsets ?? new Map();
2483
+ if (!offsets.has(normalizedKey) &&
2484
+ offsets.size >= NATIVE_SCROLL_RESTORATION_MAX_CONTAINERS_PER_ENTRY) {
2485
+ throw new RangeError(`A native history entry cannot retain more than ${String(NATIVE_SCROLL_RESTORATION_MAX_CONTAINERS_PER_ENTRY)} scroll containers.`);
2486
+ }
2487
+ const previous = offsets.get(normalizedKey);
2488
+ if (previous !== undefined &&
2489
+ previous.x === normalizedOffset.x &&
2490
+ previous.y === normalizedOffset.y) {
2491
+ return;
2492
+ }
2493
+ const previousEntryLength = this.#entrySerializedLengths.get(normalizedEntryId) ??
2494
+ nativeScrollEntrySerializedLength(normalizedEntryId, offsets);
2495
+ const nextEntryLength = previousEntryLength -
2496
+ (previous === undefined
2497
+ ? 0
2498
+ : nativeScrollContainerSerializedLength(normalizedKey, previous)) +
2499
+ nativeScrollContainerSerializedLength(normalizedKey, normalizedOffset) +
2500
+ (previous === undefined && offsets.size > 0 ? 1 : 0);
2501
+ const nextSerializedLength = this.#serializedLength -
2502
+ (this.#entrySerializedLengths.has(normalizedEntryId)
2503
+ ? previousEntryLength
2504
+ : 0) +
2505
+ nextEntryLength +
2506
+ (this.#entrySerializedLengths.has(normalizedEntryId) ||
2507
+ this.#entrySerializedLengths.size === 0
2508
+ ? 0
2509
+ : 1);
2510
+ if (nextSerializedLength > NATIVE_SCROLL_RESTORATION_MAX_SERIALIZED_LENGTH) {
2511
+ throw new RangeError(`Serialized native scroll restoration exceeds ${String(NATIVE_SCROLL_RESTORATION_MAX_SERIALIZED_LENGTH)} characters.`);
2512
+ }
2513
+ offsets.set(normalizedKey, normalizedOffset);
2514
+ if (existingOffsets === undefined) {
2515
+ this.#offsets.set(normalizedEntryId, offsets);
2516
+ }
2517
+ this.#entrySerializedLengths.set(normalizedEntryId, nextEntryLength);
2518
+ this.#serializedLength = nextSerializedLength;
2519
+ this.#notify();
2520
+ }
2521
+ dispose() {
2522
+ if (!this.#active)
2523
+ return;
2524
+ this.#active = false;
2525
+ this.#unsubscribeHistory();
2526
+ this.#listeners.clear();
2527
+ }
2528
+ #notify() {
2529
+ for (const listener of [...this.#listeners])
2530
+ listener();
2531
+ }
2532
+ }
2533
+ /**
2534
+ * Loads a scroll snapshot only when navigation itself restored stable entry
2535
+ * IDs. Fresh and deep-link launches remove old offsets before returning.
2536
+ */
2537
+ export async function createNativeScrollRestorationFromStorage(history, options) {
2538
+ if (options.historySource !== "initial" &&
2539
+ options.historySource !== "restoration" &&
2540
+ options.historySource !== "deep-link") {
2541
+ throw new TypeError("Native scroll restoration historySource must be initial, restoration, or deep-link.");
2542
+ }
2543
+ const key = persistenceKey(options.storageKey);
2544
+ const serializedSnapshot = await options.storage.getItem(key);
2545
+ if (options.historySource !== "restoration") {
2546
+ if (serializedSnapshot !== null && serializedSnapshot !== undefined) {
2547
+ await options.storage.removeItem(key);
2548
+ }
2549
+ return { restoration: new NativeScrollRestoration(history) };
2550
+ }
2551
+ if (serializedSnapshot === null || serializedSnapshot === undefined) {
2552
+ return { restoration: new NativeScrollRestoration(history) };
2553
+ }
2554
+ let snapshot;
2555
+ try {
2556
+ snapshot = deserializeNativeScrollRestorationSnapshot(serializedSnapshot);
2557
+ }
2558
+ catch (restorationError) {
2559
+ await options.storage.removeItem(key);
2560
+ return {
2561
+ restoration: new NativeScrollRestoration(history),
2562
+ restorationError,
2563
+ };
2564
+ }
2565
+ const restoration = new NativeScrollRestoration(history, { snapshot });
2566
+ if (snapshot.entries.length > 0 &&
2567
+ restoration.snapshot.entries.length === 0) {
2568
+ try {
2569
+ await options.storage.removeItem(key);
2570
+ }
2571
+ catch (error) {
2572
+ restoration.dispose();
2573
+ throw error;
2574
+ }
2575
+ }
2576
+ return { restoration };
2577
+ }
2578
+ /** Serializes and coalesces durable offset writes behind native storage. */
2579
+ export function createNativeScrollRestorationPersistence(restoration, storage, options) {
2580
+ const key = persistenceKey(options.storageKey);
2581
+ const writeDelayMs = options.writeDelayMs ?? 250;
2582
+ if (!Number.isSafeInteger(writeDelayMs) ||
2583
+ writeDelayMs < 0 ||
2584
+ writeDelayMs > 60_000) {
2585
+ throw new RangeError("Native scroll restoration writeDelayMs must be an integer between 0 and 60000.");
2586
+ }
2587
+ let pending;
2588
+ let writeTimer;
2589
+ let dirty = false;
2590
+ let draining = false;
2591
+ let flushRequested = false;
2592
+ let active = true;
2593
+ const waiters = [];
2594
+ const settleWaiters = (failed, failure) => {
2595
+ const settled = waiters.splice(0);
2596
+ for (const waiter of settled) {
2597
+ if (failed)
2598
+ waiter.reject(failure);
2599
+ else
2600
+ waiter.resolve();
2601
+ }
2602
+ };
2603
+ const reportError = (error) => {
2604
+ reportIsolatedError(options.onError, error);
2605
+ };
2606
+ const clearWriteTimer = () => {
2607
+ if (writeTimer === undefined)
2608
+ return;
2609
+ clearTimeout(writeTimer);
2610
+ writeTimer = undefined;
2611
+ };
2612
+ const enqueueLatest = () => {
2613
+ if (!dirty)
2614
+ return;
2615
+ dirty = false;
2616
+ let serialized;
2617
+ try {
2618
+ serialized = serializeNativeScrollRestorationSnapshot(restoration.snapshot);
2619
+ }
2620
+ catch (error) {
2621
+ reportError(error);
2622
+ return;
2623
+ }
2624
+ pending = serialized;
2625
+ if (!draining)
2626
+ void drain();
2627
+ };
2628
+ const scheduleIdleWrite = () => {
2629
+ if (!active ||
2630
+ !dirty ||
2631
+ draining ||
2632
+ flushRequested ||
2633
+ writeTimer !== undefined) {
2634
+ return;
2635
+ }
2636
+ writeTimer = setTimeout(() => {
2637
+ writeTimer = undefined;
2638
+ enqueueLatest();
2639
+ }, writeDelayMs);
2640
+ };
2641
+ const drain = async () => {
2642
+ draining = true;
2643
+ let failed = false;
2644
+ let failure;
2645
+ while (pending !== undefined) {
2646
+ const serialized = pending;
2647
+ pending = undefined;
2648
+ try {
2649
+ await storage.setItem(key, serialized);
2650
+ }
2651
+ catch (error) {
2652
+ reportError(error);
2653
+ // Preserve the failed value unless a newer serialized offset snapshot
2654
+ // arrived during the native write. Retry only after another change or
2655
+ // explicit flush so an unavailable store cannot create a hot loop.
2656
+ pending ??= serialized;
2657
+ failed = true;
2658
+ failure = error;
2659
+ break;
2660
+ }
2661
+ if (flushRequested && dirty)
2662
+ enqueueLatest();
2663
+ }
2664
+ draining = false;
2665
+ if (failed) {
2666
+ const rejectedFlush = flushRequested;
2667
+ flushRequested = false;
2668
+ if (rejectedFlush)
2669
+ settleWaiters(true, failure);
2670
+ if (dirty)
2671
+ scheduleIdleWrite();
2672
+ return;
2673
+ }
2674
+ if (flushRequested) {
2675
+ if (dirty) {
2676
+ enqueueLatest();
2677
+ if (draining)
2678
+ return;
2679
+ }
2680
+ flushRequested = false;
2681
+ settleWaiters(false);
2682
+ return;
2683
+ }
2684
+ scheduleIdleWrite();
2685
+ };
2686
+ const schedule = () => {
2687
+ dirty = true;
2688
+ clearWriteTimer();
2689
+ scheduleIdleWrite();
2690
+ };
2691
+ const unsubscribe = restoration.subscribe(schedule);
2692
+ schedule();
2693
+ const persistence = Object.freeze({
2694
+ async flush() {
2695
+ if (!dirty && !draining && pending === undefined) {
2696
+ return;
2697
+ }
2698
+ await new Promise((resolve, reject) => {
2699
+ waiters.push({ resolve, reject });
2700
+ flushRequested = true;
2701
+ clearWriteTimer();
2702
+ enqueueLatest();
2703
+ if (!draining) {
2704
+ if (pending === undefined) {
2705
+ flushRequested = false;
2706
+ settleWaiters(false);
2707
+ }
2708
+ else {
2709
+ void drain();
2710
+ }
2711
+ }
2712
+ });
2713
+ },
2714
+ dispose() {
2715
+ if (!active)
2716
+ return;
2717
+ active = false;
2718
+ unsubscribe();
2719
+ clearWriteTimer();
2720
+ dirty = false;
2721
+ },
2722
+ });
2723
+ if (getOwner() !== null)
2724
+ onCleanup(() => persistence.dispose());
2725
+ return persistence;
2726
+ }
2727
+ /**
2728
+ * Owns focus-only work beneath the current Solid owner. Setup runs after a
2729
+ * positive native focus event; its cleanup runs on blur, screen disposal, or
2730
+ * parent disposal before setup can run again.
2731
+ */
2732
+ export function createNativeScreenFocusEffect(isFocused, setup) {
2733
+ const owner = getOwner();
2734
+ let disposeFocused;
2735
+ effect(isFocused, (focused) => {
2736
+ disposeFocused?.();
2737
+ disposeFocused = undefined;
2738
+ if (!focused)
2739
+ return;
2740
+ runWithOwner(owner, () => {
2741
+ createRoot((dispose) => {
2742
+ disposeFocused = dispose;
2743
+ try {
2744
+ const cleanup = setup();
2745
+ if (cleanup === undefined)
2746
+ return;
2747
+ if (typeof cleanup !== "function") {
2748
+ throw new TypeError("A native screen focus setup must return a cleanup function or undefined.");
2749
+ }
2750
+ onCleanup(cleanup);
2751
+ }
2752
+ catch (error) {
2753
+ disposeFocused = undefined;
2754
+ dispose();
2755
+ throw error;
2756
+ }
2757
+ });
2758
+ });
2759
+ });
2760
+ onCleanup(() => {
2761
+ disposeFocused?.();
2762
+ disposeFocused = undefined;
2763
+ });
2764
+ }
2765
+ /**
2766
+ * Runs abort-aware asynchronous work for each native screen focus interval.
2767
+ * Blur or owner disposal aborts the interval before another task can start.
2768
+ * Rejections caused after cancellation are stale and intentionally ignored;
2769
+ * failures while the interval is active are reported without allowing a
2770
+ * failing diagnostic hook to replace the task failure.
2771
+ */
2772
+ export function createNativeScreenFocusTask(isFocused, task, options = {}) {
2773
+ const isActive = () => {
2774
+ if (!isFocused())
2775
+ return false;
2776
+ const enabled = options.enabled?.() ?? true;
2777
+ if (typeof enabled !== "boolean") {
2778
+ throw new TypeError("A native screen focus task enabled accessor must return a boolean.");
2779
+ }
2780
+ return enabled;
2781
+ };
2782
+ createNativeScreenFocusEffect(isActive, () => {
2783
+ const controller = new AbortController();
2784
+ let active = true;
2785
+ let result;
2786
+ try {
2787
+ result = task(controller.signal);
2788
+ if (result !== undefined &&
2789
+ (result === null ||
2790
+ (typeof result !== "object" && typeof result !== "function") ||
2791
+ typeof result.then !== "function")) {
2792
+ throw new TypeError("A native screen focus task must return a promise or undefined.");
2793
+ }
2794
+ }
2795
+ catch (error) {
2796
+ active = false;
2797
+ controller.abort();
2798
+ if (!reportIsolatedError(options.onError, error))
2799
+ throw error;
2800
+ return;
2801
+ }
2802
+ if (result !== undefined) {
2803
+ void Promise.resolve(result).catch((error) => {
2804
+ if (!active || controller.signal.aborted)
2805
+ return;
2806
+ if (!reportIsolatedError(options.onError, error))
2807
+ throw error;
2808
+ });
2809
+ }
2810
+ return () => {
2811
+ active = false;
2812
+ controller.abort();
2813
+ };
2814
+ });
2815
+ }
2816
+ /**
2817
+ * Moves platform accessibility focus once each time a native screen appears.
2818
+ * A target accessor is resolved at the positive native focus event, after the
2819
+ * keyed screen subtree has mounted.
2820
+ */
2821
+ export function createNativeScreenAccessibilityFocus(isFocused, target) {
2822
+ let ownerSettled = false;
2823
+ let initialFocusPending = false;
2824
+ const focusTarget = () => {
2825
+ const node = typeof target === "function" ? target() : target;
2826
+ if (node === undefined) {
2827
+ throw new Error("The native accessibility focus target was unavailable after its focused screen settled.");
2828
+ }
2829
+ void node.focusAccessibility();
2830
+ };
2831
+ // Register from the component's owner, not from the focus effect's
2832
+ // children-forbidden scope. This is the one route-mount interval where a
2833
+ // Screen may already be focused before its async match subtree assigns refs.
2834
+ onSettled(() => {
2835
+ ownerSettled = true;
2836
+ if (!initialFocusPending || !untrack(isFocused))
2837
+ return;
2838
+ initialFocusPending = false;
2839
+ focusTarget();
2840
+ });
2841
+ createNativeScreenFocusEffect(isFocused, () => {
2842
+ if (ownerSettled) {
2843
+ focusTarget();
2844
+ return;
2845
+ }
2846
+ initialFocusPending = true;
2847
+ return () => {
2848
+ initialFocusPending = false;
2849
+ };
2850
+ });
2851
+ }
2852
+ const TanStackNativeScreenContext = createContext();
2853
+ const TanStackNativeScrollRestorationContext = createContext();
2854
+ const TanStackNativeScreenContextProvider = TanStackNativeScreenContext;
2855
+ const TanStackNativeScrollRestorationContextProvider = TanStackNativeScrollRestorationContext;
2856
+ const TanStackNativeScreenShow = Show;
2857
+ /** Reads the keyed native screen owning the current route component subtree. */
2858
+ export function useTanStackNativeScreen() {
2859
+ return useContext(TanStackNativeScreenContext);
2860
+ }
2861
+ function normalizeScrollRestorationKey(value) {
2862
+ if (typeof value !== "string" ||
2863
+ value.length === 0 ||
2864
+ value.length > 128 ||
2865
+ value.includes("\0")) {
2866
+ throw new TypeError("TanStackNativeScrollView restorationKey must be a 1-128 character string without null bytes.");
2867
+ }
2868
+ return value;
2869
+ }
2870
+ function nativeScrollOffset(event) {
2871
+ const payload = event.payload;
2872
+ const contentOffset = payload !== null && typeof payload === "object" && !Array.isArray(payload)
2873
+ ? payload.contentOffset
2874
+ : undefined;
2875
+ const x = contentOffset !== null &&
2876
+ typeof contentOffset === "object" &&
2877
+ !Array.isArray(contentOffset)
2878
+ ? contentOffset.x
2879
+ : undefined;
2880
+ const y = contentOffset !== null &&
2881
+ typeof contentOffset === "object" &&
2882
+ !Array.isArray(contentOffset)
2883
+ ? contentOffset.y
2884
+ : undefined;
2885
+ if (typeof x !== "number" ||
2886
+ !Number.isFinite(x) ||
2887
+ typeof y !== "number" ||
2888
+ !Number.isFinite(y)) {
2889
+ throw new TypeError("TanStackNativeScrollView scroll events must include finite x and y content offsets.");
2890
+ }
2891
+ // UIKit reports negative bounce offsets. They are transient presentation
2892
+ // state and are not valid destinations for the portable scrollTo command.
2893
+ return { x: Math.max(0, x), y: Math.max(0, y) };
2894
+ }
2895
+ const TANSTACK_NATIVE_SCROLL_VIEW_LOCAL_PROPERTIES = new Set([
2896
+ "onRestorationError",
2897
+ "restorationKey",
2898
+ ]);
2899
+ function tanStackNativeScrollViewProps(props, ref, onScroll) {
2900
+ return new Proxy(props, {
2901
+ get(target, property, receiver) {
2902
+ if (TANSTACK_NATIVE_SCROLL_VIEW_LOCAL_PROPERTIES.has(property)) {
2903
+ return undefined;
2904
+ }
2905
+ if (property === "ref")
2906
+ return ref;
2907
+ if (property === "onScroll")
2908
+ return onScroll;
2909
+ return Reflect.get(target, property, receiver);
2910
+ },
2911
+ has(target, property) {
2912
+ if (TANSTACK_NATIVE_SCROLL_VIEW_LOCAL_PROPERTIES.has(property)) {
2913
+ return false;
2914
+ }
2915
+ return (property === "ref" || property === "onScroll" || property in target);
2916
+ },
2917
+ ownKeys(target) {
2918
+ const keys = Reflect.ownKeys(target).filter((property) => !TANSTACK_NATIVE_SCROLL_VIEW_LOCAL_PROPERTIES.has(property));
2919
+ if (!keys.includes("ref"))
2920
+ keys.push("ref");
2921
+ if (!keys.includes("onScroll"))
2922
+ keys.push("onScroll");
2923
+ return keys;
2924
+ },
2925
+ getOwnPropertyDescriptor(target, property) {
2926
+ if (TANSTACK_NATIVE_SCROLL_VIEW_LOCAL_PROPERTIES.has(property)) {
2927
+ return undefined;
2928
+ }
2929
+ if (property === "ref" || property === "onScroll") {
2930
+ return { configurable: true, enumerable: true };
2931
+ }
2932
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, property);
2933
+ return descriptor === undefined
2934
+ ? undefined
2935
+ : { ...descriptor, configurable: true };
2936
+ },
2937
+ });
2938
+ }
2939
+ /**
2940
+ * A native ScrollView whose last finite offset follows its stable TanStack
2941
+ * history entry across route-tree parking and remounting. Mounted native views
2942
+ * retain their own position and are never commanded a second time.
2943
+ */
2944
+ export function TanStackNativeScrollView(props) {
2945
+ const screen = useTanStackNativeScreen();
2946
+ const store = useContext(TanStackNativeScrollRestorationContext);
2947
+ const restorationKey = untrack(() => normalizeScrollRestorationKey(props.restorationKey ?? "primary"));
2948
+ let scrollView;
2949
+ let restoredNode;
2950
+ let restoringNode;
2951
+ let captureFailureActive = false;
2952
+ const reportRestorationError = (error) => {
2953
+ if (!reportIsolatedError(props.onRestorationError, error, screen.entry(), restorationKey)) {
2954
+ throw error;
2955
+ }
2956
+ };
2957
+ const ref = (handle) => {
2958
+ scrollView = handle;
2959
+ props.ref?.(handle);
2960
+ };
2961
+ const onScroll = (event) => {
2962
+ try {
2963
+ store.capture(screen.entry().id, restorationKey, nativeScrollOffset(event));
2964
+ captureFailureActive = false;
2965
+ }
2966
+ catch (error) {
2967
+ if (!captureFailureActive) {
2968
+ captureFailureActive = true;
2969
+ reportRestorationError(error);
2970
+ }
2971
+ }
2972
+ return props.onScroll?.(event);
2973
+ };
2974
+ const nativeScrollView = createComponent(ScrollView, tanStackNativeScrollViewProps(props, ref, onScroll));
2975
+ createNativeScreenFocusTask(screen.isFocused, () => {
2976
+ const node = scrollView;
2977
+ const offset = store.read(untrack(screen.entry).id, restorationKey);
2978
+ if (node === undefined ||
2979
+ offset === undefined ||
2980
+ restoredNode === node ||
2981
+ restoringNode === node) {
2982
+ return;
2983
+ }
2984
+ restoringNode = node;
2985
+ return node
2986
+ .scrollTo({ x: offset.x, y: offset.y, animated: false })
2987
+ .then(() => {
2988
+ restoredNode = node;
2989
+ })
2990
+ .finally(() => {
2991
+ if (restoringNode === node)
2992
+ restoringNode = undefined;
2993
+ });
2994
+ }, { onError: reportRestorationError });
2995
+ return nativeScrollView;
2996
+ }
2997
+ /** Focus-scopes work to the native screen owning the current route subtree. */
2998
+ export function createTanStackNativeScreenFocusEffect(setup) {
2999
+ createNativeScreenFocusEffect(useTanStackNativeScreen().isFocused, setup);
3000
+ }
3001
+ /** Runs abort-aware work while the current TanStack native screen is focused. */
3002
+ export function createTanStackNativeScreenFocusTask(task, options) {
3003
+ createNativeScreenFocusTask(useTanStackNativeScreen().isFocused, task, options);
3004
+ }
3005
+ /** Moves accessibility focus when the current TanStack native screen appears. */
3006
+ export function createTanStackNativeScreenAccessibilityFocus(target) {
3007
+ createNativeScreenAccessibilityFocus(useTanStackNativeScreen().isFocused, target);
3008
+ }
3009
+ function tanStackLocationIndex(state) {
3010
+ const index = state.location.state.__TSR_index;
3011
+ return typeof index === "number" && Number.isSafeInteger(index) && index >= 0
3012
+ ? index
3013
+ : undefined;
3014
+ }
3015
+ function isTanStackStateSettled(state) {
3016
+ const resolved = state.resolvedLocation;
3017
+ return (state.status === "idle" &&
3018
+ resolved !== undefined &&
3019
+ resolved.href === state.location.href &&
3020
+ resolved.state.__TSR_key === state.location.state.__TSR_key);
3021
+ }
3022
+ function tanStackPreloadCount(value) {
3023
+ if (value === undefined)
3024
+ return 0;
3025
+ if (!Number.isSafeInteger(value) ||
3026
+ value < 0 ||
3027
+ value > NATIVE_HISTORY_MAX_ENTRIES) {
3028
+ throw new RangeError(`preloadRestoredEntries must be an integer between 0 and ${String(NATIVE_HISTORY_MAX_ENTRIES)}.`);
3029
+ }
3030
+ return value;
3031
+ }
3032
+ function tanStackRestoredPreloadDecision(value) {
3033
+ if (typeof value !== "boolean") {
3034
+ throw new TypeError("shouldPreloadRestoredEntry must resolve to a boolean.");
3035
+ }
3036
+ return value;
3037
+ }
3038
+ function tanStackMountedRouteTreeLimit(value, name = "maxMountedRouteTrees") {
3039
+ if (value === undefined)
3040
+ return undefined;
3041
+ if (!Number.isSafeInteger(value) ||
3042
+ value < 1 ||
3043
+ value > NATIVE_HISTORY_MAX_ENTRIES) {
3044
+ throw new RangeError(`${name} must be an integer between 1 and ${String(NATIVE_HISTORY_MAX_ENTRIES)}.`);
3045
+ }
3046
+ return value;
3047
+ }
3048
+ function tanStackMemoryWarningCount(value) {
3049
+ if (!Number.isSafeInteger(value) || value < 0) {
3050
+ throw new RangeError("memoryPolicy.warningCount() must be a non-negative safe integer.");
3051
+ }
3052
+ return value;
3053
+ }
3054
+ function tanStackMemoryPressureState(value) {
3055
+ if (typeof value !== "boolean") {
3056
+ throw new TypeError("memoryPolicy.isUnderMemoryPressure() must return a boolean.");
3057
+ }
3058
+ return value;
3059
+ }
3060
+ function notifyTanStackNativeMemoryPressure(options, warningCount) {
3061
+ const handler = options.onMemoryPressure;
3062
+ if (handler === undefined)
3063
+ return;
3064
+ try {
3065
+ const result = handler(warningCount);
3066
+ void Promise.resolve(result).catch((error) => {
3067
+ reportIsolatedError(options.onMemoryPressureError, error, warningCount);
3068
+ });
3069
+ }
3070
+ catch (error) {
3071
+ reportIsolatedError(options.onMemoryPressureError, error, warningCount);
3072
+ }
3073
+ }
3074
+ /**
3075
+ * Couples native pressure delivery to an explicit, recoverable navigation
3076
+ * budget. The source subscription follows the current Solid owner.
3077
+ */
3078
+ export function createTanStackNativeMemoryPolicy(source, options) {
3079
+ const normalMountedRouteTrees = tanStackMountedRouteTreeLimit(options.normalMountedRouteTrees, "normalMountedRouteTrees");
3080
+ const pressuredMountedRouteTrees = tanStackMountedRouteTreeLimit(options.pressuredMountedRouteTrees, "pressuredMountedRouteTrees");
3081
+ if (pressuredMountedRouteTrees > normalMountedRouteTrees) {
3082
+ throw new RangeError("pressuredMountedRouteTrees cannot exceed normalMountedRouteTrees.");
3083
+ }
3084
+ const warningCount = createMemoryWarningCount(source);
3085
+ const [recoveredThroughWarning, setRecoveredThroughWarning] = createSignal(0);
3086
+ const isUnderMemoryPressure = createMemo(() => warningCount() > recoveredThroughWarning());
3087
+ const maxMountedRouteTrees = createMemo(() => isUnderMemoryPressure()
3088
+ ? pressuredMountedRouteTrees
3089
+ : normalMountedRouteTrees);
3090
+ let observedWarningCount = untrack(warningCount);
3091
+ effect(warningCount, (nextWarningCount) => {
3092
+ if (nextWarningCount <= observedWarningCount)
3093
+ return;
3094
+ observedWarningCount = nextWarningCount;
3095
+ notifyTanStackNativeMemoryPressure(options, nextWarningCount);
3096
+ });
3097
+ return Object.freeze({
3098
+ warningCount,
3099
+ isUnderMemoryPressure,
3100
+ maxMountedRouteTrees,
3101
+ acknowledgeRecovery() {
3102
+ setRecoveredThroughWarning(untrack(warningCount));
3103
+ },
3104
+ });
3105
+ }
3106
+ function reportTanStackPreloadError(error, entry, handler) {
3107
+ reportIsolatedError(handler, error, entry);
3108
+ }
3109
+ function TanStackNativeFrozenScreen(props) {
3110
+ const requiredState = props.state;
3111
+ const routeTreeMounted = createMemo(() => props.isRouteTreeMounted());
3112
+ const visibleState = () => routeTreeMounted() ? props.state() : undefined;
3113
+ return createComponent(TanStackNativeScreenShow, {
3114
+ get when() {
3115
+ return visibleState();
3116
+ },
3117
+ get fallback() {
3118
+ if (!routeTreeMounted() && props.renderParked !== undefined) {
3119
+ return props.renderParked(props.entry, props.index, props.isFocused);
3120
+ }
3121
+ return props.renderUnresolved(props.entry, props.index, props.isFocused);
3122
+ },
3123
+ children: (_state) => createComponent(TanStackNativeMatches, {
3124
+ state: requiredState,
3125
+ }),
3126
+ });
3127
+ }
3128
+ function TanStackNativeStackScreen(props) {
3129
+ const scrollRestoration = props.scrollRestoration;
3130
+ const state = () => {
3131
+ const live = props.readLiveState();
3132
+ const entry = props.entry();
3133
+ if (isTanStackStateSettled(live) &&
3134
+ tanStackLocationIndex(live) === props.index() &&
3135
+ live.location.href === entry.href) {
3136
+ return live;
3137
+ }
3138
+ return props.states().get(entry.id);
3139
+ };
3140
+ const context = {
3141
+ entry: props.entry,
3142
+ index: props.index,
3143
+ isFocused: props.isFocused,
3144
+ };
3145
+ return createComponent(TanStackNativeScreenContextProvider, {
3146
+ value: context,
3147
+ get children() {
3148
+ return createComponent(TanStackNativeScrollRestorationContextProvider, {
3149
+ value: scrollRestoration,
3150
+ get children() {
3151
+ return createComponent(TanStackNativeFrozenScreen, {
3152
+ state,
3153
+ isRouteTreeMounted: props.isRouteTreeMounted,
3154
+ entry: props.entry,
3155
+ index: props.index,
3156
+ isFocused: props.isFocused,
3157
+ renderUnresolved: props.renderUnresolved,
3158
+ renderParked: props.renderParked,
3159
+ });
3160
+ },
3161
+ });
3162
+ },
3163
+ });
3164
+ }
3165
+ /**
3166
+ * Couples TanStack's current match publication to keyed native screen owners.
3167
+ * By default, each visited history entry retains its last settled match tree
3168
+ * while hidden. An explicit mount budget can park older match trees while
3169
+ * retaining their keyed native Screen containers and settled router state.
3170
+ */
3171
+ export function TanStackNativeStack(props) {
3172
+ const router = props.router ?? useTanStackNativeRouter();
3173
+ const preloadRestoredEntries = tanStackPreloadCount(props.preloadRestoredEntries);
3174
+ const mountedRouteTreeLimit = () => {
3175
+ const configured = tanStackMountedRouteTreeLimit(props.maxMountedRouteTrees);
3176
+ const memoryPolicy = props.memoryPolicy;
3177
+ if (memoryPolicy === undefined)
3178
+ return configured;
3179
+ const policyLimit = tanStackMountedRouteTreeLimit(memoryPolicy.maxMountedRouteTrees(), "memoryPolicy.maxMountedRouteTrees()");
3180
+ return configured === undefined
3181
+ ? policyLimit
3182
+ : Math.min(configured, policyLimit);
3183
+ };
3184
+ untrack(mountedRouteTreeLimit);
3185
+ if (nativeHistoryByTanStackHistory.get(router.history) !==
3186
+ props.history) {
3187
+ throw new Error("TanStackNativeStack requires the NativeHistory used to create the router history adapter.");
3188
+ }
3189
+ const readLiveState = router.stores.__store.get;
3190
+ const ownsScrollRestoration = props.scrollRestoration === undefined;
3191
+ const scrollRestoration = props.scrollRestoration ?? new NativeScrollRestoration(props.history);
3192
+ if (scrollRestoration.history !== props.history) {
3193
+ if (ownsScrollRestoration)
3194
+ scrollRestoration.dispose();
3195
+ throw new Error("TanStackNativeStack scrollRestoration must own the stack's NativeHistory.");
3196
+ }
3197
+ if (ownsScrollRestoration)
3198
+ onCleanup(() => scrollRestoration.dispose());
3199
+ const readMemoryPressure = () => {
3200
+ const memoryPolicy = props.memoryPolicy;
3201
+ return memoryPolicy === undefined
3202
+ ? false
3203
+ : tanStackMemoryPressureState(memoryPolicy.isUnderMemoryPressure());
3204
+ };
3205
+ let retainedStates = new Map();
3206
+ const captureSettledState = (state) => {
3207
+ if (!isTanStackStateSettled(state))
3208
+ return false;
3209
+ const index = tanStackLocationIndex(state);
3210
+ const snapshot = props.history.snapshot;
3211
+ if (index === undefined || index > snapshot.index)
3212
+ return false;
3213
+ const currentEntry = snapshot.entries[index];
3214
+ if (currentEntry === undefined ||
3215
+ currentEntry.href !== state.location.href) {
3216
+ return false;
3217
+ }
3218
+ const activeIds = new Set(untrack(readMemoryPressure)
3219
+ ? [currentEntry.id]
3220
+ : snapshot.entries
3221
+ .slice(0, snapshot.index + 1)
3222
+ .map((entry) => entry.id));
3223
+ const nextStates = new Map();
3224
+ for (const [entryId, retained] of retainedStates) {
3225
+ if (activeIds.has(entryId))
3226
+ nextStates.set(entryId, retained);
3227
+ }
3228
+ nextStates.set(currentEntry.id, state);
3229
+ retainedStates = nextStates;
3230
+ return true;
3231
+ };
3232
+ const initialState = untrack(readLiveState);
3233
+ captureSettledState(initialState);
3234
+ const [states, setStates] = createSignal(retainedStates, {
3235
+ ownedWrite: true,
3236
+ });
3237
+ let preloading = !untrack(readMemoryPressure);
3238
+ const preloadPolicyAbortController = new AbortController();
3239
+ let preloadStarted = false;
3240
+ const initialSnapshot = props.history.snapshot;
3241
+ const firstPreloadIndex = Math.max(0, initialSnapshot.index - preloadRestoredEntries);
3242
+ const prewarm = async () => {
3243
+ for (let index = initialSnapshot.index - 1; preloading && index >= firstPreloadIndex; index--) {
3244
+ const entry = initialSnapshot.entries[index];
3245
+ if (entry === undefined || retainedStates.has(entry.id))
3246
+ continue;
3247
+ try {
3248
+ const shouldPreloadRestoredEntry = props.shouldPreloadRestoredEntry;
3249
+ if (shouldPreloadRestoredEntry !== undefined &&
3250
+ !tanStackRestoredPreloadDecision(await shouldPreloadRestoredEntry(entry, index, preloadPolicyAbortController.signal))) {
3251
+ continue;
3252
+ }
3253
+ if (preloadPolicyAbortController.signal.aborted || !preloading) {
3254
+ continue;
3255
+ }
3256
+ const state = tanStackState(entry, index);
3257
+ const options = { to: entry.href, href: entry.href, state };
3258
+ const location = router.buildLocation(options);
3259
+ const expectedMatches = router.matchRoutes(location);
3260
+ const matches = await router.preloadRoute(options);
3261
+ if (!preloading || matches === undefined)
3262
+ continue;
3263
+ const latestSnapshot = props.history.snapshot;
3264
+ const latestEntry = latestSnapshot.entries[index];
3265
+ if (index > latestSnapshot.index ||
3266
+ latestEntry?.id !== entry.id ||
3267
+ latestEntry.href !== entry.href ||
3268
+ retainedStates.has(entry.id) ||
3269
+ matches.length !== expectedMatches.length ||
3270
+ matches.some((match, matchIndex) => match.routeId !== expectedMatches[matchIndex]?.routeId ||
3271
+ match.pathname !== expectedMatches[matchIndex]?.pathname)) {
3272
+ continue;
3273
+ }
3274
+ const nextStates = new Map(retainedStates);
3275
+ nextStates.set(entry.id, {
3276
+ status: "idle",
3277
+ isLoading: false,
3278
+ matches,
3279
+ location,
3280
+ resolvedLocation: location,
3281
+ });
3282
+ retainedStates = nextStates;
3283
+ setStates(nextStates);
3284
+ }
3285
+ catch (error) {
3286
+ if (preloading) {
3287
+ reportTanStackPreloadError(error, entry, props.onPreloadError);
3288
+ }
3289
+ }
3290
+ }
3291
+ };
3292
+ const startPrewarm = (state) => {
3293
+ if (preloadRestoredEntries === 0 ||
3294
+ preloadStarted ||
3295
+ !isTanStackStateSettled(state)) {
3296
+ return;
3297
+ }
3298
+ const initialEntry = initialSnapshot.entries[initialSnapshot.index];
3299
+ if (initialEntry === undefined ||
3300
+ tanStackLocationIndex(state) !== initialSnapshot.index ||
3301
+ state.location.href !== initialEntry.href ||
3302
+ state.location.state.__TSR_key !==
3303
+ tanStackState(initialEntry, initialSnapshot.index).__TSR_key) {
3304
+ return;
3305
+ }
3306
+ preloadStarted = true;
3307
+ // TanStack reads its Solid-backed stores while constructing preload
3308
+ // locations. Run that work after this effect's untracked apply phase.
3309
+ void Promise.resolve().then(prewarm);
3310
+ };
3311
+ const discardInactiveStates = () => {
3312
+ captureSettledState(untrack(readLiveState));
3313
+ const snapshot = props.history.snapshot;
3314
+ const currentEntry = snapshot.entries[snapshot.index];
3315
+ const currentState = currentEntry === undefined
3316
+ ? undefined
3317
+ : retainedStates.get(currentEntry.id);
3318
+ retainedStates =
3319
+ currentEntry === undefined || currentState === undefined
3320
+ ? new Map()
3321
+ : new Map([[currentEntry.id, currentState]]);
3322
+ setStates(retainedStates);
3323
+ };
3324
+ let observedMemoryPolicy;
3325
+ let observedMemoryWarningCount = 0;
3326
+ let wasUnderMemoryPressure = false;
3327
+ effect(() => {
3328
+ const memoryPolicy = props.memoryPolicy;
3329
+ if (memoryPolicy === undefined) {
3330
+ return {
3331
+ isUnderMemoryPressure: false,
3332
+ memoryPolicy,
3333
+ warningCount: 0,
3334
+ };
3335
+ }
3336
+ const isUnderMemoryPressure = tanStackMemoryPressureState(memoryPolicy.isUnderMemoryPressure());
3337
+ return {
3338
+ isUnderMemoryPressure,
3339
+ memoryPolicy,
3340
+ warningCount: tanStackMemoryWarningCount(memoryPolicy.warningCount()),
3341
+ };
3342
+ }, ({ isUnderMemoryPressure, memoryPolicy, warningCount }) => {
3343
+ const policyChanged = memoryPolicy !== observedMemoryPolicy;
3344
+ const warningAdvanced = !policyChanged && warningCount > observedMemoryWarningCount;
3345
+ const pressureStarted = isUnderMemoryPressure && !wasUnderMemoryPressure;
3346
+ observedMemoryPolicy = memoryPolicy;
3347
+ observedMemoryWarningCount = warningCount;
3348
+ wasUnderMemoryPressure = isUnderMemoryPressure;
3349
+ if (!warningAdvanced && !pressureStarted)
3350
+ return;
3351
+ preloading = false;
3352
+ preloadPolicyAbortController.abort();
3353
+ discardInactiveStates();
3354
+ router.clearCache();
3355
+ });
3356
+ effect(readLiveState, (state) => {
3357
+ if (captureSettledState(state))
3358
+ setStates(retainedStates);
3359
+ startPrewarm(state);
3360
+ });
3361
+ startPrewarm(initialState);
3362
+ onCleanup(() => {
3363
+ preloading = false;
3364
+ preloadPolicyAbortController.abort();
3365
+ });
3366
+ return createComponent(NativeStack, {
3367
+ history: props.history,
3368
+ get style() {
3369
+ return props.style;
3370
+ },
3371
+ get defaultScreenOptions() {
3372
+ return props.defaultScreenOptions;
3373
+ },
3374
+ ...(props.screenOptions === undefined
3375
+ ? {}
3376
+ : { screenOptions: props.screenOptions }),
3377
+ ...(props.onTransitionEnd === undefined
3378
+ ? {}
3379
+ : { onTransitionEnd: props.onTransitionEnd }),
3380
+ ...(props.onScreenFocus === undefined
3381
+ ? {}
3382
+ : { onScreenFocus: props.onScreenFocus }),
3383
+ ...(props.onScreenBlur === undefined
3384
+ ? {}
3385
+ : { onScreenBlur: props.onScreenBlur }),
3386
+ ...(props.onScreenSheetDetentChange === undefined
3387
+ ? {}
3388
+ : {
3389
+ onScreenSheetDetentChange: props.onScreenSheetDetentChange,
3390
+ }),
3391
+ ...(props.onPlatformBack === undefined
3392
+ ? {}
3393
+ : { onPlatformBack: props.onPlatformBack }),
3394
+ ...(props.onPlatformBackCancel === undefined
3395
+ ? {}
3396
+ : { onPlatformBackCancel: props.onPlatformBackCancel }),
3397
+ ...(props.onPlatformBackBlocked === undefined
3398
+ ? {}
3399
+ : { onPlatformBackBlocked: props.onPlatformBackBlocked }),
3400
+ ...(props.onPlatformBackError === undefined
3401
+ ? {}
3402
+ : { onPlatformBackError: props.onPlatformBackError }),
3403
+ ...(props.onUpdate === undefined ? {} : { onUpdate: props.onUpdate }),
3404
+ ...(props.renderHeader === undefined
3405
+ ? {}
3406
+ : { renderHeader: props.renderHeader }),
3407
+ children: (entry, index, isFocused) => createComponent(TanStackNativeStackScreen, {
3408
+ states,
3409
+ readLiveState,
3410
+ entry,
3411
+ index,
3412
+ isFocused,
3413
+ scrollRestoration,
3414
+ isRouteTreeMounted: () => {
3415
+ const limit = mountedRouteTreeLimit();
3416
+ if (limit === undefined)
3417
+ return true;
3418
+ const liveIndex = tanStackLocationIndex(readLiveState());
3419
+ const activeIndex = liveIndex ?? props.history.snapshot.index;
3420
+ return activeIndex - index() < limit;
3421
+ },
3422
+ renderUnresolved: props.renderUnresolved,
3423
+ renderParked: props.renderParked,
3424
+ }),
3425
+ });
3426
+ }
3427
+ //# sourceMappingURL=index.js.map