rob-revisited/ide/ui/js/twig-preview.js

151 lines
6.6 KiB
JavaScript

// The preview of a Twig template (the editor's Preview of a .twig file): with "Layout + CSS" on, the page as Symfony would
// lay it out, without PHP: {% extends %} brings the parent's page with the child's blocks in it ({{ parent() }} too),
// {% include %} puts the other template inside, and the project's stylesheets are linked: asset('x.css') (AssetMapper's
// assets/ or public/), importmap('app') (assets/styles/app.css, what assets/app.js imports), encore_entry_link_tags('app')
// (public/build/app.css). Then, on or off, the tags are taken out ({{ x }} shown as x, {% %} and {# #} dropped): the page's
// look, not its data.
const MAX_DEPTH = 6;
/** {% block name %}...{% endblock %} at every level: name -> its body (nested blocks included in it) */
export function blocksOf(source) {
const out = {};
const re = /\{%-?\s*(block|endblock)\b\s*([\w]*)[^%]*-?%\}/g;
const stack = [];
let m;
while ((m = re.exec(source))) {
if (m[1] === 'block') {
// {% block title 'Text' %}: a short block, its body inline
const inline = /\{%-?\s*block\s+\w+\s+(['"])([\s\S]*?)\1\s*-?%\}/.exec(m[0]);
if (inline) { out[m[2]] = inline[2]; continue; }
stack.push({ name: m[2], start: m.index + m[0].length, open: m.index });
} else if (stack.length) {
const b = stack.pop();
out[b.name] = source.slice(b.start, m.index);
}
}
return out;
}
/** the parent's text with each block replaced by the child's one (the child's {{ parent() }} = the parent's body) */
export function fillBlocks(parent, childBlocks) {
const re = /\{%-?\s*block\s+(\w+)(\s+(['"])[\s\S]*?\3)?\s*-?%\}/g;
let out = '';
let at = 0;
let m;
while ((m = re.exec(parent))) {
const name = m[1];
let end = m.index + m[0].length;
let body = m[2] ? m[2].trim().slice(1, -1) : null;
if (body === null) {
// its {% endblock %}, nested blocks counted
const inner = /\{%-?\s*(block\s+\w+(?:\s+(['"])[\s\S]*?\2)?|endblock\b[^%]*)\s*-?%\}/g;
inner.lastIndex = end;
let depth = 1;
let n;
while (depth && (n = inner.exec(parent))) {
if (n[1].startsWith('endblock')) depth--;
else if (!n[2]) depth++;
if (!depth) { body = parent.slice(end, n.index); end = n.index + n[0].length; }
}
if (body === null) { body = parent.slice(end); end = parent.length; }
}
out += parent.slice(at, m.index);
const own = childBlocks[name];
const filledBody = fillBlocks(body, childBlocks);
out += own === undefined ? filledBody : fillBlocks(own.replace(/\{\{-?\s*parent\(\)\s*-?\}\}/g, () => filledBody), childBlocks);
at = end;
re.lastIndex = end;
}
return out + parent.slice(at);
}
/** where a template name points: templates/, beside the file, @Bundle/ */
function candidates(name, from) {
const dir = from.includes('/') ? from.slice(0, from.lastIndexOf('/')) : '';
if (name.startsWith('@')) return ['templates/' + name.replace(/^@[^/]+\//, ''), 'templates/bundles/' + name.slice(1)];
return ['templates/' + name, (dir ? dir + '/' : '') + name, name];
}
async function readTemplate(name, from, readText) {
for (const p of candidates(name, from)) {
const text = await readText(p).catch(() => null);
if (typeof text === 'string') return { path: p, text };
}
return null;
}
/** {% extends %} and {% include %} followed (depth limited), blocks merged: the whole page's Twig */
export async function composeTwig(path, source, readText, depth = 0) {
let text = source;
const ext = /\{%-?\s*extends\s+(['"])([^'"]+)\1\s*-?%\}/.exec(text);
if (ext && depth < MAX_DEPTH) {
const parent = await readTemplate(ext[2], path, readText);
if (parent) {
const parentText = await composeTwig(parent.path, parent.text, readText, depth + 1);
text = fillBlocks(parentText, blocksOf(text));
}
}
if (depth < MAX_DEPTH) {
const re = /\{%-?\s*include\s+(['"])([^'"]+)\1[^%]*-?%\}|\{\{-?\s*include\(\s*(['"])([^'"]+)\3[^}]*\}\}/g;
const parts = [];
let at = 0;
let m;
while ((m = re.exec(text))) {
const inc = await readTemplate(m[2] || m[4], path, readText);
parts.push(text.slice(at, m.index), inc ? await composeTwig(inc.path, inc.text, readText, depth + 1) : '');
at = m.index + m[0].length;
}
text = parts.join('') + text.slice(at);
}
return text;
}
/** a stylesheet of the project for an asset path, as an address from the root ('/assets/...', '/public/...'), or null */
async function cssLink(asset, readText) {
const clean = asset.replace(/^\/+/, '');
for (const p of ['assets/' + clean, 'public/' + clean]) {
if (typeof (await readText(p).catch(() => null)) === 'string') return '/' + p;
}
return null;
}
/** the project's stylesheets that Symfony's helpers would link, put as <link> where they are called */
export async function linkProjectCss(text, readText) {
let out = text;
for (const m of [...out.matchAll(/\{\{-?\s*asset\(\s*(['"])([^'"]+\.css)\1\s*\)\s*-?\}\}/g)]) {
const href = await cssLink(m[2], readText);
out = out.replace(m[0], href || m[2]);
}
const extra = [];
if (/\{\{-?\s*importmap\(/.test(out)) {
for (const p of ['assets/styles/app.css', 'assets/app.css']) {
if (typeof (await readText(p).catch(() => null)) === 'string') { extra.push('/' + p); break; }
}
}
for (const m of [...out.matchAll(/encore_entry_link_tags\(\s*(['"])([\w-]+)\1/g)]) {
const p = `public/build/${m[2]}.css`;
if (typeof (await readText(p).catch(() => null)) === 'string') extra.push('/' + p);
}
const links = extra.map((h) => `<link rel="stylesheet" href="${h}">`).join('');
if (!links) return out;
return /<\/head>/i.test(out) ? out.replace(/<\/head>/i, links + '</head>') : links + out;
}
/** Twig's tags out of the page: {{ x }} as x (its filters dropped), {% %} and {# #} dropped; a function's call ({{ importmap('app') }},
* {{ form(form) }}, {{ encore_entry_script_tags() }}) makes markup or a value the preview cannot know: dropped, path() / url() as "#" */
export function stripTwig(text) {
return text.replace(/\{#[\s\S]*?#\}/g, '').replace(/\{%[\s\S]*?%\}/g, '')
.replace(/\{\{-?\s*([\s\S]*?)\s*-?\}\}/g, (m, e) => {
const call = /^([A-Za-z_][\w.]*)\s*\(/.exec(e);
if (call) return /^(path|url|absolute_url|relative_path)$/.test(call[1]) ? '#' : '';
return e.replace(/\|.*$/, '');
});
}
/** The text the preview draws for a .twig file: laid out (extends, includes, the project's CSS) or alone. */
export async function twigPreviewText(path, source, readText, layout) {
if (!layout) return stripTwig(source);
const page = await composeTwig(path, source, readText);
return stripTwig(await linkProjectCss(page, readText));
}