- Counter is at {count}.
+ Counter is at {count}.{" "}
+
);
}
@@ -39,14 +40,78 @@ Fresh can serialize the following types of values:
- Plain objects with string keys and serializable values
- Arrays containing serializable values
- Uint8Array
+- JSX Elements (restricted to `props.children`)
- Preact Signals (if the inner value is serializable)
Circular references are supported. If an object or signal is referenced multiple
times, it is only serialized once and the references are restored upon
-deserialization.
+deserialization. Passing complex objects like `Date`, custom classes, or
+functions is not supported.
-Passing complex objects like `Date`, custom classes, or functions is not
-supported. This means that it is not possible to pass `children` to an island,
-as `children` are VNodes, which are not serializable.
+## Passing JSX to islands
-It is also not supported to nest islands within other islands.
+Islands support passing JSX elements via the `children` property. This allows
+you to pass static content rendered by the server to an island in the browser.
+
+```jsx
+// file: /route/index.tsx
+import MyIsland from "../islands/my-island.tsx";
+
+export default function Home() {
+ return (
+
+
This text is rendered on the server
+
+ );
+}
+```
+
+We can deduce which parts were rendered by the server and which parts where
+rendered by an island from the HTML alone. It contains all the information we
+need, which allows us to skip the work of having to send a serialized version of
+`props.children` to the browser.
+
+### Nesting islands
+
+Islands can be nested within other islands as well. In that scenario they act
+like a normal Preact component, but still receive the serialized props if any
+were present.
+
+```jsx
+// file: /route/index.tsx
+import MyIsland from "../islands/my-island.tsx";
+import OtherIsland from "../islands/other-island.tsx";
+
+export default function Home() {
+ return (
+
+
+
This text is rendered on the server
+
+
+ );
+}
+```
+
+In essence, fresh allows you to mix static and interactive parts in your app in
+a way that's most optimal for your use app. We'll keep sending only the
+JavaScript that is needed for the islands to the browser.
+
+```jsx
+// file: /route/index.tsx
+import MyIsland from "../islands/my-island.tsx";
+import OtherIsland from "../islands/other-island.tsx";
+
+export default function Home() {
+ return (
+
+
+
Rendered by server
+
+
also rendered by server
+
+
+
+ );
+}
+```
diff --git a/src/runtime/entrypoints/main.ts b/src/runtime/entrypoints/main.ts
index 4e613479..39c545b9 100644
--- a/src/runtime/entrypoints/main.ts
+++ b/src/runtime/entrypoints/main.ts
@@ -1,4 +1,12 @@
-import { ComponentType, h, options, render } from "preact";
+import {
+ ComponentChildren,
+ ComponentType,
+ Fragment,
+ h,
+ options,
+ render,
+ VNode,
+} from "preact";
import { assetHashingHook } from "../utils.ts";
function createRootFragment(
@@ -24,49 +32,266 @@ function createRootFragment(
};
}
+function isCommentNode(node: Node): node is Comment {
+ return node.nodeType === Node.COMMENT_NODE;
+}
+function isTextNode(node: Node): node is Text {
+ return node.nodeType === Node.TEXT_NODE;
+}
+function isElementNode(node: Node): node is HTMLElement {
+ return node.nodeType === Node.ELEMENT_NODE;
+}
+
// deno-lint-ignore no-explicit-any
export function revive(islands: Record, props: any[]) {
- async function walk(node: Node | null) {
- const tag = node!.nodeType === 8 &&
- ((node as Comment).data.match(/^\s*frsh-(.*)\s*$/) || [])[1];
- let endNode: Node | null = null;
- if (tag) {
- const startNode = node!;
- const children = [];
- const parent = node!.parentNode;
- // collect all children of the island
- while ((node = node!.nextSibling) && node.nodeType !== 8) {
- children.push(node);
- }
- startNode.parentNode!.removeChild(startNode); // remove start tag node
+ _walkInner(
+ islands,
+ props,
+ // markerstack
+ [],
+ // Keep a root node in the vnode stack to save a couple of checks
+ // later during iteration
+ [h(Fragment, null)],
+ document.body,
+ );
+}
- const [id, n] = tag.split(":");
- const _render = () => {
- render(
- h(islands[id], props[Number(n)]),
- createRootFragment(
- parent! as HTMLElement,
- children,
- // deno-lint-ignore no-explicit-any
- ) as any as HTMLElement,
- );
- };
- "scheduler" in window
- ? await scheduler!.postTask(_render)
- : setTimeout(_render, 0);
- endNode = node;
+function ServerComponent(
+ props: { children: ComponentChildren },
+): ComponentChildren {
+ return props.children;
+}
+ServerComponent.displayName = "PreactServerComponent";
+
+function addPropsChild(parent: VNode, vnode: ComponentChildren) {
+ const props = parent.props;
+ if (props.children === null) {
+ props.children = vnode;
+ } else {
+ if (!Array.isArray(props.children)) {
+ props.children = [props.children, vnode];
+ } else {
+ props.children.push(vnode);
}
-
- const sib = node!.nextSibling;
- const fc = node!.firstChild;
- if (endNode) {
- endNode.parentNode?.removeChild(endNode); // remove end tag node
- }
-
- if (sib) walk(sib);
- if (fc) walk(fc);
}
- walk(document.body);
+}
+
+const enum MarkerKind {
+ Island,
+ Slot,
+}
+
+interface Marker {
+ kind: MarkerKind;
+ // We can remove this once we drop support for RTS <6.1.0 where
+ // we rendered incorrect comments leading to `!--` and `--` being
+ // included in the comment text. Therefore this is a normalized
+ // string representing the actual intended comment value which makes
+ // a bunch of stuff easier.
+ text: string;
+ startNode: Comment;
+ endNode: Comment | null;
+}
+
+/**
+ * Revive islands and stich together any server rendered content.
+ *
+ * Conceptually we're doing an inorder depth first search over the DOM
+ * to find all our comment nodes `` which act as
+ * a marker for islands or server rendered JSX (=slots in islands).
+ * Every island or server JSX has a start and an end marker, which
+ * means there is no _single_ root nodes for these elements.
+ * The hierarchy we need to construct for the virtual-dom tree might
+ * be rendered in a flattened manner in the DOM.
+ *
+ * Example:
+ *
+ *
+ *
+ *
server content
+ *
+ *
+ *
+ *
+ * Here we have a flat DOM structure, but from the virtual-dom
+ * perspective we should render:
+ *
-> -> ServerComponent ->
server content
+ *
+ * To solve this we're keeping track of the virtual-dom hierarchy
+ * in a stack-like manner, but do the actual iteration in a list-based
+ * fashion over an HTMLElement's children list.
+ */
+function _walkInner(
+ islands: Record,
+ // deno-lint-ignore no-explicit-any
+ props: any[],
+ markerStack: Marker[],
+ vnodeStack: VNode[],
+ node: Node | Comment,
+) {
+ let sib: Node | null = node;
+ while (sib !== null) {
+ const marker = markerStack.length > 0
+ ? markerStack[markerStack.length - 1]
+ : null;
+
+ // We use comment nodes to mark fresh islands and slots
+ if (isCommentNode(sib)) {
+ let comment = sib.data;
+ if (comment.startsWith("!--")) {
+ comment = comment.slice(3, -2);
+ }
+
+ if (comment.startsWith("frsh-slot")) {
+ // Note: Nested slots are not possible as they're flattened
+ // already on the server.
+ markerStack.push({
+ startNode: sib,
+ text: comment,
+ endNode: null,
+ kind: MarkerKind.Slot,
+ });
+ // @ts-ignore TS gets confused
+ vnodeStack.push(h(ServerComponent, { key: comment }));
+ } else if (
+ marker !== null && (
+ comment.startsWith("/frsh") ||
+ // Check for old Preact RTS
+ marker.text === comment
+ )
+ ) {
+ // We're closing either a slot or an island
+ marker.endNode = sib;
+
+ markerStack.pop();
+ const parent = markerStack.length > 0
+ ? markerStack[markerStack.length - 1]
+ : null;
+
+ if (marker.kind === MarkerKind.Slot) {
+ // If we're closing a slot than it's assumed that we're
+ // inside an island
+ if (parent?.kind === MarkerKind.Island) {
+ const vnode = vnodeStack.pop();
+
+ // For now only `props.children` is supported.
+ const islandParent = vnodeStack[vnodeStack.length - 1]!;
+ // Overwrite serialized `{__slot: "children"}` with the
+ // actual vnode child.
+ islandParent.props.children = vnode;
+ }
+
+ // Remove markers
+ marker.startNode.remove();
+ sib = sib.nextSibling;
+ marker.endNode.remove();
+ continue;
+ } else if (marker.kind === MarkerKind.Island) {
+ // We're ready to revive this island if it has
+ // no roots of its own. Otherwise we'll treat it
+ // as a standard component
+ if (markerStack.length === 0) {
+ const children: Node[] = [];
+
+ let child: Node | null = marker.startNode;
+ while (
+ (child = child.nextSibling) !== null && child !== marker.endNode
+ ) {
+ children.push(child);
+ }
+
+ const vnode = vnodeStack.pop();
+
+ const parentNode = sib.parentNode! as HTMLElement;
+ const _render = () =>
+ render(
+ vnode,
+ createRootFragment(
+ parentNode,
+ children,
+ // deno-lint-ignore no-explicit-any
+ ) as any as HTMLElement,
+ );
+
+ "scheduler" in window
+ // `scheduler.postTask` is async but that can easily
+ // fire in the background. We don't want waiting for
+ // the hydration of an island block us.
+ // @ts-ignore scheduler API is not in types yet
+ ? scheduler!.postTask(_render)
+ : setTimeout(_render, 0);
+
+ // Remove markers
+ marker.startNode.remove();
+ sib = sib.nextSibling;
+ marker.endNode.remove();
+ continue;
+ } else if (parent?.kind === MarkerKind.Slot) {
+ // Treat the island as a standard component when it
+ // has an island parent or a slot parent
+ const vnode = vnodeStack.pop();
+ const parent = vnodeStack[vnodeStack.length - 1]!;
+ addPropsChild(parent, vnode);
+ }
+ }
+ } else if (comment.startsWith("frsh")) {
+ // We're opening a new island
+ const [id, n] = comment.slice(5).split(":");
+ const islandProps = props[Number(n)];
+
+ markerStack.push({
+ startNode: sib,
+ endNode: null,
+ text: comment,
+ kind: MarkerKind.Island,
+ });
+ const vnode = h(islands[id], islandProps);
+ vnodeStack.push(vnode);
+ }
+ } else if (isTextNode(sib)) {
+ const parentVNode = vnodeStack[vnodeStack.length - 1]!;
+ if (
+ marker !== null && marker.kind === MarkerKind.Slot
+ ) {
+ addPropsChild(parentVNode, sib.data);
+ }
+ } else {
+ const parentVNode = vnodeStack[vnodeStack.length - 1];
+ if (
+ marker !== null &&
+ marker.kind === MarkerKind.Slot && isElementNode(sib)
+ ) {
+ // Parse the server rendered DOM into vnodes that we can
+ // attach to the virtual-dom tree. In the future, once
+ // Preact supports a way to skip over subtrees, this
+ // can be dropped.
+ const childLen = sib.childNodes.length;
+ const props: Record = {
+ children: childLen <= 1 ? null : [],
+ };
+ for (let i = 0; i < sib.attributes.length; i++) {
+ const attr = sib.attributes[i];
+ props[attr.nodeName] = attr.nodeValue;
+ }
+ const vnode = h(sib.localName, props);
+ addPropsChild(parentVNode, vnode);
+ vnodeStack.push(vnode);
+ }
+
+ // TODO: What about script tags?
+ if (
+ sib.firstChild && (sib.nodeName !== "SCRIPT")
+ ) {
+ _walkInner(islands, props, markerStack, vnodeStack, sib.firstChild);
+ }
+
+ if (marker !== null && marker.kind === MarkerKind.Slot) {
+ vnodeStack.pop();
+ }
+ }
+
+ sib = sib.nextSibling;
+ }
}
const originalHook = options.vnode;
diff --git a/src/server/render.ts b/src/server/render.ts
index 8b1b9aab..22a16ff0 100644
--- a/src/server/render.ts
+++ b/src/server/render.ts
@@ -420,6 +420,31 @@ if (!supportsUnstableComments) {
);
}
+function wrapWithMarker(vnode: ComponentChildren, markerText: string) {
+ // Newer versions of preact-render-to-string allow you to render comments
+ if (supportsUnstableComments) {
+ return h(
+ Fragment,
+ null,
+ h(Fragment, {
+ // @ts-ignore unstable property is not typed
+ UNSTABLE_comment: markerText,
+ }),
+ vnode,
+ h(Fragment, {
+ // @ts-ignore unstable property is not typed
+ UNSTABLE_comment: "/" + markerText,
+ }),
+ );
+ } else {
+ return h(
+ `!--${markerText}--`,
+ null,
+ vnode,
+ );
+ }
+}
+
// Set up a preact option hook to track when vnode with custom functions are
// created.
const ISLANDS: Island[] = [];
@@ -440,31 +465,24 @@ options.vnode = (vnode) => {
ENCOUNTERED_ISLANDS.add(island);
vnode.type = (props) => {
ignoreNext = true;
+
+ // Only passing children JSX to islands is supported for now
+ if ("children" in props) {
+ const children = props.children;
+ // @ts-ignore nonono
+ props.children = wrapWithMarker(
+ children,
+ `frsh-slot-${island.id}:children`,
+ );
+ }
+
const child = h(originalType, props);
ISLAND_PROPS.push(props);
- // Newer versions of preact-render-to-string allow you to render comments
- if (supportsUnstableComments) {
- return h(
- Fragment,
- null,
- h(Fragment, {
- // @ts-ignore unstable property is not typed
- UNSTABLE_comment: `frsh-${island.id}:${ISLAND_PROPS.length - 1}`,
- }),
- child,
- h(Fragment, {
- // @ts-ignore unstable property is not typed
- UNSTABLE_comment: `/frsh-${island.id}:${ISLAND_PROPS.length - 1}`,
- }),
- );
- } else {
- return h(
- `!--frsh-${island.id}:${ISLAND_PROPS.length - 1}--`,
- null,
- child,
- );
- }
+ return wrapWithMarker(
+ child,
+ `frsh-${island.id}:${ISLAND_PROPS.length - 1}`,
+ );
};
}
}
diff --git a/src/server/serializer.ts b/src/server/serializer.ts
index a8efbb44..99c7167e 100644
--- a/src/server/serializer.ts
+++ b/src/server/serializer.ts
@@ -16,6 +16,7 @@
*
* The corresponding deserializer is in `src/runtime/deserializer.ts`.
*/
+import { isValidElement, VNode } from "preact";
import { KEY } from "../runtime/deserializer.ts";
interface SerializeResult {
@@ -44,6 +45,13 @@ function isSignal(x: any): x is Signal {
);
}
+// deno-lint-ignore no-explicit-any
+function isVNode(x: any): x is VNode {
+ return x !== null && typeof x === "object" && "type" in x && "ref" in x &&
+ "__k" in x &&
+ isValidElement(x);
+}
+
export function serialize(data: unknown): SerializeResult {
let requiresDeserializer = false;
let hasSignals = false;
@@ -108,6 +116,13 @@ export function serialize(data: unknown): SerializeResult {
referenceArr.push(currentPath);
}
return 0;
+ } else if (isVNode(value)) {
+ requiresDeserializer = true;
+ // No need to serialize JSX as we pick that up from
+ // the rendered HTML in the browser.
+ const res = null;
+ parentStack.push(res);
+ return res;
} else {
seen.set(value, currentPath);
}
diff --git a/tests/fixture_island_nesting/deno.json b/tests/fixture_island_nesting/deno.json
new file mode 100644
index 00000000..5a9ac92f
--- /dev/null
+++ b/tests/fixture_island_nesting/deno.json
@@ -0,0 +1,18 @@
+{
+ "lock": false,
+ "tasks": {
+ "start": "deno run -A --watch=static/,routes/ dev.ts"
+ },
+ "imports": {
+ "$fresh/": "../../",
+ "preact": "https://esm.sh/preact@10.15.1",
+ "preact/": "https://esm.sh/preact@10.15.1/",
+ "preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.1.0",
+ "@preact/signals": "https://esm.sh/*@preact/signals@1.1.3",
+ "@preact/signals-core": "https://esm.sh/@preact/signals-core@1.2.3"
+ },
+ "compilerOptions": {
+ "jsx": "react-jsx",
+ "jsxImportSource": "preact"
+ }
+}
diff --git a/tests/fixture_island_nesting/dev.ts b/tests/fixture_island_nesting/dev.ts
new file mode 100755
index 00000000..2d85d6c1
--- /dev/null
+++ b/tests/fixture_island_nesting/dev.ts
@@ -0,0 +1,5 @@
+#!/usr/bin/env -S deno run -A --watch=static/,routes/
+
+import dev from "$fresh/dev.ts";
+
+await dev(import.meta.url, "./main.ts");
diff --git a/tests/fixture_island_nesting/fresh.gen.ts b/tests/fixture_island_nesting/fresh.gen.ts
new file mode 100644
index 00000000..34266daa
--- /dev/null
+++ b/tests/fixture_island_nesting/fresh.gen.ts
@@ -0,0 +1,34 @@
+// DO NOT EDIT. This file is generated by fresh.
+// This file SHOULD be checked into source version control.
+// This file is automatically updated during development when running `dev.ts`.
+
+import * as $0 from "./routes/index.tsx";
+import * as $1 from "./routes/island_in_island.tsx";
+import * as $2 from "./routes/island_jsx_child.tsx";
+import * as $3 from "./routes/island_jsx_children.tsx";
+import * as $4 from "./routes/island_jsx_island_jsx.tsx";
+import * as $5 from "./routes/island_jsx_text.tsx";
+import * as $6 from "./routes/island_nested_props.tsx";
+import * as $7 from "./routes/island_siblings.tsx";
+import * as $$0 from "./islands/Island.tsx";
+import * as $$1 from "./islands/IslandWithProps.tsx";
+
+const manifest = {
+ routes: {
+ "./routes/index.tsx": $0,
+ "./routes/island_in_island.tsx": $1,
+ "./routes/island_jsx_child.tsx": $2,
+ "./routes/island_jsx_children.tsx": $3,
+ "./routes/island_jsx_island_jsx.tsx": $4,
+ "./routes/island_jsx_text.tsx": $5,
+ "./routes/island_nested_props.tsx": $6,
+ "./routes/island_siblings.tsx": $7,
+ },
+ islands: {
+ "./islands/Island.tsx": $$0,
+ "./islands/IslandWithProps.tsx": $$1,
+ },
+ baseUrl: import.meta.url,
+};
+
+export default manifest;
diff --git a/tests/fixture_island_nesting/islands/Island.tsx b/tests/fixture_island_nesting/islands/Island.tsx
new file mode 100644
index 00000000..1887f5af
--- /dev/null
+++ b/tests/fixture_island_nesting/islands/Island.tsx
@@ -0,0 +1,9 @@
+import { ComponentChildren } from "preact";
+
+export default function Island(props: { children?: ComponentChildren }) {
+ return (
+