expo-router 0.0.17 → 0.0.19

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/babel.js CHANGED
@@ -1,9 +1,33 @@
1
- const { relative } = require("path");
1
+ const nodePath = require("path");
2
+ const resolveFrom = require("resolve-from");
3
+
4
+ const debug = require("debug")("expo:router:babel");
5
+
6
+ function getExpoRouterAppRoot(projectRoot) {
7
+ if (process.env.EXPO_ROUTER_APP_ROOT) {
8
+ return process.env.EXPO_ROUTER_APP_ROOT;
9
+ }
10
+ const routerEntry = resolveFrom.silent(projectRoot, "expo-router/entry");
11
+
12
+ if (!routerEntry) {
13
+ console.warn(
14
+ `Required environment variable EXPO_ROUTER_APP_ROOT is not defined, bundle with Expo CLI (expo@^46.0.13) to fix.`
15
+ );
16
+ process.env.EXPO_ROUTER_APP_ROOT = "../../app";
17
+ return process.env.EXPO_ROUTER_APP_ROOT;
18
+ }
19
+ // It doesn't matter if the app folder exists.
20
+ const appFolder = nodePath.join(projectRoot, "app");
21
+ const appRoot = nodePath.relative(nodePath.dirname(routerEntry), appFolder);
22
+ debug("routerEntry", routerEntry, appFolder, appRoot);
23
+
24
+ return appRoot;
25
+ }
2
26
 
3
27
  module.exports = function (api) {
4
28
  const { types: t } = api;
5
29
  const getRelPath = (state) =>
6
- "./" + relative(state.file.opts.root, state.filename);
30
+ "./" + nodePath.relative(state.file.opts.root, state.filename);
7
31
 
8
32
  return {
9
33
  name: "expo-router",
@@ -15,35 +39,6 @@ module.exports = function (api) {
15
39
  }
16
40
  },
17
41
 
18
- // Auto add the React prop `context={require.context('./app')}` to a component named `Root` that's
19
- JSXOpeningElement(path, state) {
20
- if (!getRelPath(state).match(/^\.\/app\//)) {
21
- return;
22
- }
23
- if (path.node.name.name === "ExpoRoot") {
24
- // Check if the context prop already exists
25
- const contextProp = path.node.attributes.find(
26
- (attr) => attr.name.name === "context"
27
- );
28
- if (contextProp) {
29
- return;
30
- }
31
-
32
- path.node.attributes.push(
33
- t.jsxAttribute(
34
- t.jsxIdentifier("context"),
35
- t.jsxExpressionContainer(
36
- t.callExpression(t.identifier("require"), [
37
- t.callExpression(t.identifier("context"), [
38
- t.stringLiteral("./app"),
39
- ]),
40
- ])
41
- )
42
- )
43
- );
44
- }
45
- },
46
-
47
42
  // Convert `process.env.EXPO_ROUTER_APP_ROOT` to a string literal
48
43
  MemberExpression(path, state) {
49
44
  if (
@@ -85,9 +80,10 @@ module.exports = function (api) {
85
80
  return;
86
81
  }
87
82
 
88
- if (process.env.EXPO_ROUTER_APP_ROOT != null) {
89
- parent.replaceWith(t.stringLiteral(process.env.EXPO_ROUTER_APP_ROOT));
90
- }
83
+ parent.replaceWith(
84
+ // This is defined in Expo CLI when using Metro. It points to the relative path for the project app directory.
85
+ t.stringLiteral(getExpoRouterAppRoot(state.file.opts.root))
86
+ );
91
87
  },
92
88
  },
93
89
  };
@@ -239,6 +239,13 @@ const matchAgainstConfigs = (remaining, configs) => {
239
239
  }
240
240
  return { name };
241
241
  });
242
+ // TODO(EvanBacon): Maybe we should warn / assert if multiple slugs use the same param name.
243
+ const combinedParams = routes.reduce((acc, r) => Object.assign(acc, r.params), {});
244
+ // Combine all params so a route `[foo]/[bar]/other.js` has access to `{ foo, bar }`
245
+ routes = routes.map((r) => ({
246
+ ...r,
247
+ params: combinedParams,
248
+ }));
242
249
  remainingPath = remainingPath.replace(match[1], "");
243
250
  break;
244
251
  }
