Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: jsx-coercion #876

Merged
merged 9 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions __tests__/matchers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { expect } from 'vitest';
import { map } from 'unist-util-map';

const removePosition = ({ position, ...node }) => node;

function toStrictEqualExceptPosition(received, expected) {
kellyjosephprice marked this conversation as resolved.
Show resolved Hide resolved
const { equals } = this;
const receivedTrimmed = map(received, removePosition);
const expectedTrimmed = map(expected, removePosition);

return {
pass: equals(receivedTrimmed, expectedTrimmed),
message: () => 'Expected two trees to be equal!',
actual: receivedTrimmed,
expected: expectedTrimmed,
};
}

expect.extend({ toStrictEqualExceptPosition });
24 changes: 4 additions & 20 deletions __tests__/transformers/code-tabs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,26 +44,10 @@ Second code block
`;
const ast = mdast(md);

expect(ast.children[0].children[0].data).toMatchInlineSnapshot(`
{
"hName": "Code",
"hProperties": {
"lang": "javascript",
"meta": "First Title",
"value": "First code block",
},
}
`);
expect(ast.children[0].children[1].data).toMatchInlineSnapshot(`
{
"hName": "Code",
"hProperties": {
"lang": "text",
"meta": null,
"value": "Second code block",
},
}
`);
expect(ast.children[0].children[0]).toStrictEqual(
expect.objectContaining({ lang: 'javascript', meta: 'First Title' }),
);
expect(ast.children[0].children[1]).toStrictEqual(expect.objectContaining({ lang: 'text', meta: null }));
});

it('wraps single code blocks with tabs if they have a lang set', () => {
Expand Down
85 changes: 85 additions & 0 deletions __tests__/transformers/readme-components.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { mdast } from '../../index';

describe('Readme Components Transformer', () => {
const nodes = [
{ md: '<Callout />', type: 'rdme-callout' },
{ md: '<Code />', type: 'code' },
{ md: '<CodeTabs />', type: 'code-tabs' },
{ md: '<Image />', type: 'image' },
{ md: '<Table />', type: 'table' },
];

it.each(nodes)('transforms $md into a(n) $type node', ({ md, type }) => {
const tree = mdast(md);

expect(tree.children[0].type).toBe(type);
});

const docs = {
['rdme-callout']: {
md: `> 📘 It works!`,
mdx: `<Callout icon="📘" heading="It works!" />`,
},
code: {
md: `
~~~
This is a code block
~~~
`,
mdx: `<Code value="This is a code block" />`,
},
['code-tabs']: {
md: `
~~~
First
~~~
~~~
Second
~~~
`,
mdx: `
<CodeTabs>
<Code value='First' />
<Code value='Second' />
</CodeTabs>
`,
},
image: {
md: `![](http://placekitten.com/600/200)`,
mdx: `<Image src="http://placekitten.com/600/200" />`,
},
table: {
md: `
| h1 | h2 |
| --- | --- |
| a1 | a2 |
`,
// @todo there's text nodes that get inserted between the td's. Pretty sure
// they'd get filtered out by rehype, but lets keep the tests easy.
mdx: `
<Table>
<tr>
<td>h1</td><td>h2</td>
</tr>
<tr>
<td>a1</td><td>a2</td>
</tr>
</Table>
`,
},
};
it.each(Object.entries(docs))('matches the equivalent markdown for %s', (type, { md, mdx }) => {
let mdTree = mdast(md);
const mdxTree = mdast(mdx);

if (type === 'image') {
// @todo something about these dang paragraphs!
mdTree = {
type: 'root',
children: mdTree.children[0].children,
};
}

expect(mdxTree).toStrictEqualExceptPosition(mdTree);
});
});
21 changes: 19 additions & 2 deletions components/Callout/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,29 @@ import * as React from 'react';
interface Props extends React.PropsWithChildren<React.HTMLAttributes<HTMLQuoteElement>> {
attributes: {};
icon: string;
theme: string;
theme?: string;
heading?: React.ReactElement;
}

const themes: Record<string, string> = {
'\uD83D\uDCD8': 'info',
'\uD83D\uDEA7': 'warn',
'\u26A0\uFE0F': 'warn',
'\uD83D\uDC4D': 'okay',
'\u2705': 'okay',
'\u2757\uFE0F': 'error',
'\u2757': 'error',
'\uD83D\uDED1': 'error',
'\u2049\uFE0F': 'error',
'\u203C\uFE0F': 'error',
'\u2139\uFE0F': 'info',
'\u26A0': 'warn',
};

