@docusaurus/plugin-content-docs 2.0.0-beta.fc64c12e4 → 2.0.0

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 (236) 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 +57 -73
  5. package/lib/client/docsClientUtils.d.ts +9 -28
  6. package/lib/client/docsClientUtils.js +34 -43
  7. package/lib/client/index.d.ts +81 -0
  8. package/lib/client/index.js +67 -0
  9. package/lib/constants.d.ts +4 -0
  10. package/lib/constants.js +4 -1
  11. package/lib/docs.d.ts +33 -6
  12. package/lib/docs.js +201 -78
  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} +22 -3
  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 +120 -153
  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 +34 -26
  29. package/lib/props.d.ts +7 -2
  30. package/lib/props.js +84 -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 +25 -0
  35. package/lib/{sidebarItemsGenerator.d.ts → sidebars/generator.d.ts} +1 -7
  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 +59 -0
  41. package/lib/sidebars/postProcessor.d.ts +11 -0
  42. package/lib/sidebars/postProcessor.js +81 -0
  43. package/lib/sidebars/processor.d.ts +10 -0
  44. package/lib/sidebars/processor.js +79 -0
  45. package/lib/sidebars/types.d.ts +183 -0
  46. package/lib/{docFrontMatter.d.ts → sidebars/types.js} +2 -2
  47. package/lib/sidebars/utils.d.ts +55 -0
  48. package/lib/sidebars/utils.js +259 -0
  49. package/lib/sidebars/validation.d.ts +11 -0
  50. package/lib/sidebars/validation.js +143 -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 +100 -93
  57. package/lib/types.d.ts +13 -192
  58. package/lib/versions/files.d.ts +50 -0
  59. package/lib/versions/files.js +141 -0
  60. package/lib/versions/index.d.ts +36 -0
  61. package/lib/versions/index.js +154 -0
  62. package/lib/versions/validation.d.ts +17 -0
  63. package/lib/versions/validation.js +71 -0
  64. package/package.json +44 -30
  65. package/src/categoryGeneratedIndex.ts +60 -0
  66. package/src/cli.ts +88 -118
  67. package/src/client/docsClientUtils.ts +44 -71
  68. package/src/client/index.ts +158 -0
  69. package/src/constants.ts +4 -2
  70. package/src/docs.ts +277 -80
  71. package/src/frontMatter.ts +63 -0
  72. package/src/globalData.ts +57 -7
  73. package/src/index.ts +174 -221
  74. package/src/lastUpdate.ts +27 -38
  75. package/src/markdown/index.ts +10 -16
  76. package/src/markdown/linkify.ts +7 -4
  77. package/src/numberPrefix.ts +19 -26
  78. package/src/options.ts +38 -38
  79. package/src/plugin-content-docs.d.ts +570 -91
  80. package/src/props.ts +121 -20
  81. package/src/routes.ts +159 -0
  82. package/src/server-export.ts +26 -0
  83. package/src/sidebars/README.md +10 -0
  84. package/src/sidebars/generator.ts +292 -0
  85. package/src/sidebars/index.ts +118 -0
  86. package/src/sidebars/normalization.ts +91 -0
  87. package/src/sidebars/postProcessor.ts +112 -0
  88. package/src/sidebars/processor.ts +123 -0
  89. package/src/sidebars/types.ts +280 -0
  90. package/src/sidebars/utils.ts +393 -0
  91. package/src/sidebars/validation.ts +179 -0
  92. package/src/slug.ts +41 -22
  93. package/src/tags.ts +20 -0
  94. package/src/translations.ts +155 -124
  95. package/src/types.ts +17 -259
  96. package/src/versions/files.ts +216 -0
  97. package/src/versions/index.ts +246 -0
  98. package/src/versions/validation.ts +115 -0
  99. package/lib/.tsbuildinfo +0 -1
  100. package/lib/sidebarItemsGenerator.js +0 -215
  101. package/lib/sidebars.d.ts +0 -45
  102. package/lib/sidebars.js +0 -354
  103. package/lib/theme/hooks/useDocs.d.ts +0 -20
  104. package/lib/theme/hooks/useDocs.js +0 -75
  105. package/lib/versions.d.ts +0 -16
  106. package/lib/versions.js +0 -319
  107. package/src/__tests__/__fixtures__/bad-id-site/docs/invalid-id.md +0 -5
  108. package/src/__tests__/__fixtures__/bad-slug-on-doc-home-site/docs/docWithSlug.md +0 -5
  109. package/src/__tests__/__fixtures__/empty-site/docusaurus.config.js +0 -16
  110. package/src/__tests__/__fixtures__/empty-site/sidebars.json +0 -1
  111. package/src/__tests__/__fixtures__/sidebars/sidebars-category-shorthand.js +0 -34
  112. package/src/__tests__/__fixtures__/sidebars/sidebars-category-wrong-items.json +0 -11
  113. package/src/__tests__/__fixtures__/sidebars/sidebars-category-wrong-label.json +0 -11
  114. package/src/__tests__/__fixtures__/sidebars/sidebars-category.js +0 -44
  115. package/src/__tests__/__fixtures__/sidebars/sidebars-collapsed-first-level.json +0 -20
  116. package/src/__tests__/__fixtures__/sidebars/sidebars-collapsed.json +0 -21
  117. package/src/__tests__/__fixtures__/sidebars/sidebars-doc-id-not-string.json +0 -10
  118. package/src/__tests__/__fixtures__/sidebars/sidebars-link-wrong-href.json +0 -11
  119. package/src/__tests__/__fixtures__/sidebars/sidebars-link-wrong-label.json +0 -11
  120. package/src/__tests__/__fixtures__/sidebars/sidebars-link.json +0 -11
  121. package/src/__tests__/__fixtures__/sidebars/sidebars-unknown-type.json +0 -14
  122. package/src/__tests__/__fixtures__/sidebars/sidebars-wrong-field.json +0 -20
  123. package/src/__tests__/__fixtures__/sidebars/sidebars.json +0 -20
  124. package/src/__tests__/__fixtures__/simple-site/docs/_partials/somePartial.md +0 -3
  125. package/src/__tests__/__fixtures__/simple-site/docs/_partials/subfolder/somePartial.md +0 -3
  126. package/src/__tests__/__fixtures__/simple-site/docs/_somePartial.md +0 -3
  127. package/src/__tests__/__fixtures__/simple-site/docs/foo/bar.md +0 -69
  128. package/src/__tests__/__fixtures__/simple-site/docs/foo/baz.md +0 -70
  129. package/src/__tests__/__fixtures__/simple-site/docs/headingAsTitle.md +0 -1
  130. package/src/__tests__/__fixtures__/simple-site/docs/hello.md +0 -53
  131. package/src/__tests__/__fixtures__/simple-site/docs/ipsum.md +0 -5
  132. package/src/__tests__/__fixtures__/simple-site/docs/lorem.md +0 -6
  133. package/src/__tests__/__fixtures__/simple-site/docs/rootAbsoluteSlug.md +0 -5
  134. package/src/__tests__/__fixtures__/simple-site/docs/rootRelativeSlug.md +0 -5
  135. package/src/__tests__/__fixtures__/simple-site/docs/rootResolvedSlug.md +0 -5
  136. package/src/__tests__/__fixtures__/simple-site/docs/rootTryToEscapeSlug.md +0 -5
  137. package/src/__tests__/__fixtures__/simple-site/docs/slugs/absoluteSlug.md +0 -5
  138. package/src/__tests__/__fixtures__/simple-site/docs/slugs/relativeSlug.md +0 -5
  139. package/src/__tests__/__fixtures__/simple-site/docs/slugs/resolvedSlug.md +0 -5
  140. package/src/__tests__/__fixtures__/simple-site/docs/slugs/tryToEscapeSlug.md +0 -5
  141. package/src/__tests__/__fixtures__/simple-site/docusaurus.config.js +0 -14
  142. package/src/__tests__/__fixtures__/simple-site/sidebars.json +0 -23
  143. package/src/__tests__/__fixtures__/simple-site/wrong-sidebars.json +0 -7
  144. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/0-getting-started.md +0 -3
  145. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/1-installation.md +0 -3
  146. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/00_api-overview.md +0 -3
  147. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/01_Core APIs/0 --- Client API.md +0 -1
  148. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/01_Core APIs/1 --- Server API.md +0 -1
  149. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/02_Extension APIs/0. Plugin API.md +0 -1
  150. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/02_Extension APIs/1. Theme API.md +0 -1
  151. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/02_Extension APIs/_category_.yml +0 -1
  152. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/03_api-end.md +0 -3
  153. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/3-API/_category_.json +0 -3
  154. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/0-guide2.5.md +0 -8
  155. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/02-guide2.md +0 -7
  156. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/_category_.json +0 -3
  157. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/a-guide4.md +0 -7
  158. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/b-guide5.md +0 -7
  159. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/guide3.md +0 -8
  160. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/docs/Guides/z-guide1.md +0 -8
  161. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/partialAutogeneratedSidebars.js +0 -23
  162. package/src/__tests__/__fixtures__/site-with-autogenerated-sidebar/partialAutogeneratedSidebars2.js +0 -16
  163. package/src/__tests__/__fixtures__/site-with-doc-label/docs/hello-1.md +0 -7
  164. package/src/__tests__/__fixtures__/site-with-doc-label/docs/hello-2.md +0 -8
  165. package/src/__tests__/__fixtures__/site-with-doc-label/docusaurus.config.js +0 -14
  166. package/src/__tests__/__fixtures__/site-with-doc-label/sidebars.json +0 -14
  167. package/src/__tests__/__fixtures__/versioned-site/community/team.md +0 -1
  168. package/src/__tests__/__fixtures__/versioned-site/community_sidebars.json +0 -3
  169. package/src/__tests__/__fixtures__/versioned-site/community_versioned_docs/version-1.0.0/team.md +0 -1
  170. package/src/__tests__/__fixtures__/versioned-site/community_versioned_sidebars/version-1.0.0-sidebars.json +0 -3
  171. package/src/__tests__/__fixtures__/versioned-site/community_versions.json +0 -1
  172. package/src/__tests__/__fixtures__/versioned-site/docs/foo/bar.md +0 -4
  173. package/src/__tests__/__fixtures__/versioned-site/docs/hello.md +0 -1
  174. package/src/__tests__/__fixtures__/versioned-site/docs/slugs/absoluteSlug.md +0 -5
  175. package/src/__tests__/__fixtures__/versioned-site/docs/slugs/relativeSlug.md +0 -5
  176. package/src/__tests__/__fixtures__/versioned-site/docs/slugs/resolvedSlug.md +0 -5
  177. package/src/__tests__/__fixtures__/versioned-site/docs/slugs/tryToEscapeSlug.md +0 -5
  178. package/src/__tests__/__fixtures__/versioned-site/docusaurus.config.js +0 -18
  179. package/src/__tests__/__fixtures__/versioned-site/i18n/en/docusaurus-plugin-content-docs/version-1.0.0/hello.md +0 -1
  180. package/src/__tests__/__fixtures__/versioned-site/i18n/en/docusaurus-plugin-content-docs-community/current/team.md +0 -5
  181. package/src/__tests__/__fixtures__/versioned-site/i18n/fr/docusaurus-plugin-content-docs/version-1.0.0/hello.md +0 -1
  182. package/src/__tests__/__fixtures__/versioned-site/sidebars.json +0 -10
  183. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-1.0.0/foo/bar.md +0 -4
  184. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-1.0.0/foo/baz.md +0 -1
  185. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-1.0.0/hello.md +0 -1
  186. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-1.0.1/_partials/somePartial.md +0 -3
  187. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-1.0.1/_partials/subfolder/somePartial.md +0 -3
  188. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-1.0.1/_somePartial.md +0 -3
  189. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-1.0.1/foo/bar.md +0 -1
  190. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-1.0.1/hello.md +0 -1
  191. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/rootAbsoluteSlug.md +0 -5
  192. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/rootRelativeSlug.md +0 -5
  193. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/rootResolvedSlug.md +0 -5
  194. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/rootTryToEscapeSlug.md +0 -5
  195. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/slugs/absoluteSlug.md +0 -5
  196. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/slugs/relativeSlug.md +0 -5
  197. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/slugs/resolvedSlug.md +0 -5
  198. package/src/__tests__/__fixtures__/versioned-site/versioned_docs/version-withSlugs/slugs/tryToEscapeSlug.md +0 -5
  199. package/src/__tests__/__fixtures__/versioned-site/versioned_sidebars/version-1.0.0-sidebars.json +0 -11
  200. package/src/__tests__/__fixtures__/versioned-site/versioned_sidebars/version-1.0.1-sidebars.json +0 -10
  201. package/src/__tests__/__fixtures__/versioned-site/versioned_sidebars/version-withSlugs-sidebars.json +0 -5
  202. package/src/__tests__/__fixtures__/versioned-site/versions.json +0 -5
  203. package/src/__tests__/__snapshots__/cli.test.ts.snap +0 -95
  204. package/src/__tests__/__snapshots__/index.test.ts.snap +0 -1926
  205. package/src/__tests__/__snapshots__/sidebars.test.ts.snap +0 -233
  206. package/src/__tests__/__snapshots__/translations.test.ts.snap +0 -484
  207. package/src/__tests__/cli.test.ts +0 -337
  208. package/src/__tests__/docFrontMatter.test.ts +0 -244
  209. package/src/__tests__/docs.test.ts +0 -878
  210. package/src/__tests__/index.test.ts +0 -1885
  211. package/src/__tests__/lastUpdate.test.ts +0 -69
  212. package/src/__tests__/numberPrefix.test.ts +0 -199
  213. package/src/__tests__/options.test.ts +0 -272
  214. package/src/__tests__/sidebarItemsGenerator.test.ts +0 -358
  215. package/src/__tests__/sidebars.test.ts +0 -746
  216. package/src/__tests__/slug.test.ts +0 -109
  217. package/src/__tests__/translations.test.ts +0 -158
  218. package/src/__tests__/versions.test.ts +0 -741
  219. package/src/client/__tests__/docsClientUtils.test.ts +0 -371
  220. package/src/docFrontMatter.ts +0 -41
  221. package/src/markdown/__tests__/__fixtures__/docs/doc-localized.md +0 -1
  222. package/src/markdown/__tests__/__fixtures__/docs/doc1.md +0 -13
  223. package/src/markdown/__tests__/__fixtures__/docs/doc2.md +0 -12
  224. package/src/markdown/__tests__/__fixtures__/docs/doc4.md +0 -19
  225. package/src/markdown/__tests__/__fixtures__/docs/doc5.md +0 -6
  226. package/src/markdown/__tests__/__fixtures__/docs/subdir/doc3.md +0 -3
  227. package/src/markdown/__tests__/__fixtures__/versioned_docs/version-1.0.0/doc2.md +0 -7
  228. package/src/markdown/__tests__/__fixtures__/versioned_docs/version-1.0.0/subdir/doc1.md +0 -3
  229. package/src/markdown/__tests__/__snapshots__/linkify.test.ts.snap +0 -82
  230. package/src/markdown/__tests__/linkify.test.ts +0 -190
  231. package/src/sidebarItemsGenerator.ts +0 -315
  232. package/src/sidebars.ts +0 -589
  233. package/src/theme/hooks/useDocs.ts +0 -103
  234. package/src/versions.ts +0 -572
  235. package/tsconfig.json +0 -9
  236. package/types.d.ts +0 -13
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 _ from 'lodash';
9
+ import {createDocsByIdIndex} from './docs';
10
+ import type {VersionTag} from './types';
11
+ import type {
10
12
  SidebarItemDoc,
11
- SidebarItemLink,
12
13
  SidebarItem,
13
- } from './types';
14
- import {
14
+ SidebarItemCategory,
15
+ SidebarItemCategoryLink,
16
+ } from './sidebars/types';
17
+ import type {
15
18
  PropSidebars,
16
19
  PropVersionMetadata,
17
20
  PropSidebarItem,
18
- } from '@docusaurus/plugin-content-docs-types';
19
- import {keyBy, mapValues} from 'lodash';
21
+ PropSidebarItemCategory,
22
+ PropTagDocList,
23
+ PropTagDocListDoc,
24
+ PropSidebarItemLink,
25
+ PropVersionDocs,
26
+ DocMetadata,
27
+ LoadedVersion,
28
+ } from '@docusaurus/plugin-content-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,68 @@ 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
- label: sidebarLabel || item.label || title,
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 getCategoryLinkCustomProps(
77
+ link: SidebarItemCategoryLink | undefined,
78
+ ) {
79
+ switch (link?.type) {
80
+ case 'doc':
81
+ return getDocById(link.id).frontMatter.sidebar_custom_props;
82
+ default:
83
+ return undefined;
84
+ }
85
+ }
86
+
87
+ function convertCategory(item: SidebarItemCategory): PropSidebarItemCategory {
88
+ const {link, ...rest} = item;
89
+ const href = getCategoryLinkHref(link);
90
+ const customProps = item.customProps ?? getCategoryLinkCustomProps(link);
91
+
92
+ return {
93
+ ...rest,
94
+ items: item.items.map(normalizeItem),
95
+ ...(href && {href}),
96
+ ...(customProps && {customProps}),
97
+ };
98
+ }
99
+
100
+ function normalizeItem(item: SidebarItem): PropSidebarItem {
51
101
  switch (item.type) {
52
102
  case 'category':
53
- return {...item, items: item.items.map(normalizeItem)};
103
+ return convertCategory(item);
54
104
  case 'ref':
55
105
  case 'doc':
56
106
  return convertDocLink(item);
@@ -58,12 +108,28 @@ Available document ids are:
58
108
  default:
59
109
  return item;
60
110
  }
61
- };
111
+ }
62
112
 