@@ -1 +1 @@
1
- {"version":3,"file":"getStateFromPath.js","sourceRoot":"","sources":["../../src/fork/getStateFromPath.ts"],"names":[],"mappings":"AAKA,OAAO,MAAM,MAAM,sBAAsB,CAAC;AAC1C,OAAO,KAAK,WAAW,MAAM,cAAc,CAAC;AAE5C,OAAO,EAEL,gBAAgB,EAChB,kBAAkB,GACnB,MAAM,wBAAwB,CAAC;AAuChC;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,CAAC,OAAO,UAAU,gBAAgB,CACtC,IAAY,EACZ,OA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AI,CAAC,KAAK,QAAQ,EAChC;gBACA,MAAM,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,IAAI,CAAW,CAAC,CAAC;aAC1D;QACH,CAAC,CAAC,CAAC;KACJ;IAED,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;AACzD,CAAC,CAAC","sourcesContent":["import type {\n InitialState,\n NavigationState,\n PartialState,\n} from \"@react-navigation/routers\";\nimport escape from \"escape-string-regexp\";\nimport * as queryString from \"query-string\";\n\nimport {\n PathConfigMap,\n findFocusedRoute,\n validatePathConfig,\n} from \"@react-navigation/core\";\n\n// import findFocusedRoute from './findFocusedRoute';\n// import type { PathConfigMap } from './types';\n// import validatePathConfig from './validatePathConfig';\n\ntype Options<ParamList extends {}> = {\n initialRouteName?: string;\n screens: PathConfigMap<ParamList>;\n};\n\ntype ParseConfig = Record<string, (value: string) => any>;\n\ntype RouteConfig = {\n screen: string;\n regex?: RegExp;\n path: string;\n pattern: string;\n routeNames: string[];\n parse?: ParseConfig;\n hasChildren: boolean;\n userReadableName: string;\n};\n\ntype InitialRouteConfig = {\n initialRouteName: string;\n parentScreens: string[];\n};\n\ntype ResultState = PartialState<NavigationState> & {\n state?: ResultState;\n};\n\ntype ParsedRoute = {\n name: string;\n path?: string;\n params?: Record<string, any> | undefined;\n};\n\n/**\n * Utility to parse a path string to initial state object accepted by the container.\n * This is useful for deep linking when we need to handle the incoming URL.\n *\n * @example\n * ```js\n * getStateFromPath(\n * '/chat/jane/42',\n * {\n * screens: {\n * Chat: {\n * path: 'chat/:author/:id',\n * parse: { id: Number }\n * }\n * }\n * }\n * )\n * ```\n * @param path Path string to parse and convert, e.g. /foo/bar?count=42.\n * @param options Extra options to fine-tune how to parse the path.\n */\nexport default function getStateFromPath<ParamList extends {}>(\n path: string,\n options?: Options<ParamList>\n): ResultState | undefined {\n if (options) {\n validatePathConfig(options);\n }\n\n let initialRoutes: InitialRouteConfig[] = [];\n\n if (options?.initialRouteName) {\n initialRoutes.push({\n initialRouteName: options.initialRouteName,\n parentScreens: [],\n });\n }\n\n const screens = options?.screens;\n\n let remaining = path\n .replace(/\\/+/g, \"/\") // Replace multiple slash (//) with single ones\n .replace(/^\\//, \"\") // Remove extra leading slash\n .replace(/\\?.*$/, \"\"); // Remove query params which we will handle later\n\n // Make sure there is a trailing slash\n remaining = remaining.endsWith(\"/\") ? remaining : `${remaining}/`;\n\n if (screens === undefined) {\n // When no config is specified, use the path segments as route names\n const routes = remaining\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => {\n const name = decodeURIComponent(segment);\n return { name };\n });\n\n if (routes.length) {\n return createNestedStateObject(path, routes, initialRoutes);\n }\n\n return undefined;\n }\n\n // Create a normalized configs array which will be easier to use\n const configs = ([] as RouteConfig[])\n .concat(\n ...Object.keys(screens).map((key) =>\n createNormalizedConfigs(\n key,\n screens as PathConfigMap<object>,\n [],\n initialRoutes,\n []\n )\n )\n )\n .sort((a, b) => {\n // Sort config so that:\n // - the most exhaustive ones are always at the beginning\n // - patterns with wildcard are always at the end\n\n // If 2 patterns are same, move the one with less route names up\n // This is an error state, so it's only useful for consistent error messages\n if (a.pattern === b.pattern) {\n return b.routeNames.join(\">\").localeCompare(a.routeNames.join(\">\"));\n }\n\n // If one of the patterns starts with the other, it's more exhaustive\n // So move it up\n if (\n a.pattern.startsWith(b.pattern) &&\n // NOTE(EvanBacon): This is a hack to make sure that `*` is always at the end\n b.screen !== \"index\"\n ) {\n return -1;\n }\n\n if (b.pattern.startsWith(a.pattern) && a.screen !== \"index\") {\n return 1;\n }\n\n // NOTE(EvanBacon): Here we append `index` if the screen was `index` so the length is the same\n // as a slug or wildcard when nested more than one level deep.\n // This is so we can compare the length of the pattern, e.g. `foo/*` > `foo` vs `*` < ``.\n const aParts = a.pattern.split(\"/\");\n if (a.screen === \"index\") {\n aParts.push(\"index\");\n }\n\n const bParts = b.pattern.split(\"/\");\n if (b.screen === \"index\") {\n bParts.push(\"index\");\n }\n\n for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {\n // if b is longer, b get higher priority\n if (aParts[i] == null) {\n return 1;\n }\n // if a is longer, a get higher priority\n if (bParts[i] == null) {\n return -1;\n }\n const aWildCard = aParts[i] === \"*\";\n const bWildCard = bParts[i] === \"*\";\n // if both are wildcard we compare next component\n if (aWildCard && bWildCard) {\n continue;\n }\n // if only a is wild card, b get higher priority\n if (aWildCard) {\n return 1;\n }\n // if only b is wild card, a get higher priority\n if (bWildCard) {\n return -1;\n }\n\n const aSlug = aParts[i].startsWith(\":\");\n const bSlug = bParts[i].startsWith(\":\");\n // if both are wildcard we compare next component\n if (aSlug && bSlug) {\n continue;\n }\n // if only a is wild card, b get higher priority\n if (aSlug) {\n return 1;\n }\n // if only b is wild card, a get higher priority\n if (bSlug) {\n return -1;\n }\n }\n return bParts.length - aParts.length;\n });\n\n // Match full paths\n\n // Check for duplicate patterns in the config\n configs.reduce<Record<string, RouteConfig>>((acc, config) => {\n // NOTE(EvanBacon): Uses the regex pattern as key to detect duplicate slugs.\n const indexedKey = config.regex?.toString() ?? config.pattern;\n const alpha = acc[indexedKey];\n // NOTE(EvanBacon): Skips checking nodes that have children.\n if (alpha && !alpha.hasChildren && !config.hasChildren) {\n const a = alpha.routeNames;\n const b = config.routeNames;\n\n // It's not a problem if the path string omitted from a inner most screen\n // For example, it's ok if a path resolves to `A > B > C` or `A > B`\n const intersects =\n a.length > b.length\n ? b.every((it, i) => a[i] === it)\n : a.every((it, i) => b[i] === it);\n\n if (!intersects) {\n // NOTE(EvanBacon): Adds more context to the error message since we know about the\n // file system-based routing.\n const last = config.pattern.split(\"/\").pop();\n const routeType = last?.startsWith(\":\")\n ? \"dynamic route\"\n : last === \"*\"\n ? \"deep dynamic route\"\n : \"route\";\n throw new Error(\n `The ${routeType} pattern '${\n config.pattern || \"/\"\n }' resolves to both '${alpha.userReadableName}' and '${\n config.userReadableName\n }'. Patterns must be unique and cannot resolve to more than one route.`\n );\n }\n }\n\n return Object.assign(acc, {\n [indexedKey]: config,\n });\n }, {});\n\n if (remaining === \"/\") {\n // We need to add special handling of empty path so navigation to empty path also works\n // When handling empty path, we should only look at the root level config\n\n // NOTE(EvanBacon): We only care about matching leaf nodes.\n const leafNodes = configs.filter((config) => !config.hasChildren);\n\n const match =\n leafNodes.find(\n (config) =>\n // NOTE(EvanBacon): Test leaf node index routes that either don't have a regex or match an empty string.\n config.path === \"\" && (!config.regex || config.regex.test(\"\"))\n ) ??\n leafNodes.find(\n (config) =>\n // NOTE(EvanBacon): Test leaf node dynamic routes that match an empty string.\n config.path.startsWith(\":\") && config.regex!.test(\"\")\n ) ??\n // NOTE(EvanBacon): Test leaf node deep dynamic routes that match a slash.\n // This should be done last to enable dynamic routes having a higher priority.\n leafNodes.find(\n (config) => config.path === \"*\" && config.regex!.test(\"/\")\n );\n\n if (match) {\n return createNestedStateObject(\n path,\n match.routeNames.map((name) => ({ name })),\n initialRoutes,\n configs\n );\n }\n\n return undefined;\n }\n\n let result: PartialState<NavigationState> | undefined;\n let current: PartialState<NavigationState> | undefined;\n\n // We match the whole path against the regex instead of segments\n // This makes sure matches such as wildcard will catch any unmatched routes, even if nested\n const { routes, remainingPath } = matchAgainstConfigs(\n remaining,\n configs.map((c) => ({\n ...c,\n // Add `$` to the regex to make sure it matches till end of the path and not just beginning\n regex: c.regex ? new RegExp(c.regex.source + \"$\") : undefined,\n }))\n );\n\n if (routes !== undefined) {\n // This will always be empty if full path matched\n current = createNestedStateObject(path, routes, initialRoutes, configs);\n remaining = remainingPath;\n result = current;\n }\n\n if (current == null || result == null) {\n return undefined;\n }\n\n return result;\n}\n\nconst joinPaths = (...paths: string[]): string =>\n ([] as string[])\n .concat(...paths.map((p) => p.split(\"/\")))\n .filter(Boolean)\n .join(\"/\");\n\nconst matchAgainstConfigs = (remaining: string, configs: RouteConfig[]) => {\n let routes: ParsedRoute[] | undefined;\n let remainingPath = remaining;\n\n // Go through all configs, and see if the next path segment matches our regex\n for (const config of configs) {\n if (!config.regex) {\n continue;\n }\n\n const match = remainingPath.match(config.regex);\n\n // If our regex matches, we need to extract params from the path\n if (match) {\n // TODO: Add support for wildcard routes\n const matchedParams = config.pattern\n ?.split(\"/\")\n .filter((p) => p.startsWith(\":\"))\n .reduce<Record<string, any>>(\n (acc, p, i) =>\n Object.assign(acc, {\n // The param segments appear every second item starting from 2 in the regex match result\n [p]: match![(i + 1) * 2].replace(/\\//, \"\"),\n }),\n {}\n );\n\n routes = config.routeNames.map((name) => {\n const config = configs.find((c) => c.screen === name);\n const params = config?.path\n ?.split(\"/\")\n .filter((p) => p.startsWith(\":\"))\n .reduce<Record<string, any>>((acc, p) => {\n const paramName = p;\n const value = matchedParams[paramName];\n\n if (value) {\n const key = paramName.replace(/^:/, \"\").replace(/\\?$/, \"\");\n acc[key] = config.parse?.[key] ? config.parse[key](value) : value;\n }\n\n return acc;\n }, {});\n\n if (params && Object.keys(params).length) {\n return { name, params };\n }\n\n return { name };\n });\n\n remainingPath = remainingPath.replace(match[1], \"\");\n\n break;\n }\n }\n\n return { routes, remainingPath };\n};\n\nconst createNormalizedConfigs = (\n screen: string,\n routeConfig: PathConfigMap<object>,\n routeNames: string[] = [],\n initials: InitialRouteConfig[],\n parentScreens: string[],\n parentPattern?: string\n): RouteConfig[] => {\n const configs: RouteConfig[] = [];\n\n routeNames.push(screen);\n\n parentScreens.push(screen);\n\n const config = routeConfig[screen];\n\n if (typeof config === \"string\") {\n // If a string is specified as the value of the key(e.g. Foo: '/path'), use it as the pattern\n const pattern = parentPattern ? joinPaths(parentPattern, config) : config;\n\n configs.push(createConfigItem(screen, routeNames, pattern, config, false));\n } else if (typeof config === \"object\") {\n let pattern: string | undefined;\n\n // if an object is specified as the value (e.g. Foo: { ... }),\n // it can have `path` property and\n // it could have `screens` prop which has nested configs\n if (typeof config.path === \"string\") {\n if (config.exact && config.path === undefined) {\n throw new Error(\n \"A 'path' needs to be specified when specifying 'exact: true'. If you don't want this screen in the URL, specify it as empty string, e.g. `path: ''`.\"\n );\n }\n\n pattern =\n config.exact !== true\n ? joinPaths(parentPattern || \"\", config.path || \"\")\n : config.path || \"\";\n\n configs.push(\n createConfigItem(\n screen,\n routeNames,\n pattern!,\n config.path,\n config.screens ? !!Object.keys(config.screens)?.length : false,\n config.parse\n )\n );\n }\n\n if (config.screens) {\n // property `initialRouteName` without `screens` has no purpose\n if (config.initialRouteName) {\n initials.push({\n initialRouteName: config.initialRouteName,\n parentScreens,\n });\n }\n\n Object.keys(config.screens).forEach((nestedConfig) => {\n const result = createNormalizedConfigs(\n nestedConfig,\n config.screens as PathConfigMap<object>,\n routeNames,\n initials,\n [...parentScreens],\n pattern ?? parentPattern\n );\n\n configs.push(...result);\n });\n }\n }\n\n routeNames.pop();\n\n return configs;\n};\n\nconst createConfigItem = (\n screen: string,\n routeNames: string[],\n pattern: string,\n path: string,\n hasChildren?: boolean,\n parse?: ParseConfig\n): RouteConfig => {\n // Normalize pattern to remove any leading, trailing slashes, duplicate slashes etc.\n pattern = pattern.split(\"/\").filter(Boolean).join(\"/\");\n\n const regex = pattern\n ? new RegExp(\n `^(${pattern\n .split(\"/\")\n .map((it) => {\n if (it.startsWith(\":\")) {\n return `(([^/]+\\\\/)${it.endsWith(\"?\") ? \"?\" : \"\"})`;\n }\n\n return `${it === \"*\" ? \".*\" : escape(it)}\\\\/`;\n })\n .join(\"\")})`\n )\n : undefined;\n\n return {\n screen,\n regex,\n pattern,\n path,\n // The routeNames array is mutated, so copy it to keep the current state\n routeNames: [...routeNames],\n parse,\n userReadableName: [...routeNames.slice(0, -1), path || screen].join(\"/\"),\n hasChildren: !!hasChildren,\n };\n};\n\nconst findParseConfigForRoute = (\n routeName: string,\n flatConfig: RouteConfig[]\n): ParseConfig | undefined => {\n for (const config of flatConfig) {\n if (routeName === config.routeNames[config.routeNames.length - 1]) {\n return config.parse;\n }\n }\n\n return undefined;\n};\n\n// Try to find an initial route connected with the one passed\nconst findInitialRoute = (\n routeName: string,\n parentScreens: string[],\n initialRoutes: InitialRouteConfig[]\n): string | undefined => {\n for (const config of initialRoutes) {\n if (parentScreens.length === config.parentScreens.length) {\n let sameParents = true;\n for (let i = 0; i < parentScreens.length; i++) {\n if (parentScreens[i].localeCompare(config.parentScreens[i]) !== 0) {\n sameParents = false;\n break;\n }\n }\n if (sameParents) {\n return routeName !== config.initialRouteName\n ? config.initialRouteName\n : undefined;\n }\n }\n }\n return undefined;\n};\n\n// returns state object with values depending on whether\n// it is the end of state and if there is initialRoute for this level\nconst createStateObject = (\n initialRoute: string | undefined,\n route: ParsedRoute,\n isEmpty: boolean\n): InitialState => {\n if (isEmpty) {\n if (initialRoute) {\n return {\n index: 1,\n routes: [{ name: initialRoute }, route],\n };\n } else {\n return {\n routes: [route],\n };\n }\n } else {\n if (initialRoute) {\n return {\n index: 1,\n routes: [{ name: initialRoute }, { ...route, state: { routes: [] } }],\n };\n } else {\n return {\n routes: [{ ...route, state: { routes: [] } }],\n };\n }\n }\n};\n\nconst createNestedStateObject = (\n path: string,\n routes: ParsedRoute[],\n initialRoutes: InitialRouteConfig[],\n flatConfig?: RouteConfig[]\n) => {\n let state: InitialState;\n let route = routes.shift() as ParsedRoute;\n const parentScreens: string[] = [];\n\n let initialRoute = findInitialRoute(route.name, parentScreens, initialRoutes);\n\n parentScreens.push(route.name);\n\n state = createStateObject(initialRoute, route, routes.length === 0);\n\n if (routes.length > 0) {\n let nestedState = state;\n\n while ((route = routes.shift() as ParsedRoute)) {\n initialRoute = findInitialRoute(route.name, parentScreens, initialRoutes);\n\n const nestedStateIndex =\n nestedState.index || nestedState.routes.length - 1;\n\n nestedState.routes[nestedStateIndex].state = createStateObject(\n initialRoute,\n route,\n routes.length === 0\n );\n\n if (routes.length > 0) {\n nestedState = nestedState.routes[nestedStateIndex]\n .state as InitialState;\n }\n\n parentScreens.push(route.name);\n }\n }\n\n route = findFocusedRoute(state) as ParsedRoute;\n route.path = path;\n\n const params = parseQueryParams(\n path,\n flatConfig ? findParseConfigForRoute(route.name, flatConfig) : undefined\n );\n\n if (params) {\n route.params = { ...route.params, ...params };\n }\n\n return state;\n};\n\nconst parseQueryParams = (\n path: string,\n parseConfig?: Record<string, (value: string) => any>\n) => {\n const query = path.split(\"?\")[1];\n const params = queryString.parse(query);\n\n if (parseConfig) {\n Object.keys(params).forEach((name) => {\n if (\n Object.hasOwnProperty.call(parseConfig, name) &&\n typeof params[name] === \"string\"\n ) {\n params[name] = parseConfig[name](params[name] as string);\n }\n });\n }\n\n return Object.keys(params).length ? params : undefined;\n};\n"]}
1
+ {"version":3,"file":"getStateFromPath.js","sourceRoot":"","sources":["../../src/fork/getStateFromPath.ts"],"names":[],"mappings":"AAKA,OAAO,MAAM,MAAM,sBAAsB,CAAC;AAC1C,OAAO,KAAK,WAAW,MAAM,cAAc,CAAC;AAE5C,OAAO,EAEL,gBAAgB,EAChB,kBAAkB,GACnB,MAAM,wBAAwB,CAAC;AAuChC;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,CAAC,OAAO,UAAU,gBAAgB,CACtC,IAAY,EACZ,OAA4B;IAE5B,IAAI,OAAO,EAAE;QACX,kBAAkB,CAAC,OAAO,CAAC,CAAC;KAC7B;IAED,IAAI,aAAa,GAAyB,EAAE,CAAC;IAE7C,IAAI,OAAO,EAAE,gBAAgB,EAAE;QAC7B,aAAa,CAAC,IAAI,CAAC;YACjB,gBAAgB,EAAE,OAAO,CAAC,gBAAgB;YAC1C,aAAa,EAAE,EAAE;SAClB,CAAC,CAAC;KACJ;IAED,MAAM,OAAO,GAAG,OAAO,EAAE,OAAO,CAAC;IAEjC,IAAI,SAAS,GAAG,IAAI;SACjB,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,+CAA+C;SACpE,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,6BAA6B;SAChD,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,C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;KACJ;IAED,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;AACzD,CAAC,CAAC","sourcesContent":["import type {\n InitialState,\n NavigationState,\n PartialState,\n} from \"@react-navigation/routers\";\nimport escape from \"escape-string-regexp\";\nimport * as queryString from \"query-string\";\n\nimport {\n PathConfigMap,\n findFocusedRoute,\n validatePathConfig,\n} from \"@react-navigation/core\";\n\n// import findFocusedRoute from './findFocusedRoute';\n// import type { PathConfigMap } from './types';\n// import validatePathConfig from './validatePathConfig';\n\ntype Options<ParamList extends {}> = {\n initialRouteName?: string;\n screens: PathConfigMap<ParamList>;\n};\n\ntype ParseConfig = Record<string, (value: string) => any>;\n\ntype RouteConfig = {\n screen: string;\n regex?: RegExp;\n path: string;\n pattern: string;\n routeNames: string[];\n parse?: ParseConfig;\n hasChildren: boolean;\n userReadableName: string;\n};\n\ntype InitialRouteConfig = {\n initialRouteName: string;\n parentScreens: string[];\n};\n\ntype ResultState = PartialState<NavigationState> & {\n state?: ResultState;\n};\n\ntype ParsedRoute = {\n name: string;\n path?: string;\n params?: Record<string, any> | undefined;\n};\n\n/**\n * Utility to parse a path string to initial state object accepted by the container.\n * This is useful for deep linking when we need to handle the incoming URL.\n *\n * @example\n * ```js\n * getStateFromPath(\n * '/chat/jane/42',\n * {\n * screens: {\n * Chat: {\n * path: 'chat/:author/:id',\n * parse: { id: Number }\n * }\n * }\n * }\n * )\n * ```\n * @param path Path string to parse and convert, e.g. /foo/bar?count=42.\n * @param options Extra options to fine-tune how to parse the path.\n */\nexport default function getStateFromPath<ParamList extends {}>(\n path: string,\n options?: Options<ParamList>\n): ResultState | undefined {\n if (options) {\n validatePathConfig(options);\n }\n\n let initialRoutes: InitialRouteConfig[] = [];\n\n if (options?.initialRouteName) {\n initialRoutes.push({\n initialRouteName: options.initialRouteName,\n parentScreens: [],\n });\n }\n\n const screens = options?.screens;\n\n let remaining = path\n .replace(/\\/+/g, \"/\") // Replace multiple slash (//) with single ones\n .replace(/^\\//, \"\") // Remove extra leading slash\n .replace(/\\?.*$/, \"\"); // Remove query params which we will handle later\n\n // Make sure there is a trailing slash\n remaining = remaining.endsWith(\"/\") ? remaining : `${remaining}/`;\n\n if (screens === undefined) {\n // When no config is specified, use the path segments as route names\n const routes = remaining\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => {\n const name = decodeURIComponent(segment);\n return { name };\n });\n\n if (routes.length) {\n return createNestedStateObject(path, routes, initialRoutes);\n }\n\n return undefined;\n }\n\n // Create a normalized configs array which will be easier to use\n const configs = ([] as RouteConfig[])\n .concat(\n ...Object.keys(screens).map((key) =>\n createNormalizedConfigs(\n key,\n screens as PathConfigMap<object>,\n [],\n initialRoutes,\n []\n )\n )\n )\n .sort((a, b) => {\n // Sort config so that:\n // - the most exhaustive ones are always at the beginning\n // - patterns with wildcard are always at the end\n\n // If 2 patterns are same, move the one with less route names up\n // This is an error state, so it's only useful for consistent error messages\n if (a.pattern === b.pattern) {\n return b.routeNames.join(\">\").localeCompare(a.routeNames.join(\">\"));\n }\n\n // If one of the patterns starts with the other, it's more exhaustive\n // So move it up\n if (\n a.pattern.startsWith(b.pattern) &&\n // NOTE(EvanBacon): This is a hack to make sure that `*` is always at the end\n b.screen !== \"index\"\n ) {\n return -1;\n }\n\n if (b.pattern.startsWith(a.pattern) && a.screen !== \"index\") {\n return 1;\n }\n\n // NOTE(EvanBacon): Here we append `index` if the screen was `index` so the length is the same\n // as a slug or wildcard when nested more than one level deep.\n // This is so we can compare the length of the pattern, e.g. `foo/*` > `foo` vs `*` < ``.\n const aParts = a.pattern.split(\"/\");\n if (a.screen === \"index\") {\n aParts.push(\"index\");\n }\n\n const bParts = b.pattern.split(\"/\");\n if (b.screen === \"index\") {\n bParts.push(\"index\");\n }\n\n for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {\n // if b is longer, b get higher priority\n if (aParts[i] == null) {\n return 1;\n }\n // if a is longer, a get higher priority\n if (bParts[i] == null) {\n return -1;\n }\n const aWildCard = aParts[i] === \"*\";\n const bWildCard = bParts[i] === \"*\";\n // if both are wildcard we compare next component\n if (aWildCard && bWildCard) {\n continue;\n }\n // if only a is wild card, b get higher priority\n if (aWildCard) {\n return 1;\n }\n // if only b is wild card, a get higher priority\n if (bWildCard) {\n return -1;\n }\n\n const aSlug = aParts[i].startsWith(\":\");\n const bSlug = bParts[i].startsWith(\":\");\n // if both are wildcard we compare next component\n if (aSlug && bSlug) {\n continue;\n }\n // if only a is wild card, b get higher priority\n if (aSlug) {\n return 1;\n }\n // if only b is wild card, a get higher priority\n if (bSlug) {\n return -1;\n }\n }\n return bParts.length - aParts.length;\n });\n\n // Match full paths\n\n // Check for duplicate patterns in the config\n configs.reduce<Record<string, RouteConfig>>((acc, config) => {\n // NOTE(EvanBacon): Uses the regex pattern as key to detect duplicate slugs.\n const indexedKey = config.regex?.toString() ?? config.pattern;\n const alpha = acc[indexedKey];\n // NOTE(EvanBacon): Skips checking nodes that have children.\n if (alpha && !alpha.hasChildren && !config.hasChildren) {\n const a = alpha.routeNames;\n const b = config.routeNames;\n\n // It's not a problem if the path string omitted from a inner most screen\n // For example, it's ok if a path resolves to `A > B > C` or `A > B`\n const intersects =\n a.length > b.length\n ? b.every((it, i) => a[i] === it)\n : a.every((it, i) => b[i] === it);\n\n if (!intersects) {\n // NOTE(EvanBacon): Adds more context to the error message since we know about the\n // file system-based routing.\n const last = config.pattern.split(\"/\").pop();\n const routeType = last?.startsWith(\":\")\n ? \"dynamic route\"\n : last === \"*\"\n ? \"deep dynamic route\"\n : \"route\";\n throw new Error(\n `The ${routeType} pattern '${\n config.pattern || \"/\"\n }' resolves to both '${alpha.userReadableName}' and '${\n config.userReadableName\n }'. Patterns must be unique and cannot resolve to more than one route.`\n );\n }\n }\n\n return Object.assign(acc, {\n [indexedKey]: config,\n });\n }, {});\n\n if (remaining === \"/\") {\n // We need to add special handling of empty path so navigation to empty path also works\n // When handling empty path, we should only look at the root level config\n\n // NOTE(EvanBacon): We only care about matching leaf nodes.\n const leafNodes = configs.filter((config) => !config.hasChildren);\n\n const match =\n leafNodes.find(\n (config) =>\n // NOTE(EvanBacon): Test leaf node index routes that either don't have a regex or match an empty string.\n config.path === \"\" && (!config.regex || config.regex.test(\"\"))\n ) ??\n leafNodes.find(\n (config) =>\n // NOTE(EvanBacon): Test leaf node dynamic routes that match an empty string.\n config.path.startsWith(\":\") && config.regex!.test(\"\")\n ) ??\n // NOTE(EvanBacon): Test leaf node deep dynamic routes that match a slash.\n // This should be done last to enable dynamic routes having a higher priority.\n leafNodes.find(\n (config) => config.path === \"*\" && config.regex!.test(\"/\")\n );\n\n if (match) {\n return createNestedStateObject(\n path,\n match.routeNames.map((name) => ({ name })),\n initialRoutes,\n configs\n );\n }\n\n return undefined;\n }\n\n let result: PartialState<NavigationState> | undefined;\n let current: PartialState<NavigationState> | undefined;\n\n // We match the whole path against the regex instead of segments\n // This makes sure matches such as wildcard will catch any unmatched routes, even if nested\n const { routes, remainingPath } = matchAgainstConfigs(\n remaining,\n configs.map((c) => ({\n ...c,\n // Add `$` to the regex to make sure it matches till end of the path and not just beginning\n regex: c.regex ? new RegExp(c.regex.source + \"$\") : undefined,\n }))\n );\n\n if (routes !== undefined) {\n // This will always be empty if full path matched\n current = createNestedStateObject(path, routes, initialRoutes, configs);\n remaining = remainingPath;\n result = current;\n }\n\n if (current == null || result == null) {\n return undefined;\n }\n\n return result;\n}\n\nconst joinPaths = (...paths: string[]): string =>\n ([] as string[])\n .concat(...paths.map((p) => p.split(\"/\")))\n .filter(Boolean)\n .join(\"/\");\n\nconst matchAgainstConfigs = (remaining: string, configs: RouteConfig[]) => {\n let routes: ParsedRoute[] | undefined;\n let remainingPath = remaining;\n\n // Go through all configs, and see if the next path segment matches our regex\n for (const config of configs) {\n if (!config.regex) {\n continue;\n }\n\n const match = remainingPath.match(config.regex);\n\n // If our regex matches, we need to extract params from the path\n if (match) {\n // TODO: Add support for wildcard routes\n const matchedParams = config.pattern\n ?.split(\"/\")\n .filter((p) => p.startsWith(\":\"))\n .reduce<Record<string, any>>(\n (acc, p, i) =>\n Object.assign(acc, {\n // The param segments appear every second item starting from 2 in the regex match result\n [p]: match![(i + 1) * 2].replace(/\\//, \"\"),\n }),\n {}\n );\n\n routes = config.routeNames.map((name) => {\n const config = configs.find((c) => c.screen === name);\n const params = config?.path\n ?.split(\"/\")\n .filter((p) => p.startsWith(\":\"))\n .reduce<Record<string, any>>((acc, p) => {\n const paramName = p;\n const value = matchedParams[paramName];\n\n if (value) {\n const key = paramName.replace(/^:/, \"\").replace(/\\?$/, \"\");\n acc[key] = config.parse?.[key] ? config.parse[key](value) : value;\n }\n\n return acc;\n }, {});\n\n if (params && Object.keys(params).length) {\n return { name, params };\n }\n\n return { name };\n });\n\n // TODO(EvanBacon): Maybe we should warn / assert if multiple slugs use the same param name.\n const combinedParams = routes.reduce<Record<string, any>>(\n (acc, r) => Object.assign(acc, r.params),\n {}\n );\n\n // Combine all params so a route `[foo]/[bar]/other.js` has access to `{ foo, bar }`\n routes = routes.map((r) => ({\n ...r,\n params: combinedParams,\n }));\n\n remainingPath = remainingPath.replace(match[1], \"\");\n\n break;\n }\n }\n\n return { routes, remainingPath };\n};\n\nconst createNormalizedConfigs = (\n screen: string,\n routeConfig: PathConfigMap<object>,\n routeNames: string[] = [],\n initials: InitialRouteConfig[],\n parentScreens: string[],\n parentPattern?: string\n): RouteConfig[] => {\n const configs: RouteConfig[] = [];\n\n routeNames.push(screen);\n\n parentScreens.push(screen);\n\n const config = routeConfig[screen];\n\n if (typeof config === \"string\") {\n // If a string is specified as the value of the key(e.g. Foo: '/path'), use it as the pattern\n const pattern = parentPattern ? joinPaths(parentPattern, config) : config;\n\n configs.push(createConfigItem(screen, routeNames, pattern, config, false));\n } else if (typeof config === \"object\") {\n let pattern: string | undefined;\n\n // if an object is specified as the value (e.g. Foo: { ... }),\n // it can have `path` property and\n // it could have `screens` prop which has nested configs\n if (typeof config.path === \"string\") {\n if (config.exact && config.path === undefined) {\n throw new Error(\n \"A 'path' needs to be specified when specifying 'exact: true'. If you don't want this screen in the URL, specify it as empty string, e.g. `path: ''`.\"\n );\n }\n\n pattern =\n config.exact !== true\n ? joinPaths(parentPattern || \"\", config.path || \"\")\n : config.path || \"\";\n\n configs.push(\n createConfigItem(\n screen,\n routeNames,\n pattern!,\n config.path,\n config.screens ? !!Object.keys(config.screens)?.length : false,\n config.parse\n )\n );\n }\n\n if (config.screens) {\n // property `initialRouteName` without `screens` has no purpose\n if (config.initialRouteName) {\n initials.push({\n initialRouteName: config.initialRouteName,\n parentScreens,\n });\n }\n\n Object.keys(config.screens).forEach((nestedConfig) => {\n const result = createNormalizedConfigs(\n nestedConfig,\n config.screens as PathConfigMap<object>,\n routeNames,\n initials,\n [...parentScreens],\n pattern ?? parentPattern\n );\n\n configs.push(...result);\n });\n }\n }\n\n routeNames.pop();\n\n return configs;\n};\n\nconst createConfigItem = (\n screen: string,\n routeNames: string[],\n pattern: string,\n path: string,\n hasChildren?: boolean,\n parse?: ParseConfig\n): RouteConfig => {\n // Normalize pattern to remove any leading, trailing slashes, duplicate slashes etc.\n pattern = pattern.split(\"/\").filter(Boolean).join(\"/\");\n\n const regex = pattern\n ? new RegExp(\n `^(${pattern\n .split(\"/\")\n .map((it) => {\n if (it.startsWith(\":\")) {\n return `(([^/]+\\\\/)${it.endsWith(\"?\") ? \"?\" : \"\"})`;\n }\n\n return `${it === \"*\" ? \".*\" : escape(it)}\\\\/`;\n })\n .join(\"\")})`\n )\n : undefined;\n\n return {\n screen,\n regex,\n pattern,\n path,\n // The routeNames array is mutated, so copy it to keep the current state\n routeNames: [...routeNames],\n parse,\n userReadableName: [...routeNames.slice(0, -1), path || screen].join(\"/\"),\n hasChildren: !!hasChildren,\n };\n};\n\nconst findParseConfigForRoute = (\n routeName: string,\n flatConfig: RouteConfig[]\n): ParseConfig | undefined => {\n for (const config of flatConfig) {\n if (routeName === config.routeNames[config.routeNames.length - 1]) {\n return config.parse;\n }\n }\n\n return undefined;\n};\n\n// Try to find an initial route connected with the one passed\nconst findInitialRoute = (\n routeName: string,\n parentScreens: string[],\n initialRoutes: InitialRouteConfig[]\n): string | undefined => {\n for (const config of initialRoutes) {\n if (parentScreens.length === config.parentScreens.length) {\n let sameParents = true;\n for (let i = 0; i < parentScreens.length; i++) {\n if (parentScreens[i].localeCompare(config.parentScreens[i]) !== 0) {\n sameParents = false;\n break;\n }\n }\n if (sameParents) {\n return routeName !== config.initialRouteName\n ? config.initialRouteName\n : undefined;\n }\n }\n }\n return undefined;\n};\n\n// returns state object with values depending on whether\n// it is the end of state and if there is initialRoute for this level\nconst createStateObject = (\n initialRoute: string | undefined,\n route: ParsedRoute,\n isEmpty: boolean\n): InitialState => {\n if (isEmpty) {\n if (initialRoute) {\n return {\n index: 1,\n routes: [{ name: initialRoute }, route],\n };\n } else {\n return {\n routes: [route],\n };\n }\n } else {\n if (initialRoute) {\n return {\n index: 1,\n routes: [{ name: initialRoute }, { ...route, state: { routes: [] } }],\n };\n } else {\n return {\n routes: [{ ...route, state: { routes: [] } }],\n };\n }\n }\n};\n\nconst createNestedStateObject = (\n path: string,\n routes: ParsedRoute[],\n initialRoutes: InitialRouteConfig[],\n flatConfig?: RouteConfig[]\n) => {\n let state: InitialState;\n let route = routes.shift() as ParsedRoute;\n const parentScreens: string[] = [];\n\n let initialRoute = findInitialRoute(route.name, parentScreens, initialRoutes);\n\n parentScreens.push(route.name);\n\n state = createStateObject(initialRoute, route, routes.length === 0);\n\n if (routes.length > 0) {\n let nestedState = state;\n\n while ((route = routes.shift() as ParsedRoute)) {\n initialRoute = findInitialRoute(route.name, parentScreens, initialRoutes);\n\n const nestedStateIndex =\n nestedState.index || nestedState.routes.length - 1;\n\n nestedState.routes[nestedStateIndex].state = createStateObject(\n initialRoute,\n route,\n routes.length === 0\n );\n\n if (routes.length > 0) {\n nestedState = nestedState.routes[nestedStateIndex]\n .state as InitialState;\n }\n\n parentScreens.push(route.name);\n }\n }\n\n route = findFocusedRoute(state) as ParsedRoute;\n route.path = path;\n\n const params = parseQueryParams(\n path,\n flatConfig ? findParseConfigForRoute(route.name, flatConfig) : undefined\n );\n\n if (params) {\n route.params = { ...route.params, ...params };\n }\n\n return state;\n};\n\nconst parseQueryParams = (\n path: string,\n parseConfig?: Record<string, (value: string) => any>\n) => {\n const query = path.split(\"?\")[1];\n const params = queryString.parse(query);\n\n if (parseConfig) {\n Object.keys(params).forEach((name) => {\n if (\n Object.hasOwnProperty.call(parseConfig, name) &&\n typeof params[name] === \"string\"\n ) {\n params[name] = parseConfig[name](params[name] as string);\n }\n });\n }\n\n return Object.keys(params).length ? params : undefined;\n};\n"]}
@@ -1,4 +1,4 @@
1
- import React from 'react';
1
+ import React from "react";
2
2
  /**
3
3
  * @returns React Navigation screens for the route.
4
4
  */