const Callout = (props: Props) => {
const { attributes, children, theme, icon, heading } = props;
const { attributes, children, icon, heading } = props;

let theme = props.theme || themes[icon] || 'default';

return (
// @ts-ignore
Expand Down
2 changes: 1 addition & 1 deletion components/Code/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
let canonicalLanguage = _ => '';
if (typeof window !== 'undefined') {
// eslint-disable-next-line global-require
syntaxHighlighter = require('@readme/syntax-highlighter').default;

Check failure on line 11 in components/Code/index.tsx

View workflow job for this annotation

GitHub Actions / Bundle Watch

Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig.
// eslint-disable-next-line global-require
({ canonical: canonicalLanguage } = require('@readme/syntax-highlighter'));

Check failure on line 13 in components/Code/index.tsx

View workflow job for this annotation

GitHub Actions / Bundle Watch

Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig.
}

function CopyCode({ codeRef, rootClass = 'rdmd-code-copy', className = '' }) {
Expand Down Expand Up @@ -52,7 +52,7 @@
dark: theme === 'dark',
};

const code = value ?? children?.[0] ?? children ?? '';
const code = value ?? (Array.isArray(children) ? children[0] : children) ?? '';
const highlightedCode = syntaxHighlighter && code ? syntaxHighlighter(code, language, codeOpts) : code;

return (
Expand Down
6 changes: 4 additions & 2 deletions index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import BaseUrlContext from './contexts/BaseUrl';
import { options } from './options';

import transformers from './processor/transform';
import transformers, { readmeComponentsTransformer } from './processor/transform';
import compilers from './processor/compile';
import MdxSyntaxError from './errors/mdx-syntax-error';

Expand Down Expand Up @@ -46,6 +46,7 @@
...more,
...Components,
Variable,
code: Components.Code,
'code-tabs': Components.CodeTabs,
img: Components.Image,
table: Components.Table,
Expand Down Expand Up @@ -84,7 +85,7 @@
Fragment,
baseUrl: import.meta.url,
imports: { React },
useMDXComponents: makeUseMDXComponents(components),

Check failure on line 88 in index.tsx

View workflow job for this annotation

GitHub Actions / Bundle Watch

Type '() => { Variable: any; code: (props: Props) => React.JSX.Element; 'code-tabs': (props: any) => React.JSX.Element; img: (props: Props) => React.JSX.Element; ... 12 more ...; TableOfContents: any; }' is not assignable to type 'UseMdxComponents'.
...opts,
});

Expand All @@ -103,7 +104,8 @@
unimplemented('html export');
};

const astProcessor = (opts = {}) => remark().use(remarkMdx).use(remarkFrontmatter).use(remarkPlugins);
const astProcessor = (opts = {}) =>
remark().use(remarkMdx).use(remarkFrontmatter).use(remarkPlugins).use(readmeComponentsTransformer, {});

Check failure on line 108 in index.tsx

View workflow job for this annotation

GitHub Actions / Bundle Watch

Argument of type '[{}]' is not assignable to parameter of type '[boolean] | [{ components: any; }]'.

