Skip to content

Commit

Permalink
[ci] format
Browse files Browse the repository at this point in the history
  • Loading branch information
natemoo-re authored and astrobot-houston committed Jun 30, 2022
1 parent 032ad1c commit af23bdd
Show file tree
Hide file tree
Showing 14 changed files with 95 additions and 99 deletions.
5 changes: 1 addition & 4 deletions examples/with-mdx/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,5 @@ import preact from '@astrojs/preact';

// https://astro.build/config
export default defineConfig({
integrations: [
mdx(),
preact()
]
integrations: [mdx(), preact()],
});
18 changes: 8 additions & 10 deletions examples/with-mdx/src/pages/index.mdx
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import Counter from '../components/Counter.jsx'
import Title from '../components/Title.astro'
export const components = { h1: Title }
import Counter from '../components/Counter.jsx';
import Title from '../components/Title.astro';
export const components = { h1: Title };

# Hello world!

export const authors = [
{name: 'Jane', email: 'hi@jane.com'},
{name: 'John', twitter: '@john2002'}
]
export const published = new Date('2022-02-01')
{ name: 'Jane', email: 'hi@jane.com' },
{ name: 'John', twitter: '@john2002' },
];
export const published = new Date('2022-02-01');

Written by: {new Intl.ListFormat('en').format(authors.map(d => d.name))}.

Published on: {new Intl.DateTimeFormat('en', {dateStyle: 'long'}).format(published)}.

<Counter client:idle>
## Counter
</Counter>
<Counter client:idle>## Counter</Counter>
7 changes: 4 additions & 3 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -939,9 +939,10 @@ export interface SSRLoadedRenderer extends AstroRenderer {
};
}

export type HookParameters<Hook extends keyof AstroIntegration['hooks'], Fn = AstroIntegration['hooks'][Hook]> = Fn extends (...args: any) => any
? Parameters<Fn>[0]
: never;
export type HookParameters<
Hook extends keyof AstroIntegration['hooks'],
Fn = AstroIntegration['hooks'][Hook]
> = Fn extends (...args: any) => any ? Parameters<Fn>[0] : never;

