refactor(v2): add typing for docs plugin (#1811)

* refactor(v2): add typing for docs plugin

* nits
This commit is contained in:
Endi 2019-10-07 18:28:33 +07:00 committed by GitHub
parent f671e6b437
commit 1591128cdd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
25 changed files with 304 additions and 131 deletions

View file

@ -0,0 +1,90 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {
Sidebar,
SidebarItem,
SidebarItemDoc,
SidebarItemCategory,
Order,
} from './types';
// Build the docs meta such as next, previous, category and sidebar.
export default function createOrder(allSidebars: Sidebar = {}): Order {
const order: Order = {};
Object.keys(allSidebars).forEach(sidebarId => {
const sidebar = allSidebars[sidebarId];
const ids: string[] = [];
const categoryOrder: (string | undefined)[] = [];
const subCategoryOrder: (string | undefined)[] = [];
const indexItems = ({
items,
categoryLabel,
subCategoryLabel,
}: {
items: SidebarItem[];
categoryLabel?: string;
subCategoryLabel?: string;
}) => {
items.forEach(item => {
switch (item.type) {
case 'category':
indexItems({
items: (item as SidebarItemCategory).items,
categoryLabel:
categoryLabel || (item as SidebarItemCategory).label,
subCategoryLabel:
categoryLabel && (item as SidebarItemCategory).label,
});
break;
case 'ref':
case 'link':
// Refs and links should not be shown in navigation.
break;
case 'doc':
ids.push((item as SidebarItemDoc).id);
categoryOrder.push(categoryLabel);
subCategoryOrder.push(subCategoryLabel);
break;
default:
throw new Error(
`Unknown item type: ${item.type}. Item: ${JSON.stringify(item)}`,
);
}
});
};
indexItems({items: sidebar});
// eslint-disable-next-line
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
let previous;
let next;
if (i > 0) {
previous = ids[i - 1];
}
if (i < ids.length - 1) {
next = ids[i + 1];
}
order[id] = {
previous,
next,
sidebar: sidebarId,
category: categoryOrder[i],
subCategory: subCategoryOrder[i],
};
}
});
return order;
}