From 665d35bbc2218adb5ca07ec6bd0ac1c954f0d53e Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Wed, 27 Sep 2023 13:34:30 +0200 Subject: [PATCH] Add Partials (#1824) --- .vscode/settings.json | 1 + runtime.ts | 1 + src/constants.ts | 10 + src/runtime/Partial.tsx | 20 + src/runtime/entrypoints/main.ts | 523 +++++++++-- src/server/rendering/fresh_tags.tsx | 50 +- src/server/rendering/preact_hooks.ts | 95 +- src/server/rendering/state.ts | 5 +- tests/build_test.ts | 4 - tests/fixture_partials/components/Keyed.tsx | 5 + tests/fixture_partials/deno.json | 20 + tests/fixture_partials/dev.ts | 5 + tests/fixture_partials/fresh.gen.ts | 160 ++++ tests/fixture_partials/islands/Counter.tsx | 16 + tests/fixture_partials/islands/CounterA.tsx | 16 + tests/fixture_partials/islands/CounterB.tsx | 16 + tests/fixture_partials/islands/Fader.tsx | 26 + .../fixture_partials/islands/InvalidSlot.tsx | 11 + tests/fixture_partials/islands/Logger.tsx | 30 + tests/fixture_partials/islands/Other.tsx | 16 + .../islands/PartialTrigger.tsx | 23 + .../fixture_partials/islands/PassThrough.tsx | 15 + tests/fixture_partials/islands/PropIsland.tsx | 22 + tests/fixture_partials/islands/SignalProp.tsx | 12 + tests/fixture_partials/islands/Spinner.tsx | 7 + tests/fixture_partials/islands/Stateful.tsx | 13 + tests/fixture_partials/main.ts | 9 + tests/fixture_partials/routes/_app.tsx | 16 + .../routes/client_nav/_layout.tsx | 48 + .../routes/client_nav/index.tsx | 21 + .../routes/client_nav/injected.tsx | 10 + .../routes/client_nav/page-a.tsx | 17 + .../routes/client_nav/page-b.tsx | 20 + .../routes/client_nav/page-c.tsx | 17 + .../routes/client_nav_opt_out/_layout.tsx | 48 + .../routes/client_nav_opt_out/index.tsx | 21 + .../routes/client_nav_opt_out/injected.tsx | 10 + .../routes/client_nav_opt_out/page-a.tsx | 17 + .../routes/client_nav_opt_out/page-b.tsx | 20 + .../routes/client_nav_opt_out/page-c.tsx | 17 + tests/fixture_partials/routes/form/index.tsx | 19 + .../fixture_partials/routes/form/injected.tsx | 10 + tests/fixture_partials/routes/form/update.tsx | 19 + tests/fixture_partials/routes/index.tsx | 27 + .../routes/island_instance/index.tsx | 44 + .../routes/island_instance/injected.tsx | 10 + .../routes/island_instance/partial.tsx | 22 + .../routes/island_instance/partial_remove.tsx | 19 + .../island_instance/partial_replace.tsx | 21 + .../routes/island_instance_multiple/index.tsx | 46 + .../island_instance_multiple/injected.tsx | 10 + .../island_instance_multiple/partial.tsx | 22 + .../island_instance_multiple/partial_both.tsx | 31 + .../routes/island_instance_nested/index.tsx | 44 + .../island_instance_nested/injected.tsx | 10 + .../routes/island_instance_nested/partial.tsx | 29 + .../routes/island_instance_nested/replace.tsx | 17 + .../routes/island_props/index.tsx | 32 + .../routes/island_props/injected.tsx | 10 + .../routes/island_props/partial.tsx | 27 + .../routes/island_props_signals/index.tsx | 30 + .../routes/island_props_signals/injected.tsx | 10 + .../routes/island_props_signals/partial.tsx | 23 + tests/fixture_partials/routes/keys/index.tsx | 29 + .../fixture_partials/routes/keys/injected.tsx | 10 + tests/fixture_partials/routes/keys/swap.tsx | 25 + .../routes/keys_components/index.tsx | 36 + .../routes/keys_components/injected.tsx | 10 + .../routes/keys_components/swap.tsx | 32 + .../routes/keys_dom/index.tsx | 37 + .../routes/keys_dom/injected.tsx | 10 + .../fixture_partials/routes/keys_dom/swap.tsx | 33 + .../fixture_partials/routes/loading/index.tsx | 36 + .../routes/loading/injected.tsx | 10 + .../routes/loading/update.tsx | 20 + .../routes/missing_partial/index.tsx | 25 + .../routes/missing_partial/injected.tsx | 10 + .../routes/missing_partial/update.tsx | 16 + tests/fixture_partials/routes/mode/append.tsx | 21 + tests/fixture_partials/routes/mode/index.tsx | 45 + .../fixture_partials/routes/mode/injected.tsx | 10 + .../fixture_partials/routes/mode/prepend.tsx | 20 + .../fixture_partials/routes/mode/replace.tsx | 19 + .../routes/no_islands/index.tsx | 20 + .../routes/no_islands/injected.tsx | 10 + .../routes/no_islands/update.tsx | 16 + .../routes/partial_slot_inside_island.tsx | 5 + tests/fixture_partials/static/style.css | 8 + tests/main_test.ts | 2 +- tests/partials_test.ts | 876 ++++++++++++++++++ tests/server_components_test.ts | 2 +- tests/test_utils.ts | 49 +- 92 files changed, 3271 insertions(+), 116 deletions(-) create mode 100644 src/constants.ts create mode 100644 src/runtime/Partial.tsx create mode 100644 tests/fixture_partials/components/Keyed.tsx create mode 100644 tests/fixture_partials/deno.json create mode 100755 tests/fixture_partials/dev.ts create mode 100644 tests/fixture_partials/fresh.gen.ts create mode 100644 tests/fixture_partials/islands/Counter.tsx create mode 100644 tests/fixture_partials/islands/CounterA.tsx create mode 100644 tests/fixture_partials/islands/CounterB.tsx create mode 100644 tests/fixture_partials/islands/Fader.tsx create mode 100644 tests/fixture_partials/islands/InvalidSlot.tsx create mode 100644 tests/fixture_partials/islands/Logger.tsx create mode 100644 tests/fixture_partials/islands/Other.tsx create mode 100644 tests/fixture_partials/islands/PartialTrigger.tsx create mode 100644 tests/fixture_partials/islands/PassThrough.tsx create mode 100644 tests/fixture_partials/islands/PropIsland.tsx create mode 100644 tests/fixture_partials/islands/SignalProp.tsx create mode 100644 tests/fixture_partials/islands/Spinner.tsx create mode 100644 tests/fixture_partials/islands/Stateful.tsx create mode 100644 tests/fixture_partials/main.ts create mode 100644 tests/fixture_partials/routes/_app.tsx create mode 100644 tests/fixture_partials/routes/client_nav/_layout.tsx create mode 100644 tests/fixture_partials/routes/client_nav/index.tsx create mode 100644 tests/fixture_partials/routes/client_nav/injected.tsx create mode 100644 tests/fixture_partials/routes/client_nav/page-a.tsx create mode 100644 tests/fixture_partials/routes/client_nav/page-b.tsx create mode 100644 tests/fixture_partials/routes/client_nav/page-c.tsx create mode 100644 tests/fixture_partials/routes/client_nav_opt_out/_layout.tsx create mode 100644 tests/fixture_partials/routes/client_nav_opt_out/index.tsx create mode 100644 tests/fixture_partials/routes/client_nav_opt_out/injected.tsx create mode 100644 tests/fixture_partials/routes/client_nav_opt_out/page-a.tsx create mode 100644 tests/fixture_partials/routes/client_nav_opt_out/page-b.tsx create mode 100644 tests/fixture_partials/routes/client_nav_opt_out/page-c.tsx create mode 100644 tests/fixture_partials/routes/form/index.tsx create mode 100644 tests/fixture_partials/routes/form/injected.tsx create mode 100644 tests/fixture_partials/routes/form/update.tsx create mode 100644 tests/fixture_partials/routes/index.tsx create mode 100644 tests/fixture_partials/routes/island_instance/index.tsx create mode 100644 tests/fixture_partials/routes/island_instance/injected.tsx create mode 100644 tests/fixture_partials/routes/island_instance/partial.tsx create mode 100644 tests/fixture_partials/routes/island_instance/partial_remove.tsx create mode 100644 tests/fixture_partials/routes/island_instance/partial_replace.tsx create mode 100644 tests/fixture_partials/routes/island_instance_multiple/index.tsx create mode 100644 tests/fixture_partials/routes/island_instance_multiple/injected.tsx create mode 100644 tests/fixture_partials/routes/island_instance_multiple/partial.tsx create mode 100644 tests/fixture_partials/routes/island_instance_multiple/partial_both.tsx create mode 100644 tests/fixture_partials/routes/island_instance_nested/index.tsx create mode 100644 tests/fixture_partials/routes/island_instance_nested/injected.tsx create mode 100644 tests/fixture_partials/routes/island_instance_nested/partial.tsx create mode 100644 tests/fixture_partials/routes/island_instance_nested/replace.tsx create mode 100644 tests/fixture_partials/routes/island_props/index.tsx create mode 100644 tests/fixture_partials/routes/island_props/injected.tsx create mode 100644 tests/fixture_partials/routes/island_props/partial.tsx create mode 100644 tests/fixture_partials/routes/island_props_signals/index.tsx create mode 100644 tests/fixture_partials/routes/island_props_signals/injected.tsx create mode 100644 tests/fixture_partials/routes/island_props_signals/partial.tsx create mode 100644 tests/fixture_partials/routes/keys/index.tsx create mode 100644 tests/fixture_partials/routes/keys/injected.tsx create mode 100644 tests/fixture_partials/routes/keys/swap.tsx create mode 100644 tests/fixture_partials/routes/keys_components/index.tsx create mode 100644 tests/fixture_partials/routes/keys_components/injected.tsx create mode 100644 tests/fixture_partials/routes/keys_components/swap.tsx create mode 100644 tests/fixture_partials/routes/keys_dom/index.tsx create mode 100644 tests/fixture_partials/routes/keys_dom/injected.tsx create mode 100644 tests/fixture_partials/routes/keys_dom/swap.tsx create mode 100644 tests/fixture_partials/routes/loading/index.tsx create mode 100644 tests/fixture_partials/routes/loading/injected.tsx create mode 100644 tests/fixture_partials/routes/loading/update.tsx create mode 100644 tests/fixture_partials/routes/missing_partial/index.tsx create mode 100644 tests/fixture_partials/routes/missing_partial/injected.tsx create mode 100644 tests/fixture_partials/routes/missing_partial/update.tsx create mode 100644 tests/fixture_partials/routes/mode/append.tsx create mode 100644 tests/fixture_partials/routes/mode/index.tsx create mode 100644 tests/fixture_partials/routes/mode/injected.tsx create mode 100644 tests/fixture_partials/routes/mode/prepend.tsx create mode 100644 tests/fixture_partials/routes/mode/replace.tsx create mode 100644 tests/fixture_partials/routes/no_islands/index.tsx create mode 100644 tests/fixture_partials/routes/no_islands/injected.tsx create mode 100644 tests/fixture_partials/routes/no_islands/update.tsx create mode 100644 tests/fixture_partials/routes/partial_slot_inside_island.tsx create mode 100644 tests/fixture_partials/static/style.css create mode 100644 tests/partials_test.ts diff --git a/.vscode/settings.json b/.vscode/settings.json index dd9c9647..71c61549 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,6 +3,7 @@ "deno.lint": true, "deno.importMap": "./.vscode/import_map.json", "deno.codeLens.test": true, + "deno.documentPreloadLimit": 2000, "editor.formatOnSave": true, "editor.defaultFormatter": "denoland.vscode-deno", "[typescriptreact]": { diff --git a/runtime.ts b/runtime.ts index 3a8a6bb7..92500085 100644 --- a/runtime.ts +++ b/runtime.ts @@ -1,3 +1,4 @@ export * from "./src/runtime/utils.ts"; export * from "./src/runtime/head.ts"; export * from "./src/runtime/csp.ts"; +export * from "./src/runtime/Partial.tsx"; diff --git a/src/constants.ts b/src/constants.ts new file mode 100644 index 00000000..b4ae8f60 --- /dev/null +++ b/src/constants.ts @@ -0,0 +1,10 @@ +export const PARTIAL_SEARCH_PARAM = "fresh-partial"; +export const PARTIAL_ATTR = "fh-partial"; +export const LOADING_ATTR = "fh-loading"; +export const DATA_KEY_ATTR = "data-fresh-key"; + +export const enum PartialMode { + REPLACE, + APPEND, + PREPEND, +} diff --git a/src/runtime/Partial.tsx b/src/runtime/Partial.tsx new file mode 100644 index 00000000..caa837e5 --- /dev/null +++ b/src/runtime/Partial.tsx @@ -0,0 +1,20 @@ +import { ComponentChildren, VNode } from "preact"; + +export interface PartialProps { + children?: ComponentChildren; + /** + * The name of the partial. This value must be unique across partials. + */ + name: string; + /** + * Define how the new HTML should be applied. + * @default {"replace"} + */ + mode?: "replace" | "prepend" | "append"; +} + +export function Partial(props: PartialProps): VNode { + // deno-lint-ignore no-explicit-any + return props.children as any; +} +Partial.displayName = "Partial"; diff --git a/src/runtime/entrypoints/main.ts b/src/runtime/entrypoints/main.ts index 2e5b37a4..4bea985a 100644 --- a/src/runtime/entrypoints/main.ts +++ b/src/runtime/entrypoints/main.ts @@ -1,4 +1,5 @@ import { + Component, ComponentChildren, ComponentType, Fragment, @@ -8,6 +9,15 @@ import { VNode, } from "preact"; import { assetHashingHook } from "../utils.ts"; +import { type SerializedState } from "../../server/rendering/fresh_tags.tsx"; +import type { Signal } from "@preact/signals"; +import { + DATA_KEY_ATTR, + LOADING_ATTR, + PARTIAL_ATTR, + PARTIAL_SEARCH_PARAM, + PartialMode, +} from "../../constants.ts"; function createRootFragment( parent: Element, @@ -20,8 +30,10 @@ function createRootFragment( ) { // @ts-ignore this is fine return parent.__k = { + _frshRootFrag: true, nodeType: 1, parentNode: parent, + nextSibling: null, get firstChild() { const child = startMarker.nextSibling; if (child === endMarker) return null; @@ -61,14 +73,17 @@ 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; + return node.nodeType === Node.ELEMENT_NODE && !("_frshRootFrag" in node); } +type IslandRegistry = Record>; + export function revive( - islands: Record>, + islands: IslandRegistry, // deno-lint-ignore no-explicit-any props: any[], ) { + const result: RenderRequest[] = []; _walkInner( islands, props, @@ -78,11 +93,35 @@ export function revive( // later during iteration [h(Fragment, null)], document.body, + result, ); + + for (let i = 0; i < result.length; i++) { + const { vnode, marker, rootFragment } = result[i]; + const _render = () => { + render( + vnode, + rootFragment, + ); + + if (marker.kind === MarkerKind.Partial) { + // deno-lint-ignore no-explicit-any + partials.set(marker.text, (vnode as any).__c); + } + }; + + "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); + } } function ServerComponent( - props: { children: ComponentChildren }, + props: { children: ComponentChildren; id: string }, ): ComponentChildren { return props.children; } @@ -101,25 +140,38 @@ function addPropsChild(parent: VNode, vnode: ComponentChildren) { } } +class PartialComp extends Component< + { children?: ComponentChildren; mode: number; name: string } +> { + render() { + return this.props.children; + } +} + const enum MarkerKind { Island, Slot, + Partial, } 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: Text | Comment | null; endNode: Text | Comment | null; } +export interface RenderRequest { + vnode: VNode; + marker: Marker; + rootFragment: HTMLElement; +} + +// Useful for debugging const SHOW_MARKERS = false; +const partials = new Map(); + /** * Replace comment markers with empty text nodes to hide them * in DevTools. This is done to avoid user confusion. @@ -161,6 +213,7 @@ function addChildrenFromTemplate( markerStack: Marker[], vnodeStack: VNode[], comment: string, + result: RenderRequest[], ) { const [id, exportName, n] = comment.slice("/frsh-".length).split( ":", @@ -186,6 +239,7 @@ function addChildrenFromTemplate( markerStack, vnodeStack, node, + result, ); markerStack.pop(); @@ -227,6 +281,7 @@ function _walkInner( markerStack: Marker[], vnodeStack: VNode[], node: Node | Comment, + result: RenderRequest[], ) { let sib: Node | null = node; while (sib !== null) { @@ -251,7 +306,30 @@ function _walkInner( kind: MarkerKind.Slot, }); // @ts-ignore TS gets confused - vnodeStack.push(h(ServerComponent, { key: comment })); + vnodeStack.push(h(ServerComponent, { id: comment })); + } else if (comment.startsWith("frsh-partial")) { + // TODO: Partial key + const [_, name, mode, key] = comment.split(":"); + markerStack.push({ + startNode: sib, + text: name, + endNode: null, + kind: MarkerKind.Partial, + }); + + vnodeStack.push( + h(PartialComp, { name, key, mode: +mode }), + ); + } else if (comment.startsWith("frsh-key")) { + const key = comment.slice("frsh-key:".length); + vnodeStack.push(h(Fragment, { key })); + } else if (comment.startsWith("/frsh-key")) { + const vnode = vnodeStack.pop(); + const parent = vnodeStack[vnodeStack.length - 1]!; + addPropsChild(parent, vnode); + + sib = sib.nextSibling; + continue; } else if ( marker !== null && ( comment.startsWith("/frsh") || @@ -263,28 +341,28 @@ function _walkInner( 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(); + 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; - } + // 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; hideMarker(marker); sib = marker.endNode.nextSibling; continue; - } else if (marker.kind === MarkerKind.Island) { - // We're ready to revive this island if it has + } else if ( + marker !== null && ( + marker.kind === MarkerKind.Island || + marker.kind === MarkerKind.Partial + ) + ) { + // We're ready to revive this island or partial if it has // no roots of its own. Otherwise we'll treat it // as a standard component if (markerStack.length === 0) { @@ -297,6 +375,7 @@ function _walkInner( markerStack, vnodeStack, comment, + result, ); } vnodeStack.pop(); @@ -305,30 +384,23 @@ function _walkInner( hideMarker(marker); - const _render = () => - render( - vnode, - createRootFragment( - parentNode, - marker.startNode!, - marker.endNode!, - // deno-lint-ignore no-explicit-any - ) as any as HTMLElement, - ); + const rootFragment = createRootFragment( + parentNode, + marker.startNode!, + marker.endNode, + // 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); + result.push({ + vnode, + marker, + rootFragment, + }); sib = marker.endNode.nextSibling; continue; - } else if (parent?.kind === MarkerKind.Slot) { - // Treat the island as a standard component when it - // has an island parent or a slot parent + } else { + // Treat as a standard component const vnode = vnodeStack[vnodeStack.length - 1]; if (vnode && vnode.props.children == null) { addChildrenFromTemplate( @@ -337,6 +409,7 @@ function _walkInner( markerStack, vnodeStack, comment, + result, ); // Didn't find any template tag, proceed as usual @@ -352,13 +425,19 @@ function _walkInner( const parent = vnodeStack[vnodeStack.length - 1]!; addPropsChild(parent, vnode); + + if (marker.kind === MarkerKind.Partial) { + // deno-lint-ignore no-explicit-any + partials.set(marker.text, (vnode as any).__c); + } + sib = marker.endNode.nextSibling; continue; } } } else if (comment.startsWith("frsh")) { // We're opening a new island - const [id, exportName, n] = comment.slice(5).split(":"); + const [id, exportName, n, key] = comment.slice(5).split(":"); const islandProps = props[Number(n)]; markerStack.push({ @@ -367,67 +446,260 @@ function _walkInner( text: comment, kind: MarkerKind.Island, }); + const vnode = h(islands[id][exportName], islandProps); + if (key) vnode.key = key; vnodeStack.push(vnode); } } else if (isTextNode(sib)) { const parentVNode = vnodeStack[vnodeStack.length - 1]!; if ( - marker !== null && marker.kind === MarkerKind.Slot + marker !== null && + (marker.kind === MarkerKind.Slot || + marker.kind === MarkerKind.Partial) ) { 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]; - // Boolean attributes are always `true` when present. - // See: https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML - props[attr.nodeName] = + if (isElementNode(sib)) { + if ( + marker !== null && + (marker.kind === MarkerKind.Slot || + marker.kind === MarkerKind.Partial) + ) { + // 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 newProps: Record = { + children: childLen <= 1 ? null : [], + }; + let hasKey = false; + for (let i = 0; i < sib.attributes.length; i++) { + const attr = sib.attributes[i]; + + if (attr.nodeName === DATA_KEY_ATTR) { + hasKey = true; + newProps.key = attr.nodeValue; + continue; + } else if (attr.nodeName === LOADING_ATTR) { + console.log(attr.nodeName, attr.nodeValue); + const idx = attr.nodeValue; + const sig = props[Number(idx)][LOADING_ATTR].value; + // deno-lint-ignore no-explicit-any + (sib as any)._freshIndicator = sig; + } + + // Boolean attributes are always `true` when present. + // See: https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML + newProps[attr.nodeName] = + // deno-lint-ignore no-explicit-any + typeof (sib as any)[attr.nodeName] === "boolean" + ? true + : attr.nodeValue; + } + + // Remove internal fresh key + if (hasKey) sib.removeAttribute(DATA_KEY_ATTR); + + const vnode = h(sib.localName, newProps); + addPropsChild(parentVNode, vnode); + vnodeStack.push(vnode); + } else { + // Outside of any partial or island + const idx = sib.getAttribute(LOADING_ATTR); + if (idx !== null) { + console.log(props); + const sig = props[Number(idx)][LOADING_ATTR].value; // deno-lint-ignore no-explicit-any - typeof (sib as any)[attr.nodeName] === "boolean" - ? true - : attr.nodeValue; + (sib as any)._freshIndicator = sig; + } } - 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); + _walkInner( + islands, + props, + markerStack, + vnodeStack, + sib.firstChild, + result, + ); } - // Pop vnode if current marker is a slot or we are an island marker - // that was created inside another island + // Pop vnode if current marker is not the a top rendering + // component if ( marker !== null && - (marker.kind === MarkerKind.Slot || - markerStack.length > 1 && - markerStack[markerStack.length - 2].kind === MarkerKind.Island) + marker.kind !== MarkerKind.Island ) { vnodeStack.pop(); } } + if (sib !== null) { + sib = sib.nextSibling; + } + } +} + +const partialErrorMessage = `Unable to process partial response.`; + +async function fetchPartials(url: URL, init?: RequestInit) { + url.searchParams.set(PARTIAL_SEARCH_PARAM, "true"); + const res = await fetch(url, init); + await applyPartials(res); +} + +/** + * Apply partials from a HTML response + */ +export async function applyPartials(res: Response): Promise { + if (!res.ok) { + throw new Error(partialErrorMessage); + } + + const contentType = res.headers.get("Content-Type"); + if (contentType !== "text/html; charset=utf-8") { + throw new Error(partialErrorMessage); + } + + const resText = await res.text(); + const doc = new DOMParser().parseFromString(resText, "text/html") as Document; + + const promises: Promise[] = []; + + // Preload all islands because they need to be available synchronously + // for rendering later + const islands: IslandRegistry = {}; + const dataRaw = doc.getElementById("__FRSH_PARTIAL_DATA")!; + let data: { + islands: Record; + signals: string | null; + deserializer: string | null; + } | null = null; + if (dataRaw !== null) { + data = JSON.parse(dataRaw.textContent!); + + promises.push( + ...Array.from(Object.entries(data!.islands)).map(async (entry) => { + islands[entry[0]] = await import(`${entry[1]}`); + }), + ); + } + + const stateDom = doc.getElementById("__FRSH_STATE")?.textContent; + let state: SerializedState = [[], []]; + + // Load all dependencies + let signal: ((value: T) => Signal) | undefined; + if (data !== null && data.signals !== null) { + promises.push( + import(data.signals).then((m) => { + signal = m.signal; + }), + ); + } + + let deserialize: + | ((str: string, signal?: (value: T) => Signal) => unknown) + | undefined; + if (stateDom && data && data.deserializer !== null) { + promises.push( + import(data.deserializer).then((mod) => deserialize = mod.deserialize), + ); + } + + await Promise.all(promises); + + if (deserialize) { + state = deserialize(stateDom!, signal) as SerializedState; + } + + // Collect all partials and build up the vnode tree + const encounteredPartials: RenderRequest[] = []; + let startNode = null; + let sib: ChildNode | null = doc.body.firstChild; + while (sib !== null) { + if (isCommentNode(sib)) { + const comment = sib.data; + if (comment.startsWith("frsh-partial")) { + startNode = sib; + } else if (comment.startsWith("/frsh-partial")) { + // 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 rootFrag = { + _frshRootFrag: true, + nodeType: 1, + nextSibling: null, + firstChild: startNode, + parentNode: doc.body, + get childNodes() { + const children: ChildNode[] = [startNode!]; + let node = startNode!; + while ((node = node.nextSibling) !== null) { + children.push(node); + } + + return children; + }, + // deno-lint-ignore no-explicit-any + } as any as HTMLElement; + + _walkInner( + islands, + state[0] ?? [], + [], + [h(Fragment, null)], + rootFrag, + encounteredPartials, + ); + } + } + sib = sib.nextSibling; } + + // Update all encountered partials + for (let i = 0; i < encounteredPartials.length; i++) { + const { vnode, marker } = encounteredPartials[i]; + const instance = partials.get(marker.text); + + if (!instance) { + console.warn(`Partial "${marker.text}" not found. Skipping...`); + } else { + // deno-lint-ignore no-explicit-any + const mode = (vnode.props as any).mode; + const children = vnode.props.children; + + // Modify children depending on the replace mode + if (mode === PartialMode.REPLACE) { + instance.props.children = children; + } else { + const oldChildren = instance.props.children; + const newChildren = Array.isArray(oldChildren) + ? oldChildren + : [oldChildren]; + + if (mode === PartialMode.APPEND) { + newChildren.push(children); + } else { + newChildren.unshift(children); + } + instance.props.children = newChildren; + } + + instance.setState({}); + } + } } const originalHook = options.vnode; @@ -435,3 +707,108 @@ options.vnode = (vnode) => { assetHashingHook(vnode); if (originalHook) originalHook(vnode); }; + +// Keep track of history state to apply forward or backward animations +let index = history.state?.index || 0; +if (!history.state) { + history.replaceState({ index }, document.title); +} + +document.addEventListener("click", async (e) => { + let el = e.target; + if (el && el instanceof HTMLElement) { + // 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. + // There are two cases to account for: + // 1. Partial request + // 2. Normal request (turbolink-style) + const settingEl = el.closest("[fresh-client-nav]"); + if ( + partial === null && ( + settingEl === null || + settingEl.getAttribute("fresh-client-nav") !== "true" + ) + ) { + return; + } + + // deno-lint-ignore no-explicit-any + const indicator = (el as any)._freshIndicator; + if (indicator !== undefined) { + indicator.value = true; + } + + e.preventDefault(); + + try { + // Only add history entry when URL is new. Still apply + // the partials because sometimes users click a link to + // "refresh" the current page. + if (el.href !== window.location.href) { + index++; + history.pushState({ index }, "", el.href); + } + + const partialUrl = new URL( + partial ? partial : el.href, + location.origin, + ); + await fetchPartials(partialUrl); + } finally { + if (indicator !== undefined) { + indicator.value = false; + } + } + } + } +}); + +// deno-lint-ignore no-window-prefix +window.addEventListener("popstate", async () => { + const nextIdx = history.state?.index ?? index + 1; + index = nextIdx; + + // If we have the body partial, then we assume that we can + // do a full client-side navigation. Otherwise do a full + // page navigation. + if (partials.has("body")) { + const url = new URL(location.href, location.origin); + await fetchPartials(url); + } else { + window.location.href = location.href; + } +}); + +// Form submit +document.addEventListener("submit", async (e) => { + const el = e.target; + if (el !== null && el instanceof HTMLFormElement && !e.defaultPrevented) { + const partial = el.getAttribute(PARTIAL_ATTR); + if (partial !== null) { + e.preventDefault(); + + const url = new URL(partial, location.origin); + await fetchPartials(url); + } + } +}); diff --git a/src/server/rendering/fresh_tags.tsx b/src/server/rendering/fresh_tags.tsx index 6dacc575..c4d5fca8 100644 --- a/src/server/rendering/fresh_tags.tsx +++ b/src/server/rendering/fresh_tags.tsx @@ -6,6 +6,8 @@ import { Plugin, PluginRenderResult, PluginRenderStyleTag } from "../types.ts"; import { ContentSecurityPolicy, nonce } from "../../runtime/csp.ts"; import { h } from "preact"; +export type SerializedState = [islands: unknown[], plugins: unknown[]]; + export function renderFreshTags( renderState: RenderState, opts: { @@ -18,6 +20,8 @@ export function renderFreshTags( pluginRenderResults: [Plugin, PluginRenderResult][]; }, ) { + const { isPartial } = renderState; + if (opts.csp) { opts.csp.directives.scriptSrc = [ ...opts.csp.directives.scriptSrc ?? [], @@ -33,15 +37,17 @@ export function renderFreshTags( const preloadSet = new Set(); function addImport(path: string): string { const url = bundleAssetUrl(`/${path}`); - preloadSet.add(url); - for (const depPath of opts.dependenciesFn(path)) { - const url = bundleAssetUrl(`/${depPath}`); + if (!isPartial) { preloadSet.add(url); + for (const depPath of opts.dependenciesFn(path)) { + const url = bundleAssetUrl(`/${depPath}`); + preloadSet.add(url); + } } return url; } - const state: [islands: unknown[], plugins: unknown[]] = [ + const state: SerializedState = [ renderState.islandProps, [], ]; @@ -62,12 +68,17 @@ export function renderFreshTags( // Serialize the state into the `; + hasSignals = res.hasSignals; + requiresDeserializer = res.requiresDeserializer; + if (res.requiresDeserializer) { const url = addImport("deserializer.js"); script += `import { deserialize } from "${url}";`; @@ -102,25 +113,46 @@ export function renderFreshTags( script += `import p${i} from "${url}";runPlugin(p${i},STATE[1][${i}]);`; } - // Finally, it loads all island scripts and hydrates the islands using the - // reviver from the "main" script. - if (renderState.encounteredIslands.size > 0) { + if (renderState.encounteredIslands.size > 0 || renderState.partialCount > 0) { // Load the main.js script const url = addImport("main.js"); script += `import { revive } from "${url}";`; + } + // Finally, it loads all island scripts and hydrates the islands using the + // reviver from the "main" script. + let islandRegistry = ""; + const islandMapping: Record = {}; + if (renderState.encounteredIslands.size > 0) { // Prepare the inline script that loads and revives the islands - let islandRegistry = ""; for (const island of renderState.encounteredIslands) { const url = addImport(`island-${island.id}.js`); script += `import * as ${island.name}_${island.exportName} from "${url}";`; islandRegistry += `${island.id}:${island.name}_${island.exportName},`; + islandMapping[island.id] = url; } - script += `revive({${islandRegistry}}, STATE[0]);`; } + // Always revive to detect partials + script += `const propsArr = typeof STATE !== "undefined" ? STATE[0] : [];`; + script += `revive({${islandRegistry}}, propsArr);`; + // Append the inline script. + if (isPartial && Object.keys(islandMapping).length > 0) { + const escapedData = htmlEscapeJsonString( + JSON.stringify({ + islands: islandMapping, + signals: hasSignals ? addImport("signals.js") : null, + deserializer: requiresDeserializer + ? addImport("deserializer.js") + : null, + }), + ); + const nonce = renderState.csp ? ` nonce="${renderState.getNonce()}` : ""; + opts.bodyHtml += + ``; + } if (script !== "") { opts.bodyHtml += ``; diff --git a/src/server/rendering/preact_hooks.ts b/src/server/rendering/preact_hooks.ts index 9abddc12..23a529ba 100644 --- a/src/server/rendering/preact_hooks.ts +++ b/src/server/rendering/preact_hooks.ts @@ -1,6 +1,7 @@ import { Component, type ComponentChildren, + ComponentType, Fragment, h, isValidElement, @@ -9,9 +10,11 @@ import { type VNode, } from "preact"; import { assetHashingHook } from "../../runtime/utils.ts"; +import { Partial, PartialProps } from "../../runtime/Partial.tsx"; import { renderToString } from "preact-render-to-string"; import { RenderState } from "./state.ts"; import { Island } from "../types.ts"; +import { DATA_KEY_ATTR, LOADING_ATTR, PartialMode } from "../../constants.ts"; // See: https://github.com/preactjs/preact/blob/7748dcb83cedd02e37b3713634e35b97b26028fd/src/internal.d.ts#L3C1-L16 enum HookType { @@ -55,7 +58,7 @@ let current: RenderState | null = null; // passed as children. let ownerStack: VNode[] = []; // Keep track of all available islands -const islandByComponent = new Map(); +const islandByComponent = new Map(); export function setAllIslands(islands: Island[]) { for (let i = 0; i < islands.length; i++) { const island = islands[i]; @@ -133,6 +136,29 @@ function excludeChildren(props: Record) { return out; } +/** + * Check if the current component was rendered in an island + */ +function hasIslandOwner(current: RenderState, vnode: VNode): boolean { + let tmpVNode = vnode; + let owner; + while ((owner = current.owners.get(tmpVNode)) !== undefined) { + if (islandByComponent.has(owner.type as ComponentType)) { + return true; + } + tmpVNode = owner; + } + + return false; +} + +function encodePartialMode(mode: PartialProps["mode"]): PartialMode { + if (mode === "replace") return PartialMode.REPLACE; + else if (mode === "append") return PartialMode.APPEND; + else if (mode === "prepend") return PartialMode.PREPEND; + throw new Error(`Unknown partial mode "${mode}"`); +} + const patched = new WeakSet(); const oldVNodeHook = options.vnode; @@ -159,6 +185,16 @@ options.vnode = (vnode) => { props["ON" + key.slice(2)] = value; } } + // Don't do key preservation for nodes in . + if ( + vnode.key && vnode.type !== "meta" && vnode.type !== "title" && + vnode.type !== "style" && vnode.type !== "script" && vnode.type !== "link" + ) { + props[DATA_KEY_ATTR] = vnode.key; + } else if (props[LOADING_ATTR]) { + // Avoid automatic signals unwrapping + props[LOADING_ATTR] = { value: props[LOADING_ATTR] }; + } } else if ( current && typeof vnode.type === "function" && vnode.type !== Fragment && ownerStack.length > 0 @@ -221,32 +257,29 @@ options.__b = (vnode: VNode>) => { }); } vnode.type = Fragment; + } else if (LOADING_ATTR in vnode.props) { + current.islandProps.push({ + [LOADING_ATTR]: vnode.props[LOADING_ATTR], + }); + vnode.props[LOADING_ATTR] = current.islandProps.length - 1; } - } else if (typeof vnode.type === "function" && vnode.type !== Fragment) { + } else if (typeof vnode.type === "function") { // Detect island vnodes and wrap them with a marker const island = islandByComponent.get(vnode.type); patchIsland: if ( + vnode.type !== Fragment && island && !patched.has(vnode) ) { - // Keep track of whether we are inside an island to warn about - // hooks usage - current.islandCounter++; - // Check if an island is rendered inside another island, not just // passed as a child.In that case we treat it like a normal // Component. Example: - // function Island() {} + // function Island() { // return // } - let tmpVNode = vnode; - let owner; - while ((owner = current.owners.get(tmpVNode)) !== undefined) { - if (islandByComponent.has(owner.type)) { - break patchIsland; - } - tmpVNode = owner; + if (hasIslandOwner(current, vnode)) { + break patchIsland; } // At this point we know that we need to patch the island. Mark the @@ -304,9 +337,34 @@ options.__b = (vnode: VNode>) => { return wrapWithMarker( child, - `frsh-${island.id}:${island.exportName}:${islandProps.length - 1}`, + `frsh-${island.id}:${island.exportName}:${islandProps.length - 1}:${ + vnode.key ?? "" + }`, ); }; + // deno-lint-ignore no-explicit-any + } else if (vnode.type === (Partial as any)) { + current.partialCount++; + if (hasIslandOwner(current, vnode)) { + throw new Error( + ` components cannot be used inside islands.`, + ); + } + + const mode = encodePartialMode( + // deno-lint-ignore no-explicit-any + (vnode.props as any).mode ?? "replace", + ); + vnode.props.children = wrapWithMarker( + vnode.props.children, + `frsh-partial:${vnode.props.name}:${mode}:${vnode.key ?? ""}`, + ); + } else if (vnode.key) { + const child = h(vnode.type, vnode.props); + vnode.type = Fragment; + vnode.props = { + children: wrapWithMarker(child, `frsh-key:${vnode.key}`), + }; } } } @@ -324,9 +382,6 @@ options.__r = (vnode) => { options.diffed = (vnode: VNode>) => { if (typeof vnode.type === "function") { if (vnode.type !== Fragment) { - if (patched.has(vnode) && current) { - current.islandCounter--; - } ownerStack.pop(); } else if (vnode.props.__freshHead) { if (current) { @@ -338,11 +393,13 @@ options.diffed = (vnode: VNode>) => { }; options.__h = (component, idx, type) => { + // deno-lint-ignore no-explicit-any + const vnode = (component as any).__v; // Warn when using stateful hooks outside of islands if ( // Only error for stateful hooks for now. (type === HookType.useState || type === HookType.useReducer) && current && - current.islandCounter === 0 && + !islandByComponent.has(vnode.type) && !hasIslandOwner(current, vnode) && !current.error ) { const name = HookType[type]; diff --git a/src/server/rendering/state.ts b/src/server/rendering/state.ts index 2cd38760..0ca474d3 100644 --- a/src/server/rendering/state.ts +++ b/src/server/rendering/state.ts @@ -1,6 +1,7 @@ import { type ComponentChildren, type VNode } from "preact"; import { Island } from "../types.ts"; import { ContentSecurityPolicy } from "../../runtime/csp.ts"; +import { PARTIAL_SEARCH_PARAM } from "../../constants.ts"; export interface RenderStateRouteOptions { url: URL; @@ -36,8 +37,9 @@ export class RenderState { ownerStack: VNode[] = []; owners = new Map(); #nonce = ""; - islandCounter = 0; error: Error | null = null; + isPartial: boolean; + partialCount = 0; constructor( routeOptions: RenderStateRouteOptions, @@ -49,6 +51,7 @@ export class RenderState { this.routeOptions = routeOptions; this.csp = csp; this.componentStack = componentStack; + this.isPartial = routeOptions.url.searchParams.has(PARTIAL_SEARCH_PARAM); if (error) this.routeOptions.error = error; } diff --git a/tests/build_test.ts b/tests/build_test.ts index d182401e..043e4dbc 100644 --- a/tests/build_test.ts +++ b/tests/build_test.ts @@ -69,10 +69,6 @@ async function testBuild( Array.isArray(snapshot.files["signals.js"]), "signals.js output file not found in snapshot", ); - assert( - Array.isArray(snapshot.files["deserializer.js"]), - "deserializer.js output file not found in snapshot", - ); // Should not include `preact/debug` const mainJs = await Deno.readTextFile(path.join(outDir, "main.js")); diff --git a/tests/fixture_partials/components/Keyed.tsx b/tests/fixture_partials/components/Keyed.tsx new file mode 100644 index 00000000..4b20d8ae --- /dev/null +++ b/tests/fixture_partials/components/Keyed.tsx @@ -0,0 +1,5 @@ +import { ComponentChildren } from "preact"; + +export function Keyed(props: { children?: ComponentChildren }) { + return <>{props.children}; +} diff --git a/tests/fixture_partials/deno.json b/tests/fixture_partials/deno.json new file mode 100644 index 00000000..c4df0177 --- /dev/null +++ b/tests/fixture_partials/deno.json @@ -0,0 +1,20 @@ +{ + "lock": false, + "tasks": { + "start": "deno run -A --watch=static/,routes/ dev.ts" + }, + "imports": { + "$fresh/": "../../", + "twind": "https://esm.sh/twind@0.16.19", + "twind/": "https://esm.sh/twind@0.16.19/", + "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_partials/dev.ts b/tests/fixture_partials/dev.ts new file mode 100755 index 00000000..2d85d6c1 --- /dev/null +++ b/tests/fixture_partials/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_partials/fresh.gen.ts b/tests/fixture_partials/fresh.gen.ts new file mode 100644 index 00000000..ff47d6f7 --- /dev/null +++ b/tests/fixture_partials/fresh.gen.ts @@ -0,0 +1,160 @@ +// 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/_app.tsx"; +import * as $1 from "./routes/client_nav/_layout.tsx"; +import * as $2 from "./routes/client_nav/index.tsx"; +import * as $3 from "./routes/client_nav/injected.tsx"; +import * as $4 from "./routes/client_nav/page-a.tsx"; +import * as $5 from "./routes/client_nav/page-b.tsx"; +import * as $6 from "./routes/client_nav/page-c.tsx"; +import * as $7 from "./routes/client_nav_opt_out/_layout.tsx"; +import * as $8 from "./routes/client_nav_opt_out/index.tsx"; +import * as $9 from "./routes/client_nav_opt_out/injected.tsx"; +import * as $10 from "./routes/client_nav_opt_out/page-a.tsx"; +import * as $11 from "./routes/client_nav_opt_out/page-b.tsx"; +import * as $12 from "./routes/client_nav_opt_out/page-c.tsx"; +import * as $13 from "./routes/form/index.tsx"; +import * as $14 from "./routes/form/injected.tsx"; +import * as $15 from "./routes/form/update.tsx"; +import * as $16 from "./routes/index.tsx"; +import * as $17 from "./routes/island_instance/index.tsx"; +import * as $18 from "./routes/island_instance/injected.tsx"; +import * as $19 from "./routes/island_instance/partial.tsx"; +import * as $20 from "./routes/island_instance/partial_remove.tsx"; +import * as $21 from "./routes/island_instance/partial_replace.tsx"; +import * as $22 from "./routes/island_instance_multiple/index.tsx"; +import * as $23 from "./routes/island_instance_multiple/injected.tsx"; +import * as $24 from "./routes/island_instance_multiple/partial.tsx"; +import * as $25 from "./routes/island_instance_multiple/partial_both.tsx"; +import * as $26 from "./routes/island_instance_nested/index.tsx"; +import * as $27 from "./routes/island_instance_nested/injected.tsx"; +import * as $28 from "./routes/island_instance_nested/partial.tsx"; +import * as $29 from "./routes/island_instance_nested/replace.tsx"; +import * as $30 from "./routes/island_props/index.tsx"; +import * as $31 from "./routes/island_props/injected.tsx"; +import * as $32 from "./routes/island_props/partial.tsx"; +import * as $33 from "./routes/island_props_signals/index.tsx"; +import * as $34 from "./routes/island_props_signals/injected.tsx"; +import * as $35 from "./routes/island_props_signals/partial.tsx"; +import * as $36 from "./routes/keys/index.tsx"; +import * as $37 from "./routes/keys/injected.tsx"; +import * as $38 from "./routes/keys/swap.tsx"; +import * as $39 from "./routes/keys_components/index.tsx"; +import * as $40 from "./routes/keys_components/injected.tsx"; +import * as $41 from "./routes/keys_components/swap.tsx"; +import * as $42 from "./routes/keys_dom/index.tsx"; +import * as $43 from "./routes/keys_dom/injected.tsx"; +import * as $44 from "./routes/keys_dom/swap.tsx"; +import * as $45 from "./routes/loading/index.tsx"; +import * as $46 from "./routes/loading/injected.tsx"; +import * as $47 from "./routes/loading/update.tsx"; +import * as $48 from "./routes/missing_partial/index.tsx"; +import * as $49 from "./routes/missing_partial/injected.tsx"; +import * as $50 from "./routes/missing_partial/update.tsx"; +import * as $51 from "./routes/mode/append.tsx"; +import * as $52 from "./routes/mode/index.tsx"; +import * as $53 from "./routes/mode/injected.tsx"; +import * as $54 from "./routes/mode/prepend.tsx"; +import * as $55 from "./routes/mode/replace.tsx"; +import * as $56 from "./routes/no_islands/index.tsx"; +import * as $57 from "./routes/no_islands/injected.tsx"; +import * as $58 from "./routes/no_islands/update.tsx"; +import * as $59 from "./routes/partial_slot_inside_island.tsx"; +import * as $$0 from "./islands/Counter.tsx"; +import * as $$1 from "./islands/CounterA.tsx"; +import * as $$2 from "./islands/CounterB.tsx"; +import * as $$3 from "./islands/Fader.tsx"; +import * as $$4 from "./islands/InvalidSlot.tsx"; +import * as $$5 from "./islands/Logger.tsx"; +import * as $$6 from "./islands/Other.tsx"; +import * as $$7 from "./islands/PartialTrigger.tsx"; +import * as $$8 from "./islands/PassThrough.tsx"; +import * as $$9 from "./islands/PropIsland.tsx"; +import * as $$10 from "./islands/SignalProp.tsx"; +import * as $$11 from "./islands/Spinner.tsx"; +import * as $$12 from "./islands/Stateful.tsx"; + +const manifest = { + routes: { + "./routes/_app.tsx": $0, + "./routes/client_nav/_layout.tsx": $1, + "./routes/client_nav/index.tsx": $2, + "./routes/client_nav/injected.tsx": $3, + "./routes/client_nav/page-a.tsx": $4, + "./routes/client_nav/page-b.tsx": $5, + "./routes/client_nav/page-c.tsx": $6, + "./routes/client_nav_opt_out/_layout.tsx": $7, + "./routes/client_nav_opt_out/index.tsx": $8, + "./routes/client_nav_opt_out/injected.tsx": $9, + "./routes/client_nav_opt_out/page-a.tsx": $10, + "./routes/client_nav_opt_out/page-b.tsx": $11, + "./routes/client_nav_opt_out/page-c.tsx": $12, + "./routes/form/index.tsx": $13, + "./routes/form/injected.tsx": $14, + "./routes/form/update.tsx": $15, + "./routes/index.tsx": $16, + "./routes/island_instance/index.tsx": $17, + "./routes/island_instance/injected.tsx": $18, + "./routes/island_instance/partial.tsx": $19, + "./routes/island_instance/partial_remove.tsx": $20, + "./routes/island_instance/partial_replace.tsx": $21, + "./routes/island_instance_multiple/index.tsx": $22, + "./routes/island_instance_multiple/injected.tsx": $23, + "./routes/island_instance_multiple/partial.tsx": $24, + "./routes/island_instance_multiple/partial_both.tsx": $25, + "./routes/island_instance_nested/index.tsx": $26, + "./routes/island_instance_nested/injected.tsx": $27, + "./routes/island_instance_nested/partial.tsx": $28, + "./routes/island_instance_nested/replace.tsx": $29, + "./routes/island_props/index.tsx": $30, + "./routes/island_props/injected.tsx": $31, + "./routes/island_props/partial.tsx": $32, + "./routes/island_props_signals/index.tsx": $33, + "./routes/island_props_signals/injected.tsx": $34, + "./routes/island_props_signals/partial.tsx": $35, + "./routes/keys/index.tsx": $36, + "./routes/keys/injected.tsx": $37, + "./routes/keys/swap.tsx": $38, + "./routes/keys_components/index.tsx": $39, + "./routes/keys_components/injected.tsx": $40, + "./routes/keys_components/swap.tsx": $41, + "./routes/keys_dom/index.tsx": $42, + "./routes/keys_dom/injected.tsx": $43, + "./routes/keys_dom/swap.tsx": $44, + "./routes/loading/index.tsx": $45, + "./routes/loading/injected.tsx": $46, + "./routes/loading/update.tsx": $47, + "./routes/missing_partial/index.tsx": $48, + "./routes/missing_partial/injected.tsx": $49, + "./routes/missing_partial/update.tsx": $50, + "./routes/mode/append.tsx": $51, + "./routes/mode/index.tsx": $52, + "./routes/mode/injected.tsx": $53, + "./routes/mode/prepend.tsx": $54, + "./routes/mode/replace.tsx": $55, + "./routes/no_islands/index.tsx": $56, + "./routes/no_islands/injected.tsx": $57, + "./routes/no_islands/update.tsx": $58, + "./routes/partial_slot_inside_island.tsx": $59, + }, + islands: { + "./islands/Counter.tsx": $$0, + "./islands/CounterA.tsx": $$1, + "./islands/CounterB.tsx": $$2, + "./islands/Fader.tsx": $$3, + "./islands/InvalidSlot.tsx": $$4, + "./islands/Logger.tsx": $$5, + "./islands/Other.tsx": $$6, + "./islands/PartialTrigger.tsx": $$7, + "./islands/PassThrough.tsx": $$8, + "./islands/PropIsland.tsx": $$9, + "./islands/SignalProp.tsx": $$10, + "./islands/Spinner.tsx": $$11, + "./islands/Stateful.tsx": $$12, + }, + baseUrl: import.meta.url, +}; + +export default manifest; diff --git a/tests/fixture_partials/islands/Counter.tsx b/tests/fixture_partials/islands/Counter.tsx new file mode 100644 index 00000000..463560fb --- /dev/null +++ b/tests/fixture_partials/islands/Counter.tsx @@ -0,0 +1,16 @@ +import { useSignal } from "@preact/signals"; +import { Logger } from "./Logger.tsx"; + +export default function Counter(props: { id: string }) { + const sig = useSignal(0); + return ( + +
+

{sig.value}

+ +
+
+ ); +} diff --git a/tests/fixture_partials/islands/CounterA.tsx b/tests/fixture_partials/islands/CounterA.tsx new file mode 100644 index 00000000..b4d90568 --- /dev/null +++ b/tests/fixture_partials/islands/CounterA.tsx @@ -0,0 +1,16 @@ +import { useSignal } from "@preact/signals"; +import { Logger } from "./Logger.tsx"; + +export default function CounterA() { + const sig = useSignal(0); + return ( + +
+

{sig.value}

+ +
+
+ ); +} diff --git a/tests/fixture_partials/islands/CounterB.tsx b/tests/fixture_partials/islands/CounterB.tsx new file mode 100644 index 00000000..f41df021 --- /dev/null +++ b/tests/fixture_partials/islands/CounterB.tsx @@ -0,0 +1,16 @@ +import { useSignal } from "@preact/signals"; +import { Logger } from "./Logger.tsx"; + +export default function CounterB() { + const sig = useSignal(0); + return ( + +
+

{sig.value}

+ +
+
+ ); +} diff --git a/tests/fixture_partials/islands/Fader.tsx b/tests/fixture_partials/islands/Fader.tsx new file mode 100644 index 00000000..bbdfb69a --- /dev/null +++ b/tests/fixture_partials/islands/Fader.tsx @@ -0,0 +1,26 @@ +import { useEffect, useRef } from "preact/hooks"; +import { ComponentChildren } from "preact"; + +export function Fader(props: { children?: ComponentChildren }) { + const ref = useRef(null); + const mounted = useRef(false); + + useEffect(() => { + if (!mounted.current) { + mounted.current = true; + return; + } + if (ref.current) { + ref.current.animate([ + { backgroundColor: "white" }, + { backgroundColor: "peachpuff" }, + ], { + fill: "backwards", + easing: "ease-out", + duration: 600, + }); + } + }); + + return
{props.children}
; +} diff --git a/tests/fixture_partials/islands/InvalidSlot.tsx b/tests/fixture_partials/islands/InvalidSlot.tsx new file mode 100644 index 00000000..15215497 --- /dev/null +++ b/tests/fixture_partials/islands/InvalidSlot.tsx @@ -0,0 +1,11 @@ +import { Partial } from "$fresh/runtime.ts"; + +export default function InvalidSlot() { + return ( +
+ +

it doesn't work

+
+
+ ); +} diff --git a/tests/fixture_partials/islands/Logger.tsx b/tests/fixture_partials/islands/Logger.tsx new file mode 100644 index 00000000..a0b1c36a --- /dev/null +++ b/tests/fixture_partials/islands/Logger.tsx @@ -0,0 +1,30 @@ +import { ComponentChildren } from "preact"; +import { useEffect, useRef } from "preact/hooks"; + +export function Logger(props: { children?: ComponentChildren; name?: string }) { + const mounted = useRef(false); + + useEffect(() => { + mounted.current = true; + const logs = document.querySelector("#logs"); + if (logs) { + logs.textContent += `mount ${props.name}\n`; + } + + return () => { + if (logs) { + logs.textContent += `unmount ${props.name}\n`; + } + }; + }, []); + + if (mounted.current && typeof document !== "undefined") { + const logs = document.querySelector("#logs"); + if (logs) { + logs.textContent += `update ${props.name}\n`; + } + } + + // deno-lint-ignore no-explicit-any + return props.children as any; +} diff --git a/tests/fixture_partials/islands/Other.tsx b/tests/fixture_partials/islands/Other.tsx new file mode 100644 index 00000000..501078f6 --- /dev/null +++ b/tests/fixture_partials/islands/Other.tsx @@ -0,0 +1,16 @@ +import { useSignal } from "@preact/signals"; +import { Logger } from "./Logger.tsx"; + +export default function Other() { + const sig = useSignal(0); + return ( + +
+

{sig.value}

+ +
+
+ ); +} diff --git a/tests/fixture_partials/islands/PartialTrigger.tsx b/tests/fixture_partials/islands/PartialTrigger.tsx new file mode 100644 index 00000000..c8989947 --- /dev/null +++ b/tests/fixture_partials/islands/PartialTrigger.tsx @@ -0,0 +1,23 @@ +import { Signal } from "@preact/signals"; +import { ComponentChildren } from "preact"; + +export default function PartialTrigger( + props: { + class: string; + href: string; + partial?: string; + loading?: Signal; + children?: ComponentChildren; + }, +) { + return ( + + {props.children} + + ); +} diff --git a/tests/fixture_partials/islands/PassThrough.tsx b/tests/fixture_partials/islands/PassThrough.tsx new file mode 100644 index 00000000..fc9012fb --- /dev/null +++ b/tests/fixture_partials/islands/PassThrough.tsx @@ -0,0 +1,15 @@ +import { Fader } from "$fresh/tests/fixture_partials/islands/Fader.tsx"; +import { Logger } from "./Logger.tsx"; +import { ComponentChildren } from "preact"; + +export default function PassThrough(props: { children?: ComponentChildren }) { + return ( + + +
+ {props.children} +
+
+
+ ); +} diff --git a/tests/fixture_partials/islands/PropIsland.tsx b/tests/fixture_partials/islands/PropIsland.tsx new file mode 100644 index 00000000..89cb8902 --- /dev/null +++ b/tests/fixture_partials/islands/PropIsland.tsx @@ -0,0 +1,22 @@ +export default function PropIsland( + props: { + number: number; + string: string; + boolean: boolean; + strArr: string[]; + obj: { foo: number }; + }, +) { + return ( +
+      {JSON.stringify({
+        number: props.number,
+        string: props.string,
+        null: null,
+        boolean: props.boolean,
+        object: props.obj,
+        strArr: props.strArr,
+      },null,2)}
+    
+ ); +} diff --git a/tests/fixture_partials/islands/SignalProp.tsx b/tests/fixture_partials/islands/SignalProp.tsx new file mode 100644 index 00000000..263593db --- /dev/null +++ b/tests/fixture_partials/islands/SignalProp.tsx @@ -0,0 +1,12 @@ +import { Signal } from "@preact/signals"; + +export default function SignalProp(props: { sig: Signal }) { + return ( +
+

{props.sig.value}

+ +
+ ); +} diff --git a/tests/fixture_partials/islands/Spinner.tsx b/tests/fixture_partials/islands/Spinner.tsx new file mode 100644 index 00000000..d2c08981 --- /dev/null +++ b/tests/fixture_partials/islands/Spinner.tsx @@ -0,0 +1,7 @@ +import { Signal } from "@preact/signals"; + +export default function Spinner(props: { id: string; show: Signal }) { + return props.show.value + ?

loading...

+ : null; +} diff --git a/tests/fixture_partials/islands/Stateful.tsx b/tests/fixture_partials/islands/Stateful.tsx new file mode 100644 index 00000000..d2579baf --- /dev/null +++ b/tests/fixture_partials/islands/Stateful.tsx @@ -0,0 +1,13 @@ +import { useState } from "preact/hooks"; + +export default function Stateful(props: { id: string }) { + const [v, set] = useState(0); + return ( +
+

{v}

+ +
+ ); +} diff --git a/tests/fixture_partials/main.ts b/tests/fixture_partials/main.ts new file mode 100644 index 00000000..552ac27d --- /dev/null +++ b/tests/fixture_partials/main.ts @@ -0,0 +1,9 @@ +/// +/// +/// +/// + +import { start } from "$fresh/server.ts"; +import manifest from "./fresh.gen.ts"; + +await start(manifest); diff --git a/tests/fixture_partials/routes/_app.tsx b/tests/fixture_partials/routes/_app.tsx new file mode 100644 index 00000000..bdfa0118 --- /dev/null +++ b/tests/fixture_partials/routes/_app.tsx @@ -0,0 +1,16 @@ +import { defineApp } from "$fresh/src/server/defines.ts"; + +export default defineApp((res, ctx) => { + return ( + + + + test + + + + + + + ); +}); diff --git a/tests/fixture_partials/routes/client_nav/_layout.tsx b/tests/fixture_partials/routes/client_nav/_layout.tsx new file mode 100644 index 00000000..0390b3f7 --- /dev/null +++ b/tests/fixture_partials/routes/client_nav/_layout.tsx @@ -0,0 +1,48 @@ +import { AppProps } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; + +export default function AppLayout({ Component }: AppProps) { + return ( + + + + + fresh title + + + + + + + +

