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>
<slot:head>
<astro:head>
<meta charset="utf-8" />
<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" />
@ -42,13 +42,8 @@
<!-- Global Stylesheets -->
<link rel="stylesheet" href="/css/app.css" />
<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>
<Nav version={context.currentSnowpackVersion} />
@ -65,4 +60,3 @@
gtag('js', new Date());
gtag('config', 'UA-130280175-9', { page_path: location.pathname === '/' ? (location.pathname + location.hash) : (location.pathname) });
</script>
</slot:body>

View file

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

View file

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

View file

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

View file

@ -6,8 +6,10 @@
}
</script>
<slot:head>
<astro:head>
<link rel="stylesheet" href="/css/legacy-post.css" />
</astro:head>
<style>
.markdown-body img,
.markdown-body video,
@ -99,14 +101,11 @@
}
}
</style>
<slot></slot>
</slot:head>
<slot:body>
<div class="grid-extra-space">
<div class="grid-body-header">
<svg height="80px" style="padding-left: 8px;" viewBox="0 0 640 512" version="1.1"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<svg height="80px" style="padding-left: 8px;" viewBox="0 0 640 512" version="1.1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<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">
<path
@ -128,8 +127,8 @@
<!-- 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);">
<a class="github-button" href="https://github.com/snowpackjs/snowpack" data-icon="octicon-star"
data-size="large" data-show-count="true" aria-label="Star snowpackjs/snowpack on GitHub">Star</a>
<a class="github-button" href="https://github.com/snowpackjs/snowpack" data-icon="octicon-star" data-size="large"
data-show-count="true" aria-label="Star snowpackjs/snowpack on GitHub">Star</a>
</div>
<!-- Place this tag in your head or just before your close body tag. -->
<script defer src="https://buttons.github.io/buttons.js"></script>
@ -140,4 +139,3 @@
<slot></slot>
</article>
</div>
</slot:body>

View file

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

View file

@ -8,11 +8,9 @@
}
</script>
<slot:head>
<astro:head>
<meta charset="AAA" />
</slot:head>
<slot:body>
</astro:head>
<Hero bar={context.title}></Hero>
<div foo={context.title} class="container" style="margin: 0 auto">
@ -25,8 +23,7 @@
<article class="snow-view-main">
<div class="content">
<article class="grid-body">
<a class="img-banner" href="https://osawards.com/javascript/2020" target="_blank"
rel="noopener noreferrer">
<a class="img-banner" href="https://osawards.com/javascript/2020" target="_blank" rel="noopener noreferrer">
<img src="/img/JSAwardWinner.png" alt="2020 JavaScript Open Source Award Winner banner" />
</a>
@ -94,4 +91,3 @@
<!-- 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>
</slot:body>

View file

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

View file

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

View file

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

View file

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

View file

@ -134,7 +134,7 @@ export default function ({ filename, fileID }: { filename: string; fileID: strin
const code = node.content.styles;
const typeAttr = (node.attributes || []).find(({ name }: { name: string }) => name === 'type');
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.
// 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}) {
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 }
);
}
@ -104,9 +104,7 @@ export async function compileComponent(
): Promise<CompileResult> {
const sourceJsx = await transformFromSource(source, { compileOptions, filename, projectRoot });
const headItem = sourceJsx.head;
const bodyItem = sourceJsx.body;
const headItemJsx = !headItem ? 'null' : headItem.jsx;
const bodyItemJsx = !bodyItem ? 'null' : bodyItem.jsx;
// sort <style> tags first
// 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
// included (see below).
import { h, Fragment } from '${internalImport('h.js')}';
export default function __render(props) { return h(Fragment, null, ${sourceJsx.items.map(({ jsx }) => jsx).join(',')}); }
// <slot:*> render functions
export function __slothead(context, child) { return h(Fragment, null, ${headItemJsx}); }
export function __slotbody(context, child) { return h(Fragment, null, ${bodyItemJsx}); }
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(',')}); }
export default __render;
`;
if (headItemJsx || bodyItemJsx) {
if (headItemJsx) {
modJsx += `
// \`__renderPage()\`: Render the contents of the HMX module as a page. This is a special flow,
// 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.
export async function __renderPage({request, children}) {
const currentChild = {
__slothead,
__slotbody,
__render,
setup: typeof setup === 'undefined' ? (passthrough) => passthrough : setup,
layout: typeof layout === 'undefined' ? undefined : layout,
};
@ -166,12 +162,12 @@ export async function __renderPage({request, children}) {
let headResult;
let bodyResult;
for (const child of children.reverse()) {
headResult = await child.__slothead(mergedContext, headResult);
bodyResult = await child.__slotbody(mergedContext, bodyResult);
headResult = await child.__slothead([headResult], mergedContext);
bodyResult = await child.__render(undefined, [bodyResult], mergedContext);
}
return h(Fragment, null, [
h("head", null, currentChild.__slothead(mergedContext, headResult)),
h("body", null, currentChild.__slotbody(mergedContext, bodyResult)),
h("head", null, currentChild.__slothead([headResult], mergedContext)),
h("body", null, currentChild.__render(undefined, [bodyResult], mergedContext)),
]);
};\n`;
}

View file

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

View file

@ -7,6 +7,9 @@ import { doc } from './test-utils.js';
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');
let runtime;
@ -67,8 +70,10 @@ SnowpackDev('Can load every page', async () => {
assert.equal(result.statusCode, 200, `Loading ${pathname}`);
}
if (failed.length > 0) {
console.error(failed);
assert.equal(failed.length, 1, 'Failed pages (1 expected)');
}
assert.equal(failed.length, 0, 'Failed pages');
});
SnowpackDev.run();