@@ -1 +1 @@
1
- {"version":3,"file":"useScreens.d.ts","sourceRoot":"","sources":["../src/useScreens.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAM1B;;GAEG;AACH,wBAAgB,UAAU,IAAI,KAAK,CAAC,SAAS,EAAE,CAG9C;AAED,oBAAY,WAAW,CAAC,QAAQ,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI;IAClF,4DAA4D;IAC5D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC;IACvC,OAAO,CAAC,EAAE,QAAQ,CAAC;CACtB,CAAA;AAoCD;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC,SAAS,EAAE,CAKxE"}
1
+ {"version":3,"file":"useScreens.d.ts","sourceRoot":"","sources":["../src/useScreens.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAM1B;;GAEG;AACH,wBAAgB,UAAU,IAAI,KAAK,CAAC,SAAS,EAAE,CAM9C;AAED,oBAAY,WAAW,CACrB,QAAQ,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,IACxD;IACF,4DAA4D;IAC5D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC;IACvC,OAAO,CAAC,EAAE,QAAQ,CAAC;CACpB,CAAC;AA+CF;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC,SAAS,EAAE,CAOxE"}
@@ -1,7 +1,7 @@
1
- import React from 'react';
2
- import { Screen } from './primitives';
3
- import { Route, sortRoutes, useRoutes } from './Route';
4
- import { Try } from './views/Try';
1
+ import React from "react";
2
+ import { Screen } from "./primitives";
3
+ import { Route, sortRoutes, useRoutes } from "./Route";
4
+ import { Try } from "./views/Try";
5
5
  /**
6
6
  * @returns React Navigation screens for the route.
7
7
  */
@@ -14,7 +14,8 @@ function getSortedChildren(children, order) {
14
14
  return children.sort(sortRoutes).map((route) => ({ route, props: {} }));
15
15
  }
16
16
  const entries = [...children];
17
- const ordered = order.map(({ name, initialParams, options }) => {
17
+ const ordered = order
18
+ .map(({ name, initialParams, options }) => {
18
19
  if (!entries.length) {
19
20
  console.warn(`[Layout children]: Too many screens defined. Route "${name}" is extraneous.`);
20
21
  return null;
@@ -30,7 +31,8 @@ function getSortedChildren(children, order) {
30
31
  entries.splice(matchIndex, 1);
31
32
  return { route: match, props: { initialParams, options } };
32
33
  }
33
- }).filter(Boolean);
34
+ })
35
+ .filter(Boolean);
34
36
  // Add any remaining children
35
37
  ordered.push(...entries.sort(sortRoutes).map((route) => ({ route, props: {} })));
36
38
  return ordered;
@@ -60,7 +62,7 @@ function getQualifiedRouteComponent(value) {
60
62
  ref,
61
63
  });
62
64
  const errorBoundary = ErrorBoundary ? (React.createElement(Try, { catch: ErrorBoundary }, children)) : (children);
63
- return (React.createElement(Route, { filename: value.contextKey }, errorBoundary));
65
+ return React.createElement(Route, { filename: value.contextKey }, errorBoundary);
64
66
  });