+ + Page A + +

+

+ + Page B + +

+

+ + Page C + +

+ +
+      
+    
+  );
+}
diff --git a/tests/fixture_partials/routes/client_nav/index.tsx b/tests/fixture_partials/routes/client_nav/index.tsx
new file mode 100644
index 00000000..bf717a6a
--- /dev/null
+++ b/tests/fixture_partials/routes/client_nav/index.tsx
@@ -0,0 +1,21 @@
+import { Partial } from "$fresh/runtime.ts";
+import { RouteConfig } from "$fresh/server.ts";
+import CounterA from "../../islands/CounterA.tsx";
+import { Fader } from "../../islands/Fader.tsx";
+
+export const config: RouteConfig = {
+  skipAppWrapper: true,
+};
+
+export default function ModeDemo() {
+  return (
+    
+ + +

Initial content

+ +
+
+
+ ); +} diff --git a/tests/fixture_partials/routes/client_nav/injected.tsx b/tests/fixture_partials/routes/client_nav/injected.tsx new file mode 100644 index 00000000..3b9b5a29 --- /dev/null +++ b/tests/fixture_partials/routes/client_nav/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/client_nav", + }, + }); +}); diff --git a/tests/fixture_partials/routes/client_nav/page-a.tsx b/tests/fixture_partials/routes/client_nav/page-a.tsx new file mode 100644 index 00000000..94fcfa0b --- /dev/null +++ b/tests/fixture_partials/routes/client_nav/page-a.tsx @@ -0,0 +1,17 @@ +import { RouteConfig } from "$fresh/server.ts"; +import CounterA from "../../islands/CounterA.tsx"; +import { Fader } from "../../islands/Fader.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, +}; + +export default function PageA() { + return ( + +

Page A

+

asdfasdf asdf asdf

+ +
+ ); +} diff --git a/tests/fixture_partials/routes/client_nav/page-b.tsx b/tests/fixture_partials/routes/client_nav/page-b.tsx new file mode 100644 index 00000000..70468dc2 --- /dev/null +++ b/tests/fixture_partials/routes/client_nav/page-b.tsx @@ -0,0 +1,20 @@ +import { RouteConfig } from "$fresh/server.ts"; +import { Fader } from "../../islands/Fader.tsx"; +import CounterB from "../../islands/CounterB.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, +}; + +export default function PageB() { + return ( + + something before +
+

