sideBar.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { s3ContentsToTree } from "../utils/s3Helper";
  2. import _ from "lodash";
  3. const trimPrefix = (str, prefix, to) => {
  4. return str.replace(prefix, to);
  5. };
  6. const trimSuffix = (str) => {
  7. return str.replace(/.md$/, "");
  8. };
  9. const filterLocaleContents = (contents, prefix, sortMap) => {
  10. return contents!
  11. .filter((cont) => cont.Key!.startsWith(prefix) && cont.Key !== `${prefix}index.md`)
  12. .map((cont) => {
  13. return {
  14. ...cont,
  15. Key: trimSuffix(trimPrefix(cont.Key, prefix, "")),
  16. link: trimSuffix(`/${cont.Key}`),
  17. sortKey: trimPrefix(cont.Key, prefix, ""),
  18. };
  19. })
  20. .sort((a, b) => sortMap?.[a.sortKey] - sortMap?.[b.sortKey]);
  21. };
  22. const sideBarReducer = (r, label, i, a, Content) => {
  23. const extra = {
  24. collapsed: a.length !== i + 1,
  25. link: Content.link,
  26. };
  27. if (a.length === i + 1) {
  28. extra.items = undefined;
  29. } else {
  30. extra.link = undefined;
  31. }
  32. return extra;
  33. };
  34. export const buildSideBar = (contents, sideBarSortMap) => {
  35. const rootContents = filterLocaleContents(
  36. contents,
  37. "docs/",
  38. sideBarSortMap["zh-CN"]
  39. );
  40. const zhHKContents = filterLocaleContents(
  41. contents,
  42. "zh-HK/docs/",
  43. sideBarSortMap["zh-HK"]
  44. );
  45. const enUSContents = filterLocaleContents(
  46. contents,
  47. "en-US/docs/",
  48. sideBarSortMap["en-US"]
  49. );
  50. const rootSideBar = s3ContentsToTree(
  51. rootContents,
  52. { label: "text", children: "items" },
  53. sideBarReducer
  54. );
  55. const zhHKSideBar = s3ContentsToTree(
  56. zhHKContents,
  57. { label: "text", children: "items" },
  58. sideBarReducer
  59. );
  60. const enUSSideBar = s3ContentsToTree(
  61. enUSContents,
  62. { label: "text", children: "items" },
  63. sideBarReducer
  64. );
  65. return { rootSideBar, zhHKSideBar, enUSSideBar };
  66. };