diff --git a/scripts/qa_001.py b/scripts/qa_001.py
index b1507b2..3b91100 100644
--- a/scripts/qa_001.py
+++ b/scripts/qa_001.py
@@ -57,7 +57,7 @@ def main():
work = Path(temp)
site = work / "site"
shutil.copytree(
- ROOT / "examples/studio-site", site, ignore=shutil.ignore_patterns(".engine")
+ ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine")
)
env = {
"SITE_ROOT": str(site),
@@ -69,7 +69,7 @@ def main():
"SITE_COOKIE_SECURE": "0",
}
with patch.dict(os.environ, env), serve(create_app()) as origin, sync_playwright() as pw:
- browser = pw.chromium.launch(headless=True, args=["--no-sandbox"])
+ browser = pw.chromium.launch(channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"])
page = browser.new_page(viewport={"width": 1440, "height": 960})
page.on("pageerror", lambda exc: results["console_errors"].append(str(exc)))
page.goto(origin + "/admin/login")
@@ -82,7 +82,7 @@ def main():
("/admin/", "overview"),
("/admin/pages", "pages"),
("/admin/pages/index", "page"),
- ("/admin/pages/index/blocks/b_hero", "block"),
+ ("/admin/pages/index/blocks/hero_home", "block"),
("/admin/content", "collections"),
("/admin/content/services", "entries"),
("/admin/content/services/bots", "entry"),
@@ -140,24 +140,24 @@ def main():
results["widths"].append([mode + "-dark", width])
page.screenshot(path=str(args.out / "expert-dark-mobile.png"))
page.goto(origin + "/admin/publish")
- invoker = page.get_by_role(
- "button", name="Опубликовать текущий черновик сайта", exact=True
- )
+ page.locator('[data-pub-action=candidate]').first.click()
+ page.locator('[data-publication-root][aria-busy=false]').wait_for()
+ invoker = page.locator('[data-pub-action=publish]')
invoker.click()
- page.locator("#confirm-dialog").wait_for(state="visible")
+ page.locator("#publication-modal-root dialog[open]").wait_for(state="visible")
for _ in range(4):
page.keyboard.press("Tab")
- assert page.locator("#confirm-dialog").evaluate(
+ assert page.locator("#publication-modal-root dialog").evaluate(
"(e)=>e.contains(document.activeElement)"
)
page.keyboard.press("Escape")
- assert not page.locator("#confirm-dialog").is_visible()
+ assert not page.locator("#publication-modal-root dialog").is_visible()
assert invoker.evaluate("(e)=>e===document.activeElement")
assert not results["console_errors"], results["console_errors"]
browser.close()
# Reference is rendered from its own assets, independent of the runtime package.
with sync_playwright() as pw:
- browser = pw.chromium.launch(headless=True, args=["--no-sandbox"])
+ browser = pw.chromium.launch(channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"])
page = browser.new_page(viewport={"width": 1440, "height": 960})
page.goto((ROOT / "design/antirion-rework.html").as_uri())
page.screenshot(path=str(args.out / "reference-antirion.png"), full_page=True)
diff --git a/scripts/qa_content_001.py b/scripts/qa_content_001.py
new file mode 100644
index 0000000..d0f25f6
--- /dev/null
+++ b/scripts/qa_content_001.py
@@ -0,0 +1,468 @@
+"""Original Content design versus real FastAPI: geometry, flows and both preview origins."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import shutil
+import tempfile
+from contextlib import ExitStack
+from pathlib import Path
+from unittest.mock import patch
+
+from playwright.sync_api import expect, sync_playwright
+from qa_001 import PASSWORD, ROOT, serve
+from qa_editor_updates import idle, reserve
+from starlette.applications import Starlette
+from starlette.routing import Mount
+from starlette.staticfiles import StaticFiles
+
+from site_engine.build.pipeline import build_site
+from site_engine.services.auth import hash_password
+from site_engine.web.app import create_app
+from site_engine.web.preview_app import create_preview_app
+
+OUT = Path(os.environ.get("QA_CONTENT_OUT", "/tmp/site-engine-content-001"))
+
+
+def metrics(page, selectors):
+ return page.evaluate(
+ """selectors=>Object.fromEntries(selectors.map(s=>{
+ const e=document.querySelector(s),c=getComputedStyle(e),r=e.getBoundingClientRect();
+ return [s,{width:r.width,height:r.height,font:c.fontSize,padding:c.padding,
+ color:c.color,background:c.backgroundColor,columns:c.gridTemplateColumns}];
+ }))""",
+ selectors,
+ )
+
+
+def main():
+ OUT.mkdir(parents=True, exist_ok=True)
+ report = {
+ "runs": [],
+ "comparisons": [],
+ "page_errors": [],
+ "native_dialogs": [],
+ "console_errors": [],
+ "expected_errors": [],
+ }
+ with sync_playwright() as pw:
+ browser = pw.chromium.launch(
+ channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"]
+ )
+ for interactive in (False, True):
+ run = {"interactive": interactive, "checks": []}
+ report["runs"].append(run)
+ with (
+ tempfile.TemporaryDirectory(prefix="content-design-qa-") as tmp,
+ ExitStack() as stack,
+ ):
+ work, site = Path(tmp), Path(tmp) / "site"
+ shutil.copytree(
+ ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine")
+ )
+ original_file = (site / "content/services/bots.md").read_bytes()
+ build_site(site, work / "dist")
+ admin_socket, preview_socket = reserve(), reserve()
+ admin = "http://127.0.0.1:" + str(admin_socket.getsockname()[1])
+ preview = "http://127.0.0.1:" + str(preview_socket.getsockname()[1])
+ stack.enter_context(
+ patch.dict(
+ os.environ,
+ {
+ "SITE_ROOT": str(site),
+ "SITE_DIST": str(work / "dist"),
+ "SITE_STATE_DIR": str(work / "state"),
+ "SITE_ADMIN_LOGIN": "admin",
+ "SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10),
+ "SITE_SECRET_KEY": "content-browser-secret-" * 4,
+ "SITE_COOKIE_SECURE": "0",
+ "SITE_ADMIN_ORIGIN": admin if interactive else "",
+ "SITE_PREVIEW_ORIGIN": preview if interactive else "",
+ },
+ )
+ )
+ app, gate = create_app(), {"delay": 0}
+
+ @app.middleware("http")
+ async def delay(request, call_next, gate=gate):
+ if (
+ request.url.path.endswith("/update")
+ and request.url.path.startswith("/admin/editor/")
+ and gate["delay"]
+ ):
+ delay, gate["delay"] = gate["delay"], 0
+ await asyncio.sleep(delay)
+ return await call_next(request)
+
+ stack.enter_context(serve(app, admin_socket))
+ if interactive:
+ stack.enter_context(serve(create_preview_app(), preview_socket))
+ else:
+ preview_socket.close()
+ design_origin = stack.enter_context(
+ serve(
+ Starlette(
+ routes=[Mount("/", StaticFiles(directory=ROOT / "design", html=True))]
+ )
+ )
+ )
+ context = browser.new_context(
+ viewport={"width": 1440, "height": 1050}, reduced_motion="reduce"
+ )
+ stack.callback(context.close)
+ page, ref = context.new_page(), context.new_page()
+ page.set_default_timeout(10000)
+ page.on("pageerror", lambda e: report["page_errors"].append(str(e)))
+
+ def console(message):
+ if message.type != "error":
+ return
+ expected = (
+ any(str(code) in message.text for code in (401, 403, 409, 422, 500))
+ or "net::ERR_FAILED" in message.text
+ )
+ report["expected_errors" if expected else "console_errors"].append(
+ {"message": message.text, "url": message.location.get("url")}
+ )
+
+ page.on("console", console)
+ page.on(
+ "dialog", lambda d: (report["native_dialogs"].append(d.message), d.dismiss())
+ )
+ posts = []
+ page.on(
+ "request",
+ lambda r, posts=posts: posts.append(r.url) if r.method == "POST" else None,
+ )
+ page.goto(admin + "/admin/login")
+ page.locator("[name=login]").fill("admin")
+ page.locator("[name=password]").fill(PASSWORD)
+ page.get_by_role("button", name="Войти", exact=True).click()
+ page.goto(admin + "/admin/content/services/bots")
+ idle(page)
+ ref.goto(design_origin + "/content-antirion.html")
+ if not interactive:
+ selectors = [
+ ".entry-workspace",
+ ".collection-pane .pane-title",
+ ".entry-pane .pane-title",
+ ".entry-tabs button",
+ ".field-label",
+ ".preview-pane .pane-title",
+ ".workspace-footer",
+ ]
+ for skin in ("light", "dark"):
+ page.evaluate("(skin)=>{document.body.dataset.skin=skin}", skin)
+ # Approved dark Antirion tokens; the source has no Antirion dark palette.
+ for width in (1440, 1280, 1024, 768, 390, 360):
+ page.set_viewport_size({"width": width, "height": 1050})
+ ref.set_viewport_size({"width": width, "height": 1050})
+ actual, original = metrics(page, selectors), metrics(ref, selectors)
+ assert not page.evaluate(
+ "document.documentElement.scrollWidth>innerWidth+1"
+ ), (skin, width)
+ for selector in selectors[1:]:
+ assert actual[selector]["font"] == original[selector]["font"], (
+ selector,
+ width,
+ )
+ assert (
+ actual[selector]["padding"] == original[selector]["padding"]
+ ), (selector, width)
+ if width >= 1280:
+ a, b = (
+ actual[".entry-workspace"]["columns"].split(),
+ original[".entry-workspace"]["columns"].split(),
+ )
+ for i in (0, 1, 3):
+ assert a[i] == b[i], (width, a, b)
+ if skin == "light":
+ for selector in selectors[1:]:
+ assert (
+ actual[selector]["background"]
+ == original[selector]["background"]
+ ), (selector, width)
+ report["comparisons"].append(
+ {
+ "skin": skin,
+ "width": width,
+ "runtime": actual,
+ "reference": original,
+ }
+ )
+ page.screenshot(
+ path=str(OUT / f"content-{skin}-{width}.png"), full_page=True
+ )
+ if skin == "light":
+ ref.screenshot(
+ path=str(OUT / f"reference-{width}.png"), full_page=True
+ )
+ page.evaluate("document.body.dataset.skin='light'")
+ page.set_viewport_size({"width": 1440, "height": 1050})
+ print("PASS", interactive, len(run["checks"]) + 1, flush=True)
+ run["checks"].append("original_geometry_fonts_padding_palette_and_responsive")
+
+ # Local filters/tabs send no requests, retain keyboard focus.
+ before = len(posts)
+ page.locator("#entry-query").fill("nothing-matches")
+ expect(page.locator("[data-content-list-empty]")).to_be_visible()
+ assert page.locator("#entry-query").evaluate("e=>e===document.activeElement")
+ page.locator("#entry-query").fill("")
+ page.locator("[data-content-filter=draft]").click()
+ expect(page.locator("[data-entry=automation]")).to_be_visible()
+ expect(page.locator("[data-entry=bots]")).to_be_hidden()
+ page.locator("[data-content-filter=all]").click()
+ for tab in ("relations", "usage", "schema", "fields"):
+ page.locator("[data-content-tab=" + tab + "]").click()
+ expect(page.locator("[data-content-panel=" + tab + "]")).to_be_visible()
+ assert len(posts) == before
+ print("PASS", interactive, len(run["checks"]) + 1, flush=True)
+ run["checks"].append("local_filter_tabs_and_real_metadata")
+
+ field = page.locator('[name="p.title"]')
+ field.evaluate("e=>e.__qaInput=true")
+ page.locator("#preview-result iframe").evaluate("e=>e.__qaFrame=true")
+ before = len(posts)
+ field.fill("One background content update")
+ idle(page)
+ expect(page.frame_locator("#preview-result iframe").locator("strong")).to_have_text(
+ "One background content update"
+ )
+ assert posts[before:] == [admin + "/admin/editor/content/services/bots/update"], (
+ posts[before:]
+ )
+ assert field.evaluate("e=>e.__qaInput===true&&document.activeElement===e")
+ assert page.locator("#preview-result iframe").evaluate("e=>e.__qaFrame===true")
+ assert (site / "content/services/bots.md").read_bytes() == original_file
+ print("PASS", interactive, len(run["checks"]) + 1, flush=True)
+ run["checks"].append("one_post_keeps_field_frame_and_no_autosave")
+
+ gate["delay"] = 1
+ field.fill("Delayed candidate")
+ page.wait_for_function(
+ "()=>document.getElementById('document-editor').dataset.updating==='true'"
+ )
+ field.fill("Latest candidate during pending POST")
+ page.locator("[data-content-tab=relations]").click()
+ expect(page.locator("[data-content-panel=relations]")).to_be_visible()
+ idle(page)
+ page.locator("[data-content-tab=fields]").click()
+ expect(field).to_have_value("Latest candidate during pending POST")
+ print("PASS", interactive, len(run["checks"]) + 1, flush=True)
+ run["checks"].append("typing_and_tabs_do_not_wait_for_delayed_post")
+
+ # Asset/ref dialogs have real options and restore focus with Escape.
+ picker = page.locator('[data-content-picker="p.hero_asset"]')
+ picker.click()
+ expect(page.locator("dialog[open] .asset-option").first).to_be_visible()
+ page.keyboard.press("Escape")
+ assert picker.evaluate("e=>e===document.activeElement")
+ page.locator('[data-content-picker="p.related_scenarios"]').click()
+ expect(page.locator("dialog[open] .ref-choice")).to_have_count(3)
+ page.locator("dialog[open] input[type=checkbox]").first.uncheck()
+ page.locator("dialog[open]").get_by_role(
+ "button", name="Применить", exact=True
+ ).click()
+ idle(page)
+ page.locator('[data-content-bool="p.featured"]').uncheck()
+ idle(page)
+ assert page.evaluate("window.siteDocument.state.model.meta.featured") is False
+ print("PASS", interactive, len(run["checks"]) + 1, flush=True)
+ run["checks"].append("real_asset_ref_picker_and_boolean")
+
+ # Explicit add and remove list rows preserve names and field focus.
+ page.locator('[data-content-add="p.benefits"]').click()
+ row = page.locator('[data-list-row="p.benefits.2"] textarea')
+ row.fill("New list item")
+ idle(page)
+ expect(page.locator('[data-list-row="p.benefits.3"]')).to_be_hidden()
+ page.locator('[data-content-remove="p.benefits.0"]').click()
+ idle(page)
+ assert page.evaluate("window.siteDocument.state.model.meta.benefits.length") == 2
+ expect(page.locator('[name="p.benefits.1"]')).to_have_value("New list item")
+ print("PASS", interactive, len(run["checks"]) + 1, flush=True)
+ run["checks"].append("explicit_list_add_delete_reindexes_controls")
+
+ page.locator("[data-content-preview=page]").click()
+ idle(page)
+ expect(page.frame_locator("#preview-result iframe").locator("h1")).to_have_text(
+ "Latest candidate during pending POST"
+ )
+ page.locator("[data-content-version=live]").click()
+ idle(page)
+ expect(page.frame_locator("#preview-result iframe").locator("h1")).to_have_text(
+ "Telegram-боты"
+ )
+ page.locator("[data-content-preview=card]").click()
+ idle(page)
+ expect(page.locator("#preview-result .preview-empty")).to_contain_text("карточка")
+ page.locator("[data-content-version=workspace]").click()
+ idle(page)
+ print("PASS", interactive, len(run["checks"]) + 1, flush=True)
+ run["checks"].append("real_workspace_card_page_and_immutable_live_page")
+
+ page.locator("[data-content-validate]").first.click()
+ expect(page.locator("dialog[open] .review-summary")).to_be_visible()
+ page.screenshot(path=str(OUT / f"review-{interactive}.png"))
+ page.keyboard.press("Escape")
+ page.locator("[data-editor-mode=expert]").click()
+ expect(page.locator("#expert-pane")).to_be_visible()
+ page.locator("[data-content-diff]").click()
+ expect(page.locator("dialog[open] .diff-row.changed").first).to_be_visible()
+ page.keyboard.press("Escape")
+ source = page.locator("#document-source").input_value()
+ page.locator("#document-source").fill("---\ntitle: [\n---\nKeep this source")
+ page.wait_for_timeout(450)
+ page.wait_for_function("()=>!window.siteDocument.state.busy")
+ expect(page.locator("#document-source")).to_have_value(
+ "---\ntitle: [\n---\nKeep this source"
+ )
+ expect(page.locator("[data-content-source-errors]")).not_to_be_empty()
+ page.locator("#document-source").fill(source)
+ idle(page)
+ page.locator("[data-content-find]").click()
+ page.locator("[data-source-query]").fill("Latest candidate")
+ page.locator("dialog[open]").get_by_role("button", name="Найти", exact=True).click()
+ assert page.locator("#document-source").evaluate(
+ "e=>e.selectionEnd>e.selectionStart"
+ )
+ page.locator("[data-editor-mode=constructor]").click()
+ print("PASS", interactive, len(run["checks"]) + 1, flush=True)
+ run["checks"].append("review_expert_diff_find_invalid_yaml_recovery")
+
+ # Navigation confirmation uses the original dialog, Escape retains edits.
+ page.locator("[data-entry=ai]").click()
+ expect(page.locator("dialog[open]")).to_contain_text("несохранённые")
+ page.keyboard.press("Escape")
+ assert page.url.endswith("/services/bots")
+ page.locator("[data-save-document]").click()
+ page.wait_for_function(
+ "()=>!window.siteDocument.state.dirty&&!window.siteDocument.state.busy"
+ )
+ assert b"Latest candidate" in (site / "content/services/bots.md").read_bytes()
+ assert (work / "dist/current").exists()
+ print("PASS", interactive, len(run["checks"]) + 1, flush=True)
+ run["checks"].append("leave_confirmation_explicit_save_no_publish")
+
+ # Real CAS conflict; local unsaved text survives.
+ field.fill("My conflict candidate")
+ idle(page)
+ server_source = (
+ (site / "content/services/bots.md")
+ .read_text()
+ .replace("Latest candidate during pending POST", "Server concurrent title")
+ )
+ (site / "content/services/bots.md").write_text(server_source)
+ page.locator("[data-save-document]").click()
+ expect(page.locator("dialog[open] .conflict-grid")).to_be_visible()
+ expect(field).to_have_value("My conflict candidate")
+ page.screenshot(path=str(OUT / f"conflict-{interactive}.png"))
+ page.keyboard.press("Escape")
+ print("PASS", interactive, len(run["checks"]) + 1, flush=True)
+ run["checks"].append("real_409_preserves_unsaved_source")
+
+ # Reload is intentional and has no system dialog.
+ page.reload()
+ idle(page)
+ field = page.locator('[name="p.title"]')
+ field.fill("Copied current editor")
+ idle(page)
+ page.locator("[data-content-duplicate]").click()
+ page.wait_for_url("**/bots-copy")
+ idle(page)
+ expect(page.locator('[name="p.title"]')).to_have_value(
+ "Copied current editor (копия)"
+ )
+ assert "status: draft" in (site / "content/services/bots-copy.md").read_text()
+ page.locator("[data-content-delete]").click()
+ expect(page.locator("dialog[open]")).to_contain_text("Удалить запись?")
+ page.keyboard.press("Escape")
+ assert (site / "content/services/bots-copy.md").exists()
+ page.locator("[data-content-delete]").click()
+ page.locator("dialog[open]").get_by_role(
+ "button", name="Удалить из workspace", exact=True
+ ).click()
+ page.wait_for_url("**/services/ai")
+ assert not (site / "content/services/bots-copy.md").exists()
+ idle(page)
+ page.locator("[data-content-delete]").click()
+ expect(page.locator("#request-error")).to_contain_text("архивируйте")
+ page.locator("[data-close-request-error]").click()
+ print("PASS", interactive, len(run["checks"]) + 1, flush=True)
+ run["checks"].append(
+ "duplicate_current_candidate_delete_confirmation_and_published_guard"
+ )
+
+ # Empty/off collections and a real new draft in an enabled collection.
+ page.goto(admin + "/admin/content/posts")
+ expect(page.locator("[data-content-list-empty]")).to_contain_text(
+ "Записей пока нет"
+ )
+ expect(
+ page.get_by_role("button", name="Создать запись", exact=True)
+ ).to_be_disabled()
+ page.goto(admin + "/admin/content/services")
+ idle(page)
+ page.get_by_role("button", name="Создать запись", exact=True).click()
+ page.wait_for_url("**/services/entry-*")
+ idle(page)
+ assert page.locator("#entry-slug").input_value().startswith("entry-")
+ print("PASS", interactive, len(run["checks"]) + 1, flush=True)
+ run["checks"].append("empty_disabled_collection_and_create_real_draft")
+
+ # HTTP and network errors keep the active fields and show a message.
+ field = page.locator('[name="p.title"]')
+ page.route(
+ "**/admin/editor/**/update",
+ lambda route: route.fulfill(
+ status=500,
+ content_type="application/json",
+ body=json.dumps(
+ {
+ "error": {
+ "code": "qa_failure",
+ "message": "Проверка HTTP 500",
+ "request_id": "content-qa",
+ }
+ }
+ ),
+ ),
+ )
+ field.fill("Keep text after error")
+ expect(page.locator("#request-error")).to_contain_text("Проверка HTTP 500")
+ expect(field).to_have_value("Keep text after error")
+ page.unroute("**/admin/editor/**/update")
+ field.fill("Recovery after 500")
+ idle(page)
+ page.route("**/admin/editor/**/update", lambda route: route.abort())
+ field.fill("Keep text offline")
+ expect(page.locator("#request-error")).to_contain_text("Нет связи")
+ expect(field).to_have_value("Keep text offline")
+ page.unroute("**/admin/editor/**/update")
+ field.fill("Recovered connection")
+ idle(page)
+ print("PASS", interactive, len(run["checks"]) + 1, flush=True)
+ run["checks"].append("500_and_network_errors_visible_and_recoverable")
+ ref.close()
+ assert not report["page_errors"], report["page_errors"]
+ assert not report["native_dialogs"], report["native_dialogs"]
+ assert not report["console_errors"], report["console_errors"]
+ browser.close()
+ (OUT / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2))
+ print(
+ json.dumps(
+ {
+ "comparisons": len(report["comparisons"]),
+ "runs": report["runs"],
+ "errors": report["page_errors"],
+ },
+ ensure_ascii=False,
+ indent=2,
+ )
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/qa_editor_updates.py b/scripts/qa_editor_updates.py
index 1306652..4f26511 100644
--- a/scripts/qa_editor_updates.py
+++ b/scripts/qa_editor_updates.py
@@ -317,6 +317,8 @@ def main():
page.goto(admin + '/admin/content/services/bots')
idle(page)
+ page.locator('[data-content-preview=page]').click()
+ idle(page)
entry = page.locator('[data-inspector] [name="p.title"]')
entry.fill('Entry background update')
idle(page)
diff --git a/scripts/qa_errors_001.py b/scripts/qa_errors_001.py
index 5233aed..d3b5011 100644
--- a/scripts/qa_errors_001.py
+++ b/scripts/qa_errors_001.py
@@ -36,7 +36,7 @@ def main():
work = Path(temp)
site, dist = work / "site", work / "dist"
shutil.copytree(
- ROOT / "examples/ai-studio", site, ignore=shutil.ignore_patterns(".engine")
+ ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine")
)
build_site(site, dist)
live = (dist / "current").resolve()
@@ -61,6 +61,7 @@ def main():
options = {"headless": True}
if kind.name == "chromium":
options["args"] = ["--no-sandbox", "--no-proxy-server"]
+ options["channel"] = "chromium"
if kind.name == "firefox":
options["firefox_user_prefs"] = {"network.proxy.type": 0}
if os.environ.get("QA_BROWSER_EXECUTABLE"):
@@ -84,16 +85,13 @@ def main():
page.wait_for_url(origin + "/admin/")
page.goto(origin + "/admin/publish")
with patch(
- "site_engine.web.api.routes.publish",
+ "site_engine.services.publication.build_site",
side_effect=PermissionError("QA publish denied"),
):
- page.get_by_role("button", name="Опубликовать текущий черновик сайта").click()
with page.expect_response(
- lambda r: r.url.endswith("/admin/publish") and r.request.method == "POST"
+ lambda r: r.url.endswith("/admin/publication/build") and r.request.method == "POST"
) as failed:
- page.locator("#confirm-dialog").get_by_role(
- "button", name="Продолжить"
- ).click()
+ page.locator('[data-pub-action=candidate]').first.click()
response = failed.value
assert response.status == 500
correlation = response.headers["x-request-id"]
@@ -146,16 +144,22 @@ def main():
page.unroute("**/admin/editor/pages/index/save")
checks.append("network_failure_is_visible_and_preserves_unsaved_source")
page.get_by_role("button", name="Сохранить документ", exact=True).click()
- expect(page.locator("#editor-result")).to_have_attribute("data-saved", "1")
+ page.wait_for_function(
+ "expected => window.siteDocument?.state?.saved === expected && !window.siteDocument.state.dirty",
+ arg=edited,
+ )
assert (site / "pages/index.md").read_text() == edited
assert (dist / "current").resolve() == live
checks.append("save_recovers_after_failure_without_publishing")
page.goto(origin + "/admin/publish")
- page.get_by_role("button", name="Опубликовать текущий черновик сайта").click()
+ page.locator('[data-pub-action=candidate]').first.click()
+ page.locator('[data-publication-root][aria-busy=false]').wait_for()
+ page.locator('[data-pub-action=publish]').click()
+ page.locator('#release-comment').fill('Error recovery QA release')
with page.expect_response(
- lambda r: r.url.endswith("/admin/publish") and r.request.method == "POST"
+ lambda r: r.url.endswith("/admin/publication/activate") and r.request.method == "POST"
) as published:
- page.locator("#confirm-dialog").get_by_role("button", name="Продолжить").click()
+ page.locator('[data-pub-action=confirm-publish]').click()
assert published.value.status == 200
assert (dist / "current").resolve() != live
expect(page.locator("#request-error")).to_be_hidden()
diff --git a/scripts/qa_publication_001.py b/scripts/qa_publication_001.py
new file mode 100644
index 0000000..ba0eccc
--- /dev/null
+++ b/scripts/qa_publication_001.py
@@ -0,0 +1,376 @@
+"""Real publication workflow and original design in Chromium; isolated temporary sites."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import shutil
+import tempfile
+from contextlib import ExitStack
+from pathlib import Path
+from unittest.mock import patch
+
+from playwright.sync_api import expect, sync_playwright
+from qa_001 import PASSWORD, ROOT, serve
+from qa_editor_updates import reserve
+from starlette.applications import Starlette
+from starlette.routing import Mount
+from starlette.staticfiles import StaticFiles
+
+from site_engine.build.pipeline import hash_tree
+from site_engine.services.auth import hash_password
+from site_engine.web.app import create_app
+from site_engine.web.preview_app import create_preview_app
+
+OUT = Path(os.environ.get("QA_PUBLICATION_OUT", "/tmp/site-engine-publication-001"))
+
+
+def metrics(page, selectors):
+ return page.evaluate(
+ """selectors=>Object.fromEntries(selectors.map(s=>{
+ const e=document.querySelector(s),r=e.getBoundingClientRect(),c=getComputedStyle(e);
+ return [s,{width:r.width,font:c.fontSize,padding:c.padding,background:c.backgroundColor,columns:c.gridTemplateColumns}];
+ }))""",
+ selectors,
+ )
+
+
+def main():
+ OUT.mkdir(parents=True, exist_ok=True)
+ report = {
+ "comparisons": [],
+ "runs": [],
+ "page_errors": [],
+ "console_errors": [],
+ "expected_errors": [],
+ "native_dialogs": [],
+ }
+ with sync_playwright() as pw:
+ browser = pw.chromium.launch(
+ channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"]
+ )
+ for interactive in (False, True):
+ with tempfile.TemporaryDirectory(prefix="publication-qa-") as tmp, ExitStack() as stack:
+ work = Path(tmp)
+ site = work / "site"
+ dist = work / "dist"
+ shutil.copytree(
+ ROOT / "examples/site-studio", site, ignore=shutil.ignore_patterns(".engine")
+ )
+ admin_socket, preview_socket = reserve(), reserve()
+ admin = f"http://127.0.0.1:{admin_socket.getsockname()[1]}"
+ preview = f"http://127.0.0.1:{preview_socket.getsockname()[1]}"
+ stack.enter_context(
+ patch.dict(
+ os.environ,
+ {
+ "SITE_ROOT": str(site),
+ "SITE_DIST": str(dist),
+ "SITE_STATE_DIR": str(work / "state"),
+ "SITE_ADMIN_LOGIN": "admin",
+ "SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10),
+ "SITE_SECRET_KEY": "publication-browser-secret-" * 3,
+ "SITE_COOKIE_SECURE": "0",
+ "SITE_ADMIN_ORIGIN": admin if interactive else "",
+ "SITE_PREVIEW_ORIGIN": preview if interactive else "",
+ },
+ )
+ )
+ app = create_app()
+ gate = {"delay": 0}
+
+ @app.middleware("http")
+ async def delay(request, call_next, gate=gate):
+ if request.url.path == "/admin/publication/build" and gate["delay"]:
+ value, gate["delay"] = gate["delay"], 0
+ await asyncio.sleep(value)
+ return await call_next(request)
+
+ stack.enter_context(serve(app, admin_socket))
+ if interactive:
+ stack.enter_context(serve(create_preview_app(), preview_socket))
+ else:
+ preview_socket.close()
+ reference = stack.enter_context(
+ serve(
+ Starlette(
+ routes=[Mount("/", StaticFiles(directory=ROOT / "design", html=True))]
+ )
+ )
+ )
+ context = browser.new_context(
+ viewport={"width": 1440, "height": 1050}, reduced_motion="reduce"
+ )
+ stack.callback(context.close)
+ page, ref = context.new_page(), context.new_page()
+ page.set_default_timeout(12000)
+ page.on("pageerror", lambda e: report["page_errors"].append(str(e)))
+
+ def console(message):
+ if message.type != "error":
+ return
+ expected = (
+ any(str(code) in message.text for code in (401, 403, 409, 422, 500))
+ or "net::ERR_FAILED" in message.text
+ )
+ report["expected_errors" if expected else "console_errors"].append(
+ {"message": message.text, "url": message.location.get("url")}
+ )
+
+ page.on("console", console)
+ page.on(
+ "dialog", lambda d: (report["native_dialogs"].append(d.message), d.dismiss())
+ )
+ posts = []
+ page.on(
+ "request",
+ lambda r, posts=posts: posts.append(r.url) if r.method == "POST" else None,
+ )
+ checks = []
+ report["runs"].append({"interactive": interactive, "checks": checks})
+
+ def done(name, checks=checks, interactive=interactive):
+ checks.append(name)
+ print("PASS", interactive, len(checks), name, flush=True)
+
+ def ready(page=page):
+ expect(page.locator("[data-publication-root]")).to_have_attribute(
+ "aria-busy", "false"
+ )
+
+ def tab(name, page=page):
+ page.locator(f'[data-pub-tab="{name}"]').click()
+
+ def action(name, page=page):
+ page.locator(f'[data-pub-action="{name}"]').first.click()
+
+ def build(page=page, action=action, ready=ready):
+ action("candidate")
+ ready()
+ expect(page.locator("[data-pub-action=publish]")).to_be_visible()
+
+ def publish(comment, page=page, action=action, ready=ready):
+ action("publish")
+ page.locator("#release-comment").fill(comment)
+ action("confirm-publish")
+ ready()
+ expect(page.locator("dialog[open]")).to_have_count(0)
+
+ page.goto(admin + "/admin/login")
+ page.locator("[name=login]").fill("admin")
+ page.locator("[name=password]").fill(PASSWORD)
+ page.get_by_role("button", name="Войти", exact=True).click()
+ page.wait_for_url(admin + "/admin/")
+ with page.expect_response(lambda r, admin=admin: r.url == admin + "/admin/publish") as opened:
+ page.locator('#sidebar a[href="/admin/publish"]').click()
+ assert opened.value.request.headers.get("hx-boosted") == "true"
+ ready()
+ expect(page.locator(".livebar")).to_contain_text("Публичного релиза пока нет")
+ assert not (dist / "current").exists()
+ done("real_empty_first_release")
+ ref.goto(reference + "/publication-antirion.html")
+ if not interactive:
+ selectors = [
+ ".heading h1",
+ ".livebar",
+ ".pipe",
+ ".panel-header",
+ ".table th",
+ ".table td",
+ ".button.primary",
+ ".tabs",
+ ]
+ for skin in ("light", "dark"):
+ page.evaluate("(skin)=>{document.body.dataset.skin=skin}", skin)
+ for width in (1440, 1280, 1024, 768, 390, 360):
+ page.set_viewport_size({"width": width, "height": 1050})
+ ref.set_viewport_size({"width": width, "height": 1050})
+ a, b = metrics(page, selectors), metrics(ref, selectors)
+ assert not page.evaluate(
+ "document.documentElement.scrollWidth>innerWidth+1"
+ ), (skin, width)
+ for s in selectors:
+ assert a[s]["font"] == b[s]["font"], (s, width, a[s], b[s])
+ assert a[s]["padding"] == b[s]["padding"], (s, width, a[s], b[s])
+ if skin == "light":
+ assert a[s]["background"] == b[s]["background"], (
+ s,
+ width,
+ a[s],
+ b[s],
+ )
+ report["comparisons"].append(
+ {"skin": skin, "width": width, "runtime": a, "reference": b}
+ )
+ page.screenshot(
+ path=str(OUT / f"publication-{skin}-{width}.png"), full_page=True
+ )
+ if skin == "light":
+ ref.screenshot(
+ path=str(OUT / f"reference-{width}.png"), full_page=True
+ )
+ page.set_viewport_size({"width": 1440, "height": 1050})
+ page.evaluate("document.body.dataset.skin='light'")
+ done("original_geometry_fonts_padding_palette_responsive_12_sets")
+ before = len(posts)
+ page.locator("#pub-search").fill("no-such-document")
+ expect(page.locator(".table tbody")).to_contain_text("Ничего не найдено")
+ expect(page.locator("#pub-search")).to_be_focused()
+ page.locator("#pub-search").fill("pages/index.md")
+ page.locator('[data-pub-select="pages/index.md"]').click()
+ expect(page.locator(".split>.stack").last).to_contain_text("pages/index.md")
+ tab("checks")
+ tab("history")
+ tab("changes")
+ assert len(posts) == before
+ done("local_filters_selection_tabs_no_post")
+ action("compare-doc")
+ expect(page.locator("dialog[open]")).to_contain_text("Workspace")
+ page.keyboard.press("Escape")
+ expect(page.locator("dialog[open]")).to_have_count(0)
+ action("doc-history")
+ expect(page.locator("dialog[open]")).to_contain_text("предыдущих версий пока нет")
+ action("close-modal")
+ done("real_compare_and_empty_document_history_designer_dialog")
+ action("validate")
+ ready()
+ expect(page.locator(".summary")).to_contain_text("Проверено")
+ assert not (dist / "current").exists()
+ done("real_validate_does_not_publish")
+ gate["delay"] = 1.5
+ action("candidate")
+ tab("activity")
+ expect(page.locator("[data-pub-tab=activity]")).to_have_attribute(
+ "aria-selected", "true"
+ )
+ ready()
+ tab("candidate")
+ expect(page.locator("[data-pub-action=publish]")).to_be_enabled()
+ candidate = json.loads((work / "state/publication/candidate.json").read_text())
+ assert not (dist / "current").exists()
+ original_output = hash_tree(dist / candidate["id"])
+ done("background_candidate_does_not_freeze_tabs_or_activate")
+ action("candidate-diff")
+ expect(page.locator("dialog[open]")).to_contain_text("pages/index.md")
+ action("close-modal")
+ action("preview")
+ ready()
+ frame = page.frame_locator(".release-preview")
+ expect(frame.locator("body")).to_contain_text("Автоматизируем")
+ assert not page.frames[-1].locator("script").count()
+ page.screenshot(
+ path=str(OUT / f"candidate-preview-{interactive}.png"), full_page=True
+ )
+ action("close-modal")
+ done("immutable_candidate_diff_and_real_passive_preview")
+ action("publish")
+ page.locator("#release-comment").fill("Не публиковать")
+ action("close-modal")
+ assert not (dist / "current").exists()
+ publish("Первый проверенный релиз")
+ first = (dist / "current").resolve().name
+ assert first == candidate["id"] and hash_tree(dist / first) == original_output
+ expect(page.locator(".livebar")).to_contain_text(first)
+ done("cancel_and_explicit_publish_exact_candidate")
+ path = site / "pages/index.md"
+ source = path.read_text()
+ path.write_text(source + "\nИзменение для второго релиза.\n")
+ tab("changes")
+ action("refresh-workspace")
+ ready()
+ build()
+ candidate = json.loads((work / "state/publication/candidate.json").read_text())
+ action("publish")
+ page.locator("#release-comment").fill("Устаревший кандидат")
+ path.write_text(path.read_text() + "\nНовая правка после просмотра.\n")
+ action("confirm-publish")
+ ready()
+ expect(page.locator("#request-error")).to_contain_text("Кандидат устарел")
+ assert (dist / "current").resolve().name == first
+ action("close-modal")
+ page.locator("[data-close-request-error]").click()
+ tab("candidate")
+ expect(page.locator("[data-pub-action=publish]")).to_be_disabled()
+ done("real_stale_candidate_409_visible_and_live_unchanged")
+ build()
+ publish("Второй релиз")
+ second = (dist / "current").resolve().name
+ assert second != first
+ source_hash = hash_tree(site)
+ page.locator(f'[data-pub-action=rollback][data-release="{first}"]').click()
+ page.screenshot(path=str(OUT / f"rollback-{interactive}.png"), full_page=True)
+ action("close-modal")
+ assert (dist / "current").resolve().name == second
+ page.locator(f'[data-pub-action=rollback][data-release="{first}"]').click()
+ action("rollback-confirm")
+ ready()
+ assert (dist / "current").resolve().name == first and hash_tree(site) == source_hash
+ done("rollback_cancel_confirm_preserves_workspace")
+ page.goto(admin + "/admin/publish")
+ ready()
+ expect(page.locator(".livebar")).to_contain_text(first)
+ tab("activity")
+ expect(page.locator(".timeline")).to_contain_text("release_rollback")
+ tab("history")
+ page.locator(f'[data-pub-action=release-details][data-release="{second}"]').click()
+ expect(page.locator("dialog[open]")).to_contain_text("Второй релиз")
+ action("close-modal")
+ done("reload_real_history_comments_and_audit")
+ with patch(
+ "site_engine.core.render.Renderer.render",
+ side_effect=RuntimeError("QA render failure"),
+ ):
+ action("candidate")
+ ready()
+ expect(page.locator("#request-error")).to_contain_text("Внутренняя ошибка сервера")
+ expect(page.locator("#publication-panel")).to_contain_text("Ошибка сборки")
+ action("build-log")
+ expect(page.locator("dialog[open]")).to_contain_text("ID запроса")
+ action("close-modal")
+ assert (dist / "current").resolve().name == first
+ page.locator("[data-close-request-error]").click()
+ page.route("**/admin/publication/build", lambda route: route.abort())
+ action("candidate")
+ ready()
+ expect(page.locator("#request-error")).to_contain_text("Нет связи с сервером")
+ page.unroute("**/admin/publication/build")
+ page.locator("[data-close-request-error]").click()
+ build()
+ done("500_network_visible_logged_and_recoverable")
+ page.goto(admin + "/admin/pages/index")
+ expect(page.locator(".builder")).to_be_visible()
+ page.goto(admin + "/admin/content/services/bots")
+ expect(page.locator(".entry-workspace")).to_be_visible()
+ page.goto(admin + "/admin/theme")
+ expect(page.locator(".theme-content")).to_be_visible()
+ page.goto(admin + "/admin/publish")
+ ready()
+ tab("checks")
+ page.locator("[data-pub-tab=checks]").focus()
+ page.keyboard.press("ArrowRight")
+ expect(page.locator("[data-pub-tab=candidate]")).to_be_focused()
+ page.locator("[data-action=profile]").click()
+ page.locator("#profile-dialog button[type=submit]").click()
+ expect(page.locator("input[name=login]")).to_be_visible()
+ done("accepted_screens_keyboard_and_logout")
+ browser.close()
+ (OUT / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2))
+ assert not report["page_errors"], report["page_errors"]
+ assert not report["console_errors"], report["console_errors"]
+ assert not report["native_dialogs"], report["native_dialogs"]
+ print(
+ json.dumps(
+ {
+ "comparisons": len(report["comparisons"]),
+ "runs": report["runs"],
+ "errors": report["page_errors"],
+ },
+ ensure_ascii=False,
+ indent=2,
+ )
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/qa_publication_navigation_001.py b/scripts/qa_publication_navigation_001.py
new file mode 100644
index 0000000..2f51e07
--- /dev/null
+++ b/scripts/qa_publication_navigation_001.py
@@ -0,0 +1,132 @@
+"""Publication boot through real htmx links, history and repeated navigation."""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import tempfile
+from pathlib import Path
+from unittest.mock import patch
+
+from playwright.sync_api import expect, sync_playwright
+from qa_001 import PASSWORD, ROOT, serve
+
+from site_engine.services.auth import hash_password
+from site_engine.web.app import create_app
+
+
+def main():
+ out = Path(
+ os.environ.get("QA_PUBLICATION_NAV_OUT", "/tmp/site-engine-publication-navigation-001")
+ )
+ out.mkdir(parents=True, exist_ok=True)
+ report = {"checks": [], "page_errors": [], "console_errors": [], "native_dialogs": []}
+ with tempfile.TemporaryDirectory(prefix="publication-navigation-") as tmp:
+ work = Path(tmp)
+ shutil.copytree(
+ ROOT / "examples/site-studio", work / "site", ignore=shutil.ignore_patterns(".engine")
+ )
+ env = {
+ "SITE_ROOT": str(work / "site"),
+ "SITE_DIST": str(work / "dist"),
+ "SITE_STATE_DIR": str(work / "state"),
+ "SITE_ADMIN_LOGIN": "admin",
+ "SITE_ADMIN_PASSWORD_HASH": hash_password(PASSWORD, n=2**10),
+ "SITE_SECRET_KEY": "publication-navigation-test-" * 3,
+ "SITE_COOKIE_SECURE": "0",
+ "SITE_ADMIN_ORIGIN": "",
+ "SITE_PREVIEW_ORIGIN": "",
+ }
+ with patch.dict(os.environ, env), serve(create_app()) as origin, sync_playwright() as pw:
+ browser = pw.chromium.launch(
+ channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"]
+ )
+ context = browser.new_context(viewport={"width": 1440, "height": 960})
+ page = context.new_page()
+ page.set_default_timeout(6000)
+ page.on(
+ "pageerror",
+ lambda exc: report["page_errors"].append({"message": str(exc), "stack": exc.stack}),
+ )
+ page.on(
+ "console",
+ lambda msg: (
+ report["console_errors"].append(msg.text) if msg.type == "error" else None
+ ),
+ )
+ page.on(
+ "dialog",
+ lambda dialog: (report["native_dialogs"].append(dialog.message), dialog.dismiss()),
+ )
+
+ def ready():
+ expect(page.locator("[data-publication-root]")).to_have_attribute(
+ "aria-busy", "false"
+ )
+ expect(page.locator(".livebar")).to_contain_text("Публичного релиза пока нет")
+ assert page.evaluate(
+ "htmx.config.allowScriptTags === false && htmx.config.allowEval === false"
+ )
+
+ def nav(path):
+ if page.viewport_size["width"] < 760:
+ page.get_by_role("button", name="Открыть меню", exact=True).click()
+ with page.expect_response(
+ lambda r: r.request.method == "GET" and r.url == origin + path
+ ) as response:
+ page.locator(f'#sidebar a[href="{path}"]').click()
+ assert response.value.request.headers.get("hx-boosted") == "true"
+ page.wait_for_url(origin + path)
+ assert page.evaluate("window.__publicationNavigationDocument") == "preserved"
+
+ try:
+ page.goto(origin + "/admin/login")
+ page.locator("[name=login]").fill("admin")
+ page.locator("[name=password]").fill(PASSWORD)
+ page.get_by_role("button", name="Войти", exact=True).click()
+ page.wait_for_url(origin + "/admin/")
+ for width in (1440, 390):
+ page.set_viewport_size({"width": width, "height": 960})
+ for source in (
+ "/admin/pages",
+ "/admin/content/services/bots",
+ "/admin/pages/index",
+ ):
+ page.goto(origin + source)
+ page.evaluate("window.__publicationNavigationDocument='preserved'")
+ nav("/admin/publish")
+ ready()
+ report["checks"].append(f"htmx_from_{source}_{width}")
+ nav("/admin/pages")
+ nav("/admin/publish")
+ ready()
+ page.go_back()
+ page.wait_for_url(origin + "/admin/pages")
+ page.go_forward()
+ page.wait_for_url(origin + "/admin/publish")
+ ready()
+ assert (
+ page.evaluate("window.__publicationNavigationDocument") == "preserved"
+ )
+ report["checks"].append(f"repeat_and_back_forward_{source}_{width}")
+ page.reload()
+ ready()
+ report["checks"].append(f"direct_reload_{width}")
+ page.screenshot(path=str(out / f"publication-navigation-{width}.png"))
+ assert not report["page_errors"], report["page_errors"]
+ assert not report["console_errors"], report["console_errors"]
+ assert not report["native_dialogs"], report["native_dialogs"]
+ assert not (work / "dist/current").exists()
+ finally:
+ report["last_url"] = page.url
+ report["boot_nodes"] = page.locator("[data-publication-boot]").count()
+ (out / "report.json").write_text(
+ json.dumps(report, ensure_ascii=False, indent=2) + "\n"
+ )
+ print(json.dumps(report, ensure_ascii=False), flush=True)
+ browser.close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/qa_shell_001.py b/scripts/qa_shell_001.py
index d452780..5bec94a 100644
--- a/scripts/qa_shell_001.py
+++ b/scripts/qa_shell_001.py
@@ -37,7 +37,7 @@ def main():
report = {"geometry": [], "flows": [], "errors": []}
with tempfile.TemporaryDirectory(prefix="cms-shell-") as temp:
work = Path(temp)
- shutil.copytree(ROOT / "examples/studio-site", work / "site", ignore=shutil.ignore_patterns(".engine"))
+ shutil.copytree(ROOT / "examples/site-studio", work / "site", ignore=shutil.ignore_patterns(".engine"))
env = {
"SITE_ROOT": str(work / "site"), "SITE_DIST": str(work / "dist"),
"SITE_STATE_DIR": str(work / "state"), "SITE_ADMIN_LOGIN": "admin",
@@ -46,7 +46,7 @@ def main():
"SITE_ADMIN_ORIGIN": "", "SITE_PREVIEW_ORIGIN": "", "SITE_PUBLIC_HOST": "",
}
with patch.dict(os.environ, env), serve(create_app()) as origin, sync_playwright() as pw:
- browser = pw.chromium.launch(headless=True, args=["--no-sandbox"])
+ browser = pw.chromium.launch(channel="chromium", headless=True, args=["--no-sandbox", "--no-proxy-server"])
page = browser.new_page(viewport={"width": 1440, "height": 960}, reduced_motion="reduce")
page.on("pageerror", lambda error: report["errors"].append(str(error)))
page.on("console", lambda message: report["errors"].append(message.text) if message.type == "error" else None)
@@ -121,7 +121,7 @@ def main():
assert page.locator("[data-command-empty]").is_visible()
page.locator("#cmd-input").fill("Контент")
page.locator("[data-command-result]:visible").click()
- page.wait_for_url(origin + "/admin/content")
+ page.wait_for_url(origin + "/admin/content/**")
assert page.locator(".nav-item.active").inner_text() == "Контент"
report["flows"].append("Ctrl+K, real pages/sections, empty search, htmx navigation")
page.locator('[data-action="profile"]').click()
@@ -146,8 +146,11 @@ def main():
assert page.locator(".sidebar.open").count() == 0
page.set_viewport_size({"width": 1440, "height": 960})
page.goto(origin + "/admin/publish")
- page.get_by_role("button", name="Опубликовать текущий черновик сайта", exact=True).click()
- page.locator("#confirm-dialog button[value=confirm]").click()
+ page.locator('[data-pub-action=candidate]').first.click()
+ page.locator('[data-publication-root][aria-busy=false]').wait_for()
+ page.locator('[data-pub-action=publish]').click()
+ page.locator('#release-comment').fill('Shell QA release')
+ page.locator('[data-pub-action=confirm-publish]').click()
page.locator(".live-pip:not(.no-release) .mono").wait_for()
page.goto(origin + "/admin/pages")
assert page.locator(".live-pip .mono").inner_text().strip()
diff --git a/scripts/sync_content_design.py b/scripts/sync_content_design.py
new file mode 100644
index 0000000..95c683a
--- /dev/null
+++ b/scripts/sync_content_design.py
@@ -0,0 +1,48 @@
+"""Transfer original Content CSS and SVGs; only isolate selectors from the shell."""
+
+import json
+import re
+import sys
+from pathlib import Path
+
+from css_scope import scope_css
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def main():
+ def emit(path, content):
+ if "--check" in sys.argv:
+ if not path.exists() or path.read_text() != content:
+ raise SystemExit(f"Content design out of date: {path}")
+ else:
+ path.write_text(content)
+
+ target = ROOT / "src/site_engine/web/admin"
+ css = (
+ (ROOT / "design/assets/builder.css").read_text()
+ + "\n"
+ + (ROOT / "design/assets/content-editor.css").read_text()
+ )
+ css = re.sub(r"(? {%- endmacro %}\n',
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/sync_publication_design.py b/scripts/sync_publication_design.py
new file mode 100644
index 0000000..00b3098
--- /dev/null
+++ b/scripts/sync_publication_design.py
@@ -0,0 +1,41 @@
+"""Reproduce the original publication CSS/SVG, scoped to the accepted runtime shell."""
+
+import json
+import re
+import sys
+from pathlib import Path
+
+from css_scope import scope_css
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def main():
+ target = ROOT / "src/site_engine/web/admin"
+ css = (ROOT / "design/assets/publication.css").read_text()
+ css = re.sub(r"(? {%- endmacro %}\n',
+ target / "static/publication-icons.json": json.dumps(icons, ensure_ascii=False) + "\n",
+ }
+ for path, content in output.items():
+ if "--check" in sys.argv:
+ if not path.exists() or path.read_text() != content:
+ raise SystemExit(f"Publication design out of date: {path}")
+ else:
+ path.write_text(content)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/verify_package_001.py b/scripts/verify_package_001.py
index e447dd0..2470931 100644
--- a/scripts/verify_package_001.py
+++ b/scripts/verify_package_001.py
@@ -97,7 +97,7 @@ with TestClient(app) as client:
assert response.status_code==200
response=client.get('/admin/pages/index')
assert response.status_code==200 and 'document-editor' in response.text
- for name in ('antirion-rework.css','shell.css','pages.css','pages.js','admin.css','admin.js','editor.js','preview-update.js','builder.css','builder-adapter.css','builder.js','htmx.min.js','theme-studio.css','theme-studio.js'):
+ for name in ('antirion-rework.css','shell.css','pages.css','pages.js','admin.css','admin.js','editor.js','preview-update.js','builder.css','builder-adapter.css','builder.js','htmx.min.js','theme-studio.css','theme-studio.js','content-editor.css','content-adapter.css','content-editor.js','favicon.svg','publication.css','publication-adapter.css','publication.js','publication-icons.json'):
assert client.get('/admin/static/'+name).status_code==200,name
assert 'pages-screen' in client.get('/admin/pages').text
cookie=client.cookies.get('se_session')
@@ -139,8 +139,31 @@ with TestClient(app) as client:
result=preview.get(result.json()['url'])
assert result.status_code==200 and 'sample-site' in result.text,result.text
assert '--color-primary: #a48bfa' in result.text
+ response=client.get('/admin/content/services/bots')
+ assert response.status_code==200 and 'entry-workspace' in response.text,response.text
+ from site_engine.services.entries import EntryService
+ entry=EntryService(Path(os.environ['SITE_ROOT']),collection='services').get('bots')
+ result=client.post('/admin/editor/content/services/bots/update',data={'csrf':csrf,'payload':json.dumps({'source':entry.source,'etag':entry.etag,'revision':30,'preview_view':'card'})},headers={'Origin':'http://testserver','HX-Request':'true','Accept':'application/json'})
+ assert result.status_code==200 and 'f-entry_card' in result.json()['preview']['html'],result.text
+ assert 'data-content-tab' in result.json()['projection']
+ assert 'data-publication-root' in client.get('/admin/publish').text
+ def publication(op, payload=None):
+ return client.post('/admin/publication/'+op,data={'csrf':csrf,'payload':json.dumps(payload or {})},headers={'Origin':'http://testserver','Accept':'application/json'})
+ live=(Path(os.environ['SITE_DIST'])/'current').resolve().name
+ candidate=publication('build')
+ assert candidate.status_code==200,candidate.text
+ identity=candidate.json()['id']
+ assert (Path(os.environ['SITE_DIST'])/'current').resolve().name==live
+ passive=publication('preview',{'id':identity,'route':'/'})
+ assert passive.status_code==200,passive.text
+ with TestClient(create_preview_app()) as preview:
+ result=preview.get(passive.json()['url'])
+ assert result.status_code==200 and '", "", html, flags=re.IGNORECASE)
payload = (
base64.urlsafe_b64encode(json.dumps(data, separators=(",", ":")).encode())
.rstrip(b"=")
@@ -340,7 +371,7 @@ class PreviewStore:
atomic_write(folder / "assets" / rel, raw)
html = rewrite_assets(html, prefix, token)
live_html = html
- if self.config:
+ if self.config and not passive:
bridge = read_static("preview-update.js") + "\n" + read_static("preview.js").replace(
"__CONFIG__",
json.dumps(
diff --git a/src/site_engine/services/publication.py b/src/site_engine/services/publication.py
new file mode 100644
index 0000000..35b1a24
--- /dev/null
+++ b/src/site_engine/services/publication.py
@@ -0,0 +1,522 @@
+"""Real release workflow: private provenance, immutable candidates and guarded activation.
+
+Workspace writes still belong to ContentService. This service never edits source files.
+All cooperating builds/writes/activation use SiteLock; external filesystem writers must
+honour that lock. Private source snapshots are never copied to public dist.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+import hashlib
+import json
+import logging
+from pathlib import Path
+from types import SimpleNamespace
+
+from ..build.pipeline import (
+ _SKIP_DIRS,
+ BUILD_ID_RE,
+ build_site,
+ hash_tree,
+ render_fingerprint,
+ switch_current,
+)
+from ..core.registry import load_site
+from ..core.routes import build_route_table, route_to_output
+from ..core.validate import validate_release, validate_workspace
+from ..errors import ConflictError, EngineError, Report, UnsafePathError
+from ..parsing.frontmatter import parse
+from ..services.preview import asset_path
+from ..storage.fs import atomic_write, safe_join
+from ..storage.locks import SiteLock
+
+log = logging.getLogger("uvicorn.error")
+ROOT_FILES = {"site.yaml", "theme.yaml", "redirects.yaml"}
+TYPES = {
+ "pages": "Page",
+ "content": "Entry",
+ "menus": "Menu",
+ "assets": "Asset",
+ "layouts": "Layout",
+ "fragments": "Fragment",
+ "collections": "Schema",
+ "display": "Display",
+ "data": "Data",
+ "forms": "Form",
+}
+
+
+class ReleaseMissing(EngineError):
+ pass
+
+
+class CandidateCommitError(EngineError):
+ def __init__(self, build_id):
+ self.build_id = build_id
+ super().__init__(
+ "Кандидат собран, но запись служебных данных не завершена. Live не переключён. Обновите состояние перед повтором."
+ )
+
+
+class ReleaseCommitError(EngineError):
+ def __init__(self, build_id):
+ self.build_id = build_id
+ super().__init__(
+ "Live переключён, но запись служебных данных не завершена. Обновите состояние перед повтором."
+ )
+
+
+class PublicationService:
+ def __init__(self, root, dist, state, audit):
+ self.root, self.dist = Path(root), Path(dist)
+ self.directory, self.audit = Path(state) / "publication", audit
+
+ def current(self):
+ path = self.dist / "current"
+ if not path.exists():
+ return None
+ resolved = path.resolve()
+ if resolved.parent != self.dist.resolve() or not BUILD_ID_RE.fullmatch(resolved.name):
+ raise UnsafePathError("Некорректный указатель текущего релиза")
+ return resolved.name
+
+ def folder(self, identity):
+ if not BUILD_ID_RE.fullmatch(identity):
+ raise ReleaseMissing("Недопустимый ID релиза")
+ path = self.dist / identity
+ if path.is_symlink() or not path.is_dir():
+ raise ReleaseMissing("Релиз отсутствует или уже удалён")
+ return path
+
+ def manifest(self, identity):
+ return json.loads((self.folder(identity) / "manifest.json").read_text())
+
+ def read(self, name, default=None):
+ path = self.directory / name
+ return json.loads(path.read_text()) if path.is_file() else default
+
+ def write(self, name, data):
+ self.directory.mkdir(parents=True, exist_ok=True, mode=0o700)
+ atomic_write(self.directory / name, json.dumps(data, ensure_ascii=False, indent=2))
+
+ def provenance(self, identity):
+ return self.read(f"releases/{identity}.json") if identity else None
+
+ def sources(self):
+ result = {}
+ theme_file = load_site(self.root).site.theme_file
+ root_files = ROOT_FILES | ({theme_file} if theme_file else set())
+ for path in sorted(self.root.rglob("*")):
+ rel = path.relative_to(self.root)
+ if _SKIP_DIRS & set(rel.parts) or any(x.startswith(".") for x in rel.parts):
+ continue
+ if path.is_symlink():
+ raise UnsafePathError(f"Symlink не допускается в исходниках релиза: {rel}")
+ if not path.is_file() or (
+ rel.parts[0] not in TYPES and rel.as_posix() not in root_files
+ ):
+ continue
+ raw = path.read_bytes()
+ kind = TYPES.get(rel.parts[0], "Config")
+ title, status, text = rel.name, "configuration", None
+ if kind in {"Page", "Entry"} and path.suffix == ".md":
+ try:
+ meta, _ = parse(raw.decode())
+ title, status = (
+ str(meta.get("title") or path.stem),
+ str(meta.get("status", "draft")),
+ )
+ except (ValueError, UnicodeError):
+ status = "invalid"
+ if len(raw) <= 524288 and path.suffix in {
+ ".md",
+ ".yaml",
+ ".yml",
+ ".css",
+ ".js",
+ ".j2",
+ ".txt",
+ }:
+ try:
+ text = raw.decode()
+ except UnicodeError:
+ pass
+ result[rel.as_posix()] = {
+ "hash": hashlib.sha256(raw).hexdigest(),
+ "size": len(raw),
+ "title": title,
+ "status": status,
+ "type": kind,
+ "source": text,
+ }
+ return result
+
+ @staticmethod
+ def delta(now, before, unknown=False):
+ rows = []
+ for path in sorted(set(now) | set(before)):
+ a, b = now.get(path), before.get(path)
+ if a and b and a["hash"] == b["hash"]:
+ continue
+ row = a or b
+ rows.append(
+ {
+ "path": path,
+ "title": row["title"],
+ "type": row["type"],
+ "status": a["status"] if a else "deleted",
+ "kind": "unknown"
+ if unknown
+ else "new"
+ if not b
+ else "deleted"
+ if not a
+ else "modified",
+ "before": b,
+ "after": a,
+ }
+ )
+ return rows
+
+ def event(self, event, ctx, **fields):
+ self.audit.write(
+ "release_" + event, actor=ctx.principal.login, ip=ctx.ip, source=ctx.source, **fields
+ )
+
+ def activity(self):
+ path = self.audit.path
+ if not path.is_file():
+ return []
+ result = []
+ # Bounded tail; old events remain in the actual audit log.
+ with path.open("rb") as stream:
+ stream.seek(0, 2)
+ length = stream.tell()
+ stream.seek(max(0, length - 262144))
+ if length > 262144:
+ stream.readline()
+ for line in stream:
+ try:
+ item = json.loads(line)
+ except (ValueError, UnicodeError):
+ continue
+ if item.get("event", "").startswith("release_") or item.get("event") in {
+ "publish",
+ "rollback",
+ }:
+ result.append(
+ {
+ k: item[k]
+ for k in (
+ "ts",
+ "event",
+ "actor",
+ "object",
+ "errors",
+ "warnings",
+ "request_id",
+ )
+ if k in item
+ }
+ )
+ return result[-80:][::-1]
+
+ def state(self):
+ with SiteLock(self.root):
+ return self._state()
+
+ def _state(self):
+ live, current_sources = self.current(), self.sources()
+ baseline = self.provenance(live)
+ comparison = not live or baseline is not None
+ changes = self.delta(current_sources, (baseline or {}).get("sources", {}), not comparison)
+ candidate = self.read("candidate.json")
+ fingerprint = hash_tree(self.root)
+ renderer = render_fingerprint(load_site(self.root))
+ if candidate:
+ candidate = dict(candidate)
+ candidate["fresh"] = (
+ candidate["source_hash"] == fingerprint
+ and candidate["render_hash"] == renderer
+ and candidate["base"] == live
+ )
+ if not (self.dist / candidate["id"]).is_dir():
+ candidate["fresh"] = False
+ validation = self.read("validation.json")
+ if validation:
+ validation["fresh"] = (
+ validation["source_hash"] == fingerprint and validation["render_hash"] == renderer
+ )
+ history = []
+ if self.dist.is_dir():
+ for p in sorted(self.dist.iterdir(), reverse=True):
+ if BUILD_ID_RE.fullmatch(p.name) and p.is_dir() and not p.is_symlink():
+ m, provenance = self.manifest(p.name), self.provenance(p.name)
+ history.append(
+ {
+ "id": p.name,
+ "current": p.name == live,
+ "built_at": m.get("built_at"),
+ "pages": len(m.get("routes", [])),
+ "routes": m.get("routes", []),
+ "forms": self.forms(p.name),
+ "author": (provenance or {}).get("author"),
+ "comment": (provenance or {}).get("comment", ""),
+ "candidate": provenance is not None
+ and not provenance.get("published_at")
+ and p.name != live,
+ "comparison_available": provenance is not None,
+ }
+ )
+ return {
+ "current": live,
+ "changes": changes,
+ "comparison_available": comparison,
+ "source_hash": fingerprint,
+ "candidate": candidate,
+ "validation": validation,
+ "history": history,
+ "builds": self.read("builds.json", []),
+ "activity": self.activity(),
+ }
+
+ def forms(self, identity):
+ folder = self.folder(identity) / "_forms"
+ return sorted(p.stem for p in folder.glob("*.json"))
+
+ def validate(self, ctx):
+ with SiteLock(self.root):
+ reg, report = load_site(self.root), Report()
+ table = build_route_table(reg, report)
+ report.extend(validate_workspace(reg, table))
+ report.extend(validate_release(reg, table))
+ data = {
+ "source_hash": hash_tree(self.root),
+ "render_hash": render_fingerprint(reg),
+ "at": dt.datetime.now(dt.UTC).isoformat(),
+ "issues": [i.to_dict() for i in report.issues],
+ "errors": len(report.errors),
+ "warnings": len(report.warnings),
+ }
+ self.write("validation.json", data)
+ self.event("validate", ctx, errors=data["errors"], warnings=data["warnings"])
+ return data
+
+ def build(self, ctx, request_id=""):
+ with SiteLock(self.root):
+ started, base = dt.datetime.now(dt.UTC).isoformat(), self.current()
+ builds = self.read("builds.json", [])
+ completed = None
+ try:
+ sources = self.sources()
+ result = build_site(self.root, self.dist, activate=False)
+ completed = result.build_id
+ manifest = self.manifest(result.build_id)
+ candidate = {
+ "id": result.build_id,
+ "base": base,
+ "source_hash": result.source_hash,
+ "render_hash": manifest["render_hash"],
+ "at": started,
+ "author": ctx.principal.login,
+ "pages": result.pages,
+ "output_hash": hash_tree(result.output_dir),
+ "routes": manifest["routes"],
+ "issues": [i.to_dict() for i in result.report.issues],
+ }
+ prior = self.provenance(base)
+ changes = self.delta(
+ sources, (prior or {}).get("sources", {}), bool(base and prior is None)
+ )
+ candidate["changes"] = len(changes)
+ provenance = self.provenance(result.build_id)
+ # Identical build within one second can reuse an existing immutable release.
+ if provenance is None:
+ self.write(
+ f"releases/{result.build_id}.json", {"sources": sources, **candidate}
+ )
+ self.write("candidate.json", candidate)
+ builds.insert(
+ 0,
+ {
+ "id": result.build_id,
+ "at": started,
+ "base": base,
+ "status": "ready",
+ "pages": result.pages,
+ "request_id": request_id,
+ "log": f"validate: OK\nrender: {result.pages} страниц\nsnapshot: {result.build_id}\nlive: не переключён",
+ },
+ )
+ self.write("builds.json", builds[:40])
+ self.event("build", ctx, object=result.build_id, request_id=request_id)
+ return candidate
+ except Exception as exc:
+ if completed is not None:
+ raise CandidateCommitError(completed) from exc
+ # Keep previous candidate and live intact; diagnostics are real, no simulated progress.
+ issues = (
+ [i.to_dict() for i in exc.report.issues] if isinstance(exc, EngineError) else []
+ )
+ builds.insert(
+ 0,
+ {
+ "id": "",
+ "at": started,
+ "base": base,
+ "status": "failed",
+ "request_id": request_id,
+ "issues": issues,
+ "log": "Сборка не завершена. Live не переключён.\n"
+ + (str(exc) if issues else "См. серверный traceback по ID запроса."),
+ },
+ )
+ try:
+ self.write("builds.json", builds[:40])
+ self.event("failure", ctx, request_id=request_id)
+ except OSError:
+ log.exception("release_failure_record_failed request_id=%s", request_id)
+ raise
+
+ def activate(self, identity, expected_live, comment, ctx, *, rollback=False):
+ with SiteLock(self.root):
+ actual = self.current()
+ if actual != expected_live:
+ raise ConflictError(
+ "Live изменился в другой вкладке. Обновите данные перед подтверждением.",
+ actual or "absent",
+ )
+ manifest = self.manifest(identity)
+ provenance = self.provenance(identity)
+ if (
+ rollback
+ and provenance
+ and not provenance.get("published_at")
+ and identity != actual
+ ):
+ raise EngineError("Неопубликованный кандидат нельзя выбрать через откат")
+ if not rollback:
+ candidate = self.read("candidate.json")
+ if not candidate or candidate["id"] != identity:
+ raise ConflictError("Кандидат заменён. Проверьте актуальную сборку.", identity)
+ if (
+ candidate["base"] != actual
+ or candidate["source_hash"] != hash_tree(self.root)
+ or candidate["render_hash"] != render_fingerprint(load_site(self.root))
+ ):
+ raise ConflictError(
+ "Кандидат устарел. Проверьте и пересоберите workspace.", identity
+ )
+ if not comment.strip():
+ raise ValueError("Добавьте комментарий к релизу")
+ if manifest.get("build_id") != identity:
+ raise EngineError("Manifest не соответствует выбранному релизу")
+ if provenance and provenance.get("output_hash") != hash_tree(self.folder(identity)):
+ raise EngineError("Файлы снимка изменились после сборки. Создайте новый кандидат.")
+ switch_current(self.dist, identity)
+ try:
+ if provenance:
+ provenance.update(published_at=dt.datetime.now(dt.UTC).isoformat())
+ if not rollback:
+ provenance.update(comment=comment.strip(), author=ctx.principal.login)
+ self.write(f"releases/{identity}.json", provenance)
+ if (self.read("candidate.json") or {}).get("id") == identity:
+ self.write("candidate.json", None)
+ self.event("rollback" if rollback else "publish", ctx, object=identity)
+ except OSError as exc:
+ raise ReleaseCommitError(identity) from exc
+ return {"current": identity, "committed": True}
+
+ def release_details(self, identity):
+ with SiteLock(self.root):
+ live = self.current()
+ target = self.folder(identity)
+ base = self.folder(live) if live else None
+
+ def outputs(folder):
+ if folder is None:
+ return {}
+ result = {}
+ for p in folder.rglob("*"):
+ if p.is_file():
+ rel = p.relative_to(folder).as_posix()
+ result[rel] = hashlib.sha256(
+ asset_path(folder, rel).read_bytes()
+ ).hexdigest()
+ return result
+
+ before, after = outputs(base), outputs(target)
+ changes = [
+ {
+ "path": p,
+ "kind": "new"
+ if p not in before
+ else "deleted"
+ if p not in after
+ else "modified",
+ }
+ for p in sorted(before.keys() | after.keys())
+ if before.get(p) != after.get(p)
+ ]
+ return {"id": identity, "base": live, "changes": changes}
+
+ def candidate_diff(self):
+ with SiteLock(self.root):
+ candidate = self.read("candidate.json")
+ if not candidate:
+ raise ReleaseMissing("Кандидат пока не создан")
+ snapshot = self.provenance(candidate["id"])
+ base = self.provenance(candidate["base"])
+ available = not candidate["base"] or base is not None
+ return {
+ "id": candidate["id"],
+ "base": candidate["base"],
+ "comparison_available": available,
+ "changes": self.delta(
+ (snapshot or {}).get("sources", {}),
+ (base or {}).get("sources", {}),
+ not available,
+ ),
+ }
+
+ def compare(self, path):
+ safe_join(self.root, path)
+ with SiteLock(self.root):
+ live = self.current()
+ baseline = self.provenance(live)
+ now = self.sources().get(path)
+ before = (baseline or {}).get("sources", {}).get(path)
+ return {
+ "path": path,
+ "current": live,
+ "comparison_available": not live or baseline is not None,
+ "before": before,
+ "after": now,
+ }
+
+ def document_history(self, path):
+ safe_join(self.root, path)
+ if path.split("/", 1)[0] not in TYPES or any(p.startswith(".") for p in Path(path).parts):
+ raise UnsafePathError("История недоступна для этого пути")
+ folder = safe_join(self.root, ".engine/history/" + path)
+ versions = []
+ for p in sorted(folder.iterdir(), reverse=True) if folder.is_dir() else []:
+ if p.is_file() and not p.is_symlink():
+ versions.append({"id": p.name, "size": p.stat().st_size})
+ return {"path": path, "versions": versions[:20]}
+
+ def preview(self, identity, route, previews, principal):
+ with SiteLock(self.root):
+ manifest, folder = self.manifest(identity), self.folder(identity)
+ if route not in manifest.get("routes", []):
+ raise ReleaseMissing("Маршрут отсутствует в этом снимке")
+ html = asset_path(folder, route_to_output(route)).read_text()
+ return previews.store(
+ SimpleNamespace(root=folder),
+ html,
+ 0,
+ principal,
+ f"release:{identity}:{route}",
+ passive=True,
+ )
diff --git a/src/site_engine/services/workspace.py b/src/site_engine/services/workspace.py
index 09925ab..d77f2b7 100644
--- a/src/site_engine/services/workspace.py
+++ b/src/site_engine/services/workspace.py
@@ -29,6 +29,7 @@ def release_info(dist: Path) -> dict:
"built_at": manifest.get("built_at"),
"routes": manifest.get("routes", []),
"page_sources": manifest.get("page_sources"),
+ "entry_sources": manifest.get("entry_sources"),
}
@@ -45,6 +46,8 @@ def filter_pages(pages, *, q="", status="", layout="", changed=False):
def workspace(root: Path, dist: Path, state: Path) -> dict:
+ from .entry_context import collection_rows
+
reg = load_site(root)
report = Report()
table = build_route_table(reg, report)
@@ -92,15 +95,7 @@ def workspace(root: Path, dist: Path, state: Path) -> dict:
return {
"site_name": reg.site.name,
"pages": sorted(pages, key=lambda p: p["route"]),
- "collections": [
- {
- "id": c.id,
- "name": c.name,
- "total": len(reg.entries.get(c.id, [])),
- "published": sum(e.status == "published" for e in reg.entries.get(c.id, [])),
- }
- for c in reg.collections.values()
- ],
+ "collections": collection_rows(reg),
"layouts": sorted(reg.layouts),
"issues": [i.to_dict() for i in report.issues],
"release": {k: release[k] for k in ("current", "built_at", "routes")},
@@ -113,36 +108,16 @@ def workspace(root: Path, dist: Path, state: Path) -> dict:
}
-def entries(root: Path, collection: str) -> dict:
+def entries(root: Path, collection: str, dist: Path | None = None) -> dict:
from .documents import DocumentMissing
reg = load_site(root)
c = reg.collections.get(collection)
if c is None:
raise DocumentMissing("Нет коллекции")
- table = build_route_table(reg, Report())
- routes = {
- (r.collection.id, r.entry.slug): r.route for r in table.values() if r.collection and r.entry
- }
- items = reg.entries.get(c.id, [])
- return {
- "collection": {
- "id": c.id,
- "name": c.name,
- "total": len(items),
- "published": sum(e.status == "published" for e in items),
- },
- "entries": [
- {
- "slug": e.slug,
- "title": str(e.data.get("title", e.slug)),
- "status": e.status,
- "file": e.file,
- "route": routes.get((c.id, e.slug), "—"),
- }
- for e in items
- ],
- }
+ from .entry_context import collection_context
+
+ return collection_context(reg, collection, dist)
def releases(dist: Path) -> dict:
diff --git a/src/site_engine/web/admin/application.py b/src/site_engine/web/admin/application.py
index ea455d2..04e486d 100644
--- a/src/site_engine/web/admin/application.py
+++ b/src/site_engine/web/admin/application.py
@@ -2,6 +2,7 @@
import json
import re
+import secrets
from contextvars import ContextVar
from urllib.parse import quote
@@ -37,7 +38,13 @@ class AdminApplication:
)
def page(self, template, principal, section, status=200, **extra):
- return page_result(render(template, **self.ctx(principal, section, **extra)), status)
+ result = page_result(render(template, **self.ctx(principal, section, **extra)), status)
+ # A boosted swap retains the starting document's CSP, including frame-src.
+ if self.previews.config:
+ result.headers["Content-Security-Policy"] = result.headers[
+ "Content-Security-Policy"
+ ].replace("frame-src 'self'", "frame-src 'self' " + self.previews.config.preview)
+ return result
def message(self, principal, text, status, error=None):
return self.page(
@@ -89,10 +96,6 @@ class AdminApplication:
result.headers["Content-Security-Policy"] = result.headers[
"Content-Security-Policy"
].replace("style-src 'self'", "style-src 'self'; style-src-attr 'unsafe-inline'")
- if self.previews.config:
- result.headers["Content-Security-Policy"] = result.headers[
- "Content-Security-Policy"
- ].replace("frame-src 'self'", "frame-src 'self' " + self.previews.config.preview)
return result
try:
if path in {"/setup/theme/skip", "/setup/theme/restart"}:
@@ -278,21 +281,20 @@ class AdminApplication:
if partial
else "page_builder.html.j2"
if snap["kind"] == "page"
- else "document.html.j2"
+ else "content.html.j2"
)
result = self.page(
template, principal, "pages" if snap["kind"] == "page" else "content", status, **ctx
)
result.headers["X-Editor-Revision"] = str(snap["revision"])
- if self.previews.config:
- result.headers["Content-Security-Policy"] = result.headers[
- "Content-Security-Policy"
- ].replace("frame-src 'self'", "frame-src 'self' " + self.previews.config.preview)
return result
async def dispatch(self, request):
- json_post = request.method == "POST" and (
+ publication_json = request.url.path.startswith("/admin/publication/") and "application/json" in request.headers.get("accept", "")
+ json_post = publication_json or request.method == "POST" and (
request.url.path.startswith(("/admin/theme/", "/admin/setup/theme/"))
+ or (request.url.path.startswith("/admin/publication/")
+ and "application/json" in request.headers.get("accept", ""))
or (request.url.path.startswith("/admin/editor/")
and "application/json" in request.headers.get("accept", ""))
)
@@ -301,7 +303,7 @@ class AdminApplication:
if principal is None:
if json_post:
return self.json_failure(
- 401, "session_expired", "Сессия истекла. Скачайте YAML и войдите снова."
+ 401, "session_expired", ("Сессия истекла. Войдите снова и обновите состояние публикации." if publication_json else "Сессия истекла. Скачайте YAML и войдите снова.")
)
if request.headers.get("hx-request"):
return page_result(
@@ -329,7 +331,7 @@ class AdminApplication:
token = _navigation.set(None)
try:
lightweight = request.url.path.startswith(
- ("/admin/editor/", "/admin/preview/")
+ ("/admin/editor/", "/admin/preview/", "/admin/publication/")
) or (
request.method == "POST"
and request.url.path.startswith(("/admin/theme/", "/admin/setup/theme/"))
@@ -424,9 +426,10 @@ class AdminApplication:
**{k: data[k] for k in ("site_name", "pages", "collections", "paths")},
)
if path == "/content":
- return self.page(
- "content_index.html.j2", principal, "content", collections=data["collections"]
- )
+ if data["collections"]:
+ return redirect_result("/admin/content/" + data["collections"][0]["id"])
+ return self.page("content.html.j2", principal, "content", snap=None,
+ empty_data={"collection": None, "collections": [], "entries": [], "display": "", "comparison_available": False, "live_build": None})
if (
query.get("status")
and query["status"] not in STATUSES
@@ -481,28 +484,15 @@ class AdminApplication:
match = re.fullmatch(r"/content/([a-z][a-z0-9_]*)", path)
if match and not post:
data = await api.call("GET", f"/collections/{match[1]}/entries")
- if query.get("status") and query["status"] not in STATUSES:
- return self.message(principal, "Проверьте status", 422)
- data["entries"] = [
- e
- for e in data["entries"]
- if (not query.get("status") or e["status"] == query["status"])
- and query.get("q", "").casefold() in " ".join(str(v) for v in e.values()).casefold()
- ]
- return self.page(
- "entries_list.html.j2",
- principal,
- "content",
- **data,
- errors=[],
- slug="",
- filters=query,
- )
+ if data["entries"]:
+ selected = next((e for e in data["entries"] if e["slug"] == query.get("selected")), data["entries"][0])
+ return redirect_result(f"/admin/content/{match[1]}/{selected['slug']}")
+ return self.page("content.html.j2", principal, "content", snap=None, empty_data=data)
match = re.fullmatch(r"/content/([a-z][a-z0-9_]*)/new", path)
if match and post:
try:
snap = await api.call(
- "POST", f"/collections/{match[1]}/entries", {"id": form.first("slug").strip()}
+ "POST", f"/collections/{match[1]}/entries", {"id": form.first("slug").strip() or "entry-" + secrets.token_hex(3)}
)
except ApiError as exc:
if exc.status >= 500:
@@ -512,18 +502,38 @@ class AdminApplication:
data = await api.call("GET", f"/collections/{match[1]}/entries")
return exc.annotate(
self.page(
- "entries_list.html.j2",
- principal,
- "content",
- exc.status,
- **data,
- errors=[str(exc)],
- slug=form.first("slug"),
- filters={},
+ "content.html.j2", principal, "content", exc.status,
+ snap=None, empty_data=data, content_error=str(exc),
)
)
return redirect_result(f"/admin/content/{match[1]}/{snap['id']}")
- if path == "/publish" or path.startswith("/publish/rollback/"):
+ if path.startswith("/publication/"):
+ operation = path.removeprefix("/publication/")
+ if operation not in {"state", "validate", "build", "activate", "rollback", "compare", "candidate-diff", "release", "document-history", "preview"}:
+ return self.json_failure(404, "not_found", "Операция публикации не найдена")
+ try:
+ if post:
+ if operation not in {"validate", "build", "activate", "rollback", "preview"}:
+ return self.json_failure(405, "method_not_allowed", "Операция доступна только для чтения")
+ submitted = json.loads(form.first("payload") or "{}")
+ result = await api.call("POST", "/publication/" + operation, submitted)
+ else:
+ if operation not in {"state", "compare", "candidate-diff", "release", "document-history"}:
+ return self.json_failure(405, "method_not_allowed", "Для операции требуется POST")
+ endpoint = "/publication" if operation == "state" else "/publication/" + operation + ("?path=" + quote(query.get("path", ""), safe="") if operation in {"compare", "document-history"} else "")
+ if operation == "release":
+ endpoint += "?id=" + quote(query.get("id", ""), safe="")
+ result = await api.call("GET", endpoint)
+ return self.json_result(result)
+ except (ValueError, TypeError):
+ return self.json_failure(422, "request_validation", "Некорректный запрос публикации")
+ except ApiError as exc:
+ return exc.annotate(self.json_result(exc.data, exc.status))
+ if path == "/publish" and not post:
+ data = await api.call("GET", "/publication")
+ result = self.page("publication.html.j2", principal, "publish", boot={"state": data, "csrf": self.auth.csrf_token(principal), "tab": query.get("tab", "changes")})
+ return result
+ if path in {"/publish", "/publish/legacy"} or path.startswith("/publish/rollback/"):
endpoint = (
"/releases"
if not post
@@ -588,11 +598,13 @@ class AdminApplication:
submitted = json.loads(form.first("payload"))
except (ValueError, TypeError):
return self.json_failure(422, "request_validation", "Некорректный запрос редактора")
- if op not in {"update", "save"}:
+ if op not in {"update", "save", "duplicate", "delete", "check"}:
return self.json_failure(422, "invalid_operation", "Неизвестная операция редактора")
try:
payload = await api.call("POST", endpoint + "/" + op, submitted)
- if op == "save":
+ if op in {"delete", "check"}:
+ return self.json_result(payload)
+ if op in {"save", "duplicate"}:
payload = {"snapshot": payload, "preview": None, "preview_error": None}
payload["projection"] = self.editor_projection(principal, payload["snapshot"], docpath, form)
return self.json_result(payload)
diff --git a/src/site_engine/web/admin/forms.py b/src/site_engine/web/admin/forms.py
index 7c34f2e..df99fd9 100644
--- a/src/site_engine/web/admin/forms.py
+++ b/src/site_engine/web/admin/forms.py
@@ -35,7 +35,7 @@ def build_view(fd: FieldDef, raw: Any, name: str, ctx: Mapping[str, Any]) -> dic
view: dict[str, Any] = {
"name": name, "key": fd.key, "label": label_of(fd), "type": t, "required": fd.required,
"hint": fd.extra.get("hint"), "bind": "", "value": "", "options": [], "children": [],
- "rows": [], "kind": "input", "datalist": [],
+ "rows": [], "kind": "input", "datalist": [], "to": fd.to,
}
if _is_bind(raw):
view["bind"] = str(raw["bind"])
diff --git a/src/site_engine/web/admin/handlers.py b/src/site_engine/web/admin/handlers.py
index 7288479..8b484e8 100644
--- a/src/site_engine/web/admin/handlers.py
+++ b/src/site_engine/web/admin/handlers.py
@@ -125,7 +125,7 @@ class AdminHandlers:
ctx["site_error"] = str(exc)
return _page(render("dashboard.html.j2", **ctx))
- _STATIC: ClassVar[dict[str, str]] = {"theme-studio.css": "text/css; charset=utf-8",
+ _STATIC: ClassVar[dict[str, str]] = {"publication.css": "text/css; charset=utf-8", "publication-adapter.css": "text/css; charset=utf-8", "publication.js": "text/javascript; charset=utf-8", "publication-icons.json": "application/json","favicon.svg": "image/svg+xml","content-editor.css": "text/css; charset=utf-8", "content-adapter.css": "text/css; charset=utf-8", "content-editor.js": "text/javascript; charset=utf-8", "theme-studio.css": "text/css; charset=utf-8",
"theme-studio.js": "text/javascript; charset=utf-8","admin.css": "text/css; charset=utf-8",
"builder.css": "text/css; charset=utf-8", "builder-adapter.css": "text/css; charset=utf-8",
"builder.js": "text/javascript; charset=utf-8",
diff --git a/src/site_engine/web/admin/static/VENDOR.md b/src/site_engine/web/admin/static/VENDOR.md
index cd8d43b..550a4da 100644
--- a/src/site_engine/web/admin/static/VENDOR.md
+++ b/src/site_engine/web/admin/static/VENDOR.md
@@ -26,3 +26,25 @@ SVG в `templates/_builder_icons.html.j2` извлечены тем же скр
Адаптации находятся в `builder-adapter.css`/`builder.js`; исходный `builder.css` вручную не редактируется. Тёмные токены сопоставлены с утверждённым Antirion Rework. Проверка воспроизводимости без записи: `python scripts/sync_builder_design.py --check`. Отдельная frontend-сборка/Node/CDN не требуются.
`preview.css` переносит оформление выделения/hover и бейдж SELECTED из `previewCss` в `design/assets/builder.js` на служебные `data-preview-*` маркеры настоящих блоков. Этот CSS добавляется только в снимки предпросмотра; публичная сборка его не получает.
+
+## Content Editor (этап 4)
+
+`content-editor.css` генерируется `scripts/sync_content_design.py` из исходных `design/assets/builder.css` и `design/assets/content-editor.css`. Декларации, breakpoints и специфичность сохраняются; обычные селекторы ограничены `.entry-content-editor`, без CSS `@scope`. SVG paths извлечены из `icon()` оригинального content-editor.js; stroke-width 1.7 сохранён. Подсветка Expert перенесена из `highlightSource()`, с обязательным экранированием текста.
+
+- `design/assets/builder.css`: SHA-256 `77b5864a5e9c1c0475515f8b0d305514f032c4690f1a06da809395ebe5e399c4`.
+- `design/assets/content-editor.css`: SHA-256 `95cd9520f278dd86a4411653e0384ef87a9b7b96508d2bd41d18a57f7e33296f`.
+- `design/assets/content-editor.js`: SHA-256 `fd4fe384c33d99da39806b226277aeda953bf2c44b445eaa59d2c1a7f37b79dd`.
+- `src/site_engine/web/admin/static/content-editor.css`: SHA-256 `c160a5f94388d60f71c58e9df7ad8f90ea85f648287fdefda8525f75e0921a26`.
+
+Адаптации семантических ссылок/форм, native dialog, CSP/iframe и высоты под принятый shell — отдельные `content-adapter.css` и `content-editor.js`. Данные, YAML, CAS, зависимости и preview поступают из FastAPI через существующий HTML adapter; mock codec/storage не переносятся. Проверка воспроизводимости: `python scripts/sync_content_design.py --check`.
+
+## Publication (этап 5)
+
+Источник композиции/диалогов/поведения — `design/publication-antirion.html` и `design/assets/publication.js`. `scripts/sync_publication_design.py` переносит декларации/breakpoints исходного publication.css, ограничивая селекторы `.publication-content`, и извлекает оригинальные SVG paths/stroke-width 1.7 в `_publication_icons.html.j2` и локальный `publication-icons.json`. Runtime не требует design/.
+
+- `design/assets/publication.css`: SHA-256 `93534dbc55f29c1f3600631433bdff2cb81f896dd3849817e0feb8f57616b645`.
+- `design/assets/publication.js`: SHA-256 `3d40fe2fe037b5b5713adf0be2b4403ef9542c4fc4910d0f36198f828cf13dbc`.
+- `src/site_engine/web/admin/static/publication.css`: SHA-256 `45a07f20e19b07939982d9cc6cf166bf9a9b64fa52434c7861b2a11b65eec74e`.
+- `src/site_engine/web/admin/static/publication-icons.json`: SHA-256 `68ee8f4b7f11b8381365569551f2a0ddb401aab5fab8c461fe3ca01e3e6edd5a`.
+
+Адаптация к существующим FastAPI/HTML endpoints, реальным данным, CSP/native dialog, async busy/error и принятой тёмной палитре находится отдельно в `publication.js` и `publication-adapter.css`. Исходники дизайна не редактируются. Воспроизводимая проверка: `python scripts/sync_publication_design.py --check`. Node/CDN/frontend-сборка не требуются.
diff --git a/src/site_engine/web/admin/static/content-adapter.css b/src/site_engine/web/admin/static/content-adapter.css
new file mode 100644
index 0000000..ab5db76
--- /dev/null
+++ b/src/site_engine/web/admin/static/content-adapter.css
@@ -0,0 +1,32 @@
+/* HTML/CSP/iframe adapters only. Geometry and component styles are generated from design/. */
+.content.content-screen{padding:0}
+.entry-content-editor [hidden]{display:none!important}
+.entry-content-editor #editor-result{display:contents}
+.entry-content-editor form{margin:0}
+.entry-content-editor[data-ready='1'][data-mode='constructor'] #expert-pane,
+.entry-content-editor[data-ready='1'][data-mode='expert'] [data-constructor]{display:none}
+.entry-content-editor #preview-result iframe{display:block;width:100%;height:600px;border:0;background:#fff}
+.entry-content-editor #preview-result[data-view='card'] iframe{height:340px}
+.entry-content-editor .field-label{display:flex}
+.entry-content-editor .list-edit-row>.entry-field{flex:1;min-width:0}
+.entry-content-editor .file-picker input{min-width:0;flex:1}
+.entry-content-editor .ref-pills input{width:100%}
+.entry-content-editor .status:before{display:none}
+.entry-content-editor dialog.stage4-dialog{padding:0;position:fixed;margin:auto}
+.entry-content-editor dialog.stage4-dialog::backdrop{background:#0009}
+.entry-content-editor .dialog-mask{position:static;background:transparent;padding:0}
+.entry-content-editor .conflict-panel textarea{width:100%;min-height:220px}
+@media(prefers-reduced-motion:reduce){.entry-content-editor *{transition:none!important;scroll-behavior:auto!important}}
+
+body[data-skin='dark'] .entry-content-editor{color-scheme:dark;--bg:var(--paper);--surface:var(--paper);--surface2:var(--paper2);--surface3:var(--paper3);--text:var(--ink);--muted:var(--secondary);--border:var(--stroke);--border2:var(--stroke2);--accent:#aba2ff;--focus:#b9b2ff;--dim:#777a7d;--accentSoft:var(--accent2);--accentText:var(--paper);--positive:var(--good);--positiveBg:var(--goodbg);--warning:var(--warn);--warningBg:var(--warnbg);--danger:var(--error);--dangerBg:var(--errorbg);--previewOuter:var(--paper2);--shadow:0 10px 30px #0003}
+
+/* Native typed-link controls retain the source mini-field input geometry. */
+.entry-content-editor .mini-field select{background:var(--surface2);color:var(--text);border:1px solid var(--border);padding:9px 10px;width:100%;min-width:0;border-radius:var(--radius);font-size:11px;outline:none}
+.entry-content-editor .mini-field select:focus{border-color:var(--accent)}
+.entry-content-editor .diff-row span{overflow-wrap:anywhere;white-space:pre-wrap}
+.entry-content-editor .conflict-grid pre{white-space:pre-wrap;overflow-wrap:anywhere}
+
+/* The accepted shell's header is measured instead of the prototype's fixed 60px. */
+@media(min-width:1261px){.entry-content-editor .entry-workspace{height:var(--content-workspace-height,calc(100dvh - 211px))}}
+
+.entry-content-editor .workspace-footer>span{min-width:0;overflow-wrap:anywhere}
diff --git a/src/site_engine/web/admin/static/content-editor.css b/src/site_engine/web/admin/static/content-editor.css
new file mode 100644
index 0000000..be6cbdc
--- /dev/null
+++ b/src/site_engine/web/admin/static/content-editor.css
@@ -0,0 +1,240 @@
+/* Generated by scripts/sync_content_design.py; original declarations unchanged. */
+/* Site Engine / Stage 2.1–2.2. Shared layout, two approved visual skins. Vanilla CSS. */
+:where(.entry-content-editor){font-synthesis:none}:where(.entry-content-editor) *{box-sizing:border-box}:where(.entry-content-editor),:where(.entry-content-editor){margin:0;min-height:100%;font:12px/1.5 Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",Arial,sans-serif}:where(.entry-content-editor) button,:where(.entry-content-editor) input,:where(.entry-content-editor) textarea,:where(.entry-content-editor) select{font:inherit}:where(.entry-content-editor) button{cursor:pointer}:where(.entry-content-editor) button:disabled{opacity:.38;cursor:not-allowed}:where(.entry-content-editor) button:focus-visible,:where(.entry-content-editor) input:focus-visible,:where(.entry-content-editor) select:focus-visible,:where(.entry-content-editor) textarea:focus-visible,:where(.entry-content-editor) a:focus-visible{outline:2px solid var(--focus);outline-offset:2px}:where(.entry-content-editor) a{color:inherit;text-decoration:none}:where(.entry-content-editor) svg{width:16px;height:16px;flex:none;stroke:currentColor}:where(.entry-content-editor) button svg{width:15px;height:15px}:where(.entry-content-editor) h1,:where(.entry-content-editor) h2,:where(.entry-content-editor) h3,:where(.entry-content-editor) p{margin:0}:where(.entry-content-editor){background:var(--bg);color:var(--text)}:where(.entry-content-editor){color-scheme:light;--nav:#151719;--navhover:#26282b;--navtext:#bbc0c4;--navborder:#343639;--navactive:#ececf2;--bg:#f5f5f3;--surface:#fff;--surface2:#f0f1ee;--surface3:#e9eae7;--text:#222529;--muted:#72777c;--dim:#94999b;--border:#dcdedb;--border2:#e8e9e5;--accent:#665ad8;--accentSoft:#eeebff;--focus:#8173ed;--accentText:#fff;--positive:#2e856d;--positiveBg:#e6f4eb;--warning:#a8742a;--warningBg:#fff2e1;--danger:#b14e60;--dangerBg:#fae9ef;--previewOuter:#e9e9e5;--shadow:0 10px 30px #21282b12;--radius:3px;--pill:3px}:where(.entry-content-editor)[data-unused-rose]{color-scheme:dark;--nav:#060607;--navhover:#1b1b20;--navtext:#a5a4b1;--navborder:#29292f;--navactive:#f7f3f8;--bg:#0a0a0d;--surface:#121216;--surface2:#19191e;--surface3:#222229;--text:#f5f2f7;--muted:#a19da8;--dim:#797581;--border:#2e2c33;--border2:#26242b;--accent:#ff4f99;--accentSoft:#321824;--focus:#ff78b5;--accentText:#fff;--positive:#39d6a0;--positiveBg:#132b22;--warning:#ffc786;--warningBg:#332719;--danger:#ff829e;--dangerBg:#3b1a26;--previewOuter:#19191e;--shadow:0 12px 40px #0004;--radius:11px;--pill:7px}
+:where(.entry-content-editor) .layout{display:grid;grid-template-columns:220px minmax(0,1fr);min-height:100vh}:where(.entry-content-editor) .side{position:sticky;top:0;height:100dvh;min-width:0;background:var(--nav);border-right:1px solid var(--navborder);color:var(--navtext);display:flex;flex-direction:column;z-index:12}:where(.entry-content-editor) .side-brand{height:78px;display:flex;align-items:center;gap:11px;padding:16px 15px}:where(.entry-content-editor) .brand-logo{height:38px;width:38px;display:grid;place-items:center;background:#e7e7e5;color:#161718;font-size:19px;font-weight:750;letter-spacing:-.1em;clip-path:polygon(0 0,100% 0,100% 77%,78% 100%,0 100%)}:where(.entry-content-editor) [data-theme="rose"] .brand-logo{clip-path:none;border-radius:12px;background:linear-gradient(138deg,#fa9b5c,#ff4c87 70%,#de318c);color:#fff}:where(.entry-content-editor) .brand-copy b{display:block;color:#f5f5f5;font-size:13px}:where(.entry-content-editor) .brand-copy small{display:block;color:#80818b;margin-top:3px;letter-spacing:.12em;font-size:9px}:where(.entry-content-editor) .side-section{margin:21px 17px 8px;text-transform:uppercase;font-size:9px;letter-spacing:.12em;color:#777b80;font-weight:750}:where(.entry-content-editor) .side-nav{padding:0 8px;flex:1;overflow:auto}:where(.entry-content-editor) .side-link{display:flex;align-items:center;gap:11px;min-height:37px;padding:0 11px;color:var(--navtext);margin:2px 0;position:relative;white-space:nowrap}:where(.entry-content-editor) .side-link:hover{background:var(--navhover);color:#fff}:where(.entry-content-editor) .side-link.active{background:#292a2d;color:#fff;font-weight:700}:where(.entry-content-editor) .side-link.active:before{content:"";position:absolute;inset:0 auto 0 0;width:3px;background:#bcb5ff}:where(.entry-content-editor) [data-theme="rose"] .side-link{border-radius:10px}:where(.entry-content-editor) [data-theme="rose"] .side-link.active{background:#1b1b20}:where(.entry-content-editor) [data-theme="rose"] .side-link.active:before{top:7px;bottom:7px;border-radius:4px;background:var(--accent)}:where(.entry-content-editor) .side-link em{margin-left:auto;font:10px ui-monospace,Consolas,monospace;color:#868993;font-style:normal}:where(.entry-content-editor) .side-bottom{padding:14px;border-top:1px solid var(--navborder)}:where(.entry-content-editor) .side-site{padding:11px;border:1px solid #34383c;display:flex;gap:9px;align-items:center;color:#e8e8e8}:where(.entry-content-editor) .side-site b{font-size:10px}:where(.entry-content-editor) .side-site small{display:block;font-size:10px;color:#9397a0;margin-top:3px}:where(.entry-content-editor) [data-theme="rose"] .side-site{border-radius:11px;background:#121216}:where(.entry-content-editor) .side-footer{display:flex;justify-content:space-between;align-items:center;margin-top:12px;font-size:9px;letter-spacing:.09em;color:#777d83}:where(.entry-content-editor) .side-footer a{padding:5px;color:#b1b3bd}:where(.entry-content-editor) .main{min-width:0;min-height:100vh;display:flex;flex-direction:column}:where(.entry-content-editor) .top{height:60px;display:flex;align-items:center;gap:11px;padding:0 22px;background:var(--surface);border-bottom:1px solid var(--border);flex:none}:where(.entry-content-editor) .breadcrumbs{display:flex;gap:9px;align-items:center;color:var(--muted);font-size:11px;min-width:0;white-space:nowrap}:where(.entry-content-editor) .breadcrumbs strong{color:var(--text)}:where(.entry-content-editor) .breadcrumbs .sep{color:var(--dim)}:where(.entry-content-editor) .spacer{flex:1}:where(.entry-content-editor) .top-live{display:flex;align-items:center;gap:7px;color:var(--muted);font-size:10px;white-space:nowrap}:where(.entry-content-editor) .dot{display:inline-block;background:var(--positive);width:7px;height:7px;border-radius:50%;flex:none}:where(.entry-content-editor) .user-pill{height:29px;width:29px;display:grid;place-items:center;border:0;background:var(--text);color:var(--surface);border-radius:50%;font-size:10px;font-weight:700}:where(.entry-content-editor) [data-theme="rose"] .user-pill{background:linear-gradient(135deg,#f56790,#ac54d9);color:white}:where(.entry-content-editor) .top-icon{border:1px solid transparent;background:transparent;color:var(--muted);height:30px;width:30px;display:grid;place-items:center}:where(.entry-content-editor) .top-icon:hover{border-color:var(--border);background:var(--surface2)}:where(.entry-content-editor) .mobile-menu{display:none}:where(.entry-content-editor) .head{min-width:0;display:flex;align-items:center;gap:15px;justify-content:space-between;padding:18px 22px 16px;border-bottom:1px solid var(--border)}:where(.entry-content-editor) .head-main{min-width:0}:where(.entry-content-editor) .eyebrow{font:700 9px ui-monospace,Consolas,monospace;letter-spacing:.10em;color:var(--accent);text-transform:uppercase}:where(.entry-content-editor) .head h1{font-size:22px;font-weight:690;letter-spacing:-.05em;line-height:1.3;margin:3px 0}:where(.entry-content-editor) .head-meta{font-size:10px;color:var(--muted);display:flex;align-items:center;gap:10px;flex-wrap:wrap}:where(.entry-content-editor) .head-meta code{font-size:10px}:where(.entry-content-editor) .head-actions{display:flex;gap:8px;align-items:center;justify-content:flex-end;flex-wrap:wrap}:where(.entry-content-editor) .button{height:32px;border:1px solid var(--border);border-radius:var(--radius);display:inline-flex;align-items:center;justify-content:center;gap:7px;padding:0 12px;background:var(--surface);color:var(--text);font-size:11px;font-weight:650;white-space:nowrap}:where(.entry-content-editor) .button:hover{background:var(--surface2);border-color:var(--accent)}:where(.entry-content-editor) .button.primary{background:var(--accent);color:var(--accentText);border-color:var(--accent)}:where(.entry-content-editor) .button.primary:hover{filter:brightness(1.09)}:where(.entry-content-editor) .button.ghost{background:transparent}:where(.entry-content-editor) .button.small{height:27px;padding:0 8px;font-size:10px}:where(.entry-content-editor) .button.icon{width:30px;padding:0}:where(.entry-content-editor) .button.danger{color:var(--danger);border-color:var(--danger)}:where(.entry-content-editor) .toggle{display:flex;gap:2px;background:var(--surface2);border:1px solid var(--border);padding:3px;border-radius:var(--radius)}:where(.entry-content-editor) .toggle button{height:27px;border:0;color:var(--muted);background:transparent;padding:0 10px;font-size:10px;white-space:nowrap;border-radius:calc(var(--radius) - 2px)}:where(.entry-content-editor) .toggle button.active{background:var(--surface);color:var(--text);box-shadow:0 1px 5px #0001;font-weight:700}:where(.entry-content-editor) [data-theme="rose"] .toggle button.active{background:#2c202a;color:#ff82b6}:where(.entry-content-editor) .status{font-size:10px;display:inline-flex;align-items:center;gap:6px;padding:3px 7px;background:var(--surface3);color:var(--muted);border-radius:var(--pill);white-space:nowrap;font-weight:650}:where(.entry-content-editor) .status.changed{background:var(--accentSoft);color:var(--accent)}:where(.entry-content-editor) .status.good{background:var(--positiveBg);color:var(--positive)}:where(.entry-content-editor) .status.warn{background:var(--warningBg);color:var(--warning)}:where(.entry-content-editor) .status.error{background:var(--dangerBg);color:var(--danger)}:where(.entry-content-editor) .builder{display:grid;grid-template-columns:252px minmax(0,1fr) 302px;min-height:calc(100dvh - 165px);max-height:calc(100dvh - 165px);min-width:0}:where(.entry-content-editor) .pane{min-width:0;display:flex;flex-direction:column;overflow:hidden;background:var(--surface)}:where(.entry-content-editor) .treepane{border-right:1px solid var(--border)}:where(.entry-content-editor) .stagepane{background:var(--previewOuter)}:where(.entry-content-editor) .inspectpane{border-left:1px solid var(--border)}:where(.entry-content-editor) .pane-head{padding:13px 13px 10px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;gap:7px;flex:none}:where(.entry-content-editor) .pane-head b{font-size:12px;letter-spacing:-.01em}:where(.entry-content-editor) .pane-head small{font-size:10px;color:var(--muted)}:where(.entry-content-editor) .pane-scroll{overflow:auto;min-height:0;flex:1}:where(.entry-content-editor) .pane-foot{border-top:1px solid var(--border);padding:10px 13px;display:flex;align-items:center;gap:7px;justify-content:space-between;flex:none;color:var(--muted);font-size:10px}:where(.entry-content-editor) .tree-tabs{display:grid;grid-template-columns:1fr 1fr;padding:6px;gap:5px;border-bottom:1px solid var(--border)}:where(.entry-content-editor) .tree-tabs button{padding:8px 5px;border:0;color:var(--muted);background:transparent;font-size:10px;border-radius:var(--radius)}:where(.entry-content-editor) .tree-tabs button.active{background:var(--accentSoft);color:var(--accent);font-weight:720}:where(.entry-content-editor) .tree-group{padding:15px 11px 7px}:where(.entry-content-editor) .tree-caption{color:var(--muted);text-transform:uppercase;letter-spacing:.11em;font-size:9px;font-weight:700;margin:0 5px 8px}:where(.entry-content-editor) .tree-layout{padding:10px;background:var(--surface2);border:1px solid var(--border);display:flex;align-items:center;gap:9px;border-radius:var(--radius);margin-bottom:10px}:where(.entry-content-editor) .tree-layout b{font-size:11px}:where(.entry-content-editor) .tree-layout small{font-size:9px;display:block;color:var(--muted)}:where(.entry-content-editor) .tree-region{display:flex;align-items:center;justify-content:space-between;padding:7px 7px;color:var(--muted);font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.06em}:where(.entry-content-editor) .tree-region .plus{border:0;background:transparent;color:var(--accent);font-size:18px;height:22px;width:24px}:where(.entry-content-editor) .tree-item{width:100%;display:flex;align-items:center;gap:7px;background:transparent;border:1px solid transparent;color:var(--text);padding:9px 7px;text-align:left;min-width:0;position:relative;border-radius:var(--radius);margin:1px 0;cursor:pointer}:where(.entry-content-editor) .tree-item:hover{background:var(--surface2)}:where(.entry-content-editor) .tree-item.selected{border-color:var(--accent);background:var(--accentSoft)}:where(.entry-content-editor) .tree-item .node-icon{display:grid;place-items:center;height:25px;width:25px;flex:none;background:var(--surface3);border-radius:var(--radius);color:var(--muted)}:where(.entry-content-editor) .tree-item.selected .node-icon{color:var(--accent)}:where(.entry-content-editor) .tree-item .node-label{min-width:0;flex:1}:where(.entry-content-editor) .tree-item .node-label b{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:10px}:where(.entry-content-editor) .tree-item .node-label small{display:block;color:var(--muted);font:9px ui-monospace,Consolas,monospace;margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}:where(.entry-content-editor) .tree-item .node-badges{display:flex;gap:3px}:where(.entry-content-editor) .mini-dot{width:6px;height:6px;background:var(--accent);border-radius:50%;display:inline-block}:where(.entry-content-editor) .tree-item.fixed{opacity:.76}:where(.entry-content-editor) .tree-item.hidden{opacity:.47}:where(.entry-content-editor) .tree-item[draggable="true"]{cursor:grab}:where(.entry-content-editor) .tree-item.drag-over{border:1px dashed var(--accent)}:where(.entry-content-editor) .mapping-card{padding:11px;border-bottom:1px solid var(--border2)}:where(.entry-content-editor) .mapping-card button{width:100%;text-align:left;border:0;background:none;color:var(--text);font-weight:680;padding:2px 0}:where(.entry-content-editor) .mapping-card small{color:var(--muted);font-size:10px;display:block;margin:3px 0 6px}:where(.entry-content-editor) .map-route{display:flex;align-items:center;gap:4px;flex-wrap:wrap;color:var(--muted);font:9px ui-monospace,Consolas,monospace}:where(.entry-content-editor) .map-route span{padding:3px 5px;background:var(--surface2);border:1px solid var(--border);border-radius:var(--radius)}:where(.entry-content-editor) .mapping-note{font-size:10px;color:var(--muted);padding:12px;line-height:1.6}:where(.entry-content-editor) .stage-toolbar{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:11px 13px;border-bottom:1px solid var(--border);background:var(--surface);flex:none}:where(.entry-content-editor) .stage-toolbar .meta{color:var(--muted);font-size:10px;display:flex;align-items:center;gap:7px}:where(.entry-content-editor) .stage-scroller{flex:1;overflow:auto;padding:22px 20px 40px;display:flex;align-items:start;justify-content:center;min-width:0}:where(.entry-content-editor) .preview-frame{width:100%;max-width:100%;height:720px;border:1px solid var(--border);background:white;box-shadow:var(--shadow);border-radius:var(--radius);display:block;transition:width .18s}:where(.entry-content-editor) .preview-frame.tablet{width:768px}:where(.entry-content-editor) .preview-frame.mobile{width:390px;height:740px}:where(.entry-content-editor) .stage-caption{font:9px ui-monospace,Consolas,monospace;color:var(--muted)}:where(.entry-content-editor) .notice{padding:11px;border-bottom:1px solid var(--border);color:var(--muted);font-size:10px;background:var(--surface2)}:where(.entry-content-editor) .notice strong{color:var(--text)}:where(.entry-content-editor) .panel-tabs{padding:9px 12px;display:flex;gap:5px;border-bottom:1px solid var(--border);flex:none}:where(.entry-content-editor) .panel-tabs button{border:0;background:transparent;color:var(--muted);padding:7px 10px;font-size:10px;border-radius:var(--radius)}:where(.entry-content-editor) .panel-tabs button.active{background:var(--accentSoft);color:var(--accent);font-weight:750}:where(.entry-content-editor) .inspect-scroll{padding:15px 14px 30px;overflow:auto;min-height:0;flex:1}:where(.entry-content-editor) .inspect-title{display:flex;justify-content:space-between;align-items:start;margin-bottom:15px;gap:8px}:where(.entry-content-editor) .inspect-title h3{font-size:15px;letter-spacing:-.025em;line-height:1.35}:where(.entry-content-editor) .inspect-title code{display:block;font-size:10px;color:var(--muted);margin-top:5px;overflow-wrap:anywhere}:where(.entry-content-editor) .field{display:block;margin:0 0 15px}:where(.entry-content-editor) .field > span{display:flex;align-items:center;justify-content:space-between;font-size:10px;color:var(--muted);font-weight:680;margin-bottom:6px}:where(.entry-content-editor) .field input,:where(.entry-content-editor) .field textarea,:where(.entry-content-editor) .field select{width:100%;background:var(--surface2);border:1px solid var(--border);border-radius:var(--radius);color:var(--text);padding:8px 9px;outline:0;min-width:0}:where(.entry-content-editor) .field input,:where(.entry-content-editor) .field select{height:34px}:where(.entry-content-editor) .field textarea{resize:vertical;min-height:64px;line-height:1.5}:where(.entry-content-editor) .field input:focus,:where(.entry-content-editor) .field select:focus,:where(.entry-content-editor) .field textarea:focus{border-color:var(--focus);box-shadow:0 0 0 2px color-mix(in srgb,var(--accent) 12%,transparent)}:where(.entry-content-editor) .field small{display:block;margin-top:5px;color:var(--dim);font-size:10px;line-height:1.4}:where(.entry-content-editor) .field .inline-source{display:flex;gap:5px}:where(.entry-content-editor) .field .inline-source select{flex:0 0 104px;width:104px;font-size:10px}:where(.entry-content-editor) .field .inline-source input{min-width:0;flex:1}:where(.entry-content-editor) .field input[disabled],:where(.entry-content-editor) .field textarea[disabled]{opacity:.64;cursor:not-allowed}:where(.entry-content-editor) .field input[type="checkbox"]{height:15px;width:15px;accent-color:var(--accent)}:where(.entry-content-editor) .field .checkrow{display:flex;align-items:center;gap:9px;color:var(--text);font-size:11px}:where(.entry-content-editor) .divider{height:1px;background:var(--border);margin:14px 0}:where(.entry-content-editor) .actionrow{display:flex;gap:6px;flex-wrap:wrap;margin:12px 0 5px}:where(.entry-content-editor) .actionrow .button{flex:1}:where(.entry-content-editor) .helper{font-size:10px;color:var(--muted);line-height:1.6}:where(.entry-content-editor) .helper code{color:var(--accent)}:where(.entry-content-editor) .source-line{display:flex;gap:5px;flex-wrap:wrap;margin:7px 0}:where(.entry-content-editor) .source-line span{font:9px ui-monospace,Consolas,monospace;background:var(--surface2);border:1px solid var(--border);padding:5px;border-radius:var(--radius)}:where(.entry-content-editor) .inline-alert{margin:9px 0;padding:10px 11px;background:var(--warningBg);color:var(--warning);font-size:10px;border-left:2px solid currentColor}:where(.entry-content-editor) .inline-alert.error{color:var(--danger);background:var(--dangerBg)}:where(.entry-content-editor) .small-title{font-size:10px;text-transform:uppercase;letter-spacing:.10em;color:var(--muted);font-weight:750;margin:18px 0 9px}:where(.entry-content-editor) .codebox{font:10px/1.7 ui-monospace,Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere;padding:12px;background:var(--surface2);border:1px solid var(--border);color:var(--text);border-radius:var(--radius)}:where(.entry-content-editor) .mobilebar{display:none}:where(.entry-content-editor) .modal-back{position:fixed;inset:0;z-index:100;background:#08080bb2;display:flex;align-items:center;justify-content:center;padding:16px}:where(.entry-content-editor) .modal{width:min(560px,100%);max-height:90dvh;overflow:auto;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:0 28px 80px #0005}:where(.entry-content-editor) .modal-head{padding:18px 19px;border-bottom:1px solid var(--border)}:where(.entry-content-editor) .modal-head h2{font-size:18px;letter-spacing:-.03em}:where(.entry-content-editor) .modal-head p{font-size:11px;color:var(--muted);margin-top:5px}:where(.entry-content-editor) .modal-body{padding:17px 19px;max-height:55dvh;overflow:auto}:where(.entry-content-editor) .modal-foot{border-top:1px solid var(--border);padding:12px 19px;display:flex;justify-content:flex-end;gap:8px;flex-wrap:wrap}:where(.entry-content-editor) .modal .field{margin:0 0 13px}:where(.entry-content-editor) .catalog-search{width:100%;padding:10px;background:var(--surface2);color:var(--text);border:1px solid var(--border);border-radius:var(--radius);margin-bottom:10px}:where(.entry-content-editor) .catalog-list{display:grid;gap:6px}:where(.entry-content-editor) .catalog-item{display:flex;align-items:center;gap:12px;width:100%;background:var(--surface2);border:1px solid var(--border);text-align:left;border-radius:var(--radius);padding:11px;color:var(--text)}:where(.entry-content-editor) .catalog-item:hover{border-color:var(--accent)}:where(.entry-content-editor) .catalog-item b{display:block;font-size:11px}:where(.entry-content-editor) .catalog-item small{font-size:10px;display:block;color:var(--muted);margin-top:2px}:where(.entry-content-editor) .catalog-item svg{color:var(--accent);width:18px;height:18px}:where(.entry-content-editor) .catalog-item span{flex:1}:where(.entry-content-editor) .catalog-group{display:flex;gap:5px;margin-bottom:10px;flex-wrap:wrap}:where(.entry-content-editor) .catalog-group button{font-size:10px;border:1px solid var(--border);background:var(--surface2);color:var(--muted);border-radius:var(--radius);padding:5px 9px}:where(.entry-content-editor) .catalog-group button.active{background:var(--accentSoft);color:var(--accent);border-color:var(--accent)}:where(.entry-content-editor) #toast{position:fixed;right:18px;bottom:17px;z-index:130;background:var(--surface);border:1px solid var(--accent);border-radius:var(--radius);padding:12px 15px;color:var(--text);max-width:360px;box-shadow:var(--shadow);display:none;font-size:11px}:where(.entry-content-editor) .mobile-cover{display:none}:where(.entry-content-editor) .muted{color:var(--muted)}:where(.entry-content-editor) .mono{font-family:ui-monospace,Consolas,monospace}:where(.entry-content-editor) .empty{padding:26px 15px;text-align:center;color:var(--muted);font-size:11px}:where(.entry-content-editor) .empty b{display:block;color:var(--text);margin-bottom:4px}
+@media(max-width:1380px){:where(.entry-content-editor) .layout{grid-template-columns:205px minmax(0,1fr)}:where(.entry-content-editor) .builder{grid-template-columns:233px minmax(0,1fr) 283px}:where(.entry-content-editor) .head,:where(.entry-content-editor) .top{padding-left:16px;padding-right:16px}:where(.entry-content-editor) .head h1{font-size:20px}}
+@media(max-width:1160px){:where(.entry-content-editor) .layout{grid-template-columns:64px minmax(0,1fr)}:where(.entry-content-editor) .side-brand{justify-content:center;padding:10px}:where(.entry-content-editor) .brand-logo{width:34px;height:34px}:where(.entry-content-editor) .brand-copy,:where(.entry-content-editor) .side-section,:where(.entry-content-editor) .side-link span,:where(.entry-content-editor) .side-link em,:where(.entry-content-editor) .side-bottom .side-site,:where(.entry-content-editor) .side-footer small{display:none}:where(.entry-content-editor) .side-nav{padding:0 6px}:where(.entry-content-editor) .side-link{justify-content:center;padding:0}:where(.entry-content-editor) .side-footer{justify-content:center}:where(.entry-content-editor) .builder{grid-template-columns:226px minmax(0,1fr) 277px}}
+@media(max-width:960px){:where(.entry-content-editor) .builder{grid-template-columns:218px minmax(0,1fr);max-height:none;min-height:calc(100vh - 165px);grid-template-areas:"tree stage" "inspect inspect"}:where(.entry-content-editor) .treepane{grid-area:tree;min-height:650px;max-height:820px}:where(.entry-content-editor) .stagepane{grid-area:stage;min-height:650px;max-height:820px}:where(.entry-content-editor) .inspectpane{grid-area:inspect;min-height:0;overflow:visible;max-height:none;border:0;border-top:1px solid var(--border)}:where(.entry-content-editor) .inspect-scroll{max-width:750px;width:100%;padding:15px 20px}:where(.entry-content-editor) .pane-scroll{max-height:760px}:where(.entry-content-editor) .stage-scroller{min-height:0}:where(.entry-content-editor) .preview-frame{height:610px}:where(.entry-content-editor) .head{align-items:flex-start}:where(.entry-content-editor) .head-actions{max-width:400px}:where(.entry-content-editor) .inspectpane .pane-foot{display:none}}
+@media(max-width:700px){:where(.entry-content-editor) .layout{display:block}:where(.entry-content-editor) .side{position:fixed;left:0;top:0;bottom:0;width:230px;transform:translateX(-110%);transition:transform .2s;box-shadow:18px 0 55px #0006}:where(.entry-content-editor) .side.open{transform:translateX(0)}:where(.entry-content-editor) .mobile-cover.show{position:fixed;inset:0;background:#0009;display:block;z-index:11}:where(.entry-content-editor) .side .brand-copy,:where(.entry-content-editor) .side .side-section,:where(.entry-content-editor) .side .side-link span,:where(.entry-content-editor) .side .side-link em,:where(.entry-content-editor) .side .side-bottom .side-site,:where(.entry-content-editor) .side .side-footer small{display:block}:where(.entry-content-editor) .side .side-link{justify-content:flex-start;padding:0 11px}:where(.entry-content-editor) .mobile-menu{display:grid}:where(.entry-content-editor) .top{height:49px;padding:0 12px}:where(.entry-content-editor) .head{padding:13px 13px 14px;display:block}:where(.entry-content-editor) .head h1{font-size:21px}:where(.entry-content-editor) .head-actions{margin-top:12px;max-width:none;justify-content:flex-start}:where(.entry-content-editor) .head-actions .button{height:30px}:where(.entry-content-editor) .builder{display:flex;flex-direction:column;max-height:none;min-height:0}:where(.entry-content-editor) .pane{overflow:visible;border-left:0;border-right:0}:where(.entry-content-editor) .stagepane{order:0;min-height:0;max-height:none}:where(.entry-content-editor) .treepane{order:1;min-height:0;max-height:none;border-bottom:1px solid var(--border)}:where(.entry-content-editor) .inspectpane{order:2;min-height:0}:where(.entry-content-editor) .stage-scroller{min-height:0;overflow:auto;padding:14px 14px 20px;display:block}:where(.entry-content-editor) .preview-frame{height:440px;width:100%!important;max-width:100%;margin:auto}:where(.entry-content-editor) .preview-frame.mobile{width:390px!important;max-width:100%;height:480px}:where(.entry-content-editor) .stage-toolbar{flex-wrap:wrap;gap:5px}:where(.entry-content-editor) .treepane .pane-scroll,:where(.entry-content-editor) .inspectpane .pane-scroll,:where(.entry-content-editor) .inspect-scroll{overflow:visible;max-height:none}:where(.entry-content-editor) .tree-group{padding-bottom:15px}:where(.entry-content-editor) .tree-item{padding:12px 9px}:where(.entry-content-editor) .pane-head{padding:13px}:where(.entry-content-editor) .inspect-scroll{max-width:100%}:where(.entry-content-editor) .mobilebar{display:flex;padding:7px 12px;gap:6px;border-bottom:1px solid var(--border);background:var(--surface2)}:where(.entry-content-editor) .mobilebar button{flex:1;min-height:31px;border:1px solid var(--border);background:var(--surface);color:var(--text);border-radius:var(--radius)}:where(.entry-content-editor) .top-live{display:none}:where(.entry-content-editor) .breadcrumbs{overflow:hidden;text-overflow:ellipsis}:where(.entry-content-editor) .breadcrumbs .truncate{display:none}}
+@media(max-width:390px){:where(.entry-content-editor) .head-actions .toggle{width:100%}:where(.entry-content-editor) .head-actions .button{flex:1}:where(.entry-content-editor) .stage-toolbar .meta{width:100%}:where(.entry-content-editor) .toggle button{padding:0 7px}:where(.entry-content-editor) .head-meta code{overflow:hidden;text-overflow:ellipsis;max-width:225px}:where(.entry-content-editor) .pane-head b{font-size:11px}}
+/* Stage 2.3 — source mapping, data explorer and reverse dependencies. */
+:where(.entry-content-editor) .mapping-metrics{display:flex;gap:5px;flex-wrap:wrap;margin:11px 0}
+:where(.entry-content-editor) .mapping-metrics span{display:inline-flex;padding:4px 7px;border:1px solid var(--border);background:var(--surface2);font:10px ui-monospace,Consolas,monospace;color:var(--muted);border-radius:var(--pill)}
+:where(.entry-content-editor) .mapping-metrics .has-issues{color:var(--warning);background:var(--warningBg);border-color:color-mix(in srgb,var(--warning) 30%,var(--border))}
+:where(.entry-content-editor) .mapping-card{padding:11px 10px 13px;margin:0 5px 7px;border:1px solid var(--border);background:var(--surface);border-radius:var(--radius)}
+:where(.entry-content-editor) .mapping-card.map-selected{border-color:var(--accent);background:color-mix(in srgb,var(--accentSoft) 34%,var(--surface))}
+:where(.entry-content-editor) .mapping-card .map-block-title{display:flex;align-items:flex-start;gap:7px;text-align:left;color:var(--text);padding-bottom:8px;min-width:0}
+:where(.entry-content-editor) .mapping-card .map-block-title > svg{width:14px;height:14px;color:var(--accent);flex:none;margin-top:2px}
+:where(.entry-content-editor) .mapping-card .map-block-title span{min-width:0}
+:where(.entry-content-editor) .mapping-card .map-block-title b{display:block;overflow-wrap:anywhere}
+:where(.entry-content-editor) .mapping-card .map-block-title small{font:9px/1.5 ui-monospace,Consolas,monospace;color:var(--muted);overflow-wrap:anywhere}
+:where(.entry-content-editor) .map-edge{display:grid;grid-template-columns:minmax(0,65px) auto minmax(0,1fr) 19px;align-items:center;gap:5px;font-size:10px;padding:7px 0;border-top:1px solid var(--border2)}
+:where(.entry-content-editor) .map-edge .mono{color:var(--muted);overflow:hidden;text-overflow:ellipsis}
+:where(.entry-content-editor) .map-edge .edge-type{font-size:9px;font-weight:700;color:var(--accent);padding:1px 5px;border-radius:var(--pill);background:var(--accentSoft)}
+:where(.entry-content-editor) .map-edge .edge-type.error{color:var(--danger);background:var(--dangerBg)}
+:where(.entry-content-editor) .map-edge .edge-value{color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,Consolas,monospace;font-size:9px}
+:where(.entry-content-editor) .map-edge button{border:0;background:none;color:var(--accent);padding:0;width:19px;height:20px}
+:where(.entry-content-editor) .map-issue{color:var(--danger);font-size:9px;line-height:1.45;display:flex;align-items:start;gap:5px;padding-top:5px;overflow-wrap:anywhere}
+:where(.entry-content-editor) .map-issue svg{width:11px;height:11px;flex:none}
+:where(.entry-content-editor) .tree-error-dot{display:grid;place-items:center;font-size:9px;font-weight:900;height:16px;width:16px;background:var(--dangerBg);color:var(--danger);border-radius:50%}
+:where(.entry-content-editor) .picker-current{display:flex;align-items:center;gap:5px;background:var(--surface2);border:1px solid var(--border);border-radius:var(--radius);padding:5px 5px 5px 9px;min-width:0}
+:where(.entry-content-editor) .picker-current .mono{font-size:10px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1}
+:where(.entry-content-editor) .mini-action{border:1px solid var(--border);background:var(--surface2);border-radius:var(--pill);color:var(--muted);display:inline-flex;align-items:center;justify-content:center;gap:5px;padding:6px 8px;font-size:10px;font-weight:600;min-height:27px;white-space:nowrap}
+:where(.entry-content-editor) .mini-action svg{height:12px;width:12px}
+:where(.entry-content-editor) .mini-action:hover{color:var(--accent);border-color:var(--accent);background:var(--accentSoft)}
+:where(.entry-content-editor) .mini-action.primary-action{background:var(--accentSoft);color:var(--accent);border-color:color-mix(in srgb,var(--accent) 32%,var(--border))}
+:where(.entry-content-editor) .tiny-source{display:inline-flex;align-items:center;gap:4px;background:var(--surface2);color:var(--muted);border:1px solid var(--border);border-radius:var(--pill);font-size:9px;max-width:158px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:3px 5px}
+:where(.entry-content-editor) .tiny-source.bound{color:var(--accent);border-color:color-mix(in srgb,var(--accent) 33%,var(--border));background:var(--accentSoft)}
+:where(.entry-content-editor) .tiny-source svg{width:10px;height:10px}
+:where(.entry-content-editor) .field-issue{padding:7px 8px;display:flex;gap:5px;align-items:flex-start;font:10px/1.5 ui-monospace,Consolas,monospace;color:var(--warning);background:var(--warningBg);margin-top:7px;border-left:2px solid currentColor;overflow-wrap:anywhere}
+:where(.entry-content-editor) .field-issue svg{width:13px;height:13px;flex:none}
+:where(.entry-content-editor) .field-issue.error{color:var(--danger);background:var(--dangerBg)}
+:where(.entry-content-editor) .binding-entry{border:1px solid var(--border);background:var(--surface2);border-radius:var(--radius);padding:11px;margin:0 0 10px}
+:where(.entry-content-editor) .binding-top,:where(.entry-content-editor) .binding-actions{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}
+:where(.entry-content-editor) .binding-top b{font-size:11px}
+:where(.entry-content-editor) .source-type{font:9px ui-monospace,Consolas,monospace;padding:3px 6px;color:var(--accent);background:var(--accentSoft);border:1px solid var(--border);border-radius:var(--pill)}
+:where(.entry-content-editor) .source-type.error{color:var(--danger);background:var(--dangerBg)}
+:where(.entry-content-editor) .source-type.warn{color:var(--warning);background:var(--warningBg)}
+:where(.entry-content-editor) .binding-key{margin:8px 0;color:var(--muted);font:9px/1.5 ui-monospace,Consolas,monospace;overflow-wrap:anywhere}
+:where(.entry-content-editor) .binding-result{color:var(--text);display:flex;align-items:flex-start;gap:7px;font-size:11px;line-height:1.45;overflow-wrap:anywhere;margin:8px 0}
+:where(.entry-content-editor) .binding-result svg{color:var(--accent);width:13px;height:13px;flex:none;margin-top:2px}
+:where(.entry-content-editor) .binding-actions{justify-content:flex-start;gap:5px;margin-top:10px}
+:where(.entry-content-editor) .path-strip{display:flex;align-items:center;gap:3px;flex-wrap:wrap;font:9px ui-monospace,Consolas,monospace;color:var(--muted);padding:9px 7px;background:var(--surface2);border:1px solid var(--border);margin:0 0 16px;border-radius:var(--radius)}
+:where(.entry-content-editor) .path-strip span{overflow-wrap:anywhere}
+:where(.entry-content-editor) .picker-summary{padding:11px;display:flex;gap:7px;flex-wrap:wrap;align-items:center;border:1px solid var(--border);background:var(--surface2);border-radius:var(--radius);font:10px/1.5 ui-monospace,Consolas,monospace;margin-bottom:12px;overflow-wrap:anywhere}
+:where(.entry-content-editor) .picker-summary svg{width:15px;height:15px;color:var(--accent)}
+:where(.entry-content-editor) .choice-group{margin:14px 0 18px}
+:where(.entry-content-editor) .choice-label{font-size:10px;font-weight:750;color:var(--muted);display:flex;justify-content:space-between;text-transform:uppercase;letter-spacing:.06em;margin:10px 0 7px}
+:where(.entry-content-editor) .choice-item{width:100%;display:flex;align-items:center;gap:9px;text-align:left;color:var(--text);background:var(--surface2);border:1px solid var(--border);border-bottom:0;padding:10px;min-width:0}
+:where(.entry-content-editor) .choice-item:last-child{border-bottom:1px solid var(--border)}
+:where(.entry-content-editor) .choice-item:first-of-type{border-radius:var(--radius) var(--radius) 0 0}
+:where(.entry-content-editor) .choice-item:last-child{border-radius:0 0 var(--radius) var(--radius)}
+:where(.entry-content-editor) .choice-item:hover{background:var(--accentSoft);border-color:var(--accent)}
+:where(.entry-content-editor) .choice-item .choice-glyph{color:var(--accent);display:grid;place-items:center;flex:none;width:19px}
+:where(.entry-content-editor) .choice-item .choice-glyph svg{width:15px;height:15px}
+:where(.entry-content-editor) .choice-info{min-width:0;flex:1}
+:where(.entry-content-editor) .choice-info b{display:block;font-size:11px}
+:where(.entry-content-editor) .choice-info small{font-size:9px;color:var(--muted);display:block;overflow-wrap:anywhere}
+:where(.entry-content-editor) .choice-flag{border-radius:var(--pill);font-size:9px;color:var(--muted);border:1px solid var(--border);padding:3px 5px;flex:none}
+:where(.entry-content-editor) .choice-flag.bad{color:var(--danger);background:var(--dangerBg)}
+:where(.entry-content-editor) .choice-flag.warning{color:var(--warning);background:var(--warningBg)}
+:where(.entry-content-editor) .usage-summary{display:flex;gap:9px;align-items:center;margin-bottom:13px;overflow-wrap:anywhere}
+:where(.entry-content-editor) .usage-summary code{font-size:10px;color:var(--muted);overflow-wrap:anywhere}
+:where(.entry-content-editor) .usage-item{display:flex;align-items:center;gap:12px;justify-content:space-between;width:100%;background:var(--surface2);color:var(--text);border:1px solid var(--border);border-bottom:0;text-align:left;padding:10px;border-radius:0}
+:where(.entry-content-editor) .usage-item:last-of-type{border-bottom:1px solid var(--border)}
+:where(.entry-content-editor) .usage-item:hover{background:var(--accentSoft);color:var(--accent)}
+:where(.entry-content-editor) .usage-item span{min-width:0}
+:where(.entry-content-editor) .usage-item b{display:block;font-size:11px}
+:where(.entry-content-editor) .usage-item small{font:9px ui-monospace,Consolas,monospace;display:block;color:var(--muted);overflow-wrap:anywhere;margin-top:5px}
+:where(.entry-content-editor) .library-grid{display:grid;gap:0}
+:where(.entry-content-editor) .library-head{font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.08em;color:var(--accent);margin:15px 0 4px}
+:where(.entry-content-editor) .library-row{display:flex;align-items:center;justify-content:space-between;gap:9px;padding:9px 0;border-bottom:1px solid var(--border2)}
+:where(.entry-content-editor) .library-row b{font-size:10px;display:block}
+:where(.entry-content-editor) .library-row small{font-size:9px;display:block;color:var(--muted);overflow-wrap:anywhere}
+:where(.entry-content-editor) .library-row span{min-width:0}
+:where(.entry-content-editor) .library-row .mini-action{flex:none}
+@media(max-width:700px){:where(.entry-content-editor) .mapping-card{margin:0 10px 9px}:where(.entry-content-editor) .choice-item{padding:9px}:where(.entry-content-editor) .binding-entry{padding:12px}}
+:where(.entry-content-editor) .usage-entry{border:1px solid var(--border);border-bottom:0;background:var(--surface2);padding:9px 10px}
+:where(.entry-content-editor) .usage-entry:last-of-type{border-bottom:1px solid var(--border)}
+:where(.entry-content-editor) .usage-entry b{display:block;font-size:11px}
+:where(.entry-content-editor) .usage-entry small{display:block;margin-top:4px;color:var(--muted);font:9px ui-monospace,Consolas,monospace;overflow-wrap:anywhere}
+/* Stage 2.4 — live/workspace clarity, per-field QA, version comparisons. */
+:where(.entry-content-editor) .draft-hint{font:10px ui-monospace,Consolas,monospace;color:var(--muted)}
+:where(.entry-content-editor) .head-meta{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
+:where(.entry-content-editor) .tag-muted{font:9px ui-monospace,Consolas,monospace;color:var(--dim);text-transform:none;letter-spacing:0;margin-left:auto}
+:where(.entry-content-editor) .inspector-callout{font-size:10px;line-height:1.6;padding:10px 11px;background:var(--accentSoft);border-left:2px solid var(--accent);margin-bottom:13px;color:var(--text)}
+:where(.entry-content-editor) .serp-preview{margin:10px 0 18px;padding:13px;background:var(--surface2);border:1px solid var(--border);border-radius:var(--radius);font-size:11px;overflow-wrap:anywhere}
+:where(.entry-content-editor) .serp-url{color:var(--positive);font-size:10px;margin-bottom:4px}
+:where(.entry-content-editor) .serp-title{color:var(--accent);font-size:15px;font-weight:650;line-height:1.35;margin-bottom:5px}
+:where(.entry-content-editor) .serp-desc{color:var(--muted);font-size:11px}
+:where(.entry-content-editor) .markdown-preview{border:1px solid var(--border);background:var(--surface2);margin-top:10px;border-radius:var(--radius)}
+:where(.entry-content-editor) .markdown-preview summary{padding:10px 11px;cursor:pointer;color:var(--text);font-weight:650;font-size:10px}
+:where(.entry-content-editor) .markdown-render{padding:10px 12px;border-top:1px solid var(--border);font-size:11px;overflow-wrap:anywhere}
+:where(.entry-content-editor) .markdown-render h1{font-size:17px;margin-bottom:7px}:where(.entry-content-editor) .markdown-render h2{font-size:15px;margin-bottom:7px}:where(.entry-content-editor) .markdown-render h3{font-size:13px;margin-bottom:6px}:where(.entry-content-editor) .markdown-render p{margin:7px 0}:where(.entry-content-editor) .markdown-render ul{padding-left:20px}:where(.entry-content-editor) .markdown-render a{color:var(--accent);text-decoration:underline}
+:where(.entry-content-editor) .review-dialog,:where(.entry-content-editor) .compare-dialog{width:min(1020px,calc(100vw - 32px));max-width:100%;}
+:where(.entry-content-editor) .review-summary{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin-bottom:13px}
+:where(.entry-content-editor) .review-count{border:1px solid var(--border);background:var(--surface2);padding:12px;display:flex;flex-direction:column;gap:3px;border-radius:var(--radius)}
+:where(.entry-content-editor) .review-count b{font-size:24px;line-height:1.2;letter-spacing:-.04em}:where(.entry-content-editor) .review-count span{font-size:10px;color:var(--muted)}
+:where(.entry-content-editor) .review-count:first-child b{color:var(--danger)}:where(.entry-content-editor) .review-count:nth-child(2) b{color:var(--warning)}:where(.entry-content-editor) .review-count:nth-child(3) b{color:var(--accent)}
+:where(.entry-content-editor) .review-banner{padding:10px 12px;border-left:3px solid var(--positive);background:var(--positiveBg);font-size:11px;margin:8px 0 13px}
+:where(.entry-content-editor) .review-banner.danger{background:var(--dangerBg);border-color:var(--danger)}
+:where(.entry-content-editor) .review-filters{display:flex;gap:4px;flex-wrap:wrap;padding:4px;background:var(--surface2);border-radius:var(--radius);margin:12px 0}
+:where(.entry-content-editor) .review-filters button{border:1px solid transparent;background:transparent;color:var(--muted);padding:8px 10px;font-size:10px;border-radius:var(--pill);font-weight:650}
+:where(.entry-content-editor) .review-filters button.active{background:var(--surface);border-color:var(--border);color:var(--text)}
+:where(.entry-content-editor) .review-list{max-height:300px;overflow:auto;border:1px solid var(--border);border-radius:var(--radius)}
+:where(.entry-content-editor) .review-item{display:flex;align-items:center;width:100%;text-align:left;gap:10px;background:var(--surface);color:var(--text);padding:12px;border:0;border-bottom:1px solid var(--border2)}
+:where(.entry-content-editor) .review-item:last-child{border-bottom:0}:where(.entry-content-editor) .review-item:hover{background:var(--accentSoft)}
+:where(.entry-content-editor) .issue-label{font-size:9px;font-weight:800;padding:4px 6px;color:var(--warning);background:var(--warningBg);flex:none}
+:where(.entry-content-editor) .review-item.error .issue-label{color:var(--danger);background:var(--dangerBg)}
+:where(.entry-content-editor) .review-item span:nth-child(2){flex:1;min-width:0}
+:where(.entry-content-editor) .review-item b{font-size:11px;display:block;font-weight:600}
+:where(.entry-content-editor) .review-item small{display:block;color:var(--muted);margin-top:5px;font:9px/1.4 ui-monospace,Consolas,monospace;overflow-wrap:anywhere}
+:where(.entry-content-editor) .review-item svg{color:var(--accent)}
+:where(.entry-content-editor) .compare-meta{display:flex;gap:8px;flex-wrap:wrap;align-items:center;font-size:10px;color:var(--muted)}
+:where(.entry-content-editor) .compare-meta span{background:var(--surface2);border:1px solid var(--border);padding:6px 8px}
+:where(.entry-content-editor) .compare-meta b{color:var(--text)}
+:where(.entry-content-editor) .compare-table{border:1px solid var(--border);border-radius:var(--radius);max-height:350px;overflow:auto}
+:where(.entry-content-editor) .compare-label-head,:where(.entry-content-editor) .compare-line{display:grid;grid-template-columns:minmax(100px,.7fr) minmax(0,1fr) minmax(0,1fr);gap:8px;padding:10px;border-bottom:1px solid var(--border2);font-size:10px}
+:where(.entry-content-editor) .compare-label-head{background:var(--surface2);color:var(--muted);position:sticky;top:0;z-index:1}
+:where(.entry-content-editor) .compare-line:last-child{border-bottom:0}:where(.entry-content-editor) .compare-line code{font:10px ui-monospace,Consolas,monospace;color:var(--accent);overflow-wrap:anywhere}:where(.entry-content-editor) .compare-line span{line-height:1.5;overflow-wrap:anywhere;white-space:pre-wrap}:where(.entry-content-editor) .compare-line span:nth-child(2){color:var(--danger)}:where(.entry-content-editor) .compare-line span:nth-child(3){color:var(--positive)}
+:where(.entry-content-editor) .visual-compare{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:10px 0}
+:where(.entry-content-editor) .visual-compare>div{min-width:0}:where(.entry-content-editor) .visual-compare h3{font-size:11px;margin-bottom:8px;color:var(--muted)}
+:where(.entry-content-editor) .compare-mini{background:#f5f5f4;color:#20252d;border:1px solid #d8d9dc;font-family:ui-sans-serif,Arial,sans-serif;min-height:230px;overflow:hidden}
+:where(.entry-content-editor) .mini-header{display:flex;justify-content:space-between;background:white;border-bottom:1px solid #e2e3e5;padding:12px;font-weight:800;font-size:13px}:where(.entry-content-editor) .mini-header span{color:#c069a9}:where(.entry-content-editor) .mini-header small{font-size:9px;color:#848896}
+:where(.entry-content-editor) .mini-hero{background:#edf0f7;padding:22px 18px;min-height:100px}:where(.entry-content-editor) .mini-hero small{font-size:9px;color:#827aa0}:where(.entry-content-editor) .mini-hero strong{display:block;font-size:17px;line-height:1.2;max-width:300px;margin:8px 0;letter-spacing:-.04em}:where(.entry-content-editor) .mini-hero p{font-size:10px;line-height:1.5;color:#636b7c;max-width:310px}
+:where(.entry-content-editor) .mini-section{padding:14px 18px;border-bottom:1px solid #e2e3e5}:where(.entry-content-editor) .mini-section small{color:#898d99;display:block;font-size:9px}:where(.entry-content-editor) .mini-section b{display:block;font-size:13px;margin-top:5px;overflow-wrap:anywhere}
+@media(max-width:700px){:where(.entry-content-editor) .review-summary{grid-template-columns:repeat(2,minmax(0,1fr))}:where(.entry-content-editor) .visual-compare{grid-template-columns:1fr}:where(.entry-content-editor) .compare-label-head,:where(.entry-content-editor) .compare-line{grid-template-columns:minmax(0,.7fr) minmax(0,1fr) minmax(0,1fr);gap:5px;padding:8px 6px;font-size:9px}:where(.entry-content-editor) .review-item{padding:9px 7px;gap:6px}:where(.entry-content-editor) .issue-label{font-size:8px}:where(.entry-content-editor) .compare-mini{min-height:180px}:where(.entry-content-editor) .draft-hint{width:100%}}
+
+/* ━━━━━━━━━━━━━━━ Site Engine / Stage 3 · Expert ━━━━━━━━━━━━━━━ */
+:where(.entry-content-editor) .builder.expert-layout{grid-template-columns:218px minmax(0,1fr) 315px;min-height:calc(100dvh - 165px);max-height:calc(100dvh - 165px)}
+:where(.entry-content-editor) .expert-layout .treepane{background:var(--surface2)}
+:where(.entry-content-editor) .expert-layout .stagepane{min-height:0;background:var(--surface)}
+:where(.entry-content-editor) .expert-layout .inspectpane{background:var(--surface)}
+:where(.entry-content-editor) .expert-files{padding:9px 7px;overflow-y:auto}
+:where(.entry-content-editor) .expert-folder{display:flex;align-items:center;gap:7px;padding:16px 10px 9px;font:700 10px ui-monospace,Consolas,monospace;color:var(--muted)}
+:where(.entry-content-editor) .expert-folder svg{width:13px;height:13px;color:var(--accent)}
+:where(.entry-content-editor) .expert-folder small{margin-left:auto;font-size:9px;opacity:.75}
+:where(.entry-content-editor) .expert-file{display:flex;width:100%;border:1px solid transparent;align-items:center;gap:9px;min-height:40px;padding:7px 9px;text-align:left;color:var(--text);background:transparent;border-radius:var(--radius)}
+:where(.entry-content-editor) .expert-file svg{color:var(--muted);width:14px;height:14px}
+:where(.entry-content-editor) .expert-file span{min-width:0;display:block}:where(.entry-content-editor) .expert-file span b{font-size:10px;font-weight:700;display:block}:where(.entry-content-editor) .expert-file span small{font-size:9px;color:var(--muted);display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+:where(.entry-content-editor) .expert-file:hover{background:var(--surface3)}:where(.entry-content-editor) .expert-file.selected{background:var(--accentSoft);color:var(--accent);border-color:color-mix(in srgb,var(--accent) 40%,var(--border))}:where(.entry-content-editor) .expert-file.selected svg{color:var(--accent)}
+:where(.entry-content-editor) .expert-file.disabled-file{cursor:default;color:var(--dim);font-size:10px;opacity:.8}:where(.entry-content-editor) .expert-file.disabled-file:hover{background:transparent}:where(.entry-content-editor) .expert-tree-note{font-size:10px;line-height:1.65;color:var(--muted);padding:11px;margin:21px 5px;border:1px solid var(--border);background:var(--surface)}
+:where(.entry-content-editor) .expert-tree-note b{color:var(--text)}
+:where(.entry-content-editor) .expert-editor-header{height:40px;display:flex;align-items:center;justify-content:space-between;gap:10px;border-bottom:1px solid var(--border);padding:0 12px;background:var(--surface2);font-size:10px;color:var(--muted);flex:none}
+:where(.entry-content-editor) .expert-editor-header .filetab{align-items:center;display:flex;gap:8px;max-width:100%;min-width:0;padding:0 10px;height:100%;border-bottom:2px solid var(--accent);background:var(--surface)}
+:where(.entry-content-editor) .expert-editor-header .filetab svg{color:var(--accent);height:14px;width:14px}:where(.entry-content-editor) .expert-editor-header .filetab b{color:var(--text);font:650 10px ui-monospace,Consolas,monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+:where(.entry-content-editor) .file-edited{color:var(--warning);font-size:13px}:where(.entry-content-editor) .expert-editor-header .muted{white-space:nowrap;font-size:9px;color:var(--muted)}
+:where(.entry-content-editor) .expert-tools{display:flex;align-items:center;flex-wrap:wrap;gap:7px;padding:9px 11px;border-bottom:1px solid var(--border);background:var(--surface);flex:none;min-height:45px}
+:where(.entry-content-editor) .expert-tools>.mono{font-size:9px;color:var(--dim);margin-right:auto}:where(.entry-content-editor) .expert-find{display:flex;gap:3px}:where(.entry-content-editor) .expert-find input{width:118px;min-width:0;height:28px;padding:0 7px;border:1px solid var(--border);color:var(--text);background:var(--surface2);border-radius:var(--radius);font-size:10px}
+:where(.entry-content-editor) .expert-codebox{min-height:300px;flex:1;display:flex;overflow:hidden;position:relative;background:var(--surface)}
+:where(.entry-content-editor) .expert-codebox:focus-within{box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--accent) 32%,transparent)}
+:where(.entry-content-editor) .expert-gutter{flex:none;margin:0;width:44px;overflow:hidden;padding:13px 9px 40px 7px;border-right:1px solid var(--border);background:var(--surface2);color:var(--dim);font:11.5px/19px ui-monospace,SFMono-Regular,Consolas,monospace;text-align:right;white-space:pre;user-select:none;tab-size:2}
+:where(.entry-content-editor) .expert-codewrap{min-width:0;min-height:0;flex:1;position:relative;overflow:hidden}
+:where(.entry-content-editor) .expert-highlighter,:where(.entry-content-editor) .expert-textarea{position:absolute;inset:0;margin:0;border:0;border-radius:0;padding:13px 14px 40px;width:100%;height:100%;overflow:auto;white-space:pre;word-wrap:normal;overflow-wrap:normal;tab-size:2;letter-spacing:0;font:11.5px/19px ui-monospace,SFMono-Regular,Consolas,Monaco,monospace}
+:where(.entry-content-editor) .expert-highlighter{z-index:0;pointer-events:none;scrollbar-width:none;color:var(--text);background:transparent;white-space:pre}
+:where(.entry-content-editor) .expert-highlighter::-webkit-scrollbar{display:none}
+:where(.entry-content-editor) .expert-textarea{z-index:1;resize:none;background:transparent;color:transparent;caret-color:var(--text);-webkit-text-fill-color:transparent;outline:none;scrollbar-color:var(--border) transparent}
+:where(.entry-content-editor) .expert-textarea::selection{background:color-mix(in srgb,var(--accent) 30%,transparent);-webkit-text-fill-color:transparent}
+:where(.entry-content-editor) .expert-textarea:focus-visible{outline:none}
+:where(.entry-content-editor) .tok-key{color:var(--accent);font-weight:650}:where(.entry-content-editor) .tok-punct{color:var(--muted)}:where(.entry-content-editor) .tok-value{color:var(--text)}:where(.entry-content-editor) .tok-atom{color:var(--positive)}:where(.entry-content-editor) .tok-rule{color:var(--warning)}:where(.entry-content-editor) .tok-comment{color:var(--dim);font-style:italic}:where(.entry-content-editor) .tok-md{color:var(--text)}
+:where(.entry-content-editor) .expert-statusbar{height:29px;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:0 13px;color:var(--muted);background:var(--surface2);border-top:1px solid var(--border);flex:none;font:9px ui-monospace,Consolas,monospace;white-space:nowrap}
+:where(.entry-content-editor) .expert-statusbar #expert-source-state{overflow:hidden;text-overflow:ellipsis}:where(.entry-content-editor) .expert-status-invalid{color:var(--danger)}:where(.entry-content-editor) .expert-status-unapplied{color:var(--warning)}:where(.entry-content-editor) .expert-status-good{color:var(--positive)}
+:where(.entry-content-editor) .expert-side-scroll{overflow-y:auto;overflow-x:hidden;min-height:0;flex:1;padding:11px;display:flex;flex-direction:column;gap:11px}
+:where(.entry-content-editor) .expert-side-top{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:6px}
+:where(.entry-content-editor) .expert-mini-preview{height:205px;border:1px solid var(--border);background:var(--previewOuter);border-radius:var(--radius);overflow:hidden;flex:none}
+:where(.entry-content-editor) .expert-mini-preview iframe{display:block;height:100%;width:100%;border:0;background:#fff}
+:where(.entry-content-editor) .expert-summary{display:flex;align-items:center;justify-content:space-between;gap:8px;border-bottom:1px solid var(--border);padding:6px 0 10px;font-size:11px}
+:where(.entry-content-editor) .expert-summary #expert-validation-pip{font-size:9px;color:var(--positive)}:where(.entry-content-editor) .expert-summary #expert-validation-pip.alert{color:var(--danger)}
+:where(.entry-content-editor) .expert-issue{min-height:40px}:where(.entry-content-editor) .expert-ok{padding:10px;border-left:2px solid var(--positive);background:var(--positiveBg);font-size:10px;color:var(--positive);line-height:1.5}
+:where(.entry-content-editor) .expert-error{padding:10px;border-left:2px solid var(--danger);background:var(--dangerBg);color:var(--danger);font-size:10px;display:flex;flex-direction:column;align-items:start;gap:5px;line-height:1.4}
+:where(.entry-content-editor) .expert-error code{overflow-wrap:anywhere}:where(.entry-content-editor) .expert-error .mini-action{margin-top:5px}
+:where(.entry-content-editor) .expert-info{display:grid;gap:0;background:var(--surface2);padding:3px 10px;border:1px solid var(--border)}:where(.entry-content-editor) .expert-info>div{display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap;padding:8px 0;border-bottom:1px solid var(--border2);color:var(--muted);font-size:10px}:where(.entry-content-editor) .expert-info>div:last-child{border:0}:where(.entry-content-editor) .expert-info code{color:var(--text);overflow-wrap:anywhere}
+:where(.entry-content-editor) .expert-side-actions{display:flex;flex-wrap:wrap;gap:6px}:where(.entry-content-editor) .expert-note{border:1px solid var(--border);background:var(--surface2);padding:11px}:where(.entry-content-editor) .expert-note b{font-size:10px}:where(.entry-content-editor) .expert-note p{margin-top:6px;font-size:10px;line-height:1.65;color:var(--muted)}
+:where(.entry-content-editor) .expert-publish-issues{font-size:10px;color:var(--muted)}:where(.entry-content-editor) .expert-publish-issues>b{color:var(--text)}:where(.entry-content-editor) .expert-publish-issues p{margin-top:10px}:where(.entry-content-editor) .expert-publish-line{display:flex;gap:7px;padding:7px 0;border-bottom:1px solid var(--border2);line-height:1.4}:where(.entry-content-editor) .expert-publish-line svg{width:12px;height:12px;flex:none;color:var(--warning)}:where(.entry-content-editor) .expert-publish-line.error svg{color:var(--danger)}
+:where(.entry-content-editor) .expert-diff-dialog{width:min(940px,100%)}:where(.entry-content-editor) .expert-diff{overflow:auto;max-height:min(60dvh,650px);border:1px solid var(--border);background:var(--surface2);margin-top:10px}
+:where(.entry-content-editor) .diff-line{display:grid;grid-template-columns:35px 35px minmax(0,1fr);min-width:510px;font:10px/1.55 ui-monospace,Consolas,monospace}:where(.entry-content-editor) .diff-line>span{color:var(--dim);border-right:1px solid var(--border);padding:1px 7px;text-align:right;user-select:none}:where(.entry-content-editor) .diff-line code{white-space:pre;min-width:0;overflow:visible;padding:1px 8px;color:var(--text)}:where(.entry-content-editor) .diff-line.add{background:var(--positiveBg)}:where(.entry-content-editor) .diff-line.remove{background:var(--dangerBg)}:where(.entry-content-editor) .diff-line.add code{color:var(--positive)}:where(.entry-content-editor) .diff-line.remove code{color:var(--danger)}
+:where(.entry-content-editor) .expert-conflict-dialog{width:min(760px,100%)}:where(.entry-content-editor) .expert-conflict-meta{display:flex;gap:12px;flex-wrap:wrap;justify-content:space-between;border:1px solid var(--border);background:var(--surface2);padding:10px;margin-bottom:13px;font-size:11px}:where(.entry-content-editor) .expert-conflict-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:14px}:where(.entry-content-editor) .expert-conflict-grid section{padding:13px;border:1px solid var(--border);background:var(--surface2);min-width:0;display:flex;flex-direction:column;gap:8px}:where(.entry-content-editor) .expert-conflict-grid section:first-child{border-top:3px solid var(--accent)}:where(.entry-content-editor) .expert-conflict-grid section:last-child{border-top:3px solid var(--warning)}:where(.entry-content-editor) .expert-conflict-grid h3{font-size:12px}:where(.entry-content-editor) .expert-conflict-grid p{font-size:10px}:where(.entry-content-editor) .expert-conflict-grid code,:where(.entry-content-editor) .expert-conflict-grid small{font-size:10px;color:var(--muted);overflow-wrap:anywhere}
+@media(max-width:1380px){:where(.entry-content-editor) .builder.expert-layout{grid-template-columns:195px minmax(0,1fr) 282px}:where(.entry-content-editor) .expert-tools>.mono{display:none}}
+@media(max-width:1050px){:where(.entry-content-editor) .builder.expert-layout{grid-template-columns:190px minmax(0,1fr);grid-template-areas:"tree stage" "inspect inspect";max-height:none;min-height:calc(100dvh - 165px)}:where(.entry-content-editor) .expert-layout .treepane{grid-area:tree;min-height:620px;max-height:830px}:where(.entry-content-editor) .expert-layout .stagepane{grid-area:stage;min-height:620px;max-height:830px}:where(.entry-content-editor) .expert-layout .inspectpane{grid-area:inspect;min-height:0;max-height:none}:where(.entry-content-editor) .expert-layout .expert-side-scroll{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-items:start}:where(.entry-content-editor) .expert-layout .expert-mini-preview{height:250px}}
+@media(max-width:700px){:where(.entry-content-editor) .builder.expert-layout{display:flex;flex-direction:column;max-height:none;min-height:0}:where(.entry-content-editor) .expert-layout .stagepane{order:0;min-height:680px;max-height:none}:where(.entry-content-editor) .expert-layout .treepane{order:1;min-height:190px;max-height:none}:where(.entry-content-editor) .expert-layout .inspectpane{order:2}:where(.entry-content-editor) .expert-codebox{height:480px;flex:none;min-height:480px}:where(.entry-content-editor) .expert-tools{flex-wrap:wrap}:where(.entry-content-editor) .expert-layout .expert-side-scroll{display:flex}:where(.entry-content-editor) .expert-editor-header .muted{display:none}:where(.entry-content-editor) .expert-conflict-grid{grid-template-columns:1fr}:where(.entry-content-editor) .expert-diff{max-height:55dvh}}
+@media(max-width:390px){:where(.entry-content-editor) .expert-find input{width:88px}:where(.entry-content-editor) .expert-tools{gap:5px;padding:7px}:where(.entry-content-editor) .expert-gutter{width:34px;padding-left:4px;padding-right:6px}:where(.entry-content-editor) .expert-textarea,:where(.entry-content-editor) .expert-highlighter{font-size:10.5px;line-height:19px;padding-left:9px;padding-right:8px}:where(.entry-content-editor) .expert-statusbar>span:last-child{display:none}}
+
+/* Stage 4 · Content & Collections. Share builder.css theme tokens to stay in the approved palette. */
+:where(.entry-content-editor){--contentCol:206px;--entryCol:264px;--previewCol:288px}:where(.entry-content-editor),:where(.entry-content-editor){min-width:0}:where(.entry-content-editor){overflow-x:hidden}:where(.entry-content-editor) .main{min-width:0}:where(.entry-content-editor) .entry-workspace{display:grid;grid-template-columns:var(--contentCol) var(--entryCol) minmax(330px,1fr) var(--previewCol);min-width:0;min-height:calc(100dvh - 174px);max-height:calc(100dvh - 174px)}:where(.entry-content-editor) .entry-workspace>*,:where(.entry-content-editor) .content-editor,:where(.entry-content-editor) .preview-pane,:where(.entry-content-editor) .collection-pane,:where(.entry-content-editor) .entry-pane{min-width:0}:where(.entry-content-editor) .collection-pane,:where(.entry-content-editor) .entry-pane,:where(.entry-content-editor) .content-editor,:where(.entry-content-editor) .preview-pane{background:var(--surface);display:flex;flex-direction:column;min-height:0}:where(.entry-content-editor) .collection-pane,:where(.entry-content-editor) .entry-pane,:where(.entry-content-editor) .content-editor{border-right:1px solid var(--border)}:where(.entry-content-editor) .content-editor{overflow:hidden}:where(.entry-content-editor) .preview-pane{background:var(--surface2);overflow:hidden}:where(.entry-content-editor) .pane-title{min-height:59px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;gap:8px;padding:10px 14px;flex:none}:where(.entry-content-editor) .pane-title b{font-size:11px}:where(.entry-content-editor) .pane-title small{display:block;font-size:10px;color:var(--muted);margin-top:3px}:where(.entry-content-editor) .mini-pill{font:9px ui-monospace,Consolas,monospace;color:var(--accent);background:var(--accentSoft);padding:3px 5px;border-radius:var(--pill)}:where(.entry-content-editor) .collection-chips{padding:9px 8px;display:flex;flex-direction:column;gap:3px;flex:1;min-height:0;overflow:auto}:where(.entry-content-editor) .collection-choice{border:1px solid transparent;background:transparent;display:flex;align-items:center;justify-content:space-between;gap:8px;text-align:left;color:var(--text);width:100%;padding:11px 10px;min-height:56px;border-radius:var(--radius)}:where(.entry-content-editor) .collection-choice:hover{background:var(--surface2)}:where(.entry-content-editor) .collection-choice.active{background:var(--accentSoft);border-color:color-mix(in srgb,var(--accent) 35%,var(--border))}:where(.entry-content-editor) .collection-choice b{display:block;font-size:11px;line-height:1.4}:where(.entry-content-editor) .collection-choice small{display:block;color:var(--muted);font-size:9px;margin-top:3px}:where(.entry-content-editor) .collection-right{display:flex;align-items:center;gap:4px;flex-direction:column}:where(.entry-content-editor) .collection-right strong{font-size:12px;color:var(--muted)}:where(.entry-content-editor) .collection-right em{font:8px ui-monospace,Consolas,monospace;padding:2px 4px;background:var(--surface3);color:var(--muted);font-style:normal}:where(.entry-content-editor) .pane-help{border-top:1px solid var(--border);padding:15px 12px;color:var(--muted);font-size:10px;line-height:1.5}:where(.entry-content-editor) .pane-help b{color:var(--text);font-size:10px}:where(.entry-content-editor) .pane-help p{margin-top:5px}:where(.entry-content-editor) .search-wrap{height:33px;display:flex;align-items:center;gap:7px;margin:10px 10px 6px;padding:0 9px;border:1px solid var(--border);background:var(--surface2);border-radius:var(--radius)}:where(.entry-content-editor) .search-wrap svg{width:13px;color:var(--muted)}:where(.entry-content-editor) .search-wrap input{background:transparent;border:0;outline:none;color:var(--text);font-size:10px;width:100%;min-width:0}:where(.entry-content-editor) .entry-filters{display:flex;gap:2px;padding:4px 8px 8px;flex-wrap:wrap;border-bottom:1px solid var(--border)}:where(.entry-content-editor) .entry-filters button{padding:5px 7px;border:0;color:var(--muted);background:transparent;font-size:9px;border-radius:var(--pill)}:where(.entry-content-editor) .entry-filters button.active{color:var(--accent);background:var(--accentSoft);font-weight:750}:where(.entry-content-editor) .entry-list{overflow:auto;flex:1;min-height:0}:where(.entry-content-editor) .entry-row{width:100%;border:0;border-bottom:1px solid var(--border2);background:transparent;color:var(--text);text-align:left;display:flex;align-items:flex-start;gap:9px;padding:13px 10px}:where(.entry-content-editor) .entry-row:hover{background:var(--surface2)}:where(.entry-content-editor) .entry-row.active{background:var(--accentSoft);box-shadow:inset 3px 0 var(--accent)}:where(.entry-content-editor) .entry-row>svg{width:11px;height:11px;color:var(--dim);align-self:center}:where(.entry-content-editor) .entry-row-icon{flex:none;display:grid;place-items:center;width:24px;height:24px;color:var(--accent);background:var(--surface3);border-radius:var(--radius)}:where(.entry-content-editor) .entry-row-icon svg{width:14px;height:14px}:where(.entry-content-editor) .entry-row-copy{flex:1;min-width:0}:where(.entry-content-editor) .entry-row-copy b{display:block;font-size:11px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}:where(.entry-content-editor) .entry-row-copy small{display:block;color:var(--muted);font-size:10px;margin:3px 0}:where(.entry-content-editor) .entry-status-row{display:flex;flex-wrap:wrap;gap:4px;align-items:center}:where(.entry-content-editor) .entry-status-row .status{font-size:8px;padding:2px 5px}:where(.entry-content-editor) .entry-status-row em{font-size:8px;font-style:normal}:where(.entry-content-editor) .list-foot{padding:10px;display:flex;justify-content:space-between;gap:7px;border-top:1px solid var(--border);color:var(--muted);font-size:9px;white-space:nowrap}:where(.entry-content-editor) .list-foot .mono{overflow:hidden;text-overflow:ellipsis;min-width:0}:where(.entry-content-editor) .empty-pane{min-height:190px;padding:30px 20px;display:flex;flex-direction:column;align-items:flex-start;gap:10px;color:var(--muted);font-size:11px}:where(.entry-content-editor) .empty-pane svg{color:var(--accent);height:22px;width:22px}:where(.entry-content-editor) .empty-pane b{color:var(--text)}:where(.entry-content-editor) .empty-pane p{line-height:1.6}:where(.entry-content-editor) .content-editor{display:flex;overflow:hidden}:where(.entry-content-editor) .content-editor>#entry-editor{overflow:auto;flex:1;min-height:0}:where(.entry-content-editor) .editor-content{padding:0 19px 32px;min-width:0}:where(.entry-content-editor) .editor-title{padding:19px 0 17px;border-bottom:1px solid var(--border);display:flex;gap:9px;align-items:center;justify-content:space-between}:where(.entry-content-editor) .editor-title h2{font-size:22px;letter-spacing:-.045em;font-weight:700;margin:4px 0 3px;line-height:1.18;word-break:break-word}:where(.entry-content-editor) .editor-title p{font-size:10px;color:var(--muted);overflow-wrap:anywhere}:where(.entry-content-editor) .editor-quick{display:flex;gap:5px}:where(.entry-content-editor) .entry-tabs{display:flex;gap:3px;overflow:auto;margin:13px 0 6px;border-bottom:1px solid var(--border);scrollbar-width:thin}:where(.entry-content-editor) .entry-tabs button{flex:none;background:none;color:var(--muted);border:0;border-bottom:2px solid transparent;padding:9px 11px;font-size:10px;white-space:nowrap}:where(.entry-content-editor) .entry-tabs button.active{color:var(--accent);border-bottom-color:var(--accent);font-weight:750}:where(.entry-content-editor) .field-section{padding:16px 0 10px;border-bottom:1px solid var(--border2)}:where(.entry-content-editor) .field-section>h3{display:flex;align-items:center;gap:8px;justify-content:space-between;color:var(--text);font-size:11px;margin:0 0 14px}:where(.entry-content-editor) .field-section>h3 small{color:var(--muted);font-size:9px;font-weight:400}:where(.entry-content-editor) .field-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:13px 11px}:where(.entry-content-editor) .entry-field{min-width:0;display:flex;flex-direction:column;gap:5px;color:var(--text);font-size:10px;margin-bottom:14px}:where(.entry-content-editor) .entry-field:has(textarea),:where(.entry-content-editor) .entry-field:has(.file-picker),:where(.entry-content-editor) .entry-field:has(.ref-pills),:where(.entry-content-editor) .entry-field:has(.list-edit),:where(.entry-content-editor) .entry-field:has(.group-edit){grid-column:1/-1}:where(.entry-content-editor) .field-label{display:flex;align-items:center;gap:6px;font-weight:680}:where(.entry-content-editor) .field-label i{color:var(--danger);font-style:normal}:where(.entry-content-editor) .field-label small{font-weight:400;color:var(--muted);font-size:9px;margin-left:auto}:where(.entry-content-editor) .entry-field>input,:where(.entry-content-editor) .entry-field>textarea,:where(.entry-content-editor) .entry-field>select,:where(.entry-content-editor) .mini-field input,:where(.entry-content-editor) .list-edit-row input{background:var(--surface2);color:var(--text);border:1px solid var(--border);padding:9px 10px;width:100%;min-width:0;border-radius:var(--radius);font-size:11px;outline:none}:where(.entry-content-editor) .entry-field textarea{resize:vertical;min-height:62px;line-height:1.6}:where(.entry-content-editor) .entry-field>input:focus,:where(.entry-content-editor) .entry-field>textarea:focus,:where(.entry-content-editor) .entry-field>select:focus,:where(.entry-content-editor) .mini-field input:focus{border-color:var(--accent)}:where(.entry-content-editor) .entry-field>small{color:var(--muted);font-size:9px}:where(.entry-content-editor) .switch-line{display:flex;align-items:center;gap:8px;padding:8px 0;color:var(--muted)}:where(.entry-content-editor) .switch-line input{width:17px;height:17px;accent-color:var(--accent)}:where(.entry-content-editor) .ref-pills{display:flex;flex-wrap:wrap;gap:5px}:where(.entry-content-editor) .ref-token{display:inline-flex;align-items:center;gap:4px;background:var(--accentSoft);color:var(--accent);border:1px solid color-mix(in srgb,var(--accent) 28%,var(--border));padding:5px 8px;border-radius:var(--pill);font-size:9px}:where(.entry-content-editor) .ref-token svg{width:11px;height:11px}:where(.entry-content-editor) .file-picker{display:flex;align-items:center;gap:6px;min-width:0}:where(.entry-content-editor) .file-picker>span{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--muted);background:var(--surface2);padding:8px 9px;border:1px solid var(--border);border-radius:var(--radius);font-size:9px}:where(.entry-content-editor) .file-picker .broken{color:var(--danger)}:where(.entry-content-editor) .list-edit{display:grid;gap:6px}:where(.entry-content-editor) .list-edit-row{display:flex;gap:5px}:where(.entry-content-editor) .group-edit{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:7px}:where(.entry-content-editor) .mini-field{display:block;min-width:0}:where(.entry-content-editor) .mini-field span{color:var(--muted);font-size:9px;display:block;margin-bottom:4px}:where(.entry-content-editor) .inline-issue{display:flex;align-items:center;gap:5px;color:var(--warning);font-size:9px}:where(.entry-content-editor) .inline-issue svg{width:11px;height:11px}:where(.entry-content-editor) .inline-issue.error{color:var(--danger)}:where(.entry-content-editor) .tab-panel{padding:17px 0 24px}:where(.entry-content-editor) .panel-heading{margin-bottom:15px}:where(.entry-content-editor) .panel-heading h3{font-size:14px;margin-bottom:5px}:where(.entry-content-editor) .panel-heading p{color:var(--muted);font-size:10px}:where(.entry-content-editor) .relation-group{border:1px solid var(--border);margin:0 0 10px;border-radius:var(--radius);overflow:hidden}:where(.entry-content-editor) .relation-group-head{display:flex;align-items:center;justify-content:space-between;padding:10px;background:var(--surface2);font-size:11px}:where(.entry-content-editor) .relation-row,:where(.entry-content-editor) .usage-row{display:flex;align-items:center;gap:10px;background:var(--surface);color:var(--text);width:100%;border:0;border-top:1px solid var(--border2);padding:10px;text-align:left}:where(.entry-content-editor) .relation-row:hover,:where(.entry-content-editor) .usage-row:hover{background:var(--accentSoft)}:where(.entry-content-editor) .relation-row>div,:where(.entry-content-editor) .usage-row>span:nth-child(2){min-width:0;flex:1}:where(.entry-content-editor) .relation-row b,:where(.entry-content-editor) .usage-row b{font-size:11px;display:block}:where(.entry-content-editor) .relation-row small,:where(.entry-content-editor) .usage-row small{display:block;color:var(--muted);font-size:9px;overflow-wrap:anywhere}:where(.entry-content-editor) .relation-row.bad{color:var(--danger)}:where(.entry-content-editor) .relation-row svg{color:var(--accent)}:where(.entry-content-editor) .usage-count{display:flex;align-items:center;gap:9px;margin:10px 0;border:1px solid var(--border);padding:10px;font-size:10px;background:var(--surface2);flex-wrap:wrap}:where(.entry-content-editor) .usage-count span{color:var(--muted)}:where(.entry-content-editor) .usage-row{border:1px solid var(--border);margin-bottom:6px;border-radius:var(--radius)}:where(.entry-content-editor) .usage-glyph{width:24px;height:24px;display:grid;place-items:center;color:var(--accent);background:var(--accentSoft);flex:none}:where(.entry-content-editor) .usage-row>svg{width:13px;color:var(--muted)}:where(.entry-content-editor) .schema-contract{display:flex;align-items:center;gap:8px;margin:10px 0;color:var(--muted);font-size:10px;flex-wrap:wrap}:where(.entry-content-editor) .schema-code{margin:0;background:var(--surface2);border:1px solid var(--border);padding:15px 13px;line-height:1.7;font-size:10px;white-space:pre-wrap;overflow-wrap:anywhere}:where(.entry-content-editor) .note-inline{font-size:10px;line-height:1.6;color:var(--muted);padding:10px 11px;background:var(--accentSoft);border-left:2px solid var(--accent);margin:12px 0 0}:where(.entry-content-editor) .empty-editor{padding:40px;color:var(--muted)}:where(.entry-content-editor) .preview-pane-content{overflow:auto;flex:1;padding:12px 12px 25px;min-width:0}:where(.entry-content-editor) .w-full{width:100%;display:grid;grid-template-columns:1fr 1fr}:where(.entry-content-editor) .w-full button{width:100%;min-width:0}:where(.entry-content-editor) .preview-version{margin:8px 0 15px}:where(.entry-content-editor) .preview-route{border-bottom:1px solid var(--border);padding:8px 0 13px;font-size:9px;color:var(--muted)}:where(.entry-content-editor) .preview-route span{display:block;letter-spacing:.09em}:where(.entry-content-editor) .preview-route code{display:block;color:var(--text);margin-top:4px;overflow-wrap:anywhere}:where(.entry-content-editor) .site-card-preview{background:var(--surface);border:1px solid var(--border);overflow:hidden;border-radius:var(--radius);margin-top:13px;box-shadow:var(--shadow)}:where(.entry-content-editor) .preview-media{height:100px;display:flex;align-items:center;justify-content:center;background:linear-gradient(145deg,#1a283b,#252435);color:#dccaf9;position:relative;overflow:hidden}:where(.entry-content-editor) .preview-media>svg{width:31px;height:31px;z-index:1}:where(.entry-content-editor) .media-orbit{position:absolute;inset:0;background:radial-gradient(ellipse at 75% 25%,color-mix(in srgb,var(--orb) 32%,transparent),transparent 62%)}:where(.entry-content-editor) .preview-media small{position:absolute;bottom:8px;left:9px;color:#b5b9c8;font-size:8px}:where(.entry-content-editor) .site-card-content{padding:15px}:where(.entry-content-editor) .site-card-category{color:var(--accent);font-size:9px;text-transform:uppercase;letter-spacing:.1em;font-weight:760}:where(.entry-content-editor) .site-card-content h3{font-size:19px;line-height:1.2;margin:7px 0 9px;letter-spacing:-.04em}:where(.entry-content-editor) .site-card-content p{font-size:11px;color:var(--muted);line-height:1.65}:where(.entry-content-editor) .site-card-content>span:last-child{display:flex;align-items:center;gap:5px;color:var(--accent);font-weight:700;margin-top:14px}:where(.entry-content-editor) .site-card-content>span:last-child svg{width:12px}:where(.entry-content-editor) .preview-info{margin-top:14px;border-top:1px solid var(--border)}:where(.entry-content-editor) .preview-info>div{display:flex;justify-content:space-between;align-items:start;gap:5px;border-bottom:1px solid var(--border2);padding:8px 0;font-size:9px}:where(.entry-content-editor) .preview-info span{color:var(--muted);flex:none}:where(.entry-content-editor) .preview-info code,:where(.entry-content-editor) .preview-info b{font-weight:550;overflow-wrap:anywhere;text-align:right}:where(.entry-content-editor) .site-page-preview{background:#f0f0ec;color:#26232b;border:1px solid var(--border);margin-top:13px;border-radius:var(--radius);overflow:hidden}:where(.entry-content-editor) .fake-browser{display:flex;justify-content:space-between;gap:5px;background:#d8d8d6;padding:6px 8px;color:#7d7c82;font-size:8px}:where(.entry-content-editor) .fake-site-nav{display:flex;justify-content:space-between;gap:5px;padding:13px 12px;border-bottom:1px solid #cfcdd2;font-size:9px}:where(.entry-content-editor) .fake-site-nav b span{color:#9b81b0}:where(.entry-content-editor) .fake-site-nav>span{font-size:7px}:where(.entry-content-editor) .site-page-preview main{padding:21px 14px 27px}:where(.entry-content-editor) .site-page-kicker{color:#8161c0;font-weight:800;font-size:9px}:where(.entry-content-editor) .site-page-preview h2{font-size:24px;letter-spacing:-.06em;line-height:1.15;margin:10px 0}:where(.entry-content-editor) .site-page-lead{font-size:11px;line-height:1.55;color:#55515a}:where(.entry-content-editor) .markdown-view{margin-top:20px;border-top:1px solid #cdd0d3;padding-top:10px;font-size:10px}:where(.entry-content-editor) .markdown-view h1{font-size:17px;margin:8px 0}:where(.entry-content-editor) .markdown-view h2{font-size:14px;margin:8px 0}:where(.entry-content-editor) .markdown-view h3{font-size:12px;margin:8px 0}:where(.entry-content-editor) .markdown-view p{margin:7px 0}:where(.entry-content-editor) .fake-site-footer{background:#252631;color:#ebebee;padding:12px;font-size:9px}:where(.entry-content-editor) .preview-empty{border:1px dashed var(--border);padding:22px 12px;margin-top:14px;font-size:11px;color:var(--muted);line-height:1.6}:where(.entry-content-editor) .workspace-footer{min-height:35px;display:flex;align-items:center;justify-content:space-between;gap:10px;padding:7px 15px;background:var(--surface);border-top:1px solid var(--border);font-size:9px;color:var(--muted);flex-wrap:wrap}:where(.entry-content-editor) .entry-head{min-height:114px}:where(.entry-content-editor) .entry-head .head-actions .toggle{margin-right:3px}:where(.entry-content-editor) .expert-wrap{padding:16px 18px 22px}:where(.entry-content-editor) .expert-header{display:flex;justify-content:space-between;align-items:start;gap:14px;flex-wrap:wrap;padding-bottom:15px}:where(.entry-content-editor) .expert-header h2{font-size:15px;margin:5px 0;overflow-wrap:anywhere}:where(.entry-content-editor) .expert-header p{font-size:10px;color:var(--muted)}:where(.entry-content-editor) .expert-actions{display:flex;flex-wrap:wrap;gap:6px}:where(.entry-content-editor) .source-toolbar{height:31px;background:var(--surface2);border:1px solid var(--border);border-bottom:0;display:flex;justify-content:space-between;align-items:center;padding:0 11px;font-size:9px;color:var(--muted)}:where(.entry-content-editor) .source-code{display:flex;min-height:440px;height:58vh;max-height:650px;border:1px solid var(--border);background:var(--surface2);overflow:hidden}:where(.entry-content-editor) .code-lines{width:45px;flex:none;background:var(--surface3);border-right:1px solid var(--border);text-align:right;padding:10px 8px;font:11px/1.55 ui-monospace,Consolas,monospace;color:var(--dim);overflow:hidden}:where(.entry-content-editor) .source-code textarea{flex:1;min-width:0;width:100%;border:0;background:transparent;color:var(--text);resize:none;outline:none;padding:10px 12px;font:11px/1.55 ui-monospace,Consolas,monospace;tab-size:2;white-space:pre;overflow:auto}:where(.entry-content-editor) .source-errorbox{border:1px solid var(--border);border-top:0;min-height:35px;padding:9px;color:var(--muted);font-size:10px}:where(.entry-content-editor) .source-errorbox button{background:var(--dangerBg);color:var(--danger);padding:7px;border:0;width:100%;text-align:left;display:flex;gap:7px}:where(.entry-content-editor) .issue-callout{background:var(--dangerBg);color:var(--danger);border-left:3px solid var(--danger);padding:13px;font-size:11px;line-height:1.6}:where(.entry-content-editor) .toast{position:fixed;bottom:22px;right:22px;background:var(--surface);color:var(--text);border:1px solid var(--border);box-shadow:var(--shadow);border-radius:var(--radius);padding:13px 16px;font-size:11px;opacity:0;transform:translateY(10px);transition:all .2s;pointer-events:none;z-index:100}:where(.entry-content-editor) .toast.show{opacity:1;transform:none}:where(.entry-content-editor) .toast.error{color:var(--danger)}:where(.entry-content-editor) .toast.warn{color:var(--warning)}:where(.entry-content-editor) .dialog-mask{position:fixed;inset:0;background:#0009;display:flex;align-items:center;justify-content:center;padding:12px;z-index:60}:where(.entry-content-editor) .stage4-dialog{width:min(560px,100%);background:var(--surface);color:var(--text);border:1px solid var(--border);border-radius:var(--radius);box-shadow:0 24px 90px #0006;max-height:92vh;overflow:auto}:where(.entry-content-editor) .stage4-dialog.wide-dialog{width:min(950px,100%)}:where(.entry-content-editor) .dialog-header{border-bottom:1px solid var(--border);padding:18px;display:flex;justify-content:space-between;gap:12px;align-items:start}:where(.entry-content-editor) .dialog-header h2{font-size:19px;margin-top:5px}:where(.entry-content-editor) .dialog-body{padding:16px 18px;font-size:11px;line-height:1.55}:where(.entry-content-editor) .dialog-body>p{margin-bottom:13px}:where(.entry-content-editor) .dialog-actions{display:flex;justify-content:end;gap:8px;flex-wrap:wrap;padding:13px 18px;border-top:1px solid var(--border)}:where(.entry-content-editor) .asset-options,:where(.entry-content-editor) .ref-choices{max-height:350px;overflow:auto;display:grid;gap:6px}:where(.entry-content-editor) .asset-option{width:100%;text-align:left;background:var(--surface2);border:1px solid var(--border);color:var(--text);display:flex;align-items:center;gap:9px;padding:10px;border-radius:var(--radius)}:where(.entry-content-editor) .asset-option:hover,:where(.entry-content-editor) .asset-option.selected{border-color:var(--accent);background:var(--accentSoft)}:where(.entry-content-editor) .asset-option>span{min-width:0;flex:1}:where(.entry-content-editor) .asset-option b,:where(.entry-content-editor) .ref-choice b{display:block;font-size:11px}:where(.entry-content-editor) .asset-option small,:where(.entry-content-editor) .ref-choice small{display:block;font-size:9px;color:var(--muted)}:where(.entry-content-editor) .asset-option svg{color:var(--accent)}:where(.entry-content-editor) .ref-choice{display:flex;align-items:center;gap:10px;padding:10px;border:1px solid var(--border);background:var(--surface2)}:where(.entry-content-editor) .ref-choice input{accent-color:var(--accent)}:where(.entry-content-editor) .review-summary{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:7px}:where(.entry-content-editor) .review-count{background:var(--surface2);padding:12px;border:1px solid var(--border)}:where(.entry-content-editor) .review-count b{display:block;font-size:22px}:where(.entry-content-editor) .review-count:first-child b{color:var(--danger)}:where(.entry-content-editor) .review-count:nth-child(2) b{color:var(--warning)}:where(.entry-content-editor) .review-count:last-child b{color:var(--accent)}:where(.entry-content-editor) .review-count span{font-size:9px;color:var(--muted)}:where(.entry-content-editor) .review-list{max-height:300px;overflow:auto;margin-top:12px;border:1px solid var(--border)}:where(.entry-content-editor) .review-item{display:flex;align-items:center;gap:10px;border:0;border-bottom:1px solid var(--border2);padding:10px;width:100%;text-align:left;color:var(--text);background:var(--surface)}:where(.entry-content-editor) .review-item:hover{background:var(--accentSoft)}:where(.entry-content-editor) .review-item>span:nth-child(2){min-width:0;flex:1}:where(.entry-content-editor) .review-item b{font-size:11px;display:block}:where(.entry-content-editor) .review-item small{display:block;font-size:9px;color:var(--muted);overflow-wrap:anywhere}:where(.entry-content-editor) .issue-label{color:var(--warning);background:var(--warningBg);font:800 9px ui-monospace,Consolas,monospace;padding:4px 6px}:where(.entry-content-editor) .review-item.error .issue-label{color:var(--danger);background:var(--dangerBg)}:where(.entry-content-editor) .clean-state{padding:15px;color:var(--positive)}:where(.entry-content-editor) .conflict-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:10px}:where(.entry-content-editor) .conflict-grid>div{min-width:0}:where(.entry-content-editor) .conflict-grid pre{background:var(--surface2);padding:11px;border:1px solid var(--border);white-space:pre-wrap;overflow-wrap:anywhere;font-size:10px}:where(.entry-content-editor) .diff-table{max-height:400px;overflow:auto;border:1px solid var(--border);margin-top:12px}:where(.entry-content-editor) .diff-head,:where(.entry-content-editor) .diff-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr)}:where(.entry-content-editor) .diff-head{position:sticky;top:0;background:var(--surface3);padding:8px}:where(.entry-content-editor) .diff-row{border-top:1px solid var(--border2)}:where(.entry-content-editor) .diff-row.changed{background:var(--accentSoft)}:where(.entry-content-editor) .diff-row span{padding:4px 7px;border-right:1px solid var(--border);white-space:pre-wrap;overflow-wrap:anywhere;font:9px/1.4 ui-monospace,Consolas,monospace;min-width:0}
+/* Rose Graphite requirement: collection selection uses square corners, other tables/cards retain rounding. */
+:where(.entry-content-editor) [data-theme="rose"] .collection-choice{border-radius:0}
+@media(max-width:1600px){:where(.entry-content-editor){--contentCol:184px;--entryCol:245px;--previewCol:258px}:where(.entry-content-editor) .editor-content{padding:0 15px 22px}:where(.entry-content-editor) .preview-pane-content{padding:10px}:where(.entry-content-editor) .field-grid{grid-template-columns:1fr}:where(.entry-content-editor) .entry-field{grid-column:1/-1}}
+@media(max-width:1260px){:where(.entry-content-editor){--contentCol:170px;--entryCol:240px;--previewCol:0px}:where(.entry-content-editor) .entry-workspace{grid-template-columns:var(--contentCol) var(--entryCol) minmax(0,1fr);max-height:none;min-height:calc(100dvh - 180px)}:where(.entry-content-editor) .preview-pane{grid-column:3;min-height:0;border-top:1px solid var(--border)}:where(.entry-content-editor) .preview-pane-content{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:8px 12px}:where(.entry-content-editor) .preview-pane-content .site-card-preview,:where(.entry-content-editor) .preview-pane-content .site-page-preview,:where(.entry-content-editor) .preview-pane-content .preview-empty{grid-column:1/-1;max-width:560px}:where(.entry-content-editor) .preview-pane-content .preview-info{grid-column:1/-1}:where(.entry-content-editor) .content-editor{max-height:none;min-height:480px}:where(.entry-content-editor) .content-editor>#entry-editor{overflow:visible}:where(.entry-content-editor) .preview-pane{overflow:visible}:where(.entry-content-editor) .preview-pane-content{overflow:visible}:where(.entry-content-editor) .entry-pane,:where(.entry-content-editor) .collection-pane{grid-row:1/3}:where(.entry-content-editor) .entry-list,:where(.entry-content-editor) .collection-chips{overflow:visible}:where(.entry-content-editor) .collection-pane,:where(.entry-content-editor) .entry-pane{min-height:100%}}
+@media(max-width:980px){:where(.entry-content-editor) .entry-workspace{grid-template-columns:minmax(0,175px) minmax(0,1fr)}:where(.entry-content-editor) .collection-pane{grid-column:1;grid-row:1/3}:where(.entry-content-editor) .entry-pane{grid-column:2;grid-row:1;min-height:220px;max-height:360px}:where(.entry-content-editor) .entry-list{overflow:auto}:where(.entry-content-editor) .content-editor{grid-column:2;grid-row:2;min-height:560px}:where(.entry-content-editor) .preview-pane{grid-column:2;grid-row:3}:where(.entry-content-editor) .pane-help{display:none}}
+@media(max-width:700px){:where(.entry-content-editor) .entry-workspace{display:flex;flex-direction:column;max-height:none;min-height:0}:where(.entry-content-editor) .collection-pane{order:0;border-right:0;border-bottom:1px solid var(--border);min-height:0}:where(.entry-content-editor) .collection-chips{flex-direction:row;flex-wrap:nowrap;overflow-x:auto;padding:8px}:where(.entry-content-editor) .collection-choice{min-width:122px;width:auto;flex:none}:where(.entry-content-editor) .entry-pane{order:1;min-height:0;max-height:none;border-right:0;border-bottom:1px solid var(--border)}:where(.entry-content-editor) .entry-list{overflow:visible;display:grid;grid-template-columns:repeat(2,minmax(0,1fr))}:where(.entry-content-editor) .entry-row{min-width:0}:where(.entry-content-editor) .content-editor{order:2;min-height:0;max-height:none;overflow:visible;border-right:0}:where(.entry-content-editor) .content-editor>#entry-editor{overflow:visible}:where(.entry-content-editor) .preview-pane{order:3;border-top:1px solid var(--border)}:where(.entry-content-editor) .preview-pane-content{display:block}:where(.entry-content-editor) .entry-head{min-height:0}:where(.entry-content-editor) .entry-head .head-actions{margin-top:12px}:where(.entry-content-editor) .workspace-footer{display:block;text-align:center;padding:10px}:where(.entry-content-editor) .workspace-footer span{display:block}:where(.entry-content-editor) .field-grid{grid-template-columns:1fr}:where(.entry-content-editor) .group-edit{grid-template-columns:1fr}:where(.entry-content-editor) .entry-row{padding:11px 9px}:where(.entry-content-editor) .editor-title{flex-wrap:wrap}:where(.entry-content-editor) .editor-title h2{font-size:19px}:where(.entry-content-editor) .source-code{height:480px}:where(.entry-content-editor) .expert-wrap{padding:15px}:where(.entry-content-editor) .expert-header{display:block}:where(.entry-content-editor) .expert-actions{margin-top:12px}}
+@media(max-width:390px){:where(.entry-content-editor) .entry-list{grid-template-columns:1fr}:where(.entry-content-editor) .head-actions{gap:5px}:where(.entry-content-editor) .head-actions .toggle{width:auto}:where(.entry-content-editor) .head-actions .button{flex:1}:where(.entry-content-editor) .entry-row{padding:10px}:where(.entry-content-editor) .dialog-actions button{flex:1}:where(.entry-content-editor) .review-summary{grid-template-columns:1fr 1fr 1fr}}
+/* Keep desktop panes independently scrollable; never render the footer over form fields. */
+@media(min-width:1261px){
+ :where(.entry-content-editor) .entry-workspace{height:calc(100dvh - 209px);min-height:0;max-height:none;grid-template-rows:minmax(0,1fr)}
+ :where(.entry-content-editor) .collection-pane,:where(.entry-content-editor) .entry-pane,:where(.entry-content-editor) .content-editor,:where(.entry-content-editor) .preview-pane{min-height:0;overflow:hidden}
+ :where(.entry-content-editor) .collection-chips,:where(.entry-content-editor) .entry-list,:where(.entry-content-editor) .content-editor>#entry-editor,:where(.entry-content-editor) .preview-pane-content{min-height:0;overflow-y:auto}
+}
+/* The grid items are hosts; size them explicitly so panel interiors fill the available viewport. */
+:where(.entry-content-editor) #collection-host,:where(.entry-content-editor) #entry-list-host,:where(.entry-content-editor) #preview-host{display:flex;min-width:0;min-height:0;overflow:hidden}
+:where(.entry-content-editor) #collection-host>.collection-pane,:where(.entry-content-editor) #entry-list-host>.entry-pane,:where(.entry-content-editor) #preview-host>.preview-pane{flex:1;min-width:0;min-height:0;max-width:100%}
+:where(.entry-content-editor) .side-nav button.side-link{border:0;background:transparent;width:100%;text-align:left;font:inherit;cursor:pointer}
+:where(.entry-content-editor) .side-nav button.side-link:hover{background:var(--navhover);color:#fff}
+@media(min-width:1261px){:where(.entry-content-editor) #collection-host,:where(.entry-content-editor) #entry-list-host,:where(.entry-content-editor) #preview-host{overflow:hidden}}
+@media(min-width:701px) and (max-width:1260px){
+ :where(.entry-content-editor) #collection-host{grid-column:1;grid-row:1/3}
+ :where(.entry-content-editor) #entry-list-host{grid-column:2;grid-row:1/3}
+ :where(.entry-content-editor) #preview-host{grid-column:3;grid-row:2}
+ :where(.entry-content-editor) #collection-host,:where(.entry-content-editor) #entry-list-host,:where(.entry-content-editor) #preview-host{overflow:visible}
+}
+@media(min-width:701px) and (max-width:980px){
+ :where(.entry-content-editor) #collection-host{grid-column:1;grid-row:1/4}
+ :where(.entry-content-editor) #entry-list-host{grid-column:2;grid-row:1}
+ :where(.entry-content-editor) .content-editor{grid-column:2;grid-row:2}
+ :where(.entry-content-editor) #preview-host{grid-column:2;grid-row:3}
+}
+@media(max-width:700px){
+ :where(.entry-content-editor) #collection-host{order:0;overflow:visible}
+ :where(.entry-content-editor) #entry-list-host{order:1;overflow:visible}
+ :where(.entry-content-editor) .content-editor{order:2}
+ :where(.entry-content-editor) #preview-host{order:3;overflow:visible}
+ :where(.entry-content-editor) #collection-host>.collection-pane,:where(.entry-content-editor) #entry-list-host>.entry-pane,:where(.entry-content-editor) #preview-host>.preview-pane{overflow:visible;max-height:none}
+}
+/* Syntax overlay for Expert; editing remains a native textarea for keyboard accessibility. */
+:where(.entry-content-editor) .source-edit-wrap{position:relative;flex:1;min-width:0;min-height:0;overflow:hidden}
+:where(.entry-content-editor) .source-edit-wrap pre,:where(.entry-content-editor) .source-edit-wrap textarea{position:absolute;inset:0;margin:0;width:100%;height:100%;padding:10px 12px;font:11px/1.55 ui-monospace,Consolas,monospace;white-space:pre;tab-size:2;overflow:auto;letter-spacing:normal;word-spacing:normal}
+:where(.entry-content-editor) .source-edit-wrap pre{z-index:0;overflow:hidden;pointer-events:none;color:var(--text);background:transparent}
+:where(.entry-content-editor) .source-edit-wrap textarea{z-index:1;resize:none;border:0;outline:0;background:transparent;color:transparent;-webkit-text-fill-color:transparent;caret-color:var(--text)}
+:where(.entry-content-editor) .source-edit-wrap textarea::selection{background:color-mix(in srgb,var(--accent) 30%,transparent)}
+:where(.entry-content-editor) .hl-fence{color:var(--warning)}:where(.entry-content-editor) .hl-key{color:var(--accent)}:where(.entry-content-editor) .hl-punc{color:var(--muted)}:where(.entry-content-editor) .hl-value{color:var(--positive)}:where(.entry-content-editor) .hl-comment{color:var(--dim)}:where(.entry-content-editor) .hl-heading{color:var(--accent);font-weight:700}
+:where(.entry-content-editor) .seed-list{padding:0 3px;border:0;background:transparent;color:var(--accent);font:10px ui-monospace,Consolas,monospace;white-space:nowrap}:where(.entry-content-editor) .seed-list:hover{text-decoration:underline}
+:where(.entry-content-editor) .reset-demo{background:transparent;border:0;color:#a7a8b5;font:9px ui-monospace,Consolas,monospace;padding:4px}:where(.entry-content-editor) .reset-demo:hover{color:#fff}
diff --git a/src/site_engine/web/admin/static/content-editor.js b/src/site_engine/web/admin/static/content-editor.js
new file mode 100644
index 0000000..1eef1ee
--- /dev/null
+++ b/src/site_engine/web/admin/static/content-editor.js
@@ -0,0 +1,118 @@
+/* Content UI from design/assets/content-editor.js; persistence and parsing belong to FastAPI. */
+(() => {
+ 'use strict';
+ const $=(s,r=document)=>r?.querySelector(s), $$=(s,r=document)=>Array.from(r?.querySelectorAll(s)||[]);
+ const root=()=>$('.entry-content-editor');
+ const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
+ let filter='all',tab='fields';
+ function size(){const workspace=$('.entry-workspace',root()),footer=$('.workspace-footer',root());if(workspace&&footer&&innerWidth>1260){const height=Math.max(0,innerHeight-workspace.getBoundingClientRect().top-scrollY-footer.getBoundingClientRect().height);root().style.setProperty('--content-workspace-height',height+'px');}}
+ const sizes=new ResizeObserver(size);
+ function layout(){sizes.disconnect();if(root()){$$('.entry-head,.workspace-footer',root()).forEach(e=>sizes.observe(e));size();}}
+ addEventListener('resize',size);
+ function data(){try{return JSON.parse($('[data-content-navigation]')?.content.textContent||'{}');}catch{return {};}}
+ function error(e){window.siteAdminError?.(e,e.status);window.siteDocument?.notice(e.message||'Не удалось выполнить запрос.');}
+ function modal(title,html,actions=[],wide=false){
+ const previous=document.activeElement,dialog=document.createElement('dialog');
+ dialog.className='stage4-dialog'+(wide?' wide-dialog':'');
+ dialog.innerHTML=`
${html}
`;
+ dialog.setAttribute('aria-labelledby','content-dialog-title');
+ dialog.addEventListener('click',e=>{const r=dialog.getBoundingClientRect();if(e.target===dialog&&(e.clientXr.right||e.clientYr.bottom))dialog.close();});
+ for(const action of actions.length?actions:[{label:'Закрыть'}]){
+ const button=document.createElement('button');button.type='button';button.className='button '+(action.style||'');button.textContent=action.label;
+ button.addEventListener('click',async()=>{try{if(action.run){button.disabled=true;try{await action.run(dialog);}finally{if(button.isConnected)button.disabled=false;}}else dialog.close();}catch(e){error(e);}});$('.dialog-actions',dialog).append(button);
+ }
+ $('[data-content-close]',dialog).onclick=()=>dialog.close();
+ dialog.addEventListener('close',()=>{dialog.remove();if(previous?.isConnected)previous.focus({preventScroll:true});},{once:true});
+ $('#content-overlay',root()).append(dialog);dialog.showModal();return dialog;
+ }
+ window.siteContentConfirm=(title,message,label)=>new Promise(resolve=>{
+ const d=modal(title,`${esc(message)}
`,[{label:'Остаться'},{label,style:'danger',run:d=>{resolve(true);d.close();}}]);
+ d.addEventListener('close',()=>resolve(false),{once:true});
+ });
+ window.siteContentConflict=(e,source,accept)=>{
+ modal('409 · Conflict',`Файл изменён на сервере. Ваш исходник остаётся в редакторе.
Моя версия / workspace ${esc(source)} Версия на сервере ${esc(e.current.source)} Принимаю серверную версию как новую основу `,[{label:'Закрыть'},{label:'Принять серверную версию как основу',style:'primary',run:d=>{const check=$('[data-accept-base-check]',d);if(!check.checked){check.focus();return;}accept();d.close();}}],true);
+ };
+ function setTab(next){tab=next;$$('[data-content-tab]',root()).forEach(e=>{e.classList.toggle('active',e.dataset.contentTab===tab);e.setAttribute('aria-selected',String(e.dataset.contentTab===tab));});$$('[data-content-panel]',root()).forEach(e=>e.hidden=e.dataset.contentPanel!==tab);}
+ function list(){const query=($('#entry-query')?.value||'').toLocaleLowerCase();let shown=0;const rows=$$('[data-entry]',root());for(const row of rows){row.hidden=!(row.dataset.entrySearch.includes(query)&&(filter==='all'||(filter==='changed'?row.dataset.entryChanged==='1':row.dataset.entryStatus===filter)));if(!row.hidden)shown++;}const empty=$('[data-content-list-empty]');if(empty)empty.hidden=!!shown;const count=$('[data-content-list-count]');if(count)count.textContent=`${shown} из ${rows.length}`;}
+ function highlightSource(source){let fences=0;return source.split('\n').map(line=>{
+ if(line==='---'){fences++;return '--- ';}
+ const raw=esc(line);if(fences<2){if(/^\s*#/.test(line))return '';const m=line.match(/^(\s*-?\s*[\w.-]+)(:)(.*)$/);if(m)return ''+esc(m[1])+' : '+esc(m[3])+' ';return raw;}
+ return /^#{1,6} /.test(line)?''+raw+' ':raw;
+ }).join('\n');}
+ function source(){const input=$('#document-source',root());if(!input)return;$('#code-lines').innerHTML=input.value.split('\n').map((_,i)=>i+1).join(' ');$('#entry-highlight').innerHTML=highlightSource(input.value)+'\n';const status=$('[data-content-source-status]');if(status)status.textContent=window.siteDocument?.state?.busy?'Проверка…':'Синхронизирован';}
+ function change(input){
+ const label=$$('[data-content-picked]').find(e=>e.dataset.contentPicked===input.name);if(label)label.textContent=input.value||'Файл не выбран';
+ const tokens=$$('[data-content-tokens]').find(e=>e.dataset.contentTokens===input.name);if(tokens)tokens.innerHTML=input.value.split(/[,\s]+/).filter(Boolean).map(value=>{const ref=tokens.dataset.refTarget==='*'?value:tokens.dataset.refTarget+'/'+value;return `${esc(value)} ${$('[data-content-ref-arrow]').innerHTML} `;}).join('');
+ window.siteDocument.change(input);
+ }
+ function picker(button){
+ const input=$$('[name]',root()).find(e=>e.name===button.dataset.contentPicker),options=JSON.parse(button.dataset.pickerOptions||'[]'),type=button.dataset.pickerType;
+ if(!input)return;
+ const selected=new Set(type==='refs'?input.value.split(',').map(s=>s.trim()):[input.value]);
+ const optionValue=o=>typeof o==='string'?o:o.value;
+ const titles=window.siteDocument.state?.schema?.choices?.entry_titles||{};
+ const label=o=>typeof o==='string'?(titles[button.dataset.pickerTarget==='*'?o:button.dataset.pickerTarget+'/'+o]||o):(o.label||o.value);
+ let d;
+ if(type==='asset'){
+ d=modal('Выбор медиафайла',`Связь Entry → Asset · ${esc(input.name)}
${options.map((o,i)=>`
${esc(label(o))} ${esc(optionValue(o))} `).join('')||'
В assets пока нет файлов.
'}
`,[{label:'Очистить',run:d=>{input.value='';change(input);d.close();}},{label:'Отмена'}]);
+ $$('[data-option]',d).forEach(b=>b.onclick=()=>{input.value=optionValue(options[Number(b.dataset.option)]);change(input);d.close();});
+ }else{
+ d=modal('Выбор связанных записей',`${esc(input.name)}
${options.map((o,i)=>`
${esc(label(o))} ${esc(optionValue(o))} `).join('')||'
Нет подходящих записей.
'}
`,[{label:'Отмена'},{label:'Применить',style:'primary',run:d=>{input.value=$$('input:checked',d).map(e=>optionValue(options[Number(e.value)])).join(', ');change(input);d.close();}}]);
+ }
+ }
+ async function request(operation,extra={}){
+ const s=window.siteDocument.state,form=$('#buffer-form'),body=new FormData();body.set('csrf',form.elements.csrf.value);body.set('payload',JSON.stringify({source:s.source,etag:s.etag,revision:s.revision,...extra}));
+ let response;try{response=await fetch('/admin/editor'+s.base+'/'+operation,{method:'POST',credentials:'same-origin',headers:{'Accept':'application/json','HX-Request':'true'},body});}catch{throw {code:'network_error',message:'Нет связи с сервером. Правки остаются в редакторе.'};}
+ let result;try{result=await response.json();}catch{throw {code:'invalid_response',message:'Сервер вернул некорректный ответ.',status:response.status};}if(!response.ok)throw {...result.error,status:response.status};return result;
+ }
+ async function validate(){
+ // Flush syntax/queued field edits first; malformed Expert text still gets diagnostics.
+ await window.siteDocument.flush();const result=await request('check'),issues=result.issues,errors=issues.filter(i=>i.severity==='error').length;
+ const d=modal('Проверка записи',`${errors} ошибок · блокируют публикацию
${issues.length-errors} предупреждений
1 запись проверена
${issues.map((i,n)=>`
${i.severity==='error'?'ERROR':'WARN'} ${esc(i.message)} ${esc(i.code)} · ${esc(i.path)} `).join('')||'
✓ Ошибок и предупреждений нет
'}
Неполный черновик можно сохранить. Строгая проверка выполняется перед публикацией.
`);
+ $$('[data-issue]',d).forEach(b=>b.onclick=()=>{const issue=issues[Number(b.dataset.issue)];d.close();setTab('fields');const field=issue.path.split(/[:.]/).at(-1),input=$$('[name]',root()).find(e=>e.name==='p.'+field||e.name===field);if(input&&window.siteDocument.state.mode==='constructor'){input.focus();input.scrollIntoView({block:'center'});}else{$('[data-editor-mode=expert]').click();$('#document-source').focus();}});
+ }
+ async function duplicate(){if(!await window.siteDocument.flush())return;const revision=window.siteDocument.state.revision,navigation=data(),id=root().dataset.contentSource;let name=id+'-copy';while(navigation.entries.some(e=>e.slug===name))name+='-2';try{const result=await request('duplicate',{id:name});const go=()=>location.assign('/admin/content/'+navigation.collection.id+'/'+result.snapshot.id);if(window.siteDocument.state.revision===revision)go();else await window.siteDocument.leave(go);}catch(e){if(e.committed)window.siteDocument.notice('Копия создана, но аудит недоступен: '+e.committed.id);throw e;}}
+ async function remove(){
+ if(!await window.siteDocument.flush())return;
+ if(window.siteDocument.state.model?.meta.status==='published')throw {code:'published_entry',message:'Сначала архивируйте запись и сохраните её; затем можно удалить файл.'};
+ const d=modal('Удалить запись?',`Удаление файла ${esc(window.siteDocument.state.path)}. Запись будет удалена из workspace; опубликованный релиз сохранится.
`,[{label:'Отмена'},{label:'Удалить из workspace',style:'danger',run:async d=>{try{await request('delete');location.assign('/admin/content/'+data().collection.id);}catch(e){d.close();if(e.deleted){window.siteDocument.notice(e.message);$$('[data-content-delete],[data-save-document]').forEach(b=>b.disabled=true);}throw e;}}}]);return d;
+ }
+ function diff(){const s=window.siteDocument.state,a=s.saved.split('\n'),b=s.source.split('\n');modal('Сравнение исходника',`Последний сохранённый черновик ↔ текущее рабочее состояние
Saved draft Workspace
${Array.from({length:Math.max(a.length,b.length)},(_,i)=>`
${esc(a[i])} ${esc(b[i])}
`).join('')}
`,[],true);}
+ function find(){const d=modal('Поиск в исходнике','Строка поиска ',[{label:'Отмена'},{label:'Найти',style:'primary',run:d=>{const q=$('[data-source-query]',d).value;if(!q)return;const input=$('#document-source'),i=input.value.toLowerCase().indexOf(q.toLowerCase());if(i<0){window.siteDocument.notice('Строка не найдена.');return;}d.close();input.focus();input.setSelectionRange(i,i+q.length);}}]);$('[data-source-query]',d).focus();}
+ document.addEventListener('click',e=>{
+ if(!root()?.contains(e.target))return;const b=e.target.closest('button');if(!b)return;
+ const work=async()=>{
+ if(b.dataset.contentTab)setTab(b.dataset.contentTab);
+ if(b.dataset.contentFilter){filter=b.dataset.contentFilter;$$('[data-content-filter]').forEach(el=>el.classList.toggle('active',el===b));list();}
+ if(b.dataset.contentPicker)picker(b);
+ if(b.dataset.contentConfigure){setTab('fields');const button=$$('[data-content-picker]').find(el=>el.dataset.contentPicker===b.dataset.contentConfigure);if(button)picker(button);else{const input=$$('[name]').find(el=>el.name===b.dataset.contentConfigure+'.target');input?.focus();input?.scrollIntoView({block:'center'});}}
+ if(b.dataset.contentAdd){const list=$$('[data-list-name]').find(el=>el.dataset.listName===b.dataset.contentAdd),blank=$(':scope > .blank[hidden]',list);if(blank){blank.hidden=false;$('input:not([type=hidden]):not([type=checkbox]),textarea,select',blank)?.focus();}}
+ if(b.dataset.contentRemove){const row=b.closest('[data-list-row]'),input=$(':scope > [data-list-delete] input',row);input.checked=true;row.hidden=true;change(input);}
+ if(b.hasAttribute('data-content-validate'))await validate();
+ if(b.hasAttribute('data-content-duplicate'))await duplicate();
+ if(b.hasAttribute('data-content-delete'))await remove();
+ if(b.hasAttribute('data-content-apply'))await window.siteDocument.flush(true);
+ if(b.hasAttribute('data-content-diff')){await window.siteDocument.flush();diff();}
+ if(b.hasAttribute('data-content-find'))find();
+ if(b.dataset.contentPreview||b.dataset.contentVersion){await window.siteDocument.preview(b.dataset.contentPreview,b.dataset.contentVersion);}
+ };work().catch(error);
+ });
+ document.addEventListener('input',e=>{if(!root()?.contains(e.target))return;if(e.target.id==='entry-query')list();if(e.target.id==='document-source')source();if(e.target.dataset.contentBool){const input=$$('input[name]',e.target.closest('.entry-field')).find(el=>el.name===e.target.dataset.contentBool);input.value=String(e.target.checked);e.target.nextElementSibling.textContent=e.target.checked?'Включено':'Выключено';}},true);
+ document.addEventListener('scroll',e=>{if(root()?.contains(e.target)&&e.target.id==='document-source'){const h=$('#entry-highlight'),l=$('#code-lines');h.scrollTop=e.target.scrollTop;h.scrollLeft=e.target.scrollLeft;l.scrollTop=e.target.scrollTop;}},true);
+ document.addEventListener('document:projection',e=>{
+ if(!root()?.contains(e.target))return;const doc=e.detail?.html&&new DOMParser().parseFromString(e.detail.html,'text/html');
+ if(doc){for(const selector of ['[data-content-navigation]','[data-content-diagnostics]','[data-content-panel=relations]','[data-content-panel=usage]','[data-content-panel=schema]']){const old=$(selector,root()),fresh=$(selector,doc);if(old&&fresh)old.replaceWith(fresh);}}
+ $$('[data-list-row]').forEach(row=>{const b=$(':scope > [data-content-remove]',row);if(b)b.dataset.contentRemove=row.dataset.listRow;});setTab(tab);source();
+ });
+ document.addEventListener('document:state',()=>{
+ if(!root())return;const s=window.siteDocument?.state;if(!s)return;source();const title=$('[data-inspector] [name="p.title"]')?.value||s.model?.meta.title||root().dataset.contentSource;const heading=$('[data-entry-title]');if(heading)heading.textContent=title;
+ const row=$$('[data-entry]').find(e=>e.dataset.entry===root().dataset.contentSource),entry=data().entries?.find(e=>e.slug===root().dataset.contentSource);
+ if(row&&s.model){$('.entry-row-copy>b',row).textContent=title;row.dataset.entrySearch=(title+' '+row.dataset.entry).toLocaleLowerCase();row.dataset.entryStatus=s.model.meta.status||'draft';row.dataset.entryChanged=String(Number(s.dirty||entry?.changed));const badge=$('.status',row);badge.textContent=({published:'В каталоге',draft:'Черновик',archived:'Архив'})[row.dataset.entryStatus];badge.classList.toggle('good',row.dataset.entryStatus==='published');badge.classList.toggle('warn',row.dataset.entryStatus!=='published');}list();
+ const box=$('#preview-result');box.dataset.view=root().dataset.previewView||'card';box.classList.toggle('site-card-preview',box.dataset.view==='card');box.classList.toggle('site-page-preview',box.dataset.view==='page');
+ for(const [attr,key,fallback] of [['preview','previewView','card'],['version','previewVersion','workspace']])$$('[data-content-'+attr+']').forEach(b=>{const active=b.dataset['content'+attr[0].toUpperCase()+attr.slice(1)]===(root().dataset[key]||fallback);b.classList.toggle('active',active);b.setAttribute('aria-pressed',String(active));});
+ $('[data-content-preview-state]').textContent=(root().dataset.previewVersion||'workspace')+' / '+(s.model?.meta.status||'draft');
+ const issues=s.issues||[];const messages=$('[data-content-source-errors]');if(messages)messages.textContent=issues.map(i=>i.code+' · '+i.message).join('\n');
+ });
+ document.addEventListener('keydown',e=>{if(!root()||!window.siteDocument.state)return;if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'){e.preventDefault();$('[data-save-document]').click();}if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='f'&&e.target.id==='document-source'){e.preventDefault();find();}if((e.ctrlKey||e.metaKey)&&e.key==='Enter'&&e.target.id==='document-source'){e.preventDefault();window.siteDocument.flush(true).catch(error);}});
+ document.addEventListener('htmx:load',()=>{layout();if(root()){list();source();}});if(root()){list();source();layout();}
+})();
diff --git a/src/site_engine/web/admin/static/editor.js b/src/site_engine/web/admin/static/editor.js
index 1046447..40c7a7d 100644
--- a/src/site_engine/web/admin/static/editor.js
+++ b/src/site_engine/web/admin/static/editor.js
@@ -106,7 +106,7 @@
if(parent.moveBefore)parent.moveBefore(node,one('#expert-pane',s.root));else{window.siteDocument.previewReloading();parent.insertBefore(node,one('#expert-pane',s.root));}
}
function choose(block,scroll=true,bindings=false){
- const s=current;if(!s?.valid)return;
+ const s=current;if(!s?.valid||s.root.classList.contains('entry-content-editor'))return;
if(s.page){
const t=Array.from(s.root.querySelectorAll('[data-section-inspector]')).find(e=>e.dataset.blockId===block.id&&e.dataset.blockScope===block.scope&&e.dataset.blockOwner===block.owner);if(!t)return;
const pane=t.content.querySelector('#inspectpane').cloneNode(true);hydrate(pane);movePreviewOut();one('#inspectpane',s.root).replaceWith(pane);
@@ -144,10 +144,10 @@
const form=Array.from(s.root.querySelectorAll('[data-inspector]')).find(e=>keyOf(fields(e))===key);if(!form)continue;
const active=document.activeElement,wasInside=form.contains(active);
form.querySelectorAll('[data-list-row]').forEach(row=>{if(rename(row.dataset.listRow)===null)row.remove();});
- form.querySelectorAll('[name],[data-list-name],[data-list-row],[id^="dl-"],[list^="dl-"]').forEach(node=>{
- for(const attr of ['name','data-list-name','data-list-row','id','list']){
- const value=node.getAttribute(attr);if(!value||(['id','list'].includes(attr)&&!value.startsWith('dl-')))continue;
- const prefix=['id','list'].includes(attr)?'dl-':'',next=rename(value.slice(prefix.length));if(next!==null)node.setAttribute(attr,prefix+next);
+ form.querySelectorAll('[name],[data-list-name],[data-list-row],[id],[for],[data-field-container],[data-content-picker],[data-content-picked],[data-content-tokens],[data-content-bool],[data-content-add],[data-content-remove]').forEach(node=>{
+ for(const attr of ['name','data-list-name','data-list-row','id','list','for','data-field-container','data-content-picker','data-content-picked','data-content-tokens','data-content-bool','data-content-add','data-content-remove']){
+ const value=node.getAttribute(attr);if(!value||(['id','list','for'].includes(attr)&&!value.startsWith('dl-')&&!value.startsWith('content-')))continue;
+ const prefix=['id','list','for'].includes(attr)?(value.startsWith('dl-')?'dl-':'content-'):'',next=rename(value.slice(prefix.length));if(next!==null)node.setAttribute(attr,prefix+next);
}
});
if(wasInside&&!active.isConnected)one('input:not([type=hidden]),textarea,select',form)?.focus({preventScroll:true});
@@ -223,7 +223,7 @@
if(replaceInspector&&!s.readonlySelection&&s.entryInspector){const pane=s.entryInspector.cloneNode(true);hydrate(pane);one('.doc-inspector')?.replaceWith(pane);}
}
if(!replaceInspector)reconcileInspector();
- syncSelection();s.root.dispatchEvent(new CustomEvent('document:projection',{bubbles:true}));
+ syncSelection();s.root.dispatchEvent(new CustomEvent('document:projection',{bubbles:true,detail:{html}}));
}
function passive(frame){
const s=current,p=s?.preview;if(!p||p.interactive||p.document)return;
@@ -240,6 +240,7 @@
function displayPreview(value){
const s=current;if(value.revision!==s.rev)return;
const box=one('#preview-result'),frame=one('iframe',box),p=s.preview;
+ if(!value.url){const text=document.createElement('p');text.className='preview-empty';text.textContent=value.message||'Превью недоступно.';box.replaceChildren(text);s.preview={...value,ready:true};box.dataset.revision=String(value.revision);status();return;}
if(frame&&p?.ready&&value.html){
if(p.document&&p.document===frame.contentDocument){
window.sitePreviewDocument(p.document,value.html);Object.assign(p,value,{ready:true,document:p.document});
@@ -277,16 +278,17 @@
s.requestSelection=s.selection;
s.running=(async()=>{
try{
- const result=await post(s,'update',{source,etag:s.etag,revision:rev,operations});
+ const result=await post(s,'update',{source,etag:s.etag,revision:rev,operations,preview_view:s.root.dataset.previewView||'page',preview_version:s.root.dataset.previewVersion||'workspace'});
if(!alive(s))return false;
if(result.snapshot.revision!==rev)throw {code:'revision_mismatch',message:'Ответ редактора относится к другой версии.'};
+ s.model=result.snapshot.model;s.schema=result.snapshot.schema;s.issues=result.snapshot.issues;
acknowledgeDeletes(batch);
for(const [key,edit]of batch)if(s.edits.get(key)===edit)s.edits.delete(key);
if(s.sourceEpoch===sourceEpoch){s.buffer=result.snapshot.source;s.validated=s.buffer;s.validationPending=false;s.source.value=s.buffer;}
const structural=sourceChanged||operations.some(op=>['add','delete','duplicate','move','toggle','format'].includes(op.fields.operation?.[0]))||(s.layout&&s.layout!==result.snapshot.schema.layout);
s.layout=result.snapshot.schema.layout;
- const metadata=one('[data-inspector] [name=title]',s.root);
- const title=s.edits.has('metadata:')&&metadata?metadata.value:result.snapshot.model?.meta.title||result.snapshot.id;
+ const metadata=one('[data-inspector] [name=title]',s.root),entryTitle=one('[data-inspector] [name="p.title"]',s.root);
+ const title=s.edits.has('entry_fields:')&&entryTitle?entryTitle.value:s.edits.has('metadata:')&&metadata?metadata.value:result.snapshot.model?.meta.title||result.snapshot.id;
const heading=one('.doc-toolbar h1');if(heading)heading.textContent=title;
const badge=one('[data-page-status]');if(badge)badge.textContent=result.snapshot.model?.meta.status||'draft';
const operation=operations.at(-1)?.fields.operation?.[0];
@@ -299,7 +301,7 @@
}catch(e){
if(!alive(s)||e.name==='AbortError')return false;
s.failedRev=rev;
- if(e.buffer&&s.sourceEpoch===sourceEpoch&&!batch.length){s.valid=false;projection(e.projection);}
+ if(e.buffer&&s.sourceEpoch===sourceEpoch&&!batch.length){s.valid=false;s.issues=e.issues||[];projection(e.projection);}
failure(e,e.status);return false;
}finally{if(alive(s)){s.running=null;status();}}
})();
@@ -321,7 +323,7 @@
s.saving=(async()=>{
try{
const result=await post(s,'save',{source,etag:s.etag,revision:rev});if(!alive(s))return;
- s.etag=result.snapshot.etag;s.saved=source;
+ s.etag=result.snapshot.etag;s.saved=source;if(s.rev===rev){s.model=result.snapshot.model;s.schema=result.snapshot.schema;s.issues=result.snapshot.issues;projection(result.projection);}
notice(s.rev===rev?'Документ сохранён. Публикация не выполнялась.':'Документ сохранён; новые правки ещё не сохранены.');
}catch(e){
if(!alive(s)||e.name==='AbortError')return;
@@ -332,7 +334,7 @@
})();status();await s.saving;
}
function conflict(error,source){
- const s=current;one('[data-conflict-dialog]',s.root)?.remove();
+ const s=current;if(s.root.classList.contains('entry-content-editor')){window.siteContentConflict(error,source,()=>{s.etag=error.current.etag;status();notice('Новая основа принята. Проверьте исходник и сохраните отдельной кнопкой.');});return;}one('[data-conflict-dialog]',s.root)?.remove();
const dialog=document.createElement('dialog');dialog.className='modal builder-dialog expert-conflict-dialog conflict-panel';dialog.dataset.conflictDialog='';
dialog.innerHTML='Документ изменён на сервере Ваши правки остаются в редакторе. Сравните версии и выполните слияние в «Эксперте».
';
const texts=dialog.querySelectorAll('textarea');texts[0].value=source;texts[1].value=error.current.source;
@@ -340,7 +342,7 @@
s.root.append(dialog);dialog.addEventListener('close',()=>dialog.remove(),{once:true});dialog.showModal();
}
async function leave(action){
- const s=current,confirm=s.page?window.siteBuilderConfirm:window.siteAdminConfirm;
+ const s=current,confirm=s.page?window.siteBuilderConfirm:(s.root.classList.contains('entry-content-editor')?window.siteContentConfirm:window.siteAdminConfirm);
if(dirty()&&!await confirm('Есть несохранённые изменения','При переходе правки этой вкладки будут потеряны. Сохраните документ, если хотите оставить изменения.','Уйти без сохранения'))return false;
if(!alive(s))return false;clearTimeout(s.timer);s.controller.abort();action();return true;
}
@@ -354,13 +356,14 @@
if(!root){current=null;return;}
const form=one('#buffer-form',root),raw=JSON.parse(root.dataset.rawSource);
current={root,form,source:one('#document-source',root),buffer:raw,saved:JSON.parse(root.dataset.canonicalSource),validated:raw,rev:Number(root.dataset.revision),etag:form.elements.etag.value,
- page:root.classList.contains('page-builder'),mode:form.elements.mode.value||'constructor',selection:form.elements.selection.value,readonlySelection:one('#editor-result').dataset.readonly||'',valid:one('#editor-result').dataset.valid==='1',
+ model:null,schema:null,issues:[],page:root.classList.contains('page-builder'),mode:form.elements.mode.value||'constructor',selection:form.elements.selection.value,readonlySelection:one('#editor-result').dataset.readonly||'',valid:one('#editor-result').dataset.valid==='1',
edits:new Map(),fieldValues:new Map(),validationPending:false,sourceEpoch:0,failedRev:-1,timer:null,running:null,saving:null,controller:new AbortController(),preview:null,viewport:{x:0,y:0},device:'desktop'};
hydrate(root);root.dataset.ready='1';showMode(current.valid?current.mode:'expert');flush(true);
}
window.siteDocument={
- get state(){const s=current;return s?{source:s.buffer,saved:s.saved,dirty:dirty(),mode:s.mode,busy:!!(s.running||s.saving),base:s.root.dataset.base}:null;},
+ get state(){const s=current;return s?{source:s.buffer,saved:s.saved,dirty:dirty(),mode:s.mode,busy:!!(s.running||s.saving),base:s.root.dataset.base,etag:s.etag,revision:s.rev,model:s.model,schema:s.schema,issues:s.issues,path:one('.doc-toolbar code',s.root)?.textContent}:null;},
notice,leave,flush,
+ preview:(view,version)=>{const s=current;if(view)s.root.dataset.previewView=view;if(version)s.root.dataset.previewVersion=version;s.rev++;s.failedRev=-1;status();return enqueue(()=>flush(true));},
previewReloading:()=>{const s=current;if(s?.preview){s.preview.ready=false;s.preview.document=null;setTimeout(()=>{if(alive(s)&&!s.preview.ready)displayPreview({...s.preview,html:''});},0);}},
change:element=>remember(element,true),
transform:values=>enqueue(()=>transform(values)),
@@ -389,7 +392,7 @@
document.addEventListener('change',event=>{if(current?.root.contains(event.target)&&event.target.closest('[data-inspector]'))remember(event.target,true);});
document.addEventListener('submit',event=>{
const s=current;if(!s)return;const form=event.target;
- if(form.closest('#document-editor')){
+ if(form.closest('#document-editor')&&!form.hasAttribute('data-content-create')){
if(form.method==='dialog')return;
event.preventDefault();event.stopImmediatePropagation();
const submitter=event.submitter,data=fields(form,submitter),action=new URL(submitter?.hasAttribute('formaction')?submitter.formAction:form.action).pathname.split('/').pop();
diff --git a/src/site_engine/web/admin/static/favicon.svg b/src/site_engine/web/admin/static/favicon.svg
new file mode 100644
index 0000000..625fd36
--- /dev/null
+++ b/src/site_engine/web/admin/static/favicon.svg
@@ -0,0 +1 @@
+
diff --git a/src/site_engine/web/admin/static/publication-adapter.css b/src/site_engine/web/admin/static/publication-adapter.css
new file mode 100644
index 0000000..22239ca
--- /dev/null
+++ b/src/site_engine/web/admin/static/publication-adapter.css
@@ -0,0 +1,24 @@
+/* Runtime/CSP/native-dialog adapters; composition and declarations are in publication.css. */
+.content.publication-content { padding:0; max-width:none; }
+.publication-content { min-width:0; }
+.publication-content [hidden] { display:none!important; }
+.publication-content .wrap { font-size:13px; }
+.publication-content .publication-footer { display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap;margin-top:20px;color:var(--muted2);font-size:10px; }
+.publication-content .note-spaced { margin-top:16px; }
+.publication-content .note-separated { margin:16px 0; }
+.publication-content .inline-actions { display:flex;gap:8px;flex-wrap:wrap;margin-top:15px; }
+.publication-content .pipe strong,.publication-content .build-row small,.publication-content .live-identity strong,.publication-content .sum strong { overflow-wrap:anywhere; }
+.publication-content .live-symbol { flex:none; }
+.publication-content .dialog { padding:0; margin:auto; }
+.publication-content .dialog:not([open]) { display:none; }
+.publication-content .dialog[open] { display:flex; }
+.publication-content .dialog::backdrop { background:rgba(0,0,0,.65); }
+.publication-content .dialog-head h2 { color:var(--fg); }
+.publication-content .dialog-actions { flex-wrap:wrap; }
+.publication-content #publication-notice { position:fixed;bottom:18px;right:18px;max-width:min(430px,calc(100vw - 32px));pointer-events:none;z-index:80; }
+.publication-content #publication-notice:not(:empty) { background:var(--fg);color:var(--bg);padding:12px 16px;border-radius:7px;box-shadow:0 12px 28px #0005;font-size:11px; }
+.publication-content .release-preview { width:100%;height:420px;border:1px solid var(--border);background:var(--panel); }
+.publication-content .publication-error { overflow-wrap:anywhere; }
+/* Use the accepted Antirion dark palette; the design's Rose palette is a separate theme. */
+body[data-skin=dark] .publication-content { color-scheme:dark;--bg:var(--paper);--fg:var(--ink);--muted:var(--secondary);--muted2:var(--dim);--panel:var(--paper);--panel-soft:var(--paper2);--panel-hover:var(--paper3);--border:var(--stroke);--border2:var(--stroke2);--accent:var(--focus);--accent-bg:var(--paper3);--accent-on:#fff;--positive:var(--good);--positive-bg:var(--goodbg);--warning:var(--warn);--warning-bg:var(--warnbg);--negative:var(--error);--negative-bg:var(--errorbg);--shadow:none; }
+@media(max-width:760px) { .publication-content .check{flex-wrap:wrap}.publication-content .heading-actions{width:100%}.publication-content .heading-actions .button{flex:1}.publication-content .dialog { max-width:calc(100% - 28px) }.publication-content .dialog-head,.publication-content .dialog-content,.publication-content .dialog-actions{padding-left:14px;padding-right:14px} }
diff --git a/src/site_engine/web/admin/static/publication-icons.json b/src/site_engine/web/admin/static/publication-icons.json
new file mode 100644
index 0000000..1c17561
--- /dev/null
+++ b/src/site_engine/web/admin/static/publication-icons.json
@@ -0,0 +1 @@
+{"home": "M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h7v7h-7z", "pages": "M7 3h10l4 4v14H7z M17 3v5h4 M11 13h6 M11 17h6", "content": "M12 2 3 7l9 5 9-5-9-5z M3 12l9 5 9-5 M3 17l9 5 9-5", "publish": "M12 3v13m-5-5 5 5 5-5 M4 17v4h16v-4", "media": "M3 3h18v18H3z M7 16l4-4 3 3 3-3 4 4", "settings": "M4 6h16 M4 12h16 M4 18h16", "history": "M4 3h16v18H4z M8 9h8 M8 13h8 M8 17h5", "search": "M11 3a8 8 0 1 0 0 16a8 8 0 0 0 0-16z M17 17l4 4", "check": "M4 12l5 5 11-11", "alert": "M12 2 2 21h20L12 2z M12 9v5 M12 17v1", "plus": "M12 4v16 M4 12h16", "file": "M6 2h10l4 4v16H6z M16 2v5h4 M9 12h8 M9 16h8", "arrow": "M4 12h16m-6-6 6 6-6 6", "eye": "M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6", "refresh": "M3 11a9 9 0 1 1 3 7 M3 5v6h6", "shield": "M12 2l8 4v6c0 6-4 9-8 10-4-1-8-4-8-10V6z", "code": "M8 7l-5 5 5 5 M16 7l5 5-5 5", "menu": "M3 6h18 M3 12h18 M3 18h18", "close": "M5 5l14 14 M19 5 5 19", "clock": "M12 2a10 10 0 1 0 0 20a10 10 0 0 0 0-20z M12 7v6l4 2", "layers": "M3 7l9-4 9 4-9 5-9-5 M3 13l9 5 9-5", "copy": "M8 8h13v13H8z M3 3h13v4 M3 3v13h4"}
diff --git a/src/site_engine/web/admin/static/publication.css b/src/site_engine/web/admin/static/publication.css
new file mode 100644
index 0000000..fad47ad
--- /dev/null
+++ b/src/site_engine/web/admin/static/publication.css
@@ -0,0 +1,24 @@
+/* Generated by scripts/sync_publication_design.py; original declarations unchanged. */
+/* Stage 5 / Publication Design Prototype — responsive, static, no CDN */
+:where(.publication-content){font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Arial,sans-serif;font-synthesis:none;font-size:13px}
+:where(.publication-content) *{box-sizing:border-box}:where(.publication-content){margin:0;min-width:320px;min-height:100vh;background:var(--bg);color:var(--fg)}:where(.publication-content) button,:where(.publication-content) input,:where(.publication-content) select,:where(.publication-content) textarea{font:inherit}:where(.publication-content) button{cursor:pointer}:where(.publication-content) button:disabled{cursor:not-allowed;opacity:.42}:where(.publication-content) button:focus-visible,:where(.publication-content) input:focus-visible,:where(.publication-content) select:focus-visible,:where(.publication-content) a:focus-visible{outline:2px solid var(--accent);outline-offset:2px}:where(.publication-content) a{color:inherit;text-decoration:none}:where(.publication-content) svg{width:16px;height:16px;vertical-align:middle;flex:none}:where(.publication-content) .mono,:where(.publication-content) code{font-family:ui-monospace,SFMono-Regular,Consolas,"Liberation Mono",monospace}:where(.publication-content) code{overflow-wrap:anywhere}:where(.publication-content) .muted{color:var(--muted)}:where(.publication-content) .sr-only{position:absolute;clip:rect(0,0,0,0);width:1px;height:1px;overflow:hidden}
+:where(.publication-content){color-scheme:light;--nav:#151719;--nav-border:#343639;--nav-text:#aeb3b7;--nav-active:#2a2c31;--bg:#f7f7f5;--fg:#22252a;--muted:#74777e;--muted2:#9fa2a8;--panel:#fff;--panel-soft:#f1f1ef;--panel-hover:#f7f6fc;--border:#dedfdd;--border2:#ecece9;--accent:#7564da;--accent-bg:#f0edff;--accent-on:#fff;--positive:#27745b;--positive-bg:#e6f5eb;--warning:#98601d;--warning-bg:#fff0d7;--negative:#a13c52;--negative-bg:#fcebef;--radius:5px;--shadow:0 4px 16px rgba(20,19,33,.035)}
+:where(.publication-content)[data-unused-rose]{color-scheme:dark;--nav:#07080a;--nav-border:#27272a;--nav-text:#929299;--nav-active:#1e1e20;--bg:#0c0c0f;--fg:#f5f3f5;--muted:#a0a0a9;--muted2:#71727a;--panel:#131316;--panel-soft:#1c1c20;--panel-hover:#20151d;--border:#303035;--border2:#27272b;--accent:#f3559b;--accent-bg:#341625;--accent-on:#fff;--positive:#32d19b;--positive-bg:#103429;--warning:#e7bd71;--warning-bg:#392a1e;--negative:#f4909f;--negative-bg:#381b25;--radius:12px;--shadow:none}
+:where(.publication-content) .layout{display:grid;grid-template-columns:218px minmax(0,1fr);min-height:100vh}:where(.publication-content) .side{position:sticky;top:0;height:100vh;display:flex;flex-direction:column;background:var(--nav);border-right:1px solid var(--nav-border);color:var(--nav-text);z-index:15;min-width:0}:where(.publication-content) .brand{display:flex;align-items:center;gap:10px;height:76px;padding:15px 16px;border-bottom:1px solid var(--nav-border)}:where(.publication-content) .brand-logo{width:36px;height:36px;display:grid;place-items:center;background:linear-gradient(145deg,#ed9ecd,#d85197);color:#fff;font-size:20px;border-radius:10px;font-weight:900}:where(.publication-content) .brand-name{font-size:13px;color:#fff;font-weight:730}:where(.publication-content) .brand-tag{font-size:9px;letter-spacing:.12em;color:#898990;margin-top:3px;font-weight:700}:where(.publication-content) .side-nav{padding:16px 9px;flex:1;overflow:auto}:where(.publication-content) .navlabel{font-size:9px;letter-spacing:.12em;color:#666a73;padding:10px 12px 9px;font-weight:800}:where(.publication-content) .side-link{display:flex;align-items:center;gap:12px;min-height:39px;padding:8px 12px;color:#a4a6ab;border-radius:6px;margin-bottom:2px;position:relative;font-size:12px}:where(.publication-content) .side-link:hover{color:#fff;background:#232428}:where(.publication-content) .side-link.active{color:#fff;background:var(--nav-active);font-weight:660}:where(.publication-content) .side-link.active:before{position:absolute;left:0;top:7px;bottom:7px;width:3px;background:var(--accent);border-radius:4px;content:""}:where(.publication-content) .side-link em{font-style:normal;font-size:10px;opacity:.8;margin-left:auto}:where(.publication-content) .bottom{padding:14px 12px 18px;border-top:1px solid var(--nav-border)}:where(.publication-content) .site-picker{border:1px solid #323239;border-radius:8px;padding:11px;color:#fff;display:flex;gap:8px;align-items:center;background:#17181b}:where(.publication-content) .site-picker small{display:block;color:#94959e;font-size:10px;margin-top:4px}:where(.publication-content) .tiny{font-size:10px}:where(.publication-content) .side-note{display:flex;align-items:center;gap:8px;margin-top:14px;color:#9a9ba3;font-size:10px}:where(.publication-content) .side-note .dot{width:7px;height:7px;background:#30c98d;border-radius:50%;flex:none}
+:where(.publication-content) .main{min-width:0;display:flex;flex-direction:column}:where(.publication-content) .top{height:60px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:13px;padding:0 28px;background:var(--panel);flex:none;position:sticky;top:0;z-index:12}:where(.publication-content) .crumb{display:flex;align-items:center;gap:10px;font-size:11px;color:var(--muted);min-width:0}:where(.publication-content) .crumb strong{color:var(--fg);font-weight:680}:where(.publication-content) .push{flex:1}:where(.publication-content) .live-indicator{white-space:nowrap;display:flex;align-items:center;gap:7px;font-size:10px;font-weight:750}:where(.publication-content) .live-indicator .dot{background:var(--positive);border-radius:50%;width:7px;height:7px}:where(.publication-content) .avatar{border:1px solid var(--border);background:var(--panel-soft);color:var(--fg);display:grid;place-items:center;width:30px;height:30px;border-radius:6px;font-size:10px;font-weight:750}:where(.publication-content) .mobile-menu{display:none}:where(.publication-content) .icon-btn{width:32px;height:32px;border:1px solid transparent;background:transparent;color:var(--muted);display:grid;place-items:center;border-radius:6px}:where(.publication-content) .icon-btn:hover{border-color:var(--border);color:var(--fg)}
+:where(.publication-content) .wrap{padding:32px 28px 45px;max-width:1800px;width:100%;margin:0 auto}:where(.publication-content) .overline{text-transform:uppercase;font:700 10px/1.5 ui-monospace,monospace;letter-spacing:.11em;color:var(--accent)}:where(.publication-content) .heading{display:flex;align-items:flex-end;justify-content:space-between;gap:20px;padding-bottom:20px}:where(.publication-content) .heading h1{margin:8px 0 8px;font-size:clamp(26px,3.2vw,38px);letter-spacing:-.045em;font-weight:690}:where(.publication-content) .heading p{color:var(--muted);font-size:12px;line-height:1.55;margin:0;max-width:650px}:where(.publication-content) .heading-actions{display:flex;gap:7px;align-items:center;flex-wrap:wrap}:where(.publication-content) .button{border:1px solid var(--border);padding:0 13px;min-height:34px;border-radius:6px;background:var(--panel);color:var(--fg);display:inline-flex;align-items:center;justify-content:center;gap:7px;font-weight:660;font-size:11px;white-space:nowrap}:where(.publication-content) .button:hover:not(:disabled){background:var(--panel-soft);border-color:var(--accent)}:where(.publication-content) .button.primary{background:var(--accent);border-color:var(--accent);color:var(--accent-on)}:where(.publication-content) .button.primary:hover:not(:disabled){filter:brightness(1.07)}:where(.publication-content) .button.subtle{background:transparent}:where(.publication-content) .button.danger{color:var(--negative);border-color:var(--negative)}:where(.publication-content) .button.tiny{min-height:28px;padding:0 9px;font-size:10px}:where(.publication-content) .button svg{width:14px;height:14px}:where(.publication-content) .chip{display:inline-flex;align-items:center;gap:6px;padding:4px 8px;font-size:10px;line-height:1.2;font-weight:670;border-radius:5px;white-space:nowrap;background:var(--panel-soft);color:var(--muted)}:where(.publication-content) .chip:before{content:"";width:5px;height:5px;border-radius:50%;background:currentColor}:where(.publication-content) .chip.good{background:var(--positive-bg);color:var(--positive)}:where(.publication-content) .chip.warn{background:var(--warning-bg);color:var(--warning)}:where(.publication-content) .chip.bad{background:var(--negative-bg);color:var(--negative)}:where(.publication-content) .chip.purple{background:var(--accent-bg);color:var(--accent)}
+:where(.publication-content) .livebar{border:1px solid var(--border);border-radius:var(--radius);background:var(--panel);padding:17px 20px;display:flex;align-items:center;gap:20px;margin-bottom:20px}:where(.publication-content) .live-identity{display:flex;align-items:center;gap:12px;min-width:0}:where(.publication-content) .live-symbol{width:38px;height:38px;background:var(--positive-bg);color:var(--positive);display:grid;place-items:center;border-radius:9px}:where(.publication-content) .live-identity strong{display:block;font-size:14px}:where(.publication-content) .live-identity small{display:block;font-size:10px;color:var(--muted);margin-top:5px}:where(.publication-content) .live-actions{margin-left:auto;display:flex;gap:8px;align-items:center}:where(.publication-content) .pipeline{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-bottom:22px}:where(.publication-content) .pipe{border:1px solid var(--border);border-radius:var(--radius);background:var(--panel);padding:16px 18px;min-width:0;position:relative}:where(.publication-content) .pipe:before{content:"";position:absolute;top:-1px;left:16px;right:16px;height:2px;background:var(--border)}:where(.publication-content) .pipe:nth-child(1):before{background:var(--accent)}:where(.publication-content) .pipe:nth-child(2):before{background:var(--warning)}:where(.publication-content) .pipe:nth-child(3):before{background:var(--positive)}:where(.publication-content) .pipe .step{display:flex;justify-content:space-between;align-items:center;gap:8px;color:var(--muted);font-size:10px;text-transform:uppercase;letter-spacing:.08em;font-weight:700}:where(.publication-content) .pipe strong{font-size:20px;letter-spacing:-.035em;display:block;margin:12px 0 7px}:where(.publication-content) .pipe p{margin:0;font-size:11px;line-height:1.5;color:var(--muted)}
+:where(.publication-content) .tabs{display:flex;gap:20px;border-bottom:1px solid var(--border);margin:8px 0 22px;min-width:0;overflow-x:auto;scrollbar-width:thin}:where(.publication-content) .tab{background:none;border:0;border-bottom:2px solid transparent;color:var(--muted);padding:12px 2px;font-size:12px;white-space:nowrap;font-weight:620}:where(.publication-content) .tab.active{color:var(--fg);border-color:var(--accent)}:where(.publication-content) .tab .num{font-size:10px;padding:2px 5px;background:var(--panel-soft);border-radius:4px;margin-left:5px;color:var(--muted)}:where(.publication-content) .split{display:grid;grid-template-columns:minmax(0,1.65fr) minmax(270px,.85fr);gap:17px}:where(.publication-content) .stack{display:flex;flex-direction:column;gap:17px;min-width:0}:where(.publication-content) .panel{background:var(--panel);border:1px solid var(--border);border-radius:var(--radius);min-width:0;overflow:hidden;box-shadow:var(--shadow)}:where(.publication-content) .panel-header{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px 18px;border-bottom:1px solid var(--border2)}:where(.publication-content) .panel-header h2,:where(.publication-content) .panel-header h3{margin:0;font-size:13px;font-weight:730}:where(.publication-content) .panel-header p{margin:5px 0 0;color:var(--muted);font-size:10px}:where(.publication-content) .panel-body{padding:18px}:where(.publication-content) .panel-tools{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:12px 16px;border-bottom:1px solid var(--border2)}:where(.publication-content) .search{min-height:33px;display:flex;gap:9px;align-items:center;padding:0 10px;border:1px solid var(--border);border-radius:6px;background:var(--bg);flex:1;min-width:140px}:where(.publication-content) .search input{border:0;outline:0;background:transparent;color:var(--fg);width:100%;min-width:0;font-size:11px}:where(.publication-content) .search svg{color:var(--muted)}:where(.publication-content) select,:where(.publication-content) textarea,:where(.publication-content) input[type=text]{border:1px solid var(--border);background:var(--panel);color:var(--fg);border-radius:6px;min-height:34px;padding:7px 10px;min-width:0}:where(.publication-content) .panel-tools select{min-width:116px}:where(.publication-content) .table-scroll{overflow-x:auto;max-width:100%}:where(.publication-content) .table{width:100%;border-collapse:collapse;min-width:610px;text-align:left;font-size:11px}:where(.publication-content) .table th{background:var(--panel-soft);color:var(--muted);font-size:9px;text-transform:uppercase;letter-spacing:.07em;font-weight:720;padding:12px 13px}:where(.publication-content) .table td{padding:11px 13px;border-bottom:1px solid var(--border2);vertical-align:middle}:where(.publication-content) .table tr:last-child td{border-bottom:0}:where(.publication-content) .table tbody tr:hover{background:var(--panel-hover)}:where(.publication-content) .table tbody tr.selected{background:var(--accent-bg)}:where(.publication-content) .table .file-name{font-weight:690;overflow-wrap:anywhere}:where(.publication-content) .file-sub{display:block;font-size:10px;color:var(--muted);margin-top:4px;overflow-wrap:anywhere}:where(.publication-content) .table a{text-decoration:underline;text-decoration-color:var(--border)}:where(.publication-content) .file-button{border:0;background:transparent;color:var(--fg);font-weight:700;padding:0;text-align:left;font-size:11px}:where(.publication-content) .file-button:hover{color:var(--accent)}:where(.publication-content) .table-footer{display:flex;justify-content:space-between;gap:12px;color:var(--muted);font-size:10px;padding:12px 16px;border-top:1px solid var(--border2)}
+:where(.publication-content) .kv{display:grid;grid-template-columns:100px minmax(0,1fr);gap:10px;border-bottom:1px solid var(--border2);padding:10px 0;font-size:11px}:where(.publication-content) .kv:last-child{border-bottom:0}:where(.publication-content) .kv b{font-weight:620;overflow-wrap:anywhere}:where(.publication-content) .kv span{color:var(--muted)}:where(.publication-content) .note{font-size:11px;line-height:1.55;padding:12px 13px;border-left:2px solid var(--accent);background:var(--accent-bg);color:var(--fg)}:where(.publication-content) .empty{padding:29px;text-align:center;color:var(--muted);font-size:11px;line-height:1.6}:where(.publication-content) .empty strong{display:block;color:var(--fg);font-size:13px;margin-bottom:4px}:where(.publication-content) .check{display:flex;align-items:flex-start;gap:12px;padding:13px 16px;border-bottom:1px solid var(--border2)}:where(.publication-content) .check svg{width:17px;height:17px;color:var(--muted)}:where(.publication-content) .check.bad svg{color:var(--negative)}:where(.publication-content) .check.warn svg{color:var(--warning)}:where(.publication-content) .check.good svg{color:var(--positive)}:where(.publication-content) .check-info{min-width:0;flex:1}:where(.publication-content) .check-info b{display:block;font-size:11px}:where(.publication-content) .check-info small{display:block;color:var(--muted);margin-top:5px;overflow-wrap:anywhere;line-height:1.5}:where(.publication-content) .check-actions{display:flex;gap:6px;align-items:center;flex-wrap:wrap}:where(.publication-content) .inline-info{display:flex;align-items:center;gap:8px;color:var(--muted);font-size:10px;line-height:1.5;padding:10px 16px;background:var(--panel-soft)}:where(.publication-content) .summary{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;padding:14px 16px;border-bottom:1px solid var(--border2)}:where(.publication-content) .sum{padding:10px;border-radius:6px;background:var(--panel-soft);min-width:0}:where(.publication-content) .sum strong{font-size:20px;display:block}:where(.publication-content) .sum span{font-size:10px;color:var(--muted)}:where(.publication-content) .log{margin:0;white-space:pre-wrap;overflow-wrap:anywhere;background:var(--panel-soft);border-radius:6px;padding:14px;font:11px/1.75 ui-monospace,monospace}:where(.publication-content) .source-compare{display:grid;grid-template-columns:1fr 1fr;gap:10px}:where(.publication-content) .compare-col{padding:12px;border:1px solid var(--border);border-radius:7px;min-width:0}:where(.publication-content) .compare-col h4{font-size:10px;text-transform:uppercase;letter-spacing:.08em;margin:0 0 8px;color:var(--muted)}:where(.publication-content) .compare-col pre{font:11px/1.65 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:0;color:var(--fg)}:where(.publication-content) .compare-col .preview-mini{border:1px solid var(--border);background:var(--panel-soft);padding:13px;border-radius:6px;margin-top:8px}:where(.publication-content) .mini-head{height:10px;border-radius:4px;background:var(--border);width:70%;margin-bottom:14px}:where(.publication-content) .mini-line{height:6px;border-radius:3px;background:var(--border);margin-bottom:8px;width:90%}:where(.publication-content) .mini-line:nth-child(odd){width:65%}:where(.publication-content) .mini-pill{height:17px;background:var(--accent);width:75px;border-radius:4px;margin-top:12px}
+:where(.publication-content) .builds{display:flex;flex-direction:column}:where(.publication-content) .build-row{display:grid;grid-template-columns:105px minmax(0,1fr) 140px auto;align-items:center;gap:15px;padding:14px 16px;border-bottom:1px solid var(--border2);font-size:11px}:where(.publication-content) .build-row:last-child{border-bottom:0}:where(.publication-content) .build-row strong{display:block;font-size:11px}:where(.publication-content) .build-row small{display:block;color:var(--muted);font-size:10px;margin-top:5px}:where(.publication-content) .build-row .code-id{font:700 11px ui-monospace,monospace;overflow-wrap:anywhere}:where(.publication-content) .build-row .actions{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}:where(.publication-content) .bullet{width:6px;height:6px;border-radius:50%;display:inline-block;background:var(--accent);margin-right:7px}
+:where(.publication-content) .timeline{display:flex;flex-direction:column;gap:13px;padding:16px 18px}:where(.publication-content) .event{border-left:2px solid var(--border);padding-left:14px;font-size:11px;line-height:1.5}:where(.publication-content) .event b{display:block}:where(.publication-content) .event small{display:block;color:var(--muted);margin-top:3px}:where(.publication-content) .event.publish{border-color:var(--positive)}:where(.publication-content) .event.rollback{border-color:var(--warning)}:where(.publication-content) .event.failure{border-color:var(--negative)}
+:where(.publication-content) #modal-root:empty{display:none}:where(.publication-content) .modal-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.65);display:grid;place-items:center;z-index:50;padding:20px}:where(.publication-content) .dialog{background:var(--panel);border:1px solid var(--border);color:var(--fg);width:min(630px,100%);max-height:min(88vh,850px);display:flex;flex-direction:column;border-radius:var(--radius);box-shadow:0 20px 80px #0005}:where(.publication-content) .dialog.wide{width:min(950px,100%)}:where(.publication-content) .dialog-head{display:flex;justify-content:space-between;gap:14px;padding:19px 22px 15px;border-bottom:1px solid var(--border)}:where(.publication-content) .dialog-head h2{font-size:17px;margin:0 0 4px}:where(.publication-content) .dialog-head p{font-size:11px;color:var(--muted);margin:0}:where(.publication-content) .dialog-content{overflow:auto;padding:20px 22px}:where(.publication-content) .dialog-actions{display:flex;gap:8px;justify-content:flex-end;padding:14px 22px;border-top:1px solid var(--border)}:where(.publication-content) .field{display:block;margin:0 0 14px;font-size:11px;font-weight:670}:where(.publication-content) .field input,:where(.publication-content) .field textarea,:where(.publication-content) .field select{display:block;margin-top:7px;width:100%;min-height:35px}:where(.publication-content) .field textarea{resize:vertical;min-height:75px}:where(.publication-content) .warning-box{border:1px solid var(--negative);padding:13px;border-radius:8px;background:var(--negative-bg);font-size:11px;line-height:1.6;margin:12px 0}:where(.publication-content) .dialog pre{max-height:320px;overflow:auto}:where(.publication-content) #notice{position:fixed;bottom:18px;right:18px;max-width:min(430px,calc(100vw - 32px));pointer-events:none;z-index:80}:where(.publication-content) #notice:not(:empty){background:var(--fg);color:var(--bg);padding:12px 16px;border-radius:7px;box-shadow:0 12px 28px #0005;font-size:11px}:where(.publication-content) .mobile-cover{display:none}:where(.publication-content) .responsive-only{display:none}
+:where(.publication-content) .brand-logo{background:#f4f4f1;color:#1b1d21;clip-path:polygon(0 0,100% 0,100% 76%,78% 100%,0 100%);border-radius:0}:where(.publication-content) .side-link.active:before{background:#c4b9ff}:where(.publication-content)[data-unused-rose] .brand-logo{background:linear-gradient(135deg,#fa823a,#ff3f8d);border-radius:10px}:where(.publication-content)[data-unused-rose] .side-link.active{border-radius:12px}:where(.publication-content)[data-unused-rose] .pipe,:where(.publication-content)[data-unused-rose] .panel{box-shadow:none}:where(.publication-content)[data-unused-rose] .table tbody tr.selected{background:#261723}:where(.publication-content)[data-unused-rose] .button.primary{background:linear-gradient(110deg,#f07655,#ed438c)}
+@media(max-width:1200px){:where(.publication-content) .wrap{padding:28px 20px}:where(.publication-content) .top{padding:0 20px}:where(.publication-content) .layout{grid-template-columns:196px minmax(0,1fr)}:where(.publication-content) .split{grid-template-columns:minmax(0,1.3fr) minmax(235px,.8fr)}}
+@media(max-width:990px){:where(.publication-content) .split{grid-template-columns:1fr}:where(.publication-content) .pipeline{gap:9px}:where(.publication-content) .pipe{padding:13px}:where(.publication-content) .pipe strong{font-size:17px}:where(.publication-content) .build-row{grid-template-columns:95px 1fr auto}:where(.publication-content) .build-row .meta-date{display:none}}
+@media(max-width:760px){:where(.publication-content) .layout{grid-template-columns:minmax(0,1fr)}:where(.publication-content) .side{position:fixed;left:0;top:0;width:248px;height:100dvh;transform:translateX(-104%);transition:transform .18s ease;box-shadow:0 10px 40px #0006}:where(.publication-content) .layout.menu-open .side{transform:translateX(0)}:where(.publication-content) .mobile-cover{display:block;position:fixed;inset:0;background:#0009;z-index:14;opacity:0;pointer-events:none}:where(.publication-content) .layout.menu-open .mobile-cover{opacity:1;pointer-events:auto}:where(.publication-content) .mobile-menu{display:grid}:where(.publication-content) .top{padding:0 15px}:where(.publication-content) .top .crumb{overflow:hidden}:where(.publication-content) .crumb .hide-small{display:none}:where(.publication-content) .live-indicator{font-size:9px}:where(.publication-content) .heading{align-items:flex-start;flex-direction:column}:where(.publication-content) .wrap{padding:23px 14px 35px}:where(.publication-content) .livebar{flex-wrap:wrap;padding:14px}:where(.publication-content) .live-actions{width:100%;justify-content:space-between;margin:0}:where(.publication-content) .pipeline{grid-template-columns:1fr}:where(.publication-content) .pipe{padding:12px 14px}:where(.publication-content) .pipe strong{margin:7px 0 3px}:where(.publication-content) .tabs{margin-bottom:15px}:where(.publication-content) .build-row{grid-template-columns:90px minmax(0,1fr);gap:9px}:where(.publication-content) .build-row .actions{grid-column:2;justify-content:flex-start}:where(.publication-content) .source-compare{grid-template-columns:1fr}:where(.publication-content) .summary{gap:6px}:where(.publication-content) .sum{padding:8px}:where(.publication-content) .panel-header,:where(.publication-content) .panel-body{padding:14px}:where(.publication-content) .heading-actions .button{flex:1}}
+@media(max-width:420px){:where(.publication-content) .top .live-indicator .mono{display:none}:where(.publication-content) .button{font-size:10px;padding:0 10px}:where(.publication-content) .panel-tools{padding:11px;gap:7px}:where(.publication-content) .panel-tools select{flex:1;min-width:0}:where(.publication-content) .search{flex-basis:100%}:where(.publication-content) .table{min-width:560px}:where(.publication-content) .heading h1{font-size:27px}:where(.publication-content) .livebar .chip{font-size:9px}}
+@media(prefers-reduced-motion:reduce){:where(.publication-content) *{transition:none!important;scroll-behavior:auto!important}}
+/* Header mobile trigger should remain hidden at desktop widths (icon-btn displays grid). */
+:where(.publication-content) .top .mobile-menu{display:none}
+@media(max-width:760px){:where(.publication-content) .top .mobile-menu{display:grid}}
diff --git a/src/site_engine/web/admin/static/publication.js b/src/site_engine/web/admin/static/publication.js
new file mode 100644
index 0000000..b3d7684
--- /dev/null
+++ b/src/site_engine/web/admin/static/publication.js
@@ -0,0 +1,225 @@
+/* Publication: original design composition and interactions, real FastAPI operations.
+ * Browser storage is never a source of release/workspace state. */
+(() => {
+ 'use strict';
+ if (window.sitePublication) return;
+ window.sitePublication = true;
+ const $ = (q, root = document) => root?.querySelector(q);
+ const esc = x => String(x ?? '').replace(/[&<>"']/g, ch => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[ch]));
+ const tabs = ['changes', 'checks', 'candidate', 'history', 'activity'];
+ let root, data, csrf, icons = {}, busy = false, generation = 0, invoker;
+ let state = {tab:'changes', filter:'all', query:'', type:'all', selected:''};
+ const icon = n => ` `;
+ const btn = (text, action, cls = '', extra = '') => `${text} `;
+ const chip = (text, style = '') => `${esc(text)} `;
+ const date = value => value ? new Date(value).toLocaleString('ru-RU') : '—';
+ const chosen = () => data.changes.find(x => x.path === state.selected) || data.changes[0] || null;
+ const issues = () => data.validation?.issues || [];
+ const editUrl = c => !c || !c.after ? '' : c.type === 'Page' ? '/admin/pages/' + c.path.slice(6, -3).split('/').map(encodeURIComponent).join('/') : c.type === 'Entry' ? '/admin/content/' + c.path.slice(8, -3).split('/').map(encodeURIComponent).join('/') : c.path === 'theme.yaml' ? '/admin/theme' : '';
+ function notify(message) {
+ const el = $('#publication-notice', root);
+ if (el) el.textContent = message;
+ }
+ function error(detail, status) {
+ window.siteAdminError?.(detail, status);
+ notify([detail.message, detail.code, detail.request_id && 'ID запроса: ' + detail.request_id].filter(Boolean).join(' · '));
+ }
+ async function call(operation, payload, query = '') {
+ const originRoot=root,originGeneration=generation;
+ const options = {headers:{Accept:'application/json'}};
+ if (payload !== undefined) {
+ const form = new FormData();
+ form.set('csrf', csrf); form.set('payload', JSON.stringify(payload));
+ options.method = 'POST'; options.body = form;
+ }
+ let response;
+ try { response = await fetch('/admin/publication/' + operation + query, options); }
+ catch (_) { throw {status:0, detail:{code:'network_error', message:'Нет связи с сервером. Обновите состояние перед повтором операции.'}}; }
+ let result;
+ try { result = await response.json(); }
+ catch (_) { throw {status:response.status, detail:{code:'invalid_response', message:'Сервер вернул некорректный ответ. Обновите состояние перед повтором.', request_id:response.headers.get('X-Request-ID')}}; }
+ if(originGeneration!==generation||!originRoot?.isConnected)throw {cancelled:true};
+ if (!response.ok) throw {status:response.status, detail:result.error || {code:'http_error', message:'Не удалось выполнить запрос'}};
+ return result;
+ }
+ function heading() {
+ return `05 / RELEASE WORKFLOW · ATOMIC SITE RELEASES
Публикация сайта Проверьте изменённые документы, соберите снимок-кандидат и переключите live. Редактируемые файлы workspace остаются отдельно от неизменяемого релиза.
${btn(icon('check')+' Проверить','validate')}${btn(icon('plus')+' Собрать кандидата','candidate','primary')}
`;
+ }
+ function liveBar() {
+ const r = data.history.find(x => x.current);
+ return `${icon(r ? 'check' : 'clock')}
${r ? 'Активный релиз '+esc(data.current)+'' : 'Публичного релиза пока нет'} ${r ? `Собран ${date(r.built_at)}${r.author ? ' · '+esc(r.author) : ''} · ${r.pages} страниц` : 'Соберите и проверьте первый снимок сайта'}
${chip(r ? 'LIVE' : 'Нет публикаций', r ? 'good' : 'warn')}${btn('История','history-tab','subtle tiny')}
`;
+ }
+ function pipeline() {
+ const candidate = data.candidate, errors = data.validation?.errors;
+ return `01 / Workspace ${chip(!data.comparison_available ? 'Нет сравнения' : data.changes.length ? 'Есть изменения' : 'Без изменений', data.changes.length ? 'purple' : 'good')}
${data.changes.length} файлов Сохранённые документы и настройки. ${errors === undefined ? 'Строгая проверка выполняется при сборке.' : 'Ошибок последней проверки: '+errors+'.'}
02 / Candidate ${chip(candidate?.fresh ? 'Ready' : candidate ? 'Устарел' : 'Не собран', candidate?.fresh ? 'good' : 'warn')}
${candidate ? esc(candidate.id) : 'Ожидает проверки'} ${candidate ? `Зафиксирован ${date(candidate.at)} · ${candidate.changes} изменений` : 'Снимок создаётся только после строгой валидации workspace.'}
03 / Live ${chip(data.current ? 'Active' : 'Ожидает', data.current ? 'good' : 'warn')}
${esc(data.current || 'Нет публикаций')} Неизменяемый build_id. Ошибочная сборка не меняет публичную версию.
`;
+ }
+ function tabBar() {
+ const counts = [data.changes.length, issues().length, data.candidate ? 1 : 0, data.history.length, data.activity.length];
+ return `${['Изменения','Проверки','Кандидат','История','Журнал'].map((title,i) => `${title}${counts[i]} `).join('')}
`;
+ }
+ function filteredChanges() {
+ return data.changes.filter(x => (state.filter==='all'||state.filter===x.kind) && (state.type==='all'||state.type===x.type) && [x.title,x.path].some(s => s.toLocaleLowerCase().includes(state.query.toLocaleLowerCase())));
+ }
+ function changeTable() {
+ const rows=filteredChanges();
+ const options = (choices, value) => choices.map(([k,l])=>`${l} `).join('');
+ return `${icon('search')} ${options([['all','Все изменения'],['modified','Изменены'],['new','Добавлены'],['deleted','Удалены'],['unknown','Без сравнения']],state.filter)} ${options([['all','Все типы'],...Array.from(new Set(data.changes.map(x=>x.type))).sort().map(x=>[x,x])],state.type)}
${!data.comparison_available ? 'У активного релиза нет частного снимка исходников. Показан текущий workspace; изменения относительно live неизвестны.
' : ''} `;
+ }
+ function selectedPanel() {
+ const c=chosen();
+ if(!c) return '';
+ return `Сущность ${esc(c.type)}
Изменение ${esc(c.kind)}
Workspace ${c.after?'Сохранённая версия':'Удалён'}
Live ${!data.comparison_available?'Нет исходного снимка':c.before?'В снимке '+esc(data.current):'Нет в live'}
Размер ${c.after?.size??c.before?.size??0} байт
Флаг status: published в файле не означает, что последние изменения уже видны посетителям.
${btn(icon('code')+' Diff','compare-doc','tiny')}${btn('История документа','doc-history','tiny')}${editUrl(c)?`
Редактор ${icon('arrow')} `:''}
`;
+ }
+ function modelPanel() {
+ return 'Workspace Текущие редактируемые файлы
Candidate Проверенный immutable snapshot
Live Указатель на конкретный build ID
В публикацию входят сохранённые файлы. Несохранённые правки в открытых редакторах остаются в этих вкладках.
';
+ }
+ function changesTab() {
+ return `${changeTable()}
${icon('check')}
Workspace не равен Live Открытие редактора не публикует файл. Обновлённые документы подхватываются после обновления списка.
${icon('alert')}
Связанные файлы должны проходить проверку вместе Публикация записи создаёт согласованный релиз сайта.
${selectedPanel()}${modelPanel()}
`;
+ }
+ function checksTab() {
+ const v=data.validation;
+ return `${v?.errors??'—'} Ошибок
${v?.warnings??'—'} Предупреждений
${v?.fresh?'Проверено':v?'Устарело':'—'} ${date(v?.at)}
${!v?.fresh?'Запустите проверку текущего workspace. Сборка дополнительно проверит реальный рендер.
':''}${issues().map(x=>`${icon('alert')}
${esc(x.message)} ${esc(x.code)} · ${esc(x.path)} · ${esc(x.hint)}
${chip(x.severity==='error'?'ERROR':'WARNING',x.severity==='error'?'bad':'warn')}${btn('К файлу','issue','tiny',`data-path="${esc(x.path)}"`)}
`).join('')||(v?`${icon('check')}
Проблем не найдено Серверная проверка структуры, схем и ссылок пройдена.
${chip('OK','good')}
`:'Проверка ещё не запускалась.
')}Текущая версия ${esc(data.current||'Нет публикаций')}
Ошибки ${v?.errors??'—'}
Предупреждения ${v?.warnings??'—'}
Сохранение неполного draft допускается. Полнота опубликованных документов и строгий рендер проверяются перед созданием релиза.
${selectedPanel()}
`;
+ }
+ function candidateTab() {
+ const c=data.candidate;
+ return `${!c?`Кандидат пока не создан Исправьте ошибки и соберите проверенный снимок.
${btn('Перейти к проверкам','checks-tab')}
`:`Build ID ${esc(c.id)}
Состояние ${chip(c.fresh?'READY':'STALE — изменился workspace или live',c.fresh?'good':'bad')}
Основа ${esc(c.base||'Первая публикация')}
Создан ${date(c.at)}
Автор ${esc(c.author)}
Снимок ${c.pages} страниц · ${c.changes} изменений
Кандидат фиксирует данные на момент сборки. Правки после его создания требуют повторной сборки.
${btn('Просмотр сборки','preview')}${btn('Сравнить с live','candidate-diff')}${btn('Опубликовать','publish','primary',c.fresh?'':'disabled')}
`} ${data.builds.map((b,i)=>`${esc(b.id||'Не завершена')} ${b.status==='ready'?'Кандидат собран':'Ошибка сборки'} ${date(b.at)} · ${esc(b.base||'Первый релиз')}
${chip(b.status==='ready'?'Успешно':'Ошибка',b.status==='ready'?'good':'bad')}${btn('Лог','build-log','tiny',`data-index="${i}"`)}
`).join('')||'Сборок пока нет.
'} ${modelPanel()}${selectedPanel()}
`;
+ }
+ function historyTab() {
+ return `${data.history.map(r=>`${esc(r.id)}
${esc(r.comment||(r.candidate?'Неопубликованный кандидат':'Снимок сайта'))} ${date(r.built_at)}${r.author?' · '+esc(r.author):''} · ${r.pages} страниц
${chip(r.current?'LIVE':r.candidate?'Candidate':'История',r.current?'good':'')}
${btn('Детали','release-details','tiny',`data-release="${r.id}"`)}${!r.current&&!r.candidate?btn('Откат','rollback','tiny',`data-release="${r.id}"`):''}
`).join('')||'Релизов пока нет.
'} Live ${esc(data.current||'Нет публикаций')}
Workspace Не меняется при rollback
Формы Приём заявок пока недоступен (HTTP 501)
Откат выбирает ранее созданный снимок. Перед подтверждением проверьте страницы и конфигурации форм релиза.
`;
+ }
+ function activityTab() {
+ return `${data.activity.length?`${data.activity.map(e=>`
${esc(e.event)} ${esc(e.object||'')} ${date(e.ts)} · ${esc(e.actor||'—')}${e.request_id?' · ID '+esc(e.request_id):''}
`).join('')}
`:'Пока событий нет. Запустите проверку или сборку.
'} Источник Серверный audit.jsonl
Доступ Действующая сессия администратора
Показаны последние события публикации. Полный журнал хранится на сервере.
`;
+ }
+ function render() {
+ if(!root?.isConnected) return;
+ $('[data-publication-view]',root).innerHTML=heading()+liveBar()+pipeline()+tabBar()+`${({changes:changesTab,checks:checksTab,candidate:candidateTab,history:historyTab,activity:activityTab})[state.tab]()}
`;
+ root.setAttribute('aria-busy',String(busy));
+ root.querySelectorAll('[data-pub-action]').forEach(b=>{if(!b.hasAttribute('data-pub-disabled'))b.dataset.pubDisabled=String(b.disabled);b.disabled=busy||b.dataset.pubDisabled==='true';});
+ }
+ function closeModal() { $('dialog[open]',root)?.close(); }
+ function modal(title,description,body,actions='',wide=false) {
+ closeModal(); invoker=document.activeElement;
+ $('#publication-modal-root',root).innerHTML=`${esc(title)} ${esc(description)}
${icon('close')} ${body}
${actions||btn('Закрыть','close-modal')}
`;
+ const dialog=$('dialog',root);
+ dialog.addEventListener('close',()=>{if(invoker?.isConnected) invoker.focus();else $(`[data-pub-tab="${state.tab}"]`,root)?.focus();});
+ dialog.addEventListener('click',e=>{if(e.target!==dialog)return;const r=dialog.getBoundingClientRect();if(e.clientXr.right||e.clientYr.bottom)dialog.close();});
+ dialog.showModal();
+ $('input,button',dialog)?.focus();
+ }
+ async function refresh() {
+ const mine=generation, next=await call('state');
+ if(mine!==generation||!root?.isConnected) return;
+ data=next;render();
+ const pip=$('.live-pip');
+ if(pip){pip.classList.toggle('no-release',!data.current);pip.title=data.current?'Активный публичный релиз: '+data.current:'Публичного релиза пока нет';pip.innerHTML=data.current?'LIVE '+esc(data.current)+' ':'НЕТ РЕЛИЗА';}
+ }
+ async function run(action,button) {
+ if(busy) return;
+ if(action==='close-modal'){closeModal();return;}
+ if(action.endsWith('-tab')){state.tab=action.split('-')[0];render();return;}
+ if(action==='publish') {
+ const c=data.candidate;if(!c?.fresh)return;
+ modal('Подтвердить публикацию','Атомарное переключение LIVE',`Текущий live ${esc(data.current||'Нет публикаций')}
Кандидат ${esc(c.id)}
Снимок ${c.pages} страниц · ${c.changes} изменений
Комментарий к релизу Будет опубликован проверенный снимок. Рабочие файлы останутся прежними.
`,btn('Отмена','close-modal')+btn('Опубликовать','confirm-publish','primary',`data-release="${c.id}" data-base="${esc(data.current||'')}"`));
+ $('#release-comment',root)?.focus();return;
+ }
+ if(action==='build-log') {
+ const b=data.builds[Number(button.dataset.index)];if(!b)return;
+ modal('Лог сборки '+(b.id||''),`${date(b.at)} · ${b.status}`,`${esc(b.log)}${b.request_id?'\nID запроса: '+esc(b.request_id):''} ${(b.issues||[]).map(x=>`${esc(x.code)} · ${esc(x.path)} · ${esc(x.message)}
`).join('')}`);return;
+ }
+ if(action==='issue') {
+ const path=button.dataset.path;
+ state.selected=data.changes.find(x=>path===x.path||path.startsWith(x.path+'.'))?.path||'';
+ state.tab='changes';state.query='';state.filter='all';state.type='all';render();return;
+ }
+ if(action==='confirm-publish'&&!$('#release-comment',root)?.value.trim()) {$('#release-comment',root)?.focus();notify('Добавьте комментарий к релизу');return;}
+ busy=true;render();notify(({validate:'Проверяем сохранённые файлы…',candidate:'Собираем снимок…', 'confirm-publish':'Переключаем live…','rollback-confirm':'Выполняем откат…'})[action]||'Загружаем данные…');
+ const mine=generation;
+ try {
+ if(action==='refresh-workspace') await refresh();
+ else if(action==='validate') {await call('validate',{});state.tab='checks';await refresh();}
+ else if(action==='candidate') {await call('build',{});state.tab='candidate';await refresh();}
+ else if(action==='confirm-publish'||action==='rollback-confirm') {
+ const payload={id:button.dataset.release,expected_live:button.dataset.base||null,comment:$('#release-comment',root)?.value||''};
+ await call(action==='confirm-publish'?'activate':'rollback',payload);closeModal();state.tab='history';await refresh();
+ } else if(action==='release-details'||action==='rollback') {
+ const r=data.history.find(x=>x.id===button.dataset.release);if(!r)return;
+ const detail=await call('release',undefined,'?id='+encodeURIComponent(r.id));
+ if(action==='rollback') {
+ modal('Проверить откат','Просмотр последствий до подтверждения',`Сейчас live ${esc(detail.base||'Нет публикаций')}
Выбран ${esc(r.id)}
Изменится ${detail.changes.length} файлов в публичном снимке
Страниц ${r.pages}
Формы ${esc(r.forms.join(', ')||'Нет конфигураций')}
Live будет указывать на выбранный релиз. Файлы workspace не изменятся. Приём публичных форм пока возвращает HTTP 501.
${esc(detail.changes.map(c=>c.kind+' · '+c.path).join('\n')||'Нет отличающихся файлов')} `,btn('Отмена','close-modal')+btn('Подтвердить откат','rollback-confirm','danger',`data-release="${r.id}" data-base="${esc(detail.base||'')}"`));
+ } else modal('Релиз '+r.id,`${date(r.built_at)}${r.author?' · '+r.author:''}`,`Комментарий ${esc(r.comment||'—')}
Статус ${chip(r.current?'LIVE':r.candidate?'Кандидат':'Исторический',r.current?'good':'')}
Страниц ${r.pages}
Формы ${esc(r.forms.join(', ')||'Нет конфигураций')}
${esc(r.routes.join('\n'))} `,btn('Просмотр снимка','preview','',`data-release="${r.id}"`)+(r.current||r.candidate?'':btn('Подготовить откат','rollback','danger',`data-release="${r.id}"`))+btn('Закрыть','close-modal'));
+ } else if(action==='candidate-diff') {
+ const x=await call('candidate-diff');
+ modal('Кандидат ↔ Live',`${x.id} ↔ ${x.base||'Первая публикация'}`,`${esc(x.changes.map(c=>c.kind+' · '+c.path).join('\n')||'Изменений нет')} ${x.comparison_available?'Сравнение зафиксированных исходников кандидата с его базовым релизом.':'У базового релиза нет частного снимка исходников; сравнение неизвестно.'}
`, '', true);
+ } else if(action==='compare-doc') {
+ const c=chosen();if(!c)return;
+ const x=await call('compare',undefined,'?path='+encodeURIComponent(c.path));
+ const serial=d=>d ? d.source??`SHA-256: ${d.hash}\nРазмер: ${d.size} байт\nИсходник недоступен для двоичного или большого файла.` : '(файл отсутствует)';
+ modal('Сравнение изменений',`${x.path} · Workspace ↔ Live`,`LIVE / ${esc(x.current||'Нет публикаций')} ${esc(x.comparison_available?serial(x.before):'У релиза нет частного снимка исходников.')} Workspace / сохранённая версия ${esc(serial(x.after))} `,btn('Закрыть','close-modal'),true);
+ } else if(action==='doc-history') {
+ const c=chosen();if(!c)return;
+ const x=await call('document-history',undefined,'?path='+encodeURIComponent(c.path));
+ modal('История документа',`Файл: ${x.path}`,x.versions.length?`${x.versions.map(v=>`
${esc(v.id)} ${v.size} байт
`).join('')}
`:'Сохранённых предыдущих версий пока нет.
');
+ } else if(action==='preview') {
+ const id=button.dataset.release||data.candidate?.id,r=data.history.find(x=>x.id===id);if(!r)return;
+ const route=r.routes.includes('/')?'/':r.routes[0];if(!route)return;
+ const preview=await call('preview',{id,route});
+ // Release snapshots remain passive even when the editor bridge is configured.
+ modal('Просмотр сборки',`${id} · ${route}`,'',btn('Закрыть','close-modal'),true);
+ $('.release-preview',root).src=preview.url;
+ }
+ if(mine===generation)notify(({validate:'Проверка завершена.',candidate:'Кандидат собран. Live не изменён.','confirm-publish':'Релиз опубликован.','rollback-confirm':'Live переключён. Workspace не изменён.'})[action]||'Данные загружены.');
+ } catch(exc) {
+ if(mine!==generation||exc.cancelled)return;
+ if(['candidate','confirm-publish','rollback-confirm'].includes(action)) {
+ if(action==='candidate')state.tab='candidate';
+ try{await refresh();}catch(_){}
+ }
+ error(exc.detail||{code:'client_error',message:'Не удалось выполнить операцию.'},exc.status);
+ } finally {if(mine===generation){busy=false;render();}}
+ }
+ async function initialize() {
+ const next=$('[data-publication-root]');if(!next||next===root)return;
+ const bootstrap=$('[data-publication-boot]',next);
+ let boot;
+ try {boot=JSON.parse(bootstrap.value);}
+ catch(_) {window.siteAdminError?.({code:'invalid_bootstrap',message:'Не удалось прочитать данные публикации. Обновите страницу.'},0);return;}
+ root=next;generation++;busy=false;
+ csrf=boot.csrf;data=boot.state;state={tab:tabs.includes(boot.tab)?boot.tab:'changes',filter:'all',type:'all',query:'',selected:''};
+ const mine=generation;
+ try {
+ const response=await fetch('/admin/static/publication-icons.json');
+ if(!response.ok)throw new Error('icons');
+ const loaded=await response.json();
+ if(mine!==generation||!next.isConnected)return;
+ icons=loaded;
+ } catch(_) {
+ if(mine!==generation||!next.isConnected)return;
+ error({code:'resource_error',message:'Не удалось загрузить иконки публикации. Обновите страницу.'},0);
+ }
+ render();
+ }
+ document.addEventListener('click',event=>{
+ if(!root?.contains(event.target))return;
+ const tab=event.target.closest('[data-pub-tab]');if(tab){state.tab=tab.dataset.pubTab;render();$(`[data-pub-tab="${state.tab}"]`,root)?.focus();return;}
+ const selected=event.target.closest('[data-pub-select]');if(selected){state.selected=selected.dataset.pubSelect;render();root.querySelectorAll('[data-pub-select]').forEach(x=>{if(x.dataset.pubSelect===state.selected)x.focus();});return;}
+ const button=event.target.closest('[data-pub-action]');if(button)run(button.dataset.pubAction,button);
+ });
+ document.addEventListener('input',event=>{
+ if(event.target.id!=='pub-search'||!root?.contains(event.target))return;
+ state.query=event.target.value;const start=event.target.selectionStart,end=event.target.selectionEnd;
+ $('[data-pub-table]',root).outerHTML=changeTable();const input=$('#pub-search',root);input.focus();input.setSelectionRange(start,end);
+ });
+ document.addEventListener('change',event=>{
+ if(!root?.contains(event.target))return;
+ if(event.target.id==='pub-change-kind'){state.filter=event.target.value;render();$('#pub-change-kind',root)?.focus();}
+ if(event.target.id==='pub-change-type'){state.type=event.target.value;render();$('#pub-change-type',root)?.focus();}
+ });
+ document.addEventListener('keydown',event=>{
+ const tab=event.target.closest?.('[data-pub-tab]');if(!tab||!root?.contains(tab))return;
+ let i=tabs.indexOf(tab.dataset.pubTab);
+ if(event.key==='ArrowRight')i=(i+1)%tabs.length;else if(event.key==='ArrowLeft')i=(i+tabs.length-1)%tabs.length;else if(event.key==='Home')i=0;else if(event.key==='End')i=tabs.length-1;else return;
+ event.preventDefault();state.tab=tabs[i];render();$(`[data-pub-tab="${state.tab}"]`,root)?.focus();
+ });
+ document.addEventListener('htmx:load',initialize);
+ initialize();
+})();
diff --git a/src/site_engine/web/admin/templates/_content_fields.html.j2 b/src/site_engine/web/admin/templates/_content_fields.html.j2
new file mode 100644
index 0000000..8a1fad1
--- /dev/null
+++ b/src/site_engine/web/admin/templates/_content_fields.html.j2
@@ -0,0 +1,30 @@
+{% from '_content_icons.html.j2' import ci %}
+{% from '_fields.html.j2' import field as fallback %}
+{% macro cf(f, compact=false) %}
+
+
{{ f.label }}{% if f.required %}* {% endif %}{{ f.key }}
+{% if f.type == 'asset' %}
+
{{ f.value or 'Файл не выбран' }} {{ ci('image') }} Выбрать
+{% elif f.type in ['ref','refs'] %}
+
{% for value in f.value.replace(',', ' ').split() %}{% if value in f.datalist %}
{{ value }} {{ ci('arrow') }} {% else %}
{{ value }} {{ ci('alert') }} {% endif %}{% endfor %}
{{ ci('link') }} Выбрать записи
+{% elif f.type == 'boolean' %}
+
{{ 'Включено' if f.options[1].selected else 'Выключено' }}
+{% elif f.kind == 'list' %}
+
+{% for row in f.rows %}
+{% if row.bind %}
Источник: {{ row.bind }} {% endif %}
+{% if row.item %}{{ cf(row.item, true) }}{% else %}
{% for child in row.children %}{{ cf(child, true) }}{% endfor %}
{% endif %}
+
+
× {% endfor %}
+
{{ ci('plus') }} Добавить строку
+{% elif f.kind == 'group' %}
{% for child in f.children %}{{ cf(child, true) }}{% endfor %}
+{% elif f.kind == 'link' %}
Тип ссылки {% for kind,label in [('page','Страница'),('entry','Запись'),('url','Адрес')] %}{{ label }} {% endfor %} Цель Подпись В новой вкладке
+{% elif f.kind == 'textarea' %}
+{% elif f.kind == 'select' %}
{% for o in f.options %}{{ o.label }} {% endfor %}
+{% elif f.kind in ['query','multiselect'] %}{{ fallback(f) }}
+{% else %}
+{% endif %}
+{% if f.hint %}
{{ f.hint }} {% endif %}
+{% if f.bind %}
Источник: {{ f.bind }} {% endif %}
+
+{% endmacro %}
diff --git a/src/site_engine/web/admin/templates/_content_icons.html.j2 b/src/site_engine/web/admin/templates/_content_icons.html.j2
new file mode 100644
index 0000000..efb177c
--- /dev/null
+++ b/src/site_engine/web/admin/templates/_content_icons.html.j2
@@ -0,0 +1 @@
+{% macro ci(name) -%}{% set paths = {"grid": "M3 3h8v8H3zM13 3h8v8h-8zM3 13h8v8H3zM13 13h8v8h-8z", "file": "M5 2h10l4 4v16H5z M14 2v5h5 M9 13h6 M9 17h6", "layers": "M12 2 3 7l9 5 9-5-9-5z M3 12l9 5 9-5 M3 17l9 5 9-5", "globe": "M12 2a10 10 0 1 0 0 20a10 10 0 0 0 0-20z M2 12h20", "edit": "M12 20h9 M3 17l11-11 4 4-11 11H3z M14 6l3-3 4 4-3 3", "search": "M11 3a8 8 0 1 0 0 16a8 8 0 0 0 0-16z M17 17l4 4", "plus": "M12 4v16 M4 12h16", "save": "M4 3h14l3 3v15H3V3z M7 3v7h10V3 M7 21v-8h10v8", "check": "M4 12l5 5 11-11", "code": "M8 7l-5 5 5 5 M16 7l5 5-5 5", "eye": "M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z M12 9a3 3 0 1 0 0 6a3 3 0 0 0 0-6", "link": "M10 14a4 4 0 0 0 6 0l3-3a4 4 0 0 0-6-6l-1 1 M14 10a4 4 0 0 0-6 0l-3 3a4 4 0 0 0 6 6l1-1", "alert": "M12 2 2 21h20L12 2z M12 9v5 M12 17v1", "trash": "M4 7h16 M8 7V4h8v3 M6 7l1 14h10l1-14", "copy": "M8 8h13v13H8z M3 3h13v4 M3 3v13h4", "arrow": "M4 12h16m-6-6 6 6-6 6", "menu": "M3 6h18 M3 12h18 M3 18h18", "close": "M5 5l14 14 M19 5 5 19", "date": "M4 5h16v16H4z M8 2v6 M16 2v6 M4 10h16", "image": "M3 3h18v18H3z M8 8h2 M3 19l7-7 4 4 3-3 4 4", "refresh": "M3 11a9 9 0 1 1 3 7 M3 5v6h6", "chevron": "M9 5l7 7-7 7", "lock": "M5 10h14v12H5z M8 10V7a4 4 0 0 1 8 0v3"} %} {%- endmacro %}
diff --git a/src/site_engine/web/admin/templates/_publication_icons.html.j2 b/src/site_engine/web/admin/templates/_publication_icons.html.j2
new file mode 100644
index 0000000..51751f1
--- /dev/null
+++ b/src/site_engine/web/admin/templates/_publication_icons.html.j2
@@ -0,0 +1 @@
+{% macro pi(name) -%}{% set paths = {"home": "M3 3h7v7H3zM14 3h7v7h-7zM3 14h7v7H3zM14 14h7v7h-7z", "pages": "M7 3h10l4 4v14H7z M17 3v5h4 M11 13h6 M11 17h6", "content": "M12 2 3 7l9 5 9-5-9-5z M3 12l9 5 9-5 M3 17l9 5 9-5", "publish": "M12 3v13m-5-5 5 5 5-5 M4 17v4h16v-4", "media": "M3 3h18v18H3z M7 16l4-4 3 3 3-3 4 4", "settings": "M4 6h16 M4 12h16 M4 18h16", "history": "M4 3h16v18H4z M8 9h8 M8 13h8 M8 17h5", "search": "M11 3a8 8 0 1 0 0 16a8 8 0 0 0 0-16z M17 17l4 4", "check": "M4 12l5 5 11-11", "alert": "M12 2 2 21h20L12 2z M12 9v5 M12 17v1", "plus": "M12 4v16 M4 12h16", "file": "M6 2h10l4 4v16H6z M16 2v5h4 M9 12h8 M9 16h8", "arrow": "M4 12h16m-6-6 6 6-6 6", "eye": "M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6", "refresh": "M3 11a9 9 0 1 1 3 7 M3 5v6h6", "shield": "M12 2l8 4v6c0 6-4 9-8 10-4-1-8-4-8-10V6z", "code": "M8 7l-5 5 5 5 M16 7l5 5-5 5", "menu": "M3 6h18 M3 12h18 M3 18h18", "close": "M5 5l14 14 M19 5 5 19", "clock": "M12 2a10 10 0 1 0 0 20a10 10 0 0 0 0-20z M12 7v6l4 2", "layers": "M3 7l9-4 9 4-9 5-9-5 M3 13l9 5 9-5", "copy": "M8 8h13v13H8z M3 3h13v4 M3 3v13h4"} %} {%- endmacro %}
diff --git a/src/site_engine/web/admin/templates/base.html.j2 b/src/site_engine/web/admin/templates/base.html.j2
index 190a34a..44b74bb 100644
--- a/src/site_engine/web/admin/templates/base.html.j2
+++ b/src/site_engine/web/admin/templates/base.html.j2
@@ -2,6 +2,7 @@
+
@@ -12,6 +13,10 @@
+
+
+
+
{% block styles %}{% endblock %}
@@ -24,5 +29,7 @@
+
+
diff --git a/src/site_engine/web/admin/templates/content.html.j2 b/src/site_engine/web/admin/templates/content.html.j2
new file mode 100644
index 0000000..65cc073
--- /dev/null
+++ b/src/site_engine/web/admin/templates/content.html.j2
@@ -0,0 +1,33 @@
+{% extends 'shell.html.j2' %}
+{% from '_content_icons.html.j2' import ci %}
+{% set data = snap.schema.content if snap else empty_data %}
+{% block contentclass %}design-content content-screen{% endblock %}
+{% block title %}{{ meta.get('title', snap.id) if snap else 'Контент и коллекции' }} — Site Engine{% endblock %}
+{% block content %}
+
+
04 / CONTENT OPERATIONS · ENTRY EDITOR
{{ meta.get('title', snap.id) if snap else 'Управление контентом' }} Нет несохранённых изменений {% if snap %}{{ snap.path }}{% endif %}Pages ≠ Entries
{% if snap %}
Конструктор Эксперт
{{ ci('check') }} Проверить {{ ci('save') }} Сохранить черновик {% endif %}
+{% if content_error|default('') %}
{{ content_error }}
{% endif %}
+
+
Коллекции collections/*.yaml
{{ data.collections|length }} File-first CMS Контент хранится в Markdown + YAML. SQLite не является источником публичных записей.
+
Записи / {{ data.collection.id if data.collection else '—' }} {{ data.entries|length }} записей · {{ 'активна' if data.collection and data.collection.enabled else 'коллекция выключена' }}
{% if data.collection %}
{% endif %}
+{{ ci('search') }}
{% for value,label in [('all','Все'),('published','В каталоге'),('draft','Черновики'),('changed','Изменены')] %}{{ label }} {% endfor %}
+{% for e in data.entries %}
{{ ci('file') }} {{ e.title }} {{ e.slug }} {{ {'published':'В каталоге','draft':'Черновик','archived':'Архив'}.get(e.status,e.status) }} {% if e.changed %}● Правки {% endif %} {{ ci('chevron') }}{% endfor %}
+
{{ ci('search') }}
{{ 'Ничего не найдено' if data.entries else 'Записей пока нет' }} {{ 'Измените фильтры или создайте запись.' if not data.collection or data.collection.enabled else 'Коллекция выключена: записи не участвуют в публичной сборке.' }}
+
+{% if snap %}
+{% include 'entry_editor_result.html.j2' %}
+
{% else %}
Выберите запись или активную коллекцию.
{% endif %}
+
+
+
+
{{ ci('arrow') }}
+
+{% endblock %}
diff --git a/src/site_engine/web/admin/templates/entry_editor_result.html.j2 b/src/site_engine/web/admin/templates/entry_editor_result.html.j2
index 3da5805..4d3bdda 100644
--- a/src/site_engine/web/admin/templates/entry_editor_result.html.j2
+++ b/src/site_engine/web/admin/templates/entry_editor_result.html.j2
@@ -1,46 +1,35 @@
-{% from '_fields.html.j2' import field %}
-{% macro buffer_fields() %} {% if not compact_update|default(false) %}{{ snap.source }} {% endif %}{% endmacro %}
-
- {% if not compact_update|default(false) %}
{{ snap.source }} {% endif %}
- {% if saved %}
Документ сохранён. Публикация не выполнялась.
{% endif %}
- {% if errors %}
{% for e in errors %}{{ e }} {% endfor %} {% endif %}
- {% if submitted_fields %}
Отправленные значения формы {% for key, values in submitted_fields %}{% if key not in ['csrf','source'] %}{{ key }}: {{ values|join(', ') }}
{% endif %}{% endfor %}{% endif %}
- {% if snap.issues %}
{% for i in snap.issues %}{{ i.code }} {{ i.path }}: {{ i.message }} {% endfor %} {% endif %}
- {% if conflict %}
Документ изменён на сервере Ваш буфер сохранён. Сравните версии, внесите слияние в «Эксперте», затем явно примите новую основу и нажмите Save.
Отправленный исходник{{ snap.source }} Серверный исходник{{ conflict.source }}
{{ buffer_fields() }} Принимаю указанную серверную версию как новую основуПринять эту серверную версию как основу Кнопка меняет только ETag основы; исходник остаётся вашим. Повторное сохранение — отдельное действие.
{% endif %}
-
- {% if snap.model %}
-
-
- {% else %}
Конструктор недоступен: исправьте исходник в режиме «Эксперт». Последнее корректное дерево сохраняется в открытом редакторе.
{% endif %}
-
+{% from '_content_icons.html.j2' import ci %}
+{% from '_content_fields.html.j2' import cf %}
+{% set data = snap.schema.content %}
+{% macro slug_field() %}
Slug / маршрутslug
{% endmacro %}
+
+{% if not compact_update|default(false) %}
{{ snap.source }} {% endif %}
+
+
ENTRY / {{ data.collection.id }}
{{ meta.get('title', snap.id) }} {{ snap.path }}
{{ ci('copy') }} Дублировать {{ ci('trash') }} Удалить
+
{% for tab,label in [('fields','Поля'),('relations','Связи'),('usage','Где используется'),('schema','Схема')] %}{{ label }} {% endfor %}
+
+
+{% if errors %}
{% for error in errors %}
{{ error }}
{% endfor %}
{% endif %}
+{% if not snap.model %}
Исправьте исходник в режиме «Эксперт». Ваш текст остаётся в редакторе.
{% else %}
+
+
+{% if not compact_update|default(false) %}{{ snap.source }} {% endif %}
+Поля коллекции генерируются по collections/{{ data.collection.id }}.yaml
+{% if not fields|selectattr('key','equalto','title')|list %}{{ slug_field() }}{% endif %}
+{% for f in fields %}{{ cf(f) }}{% if f.key == 'title' %}{{ slug_field() }}{% endif %}{% endfor %}
+
+
+{% if snap.schema.has_body %}Markdown body Основной текстbody {{ body }} Markdown body хранится отдельно от front matter
{% endif %}
+
Файловый статус Статус документа {% for value,label in [('draft','Черновик · draft'),('published','В каталоге · published'),('archived','Архив · archived')] %}{{ label }} {% endfor %} published в файле ≠ текущий live build
+Применить изменения
+ {% endif %}
+
Связи записи Entry → refs → Entry · редактируются в форме или напрямую здесь
+{% for f in data.ref_fields %}
{% else %}
В схеме этой коллекции нет полей refs.
{% endfor %}
+
При удалении записи связь не исправляется автоматически: серверная валидация находит битые ссылки.
+
+
Схема коллекции Только чтение · определения типов коллекции
READ ONLY collections/{{ data.collection.id }}.yaml
{{ data.schema_text }} Редактор записей и редактор YAML документа используют одну схему. Эксперт не меняет определения типов.
+
{{ snap.issues|tojson }}
+
{{ data|tojson }}
+
diff --git a/src/site_engine/web/admin/templates/publication.html.j2 b/src/site_engine/web/admin/templates/publication.html.j2
new file mode 100644
index 0000000..70eced3
--- /dev/null
+++ b/src/site_engine/web/admin/templates/publication.html.j2
@@ -0,0 +1,11 @@
+{% extends 'shell.html.j2' %}
+{% block title %}Публикация — админка{% endblock %}
+{% block contentclass %}design-content publication-content{% endblock %}
+{% block content %}
+
+
05 / RELEASE WORKFLOW · ATOMIC SITE RELEASES
Публикация сайта Загрузка данных публикации…
+
{{ boot|tojson }}
+
Для просмотра кандидата и сравнения включите JavaScript. Доступна обычная форма публикации .
+
+
+{% endblock %}
diff --git a/src/site_engine/web/api/models.py b/src/site_engine/web/api/models.py
index c012525..9c70f9b 100644
--- a/src/site_engine/web/api/models.py
+++ b/src/site_engine/web/api/models.py
@@ -107,9 +107,26 @@ class InspectorEdit(DTO):
class EditorUpdate(Buffer):
+ preview_view: Literal["page", "card"] = "page"
+ preview_version: Literal["workspace", "live"] = "workspace"
operations: list[Action | InspectorEdit] = Field(default_factory=list, max_length=100)
+class EntryDeleted(DTO):
+ deleted: Literal[True]
+ id: str
+ collection: str
+
+
+class EntryCheck(DTO):
+ revision: int
+ issues: list[IssueDTO]
+
+
+class EntryCopy(Buffer):
+ id: str = Field(pattern=r"^[a-z0-9][a-z0-9_-]*$", max_length=200)
+
+
class Create(DTO):
id: str = Field(min_length=1, max_length=200)
title: str = ""
@@ -172,6 +189,8 @@ class ErrorBody(DTO):
current: Snapshot | ThemeSnapshot | None = None
committed: Snapshot | ThemeSnapshot | None = None
buffer: Snapshot | None = None
+ deleted: bool | None = None
+ committed_build: str | None = None
class ErrorEnvelope(DTO):
@@ -194,6 +213,8 @@ class PageRow(DTO):
class EntryRow(DTO):
+ changed: bool | None = None
+ url: str = ""
slug: str
title: str
status: str
@@ -202,6 +223,7 @@ class EntryRow(DTO):
class CollectionRow(DTO):
+ enabled: bool = True
id: str
name: str
total: int
@@ -226,6 +248,12 @@ class Workspace(DTO):
class Entries(DTO):
+ collections: list[CollectionRow] = Field(default_factory=list)
+ schema_text: str = ""
+ display: str = ""
+ kind: str = "content"
+ live_build: str | None = None
+ comparison_available: bool = False
collection: CollectionRow
entries: list[EntryRow]
@@ -272,3 +300,45 @@ def snapshot_dto(value):
schema=value.schema,
revision=value.revision,
)
+
+
+class PublicationDocument(DTO):
+ hash: str
+ size: int
+ title: str
+ status: str
+ type: str
+ source: str | None = None
+
+
+class PublicationChange(DTO):
+ path: str
+ title: str
+ type: str
+ status: str
+ kind: Literal["new", "modified", "deleted", "unknown"]
+ before: PublicationDocument | None = None
+ after: PublicationDocument | None = None
+
+
+class PublicationState(DTO):
+ current: str | None
+ source_hash: str
+ comparison_available: bool
+ changes: list[PublicationChange]
+ candidate: dict[str, Any] | None = None
+ validation: dict[str, Any] | None = None
+ history: list[dict[str, Any]]
+ builds: list[dict[str, Any]]
+ activity: list[dict[str, Any]]
+
+
+class ReleaseActivate(DTO):
+ id: str = Field(pattern=r"^\d{8}T\d{6}-[0-9a-f]{8}$")
+ expected_live: str | None
+ comment: str = Field(default="", max_length=150)
+
+
+class ReleasePreview(DTO):
+ id: str = Field(pattern=r"^\d{8}T\d{6}-[0-9a-f]{8}$")
+ route: str = Field(default="/", max_length=2000)
diff --git a/src/site_engine/web/api/routes.py b/src/site_engine/web/api/routes.py
index 06806b9..e70f59e 100644
--- a/src/site_engine/web/api/routes.py
+++ b/src/site_engine/web/api/routes.py
@@ -12,9 +12,15 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
from ...core.models import STATUSES
from ...errors import ConflictError, EngineError, UnsafePathError
from ...services.documents import AuditCommitError, DocumentMissing, EditorContext
-from ...services.entries import EntryService
+from ...services.entries import EntryDeleteCommitError, EntryService
from ...services.pages import PageService
from ...services.preview import asset_path
+from ...services.publication import (
+ CandidateCommitError,
+ PublicationService,
+ ReleaseCommitError,
+ ReleaseMissing,
+)
from ...services.publish import publish, rollback
from ...services.theme import OnboardingService, ThemeCommitError, ThemeService
from ...services.workspace import entries, filter_pages, releases, workspace
@@ -27,10 +33,16 @@ from .models import (
EditorUpdate,
EditorUpdateResult,
Entries,
+ EntryCheck,
+ EntryCopy,
+ EntryDeleted,
ErrorEnvelope,
OnboardingState,
PageRow,
Preview,
+ PublicationState,
+ ReleaseActivate,
+ ReleasePreview,
Releases,
Rollback,
Snapshot,
@@ -81,7 +93,7 @@ def install_api(app, auth, root, dist, previews):
return (
PageService(root, auth.audit)
if kind == "page"
- else EntryService(root, auth.audit, collection)
+ else EntryService(root, auth.audit, collection, dist=dist)
)
def themes():
@@ -110,7 +122,7 @@ def install_api(app, auth, root, dist, previews):
409,
"conflict",
exc,
- submitted=buf.model_dump(exclude={"action", "operations"}) if buf else None,
+ submitted=buf.model_dump(include={"source", "etag", "revision"}) if buf else None,
current=current,
)
except AuditCommitError as exc:
@@ -121,6 +133,9 @@ def install_api(app, auth, root, dist, previews):
exc,
committed=snapshot_dto(exc.snapshot).model_dump(by_alias=True, mode="json"),
)
+ except EntryDeleteCommitError as exc:
+ log.exception("entry_delete_after_commit request_id=%s", request_id())
+ return error(500, "entry_deleted_audit_failed", exc, deleted=True)
except DocumentMissing as exc:
return error(404, "not_found", exc)
except UnsafePathError as exc:
@@ -131,7 +146,7 @@ def install_api(app, auth, root, dist, previews):
"validation",
exc,
issues=[i.to_dict() for i in exc.report.issues],
- submitted=buf.model_dump(exclude={"action", "operations"}) if buf else None,
+ submitted=buf.model_dump(include={"source", "etag", "revision"}) if buf else None,
)
except (ValueError, KeyError) as exc:
return error(422, "invalid_operation", exc)
@@ -235,7 +250,7 @@ def install_api(app, auth, root, dist, previews):
def read():
if status and status not in STATUSES:
raise EngineError("Некорректный status")
- data = entries(root, collection)
+ data = entries(root, collection, dist)
data["entries"] = [
e
for e in data["entries"]
@@ -246,6 +261,69 @@ def install_api(app, auth, root, dist, previews):
return invoke(read)
+ def publication():
+ return PublicationService(root, dist, auth.state_dir, auth.audit)
+
+ def publication_invoke(fn):
+ try:
+ return fn()
+ except ReleaseMissing as exc:
+ return error(404, "release_not_found", exc)
+ except CandidateCommitError as exc:
+ log.exception("candidate_after_build request_id=%s", request_id())
+ return error(500, "candidate_after_build", exc, committed_build=exc.build_id)
+ except ReleaseCommitError as exc:
+ log.exception("release_after_commit request_id=%s", request_id())
+ return error(500, "release_after_commit", exc, committed_build=exc.build_id)
+ except ConflictError as exc:
+ return error(409, "release_conflict", exc)
+ except UnsafePathError as exc:
+ return error(403, "forbidden", exc)
+ except EngineError as exc:
+ return error(422, "release_validation", exc, issues=[i.to_dict() for i in exc.report.issues])
+ except ValueError as exc:
+ return error(422, "invalid_operation", exc)
+
+ @router.get("/publication", response_model=PublicationState)
+ def publication_state():
+ return publication_invoke(lambda: publication().state())
+
+ @router.post("/publication/validate")
+ def publication_validate(ctx: Ctx):
+ return publication_invoke(lambda: publication().validate(ctx))
+
+ @router.post("/publication/build")
+ def publication_build(ctx: Ctx):
+ return publication_invoke(lambda: publication().build(ctx, request_id()))
+
+ @router.post("/publication/activate")
+ def publication_activate(body: ReleaseActivate, ctx: Ctx):
+ return publication_invoke(lambda: publication().activate(body.id, body.expected_live, body.comment, ctx))
+
+ @router.post("/publication/rollback")
+ def publication_rollback(body: ReleaseActivate, ctx: Ctx):
+ return publication_invoke(lambda: publication().activate(body.id, body.expected_live, body.comment, ctx, rollback=True))
+
+ @router.get("/publication/release")
+ def publication_release(id: str):
+ return publication_invoke(lambda: publication().release_details(id))
+
+ @router.get("/publication/candidate-diff")
+ def publication_candidate_diff():
+ return publication_invoke(lambda: publication().candidate_diff())
+
+ @router.get("/publication/compare")
+ def publication_compare(path: str):
+ return publication_invoke(lambda: publication().compare(path))
+
+ @router.get("/publication/document-history")
+ def publication_document_history(path: str):
+ return publication_invoke(lambda: publication().document_history(path))
+
+ @router.post("/publication/preview", response_model=Preview)
+ def publication_preview(body: ReleasePreview, ctx: Ctx):
+ return publication_invoke(lambda: publication().preview(body.id, body.route, previews, ctx.principal))
+
@router.get("/releases", response_model=Releases)
def release_list():
return releases(dist)
@@ -386,7 +464,8 @@ def install_api(app, auth, root, dist, previews):
preview, preview_error = None, None
try:
preview = previews.render_document(
- reg, svc, identity, body.revision, ctx.principal, include_html=True
+ reg, svc, identity, body.revision, ctx.principal, include_html=True,
+ target=body.preview_view, version=body.preview_version, dist=dist
)
except Exception as exc: # noqa: BLE001 - preview failure is an independent result
# A failed preview must never roll back accepted in-memory edits.
@@ -410,6 +489,21 @@ def install_api(app, auth, root, dist, previews):
def entry_update(collection: str, identity: str, body: EditorUpdate, ctx: Ctx):
return update("entry", identity, body, ctx, collection)
+ @router.post("/collections/{collection}/entries/{identity}/check", response_model=EntryCheck)
+ def entry_check(collection: str, identity: str, body: Buffer, ctx: Ctx):
+ svc = service("entry", collection)
+ return invoke(lambda: svc.check(identity, body.source, body.etag, body.revision), svc, identity, body)
+
+ @router.post("/collections/{collection}/entries/{identity}/duplicate", response_model=Snapshot, status_code=201)
+ def entry_duplicate(collection: str, identity: str, body: EntryCopy, ctx: Ctx):
+ svc = service("entry", collection)
+ return invoke(lambda: snapshot_dto(svc.duplicate(identity, body.id, body.source, body.etag, ctx)), svc, identity, body)
+
+ @router.post("/collections/{collection}/entries/{identity}/delete", response_model=EntryDeleted)
+ def entry_delete(collection: str, identity: str, body: Buffer, ctx: Ctx):
+ svc = service("entry", collection)
+ return invoke(lambda: svc.delete(identity, body.etag, ctx), svc, identity, body)
+
@router.post("/editor/pages/{identity:path}/validate", response_model=Snapshot)
@router.post("/pages/{identity:path}/validate", response_model=Snapshot)
def page_validate(identity: str, body: Buffer, ctx: Ctx):
diff --git a/src/site_engine/web/preview_app.py b/src/site_engine/web/preview_app.py
index 3afd312..b5fc33a 100644
--- a/src/site_engine/web/preview_app.py
+++ b/src/site_engine/web/preview_app.py
@@ -17,7 +17,7 @@ def snapshot_response(store, snapshot, token, asset=None):
except (PermissionError, OSError, ValueError, UnsafePathError):
return Response("Превью недоступно", status_code=403, headers={"Cache-Control": "no-store"})
config = store.config
- script = f"'nonce-{data['nonce']}'" if config else "'none'"
+ script = f"'nonce-{data['nonce']}'" if config and not data.get("passive") else "'none'"
ancestors = config.admin if config else "'self'"
headers = {
"Cache-Control": "no-store",
diff --git a/tests/test_content_editor.py b/tests/test_content_editor.py
new file mode 100644
index 0000000..c02de37
--- /dev/null
+++ b/tests/test_content_editor.py
@@ -0,0 +1,359 @@
+"""Content editor contract: real metadata, stateless readiness, CAS and immutable Live."""
+
+import json
+import os
+import shutil
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from fastapi.testclient import TestClient
+
+from site_engine.build.pipeline import build_site
+from site_engine.core.registry import load_site
+from site_engine.parsing.frontmatter import dumps, parse
+from site_engine.parsing.yamlio import dump_yaml, load_yaml
+from site_engine.services.auth import hash_password
+from site_engine.services.documents import EditorContext
+from site_engine.services.entries import EntryService
+from site_engine.web.app import create_app
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+class ContentEditorTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.password = "content editor test password"
+ cls.password_hash = hash_password(cls.password, n=2**10)
+
+ def setUp(self):
+ tmp = tempfile.TemporaryDirectory(prefix="content-editor-test-")
+ self.addCleanup(tmp.cleanup)
+ self.work = Path(tmp.name)
+ self.site = self.work / "site"
+ self.dist = self.work / "dist"
+ shutil.copytree(
+ ROOT / "examples/site-studio", self.site, ignore=shutil.ignore_patterns(".engine")
+ )
+ env = patch.dict(
+ os.environ,
+ {
+ "SITE_ROOT": str(self.site),
+ "SITE_DIST": str(self.dist),
+ "SITE_STATE_DIR": str(self.work / "state"),
+ "SITE_ADMIN_LOGIN": "admin",
+ "SITE_ADMIN_PASSWORD_HASH": self.password_hash,
+ "SITE_SECRET_KEY": "content-editor-test-secret-" * 3,
+ "SITE_COOKIE_SECURE": "0",
+ "SITE_ADMIN_ORIGIN": "",
+ "SITE_PREVIEW_ORIGIN": "",
+ },
+ )
+ env.start()
+ self.addCleanup(env.stop)
+ self.app = create_app()
+ self.client = TestClient(self.app)
+ self.addCleanup(self.client.close)
+ cookie = self.app.state.auth.login("admin", self.password, "testclient")
+ self.client.cookies.set("se_session", cookie)
+ self.app.state.api_credentials["test"] = (cookie, "testclient")
+ self.principal = self.app.state.auth.authenticate(cookie)
+ self.ctx = EditorContext(self.principal, "testclient")
+ self.csrf = self.app.state.auth.csrf_token(self.principal)
+ self.svc = EntryService(self.site, collection="services", dist=self.dist)
+ self.snap = self.svc.get("bots")
+
+ def payload(self, **extra):
+ return {"source": self.snap.source, "etag": self.snap.etag, "revision": 7, **extra}
+
+ def api(self, op, payload=None, identity="bots"):
+ return self.client.post(
+ f"/admin/api/v1/collections/services/entries/{identity}/{op}",
+ json=self.payload() if payload is None else payload,
+ headers={"Authorization": "Bearer test"},
+ )
+
+ def ui(self, op, payload=None, csrf=None):
+ return self.client.post(
+ "/admin/editor/content/services/bots/" + op,
+ data={
+ "csrf": self.csrf if csrf is None else csrf,
+ "payload": json.dumps(self.payload() if payload is None else payload),
+ },
+ headers={
+ "Origin": "http://testserver",
+ "HX-Request": "true",
+ "Accept": "application/json",
+ },
+ )
+
+ def test_original_workspace_markup_static_and_empty_disabled_collection(self):
+ response = self.client.get("/admin/content/services/bots")
+ self.assertEqual(response.status_code, 200)
+ for marker in (
+ "entry-workspace",
+ "collection-pane",
+ "entry-pane",
+ "editor-content",
+ "preview-pane",
+ "entry-tabs",
+ "source-edit-wrap",
+ "data-content-picker",
+ ):
+ self.assertIn(marker, response.text)
+ self.assertNotIn("409 Demo", response.text)
+ for name in ("content-editor.css", "content-adapter.css", "content-editor.js"):
+ self.assertEqual(self.client.get("/admin/static/" + name).status_code, 200)
+ empty = self.client.get("/admin/content/posts")
+ self.assertEqual(empty.status_code, 200)
+ self.assertIn("Записей пока нет", empty.text)
+ self.assertIn("OFF", empty.text)
+ self.assertIn("disabled", empty.text)
+
+ def test_update_has_one_registry_and_api_call_and_no_write(self):
+ before = (self.site / self.snap.path).read_bytes()
+ calls = self.app.state.api_calls
+ payload = self.payload(
+ preview_view="card",
+ operations=[{"type": "entry_fields", "values": {"title": "Current candidate"}}],
+ )
+ with patch("site_engine.services.documents.load_site", wraps=load_site) as load:
+ response = self.ui("update", payload)
+ self.assertEqual(response.status_code, 200, response.text)
+ self.assertEqual(load.call_count, 1)
+ self.assertEqual(self.app.state.api_calls - calls, 1)
+ result = response.json()
+ self.assertIn("Current candidate", result["preview"]["html"])
+ self.assertIn("f-entry_card", result["preview"]["html"])
+ self.assertIn("data-content-panel", result["projection"])
+ self.assertNotIn("name='source'", result["projection"])
+ self.assertEqual((self.site / self.snap.path).read_bytes(), before)
+ self.assertFalse((self.site / ".engine/history").exists())
+ self.assertFalse((self.dist / "current").exists())
+
+ def test_readiness_missing_required_and_render_errors_does_not_block_draft_save(self):
+ meta, body = parse(self.snap.source)
+ meta.update(
+ status="draft", hero_asset="assets/missing.webp", cta={"href": {"page": "missing-page"}}
+ )
+ meta.pop("title")
+ source = dumps(meta, body)
+ response = self.ui("check", self.payload(source=source))
+ self.assertEqual(response.status_code, 200, response.text)
+ codes = {i["code"] for i in response.json()["issues"]}
+ self.assertIn("E_ENTRY_REQUIRED", codes)
+ self.assertTrue({"E_ASSET_MISSING", "E_LINK_BROKEN"} & codes, codes)
+ self.assertEqual((self.site / self.snap.path).read_text(), self.snap.source)
+ self.assertEqual(self.ui("save", self.payload(source=source)).status_code, 200)
+ self.assertFalse((self.dist / "current").exists())
+
+ def test_readiness_reports_invalid_yaml_without_rewriting_source(self):
+ source = "---\ntitle: [\n---\nCurrent text"
+ response = self.api("check", self.payload(source=source))
+ self.assertEqual(response.status_code, 200)
+ self.assertTrue(response.json()["issues"])
+ self.assertEqual((self.site / self.snap.path).read_text(), self.snap.source)
+
+ def test_dependencies_use_candidate_query_membership_and_nested_typed_refs(self):
+ schema_file = self.site / "collections/cases.yaml"
+ schema = load_yaml(schema_file.read_text())
+ schema["fields"].append(
+ {
+ "key": "nested",
+ "type": "list",
+ "fields": [
+ {"key": "related", "type": "ref", "to": "*"},
+ {"key": "link", "type": "link"},
+ ],
+ }
+ )
+ schema_file.write_text(dump_yaml(schema))
+ target = self.site / "content/cases/booking.md"
+ meta, body = parse(target.read_text())
+ meta["nested"] = [{"related": "services/bots", "link": {"entry": "services/bots"}}]
+ target.write_text(dumps(meta, body))
+ meta, body = parse(self.snap.source)
+ result = self.svc.validate_source("bots", self.snap.source, self.snap.etag).schema[
+ "content"
+ ]
+ self.assertTrue(any(u["field"] == "nested.0.related" for u in result["usages"]))
+ self.assertTrue(any(u["field"] == "nested.0.link" for u in result["usages"]))
+ # Home's featured query uses the candidate, not the saved file.
+ home_before = [u for u in result["usages"] if u["file"] == "pages/index.md"]
+ self.assertTrue(home_before)
+ meta["status"] = "draft"
+ result = self.svc.validate_source("bots", dumps(meta, body), self.snap.etag).schema[
+ "content"
+ ]
+ self.assertFalse(any(u["file"] == "pages/index.md" for u in result["usages"]))
+ self.assertTrue(any(r["target"] == "scenarios/legal" for r in result["relations"]))
+ self.assertFalse(next(c for c in result["collections"] if c["id"] == "posts")["enabled"])
+
+ def test_typed_form_preserves_link_list_refs_and_optional_boolean(self):
+ response = self.api(
+ "update",
+ self.payload(
+ operations=[
+ {
+ "type": "inspector",
+ "fields": {
+ "operation": ["entry_fields"],
+ "p.title": ["Typed fields"],
+ "p.featured": ["false"],
+ "p.cta.href.kind": ["entry"],
+ "p.cta.href.target": ["services/ai"],
+ "p.benefits.0": ["First"],
+ "p.benefits.1": ["Second"],
+ "p.benefits.0._del": ["1"],
+ "p.related_scenarios": ["legal, services"],
+ "status": ["draft"],
+ },
+ }
+ ]
+ ),
+ )
+ self.assertEqual(response.status_code, 200, response.text)
+ meta = response.json()["snapshot"]["model"]["meta"]
+ self.assertEqual(meta["benefits"], ["Second"])
+ self.assertEqual(meta["cta"]["href"], {"entry": "services/ai"})
+ self.assertEqual(meta["related_scenarios"], ["legal", "services"])
+ self.assertFalse(meta["featured"])
+
+ def test_duplicate_uses_current_editor_and_cas_both_files(self):
+ source = self.snap.source.replace("Telegram-боты", "My candidate", 1)
+ response = self.ui("duplicate", self.payload(source=source, id="bots-copy"))
+ self.assertEqual(response.status_code, 200, response.text)
+ copy = response.json()["snapshot"]
+ self.assertEqual(copy["model"]["meta"]["status"], "draft")
+ self.assertEqual(copy["model"]["meta"]["title"], "My candidate (копия)")
+ self.assertEqual(copy["model"]["meta"]["slug"], "bots-copy")
+ self.assertEqual((self.site / self.snap.path).read_text(), self.snap.source)
+ self.assertEqual(self.api("duplicate", self.payload(id="bots-copy")).status_code, 409)
+ (self.site / self.snap.path).write_text(self.snap.source + "\nchanged")
+ self.assertEqual(self.api("duplicate", self.payload(id="bots-another")).status_code, 409)
+ self.assertFalse((self.site / "content/services/bots-another.md").exists())
+ self.assertEqual(self.api("duplicate", self.payload(id="../outside")).status_code, 422)
+
+ def test_delete_requires_saved_archive_cas_and_history(self):
+ self.assertEqual(self.api("delete").status_code, 422)
+ # Unsaved status does not authorize deleting a published file.
+ self.assertEqual(
+ self.api(
+ "delete", self.payload(source=self.snap.source.replace("published", "archived"))
+ ).status_code,
+ 422,
+ )
+ snapshot = self.svc.save_source(
+ "bots", self.snap.source.replace("published", "archived"), self.snap.etag, self.ctx
+ )
+ self.assertEqual(self.api("delete").status_code, 409)
+ response = self.api("delete", {"source": snapshot.source, "etag": snapshot.etag})
+ self.assertEqual(response.status_code, 200, response.text)
+ self.assertTrue(response.json()["deleted"])
+ self.assertFalse((self.site / self.snap.path).exists())
+ history = list((self.site / ".engine/history").rglob("*"))
+ self.assertTrue(any(p.is_file() for p in history))
+
+ def test_after_commit_audit_failure_reports_committed_copy_or_deleted_flag(self):
+ with patch.object(
+ self.app.state.auth.audit, "write", side_effect=OSError("audit unavailable")
+ ):
+ with self.assertLogs("uvicorn.error", level="ERROR") as logs:
+ response = self.api("duplicate", self.payload(id="bots-copy"))
+ self.assertEqual(response.status_code, 500)
+ self.assertEqual(response.json()["error"]["committed"]["id"], "bots-copy")
+ self.assertTrue(any("Traceback" in item for item in logs.output))
+ copy_svc = EntryService(self.site, collection="services")
+ snapshot = copy_svc.get("bots-copy")
+ with patch.object(
+ self.app.state.auth.audit, "write", side_effect=OSError("audit unavailable")
+ ):
+ response = self.api(
+ "delete", {"source": snapshot.source, "etag": snapshot.etag}, identity="bots-copy"
+ )
+ self.assertEqual(response.status_code, 500)
+ self.assertTrue(response.json()["error"]["deleted"])
+ self.assertFalse((self.site / snapshot.path).exists())
+
+ def test_live_is_release_html_and_assets_not_current_workspace(self):
+ build_site(self.site, self.dist)
+ manifest = json.loads((self.dist / "current/manifest.json").read_text())
+ self.assertEqual(manifest["entry_routes"]["services/bots"], "/services/bots/")
+ self.assertIn(self.snap.path, manifest["entry_sources"])
+ response = self.api(
+ "update",
+ self.payload(
+ preview_version="live",
+ preview_view="page",
+ source=self.snap.source.replace("Telegram-боты", "Only workspace", 1),
+ ),
+ )
+ self.assertEqual(response.status_code, 200, response.text)
+ preview = response.json()["preview"]
+ self.assertIn("Telegram-боты", preview["html"])
+ self.assertNotIn("Only workspace", preview["html"])
+ result = self.client.get(preview["url"])
+ self.assertEqual(result.status_code, 200)
+ self.assertIn("script-src 'none'", result.headers["content-security-policy"])
+ from urllib.parse import parse_qs, urlsplit
+
+ token = parse_qs(urlsplit(preview["url"]).query)["token"][0]
+ folder, _meta = self.app.state.previews.authorize(preview["snapshot"], token)
+ self.assertTrue(list((folder / "assets").glob("site.*.css")))
+ self.assertEqual(self.client.get(preview["url"].split("?")[0]).status_code, 403)
+ card = self.api("update", self.payload(preview_version="live", preview_view="card")).json()[
+ "preview"
+ ]
+ self.assertFalse(card["url"])
+ self.assertIn("карточка", card["message"])
+
+ def test_comparison_uses_unsaved_candidate_and_old_release_is_unknown(self):
+ build_site(self.site, self.dist)
+ self.assertFalse(
+ next(
+ e for e in self.svc.get("bots").schema["content"]["entries"] if e["slug"] == "bots"
+ )["changed"]
+ )
+ candidate = self.svc.validate_source("bots", self.snap.source + "\nunsaved", self.snap.etag)
+ self.assertTrue(
+ next(e for e in candidate.schema["content"]["entries"] if e["slug"] == "bots")[
+ "changed"
+ ]
+ )
+ manifest_file = self.dist / "current/manifest.json"
+ manifest = json.loads(manifest_file.read_text())
+ del manifest["entry_sources"]
+ del manifest["entry_routes"]
+ manifest_file.write_text(json.dumps(manifest))
+ result = self.svc.get("bots").schema["content"]
+ self.assertFalse(result["comparison_available"])
+ self.assertIsNone(result["entries"][0]["changed"])
+ live = self.api("update", self.payload(preview_version="live")).json()["preview"]
+ self.assertFalse(live["url"])
+ self.assertIn("snapshots", live["message"])
+
+ def test_empty_new_draft_has_real_card_without_inventing_saved_title(self):
+ snap = self.svc.create("empty-draft", "", None, self.ctx)
+ response = self.api(
+ "update",
+ {"source": snap.source, "etag": snap.etag, "preview_view": "card"},
+ identity="empty-draft",
+ )
+ self.assertEqual(response.status_code, 200, response.text)
+ self.assertIsNone(response.json()["preview_error"])
+ self.assertIn("empty-draft", response.json()["preview"]["html"])
+ self.assertNotIn("title", parse((self.site / snap.path).read_text())[0])
+
+ def test_auth_csrf_and_validation_failures_have_visible_json_contract(self):
+ response = self.ui("check", csrf="bad")
+ self.assertEqual(response.status_code, 403)
+ self.assertTrue(response.json()["error"]["request_id"])
+ self.assertEqual(self.api("update", self.payload(preview_view="fake")).status_code, 422)
+ self.client.cookies.clear()
+ self.assertEqual(self.ui("delete").status_code, 401)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_publication.py b/tests/test_publication.py
new file mode 100644
index 0000000..5f28d25
--- /dev/null
+++ b/tests/test_publication.py
@@ -0,0 +1,397 @@
+"""Publication contract: real candidates, private provenance, CAS and immutable live."""
+
+import json
+import os
+import shutil
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from fastapi.testclient import TestClient
+
+from site_engine.build.pipeline import build_site, hash_tree
+from site_engine.services.auth import hash_password
+from site_engine.services.documents import EditorContext
+from site_engine.services.publication import PublicationService
+from site_engine.web.app import create_app
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+class PublicationTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.password = "publication test password"
+ cls.password_hash = hash_password(cls.password, n=2**10)
+
+ def setUp(self):
+ tmp = tempfile.TemporaryDirectory(prefix="publication-test-")
+ self.addCleanup(tmp.cleanup)
+ self.work = Path(tmp.name)
+ self.site, self.dist, self.state = (self.work / n for n in ("site", "dist", "state"))
+ shutil.copytree(
+ ROOT / "examples/site-studio", self.site, ignore=shutil.ignore_patterns(".engine")
+ )
+ env = patch.dict(
+ os.environ,
+ {
+ "SITE_ROOT": str(self.site),
+ "SITE_DIST": str(self.dist),
+ "SITE_STATE_DIR": str(self.state),
+ "SITE_ADMIN_LOGIN": "admin",
+ "SITE_ADMIN_PASSWORD_HASH": self.password_hash,
+ "SITE_SECRET_KEY": "publication-test-secret-" * 4,
+ "SITE_COOKIE_SECURE": "0",
+ "SITE_ADMIN_ORIGIN": "",
+ "SITE_PREVIEW_ORIGIN": "",
+ },
+ )
+ env.start()
+ self.addCleanup(env.stop)
+ self.app = create_app()
+ self.client = TestClient(self.app)
+ self.addCleanup(self.client.close)
+ cookie = self.app.state.auth.login("admin", self.password, "testclient")
+ self.client.cookies.set("se_session", cookie)
+ self.app.state.api_credentials["test"] = (cookie, "testclient")
+ self.principal = self.app.state.auth.authenticate(cookie)
+ self.ctx = EditorContext(self.principal, "testclient")
+ self.csrf = self.app.state.auth.csrf_token(self.principal)
+ self.svc = PublicationService(self.site, self.dist, self.state, self.app.state.auth.audit)
+
+ def api(self, method="GET", path="", payload=None):
+ return self.client.request(
+ method,
+ "/admin/api/v1/publication" + path,
+ json=payload,
+ headers={"Authorization": "Bearer test"},
+ )
+
+ def ui(self, operation, payload=None, csrf=None):
+ return self.client.post(
+ "/admin/publication/" + operation,
+ data={
+ "csrf": self.csrf if csrf is None else csrf,
+ "payload": json.dumps(payload or {}),
+ },
+ headers={"Origin": "http://testserver", "Accept": "application/json"},
+ )
+
+ def build(self):
+ r = self.api("POST", "/build")
+ self.assertEqual(r.status_code, 200, r.text)
+ return r.json()
+
+ def activate(self, candidate, base=None, comment="Проверенный релиз"):
+ return self.api(
+ "POST", "/activate", {"id": candidate["id"], "expected_live": base, "comment": comment}
+ )
+
+ def edit(self, rel="pages/index.md", old="Студия автоматизации", new="Новая студия"):
+ path = self.site / rel
+ source = path.read_text()
+ if old not in source:
+ source += "\n" + new
+ else:
+ source = source.replace(old, new)
+ path.write_text(source)
+
+ def test_original_screen_and_api_only_adapter_static_and_csrf(self):
+ r = self.client.get("/admin/publish")
+ self.assertEqual(r.status_code, 200, r.text)
+ self.assertIn("data-publication-root", r.text)
+ for name in (
+ "publication.css",
+ "publication-adapter.css",
+ "publication.js",
+ "publication-icons.json",
+ ):
+ self.assertEqual(self.client.get("/admin/static/" + name).status_code, 200, name)
+ before = self.app.state.api_calls
+ self.assertEqual(self.ui("validate").status_code, 200)
+ self.assertEqual(self.app.state.api_calls - before, 1)
+ self.assertEqual(self.ui("build", csrf="bad").status_code, 403)
+ self.assertEqual(self.client.get("/admin/publication/build").status_code, 405)
+ self.assertEqual(self.client.get("/admin/publication/unknown").status_code, 404)
+
+ def test_build_never_activates_and_private_snapshots_never_in_dist(self):
+ initial = hash_tree(self.site)
+ c = self.build()
+ self.assertIsNone(self.svc.current())
+ self.assertEqual(hash_tree(self.site), initial)
+ self.assertTrue((self.dist / c["id"] / "index.html").is_file())
+ self.assertFalse((self.dist / c["id"] / "pages").exists())
+ self.assertFalse((self.dist / c["id"] / "content").exists())
+ self.assertNotIn("sources", self.svc.manifest(c["id"]))
+ self.assertIn("content/services/automation.md", self.svc.provenance(c["id"])["sources"])
+ state = self.api().json()
+ self.assertTrue(state["candidate"]["fresh"])
+ self.assertTrue(state["history"][0]["candidate"])
+ self.assertEqual(state["builds"][0]["status"], "ready")
+
+ def test_activate_exact_existing_output_and_no_rebuild(self):
+ c = self.build()
+ output = hash_tree(self.dist / c["id"])
+ with patch(
+ "site_engine.services.publication.build_site",
+ side_effect=AssertionError("must not rebuild"),
+ ):
+ r = self.activate(c)
+ self.assertEqual(r.status_code, 200, r.text)
+ self.assertEqual(self.svc.current(), c["id"])
+ self.assertEqual(hash_tree(self.dist / c["id"]), output)
+ state = self.api().json()
+ self.assertIsNone(state["candidate"])
+ self.assertFalse(state["changes"])
+ self.assertEqual(state["history"][0]["comment"], "Проверенный релиз")
+
+ def test_stale_source_and_replaced_candidate_cannot_activate_or_rollback(self):
+ c = self.build()
+ self.edit()
+ self.assertFalse(self.api().json()["candidate"]["fresh"])
+ self.assertEqual(self.activate(c).status_code, 409)
+ self.assertEqual(
+ self.api("POST", "/rollback", {"id": c["id"], "expected_live": None}).status_code, 422
+ )
+ newer = self.build()
+ self.assertNotEqual(c["id"], newer["id"])
+ self.assertEqual(self.activate(c).status_code, 409)
+ self.assertIsNone(self.svc.current())
+
+ def test_engine_resources_and_output_tampering_invalidate_candidate(self):
+ c = self.build()
+ with patch(
+ "site_engine.services.publication.render_fingerprint", return_value="changed-engine"
+ ):
+ self.assertFalse(self.api().json()["candidate"]["fresh"])
+ self.assertEqual(self.activate(c).status_code, 409)
+ (self.dist / c["id"] / "index.html").write_text("tampered")
+ self.assertEqual(self.activate(c).status_code, 422)
+ self.assertIsNone(self.svc.current())
+
+ def test_live_cas_and_rollback_do_not_touch_workspace(self):
+ a = self.build()
+ self.assertEqual(self.activate(a).status_code, 200)
+ self.edit()
+ b = self.build()
+ self.assertEqual(self.activate(b, base="20000101T000000-12345678").status_code, 409)
+ self.assertEqual(self.activate(b, base=a["id"]).status_code, 200)
+ before = hash_tree(self.site)
+ r = self.api("POST", "/rollback", {"id": a["id"], "expected_live": b["id"]})
+ self.assertEqual(r.status_code, 200, r.text)
+ self.assertEqual(self.svc.current(), a["id"])
+ self.assertEqual(hash_tree(self.site), before)
+ self.assertEqual(
+ self.api("POST", "/rollback", {"id": b["id"], "expected_live": b["id"]}).status_code,
+ 409,
+ )
+ self.assertTrue(self.api().json()["changes"])
+
+ def test_comparison_actual_text_added_deleted_assets_and_old_release_unknown(self):
+ a = self.build()
+ self.activate(a)
+ self.edit()
+ (self.site / "assets/new.txt").write_text("new asset")
+ (self.site / "assets/hero.webp").unlink()
+ state = self.api().json()
+ rows = {x["path"]: x for x in state["changes"]}
+ self.assertEqual(rows["pages/index.md"]["kind"], "modified")
+ self.assertEqual(rows["assets/new.txt"]["kind"], "new")
+ self.assertEqual(rows["assets/hero.webp"]["kind"], "deleted")
+ diff = self.api(path="/compare?path=pages/index.md").json()
+ self.assertNotEqual(diff["before"]["source"], diff["after"]["source"])
+ (self.state / "publication/releases" / f"{a['id']}.json").unlink()
+ state = self.api().json()
+ self.assertFalse(state["comparison_available"])
+ self.assertTrue(all(x["kind"] == "unknown" for x in state["changes"]))
+ self.assertIsNone(self.api(path="/compare?path=pages/index.md").json()["before"])
+
+ def test_candidate_diff_is_immutable_after_workspace_change(self):
+ a = self.build()
+ self.activate(a)
+ self.edit()
+ self.build()
+ before = self.api(path="/candidate-diff").json()
+ (self.site / "assets/not-in-candidate.txt").write_text("later")
+ after = self.api(path="/candidate-diff").json()
+ self.assertEqual(before, after)
+ self.assertNotIn("assets/not-in-candidate.txt", json.dumps(after))
+
+ def test_validation_and_failed_strict_render_preserve_live_and_previous_candidate(self):
+ a = self.build()
+ self.activate(a)
+ self.edit()
+ b = self.build()
+ with (
+ patch(
+ "site_engine.core.render.Renderer.render",
+ side_effect=RuntimeError("real render probe"),
+ ),
+ self.assertLogs("uvicorn.error", level="ERROR") as captured,
+ ):
+ r = self.api("POST", "/build")
+ self.assertEqual(r.status_code, 500)
+ self.assertIn("real render probe", "\n".join(captured.output))
+ self.assertTrue(r.json()["error"]["request_id"])
+ state = self.api().json()
+ self.assertEqual(state["current"], a["id"])
+ self.assertEqual(state["candidate"]["id"], b["id"])
+ self.assertEqual(state["builds"][0]["status"], "failed")
+ self.edit(
+ "pages/index.md", "status: published", "status: published\nlayout: missing-layout"
+ )
+ r = self.api("POST", "/validate")
+ self.assertEqual(r.status_code, 200, r.text)
+ self.assertGreater(r.json()["errors"], 0)
+ self.assertEqual(self.api("POST", "/build").status_code, 422)
+ self.assertEqual(self.svc.current(), a["id"])
+
+ def test_passive_snapshot_is_real_build_with_assets_and_no_site_scripts(self):
+ c = self.build()
+ self.edit()
+ r = self.api("POST", "/preview", {"id": c["id"], "route": "/"})
+ self.assertEqual(r.status_code, 200, r.text)
+ preview = r.json()
+ page = self.client.get(preview["url"])
+ self.assertEqual(page.status_code, 200)
+ self.assertNotIn("