65
67
  QualifiedRoute.displayName = `Route(${Component.displayName || Component.name || value.route})`;
66
68
  qualifiedStore.set(value, QualifiedRoute);
@@ -68,15 +70,17 @@ function getQualifiedRouteComponent(value) {
68
70
  }
69
71
  function routeToScreen(route, { options, ...props } = {}) {
70
72
  const staticOptions = route.getExtras()?.getNavOptions;
71
- return (
72
- // @ts-expect-error: fixme
73
- React.createElement(Screen, { ...props, name: route.route, key: route.route, options: options ? (args) => {
74
- const staticResult = typeof staticOptions === 'function' ? staticOptions(args) : staticOptions;
75
- const dynamicResult = typeof options === 'function' ? options?.(args) : options;
76
- return {
77
- ...staticResult,
78
- ...dynamicResult,
79
- };
80
- } : staticOptions, component: getQualifiedRouteComponent(route) }));
73
+ return (React.createElement(Screen, { ...props, name: route.route, key: route.route, options: options
74
+ ? (args) => {
75
+ const staticResult = typeof staticOptions === "function"
76
+ ? staticOptions(args)
77
+ : staticOptions;
78
+ const dynamicResult = typeof options === "function" ? options?.(args) : options;
79
+ return {
80
+ ...staticResult,
81
+ ...dynamicResult,
82
+ };
83
+ }
84
+ : staticOptions, getComponent: () => getQualifiedRouteComponent(route) }));
81
85
  }
