@docusaurus/plugin-content-docs 2.0.0-beta.2 → 2.0.0-beta.20

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.
Files changed (229) hide show
  1. package/lib/categoryGeneratedIndex.d.ts +12 -0
  2. package/lib/categoryGeneratedIndex.js +37 -0
  3. package/lib/cli.d.ts +3 -2
  4. package/lib/cli.js +60 -69
  5. package/lib/client/docsClientUtils.d.ts +9 -28
  6. package/lib/client/docsClientUtils.js +33 -34
  7. package/lib/client/index.d.ts +22 -0
  8. package/lib/client/index.js +72 -0
  9. package/lib/constants.d.ts +4 -0
  10. package/lib/constants.js +4 -1
  11. package/lib/docs.d.ts +32 -3
  12. package/lib/docs.js +164 -63
  13. package/{src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docusaurus.config.js → lib/frontMatter.d.ts} +4 -8
  14. package/lib/{docFrontMatter.js → frontMatter.js} +13 -4
  15. package/lib/globalData.d.ts +3 -3
  16. package/lib/globalData.js +35 -6
  17. package/lib/index.d.ts +3 -3
  18. package/lib/index.js +122 -148
  19. package/lib/lastUpdate.d.ts +4 -6
  20. package/lib/lastUpdate.js +22 -26
  21. package/lib/markdown/index.d.ts +3 -6
  22. package/lib/markdown/index.js +3 -3
  23. package/lib/markdown/linkify.d.ts +1 -1
  24. package/lib/markdown/linkify.js +6 -3
  25. package/lib/numberPrefix.d.ts +1 -1
  26. package/lib/numberPrefix.js +16 -21
  27. package/lib/options.d.ts +3 -5
  28. package/lib/options.js +54 -13
  29. package/lib/props.d.ts +7 -2
  30. package/lib/props.js +69 -13
  31. package/lib/routes.d.ts +29 -0
  32. package/lib/routes.js +96 -0
  33. package/lib/server-export.d.ts +9 -0
  34. package/lib/server-export.js +22 -0
  35. package/lib/{sidebarItemsGenerator.d.ts → sidebars/generator.d.ts} +1 -6
  36. package/lib/sidebars/generator.js +209 -0
  37. package/lib/sidebars/index.d.ts +13 -0
  38. package/lib/sidebars/index.js +92 -0
  39. package/lib/sidebars/normalization.d.ts +13 -0
  40. package/lib/sidebars/normalization.js +55 -0
  41. package/lib/sidebars/postProcessor.d.ts +8 -0
  42. package/lib/sidebars/postProcessor.js +65 -0
  43. package/lib/sidebars/processor.d.ts +10 -0
  44. package/lib/sidebars/processor.js +90 -0
  45. package/lib/sidebars/types.d.ts +178 -0
  46. package/lib/{docFrontMatter.d.ts → sidebars/types.js} +2 -2
  47. package/lib/sidebars/utils.d.ts +54 -0
  48. package/lib/sidebars/utils.js +255 -0
  49. package/lib/sidebars/validation.d.ts +11 -0
  50. package/lib/sidebars/validation.js +138 -0
  51. package/lib/slug.d.ts +5 -4
  52. package/lib/slug.js +28 -18
  53. package/{src/__tests__/__fixtures__/sidebars/sidebars-first-level-not-category.js → lib/tags.d.ts} +3 -14
  54. package/lib/tags.js +21 -0
  55. package/lib/translations.d.ts +3 -3
  56. package/lib/translations.js +84 -94
  57. package/lib/types.d.ts +13 -184
  58. package/lib/versions/files.d.ts +44 -0
  59. package/lib/versions/files.js +142 -0
  60. package/lib/versions/index.d.ts +36 -0
  61. package/lib/versions/index.js +155 -0
  62. package/lib/versions/validation.d.ts +17 -0
  63. package/lib/versions/validation.js +71 -0
  64. package/package.json +32 -27
  65. package/src/categoryGeneratedIndex.ts +60 -0
  66. package/src/cli.ts +84 -109
  67. package/src/client/docsClientUtils.ts +43 -70
  68. package/src/client/index.ts +103 -0
  69. package/src/constants.ts +4 -2
  70. package/{types.d.ts → src/deps.d.ts} +1 -1
  71. package/src/docs.ts +228 -65
  72. package/src/{docFrontMatter.ts → frontMatter.ts} +21 -11
  73. package/src/globalData.ts +57 -7
  74. package/src/index.ts +169 -210
  75. package/src/lastUpdate.ts +26 -37
  76. package/src/markdown/index.ts +10 -16
  77. package/src/markdown/linkify.ts +7 -4
  78. package/src/numberPrefix.ts +19 -26
  79. package/src/options.ts +60 -18
  80. package/src/plugin-content-docs.d.ts +625 -89
  81. package/src/props.ts +102 -20
  82. package/src/routes.ts +159 -0
  83. package/src/server-export.ts +22 -0
  84. package/src/sidebars/README.md +9 -0
  85. package/src/sidebars/generator.ts +292 -0
  86. package/src/sidebars/index.ts +118 -0
  87. package/src/sidebars/normalization.ts +85 -0
  88. package/src/sidebars/postProcessor.ts +89 -0
  89. package/src/sidebars/processor.ts +139 -0
  90. package/src/sidebars/types.ts +275 -0
  91. package/src/sidebars/utils.ts +391 -0
  92. package/src/sidebars/validation.ts +174 -0
  93. package/src/slug.ts +41 -22
  94. package/src/tags.ts +20 -0
  95. package/src/translations.ts +124 -117
  96. package/src/types.ts +18 -247
  97. package/src/versions/files.ts +220 -0
  98. package/src/versions/index.ts +247 -0
  99. package/src/versions/validation.ts +113 -0
  100. package/lib/.tsbuildinfo +0 -1
  101. package/lib/sidebarItemsGenerator.js +0 -211
  102. package/lib/sidebars.d.ts +0 -43
  103. package/lib/sidebars.js +0 -320
  104. package/lib/theme/hooks/useDocs.d.ts +0 -20
  105. package/lib/theme/hooks/useDocs.js +0 -72
  106. package/lib/versions.d.ts +0 -16
  107. package/lib/versions.js +0 -319
  108. package/src/__tests__/__fixtures__/bad-id-site/docs/invalid-id.md +0 -5
  109. package/src/__tests__/__fixtures__/bad-slug-on-doc-home-site/docs/docWithSlug.md +0 -5
  110. package/src/__tests__/__fixtures__/empty-site/docusaurus.config.js +0 -16
  111. package/src/__tests__/__fixtures__/empty-site/sidebars.json +0 -1
  112. package/src/__tests__/__fixtures__/sidebars/sidebars-category-shorthand.js +0 -34
  113. package/src/__tests__/__fixtures__/sidebars/sidebars-category-wrong-items.json +0 -11
  114. package/src/__tests__/__fixtures__/sidebars/sidebars-category-wrong-label.json +0 -11
  115. package/src/__tests__/__fixtures__/sidebars/sidebars-category.js +0 -44
  116. package/src/__tests__/__fixtures__/sidebars/sidebars-collapsed-first-level.json +0 -20
  117. package/src/__tests__/__fixtures__/sidebars/sidebars-collapsed.json +0 -21
  118. package/src/__tests__/__fixtures__/sidebars/sidebars-doc-id-not-string.json +0 -10
  119. package/src/__tests__/__fixtures__/sidebars/sidebars-link-wrong-href.json +0 -11
  120. package/src/__tests__/__fixtures__/sidebars/sidebars-link-wrong-label.json +0 -11
  121. package/src/__tests__/__fixtures__/sidebars/sidebars-link.json +0 -11
  122. package/src/__tests__/__fixtures__/sidebars/sidebars-unknown-type.json +0 -14
  123. package/src/__tests__/__fixtures__/sidebars/sidebars-wrong-field.json +0 -20
  124. package/src/__tests__/__fixtures__/sidebars/sidebars.json +0 -20
  125. package/src/__tests__/__fixtures__/simple-site/docs/foo/bar.md +0 -69
  126. package/src/__tests__/__fixtures__/simple-site/docs/foo/baz.md +0 -70
  127. package/src/__tests__/__fixtures__/simple-site/docs/headingAsTitle.md +0 -1
  128. package/src/__tests__/__fixtures__/simple-site/docs/hello.md +0 -53
  129. package/src/__tests__/__fixtures__/simple-site/docs/ipsum.md +0 -5
  130. package/src/__tests__/__fixtures__/simple-site/docs/lorem.md +0 -6
  131. package/src/__tests__/__fixtures__/simple-site/docs/rootAbsoluteSlug.md +0 -5
  132. package/src/__tests__/__fixtures__/simple-site/docs/rootRelativeSlug.md +0 -5
  133. package/src/__tests__/__fixtures__/simple-site/docs/rootResolvedSlug.md +0 -5
  134. package/src/__tests__/__fixtures__/simple-site/docs/rootTryToEscapeSlug.md +0 -5
  135. package/src/__tests__/__fixtures__/simple-site/docs/slugs/absoluteSlug.md +0 -5
  136. package/src/__tests__/__fixtures__/simple-site/docs/slugs/relativeSlug.md +0 -5
  137. package/src/__tests__/__fixtures__/simple-site/docs/slugs/resolvedSlug.md +0 -5
  138. package/src/__tests__/__fixtures__/simple-site/docs/slugs/tryToEscapeSlug.md +0 -5
  139. package/src/__tests__/__fixtures__/simple-site/docusaurus.config.js +0 -14
  140. package/src/__tests__/__fixtures__/simple-site/sidebars.json +0 -23
  141. package/src/__tests__/__fixtures__/simple-site/wrong-sidebars.json +0 -7
  142. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/0-getting-started.md +0 -3
  143. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/1-installation.md +0 -3
  144. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/00_api-overview.md +0 -3
  145. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/01_Core APIs/0 --- Client API.md +0 -1
  146. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/01_Core APIs/1 --- Server API.md +0 -1
  147. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/02_Extension APIs/0. Plugin API.md +0 -1
  148. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/02_Extension APIs/1. Theme API.md +0 -1
  149. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/02_Extension APIs/_category_.yml +0 -1
  150. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/03_api-end.md +0 -3
  151. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/_category_.json +0 -3
  152. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/0-guide2.5.md +0 -8
  153. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/02-guide2.md +0 -7
  154. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/_category_.json +0 -3
  155. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/a-guide4.md +0 -7
  156. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/b-guide5.md +0 -7
  157. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/guide3.md +0 -8
  158. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/z-guide1.md +0 -8
  159. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/partialAutogeneratedSidebars.js +0 -23
  160. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/partialAutogeneratedSidebars2.js +0 -16
  161. package/src/__tests__/__fixtures__/site-with-doc-label/docs/hello-1.md +0 -7
  162. package/src/__tests__/__fixtures__/site-with-doc-label/docs/hello-2.md +0 -8
  163. package/src/__tests__/__fixtures__/site-with-doc-label/docusaurus.config.js +0 -14
  164. package/src/__tests__/__fixtures__/site-with-doc-label/sidebars.json +0 -14
  165. package/src/__tests__/__fixtures__/versioned-site/community/team.md +0 -1
  166. package/src/__tests__/__fixtures__/versioned-site/community_sidebars.json +0 -3
  167. package/src/__tests__/__fixtures__/versioned-site/community_versioned_docs/version-1.0.0/team.md +0 -1
  168. package/src/__tests__/__fixtures__/versioned-site/community_versioned_sidebars/version-1.0.0-sidebars.json +0 -3
  169. package/src/__tests__/__fixtures__/versioned-site/community_versions.json +0 -1
  170. package/src/__tests__/__fixtures__/versioned-site/docs/foo/bar.md +0 -4
  171. package/src/__tests__/__fixtures__/versioned-site/docs/hello.md +0 -1
  172. package/src/__tests__/__fixtures__/versioned-site/docs/slugs/absoluteSlug.md +0 -5
  173. package/src/__tests__/__fixtures__/versioned-site/docs/slugs/relativeSlug.md +0 -5
  174. package/src/__tests__/__fixtures__/versioned-site/docs/slugs/resolvedSlug.md +0 -5
  175. package/src/__tests__/__fixtures__/versioned-site/docs/slugs/tryToEscapeSlug.md +0 -5
  176. package/src/__tests__/__fixtures__/versioned-site/docusaurus.config.js +0 -18
  177. package/src/__tests__/__fixtures__/versioned-site/i18n/en/docusaurus-plugin-content-docs/version-1.0.0/hello.md +0 -1
  178. package/src/__tests__/__fixtures__/versioned-site/i18n/en/docusaurus-plugin-content-docs-community/current/team.md +0 -5
  179. package/src/__tests__/__fixtures__/versioned-site/i18n/fr/docusaurus-plugin-content-docs/version-1.0.0/hello.md +0 -1
  180. package/src/__tests__/__fixtures__/versioned-site/sidebars.json +0 -10
  181. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-1.0.0/foo/bar.md +0 -4
  182. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-1.0.0/foo/baz.md +0 -1
  183. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-1.0.0/hello.md +0 -1
  184. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-1.0.1/foo/bar.md +0 -1
  185. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-1.0.1/hello.md +0 -1
  186. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/rootAbsoluteSlug.md +0 -5
  187. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/rootRelativeSlug.md +0 -5
  188. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/rootResolvedSlug.md +0 -5
  189. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/rootTryToEscapeSlug.md +0 -5
  190. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/slugs/absoluteSlug.md +0 -5
  191. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/slugs/relativeSlug.md +0 -5
  192. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/slugs/resolvedSlug.md +0 -5
  193. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/slugs/tryToEscapeSlug.md +0 -5
  194. package/src/__tests__/__fixtures__/versioned-site/versioned_sidebars/version-1.0.0-sidebars.json +0 -11
  195. package/src/__tests__/__fixtures__/versioned-site/versioned_sidebars/version-1.0.1-sidebars.json +0 -10
  196. package/src/__tests__/__fixtures__/versioned-site/versioned_sidebars/version-withSlugs-sidebars.json +0 -5
  197. package/src/__tests__/__fixtures__/versioned-site/versions.json +0 -5
  198. package/src/__tests__/__snapshots__/cli.test.ts.snap +0 -90
  199. package/src/__tests__/__snapshots__/index.test.ts.snap +0 -1916
  200. package/src/__tests__/__snapshots__/sidebars.test.ts.snap +0 -218
  201. package/src/__tests__/__snapshots__/translations.test.ts.snap +0 -487
  202. package/src/__tests__/cli.test.ts +0 -333
  203. package/src/__tests__/docFrontMatter.test.ts +0 -244
  204. package/src/__tests__/docs.test.ts +0 -878
  205. package/src/__tests__/index.test.ts +0 -1871
  206. package/src/__tests__/lastUpdate.test.ts +0 -69
  207. package/src/__tests__/numberPrefix.test.ts +0 -199
  208. package/src/__tests__/options.test.ts +0 -231
  209. package/src/__tests__/sidebarItemsGenerator.test.ts +0 -336
  210. package/src/__tests__/sidebars.test.ts +0 -639
  211. package/src/__tests__/slug.test.ts +0 -109
  212. package/src/__tests__/translations.test.ts +0 -159
  213. package/src/__tests__/versions.test.ts +0 -741
  214. package/src/client/__tests__/docsClientUtils.test.ts +0 -371
  215. package/src/markdown/__tests__/__fixtures__/docs/doc-localized.md +0 -1
  216. package/src/markdown/__tests__/__fixtures__/docs/doc1.md +0 -13
  217. package/src/markdown/__tests__/__fixtures__/docs/doc2.md +0 -12
  218. package/src/markdown/__tests__/__fixtures__/docs/doc4.md +0 -19
  219. package/src/markdown/__tests__/__fixtures__/docs/doc5.md +0 -6
  220. package/src/markdown/__tests__/__fixtures__/docs/subdir/doc3.md +0 -3
  221. package/src/markdown/__tests__/__fixtures__/versioned_docs/version-1.0.0/doc2.md +0 -7
  222. package/src/markdown/__tests__/__fixtures__/versioned_docs/version-1.0.0/subdir/doc1.md +0 -3
  223. package/src/markdown/__tests__/__snapshots__/linkify.test.ts.snap +0 -82
  224. package/src/markdown/__tests__/linkify.test.ts +0 -190
  225. package/src/sidebarItemsGenerator.ts +0 -307
  226. package/src/sidebars.ts +0 -522
  227. package/src/theme/hooks/useDocs.ts +0 -99
  228. package/src/versions.ts +0 -572
  229. package/tsconfig.json +0 -9
