summaryrefslogtreecommitdiff
path: root/src/frontend/render/preact.ts
diff options
context:
space:
mode:
authorGravatar Nate Moore <natemoo-re@users.noreply.github.com> 2021-03-26 17:09:28 -0500
committerGravatar GitHub <noreply@github.com> 2021-03-26 17:09:28 -0500
commit9ab1f52a1ca018b7551dc610f7099d300ce5b473 (patch)
tree739ea1e6385c1af866f0c7f5ab154c7d0b68c0ab /src/frontend/render/preact.ts
parent202973291f55bdf21050ab2c1c7db13b2fdb62eb (diff)
downloadastro-9ab1f52a1ca018b7551dc610f7099d300ce5b473.tar.gz
astro-9ab1f52a1ca018b7551dc610f7099d300ce5b473.tar.zst
astro-9ab1f52a1ca018b7551dc610f7099d300ce5b473.zip
New hydration methods (#29)
* WIP: new hydration methods * refactor: genericize load/idle/visible renderers * fix: do not pass "data-astro-id" to component * docs: add hydration section to README * docs: update README Co-authored-by: Nate Moore <nate@skypack.dev>
Diffstat (limited to 'src/frontend/render/preact.ts')
-rw-r--r--src/frontend/render/preact.ts43
1 files changed, 19 insertions, 24 deletions
diff --git a/src/frontend/render/preact.ts b/src/frontend/render/preact.ts
index 50bb9344e..359202372 100644
--- a/src/frontend/render/preact.ts
+++ b/src/frontend/render/preact.ts
@@ -1,30 +1,25 @@
-import renderToString from 'preact-render-to-string';
+import { Renderer, createRenderer } from './renderer';
import { h, render } from 'preact';
-import type { Component } from 'preact';
+import { renderToString } from 'preact-render-to-string';
// This prevents tree-shaking of render.
Function.prototype(render);
-export function __preact_static(PreactComponent: Component) {
- return (attrs: Record<string, any>, ...children: any): string => {
- let html = renderToString(
- h(
- PreactComponent as any, // Preact's types seem wrong...
- attrs,
- children
- )
- );
- return html;
- };
-}
+const Preact: Renderer = {
+ renderStatic(Component) {
+ return (props, ...children) => renderToString(h(Component, props, ...children));
+ },
+ imports: {
+ preact: ['render', 'h'],
+ },
+ render({ Component, root, props }) {
+ return `render(h(${Component}, ${props}), ${root})`;
+ },
+};
-export function __preact_dynamic(PreactComponent: Component, importUrl: string, preactUrl: string) {
- const placeholderId = `placeholder_${String(Math.random())}`;
- return (attrs: Record<string, string>, ...children: any) => {
- return `<div id="${placeholderId}"></div><script type="module">
- import {h, render} from '${preactUrl}';
- import Component from '${importUrl}';
- render(h(Component, ${JSON.stringify(attrs)}), document.getElementById('${placeholderId}'));
- </script>`;
- };
-}
+const renderer = createRenderer(Preact);
+
+export const __preact_static = renderer.static;
+export const __preact_load = renderer.load;
+export const __preact_idle = renderer.idle;
+export const __preact_visible = renderer.visible;