diff --git a/src/features/web/WebEditor.test.tsx b/src/features/web/WebEditor.test.tsx new file mode 100644 index 000000000..05aa7aa61 --- /dev/null +++ b/src/features/web/WebEditor.test.tsx @@ -0,0 +1,70 @@ +import { act, cleanup, render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { _emitEditorEvent } from "@/editor/api"; +import { commands, emitLocalIdeEvent } from "@/platform/ipc"; +import { WebEditor } from "./WebEditor"; +import { togglePreview, useWebPreview } from "./browsers"; + +const path = "/project/site/index.html"; +const url = "http://127.0.0.1:43210/token/project/site/index.html"; +const style = "/project/shared/main.css"; +const script = "/project/site/app.js"; +const frame = () => screen.getByTitle("HTML preview"); +const save = (path: string) => _emitEditorEvent({ type: "docSaved", doc: 1, path }); +const change = (...modified: string[]) => emitLocalIdeEvent({ type: "fsChanged", created: [], modified, removed: [] }); + +describe("HTML preview reload", () => { + let html: string; + + beforeEach(async () => { + html = ''; + vi.spyOn(commands, "webUrl").mockResolvedValue({ status: "ok", data: url }); + vi.spyOn(commands, "fsReadText").mockImplementation(async () => ({ status: "ok", data: html })); + togglePreview(path, true); + render( + + HTML editor + , + ); + await screen.findByTitle("HTML preview"); + vi.useFakeTimers(); + }); + + afterEach(() => { + cleanup(); + vi.useRealTimers(); + vi.restoreAllMocks(); + useWebPreview.setState({}, true); + }); + + async function after(event: () => void) { + await act(async () => { + event(); + await vi.advanceTimersByTimeAsync(300); + }); + return frame(); + } + + it("keeps the same iframe after unrelated files are saved, including unlinked web assets", async () => { + const original = frame(); + expect( + await after(() => change("/project/site/notes.txt", "/project/site/unused.css", "/project/other.html")), + ).toBe(original); + expect(await after(() => save("/project/site/unused.js"))).toBe(original); + expect(await after(() => emitLocalIdeEvent({ type: "docDirty", doc: 2, dirty: false }))).toBe(original); + }); + + it("reloads when linked CSS or JS changes and refreshes dependencies on HTML save", async () => { + const original = frame(); + const afterStyle = await after(() => change(style)); + expect(afterStyle).not.toBe(original); + const afterScript = await after(() => save(script)); + expect(afterScript).not.toBe(afterStyle); + + html = ''; + const afterPage = await after(() => save(path)); + expect(afterPage).not.toBe(afterScript); + expect(await after(() => change(script, style))).toBe(afterPage); + expect(await after(() => change("/project/shared/replacement.js"))).not.toBe(afterPage); + }); +}); diff --git a/src/features/web/WebEditor.tsx b/src/features/web/WebEditor.tsx index df7cd9838..22935ce47 100644 --- a/src/features/web/WebEditor.tsx +++ b/src/features/web/WebEditor.tsx @@ -5,10 +5,11 @@ */ import { useEffect, useRef, useState, type ReactNode } from "react"; import clsx from "clsx"; -import { onIdeEvent } from "@/platform/ipc"; -import { useProject } from "@/platform/project"; +import { onEditorEvent } from "@/editor/api"; +import { call, commands, onIdeEvent } from "@/platform/ipc"; import { FloatingToolbar, IconButton } from "@/ui"; import { browserIcon, openInBrowser, useBrowsers, useWebPreview, webUrl } from "./browsers"; +import { previewResources } from "./previewResources"; import styles from "./Web.module.css"; import { tx } from "@/platform/i18n"; @@ -46,7 +47,7 @@ export function WebEditor({ path, children }: { path: string; tabId: string; chi - {preview && } + {preview && } ); } @@ -55,39 +56,57 @@ function WebPreview({ path }: { path: string }) { const [url, setUrl] = useState(null); const [error, setError] = useState(null); const [seq, setSeq] = useState(0); - const root = useProject((s) => s.project?.root ?? null); - useEffect(() => { let live = true; - webUrl(path).then( - (u) => live && setUrl(u), - (e: unknown) => live && setError(e instanceof Error ? e.message : String(e)), - ); + let timer: ReturnType | undefined; + let pageUrl: string | null = null; + let resources = new Set([path]); + let scan = 0; + let pageChanged = false; + + const updateResources = async (url: string) => { + const id = ++scan; + const next = await call(commands.fsReadText(path)) + .then((html) => previewResources(path, url, html)) + .catch(() => new Set([path])); + if (!live || scan !== id) return false; + resources = next; + return true; + }; + void webUrl(path) + .then(async (url) => { + if (!live) return; + pageUrl = url; + await updateResources(url); + if (live) setUrl(url); + }) + .catch((e: unknown) => live && setError(e instanceof Error ? e.message : String(e))); + + const changed = (paths: readonly string[]) => { + if (!paths.some((changedPath) => resources.has(changedPath))) return; + pageChanged ||= paths.includes(path); + clearTimeout(timer); + timer = setTimeout(() => { + if (!pageUrl) return; + if (pageChanged) { + pageChanged = false; + void updateResources(pageUrl).then((current) => { + if (current) setSeq((n) => n + 1); + }); + } else setSeq((n) => n + 1); + }, RELOAD_DELAY); + }; + const offFs = onIdeEvent("fsChanged", (e) => changed([...e.created, ...e.modified, ...e.removed])); + const offSaved = onEditorEvent((e) => { + if (e.type === "docSaved") changed([e.path]); + }); return () => { live = false; - }; - }, [path]); - - // Saved edits anywhere in the project (scripts, styles) reload the page. - useEffect(() => { - const scope = root ?? path.slice(0, path.lastIndexOf("/")); - let timer: ReturnType | undefined; - const reload = () => { - clearTimeout(timer); - timer = setTimeout(() => setSeq((n) => n + 1), RELOAD_DELAY); - }; - const offFs = onIdeEvent("fsChanged", (e) => { - if ([...e.created, ...e.modified, ...e.removed].some((p) => p === scope || p.startsWith(scope + "/"))) reload(); - }); - const offDirty = onIdeEvent("docDirty", (e) => { - if (!e.dirty) reload(); - }); - return () => { clearTimeout(timer); offFs(); - offDirty(); + offSaved(); }; - }, [path, root]); + }, [path]); if (error) return
{error}
; if (!url) return
; diff --git a/src/features/web/previewResources.ts b/src/features/web/previewResources.ts new file mode 100644 index 000000000..e5f839681 --- /dev/null +++ b/src/features/web/previewResources.ts @@ -0,0 +1,59 @@ +const LOADABLE_LINKS = new Set(["stylesheet", "icon", "manifest", "preload", "prefetch", "modulepreload"]); + +function relativePath(pathname: string): string | null { + try { + const segments = pathname.split("/").map(decodeURIComponent); + return segments.some((part) => /[/\\:\0]/.test(part)) ? null : segments.filter(Boolean).join("/"); + } catch { + return null; + } +} + +/** Local resources referenced by a page inside the built-in server's URL namespace. */ +export function previewResources(path: string, url: string, html: string): Set { + const resources = new Set([path]); + const page = new URL(url); + // The first two URL segments are the server token and the served directory's key. + const prefix = page.pathname.split("/").slice(0, 3).join("/") + "/"; + const pagePath = relativePath(page.pathname.slice(prefix.length)); + if (!pagePath || !path.endsWith(`/${pagePath}`)) return resources; + const directory = path.slice(0, -pagePath.length); + + const template = document.createElement("template"); + template.innerHTML = html; + const doc = template.content; + let base = page; + try { + base = new URL(doc.querySelector("base[href]")?.getAttribute("href") ?? "", page); + } catch { + // Invalid base URLs leave relative resources on the page URL. + } + + const add = (reference: string | null) => { + if (!reference?.trim() || reference.trimStart().startsWith("#")) return; + try { + const resource = new URL(reference, base); + if (resource.origin !== page.origin || !resource.pathname.startsWith(prefix)) return; + const relative = relativePath(resource.pathname.slice(prefix.length)); + if (relative) resources.add(directory + relative); + } catch { + // The browser ignores invalid resource URLs too. + } + }; + for (const element of doc.querySelectorAll("[src]")) add(element.getAttribute("src")); + for (const element of doc.querySelectorAll("link[href]")) { + if ( + element + .getAttribute("rel") + ?.toLowerCase() + .split(/\s+/) + .some((rel) => LOADABLE_LINKS.has(rel)) + ) + add(element.getAttribute("href")); + } + for (const element of doc.querySelectorAll("video[poster]")) add(element.getAttribute("poster")); + for (const element of doc.querySelectorAll("object[data]")) add(element.getAttribute("data")); + for (const element of doc.querySelectorAll("svg image, svg use")) + add(element.getAttribute("href") ?? element.getAttribute("xlink:href")); + return resources; +}