export const mdast: any = (text: string, opts = {}) => {
const processor = astProcessor(opts);
Expand Down
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "@readme/markdown",
"name": "@readme/mdx",
"description": "ReadMe's React-based Markdown parser",
"author": "Rafe Goldberg <[email protected]>",
"version": "6.75.0-beta.30",
Expand Down Expand Up @@ -111,6 +111,7 @@
"terser-webpack-plugin": "^5.3.7",
"ts-loader": "^9.4.2",
"typescript": "^5.4.5",
"unist-util-map": "^4.0.0",
"vitest": "^1.4.0",
"webpack": "^5.56.0",
"webpack-cli": "^5.0.1",
Expand Down
22 changes: 0 additions & 22 deletions processor/transform/callouts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,6 @@ import { Blockquote, BlockContent, Parent, DefinitionContent } from 'mdast';

const regex = `^(${emojiRegex().source}|⚠)(\\s+|$)`;

const themes: Record<string, string> = {
'\uD83D\uDCD8': 'info',
'\uD83D\uDEA7': 'warn',
'\u26A0\uFE0F': 'warn',
'\uD83D\uDC4D': 'okay',
'\u2705': 'okay',
'\u2757\uFE0F': 'error',
'\u2757': 'error',
'\uD83D\uDED1': 'error',
'\u2049\uFE0F': 'error',
'\u203C\uFE0F': 'error',
'\u2139\uFE0F': 'info',
'\u26A0': 'warn',
};

const toString = (node: Node): string => {
if ('value' in node && node.value) return node.value as string;
if ('children' in node && node.children) return (node.children as Node[]).map(child => toString(child)).join('');
return '';
};

interface Callout extends Parent {
type: 'rdme-callout';
children: Array<BlockContent | DefinitionContent>;
Expand All @@ -49,7 +28,6 @@ const calloutTransformer = () => {
hProperties: {
heading,
icon,
theme: themes[icon] || 'default',
},
};
}
Expand Down
1 change: 0 additions & 1 deletion processor/transform/code-tabs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ const codeTabs = () => tree => {
const { lang, meta, value } = node;

node.data = {
hName: 'Code',
hProperties: { lang, meta, value },
};
});
Expand Down
3 changes: 3 additions & 0 deletions processor/transform/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import calloutTransformer from './callouts';
import codeTabsTransfromer from './code-tabs';
import gemojiTransformer from './gemoji+';
import readmeComponentsTransformer from './readme-components';

export { readmeComponentsTransformer };

export default [calloutTransformer, codeTabsTransfromer, gemojiTransformer];
97 changes: 97 additions & 0 deletions processor/transform/readme-components.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { BlockContent, Paragraph, Root, TableRow } from 'mdast';
import { MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';

const types = {
Callout: 'rdme-callout',
Code: 'code',
CodeTabs: 'code-tabs',
Image: 'image',
Table: 'table',
tr: 'tableRow',
td: 'tableCell',
};

const attributes = (jsx: MdxJsxFlowElement) =>
jsx.attributes.reduce((memo, attr) => {
memo[attr.name] = attr.value;

Check failure on line 17 in processor/transform/readme-components.ts

View workflow job for this annotation

GitHub Actions / Bundle Watch

Property 'name' does not exist on type 'MdxJsxAttribute | MdxJsxExpressionAttribute'.
return memo;
}, {});

const readmeComponents =
({ components }) =>
(tree: Root) => {
visit(tree, ['mdxJsxFlowElement', 'mdxJsxTextElement'], (node, index, parent) => {

Check failure on line 24 in processor/transform/readme-components.ts

View workflow job for this annotation

GitHub Actions / Bundle Watch

No overload matches this call.
if (node.name === 'Code') {

Check failure on line 25 in processor/transform/readme-components.ts

View workflow job for this annotation

GitHub Actions / Bundle Watch

Property 'name' does not exist on type 'Node<Data>'.
const { position } = node;
const { value, lang = null, meta = null } = attributes(node);

Check failure on line 27 in processor/transform/readme-components.ts

View workflow job for this annotation

GitHub Actions / Bundle Watch

Property 'value' does not exist on type '{}'.

Check failure on line 27 in processor/transform/readme-components.ts

View workflow job for this annotation

GitHub Actions / Bundle Watch

Property 'lang' does not exist on type '{}'.

const mdNode = {
lang,
meta,
position,
type: 'code',
value,
data: {
hProperties: { value, lang, meta },
},
};

parent.children[index] = mdNode;
} else if (node.name === 'Image') {
const { position } = node;
const { alt = '', src, title = null } = attributes(node);

const mdNode = {
alt,
position,
title,
type: 'image',
url: src,
};

parent.children[index] = mdNode;
} else if (node.name === 'Table') {
const { children, position } = node;
const { align = [...new Array(node.children.length)].map(() => null) } = attributes(node);

const mdNode = {
align,
type: 'table',
position,
children,
};

parent.children[index] = mdNode;
} else if (node.name in types) {
const hProperties = attributes(node);

const mdNode = {
children: node.children,
type: types[node.name],
...(['tr', 'td'].includes(node.name)
? {}
: {
data: {
hName: node.name,
...(Object.keys(hProperties).length ? { hProperties } : {}),
},
}),
position: node.position,
};

parent.children[index] = mdNode;
}
});

visit(tree, 'paragraph', (node: Paragraph, index: number, parent: BlockContent | TableRow) => {
if (parent.type !== 'tableRow') return;

// @ts-ignore
parent.children.splice(index, 1, ...node.children);
});

return tree;
};

export default readmeComponents;
Loading
Loading