Skip to content

Commit

Permalink
fix(v2): improve dx sidebar config, ability to have no sidebars file (#…
Browse files Browse the repository at this point in the history
…4775)

* Improve sidebar config

* Edit message

* fix some little issues in the way undefined/false sidebars are handled

* remove old error message as it has been moved to a better place

Co-authored-by: Nam Hoang Le <[email protected]>
Co-authored-by: slorber <[email protected]>
  • Loading branch information
3 people authored May 18, 2021
1 parent e85ec1a commit 1ab8aa0
Show file tree
Hide file tree
Showing 10 changed files with 235 additions and 129 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`sidebar site with wrong sidebar content 1`] = `
"Bad sidebars file.
These sidebar document ids do not exist:
- goku,
Available document ids=
- foo/bar
- foo/baz
- headingAsTitle
- hello
- ipsum
- lorem
- rootAbsoluteSlug
- rootRelativeSlug
- rootResolvedSlug
- rootTryToEscapeSlug
- slugs/absoluteSlug
- slugs/relativeSlug
- slugs/resolvedSlug
- slugs/tryToEscapeSlug"
`;

exports[`simple website content 1`] = `
Object {
"docs": Array [
Expand Down Expand Up @@ -790,28 +812,6 @@ Object {
}
`;

exports[`site with wrong sidebar file 1`] = `
"Bad sidebars file.
These sidebar document ids do not exist:
- goku,
Available document ids=
- foo/bar
- foo/baz
- headingAsTitle
- hello
- ipsum
- lorem
- rootAbsoluteSlug
- rootRelativeSlug
- rootResolvedSlug
- rootTryToEscapeSlug
- slugs/absoluteSlug
- slugs/relativeSlug
- slugs/resolvedSlug
- slugs/tryToEscapeSlug"
`;

