Files
rose-ash/tests/playwright/navigation.spec.js
giles d81a518732 Fix JIT compiler, CSSX browser support, double-fetch, SPA layout
JIT compiler:
- Fix jit_compile_lambda: resolve `compile` via symbol lookup in env
  instead of embedding VmClosure in AST (CEK dispatches differently)
- Register eval-defcomp/eval-defisland/eval-defmacro runtime helpers
  in browser kernel for bytecoded defcomp forms
- Disable broken .sxbc.json path (missing arity in nested code blocks),
  use .sxbc text format only
- Mark JIT-failed closures as sentinel to stop retrying

CSSX in browser:
- Add cssx.sx symlink + cssx.sxbc to browser web stack
- Add flush-cssx! to orchestration.sx post-swap for SPA nav
- Add cssx.sx to compile-modules.js and mcp_tree.ml bytecode lists

SPA navigation:
- Fix double-fetch: check e.defaultPrevented in click delegation
  (bind-event already handled the click)
- Fix layout destruction: change nav links from outerHTML to innerHTML
  swap (outerHTML destroyed #main-panel when response lacked it)
- Guard JS popstate handler when SX engine is booted
- Rename sx-platform.js → sx-platform-2.js to bust immutable cache

Playwright tests:
- Add trackErrors() helper to all test specs
- Add SPA DOM comparison test (SPA nav vs fresh load)
- Add single-fetch + no-duplicate-elements test
- Improve MCP tool output: show failure details and error messages

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 20:48:43 +00:00

253 lines
9.3 KiB
JavaScript

// Navigation tests for sx-docs
// Verifies navigation works correctly with the OCaml sx-host.
const { test, expect } = require('playwright/test');
const { BASE_URL, waitForSxReady, loadPage, trackErrors } = require('./helpers');
test.describe('Page Navigation', () => {
let t;
test.beforeEach(({ page }) => { t = trackErrors(page); });
test.afterEach(() => { expect(t.errors()).toEqual([]); });
test('clicking nav button navigates to new page', async ({ page }) => {
await loadPage(page, '(geography)');
// Click "Reactive Islands" nav link
await page.click('a[href*="geography.(reactive)"]:not([href*="runtime"])');
await expect(page).toHaveURL(/reactive/, { timeout: 5000 });
// Page should show Reactive Islands content
const body = await page.textContent('body');
expect(body).toContain('Reactive Islands');
});
test('clicking header logo navigates home', async ({ page }) => {
await loadPage(page, '(geography)');
// Click the logo in the header island
await page.click('[data-sx-island="layouts/header"] a[href="/sx/"]');
await expect(page).toHaveURL(/\/sx\/?$/, { timeout: 5000 });
});
test('back button works after navigation', async ({ page }) => {
await loadPage(page, '(geography)');
// Navigate to Reactive Islands
await page.click('a[href*="geography.(reactive)"]:not([href*="runtime"])');
await expect(page).toHaveURL(/reactive/, { timeout: 5000 });
// Go back
await page.goBack();
await expect(page).toHaveURL(/geography/, { timeout: 5000 });
await expect(page).not.toHaveURL(/reactive/);
// Geography heading should be visible
const heading = await page.locator('h1, h2').first();
await expect(heading).toContainText('Geography', { timeout: 5000 });
});
test('no console errors on page load', async ({ page }) => {
await loadPage(page, '(geography)');
// afterEach handles assertion
});
test('copyright shows current route after SX navigation', async ({ page }) => {
await loadPage(page, '');
// Mark the page to verify SX navigation (not full reload)
await page.evaluate(() => window.__sx_nav_marker = true);
// Before: copyright shows the current path
const before = await page.evaluate(() =>
document.querySelector('[data-sx-lake="copyright"]')?.textContent);
expect(before).toContain('/sx/');
// Navigate via SX (sx-get link)
await page.click('a[sx-get*="(geography)"]');
await expect(page).toHaveURL(/geography/, { timeout: 5000 });
// Verify SX navigation (marker survives SX nav, lost on reload)
const marker = await page.evaluate(() => window.__sx_nav_marker);
expect(marker).toBe(true);
// After: copyright lake still visible (lakes persist across SPA nav)
const after = await page.evaluate(() =>
document.querySelector('[data-sx-lake="copyright"]')?.textContent);
expect(after).toContain('Giles Bradshaw');
});
test('stepper persists index across navigation', async ({ page }) => {
await loadPage(page, '');
// Get the initial stepper index
const getIndex = () => page.evaluate(() => {
const el = document.querySelector('[data-sx-island="home/stepper"]');
const m = el && el.textContent.match(/(\d+)\s*\/\s*\d+/);
return m ? parseInt(m[1]) : null;
});
const initial = await getIndex();
expect(initial).not.toBeNull();
// Advance the stepper
await page.evaluate(() => {
const btns = document.querySelectorAll('[data-sx-island="home/stepper"] button');
if (btns.length >= 2) btns[1].click(); // next button
});
await page.waitForTimeout(300);
const advanced = await getIndex();
expect(advanced).toBe(initial + 1);
// Navigate away
await page.click('a[sx-get*="(geography)"]');
await expect(page).toHaveURL(/geography/, { timeout: 5000 });
// Navigate back home
await page.evaluate(() => {
const link = document.querySelector('a[sx-get*="/sx/"]');
if (link) link.click();
});
await expect(page).toHaveURL(/\/sx\/?$/, { timeout: 5000 });
// Stepper should still show the advanced index
const afterNav = await getIndex();
expect(afterNav).toBe(advanced);
});
test('sx-get link fetches SX not HTML and preserves layout', async ({ page }) => {
await loadPage(page, '');
// Mark page so we can detect full reload vs SPA nav
await page.evaluate(() => window.__spa_marker = true);
// Click a nav link (Geography)
await page.click('a[sx-get*="(geography)"]');
await expect(page).toHaveURL(/geography/, { timeout: 5000 });
// Must be SPA navigation — marker survives (full reload clears it)
const marker = await page.evaluate(() => window.__spa_marker);
expect(marker).toBe(true);
// After SPA nav, key layout elements should still exist (not destroyed by swap)
const layout = await page.evaluate(() => ({
hasNav: !!document.querySelector('#sx-nav'),
hasPanel: !!document.querySelector('#main-panel'),
navCount: document.querySelectorAll('#sx-nav').length,
panelCount: document.querySelectorAll('#main-panel').length,
}));
expect(layout.hasNav).toBe(true);
expect(layout.hasPanel).toBe(true);
expect(layout.navCount).toBe(1);
expect(layout.panelCount).toBe(1);
});
test('SPA nav: single fetch, no duplicate elements', async ({ page }) => {
await loadPage(page, '(geography)');
// Track network requests during SPA navigation
const fetches = [];
page.on('request', req => {
if (req.url().includes('/sx/') && !req.url().includes('/static/'))
fetches.push(req.url());
});
// SPA navigate
await page.click('a[sx-get*="(geography.(reactive))"]:not([href*="runtime"])');
await expect(page).toHaveURL(/reactive/, { timeout: 5000 });
await page.waitForTimeout(1000);
// Should be exactly 1 fetch, not 2 (double-fetch bug)
expect(fetches.length).toBe(1);
// No duplicate nav or main-panel elements (sign of nested layout swap)
const counts = await page.evaluate(() => ({
navCount: document.querySelectorAll('#sx-nav').length,
panelCount: document.querySelectorAll('#main-panel').length,
}));
expect(counts.navCount).toBe(1);
expect(counts.panelCount).toBe(1);
});
test('header island renders with SSR', async ({ page }) => {
await loadPage(page, '(geography)');
// Header should be visible
const header = page.locator('[data-sx-island="layouts/header"]');
await expect(header).toBeVisible();
// Should contain the logo
await expect(header).toContainText('sx');
// Should contain copyright
await expect(header).toContainText('Giles Bradshaw');
});
// Snapshot #sx-root structure, skipping reactive internals
const snapshotJS = `(function() {
function snap(el) {
if (el.nodeType === 3) { const t = el.textContent.trim(); return t ? { t } : null; }
if (el.nodeType !== 1) return null;
const n = { tag: el.tagName.toLowerCase() };
if (el.id) n.id = el.id;
const cls = Array.from(el.classList).sort().join(' ');
if (cls) n.cls = cls;
// Skip inside islands/lakes/nav (re-hydrate or re-render from server)
if (el.hasAttribute('data-sx-island') || el.hasAttribute('data-sx-lake')
|| el.hasAttribute('data-sx-reactive') || el.id === 'sx-nav') {
n.island = el.getAttribute('data-sx-island') || el.getAttribute('data-sx-lake') || el.id || 'reactive';
return n;
}
const ch = [];
for (const c of el.childNodes) { const s = snap(c); if (s) ch.push(s); }
if (ch.length) n.ch = ch;
return n;
}
const root = document.querySelector('#main-panel') || document.querySelector('#sx-root');
return root ? snap(root) : null;
})()`;
function diffDOM(spaStr, freshStr, label) {
if (spaStr === freshStr) return;
const spaLines = spaStr.split('\n');
const freshLines = freshStr.split('\n');
const diffs = [];
for (let i = 0; i < Math.max(spaLines.length, freshLines.length); i++) {
if (spaLines[i] !== freshLines[i]) {
diffs.push(` Line ${i+1}:`);
diffs.push(` SPA: ${(spaLines[i]||'(missing)').trim()}`);
diffs.push(` Fresh: ${(freshLines[i]||'(missing)').trim()}`);
if (diffs.length > 15) { diffs.push(' ...'); break; }
}
}
expect(spaStr === freshStr, `${label}\n${diffs.join('\n')}`).toBe(true);
}
const navRoutes = [
{ from: '(geography)', click: 'a[sx-get*="(geography.(reactive))"]:not([href*="runtime"])', url: /reactive/ },
{ from: '', click: 'a[sx-get*="(language)"]', url: /language/ },
{ from: '', click: 'a[sx-get*="(geography)"]', url: /geography/ },
];
for (const { from, click, url } of navRoutes) {
test(`SPA nav DOM matches fresh: ${from || '/'}${click.match(/\(([^)]+)\)/)?.[0] || '?'}`, async ({ page }) => {
await loadPage(page, from);
await page.click(click);
await expect(page).toHaveURL(url, { timeout: 5000 });
await page.waitForTimeout(1000);
const spaDOM = await page.evaluate(snapshotJS);
// Fresh load same URL
await page.goto(page.url(), { waitUntil: 'domcontentloaded' });
await waitForSxReady(page);
const freshDOM = await page.evaluate(snapshotJS);
diffDOM(
JSON.stringify(spaDOM, null, 2),
JSON.stringify(freshDOM, null, 2),
`SPA from ${from || '/'} to ${page.url()}`
);
});
}
});