Page B

+
+ +

asdfasdf asdf asdf

+
+ ); +} diff --git a/tests/fixture_partials/routes/client_nav/page-c.tsx b/tests/fixture_partials/routes/client_nav/page-c.tsx new file mode 100644 index 00000000..577849e7 --- /dev/null +++ b/tests/fixture_partials/routes/client_nav/page-c.tsx @@ -0,0 +1,17 @@ +import { RouteConfig } from "$fresh/server.ts"; +import { Fader } from "../../islands/Fader.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, +}; + +export default function PageB() { + return ( + +

Page C

+ +

asdfasdf asdf asdf

+
+
+ ); +} diff --git a/tests/fixture_partials/routes/client_nav_opt_out/_layout.tsx b/tests/fixture_partials/routes/client_nav_opt_out/_layout.tsx new file mode 100644 index 00000000..56ac8878 --- /dev/null +++ b/tests/fixture_partials/routes/client_nav_opt_out/_layout.tsx @@ -0,0 +1,48 @@ +import { AppProps } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; + +export default function AppLayout({ Component }: AppProps) { + return ( + + + + + fresh title + + + + + + + +

+ + Page A + +

+

+ + Page B + +

+

+ + Page C + +

+ +
+      
+    
+  );
+}
diff --git a/tests/fixture_partials/routes/client_nav_opt_out/index.tsx b/tests/fixture_partials/routes/client_nav_opt_out/index.tsx
new file mode 100644
index 00000000..bf717a6a
--- /dev/null
+++ b/tests/fixture_partials/routes/client_nav_opt_out/index.tsx
@@ -0,0 +1,21 @@
+import { Partial } from "$fresh/runtime.ts";
+import { RouteConfig } from "$fresh/server.ts";
+import CounterA from "../../islands/CounterA.tsx";
+import { Fader } from "../../islands/Fader.tsx";
+
+export const config: RouteConfig = {
+  skipAppWrapper: true,
+};
+
+export default function ModeDemo() {
+  return (
+    
+ + +

Initial content

+ +
+
+
+ ); +} diff --git a/tests/fixture_partials/routes/client_nav_opt_out/injected.tsx b/tests/fixture_partials/routes/client_nav_opt_out/injected.tsx new file mode 100644 index 00000000..52fc8fff --- /dev/null +++ b/tests/fixture_partials/routes/client_nav_opt_out/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/client_nav_opt_out", + }, + }); +}); diff --git a/tests/fixture_partials/routes/client_nav_opt_out/page-a.tsx b/tests/fixture_partials/routes/client_nav_opt_out/page-a.tsx new file mode 100644 index 00000000..94fcfa0b --- /dev/null +++ b/tests/fixture_partials/routes/client_nav_opt_out/page-a.tsx @@ -0,0 +1,17 @@ +import { RouteConfig } from "$fresh/server.ts"; +import CounterA from "../../islands/CounterA.tsx"; +import { Fader } from "../../islands/Fader.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, +}; + +export default function PageA() { + return ( + +

Page A

+

asdfasdf asdf asdf

+ +
+ ); +} diff --git a/tests/fixture_partials/routes/client_nav_opt_out/page-b.tsx b/tests/fixture_partials/routes/client_nav_opt_out/page-b.tsx new file mode 100644 index 00000000..70468dc2 --- /dev/null +++ b/tests/fixture_partials/routes/client_nav_opt_out/page-b.tsx @@ -0,0 +1,20 @@ +import { RouteConfig } from "$fresh/server.ts"; +import { Fader } from "../../islands/Fader.tsx"; +import CounterB from "../../islands/CounterB.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, +}; + +export default function PageB() { + return ( + + something before +
+

