another pass at head/body handling in pages

This commit is contained in:
Fred K. Schott 2021-03-21 20:34:11 -07:00
parent e03afbd980
commit 6e4367fd49
16 changed files with 374 additions and 442 deletions

View file

@ -12,7 +12,7 @@
} }
</script> </script>
<slot:head> <astro:head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" /> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png" /> <link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png" />
@ -42,13 +42,8 @@
<!-- Global Stylesheets --> <!-- Global Stylesheets -->
<link rel="stylesheet" href="/css/app.css" /> <link rel="stylesheet" href="/css/app.css" />
<link href="https://fonts.googleapis.com/css2?family=Overpass:wght@400;700;900&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=Overpass:wght@400;700;900&display=swap" rel="stylesheet" />
</astro:head>
<!-- Note: You can then add additional, custom things here as well. -->
<!-- if no slot given, assume add to bottom -->
<slot></slot>
</slot:head>
<slot:body>
<Banner></Banner> <Banner></Banner>
<Nav version={context.currentSnowpackVersion} /> <Nav version={context.currentSnowpackVersion} />
@ -65,4 +60,3 @@
gtag('js', new Date()); gtag('js', new Date());
gtag('config', 'UA-130280175-9', { page_path: location.pathname === '/' ? (location.pathname + location.hash) : (location.pathname) }); gtag('config', 'UA-130280175-9', { page_path: location.pathname === '/' ? (location.pathname + location.hash) : (location.pathname) });
</script> </script>
</slot:body>

View file

@ -8,7 +8,7 @@
} }
</script> </script>
<slot:head>
<style> <style>
.cover-wrapper { .cover-wrapper {
width: 100%; width: 100%;
@ -48,11 +48,6 @@
} }
</style> </style>
<slot></slot>
</slot:head>
<slot:body>
<div class="cover-wrapper"> <div class="cover-wrapper">
<img class="cover-blur" src={context.cover} alt=""/> <img class="cover-blur" src={context.cover} alt=""/>
<img class="cover" src={context.cover} alt=""/> <img class="cover" src={context.cover} alt=""/>
@ -81,4 +76,3 @@
<Subnav title={context.title} headers={context.content.headers} /> <Subnav title={context.title} headers={context.content.headers} />
</section> </section>
</div> </div>
</slot:body>

View file

@ -11,12 +11,6 @@
} }
</script> </script>
<slot:head>
<slot></slot>
</slot:head>
<slot:body>
<div class="container"> <div class="container">
<section class="snow-view__docs has-subnav"> <section class="snow-view__docs has-subnav">
@ -41,4 +35,3 @@
</section> </section>
</div> </div>
</slot:body>

View file

@ -6,13 +6,6 @@
} }
</script> </script>
<slot:head>
<!-- hi -->
<slot></slot>
</slot:head>
<slot:body>
<div class="container"> <div class="container">
<section class="snow-view__docs is-full"> <section class="snow-view__docs is-full">
@ -26,4 +19,3 @@
</section> </section>
</div> </div>
</slot:body>

View file

