diff --git a/.agents/skills/formweb-harness/SKILL.md b/.agents/skills/formweb-harness/SKILL.md index 6ed094a4..f031bd07 100644 --- a/.agents/skills/formweb-harness/SKILL.md +++ b/.agents/skills/formweb-harness/SKILL.md @@ -5,7 +5,7 @@ license: Apache-2.0 compatibility: "Project skill for Claude Code and other clients with the FormWeb MCP server connected. Requires a running local FormWeb FastAPI service and explicit Agents enablement." metadata: author: "nodemode-ai" - version: "0.31.2" + version: "0.33.0" --- # FormWeb Harness diff --git a/.claude/skills/formweb-harness/SKILL.md b/.claude/skills/formweb-harness/SKILL.md index 6ed094a4..f031bd07 100644 --- a/.claude/skills/formweb-harness/SKILL.md +++ b/.claude/skills/formweb-harness/SKILL.md @@ -5,7 +5,7 @@ license: Apache-2.0 compatibility: "Project skill for Claude Code and other clients with the FormWeb MCP server connected. Requires a running local FormWeb FastAPI service and explicit Agents enablement." metadata: author: "nodemode-ai" - version: "0.31.2" + version: "0.33.0" --- # FormWeb Harness diff --git a/.docs/wiki/Architecture.md b/.docs/wiki/Architecture.md index 1b67a11e..130fb176 100644 --- a/.docs/wiki/Architecture.md +++ b/.docs/wiki/Architecture.md @@ -55,6 +55,14 @@ New features are modules at the existing layer seams. Read `frontend/HASHOUT_LOG **Layout grid (0.31.1, issue #36 "snap and grid").** The snap and grid of a structured layout, never a pixel grid: nothing here writes offsets, and nothing relates to breakpoints or the canvas width (see CLAUDE.md). `features/layout-grid.ts` holds the pure geometry, unit-tested in `tests/unit/canvas/`: `slotsOf(kids, flow)` gives one slot per landing place (before the first child, between each two at the middle of the gap, after the last), each with one line, or two where the flow wraps (after the last box of one line and before the first of the next); `nearestSlot` and `lineDistance` pick the slot whose line is nearest the pointer, so a container that takes the element has no dead zone; `trackSizes` and `gridCells` turn a computed `grid-template-columns`/`rows` and the gaps into cells from the content box; `alignOf` reads `align-items` (`justify-items` for a one-column grid; block flow is start) and `alignGuides` draws an edge only when every neighbour shares it within 1 px; `spacing` draws the container's `gap` (flex or grid) or the neighbours' facing margins (block) from each neighbour towards the slot, at a quarter and three quarters across them so the two never overlap; `landing` words the target as "Before {0}", "Inside {0}, at the end" or "Inside {0}". In `canvas-drag.ts`, `Lanes` measures a container's children and slots once per container per drag (cleared when the canvas document scrolls), `findDrop` takes the drag's `Lanes` and returns the spot with its `line` and `lane` (over a container that is a sibling of a dragged element the before or after band is a quarter of its size along the flow, otherwise 12 px, so a card dragged over the next card in a row reorders the row unless it is held over the middle half), and `markOf` draws that line, so the orange line is always one of the drawn slots; a drop on the element's own place is returned as a spot without commands (label "Stays where it is", the drop moves nothing). At drag start the containers that can take the element (`canContain` on the page tree outside the dragged subtrees and linked instances, the same rule `dropTarget` applies to "into") are measured once and drawn shifted by the canvas scroll; per pointer move the scene is redrawn only when the slot, the scroll or the frame position changes. `features/layout-layer.ts` (`styles/layout-grid.css`, `--z-raised`, tokens only, `pointer-events: none`) draws boxes, cells, slot lines, guides and gap measures from pools of fixed elements in `#overlay-root` that grow once and are hidden with `hidden`, converting with `FrameMap.still()` (one frame rectangle read per draw, so no layout thrash). With about 370 elements on the canvas the pointer-move handler measured 0.76 ms on average for small moves and 1.24 ms for random jumps (main: 0.73 and 1.20), and a drag start 20 to 37 ms (main: 20 to 43). The drag clears the layer on drop, Escape, pointer cancel and a second finger. `view.layout-outlines` (Ctrl+Alt+G, registered from `installCanvasDrag`'s returned `commands`) draws the same layer without a drag for the parent chain of the selection (the page root when it is selected), with grid cells; it is kept in `localStorage` (`formweb.canvas.layout-outlines`, read and written in try/catch), repaints on a requestAnimationFrame from a MutationObserver on the canvas document, its scroll, the stage scroll and ResizeObservers on the frame and the stage, is hidden while the Live responsive preview is on (`editing()` false, frame hidden) and, by CSS, while Preview as published is open. The style element in the canvas head also gives a selected or marked element, other than the page root and text being edited, `cursor: move`, and a MutationObserver on `data-fw-selected` shows the drag tip in the status line the first time a canvas press selects an element (once per tab, `sessionStorage` `formweb.canvas.drag-hint`). +**Hover outlines (0.32.0).** `features/hover-outline.ts` (the row tint in `styles/hover-outline.css`) registers `view.hover-outline` (View > Show hover outlines, on unless `localStorage` `formweb.canvas.hover-outline` is `'0'`). Delegated pointer listeners on the Layers list and, once `canvas.loaded()` resolves, on the canvas document set the attribute `data-fw-hover` on at most one canvas node and, when the pointer is on the canvas, on its layer row; one requestAnimationFrame per change, and an attribute is written only when the hovered key changes. It is an attribute, never a class, so `keyed()` rows and exact-class checks are untouched and `ui/canvas.ts` never removes it. One `"), + "Caf\u00e9.HTML": page("Caf\u00e9", "

menu

"), + "long.html": OVER_CAP, +} + + +def test_the_review_of_loose_files_equals_the_review_of_a_zip_of_the_same_files(client, blank): + from_loose = review_of(client, EQUIVALENT) + from_zip = client.post(REVIEW, content=zip_of(EQUIVALENT, zipfile.ZIP_STORED)) + assert from_zip.status_code == 200, from_zip.text[:400] + assert from_loose == from_zip.json() + assert len(from_loose["pages"]) == 4 + + +def test_importing_loose_files_gives_the_same_pages_as_importing_a_zip_of_the_same_files(client): + client.post("/api/new", json={"name": "Same", "blank": True}) + _, loose_result = imported(client, loose(EQUIVALENT)) + loose_site = pages_as_seen(state_of(client)[1]) + client.post("/api/new", json={"name": "Same", "blank": True}) + _, zip_result = imported(client, zip_of(EQUIVALENT, zipfile.ZIP_STORED), zipped=True) + zip_site = pages_as_seen(state_of(client)[1]) + assert loose_result["message"] == zip_result["message"] + assert loose_result["skipped"] == zip_result["skipped"] + assert loose_result["warnings"] == zip_result["warnings"] + assert len(loose_site) == 5 + assert loose_site == zip_site + + +def test_an_import_of_loose_files_is_one_undo_step(client, blank): + before = state_of(client)[1] + imported(client, loose({"about.html": page("About", "

a

"), "contact.html": page("Contact", "

c

")})) + assert len(state_of(client)[1]["pages"]) == 3 + client.post("/api/command", json={"command": "history.undo", "params": {}}) + assert state_of(client)[1] == before + + +def test_an_import_of_loose_files_after_the_site_changed_since_the_review_is_refused(client, blank): + body = loose({"about.html": page("About", "

a

")}) + revision = review_of(client, {"about.html": page("About", "

a

")})["revision"] + client.post("/api/command", json={"command": "page.add", "params": {"name": "Meanwhile", "slug": "/meanwhile"}}) + before = state_of(client) + r = client.post(f"{IMPORT}?mode=new&revision={revision}", json=body) + assert r.status_code == 409, r.text[:400] + assert "review" in r.json()["detail"].lower() + assert state_of(client) == before + + +def test_loose_files_imported_again_with_replace_mode_swap_content_without_adding_pages(client, blank): + imported(client, loose({"about.html": page("About", "

About first

")})) + count = len(state_of(client)[1]["pages"]) + review, _ = imported(client, loose({"about.html": page("About", "

About second

")}), mode="replace") + assert review["canReplace"] is True + site = state_of(client)[1] + assert len(site["pages"]) == count + seen = dict((slug, html) for slug, _, _, html in pages_as_seen(site)) + assert "About second" in "".join(seen["/about"]) and "About first" not in "".join(seen["/about"]) diff --git a/backend/tests/site_import/test_site_import_source_project.py b/backend/tests/site_import/test_site_import_source_project.py new file mode 100644 index 00000000..2b329190 --- /dev/null +++ b/backend/tests/site_import/test_site_import_source_project.py @@ -0,0 +1,131 @@ +import json + +import pytest + +from site_zips import answered_within, page, zip_of + +REVIEW = "/api/library/import-site/review" +IMPORT = "/api/library/import-site" +BOUND = 30 +NOTHING = "Nothing was imported." +PACKAGE = json.dumps({"name": "shop", "private": True, "scripts": {"dev": "vite", "build": "vite build"}, "devDependencies": {"vite": "^5.0.0"}}) + + +@pytest.fixture() +def blank(client): + r = client.post("/api/new", json={"name": "Blank", "blank": True}) + assert r.status_code == 200, r.text + return r.json() + + +def state_of(client): + state = client.get("/api/state").json() + return state["revision"], state["site"] + + +def source_page(script): + return page("Shop", '
', f'') + + +def refusal(client, route, data): + before = state_of(client) + r = answered_within(BOUND, lambda: client.post(route, content=data)) + assert state_of(client) == before, "a refused import changed the site or its revision" + assert 400 <= r.status_code < 500, (r.status_code, r.text[:400]) + return r.status_code, r.json()["detail"] + + +def says_build_first(detail): + assert "source" in detail.lower(), detail + assert "npm run build" in detail, detail + assert "output folder" in detail, detail + assert detail.endswith(NOTHING), detail + + +@pytest.mark.parametrize("route", [REVIEW, IMPORT]) +def test_a_zip_with_package_json_and_no_html_page_is_refused_as_a_projects_source(client, blank, route): + status, detail = refusal(client, route, zip_of({"package.json": PACKAGE, "src/app.js": "console.log(1);\n", "README.md": "# Shop\n"})) + assert status == 400 + says_build_first(detail) + assert "no HTML page" in detail + + +@pytest.mark.parametrize("script", ["src/main.ts", "src/main.tsx", "src/main.jsx", "src/App.vue", "src/App.svelte"]) +def test_a_page_that_loads_a_script_needing_a_build_is_refused_and_the_script_is_named(client, blank, script): + files = {"package.json": PACKAGE, "index.html": source_page("/" + script), script: "export default 1;\n", "src/style.css": "body{margin:0}"} + status, detail = refusal(client, REVIEW, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert script in detail + + +def test_a_project_folder_one_level_down_is_still_recognised_as_source(client, blank): + files = {"shop/package.json": PACKAGE, "shop/index.html": source_page("./src/main.tsx"), "shop/src/main.tsx": "export {};\n"} + status, detail = refusal(client, IMPORT, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert "src/main.tsx" in detail + + +def test_a_source_zip_that_holds_no_built_copy_does_not_name_one(client, blank): + files = {"package.json": PACKAGE, "index.html": source_page("/src/main.tsx"), "src/main.tsx": "export {};\n"} + _, detail = refusal(client, REVIEW, zip_of(files)) + says_build_first(detail) + assert "dist folder" not in detail and "build folder" not in detail + + +@pytest.mark.parametrize("built", ["dist", "build"]) +def test_a_source_zip_that_also_holds_a_built_copy_names_that_folder(client, blank, built): + files = { + "package.json": PACKAGE, + "index.html": source_page("/src/main.tsx"), + "src/main.tsx": "export {};\n", + f"{built}/index.html": page("Shop", '
', ''), + f"{built}/assets/index-1a2b.js": "console.log(1);\n", + } + status, detail = refusal(client, REVIEW, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert f"{built} folder" in detail + + +def test_a_built_copy_one_folder_down_is_named_with_its_path(client, blank): + files = { + "shop/package.json": PACKAGE, + "shop/index.html": source_page("/src/main.tsx"), + "shop/src/main.tsx": "export {};\n", + "shop/dist/index.html": page("Shop", "