Page B

+
+ +

asdfasdf asdf asdf

+
+ ); +} diff --git a/tests/fixture_partials/routes/client_nav_opt_out/page-c.tsx b/tests/fixture_partials/routes/client_nav_opt_out/page-c.tsx new file mode 100644 index 00000000..577849e7 --- /dev/null +++ b/tests/fixture_partials/routes/client_nav_opt_out/page-c.tsx @@ -0,0 +1,17 @@ +import { RouteConfig } from "$fresh/server.ts"; +import { Fader } from "../../islands/Fader.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, +}; + +export default function PageB() { + return ( + +

Page C

+ +

asdfasdf asdf asdf

+
+
+ ); +} diff --git a/tests/fixture_partials/routes/form/index.tsx b/tests/fixture_partials/routes/form/index.tsx new file mode 100644 index 00000000..77cd87b9 --- /dev/null +++ b/tests/fixture_partials/routes/form/index.tsx @@ -0,0 +1,19 @@ +import { Partial } from "$fresh/runtime.ts"; + +export default function SlotDemo() { + return ( +
+
+ +

Default content

+

+ +

+
+ +
+
+ ); +} diff --git a/tests/fixture_partials/routes/form/injected.tsx b/tests/fixture_partials/routes/form/injected.tsx new file mode 100644 index 00000000..c26cf8ac --- /dev/null +++ b/tests/fixture_partials/routes/form/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/form", + }, + }); +}); diff --git a/tests/fixture_partials/routes/form/update.tsx b/tests/fixture_partials/routes/form/update.tsx new file mode 100644 index 00000000..61b9d822 --- /dev/null +++ b/tests/fixture_partials/routes/form/update.tsx @@ -0,0 +1,19 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + +

