(treePage, englishTree, originalPath, modifiedPath)
| 3 | // This module recursively searches a given part of the site tree by iterating through child |
| 4 | // pages and finding a path that matches the original path provided. |
| 5 | export default function findPageInSiteTree(treePage, englishTree, originalPath, modifiedPath) { |
| 6 | if (Array.isArray(treePage)) throw new Error('received array instead of object') |
| 7 | |
| 8 | // If the tree page already matches the path, or if it has no child pages, return the page itself. |
| 9 | if (treePage.href === originalPath || !treePage.childPages) { |
| 10 | return treePage |
| 11 | } |
| 12 | |
| 13 | // If no modified path is provided, set it to the original path. |
| 14 | if (!modifiedPath) { |
| 15 | modifiedPath = originalPath |
| 16 | } |
| 17 | |
| 18 | // Find the index of the modified path in the array of child pages. |
| 19 | const foundIndex = treePage.childPages.findIndex(({ href }) => href === modifiedPath) |
| 20 | |
| 21 | // Use that index to find the child page that matches the path. |
| 22 | const foundPage = treePage.childPages[foundIndex] |
| 23 | |
| 24 | // If we found a page... |
| 25 | if (foundPage) { |
| 26 | return modifiedPath === originalPath |
| 27 | ? // Check if it matches the _original_ path, and return it if so. |
| 28 | foundPage |
| 29 | : // If we found a page with the modified path, keep going down the tree until we find the original path. |
| 30 | findPageInSiteTree(foundPage, englishTree, originalPath) |
| 31 | } |
| 32 | |
| 33 | // If no page was found at the path we tried, try again by removing the last segment of the path. |
| 34 | modifiedPath = modifiedPath.replace(/\/[^/]+?$/, '') |
| 35 | |
| 36 | // Error out or we'll just recurse forever until the stack size is exceeded. |
| 37 | if (!modifiedPath) { |
| 38 | const langCode = originalPath.match(getLanguageCode)[1] |
| 39 | |
| 40 | // Fall back to English if this is a localized path. |
| 41 | if (langCode === 'en') { |
| 42 | throw new Error(`can't find ${originalPath} in site tree`) |
| 43 | } else { |
| 44 | // This isn't ideal because it will serve up English content at a localized path, |
| 45 | // including links with `/en` in them. But it seems like the only way to not throw errors. |
| 46 | originalPath = originalPath.replace(`/${langCode}`, '/en') |
| 47 | return findPageInSiteTree(englishTree, englishTree, originalPath) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | // This will return a higher segment of the tree, so we can traverse down the tree until we find the original path. |
| 52 | return findPageInSiteTree(treePage, englishTree, originalPath, modifiedPath) |
| 53 | } |
no outgoing calls
no test coverage detected