Skip to content

Commit

Permalink
refactor: avoid using async-await in client module, fix ESLint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh-Cena committed Jun 7, 2022
1 parent bada5c1 commit ac892eb
Show file tree
Hide file tree
Showing 14 changed files with 204 additions and 247 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Expand Up @@ -191,6 +191,7 @@ module.exports = {
'no-template-curly-in-string': WARNING,
'no-unused-expressions': [WARNING, {allowTaggedTemplates: true}],
'no-useless-escape': WARNING,
'no-void': [ERROR, {allowAsStatement: true}],
'prefer-destructuring': WARNING,
'prefer-named-capture-group': WARNING,
'prefer-template': WARNING,
Expand Down
Expand Up @@ -70,7 +70,11 @@ const plugin: Plugin = function plugin(
}

const now = eat.now();
const [opening, keyword, title] = match;
const [opening, keyword, title] = match as string[] as [
string,
string,
string,
];
const food = [];
const content = [];

Expand Down Expand Up @@ -169,7 +173,7 @@ const plugin: Plugin = function plugin(
visit(
root,
(node: unknown): node is Literal =>
(node as Literal)?.type !== admonitionNodeType,
(node as Literal | undefined)?.type !== admonitionNodeType,
(node: Literal) => {
if (node.value) {
node.value = node.value.replace(escapeTag, options.tag);
Expand Down
28 changes: 17 additions & 11 deletions packages/docusaurus-mdx-loader/src/remark/transformImage/index.ts
Expand Up @@ -21,6 +21,7 @@ import visit from 'unist-util-visit';
import escapeHtml from 'escape-html';
import sizeOf from 'image-size';
import type {Transformer} from 'unified';
import type {Parent} from 'unist';
import type {Image, Literal} from 'mdast';

const {
Expand All @@ -36,12 +37,13 @@ type Context = PluginOptions & {
filePath: string;
};

type Target = [node: Image, index: number, parent: Parent];

async function toImageRequireNode(
node: Image,
[node, index, parent]: Target,
imagePath: string,
filePath: string,
) {
const jsxNode = node as Literal & Partial<Image>;
let relativeImagePath = posixPath(
path.relative(path.dirname(filePath), imagePath),
);
Expand Down Expand Up @@ -75,12 +77,12 @@ ${(err as Error).message}`;
}
}

Object.keys(jsxNode).forEach(
(key) => delete jsxNode[key as keyof typeof jsxNode],
);
const jsxNode: Literal = {
type: 'jsx',
value: `<img ${alt}src={${src}}${title}${width}${height} />`,
};

(jsxNode as Literal).type = 'jsx';
jsxNode.value = `<img ${alt}src={${src}}${title}${width}${height} />`;
parent.children.splice(index, 1, jsxNode);
}

async function ensureImageFileExist(imagePath: string, sourceFilePath: string) {
Expand Down Expand Up @@ -129,7 +131,8 @@ async function getImageAbsolutePath(
return imageFilePath;
}

async function processImageNode(node: Image, context: Context) {
async function processImageNode(target: Target, context: Context) {
const [node] = target;
if (!node.url) {
throw new Error(
`Markdown image URL is mandatory in "${toMessageRelativeFilePath(
Expand All @@ -151,15 +154,18 @@ async function processImageNode(node: Image, context: Context) {
// We try to convert image urls without protocol to images with require calls
// going through webpack ensures that image assets exist at build time
const imagePath = await getImageAbsolutePath(parsedUrl.pathname, context);
await toImageRequireNode(node, imagePath, context.filePath);
await toImageRequireNode(target, imagePath, context.filePath);
}

export default function plugin(options: PluginOptions): Transformer {
return async (root, vfile) => {
const promises: Promise<void>[] = [];
visit(root, 'image', (node: Image) => {
visit(root, 'image', (node: Image, index, parent) => {
promises.push(
processImageNode(node, {...options, filePath: vfile.path!}),
processImageNode([node, index, parent!], {
...options,
filePath: vfile.path!,
}),
);
});
await Promise.all(promises);
Expand Down
41 changes: 26 additions & 15 deletions packages/docusaurus-mdx-loader/src/remark/transformLinks/index.ts
Expand Up @@ -19,6 +19,7 @@ import visit from 'unist-util-visit';
import escapeHtml from 'escape-html';
import {stringifyContent} from '../utils';
import type {Transformer} from 'unified';
import type {Parent} from 'unist';
import type {Link, Literal} from 'mdast';

const {
Expand All @@ -34,16 +35,20 @@ type Context = PluginOptions & {
filePath: string;
};

type Target = [node: Link, index: number, parent: Parent];

/**
* Transforms the link node to a JSX `<a>` element with a `require()` call.
*/
function toAssetRequireNode(node: Link, assetPath: string, filePath: string) {
const jsxNode = node as Literal & Partial<Link>;
let relativeAssetPath = posixPath(
path.relative(path.dirname(filePath), assetPath),
);
function toAssetRequireNode(
[node, index, parent]: Target,
assetPath: string,
filePath: string,
) {
// require("assets/file.pdf") means requiring from a package called assets
relativeAssetPath = `./${relativeAssetPath}`;
const relativeAssetPath = `./${posixPath(
path.relative(path.dirname(filePath), assetPath),
)}`;

const parsedUrl = url.parse(node.url);
const hash = parsedUrl.hash ?? '';
Expand All @@ -60,12 +65,12 @@ function toAssetRequireNode(node: Link, assetPath: string, filePath: string) {
const children = stringifyContent(node);
const title = node.title ? ` title="${escapeHtml(node.title)}"` : '';

Object.keys(jsxNode).forEach(
(key) => delete jsxNode[key as keyof typeof jsxNode],
);
const jsxNode: Literal = {
type: 'jsx',
value: `<a target="_blank" href={${href}}${title}>${children}</a>`,
};

(jsxNode as Literal).type = 'jsx';
jsxNode.value = `<a target="_blank" href={${href}}${title}>${children}</a>`;
parent.children.splice(index, 1, jsxNode);
}

async function ensureAssetFileExist(assetPath: string, sourceFilePath: string) {
Expand Down Expand Up @@ -106,7 +111,8 @@ async function getAssetAbsolutePath(
return null;
}

async function processLinkNode(node: Link, context: Context) {
async function processLinkNode(target: Target, context: Context) {
const [node] = target;
if (!node.url) {
// Try to improve error feedback
// see https://github.com/facebook/docusaurus/issues/3309#issuecomment-690371675
Expand Down Expand Up @@ -138,15 +144,20 @@ async function processLinkNode(node: Link, context: Context) {
context,
);
if (assetPath) {
toAssetRequireNode(node, assetPath, context.filePath);
toAssetRequireNode(target, assetPath, context.filePath);
}
}

export default function plugin(options: PluginOptions): Transformer {
return async (root, vfile) => {
const promises: Promise<void>[] = [];
visit(root, 'link', (node: Link) => {
promises.push(processLinkNode(node, {...options, filePath: vfile.path!}));
visit(root, 'link', (node: Link, index, parent) => {
promises.push(
processLinkNode([node, index, parent!], {
...options,
filePath: vfile.path!,
}),
);
});
await Promise.all(promises);
};
Expand Down
8 changes: 4 additions & 4 deletions packages/docusaurus-migrate/bin/index.mjs
Expand Up @@ -34,19 +34,19 @@ cli
.option('--mdx', 'try to migrate MD to MDX too')
.option('--page', 'try to migrate pages too')
.description('Migrate between versions of Docusaurus website.')
.action((siteDir = '.', newDir = '.', {mdx, page} = {}) => {
.action(async (siteDir = '.', newDir = '.', {mdx, page} = {}) => {
const sitePath = path.resolve(siteDir);
const newSitePath = path.resolve(newDir);
migrateDocusaurusProject(sitePath, newSitePath, mdx, page);
await migrateDocusaurusProject(sitePath, newSitePath, mdx, page);
});

cli
.command('mdx [siteDir] [newDir]')
.description('Migrate markdown files to MDX.')
.action((siteDir = '.', newDir = '.') => {
.action(async (siteDir = '.', newDir = '.') => {
const sitePath = path.resolve(siteDir);
const newSitePath = path.resolve(newDir);
migrateMDToMDX(sitePath, newSitePath);
await migrateMDToMDX(sitePath, newSitePath);
});

cli.parse(process.argv);
Expand Down
Expand Up @@ -22,7 +22,7 @@ describe('getFileLastUpdate', () => {
const lastUpdateData = await getFileLastUpdate(existingFilePath);
expect(lastUpdateData).not.toBeNull();

const {author, timestamp} = lastUpdateData;
const {author, timestamp} = lastUpdateData!;
expect(author).not.toBeNull();
expect(typeof author).toBe('string');

Expand All @@ -38,7 +38,7 @@ describe('getFileLastUpdate', () => {
const lastUpdateData = await getFileLastUpdate(filePathWithSpace);
expect(lastUpdateData).not.toBeNull();

const {author, timestamp} = lastUpdateData;
const {author, timestamp} = lastUpdateData!;
expect(author).not.toBeNull();
expect(typeof author).toBe('string');

Expand All @@ -61,8 +61,6 @@ describe('getFileLastUpdate', () => {
expect(consoleMock).toHaveBeenLastCalledWith(
expect.stringMatching(/because the file does not exist./),
);
await expect(getFileLastUpdate(null)).resolves.toBeNull();
await expect(getFileLastUpdate(undefined)).resolves.toBeNull();
consoleMock.mockRestore();
});

Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-content-docs/src/lastUpdate.ts
Expand Up @@ -16,7 +16,7 @@ let showedGitRequirementError = false;
let showedFileNotTrackedError = false;

export async function getFileLastUpdate(
filePath?: string,
filePath: string,
): Promise<{timestamp: number; author: string} | null> {
if (!filePath) {
return null;
Expand Down

0 comments on commit ac892eb

Please sign in to comment.