@azerion/bunosaurus-plugin-content-docs 0.0.0-stage → 4.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 (119) hide show
  1. package/README.md +6 -2
  2. package/lib/categoryGeneratedIndex.d.ts +12 -0
  3. package/lib/categoryGeneratedIndex.js +36 -0
  4. package/lib/cli.d.ts +13 -0
  5. package/lib/cli.js +124 -0
  6. package/lib/client/doc.d.ts +29 -0
  7. package/lib/client/doc.js +47 -0
  8. package/lib/client/docSidebarItemsExpandedState.d.ts +30 -0
  9. package/lib/client/docSidebarItemsExpandedState.js +27 -0
  10. package/lib/client/docsClientUtils.d.ts +15 -0
  11. package/lib/client/docsClientUtils.js +86 -0
  12. package/lib/client/docsPreferredVersion.d.ts +29 -0
  13. package/lib/client/docsPreferredVersion.js +124 -0
  14. package/lib/client/docsSearch.d.ts +19 -0
  15. package/lib/client/docsSearch.js +39 -0
  16. package/lib/client/docsSidebar.d.ts +25 -0
  17. package/lib/client/docsSidebar.js +29 -0
  18. package/lib/client/docsUtils.d.ts +112 -0
  19. package/lib/client/docsUtils.js +299 -0
  20. package/lib/client/docsVersion.d.ts +19 -0
  21. package/lib/client/docsVersion.js +25 -0
  22. package/lib/client/index.d.ts +91 -0
  23. package/lib/client/index.js +83 -0
  24. package/lib/client/structuredDataUtils.d.ts +11 -0
  25. package/lib/client/structuredDataUtils.js +35 -0
  26. package/lib/constants.d.ts +14 -0
  27. package/lib/constants.js +17 -0
  28. package/lib/contentHelpers.d.ts +12 -0
  29. package/lib/contentHelpers.js +31 -0
  30. package/lib/docs.d.ts +48 -0
  31. package/lib/docs.js +252 -0
  32. package/lib/frontMatter.d.ts +10 -0
  33. package/lib/frontMatter.js +46 -0
  34. package/lib/globalData.d.ts +9 -0
  35. package/lib/globalData.js +59 -0
  36. package/lib/index.d.ts +10 -0
  37. package/lib/index.js +198 -0
  38. package/lib/numberPrefix.d.ts +11 -0
  39. package/lib/numberPrefix.js +50 -0
  40. package/lib/options.d.ts +10 -0
  41. package/lib/options.js +138 -0
  42. package/lib/props.d.ts +21 -0
  43. package/lib/props.js +156 -0
  44. package/lib/routes.d.ts +22 -0
  45. package/lib/routes.js +184 -0
  46. package/lib/server-export.d.ts +9 -0
  47. package/lib/server-export.js +25 -0
  48. package/lib/sidebars/generator.d.ts +10 -0
  49. package/lib/sidebars/generator.js +217 -0
  50. package/lib/sidebars/index.d.ts +13 -0
  51. package/lib/sidebars/index.js +99 -0
  52. package/lib/sidebars/normalization.d.ts +13 -0
  53. package/lib/sidebars/normalization.js +58 -0
  54. package/lib/sidebars/postProcessor.d.ts +11 -0
  55. package/lib/sidebars/postProcessor.js +82 -0
  56. package/lib/sidebars/processor.d.ts +10 -0
  57. package/lib/sidebars/processor.js +77 -0
  58. package/lib/sidebars/types.d.ts +192 -0
  59. package/lib/sidebars/types.js +8 -0
  60. package/lib/sidebars/utils.d.ts +69 -0
  61. package/lib/sidebars/utils.js +327 -0
  62. package/lib/sidebars/validation.d.ts +11 -0
  63. package/lib/sidebars/validation.js +152 -0
  64. package/lib/slug.d.ts +15 -0
  65. package/lib/slug.js +51 -0
  66. package/lib/translations.d.ts +10 -0
  67. package/lib/translations.js +243 -0
  68. package/lib/types.d.ts +27 -0
  69. package/lib/types.js +8 -0
  70. package/lib/versions/files.d.ts +54 -0
  71. package/lib/versions/files.js +152 -0
  72. package/lib/versions/loadVersion.d.ts +17 -0
  73. package/lib/versions/loadVersion.js +126 -0
  74. package/lib/versions/validation.d.ts +17 -0
  75. package/lib/versions/validation.js +70 -0
  76. package/lib/versions/version.d.ts +40 -0
  77. package/lib/versions/version.js +189 -0
  78. package/package.json +70 -4
  79. package/src/categoryGeneratedIndex.ts +60 -0
  80. package/src/cli.ts +180 -0
  81. package/src/client/doc.tsx +71 -0
  82. package/src/client/docSidebarItemsExpandedState.tsx +55 -0
  83. package/src/client/docsClientUtils.ts +140 -0
  84. package/src/client/docsPreferredVersion.tsx +245 -0
  85. package/src/client/docsSearch.test.ts +15 -0
  86. package/src/client/docsSearch.ts +57 -0
  87. package/src/client/docsSidebar.tsx +50 -0
  88. package/src/client/docsUtils.tsx +442 -0
  89. package/src/client/docsVersion.tsx +36 -0
  90. package/src/client/index.ts +211 -0
  91. package/src/client/structuredDataUtils.ts +54 -0
  92. package/src/constants.ts +15 -0
  93. package/src/contentHelpers.ts +34 -0
  94. package/src/docs.ts +402 -0
  95. package/src/frontMatter.ts +57 -0
  96. package/src/globalData.ts +79 -0
  97. package/src/index.ts +289 -0
  98. package/src/numberPrefix.ts +62 -0
  99. package/src/options.ts +185 -0
  100. package/src/plugin-content-docs.d.ts +667 -0
  101. package/src/props.ts +223 -0
  102. package/src/routes.ts +263 -0
  103. package/src/server-export.ts +26 -0
  104. package/src/sidebars/README.md +10 -0
  105. package/src/sidebars/generator.ts +307 -0
  106. package/src/sidebars/index.ts +130 -0
  107. package/src/sidebars/normalization.ts +91 -0
  108. package/src/sidebars/postProcessor.ts +115 -0
  109. package/src/sidebars/processor.ts +122 -0
  110. package/src/sidebars/types.ts +293 -0
  111. package/src/sidebars/utils.ts +529 -0
  112. package/src/sidebars/validation.ts +189 -0
  113. package/src/slug.ts +79 -0
  114. package/src/translations.ts +365 -0
  115. package/src/types.ts +34 -0
  116. package/src/versions/files.ts +240 -0
  117. package/src/versions/loadVersion.ts +185 -0
  118. package/src/versions/validation.ts +115 -0
  119. package/src/versions/version.ts +300 -0