it works

+

+ +

+
+ ); +}); diff --git a/tests/fixture_partials/routes/index.tsx b/tests/fixture_partials/routes/index.tsx new file mode 100644 index 00000000..9c432289 --- /dev/null +++ b/tests/fixture_partials/routes/index.tsx @@ -0,0 +1,27 @@ +import * as path from "https://deno.land/std@0.192.0/path/mod.ts"; + +const __dirname = path.dirname(path.fromFileUrl(import.meta.url)); + +const links: string[] = []; +for (const file of Deno.readDirSync(__dirname)) { + if (file.name.startsWith("index")) continue; + const name = path.basename(file.name, path.extname(file.name)); + links.push(name); +} + +export default function Home() { + return ( +
+

Tests

+
    + {links.sort().map((link) => { + return ( +
  • + {link} +
  • + ); + })} +
+
+ ); +} diff --git a/tests/fixture_partials/routes/island_instance/index.tsx b/tests/fixture_partials/routes/island_instance/index.tsx new file mode 100644 index 00000000..bb41caa4 --- /dev/null +++ b/tests/fixture_partials/routes/island_instance/index.tsx @@ -0,0 +1,44 @@ +import { Partial } from "$fresh/runtime.ts"; +import CounterA from "../../islands/CounterA.tsx"; +import { Fader } from "../../islands/Fader.tsx"; + +export default function SlotDemo() { + return ( +
+ + +

Initial content

+ +
+
+

+ + Update + +

+

+ + Remove + +

+

+ + Replace + +

+
+    
+ ); +} diff --git a/tests/fixture_partials/routes/island_instance/injected.tsx b/tests/fixture_partials/routes/island_instance/injected.tsx new file mode 100644 index 00000000..cb6b2285 --- /dev/null +++ b/tests/fixture_partials/routes/island_instance/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/island_instance", + }, + }); +}); diff --git a/tests/fixture_partials/routes/island_instance/partial.tsx b/tests/fixture_partials/routes/island_instance/partial.tsx new file mode 100644 index 00000000..ba517449 --- /dev/null +++ b/tests/fixture_partials/routes/island_instance/partial.tsx @@ -0,0 +1,22 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import CounterA from "../../islands/CounterA.tsx"; +import { Fader } from "../../islands/Fader.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + + +

Another page

+

updated content

+ +
+
+ ); +}); diff --git a/tests/fixture_partials/routes/island_instance/partial_remove.tsx b/tests/fixture_partials/routes/island_instance/partial_remove.tsx new file mode 100644 index 00000000..1490c7c7 --- /dev/null +++ b/tests/fixture_partials/routes/island_instance/partial_remove.tsx @@ -0,0 +1,19 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + + +

no islands

+
+
+ ); +}); diff --git a/tests/fixture_partials/routes/island_instance/partial_replace.tsx b/tests/fixture_partials/routes/island_instance/partial_replace.tsx new file mode 100644 index 00000000..d1d83b36 --- /dev/null +++ b/tests/fixture_partials/routes/island_instance/partial_replace.tsx @@ -0,0 +1,21 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; +import Other from "../../islands/Other.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + + +

replaced content

