289 lines
13 KiB
JavaScript
289 lines
13 KiB
JavaScript
// The Bootstrap editor's model (no DOM: node --test runs it): an offset-accurate reader of HTML + Twig (elements, attributes,
|
|
// the class attribute split in tokens) and the edits that change the code (one edit on one attribute, nothing else moves).
|
|
// Twig ({{ }}, {% %}, {# #}) is looked past when the tags are read, and kept as it is when a class attribute is rewritten.
|
|
|
|
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr', 'param']);
|
|
const RAW = new Set(['script', 'style', 'textarea', 'title']);
|
|
// elements a new <li> / <p>... closes when the previous one was not closed (the implied end tags that matter for nesting)
|
|
const CLOSES = { li: ['li'], dt: ['dt', 'dd'], dd: ['dt', 'dd'], tr: ['tr', 'td', 'th'], td: ['td', 'th'], th: ['td', 'th'], option: ['option'], p: ['p'], thead: ['tbody', 'tfoot'], tbody: ['thead', 'tbody', 'tfoot'] };
|
|
|
|
const TWIG = /\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}|\{#[\s\S]*?#\}/g;
|
|
|
|
/** the text with every Twig tag and HTML comment blanked (same length, same line breaks): what the tag scanner reads */
|
|
export function maskTwig(text) {
|
|
const blank = (m) => m.replace(/[^\n]/g, ' ');
|
|
return text.replace(TWIG, blank).replace(/<!--[\s\S]*?-->/g, blank);
|
|
}
|
|
|
|
/** a class attribute's value in tokens: whitespace separated, a Twig tag (spaces inside it included) is one token */
|
|
export function classTokens(raw) {
|
|
const tokens = [];
|
|
let i = 0;
|
|
while (i < raw.length) {
|
|
if (/\s/.test(raw[i])) { i++; continue; }
|
|
const start = i;
|
|
while (i < raw.length && !/\s/.test(raw[i])) {
|
|
const open = raw.startsWith('{{', i) ? '}}' : raw.startsWith('{%', i) ? '%}' : raw.startsWith('{#', i) ? '#}' : null;
|
|
if (open) { const close = raw.indexOf(open, i + 2); i = close < 0 ? raw.length : close + 2; } else i++;
|
|
}
|
|
const text = raw.slice(start, i);
|
|
tokens.push({ start, end: i, text, twig: /\{[{%#]/.test(text) });
|
|
}
|
|
return tokens;
|
|
}
|
|
|
|
/**
|
|
* Reads the markup: [{tag, start, end (end of the open tag), index, parent, children, depth, attrs: [{name, start, end, valueStart,
|
|
* valueEnd, value}], closeStart, closeEnd (the whole element), selfClosing, hasTwig}], in document order.
|
|
*/
|
|
export function parseMarkup(text) {
|
|
const masked = maskTwig(text);
|
|
const elements = [];
|
|
const stack = [];
|
|
const len = masked.length;
|
|
const re = /<(\/?)([A-Za-z][A-Za-z0-9:-]*)/g;
|
|
let m;
|
|
const closeTop = (to, end, unclosed = false) => { const e = stack.pop(); e.closeStart = to; e.closeEnd = end; if (unclosed) e.unclosed = true; };
|
|
while ((m = re.exec(masked))) {
|
|
const tag = m[2].toLowerCase();
|
|
const at = m.index;
|
|
if (m[1]) { // </tag>
|
|
const gt = masked.indexOf('>', at);
|
|
const end = gt < 0 ? len : gt + 1;
|
|
let k = stack.length - 1;
|
|
while (k >= 0 && stack[k].tag !== tag) k--;
|
|
if (k >= 0) { while (stack.length - 1 > k) closeTop(at, at, true); closeTop(at, end); }
|
|
re.lastIndex = end;
|
|
continue;
|
|
}
|
|
// the open tag: attributes up to its >
|
|
let i = at + m[0].length;
|
|
const attrs = [];
|
|
let selfClosing = false;
|
|
while (i < len) {
|
|
while (i < len && /\s/.test(masked[i])) i++;
|
|
if (i >= len) break;
|
|
if (masked[i] === '>') { i++; break; }
|
|
if (masked[i] === '/' && masked[i + 1] === '>') { selfClosing = true; i += 2; break; }
|
|
if (masked[i] === '/') { i++; continue; }
|
|
const ns = i;
|
|
while (i < len && !/[\s=>/]/.test(masked[i])) i++;
|
|
if (i === ns) { i++; continue; }
|
|
const name = masked.slice(ns, i);
|
|
let j = i;
|
|
while (j < len && /\s/.test(masked[j])) j++;
|
|
const attr = { name: name.toLowerCase(), start: ns, end: i, valueStart: -1, valueEnd: -1, value: null, quote: '' };
|
|
if (masked[j] === '=') {
|
|
j++;
|
|
while (j < len && /\s/.test(masked[j])) j++;
|
|
const q = masked[j];
|
|
if (q === '"' || q === "'") {
|
|
const close = masked.indexOf(q, j + 1);
|
|
const e = close < 0 ? len : close;
|
|
attr.valueStart = j + 1; attr.valueEnd = e; attr.quote = q;
|
|
i = close < 0 ? len : close + 1;
|
|
} else {
|
|
const vs = j;
|
|
while (j < len && !/[\s>]/.test(masked[j])) j++;
|
|
attr.valueStart = vs; attr.valueEnd = j; i = j;
|
|
}
|
|
attr.value = text.slice(attr.valueStart, attr.valueEnd);
|
|
attr.end = i;
|
|
}
|
|
attrs.push(attr);
|
|
}
|
|
const el = { tag, start: at, end: i, index: elements.length, parent: null, children: [], depth: 0, attrs, closeStart: -1, closeEnd: -1, unclosed: false,
|
|
selfClosing, hasTwig: /\{[{%]/.test(text.slice(at, i)) };
|
|
// implied end tags: a new <li> ends the open <li>
|
|
if (CLOSES[tag]) {
|
|
const top = stack[stack.length - 1];
|
|
if (top && CLOSES[tag].includes(top.tag)) closeTop(at, at);
|
|
}
|
|
el.parent = stack[stack.length - 1] || null;
|
|
el.depth = stack.length;
|
|
el.parent?.children.push(el);
|
|
elements.push(el);
|
|
if (VOID.has(tag) || selfClosing) { el.closeStart = el.closeEnd = i; }
|
|
else if (RAW.has(tag)) {
|
|
const close = new RegExp(`</${tag}\\s*>`, 'ig');
|
|
close.lastIndex = i;
|
|
const c = close.exec(masked);
|
|
el.closeStart = c ? c.index : len;
|
|
el.closeEnd = c ? c.index + c[0].length : len;
|
|
i = el.closeEnd;
|
|
} else stack.push(el);
|
|
re.lastIndex = i;
|
|
}
|
|
while (stack.length) closeTop(len, len, true);
|
|
return { elements, text };
|
|
}
|
|
|
|
/** the value of an attribute of an element ('' for an attribute without value, null when absent) */
|
|
export const attr = (el, name) => el.attrs.find((a) => a.name === name);
|
|
export const attrValue = (el, name) => { const a = attr(el, name); return a ? (a.value ?? '') : null; };
|
|
|
|
/** the element's classes: plain ones (a Twig tag is not a class) */
|
|
export function classesOf(el) {
|
|
const a = attr(el, 'class');
|
|
if (!a || a.value === null) return [];
|
|
return classTokens(a.value).filter((t) => !t.twig).map((t) => t.text);
|
|
}
|
|
export const hasTwigClass = (el) => { const a = attr(el, 'class'); return !!a && a.value !== null && classTokens(a.value).some((t) => t.twig); };
|
|
|
|
/** the innermost element that holds the offset (in its open tag, or between its tags) */
|
|
export function elementAt(model, offset) {
|
|
let best = null;
|
|
for (const el of model.elements) {
|
|
if (el.start > offset) break;
|
|
if (offset <= (el.closeEnd >= 0 ? el.closeEnd : el.end)) best = el; // later ones start later: the innermost wins
|
|
}
|
|
return best;
|
|
}
|
|
|
|
/** where a new element goes: before / after the element, at the start / end of its content */
|
|
export function insertionOffset(el, where) {
|
|
if (where === 'before') return el.start;
|
|
if (where === 'after') return el.closeEnd >= 0 ? el.closeEnd : el.end;
|
|
if (where === 'start') return el.end;
|
|
return el.closeStart >= 0 && el.closeStart >= el.end ? el.closeStart : el.end; // 'end' (inside, last)
|
|
}
|
|
|
|
/** the edits: [{start, end, text}] applied to text (from the last one, so offsets hold) */
|
|
export function applyEdits(text, edits) {
|
|
let out = text;
|
|
for (const e of [...edits].sort((a, b) => b.start - a.start || b.end - a.end)) out = out.slice(0, e.start) + e.text + out.slice(e.end);
|
|
return out;
|
|
}
|
|
|
|
const quoted = (value) => (value.includes('"') ? `'${value}'` : `"${value}"`);
|
|
|
|
/**
|
|
* The one edit that gives the element these classes. The class attribute's value only changes (a class attribute is added
|
|
* after the tag name when there is none, removed when no class is left and it was plain). Twig tags of the value stay where
|
|
* they were: a class removed leaves them alone, a class added goes at the end.
|
|
*/
|
|
export function setClasses(model, el, wanted) {
|
|
const a = attr(el, 'class');
|
|
const unique = [...new Set(wanted)];
|
|
if (!a || a.value === null) {
|
|
if (!unique.length) return null;
|
|
const at = el.start + 1 + el.tag.length;
|
|
return { start: at, end: at, text: ` class="${unique.join(' ')}"` };
|
|
}
|
|
const tokens = classTokens(a.value);
|
|
let parts;
|
|
if (!tokens.some((t) => t.twig)) {
|
|
// plain classes: the wanted list, in its order (a class replaced in place keeps its place)
|
|
if (tokens.map((t) => t.text).join(' ') === unique.join(' ')) return null;
|
|
parts = unique;
|
|
} else {
|
|
// Twig in the value: it stays where it was; what is still wanted keeps its place, what is new goes at the end
|
|
const keep = new Set(unique);
|
|
parts = [];
|
|
const seen = new Set();
|
|
for (const t of tokens) {
|
|
if (t.twig) parts.push(t.text);
|
|
else if (keep.has(t.text) && !seen.has(t.text)) { parts.push(t.text); seen.add(t.text); }
|
|
}
|
|
for (const c of unique) if (!seen.has(c)) { parts.push(c); seen.add(c); }
|
|
}
|
|
const value = parts.join(' ');
|
|
if (value === a.value) return null;
|
|
if (!value && !tokens.some((t) => t.twig)) return { start: a.start - (/\s/.test(model.text[a.start - 1] || '') ? 1 : 0), end: a.end, text: '' };
|
|
if (a.quote) return { start: a.valueStart, end: a.valueEnd, text: value };
|
|
return { start: a.start, end: a.end, text: `class=${quoted(value)}` };
|
|
}
|
|
|
|
/** adds / removes classes: setClasses over the current plain ones */
|
|
export function changeClasses(model, el, { add = [], remove = [] }) {
|
|
const drop = new Set(remove);
|
|
return setClasses(model, el, [...classesOf(el).filter((c) => !drop.has(c)), ...add]);
|
|
}
|
|
|
|
/** an attribute added or replaced (value null: removed): one edit */
|
|
export function setAttribute(model, el, name, value) {
|
|
const a = attr(el, name);
|
|
if (a) {
|
|
if (value === null) return { start: a.start - (/\s/.test(model.text[a.start - 1] || '') ? 1 : 0), end: a.end, text: '' };
|
|
if (a.value !== null && a.quote) return { start: a.valueStart, end: a.valueEnd, text: value };
|
|
return { start: a.start, end: a.end, text: `${name}=${quoted(value)}` };
|
|
}
|
|
if (value === null) return null;
|
|
const at = el.start + 1 + el.tag.length;
|
|
return { start: at, end: at, text: value === '' ? ` ${name}` : ` ${name}=${quoted(value)}` };
|
|
}
|
|
|
|
/** every id of the document (a Twig-built id is not one) */
|
|
export function idsOf(model) {
|
|
const ids = new Map();
|
|
for (const el of model.elements) {
|
|
const v = attrValue(el, 'id');
|
|
if (v && !/\{[{%]/.test(v)) (ids.get(v) || ids.set(v, []).get(v)).push(el);
|
|
}
|
|
return ids;
|
|
}
|
|
|
|
/** the line's indentation at an offset */
|
|
export function indentAt(text, offset) {
|
|
const from = text.lastIndexOf('\n', offset - 1) + 1;
|
|
return /^[ \t]*/.exec(text.slice(from, offset))[0];
|
|
}
|
|
|
|
/** snippet lines after the first get the target's indentation (the editor's own indent unit: spaces) */
|
|
export function indentSnippet(snippet, indent, unit = ' ') {
|
|
const lines = snippet.replace(/\n$/, '').split('\n');
|
|
return lines.map((l, i) => (i === 0 ? l : indent + (unit === ' ' ? l : l.replace(/^( {2})+/, (s) => unit.repeat(s.length / 2))))).join('\n');
|
|
}
|
|
|
|
/**
|
|
* The edit that inserts a snippet on its own lines: before / after an element (same indentation), or at the end of its
|
|
* content (one level deeper). Returns {start, end, text}.
|
|
*/
|
|
export function insertSnippet(model, el, where, snippet, unit = ' ') {
|
|
const text = model.text;
|
|
const lineStart = text.lastIndexOf('\n', el.start - 1) + 1;
|
|
const prefix = text.slice(lineStart, el.start);
|
|
const base = /^[ \t]*$/.test(prefix) ? prefix : indentAt(text, el.start);
|
|
if (where === 'before') {
|
|
if (/^[ \t]*$/.test(prefix)) return { start: lineStart, end: lineStart, text: base + indentSnippet(snippet, base, unit) + '\n' };
|
|
return { start: el.start, end: el.start, text: indentSnippet(snippet, base, unit) + '\n' + base };
|
|
}
|
|
const at = insertionOffset(el, where);
|
|
if (where === 'after') return { start: at, end: at, text: '\n' + base + indentSnippet(snippet, base, unit) };
|
|
// inside (start / end of the content): on lines of their own
|
|
const inner = base + unit;
|
|
const own = /^[ \t]*$/.test(text.slice(text.lastIndexOf('\n', at - 1) + 1, at)); // the closing tag is alone on its line
|
|
if (where === 'start') return { start: at, end: at, text: '\n' + inner + indentSnippet(snippet, inner, unit) };
|
|
return own ? { start: text.lastIndexOf('\n', at - 1) + 1, end: text.lastIndexOf('\n', at - 1) + 1, text: inner + indentSnippet(snippet, inner, unit) + '\n' }
|
|
: { start: at, end: at, text: '\n' + inner + indentSnippet(snippet, inner, unit) + '\n' + base };
|
|
}
|
|
|
|
/** a snippet at a cursor offset: the lines after the first take the line's indentation */
|
|
export function insertAtOffset(model, offset, snippet, unit = ' ') {
|
|
return { start: offset, end: offset, text: indentSnippet(snippet, indentAt(model.text, offset), unit) };
|
|
}
|
|
|
|
/** the tags of the template get a marker (data-jb="<offset of the tag>"): what a click in the preview gives back */
|
|
export function markElements(text, attrName = 'data-jb') {
|
|
const model = parseMarkup(text);
|
|
const edits = [];
|
|
for (const el of model.elements) {
|
|
if (['html', 'head', 'meta', 'title', 'link', 'script', 'style', 'base'].includes(el.tag)) continue;
|
|
const at = el.start + 1 + el.tag.length;
|
|
edits.push({ start: at, end: at, text: ` ${attrName}="${el.start}"` });
|
|
}
|
|
return applyEdits(text, edits);
|
|
}
|
|
|
|
/** the path of the element in the document (indexes of its ancestors): it finds the same element again after an edit */
|
|
export function pathOf(el) {
|
|
const path = [];
|
|
for (let n = el; n; n = n.parent) path.unshift(n.parent ? n.parent.children.indexOf(n) : n.index);
|
|
return path;
|
|
}
|
|
export function elementByPath(model, path) {
|
|
if (!path?.length) return null;
|
|
let el = model.elements.filter((e) => !e.parent)[path[0]];
|
|
for (const i of path.slice(1)) el = el?.children[i];
|
|
return el || null;
|
|
}
|