595 lines
33 KiB
JavaScript
595 lines
33 KiB
JavaScript
// The live preview of an HTML or CSS file (the editor's Preview mode, the quick editor's Preview): the page drawn in a
|
|
// sandboxed frame (srcdoc, no allow-same-origin: it can never reach the IDE), updated as one types. The project's own
|
|
// files it uses are put inside the page: linked .css as <style>, pictures and fonts as data: URLs. Remote scripts never
|
|
// run; the page's local scripts only when "Scripts" is on (off by default). A .css file is shown applied to a sample page,
|
|
// or to one of the project's HTML pages chosen in the list.
|
|
import { t, prefs } from './ui.js';
|
|
import { STATIC, groupRoutes, routeLabel, pickRoute, findRoute, inputsOf, missingValues, suggestSql, firstColumn, followRedirects, statusOf,
|
|
absoluteOf, inlineCss, choiceKey, choiceOf, offlinePage } from './page-preview-model.js';
|
|
|
|
const DEVICES = [['fit', 'Fit', 0], ['desktop', 'Desktop', 1280], ['tablet', 'Tablet', 768], ['phone', 'Phone', 390]];
|
|
|
|
const MIME = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', bmp: 'image/bmp',
|
|
ico: 'image/x-icon', svg: 'image/svg+xml', woff: 'font/woff', woff2: 'font/woff2', ttf: 'font/ttf', otf: 'font/otf', mp4: 'video/mp4',
|
|
webm: 'video/webm', mp3: 'audio/mpeg', ogg: 'audio/ogg', wav: 'audio/wav', css: 'text/css', js: 'text/javascript', json: 'application/json' };
|
|
export const mimeOf = (path) => MIME[(path.split('.').pop() || '').toLowerCase()] || 'application/octet-stream';
|
|
|
|
/** a link of the page -> the project file it names (relative to the page's folder), or null (remote, data:, #anchor...) */
|
|
export function resolveLocal(base, url) {
|
|
if (!url) return null;
|
|
const u = url.trim();
|
|
if (!u || /^([a-z][a-z0-9+.-]*:|\/\/|#)/i.test(u)) return null;
|
|
const clean = u.split('#')[0].split('?')[0];
|
|
if (!clean) return null;
|
|
let decoded = clean;
|
|
try { decoded = decodeURIComponent(clean); } catch { /* as it is */ }
|
|
const parts = (decoded.startsWith('/') ? decoded.slice(1) : (base ? base + '/' : '') + decoded).split('/');
|
|
const out = [];
|
|
for (const p of parts) { if (p === '..') out.pop(); else if (p !== '.' && p !== '') out.push(p); }
|
|
return out.join('/');
|
|
}
|
|
|
|
const dirOf = (path) => (path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '');
|
|
|
|
const SAMPLE = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Sample</title></head>
|
|
<body>
|
|
<header><nav><a href="#">Home</a> · <a href="#">Games</a> · <a href="#">About</a></nav></header>
|
|
<main>
|
|
<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3><h4>Heading 4</h4>
|
|
<p>A paragraph with <a href="#">a link</a>, <strong>strong</strong>, <em>emphasis</em>, <code>code</code>, <small>small</small> and <mark>marked</mark> text.
|
|
The quick brown fox jumps over the lazy dog.</p>
|
|
<blockquote>A quotation, in a blockquote.</blockquote>
|
|
<ul><li>First item</li><li>Second item</li></ul><ol><li>One</li><li>Two</li></ol>
|
|
<p><button>Button</button> <button class="primary btn btn-primary">Primary</button> <button disabled>Disabled</button></p>
|
|
<form><fieldset><legend>A form</legend>
|
|
<p><label>Name <input type="text" placeholder="Ada Lovelace"></label></p>
|
|
<p><label>E-mail <input type="email" value="[email protected]"></label></p>
|
|
<p><label>Choice <select><option>One</option><option>Two</option></select></label></p>
|
|
<p><label><input type="checkbox" checked> Checkbox</label> <label><input type="radio" name="r" checked> Radio</label></p>
|
|
<p><textarea rows="3">Text area</textarea></p>
|
|
<p><input type="submit" value="Send"></p></fieldset></form>
|
|
<table><caption>A table</caption><thead><tr><th>Game</th><th>Year</th><th>Score</th></tr></thead>
|
|
<tbody><tr><td>Pong</td><td>1972</td><td>11</td></tr><tr><td>Breakout</td><td>1976</td><td>448</td></tr></tbody></table>
|
|
<pre>pre-formatted
|
|
text</pre><hr>
|
|
</main><footer><p>Footer</p></footer>
|
|
</body></html>`;
|
|
|
|
const STYLE = `
|
|
.hprev { position: absolute; inset: 0; display: flex; flex-direction: column; background: var(--bg, #1e1f22); color: var(--text, #dfe1e5); font-size: 12px; }
|
|
.hprev-bar { display: flex; align-items: center; gap: 4px; padding: 4px 8px; border-bottom: 1px solid var(--border-2, var(--line, #393b40)); flex: none; flex-wrap: wrap; }
|
|
.hprev-bar button, .hprev-bar select { font: inherit; color: inherit; background: transparent; border: 1px solid transparent; border-radius: 4px; padding: 2px 8px; cursor: pointer; }
|
|
.hprev-bar select { border-color: var(--border-2, var(--line, #393b40)); max-width: 260px; background: var(--bg, #1e1f22); }
|
|
.hprev-bar button:hover { border-color: var(--border-2, var(--line, #393b40)); }
|
|
.hprev-bar button.on { background: var(--accent, #3574f0); color: #fff; }
|
|
.hprev-bar label { display: flex; align-items: center; gap: 4px; margin-left: 6px; cursor: pointer; }
|
|
.hprev-bar .grow { flex: 1; }
|
|
.hprev-bar .route { max-width: 300px; }
|
|
.hprev-bar input.param { width: 90px; font: inherit; color: inherit; background: var(--bg, #1e1f22); border: 1px solid var(--border-2, var(--line, #393b40)); border-radius: 4px; padding: 2px 6px; }
|
|
.hprev-bar input.param.bad { border-color: #e5484d; }
|
|
.hprev-bar .pname { color: var(--text-2, var(--muted, #8c8f96)); }
|
|
.hprev-note { display: flex; align-items: center; gap: 8px; padding: 3px 10px; font-size: 11.5px; border-bottom: 1px solid var(--border-2, var(--line, #393b40)); flex: none; }
|
|
.hprev-note.error { background: rgba(229,72,77,.14); } .hprev-note.warn, .hprev-note.redirect { background: rgba(245,166,35,.14); } .hprev-note.ok { color: var(--text-2, var(--muted, #8c8f96)); }
|
|
.hprev-note button { font: inherit; color: inherit; background: transparent; border: 1px solid var(--border-2, var(--line, #393b40)); border-radius: 4px; padding: 1px 8px; cursor: pointer; }
|
|
.hprev-bar .size { color: var(--text-2, var(--muted, #8c8f96)); white-space: nowrap; }
|
|
.hprev-stage { flex: 1; min-height: 0; overflow: hidden; position: relative; background: repeating-conic-gradient(rgba(127,127,127,.12) 0% 25%, transparent 0% 50%) 50% / 16px 16px; }
|
|
.hprev-stage iframe { position: absolute; left: 0; top: 0; border: 0; background: #fff; transform-origin: 0 0; box-shadow: 0 2px 14px rgba(0,0,0,.35); }
|
|
`;
|
|
|
|
// runs in the preview's frame (inspect): outlines the elements of a selector, tells which rules a clicked element matches
|
|
const INSPECTOR = `(() => {
|
|
let state = { selector: '', rules: [] };
|
|
let layer = null, hover = null;
|
|
const box = (r, css) => { const b = document.createElement('div'); b.style.cssText = 'position:fixed;box-sizing:border-box;pointer-events:none;left:' + r.left + 'px;top:' + r.top + 'px;width:' + r.width + 'px;height:' + r.height + 'px;' + css; return b; };
|
|
const matches = (el, sel) => { try { return el.matches(sel); } catch (e) { return false; } };
|
|
function draw(scroll) {
|
|
if (!document.body) return;
|
|
if (!layer) { layer = document.createElement('div'); layer.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:2147483646'; document.documentElement.append(layer); }
|
|
layer.replaceChildren();
|
|
let list = [];
|
|
try { list = state.selector ? [...document.querySelectorAll(state.selector)] : []; } catch (e) { list = []; }
|
|
for (const el of list.slice(0, 400)) {
|
|
const r = el.getBoundingClientRect();
|
|
if (r.width || r.height) layer.append(box(r, 'background:rgba(255,170,0,.16);outline:2px solid #ffaa00;'));
|
|
}
|
|
if (scroll && list[0]) list[0].scrollIntoView({ block: 'nearest' });
|
|
parent.postMessage({ jumphpCss: 'count', count: list.length }, '*');
|
|
}
|
|
const describe = (el) => el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + [...el.classList].slice(0, 3).map((c) => '.' + c).join('');
|
|
addEventListener('message', (e) => { if (e.source !== parent || !e.data || e.data.jumphpCss !== 'highlight') return; state = e.data; draw(!!e.data.scroll); });
|
|
addEventListener('scroll', () => draw(false), true);
|
|
addEventListener('resize', () => draw(false));
|
|
document.addEventListener('mouseover', (e) => {
|
|
if (!layer) draw(false);
|
|
hover?.remove();
|
|
const r = e.target.getBoundingClientRect();
|
|
hover = box(r, 'outline:1px dashed #3574f0;background:rgba(53,116,240,.08);');
|
|
layer?.append(hover);
|
|
}, true);
|
|
document.addEventListener('mouseout', () => { hover?.remove(); hover = null; }, true);
|
|
document.addEventListener('click', (e) => {
|
|
e.preventDefault(); e.stopPropagation();
|
|
const el = e.target;
|
|
const chain = [];
|
|
for (let n = el; n && n.nodeType === 1 && chain.length < 6; n = n.parentElement) chain.push(describe(n));
|
|
parent.postMessage({ jumphpCss: 'pick', ids: state.rules.filter((r) => matches(el, r.selector)).map((r) => r.id), label: describe(el), chain: chain.reverse() }, '*');
|
|
}, true);
|
|
const ready = () => { draw(false); parent.postMessage({ jumphpCss: 'ready' }, '*'); };
|
|
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', ready); else ready();
|
|
})();`;
|
|
|
|
function addStyle() {
|
|
if (document.getElementById('hprev-style')) return;
|
|
const style = document.createElement('style');
|
|
style.id = 'hprev-style';
|
|
style.textContent = STYLE;
|
|
document.head.append(style);
|
|
}
|
|
|
|
const make = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = text; return n; };
|
|
|
|
export class HtmlPreview {
|
|
/**
|
|
* @param {HTMLElement} host
|
|
* @param {{path: string, kind: 'html'|'css', text: () => string, readText: (path: string) => Promise<?string>,
|
|
* readDataUrl: (path: string) => Promise<?string>, htmlFiles?: () => string[], prefix?: string}} options
|
|
* prefix: the key of the remembered choices (device, scripts, the page of a .css)
|
|
*/
|
|
constructor(host, options) {
|
|
addStyle();
|
|
this.o = options;
|
|
this.prefix = options.prefix || 'preview';
|
|
this.device = prefs.get(this.prefix + 'Device', 'fit');
|
|
this.scripts = !!prefs.get(this.prefix + 'Scripts', false);
|
|
this.layout = prefs.get(this.prefix + 'TwigLayout', true) !== false; // a .twig: its {% extends %} and the project's CSS
|
|
this.page = options.kind === 'css' ? prefs.get(this.prefix + 'Page:' + options.path, '') : '';
|
|
this.live = options.live || null; // the Twig preview's real page: {routes, site, fetch, suggest, startSite} (editor.js)
|
|
this.routes = [];
|
|
this.route = STATIC;
|
|
this.values = {};
|
|
this.session = false;
|
|
this.siteUrl = '';
|
|
this.siteDown = false;
|
|
this.result = null;
|
|
this.images = new Map(); // path -> data URL (pictures and fonts do not change as one types)
|
|
this.generation = 0;
|
|
this.node = make('div', 'hprev');
|
|
const bar = make('div', 'hprev-bar');
|
|
this.buttons = DEVICES.map(([id, label, width]) => {
|
|
const b = make('button', id === this.device ? 'on' : '', t(label));
|
|
b.title = width ? `${width} px` : t('The width of the preview');
|
|
b.onclick = () => { this.device = id; prefs.set(this.prefix + 'Device', id); for (const x of this.buttons) x.classList.toggle('on', x === b); this.fit(); };
|
|
return b;
|
|
});
|
|
bar.append(...this.buttons);
|
|
if (options.kind === 'css') {
|
|
this.select = make('select');
|
|
this.select.title = t('The page the stylesheet is applied to');
|
|
this.fillPages();
|
|
this.select.onchange = () => { this.page = this.select.value; prefs.set(this.prefix + 'Page:' + options.path, this.page); this.update(); };
|
|
bar.append(this.select);
|
|
}
|
|
const scripts = make('label');
|
|
const box = make('input');
|
|
box.type = 'checkbox';
|
|
box.checked = this.scripts;
|
|
box.onchange = () => { this.scripts = box.checked; prefs.set(this.prefix + 'Scripts', this.scripts); this.update(); };
|
|
scripts.title = t('Run the page\'s own scripts (never remote ones), in a sandbox that cannot reach the IDE');
|
|
scripts.append(box, t('Scripts'));
|
|
let layout = null;
|
|
if (options.twig) {
|
|
layout = make('label');
|
|
layout.setAttribute('data-tour', 'twig-layout');
|
|
const on = make('input');
|
|
on.type = 'checkbox';
|
|
on.checked = this.layout;
|
|
on.onchange = () => { this.layout = on.checked; prefs.set(this.prefix + 'TwigLayout', this.layout); this.update(); };
|
|
layout.title = t('Lay the template out as Symfony would: its {% extends %} and {% include %}, and the project\'s stylesheets');
|
|
layout.append(on, t('Layout + CSS'));
|
|
}
|
|
const reload = make('button', '', '⟳');
|
|
reload.title = t('Reload the preview');
|
|
reload.onclick = () => { this.images.clear(); this.update(); };
|
|
this.sizeLabel = make('span', 'size');
|
|
this.layoutLabel = layout;
|
|
if (this.live) this.buildLiveBar(bar);
|
|
bar.append(...(layout ? [layout] : []), scripts, make('span', 'grow'), this.sizeLabel, reload);
|
|
this.note = make('div', 'hprev-note');
|
|
this.note.style.display = 'none';
|
|
this.stage = make('div', 'hprev-stage');
|
|
this.frame = make('iframe');
|
|
this.frame.title = t('Preview');
|
|
this.frame.setAttribute('sandbox', '');
|
|
this.frame.setAttribute('referrerpolicy', 'no-referrer');
|
|
this.stage.append(this.frame);
|
|
this.node.append(bar, this.note, this.stage);
|
|
host.append(this.node);
|
|
this.resize = new ResizeObserver(() => this.fit());
|
|
this.resize.observe(this.stage);
|
|
// inspect (the visual stylesheet editor): the elements a selector matches outlined, a click gives what was clicked
|
|
this.highlighted = null;
|
|
this.onMessage = (e) => {
|
|
if (!(options.inspect || options.onFrameMessage) || e.source !== this.frame.contentWindow || !e.data || typeof e.data !== 'object') return;
|
|
options.onFrameMessage?.(e.data); // the Bootstrap editor's own script in the page (options.script)
|
|
if (!options.inspect) return;
|
|
if (e.data.jumphpCss === 'ready' && this.highlighted) this.post(this.highlighted);
|
|
if (e.data.jumphpCss === 'pick') options.onPick?.(e.data);
|
|
if (e.data.jumphpCss === 'count') options.onCount?.(e.data.count);
|
|
};
|
|
addEventListener('message', this.onMessage);
|
|
if (this.live) this.loadRoutes(); else this.update();
|
|
}
|
|
|
|
/** the route selector, the inputs of its parameters, "My session", "Start the site" (the Twig preview's real page) */
|
|
buildLiveBar(bar) {
|
|
this.routeSelect = make('select', 'route');
|
|
this.routeSelect.setAttribute('data-tour', 'twig-route');
|
|
this.routeSelect.title = t('The page of the running site this template is shown in: its data comes from the controller. Static: the template alone, no PHP.');
|
|
this.routeSelect.onchange = () => this.chooseRoute(this.routeSelect.value, true);
|
|
this.params = make('span');
|
|
this.params.style.display = 'contents';
|
|
const session = make('label');
|
|
this.sessionBox = make('input');
|
|
this.sessionBox.type = 'checkbox';
|
|
this.sessionBox.onchange = () => { this.session = this.sessionBox.checked; this.remember(); this.update(); };
|
|
session.title = t('Fetch the page with the cookies of the HTTP Client\'s session (a login made there) instead of as a stranger');
|
|
session.append(this.sessionBox, t('My session'));
|
|
this.sessionLabel = session;
|
|
this.startButton = make('button', '', t('Start the site'));
|
|
this.startButton.title = t('Run "Serve the site", then the page shows by itself');
|
|
this.startButton.style.display = 'none';
|
|
this.startButton.onclick = () => this.startSite();
|
|
bar.append(this.routeSelect, this.params, session, this.startButton);
|
|
}
|
|
|
|
async loadRoutes() {
|
|
let found = null;
|
|
try { found = await this.live.routes(); } catch { found = null; }
|
|
this.routes = found?.routes || [];
|
|
this.siteUrl = found?.site || '';
|
|
if (!this.routes.length) { // no controller with routes: the static preview only, no selector
|
|
for (const n of [this.routeSelect, this.params, this.sessionLabel]) n.style.display = 'none';
|
|
this.live = null;
|
|
this.update();
|
|
return;
|
|
}
|
|
const saved = prefs.get(choiceKey(this.prefix, this.o.path), null);
|
|
this.session = !!saved?.session;
|
|
this.sessionBox.checked = this.session;
|
|
this.fillRoutes();
|
|
await this.chooseRoute(pickRoute(this.routes, saved), false, saved?.values || {});
|
|
}
|
|
|
|
fillRoutes() {
|
|
const g = groupRoutes(this.routes);
|
|
const option = (value, text) => { const o = make('option', '', text); o.value = value; return o; };
|
|
const group = (label, list) => { if (!list.length) return []; const og = make('optgroup'); og.label = label; og.append(...list.map((r) => option(r.name, routeLabel(r)))); return [og]; };
|
|
this.routeSelect.replaceChildren(option(STATIC, t('Static (no PHP)')), ...group(t('Renders this template'), g.renders), ...group(t('Other routes'), g.get), ...group(t('Other methods'), g.other));
|
|
this.routeSelect.value = this.route;
|
|
}
|
|
|
|
async chooseRoute(name, userChoice, values = null) {
|
|
this.route = name;
|
|
this.routeSelect.value = name;
|
|
const route = findRoute(this.routes, name);
|
|
const saved = prefs.get(choiceKey(this.prefix, this.o.path), null);
|
|
this.inputs = inputsOf(route, values ?? (saved?.route === name ? saved.values : {}) ?? {});
|
|
this.params.replaceChildren();
|
|
for (const input of this.inputs) {
|
|
const label = make('span', 'pname', input.name);
|
|
const box = make('input', 'param');
|
|
box.value = input.value;
|
|
box.placeholder = input.placeholder;
|
|
box.title = `{${input.name}}`;
|
|
if (input.entity) box.setAttribute('list', 'hprev-ids-' + input.name);
|
|
const list = make('datalist');
|
|
list.id = 'hprev-ids-' + input.name;
|
|
box.onchange = () => { input.value = box.value; this.remember(); this.update(); };
|
|
box.onkeydown = (e) => { if (e.key === 'Enter') box.onchange(); };
|
|
input.node = box;
|
|
input.list = list;
|
|
this.params.append(label, box, list);
|
|
}
|
|
if (this.layoutLabel) this.layoutLabel.style.display = name === STATIC ? '' : 'none';
|
|
this.sessionLabel.style.display = name === STATIC ? 'none' : '';
|
|
if (userChoice) this.remember();
|
|
// an entity's id: the first ones of the database, when the Database window has a connection open
|
|
const wait = this.suggest();
|
|
if (name === STATIC) { this.hideNote(); this.startButton.style.display = 'none'; }
|
|
await wait;
|
|
this.update();
|
|
}
|
|
|
|
async suggest() {
|
|
const generation = this.generation;
|
|
await Promise.all(this.inputs.filter((i) => i.entity && this.live.suggest).map(async (input) => {
|
|
const sql = suggestSql(input);
|
|
let values = [];
|
|
try { values = sql ? firstColumn(await this.live.suggest(sql)) : []; } catch { values = []; }
|
|
input.list?.replaceChildren(...values.map((v) => { const o = make('option'); o.value = v; return o; }));
|
|
if (values.length && !String(input.value).trim() && input.required) { input.value = values[0]; input.node.value = values[0]; }
|
|
}));
|
|
}
|
|
|
|
remember() { prefs.set(choiceKey(this.prefix, this.o.path), choiceOf(this.route, Object.fromEntries((this.inputs || []).map((i) => [i.name, i.value])), this.session)); }
|
|
|
|
/** "Start the site": the run configuration, then the address is asked every 3 s until it answers */
|
|
startSite() {
|
|
this.live.startSite?.();
|
|
clearInterval(this.waiting);
|
|
const begun = Date.now();
|
|
this.showNote('warn', t('Starting the site…'));
|
|
this.waiting = setInterval(async () => {
|
|
let site = null;
|
|
try { site = await this.live.site(); } catch { site = null; }
|
|
if (site?.running) { clearInterval(this.waiting); this.siteUrl = site.url; this.update(); }
|
|
else if (Date.now() - begun > 180000) { clearInterval(this.waiting); this.update(); }
|
|
}, 3000);
|
|
}
|
|
|
|
showNote(kind, text, action = null) {
|
|
this.note.className = 'hprev-note ' + kind;
|
|
this.note.replaceChildren(make('span', '', text));
|
|
if (action) { const b = make('button', '', action[0]); b.onclick = action[1]; this.note.append(b); }
|
|
this.note.style.display = '';
|
|
this.fit();
|
|
}
|
|
|
|
hideNote() { this.note.style.display = 'none'; this.fit(); }
|
|
|
|
destroy() { clearInterval(this.waiting); this.resize.disconnect(); removeEventListener('message', this.onMessage); this.node.remove(); }
|
|
|
|
post(message) { try { this.frame.contentWindow?.postMessage(message, '*'); } catch { /* the frame is being replaced */ } }
|
|
|
|
/** inspect: outline what `selector` matches (scroll: to the first one); rules [{id, selector}] are what a click is matched against */
|
|
highlight(selector, rules = null, scroll = false) {
|
|
this.highlighted = { jumphpCss: 'highlight', selector: selector || '', rules: rules || this.highlighted?.rules || [], scroll };
|
|
this.post(this.highlighted);
|
|
}
|
|
|
|
fillPages() {
|
|
const pages = (this.o.htmlFiles?.() || []).filter((p) => /\.html?$/i.test(p)).slice(0, 500);
|
|
if (this.page && !pages.includes(this.page)) this.page = '';
|
|
this.select.replaceChildren(make('option', '', t('Sample page')), ...pages.map((p) => make('option', '', p)));
|
|
this.select.options[0].value = '';
|
|
for (const opt of [...this.select.options].slice(1)) opt.value = opt.textContent;
|
|
this.select.value = this.page;
|
|
}
|
|
|
|
/** the frame at the chosen width, scaled down when the room is narrower */
|
|
fit() {
|
|
const width = DEVICES.find((d) => d[0] === this.device)?.[2] || 0;
|
|
const room = this.stage.clientWidth;
|
|
const height = this.stage.clientHeight;
|
|
const w = width || room;
|
|
const scale = width && width > room ? room / width : 1;
|
|
Object.assign(this.frame.style, { width: w + 'px', height: (height / scale) + 'px', transform: scale !== 1 ? `scale(${scale})` : '', left: scale === 1 && width ? Math.max(0, (room - w) / 2) + 'px' : '0' });
|
|
this.sizeLabel.textContent = `${Math.round(w)} px${scale !== 1 ? ` · ${Math.round(scale * 100)} %` : ''}`;
|
|
}
|
|
|
|
/** cause 'typing': the real page shows what is saved, so a keystroke changes nothing there; 'saved': a file was written */
|
|
async update(cause = '') {
|
|
const real = this.live && this.route !== STATIC;
|
|
if (real && cause === 'typing' && !this.siteDown) return;
|
|
const generation = ++this.generation;
|
|
let html;
|
|
try { html = real ? await this.buildLive() : await this.build(); } catch (e) { html = `<pre style="color:#b00;white-space:pre-wrap">${String(e.message || e).replace(/</g, '<')}</pre>`; }
|
|
if (generation !== this.generation) return; // an older build finished after a newer one started
|
|
this.frame.setAttribute('sandbox', this.scripts || this.o.inspect || this.o.script ? 'allow-scripts' : '');
|
|
this.frame.srcdoc = html;
|
|
this.fit();
|
|
}
|
|
|
|
/** the real page of the chosen route, fetched from the local site (stylesheets and pictures put inside it), or the static preview meanwhile */
|
|
async buildLive() {
|
|
const route = findRoute(this.routes, this.route);
|
|
if (!route) return this.build();
|
|
const missing = missingValues(this.inputs);
|
|
for (const i of this.inputs) i.node?.classList.toggle('bad', missing.includes(i.name));
|
|
if (missing.length) {
|
|
this.showNote('warn', t('Fill in {names} to see the page of this route (the static preview meanwhile).', { names: missing.join(', ') }));
|
|
return this.build();
|
|
}
|
|
const values = Object.fromEntries(this.inputs.map((i) => [i.name, i.value]));
|
|
const defaults = Object.fromEntries((route.params || []).filter((p) => p.default !== null && p.default !== undefined).map((p) => [p.name, p.default]));
|
|
const site = this.siteUrl;
|
|
const session = this.session;
|
|
let result;
|
|
try {
|
|
result = await followRedirects(() => this.live.fetch({ path: route.path, values, defaults, site, session }), (url) => this.live.fetch({ url, site, session }));
|
|
} catch (e) {
|
|
this.siteDown = true;
|
|
this.startButton.style.display = '';
|
|
this.showNote('warn', t('The site does not answer ({message}): the static preview meanwhile.', { message: String(e.message || e).slice(0, 120) }));
|
|
return this.build();
|
|
}
|
|
this.siteDown = false;
|
|
this.startButton.style.display = 'none';
|
|
this.result = result;
|
|
const s = statusOf(result);
|
|
const detail = `${s.text} · ${s.url ? s.url.replace(/^https?:\/\/[^/]+/, '') : ''}${s.time !== undefined ? ` · ${s.time} ms` : ''}`;
|
|
if (result.login && !session) {
|
|
this.showNote('warn', t('Redirected to the sign-in page: {detail}', { detail }), [t('Use my session'), () => { this.session = true; this.sessionBox.checked = true; this.remember(); this.update(); }]);
|
|
} else if (result.loop) this.showNote('warn', t('Too many redirects: {detail}', { detail }));
|
|
else if (s.kind === 'error') this.showNote('error', t('{detail}: Symfony\'s error page, as the site sends it.', { detail }));
|
|
else if (s.kind === 'warn' || s.kind === 'redirect') this.showNote('warn', detail);
|
|
else this.showNote('ok', detail);
|
|
const r = result.response;
|
|
if (r.binary) return offlinePage(t('The page is not text ({type}).', { type: r.type }));
|
|
if (!/html|xhtml/i.test(r.type) && r.type !== '') return `<pre style="white-space:pre-wrap;font:12px monospace;margin:1em">${String(r.body).replace(/&/g, '&').replace(/</g, '<')}</pre>`;
|
|
return this.build({ html: r.body, url: r.url });
|
|
}
|
|
|
|
/** the page, with the project's files it uses put inside it, and a policy that keeps it off the network for scripts */
|
|
async build(live = null) {
|
|
const { kind, path } = this.o;
|
|
const R = live ? this.liveContext(live.url) : this.localContext();
|
|
let source;
|
|
let base;
|
|
let extraCss = null;
|
|
if (live) {
|
|
source = live.html;
|
|
base = live.url;
|
|
} else if (kind === 'css') {
|
|
if (this.page) {
|
|
source = (await this.o.readText(this.page)) ?? SAMPLE;
|
|
base = dirOf(this.page);
|
|
} else {
|
|
source = SAMPLE;
|
|
base = dirOf(path);
|
|
}
|
|
extraCss = path;
|
|
} else {
|
|
source = await this.o.text(this);
|
|
base = dirOf(path);
|
|
}
|
|
const doc = new DOMParser().parseFromString(source, 'text/html');
|
|
// options.head(doc): markup the caller adds to the page's head (the Bootstrap editor links Bootstrap's CSS when the page has none)
|
|
if (this.o.head) doc.head.insertAdjacentHTML('afterbegin', (await this.o.head(doc)) || '');
|
|
// stylesheets of the project: inlined (the .css being edited: its text as it is now, not as saved)
|
|
let linked = false;
|
|
for (const link of [...doc.querySelectorAll('link[rel~="stylesheet" i][href]')]) {
|
|
const file = R.res(base, link.getAttribute('href'));
|
|
if (!file) continue;
|
|
if (file === extraCss) linked = true;
|
|
const css = file === extraCss ? await this.o.text() : await R.text(file);
|
|
const style = doc.createElement('style');
|
|
style.dataset.done = '1';
|
|
if (link.media) style.media = link.media;
|
|
style.textContent = css === null || css === undefined ? `/* ${file}: not found */` : await this.css(css, R.dir(file), new Set([file]), R);
|
|
link.replaceWith(style);
|
|
}
|
|
if (extraCss && !linked) {
|
|
const style = doc.createElement('style');
|
|
style.dataset.done = '1';
|
|
style.textContent = await this.css(await this.o.text(), R.dir(extraCss), new Set([extraCss]), R);
|
|
doc.head.append(style);
|
|
}
|
|
for (const style of [...doc.querySelectorAll('style')]) {
|
|
if (!style.dataset.done) style.textContent = await this.css(style.textContent, base, new Set(), R);
|
|
}
|
|
for (const node of [...doc.querySelectorAll('[style]')]) {
|
|
const value = node.getAttribute('style');
|
|
if (/url\(/i.test(value)) node.setAttribute('style', await this.css(value, base, new Set(), R));
|
|
}
|
|
// pictures, films, sounds, icons
|
|
for (const [selector, attr] of [['img[src]', 'src'], ['source[src]', 'src'], ['video[src]', 'src'], ['audio[src]', 'src'], ['video[poster]', 'poster'],
|
|
['input[type="image" i][src]', 'src'], ['link[rel~="icon" i][href]', 'href'], ['object[data]', 'data'], ['embed[src]', 'src']]) {
|
|
for (const node of [...doc.querySelectorAll(selector)]) {
|
|
const file = R.res(base, node.getAttribute(attr));
|
|
if (file) node.setAttribute(attr, (await this.dataUrl(file, R)) || '');
|
|
}
|
|
}
|
|
for (const node of [...doc.querySelectorAll('[srcset]')]) {
|
|
const parts = [];
|
|
for (const candidate of node.getAttribute('srcset').split(',')) {
|
|
const [url, ...rest] = candidate.trim().split(/\s+/);
|
|
const file = R.res(base, url);
|
|
parts.push([file ? (await this.dataUrl(file, R)) || url : url, ...rest].join(' '));
|
|
}
|
|
node.setAttribute('srcset', parts.join(', '));
|
|
}
|
|
for (const node of [...doc.querySelectorAll('svg image[href], image[href]')]) {
|
|
const file = R.res(base, node.getAttribute('href'));
|
|
if (file) node.setAttribute('href', (await this.dataUrl(file, R)) || '');
|
|
}
|
|
// scripts: remote ones never; the page's own only when asked (inlined)
|
|
for (const script of [...doc.querySelectorAll('script')]) {
|
|
const src = script.getAttribute('src');
|
|
if (!this.scripts) { script.remove(); continue; }
|
|
if (src === null) continue;
|
|
const file = R.res(base, src);
|
|
const code = file ? await R.text(file) : null;
|
|
if (code === null || code === undefined) { script.remove(); continue; }
|
|
script.removeAttribute('src');
|
|
script.textContent = code;
|
|
}
|
|
// no navigation out of the preview: links do nothing (a sandbox without popups), forms are not sent
|
|
for (const old of [...doc.querySelectorAll('meta[http-equiv]')]) if (/refresh|content-security-policy/i.test(old.getAttribute('http-equiv'))) old.remove();
|
|
for (const old of [...doc.querySelectorAll('base')]) old.remove();
|
|
const csp = doc.createElement('meta');
|
|
csp.setAttribute('http-equiv', 'Content-Security-Policy');
|
|
// inspect: one script of ours (a nonce: the page's own inline handlers still never run unless Scripts is on)
|
|
const nonce = this.o.inspect || this.o.script ? Math.random().toString(36).slice(2) + Date.now().toString(36) : '';
|
|
const scriptSrc = this.scripts ? "'unsafe-inline'" : nonce ? `'nonce-${nonce}'` : "'none'";
|
|
csp.setAttribute('content', `default-src 'none'; style-src 'unsafe-inline' https: data:; img-src data: blob: https:; font-src data: https:; media-src data: blob: https:; script-src ${scriptSrc}; form-action 'none'; connect-src 'none'; frame-src 'none'`);
|
|
doc.head.prepend(csp);
|
|
if (nonce) {
|
|
const script = doc.createElement('script');
|
|
script.setAttribute('nonce', nonce);
|
|
script.textContent = (this.o.inspect ? INSPECTOR + '\n' : '') + (this.o.script || '');
|
|
doc.head.append(script);
|
|
}
|
|
if (!doc.querySelector('meta[charset]')) { const m = doc.createElement('meta'); m.setAttribute('charset', 'utf-8'); doc.head.prepend(m); }
|
|
return '<!doctype html>\n' + doc.documentElement.outerHTML;
|
|
}
|
|
|
|
/** a stylesheet with its url(...) of the project as data: URLs and its @import of the project inlined */
|
|
async css(text, base, seen, R) {
|
|
if (R.live) return inlineCss(text, base, { text: R.text, dataUrl: (u) => this.dataUrl(u, R) }, R.origin, seen);
|
|
let out = String(text || '');
|
|
const imports = [...out.matchAll(/@import\s+(?:url\(\s*)?(['"]?)([^'")\s;]+)\1\s*\)?([^;]*);/gi)];
|
|
for (const m of imports) {
|
|
const file = R.res(base, m[2]);
|
|
if (!file || seen.has(file)) continue;
|
|
seen.add(file);
|
|
const inner = await R.text(file);
|
|
const media = m[3].trim();
|
|
const body = inner === null || inner === undefined ? `/* ${file}: not found */` : await this.css(inner, R.dir(file), seen, R);
|
|
out = out.replace(m[0], media ? `@media ${media} {\n${body}\n}` : body);
|
|
}
|
|
const urls = [...out.matchAll(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi)];
|
|
for (const m of urls) {
|
|
const file = R.res(base, m[2]);
|
|
if (!file) continue;
|
|
const data = await this.dataUrl(file, R);
|
|
if (data) out = out.split(m[0]).join(`url("${data}")`);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
localContext() {
|
|
return { live: false, res: resolveLocal, dir: dirOf, text: (f) => this.o.readText(f), data: (f) => this.o.readDataUrl(f) };
|
|
}
|
|
|
|
/** the real page's files: addresses of the local site, asked through the backend (text, or base64 for pictures and fonts) */
|
|
liveContext(pageUrl) {
|
|
let origin = '';
|
|
try { origin = new URL(pageUrl).origin; } catch { origin = ''; }
|
|
const ask = async (url, accept) => {
|
|
try {
|
|
const r = await this.live.fetch({ url, site: this.siteUrl, session: this.session, accept });
|
|
return r.status < 400 ? r : null;
|
|
} catch { return null; }
|
|
};
|
|
return {
|
|
live: true, origin, res: (b, u) => absoluteOf(b, u, origin), dir: (f) => f,
|
|
text: async (url) => { const r = await ask(url, 'text/css,text/javascript,*/*;q=0.1'); return r && !r.binary ? r.body : null; },
|
|
data: async (url) => {
|
|
const r = await ask(url, '*/*');
|
|
if (!r) return null;
|
|
const type = r.type || mimeOf(url);
|
|
return r.binary ? `data:${type};base64,${r.body}` : `data:${type};charset=utf-8,${encodeURIComponent(r.body)}`;
|
|
},
|
|
};
|
|
}
|
|
|
|
async dataUrl(file, R = this.localContext()) {
|
|
if (this.images.has(file)) return this.images.get(file);
|
|
let data = null;
|
|
try { data = await R.data(file); } catch { data = null; }
|
|
this.images.set(file, data);
|
|
return data;
|
|
}
|
|
}
|
|
|
|
/** the data: URL of a file from base64 bytes */
|
|
export const dataUrlOf = (path, base64) => `data:${mimeOf(path)};base64,${base64}`;
|
|
|
|
/** UTF-8 text from base64 bytes */
|
|
export function textOfBase64(base64) {
|
|
const bin = atob(base64 || '');
|
|
const bytes = new Uint8Array(bin.length);
|
|
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
|
return new TextDecoder().decode(bytes);
|
|
}
|