+ +
+
+ ); +}); diff --git a/tests/fixture_partials/routes/island_instance_multiple/index.tsx b/tests/fixture_partials/routes/island_instance_multiple/index.tsx new file mode 100644 index 00000000..30ca9231 --- /dev/null +++ b/tests/fixture_partials/routes/island_instance_multiple/index.tsx @@ -0,0 +1,46 @@ +import { Partial } from "$fresh/runtime.ts"; +import CounterA from "../../islands/CounterA.tsx"; +import CounterB from "../../islands/CounterB.tsx"; +import { Fader } from "../../islands/Fader.tsx"; + +export default function SlotDemo() { + return ( +
+
+ + +

Initial content slot 1

+ +
+
+
+ + +

Initial content slot 2

+ +
+
+
+
+

+ + update second + +

+

+ + update both + +

+
+    
+ ); +} diff --git a/tests/fixture_partials/routes/island_instance_multiple/injected.tsx b/tests/fixture_partials/routes/island_instance_multiple/injected.tsx new file mode 100644 index 00000000..7c596212 --- /dev/null +++ b/tests/fixture_partials/routes/island_instance_multiple/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/island_instance_multiple", + }, + }); +}); diff --git a/tests/fixture_partials/routes/island_instance_multiple/partial.tsx b/tests/fixture_partials/routes/island_instance_multiple/partial.tsx new file mode 100644 index 00000000..36fbcebb --- /dev/null +++ b/tests/fixture_partials/routes/island_instance_multiple/partial.tsx @@ -0,0 +1,22 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import CounterB from "../../islands/CounterB.tsx"; +import { Fader } from "../../islands/Fader.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + + +

Another page

+

updated content {Math.random()}

+ +
+
+ ); +}); diff --git a/tests/fixture_partials/routes/island_instance_multiple/partial_both.tsx b/tests/fixture_partials/routes/island_instance_multiple/partial_both.tsx new file mode 100644 index 00000000..b2d962c1 --- /dev/null +++ b/tests/fixture_partials/routes/island_instance_multiple/partial_both.tsx @@ -0,0 +1,31 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import CounterA from "../../islands/CounterA.tsx"; +import CounterB from "../../islands/CounterB.tsx"; +import { Fader } from "../../islands/Fader.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + <> + + +

updated content {Math.random()}

+ +
+
+ + +

Another page

+

updated content {Math.random()}

+ +
+
+ + ); +}); diff --git a/tests/fixture_partials/routes/island_instance_nested/index.tsx b/tests/fixture_partials/routes/island_instance_nested/index.tsx new file mode 100644 index 00000000..8b8c968f --- /dev/null +++ b/tests/fixture_partials/routes/island_instance_nested/index.tsx @@ -0,0 +1,44 @@ +import { Partial } from "$fresh/runtime.ts"; +import CounterA from "../../islands/CounterA.tsx"; +import CounterB from "../../islands/CounterB.tsx"; +import PassThrough from "../../islands/PassThrough.tsx"; + +export default function SlotDemo() { + return ( +
+ + +
+

server content

+ +
+
+ +

another pass through

+ +
+
+
+
+

+ + update + +

+

+ + replace + +

+
+    
+ ); +} diff --git a/tests/fixture_partials/routes/island_instance_nested/injected.tsx b/tests/fixture_partials/routes/island_instance_nested/injected.tsx new file mode 100644 index 00000000..28047c46 --- /dev/null +++ b/tests/fixture_partials/routes/island_instance_nested/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/island_instance_nested", + }, + }); +}); diff --git a/tests/fixture_partials/routes/island_instance_nested/partial.tsx b/tests/fixture_partials/routes/island_instance_nested/partial.tsx new file mode 100644 index 00000000..68ef0be9 --- /dev/null +++ b/tests/fixture_partials/routes/island_instance_nested/partial.tsx @@ -0,0 +1,29 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import CounterA from "../../islands/CounterA.tsx"; +import CounterB from "../../islands/CounterB.tsx"; +import PassThrough from "../../islands/PassThrough.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + + +
+

updated server content

+ +
+
+ +

another pass through

+ +
+
+
+ ); +}); diff --git a/tests/fixture_partials/routes/island_instance_nested/replace.tsx b/tests/fixture_partials/routes/island_instance_nested/replace.tsx new file mode 100644 index 00000000..cca21480 --- /dev/null +++ b/tests/fixture_partials/routes/island_instance_nested/replace.tsx @@ -0,0 +1,17 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import CounterA from "../../islands/CounterA.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + + + + ); +}); diff --git a/tests/fixture_partials/routes/island_props/index.tsx b/tests/fixture_partials/routes/island_props/index.tsx new file mode 100644 index 00000000..53069258 --- /dev/null +++ b/tests/fixture_partials/routes/island_props/index.tsx @@ -0,0 +1,32 @@ +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; +import PropIsland from "../../islands/PropIsland.tsx"; + +export default function PropsDemo() { + return ( +
+ + +

initial

+ +
+
+

+ + Update + +

+
+    
+ ); +} diff --git a/tests/fixture_partials/routes/island_props/injected.tsx b/tests/fixture_partials/routes/island_props/injected.tsx new file mode 100644 index 00000000..354492a8 --- /dev/null +++ b/tests/fixture_partials/routes/island_props/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/island_props", + }, + }); +}); diff --git a/tests/fixture_partials/routes/island_props/partial.tsx b/tests/fixture_partials/routes/island_props/partial.tsx new file mode 100644 index 00000000..5ffb2abe --- /dev/null +++ b/tests/fixture_partials/routes/island_props/partial.tsx @@ -0,0 +1,27 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; +import PropIsland from "../../islands/PropIsland.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + + +

updated

+ +
+
+ ); +}); diff --git a/tests/fixture_partials/routes/island_props_signals/index.tsx b/tests/fixture_partials/routes/island_props_signals/index.tsx new file mode 100644 index 00000000..4b0848b5 --- /dev/null +++ b/tests/fixture_partials/routes/island_props_signals/index.tsx @@ -0,0 +1,30 @@ +import { Partial } from "$fresh/runtime.ts"; +import { useSignal } from "@preact/signals"; +import { Fader } from "../../islands/Fader.tsx"; +import SignalProp from "../../islands/SignalProp.tsx"; + +export default function PropsDemo() { + const sig = useSignal(0); + + return ( +
+ + +

initial

+ +
+
+

+ + Update + +

+
+ ); +} diff --git a/tests/fixture_partials/routes/island_props_signals/injected.tsx b/tests/fixture_partials/routes/island_props_signals/injected.tsx new file mode 100644 index 00000000..3ebbce74 --- /dev/null +++ b/tests/fixture_partials/routes/island_props_signals/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/island_props_signals", + }, + }); +}); diff --git a/tests/fixture_partials/routes/island_props_signals/partial.tsx b/tests/fixture_partials/routes/island_props_signals/partial.tsx new file mode 100644 index 00000000..80761842 --- /dev/null +++ b/tests/fixture_partials/routes/island_props_signals/partial.tsx @@ -0,0 +1,23 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; +import SignalProp from "../../islands/SignalProp.tsx"; +import { signal } from "@preact/signals"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + const sig = signal(0); + return ( + + +

update

+ +
+
+ ); +}); diff --git a/tests/fixture_partials/routes/keys/index.tsx b/tests/fixture_partials/routes/keys/index.tsx new file mode 100644 index 00000000..c5609eff --- /dev/null +++ b/tests/fixture_partials/routes/keys/index.tsx @@ -0,0 +1,29 @@ +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; +import Stateful from "../../islands/Stateful.tsx"; + +export default function SlotDemo() { + return ( +
+ + +

Initial content

+ {[ + , + , + , + ]} +
+
+

+ + swap + +

+
+ ); +} diff --git a/tests/fixture_partials/routes/keys/injected.tsx b/tests/fixture_partials/routes/keys/injected.tsx new file mode 100644 index 00000000..a3de161f --- /dev/null +++ b/tests/fixture_partials/routes/keys/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/keys", + }, + }); +}); diff --git a/tests/fixture_partials/routes/keys/swap.tsx b/tests/fixture_partials/routes/keys/swap.tsx new file mode 100644 index 00000000..b1c179e2 --- /dev/null +++ b/tests/fixture_partials/routes/keys/swap.tsx @@ -0,0 +1,25 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; +import Stateful from "../../islands/Stateful.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + + +

swapped content

+ {[ + , + , + , + ]} +
+
+ ); +}); diff --git a/tests/fixture_partials/routes/keys_components/index.tsx b/tests/fixture_partials/routes/keys_components/index.tsx new file mode 100644 index 00000000..372f676e --- /dev/null +++ b/tests/fixture_partials/routes/keys_components/index.tsx @@ -0,0 +1,36 @@ +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; +import Stateful from "../../islands/Stateful.tsx"; +import { Keyed } from "../../components/Keyed.tsx"; + +export default function SlotDemo() { + return ( +
+ + +

Initial content

+ {[ + + + , + + + , + + + , + ]} +
+
+

+ + swap + +

+
+ ); +} diff --git a/tests/fixture_partials/routes/keys_components/injected.tsx b/tests/fixture_partials/routes/keys_components/injected.tsx new file mode 100644 index 00000000..fd804e21 --- /dev/null +++ b/tests/fixture_partials/routes/keys_components/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/keys_components", + }, + }); +}); diff --git a/tests/fixture_partials/routes/keys_components/swap.tsx b/tests/fixture_partials/routes/keys_components/swap.tsx new file mode 100644 index 00000000..6fe2892e --- /dev/null +++ b/tests/fixture_partials/routes/keys_components/swap.tsx @@ -0,0 +1,32 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; +import Stateful from "../../islands/Stateful.tsx"; +import { Keyed } from "../../components/Keyed.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + + +

swapped content

+ {[ + + + , + + + , + + + , + ]} +
+
+ ); +}); diff --git a/tests/fixture_partials/routes/keys_dom/index.tsx b/tests/fixture_partials/routes/keys_dom/index.tsx new file mode 100644 index 00000000..9369494b --- /dev/null +++ b/tests/fixture_partials/routes/keys_dom/index.tsx @@ -0,0 +1,37 @@ +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; +import Stateful from "../../islands/Stateful.tsx"; + +export default function SlotDemo() { + return ( +
+ + +

Initial content

+
    + {[ +
  • + +
  • , +
  • + +
  • , +
  • + +
  • , + ]} +
+
+
+

+ + swap + +

+
+ ); +} diff --git a/tests/fixture_partials/routes/keys_dom/injected.tsx b/tests/fixture_partials/routes/keys_dom/injected.tsx new file mode 100644 index 00000000..400eb666 --- /dev/null +++ b/tests/fixture_partials/routes/keys_dom/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/keys_dom", + }, + }); +}); diff --git a/tests/fixture_partials/routes/keys_dom/swap.tsx b/tests/fixture_partials/routes/keys_dom/swap.tsx new file mode 100644 index 00000000..61ea19c6 --- /dev/null +++ b/tests/fixture_partials/routes/keys_dom/swap.tsx @@ -0,0 +1,33 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; +import Stateful from "../../islands/Stateful.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + + +

swapped content

+
    + {[ +
  • + +
  • , +
  • + +
  • , +
  • + +
  • , + ]} +
+
+
+ ); +}); diff --git a/tests/fixture_partials/routes/loading/index.tsx b/tests/fixture_partials/routes/loading/index.tsx new file mode 100644 index 00000000..e9336c7d --- /dev/null +++ b/tests/fixture_partials/routes/loading/index.tsx @@ -0,0 +1,36 @@ +import { Partial } from "$fresh/runtime.ts"; +import { useSignal } from "@preact/signals"; +import Spinner from "../../islands/Spinner.tsx"; +import PartialTrigger from "../../islands/PartialTrigger.tsx"; + +export default function SlotDemo() { + const sig = useSignal(false); + return ( +
+
+ +

Default content

+ +
+
+ + + update + +
+ + partial trigger + +
+ ); +} diff --git a/tests/fixture_partials/routes/loading/injected.tsx b/tests/fixture_partials/routes/loading/injected.tsx new file mode 100644 index 00000000..366b3bf7 --- /dev/null +++ b/tests/fixture_partials/routes/loading/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/loading", + }, + }); +}); diff --git a/tests/fixture_partials/routes/loading/update.tsx b/tests/fixture_partials/routes/loading/update.tsx new file mode 100644 index 00000000..78e74f52 --- /dev/null +++ b/tests/fixture_partials/routes/loading/update.tsx @@ -0,0 +1,20 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import { delay } from "../../../deps.ts"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute(async (req, ctx) => { + // A bit of artificial delay to show the loader + await delay(200); + + return ( + +

it works

+
+ ); +}); diff --git a/tests/fixture_partials/routes/missing_partial/index.tsx b/tests/fixture_partials/routes/missing_partial/index.tsx new file mode 100644 index 00000000..307f4542 --- /dev/null +++ b/tests/fixture_partials/routes/missing_partial/index.tsx @@ -0,0 +1,25 @@ +import { Partial } from "$fresh/runtime.ts"; +import CounterA from "../../islands/CounterA.tsx"; +import { Fader } from "../../islands/Fader.tsx"; + +export default function WarnDemo() { + return ( +
+ + +

Initial content

+ +
+
+

+ + update + +

+
+ ); +} diff --git a/tests/fixture_partials/routes/missing_partial/injected.tsx b/tests/fixture_partials/routes/missing_partial/injected.tsx new file mode 100644 index 00000000..e8cee1f6 --- /dev/null +++ b/tests/fixture_partials/routes/missing_partial/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/missing_partial", + }, + }); +}); diff --git a/tests/fixture_partials/routes/missing_partial/update.tsx b/tests/fixture_partials/routes/missing_partial/update.tsx new file mode 100644 index 00000000..6b8e1f17 --- /dev/null +++ b/tests/fixture_partials/routes/missing_partial/update.tsx @@ -0,0 +1,16 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + +

append content

+
+ ); +}); diff --git a/tests/fixture_partials/routes/mode/append.tsx b/tests/fixture_partials/routes/mode/append.tsx new file mode 100644 index 00000000..8f8e023f --- /dev/null +++ b/tests/fixture_partials/routes/mode/append.tsx @@ -0,0 +1,21 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; +import Other from "../../islands/Other.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + + +

append content

