Skip to content

Commit

Permalink
Migrates examples/site/ to use Preact.
Browse files Browse the repository at this point in the history
Refs #71.

This was definitely the most involved migration, though most of it is busy work. Modified and updated tests to be more stable and useful. In particular, I managed to escape the Markdown HTML content yet no tests failed, which should be fixed now.
  • Loading branch information
dgp1130 committed Mar 13, 2023
1 parent f32c6bc commit 811924c
Show file tree
Hide file tree
Showing 34 changed files with 479 additions and 408 deletions.
7 changes: 7 additions & 0 deletions examples/site/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
load("@aspect_bazel_lib//lib:copy_to_bin.bzl", "copy_to_bin")
load("//:index.bzl", "web_resources", "web_resources_devserver")

copy_to_bin(
name = "package",
srcs = ["package.json"],
visibility = [":__subpackages__"],
)

web_resources(
name = "site",
deps = [
Expand Down
13 changes: 8 additions & 5 deletions examples/site/about/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@ load("//:index.bzl", "css_library", "prerender_pages", "web_resources")

prerender_pages(
name = "about",
src = "about.mts",
src = "about.tsx",
tsconfig = "//:tsconfig",
source_map = True,
lib_deps = [
"//examples/site/common:links",
"//:node_modules/rules_prerender",
],
# Need `"type": "module"` to load `*.js` files output by `*.tsx` compilation.
data = ["//examples/site:package"],
styles = [":styles"],
resources = [":resources"],
visibility = ["//examples/site:__pkg__"],
lib_deps = [
"//examples/site/common:links",
"//:node_modules/@rules_prerender/preact",
"//:node_modules/preact",
],
deps = [
"//examples/site/components/base",
"//:prerender_components/@rules_prerender/declarative_shadow_dom",
Expand Down
65 changes: 0 additions & 65 deletions examples/site/about/about.mts

This file was deleted.

82 changes: 82 additions & 0 deletions examples/site/about/about.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { PrerenderResource, Template, inlineStyle, renderToHtml } from '@rules_prerender/preact';
import { polyfillDeclarativeShadowDom } from '@rules_prerender/declarative_shadow_dom/preact.mjs';
import { baseLayout } from '../components/base/base.js';
import { srcLink } from '../common/links.mjs';

/** Renders the about page. */
export default function*(): Generator<PrerenderResource, void, void> {
yield PrerenderResource.of(
'/about/index.html',
renderToHtml(baseLayout('About',
<article>
<Template shadowroot="open">
{polyfillDeclarativeShadowDom()}

<p>
This is the about page. It gives additional background
on the project and this example.
</p>

<img src="/images/icon" />

<p>
This page includes an image resource
at <code>/images/icon</code> although in source it is
called <a href={srcLink('/examples/site/about/logo.png').toString()} rel="noopener"><code>logo.png</code></a>.
As part of the build process it gets renamed and
propagated to the final build directory. This gives
developers full control over the URL structure of their
site. If another file were to be given the same
path, <code>rules_prerender</code> would throw an error
and fail the build with a precise error message about
the file conflict.
</p>

<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Sed nisi ex, pellentesque eu dignissim ac, mattis ac
felis. Vestibulum congue tellus quis lectus hendrerit
luctus. Praesent sollicitudin tempor semper. Mauris
dictum metus a mi maximus ultricies. Phasellus eu congue
metus, ut posuere lacus. Quisque ornare pulvinar orci,
eu tristique massa feugiat non. Nulla eleifend velit sed
orci scelerisque, vitae fringilla dolor bibendum.
</p>

<p>
Pellentesque ac purus in lacus molestie sodales
imperdiet sit amet turpis. Suspendisse tempus ligula
efficitur, molestie urna auctor, luctus augue. In
sagittis fermentum elit, id ullamcorper ante porttitor
vel. Donec mattis posuere accumsan. Vestibulum vitae
fermentum purus, nec rhoncus mauris. Donec lacinia,
justo vel tempus facilisis, ipsum dui posuere elit, a
posuere odio diam iaculis velit. Proin vel vestibulum
erat. Duis semper molestie mattis. Nulla gravida sem
vel odio placerat consectetur. Vestibulum vestibulum
purus nec enim faucibus pellentesque. Aenean nec elit
interdum, imperdiet tellus eget, convallis lectus.
Suspendisse eleifend nec quam vel dignissim. Phasellus
porttitor semper tellus, a dictum erat euismod vitae.
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Fusce tempus leo ante, in facilisis ante lobortis ac.
</p>

<p>
Praesent aliquet fringilla dignissim. Aenean dapibus,
tortor eget finibus hendrerit, tortor diam aliquam
nulla, et egestas libero dui non velit. Integer
pellentesque lobortis mattis. Suspendisse consectetur
elit augue, id semper elit lobortis vitae. Nulla tempor
libero et ex finibus, id convallis justo blandit. Ut
turpis nisl, faucibus sed ignissim quis, venenatis non
mi. Curabitur lacinia tincidunt vulputate. Proin non
vehicula risus, id pharetra lorem.
</p>

{inlineStyle('./about.css', import.meta)}
</Template>
</article>
)),
);
}
8 changes: 5 additions & 3 deletions examples/site/blog/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
load("//tools/typescript:defs.bzl", "ts_project")
load("//:index.bzl", "prerender_pages")
load("//tools/jasmine:defs.bzl", "jasmine_node_test")
load("//tools/typescript:defs.bzl", "ts_project")

prerender_pages(
name = "blog",
src = "blog.mts",
src = "blog.tsx",
tsconfig = "//:tsconfig",
source_map = True,
data = glob(["posts/*.md"]) + [
"//:node_modules/markdown-it",
# Need `"type": "module"` to load `*.js` files output by `*.tsx`
# compilation.
"//examples/site:package",
],
visibility = ["//examples/site:__pkg__"],
lib_deps = [
Expand Down
61 changes: 32 additions & 29 deletions examples/site/blog/blog.mts → examples/site/blog/blog.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { PrerenderResource, Template, renderToHtml } from '@rules_prerender/preact';
import { polyfillDeclarativeShadowDom } from '@rules_prerender/declarative_shadow_dom/preact.mjs';
import { promises as fs } from 'fs';
import * as path from 'path';
import mdLib from 'markdown-it';
import { PrerenderResource } from 'rules_prerender';
import { polyfillDeclarativeShadowDom } from '@rules_prerender/declarative_shadow_dom';
import { srcLink } from '../common/links.mjs';
import { baseLayout } from '../components/base/base.mjs';
import { baseLayout } from '../components/base/base.js';

interface PostMeta {
fileName: string;
Expand Down Expand Up @@ -46,25 +46,26 @@ export default async function*():
}

/** Generate and return a resource with the list of posts at the given path. */
async function generatePostList(path: string, posts: PostMeta[]):
Promise<PrerenderResource> {
return PrerenderResource.of(path, await baseLayout('Blog', () => `
<article>
<template shadowroot="open">
${polyfillDeclarativeShadowDom()}
function generatePostList(path: string, posts: PostMeta[]): PrerenderResource {
return PrerenderResource.of(path, renderToHtml(baseLayout('Blog',
<article>
<Template shadowroot='open'>
{polyfillDeclarativeShadowDom()}

<p>Check out some blog posts! Each of these pages is authored as simple
markdown. They are each generated into a full HTML page, leveraging
shared components and infrastructure.</p>
<p>
Check out some blog posts! Each of these pages is authored
as simple markdown. They are each generated into a full HTML
page, leveraging shared components and infrastructure.
</p>

<ul>
${posts.map(({ title, urlPath: path }) => `
<li><a href="${path}">${title}</a></li>
`).join('')}
</ul>
</template>
</article>
`.trim()));
<ul>
{posts.map(({ title, urlPath: path }) =>
<li><a href={path}>{title}</a></li>
)}
</ul>
</Template>
</article>
)));
}

/** Generate and return a resource with the content of the post in HTML. */
Expand All @@ -75,15 +76,17 @@ async function generatePost({ urlPath, title, fileName }: PostMeta):
});
const link = srcLink(`/examples/site/blog/posts/${fileName}`);

return PrerenderResource.of(urlPath, await baseLayout(title, () => `
<article>
<template shadowroot="open">
${polyfillDeclarativeShadowDom()}
return PrerenderResource.of(urlPath, renderToHtml(baseLayout(title,
<article>
<Template shadowroot='open'>
{polyfillDeclarativeShadowDom()}

<p>This post generated from <a href="${link}">${fileName}</a>.</p>
<p>This post generated from <a href={link.toString()}>{fileName}</a>.</p>

${mdLib().render(markdown)}
</template>
</article>
`));
<div dangerouslySetInnerHTML={{
__html: mdLib().render(markdown)
}}></div>
</Template>
</article>
)));
}
11 changes: 10 additions & 1 deletion examples/site/blog/blog_test.mts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { parse } from 'node-html-parser';
import renderBlog from './blog.mjs';
import renderBlog from './blog.js';