built

"), + } + _, detail = refusal(client, REVIEW, zip_of(files)) + says_build_first(detail) + assert "shop/dist folder" in detail + + +@pytest.mark.parametrize("route", [REVIEW, IMPORT]) +def test_a_source_project_over_the_file_limit_gets_the_source_sentence_instead_of_the_bare_limit(client, blank, route): + files = {"package.json": PACKAGE, "index.html": source_page("/src/main.tsx"), "src/main.tsx": "export {};\n"} + files.update({f"src/components/C{i}.tsx": "export {};\n" for i in range(1100)}) + files.update({f"node_modules/react/f{i}.js": "x" for i in range(400)}) + status, detail = refusal(client, route, zip_of(files)) + assert status == 413 + says_build_first(detail) + assert "main.tsx" in detail + assert "1,103" not in detail and "1,000" not in detail + + +def test_a_finished_static_site_with_a_harmless_package_json_is_reviewed_and_imported(client, blank): + files = { + "package.json": json.dumps({"name": "brochure", "version": "1.0.0", "scripts": {"start": "serve ."}}), + "index.html": page("Brochure", "

Welcome

", ''), + "about.html": page("About", "

About

"), + "app.js": "document.body.dataset.ok = '1';\n", + } + data = zip_of(files) + review = client.post(REVIEW, content=data) + assert review.status_code == 200, review.text[:400] + assert sorted(p["file"] for p in review.json()["pages"]) == ["about.html", "index.html"] + assert [s["file"] for s in review.json()["skipped"]] == ["package.json"] + r = client.post(f"{IMPORT}?mode=new&revision={review.json()['revision']}", content=data) + assert r.status_code == 200, r.text[:400] + assert len(r.json()["pages"]) == 2 + assert {p["seo"]["title"] for p in state_of(client)[1]["pages"]} >= {"Brochure", "About"} diff --git a/backend/tests/site_import/test_site_import_source_rule.py b/backend/tests/site_import/test_site_import_source_rule.py new file mode 100644 index 00000000..70a8e401 --- /dev/null +++ b/backend/tests/site_import/test_site_import_source_rule.py @@ -0,0 +1,150 @@ +import json + +import pytest + +from site_zips import answered_within, page, zip_of + +REVIEW = "/api/library/import-site/review" +IMPORT = "/api/library/import-site" +BOUND = 30 +NOTHING = "Nothing was imported." +PACKAGE = json.dumps({"name": "app", "private": True, "scripts": {"build": "vite build"}}) + + +@pytest.fixture() +def blank(client): + r = client.post("/api/new", json={"name": "Blank", "blank": True}) + assert r.status_code == 200, r.text + return r.json() + + +def state_of(client): + state = client.get("/api/state").json() + return state["revision"], state["site"] + + +def refusal(client, route, data): + before = state_of(client) + r = answered_within(BOUND, lambda: client.post(route, content=data)) + assert state_of(client) == before, "a refused import changed the site or its revision" + assert 400 <= r.status_code < 500, (r.status_code, r.text[:400]) + return r.status_code, r.json()["detail"] + + +def says_build_first(detail): + assert "source" in detail.lower(), detail + assert "npm run build" in detail, detail + assert "output folder" in detail, detail + assert detail.endswith(NOTHING), detail + + +def imports(client, files, pages): + data = zip_of(files) + review = client.post(REVIEW, content=data) + assert review.status_code == 200, review.text[:400] + assert "package.json" in [s["file"] for s in review.json()["skipped"]] + r = client.post(f"{IMPORT}?mode=new&revision={review.json()['revision']}", content=data) + assert r.status_code == 200, r.text[:400] + assert len(r.json()["pages"]) == pages + return r.json() + + +def module_page(title="App", extra_head=""): + return page(title, '
', extra_head + '') + + +@pytest.mark.parametrize("route", [REVIEW, IMPORT]) +def test_a_page_with_a_public_url_placeholder_is_refused_as_a_projects_source(client, blank, route): + files = { + "package.json": PACKAGE, + "public/index.html": page("App", '
', ''), + "src/index.js": "document.title = 'x';\n", + } + status, detail = refusal(client, route, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert detail.count("public/index.html") == 1 + + +@pytest.mark.parametrize("script", ["src/util.ts", "src/App.tsx", "src/App.jsx", "src/App.vue", "src/App.svelte"]) +def test_a_script_needing_a_build_under_src_is_refused_even_when_no_page_loads_it(client, blank, script): + files = {"package.json": PACKAGE, "index.html": page("Home", "

h

", ''), "app.js": "1;\n", script: "export default 1;\n"} + status, detail = refusal(client, REVIEW, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert detail.count(script) == 1 + + +@pytest.mark.parametrize("route", [REVIEW, IMPORT]) +def test_a_module_script_that_imports_a_package_by_name_is_refused_and_both_are_named(client, blank, route): + files = {"package.json": PACKAGE, "index.html": module_page(), "src/main.js": 'import confetti from "canvas-confetti";\nconfetti();\n'} + status, detail = refusal(client, route, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert detail.count("src/main.js") == 1 + assert "canvas-confetti" in detail + + +def test_a_module_script_that_imports_a_package_named_in_an_import_map_imports(client, blank): + importmap = '' + files = {"package.json": PACKAGE, "index.html": module_page(extra_head=importmap), "src/main.js": 'import confetti from "canvas-confetti";\nconfetti();\n'} + imports(client, files, 1) + + +def test_a_finished_site_with_package_json_and_a_src_folder_of_plain_js_and_css_using_relative_imports_imports(client, blank): + files = { + "package.json": PACKAGE, + "index.html": module_page("Home", ''), + "about.html": page("About", "

about

", ''), + "src/main.js": 'import { label } from "./util.js";\nexport * from "./util.js";\ndocument.title = label;\n', + "src/util.js": "export const label = 'abc';\nexport default 'abc';\n", + "src/site.css": "body{margin:0}\n", + "js/old.js": "window.old = 1;\n", + } + imports(client, files, 2) + + +def test_a_module_script_that_imports_from_an_https_address_imports(client, blank): + files = {"package.json": PACKAGE, "index.html": module_page(), "src/main.js": 'import confetti from "https://cdn.example.org/confetti.mjs";\nconfetti();\n'} + imports(client, files, 1) + + +NAMED_ONCE = { + "a_page_in_src_loading_a_script_beside_it": ({"package.json": PACKAGE, "src/index.html": page("A", "

a

", ''), "src/main.ts": "export {};\n"}, "src/main.ts"), + "the_same_one_folder_down_with_a_dot_slash": ({"app/package.json": PACKAGE, "app/src/index.html": page("A", "

a

", ''), "app/src/main.ts": "export {};\n"}, "app/src/main.ts"), + "a_top_page_loading_from_the_root": ({"package.json": PACKAGE, "index.html": page("A", "

a

", ''), "src/main.tsx": "export {};\n"}, "src/main.tsx"), + "a_top_page_loading_from_the_root_one_folder_down": ({"p/package.json": PACKAGE, "p/index.html": page("A", "

a

", ''), "p/src/main.tsx": "export {};\n"}, "p/src/main.tsx"), + "a_placeholder_page_one_folder_down": ({"p/package.json": PACKAGE, "p/public/index.html": page("A", "

a

", ''), "p/src/index.js": "1;\n"}, "p/public/index.html"), + "a_by_name_import_one_folder_down": ({"p/package.json": PACKAGE, "p/index.html": module_page(), "p/src/main.js": 'import x from "lib";\n'}, "p/src/main.js"), +} + + +@pytest.mark.parametrize("case", list(NAMED_ONCE)) +def test_each_script_or_page_is_named_once_by_its_path_in_the_archive(client, blank, case): + files, path = NAMED_ONCE[case] + status, detail = refusal(client, REVIEW, zip_of(files)) + assert status == 400 + says_build_first(detail) + assert detail.count(path) == 1, detail + name = path.rsplit("/", 1)[-1] + assert detail.count(name) == 1, detail + + +def test_an_over_limit_zip_of_video_segments_named_ts_outside_src_gets_the_plain_count_sentence(client, blank): + files = {"package.json": PACKAGE, "index.html": page("Video", '')} + files.update({f"video/seg{i}.ts": b"\x47" * 188 for i in range(1200)}) + status, detail = refusal(client, REVIEW, zip_of(files)) + assert status == 413 + assert "1,202" in detail + assert "npm run build" not in detail + assert "zip only the folder that holds the finished site" in detail.lower() + assert detail.endswith(NOTHING) + + +def test_an_over_limit_zip_with_the_same_count_of_ts_files_under_src_gets_the_source_sentence(client, blank): + files = {"package.json": PACKAGE, "index.html": page("App", "