package/src/props.ts CHANGED
@@ -5,26 +5,33 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- import {
9
- LoadedVersion,
8
+ import type {VersionTag} from './types';
9
+ import type {
10
10
  SidebarItemDoc,
11
- SidebarItemLink,
12
11
  SidebarItem,
13
- } from './types';
14
- import {
12
+ SidebarItemCategory,
13
+ SidebarItemCategoryLink,
14
+ } from './sidebars/types';
15
+ import type {
15
16
  PropSidebars,
16
17
  PropVersionMetadata,
17
18
  PropSidebarItem,
18
- } from '@docusaurus/plugin-content-docs-types';
19
- import {keyBy, mapValues} from 'lodash';
19
+ PropSidebarItemCategory,
20
+ PropTagDocList,
21
+ PropTagDocListDoc,
22
+ PropSidebarItemLink,
23
+ PropVersionDocs,
24
+ DocMetadata,
25
+ LoadedVersion,
26
+ } from '@docusaurus/plugin-content-docs';
27
+ import _ from 'lodash';
28
+ import {createDocsByIdIndex} from './docs';
20
29
 
21
30
  export function toSidebarsProp(loadedVersion: LoadedVersion): PropSidebars {
22
- const docsById = keyBy(loadedVersion.docs, (doc) => doc.id);
31
+ const docsById = createDocsByIdIndex(loadedVersion.docs);
23
32
 
24
- const convertDocLink = (item: SidebarItemDoc): SidebarItemLink => {
25
- const docId = item.id;
33
+ function getDocById(docId: string): DocMetadata {
26
34
  const docMetadata = docsById[docId];
27
-
28
35
  if (!docMetadata) {
29
36
  throw new Error(
30
37
  `Invalid sidebars file. The document with id "${docId}" was used in the sidebar, but no document with this id could be found.
@@ -32,25 +39,50 @@ Available document ids are:
32
39
  - ${Object.keys(docsById).sort().join('\n- ')}`,
33
40
  );
34
41
  }
42
+ return docMetadata;
43
+ }
35
44
 
45
+ const convertDocLink = (item: SidebarItemDoc): PropSidebarItemLink => {
46
+ const docMetadata = getDocById(item.id);
36
47
  const {
37
48
  title,
38
49
  permalink,
39
50
  frontMatter: {sidebar_label: sidebarLabel},
40
51
  } = docMetadata;
41
-
42
52
  return {
43
53
  type: 'link',
44
54
  label: sidebarLabel || item.label || title,
45
55
  href: permalink,
46
- customProps: item.customProps,
56
+ className: item.className,
57
+ customProps:
58
+ item.customProps ?? docMetadata.frontMatter.sidebar_custom_props,
59
+ docId: docMetadata.unversionedId,
47
60
  };
48
61
  };
49
62
 
50
- const normalizeItem = (item: SidebarItem): PropSidebarItem => {
63
+ function getCategoryLinkHref(
64
+ link: SidebarItemCategoryLink | undefined,
65
+ ): string | undefined {
66
+ switch (link?.type) {
67
+ case 'doc':
68
+ return getDocById(link.id).permalink;
69
+ case 'generated-index':
70
+ return link.permalink;
71
+ default:
72
+ return undefined;
73
+ }
74
+ }
75
+
76
+ function convertCategory(item: SidebarItemCategory): PropSidebarItemCategory {
77
+ const {link, ...rest} = item;
78
+ const href = getCategoryLinkHref(link);
79
+ return {...rest, items: item.items.map(normalizeItem), ...(href && {href})};
80
+ }
81
+
82
+ function normalizeItem(item: SidebarItem): PropSidebarItem {
51
83
  switch (item.type) {
52
84
  case 'category':
53
- return {...item, items: item.items.map(normalizeItem)};
85
+ return convertCategory(item);
54
86
  case 'ref':
55
87
  case 'doc':
56
88
  return convertDocLink(item);
@@ -58,12 +90,28 @@ Available document ids are:
58
90
  default:
59
91
  return item;
60
92
  }
61
- };
93
+ }
62
94
 
63
95
  // Transform the sidebar so that all sidebar item will be in the
64
96
  // form of 'link' or 'category' only.
65
97
  // This is what will be passed as props to the UI component.
66
- return mapValues(loadedVersion.sidebars, (items) => items.map(normalizeItem));
98
+ return _.mapValues(loadedVersion.sidebars, (items) =>
99
+ items.map(normalizeItem),
100
+ );
101
+ }
102
+
103
+ function toVersionDocsProp(loadedVersion: LoadedVersion): PropVersionDocs {
104
+ return Object.fromEntries(
105
+ loadedVersion.docs.map((doc) => [
106
+ doc.unversionedId,
107
+ {
108
+ id: doc.unversionedId,
109
+ title: doc.title,
110
+ description: doc.description,
111
+ sidebar: doc.sidebar,
112
+ },
113
+ ]),
114
+ );
67
115
  }
68
116
 
69
117
  export function toVersionMetadataProp(
@@ -73,10 +121,44 @@ export function toVersionMetadataProp(
73
121
  return {
74
122
  pluginId,
75
123
  version: loadedVersion.versionName,
76
- label: loadedVersion.versionLabel,
77
- banner: loadedVersion.versionBanner,
124
+ label: loadedVersion.label,
125
+ banner: loadedVersion.banner,
126
+ badge: loadedVersion.badge,
127
+ className: loadedVersion.className,
78
128
  isLast: loadedVersion.isLast,
79
129
  docsSidebars: toSidebarsProp(loadedVersion),
80
- permalinkToSidebar: loadedVersion.permalinkToSidebar,
130
+ docs: toVersionDocsProp(loadedVersion),
131
+ };
132
+ }
133
+
134
+ export function toTagDocListProp({
135
+ allTagsPath,
136
+ tag,
137
+ docs,
138
+ }: {
139
+ allTagsPath: string;
140
+ tag: VersionTag;
141
+ docs: DocMetadata[];
142
+ }): PropTagDocList {
143
+ function toDocListProp(): PropTagDocListDoc[] {
144
+ const list = _.compact(
145
+ tag.docIds.map((id) => docs.find((doc) => doc.id === id)),
146
+ );
147
+ // Sort docs by title
148
+ list.sort((doc1, doc2) => doc1.title.localeCompare(doc2.title));
149
+ return list.map((doc) => ({
150
+ id: doc.id,
151
+ title: doc.title,
152
+ description: doc.description,
153
+ permalink: doc.permalink,
154
+ }));
155
+ }
156
+
157
+ return {
158
+ label: tag.label,
159
+ permalink: tag.permalink,
160
+ allTagsPath,
161
+ count: tag.docIds.length,
162
+ items: toDocListProp(),
81
163
  };
82
164
  }
package/src/routes.ts ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import type {PluginContentLoadedActions, RouteConfig} from '@docusaurus/types';
9
+ import {docuHash, createSlugger} from '@docusaurus/utils';
10
+ import type {FullVersion} from './types';
11
+ import type {
12
+ CategoryGeneratedIndexMetadata,
13
+ DocMetadata,
14
+ } from '@docusaurus/plugin-content-docs';
15
+ import {toVersionMetadataProp} from './props';
16
+ import logger from '@docusaurus/logger';
17
+
18
+ export async function createCategoryGeneratedIndexRoutes({
19
+ version,
20
+ actions,
21
+ docCategoryGeneratedIndexComponent,
22
+ aliasedSource,
23
+ }: {
24
+ version: FullVersion;
25
+ actions: PluginContentLoadedActions;
26
+ docCategoryGeneratedIndexComponent: string;
27
+ aliasedSource: (str: string) => string;
28
+ }): Promise<RouteConfig[]> {
29
+ const slugs = createSlugger();
30
+
31
+ async function createCategoryGeneratedIndexRoute(
32
+ categoryGeneratedIndex: CategoryGeneratedIndexMetadata,
33
+ ): Promise<RouteConfig> {
34
+ const {sidebar, ...prop} = categoryGeneratedIndex;
35
+
36
+ const propFileName = slugs.slug(
37
+ `${version.path}-${categoryGeneratedIndex.sidebar}-category-${categoryGeneratedIndex.title}`,
38
+ );
39
+
40
+ const propData = await actions.createData(
41
+ `${docuHash(`category/${propFileName}`)}.json`,
42
+ JSON.stringify(prop, null, 2),
43
+ );
44
+
45
+ return {
46
+ path: categoryGeneratedIndex.permalink,
47
+ component: docCategoryGeneratedIndexComponent,
48
+ exact: true,
49
+ modules: {
50
+ categoryGeneratedIndex: aliasedSource(propData),
51
+ },
52
+ // Same as doc, this sidebar route attribute permits to associate this
53
+ // subpage to the given sidebar
54
+ ...(sidebar && {sidebar}),
55
+ };
56
+ }
57
+
58
+ return Promise.all(
59
+ version.categoryGeneratedIndices.map(createCategoryGeneratedIndexRoute),
60
+ );
61
+ }
62
+
63
+ export async function createDocRoutes({
64
+ docs,
65
+ actions,
66
+ docItemComponent,
67
+ }: {
68
+ docs: DocMetadata[];
69
+ actions: PluginContentLoadedActions;
70
+ docItemComponent: string;
71
+ }): Promise<RouteConfig[]> {
72
+ return Promise.all(
73
+ docs.map(async (metadataItem) => {
74
+ await actions.createData(
75
+ // Note that this created data path must be in sync with
76
+ // metadataPath provided to mdx-loader.
77
+ `${docuHash(metadataItem.source)}.json`,
78
+ JSON.stringify(metadataItem, null, 2),
79
+ );
80
+
81
+ const docRoute: RouteConfig = {
82
+ path: metadataItem.permalink,
83
+ component: docItemComponent,
84
+ exact: true,
85
+ modules: {
86
+ content: metadataItem.source,
87
+ },
88
+ // Because the parent (DocPage) comp need to access it easily
89
+ // This permits to render the sidebar once without unmount/remount when
90
+ // navigating (and preserve sidebar state)
91
+ ...(metadataItem.sidebar && {
92
+ sidebar: metadataItem.sidebar,
93
+ }),
94
+ };
95
+
96
+ return docRoute;
97
+ }),
98
+ );
99
+ }
100
+
101
+ export async function createVersionRoutes({
102
+ version,
103
+ actions,
104
+ docItemComponent,
105
+ docLayoutComponent,
106
+ docCategoryGeneratedIndexComponent,
107
+ pluginId,
108
+ aliasedSource,
109
+ }: {
110
+ version: FullVersion;
111
+ actions: PluginContentLoadedActions;
112
+ docLayoutComponent: string;
113
+ docItemComponent: string;
114
+ docCategoryGeneratedIndexComponent: string;
115
+ pluginId: string;
116
+ aliasedSource: (str: string) => string;
117
+ }): Promise<void> {
118
+ async function doCreateVersionRoutes(): Promise<void> {
119
+ const versionMetadata = toVersionMetadataProp(pluginId, version);
120
+ const versionMetadataPropPath = await actions.createData(
121
+ `${docuHash(`version-${version.versionName}-metadata-prop`)}.json`,
122
+ JSON.stringify(versionMetadata, null, 2),
123
+ );
124
+
125
+ async function createVersionSubRoutes() {
126
+ const [docRoutes, sidebarsRoutes] = await Promise.all([
127
+ createDocRoutes({docs: version.docs, actions, docItemComponent}),
128
+ createCategoryGeneratedIndexRoutes({
129
+ version,
130
+ actions,
131
+ docCategoryGeneratedIndexComponent,
132
+ aliasedSource,
133
+ }),
134
+ ]);
135
+
136
+ const routes = [...docRoutes, ...sidebarsRoutes];
137
+ return routes.sort((a, b) => a.path.localeCompare(b.path));
138
+ }
139
+
140
+ actions.addRoute({
141
+ path: version.path,
142
+ // Allow matching /docs/* since this is the wrapping route
143
+ exact: false,
144
+ component: docLayoutComponent,
145
+ routes: await createVersionSubRoutes(),
146
+ modules: {
147
+ versionMetadata: aliasedSource(versionMetadataPropPath),
148
+ },
149
+ priority: version.routePriority,
150
+ });
151
+ }
152
+
153
+ try {
154
+ return await doCreateVersionRoutes();
155
+ } catch (err) {
156
+ logger.error`Can't create version routes for version name=${version.versionName}`;
157
+ throw err;
158
+ }
159
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ // APIs available to Node.js
9
+ export {
10
+ CURRENT_VERSION_NAME,
11
+ VERSIONED_DOCS_DIR,
12
+ VERSIONED_SIDEBARS_DIR,
13
+ VERSIONS_JSON_FILE,
14
+ } from './constants';
15
+
16
+ export {
17
+ filterVersions,
18
+ getDefaultVersionBanner,
19
+ getVersionBadge,
20
+ getVersionBanner,
21
+ } from './versions';
22
+ export {readVersionNames} from './versions/files';
@@ -0,0 +1,9 @@
1
+ # Sidebars
2
+
3
+ This part is very complicated and hard to navigate. Sidebars are loaded through the following steps:
4
+
5
+ 1. **Loading**. The sidebars file is read. Returns `SidebarsConfig`.
6
+ 2. **Normalization**. The shorthands are expanded. This step is very lenient about the sidebars' shapes. Returns `NormalizedSidebars`.
7
+ 3. **Validation**. The normalized sidebars are validated. This step happens after normalization, because the normalized sidebars are easier to validate, and allows us to repeatedly validate & generate in the future.
8
+ 4. **Generation**. This step is done through the "processor" (naming is hard). The `autogenerated` items are unwrapped. In the future, steps 3 and 4 may be repeatedly done until all autogenerated items are unwrapped. Returns `ProcessedSidebars`.
9
+ 5. **Post-processing**. Defaults are applied (collapsed states), category links are resolved, empty categories are flattened. Returns `Sidebars`.
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import type {
9
+ SidebarItemDoc,
10
+ SidebarItemsGenerator,
11
+ SidebarItemsGeneratorDoc,
12
+ NormalizedSidebarItemCategory,
13
+ NormalizedSidebarItem,
14
+ SidebarItemCategoryLinkConfig,
15
+ } from './types';
16
+ import _ from 'lodash';
17
+ import {addTrailingSlash} from '@docusaurus/utils';
18
+ import logger from '@docusaurus/logger';
19
+ import path from 'path';
20
+ import {createDocsByIdIndex, toCategoryIndexMatcherParam} from '../docs';
21
+
22
+ const BreadcrumbSeparator = '/';
23
+
24
+ // Just an alias to the make code more explicit
25
+ function getLocalDocId(docId: string): string {
26
+ return _.last(docId.split('/'))!;
27
+ }
28
+
29
+ export const CategoryMetadataFilenameBase = '_category_';
30
+ export const CategoryMetadataFilenamePattern = '_category_.{json,yml,yaml}';
31
+
32
+ type WithPosition<T> = T & {
33
+ position?: number;
34
+ /** The source is the file/folder name */
35
+ source?: string;
36
+ };
37
+
38
+ /**
39
+ * A representation of the fs structure. For each object entry:
40
+ * If it's a folder, the key is the directory name, and value is the directory
41
+ * content; If it's a doc file, the key is the doc's source file name, and value
42
+ * is the doc ID
43
+ */
44
+ type Dir = {
45
+ [item: string]: Dir | string;
46
+ };
47
+
48
+ // Comment for this feature: https://github.com/facebook/docusaurus/issues/3464#issuecomment-818670449
49
+ export const DefaultSidebarItemsGenerator: SidebarItemsGenerator = async ({
50
+ numberPrefixParser,
51
+ isCategoryIndex,
52
+ docs: allDocs,
53
+ item: {dirName: autogenDir},
54
+ categoriesMetadata,
55
+ }) => {
56
+ const docsById = createDocsByIdIndex(allDocs);
57
+ const findDoc = (docId: string): SidebarItemsGeneratorDoc | undefined =>
58
+ docsById[docId];
59
+ const getDoc = (docId: string): SidebarItemsGeneratorDoc => {
60
+ const doc = findDoc(docId);
61
+ if (!doc) {
62
+ throw new Error(
63
+ `Can't find any doc with ID ${docId}.
64
+ Available doc IDs:
65
+ - ${Object.keys(docsById).join('\n- ')}`,
66
+ );
67
+ }
68
+ return doc;
69
+ };
70
+
71
+ /**
72
+ * Step 1. Extract the docs that are in the autogen dir.
73
+ */
74
+ function getAutogenDocs(): SidebarItemsGeneratorDoc[] {
75
+ function isInAutogeneratedDir(doc: SidebarItemsGeneratorDoc) {
76
+ return (
77
+ // Doc at the root of the autogenerated sidebar dir
78
+ doc.sourceDirName === autogenDir ||
79
+ // Autogen dir is . and doc is in subfolder
80
+ autogenDir === '.' ||
81
+ // Autogen dir is not . and doc is in subfolder
82
+ // "api/myDoc" startsWith "api/" (note "api2/myDoc" is not included)
83
+ doc.sourceDirName.startsWith(addTrailingSlash(autogenDir))
84
+ );
85
+ }
86
+ const docs = allDocs.filter(isInAutogeneratedDir);
87
+
88
+ if (docs.length === 0) {
89
+ logger.warn`No docs found in path=${autogenDir}: can't auto-generate a sidebar.`;
90
+ }
91
+ return docs;
92
+ }
93
+
94
+ /**
95
+ * Step 2. Turn the linear file list into a tree structure.
96
+ */
97
+ function treeify(docs: SidebarItemsGeneratorDoc[]): Dir {
98
+ // Get the category breadcrumb of a doc (relative to the dir of the
99
+ // autogenerated sidebar item)
100
+ // autogenDir=a/b and docDir=a/b/c/d => returns [c, d]
101
+ // autogenDir=a/b and docDir=a/b => returns []
102
+ // TODO: try to use path.relative()
103
+ function getRelativeBreadcrumb(doc: SidebarItemsGeneratorDoc): string[] {
104
+ return autogenDir === doc.sourceDirName
105
+ ? []
106
+ : doc.sourceDirName
107
+ .replace(addTrailingSlash(autogenDir), '')
108
+ .split(BreadcrumbSeparator);
109
+ }
110
+ const treeRoot: Dir = {};
111
+ docs.forEach((doc) => {
112
+ const breadcrumb = getRelativeBreadcrumb(doc);
113
+ // We walk down the file's path to generate the fs structure
114
+ let currentDir = treeRoot;
115
+ breadcrumb.forEach((dir) => {
116
+ if (typeof currentDir[dir] === 'undefined') {
117
+ currentDir[dir] = {}; // Create new folder.
118
+ }
119
+ currentDir = currentDir[dir] as Dir; // Go into the subdirectory.
120
+ });
121
+ // We've walked through the path. Register the file in this directory.
122
+ currentDir[path.basename(doc.source)] = doc.id;
123
+ });
124
+ return treeRoot;
125
+ }
126
+
127
+ /**
128
+ * Step 3. Recursively transform the tree-like structure to sidebar items.
129
+ * (From a record to an array of items, akin to normalizing shorthand)
130
+ */
131
+ function generateSidebar(
132
+ fsModel: Dir,
133
+ ): WithPosition<NormalizedSidebarItem>[] {
134
+ function createDocItem(
135
+ id: string,
136
+ fullPath: string,
137
+ fileName: string,
138
+ ): WithPosition<SidebarItemDoc> {
139
+ const {
140
+ sidebarPosition: position,
141
+ frontMatter: {sidebar_label: label, sidebar_class_name: className},
142
+ } = getDoc(id);
143
+ return {
144
+ type: 'doc',
145
+ id,
146
+ position,
147
+ source: fileName,
148
+ // We don't want these fields to magically appear in the generated
149
+ // sidebar
150
+ ...(label !== undefined && {label}),
151
+ ...(className !== undefined && {className}),
152
+ };
153
+ }
154
+ function createCategoryItem(
155
+ dir: Dir,
156
+ fullPath: string,
157
+ folderName: string,
158
+ ): WithPosition<NormalizedSidebarItemCategory> {
159
+ const categoryMetadata =
160
+ categoriesMetadata[path.posix.join(autogenDir, fullPath)];
161
+ const allItems = Object.entries(dir).map(([key, content]) =>
162
+ dirToItem(content, key, `${fullPath}/${key}`),
163
+ );
164
+
165
+ // Try to match a doc inside the category folder,
166
+ // using the "local id" (myDoc) or "qualified id" (dirName/myDoc)
167
+ function findDocByLocalId(localId: string): SidebarItemDoc | undefined {
168
+ return allItems.find(
169
+ (item): item is SidebarItemDoc =>
170
+ item.type === 'doc' && getLocalDocId(item.id) === localId,
171
+ );
172
+ }
173
+
174
+ function findConventionalCategoryDocLink(): SidebarItemDoc | undefined {
175
+ return allItems.find((item): item is SidebarItemDoc => {
176
+ if (item.type !== 'doc') {
177
+ return false;
178
+ }
179
+ const doc = getDoc(item.id);
180
+ return isCategoryIndex(toCategoryIndexMatcherParam(doc));
181
+ });
182
+ }
183
+
184
+ // In addition to the ID, this function also retrieves metadata of the
185
+ // linked doc that could be used as fallback values for category metadata
186
+ function getCategoryLinkedDocMetadata():
187
+ | {
188
+ id: string;
189
+ position?: number;
190
+ label?: string;
191
+ customProps?: {[key: string]: unknown};
192
+ className?: string;
193
+ }
194
+ | undefined {
195
+ const link = categoryMetadata?.link;
196
+ if (link !== undefined && link?.type !== 'doc') {
197
+ // If a link is explicitly specified, we won't apply conventions
198
+ return undefined;
199
+ }
200
+ const id = link
201
+ ? findDocByLocalId(link.id)?.id ?? getDoc(link.id).id
202
+ : findConventionalCategoryDocLink()?.id;
203
+ if (!id) {
204
+ return undefined;
205
+ }
206
+ const doc = getDoc(id);
207
+ return {
208
+ id,
209
+ position: doc.sidebarPosition,
210
+ label: doc.frontMatter.sidebar_label ?? doc.title,
211
+ customProps: doc.frontMatter.sidebar_custom_props,
212
+ className: doc.frontMatter.sidebar_class_name,
213
+ };
214
+ }
215
+ const categoryLinkedDoc = getCategoryLinkedDocMetadata();
216
+ const link: SidebarItemCategoryLinkConfig | null | undefined =
217
+ categoryLinkedDoc
218
+ ? {
219
+ type: 'doc',
220
+ id: categoryLinkedDoc.id, // We "remap" a potentially "local id" to a "qualified id"
221
+ }
222
+ : categoryMetadata?.link;
223
+ // If a doc is linked, remove it from the category subItems
224
+ const items = allItems.filter(
225
+ (item) => !(item.type === 'doc' && item.id === categoryLinkedDoc?.id),
226
+ );
227
+
228
+ const className =
229
+ categoryMetadata?.className ?? categoryLinkedDoc?.className;
230
+ const customProps =
231
+ categoryMetadata?.customProps ?? categoryLinkedDoc?.customProps;
232
+ const {filename, numberPrefix} = numberPrefixParser(folderName);
233
+
234
+ return {
235
+ type: 'category',
236
+ label: categoryMetadata?.label ?? categoryLinkedDoc?.label ?? filename,
237
+ collapsible: categoryMetadata?.collapsible,
238
+ collapsed: categoryMetadata?.collapsed,
239
+ position:
240
+ categoryMetadata?.position ??
241
+ categoryLinkedDoc?.position ??
242
+ numberPrefix,
243
+ source: folderName,
244
+ ...(customProps !== undefined && {customProps}),
245
+ ...(className !== undefined && {className}),
246
+ items,
247
+ ...(link && {link}),
248
+ };
249
+ }
250
+ function dirToItem(
251
+ dir: Dir | string, // The directory item to be transformed.
252
+ itemKey: string, // File/folder name; for categories, it's used to generate the next `relativePath`.
253
+ fullPath: string, // `dir`'s full path relative to the autogen dir.
254
+ ): WithPosition<NormalizedSidebarItem> {
255
+ return typeof dir === 'object'
256
+ ? createCategoryItem(dir, fullPath, itemKey)
257
+ : createDocItem(dir, fullPath, itemKey);
258
+ }
259
+ return Object.entries(fsModel).map(([key, content]) =>
260
+ dirToItem(content, key, key),
261
+ );
262
+ }
263
+
264
+ /**
265
+ * Step 4. Recursively sort the categories/docs + remove the "position"
266
+ * attribute from final output. Note: the "position" is only used to sort
267
+ * "inside" a sidebar slice. It is not used to sort across multiple
268
+ * consecutive sidebar slices (i.e. a whole category composed of multiple
269
+ * autogenerated items)
270
+ */
271
+ function sortItems(
272
+ sidebarItems: WithPosition<NormalizedSidebarItem>[],
273
+ ): NormalizedSidebarItem[] {
274
+ const processedSidebarItems = sidebarItems.map((item) => {
275
+ if (item.type === 'category') {
276
+ return {...item, items: sortItems(item.items)};
277
+ }
278
+ return item;
279
+ });
280
+ const sortedSidebarItems = _.sortBy(processedSidebarItems, [
281
+ 'position',
282
+ 'source',
283
+ ]);
284
+ return sortedSidebarItems.map(({position, source, ...item}) => item);
285
+ }
286
+ // TODO: the whole code is designed for pipeline operator
287
+ const docs = getAutogenDocs();
288
+ const fsModel = treeify(docs);
289
+ const sidebarWithPosition = generateSidebar(fsModel);
290
+ const sortedSidebar = sortItems(sidebarWithPosition);
291
+ return sortedSidebar;
292
+ };