+ +
+
+ ); +}); diff --git a/tests/fixture_partials/routes/mode/index.tsx b/tests/fixture_partials/routes/mode/index.tsx new file mode 100644 index 00000000..a4d38007 --- /dev/null +++ b/tests/fixture_partials/routes/mode/index.tsx @@ -0,0 +1,45 @@ +import { Partial } from "$fresh/runtime.ts"; +import CounterA from "../../islands/CounterA.tsx"; +import { Fader } from "../../islands/Fader.tsx"; + +export default function ModeDemo() { + return ( +
+ + +

Initial content

+ +
+
+

+ + replace + +

+

+ + append + +

+

+ + prepend + +

+ +
+    
+ ); +} diff --git a/tests/fixture_partials/routes/mode/injected.tsx b/tests/fixture_partials/routes/mode/injected.tsx new file mode 100644 index 00000000..860ef429 --- /dev/null +++ b/tests/fixture_partials/routes/mode/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/mode", + }, + }); +}); diff --git a/tests/fixture_partials/routes/mode/prepend.tsx b/tests/fixture_partials/routes/mode/prepend.tsx new file mode 100644 index 00000000..5596a943 --- /dev/null +++ b/tests/fixture_partials/routes/mode/prepend.tsx @@ -0,0 +1,20 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + + +

prepend

+

prepend content

+
+
+ ); +}); diff --git a/tests/fixture_partials/routes/mode/replace.tsx b/tests/fixture_partials/routes/mode/replace.tsx new file mode 100644 index 00000000..55a7ddc8 --- /dev/null +++ b/tests/fixture_partials/routes/mode/replace.tsx @@ -0,0 +1,19 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; +import { Fader } from "../../islands/Fader.tsx"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + + +

replace