export interface AstroIntegration {
/** The name of the integration. */
Expand Down
4 changes: 1 addition & 3 deletions packages/astro/src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -346,9 +346,7 @@ export async function validateConfig(
adapter: undefined,
},
};
if (
result.integrations.find((integration) => integration.name === '@astrojs/mdx')
) {
if (result.integrations.find((integration) => integration.name === '@astrojs/mdx')) {
// Enable default JSX integration. It needs to come first, so unshift rather than push!
const { default: jsxRenderer } = await import('../jsx/renderer.js');
(result._ctx.renderers as any[]).unshift(jsxRenderer);
Expand Down
6 changes: 4 additions & 2 deletions packages/astro/src/core/create-vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,11 @@ function getPluginName(plugin: vite.PluginOption) {

function sortPlugins(result: ViteConfigWithSSR) {
// HACK: move mdxPlugin to top because it needs to run before internal JSX plugin
const mdxPluginIndex = result.plugins?.findIndex(plugin => getPluginName(plugin) === '@mdx-js/rollup') ?? -1;
const mdxPluginIndex =
result.plugins?.findIndex((plugin) => getPluginName(plugin) === '@mdx-js/rollup') ?? -1;
if (mdxPluginIndex === -1) return;
const jsxPluginIndex = result.plugins?.findIndex(plugin => getPluginName(plugin) === 'astro:jsx') ?? -1;
const jsxPluginIndex =
result.plugins?.findIndex((plugin) => getPluginName(plugin) === 'astro:jsx') ?? -1;
const mdxPlugin = result.plugins?.[mdxPluginIndex];
result.plugins?.splice(mdxPluginIndex, 1);
result.plugins?.splice(jsxPluginIndex, 0, mdxPlugin);
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/render/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type {
} from '../../@types/astro';
import type { LogOptions } from '../logger/core.js';

import { renderComponent, renderPage } from '../../runtime/server/index.js';
import { renderPage } from '../../runtime/server/index.js';
import { getParams } from '../routing/params.js';
import { createResult } from './result.js';
import { callGetStaticPaths, findPathItemByKey, RouteCache } from './route-cache.js';
Expand Down
6 changes: 2 additions & 4 deletions packages/astro/src/integrations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import type { AddressInfo } from 'net';
import type { ViteDevServer } from 'vite';
import {
AstroConfig,
HookParameters,
AstroRenderer,
BuildConfig,
HookParameters,
RouteData,
} from '../@types/astro.js';
import ssgAdapter from '../adapter-ssg/index.js';
Expand Down Expand Up @@ -58,9 +58,7 @@ export async function runHookConfigSetup({
};
// Semi-private `addPageExtension` hook
function addPageExtension(...input: (string | string[])[]) {
const exts = (input.flat(Infinity) as string[]).map(
(ext) => `.${ext.replace(/^\./, '')}`
);
const exts = (input.flat(Infinity) as string[]).map((ext) => `.${ext.replace(/^\./, '')}`);
updatedConfig._ctx.pageExtensions.push(...exts);
}
Object.defineProperty(hooks, 'addPageExtension', {
Expand Down
22 changes: 14 additions & 8 deletions packages/astro/src/runtime/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,7 @@ function formatList(values: string[]): string {
return `${values.slice(0, -1).join(', ')} or ${values[values.length - 1]}`;
}

const rendererAliases = new Map([
['solid', 'solid-js']
])
const rendererAliases = new Map([['solid', 'solid-js']]);

export async function renderComponent(
result: SSRResult,
Expand Down Expand Up @@ -283,7 +281,9 @@ Did you mean to add ${formatList(probableRendererNames.map((r) => '`' + r + '`')
// Attempt: use explicitly passed renderer name
if (metadata.hydrateArgs) {
const passedName = metadata.hydrateArgs;
const rendererName = rendererAliases.has(passedName) ? rendererAliases.get(passedName) : passedName;
const rendererName = rendererAliases.has(passedName)
? rendererAliases.get(passedName)
: passedName;
renderer = renderers.filter(
({ name }) => name === `@astrojs/${rendererName}` || name === rendererName
)[0];
Expand Down Expand Up @@ -709,16 +709,22 @@ export async function renderPage(
let iterable: AsyncIterable<any>;
if (!componentFactory.isAstroComponentFactory) {
const pageProps: Record<string, any> = { ...(props ?? {}), 'server:root': true };
const output = await renderComponent(result, componentFactory.name, componentFactory, pageProps, null);
let html = output.toString()
const output = await renderComponent(
result,
componentFactory.name,
componentFactory,
pageProps,
null
);
let html = output.toString();
if (!/<!doctype html/i.test(html)) {
html = `<!DOCTYPE html>\n${await maybeRenderHead(result)}${html}`;
}
return new Response(html, {
headers: new Headers([
['Content-Type', 'text/html; charset=utf-8'],
['Content-Length', `${Buffer.byteLength(html, 'utf-8')}`]
])
['Content-Length', `${Buffer.byteLength(html, 'utf-8')}`],
]),
});
}
const factoryReturnValue = await componentFactory(result, props, children);
Expand Down
7 changes: 5 additions & 2 deletions packages/astro/src/runtime/server/jsx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,16 @@ export async function renderJSX(result: any, vnode: any): Promise<any> {
let props: Record<string, any> = {};
let slots: Record<string, any> = {};
for (const [key, value] of Object.entries(vnode.props ?? {})) {
if (key === 'children' || value && typeof value === 'object' && (value as any)['$$slot']) {
if (
key === 'children' ||
(value && typeof value === 'object' && (value as any)['$$slot'])
) {
slots[key === 'children' ? 'default' : key] = () => renderJSX(result, value);
} else {
props[key] = value;
}
}
return await renderToString(result, vnode.type, props, slots)
return await renderToString(result, vnode.type, props, slots);
}
}
if (vnode[AstroJSX]) {
Expand Down
1 change: 0 additions & 1 deletion packages/astro/src/vite-plugin-jsx/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,6 @@ export default function jsx({ config, logging }: AstroPluginJSXOptions): Plugin
}
}


// if no imports were found, look for @jsxImportSource comment
if (!importSource) {
const multiline = code.match(/\/\*\*?[\S\s]*\*\//gm) || [];
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/test/test-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export async function loadFixture(inlineConfig) {
cwd = new URL(cwd.replace(/\/?$/, '/'), import.meta.url);
}
}

// Load the config.
let config = await loadConfig({ cwd: fileURLToPath(cwd) });
config = merge(config, { ...inlineConfig, root: cwd });
Expand All @@ -83,7 +83,7 @@ export async function loadFixture(inlineConfig) {
if (inlineConfig.base && !inlineConfig.base.endsWith('/')) {
config.base = inlineConfig.base + '/';
}
if (config.integrations.find(integration => integration.name === '@astrojs/mdx')) {
if (config.integrations.find((integration) => integration.name === '@astrojs/mdx')) {
// Enable default JSX integration. It needs to come first, so unshift rather than push!
const { default: jsxRenderer } = await import('astro/jsx/renderer.js');
config._ctx.renderers.unshift(jsxRenderer);
Expand Down
66 changes: 33 additions & 33 deletions packages/integrations/mdx/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,39 @@
import type { AstroIntegration } from 'astro';
import mdxPlugin from '@mdx-js/rollup';
import type { AstroIntegration } from 'astro';

export default function mdx(): AstroIntegration {
return {
name: '@astrojs/mdx',
hooks: {
'astro:config:setup': ({ updateConfig, addPageExtension, command }: any) => {
addPageExtension('.mdx');
updateConfig({
vite: {
plugins: [
{
enforce: 'pre',
...mdxPlugin({
jsx: true,
jsxImportSource: 'astro',
// Note: disable `.md` support
format: 'mdx',
mdExtensions: []
})
},
command === 'dev' && {
name: '@astrojs/mdx',
transform(code: string, id: string) {
if (!id.endsWith('.mdx')) return;
// TODO: decline HMR updates until we have a stable approach
return `${code}\nif (import.meta.hot) {
name: '@astrojs/mdx',
hooks: {
'astro:config:setup': ({ updateConfig, addPageExtension, command }: any) => {
addPageExtension('.mdx');
updateConfig({
vite: {
plugins: [
{
enforce: 'pre',
...mdxPlugin({
jsx: true,
jsxImportSource: 'astro',
// Note: disable `.md` support
format: 'mdx',
mdExtensions: [],
}),
},
command === 'dev' && {
name: '@astrojs/mdx',
transform(code: string, id: string) {
if (!id.endsWith('.mdx')) return;
// TODO: decline HMR updates until we have a stable approach
return `${code}\nif (import.meta.hot) {
import.meta.hot.decline();
}`
}
}
]
}
})
}
}
}
}`;
},
},
],
},
});
},
},
};
}
23 changes: 10 additions & 13 deletions packages/integrations/mdx/test/mdx-component.test.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
import mdx from '@astrojs/mdx';

import { expect } from 'chai';
import { parseHTML } from 'linkedom'
import { parseHTML } from 'linkedom';
import { loadFixture } from '../../../astro/test/test-utils.js';

describe('MDX Component', () => {
let fixture;

before(async () => {
fixture = await loadFixture({
fixture = await loadFixture({
root: new URL('./fixtures/mdx-component/', import.meta.url),
integrations: [
mdx()
]
integrations: [mdx()],
});
});

Expand All @@ -21,22 +19,21 @@ describe('MDX Component', () => {
await fixture.build();
});


it('works', async () => {
const html = await fixture.readFile('/index.html');
const { document } = parseHTML(html);

const h1 = document.querySelector('h1');
const foo = document.querySelector('#foo');

expect(h1.textContent).to.equal('Hello component!');
expect(foo.textContent).to.equal('bar');
});
})
});

describe('dev', () => {
let devServer;

before(async () => {
devServer = await fixture.startDevServer();
});
Expand All @@ -52,12 +49,12 @@ describe('MDX Component', () => {

const html = await res.text();
const { document } = parseHTML(html);

const h1 = document.querySelector('h1');
const foo = document.querySelector('#foo');

expect(h1.textContent).to.equal('Hello component!');
expect(foo.textContent).to.equal('bar');
});
})
})
});
});
Loading

0 comments on commit af23bdd

Please sign in to comment.