@ -6,8 +6,10 @@
} }
</script> </script>
<slot:head> <astro:head>
<link rel="stylesheet" href="/css/legacy-post.css" /> <link rel="stylesheet" href="/css/legacy-post.css" />
</astro:head>
<style> <style>
.markdown-body img, .markdown-body img,
.markdown-body video, .markdown-body video,
@ -99,14 +101,11 @@
} }
} }
</style> </style>
<slot></slot>
</slot:head>
<slot:body>
<div class="grid-extra-space"> <div class="grid-extra-space">
<div class="grid-body-header"> <div class="grid-body-header">
<svg height="80px" style="padding-left: 8px;" viewBox="0 0 640 512" version="1.1" <svg height="80px" style="padding-left: 8px;" viewBox="0 0 640 512" version="1.1" xmlns="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="Page-1" stroke="none" stroke-width="1" fill="currentColor" fill-rule="evenodd"> <g id="Page-1" stroke="none" stroke-width="1" fill="currentColor" fill-rule="evenodd">
<g id="mountain-solid" transform="translate(-1.000000, 0.000000)" fill-rule="nonzero"> <g id="mountain-solid" transform="translate(-1.000000, 0.000000)" fill-rule="nonzero">
<path <path
@ -128,8 +127,8 @@
<!-- Place this tag where you want the button to render. --> <!-- Place this tag where you want the button to render. -->
<div class="hidden-mobile" style="text-align: center; margin-top: 0.5rem; filter: scale(2);"> <div class="hidden-mobile" style="text-align: center; margin-top: 0.5rem; filter: scale(2);">
<a class="github-button" href="https://github.com/snowpackjs/snowpack" data-icon="octicon-star" <a class="github-button" href="https://github.com/snowpackjs/snowpack" data-icon="octicon-star" data-size="large"
data-size="large" data-show-count="true" aria-label="Star snowpackjs/snowpack on GitHub">Star</a> data-show-count="true" aria-label="Star snowpackjs/snowpack on GitHub">Star</a>
</div> </div>
<!-- Place this tag in your head or just before your close body tag. --> <!-- Place this tag in your head or just before your close body tag. -->
<script defer src="https://buttons.github.io/buttons.js"></script> <script defer src="https://buttons.github.io/buttons.js"></script>
@ -140,4 +139,3 @@
<slot></slot> <slot></slot>
</article> </article>
</div> </div>
</slot:body>

View file

@ -42,11 +42,6 @@
} }
</script> </script>
<slot:head>
</slot:head>
<slot:body>
<h2 class="content-title"> <h2 class="content-title">
{context.title} {context.title}
</h2> </h2>
@ -76,4 +71,3 @@
<Card item={post} />; <Card item={post} />;
})} })}
</div> </div>
</slot:body>

View file

@ -8,11 +8,9 @@
} }
</script> </script>
<slot:head> <astro:head>
<meta charset="AAA" /> <meta charset="AAA" />
</slot:head> </astro:head>
<slot:body>
<Hero bar={context.title}></Hero> <Hero bar={context.title}></Hero>
<div foo={context.title} class="container" style="margin: 0 auto"> <div foo={context.title} class="container" style="margin: 0 auto">
@ -25,8 +23,7 @@
<article class="snow-view-main"> <article class="snow-view-main">
<div class="content"> <div class="content">
<article class="grid-body"> <article class="grid-body">
<a class="img-banner" href="https://osawards.com/javascript/2020" target="_blank" <a class="img-banner" href="https://osawards.com/javascript/2020" target="_blank" rel="noopener noreferrer">
rel="noopener noreferrer">
<img src="/img/JSAwardWinner.png" alt="2020 JavaScript Open Source Award Winner banner" /> <img src="/img/JSAwardWinner.png" alt="2020 JavaScript Open Source Award Winner banner" />
</a> </a>
@ -94,4 +91,3 @@
<!-- Place this tag in your head or just before your close body tag. --> <!-- Place this tag in your head or just before your close body tag. -->
<script async="async" defer="defer" src="https://buttons.github.io/buttons.js"></script> <script async="async" defer="defer" src="https://buttons.github.io/buttons.js"></script>
</slot:body>

View file

@ -25,9 +25,6 @@
} }
</script> </script>
<slot:head> </slot:head>
<slot:body>
<NewsTitle title={context.title} /> <NewsTitle title={context.title} />
<p> <p>
@ -79,4 +76,3 @@
<NewsAssets /> <NewsAssets />
</div> </div>
</slot:body>

View file

@ -13,10 +13,6 @@
} }
</script> </script>
<slot:head>
</slot:head>
<slot:body>
<h2 class="content-title"> <h2 class="content-title">
{ context.title } { context.title }
</h2> </h2>
@ -28,4 +24,3 @@
</p> </p>
<PluginSearchPage:dynamic /> <PluginSearchPage:dynamic />
</slot:body>

View file