a

")} + files.update({f"src/seg{i}.ts": "export {};\n" for i in range(1200)}) + status, detail = refusal(client, REVIEW, zip_of(files)) + assert status == 413 + says_build_first(detail) + assert "1,202" not in detail diff --git a/docs/AGENT_QUICKSTART.md b/docs/AGENT_QUICKSTART.md index 6bba1e56..6dd6aaf4 100644 --- a/docs/AGENT_QUICKSTART.md +++ b/docs/AGENT_QUICKSTART.md @@ -143,7 +143,7 @@ The pack's [scenario evaluations](../.claude/skills/formweb-harness/references/e ## Driving the editor window -Every menu action has a stable command id (`file.save`, `edit.undo`, `insert.heading`, `view.mobile`, `window.studio` and so on). In the browser, `window.formweb.commands()` lists them with label, menu, shortcut and whether each is enabled right now, and `window.formweb.run(id)` runs one exactly as the menu would, returning false when it is disabled. Menu rows and command-search results carry the id in `data-command`. People reach the same actions from the menubar or with Ctrl/Cmd+K. Prefer MCP for site changes; use these ids (or `list_ui_commands` and `run_ui_command`) when an agent has to operate the window itself (switching breakpoint, opening a panel or dialog). Agent ids: `window.agents` (Agent Connect panel), `agents.toggle` (MCP and terminal on or off), `view.terminal` (Ctrl+`), `terminal.new`; panel buttons carry `agents.client.`, `agents.launch.`, `approvals.approve` and `approvals.deny`. `file.home` (File > Home, Alt+Ctrl/Cmd+H) shows the Home screen over the editor. `file.import-site` (File > Import site from zip...) opens the Library's site import view and its file picker; the person picks the zip and confirms the review, so an agent holding the zip bytes should call `library_import_site` instead. `inspector.search` (Window > Search properties, Alt+Ctrl/Cmd+F) opens the right panel and focuses its property search. Demo ids (Help > Demos, also the demo cards on Home): `demo.lowlight`, `demo.looking-back`, `demo.harbour-ferries` and the five whole-site starters `demo.coldmere-plumbing` (business), `demo.northfold-studio` (portfolio), `demo.slow-allotment` (blog), `demo.wenlow-type-day` (event) and `demo.fernhollow-pottery` (shop) each open that demo as a new, unsaved site; they replace the open site, and the window asks the person first when that site has changes not saved as a project. `demo.preview` (optional `id`: any of the eight demo ids) shows a finished demo in a preview over the window and changes nothing, and `demo.preview-close` closes it; while the preview is open every command except the `demo.` ids is disabled, and running one of the eight open ids closes the preview first. `view.preview-full` (Mod+Shift+P, the eye Preview button) opens or closes Preview as published, the compiled open site over the whole window, and changes nothing; while it is open every other command is disabled. `view.preview` toggles the in-canvas Live responsive preview. Layout ids: `window.toggle-left`, `window.toggle-right`, `window.toggle-rail` and the presets `workspace.design`, `workspace.content`, `workspace.build`, `workspace.focus`; rail buttons and collapsed-panel strip buttons carry the same `data-command` ids. Pages and layers panel ids (0.29.0) take an optional `id` (the open page or the selected element when left out): `page.open` `{id}`, `page.rename` `{id?, name?}`, `page.duplicate`, `page.set-home`, `page.move-up`, `page.move-down` and `layer.rename` `{id?, name?}` change the site, one undo step each (without `name` a rename opens the name for the person to type); `layer.collapse-all` and `layer.expand-all` change only the layers list. `page.set-home` also points links and click actions at the page's old address to `/`, and refuses, with the reason in the status line, when either page is a CMS template or has a translated address, or a password protects the page through a route other than `/`. To reorder pages from MCP use the engine command `page.move {id, index}`. +Every menu action has a stable command id (`file.save`, `edit.undo`, `insert.heading`, `view.mobile`, `window.studio` and so on). In the browser, `window.formweb.commands()` lists them with label, menu, shortcut and whether each is enabled right now, and `window.formweb.run(id)` runs one exactly as the menu would, returning false when it is disabled. Menu rows and command-search results carry the id in `data-command`. People reach the same actions from the menubar or with Ctrl/Cmd+K. Prefer MCP for site changes; use these ids (or `list_ui_commands` and `run_ui_command`) when an agent has to operate the window itself (switching breakpoint, opening a panel or dialog). Agent ids: `window.agents` (Agent Connect panel), `agents.toggle` (MCP and terminal on or off), `view.terminal` (Ctrl+`), `terminal.new`; panel buttons carry `agents.client.`, `agents.launch.`, `approvals.approve` and `approvals.deny`. `file.home` (File > Home, Alt+Ctrl/Cmd+H) shows the Home screen over the editor. `file.import-site` (File > Import site from zip...) opens the Library's site import view and its file picker; the person picks the zip and confirms the review, so an agent holding the zip bytes should call `library_import_site` instead; a zip of a project's source (a `package.json` with no HTML page, `.ts`, `.tsx`, `.jsx`, `.vue` or `.svelte` files under its `src` folder or loaded by a page, a `%PUBLIC_URL%` placeholder, or a module script importing a package by name with no import map; `docs/LIBRARY.md` has the exact rule) is refused with a sentence that says to build it and import the output folder. `file.import-html` (File > Import HTML files..., the label was Import HTML...) opens the file picker for one or several `.html` files with Library > Import HTML behind it; the person then chooses As new pages (the same review and one-undo-step import as a site zip) or, for one file, As a section of this page. An agent with the HTML text should call `library_import_html` instead. `view.hover-outline` (View > Show hover outlines, no key, on by default) turns hover outlines on or off: a Layers row under the mouse outlines its element on the canvas, and an element under the mouse is outlined and tints its row. It changes only the view, is remembered in the browser and never saved with the site. `view.design-controls` (View > Show controls in Design fields, checkable, no key) shows or hides the sliders, color swatches and layout choosers beside the Design fields for every field without its own choice (Preferences > Interface > Design fields; each field's label has its own switch). It changes only the editor, is remembered in the browser and never saved with the site; a style value is still one CSS string that you set with `node.update` exactly as before, and the person's controls follow it. `inspector.search` (Window > Search properties, Alt+Ctrl/Cmd+F) opens the right panel and focuses its property search. Demo ids (Help > Demos, also the demo cards on Home): `demo.lowlight`, `demo.looking-back`, `demo.harbour-ferries` and the five whole-site starters `demo.coldmere-plumbing` (business), `demo.northfold-studio` (portfolio), `demo.slow-allotment` (blog), `demo.wenlow-type-day` (event) and `demo.fernhollow-pottery` (shop) each open that demo as a new, unsaved site; they replace the open site, and the window asks the person first when that site has changes not saved as a project. `demo.preview` (optional `id`: any of the eight demo ids) shows a finished demo in a preview over the window and changes nothing, and `demo.preview-close` closes it; while the preview is open every command except the `demo.` ids is disabled, and running one of the eight open ids closes the preview first. `view.preview-full` (Mod+Shift+P, the eye Preview button) opens or closes Preview as published, the compiled open site over the whole window, and changes nothing; while it is open every other command is disabled. `view.preview` toggles the in-canvas Live responsive preview. Layout ids: `window.toggle-left`, `window.toggle-right`, `window.toggle-rail` and the presets `workspace.design`, `workspace.content`, `workspace.build`, `workspace.focus`; rail buttons and collapsed-panel strip buttons carry the same `data-command` ids. Pages and layers panel ids (0.29.0) take an optional `id` (the open page or the selected element when left out): `page.open` `{id}`, `page.rename` `{id?, name?}`, `page.duplicate`, `page.set-home`, `page.move-up`, `page.move-down` and `layer.rename` `{id?, name?}` change the site, one undo step each (without `name` a rename opens the name for the person to type); `layer.collapse-all` and `layer.expand-all` change only the layers list. `page.set-home` also points links and click actions at the page's old address to `/`, and refuses, with the reason in the status line, when either page is a CMS template or has a translated address, or a password protects the page through a route other than `/`. To reorder pages from MCP use the engine command `page.move {id, index}`. Canvas context menu ids act on the selected element: `edit.text` starts inline text editing on the canvas, `edit.select-parent` selects the containing element, `edit.wrap` puts the element, with any other selected elements beside it in the same parent, in a new empty div (one undo step), `style.copy` remembers its styles for the picked breakpoint in the window and `style.paste` applies them to the selection (one undo step), and `inspector.text-style`, `inspector.background`, `inspector.spacing`, `inspector.size`, `inspector.link` and `inspector.image` open the right panel at that field. From MCP, change styles with the engine command `node.update` instead. diff --git a/docs/CONTENT_PORTABILITY.md b/docs/CONTENT_PORTABILITY.md index bc0fbb08..e7db8d24 100644 --- a/docs/CONTENT_PORTABILITY.md +++ b/docs/CONTENT_PORTABILITY.md @@ -16,6 +16,6 @@ Local library storage is a component sharing workflow across projects in this Fo POST /api/library/import-site/review takes the bytes of a .zip holding a static site (HTML, CSS, JavaScript, pictures, fonts) and answers what an import would do without changing anything: each page with its file, proposed route and the route it would replace, the number and size of assets, every skipped file with a reason, the count of ignored system files, whether replacing matching routes is safe, and the revision it was computed against. POST /api/library/import-site?mode=new|replace&revision=N imports the same bytes as one Rust-validated batch, so one undo step, and refuses with 409 when the site has changed since that revision. File > Import site from zip... and the MCP tool library_import_site use these routes. -Each HTML file becomes a page holding one code section under the single-page Import HTML rules; it is editable as code. In the editor the import offers to bring pages in as editable elements, and any code section can be converted later (Convert to editable elements..., command `library.convert-section`); the section below says what that keeps. Pictures, videos and WOFF2 fonts are stored through the asset store with its type and size checks and their references rewritten; links between imported pages are rewritten to the new routes; external URLs are untouched; title and meta description fill page SEO. The archive is read in memory under hard caps (64 MiB archive, 1,000 entries, 2 MiB file list, 128 MiB unpacked, 12 folder levels, a 100 to 1 expansion limit for entries over 1 MiB, per-file caps matching the asset caps) and refused whole for absolute, drive-letter or `..` names, symbolic links and passwords. The import changes neither the site document model nor GET /api/export: an imported page exports like any page with a code section. [LIBRARY.md](LIBRARY.md) lists the exact rules. +Each HTML file becomes a page holding one code section under the single-page Import HTML rules; it is editable as code. In the editor the import offers to bring pages in as editable elements, and any code section can be converted later (Convert to editable elements..., command `library.convert-section`); the section below says what that keeps. Pictures, videos and WOFF2 fonts are stored through the asset store with its type and size checks and their references rewritten; links between imported pages are rewritten to the new routes; external URLs are untouched; title and meta description fill page SEO. The archive is read in memory under hard caps (64 MiB archive, 40,000 entries and a 2 MiB file list in all, 1,000 entries and 12 folder levels outside the ignored `__MACOSX`, `node_modules` and dot folders, 128 MiB unpacked, a 100 to 1 expansion limit for entries over 1 MiB, per-file caps matching the asset caps) and refused whole for absolute, drive-letter or `..` names, symbolic links and passwords, and for a project's source that still needs a build step (a `package.json` at the top or one folder down with no HTML page, `.ts`, `.tsx`, `.jsx`, `.vue` or `.svelte` files under its `src` folder, a page loading such a script or holding `%PUBLIC_URL%`, or a module script importing a package by name with no import map; [LIBRARY.md](LIBRARY.md) has the exact rule). The same two routes also take loose HTML pages as `{"files": [{"name", "html"}]}` (File > Import HTML files...), read as if they were the top level of a zip. The import changes neither the site document model nor GET /api/export: an imported page exports like any page with a code section. [LIBRARY.md](LIBRARY.md) lists the exact rules. Converting HTML to editable elements happens in the editor window, because it needs a browser to work out the cascade: the section's HTML and CSS are rendered in a hidden frame with no scripts and no outside network, each element's computed style is reduced to what differs from that element's own default, and the result goes to the engine as one batch of `node.add` commands with chosen ids (one undo step), so the engine's tag, attribute, URL and style allowlists are the last word. What converts: every tag the engine takes (structure, headings, text, inline formatting as child elements, links, pictures, lists, tables, forms and fields, figures, details, video and audio), with text, ids, link addresses and targets, picture sources, alternative text and sizes, form attributes and table spans; old presentational tags and attributes (``, `
`, `bgcolor`, `align`, `cellpadding`) become styles. Base styles only: layout (display, flex, grid, gaps, alignment, position), sizes, spacing, type (family, size, weight, style, line height, letter spacing, alignment, case, decoration), colours, background colours and gradients, borders, radius, shadows, opacity, overflow, object fit, list and table styles, transforms. Self-hosted WOFF2 faces the page uses join `design.fonts`. What stays as code, in place, as small code sections with their measured look inlined: scripts (the page script is kept unless the person unticks it), inline frames, ``, `` and ``, `` and custom elements. What is lost, and named in the result: `@media` rules (no breakpoint is created; redo small screens in the breakpoint list), `:hover` and `:focus` styles, `::before` and `::after` content, `url()` background pictures from other websites or tiled (the style allowlist takes no `url()`; an own-asset picture sized `cover` or `contain` instead becomes an `img` placed behind the content with `position: absolute`, `z-index: -1` and `object-fit`, its box given `isolation: isolate`), floats (no `float` property), event handlers and `javascript:` links, classes, and any value the engine refuses (counted). A page drawn by the browser in quirks or almost-standards mode (an old HTML 4 doctype) can differ by a few pixels of line height, since exported pages use standards mode. One section converts to at most 480 elements, and the pages of a site import convert together in one batch (up to the engine's 4,000 commands), a page too large for that staying a code section; a larger page converts one top-level part at a time, its remaining code scoped to its own element. The exported page and the canvas of a converted page draw the same at desktop width; the measured difference is in [Importing](guide/09-importing.md#how-close-the-result-is). diff --git a/docs/DESKTOP_TESTING.md b/docs/DESKTOP_TESTING.md index 5cee0404..2b3d6a95 100644 --- a/docs/DESKTOP_TESTING.md +++ b/docs/DESKTOP_TESTING.md @@ -1,6 +1,6 @@ # Testing the desktop app by hand -These steps check four things that only the desktop app does, because it saves downloads itself and hands links to the system browser: the export notice, Show in folder, the " (1)" name for a second copy, and Open in browser. Run them on each system before a release and write the result in the table below. +These steps check four things that only the desktop app does, because it saves downloads itself and hands links to the system browser: the export notice, Show in folder, the " (1)" name for a second copy, and Open in browser. Run them on each system before a release and write the result in the table below. Step 6 reads how long the app took to start. ## What has been run @@ -12,7 +12,7 @@ These steps check four things that only the desktop app does, because it saves d | 2026-11-25 | macOS | Not run | Nothing | Not verified | | 2026-11-25 | Windows | Not run | Nothing | Not verified | -The Windows and macOS code of the shell was compiled for those systems on Linux (`cargo check` for `x86_64-pc-windows-gnu` and `aarch64-apple-darwin`), which shows that it builds, not that it works. +The Windows and macOS code of the shell was compiled for those systems on Linux (`cargo check` for `x86_64-pc-windows-gnu` and `aarch64-apple-darwin`), which shows that it builds, not that it works. The 0.32.0 start-up change (step 6) was checked the same way for `x86_64-pc-windows-msvc` only, and has not been run on any system. ## Before you start (every system) @@ -66,6 +66,29 @@ The folder in the notice is: The canvas frame is allowed to run scripts because WebKit, which the desktop app uses on macOS and Linux, runs none of the editor's click, key and drag handlers in a frame that is not. No script from the site runs there: the canvas document's own policy blocks every script, the canvas never builds script, frame or plugin elements, and the frame never leaves that document, since canvas links have no `href` and every other navigation of the frame is cancelled. Step 4 checks the last part; the reasoning is in the wiki's Architecture page under "Canvas frame and scripts". +## 6. Start-up time + +The app shows its window as soon as the editor is ready, after at least 0.5 s of the splash. When the window is shown it writes one line to its error output: + +`[formweb] start-up: service started 120 ms, service ready 2140 ms, editor ready 2630 ms, window shown 2850 ms` + +Each time is counted from the moment the app started: the local service was started, the service answered and the window could open, the editor reported that it was ready, and the window was shown. "Window shown" is normally "editor ready" plus about 220 ms, the time the splash bar takes to finish. A moment that never happened reads, for example, `editor ready not reached`, which means the window was shown by the 20-second fallback. When the app found a FormWeb service of the same version already running, the line starts with `service already running`. + +Windows. The app has no console, so its error output must be sent to a file: + +1. Quit FormWeb if it is running. +2. In PowerShell, run `Start-Process -FilePath "$env:LOCALAPPDATA\FormWeb\FormWeb.exe" -RedirectStandardError "$env:TEMP\formweb-start.txt" -Wait`, with the real path of the installed `FormWeb.exe` if yours is elsewhere. +3. Wait for the window, then quit the app. +4. Run `Select-String "start-up" $env:TEMP\formweb-start.txt`. + +macOS: + +1. Quit FormWeb if it is running. +2. Run `ls /Applications/FormWeb.app/Contents/MacOS/` and note the program that is not `formweb-engine`. +3. Start it from Terminal, for example `/Applications/FormWeb.app/Contents/MacOS/ 2>&1 | grep start-up`, wait for the window, then quit the app. + +On both, expect one line starting `[formweb] start-up:` with four values. Start the app twice and write down both lines, to compare a first start with a second one. When "service ready" is close to "editor ready", most of the wait is the service starting; on Windows that includes the service unpacking itself, between "service started" and "service ready". To see the `service already running` form, start a service first with `./formweb serve` from a copy of the source of the same version. + ## When something fails Write down the system and its version, what you pressed, what the notice or status line said, and the path of the file. On Linux, start the app from a terminal and copy its output. diff --git a/docs/LIBRARY.md b/docs/LIBRARY.md index a50176aa..745912e2 100644 --- a/docs/LIBRARY.md +++ b/docs/LIBRARY.md @@ -241,8 +241,8 @@ All routes live in `backend/app/library_routes.py`. Reads authorize `read`, writ | `POST /api/library/presets/{id}/apply` | `{mode?, page?}` where `mode` is `all` (default) or `missing` | The batch result plus `{changed}`; `{changed: false}` when there is nothing to do. | | `POST /api/library/starters/{id}/apply` | `{values?, updateComponents?}` | The batch result plus `{pages, warnings}`. `values` re-casts fields shared by the sections, such as tint and name. | | `POST /api/library/import-html` | `{html, css?, name?, parent?, index?, page?}` | The batch result plus `{root, warnings}`. | -| `POST /api/library/import-site/review` | the `.zip` bytes as the body | `{pages, assets: {count, bytes}, supportFiles, skipped, ignored, canReplace, replaceNote, notes, revision}`. Changes nothing. | -| `POST /api/library/import-site?mode=new\|replace&revision=N` | the same `.zip` bytes | The batch result plus `{pages, assets, skipped, warnings, message}`. 409 when the site's revision is no longer `revision`. | +| `POST /api/library/import-site/review` | the `.zip` bytes as the body, or loose pages as `{"files": [{"name", "html"}]}` with `Content-Type: application/json` | `{pages, assets: {count, bytes}, supportFiles, skipped, ignored, canReplace, replaceNote, notes, revision}`. Changes nothing. | +| `POST /api/library/import-site?mode=new\|replace&revision=N` | the same `.zip` bytes, or the same JSON | The batch result plus `{pages, assets, skipped, warnings, message}`. 409 when the site's revision is no longer `revision`. | An insert uploads and owns the bundled media, merges the missing built components into the site's `code` group, applies the preset in mode `missing`, expands the template under `parent`, moves it to `index` if given, and appends the behaviors command, all in the one batch. A component the site already has with a different `sourceDigest` is kept, with a warning, unless the request sets `updateComponents`; a component with no built record is compiled on the spot, with a warning. If the template sets an unscoped variable (a name written without `%%`) that the site already has, the insert warns that every copy shares it; the shipped templates scope all of theirs. @@ -260,15 +260,18 @@ Caps: 512 KiB of markup, 256 KiB of styles and 512 KiB of script; larger input i ## Import site from zip -`backend/app/site_import.py` turns a zip of a static site into pages; the two `import-site` routes in `library_routes.py` call it, and the editor's site import view (`frontend/src/features/library/site-import.ts`, opened by `file.import-site` or from the Import HTML view) shows the review and sends the same bytes twice. Both routes authorize `edit`, sit behind the same loopback, origin, identity and window-key middleware as every library route, and the request guard in `main.py` caps their bodies at 64 MiB (`MAX_SITE_ARCHIVE_BYTES`, listed in `SITE_ARCHIVE_PATHS`); the editor's review call waits for queued edits like `/api/audit` does. +`backend/app/site_import.py` turns a zip of a static site into pages; the two `import-site` routes in `library_routes.py` call it, and the editor's site import view (`frontend/src/features/library/site-import.ts`, opened by `file.import-site`, by `file.import-html` once files are picked, or from the Import HTML view) shows the review and sends the same bytes, or the same JSON, twice. Both routes authorize `edit`, sit behind the same loopback, origin, identity and window-key middleware as every library route, and the request guard in `main.py` caps their bodies at 64 MiB (`MAX_SITE_ARCHIVE_BYTES`, listed in `SITE_ARCHIVE_PATHS`); the editor's review call waits for queued edits like `/api/audit` does. Reading the archive, all in memory with the standard library's `zipfile`; nothing is written to disk under an entry's name: -- Before `zipfile` parses anything, the end record must claim at most 1,000 entries and a file list of at most 2 MiB. -- Refused whole, with a plain sentence: a name that is absolute, has a drive letter, a NUL or a `..` part; a symbolic link entry; an encrypted entry; a path deeper than 12 folders; a name that appears twice ignoring case; an entry over 1 MiB that expands more than 100 times; more than 128 MiB unpacked (declared or read). -- Ignored and counted: `__MACOSX`, any dotfile or dot folder, anything under `node_modules`. A single top folder shared by every kept entry is stripped. +- Before `zipfile` parses anything, the end record must claim at most 40,000 entries and a file list of at most 2 MiB; after parsing, the list must hold at most 40,000 entries (for zip64 archives, whose end record can claim more). These count every entry, ignored ones included. +- Ignored and counted in `ignored`, never opened: `__MACOSX`, any dotfile or dot folder, anything under `node_modules`. Ignored entries do not count toward the 1,000 below and are not checked for depth. +- Refused whole, with a plain sentence: a name that is absolute, has a drive letter, a NUL or a `..` part; a symbolic link entry; an encrypted entry; a kept path deeper than 12 folders; a name that appears twice ignoring case; an entry over 1 MiB that expands more than 100 times; more than 1,000 kept entries, checked after parsing; more than 128 MiB unpacked (declared or read). Every refusal ends with "Nothing was imported.", and the count and size sentences also say what to do (zip only the folder that holds the finished site). A single top folder shared by every kept entry is stripped. +- A project's source is refused with status 400 (`_project`). It needs a `package.json` at the top or one folder down, outside ignored folders; the folder that holds it is the project folder. Then any one of these makes it source: no `.html` or `.htm` file outside ignored folders; a `.ts`, `.tsx`, `.jsx`, `.vue` or `.svelte` file anywhere under the project folder's `src/` folder (`src/main.ts`, `app/src/App.jsx`); or, once the pages are read, a kept page that loads a local script ending in one of those five extensions, a kept page that contains `%PUBLIC_URL%`, or a kept page that loads a local `type="module"` script importing a package by name while no kept page has a `', + "src/main.tsx": "export const app = 1;", + }) + before = harbour.site() + with harbour.page.expect_file_chooser() as chooser: + harbour.page.evaluate("window.formweb.run('file.import-site')") + chooser.value.set_files(str(source)) + view = harbour.page.locator(".fw-lib-site") + expect(view.locator(".fw-lib-note")).to_contain_text("Nothing was imported.") + status, sentence = service_review(harbour, source) + assert status == 400, f"the service accepted a project's source: {sentence}" + assert "Build it first" in sentence and sentence.endswith("Nothing was imported.") + expect(view.locator(".fw-lib-note")).to_have_text(sentence) + expect(view.locator(".fw-lib-site-review")).to_be_hidden() + expect(view.locator(".fw-lib-insert")).to_be_disabled() + assert harbour.site() == before, "the refused zip changed the site" + + +def test_a_pick_that_mixes_a_zip_with_an_html_file_is_refused_with_one_sentence_and_nothing_is_sent(harbour, tmp_path): + site_zip = zip_file(tmp_path, "site.zip", {"index.html": html_page("Home", "Welcome")}) + loose = html_file(tmp_path, "extra.html", "Extra") + sent = [] + harbour.page.on("request", lambda r: sent.append(r.url) if "/api/library/import-site" in r.url else None) + before = harbour.site() + view = pick(harbour, "file.import-site", site_zip, loose) + expect(view.locator(".fw-lib-note")).to_have_text("Choose one .zip file, or one or more .html files.") + expect(view.locator(".fw-lib-site-review")).to_be_hidden() + expect(view.locator(".fw-lib-insert")).to_be_disabled() + assert sent == [], f"the mixed pick was sent to the service: {sent}" + assert harbour.site() == before, "the refused pick changed the site" + + +def test_the_review_of_a_zip_says_how_many_files_in_system_and_dependency_folders_were_ignored(harbour, tmp_path): + archive = zip_file(tmp_path, "with-folders.zip", { + "index.html": html_page("Home", "Welcome"), + "node_modules/left/index.js": "module.exports = 1;", + "node_modules/right/index.js": "module.exports = 2;", + "__MACOSX/._index.html": "x", + }) + view = pick(harbour, "file.import-site", archive) + expect(view.locator(".fw-lib-site-review")).to_contain_text("3 files in system and dependency folders are ignored.") + + +def test_a_second_import_starts_from_a_clean_view_with_no_earlier_review_note_or_greyed_button_behind_the_picker(harbour, tmp_path): + before = harbour.site()["site"] + view = pick(harbour, "file.import-site", zip_file(tmp_path, "first.zip", {"timetable.html": html_page("Timetable", "Sailings")})) + view.locator('[data-bring="code"]').click() + view.locator(".fw-lib-insert:not([disabled])").click() + expect(view.locator(".fw-lib-insert")).to_contain_text("Imported") + harbour.until(lambda s: len(s["pages"]) == len(before["pages"]) + 1, "the first import") + with harbour.page.expect_file_chooser() as chooser: + harbour.page.evaluate("window.formweb.run('file.import-site')") + expect_clean_site_view(view) + chooser.value.set_files(str(zip_file(tmp_path, "second.zip", {"fares.html": html_page("Fares", "Prices")}))) + rows = view.locator(".fw-lib-site-review .fw-lib-site-item") + expect(rows).to_have_count(1) + expect(rows).to_contain_text("fares.html") + expect(view.locator(".fw-lib-note")).to_have_text("") + with harbour.page.expect_file_chooser(): + harbour.page.evaluate("window.formweb.run('file.import-html')") + expect(view).to_be_hidden() + expect(harbour.page.locator(".fw-lib-import:not(.fw-lib-site) .fw-lib-import-part").first).to_be_visible() + + +def test_nothing_above_the_review_or_a_refusal_moves_when_it_appears(harbour, tmp_path): + with harbour.page.expect_file_chooser() as chooser: + harbour.page.evaluate("window.formweb.run('file.import-site')") + view = harbour.page.locator(".fw-lib-site") + choose = view.locator(".fw-lib-choose:not(.fw-lib-site-back)") + files = view.locator(".fw-lib-site-files") + button = view.locator(".fw-lib-insert") + expect(choose).to_be_visible() + places = lambda: {"choose button (top, height)": box(choose), "chosen-file list top": box(files)[0], "import button (top, height)": box(button)} + waiting = places() + chooser.value.set_files(str(zip_file(tmp_path, "two.zip", {"a.html": html_page("Alpha", "A"), "b.html": html_page("Beta", "B")}))) + expect(view.locator(".fw-lib-site-review .fw-lib-site-item")).to_have_count(2) + assert places() == waiting, "something above the review moved when the review appeared" + refused = zip_file(tmp_path, "notes.zip", {"package.json": "{}", "src/app.js": "x"}) + with harbour.page.expect_file_chooser() as chooser: + harbour.page.evaluate("window.formweb.run('file.import-site')") + assert places() == waiting, "the view behind the second picker is not laid out as the first waiting view" + chooser.value.set_files(str(refused)) + expect(view.locator(".fw-lib-note")).to_contain_text("Nothing was imported.") + assert places() == waiting, "something moved when the refusal appeared" + + +HEADING = "Crème brûlée à €4,50" +PARAGRAPH = "“Déjà vu” – naïve façade, Œuvre, señor, Zürich, ‘quoted’." + + +def encoded_page(title, encoding): + return f"{title}

