Files
hrynco-kswitcher/tests/files_markdown_browser.mjs
T

292 lines
18 KiB
JavaScript

import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
import { setTimeout as delay } from 'node:timers/promises';
const [port, scenario, artifact, title] = process.argv.slice(2);
const terminalScenario = scenario.startsWith('terminal-');
let socket;
const pending = new Map();
let sequence = 0;
async function waitFor(callback, label) {
for (let i = 0; i < 150; ++i) {
const result = await callback();
if (result) return result;
await delay(100);
}
throw new Error('Timed out waiting for ' + label);
}
function command(method, params = {}) {
const id = ++sequence;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error('DevTools timed out on ' + method));
}, 5000);
pending.set(id, reply => {
clearTimeout(timer);
if (reply.error) reject(new Error(reply.error.message));
else resolve(reply.result);
});
socket.send(JSON.stringify({ id, method, params }));
});
}
async function evaluate(expression) {
const reply = await command('Runtime.evaluate', { expression, returnByValue: true });
if (reply.exceptionDetails) throw new Error(reply.exceptionDetails.exception.description);
return reply.result.value;
}
async function pressKey(key, code, windowsVirtualKeyCode, modifiers = 0) {
const params = { key, code, windowsVirtualKeyCode, modifiers };
await command('Input.dispatchKeyEvent', { type: 'keyDown', ...params });
await command('Input.dispatchKeyEvent', { type: 'keyUp', ...params });
}
const target = await waitFor(async () => {
const response = await fetch('http://127.0.0.1:' + port + '/json/list').catch(() => null);
if (!response?.ok) return;
const url = terminalScenario
? 'https://kswitcher-terminal.invalid/index.html'
: 'https://kswitcher-markdown.invalid/markdown.html';
return (await response.json()).find(item => item.url === url &&
(!title || item.title === title));
}, 'the target WebView2 page');
socket = new WebSocket(target.webSocketDebuggerUrl);
socket.addEventListener('message', event => {
const reply = JSON.parse(event.data);
const callback = pending.get(reply.id);
if (callback) {
pending.delete(reply.id);
callback(reply);
}
});
await new Promise((resolve, reject) => {
socket.addEventListener('open', resolve, { once: true });
socket.addEventListener('error', reject, { once: true });
});
try {
if (scenario === 'terminal-startup-pause' || scenario === 'terminal-startup-resume') {
await waitFor(() => evaluate('typeof startTerminalFixture === "function"'), 'the delayed terminal page');
if (scenario === 'terminal-startup-resume') await evaluate('startTerminalFixture()');
} else if (scenario === 'terminal-select-output') {
const selection = await waitFor(() => evaluate(`(() => {
const marker = 'terminal-output-copy-fixture';
const buffer = terminal.buffer.active;
for (let row = buffer.viewportY; row < buffer.viewportY + terminal.rows; row++) {
if (buffer.getLine(row)?.translateToString(true) !== marker) continue;
terminal.select(0, row, marker.length);
document.querySelector('#terminal').dispatchEvent(new PointerEvent('pointerup', { bubbles:true }));
return terminal.getSelection();
}
})()`), 'the terminal output fixture');
assert.equal(selection, 'terminal-output-copy-fixture');
} else if (scenario === 'terminal-prompt-text') {
await evaluate('terminal.focus()');
await command('Input.insertText', { text: artifact });
} else if (scenario === 'terminal-interrupt') {
await evaluate('terminal.focus()');
await pressKey('c', 'KeyC', 67, 2);
} else if (terminalScenario) {
assert.equal(await evaluate('terminal.options.cursorInactiveStyle'), 'none');
assert.equal(await evaluate('document.querySelectorAll(".xterm-cursor-outline").length'), 0);
await evaluate('document.querySelector(".xterm-helper-textarea").focus()');
const key = scenario === 'terminal-copy'
? { key:'Insert', code:'Insert', modifiers:2, windowsVirtualKeyCode:45 }
: { key:'Enter', code:'Enter', windowsVirtualKeyCode:13 };
await command('Input.dispatchKeyEvent', { type:'keyDown', ...key });
await command('Input.dispatchKeyEvent', { type:'keyUp', ...key });
} else if (scenario === 'render') {
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
!!document.querySelector('figure svg') &&
document.querySelector('img')?.naturalWidth === 1`), 'rendered Mermaid SVG and relative image');
assert.equal(await evaluate(`document.querySelector('h1').textContent`), 'Перегляд Markdown');
assert.equal(await evaluate(`[...document.querySelectorAll('nav button')].every(button => {
const style = getComputedStyle(button);
return style.borderTopWidth === '0px' && style.backgroundColor === 'rgba(0, 0, 0, 0)';
})`), true);
assert.equal(await evaluate(`document.querySelector('td').textContent`), 'Cell');
assert.deepEqual(await evaluate(`(() => {
const span = document.querySelector('td #nowrap-cell');
return span && [span.textContent, getComputedStyle(span).whiteSpace,
getComputedStyle(span).color, span.style.position, span.hasAttribute('onclick')];
})()`), ['In Development', 'nowrap', 'rgb(255, 0, 0)', '', false]);
assert.deepEqual(await evaluate(`(() => {
const table = document.querySelector('#html-table');
return table && [table.caption.textContent, table.querySelector('th').colSpan,
table.querySelector('td strong').textContent];
})()`), ['Raw HTML table', 2, 'Highest']);
await waitFor(() => evaluate(`document.querySelector('img[alt="HTML relative image"]')?.naturalWidth === 1`),
'the relative image in HTML');
assert.equal(await evaluate(`document.querySelector('figure svg').getBoundingClientRect().height > 0`), true);
assert.equal(await evaluate(`document.querySelector('figure svg').textContent.includes('Render target')`), true);
assert.equal(await evaluate(`(() => {
const paths = document.querySelector('figure svg g.edgePaths');
const labels = document.querySelector('figure svg g.edgeLabels');
const background = labels?.querySelector('.edgeLabel rect');
return !!(paths && labels && background && labels.textContent.includes('Transition') &&
(paths.compareDocumentPosition(labels) & Node.DOCUMENT_POSITION_FOLLOWING) &&
getComputedStyle(background).opacity === '1');
})()`), true);
assert.equal(await evaluate(`!!document.querySelector('pre code.language-mermaid') &&
document.querySelector('main').textContent.includes('Invalid Mermaid diagram')`), true);
assert.equal(await evaluate(`!!document.querySelector('pre code.language-js') && !document.querySelector('iframe')`), true);
assert.equal(await evaluate(`performance.getEntriesByType('resource')
.every(entry => entry.name.startsWith(location.origin + '/') || entry.name.startsWith('data:'))`), true);
await waitFor(() => evaluate(`document.querySelector('img[alt="Missing image"]')?.title === 'Image unavailable'`),
'missing image feedback');
assert.deepEqual(await evaluate(`[...document.querySelectorAll('main input')].map(box => box.checked)`), [false, true]);
if (artifact) {
const { cssContentSize } = await command('Page.getLayoutMetrics');
const { data } = await command('Page.captureScreenshot', { captureBeyondViewport: true,
clip: { x:0, y:0, width:cssContentSize.width, height:Math.min(cssContentSize.height, 620), scale:1 } });
await writeFile(artifact, Buffer.from(data, 'base64'));
}
} else if (scenario === 'startup-stalled') {
await waitFor(() => evaluate(`document.documentElement?.dataset.startup === 'stalled'`),
'the preview page to load without announcing readiness');
} else if (scenario === 'reopen') {
const heading = title === 'Reopen.md' ? 'Reopened Markdown' : 'Second Markdown';
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
document.querySelector('h1')?.textContent === ${JSON.stringify(heading)}`), heading);
assert.equal(await evaluate(`performance.getEntriesByName(new URL('mermaid.js', location.href).href).length`),
0, 'Reopening a document without diagrams must not load Mermaid');
} else if (scenario === 'external-replacement') {
await waitFor(() => evaluate(`document.documentElement?.classList.contains('rendered') &&
document.querySelector('main')?.textContent.trim() === 'An external replacement'`),
'the replacement file rendered after discarding edits');
} else if (scenario === 'diagram-reference') {
await waitFor(() => evaluate("document.documentElement.classList.contains('rendered')"), 'rendered diagram page');
const diagram = await evaluate(`(() => {
const svg = document.querySelector('figure svg');
const paths = svg?.querySelector('g.edgePaths');
const labels = svg?.querySelector('g.edgeLabels');
return {
error: document.querySelector('pre code.language-mermaid')?.parentElement.previousElementSibling?.title,
labels: [...(labels?.querySelectorAll('.edgeLabel') ?? [])]
.map(label => label.textContent.trim()).filter(Boolean),
paintedAbove: !!(paths && labels &&
(paths.compareDocumentPosition(labels) & Node.DOCUMENT_POSITION_FOLLOWING)),
opaque: [...(labels?.querySelectorAll('.edgeLabel rect') ?? [])].every(rect =>
getComputedStyle(rect).opacity === '1'),
};
})()`);
assert.equal(diagram.error, undefined, diagram.error);
assert.deepEqual(diagram.labels.sort(), ['F3', 'F6', 'F6']);
assert.equal(diagram.paintedAbove && diagram.opaque, true);
if (artifact) {
const { data } = await command('Page.captureScreenshot');
await writeFile(artifact, Buffer.from(data, 'base64'));
}
} else if (scenario === 'toggle-first-task' || scenario === 'first-task-checked') {
await waitFor(() => evaluate(`document.documentElement.classList.contains('rendered') &&
!!document.querySelector('main li.task input')`), 'rendered Markdown task');
if (scenario === 'toggle-first-task') {
const target = "document.querySelector('main li.task input')";
const before = await evaluate(target + '.checked');
await evaluate(target + '.click()');
await waitFor(() => evaluate(`!pendingTask && ${target}.checked !== ${before}`), 'saved Markdown task');
}
else
assert.equal(await evaluate(`document.querySelector('main li.task input').checked`), true);
} else if (scenario === 'search-menu' || scenario === 'search') {
const searchFocused = 'document.activeElement === document.getElementById("search-query")';
const searchClosed = 'document.getElementById("search").hidden';
if (scenario === 'search-menu') {
await waitFor(() => evaluate(searchFocused), 'the viewer menu opening rendered Markdown search');
await pressKey('Escape', 'Escape', 27);
await waitFor(() => evaluate(searchClosed), 'Escape closing only the search');
} else {
await pressKey('f', 'KeyF', 70, 2);
await waitFor(() => evaluate(searchFocused), 'Ctrl+F opening search and focusing the search field');
const status = 'document.getElementById("search-status").value';
const active = '[...(CSS.highlights.get("markdown-search-active") || [])][0]?.toString()';
const query = async text => {
await evaluate('document.getElementById("search-query").select()');
await command('Input.insertText', { text });
};
await query('ЗБІГ ПОШУКУ');
assert.equal(await evaluate(status), '1 / 2');
const toolbar = await evaluate(`({
queryWidth: document.getElementById('search-query').getBoundingClientRect().width,
closeRight: document.getElementById('search-close').getBoundingClientRect().right,
viewportWidth: document.documentElement.clientWidth
})`);
assert.ok(toolbar.queryWidth >= 100 && toolbar.closeRight <= toolbar.viewportWidth,
'The search controls must fit the viewer: ' + JSON.stringify(toolbar));
assert.equal(await evaluate(active), 'Збіг пошуку');
await pressKey('Enter', 'Enter', 13);
assert.equal(await evaluate(status), '2 / 2');
assert.equal(await evaluate(active), 'збіг пошуку');
await pressKey('F3', 'F3', 114);
assert.equal(await evaluate(status), '1 / 2');
await pressKey('Enter', 'Enter', 13, 8);
assert.equal(await evaluate(status), '2 / 2');
await pressKey('F3', 'F3', 114, 8);
assert.equal(await evaluate(status), '1 / 2');
await evaluate('document.getElementById("search-previous").click()');
assert.equal(await evaluate(status), '2 / 2');
await evaluate('document.getElementById("search-next").click()');
assert.equal(await evaluate(status), '1 / 2');
if (artifact) {
const { data } = await command('Page.captureScreenshot');
await writeFile(artifact, Buffer.from(data, 'base64'));
}
await query('для збіг пошуку');
assert.equal(await evaluate(status), '1 / 1');
assert.equal(await evaluate(active), 'для збіг пошуку');
await query('RENDER TARGET');
assert.equal(await evaluate(status), '1 / 1');
assert.equal(await evaluate(active), 'Render target');
await query('[no matches]');
assert.equal(await evaluate(status), 'No matches');
assert.equal(await evaluate(active), undefined);
await pressKey('Escape', 'Escape', 27);
assert.equal(await evaluate(searchClosed), true);
assert.equal(await evaluate('document.documentElement.classList.contains("rendered")'), true);
await evaluate('document.getElementById("search-open").click()');
assert.equal(await evaluate(searchFocused), true);
await evaluate('document.getElementById("search-close").click()');
assert.equal(await evaluate(searchClosed), true);
}
} else if (scenario === 'appearance-width' || scenario === 'appearance-full') {
const width = scenario === 'appearance-full' ? 'none' : '1200px';
await waitFor(() => evaluate(`(() => {
const text = getComputedStyle(document.querySelector('main'));
return getComputedStyle(document.body).maxWidth === ${JSON.stringify(width)} &&
text.fontSize === '24px' && text.fontFamily.startsWith('Georgia,');
})()`), 'the saved Markdown width, font family and font size');
} else if (scenario === 'edit') {
await command('Input.dispatchKeyEvent', { type: 'keyDown', key: 'F6', code: 'F6', windowsVirtualKeyCode: 117 });
} else if (['follow', 'shift-follow', 'ctrl-follow'].includes(scenario)) {
await evaluate(`document.querySelector('a[href^="child/"]').dispatchEvent(new MouseEvent('click', {
bubbles: true, cancelable: true, shiftKey: ${scenario === 'shift-follow'}, ctrlKey: ${scenario === 'ctrl-follow'}
}))`);
} else if (scenario === 'mouse-back' || scenario === 'mouse-forward') {
const button = scenario === 'mouse-back' ? 'back' : 'forward';
await waitFor(() => evaluate(`!document.getElementById('${button}').disabled`), button);
await command('Input.dispatchMouseEvent', {type:'mousePressed', x:15, y:80, button, buttons:button === 'back' ? 8 : 16});
await command('Input.dispatchMouseEvent', {type:'mouseReleased', x:15, y:80, button, buttons:0});
} else if (scenario === 'back' || scenario === 'forward') {
await waitFor(() => evaluate(`!document.getElementById('${scenario}').disabled`), scenario);
await evaluate(`document.getElementById('${scenario}').click()`);
} else if (scenario === 'cycle' || scenario === 'cycle-reverse') {
const modifiers = scenario === 'cycle-reverse' ? 10 : 2;
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'Tab', code:'Tab', modifiers, windowsVirtualKeyCode:9});
} else if (scenario === 'close') {
await command('Input.dispatchKeyEvent', {type:'keyDown', key:'w', code:'KeyW', modifiers:2, windowsVirtualKeyCode:87});
} else {
await waitFor(() => evaluate('document.documentElement?.classList.contains("rendered") && ' +
'document.querySelector("h1")?.textContent === ' + JSON.stringify(scenario)), scenario);
if (scenario === 'Linked Markdown') {
await waitFor(() => evaluate('scrollY > 0 && document.getElementById("target-heading").getBoundingClientRect().top < innerHeight'),
'the relative heading fragment to scroll into view');
}
}
} finally {
socket.close();
}