63
113
  // Transform the sidebar so that all sidebar item will be in the
64
114
  // form of 'link' or 'category' only.
65
115
  // This is what will be passed as props to the UI component.
66
- return mapValues(loadedVersion.sidebars, (items) => items.map(normalizeItem));
116
+ return _.mapValues(loadedVersion.sidebars, (items) =>
117
+ items.map(normalizeItem),
118
+ );
119
+ }
120
+
121
+ function toVersionDocsProp(loadedVersion: LoadedVersion): PropVersionDocs {
122
+ return Object.fromEntries(
123
+ loadedVersion.docs.map((doc) => [
124
+ doc.unversionedId,
125
+ {
126
+ id: doc.unversionedId,
127
+ title: doc.title,
128
+ description: doc.description,
129
+ sidebar: doc.sidebar,
130
+ },
131
+ ]),
132
+ );
67
133
  }
68
134
 
69
135
  export function toVersionMetadataProp(
@@ -73,9 +139,44 @@ export function toVersionMetadataProp(
73
139
  return {
74
140
  pluginId,
75
141
  version: loadedVersion.versionName,
76
- label: loadedVersion.versionLabel,
77
- banner: loadedVersion.versionBanner,
142
+ label: loadedVersion.label,
143
+ banner: loadedVersion.banner,
144
+ badge: loadedVersion.badge,
145
+ className: loadedVersion.className,
78
146
  isLast: loadedVersion.isLast,
79
147
  docsSidebars: toSidebarsProp(loadedVersion),
148
+ docs: toVersionDocsProp(loadedVersion),
149
+ };
150
+ }
151
+
152
+ export function toTagDocListProp({
153
+ allTagsPath,
154
+ tag,
155
+ docs,
156
+ }: {
157
+ allTagsPath: string;
158
+ tag: VersionTag;
159
+ docs: DocMetadata[];
160
+ }): PropTagDocList {
161
+ function toDocListProp(): PropTagDocListDoc[] {
162
+ const list = _.compact(
163
+ tag.docIds.map((id) => docs.find((doc) => doc.id === id)),
164
+ );
165
+ // Sort docs by title
166
+ list.sort((doc1, doc2) => doc1.title.localeCompare(doc2.title));
167
+ return list.map((doc) => ({
168
+ id: doc.id,
169
+ title: doc.title,
170
+ description: doc.description,
171
+ permalink: doc.permalink,
172
+ }));
173
+ }
174
+
175
+ return {
176
+ label: tag.label,
177
+ permalink: tag.permalink,
178
+ allTagsPath,
179
+ count: tag.docIds.length,
180
+ items: toDocListProp(),
80
181
  };
81
182
  }
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 logger from '@docusaurus/logger';
9
+ import {docuHash, createSlugger} from '@docusaurus/utils';
10
+ import {toVersionMetadataProp} from './props';
11
+ import type {PluginContentLoadedActions, RouteConfig} from '@docusaurus/types';
12
+ import type {FullVersion} from './types';
13
+ import type {
14
+ CategoryGeneratedIndexMetadata,
15
+ DocMetadata,
16
+ } from '@docusaurus/plugin-content-docs';
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,26 @@
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
+ // Those are undocumented but used by some third-party plugins
10
+ // For this reason it's preferable to avoid doing breaking changes
11
+ // See also https://github.com/facebook/docusaurus/pull/6477
12
+
13
+ export {
14
+ CURRENT_VERSION_NAME,
15
+ VERSIONED_DOCS_DIR,
16
+ VERSIONED_SIDEBARS_DIR,
17
+ VERSIONS_JSON_FILE,
18
+ } from './constants';
19
+
20
+ export {
21
+ filterVersions,
22
+ getDefaultVersionBanner,
23
+ getVersionBadge,
24
+ getVersionBanner,
25
+ } from './versions';
26
+ export {readVersionNames} from './versions/files';
@@ -0,0 +1,10 @@
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
+ - **Important**: this step should only care about unwrapping autogenerated items, not filtering them, writing additional metadata, applying defaults, etc.—everything will be handled in the post-processor. Important because the generator is exposed to the end-user and we want it to be easy to be reasoned about.
10
+ 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 path from 'path';
9
+ import _ from 'lodash';
10
+ import logger from '@docusaurus/logger';
11
+ import {addTrailingSlash} from '@docusaurus/utils';
12
+ import {createDocsByIdIndex, toCategoryIndexMatcherParam} from '../docs';
13
+ import type {
14
+ SidebarItemDoc,
15
+ SidebarItemsGenerator,
16
+ SidebarItemsGeneratorDoc,
17
+ NormalizedSidebarItemCategory,
18
+ NormalizedSidebarItem,
19
+ SidebarItemCategoryLinkConfig,
20
+ } from './types';
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 = ({
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
+ };