{HEADING}

{PARAGRAPH}

".encode(encoding) + + +def import_as_code(editor, view, what): + before = code_sections(editor.site()["site"]) + view.locator('[data-bring="code"]').click() + view.locator(".fw-lib-insert:not([disabled])").click() + site = editor.until(lambda s: len(code_sections(s)) == len(before) + 1, what) + added = [record for key, record in code_sections(site).items() if key not in before] + return site, added[0]["html"] + + +@pytest.mark.parametrize("encoding", ["windows-1252", "utf-8-sig"]) +def test_a_picked_html_file_not_in_plain_utf8_arrives_with_the_same_text_as_inside_a_zip_as_a_page_and_as_a_section(harbour, tmp_path, encoding): + title = "Café " + encoding + data = encoded_page(title, encoding) + assert data.startswith(b"\xef\xbb\xbf") if encoding == "utf-8-sig" else b"\x80" in data and b"\x93" in data + archive = tmp_path / "zipped.zip" + with zipfile.ZipFile(archive, "w") as handle: + handle.writestr("zipped.html", data) + loose = tmp_path / "loose.html" + loose.write_bytes(data) + _, zipped = import_as_code(harbour, pick(harbour, "file.import-site", archive), "the zipped page") + site, as_page = import_as_code(harbour, pick(harbour, "file.import-html", loose), "the picked file as a page") + view = pick(harbour, "file.import-html", loose) + view.get_by_role("radio", name="As a section of this page").click() + _, as_section = import_as_code(harbour, view, "the picked file as a section") + for path, html in (("inside a zip", zipped), ("picked as a page", as_page), ("picked as a section", as_section)): + assert HEADING in html and PARAGRAPH in html, f"{path}, the text did not arrive as written: {html[:300]!r}" + assert "�" not in html and "" not in html, f"{path}, a replacement or byte order mark character was stored: {html[:300]!r}" + assert as_page == zipped, "the picked page differs from the same bytes imported inside a zip" + assert [name for name in harbour.page_names(site) if name.startswith("Caf")] == [title, title] + + +def test_after_the_service_refuses_a_picked_file_the_sentence_stays_in_view_nothing_can_be_imported_and_a_new_pick_works(harbour, tmp_path): + hidden = tmp_path / ".hidden.html" + hidden.write_text(html_page("Hidden", "Hidden"), "utf-8") + before = harbour.site() + view = pick(harbour, "file.import-html", hidden) + note = view.locator(".fw-lib-note") + expect(note).to_contain_text("Nothing was imported.") + request = urllib.request.Request(harbour.base + "/api/library/import-site/review", data=json.dumps({"files": [{"name": ".hidden.html", "html": hidden.read_text("utf-8")}]}).encode(), method="POST", headers={"Content-Type": "application/json", "X-FormWeb-Window-Key": harbour.window_key}) + try: + urllib.request.urlopen(request, timeout=30) + raise AssertionError("the service accepted a file whose name starts with a dot") + except urllib.error.HTTPError as error: + sentence = json.loads(error.read())["detail"] + expect(note).to_have_text(sentence) + expect(note).to_be_in_viewport() + button = view.locator(".fw-lib-insert") + expect(button).to_be_disabled() + view.get_by_role("radio", name="As a section of this page").click() + expect(view.get_by_role("radio", name="As a section of this page")).to_have_attribute("aria-checked", "true") + expect(button).to_be_disabled() + expect(note).to_have_text(sentence) + expect(note).to_be_in_viewport() + assert harbour.site() == before, "the refused file changed the site" + with harbour.page.expect_file_chooser() as chooser: + view.locator(".fw-lib-choose:not(.fw-lib-site-back)").click() + chooser.value.set_files(str(html_file(tmp_path, "harbour-walk.html", "Harbour walk"))) + expect(note).to_have_text("") + expect(view.locator(".fw-lib-site-review")).to_contain_text("/harbour-walk") + view.locator('[data-bring="code"]').click() + view.locator(".fw-lib-insert:not([disabled])").click() + after = harbour.until(lambda s: len(s["pages"]) == len(before["site"]["pages"]) + 1, "the new pick to import one page") + assert "Harbour walk" in harbour.page_names(after) diff --git a/frontend/tests/window/test_page_script.py b/frontend/tests/window/test_page_script.py new file mode 100644 index 00000000..f469963c --- /dev/null +++ b/frontend/tests/window/test_page_script.py @@ -0,0 +1,191 @@ +import re + +import pytest +from playwright.sync_api import expect + +SCRIPT = "document.getElementById('ps-target').textContent = 'The page script ran'" +NOTE = "A page script has no box on the page, so these settings do not apply to it." +CONTROLS = "input:visible, select:visible, textarea:visible, button:visible" + + +def element(key, name, tag="div", text="", attrs=None, styles=None): + return {"id": key, "tag": tag, "name": name, "text": text, "children": [], "attrs": attrs or {}, "styles": styles or {}, "breakpoints": {}} + + +@pytest.fixture +def old_script(coldmere): + coldmere.command(None, [ + {"command": "code.sections.allow", "params": {"enabled": True}}, + {"command": "node.add", "params": {"parent": "hm-hero-copy", "node": element("ps-target", "Target", "p", "Waiting", {"id": "ps-target"})}}, + {"command": "node.add", "params": {"parent": "hm-hero-copy", "node": element("old-script", "Old script", styles={"display": "contents"})}}, + {"command": "code.section.set", "params": {"node": "old-script", "value": {"enabled": True, "html": "", "js": SCRIPT}}}, + {"command": "node.add", "params": {"parent": "hm-hero-copy", "node": element("old-code", "Old code", styles={"display": "contents"})}}, + {"command": "code.section.set", "params": {"node": "old-code", "value": {"enabled": True, "html": "