82
86
  //# sourceMappingURL=useScreens.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useScreens.js","sourceRoot":"","sources":["../src/useScreens.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,KAAK,EAAa,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAElC;;GAEG;AAC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AAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;YAChF,OAAO;gBACH,GAAG,YAAY;gBACf,GAAG,aAAa;aACnB,CAAC;QACN,CAAC,CAAC,CAAC,CAAC,aAAa,EACjB,SAAS,EAAE,0BAA0B,CAAC,KAAK,CAAC,GAC9C,CACL,CAAC;AACN,CAAC","sourcesContent":["import React from 'react';\n\nimport { Screen } from './primitives';\nimport { Route, RouteNode, sortRoutes, useRoutes } from './Route';\nimport { Try } from './views/Try';\n\n/**\n * @returns React Navigation screens for the route.\n */\nexport function useScreens(): React.ReactNode[] {\n const children = useRoutes();\n return React.useMemo(() => children.map((value) => routeToScreen(value)), [children]);\n}\n\nexport type ScreenProps<TOptions extends Record<string, any> = Record<string, any>> = {\n /** Name is required when used inside a Layout component. */\n name?: string,\n initialParams?: { [key: string]: any };\n options?: TOptions;\n}\n\nfunction getSortedChildren(children: RouteNode[], order?: ScreenProps[]): { route: RouteNode, props: any }[] {\n if (!order?.length) {\n return children.sort(sortRoutes).map((route) => ({ route, props: {} }));\n }\n const entries = [...children];\n\n const ordered = order.map(({ name, initialParams, options }) => {\n if (!entries.length) {\n console.warn(`[Layout children]: Too many screens defined. Route \"${name}\" is extraneous.`);\n return null;\n }\n const matchIndex = entries.findIndex((child) => child.route === name)\n if (matchIndex === -1) {\n console.warn(`[Layout children]: No route named \"${name}\" exists in nested children:`, children.map(({ route }) => route));\n return null;\n } else {\n // Get match and remove from entries\n const match = entries[matchIndex];\n entries.splice(matchIndex, 1);\n\n return { route: match, props: { initialParams, options } }\n }\n }).filter(Boolean) as {\n route: RouteNode;\n props: Partial<ScreenProps>;\n }[]\n\n // Add any remaining children\n ordered.push(...entries.sort(sortRoutes).map((route) => ({ route, props: {} })));\n\n return ordered;\n}\n\n\n/** \n * @returns React Navigation screens sorted by the `route` property.\n */\nexport function useSortedScreens(order: ScreenProps[]): React.ReactNode[] {\n const children = useRoutes();\n const sorted = getSortedChildren(children, order);\n return React.useMemo(() =>\n sorted.map((value) => routeToScreen(value.route, value.props)), [sorted]);\n}\n\n\n// TODO: Maybe there's a more React-y way to do this?\n// Without this store, the process enters a recursive loop.\nconst qualifiedStore = new WeakMap<RouteNode, React.ComponentType<any>>();\n\n/** Wrap the component with various enhancements and add access to child routes. */\nfunction getQualifiedRouteComponent(value: RouteNode) {\n if (qualifiedStore.has(value)) {\n return qualifiedStore.get(value);\n }\n\n const Component = value.getComponent();\n\n const { ErrorBoundary } = value.getExtras();\n\n const QualifiedRoute = React.forwardRef(\n (props: { route: any; navigation: any }, ref: any) => {\n // Surface dynamic name as props to the view\n const children = React.createElement(Component, {\n ...props,\n ref,\n });\n\n const errorBoundary = ErrorBoundary ? (\n <Try catch={ErrorBoundary}>{children}</Try>\n ) : (\n children\n );\n\n return (\n <Route filename={value.contextKey}>\n {errorBoundary}\n </Route>\n );\n }\n );\n\n QualifiedRoute.displayName = `Route(${Component.displayName || Component.name || value.route})`;\n qualifiedStore.set(value, QualifiedRoute);\n return QualifiedRoute;\n}\n\nfunction routeToScreen(route: RouteNode, { options, ...props }: Partial<ScreenProps> = {}) {\n const staticOptions = route.getExtras()?.getNavOptions;\n return (\n // @ts-expect-error: fixme\n <Screen\n {...props}\n name={route.route}\n key={route.route}\n options={options ? (args) => {\n const staticResult = typeof staticOptions === 'function' ? staticOptions(args) : staticOptions;\n const dynamicResult = typeof options === 'function' ? options?.(args) : options;\n return {\n ...staticResult,\n ...dynamicResult,\n };\n } : staticOptions}\n component={getQualifiedRouteComponent(route)}\n />\n );\n}\n"]}
