major: import Fresh 2.0 code (#2449)

🎉
This commit is contained in:
Marvin Hagemeister
2024-05-24 09:40:08 +02:00
committed by GitHub
parent 990357629e
commit 287929e4d2
958 changed files with 15794 additions and 28287 deletions
+134
View File
@@ -0,0 +1,134 @@
import "preact/debug";
export * from "./mod.tsx";
import { IS_BROWSER } from "../shared.ts";
let ws: WebSocket;
let revision = 0;
let reconnectTimer: number;
const backoff = [
// Wait 100ms initially, because we could also be
// disconnected because of a form submit.
100,
150,
200,
250,
300,
350,
400,
450,
500,
500,
605,
750,
1000,
1250,
1500,
1750,
2000,
];
let backoffIdx = 0;
function reconnect() {
if (ws.readyState !== ws.CLOSED) return;
reconnectTimer = setTimeout(() => {
if (backoffIdx === 0) {
console.log(
`%c Fresh %c Connection closed. Trying to reconnect...`,
"background-color: #86efac; color: black",
"color: inherit",
);
}
backoffIdx++;
try {
connect();
clearTimeout(reconnectTimer);
} catch (_err) {
reconnect();
}
}, backoff[Math.min(backoffIdx, backoff.length - 1)]);
}
function onOpenWs() {
backoffIdx = 0;
}
function onCloseWs() {
disconnect();
reconnect();
}
function connect() {
const url = new URL("/_frsh/alive", location.origin.replace("http", "ws"));
ws = new WebSocket(
url,
);
ws.addEventListener("open", onOpenWs);
ws.addEventListener("close", onCloseWs);
ws.addEventListener("message", handleMessage);
ws.addEventListener("error", handleError);
}
function disconnect() {
ws.removeEventListener("open", onOpenWs);
ws.removeEventListener("close", onCloseWs);
ws.removeEventListener("message", handleMessage);
ws.removeEventListener("error", handleError);
ws.close();
}
function handleMessage(e: MessageEvent) {
const data = JSON.parse(e.data);
switch (data.type) {
case "initial-state": {
if (revision === 0) {
console.log(
`%c Fresh %c Connected to development server.`,
"background-color: #86efac; color: black",
"color: inherit",
);
}
if (revision === 0) {
revision = data.revision;
} else if (revision < data.revision) {
disconnect();
// Needs reload
location.reload();
}
}
}
}
function handleError(e: Event) {
// TODO
// deno-lint-ignore no-explicit-any
if (e && (e as any).code === "ECONNREFUSED") {
setTimeout(connect, 1000);
}
}
if (IS_BROWSER) {
connect();
addEventListener("message", (ev) => {
if (ev.origin !== location.origin) return;
if (typeof ev.data !== "string" || ev.data !== "close-error-overlay") {
return;
}
document.querySelector("#fresh-error-overlay")?.remove();
});
// Disconnect when the tab becomes inactive and re-connect when it
// becomes active again
addEventListener("visibilitychange", () => {
if (document.hidden) {
disconnect();
} else {
connect();
}
});
}
+4
View File
@@ -0,0 +1,4 @@
import "./polyfills.ts";
import "./partials.ts";
export { asset, IS_BROWSER, Partial, type PartialProps } from "../shared.ts";
export { boot, revive } from "./reviver.ts";
+507
View File
@@ -0,0 +1,507 @@
import { type ComponentChildren, h } from "preact";
import {
CLIENT_NAV_ATTR,
DATA_ANCESTOR,
DATA_CURRENT,
matchesUrl,
PartialMode,
UrlMatchKind,
} from "../shared_internal.tsx";
import {
ACTIVE_PARTIALS,
copyOldChildren,
CUSTOM_PARSER,
type DeserializedProps,
domToVNode,
ISLAND_REGISTRY,
Marker,
maybeHideMarker,
PartialComp,
} from "./reviver.ts";
import { createRootFragment, isCommentNode, isElementNode } from "./reviver.ts";
import type { PartialStateJson } from "../server/preact_hooks.tsx";
import { parse } from "../../jsonify/parse.ts";
import { INTERNAL_PREFIX } from "../../constants.ts";
export const PARTIAL_ATTR = "f-partial";
export const PARTIAL_SEARCH_PARAM = "fresh-partial";
class NoPartialsError extends Error {}
export interface FreshHistoryState {
index: number;
scrollX: number;
scrollY: number;
}
function checkClientNavEnabled(el: HTMLElement) {
const setting = el.closest(`[${CLIENT_NAV_ATTR}]`);
if (setting === null) return false;
return setting.getAttribute(CLIENT_NAV_ATTR) !== "false";
}
// Keep track of history state to apply forward or backward animations
let index = history.state?.index || 0;
if (!history.state) {
const state: FreshHistoryState = {
index,
scrollX,
scrollY,
};
history.replaceState(state, document.title);
}
function maybeUpdateHistory(nextUrl: URL) {
// Only add history entry when URL is new. Still apply
// the partials because sometimes users click a link to
// "refresh" the current page.
if (nextUrl.href !== globalThis.location.href) {
const state: FreshHistoryState = {
index,
scrollX: globalThis.scrollX,
scrollY: globalThis.scrollY,
};
// Store current scroll position
history.replaceState({ ...state }, "", location.href);
// Now store the new position
index++;
state.scrollX = 0;
state.scrollY = 0;
history.pushState(state, "", nextUrl.href);
}
}
document.addEventListener("click", async (e) => {
let el = e.target;
if (el && el instanceof HTMLElement) {
const originalEl = el;
// Check if we clicked inside an anchor link
if (el.nodeName !== "A") {
el = el.closest("a");
}
if (
// Check that we're still dealing with an anchor tag
el && el instanceof HTMLAnchorElement &&
// Check if it's an internal link
el.href && (!el.target || el.target === "_self") &&
el.origin === location.origin &&
// Check if it was a left click and not a right click
e.button === 0 &&
// Check that the user doesn't press a key combo to open the
// link in a new tab or something
!(e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.button) &&
// Check that the event isn't aborted already
!e.defaultPrevented
) {
const partial = el.getAttribute(PARTIAL_ATTR);
// Check if the user opted out of client side navigation or if
// we're doing a fragment navigation.
if (
el.getAttribute("href")?.startsWith("#") ||
!checkClientNavEnabled(el)
) {
return;
}
// deno-lint-ignore no-explicit-any
const indicator = (el as any)._freshIndicator;
if (indicator !== undefined) {
indicator.value = true;
}
e.preventDefault();
const nextUrl = new URL(el.href);
try {
maybeUpdateHistory(nextUrl);
const partialUrl = new URL(
partial ? partial : nextUrl.href,
location.href,
);
await fetchPartials(partialUrl);
updateLinks(nextUrl);
scrollTo({ left: 0, top: 0, behavior: "instant" });
} finally {
if (indicator !== undefined) {
indicator.value = false;
}
}
} else {
let button: HTMLButtonElement | HTMLElement | null = originalEl;
// Check if we clicked on a button
if (button.nodeName !== "A") {
button = button.closest("button");
}
if (
button !== null && button instanceof HTMLButtonElement &&
(button.type !== "submit" || button.form === null)
) {
const partial = button.getAttribute(PARTIAL_ATTR);
// Check if the user opted out of client side navigation.
if (
partial === null ||
!checkClientNavEnabled(button)
) {
return;
}
const partialUrl = new URL(
partial,
location.href,
);
await fetchPartials(partialUrl);
}
}
}
});
addEventListener("popstate", async (e) => {
// When state is `null` then the browser navigated to a document
// fragment. In this case we do nothing.
if (e.state === null) {
// Reset to browser default
if (history.scrollRestoration) {
history.scrollRestoration = "auto";
}
return;
}
const state: FreshHistoryState = history.state;
const nextIdx = state.index ?? index + 1;
index = nextIdx;
const setting = document.querySelector(`[${CLIENT_NAV_ATTR}]`);
if (setting === null || setting.getAttribute(CLIENT_NAV_ATTR) === "false") {
location.reload();
return;
}
// We need to keep track of that ourselves since we do client side
// navigation.
if (history.scrollRestoration) {
history.scrollRestoration = "manual";
}
const url = new URL(location.href, location.origin);
try {
await fetchPartials(url);
updateLinks(url);
scrollTo({
left: state.scrollX ?? 0,
top: state.scrollY ?? 0,
behavior: "instant",
});
} catch (err) {
// If the response didn't contain a partial, then we can only
// do a reload.
if (err instanceof NoPartialsError) {
location.reload();
return;
}
throw err;
}
});
// Form submit
document.addEventListener("submit", async (e) => {
const el = e.target;
if (el !== null && el instanceof HTMLFormElement && !e.defaultPrevented) {
if (
// Check if form has client nav enabled
!checkClientNavEnabled(el) ||
// Bail out if submitter is set and client nav is disabled
(e.submitter !== null && !checkClientNavEnabled(e.submitter))
) {
return;
}
const lowerMethod =
e.submitter?.getAttribute("formmethod")?.toLowerCase() ??
el.method.toLowerCase();
if (
lowerMethod !== "get" && lowerMethod !== "post" &&
lowerMethod !== "dialog"
) {
return;
}
const action = e.submitter?.getAttribute(PARTIAL_ATTR) ??
e.submitter?.getAttribute("formaction") ??
el.getAttribute(PARTIAL_ATTR) ?? el.action;
if (action !== "") {
e.preventDefault();
const url = new URL(action, location.href);
let init: RequestInit | undefined;
// GET method appends form data via url search params
if (lowerMethod === "get") {
// TODO: Looks like constructor type for URLSearchParam is wrong
// deno-lint-ignore no-explicit-any
const qs = new URLSearchParams(new FormData(el) as any);
qs.forEach((value, key) => url.searchParams.set(key, value));
} else {
init = { body: new FormData(el), method: lowerMethod };
}
maybeUpdateHistory(url);
await fetchPartials(url, init);
}
}
});
function updateLinks(url: URL) {
document.querySelectorAll("a").forEach((link) => {
const match = matchesUrl(url.pathname, link.href);
if (match === UrlMatchKind.Current) {
link.setAttribute(DATA_CURRENT, "true");
link.setAttribute("aria-current", "page");
link.removeAttribute(DATA_ANCESTOR);
} else if (match === UrlMatchKind.Ancestor) {
link.setAttribute(DATA_ANCESTOR, "true");
link.setAttribute("aria-current", "true");
link.removeAttribute(DATA_CURRENT);
} else {
link.removeAttribute(DATA_CURRENT);
link.removeAttribute(DATA_ANCESTOR);
link.removeAttribute("aria-current");
}
});
}
async function fetchPartials(url: URL, init: RequestInit = {}) {
init.redirect = "follow";
url.searchParams.set(PARTIAL_SEARCH_PARAM, "true");
const res = await fetch(url, init);
await applyPartials(res);
}
interface PartialReviveCtx {
foundPartials: number;
}
/**
* Apply partials from a HTML response
*/
export async function applyPartials(res: Response): Promise<void> {
const contentType = res.headers.get("Content-Type");
if (contentType !== "text/html; charset=utf-8") {
throw new Error(`Unable to process partial response.`);
}
const id = res.headers.get("X-Fresh-Id");
const resText = await res.text();
const doc = new DOMParser().parseFromString(resText, "text/html") as Document;
const state = doc.querySelector(`#__FRSH_STATE_${id}`);
let allProps: DeserializedProps = [];
if (state !== null) {
const json = JSON.parse(state.textContent!) as PartialStateJson;
const promises: Promise<void>[] = [];
allProps = parse<DeserializedProps>(json.props, CUSTOM_PARSER);
for (let i = 0; i < json.islands.length; i++) {
const island = json.islands[i];
promises.push(
import(island.chunk).then((mod) => {
ISLAND_REGISTRY.set(island.name, mod[island.exportName]);
}),
);
}
await Promise.all(promises);
}
const ctx: PartialReviveCtx = {
foundPartials: 0,
};
if (doc.title) {
document.title = doc.title;
}
// Needs to be converted to an array otherwise somehow <link>-tags
// are missing.
Array.from(doc.head.childNodes).forEach((childNode) => {
const child = childNode as HTMLElement;
if (child.nodeName === "TITLE") return;
if (child.nodeName === "META") {
const meta = child as HTMLMetaElement;
// Ignore charset which is usually set site wide anyway
if (meta.hasAttribute("charset")) return;
const name = meta.name;
if (name !== "") {
const existing = document.head.querySelector(`meta[name="${name}"]`) as
| HTMLMetaElement
| null;
if (existing !== null) {
if (existing.content !== meta.content) {
existing.content = meta.content;
}
} else {
document.head.appendChild(meta);
}
} else {
const property = child.getAttribute("property");
const existing = document.head.querySelector(
`meta[property="${property}"]`,
) as HTMLMetaElement | null;
if (existing !== null) {
if (existing.content !== meta.content) {
existing.content = meta.content;
}
} else {
document.head.appendChild(meta);
}
}
} else if (child.nodeName === "LINK") {
const link = child as HTMLLinkElement;
if (link.rel === "modulepreload") return;
if (link.rel === "stylesheet") {
// The `href` attribute may be root relative. This ensures
// that they both have the same format
const existing = Array.from(document.head.querySelectorAll("link"))
.find((existingLink) => existingLink.href === link.href);
if (existing === undefined) {
document.head.appendChild(link);
}
}
} else if (child.nodeName === "SCRIPT") {
const script = child as HTMLScriptElement;
if (script.src === `${INTERNAL_PREFIX}/fresh-runtime.js`) return;
// TODO: What to do with script tags?
} else if (child.nodeName === "STYLE") {
const style = child as HTMLStyleElement;
// TODO: Do we need a smarter merging strategy?
// Don't overwrie existing style sheets that are flagged as unique
if (style.id === "") {
document.head.appendChild(style);
}
}
});
revivePartials(ctx, allProps, doc.body);
if (ctx.foundPartials === 0) {
throw new NoPartialsError(
`Found no partials in HTML response. Please make sure to render at least one partial. Requested url: ${res.url}`,
);
}
}
function revivePartials(
ctx: PartialReviveCtx,
allProps: DeserializedProps,
node: Element,
) {
let startNode = null;
let sib: ChildNode | null = node.firstChild;
let partialCount = 0;
let partialName = "";
let partialKey = "";
let partialMode = PartialMode.Replace;
while (sib !== null) {
if (isCommentNode(sib)) {
const comment = sib.data;
const parts = comment.split(":");
if (parts[0] === "frsh") {
sib = maybeHideMarker(sib);
}
if (parts[0] === "frsh" && parts[1] === "partial") {
if (++partialCount === 1) {
startNode = sib;
partialName = parts[2];
partialMode = +parts[3] as PartialMode;
partialKey = parts[4];
}
} else if (comment === "/frsh:partial") {
ctx.foundPartials++;
// Skip hydrating nested partials, only hydrate the outer one
if (--partialCount > 0) {
sib = sib.nextSibling;
continue;
}
// Create a fake DOM node that spans the partial we discovered.
// We need to include the partial markers itself for _walkInner
// to register them.
const container = createRootFragment(
node,
startNode as Comment,
sib as Comment,
);
const root = h(PartialComp, {
key: partialKey !== "" ? partialKey : undefined,
name: partialName,
mode: partialMode,
children: null,
});
domToVNode(
allProps,
[root],
[Marker.Partial],
container,
sib as Comment,
);
const instance = ACTIVE_PARTIALS.get(partialName);
if (instance === undefined) {
console.warn(`Partial "${partialName}" not found. Skipping...`);
// Partial doesn't exist on the current page
} else {
if (partialMode === PartialMode.Replace) {
instance.props.children = root.props.children;
} else if (partialMode === PartialMode.Append) {
const active = ACTIVE_PARTIALS.get(partialName);
if (active !== undefined) {
copyOldChildren(instance.props, active.props.children);
(instance.props.children as ComponentChildren[]).push(
root.props.children,
);
} else {
instance.props.children = root.props.children;
}
} else if (partialMode === PartialMode.Prepend) {
const active = ACTIVE_PARTIALS.get(partialName);
if (active !== undefined) {
copyOldChildren(instance.props, active.props.children);
(instance.props.children as ComponentChildren[]).unshift(
root.props.children,
);
} else {
instance.props.children = root.props.children;
}
}
instance.setState({});
}
}
} else if (partialCount === 0 && isElementNode(sib)) {
// Do not recurse if we know that we are inisde a partial
revivePartials(ctx, allProps, sib);
}
sib = sib.nextSibling;
}
}
+7
View File
@@ -0,0 +1,7 @@
// deno-lint-ignore-file ban-unknown-rule-code ban-unused-ignore
// Polyfill for old safari versions
if (typeof globalThis === "undefined") {
// @ts-ignore polyfill
// deno-lint-ignore no-window
window.globalThis = window;
}
@@ -0,0 +1,9 @@
import { options } from "preact";
import { assetHashingHook } from "../shared_internal.tsx";
import { BUILD_ID } from "../build_id.ts";
const oldVNodeHook = options.vnode;
options.vnode = (vnode) => {
assetHashingHook(vnode, BUILD_ID);
oldVNodeHook?.(vnode);
};
+567
View File
@@ -0,0 +1,567 @@
import {
Component,
type ComponentChildren,
type ComponentType,
Fragment,
h,
render,
type VNode,
} from "preact";
import { type CustomParser, parse } from "../../jsonify/parse.ts";
import { signal } from "@preact/signals";
import { DATA_FRESH_KEY, PartialMode } from "../shared_internal.tsx";
const enum RootKind {
Island,
Partial,
}
interface IslandReq {
kind: RootKind.Island;
name: string;
propsIdx: number;
key: string | null;
start: Comment | Text;
end: Comment | Text | null;
}
interface PartialReq {
kind: RootKind.Partial;
name: string;
key: string | null;
start: Comment | Text;
end: Comment | Text | null;
}
interface ReviveContext {
roots: Array<IslandReq | PartialReq>;
stack: Array<PartialReq | IslandReq>;
slots: Map<number, { name: string; start: Comment; end: Comment | null }>;
slotIdStack: number[];
}
interface SlotRef {
kind: typeof SLOT_SYMBOL;
name: string;
id: number;
}
const SLOT_SYMBOL = Symbol.for("_FRESH_SLOT");
function isSlotRef(x: unknown): x is SlotRef {
return x !== null && typeof x === "object" && "kind" in x &&
x.kind === SLOT_SYMBOL;
}
export type DeserializedProps = {
props: Record<string, unknown>;
slots: SlotRef[];
}[];
export const ACTIVE_PARTIALS = new Map<string, PartialComp>();
export class PartialComp extends Component<
{ children?: ComponentChildren; mode: PartialMode; name: string }
> {
componentDidMount() {
ACTIVE_PARTIALS.set(this.props.name, this);
}
render() {
return this.props.children;
}
}
PartialComp.displayName = "Partial";
export function revive(
props: Record<string, unknown>,
component: ComponentType,
container: HTMLElement,
slots: ReviveContext["slots"],
allProps: DeserializedProps,
) {
const _render = () => {
for (const propName in props) {
const value = props[propName];
if (isSlotRef(value)) {
const marker = slots.get(value.id);
if (marker !== undefined) {
const root = h(Fragment, null);
const slotContainer = createRootFragment(
container,
marker.start,
marker.end!,
);
domToVNode(
allProps,
[root],
[Marker.Slot],
slotContainer,
marker.end!,
);
props[propName] = root;
} else {
const template = document.querySelector(
`#frsh-${value.id}-${value.name}`,
) as HTMLTemplateElement | null;
if (template !== null) {
const root = h(Fragment, null);
domToVNode(allProps, [root], [Marker.Slot], template.content, null);
props[propName] = root;
}
}
}
}
// TODO: explore hydrate?
render(h(component, props), container as unknown as HTMLElement);
};
// deno-lint-ignore no-window
"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);
}
export const ISLAND_REGISTRY = new Map<string, ComponentType>();
export const CUSTOM_PARSER: CustomParser = {
Signal: (value: unknown) => signal(value),
Slot: (value: { name: string; id: number }): SlotRef => {
return { kind: SLOT_SYMBOL, name: value.name, id: value.id };
},
};
export function createReviveCtx(): ReviveContext {
return {
roots: [],
stack: [],
slots: new Map(),
slotIdStack: [],
};
}
export function boot(
initialIslands: Record<string, ComponentType>,
islandProps: string,
) {
const ctx = createReviveCtx();
_walkInner(ctx, document.body);
const keys = Object.keys(initialIslands);
for (let i = 0; i < keys.length; i++) {
const name = keys[i];
ISLAND_REGISTRY.set(name, initialIslands[name]);
}
const allProps = parse<DeserializedProps>(
islandProps,
CUSTOM_PARSER,
);
for (let i = 0; i < ctx.roots.length; i++) {
const root = ctx.roots[i];
const container = createRootFragment(
// deno-lint-ignore no-explicit-any
root.start.parentNode as any,
root.start,
root.end!,
);
if (root.kind === RootKind.Island) {
const props = allProps[root.propsIdx].props;
const component = ISLAND_REGISTRY.get(root.name)!;
revive(props, component, container, ctx.slots, allProps);
} else if (root.kind === RootKind.Partial) {
const props: Record<string, unknown> = {
name: root.name,
children: null,
};
const domRoot = h(Fragment, null);
domToVNode(allProps, [domRoot], [Marker.Partial], container, root.end!);
props.children = domRoot.props.children;
// deno-lint-ignore no-explicit-any
revive(props, PartialComp as any, container, ctx.slots, allProps);
}
}
}
const SHOW_MARKERS = false;
interface FreshMarker extends Text {
_frshMarker: string;
}
export function isFreshMarkerText(node: Node): node is FreshMarker {
return node.nodeType === Node.TEXT_NODE &&
// deno-lint-ignore no-explicit-any
typeof (node as any)._frshMarker === "string";
}
/**
* Replace comment markers with empty text nodes to hide them
* in DevTools. This is done to avoid user confusion.
*/
export function maybeHideMarker(marker: Comment): Comment | Text {
if (SHOW_MARKERS) return marker;
const text = new Text("") as FreshMarker;
text._frshMarker = marker.data;
marker.parentNode!.insertBefore(text, marker);
marker.remove();
return text;
}
function _walkInner(
ctx: ReviveContext,
node: Node | Comment,
) {
if (isElementNode(node)) {
// No need to traverse into <script> or <style> tags.
// No need to traverse deeper if we found a slotStart marker.
// We'll parse slots later when the island is revived.
if (
node.nodeName === "SCRIPT" || node.nodeName === "STYLE" ||
ctx.slotIdStack.length > 0
) {
return;
}
for (let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
_walkInner(ctx, child);
}
} else if (isCommentNode(node)) {
const comment = node.data;
if (comment.startsWith("frsh:")) {
node = maybeHideMarker(node);
const parts = comment.split(":");
const kind = parts[1];
if (kind === "island") {
const name = parts[2];
const propsIdx = parts[3];
const key = parts[4];
const found: IslandReq = {
kind: RootKind.Island,
name,
propsIdx: Number(propsIdx),
key: key === "" ? null : key,
start: node as Comment,
end: null,
};
if (ctx.stack.length === 0) {
ctx.roots.push(found);
}
ctx.stack.push(found);
} else if (kind === "slot") {
const id = +parts[2];
const slotName = parts[3];
ctx.slotIdStack.push(id);
ctx.slots.set(id, {
name: slotName,
start: node as Comment,
end: null,
});
} else if (kind === "partial") {
const name = parts[2];
const key = parts[3];
const found: PartialReq = {
kind: RootKind.Partial,
name,
key: key === "" ? null : key,
start: node as Comment,
end: null,
};
if (ctx.stack.length === 0) {
ctx.roots.push(found);
}
ctx.stack.push(found);
}
} else if (comment === "/frsh:island" || comment === "/frsh:partial") {
node = maybeHideMarker(node);
const item = ctx.stack.pop();
if (item !== undefined) {
item.end = node as Comment;
}
} else if (comment === "/frsh:slot") {
node = maybeHideMarker(node);
const item = ctx.slotIdStack.pop();
if (item !== undefined) {
ctx.slots.get(item)!.end = node as Comment;
}
}
}
}
export const enum Marker {
Island,
Partial,
Slot,
}
interface ServerSlotProps {
name: string;
id: number;
children?: ComponentChildren;
}
// deno-lint-ignore no-explicit-any
function ServerSlot(props: ServerSlotProps): any {
return props.children;
}
export function domToVNode(
allProps: DeserializedProps,
// deno-lint-ignore no-explicit-any
vnodeStack: VNode<any>[],
markerStack: Marker[],
node: Text | Comment | Node | DocumentFragment,
end: Text | Comment | null,
): void {
let sib: Node | ChildNode | null = node;
while (sib !== null) {
if (sib === end) return;
// deno-lint-ignore no-explicit-any
if ((sib as any)._frshRootFrag || sib instanceof DocumentFragment) {
const firstChild = sib.firstChild;
if (firstChild !== null) {
domToVNode(allProps, vnodeStack, markerStack, firstChild, end);
}
} else if (isElementNode(sib)) {
const props: Record<string, unknown> = {};
for (let i = 0; i < sib.attributes.length; i++) {
const attr = sib.attributes[i];
if (attr.nodeName === DATA_FRESH_KEY) {
props.key = attr.nodeValue;
continue;
}
// Boolean attributes are always `true` when present.
// See: https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML
props[attr.nodeName] =
// deno-lint-ignore no-explicit-any
typeof (sib as any)[attr.nodeName] === "boolean"
? true
: attr.nodeValue;
}
const vnode = h(sib.localName, props);
const marker = markerStack.at(-1);
const appendVNode = marker === Marker.Slot || marker === Marker.Partial;
if (appendVNode) {
addVNodeChild(vnodeStack.at(-1)!, vnode);
vnodeStack.push(vnode);
}
const firstChild = sib.firstChild;
if (firstChild !== null) {
domToVNode(allProps, vnodeStack, markerStack, firstChild, end);
}
if (appendVNode) {
vnodeStack.pop();
}
} else if (isCommentNode(sib) || isFreshMarkerText(sib)) {
const comment = isFreshMarkerText(sib) ? sib._frshMarker : sib.data;
if (comment.startsWith("frsh:")) {
const parts = comment.split(":");
const kind = parts[1];
if (kind === "island") {
sib = maybeHideMarker(sib);
markerStack.push(Marker.Island);
const name = parts[2];
const propsIdx = parts[3];
const key = parts[4];
const island = ISLAND_REGISTRY.get(name);
if (island === undefined) {
throw new Error(`Encountered unknown island: ${name}`);
}
const props = allProps[+propsIdx].props;
props.key = key === "" ? undefined : key;
// deno-lint-ignore no-explicit-any
const islandVNode = h<any>(island, props);
addVNodeChild(vnodeStack.at(-1)!, islandVNode);
vnodeStack.push(islandVNode);
} else if (kind === "slot") {
sib = maybeHideMarker(sib);
markerStack.push(Marker.Slot);
const id = +parts[2];
const slotName = parts[3];
const key = parts[4];
const vnode = h(ServerSlot, {
key: key === "" ? undefined : key,
id,
name: slotName,
children: [],
});
const parentVNode = vnodeStack.at(-1)!;
if (slotName === "children") {
addVNodeChild(parentVNode, vnode);
} else {
parentVNode.props[slotName] = vnode;
}
vnodeStack.push(vnode);
} else if (kind === "partial") {
sib = maybeHideMarker(sib);
markerStack.push(Marker.Partial);
const name = parts[2];
const mode = +parts[3] as PartialMode;
const key = parts[4];
// deno-lint-ignore no-explicit-any
let vnode: VNode<any> = h(PartialComp, {
name,
key: key === "" ? undefined : key,
mode,
});
const parentVNode = vnodeStack.at(-1);
if (parentVNode !== undefined) {
addVNodeChild(parentVNode, vnode);
}
if (mode === PartialMode.Append) {
const active = ACTIVE_PARTIALS.get(name);
if (active !== undefined) {
copyOldChildren(vnode.props, active.props.children);
const wrapper = h(Fragment, null);
addVNodeChild(vnode, wrapper);
vnode = wrapper;
}
} else if (mode === PartialMode.Prepend) {
const active = ACTIVE_PARTIALS.get(name);
if (active !== undefined) {
copyOldChildren(vnode.props, active.props.children);
const wrapper = h(Fragment, null);
if (!vnode.props.children) {
vnode.props.children = [];
}
// deno-lint-ignore no-explicit-any
(vnode.props.children as Array<VNode<any> | string>).unshift(
wrapper,
);
vnode = wrapper;
}
}
vnodeStack.push(vnode);
} else if (kind === "key") {
if (!SHOW_MARKERS) {
const current = sib;
sib = sib.nextSibling;
current.remove();
}
const vnode = h(Fragment, { key: parts[2] });
addVNodeChild(vnodeStack.at(-1)!, vnode);
vnodeStack.push(vnode);
continue;
}
} else if (
comment === "/frsh:island" || comment === "/frsh:slot" ||
comment === "/frsh:partial"
) {
vnodeStack.pop();
markerStack.pop();
sib = maybeHideMarker(sib);
} else if (comment === "/frsh:key") {
vnodeStack.pop();
sib = maybeHideMarker(sib);
}
} else if (isTextNode(sib)) {
const marker = markerStack.at(-1);
if (marker === Marker.Slot || marker === Marker.Partial) {
addVNodeChild(vnodeStack.at(-1)!, sib.data);
}
}
sib = sib.nextSibling;
}
}
// deno-lint-ignore no-explicit-any
function addVNodeChild(parent: VNode<any>, child: VNode<any> | string) {
if (!parent.props.children) {
parent.props.children = [];
}
// deno-lint-ignore no-explicit-any
(parent.props.children as Array<VNode<any> | string>).push(child);
}
export function copyOldChildren(
props: Record<string, unknown>,
oldChildren: ComponentChildren,
) {
props.children = oldChildren !== undefined && oldChildren !== null
? Array.isArray(oldChildren) ? oldChildren : [oldChildren]
: [];
}
export function isCommentNode(node: Node): node is Comment {
return node.nodeType === Node.COMMENT_NODE;
}
export function isTextNode(node: Node): node is Text {
return node.nodeType === Node.TEXT_NODE;
}
export function isElementNode(node: Node): node is HTMLElement {
return node.nodeType === Node.ELEMENT_NODE && !("_frshRootFrag" in node);
}
export function createRootFragment(
parent: Element,
startMarker: Text | Comment,
// We need an end marker for islands because multiple
// islands can share the same parent node. Since
// islands are root-level render calls any calls to
// `.appendChild` would lead to a wrong result.
endMarker: Text | Comment,
): HTMLElement & { _frshRootFrag: boolean } {
// @ts-ignore this is fine
return {
_frshRootFrag: true,
nodeType: 1,
parentNode: parent,
nextSibling: null,
get firstChild() {
const child = startMarker.nextSibling;
if (child === endMarker) return null;
return child;
},
get childNodes() {
const children: ChildNode[] = [];
let child = startMarker.nextSibling;
while (child !== null && child !== endMarker) {
children.push(child);
child = child.nextSibling;
}
return children;
},
insertBefore(node: Node, child: Node | null) {
parent.insertBefore(node, child ?? endMarker);
},
appendChild(child: Node) {
// We cannot blindly call `.append()` as that would add
// the new child to the very end of the parent node. This
// leads to ordering issues when the multiple islands
// share the same parent node.
parent.insertBefore(child, endMarker);
},
removeChild(child: Node) {
parent.removeChild(child);
},
// deno-lint-ignore no-explicit-any
} as any;
}