Kept as code

", "css": ""}}}, + ], batch=True) + coldmere.until(lambda site: "old-code" in site["nodes"], "the old-way page script and code section") + expect(block(coldmere, "old-script")).to_be_visible() + expect(coldmere.layer_row("old-script")).to_be_visible() + return coldmere + + +def block(editor, key): + return editor.canvas.locator(f'[data-fw-id="{key}"] > [data-fw-poster]') + + +def click_block(editor, key, button="left"): + box = block(editor, key).bounding_box() + editor.page.mouse.click(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2, button=button) + + +def tab(editor, name): + return editor.page.locator(".inspector button.quiet", has_text=name) + + +def is_open(editor, name): + expect(tab(editor, name)).to_have_class(re.compile(r"\bactive\b")) + + +def selected(editor): + return editor.page.locator('#fw-layers-list .layer-row[aria-selected="true"]').evaluate_all("rows => rows.map(r => r.dataset.key)") + + +def drawn_icon(editor, key): + return editor.layer_row(key).locator(":scope > .icon").evaluate("i => [...i.querySelectorAll('svg')].filter(s => s.getClientRects().length).map(s => s.innerHTML)") + + +def outline(locator): + return locator.evaluate("e => { const s = getComputedStyle(e); return [s.outlineStyle, s.outlineWidth, s.outlineColor]; }") + + +def script_box(editor): + boxes = editor.page.locator(".inspector-scroll textarea") + values = boxes.evaluate_all("ts => ts.map(t => t.value)") + assert SCRIPT in values, f"no field in the right panel holds the script; the text fields hold {values}" + return boxes.nth(values.index(SCRIPT)) + + +def menu_entries(editor): + return [item.inner_text().split("\n")[0] for item in editor.menu().locator('[role="menuitem"]').all()] + + +def test_a_script_only_code_section_made_the_old_way_is_shown_on_the_canvas_as_a_page_script_block(old_script): + words = block(old_script, "old-script").inner_text().split("\n") + assert words[0] == "Page script" + assert "Runs in Preview and on the published site, not on this canvas." in words + expect(old_script.canvas.locator("#ps-target")).to_have_text("Waiting") + + +def test_clicking_the_page_script_block_selects_its_layer_and_the_block_shows_the_selection_outline(old_script): + start = old_script.site()["site"] + old_script.canvas.locator('[data-fw-id="hm-lead"]').click() + expect(old_script.layer_row("hm-lead")).to_have_attribute("aria-selected", "true") + selection = outline(old_script.canvas.locator('[data-fw-id="hm-lead"]')) + assert outline(block(old_script, "old-script")) != selection + click_block(old_script, "old-script") + expect(old_script.layer_row("old-script")).to_have_attribute("aria-selected", "true") + expect(old_script.page.locator(".inspector-name")).to_have_text("Old script") + assert selected(old_script) == ["old-script"] + assert outline(block(old_script, "old-script")) == selection + after = old_script.site()["site"] + assert after["nodes"]["old-script"] == start["nodes"]["old-script"] + assert after["extensions"]["code"]["sections"]["old-script"] == start["extensions"]["code"]["sections"]["old-script"] + + +def test_the_page_script_layer_row_shows_its_own_icon_and_ordinary_rows_do_not(old_script): + script = drawn_icon(old_script, "old-script") + ordinary = [drawn_icon(old_script, key) for key in ("hm-lead", "hm-btns", "ps-target")] + assert len(script) == 1 and all(len(icon) == 1 for icon in ordinary) + assert all(icon == ordinary[0] for icon in ordinary) + assert script != ordinary[0], "the Page script row draws the same icon as an ordinary element" + assert script != drawn_icon(old_script, "old-code"), "the Page script row draws the same icon as a code section with HTML" + + +def test_a_selected_page_script_shows_its_code_on_content_and_only_the_note_on_design_and_motion(old_script): + old_script.canvas.locator('[data-fw-id="hm-h1"]').click() + tab(old_script, "Motion").click() + is_open(old_script, "Motion") + click_block(old_script, "old-script") + expect(old_script.layer_row("old-script")).to_have_attribute("aria-selected", "true") + is_open(old_script, "Content") + expect(script_box(old_script)).to_be_in_viewport() + for name in ("Design", "Motion"): + tab(old_script, name).click() + is_open(old_script, name) + expect(old_script.page.locator(".inspector-scroll").locator(CONTROLS)).to_have_count(0) + shown = old_script.page.locator(".inspector-scroll").inner_text().strip() + assert shown == NOTE, f"{name} shows {shown[:300]!r}" + + +def test_selecting_an_ordinary_element_after_the_page_script_brings_the_controls_and_the_earlier_tab_back(old_script): + old_script.canvas.locator('[data-fw-id="hm-h1"]').click() + tab(old_script, "Motion").click() + is_open(old_script, "Motion") + controls = old_script.page.locator(".inspector-scroll").locator(CONTROLS) + expect(controls.first).to_be_visible() + click_block(old_script, "old-script") + is_open(old_script, "Content") + old_script.canvas.locator('[data-fw-id="hm-lead"]').click() + expect(old_script.layer_row("hm-lead")).to_have_attribute("aria-selected", "true") + is_open(old_script, "Motion") + expect(controls.first).to_be_visible() + expect(old_script.page.locator(".inspector-scroll").get_by_text(NOTE, exact=True).locator("visible=true")).to_have_count(0) + tab(old_script, "Design").click() + is_open(old_script, "Design") + expect(controls.first).to_be_visible() + expect(old_script.page.locator(".inspector-scroll").get_by_text(NOTE, exact=True).locator("visible=true")).to_have_count(0) + + +def test_the_page_script_menu_has_no_background_spacing_or_size_while_an_ordinary_elements_menu_has_them(old_script): + design = {"Background", "Spacing", "Size"} + click_block(old_script, "old-script", button="right") + expect(old_script.menu()).to_be_visible() + script = menu_entries(old_script) + old_script.page.keyboard.press("Escape") + assert selected(old_script) == ["old-script"] + assert {"Copy", "Delete", "Rename", "Select parent"} <= set(script), script + assert not design & set(script), script + old_script.canvas.locator('[data-fw-id="hm-lead"]').click(button="right") + expect(old_script.menu()).to_be_visible() + ordinary = menu_entries(old_script) + old_script.page.keyboard.press("Escape") + assert design <= set(ordinary), ordinary + + +def test_a_code_section_with_html_reads_code_section_and_a_click_on_its_block_goes_to_the_element_around_it(old_script): + expect(block(old_script, "old-code")).to_have_text("Code section") + click_block(old_script, "old-code") + expect(old_script.layer_row("hm-hero-copy")).to_have_attribute("aria-selected", "true") + assert selected(old_script) == ["hm-hero-copy"] + + +def test_a_heading_dragged_onto_the_page_script_block_is_never_dropped_inside_it(old_script): + start = old_script.site()["site"] + old_script.canvas.locator('[data-fw-id="hm-h1"]').click() + expect(old_script.layer_row("hm-h1")).to_have_attribute("aria-selected", "true") + source = old_script.canvas.locator('[data-fw-id="hm-h1"]').bounding_box() + target = block(old_script, "old-script").bounding_box() + pointer = old_script.canvas_pointer() + pointer.move(source["x"] + 12, source["y"] + 8) + pointer.down() + pointer.move(target["x"] + target["width"] / 2, target["y"] + target["height"] / 2, steps=15, held=True) + where = old_script.page.locator(".fw-canvas-proxy-where") + expect(where).to_have_text(re.compile(r"\S")) + landing = where.inner_text() + assert not landing.startswith("Inside Old script"), landing + pointer.up() + expect(old_script.page.locator("body")).not_to_have_class(re.compile(r"\bfw-canvas-dragging\b")) + if landing == "Stays where it is": + assert old_script.site()["site"] == start + else: + old_script.changed_from(start) + assert old_script.site()["site"]["nodes"]["old-script"]["children"] == [] + + +def test_the_page_script_runs_in_preview_as_published(old_script): + expect(old_script.canvas.locator("#ps-target")).to_have_text("Waiting") + old_script.page.locator('[data-cmd="view.preview-full"]').click() + overlay = old_script.page.get_by_role("dialog", name="Preview as published") + expect(overlay).to_be_visible() + shown = overlay.locator("iframe.fw-fp-frame:visible") + expect(shown).to_have_count(1) + expect(overlay.frame_locator("iframe.fw-fp-frame:visible").locator("#ps-target")).to_have_text("The page script ran") diff --git a/frontend/tests/window/test_stage_path.py b/frontend/tests/window/test_stage_path.py new file mode 100644 index 00000000..01d32daa --- /dev/null +++ b/frontend/tests/window/test_stage_path.py @@ -0,0 +1,161 @@ +import pytest +from playwright.sync_api import expect + +WIDTHS = (900, 1024, 1280, 1440, 1920) +PAGE_NAME = "Harbour ferries winter timetable and crossing notices for island residents" +PAGE_SLUG = "winter-2026/island-residents/ferry-timetable-and-crossing-notices-for-the-outer-isles" +DEEP = "h-lm-c" +DEEP_NAME = "Lighthouse beam circle of the harbour logo" +OTHERS = ("hero-b1", "h-nav-fares", "hero-h", "hero-k") +TWO_FRAMES = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))" + +NAME = """nav => { + const bar = nav.parentElement; + const crumb = nav.querySelector('[aria-current="true"]'); + if (!crumb) return null; + const box = el => { const r = el.getBoundingClientRect(); return { left: r.left, right: r.right, width: r.width, height: r.height }; }; + const inner = el => { const r = el.getBoundingClientRect(); return { left: r.left + el.clientLeft, right: r.left + el.clientLeft + el.clientWidth }; }; + const label = el => el.tagName.toLowerCase() + (el.className ? '.' + String(el.className).trim().split(/\\s+/).join('.') : ''); + const walker = document.createTreeWalker(crumb, NodeFilter.SHOW_TEXT); + let text = null; + for (let node = walker.nextNode(); node; node = walker.nextNode()) if (node.textContent.trim()) { text = node; break; } + if (!text) return { crumb: box(crumb), text: null }; + const range = document.createRange(); + range.selectNodeContents(text); + const holder = text.parentElement; + const style = getComputedStyle(holder); + const clippers = []; + for (let el = holder; el && el !== bar.parentElement; el = el.parentElement) { + if (getComputedStyle(el).overflowX !== 'visible') clippers.push({ name: label(el), self: el === holder, box: box(el), inner: inner(el) }); + } + return { crumb: box(crumb), text: text.textContent, glyphs: box(range), holder: { name: label(holder), tag: holder.tagName, box: box(holder), display: style.display, overflow: style.overflowX, textOverflow: style.textOverflow, whiteSpace: style.whiteSpace }, clippers }; +}""" + +BAR = """nav => { + const bar = nav.parentElement; + const shown = el => { const s = getComputedStyle(el); const r = el.getBoundingClientRect(); return s.display !== 'none' && s.visibility !== 'hidden' && r.width > 0 && r.height > 0; }; + const label = el => el.tagName.toLowerCase() + (el.className ? '.' + String(el.className).trim().split(/\\s+/).join('.') : ''); + const box = el => { const r = el.getBoundingClientRect(); return [r.left, r.top, r.right, r.bottom]; }; + const children = [...bar.children].map((el, i) => ({ name: i + ' ' + label(el), shown: shown(el), box: box(el) })); + const crumbs = [...nav.children].filter(shown).map(el => ({ name: el.textContent.trim() || el.getAttribute('aria-label'), box: box(el) })); + return { bar: box(bar), scroll: bar.scrollWidth, client: bar.clientWidth, nav: box(nav), children, crumbs }; +}""" + + +def nav(editor): + return editor.page.locator('nav[aria-label="Selection path"]') + + +def current_crumb(editor): + return nav(editor).locator('[aria-current="true"]') + + +def set_panels(editor, state): + workspace = editor.page.locator("[data-left][data-right]").first + for side, key in (("left", "Control+["), ("right", "Control+]")): + if workspace.get_attribute(f"data-{side}") != state: + editor.page.keyboard.press(key) + expect(workspace).to_have_attribute(f"data-{side}", state) + + +def select_on_canvas(editor, key, clicked=None): + editor.canvas.locator(f'[data-fw-id="{clicked or key}"]').click() + expect(current_crumb(editor)).to_have_attribute("data-key", key) + + +def select_deep(editor): + select_on_canvas(editor, DEEP, clicked="h-logo-mark") + expect(current_crumb(editor)).to_contain_text(DEEP_NAME) + + +def heads(editor): + for width in WIDTHS: + for panels in ("open", "collapsed"): + editor.page.set_viewport_size({"width": width, "height": 900}) + set_panels(editor, panels) + editor.page.evaluate(TWO_FRAMES) + yield f"{width} px wide, both panels {panels}" + + +def overlap(a, b): + return min(a[2], b[2]) - max(a[0], b[0]) > 0.5 and min(a[3], b[3]) - max(a[1], b[1]) > 0.5 + + +@pytest.fixture +def long_page(harbour): + site = harbour.site()["site"] + home = next(p for p in site["pages"] if p["root"] == "root") + harbour.command("page.update", {"id": home["id"], "patch": {"name": PAGE_NAME, "slug": PAGE_SLUG}}) + harbour.command("node.update", {"id": DEEP, "patch": {"name": DEEP_NAME}}) + harbour.until(lambda s: next(p for p in s["pages"] if p["root"] == "root")["name"] == PAGE_NAME and s["nodes"][DEEP]["name"] == DEEP_NAME, "the long page name, address and element name") + select_deep(harbour) + return harbour + + +def test_the_selected_name_in_the_path_starts_at_its_first_letter_and_is_whole_or_ends_in_a_drawn_ellipsis_at_every_width(long_page): + for head in heads(long_page): + seen = nav(long_page).evaluate(NAME) + assert seen, f"{head}: the path has no current crumb" + assert seen["crumb"]["width"] > 0 and seen["crumb"]["height"] > 0, f"{head}: the selected element's crumb is not displayed: {seen['crumb']}" + assert seen["text"] and seen["text"].strip() == DEEP_NAME, f"{head}: the crumb reads {seen['text']!r}" + glyphs = seen["glyphs"] + assert glyphs["width"] > 0, f"{head}: the selected name has no box" + for clip in seen["clippers"]: + assert glyphs["left"] >= clip["inner"]["left"] - 0.5, f"{head}: the start of {DEEP_NAME!r} is cut off by {clip['name']} (text starts at {glyphs['left']:.1f}, the box at {clip['inner']['left']:.1f})" + cut = [clip for clip in seen["clippers"] if glyphs["right"] > clip["inner"]["right"] + 0.5] + if not cut: + continue + holder = seen["holder"] + assert holder["tag"] != "BUTTON", f"{head}: the name is a button's own text, cut by {[c['name'] for c in cut]}; Chromium draws no ellipsis there" + assert (holder["overflow"], holder["textOverflow"], holder["whiteSpace"]) == ("hidden", "ellipsis", "nowrap"), f"{head}: {holder['name']} cuts the name without an ellipsis: {holder}" + assert holder["display"] != "inline", f"{head}: {holder['name']} is inline, where no ellipsis is drawn" + for clip in seen["clippers"]: + if not clip["self"]: + assert holder["box"]["left"] >= clip["inner"]["left"] - 0.5 and holder["box"]["right"] <= clip["inner"]["right"] + 0.5, f"{head}: {clip['name']} cuts the name box itself, so its ellipsis is not seen: {holder['box']} in {clip['inner']}" + + +def test_nothing_in_the_bar_above_the_canvas_overflows_it_or_overlaps_a_neighbour_at_every_width(long_page): + for head in heads(long_page): + seen = nav(long_page).evaluate(BAR) + bar = seen["bar"] + assert seen["scroll"] <= seen["client"], f"{head}: the bar's content is {seen['scroll']} px wide in {seen['client']} px" + shown = [c for c in seen["children"] if c["shown"]] + for child in shown: + box = child["box"] + assert box[0] >= bar[0] - 0.5 and box[2] <= bar[2] + 0.5, f"{head}: {child['name']} {box} sticks out of the bar {bar}" + for i, a in enumerate(shown): + for b in shown[i + 1:]: + assert not overlap(a["box"], b["box"]), f"{head}: {a['name']} {a['box']} overlaps {b['name']} {b['box']}" + for i, a in enumerate(seen["crumbs"]): + assert a["box"][0] >= seen["nav"][0] - 0.5 and a["box"][2] <= seen["nav"][2] + 0.5, f"{head}: crumb {a['name']!r} {a['box']} sticks out of the path {seen['nav']}" + for b in seen["crumbs"][i + 1:]: + assert not overlap(a["box"], b["box"]), f"{head}: crumb {a['name']!r} overlaps {b['name']!r}" + + +def test_nothing_in_the_bar_above_the_canvas_moves_when_the_selection_changes(long_page): + for head in heads(long_page): + select_deep(long_page) + first = nav(long_page).evaluate(BAR) + for key in OTHERS: + select_on_canvas(long_page, key) + long_page.page.evaluate(TWO_FRAMES) + now = nav(long_page).evaluate(BAR) + assert now["bar"] == first["bar"], f"{head}: the bar moved after selecting {key}" + for before, after in zip(first["children"], now["children"]): + assert (after["shown"], after["box"]) == (before["shown"], before["box"]), f"{head}: {before['name']} moved after selecting {key}: {before['box']} then {after['box']}" + + +def test_a_click_on_a_middle_crumb_selects_that_ancestor(long_page): + long_page.page.set_viewport_size({"width": 1920, "height": 900}) + set_panels(long_page, "collapsed") + select_on_canvas(long_page, "h-nav-fares") + middle = nav(long_page).locator("[data-key]:visible").evaluate_all("cs => cs.map(c => c.dataset.key)") + middle = [key for key in middle[1:] if key.strip() != "more" and key != "h-nav-fares"] + assert middle, "no middle crumb is shown at 1920 px with both panels closed" + target = middle[-1] + crumb = nav(long_page).locator(f'[data-key="{target}"]') + name = crumb.inner_text().strip() + crumb.click() + expect(current_crumb(long_page)).to_have_attribute("data-key", target) + set_panels(long_page, "open") + expect(long_page.page.locator(".inspector-name")).to_have_text(name) diff --git a/native/Cargo.lock b/native/Cargo.lock index ecdac498..63412465 100644 --- a/native/Cargo.lock +++ b/native/Cargo.lock @@ -54,7 +54,7 @@ dependencies = [ [[package]] name = "formweb-core" -version = "0.31.2" +version = "0.33.0" dependencies = [ "formweb-engine", "formweb-export", @@ -64,7 +64,7 @@ dependencies = [ [[package]] name = "formweb-engine" -version = "0.31.2" +version = "0.33.0" dependencies = [ "formweb-model", "getrandom", @@ -73,7 +73,7 @@ dependencies = [ [[package]] name = "formweb-export" -version = "0.31.2" +version = "0.33.0" dependencies = [ "formweb-model", "serde_json", @@ -82,7 +82,7 @@ dependencies = [ [[package]] name = "formweb-model" -version = "0.31.2" +version = "0.33.0" dependencies = [ "serde", "serde_json", diff --git a/native/Cargo.toml b/native/Cargo.toml index 48b23704..76e6406b 100644 --- a/native/Cargo.toml +++ b/native/Cargo.toml @@ -5,7 +5,7 @@ exclude = ["crates/formweb-render"] resolver = "2" [workspace.package] -version = "0.31.2" +version = "0.33.0" edition = "2021" license = "Apache-2.0" diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 44479eb2..08fca455 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1124,7 +1124,7 @@ dependencies = [ [[package]] name = "formweb" -version = "0.31.2" +version = "0.33.0" dependencies = [ "formweb-render", "objc2", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 853d959f..8d7e1613 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formweb" -version = "0.31.2" +version = "0.33.0" description = "FormWeb desktop shell" authors = ["nodemode-ai"] license = "Apache-2.0" diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index e7e7a2da..34cf0d2c 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -28,6 +28,7 @@ mod downloads; mod engine_start; mod render; mod reveal; +mod start_times; mod text_edit; mod traffic_lights; #[cfg(windows)] @@ -415,6 +416,7 @@ fn main() { Ok(child) => child, Err(failure) => engine_failed(&handle, failure, packaged), }; + start_times::mark(&start_times::SERVICE_STARTED); capture_window_key(&mut child); #[cfg(unix)] SERVICE_GROUP.store(child.id() as i32, std::sync::atomic::Ordering::SeqCst); @@ -430,6 +432,7 @@ fn main() { engine_failed(&handle, failure, packaged); } } + start_times::mark(&start_times::SERVICE_READY); let main_thread = handle.clone(); let _ = handle.run_on_main_thread(move || open_editor(&main_thread)); }); diff --git a/src-tauri/src/reveal.rs b/src-tauri/src/reveal.rs index ef2e0430..f035d2f8 100644 --- a/src-tauri/src/reveal.rs +++ b/src-tauri/src/reveal.rs @@ -4,7 +4,7 @@ use std::time::{Duration, Instant}; use tauri::{Manager, Runtime, WebviewWindow}; -pub const SPLASH_MIN: Duration = Duration::from_millis(2600); +pub const SPLASH_MIN: Duration = Duration::from_millis(500); pub const BACKGROUND: tauri::window::Color = tauri::window::Color(10, 10, 10, 255); const BAR_FINISH: Duration = Duration::from_millis(220); const FALLBACK: Duration = Duration::from_secs(20); @@ -16,6 +16,10 @@ pub fn mark_launch() { let _ = LAUNCH.set(Instant::now()); } +pub fn since_launch() -> Duration { + LAUNCH.get_or_init(Instant::now).elapsed() +} + pub const BUILD_VISIBLE: bool = !cfg!(target_os = "macos"); pub fn conceal(window: &WebviewWindow) { @@ -38,6 +42,7 @@ pub fn close_splash(app: &tauri::AppHandle) { #[tauri::command(async)] pub fn app_ready(app: tauri::AppHandle) { + crate::start_times::mark(&crate::start_times::EDITOR_READY); show_main(&app); } @@ -58,8 +63,10 @@ fn show_main(app: &tauri::AppHandle) { let _ = main.show(); let _ = main.set_focus(); crate::traffic_lights::place(&main.as_ref().window()); + crate::start_times::mark(&crate::start_times::WINDOW_SHOWN); } close_splash(app); + crate::start_times::report(); } #[cfg(target_os = "macos")] diff --git a/src-tauri/src/start_times.rs b/src-tauri/src/start_times.rs new file mode 100644 index 00000000..bcf99045 --- /dev/null +++ b/src-tauri/src/start_times.rs @@ -0,0 +1,94 @@ +use std::io::Write; +use std::sync::OnceLock; +use std::time::Duration; + +pub static SERVICE_STARTED: OnceLock = OnceLock::new(); +pub static SERVICE_READY: OnceLock = OnceLock::new(); +pub static EDITOR_READY: OnceLock = OnceLock::new(); +pub static WINDOW_SHOWN: OnceLock = OnceLock::new(); + +pub fn mark(moment: &OnceLock) { + let _ = moment.set(crate::reveal::since_launch()); +} + +pub fn report() { + let text = line(SERVICE_STARTED.get().copied(), SERVICE_READY.get().copied(), EDITOR_READY.get().copied(), WINDOW_SHOWN.get().copied()); + let _ = writeln!(std::io::stderr(), "{text}"); +} + +/// The shell's start-up summary. A service that answered without being started is one the shell found already running. +pub fn line(started: Option, ready: Option, editor: Option, shown: Option) -> String { + let moment = |name: &str, at: Option| match at { + Some(at) => format!("{name} {} ms", at.as_millis()), + None => format!("{name} not reached"), + }; + let first = match (started, ready) { + (None, Some(_)) => "service already running".to_string(), + _ => moment("service started", started), + }; + format!("[formweb] start-up: {first}, {}, {}, {}", moment("service ready", ready), moment("editor ready", editor), moment("window shown", shown)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ms(value: u64) -> Option { + Some(Duration::from_millis(value)) + } + + #[test] + fn the_start_up_line_names_the_four_moments_in_milliseconds_in_order() { + assert_eq!( + line(ms(140), ms(1980), ms(2510), ms(2735)), + "[formweb] start-up: service started 140 ms, service ready 1980 ms, editor ready 2510 ms, window shown 2735 ms" + ); + } + + #[test] + fn a_service_found_already_running_is_said_to_be_already_running() { + assert_eq!( + line(None, ms(40), ms(610), ms(830)), + "[formweb] start-up: service already running, service ready 40 ms, editor ready 610 ms, window shown 830 ms" + ); + } + + #[test] + fn an_editor_that_never_reported_ready_is_named_as_not_reached_when_the_fallback_shows_the_window() { + assert_eq!( + line(ms(118), ms(2201), None, ms(22150)), + "[formweb] start-up: service started 118 ms, service ready 2201 ms, editor ready not reached, window shown 22150 ms" + ); + } + + #[test] + fn every_moment_that_was_never_reached_is_named_as_not_reached() { + assert_eq!( + line(None, None, None, None), + "[formweb] start-up: service started not reached, service ready not reached, editor ready not reached, window shown not reached" + ); + assert_eq!( + line(ms(90), None, None, None), + "[formweb] start-up: service started 90 ms, service ready not reached, editor ready not reached, window shown not reached" + ); + } + + #[test] + fn a_part_of_a_millisecond_is_cut_off_and_never_rounded_up() { + assert_eq!( + line(Some(Duration::from_micros(99_999)), ms(0), ms(1), ms(2)), + "[formweb] start-up: service started 99 ms, service ready 0 ms, editor ready 1 ms, window shown 2 ms" + ); + } + + #[test] + fn a_moment_already_recorded_keeps_its_first_time_when_it_is_marked_again() { + let moment = OnceLock::new(); + moment.set(Duration::from_secs(86_400)).unwrap(); + mark(&moment); + assert_eq!(moment.get(), Some(&Duration::from_secs(86_400))); + let fresh = OnceLock::new(); + mark(&fresh); + assert!(fresh.get().is_some()); + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 58365223..1dae9d54 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "FormWeb", - "version": "0.31.2", + "version": "0.33.0", "identifier": "ai.nodemode.formweb", "build": { "frontendDist": "../frontend/dist"