+
+
+ ); +}); diff --git a/tests/fixture_partials/routes/no_islands/index.tsx b/tests/fixture_partials/routes/no_islands/index.tsx new file mode 100644 index 00000000..7dfb196e --- /dev/null +++ b/tests/fixture_partials/routes/no_islands/index.tsx @@ -0,0 +1,20 @@ +import { Partial } from "$fresh/runtime.ts"; + +export default function SlotDemo() { + return ( +
+
+ +

Default content

+
+
+ + update + +
+ ); +} diff --git a/tests/fixture_partials/routes/no_islands/injected.tsx b/tests/fixture_partials/routes/no_islands/injected.tsx new file mode 100644 index 00000000..ef04413d --- /dev/null +++ b/tests/fixture_partials/routes/no_islands/injected.tsx @@ -0,0 +1,10 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; + +export default defineRoute(() => { + return new Response("", { + status: 302, + headers: { + Location: "/no_islands", + }, + }); +}); diff --git a/tests/fixture_partials/routes/no_islands/update.tsx b/tests/fixture_partials/routes/no_islands/update.tsx new file mode 100644 index 00000000..e8a01eb5 --- /dev/null +++ b/tests/fixture_partials/routes/no_islands/update.tsx @@ -0,0 +1,16 @@ +import { defineRoute } from "$fresh/src/server/defines.ts"; +import { RouteConfig } from "$fresh/server.ts"; +import { Partial } from "$fresh/runtime.ts"; + +export const config: RouteConfig = { + skipAppWrapper: true, + skipInheritedLayouts: true, +}; + +export default defineRoute((req, ctx) => { + return ( + +

it works

+
+ ); +}); diff --git a/tests/fixture_partials/routes/partial_slot_inside_island.tsx b/tests/fixture_partials/routes/partial_slot_inside_island.tsx new file mode 100644 index 00000000..17f5b3fc --- /dev/null +++ b/tests/fixture_partials/routes/partial_slot_inside_island.tsx @@ -0,0 +1,5 @@ +import InvalidSlot from "../islands/InvalidSlot.tsx"; + +export default function SlotDemo() { + return ; +} diff --git a/tests/fixture_partials/static/style.css b/tests/fixture_partials/static/style.css new file mode 100644 index 00000000..f60ef4f5 --- /dev/null +++ b/tests/fixture_partials/static/style.css @@ -0,0 +1,8 @@ +@keyframes fade { + 0% { + background: white; + } + 100% { + background: peachpuff; + } +} diff --git a/tests/main_test.ts b/tests/main_test.ts index e0cdc90b..b29fefae 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -858,7 +858,7 @@ Deno.test("rendering custom _500.tsx page for default handlers", async (t) => { Deno.test("renders error boundary", async () => { await withPageName("./tests/fixture/main.ts", async (page, address) => { await page.goto(`${address}/error_boundary`); - const text = await page.$eval("body", (el) => el.textContent); + const text = await page.$eval("p", (el) => el.textContent); assertEquals(text, "it works"); }); }); diff --git a/tests/partials_test.ts b/tests/partials_test.ts new file mode 100644 index 00000000..e44b2c74 --- /dev/null +++ b/tests/partials_test.ts @@ -0,0 +1,876 @@ +import { assertEquals, assertMatch } from "$std/testing/asserts.ts"; +import { Page } from "./deps.ts"; +import { + assertNoPageComments, + assertNotSelector, + assertSelector, + assertTextMany, + parseHtml, + waitFor, + waitForText, + withFakeServe, + withPageName, +} from "./test_utils.ts"; + +async function assertLogs(page: Page, expected: string[]) { + await waitForText(page, "#logs", expected.join("\n") + "\n"); +} + +Deno.test("injects server content with no islands present", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/no_islands`); + await page.waitForSelector(".output"); + await assertNoPageComments(page); + + const href = await page.$eval(".update-link", (el) => el.href); + await page.click(".update-link"); + await waitForText(page, "p", "it works"); + + assertEquals(href, await page.url()); + await assertNoPageComments(page); + }, + ); +}); + +Deno.test( + "throws when Partial is instantiated inside an island", + async () => { + await withFakeServe( + "./tests/fixture_partials/main.ts", + async (server) => { + const html = await server.getHtml("/partial_slot_inside_island"); + assertMatch( + html.querySelector("h1")!.textContent!, + / components cannot be used inside islands/, + ); + }, + ); + }, +); + +Deno.test("warns on missing partial", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + const logs: string[] = []; + page.on("console", (msg) => logs.push(msg.text())); + + const initialUrl = `${address}/missing_partial`; + await page.goto(initialUrl); + await page.waitForSelector(".status-initial"); + + await page.click(".update-link"); + + await waitFor(() => + logs.find((line) => /^Partial.*not found/.test(line)) + ); + }, + ); +}); + +Deno.test("injects content with island and keeps island instance alive", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/island_instance`); + await page.waitForSelector(".output-a"); + + // Update island state + await page.click(".island button"); + await waitForText(page, ".output-a", "1"); + await assertLogs(page, ["mount Counter A", "update Counter A"]); + await assertNoPageComments(page); + + const href = await page.$eval(".update-link", (el) => el.href); + await page.click(".update-link"); + await waitForText(page, ".status", "updated content"); + await assertLogs(page, ["mount Counter A", "update Counter A"]); + + assertEquals(href, await page.url()); + + // Check that island value didn't change + await waitForText(page, ".output-a", "1"); + await assertNoPageComments(page); + }, + ); +}); + +Deno.test("unmounts island", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/island_instance`); + await page.waitForSelector(".output-a"); + + const href = await page.$eval(".remove-link", (el) => el.href); + await page.click(".remove-link"); + await waitForText(page, ".status", "no islands"); + await assertNoPageComments(page); + + assertEquals(href, await page.url()); + await assertLogs(page, ["mount Counter A", "unmount Counter A"]); + + await page.click(".update-link"); + await waitForText(page, ".status", "updated content"); + await assertNoPageComments(page); + + await assertLogs(page, [ + "mount Counter A", + "unmount Counter A", + "mount Counter A", + ]); + }, + ); +}); + +Deno.test("unmounts island on replace", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/island_instance`); + await page.waitForSelector(".output-a"); + + // Update island state + await page.click(".island-a button"); + await waitForText(page, ".output-a", "1"); + await assertNoPageComments(page); + + const href = await page.$eval(".replace-link", (el) => el.href); + await page.click(".replace-link"); + await waitForText(page, ".status-replaced", "replaced content"); + await assertNoPageComments(page); + + assertEquals(href, await page.url()); + await assertLogs(page, [ + "mount Counter A", + "update Counter A", + "unmount Counter A", + "mount Other", + ]); + + await page.click(".island-other button"); + await waitForText(page, ".output-other", "1"); + await assertNoPageComments(page); + + await assertLogs(page, [ + "mount Counter A", + "update Counter A", + "unmount Counter A", + "mount Other", + "update Other", + ]); + }, + ); +}); + +Deno.test("updates only one partial of many", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/island_instance_multiple`); + await page.waitForSelector(".output-a"); + + // Update island state + await page.click(".island-a button"); + await waitForText(page, ".output-a", "1"); + await assertNoPageComments(page); + + await page.click(".island-b button"); + await waitForText(page, ".output-b", "1"); + await assertNoPageComments(page); + + await assertLogs(page, [ + "mount Counter A", + "mount Counter B", + "update Counter A", + "update Counter B", + ]); + + const href = await page.$eval(".update-second-link", (el) => el.href); + await page.click(".update-second-link"); + await page.waitForSelector(".status-2"); + await assertNoPageComments(page); + + assertEquals(href, await page.url()); + + // Check that island value didn't change + await waitForText(page, ".output-a", "1"); + await waitForText(page, ".output-b", "1"); + }, + ); +}); + +Deno.test("updates many partials at once", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/island_instance_multiple`); + await page.waitForSelector(".output-a"); + + // Update island state + await page.click(".island-a button"); + await waitForText(page, ".output-a", "1"); + await assertNoPageComments(page); + + await page.click(".island-b button"); + await waitForText(page, ".output-b", "1"); + await assertNoPageComments(page); + + await assertLogs(page, [ + "mount Counter A", + "mount Counter B", + "update Counter A", + "update Counter B", + ]); + + const href = await page.$eval(".update-both-link", (el) => el.href); + await page.click(".update-both-link"); + await page.waitForSelector(".status-1"); + await page.waitForSelector(".status-2"); + await assertNoPageComments(page); + + assertEquals(href, await page.url()); + + // Check that island value didn't change + await waitForText(page, ".output-a", "1"); + await waitForText(page, ".output-b", "1"); + }, + ); +}); + +Deno.test("keeps nested island state", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/island_instance_nested`); + await page.waitForSelector(".output-a"); + + // Update island state + await page.click(".island-a button"); + await waitForText(page, ".output-a", "1"); + await assertNoPageComments(page); + + await page.click(".island-b button"); + await waitForText(page, ".output-b", "1"); + await assertNoPageComments(page); + + await assertLogs(page, [ + "mount Counter A", + "mount Counter B", + "mount PassThrough", + "mount PassThrough", + "update Counter A", + "update Counter B", + ]); + + const href = await page.$eval(".update-link", (el) => el.href); + await page.click(".update-link"); + await page.waitForSelector(".status-a"); + await page.waitForSelector(".status-b"); + await assertNoPageComments(page); + + assertEquals(href, await page.url()); + + // Check that island value didn't change + await waitForText(page, ".output-a", "1"); + await waitForText(page, ".output-b", "1"); + }, + ); +}); + +Deno.test("replace island if parent type changes", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/island_instance_nested`); + await page.waitForSelector(".output-a"); + + // Update island state + await page.click(".island-a button"); + await waitForText(page, ".output-a", "1"); + await assertNoPageComments(page); + + await page.click(".island-b button"); + await waitForText(page, ".output-b", "1"); + await assertNoPageComments(page); + + await assertLogs(page, [ + "mount Counter A", + "mount Counter B", + "mount PassThrough", + "mount PassThrough", + "update Counter A", + "update Counter B", + ]); + + const href = await page.$eval(".replace-link", (el) => el.href); + await page.click(".replace-link"); + await page.waitForSelector(".output-a"); + await assertNoPageComments(page); + + assertEquals(href, await page.url()); + + // Check that island value was destroyed since we replaced it + await waitForText(page, ".output-a", "0"); + + await assertLogs(page, [ + "mount Counter A", + "mount Counter B", + "mount PassThrough", + "mount PassThrough", + "update Counter A", + "update Counter B", + "unmount PassThrough", + "unmount Counter A", + "unmount PassThrough", + "unmount Counter B", + "mount Counter A", + ]); + }, + ); +}); + +Deno.test("serializes props", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/island_props`); + await page.waitForSelector(".pre-props"); + + let text = JSON.parse( + await page.$eval(".pre-props", (el) => el.textContent!), + ); + assertEquals( + text, + { + number: 1, + string: "foo", + boolean: true, + null: null, + object: { foo: 123 }, + strArr: ["foo"], + }, + ); + + await page.click(".update-link"); + await page.waitForSelector(".status-updated"); + text = JSON.parse( + await page.$eval(".pre-props", (el) => el.textContent!), + ); + + assertEquals( + text, + { + number: 42, + string: "foobar", + boolean: false, + null: null, + object: { foo: 123456 }, + strArr: ["foo", "bar"], + }, + ); + + await assertNoPageComments(page); + }, + ); +}); + +Deno.test("serializes signals", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/island_props_signals`); + await page.waitForSelector(".island"); + + await page.click("button"); + await waitForText(page, ".output", "1"); + await assertNoPageComments(page); + + await page.click(".update-link"); + await page.waitForSelector(".status-update"); + await assertNoPageComments(page); + + // Currently, signal props are reset. This may change in + // the future + await waitForText(page, ".output", "0"); + }, + ); +}); + +Deno.test("reconciles keyed islands", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/keys`); + await page.waitForSelector(".island"); + + await page.click(".btn-A"); + await waitForText(page, ".output-A", "1"); + await assertNoPageComments(page); + + await page.click(".btn-B"); + await waitForText(page, ".output-B", "1"); + await page.click(".btn-B"); + await waitForText(page, ".output-B", "2"); + await assertNoPageComments(page); + + await page.click(".btn-C"); + await waitForText(page, ".output-C", "1"); + await page.click(".btn-C"); + await waitForText(page, ".output-C", "2"); + await page.click(".btn-C"); + await waitForText(page, ".output-C", "3"); + await assertNoPageComments(page); + + await page.click(".swap-link"); + await page.waitForSelector(".status-swap"); + await assertNoPageComments(page); + + // Check that result is stable + await waitForText(page, ".output-A", "1"); + await waitForText(page, ".output-B", "2"); + await waitForText(page, ".output-C", "3"); + }, + ); +}); + +Deno.test("reconciles keyed DOM nodes", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/keys_dom`); + await page.waitForSelector(".island"); + + await page.click(".btn-A"); + await waitForText(page, ".output-A", "1"); + await assertNoPageComments(page); + + await page.click(".btn-B"); + await waitForText(page, ".output-B", "1"); + await page.click(".btn-B"); + await waitForText(page, ".output-B", "2"); + await assertNoPageComments(page); + + await page.click(".btn-C"); + await waitForText(page, ".output-C", "1"); + await page.click(".btn-C"); + await waitForText(page, ".output-C", "2"); + await page.click(".btn-C"); + await waitForText(page, ".output-C", "3"); + await assertNoPageComments(page); + + await page.click(".swap-link"); + await page.waitForSelector(".status-swap"); + await assertNoPageComments(page); + + // Check that result is stable + await waitForText(page, ".output-A", "1"); + await waitForText(page, ".output-B", "2"); + await waitForText(page, ".output-C", "3"); + + // Check that no element has `data-fresh-key` attribute + const doc = parseHtml(await page.content()); + assertNotSelector(doc, "[data-fresh-key]"); + }, + ); +}); + +Deno.test("reconciles keyed non island components", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/keys_components`); + await page.waitForSelector(".island"); + + await page.click(".btn-A"); + await waitForText(page, ".output-A", "1"); + await assertNoPageComments(page); + + await page.click(".btn-B"); + await waitForText(page, ".output-B", "1"); + await page.click(".btn-B"); + await waitForText(page, ".output-B", "2"); + await assertNoPageComments(page); + + await page.click(".btn-C"); + await waitForText(page, ".output-C", "1"); + await page.click(".btn-C"); + await waitForText(page, ".output-C", "2"); + await page.click(".btn-C"); + await waitForText(page, ".output-C", "3"); + await assertNoPageComments(page); + + await page.click(".swap-link"); + await page.waitForSelector(".status-swap"); + await assertNoPageComments(page); + + // Check that result is stable + await waitForText(page, ".output-A", "1"); + await waitForText(page, ".output-B", "2"); + await waitForText(page, ".output-C", "3"); + + // Check that no element has `data-fresh-key` attribute + const doc = parseHtml(await page.content()); + assertNotSelector(doc, "[data-fresh-key]"); + }, + ); +}); + +Deno.test("partial injection mode", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + await page.goto(`${address}/mode`); + await page.waitForSelector(".island"); + + await page.click("button"); + await waitForText(page, ".output-a", "1"); + await assertNoPageComments(page); + + // Append + await page.click(".append-link"); + await page.waitForSelector(".status-append"); + // Check that old content is still there + await page.waitForSelector(".status-initial"); + await assertNoPageComments(page); + + // Check that newly inserted island is interactive + await page.click(".island-other button"); + await waitForText(page, ".output-other", "1"); + await assertNoPageComments(page); + + // Prepend + await page.click(".prepend-link"); + await page.waitForSelector(".status-prepend"); + // Check that old content is still there + await page.waitForSelector(".status-append"); + await page.waitForSelector(".status-initial"); + await assertNoPageComments(page); + + // Replace + await page.click(".replace-link"); + await page.waitForSelector(".status-replace"); + await assertNoPageComments(page); + + const doc = parseHtml(await page.content()); + assertNotSelector(doc, ".status-append"); + assertNotSelector(doc, ".status-prepend"); + }, + ); +}); + +Deno.test("partial navigation", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + const initialUrl = `${address}/mode`; + await page.goto(initialUrl); + await page.waitForSelector(".island"); + + await page.click(".append-link"); + await page.waitForSelector(".status-append"); + await assertNoPageComments(page); + + await page.click(".island-other button"); + await waitForText(page, ".output-other", "1"); + await assertNoPageComments(page); + + const url = page.url(); + + // Click link again + await page.click(".append-link"); + await page.waitForFunction(() => + document.querySelectorAll(".status-append").length > 1 + ); + assertEquals(page.url(), url); + await assertNoPageComments(page); + + // Go back + await page.goBack(); + await page.waitForFunction(() => + document.querySelectorAll(".island").length === 1 + ); + assertEquals(page.url(), initialUrl); + await waitForText(page, "pre", "mount Counter A\n"); + await assertNoPageComments(page); + }, + ); +}); + +Deno.test("non-partial client navigation", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + const initialUrl = `${address}/client_nav`; + await page.goto(initialUrl); + await page.waitForSelector(".island"); + + // Add marker to check if the page reloaded or not + await page.evaluate(() => { + const marker = document.createElement("fresh-nav-marker"); + document.body.appendChild(marker); + }); + + await page.click(".island-a button"); + await waitForText(page, ".output-a", "1"); + await assertNoPageComments(page); + + // Go to page B + await page.click(".page-b-link"); + await page.waitForSelector(".island-b"); + await assertNoPageComments(page); + + let doc = parseHtml(await page.content()); + assertNotSelector(doc, ".island-a"); + assertSelector(doc, "fresh-nav-marker"); + assertEquals(page.url(), `${address}/client_nav/page-b`); + + await page.click(".island-b button"); + await waitForText(page, ".output-b", "1"); + await assertNoPageComments(page); + + // Go to page C + await page.click(".page-c-link"); + await page.waitForSelector(".page-c-text"); + await assertNoPageComments(page); + + doc = parseHtml(await page.content()); + assertNotSelector(doc, ".island-a"); + assertNotSelector(doc, ".island-b"); + assertSelector(doc, "fresh-nav-marker"); + assertEquals(page.url(), `${address}/client_nav/page-c`); + + // Go back to B + await page.goBack(); + await page.waitForSelector(".island-b"); + + doc = parseHtml(await page.content()); + assertNotSelector(doc, ".island-a"); + assertSelector(doc, "fresh-nav-marker"); + assertNotSelector(doc, ".page-c-text"); + + // Non-shared state is reset + assertTextMany(doc, ".output-b", ["0"]); + + // Check that island is interactive + await page.click(".island-b button"); + await waitForText(page, ".output-b", "1"); + await assertNoPageComments(page); + + // Go back to A + await page.goBack(); + await page.waitForSelector(".island-a"); + + doc = parseHtml(await page.content()); + assertNotSelector(doc, ".island-b"); + assertNotSelector(doc, ".page-c-text"); + assertSelector(doc, "fresh-nav-marker"); + + // Non-shared state is reset + assertTextMany(doc, ".output-a", ["0"]); + + // Check that island is interactive + await page.click(".island-a button"); + await waitForText(page, ".output-a", "1"); + await assertNoPageComments(page); + + // Go forward to B + await page.goForward(); + await page.waitForSelector(".island-b"); + + doc = parseHtml(await page.content()); + assertNotSelector(doc, ".island-a"); + assertNotSelector(doc, ".page-c-text"); + assertSelector(doc, "fresh-nav-marker"); + + // Non-shared state is reset + assertTextMany(doc, ".output-b", ["0"]); + + // Check that island is interactive + await page.click(".island-b button"); + await waitForText(page, ".output-b", "1"); + await assertNoPageComments(page); + }, + ); +}); + +Deno.test("allow opting out of client navigation", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + const initialUrl = `${address}/client_nav_opt_out`; + await page.goto(initialUrl); + await page.waitForSelector(".island"); + + async function addMarker() { + await page.evaluate(() => { + const marker = document.createElement("fresh-nav-marker"); + document.body.appendChild(marker); + }); + } + + // Add marker to check if the page reloaded or not + await addMarker(); + + await page.click(".island-a button"); + await waitForText(page, ".output-a", "1"); + await assertNoPageComments(page); + + // Go to page B + await page.click(".page-b-link"); + await page.waitForSelector(".island-b"); + await assertNoPageComments(page); + + let doc = parseHtml(await page.content()); + assertNotSelector(doc, ".island-a"); + assertNotSelector(doc, "fresh-nav-marker"); + assertEquals(page.url(), `${address}/client_nav_opt_out/page-b`); + + await page.click(".island-b button"); + await waitForText(page, ".output-b", "1"); + await assertNoPageComments(page); + + // Add marker to check if the page reloaded or not + await addMarker(); + + // Go to page C + await page.click(".page-c-link"); + await page.waitForSelector(".page-c-text"); + await assertNoPageComments(page); + + doc = parseHtml(await page.content()); + assertNotSelector(doc, ".island-a"); + assertNotSelector(doc, ".island-b"); + assertNotSelector(doc, "fresh-nav-marker"); + assertEquals(page.url(), `${address}/client_nav_opt_out/page-c`); + + // Add marker to check if the page reloaded or not + await addMarker(); + + // Go back to B + await page.goBack(); + await page.waitForSelector(".island-b"); + + doc = parseHtml(await page.content()); + assertNotSelector(doc, ".island-a"); + assertNotSelector(doc, "fresh-nav-marker"); + assertNotSelector(doc, ".page-c-text"); + + // Non-shared state is reset + assertTextMany(doc, ".output-b", ["0"]); + + // Check that island is interactive + await page.click(".island-b button"); + await waitForText(page, ".output-b", "1"); + await assertNoPageComments(page); + + // Go back to A + await page.goBack(); + await page.waitForSelector(".island-a"); + + doc = parseHtml(await page.content()); + assertNotSelector(doc, ".island-b"); + assertNotSelector(doc, ".page-c-text"); + assertNotSelector(doc, "fresh-nav-marker"); + + // Non-shared state is reset + assertTextMany(doc, ".output-a", ["0"]); + + // Check that island is interactive + await page.click(".island-a button"); + await waitForText(page, ".output-a", "1"); + await assertNoPageComments(page); + + // Go forward to B + await page.goForward(); + await page.waitForSelector(".island-b"); + + doc = parseHtml(await page.content()); + assertNotSelector(doc, ".island-a"); + assertNotSelector(doc, ".page-c-text"); + assertNotSelector(doc, "fresh-nav-marker"); + + // Non-shared state is reset + assertTextMany(doc, ".output-b", ["0"]); + + // Check that island is interactive + await page.click(".island-b button"); + await waitForText(page, ".output-b", "1"); + }, + ); +}); + +Deno.test("shows loading indicator if trigger outside island", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + const initialUrl = `${address}/loading`; + await page.goto(initialUrl); + await page.waitForSelector(".status"); + + let doc = parseHtml(await page.content()); + assertNotSelector(doc, ".spinner"); + + await Promise.all([ + page.waitForSelector(".spinner-inner"), + page.waitForSelector(".spinner-outer"), + page.click(".update-link"), + ]); + + await page.waitForSelector(".status-updated"); + await assertNoPageComments(page); + + doc = parseHtml(await page.content()); + assertNotSelector(doc, ".spinner"); + }, + ); +}); + +Deno.test("shows loading indicator if trigger inside island", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + const initialUrl = `${address}/loading`; + await page.goto(initialUrl); + await page.waitForSelector(".status"); + + let doc = parseHtml(await page.content()); + assertNotSelector(doc, ".spinner"); + + await Promise.all([ + page.waitForSelector(".spinner-inner"), + page.waitForSelector(".spinner-outer"), + page.click(".trigger"), + ]); + + await page.waitForSelector(".status-updated"); + await assertNoPageComments(page); + + doc = parseHtml(await page.content()); + assertNotSelector(doc, ".spinner"); + }, + ); +}); + +Deno.test("submit form", async () => { + await withPageName( + "./tests/fixture_partials/main.ts", + async (page, address) => { + const initialUrl = `${address}/form`; + await page.goto(initialUrl); + await page.waitForSelector(".status"); + + await page.click(".submit"); + await page.waitForSelector(".status-updated"); + await assertNoPageComments(page); + }, + ); +}); + +// TODO Head merging +// TODO Active links +// TODO Children Keys +// TODO Leftover comments +// TODO HTML validation diff --git a/tests/server_components_test.ts b/tests/server_components_test.ts index f303ef00..be15e6f3 100644 --- a/tests/server_components_test.ts +++ b/tests/server_components_test.ts @@ -127,7 +127,7 @@ Deno.test({ await page.goto(`${address}/twind`); await page.waitForSelector("h1"); - const text = await page.$eval("body", (el) => el.textContent); + const text = await page.$eval("h1", (el) => el.textContent); assertEquals(text, "it works"); // Check that CSS was applied accordingly diff --git a/tests/test_utils.ts b/tests/test_utils.ts index 75d964cb..796219fa 100644 --- a/tests/test_utils.ts +++ b/tests/test_utils.ts @@ -363,14 +363,25 @@ export async function waitForText( text: string, ) { await page.waitForSelector(selector); - await page.waitForFunction( - (sel, value) => { - return document.querySelector(sel)!.textContent === value; - }, - { timeout: 2000 }, - selector, - String(text), - ); + try { + await page.waitForFunction( + (sel, value) => { + return document.querySelector(sel)!.textContent === value; + }, + { timeout: 2000 }, + selector, + String(text), + ); + } catch (err) { + const body = await page.content(); + // deno-lint-ignore no-explicit-any + const pretty = prettyDom(parseHtml(body) as any); + + console.log( + `Text "${text}" not found on selector "${selector}" in html:\n\n${pretty}`, + ); + throw err; + } } export async function waitForStyle( @@ -486,6 +497,28 @@ export function getStdOutput( return { stdout, stderr }; } +export async function waitFor( + fn: () => Promise | unknown, +): Promise { + let now = Date.now(); + const limit = now + 2000; + + while (now < limit) { + try { + if (await fn()) return; + } catch (err) { + if (now > limit) { + throw err; + } + } finally { + await delay(100); + now = Date.now(); + } + } + + throw new Error(`Timed out`); +} + function walk(doc: Document, node: HTMLElement): string | null { for (let i = 0; i < node.childNodes.length; i++) { const child = node.childNodes[i];