[ci] yarn format

This commit is contained in:
natemoo-re 2021-05-17 14:30:21 +00:00 committed by GitHub Actions
parent b3886c206f
commit a2ae7018ca
20 changed files with 103 additions and 100 deletions

View file

@ -17,6 +17,7 @@ Astro treats any `.md` files inside of the `/src/pages` directory as pages. Thes
The only special Frontmatter key is `layout`, which defines the relative path to a `.astro` component which should wrap your Markdown content. The only special Frontmatter key is `layout`, which defines the relative path to a `.astro` component which should wrap your Markdown content.
`src/pages/index.md` `src/pages/index.md`
```md ```md
--- ---
layout: ../layouts/main.astro layout: ../layouts/main.astro
@ -30,6 +31,7 @@ Layout files are normal `.astro` components. Any Frontmatter defined in your `.m
The rendered Markdown content is placed into the default `<slot />` element. The rendered Markdown content is placed into the default `<slot />` element.
`src/layouts/main.astro` `src/layouts/main.astro`
```jsx ```jsx
--- ---
export let content; export let content;
@ -52,7 +54,7 @@ Similar to tools like [MDX](https://mdxjs.com/) or [MDsveX](https://github.com/p
Astro exposes a special `Markdown` component for `.astro` files which enables markdown syntax for its children **recursively**. Within the `Markdown` component you may also use plain HTML or any other type of component that is supported by Astro. Astro exposes a special `Markdown` component for `.astro` files which enables markdown syntax for its children **recursively**. Within the `Markdown` component you may also use plain HTML or any other type of component that is supported by Astro.
```jsx ````jsx
--- ---
// For now, this import _must_ be named "Markdown" and _must not_ be wrapped with a custom component // For now, this import _must_ be named "Markdown" and _must not_ be wrapped with a custom component
// We're working on easing these restrictions! // We're working on easing these restrictions!
@ -91,7 +93,7 @@ const expressions = 'Lorem ipsum';
</MyFancyCodePreview:visible> </MyFancyCodePreview:visible>
</Markdown> </Markdown>
</Layout> </Layout>
``` ````
### Remote Markdown ### Remote Markdown

View file

@ -1,5 +1,10 @@
import { h, Fragment } from 'preact'; import { h, Fragment } from 'preact';
export default function Yell({ children }) { export default function Yell({ children }) {
return children.filter(v => typeof v === 'string').join('').toUpperCase() + '!' return (
children
.filter((v) => typeof v === 'string')
.join('')
.toUpperCase() + '!'
);
} }

View file

@ -23,7 +23,7 @@ export default function codefence(parser: Parser) {
type: 'CodeFence', type: 'CodeFence',
raw: `${raw}` + trailingWhitespace, raw: `${raw}` + trailingWhitespace,
metadata, metadata,
data data,
}; };
parser.current().children.push(node); parser.current().children.push(node);

View file

@ -18,7 +18,10 @@ export default function codespan(parser: Parser) {
end: parser.index, end: parser.index,
type: 'CodeSpan', type: 'CodeSpan',
raw, raw,
data: raw?.slice(open?.length, open?.length * -1).replace(/^ /, '').replace(/ $/, '') data: raw
?.slice(open?.length, open?.length * -1)
.replace(/^ /, '')
.replace(/ $/, ''),
}; };
parser.current().children.push(node); parser.current().children.push(node);

View file

@ -306,7 +306,7 @@ interface CodegenState {
components: Components; components: Components;
css: string[]; css: string[];
markers: { markers: {
insideMarkdown: boolean|string; insideMarkdown: boolean | string;
}; };
importExportStatements: Set<string>; importExportStatements: Set<string>;
dynamicImports: DynamicImportMap; dynamicImports: DynamicImportMap;
@ -583,41 +583,41 @@ function compileHtml(enterNode: TemplateNode, state: CodegenState, compileOption
try { try {
const attributes = getAttributes(node.attributes); const attributes = getAttributes(node.attributes);
outSource += outSource === '' ? '' : ','; outSource += outSource === '' ? '' : ',';
if (node.type === 'Slot') { if (node.type === 'Slot') {
outSource += `(children`; outSource += `(children`;
return;
}
const COMPONENT_NAME_SCANNER = /^[A-Z]/;
if (!COMPONENT_NAME_SCANNER.test(name)) {
outSource += `h("${name}", ${attributes ? generateAttributes(attributes) : 'null'}`;
if (state.markers.insideMarkdown) {
outSource += `,h(__astroMarkdownRender, null`
}
return;
}
const [componentName, componentKind] = name.split(':');
const componentImportData = components[componentName];
if (!componentImportData) {
throw new Error(`Unknown Component: ${componentName}`);
}
if (componentImportData.type === '.astro') {
if (componentName === 'Markdown') {
const attributeStr = attributes ? generateAttributes(attributes) : 'null';
state.markers.insideMarkdown = attributeStr;
outSource += `h(__astroMarkdownRender, ${attributeStr}`
return; return;
} }
} const COMPONENT_NAME_SCANNER = /^[A-Z]/;
const { wrapper, wrapperImport } = getComponentWrapper(name, components[componentName], { astroConfig, dynamicImports, filename }); if (!COMPONENT_NAME_SCANNER.test(name)) {
if (wrapperImport) { outSource += `h("${name}", ${attributes ? generateAttributes(attributes) : 'null'}`;
importExportStatements.add(wrapperImport); if (state.markers.insideMarkdown) {
} outSource += `,h(__astroMarkdownRender, null`;
}
return;
}
const [componentName, componentKind] = name.split(':');
const componentImportData = components[componentName];
if (!componentImportData) {
throw new Error(`Unknown Component: ${componentName}`);
}
if (componentImportData.type === '.astro') {
if (componentName === 'Markdown') {
const attributeStr = attributes ? generateAttributes(attributes) : 'null';
state.markers.insideMarkdown = attributeStr;
outSource += `h(__astroMarkdownRender, ${attributeStr}`;
return;
}
}
const { wrapper, wrapperImport } = getComponentWrapper(name, components[componentName], { astroConfig, dynamicImports, filename });
if (wrapperImport) {
importExportStatements.add(wrapperImport);
}
outSource += `h(${wrapper}, ${attributes ? generateAttributes(attributes) : 'null'}`; outSource += `h(${wrapper}, ${attributes ? generateAttributes(attributes) : 'null'}`;
if (state.markers.insideMarkdown) { if (state.markers.insideMarkdown) {
const attributeStr = state.markers.insideMarkdown; const attributeStr = state.markers.insideMarkdown;
outSource += `,h(__astroMarkdownRender, ${attributeStr}` outSource += `,h(__astroMarkdownRender, ${attributeStr}`;
} }
} catch (err) { } catch (err) {
// handle errors in scope with filename // handle errors in scope with filename
@ -710,10 +710,10 @@ export async function codegen(ast: Ast, { compileOptions, filename }: CodeGenOpt
components: {}, components: {},
css: [], css: [],
markers: { markers: {
insideMarkdown: false insideMarkdown: false,
}, },
importExportStatements: new Set(), importExportStatements: new Set(),
dynamicImports: new Map() dynamicImports: new Map(),
}; };
const { script, componentPlugins, createCollection } = compileModule(ast.module, state, compileOptions); const { script, componentPlugins, createCollection } = compileModule(ast.module, state, compileOptions);

View file

@ -48,13 +48,17 @@ async function convertAstroToJsx(template: string, opts: ConvertAstroOptions): P
* .md -> .astro source * .md -> .astro source
*/ */
export async function convertMdToAstroSource(contents: string, { filename }: { filename: string }): Promise<string> { export async function convertMdToAstroSource(contents: string, { filename }: { filename: string }): Promise<string> {
const { content, frontmatter: { layout, ...frontmatter }, ...data } = await renderMarkdownWithFrontmatter(contents); const {
content,
frontmatter: { layout, ...frontmatter },
...data
} = await renderMarkdownWithFrontmatter(contents);
if (frontmatter['astro'] !== undefined) { if (frontmatter['astro'] !== undefined) {
throw new Error(`"astro" is a reserved word but was used as a frontmatter value!\n\tat ${filename}`); throw new Error(`"astro" is a reserved word but was used as a frontmatter value!\n\tat ${filename}`);
} }
const contentData: any = { const contentData: any = {
...frontmatter, ...frontmatter,
...data ...data,
}; };
// </script> can't be anywhere inside of a JS string, otherwise the HTML parser fails. // </script> can't be anywhere inside of a JS string, otherwise the HTML parser fails.
// Break it up here so that the HTML parser won't detect it. // Break it up here so that the HTML parser won't detect it.
@ -75,7 +79,7 @@ async function convertMdToJsx(
contents: string, contents: string,
{ compileOptions, filename, fileID }: { compileOptions: CompileOptions; filename: string; fileID: string } { compileOptions, filename, fileID }: { compileOptions: CompileOptions; filename: string; fileID: string }
): Promise<TransformResult> { ): Promise<TransformResult> {
const raw = await convertMdToAstroSource(contents, { filename }); const raw = await convertMdToAstroSource(contents, { filename });
const convertOptions = { compileOptions, filename, fileID }; const convertOptions = { compileOptions, filename, fileID };
return await convertAstroToJsx(raw, convertOptions); return await convertAstroToJsx(raw, convertOptions);
} }
@ -105,7 +109,7 @@ export async function compileComponent(
): Promise<CompileResult> { ): Promise<CompileResult> {
const result = await transformFromSource(source, { compileOptions, filename, projectRoot }); const result = await transformFromSource(source, { compileOptions, filename, projectRoot });
const site = compileOptions.astroConfig.buildOptions.site || `http://localhost:${compileOptions.astroConfig.devOptions.port}`; const site = compileOptions.astroConfig.buildOptions.site || `http://localhost:${compileOptions.astroConfig.devOptions.port}`;
const usesMarkdown = !!result.imports.find(spec => spec.indexOf('Markdown') > -1); const usesMarkdown = !!result.imports.find((spec) => spec.indexOf('Markdown') > -1);
// return template // return template
let modJsx = ` let modJsx = `

View file

@ -7,7 +7,7 @@ export default function createCollectHeaders() {
const visitor = (node: any) => { const visitor = (node: any) => {
if (node.type !== 'element') return; if (node.type !== 'element') return;
const { tagName, children } = node const { tagName, children } = node;
if (tagName[0] !== 'h') return; if (tagName[0] !== 'h') return;
let [_, depth] = tagName.match(/h([0-6])/) ?? []; let [_, depth] = tagName.match(/h([0-6])/) ?? [];
if (!depth) return; if (!depth) return;
@ -16,7 +16,7 @@ export default function createCollectHeaders() {
let text = ''; let text = '';
visit(node, 'text', (child) => { visit(node, 'text', (child) => {
text += child.value; text += child.value;
}) });
let slug = slugger.slug(text); let slug = slugger.slug(text);
node.properties = node.properties || {}; node.properties = node.properties || {};
@ -24,7 +24,7 @@ export default function createCollectHeaders() {
headers.push({ depth, slug, text }); headers.push({ depth, slug, text });
return node; return node;
} };
return { headers, rehypeCollectHeaders: () => (tree: any) => visit(tree, visitor) } return { headers, rehypeCollectHeaders: () => (tree: any) => visit(tree, visitor) };
} }

View file

@ -2,24 +2,24 @@ import fromMarkdown from 'mdast-util-mdx/from-markdown.js';
import toMarkdown from 'mdast-util-mdx/to-markdown.js'; import toMarkdown from 'mdast-util-mdx/to-markdown.js';
/** See https://github.com/micromark/micromark-extension-mdx-md */ /** See https://github.com/micromark/micromark-extension-mdx-md */
const syntax = { disable: {null: ['autolink', 'codeIndented']} }; const syntax = { disable: { null: ['autolink', 'codeIndented'] } };
/** /**
* Lite version of https://github.com/mdx-js/mdx/tree/main/packages/remark-mdx * Lite version of https://github.com/mdx-js/mdx/tree/main/packages/remark-mdx
* We don't need all the features MDX does because all components are precompiled * We don't need all the features MDX does because all components are precompiled
* to HTML. We just want to disable a few MD features that cause issues. * to HTML. We just want to disable a few MD features that cause issues.
*/ */
function mdxLite (this: any) { function mdxLite(this: any) {
let data = this.data() let data = this.data();
add('micromarkExtensions', syntax); add('micromarkExtensions', syntax);
add('fromMarkdownExtensions', fromMarkdown) add('fromMarkdownExtensions', fromMarkdown);
add('toMarkdownExtensions', toMarkdown) add('toMarkdownExtensions', toMarkdown);
/** Adds remark plugin */ /** Adds remark plugin */
function add(field: string, value: any) { function add(field: string, value: any) {
if (data[field]) data[field].push(value) if (data[field]) data[field].push(value);
else data[field] = [value] else data[field] = [value];
} }
} }

View file

@ -6,13 +6,13 @@ export default function scopedStyles(className: string) {
const visitor = (node: any) => { const visitor = (node: any) => {
if (noVisit.has(node.type)) return; if (noVisit.has(node.type)) return;
const {data} = node const { data } = node;
const currentClassName = data?.hProperties?.class ?? ''; const currentClassName = data?.hProperties?.class ?? '';
node.data = node.data || {}; node.data = node.data || {};
node.data.hProperties = node.data.hProperties || {}; node.data.hProperties = node.data.hProperties || {};
node.data.hProperties.className = `${className} ${currentClassName}`.trim(); node.data.hProperties.className = `${className} ${currentClassName}`.trim();
return node; return node;
} };
return () => (tree: any) => visit(tree, visitor); return () => (tree: any) => visit(tree, visitor);
} }

View file

@ -214,7 +214,7 @@ export default function transformStyles({ compileOptions, filename, fileID }: Tr
enter(node) { enter(node) {
if (node.name !== 'Markdown') return; if (node.name !== 'Markdown') return;
injectScopedClassAttribute(node, scopedClass, '$scope'); injectScopedClassAttribute(node, scopedClass, '$scope');
} },
}, },
Element: { Element: {
enter(node) { enter(node) {

View file

@ -18,13 +18,10 @@ export interface MarkdownRenderingOptions {
} }
/** Internal utility for rendering a full markdown file and extracting Frontmatter data */ /** Internal utility for rendering a full markdown file and extracting Frontmatter data */
export async function renderMarkdownWithFrontmatter(contents: string, opts?: MarkdownRenderingOptions|null) { export async function renderMarkdownWithFrontmatter(contents: string, opts?: MarkdownRenderingOptions | null) {
// Dynamic import to ensure that "gray-matter" isn't built by Snowpack // Dynamic import to ensure that "gray-matter" isn't built by Snowpack
const { default: matter } = await import('gray-matter'); const { default: matter } = await import('gray-matter');
const { const { data: frontmatter, content } = matter(contents);
data: frontmatter,
content,
} = matter(contents);
const value = await renderMarkdown(content, opts); const value = await renderMarkdown(content, opts);
return { ...value, frontmatter }; return { ...value, frontmatter };
} }
@ -41,12 +38,12 @@ export async function renderMarkdown(content: string, opts?: MarkdownRenderingOp
} }
if (useGfm) { if (useGfm) {
const {default:gfm} = await import('remark-gfm'); const { default: gfm } = await import('remark-gfm');
parser = parser.use(gfm); parser = parser.use(gfm);
} }
if (useFootnotes) { if (useFootnotes) {
const {default:footnotes} = await import('remark-footnotes'); const { default: footnotes } = await import('remark-footnotes');
parser = parser.use(footnotes); parser = parser.use(footnotes);
} }

View file

@ -1,14 +1,14 @@
import { renderMarkdown } from '../compiler/utils.js'; import { renderMarkdown } from '../compiler/utils.js';
/** /**
* Functional component which uses Astro's built-in Markdown rendering * Functional component which uses Astro's built-in Markdown rendering
* to render out its children. * to render out its children.
* *
* Note: the children have already been properly escaped/rendered * Note: the children have already been properly escaped/rendered
* by the parser and Astro, so at this point we're just rendering * by the parser and Astro, so at this point we're just rendering
* out plain markdown, no need for JSX support * out plain markdown, no need for JSX support
*/ */
export default async function Markdown(props: { $scope: string|null }, ...children: string[]): Promise<string> { export default async function Markdown(props: { $scope: string | null }, ...children: string[]): Promise<string> {
const { $scope = null } = props ?? {}; const { $scope = null } = props ?? {};
const text = dedent(children.join('').trimEnd()); const text = dedent(children.join('').trimEnd());
let { content } = await renderMarkdown(text, { $: { scopedClassName: $scope } }); let { content } = await renderMarkdown(text, { $: { scopedClassName: $scope } });
@ -21,6 +21,6 @@ export default async function Markdown(props: { $scope: string|null }, ...childr
/** Remove leading indentation based on first line */ /** Remove leading indentation based on first line */
function dedent(str: string) { function dedent(str: string) {
let arr = str.match(/^[ \t]*(?=\S)/gm); let arr = str.match(/^[ \t]*(?=\S)/gm);
let first = !!arr && arr.find(x => x.length > 0)?.length; let first = !!arr && arr.find((x) => x.length > 0)?.length;
return (!arr || !first) ? str : str.replace(new RegExp(`^[ \\t]{0,${first}}`, 'gm'), ''); return !arr || !first ? str : str.replace(new RegExp(`^[ \\t]{0,${first}}`, 'gm'), '');
} }

View file

@ -39,11 +39,11 @@ export function createRenderer(renderer: SupportedComponentRenderer) {
const script = `${typeof wrapperStart === 'function' ? wrapperStart(innerContext) : wrapperStart} const script = `${typeof wrapperStart === 'function' ? wrapperStart(innerContext) : wrapperStart}
${_imports(renderContext)} ${_imports(renderContext)}
${renderer.render({ ${renderer.render({
...innerContext, ...innerContext,
props: serializeProps(props), props: serializeProps(props),
children: `[${childrenToH(renderer, children) ?? ''}]`, children: `[${childrenToH(renderer, children) ?? ''}]`,
childrenAsString: `\`${children}\``, childrenAsString: `\`${children}\``,
})} })}
${typeof wrapperEnd === 'function' ? wrapperEnd(innerContext) : wrapperEnd}`; ${typeof wrapperEnd === 'function' ? wrapperEnd(innerContext) : wrapperEnd}`;
return [value, `<script type="module">${script.trim()}</script>`].join('\n'); return [value, `<script type="module">${script.trim()}</script>`].join('\n');

View file

@ -42,7 +42,7 @@ export const childrenToH = moize.deep(function childrenToH(renderer: ComponentRe
const simpleTypes = new Set(['number', 'boolean']); const simpleTypes = new Set(['number', 'boolean']);
const serializeChild = (child: unknown) => { const serializeChild = (child: unknown) => {
if (typeof child === 'string') return JSON.stringify(child).replace(/<\/script>/gmi, '</script" + ">'); if (typeof child === 'string') return JSON.stringify(child).replace(/<\/script>/gim, '</script" + ">');
if (simpleTypes.has(typeof child)) return JSON.stringify(child); if (simpleTypes.has(typeof child)) return JSON.stringify(child);
if (child === null) return `null`; if (child === null) return `null`;
if ((child as any).__SERIALIZED) return (child as any).__SERIALIZED; if ((child as any).__SERIALIZED) return (child as any).__SERIALIZED;

View file

@ -314,11 +314,7 @@ async function createSnowpack(astroConfig: AstroConfig, options: CreateSnowpackO
}, },
packageOptions: { packageOptions: {
knownEntrypoints: ['preact-render-to-string'], knownEntrypoints: ['preact-render-to-string'],
external: [ external: ['@vue/server-renderer', 'node-fetch', 'prismjs/components/index.js'],
'@vue/server-renderer',
'node-fetch',
'prismjs/components/index.js'
],
}, },
}); });

View file

@ -45,7 +45,7 @@ export function searchForPage(url: URL, astroRoot: URL): SearchResult {
// Try to find index.astro/md paths // Try to find index.astro/md paths
if (reqPath.endsWith('/')) { if (reqPath.endsWith('/')) {
const candidates = [`${base}index.astro`, `${base}index.md`,]; const candidates = [`${base}index.astro`, `${base}index.md`];
const location = findAnyPage(candidates, astroRoot); const location = findAnyPage(candidates, astroRoot);
if (location) { if (location) {
return { return {

View file

@ -8,7 +8,6 @@ const Markdown = suite('Astro Markdown tests');
setup(Markdown, './fixtures/astro-markdown'); setup(Markdown, './fixtures/astro-markdown');
setupBuild(Markdown, './fixtures/astro-markdown'); setupBuild(Markdown, './fixtures/astro-markdown');
Markdown('Can load markdown pages with Astro', async ({ runtime }) => { Markdown('Can load markdown pages with Astro', async ({ runtime }) => {
const result = await runtime.load('/post'); const result = await runtime.load('/post');
if (result.error) throw new Error(result.error); if (result.error) throw new Error(result.error);

View file

@ -34,5 +34,4 @@ Markdown('Builds markdown pages for prod', async (context) => {
await context.build(); await context.build();
}); });
Markdown.run(); Markdown.run();

View file

@ -16,13 +16,11 @@
{ "open": "'", "close": "'" }, { "open": "'", "close": "'" },
{ "open": "\"", "close": "\"" }, { "open": "\"", "close": "\"" },
{ {
"open": "<", "open": "<",
"close": ">", "close": ">",
"notIn": [ "notIn": ["string"]
"string" },
] { "open": "<!--", "close": "-->", "notIn": ["comment", "string"] }
},
{ "open": "<!--", "close": "-->", "notIn": ["comment", "string"] },
], ],
"autoCloseBefore": ";:.,=}])>` \n\t", "autoCloseBefore": ";:.,=}])>` \n\t",
"surroundingPairs": [ "surroundingPairs": [