describe('Blog', () => {
it('generates a list of posts', async () => {
Expand Down Expand Up @@ -35,6 +35,9 @@ describe('Blog', () => {

const article = page.querySelector('article')!;
expect(article.text).toContain('This is a blog post about Foo!');

// Markdown should be rendered to unescaped HTML.
expect(article.querySelector('h1')!.textContent).toBe('Foo');
});

it('generates the `Bar` post', async () => {
Expand All @@ -51,6 +54,9 @@ describe('Blog', () => {
const article = page.querySelector('article')!;
expect(article.text)
.toContain('This is another blog post generated from markdown.');

// Markdown should be rendered to unescaped HTML.
expect(article.querySelector('h1')!.textContent).toBe('Bar');
});

it('generates the `Baz` post', async () => {
Expand All @@ -67,6 +73,9 @@ describe('Blog', () => {
const article = page.querySelector('article')!;
expect(article.text).toContain(
'Here is one more blog post about nothing in particular');

// Markdown should be rendered to unescaped HTML.
expect(article.querySelector('h1')!.textContent).toBe('Baz');
});
});

Expand Down
14 changes: 8 additions & 6 deletions examples/site/components/base/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
load("//tools/typescript:defs.bzl", "ts_project")
load("//:index.bzl", "css_library", "prerender_component")
load("//tools/jasmine:defs.bzl", "jasmine_node_test")
load("//tools/typescript:defs.bzl", "ts_project")

prerender_component(
name = "base",
srcs = ["base.mts"],
srcs = ["base.tsx"],
tsconfig = "//:tsconfig",
source_map = True,
data = ["//:node_modules/rules_prerender"],
lib_deps = ["//:node_modules/rules_prerender"],
styles = [":styles"],
visibility = ["//examples/site:__subpackages__"],
lib_deps = [
"//:node_modules/@rules_prerender/preact",
"//:node_modules/preact",
],
deps = [
"//examples/site/components/footer",
"//examples/site/components/header",
Expand All @@ -25,11 +27,11 @@ css_library(

ts_project(
name = "base_test_lib",
srcs = ["base_test.mts"],
srcs = ["base_test.tsx"],
testonly = True,
data = ["//:node_modules/node-html-parser"],
deps = [
":base_prerender_for_test",
"//:node_modules/@rules_prerender/preact",
"//:node_modules/@types/jasmine",
"//:node_modules/node-html-parser",
],
Expand Down
Loading

0 comments on commit 811924c

Please sign in to comment.