-
-
Notifications
You must be signed in to change notification settings - Fork 8k
/
normalization.ts
91 lines (84 loc) · 2.54 KB
/
normalization.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import _ from 'lodash';
import logger from '@docusaurus/logger';
import {isCategoriesShorthand} from './utils';
import type {
NormalizedSidebarItem,
NormalizedSidebar,
NormalizedSidebars,
SidebarCategoriesShorthand,
SidebarItemCategoryConfig,
SidebarItemConfig,
SidebarConfig,
SidebarsConfig,
NormalizedSidebarItemCategory,
} from './types';
function normalizeCategoriesShorthand(
sidebar: SidebarCategoriesShorthand,
): SidebarItemCategoryConfig[] {
return Object.entries(sidebar).map(([label, items]) => ({
type: 'category',
label,
items,
}));
}
/**
* Normalizes recursively item and all its children. Ensures that at the end
* each item will be an object with the corresponding type.
*/
export function normalizeItem(
item: SidebarItemConfig,
): NormalizedSidebarItem[] {
if (typeof item === 'string') {
return [{type: 'doc', id: item}];
}
if (isCategoriesShorthand(item)) {
// This will never throw anyways
return normalizeSidebar(item, 'sidebar items slice');
}
if (
(item.type === 'doc' || item.type === 'ref') &&
typeof item.label === 'string'
) {
return [{...item, translatable: true}];
}
if (item.type === 'category') {
const normalizedCategory: NormalizedSidebarItemCategory = {
...item,
items: normalizeSidebar(
item.items,
logger.interpolate`code=${'items'} of the category name=${item.label}`,
),
};
return [normalizedCategory];
}
return [item];
}
function normalizeSidebar(
sidebar: SidebarConfig,
place: string,
): NormalizedSidebar {
if (!Array.isArray(sidebar) && !isCategoriesShorthand(sidebar)) {
throw new Error(
logger.interpolate`Invalid sidebar items collection code=${JSON.stringify(
sidebar,
)} 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.`,
);
}
const normalizedSidebar = Array.isArray(sidebar)
? sidebar
: normalizeCategoriesShorthand(sidebar);
return normalizedSidebar.flatMap((subItem) => normalizeItem(subItem));
}
export function normalizeSidebars(
sidebars: SidebarsConfig,
): NormalizedSidebars {
return _.mapValues(sidebars, (sidebar, id) =>
normalizeSidebar(sidebar, logger.interpolate`sidebar name=${id}`),
);
}