@@ -0,0 +1,307 @@
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 'node:path';
9
+ import _ from 'lodash';
10
+ import logger from '@docusaurus/logger';
11
+ import {addTrailingSlash} from '@docusaurus/utils-common';
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: {
142
+ sidebar_key: key,
143
+ sidebar_label: label,
144
+ sidebar_class_name: className,
145
+ sidebar_custom_props: customProps,
146
+ },
147
+ } = getDoc(id);
148
+ return {
149
+ type: 'doc',
150
+ id,
151
+ position,
152
+ source: fileName,
153
+ // We don't want these fields to magically appear in the generated
154
+ // sidebar
155
+ ...(key !== undefined && {key}),
156
+ ...(label !== undefined && {label}),
157
+ ...(className !== undefined && {className}),
158
+ ...(customProps !== undefined && {customProps}),
159
+ };
160
+ }
161
+ function createCategoryItem(
162
+ dir: Dir,
163
+ fullPath: string,
164
+ folderName: string,
165
+ ): WithPosition<NormalizedSidebarItemCategory> {
166
+ const categoryMetadata =
167
+ categoriesMetadata[path.posix.join(autogenDir, fullPath)];
168
+ const allItems = Object.entries(dir).map(([key, content]) =>
169
+ dirToItem(content, key, `${fullPath}/${key}`),
170
+ );
171
+
172
+ // Try to match a doc inside the category folder,
173
+ // using the "local id" (myDoc) or "qualified id" (dirName/myDoc)
174
+ function findDocByLocalId(localId: string): SidebarItemDoc | undefined {
175
+ return allItems.find(
176
+ (item): item is SidebarItemDoc =>
177
+ item.type === 'doc' && getLocalDocId(item.id) === localId,
178
+ );
179
+ }
180
+
181
+ function findConventionalCategoryDocLink(): SidebarItemDoc | undefined {
182
+ return allItems.find((item): item is SidebarItemDoc => {
183
+ if (item.type !== 'doc') {
184
+ return false;
185
+ }
186
+ const doc = getDoc(item.id);
187
+ return isCategoryIndex(toCategoryIndexMatcherParam(doc));
188
+ });
189
+ }
190
+
191
+ // In addition to the ID, this function also retrieves metadata of the
192
+ // linked doc that could be used as fallback values for category metadata
193
+ function getCategoryLinkedDocMetadata():
194
+ | {
195
+ id: string;
196
+ key?: string;
197
+ position?: number;
198
+ label?: string;
199
+ customProps?: {[key: string]: unknown};
200
+ className?: string;
201
+ }
202
+ | undefined {
203
+ const link = categoryMetadata?.link;
204
+ if (link !== undefined && link?.type !== 'doc') {
205
+ // If a link is explicitly specified, we won't apply conventions
206
+ return undefined;
207
+ }
208
+ const id = link
209
+ ? (findDocByLocalId(link.id)?.id ?? getDoc(link.id).id)
210
+ : findConventionalCategoryDocLink()?.id;
211
+ if (!id) {
212
+ return undefined;
213
+ }
214
+ const doc = getDoc(id);
215
+ return {
216
+ id,
217
+ position: doc.sidebarPosition,
218
+ key: doc.frontMatter.sidebar_key,
219
+ label: doc.frontMatter.sidebar_label ?? doc.title,
220
+ customProps: doc.frontMatter.sidebar_custom_props,
221
+ className: doc.frontMatter.sidebar_class_name,
222
+ };
223
+ }
224
+ const categoryLinkedDoc = getCategoryLinkedDocMetadata();
225
+ const link: SidebarItemCategoryLinkConfig | null | undefined =
226
+ categoryLinkedDoc
227
+ ? {
228
+ type: 'doc',
229
+ id: categoryLinkedDoc.id, // We "remap" a potentially "local id" to a "qualified id"
230
+ }
231
+ : categoryMetadata?.link;
232
+ // If a doc is linked, remove it from the category subItems
233
+ const items = allItems.filter(
234
+ (item) => !(item.type === 'doc' && item.id === categoryLinkedDoc?.id),
235
+ );
236
+
237
+ const className =
238
+ categoryMetadata?.className ?? categoryLinkedDoc?.className;
239
+ const customProps =
240
+ categoryMetadata?.customProps ?? categoryLinkedDoc?.customProps;
241
+ const {filename, numberPrefix} = numberPrefixParser(folderName);
242
+
243
+ const key = categoryMetadata?.key ?? categoryLinkedDoc?.key;
244
+
245
+ return {
246
+ type: 'category',
247
+ label: categoryMetadata?.label ?? categoryLinkedDoc?.label ?? filename,
248
+ collapsible: categoryMetadata?.collapsible,
249
+ collapsed: categoryMetadata?.collapsed,
250
+ position:
251
+ categoryMetadata?.position ??
252
+ categoryLinkedDoc?.position ??
253
+ numberPrefix,
254
+ source: folderName,
255
+ ...(customProps !== undefined && {customProps}),
256
+ ...(className !== undefined && {className}),
257
+ items,
258
+ ...(categoryMetadata?.description && {
259
+ description: categoryMetadata?.description,
260
+ }),
261
+ ...(key && {key}),
262
+ ...(link && {link}),
263
+ };
264
+ }
265
+ function dirToItem(
266
+ dir: Dir | string, // The directory item to be transformed.
267
+ itemKey: string, // File/folder name; for categories, it's used to generate the next `relativePath`.
268
+ fullPath: string, // `dir`'s full path relative to the autogen dir.
269
+ ): WithPosition<NormalizedSidebarItem> {
270
+ return typeof dir === 'object'
271
+ ? createCategoryItem(dir, fullPath, itemKey)
272
+ : createDocItem(dir, fullPath, itemKey);
273
+ }
274
+ return Object.entries(fsModel).map(([key, content]) =>
275
+ dirToItem(content, key, key),
276
+ );
277
+ }
278
+
279
+ /**
280
+ * Step 4. Recursively sort the categories/docs + remove the "position"
281
+ * attribute from final output. Note: the "position" is only used to sort
282
+ * "inside" a sidebar slice. It is not used to sort across multiple
283
+ * consecutive sidebar slices (i.e. a whole category composed of multiple
284
+ * autogenerated items)
285
+ */
286
+ function sortItems(
287
+ sidebarItems: WithPosition<NormalizedSidebarItem>[],
288
+ ): NormalizedSidebarItem[] {
289
+ const processedSidebarItems = sidebarItems.map((item) => {
290
+ if (item.type === 'category') {
291
+ return {...item, items: sortItems(item.items)};
292
+ }
293
+ return item;
294
+ });
295
+ const sortedSidebarItems = _.sortBy(processedSidebarItems, [
296
+ 'position',
297
+ 'source',
298
+ ]);
299
+ return sortedSidebarItems.map(({position, source, ...item}) => item);
300
+ }
301
+ // TODO: the whole code is designed for pipeline operator
302
+ const docs = getAutogenDocs();
303
+ const fsModel = treeify(docs);
304
+ const sidebarWithPosition = generateSidebar(fsModel);
305
+ const sortedSidebar = sortItems(sidebarWithPosition);
306
+ return sortedSidebar;
307
+ };
@@ -0,0 +1,130 @@
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 'node:path';
9
+ import _ from 'lodash';
10
+ import logger from '@docusaurus/logger';
11
+ import {loadFreshModule} from '@docusaurus/utils';
12
+ import {glob} from '@docusaurus/glob';
13
+ import * as Yaml from 'js-yaml';
14
+ import combinePromises from 'combine-promises';
15
+ import {fs, pathExists} from '@docusaurus/fs';
16
+ import {validateSidebars, validateCategoryMetadataFile} from './validation';
17
+ import {normalizeSidebars} from './normalization';
18
+ import {processSidebars} from './processor';
19
+ import {postProcessSidebars} from './postProcessor';
20
+ import type {PluginOptions} from '@docusaurus/plugin-content-docs';
21
+ import type {SidebarsConfig, Sidebars, SidebarProcessorParams} from './types';
22
+
23
+ export const DefaultSidebars: SidebarsConfig = {
24
+ defaultSidebar: [
25
+ {
26
+ type: 'autogenerated',
27
+ dirName: '.',
28
+ },
29
+ ],
30
+ };
31
+
32
+ export const DisabledSidebars: SidebarsConfig = {};
33
+
34
+ // If a path is provided, make it absolute
35
+ export function resolveSidebarPathOption(
36
+ siteDir: string,
37
+ sidebarPathOption: PluginOptions['sidebarPath'],
38
+ ): PluginOptions['sidebarPath'] {
39
+ return sidebarPathOption
40
+ ? path.resolve(siteDir, sidebarPathOption)
41
+ : sidebarPathOption;
42
+ }
43
+
44
+ async function readCategoriesMetadata(contentPath: string) {
45
+ const categoryFiles = await glob('**/_category_.{json,yml,yaml}', {
46
+ cwd: contentPath,
47
+ });
48
+ const categoryToFile = _.groupBy(categoryFiles, path.dirname);
49
+ return combinePromises(
50
+ _.mapValues(categoryToFile, async (files, folder) => {
51
+ const filePath = files[0]!;
52
+ if (files.length > 1) {
53
+ logger.warn`There are more than one category metadata files for path=${folder}: ${files.join(
54
+ ', ',
55
+ )}. The behavior is undetermined.`;
56
+ }
57
+ const content = await fs.readFile(
58
+ path.join(contentPath, filePath),
59
+ 'utf-8',
60
+ );
61
+ try {
62
+ return validateCategoryMetadataFile(Yaml.load(content));
63
+ } catch (err) {
64
+ logger.error`The docs sidebar category metadata file path=${filePath} looks invalid!`;
65
+ throw err;
66
+ }
67
+ }),
68
+ );
69
+ }
70
+
71
+ async function loadSidebarsFileUnsafe(
72
+ sidebarFilePath: string | false | undefined,
73
+ ): Promise<SidebarsConfig> {
74
+ // false => no sidebars
75
+ if (sidebarFilePath === false) {
76
+ return DisabledSidebars;
77
+ }
78
+
79
+ // undefined => defaults to autogenerated sidebars
80
+ if (typeof sidebarFilePath === 'undefined') {
81
+ return DefaultSidebars;
82
+ }
83
+
84
+ // Non-existent sidebars file: no sidebars
85
+ // Note: this edge case can happen on versioned docs, not current version
86
+ // We avoid creating empty versioned sidebars file with the CLI
87
+ if (!(await pathExists(sidebarFilePath))) {
88
+ return DisabledSidebars;
89
+ }
90
+
91
+ // We don't want sidebars to be cached because of hot reloading.
92
+ const module = await loadFreshModule(sidebarFilePath, {default: true});
93
+
94
+ // TODO unsafe, need to refactor and improve validation
95
+ return module as SidebarsConfig;
96
+ }
97
+
98
+ export async function loadSidebarsFile(
99
+ sidebarFilePath: string | false | undefined,
100
+ ): Promise<SidebarsConfig> {
101
+ const sidebars = await loadSidebarsFileUnsafe(sidebarFilePath);
102
+
103
+ // TODO unsafe, need to refactor and improve validation
104
+ return sidebars as SidebarsConfig;
105
+ }
106
+
107
+ export async function loadSidebars(
108
+ sidebarFilePath: string | false | undefined,
109
+ options: SidebarProcessorParams,
110
+ ): Promise<Sidebars> {
111
+ try {
112
+ const sidebarsConfig = await loadSidebarsFileUnsafe(sidebarFilePath);
113
+ const normalizedSidebars = normalizeSidebars(sidebarsConfig);
114
+ validateSidebars(normalizedSidebars);
115
+ const categoriesMetadata = await readCategoriesMetadata(
116
+ options.version.contentPath,
117
+ );
118
+ const processedSidebars = await processSidebars(
119
+ normalizedSidebars,
120
+ categoriesMetadata,
121
+ options,
122
+ );
123
+ return postProcessSidebars(processedSidebars, options);
124
+ } catch (err) {
125
+ logger.error`Sidebars file at path=${
126
+ sidebarFilePath as string
127
+ } failed to be loaded.`;
128
+ throw err;
129
+ }
130
+ }
@@ -0,0 +1,91 @@
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 _ from 'lodash';
9
+ import logger from '@docusaurus/logger';
10
+ import {isCategoriesShorthand} from './utils';
11
+ import type {
12
+ NormalizedSidebarItem,
13
+ NormalizedSidebar,
14
+ NormalizedSidebars,
15
+ SidebarCategoriesShorthand,
16
+ SidebarItemCategoryConfig,
17
+ SidebarItemConfig,
18
+ SidebarConfig,
19
+ SidebarsConfig,
20
+ NormalizedSidebarItemCategory,
21
+ } from './types';
22
+
23
+ function normalizeCategoriesShorthand(
24
+ sidebar: SidebarCategoriesShorthand,
25
+ ): SidebarItemCategoryConfig[] {
26
+ return Object.entries(sidebar).map(([label, items]) => ({
27
+ type: 'category',
28
+ label,
29
+ items,
30
+ }));
31
+ }
32
+
33
+ /**
34
+ * Normalizes recursively item and all its children. Ensures that at the end
35
+ * each item will be an object with the corresponding type.
36
+ */
37
+ export function normalizeItem(
38
+ item: SidebarItemConfig,
39
+ ): NormalizedSidebarItem[] {
40
+ if (typeof item === 'string') {
41
+ return [{type: 'doc', id: item}];
42
+ }
43
+ if (isCategoriesShorthand(item)) {
44
+ // This will never throw anyways
45
+ return normalizeSidebar(item, 'sidebar items slice');
46
+ }
47
+ if (
48
+ (item.type === 'doc' || item.type === 'ref') &&
49
+ typeof item.label === 'string'
50
+ ) {
51
+ return [{...item, translatable: true}];
52
+ }
53
+ if (item.type === 'category') {
54
+ const normalizedCategory: NormalizedSidebarItemCategory = {
55
+ ...item,
56
+ items: normalizeSidebar(
57
+ item.items,
58
+ logger.interpolate`code=${'items'} of the category name=${item.label}`,
59
+ ),
60
+ };
61
+ return [normalizedCategory];
62
+ }
63
+ return [item];
64
+ }
65
+
66
+ function normalizeSidebar(
67
+ sidebar: SidebarConfig,
68
+ place: string,
69
+ ): NormalizedSidebar {
70
+ if (!Array.isArray(sidebar) && !isCategoriesShorthand(sidebar)) {
71
+ throw new Error(
72
+ logger.interpolate`Invalid sidebar items collection code=${JSON.stringify(
73
+ sidebar,
74
+ )} in ${place}: it must either be an array of sidebar items or a shorthand notation (which doesn't contain a code=${'type'} property). See url=${'https://docusaurus.io/docs/sidebar/items'} for all valid syntaxes.`,
75
+ );
76
+ }
77
+
78
+ const normalizedSidebar = Array.isArray(sidebar)
79
+ ? sidebar
80
+ : normalizeCategoriesShorthand(sidebar);
81
+
82
+ return normalizedSidebar.flatMap((subItem) => normalizeItem(subItem));
83
+ }
84
+
85
+ export function normalizeSidebars(
86
+ sidebars: SidebarsConfig,
87
+ ): NormalizedSidebars {
88
+ return _.mapValues(sidebars, (sidebar, id) =>
89
+ normalizeSidebar(sidebar, logger.interpolate`sidebar name=${id}`),
90
+ );
91
+ }
@@ -0,0 +1,115 @@
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 _ from 'lodash';
9
+ import {normalizeUrl} from '@docusaurus/utils';
10
+ import type {
11
+ SidebarItem,
12
+ Sidebars,
13
+ SidebarProcessorParams,
14
+ ProcessedSidebarItemCategory,
15
+ ProcessedSidebarItem,
16
+ ProcessedSidebars,
17
+ SidebarItemCategoryLink,
18
+ } from './types';
19
+
20
+ export type SidebarPostProcessorParams = SidebarProcessorParams & {
21
+ draftIds: Set<string>;
22
+ };
23
+
24
+ function normalizeCategoryLink(
25
+ category: ProcessedSidebarItemCategory,
26
+ params: SidebarPostProcessorParams,
27
+ ): SidebarItemCategoryLink | undefined {
28
+ if (category.link?.type === 'doc' && params.draftIds.has(category.link.id)) {
29
+ return undefined;
30
+ }
31
+ if (category.link?.type === 'generated-index') {
32
+ // Default slug logic can be improved
33
+ const getDefaultSlug = () =>
34
+ `/category/${params.categoryLabelSlugger.slug(category.label)}`;
35
+ const slug = category.link.slug ?? getDefaultSlug();
36
+ const permalink = normalizeUrl([params.version.path, slug]);
37
+ return {
38
+ ...category.link,
39
+ slug,
40
+ permalink,
41
+ };
42
+ }
43
+ return category.link;
44
+ }
45
+
46
+ function postProcessSidebarItem(
47
+ item: ProcessedSidebarItem,
48
+ params: SidebarPostProcessorParams,
49
+ ): SidebarItem | null {
50
+ if (item.type === 'category') {
51
+ // Fail-fast if there's actually no subitems, no because all subitems are
52
+ // drafts. This is likely a configuration mistake.
53
+ if (item.items.length === 0 && !item.link) {
54
+ throw new Error(
55
+ `Sidebar category ${item.label} has neither any subitem nor a link. This makes this item not able to link to anything.`,
56
+ );
57
+ }
58
+ const category = {
59
+ ...item,
60
+ collapsed: item.collapsed ?? params.sidebarOptions.sidebarCollapsed,
61
+ collapsible: item.collapsible ?? params.sidebarOptions.sidebarCollapsible,
62
+ link: normalizeCategoryLink(item, params),
63
+ items: item.items
64
+ .map((subItem) => postProcessSidebarItem(subItem, params))
65
+ .filter((v): v is SidebarItem => Boolean(v)),
66
+ };
67
+
68
+ // If the current category doesn't have subitems, we render a normal link
69
+ // instead.
70
+ if (category.items.length === 0) {
71
+ // Doesn't make sense to render an empty generated index page, so we
72
+ // filter the entire category out as well.
73
+ if (
74
+ !category.link ||
75
+ category.link.type === 'generated-index' ||
76
+ params.draftIds.has(category.link.id)
77
+ ) {
78
+ return null;
79
+ }
80
+ const {label, className, customProps} = category;
81
+ return {
82
+ type: 'doc',
83
+ id: category.link.id,
84
+ label,
85
+ ...(className && {className}),
86
+ ...(customProps && {customProps}),
87
+ };
88
+ }
89
+ // A non-collapsible category can't be collapsed!
90
+ if (!category.collapsible) {
91
+ category.collapsed = false;
92
+ }
93
+ return category;
94
+ }
95
+ if (
96
+ (item.type === 'doc' || item.type === 'ref') &&
97
+ params.draftIds.has(item.id)
98
+ ) {
99
+ return null;
100
+ }
101
+ return item;
102
+ }
103
+
104
+ export function postProcessSidebars(
105
+ sidebars: ProcessedSidebars,
106
+ params: SidebarProcessorParams,
107
+ ): Sidebars {
108
+ const draftIds = new Set(params.drafts.map((d) => d.id));
109
+
110
+ return _.mapValues(sidebars, (sidebar) =>
111
+ sidebar
112
+ .map((item) => postProcessSidebarItem(item, {...params, draftIds}))
113
+ .filter((v): v is SidebarItem => Boolean(v)),
114
+ );
115
+ }