@ -18,7 +18,6 @@ export interface JsxItem {
export interface TransformResult { export interface TransformResult {
script: string; script: string;
head: JsxItem | undefined; head: JsxItem | undefined;
body: JsxItem | undefined;
items: JsxItem[]; items: JsxItem[];
} }

View file

@ -189,9 +189,7 @@ export async function codegen(ast: Ast, { compileOptions }: CodeGenOptions): Pro
const additionalImports = new Set<string>(); const additionalImports = new Set<string>();
let headItem: JsxItem | undefined; let headItem: JsxItem | undefined;
let bodyItem: JsxItem | undefined;
let items: JsxItem[] = []; let items: JsxItem[] = [];
let mode: 'JSX' | 'SCRIPT' | 'SLOT' = 'JSX';
let collectionItem: JsxItem | undefined; let collectionItem: JsxItem | undefined;
let currentItemName: string | undefined; let currentItemName: string | undefined;
let currentDepth = 0; let currentDepth = 0;
@ -225,10 +223,6 @@ export async function codegen(ast: Ast, { compileOptions }: CodeGenOptions): Pro
} }
collectionItem!.jsx += `,(${code.trim().replace(/\;$/, '')})`; collectionItem!.jsx += `,(${code.trim().replace(/\;$/, '')})`;
return; return;
case 'Slot':
mode = 'SLOT';
collectionItem!.jsx += `,child`;
return;
case 'Comment': case 'Comment':
return; return;
case 'Fragment': case 'Fragment':
@ -239,8 +233,8 @@ export async function codegen(ast: Ast, { compileOptions }: CodeGenOptions): Pro
} }
break; break;
case 'Slot':
case 'Head': case 'Head':
case 'Body':
case 'InlineComponent': case 'InlineComponent':
case 'Title': case 'Title':
case 'Element': { case 'Element': {
@ -251,7 +245,6 @@ export async function codegen(ast: Ast, { compileOptions }: CodeGenOptions): Pro
const attributes = getAttributes(node.attributes); const attributes = getAttributes(node.attributes);
currentDepth++; currentDepth++;
currentItemName = name; currentItemName = name;
if (!collectionItem) { if (!collectionItem) {
collectionItem = { name, jsx: '' }; collectionItem = { name, jsx: '' };
if (node.type === 'Head') { if (node.type === 'Head') {
@ -259,14 +252,13 @@ export async function codegen(ast: Ast, { compileOptions }: CodeGenOptions): Pro
headItem = collectionItem; headItem = collectionItem;
return; return;
} }
if (node.type === 'Body') {
collectionItem.jsx += `h(Fragment, null`;
bodyItem = collectionItem;
return;
}
items.push(collectionItem); items.push(collectionItem);
} }
collectionItem.jsx += collectionItem.jsx === '' ? '' : ','; collectionItem.jsx += collectionItem.jsx === '' ? '' : ',';
if (node.type === 'Slot') {
collectionItem.jsx += `(children`;
return;
}
const COMPONENT_NAME_SCANNER = /^[A-Z]/; const COMPONENT_NAME_SCANNER = /^[A-Z]/;
if (!COMPONENT_NAME_SCANNER.test(name)) { if (!COMPONENT_NAME_SCANNER.test(name)) {
collectionItem.jsx += `h("${name}", ${attributes ? generateAttributes(attributes) : 'null'}`; collectionItem.jsx += `h("${name}", ${attributes ? generateAttributes(attributes) : 'null'}`;
@ -296,9 +288,6 @@ export async function codegen(ast: Ast, { compileOptions }: CodeGenOptions): Pro
} }
case 'Text': { case 'Text': {
const text = getTextFromAttribute(node); const text = getTextFromAttribute(node);
if (mode === 'SLOT') {
return;
}
if (!text.trim()) { if (!text.trim()) {
return; return;
} }
@ -323,17 +312,11 @@ export async function codegen(ast: Ast, { compileOptions }: CodeGenOptions): Pro
case 'Attribute': case 'Attribute':
case 'Comment': case 'Comment':
return; return;
case 'Slot': {
const name = node.name;
if (name === 'slot') {
mode = 'JSX';
}
return;
}
case 'Fragment': case 'Fragment':
if (!collectionItem) { if (!collectionItem) {
return; return;
} }
case 'Slot':
case 'Head': case 'Head':
case 'Body': case 'Body':
case 'Title': case 'Title':
@ -360,7 +343,6 @@ export async function codegen(ast: Ast, { compileOptions }: CodeGenOptions): Pro
return { return {
script: script + '\n' + Array.from(additionalImports).join('\n'), script: script + '\n' + Array.from(additionalImports).join('\n'),
head: headItem, head: headItem,
body: bodyItem,
items, items,
}; };
} }

View file

@ -14,8 +14,8 @@ import list from '../../utils/list.js';
const valid_tag_name = /^\!?[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/; const valid_tag_name = /^\!?[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/;
const meta_tags = new Map([ const meta_tags = new Map([
['slot:head', 'Head'], ['astro:head', 'Head'],
['slot:body', 'Body'], // ['slot:body', 'Body'],
// ['astro:options', 'Options'], // ['astro:options', 'Options'],
// ['astro:window', 'Window'], // ['astro:window', 'Window'],
// ['astro:body', 'Body'], // ['astro:body', 'Body'],

View file

@ -134,7 +134,7 @@ export default function ({ filename, fileID }: { filename: string; fileID: strin
const code = node.content.styles; const code = node.content.styles;
const typeAttr = (node.attributes || []).find(({ name }: { name: string }) => name === 'type'); const typeAttr = (node.attributes || []).find(({ name }: { name: string }) => name === 'type');
styleNodes.push(node); styleNodes.push(node);
styleTransformPromises.push(transformStyle(code, { type: (typeAttr.value[0] && typeAttr.value[0].raw) || undefined, filename, fileID })); styleTransformPromises.push(transformStyle(code, { type: (typeAttr && typeAttr.value[0] && typeAttr.value[0].raw) || undefined, filename, fileID }));
// TODO: we should delete the old untransformed <style> node after were done. // TODO: we should delete the old untransformed <style> node after were done.
// However, the svelte parser left it in ast.css, not ast.html. At the final step, this just gets ignored, so it will be deleted, in a sense. // However, the svelte parser left it in ast.css, not ast.html. At the final step, this just gets ignored, so it will be deleted, in a sense.

View file

@ -78,7 +78,7 @@ async function convertMdToJsx(
export function setup({context}) { export function setup({context}) {
return {context: ${stringifiedSetupContext} }; return {context: ${stringifiedSetupContext} };
} }
</script><slot:head></slot:head><slot:body><section>{${JSON.stringify(mdHtml)}}</section></slot:body>`, </script><section>{${JSON.stringify(mdHtml)}}</section>`,
{ compileOptions, filename, fileID } { compileOptions, filename, fileID }
); );
} }
@ -104,9 +104,7 @@ export async function compileComponent(
): Promise<CompileResult> { ): Promise<CompileResult> {
const sourceJsx = await transformFromSource(source, { compileOptions, filename, projectRoot }); const sourceJsx = await transformFromSource(source, { compileOptions, filename, projectRoot });
const headItem = sourceJsx.head; const headItem = sourceJsx.head;
const bodyItem = sourceJsx.body;
const headItemJsx = !headItem ? 'null' : headItem.jsx; const headItemJsx = !headItem ? 'null' : headItem.jsx;
const bodyItemJsx = !bodyItem ? 'null' : bodyItem.jsx;
// sort <style> tags first // sort <style> tags first
// TODO: remove these and inject in <head> // TODO: remove these and inject in <head>
@ -120,23 +118,21 @@ ${sourceJsx.script}
// \`__render()\`: Render the contents of the HMX module. "<slot:*>" elements are not // \`__render()\`: Render the contents of the HMX module. "<slot:*>" elements are not
// included (see below). // included (see below).
import { h, Fragment } from '${internalImport('h.js')}'; import { h, Fragment } from '${internalImport('h.js')}';
export default function __render(props) { return h(Fragment, null, ${sourceJsx.items.map(({ jsx }) => jsx).join(',')}); } export function __slothead(children, context) { return h(Fragment, null, ${headItemJsx}); }
function __render(props, children, context) { return h(Fragment, null, ${sourceJsx.items.map(({ jsx }) => jsx).join(',')}); }
// <slot:*> render functions export default __render;
export function __slothead(context, child) { return h(Fragment, null, ${headItemJsx}); }
export function __slotbody(context, child) { return h(Fragment, null, ${bodyItemJsx}); }
`; `;
if (headItemJsx || bodyItemJsx) { if (headItemJsx) {
modJsx += ` modJsx += `
// \`__renderPage()\`: Render the contents of the HMX module as a page. This is a special flow, // \`__renderPage()\`: Render the contents of the HMX module as a page. This is a special flow,
// triggered by loading a component directly by URL. // triggered by loading a component directly by URL.
// If the page exports a defined "layout", then load + render those first. "context", "slot:head", // If the page exports a defined "layout", then load + render those first. "context", "astro:head",
// and "slot:body" should all inherit from parent layouts, merging together in the correct order. // and "slot:body" should all inherit from parent layouts, merging together in the correct order.
export async function __renderPage({request, children}) { export async function __renderPage({request, children}) {
const currentChild = { const currentChild = {
__slothead, __slothead,
__slotbody, __render,
setup: typeof setup === 'undefined' ? (passthrough) => passthrough : setup, setup: typeof setup === 'undefined' ? (passthrough) => passthrough : setup,
layout: typeof layout === 'undefined' ? undefined : layout, layout: typeof layout === 'undefined' ? undefined : layout,
}; };
@ -166,12 +162,12 @@ export async function __renderPage({request, children}) {
let headResult; let headResult;
let bodyResult; let bodyResult;
for (const child of children.reverse()) { for (const child of children.reverse()) {
headResult = await child.__slothead(mergedContext, headResult); headResult = await child.__slothead([headResult], mergedContext);
bodyResult = await child.__slotbody(mergedContext, bodyResult); bodyResult = await child.__render(undefined, [bodyResult], mergedContext);
} }
return h(Fragment, null, [ return h(Fragment, null, [
h("head", null, currentChild.__slothead(mergedContext, headResult)), h("head", null, currentChild.__slothead([headResult], mergedContext)),
h("body", null, currentChild.__slotbody(mergedContext, bodyResult)), h("body", null, currentChild.__render(undefined, [bodyResult], mergedContext)),
]); ]);
};\n`; };\n`;
} }

View file

@ -6,10 +6,8 @@
} }
</script> </script>
<slot:head> <astro:head>
<!-- Head Stuff --> <!-- Head Stuff -->
</slot:head> </astro:head>
<slot:body>
<h1>Hello world!</h1> <h1>Hello world!</h1>
</slot:body>

View file

@ -7,6 +7,9 @@ import { doc } from './test-utils.js';
const { readdir, stat } = fsPromises; const { readdir, stat } = fsPromises;
// Bug: Snowpack config is still loaded relative to the current working directory.
process.chdir(new URL('../examples/snowpack/', import.meta.url).pathname);
const SnowpackDev = suite('snowpack.dev'); const SnowpackDev = suite('snowpack.dev');
let runtime; let runtime;
@ -67,8 +70,10 @@ SnowpackDev('Can load every page', async () => {
assert.equal(result.statusCode, 200, `Loading ${pathname}`); assert.equal(result.statusCode, 200, `Loading ${pathname}`);
} }
if (failed.length > 0) {
console.error(failed); console.error(failed);
assert.equal(failed.length, 1, 'Failed pages (1 expected)'); }
assert.equal(failed.length, 0, 'Failed pages');
}); });
SnowpackDev.run(); SnowpackDev.run();