Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

find-page-in-site-tree.js 2.3 KB

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

Press p or to see the previous file or, n or to see the next file

Comments

Loading...