Skip to content

Commit

Permalink
refactor: replace non-prop interface with type; allow plugin lifecycl…
Browse files Browse the repository at this point in the history
…es to have sync type (#7080)

* refactor: replace non-prop interface with type; allow plugin lifecycles to have sync type

* fix
  • Loading branch information
Josh-Cena authored Mar 31, 2022
1 parent ce2b631 commit 24c205a
Show file tree
Hide file tree
Showing 38 changed files with 145 additions and 138 deletions.
4 changes: 2 additions & 2 deletions packages/docusaurus-mdx-loader/src/deps.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ declare module '@mdx-js/mdx' {
import type {Processor} from 'unified';
import type {RemarkOrRehypePlugin} from '@docusaurus/mdx-loader';

export interface Options {
export type Options = {
filepath?: string;
skipExport?: boolean;
wrapExport?: string;
remarkPlugins?: RemarkOrRehypePlugin[];
rehypePlugins?: RemarkOrRehypePlugin[];
}
};

export function sync(content: string, options?: Options): string;
export function createMdxAstCompiler(options?: Options): Processor;
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus-mdx-loader/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,9 @@ export default async function mdxLoader(
// Partial are not expected to have associated metadata files or front matter
const isMDXPartial = options.isMDXPartial?.(filePath);
if (isMDXPartial && hasFrontMatter) {
const errorMessage = `Docusaurus MDX partial files should not contain FrontMatter.
const errorMessage = `Docusaurus MDX partial files should not contain front matter.
Those partial files use the _ prefix as a convention by default, but this is configurable.
File at ${filePath} contains FrontMatter that will be ignored:
File at ${filePath} contains front matter that will be ignored:
${JSON.stringify(frontMatter, null, 2)}`;

if (!options.isMDXPartialFrontMatterWarningDisabled) {
Expand Down
9 changes: 3 additions & 6 deletions packages/docusaurus-mdx-loader/src/remark/headings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@

import {parseMarkdownHeadingId, createSlugger} from '@docusaurus/utils';
import visit from 'unist-util-visit';
import toString from 'mdast-util-to-string';
import mdastToString from 'mdast-util-to-string';
import type {Transformer} from 'unified';
import type {Parent} from 'unist';
import type {Heading, Text} from 'mdast';

export default function plugin(): Transformer {
Expand All @@ -30,10 +29,8 @@ export default function plugin(): Transformer {
const headingTextNodes = headingNode.children.filter(
({type}) => !['html', 'jsx'].includes(type),
);
const heading = toString(
headingTextNodes.length > 0
? ({children: headingTextNodes} as Parent)
: headingNode,
const heading = mdastToString(
headingTextNodes.length > 0 ? headingTextNodes : headingNode,
);

// Support explicit heading IDs
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus-mdx-loader/src/remark/toc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ const isImport = (child: Node): child is Literal => child.type === 'import';
const hasImports = (index: number) => index > -1;
const isExport = (child: Node): child is Literal => child.type === 'export';

interface PluginOptions {
type PluginOptions = {
name?: string;
}
};

const isTarget = (child: Literal, name: string) => {
let found = false;
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus-migrate/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export type SidebarEntries = {
| Array<{[key: string]: unknown} | string>;
};

export interface VersionTwoConfig {
export type VersionTwoConfig = {
baseUrl: string;
favicon: string;
tagline?: string;
Expand Down Expand Up @@ -93,7 +93,7 @@ export interface VersionTwoConfig {
[key: string]: unknown;
}
)[];
}
};

export type VersionOneConfig = {
title?: string;
Expand Down
3 changes: 2 additions & 1 deletion packages/docusaurus-module-type-aliases/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,9 @@ declare module '@docusaurus/Head' {

declare module '@docusaurus/Link' {
import type {CSSProperties, ComponentProps} from 'react';
import type {NavLinkProps as RRNavLinkProps} from 'react-router-dom';

type NavLinkProps = Partial<import('react-router-dom').NavLinkProps>;
type NavLinkProps = Partial<RRNavLinkProps>;
export type Props = NavLinkProps &
ComponentProps<'a'> & {
readonly className?: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,10 @@ describe('validateBlogPostFrontMatter tags', () => {
{tags: ['hello', {label: 'tagLabel', permalink: '/tagPermalink'}]},
],
invalidFrontMatters: [
[{tags: ''}, '"tags" does not look like a valid FrontMatter Yaml array.'],
[
{tags: ''},
'"tags" does not look like a valid front matter Yaml array.',
],
[{tags: ['']}, 'not allowed to be empty'],
],
// See https://github.com/facebook/docusaurus/issues/4642
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-content-blog/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ export default async function pluginContentBlog(
) as string[];
},

async getTranslationFiles() {
getTranslationFiles() {
return getTranslationFiles(options);
},

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ declare module '@docusaurus/plugin-content-blog' {
import type {FrontMatterTag, Tag} from '@docusaurus/utils';
import type {Overwrite} from 'utility-types';

export interface Assets {
export type Assets = {
/**
* If `metadata.image` is a collocated image path, this entry will be the
* bundler-generated image path. Otherwise, it's empty, and the image URL
Expand All @@ -25,13 +25,9 @@ declare module '@docusaurus/plugin-content-blog' {
* should be accessed through `authors.imageURL`.
*/
authorsImageUrls: (string | undefined)[];
}
};

/**
* Unknown keys are allowed, so that we can pass custom fields to authors,
* e.g., `twitter`.
*/
export interface Author extends Record<string, unknown> {
export type Author = {
/**
* If `name` doesn't exist, an `imageURL` is expected.
*/
Expand All @@ -55,7 +51,12 @@ declare module '@docusaurus/plugin-content-blog' {
* to generate a fallback `mailto:` URL.
*/
email?: string;
}
/**
* Unknown keys are allowed, so that we can pass custom fields to authors,
* e.g., `twitter`.
*/
[key: string]: unknown;
};

/**
* Everything is partial/unnormalized, because front matter is always
Expand Down Expand Up @@ -443,8 +444,6 @@ declare module '@theme/BlogPostPage' {
>;

export type Content = {
// TODO remove this. `metadata.frontMatter` is preferred because it can be
// accessed in enhanced plugins
/** Same as `metadata.frontMatter` */
readonly frontMatter: FrontMatter;
/**
Expand Down
26 changes: 14 additions & 12 deletions packages/docusaurus-plugin-content-blog/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,39 +11,41 @@ import type {Metadata as BlogPaginatedMetadata} from '@theme/BlogListPage';

export type BlogContentPaths = ContentPaths;

export interface BlogContent {
export type BlogContent = {
blogSidebarTitle: string;
blogPosts: BlogPost[];
blogListPaginated: BlogPaginated[];
blogTags: BlogTags;
blogTagsListPath: string | null;
}
};

export interface BlogTags {
export type BlogTags = {
// TODO, the key is the tag slug/permalink
// This is due to legacy frontmatter: tags:
// [{label: "xyz", permalink: "/1"}, {label: "xyz", permalink: "/2"}]
// Soon we should forbid declaring permalink through frontmatter
[tagKey: string]: BlogTag;
}
};

export interface BlogTag {
export type BlogTag = {
name: string;
items: string[]; // blog post permalinks
/** Blog post permalinks. */
items: string[];
permalink: string;
pages: BlogPaginated[];
}
};

export interface BlogPost {
export type BlogPost = {
id: string;
metadata: BlogPostMetadata;
content: string;
}
};

export interface BlogPaginated {
export type BlogPaginated = {
metadata: BlogPaginatedMetadata;
items: string[]; // blog post permalinks
}
/** Blog post permalinks. */
items: string[];
};

export type BlogBrokenMarkdownLink = BrokenMarkdownLink<BlogContentPaths>;
export type BlogMarkdownLoaderOptions = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,10 +265,13 @@ describe('validateDocFrontMatter tags', () => {
validFrontMatters: [{}, {tags: undefined}, {tags: ['tag1', 'tag2']}],
convertibleFrontMatter: [[{tags: ['tag1', 42]}, {tags: ['tag1', '42']}]],
invalidFrontMatters: [
[{tags: 42}, '"tags" does not look like a valid FrontMatter Yaml array.'],
[
{tags: 42},
'"tags" does not look like a valid front matter Yaml array.',
],
[
{tags: 'tag1, tag2'},
'"tags" does not look like a valid FrontMatter Yaml array.',
'"tags" does not look like a valid front matter Yaml array.',
],
[{tags: [{}]}, '"tags[0]" does not look like a valid tag'],
[{tags: [true]}, '"tags[0]" does not look like a valid tag'],
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-content-docs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ export default async function pluginContentDocs(
});
},

async getTranslationFiles({content}) {
getTranslationFiles({content}) {
return getLoadedContentTranslationFiles(content);
},

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ declare module '@docusaurus/plugin-content-docs' {
import type {ContentPaths, Tag, FrontMatterTag} from '@docusaurus/utils';
import type {Required} from 'utility-types';

export interface Assets {
export type Assets = {
image?: string;
}
};

/**
* Custom callback for parsing number prefixes from file/folder names.
Expand Down
19 changes: 8 additions & 11 deletions packages/docusaurus-plugin-content-docs/src/sidebars/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,18 +254,15 @@ export type SidebarItemsGenerator = (
generatorArgs: SidebarItemsGeneratorArgs,
) => Promise<NormalizedSidebar>;

// Also inject the default generator to conveniently wrap/enhance/sort the
// default sidebar gen logic
// see https://github.com/facebook/docusaurus/issues/4640#issuecomment-822292320
export type SidebarItemsGeneratorOptionArgs = {
/**
* Useful to re-use/enhance the default sidebar generation logic from
* Docusaurus.
*/
defaultSidebarItemsGenerator: SidebarItemsGenerator;
} & SidebarItemsGeneratorArgs;
export type SidebarItemsGeneratorOption = (
generatorArgs: SidebarItemsGeneratorOptionArgs,
generatorArgs: {
/**
* Useful to re-use/enhance the default sidebar generation logic from
* Docusaurus.
* @see https://github.com/facebook/docusaurus/issues/4640#issuecomment-822292320
*/
defaultSidebarItemsGenerator: SidebarItemsGenerator;
} & SidebarItemsGeneratorArgs,
) => Promise<NormalizedSidebarItem[]>;

export type SidebarProcessorParams = {
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus-plugin-ideal-image/src/deps.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ declare module '@endiliey/react-ideal-image' {
| 'noicon'
| 'offline';

export interface SrcType {
export type SrcType = {
width: number;
src?: string;
size?: number;
format?: 'webp' | 'jpeg' | 'png' | 'gif';
}
};

type ThemeKey = 'placeholder' | 'img' | 'icon' | 'noscript';

Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus-remark-plugin-npm2yarn/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ import type {Node, Parent} from 'unist';
import visit from 'unist-util-visit';
import npmToYarn from 'npm-to-yarn';

interface PluginOptions {
type PluginOptions = {
sync?: boolean;
}
};

// E.g. global install: 'npm i' -> 'yarn'
const convertNpmToYarn = (npmCode: string) => npmToYarn(npmCode, 'yarn');
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-theme-classic/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ export default function docusaurusThemeClassic(
return '../src/theme';
},

getTranslationFiles: async () => getTranslationFiles({themeConfig}),
getTranslationFiles: () => getTranslationFiles({themeConfig}),

translateThemeConfig: (params) =>
translateThemeConfig({
Expand Down
14 changes: 7 additions & 7 deletions packages/docusaurus-theme-common/src/contexts/docsSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ import {ReactContextError} from '../utils/reactUtils';
// Inspired by https://github.com/jamiebuilds/unstated-next/blob/master/src/unstated-next.tsx
const EmptyContext: unique symbol = Symbol('EmptyContext');

type SidebarContextValue = {name: string; items: PropSidebar};
type ContextValue = {name: string; items: PropSidebar};

const Context = React.createContext<
SidebarContextValue | null | typeof EmptyContext
>(EmptyContext);
const Context = React.createContext<ContextValue | null | typeof EmptyContext>(
EmptyContext,
);

/**
* Provide the current sidebar to your children.
Expand All @@ -31,7 +31,7 @@ export function DocsSidebarProvider({
name: string | undefined;
items: PropSidebar | undefined;
}): JSX.Element {
const stableValue: SidebarContextValue | null = useMemo(
const stableValue: ContextValue | null = useMemo(
() =>
name && items
? {
Expand All @@ -45,9 +45,9 @@ export function DocsSidebarProvider({
}

/**
* Gets the sidebar data that's currently displayed, or `null` if there isn't one
* Gets the sidebar that's currently displayed, or `null` if there isn't one
*/
export function useDocsSidebar(): SidebarContextValue | null {
export function useDocsSidebar(): ContextValue | null {
const value = useContext(Context);
if (value === EmptyContext) {
throw new ReactContextError('DocsSidebarProvider');
Expand Down
10 changes: 6 additions & 4 deletions packages/docusaurus-theme-common/src/utils/docsUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,9 @@ export function useDocsVersionCandidates(

/**
* The layout components, like navbar items, must be able to work on all pages,
* even on non-doc ones. This hook would always return a sidebar to be linked
* to. See also {@link useDocsVersionCandidates} for how this selection is done.
* even on non-doc ones where there's no version context, so a sidebar ID could
* be ambiguous. This hook would always return a sidebar to be linked to. See
* also {@link useDocsVersionCandidates} for how this selection is done.
*
* @throws This hook throws if a sidebar with said ID is not found.
*/
Expand Down Expand Up @@ -252,8 +253,9 @@ export function useLayoutDocsSidebar(

/**
* The layout components, like navbar items, must be able to work on all pages,
* even on non-doc ones. This hook would always return a doc to be linked
* to. See also {@link useDocsVersionCandidates} for how this selection is done.
* even on non-doc ones where there's no version context, so a doc ID could be
* ambiguous. This hook would always return a doc to be linked to. See also
* {@link useDocsVersionCandidates} for how this selection is done.
*
* @throws This hook throws if a doc with said ID is not found.
*/
Expand Down
4 changes: 2 additions & 2 deletions packages/docusaurus-theme-common/src/utils/metadataUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ import useRouteContext from '@docusaurus/useRouteContext';
import {useBaseUrlUtils} from '@docusaurus/useBaseUrl';
import {useTitleFormatter} from './generalUtils';

interface PageMetadataProps {
type PageMetadataProps = {
readonly title?: string;
readonly description?: string;
readonly keywords?: readonly string[] | string;
readonly image?: string;
readonly children?: ReactNode;
}
};

/**
* Helper component to manipulate page metadata and override site defaults.
Expand Down
Loading

0 comments on commit 24c205a

Please sign in to comment.