exports[`versioned website (community) content: 100 version sidebars 1`] = `
Object {
"version-1.0.0/community": Array [
Expand Down
90 changes: 79 additions & 11 deletions packages/docusaurus-plugin-content-docs/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {toSidebarsProp} from '../props';

import {validate} from 'webpack';
import {DefaultSidebarItemsGenerator} from '../sidebarItemsGenerator';
import {DisabledSidebars} from '../sidebars';

function findDocById(version: LoadedVersion, unversionedId: string) {
return version.docs.find((item) => item.unversionedId === unversionedId);
Expand Down Expand Up @@ -124,17 +125,84 @@ Entries created:
};
};

test('site with wrong sidebar file', async () => {
const siteDir = path.join(__dirname, '__fixtures__', 'simple-site');
const context = await loadContext(siteDir);
const sidebarPath = path.join(siteDir, 'wrong-sidebars.json');
const plugin = pluginContentDocs(
context,
normalizePluginOptions(OptionsSchema, {
sidebarPath,
}),
);
await expect(plugin.loadContent!()).rejects.toThrowErrorMatchingSnapshot();
describe('sidebar', () => {
test('site with wrong sidebar content', async () => {
const siteDir = path.join(__dirname, '__fixtures__', 'simple-site');
const context = await loadContext(siteDir);
const sidebarPath = path.join(siteDir, 'wrong-sidebars.json');
const plugin = pluginContentDocs(
context,
normalizePluginOptions(OptionsSchema, {
sidebarPath,
}),
);
await expect(plugin.loadContent!()).rejects.toThrowErrorMatchingSnapshot();
});

test('site with wrong sidebar file path', async () => {
const siteDir = path.join(__dirname, '__fixtures__', 'site-with-doc-label');
const context = await loadContext(siteDir);

await expect(async () => {
const plugin = pluginContentDocs(
context,
normalizePluginOptions(OptionsSchema, {
sidebarPath: 'wrong-path-sidebar.json',
}),
);
await plugin.loadContent!();
}).rejects.toThrowErrorMatchingInlineSnapshot(`
"The path to the sidebar file does not exist at [wrong-path-sidebar.json].
Please set the docs [sidebarPath] field in your config file to:
- a sidebars path that exists
- false: to disable the sidebar
- undefined: for Docusaurus generates it automatically"
`);
});

test('site with undefined sidebar', async () => {
const siteDir = path.join(__dirname, '__fixtures__', 'site-with-doc-label');
const context = await loadContext(siteDir);
const plugin = pluginContentDocs(
context,
normalizePluginOptions(OptionsSchema, {
sidebarPath: undefined,
}),
);
const result = await plugin.loadContent!();

expect(result.loadedVersions).toHaveLength(1);
expect(result.loadedVersions[0].sidebars).toMatchInlineSnapshot(`
Object {
"defaultSidebar": Array [
Object {
"id": "hello-1",
"type": "doc",
},
Object {
"id": "hello-2",
"label": "Hello 2 From Doc",
"type": "doc",
},
],
}
`);
});

test('site with disabled sidebar', async () => {
const siteDir = path.join(__dirname, '__fixtures__', 'site-with-doc-label');
const context = await loadContext(siteDir);
const plugin = pluginContentDocs(
context,
normalizePluginOptions(OptionsSchema, {
sidebarPath: false,
}),
);
const result = await plugin.loadContent!();

expect(result.loadedVersions).toHaveLength(1);
expect(result.loadedVersions[0].sidebars).toEqual(DisabledSidebars);
});
});

describe('empty/no docs website', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ import {
collectSidebarCategories,
collectSidebarLinks,
transformSidebarItems,
DefaultSidebars,
processSidebars,
DefaultSidebars,
DisabledSidebars,
} from '../sidebars';
import {
Sidebar,
Expand Down Expand Up @@ -127,35 +128,15 @@ describe('loadSidebars', () => {
});

test('unexisting path', () => {
/*
expect(() => loadSidebars('badpath')).toThrowErrorMatchingInlineSnapshot(
`"No sidebar file exist at path: badpath"`,
);
*/
// See https://github.com/facebook/docusaurus/issues/3366
expect(loadSidebars('badpath')).toEqual(DefaultSidebars);
expect(loadSidebars('badpath')).toEqual(DisabledSidebars);
});

test('undefined path', () => {
expect(() =>
loadSidebars(
// @ts-expect-error: bad arg
undefined,
),
).toThrowErrorMatchingInlineSnapshot(
`"sidebarFilePath not provided: undefined"`,
);
expect(loadSidebars(undefined)).toEqual(DefaultSidebars);
});

test('null path', () => {
expect(() =>
loadSidebars(
// @ts-expect-error: bad arg
null,
),
).toThrowErrorMatchingInlineSnapshot(
`"sidebarFilePath not provided: null"`,
);
test('literal false path', () => {
expect(loadSidebars(false)).toEqual(DisabledSidebars);
});

test('sidebars with category.collapsed property', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ describe('simple site', () => {
),
isLast: true,
routePriority: -1,
sidebarFilePath: path.join(simpleSiteDir, 'sidebars.json'),
sidebarFilePath: undefined,
versionLabel: 'Next',
versionName: 'current',
versionPath: '/docs',
Expand Down Expand Up @@ -138,6 +138,9 @@ describe('simple site', () => {
versionPath: '/myBaseUrl/docs/current-path',
versionLabel: 'current-label',
routePriority: undefined,
sidebarFilePath: undefined,
versionEditUrl: undefined,
versionEditUrlLocalized: undefined,
},
]);
});
Expand Down Expand Up @@ -210,6 +213,7 @@ describe('versioned site, pluginId=default', () => {
const defaultOptions: PluginOptions = {
id: DEFAULT_PLUGIN_ID,
...DEFAULT_OPTIONS,
sidebarPath: 'sidebars.json',
};
const defaultContext = {
siteDir: versionedSiteDir,
Expand Down Expand Up @@ -607,6 +611,7 @@ describe('versioned site, pluginId=community', () => {
id: 'community',
path: 'community',
routeBasePath: 'communityBasePath',
sidebarPath: 'sidebars.json',
};
const defaultContext = {
siteDir: versionedSiteDir,
Expand Down
106 changes: 62 additions & 44 deletions packages/docusaurus-plugin-content-docs/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,67 @@ import {
import {loadSidebars} from './sidebars';
import {DEFAULT_PLUGIN_ID} from '@docusaurus/core/lib/constants';

function createVersionedSidebarFile({
siteDir,
pluginId,
sidebarPath,
version,
}: {
siteDir: string;
pluginId: string;
sidebarPath: string | false | undefined;
version: string;
}) {
// Load current sidebar and create a new versioned sidebars file (if needed).
const loadedSidebars = loadSidebars(sidebarPath);

// Do not create a useless versioned sidebars file if sidebars file is empty or sidebars are disabled/false)
const shouldCreateVersionedSidebarFile =
Object.keys(loadedSidebars).length > 0;

if (shouldCreateVersionedSidebarFile) {
// TODO @slorber: this "version prefix" in versioned sidebars looks like a bad idea to me
// TODO try to get rid of it
// Transform id in original sidebar to versioned id.
const normalizeItem = (
item: UnprocessedSidebarItem,
): UnprocessedSidebarItem => {
switch (item.type) {
case 'category':
return {...item, items: item.items.map(normalizeItem)};
case 'ref':
case 'doc':
return {
type: item.type,
id: `version-${version}/${item.id}`,
};
default:
return item;
}
};

const versionedSidebar: UnprocessedSidebars = Object.entries(
loadedSidebars,
).reduce((acc: UnprocessedSidebars, [sidebarId, sidebarItems]) => {
const newVersionedSidebarId = `version-${version}/${sidebarId}`;
acc[newVersionedSidebarId] = sidebarItems.map(normalizeItem);
return acc;
}, {});

const versionedSidebarsDir = getVersionedSidebarsDirPath(siteDir, pluginId);
const newSidebarFile = path.join(
versionedSidebarsDir,
`version-${version}-sidebars.json`,
);
fs.ensureDirSync(path.dirname(newSidebarFile));
fs.writeFileSync(
newSidebarFile,
`${JSON.stringify(versionedSidebar, null, 2)}\n`,
'utf8',
);
}
}

// Tests depend on non-default export for mocking.
// eslint-disable-next-line import/prefer-default-export
export function cliDocsVersionCommand(
Expand Down Expand Up @@ -92,50 +153,7 @@ export function cliDocsVersionCommand(
throw new Error(`${pluginIdLogPrefix}There is no docs to version !`);
}

// Load current sidebar and create a new versioned sidebars file.
if (fs.existsSync(sidebarPath)) {
const loadedSidebars = loadSidebars(sidebarPath);

// TODO @slorber: this "version prefix" in versioned sidebars looks like a bad idea to me
// TODO try to get rid of it
// Transform id in original sidebar to versioned id.
const normalizeItem = (
item: UnprocessedSidebarItem,
): UnprocessedSidebarItem => {
switch (item.type) {
case 'category':
return {...item, items: item.items.map(normalizeItem)};
case 'ref':
case 'doc':
return {
type: item.type,
id: `version-${version}/${item.id}`,
};
default:
return item;
}
};

const versionedSidebar: UnprocessedSidebars = Object.entries(
loadedSidebars,
).reduce((acc: UnprocessedSidebars, [sidebarId, sidebarItems]) => {
const newVersionedSidebarId = `version-${version}/${sidebarId}`;
acc[newVersionedSidebarId] = sidebarItems.map(normalizeItem);
return acc;
}, {});

const versionedSidebarsDir = getVersionedSidebarsDirPath(siteDir, pluginId);
const newSidebarFile = path.join(
versionedSidebarsDir,
`version-${version}-sidebars.json`,
);
fs.ensureDirSync(path.dirname(newSidebarFile));
fs.writeFileSync(
newSidebarFile,
`${JSON.stringify(versionedSidebar, null, 2)}\n`,
'utf8',
);
}
createVersionedSidebarFile({siteDir, pluginId, version, sidebarPath});

// Update versions.json file.
versions.unshift(version);
Expand Down
7 changes: 5 additions & 2 deletions packages/docusaurus-plugin-content-docs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,7 @@ export default function pluginContentDocs(

getPathsToWatch() {
function getVersionPathsToWatch(version: VersionMetadata): string[] {
return [
version.sidebarFilePath,
const result = [
...flatten(
options.include.map((pattern) =>
getDocsDirPaths(version).map(
Expand All @@ -129,6 +128,10 @@ export default function pluginContentDocs(
),
`${version.contentPath}/**/${CategoryMetadataFilenamePattern}`,
];
if (typeof version.sidebarFilePath === 'string') {
result.unshift(version.sidebarFilePath);
}
return result;
}

return flatten(versionsMetadata.map(getVersionPathsToWatch));
Expand Down
Loading

0 comments on commit 1ab8aa0

Please sign in to comment.