reducer.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.reducer = reducer;
  6. exports.ACTION_PREFETCH = exports.ACTION_SERVER_PATCH = exports.ACTION_RESTORE = exports.ACTION_NAVIGATE = exports.ACTION_RELOAD = void 0;
  7. var _extends = require("@swc/helpers/lib/_extends.js").default;
  8. var _react = require("react");
  9. var _matchSegments = require("./match-segments");
  10. var _appRouterClient = require("./app-router.client");
  11. /**
  12. * Invalidate cache one level down from the router state.
  13. */ // TODO-APP: Verify if this needs to be recursive.
  14. function invalidateCacheByRouterState(newCache, existingCache, routerState) {
  15. // Remove segment that we got data for so that it is filled in during rendering of subTreeData.
  16. for(const key in routerState[1]){
  17. const segmentForParallelRoute = routerState[1][key][0];
  18. const cacheKey = Array.isArray(segmentForParallelRoute) ? segmentForParallelRoute[1] : segmentForParallelRoute;
  19. const existingParallelRoutesCacheNode = existingCache.parallelRoutes.get(key);
  20. if (existingParallelRoutesCacheNode) {
  21. let parallelRouteCacheNode = new Map(existingParallelRoutesCacheNode);
  22. parallelRouteCacheNode.delete(cacheKey);
  23. newCache.parallelRoutes.set(key, parallelRouteCacheNode);
  24. }
  25. }
  26. }
  27. /**
  28. * Fill cache with subTreeData based on flightDataPath
  29. */ function fillCacheWithNewSubTreeData(newCache, existingCache, flightDataPath) {
  30. const isLastEntry = flightDataPath.length <= 4;
  31. const [parallelRouteKey, segment] = flightDataPath;
  32. const segmentForCache = Array.isArray(segment) ? segment[1] : segment;
  33. const existingChildSegmentMap = existingCache.parallelRoutes.get(parallelRouteKey);
  34. if (!existingChildSegmentMap) {
  35. // Bailout because the existing cache does not have the path to the leaf node
  36. // Will trigger lazy fetch in layout-router because of missing segment
  37. return;
  38. }
  39. let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey);
  40. if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
  41. childSegmentMap = new Map(existingChildSegmentMap);
  42. newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap);
  43. }
  44. const existingChildCacheNode = existingChildSegmentMap.get(segmentForCache);
  45. let childCacheNode = childSegmentMap.get(segmentForCache);
  46. // In case of last segment start the fetch at this level and don't copy further down.
  47. if (isLastEntry) {
  48. if (!childCacheNode || !childCacheNode.data || childCacheNode === existingChildCacheNode) {
  49. childCacheNode = {
  50. data: null,
  51. subTreeData: flightDataPath[3],
  52. // Ensure segments other than the one we got data for are preserved.
  53. parallelRoutes: existingChildCacheNode ? new Map(existingChildCacheNode.parallelRoutes) : new Map()
  54. };
  55. if (existingChildCacheNode) {
  56. invalidateCacheByRouterState(childCacheNode, existingChildCacheNode, flightDataPath[2]);
  57. }
  58. childSegmentMap.set(segmentForCache, childCacheNode);
  59. }
  60. return;
  61. }
  62. if (!childCacheNode || !existingChildCacheNode) {
  63. // Bailout because the existing cache does not have the path to the leaf node
  64. // Will trigger lazy fetch in layout-router because of missing segment
  65. return;
  66. }
  67. if (childCacheNode === existingChildCacheNode) {
  68. childCacheNode = {
  69. data: childCacheNode.data,
  70. subTreeData: childCacheNode.subTreeData,
  71. parallelRoutes: new Map(childCacheNode.parallelRoutes)
  72. };
  73. childSegmentMap.set(segmentForCache, childCacheNode);
  74. }
  75. fillCacheWithNewSubTreeData(childCacheNode, existingChildCacheNode, flightDataPath.slice(2));
  76. }
  77. /**
  78. * Fill cache up to the end of the flightSegmentPath, invalidating anything below it.
  79. */ function invalidateCacheBelowFlightSegmentPath(newCache, existingCache, flightSegmentPath) {
  80. const isLastEntry = flightSegmentPath.length <= 2;
  81. const [parallelRouteKey, segment] = flightSegmentPath;
  82. const segmentForCache = Array.isArray(segment) ? segment[1] : segment;
  83. const existingChildSegmentMap = existingCache.parallelRoutes.get(parallelRouteKey);
  84. if (!existingChildSegmentMap) {
  85. // Bailout because the existing cache does not have the path to the leaf node
  86. // Will trigger lazy fetch in layout-router because of missing segment
  87. return;
  88. }
  89. let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey);
  90. if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
  91. childSegmentMap = new Map(existingChildSegmentMap);
  92. newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap);
  93. }
  94. // In case of last entry don't copy further down.
  95. if (isLastEntry) {
  96. childSegmentMap.delete(segmentForCache);
  97. return;
  98. }
  99. const existingChildCacheNode = existingChildSegmentMap.get(segmentForCache);
  100. let childCacheNode = childSegmentMap.get(segmentForCache);
  101. if (!childCacheNode || !existingChildCacheNode) {
  102. // Bailout because the existing cache does not have the path to the leaf node
  103. // Will trigger lazy fetch in layout-router because of missing segment
  104. return;
  105. }
  106. if (childCacheNode === existingChildCacheNode) {
  107. childCacheNode = {
  108. data: childCacheNode.data,
  109. subTreeData: childCacheNode.subTreeData,
  110. parallelRoutes: new Map(childCacheNode.parallelRoutes)
  111. };
  112. childSegmentMap.set(segmentForCache, childCacheNode);
  113. }
  114. invalidateCacheBelowFlightSegmentPath(childCacheNode, existingChildCacheNode, flightSegmentPath.slice(2));
  115. }
  116. /**
  117. * Fill cache with subTreeData based on flightDataPath that was prefetched
  118. * This operation is append-only to the existing cache.
  119. */ function fillCacheWithPrefetchedSubTreeData(existingCache, flightDataPath) {
  120. const isLastEntry = flightDataPath.length <= 4;
  121. const [parallelRouteKey, segment] = flightDataPath;
  122. const segmentForCache = Array.isArray(segment) ? segment[1] : segment;
  123. const existingChildSegmentMap = existingCache.parallelRoutes.get(parallelRouteKey);
  124. if (!existingChildSegmentMap) {
  125. // Bailout because the existing cache does not have the path to the leaf node
  126. return;
  127. }
  128. const existingChildCacheNode = existingChildSegmentMap.get(segmentForCache);
  129. // In case of last segment start the fetch at this level and don't copy further down.
  130. if (isLastEntry) {
  131. if (!existingChildCacheNode) {
  132. existingChildSegmentMap.set(segmentForCache, {
  133. data: null,
  134. subTreeData: flightDataPath[3],
  135. parallelRoutes: new Map()
  136. });
  137. }
  138. return;
  139. }
  140. if (!existingChildCacheNode) {
  141. // Bailout because the existing cache does not have the path to the leaf node
  142. return;
  143. }
  144. fillCacheWithPrefetchedSubTreeData(existingChildCacheNode, flightDataPath.slice(2));
  145. }
  146. /**
  147. * Kick off fetch based on the common layout between two routes. Fill cache with data property holding the in-progress fetch.
  148. */ function fillCacheWithDataProperty(newCache, existingCache, segments, fetchResponse) {
  149. const isLastEntry = segments.length === 1;
  150. const parallelRouteKey = 'children';
  151. const [segment] = segments;
  152. const existingChildSegmentMap = existingCache.parallelRoutes.get(parallelRouteKey);
  153. if (!existingChildSegmentMap) {
  154. // Bailout because the existing cache does not have the path to the leaf node
  155. // Will trigger lazy fetch in layout-router because of missing segment
  156. return {
  157. bailOptimistic: true
  158. };
  159. }
  160. let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey);
  161. if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
  162. childSegmentMap = new Map(existingChildSegmentMap);
  163. newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap);
  164. }
  165. const existingChildCacheNode = existingChildSegmentMap.get(segment);
  166. let childCacheNode = childSegmentMap.get(segment);
  167. // In case of last segment start off the fetch at this level and don't copy further down.
  168. if (isLastEntry) {
  169. if (!childCacheNode || !childCacheNode.data || childCacheNode === existingChildCacheNode) {
  170. childSegmentMap.set(segment, {
  171. data: fetchResponse(),
  172. subTreeData: null,
  173. parallelRoutes: new Map()
  174. });
  175. }
  176. return;
  177. }
  178. if (!childCacheNode || !existingChildCacheNode) {
  179. // Start fetch in the place where the existing cache doesn't have the data yet.
  180. if (!childCacheNode) {
  181. childSegmentMap.set(segment, {
  182. data: fetchResponse(),
  183. subTreeData: null,
  184. parallelRoutes: new Map()
  185. });
  186. }
  187. return;
  188. }
  189. if (childCacheNode === existingChildCacheNode) {
  190. childCacheNode = {
  191. data: childCacheNode.data,
  192. subTreeData: childCacheNode.subTreeData,
  193. parallelRoutes: new Map(childCacheNode.parallelRoutes)
  194. };
  195. childSegmentMap.set(segment, childCacheNode);
  196. }
  197. return fillCacheWithDataProperty(childCacheNode, existingChildCacheNode, segments.slice(1), fetchResponse);
  198. }
  199. /**
  200. * Create optimistic version of router state based on the existing router state and segments.
  201. * This is used to allow rendering layout-routers up till the point where data is missing.
  202. */ function createOptimisticTree(segments, flightRouterState, _isFirstSegment, parentRefetch, _href) {
  203. const [existingSegment, existingParallelRoutes] = flightRouterState || [
  204. null,
  205. {},
  206. ];
  207. const segment = segments[0];
  208. const isLastSegment = segments.length === 1;
  209. const segmentMatches = existingSegment !== null && (0, _matchSegments).matchSegment(existingSegment, segment);
  210. const shouldRefetchThisLevel = !flightRouterState || !segmentMatches;
  211. let parallelRoutes = {};
  212. if (existingSegment !== null && segmentMatches) {
  213. parallelRoutes = existingParallelRoutes;
  214. }
  215. let childTree;
  216. if (!isLastSegment) {
  217. const childItem = createOptimisticTree(segments.slice(1), parallelRoutes ? parallelRoutes.children : null, false, parentRefetch || shouldRefetchThisLevel);
  218. childTree = childItem;
  219. }
  220. const result = [
  221. segment,
  222. _extends({}, parallelRoutes, childTree ? {
  223. children: childTree
  224. } : {}),
  225. ];
  226. if (!parentRefetch && shouldRefetchThisLevel) {
  227. result[3] = 'refetch';
  228. }
  229. // TODO-APP: Revisit
  230. // Add url into the tree
  231. // if (isFirstSegment) {
  232. // result[2] = href
  233. // }
  234. return result;
  235. }
  236. /**
  237. * Apply the router state from the Flight response. Creates a new router state tree.
  238. */ function applyRouterStatePatchToTree(flightSegmentPath, flightRouterState, treePatch) {
  239. const [segment, parallelRoutes /* , url */ ] = flightRouterState;
  240. // Root refresh
  241. if (flightSegmentPath.length === 1) {
  242. const tree = [
  243. ...treePatch
  244. ];
  245. // TODO-APP: revisit
  246. // if (url) {
  247. // tree[2] = url
  248. // }
  249. return tree;
  250. }
  251. const [currentSegment, parallelRouteKey] = flightSegmentPath;
  252. // Tree path returned from the server should always match up with the current tree in the browser
  253. if (!(0, _matchSegments).matchSegment(currentSegment, segment)) {
  254. return null;
  255. }
  256. const lastSegment = flightSegmentPath.length === 2;
  257. let parallelRoutePatch;
  258. if (lastSegment) {
  259. parallelRoutePatch = treePatch;
  260. } else {
  261. parallelRoutePatch = applyRouterStatePatchToTree(flightSegmentPath.slice(2), parallelRoutes[parallelRouteKey], treePatch);
  262. if (parallelRoutePatch === null) {
  263. return null;
  264. }
  265. }
  266. const tree = [
  267. flightSegmentPath[0],
  268. _extends({}, parallelRoutes, {
  269. [parallelRouteKey]: parallelRoutePatch
  270. }),
  271. ];
  272. // TODO-APP: Revisit
  273. // if (url) {
  274. // tree[2] = url
  275. // }
  276. return tree;
  277. }
  278. function shouldHardNavigate(flightSegmentPath, flightRouterState, treePatch) {
  279. const [segment, parallelRoutes] = flightRouterState;
  280. // TODO-APP: Check if `as` can be replaced.
  281. const [currentSegment, parallelRouteKey] = flightSegmentPath;
  282. // If dynamic parameter in tree doesn't match up with segment path a hard navigation is triggered.
  283. if (Array.isArray(currentSegment) && !(0, _matchSegments).matchSegment(currentSegment, segment)) {
  284. return true;
  285. }
  286. const lastSegment = flightSegmentPath.length <= 2;
  287. if (lastSegment) {
  288. return false;
  289. }
  290. return shouldHardNavigate(flightSegmentPath.slice(2), parallelRoutes[parallelRouteKey], treePatch);
  291. }
  292. const ACTION_RELOAD = 'reload';
  293. exports.ACTION_RELOAD = ACTION_RELOAD;
  294. const ACTION_NAVIGATE = 'navigate';
  295. exports.ACTION_NAVIGATE = ACTION_NAVIGATE;
  296. const ACTION_RESTORE = 'restore';
  297. exports.ACTION_RESTORE = ACTION_RESTORE;
  298. const ACTION_SERVER_PATCH = 'server-patch';
  299. exports.ACTION_SERVER_PATCH = ACTION_SERVER_PATCH;
  300. const ACTION_PREFETCH = 'prefetch';
  301. exports.ACTION_PREFETCH = ACTION_PREFETCH;
  302. function reducer(state, action) {
  303. switch(action.type){
  304. case ACTION_NAVIGATE:
  305. {
  306. const { url , navigateType , cache , mutable , forceOptimisticNavigation } = action;
  307. const { pathname , search , hash } = url;
  308. const href = pathname + search + hash;
  309. const pendingPush = navigateType === 'push';
  310. // Handle concurrent rendering / strict mode case where the cache and tree were already populated.
  311. if (mutable.patchedTree && JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)) {
  312. return {
  313. // Set href.
  314. canonicalUrl: href,
  315. // TODO-APP: verify mpaNavigation not being set is correct here.
  316. pushRef: {
  317. pendingPush,
  318. mpaNavigation: false
  319. },
  320. // All navigation requires scroll and focus management to trigger.
  321. focusAndScrollRef: {
  322. apply: true
  323. },
  324. // Apply cache.
  325. cache: mutable.useExistingCache ? state.cache : cache,
  326. prefetchCache: state.prefetchCache,
  327. // Apply patched router state.
  328. tree: mutable.patchedTree
  329. };
  330. }
  331. const prefetchValues = state.prefetchCache.get(href);
  332. if (prefetchValues) {
  333. // The one before last item is the router state tree patch
  334. const { flightSegmentPath , treePatch } = prefetchValues;
  335. // Create new tree based on the flightSegmentPath and router state patch
  336. const newTree = applyRouterStatePatchToTree(// TODO-APP: remove ''
  337. [
  338. '',
  339. ...flightSegmentPath
  340. ], state.tree, treePatch);
  341. if (newTree !== null) {
  342. mutable.previousTree = state.tree;
  343. mutable.patchedTree = newTree;
  344. const hardNavigate = // TODO-APP: Revisit if this is correct.
  345. search !== location.search || shouldHardNavigate(// TODO-APP: remove ''
  346. [
  347. '',
  348. ...flightSegmentPath
  349. ], state.tree, newTree);
  350. if (hardNavigate) {
  351. // TODO-APP: segments.slice(1) strips '', we can get rid of '' altogether.
  352. // Copy subTreeData for the root node of the cache.
  353. cache.subTreeData = state.cache.subTreeData;
  354. invalidateCacheBelowFlightSegmentPath(cache, state.cache, flightSegmentPath);
  355. } else {
  356. mutable.useExistingCache = true;
  357. }
  358. return {
  359. // Set href.
  360. canonicalUrl: href,
  361. // Set pendingPush.
  362. pushRef: {
  363. pendingPush,
  364. mpaNavigation: false
  365. },
  366. // All navigation requires scroll and focus management to trigger.
  367. focusAndScrollRef: {
  368. apply: true
  369. },
  370. // Apply patched cache.
  371. cache: mutable.useExistingCache ? state.cache : cache,
  372. prefetchCache: state.prefetchCache,
  373. // Apply patched tree.
  374. tree: newTree
  375. };
  376. }
  377. }
  378. // When doing a hard push there can be two cases: with optimistic tree and without
  379. // The with optimistic tree case only happens when the layouts have a loading state (loading.js)
  380. // The without optimistic tree case happens when there is no loading state, in that case we suspend in this reducer
  381. // forceOptimisticNavigation is used for links that have `prefetch={false}`.
  382. if (forceOptimisticNavigation) {
  383. const segments = pathname.split('/');
  384. // TODO-APP: figure out something better for index pages
  385. segments.push('');
  386. // Optimistic tree case.
  387. // If the optimistic tree is deeper than the current state leave that deeper part out of the fetch
  388. const optimisticTree = createOptimisticTree(segments, state.tree, true, false, href);
  389. // Fill in the cache with blank that holds the `data` field.
  390. // TODO-APP: segments.slice(1) strips '', we can get rid of '' altogether.
  391. // Copy subTreeData for the root node of the cache.
  392. cache.subTreeData = state.cache.subTreeData;
  393. // Copy existing cache nodes as far as possible and fill in `data` property with the started data fetch.
  394. // The `data` property is used to suspend in layout-router during render if it hasn't resolved yet by the time it renders.
  395. const res = fillCacheWithDataProperty(cache, state.cache, segments.slice(1), ()=>(0, _appRouterClient).fetchServerResponse(url, optimisticTree));
  396. // If optimistic fetch couldn't happen it falls back to the non-optimistic case.
  397. if (!(res == null ? void 0 : res.bailOptimistic)) {
  398. mutable.previousTree = state.tree;
  399. mutable.patchedTree = optimisticTree;
  400. return {
  401. // Set href.
  402. canonicalUrl: href,
  403. // Set pendingPush.
  404. pushRef: {
  405. pendingPush,
  406. mpaNavigation: false
  407. },
  408. // All navigation requires scroll and focus management to trigger.
  409. focusAndScrollRef: {
  410. apply: true
  411. },
  412. // Apply patched cache.
  413. cache: cache,
  414. prefetchCache: state.prefetchCache,
  415. // Apply optimistic tree.
  416. tree: optimisticTree
  417. };
  418. }
  419. }
  420. // Below is the not-optimistic case. Data is fetched at the root and suspended there without a suspense boundary.
  421. // If no in-flight fetch at the top, start it.
  422. if (!cache.data) {
  423. cache.data = (0, _appRouterClient).fetchServerResponse(url, state.tree);
  424. }
  425. // Unwrap cache data with `use` to suspend here (in the reducer) until the fetch resolves.
  426. const [flightData] = (0, _react).experimental_use(cache.data);
  427. // Handle case when navigating to page in `pages` from `app`
  428. if (typeof flightData === 'string') {
  429. return {
  430. canonicalUrl: flightData,
  431. // Enable mpaNavigation
  432. pushRef: {
  433. pendingPush: true,
  434. mpaNavigation: true
  435. },
  436. // Don't apply scroll and focus management.
  437. focusAndScrollRef: {
  438. apply: false
  439. },
  440. cache: state.cache,
  441. prefetchCache: state.prefetchCache,
  442. tree: state.tree
  443. };
  444. }
  445. // Remove cache.data as it has been resolved at this point.
  446. cache.data = null;
  447. // TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths.
  448. const flightDataPath = flightData[0];
  449. // The one before last item is the router state tree patch
  450. const [treePatch] = flightDataPath.slice(-2);
  451. // Path without the last segment, router state, and the subTreeData
  452. const flightSegmentPath = flightDataPath.slice(0, -3);
  453. // Create new tree based on the flightSegmentPath and router state patch
  454. const newTree = applyRouterStatePatchToTree(// TODO-APP: remove ''
  455. [
  456. '',
  457. ...flightSegmentPath
  458. ], state.tree, treePatch);
  459. if (newTree === null) {
  460. throw new Error('SEGMENT MISMATCH');
  461. }
  462. mutable.previousTree = state.tree;
  463. mutable.patchedTree = newTree;
  464. // Copy subTreeData for the root node of the cache.
  465. cache.subTreeData = state.cache.subTreeData;
  466. // Create a copy of the existing cache with the subTreeData applied.
  467. fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath);
  468. return {
  469. // Set href.
  470. canonicalUrl: href,
  471. // Set pendingPush.
  472. pushRef: {
  473. pendingPush,
  474. mpaNavigation: false
  475. },
  476. // All navigation requires scroll and focus management to trigger.
  477. focusAndScrollRef: {
  478. apply: true
  479. },
  480. // Apply patched cache.
  481. cache: cache,
  482. prefetchCache: state.prefetchCache,
  483. // Apply patched tree.
  484. tree: newTree
  485. };
  486. }
  487. case ACTION_SERVER_PATCH:
  488. {
  489. const { flightData , previousTree , cache , mutable } = action;
  490. // When a fetch is slow to resolve it could be that you navigated away while the request was happening or before the reducer runs.
  491. // In that case opt-out of applying the patch given that the data could be stale.
  492. if (JSON.stringify(previousTree) !== JSON.stringify(state.tree)) {
  493. // TODO-APP: Handle tree mismatch
  494. console.log('TREE MISMATCH');
  495. // Keep everything as-is.
  496. return state;
  497. }
  498. // Handle concurrent rendering / strict mode case where the cache and tree were already populated.
  499. if (mutable.patchedTree) {
  500. return {
  501. // Keep href as it was set during navigate / restore
  502. canonicalUrl: state.canonicalUrl,
  503. // Keep pushRef as server-patch only causes cache/tree update.
  504. pushRef: state.pushRef,
  505. // Keep focusAndScrollRef as server-patch only causes cache/tree update.
  506. focusAndScrollRef: state.focusAndScrollRef,
  507. // Apply patched router state
  508. tree: mutable.patchedTree,
  509. prefetchCache: state.prefetchCache,
  510. // Apply patched cache
  511. cache: cache
  512. };
  513. }
  514. // Handle case when navigating to page in `pages` from `app`
  515. if (typeof flightData === 'string') {
  516. return {
  517. // Set href.
  518. canonicalUrl: flightData,
  519. // Enable mpaNavigation as this is a navigation that the app-router shouldn't handle.
  520. pushRef: {
  521. pendingPush: true,
  522. mpaNavigation: true
  523. },
  524. // Don't apply scroll and focus management.
  525. focusAndScrollRef: {
  526. apply: false
  527. },
  528. // Other state is kept as-is.
  529. cache: state.cache,
  530. prefetchCache: state.prefetchCache,
  531. tree: state.tree
  532. };
  533. }
  534. // TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths.
  535. const flightDataPath = flightData[0];
  536. // Slices off the last segment (which is at -3) as it doesn't exist in the tree yet
  537. const treePath = flightDataPath.slice(0, -3);
  538. const [treePatch] = flightDataPath.slice(-2);
  539. const newTree = applyRouterStatePatchToTree(// TODO-APP: remove ''
  540. [
  541. '',
  542. ...treePath
  543. ], state.tree, treePatch);
  544. if (newTree === null) {
  545. throw new Error('SEGMENT MISMATCH');
  546. }
  547. mutable.patchedTree = newTree;
  548. // Copy subTreeData for the root node of the cache.
  549. cache.subTreeData = state.cache.subTreeData;
  550. fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath);
  551. return {
  552. // Keep href as it was set during navigate / restore
  553. canonicalUrl: state.canonicalUrl,
  554. // Keep pushRef as server-patch only causes cache/tree update.
  555. pushRef: state.pushRef,
  556. // Keep focusAndScrollRef as server-patch only causes cache/tree update.
  557. focusAndScrollRef: state.focusAndScrollRef,
  558. // Apply patched router state
  559. tree: newTree,
  560. prefetchCache: state.prefetchCache,
  561. // Apply patched cache
  562. cache: cache
  563. };
  564. }
  565. case ACTION_RESTORE:
  566. {
  567. const { url , tree } = action;
  568. const href = url.pathname + url.search + url.hash;
  569. return {
  570. // Set canonical url
  571. canonicalUrl: href,
  572. pushRef: state.pushRef,
  573. focusAndScrollRef: state.focusAndScrollRef,
  574. cache: state.cache,
  575. prefetchCache: state.prefetchCache,
  576. // Restore provided tree
  577. tree: tree
  578. };
  579. }
  580. case ACTION_RELOAD:
  581. {
  582. const { cache , mutable } = action;
  583. const href = state.canonicalUrl;
  584. // Handle concurrent rendering / strict mode case where the cache and tree were already populated.
  585. if (mutable.patchedTree && JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)) {
  586. return {
  587. // Set href.
  588. canonicalUrl: href,
  589. // set pendingPush (always false in this case).
  590. pushRef: state.pushRef,
  591. // Apply focus and scroll.
  592. // TODO-APP: might need to disable this for Fast Refresh.
  593. focusAndScrollRef: {
  594. apply: true
  595. },
  596. cache: cache,
  597. prefetchCache: state.prefetchCache,
  598. tree: mutable.patchedTree
  599. };
  600. }
  601. if (!cache.data) {
  602. // Fetch data from the root of the tree.
  603. cache.data = (0, _appRouterClient).fetchServerResponse(new URL(href, location.origin), [
  604. state.tree[0],
  605. state.tree[1],
  606. state.tree[2],
  607. 'refetch',
  608. ]);
  609. }
  610. const [flightData] = (0, _react).experimental_use(cache.data);
  611. // Handle case when navigating to page in `pages` from `app`
  612. if (typeof flightData === 'string') {
  613. return {
  614. canonicalUrl: flightData,
  615. pushRef: {
  616. pendingPush: true,
  617. mpaNavigation: true
  618. },
  619. focusAndScrollRef: {
  620. apply: false
  621. },
  622. cache: state.cache,
  623. prefetchCache: state.prefetchCache,
  624. tree: state.tree
  625. };
  626. }
  627. // Remove cache.data as it has been resolved at this point.
  628. cache.data = null;
  629. // TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths.
  630. const flightDataPath = flightData[0];
  631. // FlightDataPath with more than two items means unexpected Flight data was returned
  632. if (flightDataPath.length !== 2) {
  633. // TODO-APP: handle this case better
  634. console.log('RELOAD FAILED');
  635. return state;
  636. }
  637. // Given the path can only have two items the items are only the router state and subTreeData for the root.
  638. const [treePatch, subTreeData] = flightDataPath;
  639. const newTree = applyRouterStatePatchToTree(// TODO-APP: remove ''
  640. [
  641. ''
  642. ], state.tree, treePatch);
  643. if (newTree === null) {
  644. throw new Error('SEGMENT MISMATCH');
  645. }
  646. mutable.previousTree = state.tree;
  647. mutable.patchedTree = newTree;
  648. // Set subTreeData for the root node of the cache.
  649. cache.subTreeData = subTreeData;
  650. return {
  651. // Set href, this doesn't reuse the state.canonicalUrl as because of concurrent rendering the href might change between dispatching and applying.
  652. canonicalUrl: href,
  653. // set pendingPush (always false in this case).
  654. pushRef: state.pushRef,
  655. // TODO-APP: might need to disable this for Fast Refresh.
  656. focusAndScrollRef: {
  657. apply: false
  658. },
  659. // Apply patched cache.
  660. cache: cache,
  661. prefetchCache: state.prefetchCache,
  662. // Apply patched router state.
  663. tree: newTree
  664. };
  665. }
  666. case ACTION_PREFETCH:
  667. {
  668. const { url , flightData } = action;
  669. // TODO-APP: Implement prefetch for hard navigation
  670. if (typeof flightData === 'string') {
  671. return state;
  672. }
  673. const { pathname , search , hash } = url;
  674. const href = pathname + search + hash;
  675. // TODO-APP: Currently the Flight data can only have one item but in the future it can have multiple paths.
  676. const flightDataPath = flightData[0];
  677. // The one before last item is the router state tree patch
  678. const [treePatch, subTreeData] = flightDataPath.slice(-2);
  679. // TODO-APP: Verify if `null` can't be returned from user code.
  680. // If subTreeData is null the prefetch did not provide a component tree.
  681. if (subTreeData !== null) {
  682. fillCacheWithPrefetchedSubTreeData(state.cache, flightDataPath);
  683. }
  684. // Create new tree based on the flightSegmentPath and router state patch
  685. state.prefetchCache.set(href, {
  686. // Path without the last segment, router state, and the subTreeData
  687. flightSegmentPath: flightDataPath.slice(0, -2),
  688. treePatch
  689. });
  690. return state;
  691. }
  692. // This case should never be hit as dispatch is strongly typed.
  693. default:
  694. throw new Error('Unknown action');
  695. }
  696. }
  697. if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
  698. Object.defineProperty(exports.default, '__esModule', { value: true });
  699. Object.assign(exports.default, exports);
  700. module.exports = exports.default;
  701. }
  702. //# sourceMappingURL=reducer.js.map