1
+ {"version":3,"file":"useScreens.js","sourceRoot":"","sources":["../src/useScreens.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,KAAK,EAAa,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAElC;;GAEG;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AAC;gBAC5D,OAAO;oBACL,GAAG,YAAY;oBACf,GAAG,aAAa;iBACjB,CAAC;YACJ,CAAC;YACH,CAAC,CAAC,aAAa,EAEnB,YAAY,EAAE,GAAG,EAAE,CAAC,0BAA0B,CAAC,KAAK,CAAC,GACrD,CACH,CAAC;AACJ,CAAC","sourcesContent":["import React from \"react\";\n\nimport { Screen } from \"./primitives\";\nimport { Route, RouteNode, sortRoutes, useRoutes } from \"./Route\";\nimport { Try } from \"./views/Try\";\n\n/**\n * @returns React Navigation screens for the route.\n */\nexport function useScreens(): React.ReactNode[] {\n const children = useRoutes();\n return React.useMemo(\n () => children.map((value) => routeToScreen(value)),\n [children]\n );\n}\n\nexport type ScreenProps<\n TOptions extends Record<string, any> = Record<string, any>\n> = {\n /** Name is required when used inside a Layout component. */\n name?: string;\n initialParams?: { [key: string]: any };\n options?: TOptions;\n};\n\nfunction getSortedChildren(\n children: RouteNode[],\n order?: ScreenProps[]\n): { route: RouteNode; props: any }[] {\n if (!order?.length) {\n return children.sort(sortRoutes).map((route) => ({ route, props: {} }));\n }\n const entries = [...children];\n\n const ordered = order\n .map(({ name, initialParams, options }) => {\n if (!entries.length) {\n console.warn(\n `[Layout children]: Too many screens defined. Route \"${name}\" is extraneous.`\n );\n return null;\n }\n const matchIndex = entries.findIndex((child) => child.route === name);\n if (matchIndex === -1) {\n console.warn(\n `[Layout children]: No route named \"${name}\" exists in nested children:`,\n children.map(({ route }) => route)\n );\n return null;\n } else {\n // Get match and remove from entries\n const match = entries[matchIndex];\n entries.splice(matchIndex, 1);\n\n return { route: match, props: { initialParams, options } };\n }\n })\n .filter(Boolean) as {\n route: RouteNode;\n props: Partial<ScreenProps>;\n }[];\n\n // Add any remaining children\n ordered.push(\n ...entries.sort(sortRoutes).map((route) => ({ route, props: {} }))\n );\n\n return ordered;\n}\n\n/**\n * @returns React Navigation screens sorted by the `route` property.\n */\nexport function useSortedScreens(order: ScreenProps[]): React.ReactNode[] {\n const children = useRoutes();\n const sorted = getSortedChildren(children, order);\n return React.useMemo(\n () => sorted.map((value) => routeToScreen(value.route, value.props)),\n [sorted]\n );\n}\n\n// TODO: Maybe there's a more React-y way to do this?\n// Without this store, the process enters a recursive loop.\nconst qualifiedStore = new WeakMap<RouteNode, React.ComponentType<any>>();\n\n/** Wrap the component with various enhancements and add access to child routes. */\nfunction getQualifiedRouteComponent(value: RouteNode) {\n if (qualifiedStore.has(value)) {\n return qualifiedStore.get(value)!;\n }\n\n const Component = value.getComponent();\n\n const { ErrorBoundary } = value.getExtras();\n\n const QualifiedRoute = React.forwardRef(\n (props: { route: any; navigation: any }, ref: any) => {\n // Surface dynamic name as props to the view\n const children = React.createElement(Component, {\n ...props,\n ref,\n });\n\n const errorBoundary = ErrorBoundary ? (\n <Try catch={ErrorBoundary}>{children}</Try>\n ) : (\n children\n );\n\n return <Route filename={value.contextKey}>{errorBoundary}</Route>;\n }\n );\n\n QualifiedRoute.displayName = `Route(${\n Component.displayName || Component.name || value.route\n })`;\n qualifiedStore.set(value, QualifiedRoute);\n return QualifiedRoute;\n}\n\nfunction routeToScreen(\n route: RouteNode,\n { options, ...props }: Partial<ScreenProps> = {}\n) {\n const staticOptions = route.getExtras()?.getNavOptions;\n return (\n <Screen\n {...props}\n name={route.route}\n key={route.route}\n options={\n options\n ? (args) => {\n const staticResult =\n typeof staticOptions === \"function\"\n ? staticOptions(args)\n : staticOptions;\n const dynamicResult =\n typeof options === \"function\" ? options?.(args) : options;\n return {\n ...staticResult,\n ...dynamicResult,\n };\n }\n : staticOptions\n }\n getComponent={() => getQualifiedRouteComponent(route)}\n />\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "expo-router",
3
- "version": "0.0.17",
3
+ "version": "0.0.19",
4
4
  "main": "build/index.js",
5
5
  "files": [
6
6
  "entry.js",