Skip to content

Commit

Permalink
refactor: remove a lot of implicit anys (#7468)
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh-Cena authored May 23, 2022
1 parent 0c8e57d commit 3666a2e
Show file tree
Hide file tree
Showing 23 changed files with 148 additions and 163 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
__fixtures__
__mocks__
dist
node_modules
.yarn
Expand Down
22 changes: 18 additions & 4 deletions admin/scripts/generateExamples.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,27 @@
* LICENSE file in the root directory of this source tree.
*/

// @ts-check

import fs from 'fs-extra';
import shell from 'shelljs';

const NODE_MAJOR_VERSION = parseInt(process.versions.node.split('.')[0], 10);
const NODE_MAJOR_VERSION = parseInt(
/** @type {string} */ (process.versions.node.split('.')[0]),
10,
);
if (NODE_MAJOR_VERSION < 16) {
throw new Error(
'This generateExamples Docusaurus script requires at least Node.js 16 and npm 7. See why here: https://github.com/facebook/docusaurus/pull/5722#issuecomment-948847891',
);
}

// Generate one example per init template
// We use those generated examples as CodeSandbox projects
// See https://github.com/facebook/docusaurus/issues/1699
/**
* Generate one example per init template
* We use those generated examples as CodeSandbox projects
* See https://github.com/facebook/docusaurus/issues/1699
* @param {string} template
*/
async function generateTemplateExample(template) {
try {
console.log(
Expand Down Expand Up @@ -103,6 +111,12 @@ async function generateTemplateExample(template) {
* Button visible here: https://jamstack.org/generators/
*/
function updateStarters() {
/**
* @param {Object} param0
* @param {string} param0.subfolder
* @param {string} param0.remote
* @param {string} param0.remoteBranch
*/
function forcePushGitSubtree({subfolder, remote, remoteBranch}) {
console.log('');
// See https://stackoverflow.com/questions/33172857/how-do-i-force-a-subtree-push-to-overwrite-remote-changes
Expand Down
24 changes: 6 additions & 18 deletions packages/create-docusaurus/bin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,24 +45,12 @@ program
\`custom\`: enter your custom git clone command. We will prompt you for it.`,
)
.description('Initialize website.')
.action(
(
siteName,
template,
rootDir = '.',
{packageManager, skipInstall, typescript, gitStrategy} = {},
) => {
// See https://github.com/facebook/docusaurus/pull/6860
import('../lib/index.js').then(({default: init}) => {
init(path.resolve(rootDir), siteName, template, {
packageManager,
skipInstall,
typescript,
gitStrategy,
});
});
},
);
.action((siteName, template, rootDir, options) => {
// See https://github.com/facebook/docusaurus/pull/6860
import('../lib/index.js').then(({default: init}) => {
init(path.resolve(rootDir ?? '.'), siteName, template, options);
});
});

program.parse(process.argv);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import toString from 'mdast-util-to-string';
import visit from 'unist-util-visit';
import slug from '../index';
import type {Plugin} from 'unified';
import type {Parent} from 'unist';

function process(doc: string, plugins: Plugin[] = []) {
const processor = remark().use({plugins: [...plugins, slug]});
Expand Down Expand Up @@ -58,11 +59,8 @@ describe('headings remark plugin', () => {

it('does not overwrite `data` on headings', () => {
const result = process('# Normal\n', [
() => {
function transform(tree) {
tree.children[0].data = {foo: 'bar'};
}
return transform;
() => (root) => {
(root as Parent).children[0]!.data = {foo: 'bar'};
},
]);
const expected = u('root', [
Expand All @@ -81,11 +79,10 @@ describe('headings remark plugin', () => {

it('does not overwrite `data.hProperties` on headings', () => {
const result = process('# Normal\n', [
() => {
function transform(tree) {
tree.children[0].data = {hProperties: {className: ['foo']}};
}
return transform;
() => (root) => {
(root as Parent).children[0]!.data = {
hProperties: {className: ['foo']},
};
},
]);
const expected = u('root', [
Expand All @@ -111,12 +108,9 @@ describe('headings remark plugin', () => {
'## Something also',
].join('\n\n'),
[
() => {
function transform(tree) {
tree.children[1].data = {hProperties: {id: 'here'}};
tree.children[3].data = {hProperties: {id: 'something'}};
}
return transform;
() => (root) => {
(root as Parent).children[1]!.data = {hProperties: {id: 'here'}};
(root as Parent).children[3]!.data = {hProperties: {id: 'something'}};
},
],
);
Expand Down Expand Up @@ -270,9 +264,9 @@ describe('headings remark plugin', () => {
# {#text-after} custom ID
`);

const headers = [];
const headers: {text: string; id: string}[] = [];
visit(result, 'heading', (node) => {
headers.push({text: toString(node), id: node.data.id});
headers.push({text: toString(node), id: node.data!.id as string});
});

expect(headers).toEqual([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,50 +75,6 @@ exports[`toc remark plugin exports even with existing name 1`] = `
"
`;

exports[`toc remark plugin exports with custom name 1`] = `
"export const customName = [
{
value: 'Endi',
id: 'endi',
level: 3
},
{
value: 'Endi',
id: 'endi-1',
level: 2
},
{
value: 'Yangshun',
id: 'yangshun',
level: 3
},
{
value: 'I ♥ unicode.',
id: 'i--unicode',
level: 2
}
];
### Endi
\`\`\`md
## This is ignored
\`\`\`
## Endi
Lorem ipsum
### Yangshun
Some content here
## I ♥ unicode.
export const c = 1;
"
`;

exports[`toc remark plugin handles empty headings 1`] = `
"export const toc = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ import vfile from 'to-vfile';
import plugin from '../index';
import headings from '../../headings/index';

const processFixture = async (name, options?) => {
const processFixture = async (name: string) => {
const filePath = path.join(__dirname, '__fixtures__', `${name}.md`);
const file = await vfile.read(filePath);
const result = await remark()
.use(headings)
.use(mdx)
.use(plugin, options)
.use(plugin)
.process(file);

return result.toString();
Expand All @@ -45,14 +45,6 @@ describe('toc remark plugin', () => {
expect(result).toMatchSnapshot();
});

it('exports with custom name', async () => {
const options = {
name: 'customName',
};
const result = await processFixture('just-content', options);
expect(result).toMatchSnapshot();
});

it('inserts below imports', async () => {
const result = await processFixture('insert-below-imports');
expect(result).toMatchSnapshot();
Expand Down
18 changes: 7 additions & 11 deletions packages/docusaurus-mdx-loader/src/remark/toc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,13 @@ const parseOptions: ParserOptions = {
sourceType: 'module',
};

const name = 'toc';

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';

type PluginOptions = {
name?: string;
};

const isTarget = (child: Literal, name: string) => {
const isTarget = (child: Literal) => {
let found = false;
const ast = parse(child.value, parseOptions);
traverse(ast, {
Expand All @@ -44,14 +42,14 @@ const isTarget = (child: Literal, name: string) => {
return found;
};

const getOrCreateExistingTargetIndex = (children: Node[], name: string) => {
const getOrCreateExistingTargetIndex = (children: Node[]) => {
let importsIndex = -1;
let targetIndex = -1;

children.forEach((child, index) => {
if (isImport(child)) {
importsIndex = index;
} else if (isExport(child) && isTarget(child, name)) {
} else if (isExport(child) && isTarget(child)) {
targetIndex = index;
}
});
Expand All @@ -70,9 +68,7 @@ const getOrCreateExistingTargetIndex = (children: Node[], name: string) => {
return targetIndex;
};

export default function plugin(options: PluginOptions = {}): Transformer {
const name = options.name || 'toc';

export default function plugin(): Transformer {
return (root) => {
const headings: TOCItem[] = [];

Expand All @@ -91,7 +87,7 @@ export default function plugin(options: PluginOptions = {}): Transformer {
});
});
const {children} = root as Parent<Literal>;
const targetIndex = getOrCreateExistingTargetIndex(children, name);
const targetIndex = getOrCreateExistingTargetIndex(children);

if (headings.length) {
children[targetIndex]!.value = `export const ${name} = ${stringifyObject(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,19 @@ import path from 'path';
import remark from 'remark';
import mdx from 'remark-mdx';
import vfile from 'to-vfile';
import plugin from '../index';
import plugin, {type PluginOptions} from '../index';
import headings from '../../headings/index';

const processFixture = async (name, options) => {
const processFixture = async (
name: string,
options: Partial<PluginOptions>,
) => {
const filePath = path.join(__dirname, `__fixtures__/${name}.md`);
const file = await vfile.read(filePath);
const result = await remark()
.use(headings)
.use(mdx)
.use(plugin, {...options, filePath})
.use(plugin, {siteDir: __dirname, staticDirs: [], ...options})
.process(file);

return result.toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const {
loaders: {inlineMarkdownImageFileLoader},
} = getFileLoaderUtils();

type PluginOptions = {
export type PluginOptions = {
staticDirs: string[];
siteDir: string;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import remark from 'remark';
import mdx from 'remark-mdx';
import vfile from 'to-vfile';
import plugin from '..';
import transformImage from '../../transformImage';
import transformImage, {type PluginOptions} from '../../transformImage';

const processFixture = async (name: string, options?) => {
const processFixture = async (name: string, options?: PluginOptions) => {
const filePath = path.join(__dirname, `__fixtures__/${name}.md`);
const staticDirs = [
path.join(__dirname, '__fixtures__/static'),
Expand All @@ -24,7 +24,6 @@ const processFixture = async (name: string, options?) => {
.use(transformImage, {...options, filePath, staticDirs})
.use(plugin, {
...options,
filePath,
staticDirs,
siteDir: path.join(__dirname, '__fixtures__'),
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const {
loaders: {inlineMarkdownLinkFileLoader},
} = getFileLoaderUtils();

type PluginOptions = {
export type PluginOptions = {
staticDirs: string[];
siteDir: string;
};
Expand Down
12 changes: 10 additions & 2 deletions packages/docusaurus-migrate/src/deps.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@
* LICENSE file in the root directory of this source tree.
*/

declare module '@mapbox/hast-util-to-jsx';
declare module '@mapbox/hast-util-to-jsx' {
import type {Node} from 'unist';

declare module 'hast-util-to-string';
export default function toJsx(node: Node): string;
}

declare module 'hast-util-to-string' {
import type {Node} from 'unist';

export default function toString(node: Node): string;
}
Binary file modified packages/docusaurus-plugin-content-docs/src/__tests__/cli.test.ts
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {normalizeThemeConfig} from '@docusaurus/utils-validation';
import theme from 'prism-react-renderer/themes/github';
import darkTheme from 'prism-react-renderer/themes/dracula';
import {ThemeConfigSchema, DEFAULT_CONFIG} from '../validateThemeConfig';
import type {ThemeConfig} from '@docusaurus/theme-common';

function testValidateThemeConfig(partialThemeConfig: {[key: string]: unknown}) {
return normalizeThemeConfig(ThemeConfigSchema, {
Expand Down Expand Up @@ -656,7 +657,7 @@ describe('themeConfig', () => {
});

describe('color mode config', () => {
const withDefaultValues = (colorMode) =>
const withDefaultValues = (colorMode: ThemeConfig['colorMode']) =>
_.merge({}, DEFAULT_CONFIG.colorMode, colorMode);

it('switch config', () => {
Expand Down
Loading

0 comments on commit 3666a2e

Please sign in to comment.