816 lines
40 KiB
JavaScript
816 lines
40 KiB
JavaScript
// The CSS / SCSS model of the visual stylesheet editor (css-designer.js) and of the colour swatches (css-colors.js): a
|
||
// tolerant parser that keeps the exact positions of every rule, at-rule and declaration, and the edits that change one
|
||
// declaration (or move / copy / delete one rule) as a single text edit, so the text stays the source of truth: nothing
|
||
// is ever reformatted. No DOM here: tested with node (css-model.test.mjs).
|
||
|
||
// parsing ------------------------------------------------------------------------------------------------------------
|
||
|
||
/**
|
||
* The stylesheet as a tree. Nodes:
|
||
* comment {type, start, end}
|
||
* decl {type, prop, value, important, start, end, propStart, propEnd, valueStart, valueEnd, semicolon}
|
||
* (valueStart..valueEnd: the value with its !important; prop "--x" custom property, "$x" SCSS variable)
|
||
* rule {type, selector, start, end, open, close, preludeEnd, children}
|
||
* atrule {type, name, params, start, end, preludeEnd, open?, close?, children?} (open: with a block)
|
||
* raw {type, start, end} text that is neither (an error is noted)
|
||
* Every node has `parent` (null at the top). errors: [{offset, message}].
|
||
* @param {string} text
|
||
* @param {{scss?: boolean}} options scss: // comments, #{} interpolation, nesting
|
||
*/
|
||
export function parseStylesheet(text, { scss = false } = {}) {
|
||
const errors = [];
|
||
const root = { type: 'root', start: 0, end: text.length, children: [], parent: null };
|
||
parseBlock(text, 0, text.length, root, scss, errors);
|
||
return { root, errors, text, scss };
|
||
}
|
||
|
||
function parseBlock(text, from, to, parent, scss, errors) {
|
||
let i = from;
|
||
while (i < to) {
|
||
const c = text[i];
|
||
if (/\s/.test(c)) { i++; continue; }
|
||
if (c === '/' && text[i + 1] === '*') {
|
||
const end = text.indexOf('*/', i + 2);
|
||
if (end < 0 || end + 2 > to) errors.push({ offset: i, message: 'Unclosed comment' });
|
||
const stop = end < 0 ? to : Math.min(to, end + 2);
|
||
parent.children.push({ type: 'comment', start: i, end: stop, parent });
|
||
i = stop;
|
||
continue;
|
||
}
|
||
if (scss && c === '/' && text[i + 1] === '/') {
|
||
let end = text.indexOf('\n', i);
|
||
if (end < 0 || end > to) end = to;
|
||
parent.children.push({ type: 'comment', start: i, end, parent });
|
||
i = end;
|
||
continue;
|
||
}
|
||
if (c === '}') {
|
||
errors.push({ offset: i, message: 'Unexpected }' });
|
||
i++;
|
||
continue;
|
||
}
|
||
if (c === ';') { i++; continue; }
|
||
const stop = scanStatement(text, i, to, scss, errors);
|
||
const prelude = text.slice(i, stop.at);
|
||
if (stop.char === '{') {
|
||
const close = matchBrace(text, stop.at, to, scss);
|
||
if (close < 0) errors.push({ offset: stop.at, message: 'Missing }' });
|
||
const closeAt = close < 0 ? to : close;
|
||
const trimmed = prelude.replace(/\s+$/, '');
|
||
const node = { start: i, end: close < 0 ? to : close + 1, preludeEnd: i + trimmed.length, open: stop.at, close: closeAt, children: [], parent };
|
||
if (trimmed.startsWith('@')) {
|
||
const m = /^@([\w-]+)\s*([\s\S]*)$/.exec(trimmed);
|
||
Object.assign(node, { type: 'atrule', name: (m?.[1] || '').toLowerCase(), params: clean(m?.[2] || '') });
|
||
} else if (/^--[\w-]*\s*:/.test(trimmed)) {
|
||
// a custom property whose value is a block ({...}): a declaration
|
||
parent.children.push(declaration(text, i, close < 0 ? to : close + 1, false, parent));
|
||
i = close < 0 ? to : close + 1;
|
||
continue;
|
||
} else {
|
||
Object.assign(node, { type: 'rule', selector: clean(stripComments(trimmed, scss)) });
|
||
}
|
||
parent.children.push(node);
|
||
parseBlock(text, stop.at + 1, closeAt, node, scss, errors);
|
||
i = node.end;
|
||
continue;
|
||
}
|
||
// a statement: up to its ';' (included), or the end of the block
|
||
const end = stop.char === ';' ? stop.at + 1 : stop.at;
|
||
const body = text.slice(i, stop.at).replace(/\s+$/, '');
|
||
if (body.startsWith('@')) {
|
||
const m = /^@([\w-]+)\s*([\s\S]*)$/.exec(body);
|
||
parent.children.push({ type: 'atrule', name: (m?.[1] || '').toLowerCase(), params: clean(m?.[2] || ''), start: i, end, preludeEnd: i + body.length, parent });
|
||
} else if (/^(\$|--)?[\w-]+(\.[\w-]+)?\s*:/.test(body) || (scss && /^#\{/.test(body) && body.includes(':'))) {
|
||
const node = declaration(text, i, end, stop.char === ';', parent);
|
||
if (parent.type === 'root' && !scss && !node.prop.startsWith('$')) errors.push({ offset: i, message: 'A declaration outside a rule' });
|
||
parent.children.push(node);
|
||
} else {
|
||
errors.push({ offset: i, message: body.includes(':') ? 'Unexpected text' : 'Expected a declaration (property: value)' });
|
||
parent.children.push({ type: 'raw', start: i, end, parent });
|
||
}
|
||
i = end;
|
||
}
|
||
}
|
||
|
||
/** where a statement started at `from` stops: {at, char} with char '{', ';' or '' (end of the block) */
|
||
function scanStatement(text, from, to, scss, errors) {
|
||
let parens = 0;
|
||
for (let i = from; i < to; i++) {
|
||
const c = text[i];
|
||
if (c === '"' || c === "'") {
|
||
const end = skipString(text, i, to);
|
||
if (end < 0) { errors.push({ offset: i, message: 'Unclosed string' }); return { at: to, char: '' }; }
|
||
i = end;
|
||
} else if (c === '/' && text[i + 1] === '*') {
|
||
const end = text.indexOf('*/', i + 2);
|
||
if (end < 0) return { at: to, char: '' };
|
||
i = end + 1;
|
||
} else if (scss && c === '/' && text[i + 1] === '/' && parens === 0 && text[i - 1] !== ':') {
|
||
const end = text.indexOf('\n', i);
|
||
if (end < 0 || end > to) return { at: to, char: '' };
|
||
i = end;
|
||
} else if (scss && c === '#' && text[i + 1] === '{') {
|
||
const close = matchBrace(text, i + 1, to, scss);
|
||
if (close < 0) return { at: to, char: '' };
|
||
i = close;
|
||
} else if (c === '(' || c === '[') parens++;
|
||
else if (c === ')' || c === ']') parens = Math.max(0, parens - 1);
|
||
else if (parens === 0 && (c === '{' || c === ';')) return { at: i, char: c };
|
||
else if (c === '}') return { at: i, char: '' };
|
||
}
|
||
return { at: to, char: '' };
|
||
}
|
||
|
||
/** the end of a string started at `i` (its closing quote), -1 when it is not closed on its line */
|
||
function skipString(text, i, to) {
|
||
const q = text[i];
|
||
for (let j = i + 1; j < to; j++) {
|
||
if (text[j] === '\\') { j++; continue; }
|
||
if (text[j] === q) return j;
|
||
if (text[j] === '\n') return -1;
|
||
}
|
||
return -1;
|
||
}
|
||
|
||
/** the "}" that closes the "{" at `open`, -1 when there is none before `to` */
|
||
export function matchBrace(text, open, to = text.length, scss = false) {
|
||
let depth = 0;
|
||
for (let i = open; i < to; i++) {
|
||
const c = text[i];
|
||
if (c === '/' && text[i + 1] === '*') {
|
||
const end = text.indexOf('*/', i + 2);
|
||
if (end < 0) return -1;
|
||
i = end + 1;
|
||
} else if (scss && c === '/' && text[i + 1] === '/' && text[i - 1] !== ':') {
|
||
const end = text.indexOf('\n', i);
|
||
if (end < 0) return -1;
|
||
i = end;
|
||
} else if (c === '"' || c === "'") {
|
||
const end = skipString(text, i, to);
|
||
if (end < 0) continue;
|
||
i = end;
|
||
} else if (c === '{') depth++;
|
||
else if (c === '}') { depth--; if (depth === 0) return i; }
|
||
}
|
||
return -1;
|
||
}
|
||
|
||
function declaration(text, start, end, semicolon, parent) {
|
||
const stop = semicolon ? end - 1 : end;
|
||
const colon = text.indexOf(':', start);
|
||
const propEnd = start + text.slice(start, colon).replace(/\s+$/, '').length;
|
||
let valueStart = colon + 1;
|
||
while (valueStart < stop && /\s/.test(text[valueStart])) valueStart++;
|
||
let valueEnd = stop;
|
||
while (valueEnd > valueStart && /\s/.test(text[valueEnd - 1])) valueEnd--;
|
||
const raw = text.slice(valueStart, valueEnd);
|
||
const imp = /\s*!\s*important\s*$/i.exec(raw);
|
||
return {
|
||
type: 'decl', prop: text.slice(start, propEnd), value: imp ? raw.slice(0, imp.index) : raw, important: !!imp,
|
||
start, end: semicolon ? end : valueEnd, propStart: start, propEnd, valueStart, valueEnd, semicolon, parent,
|
||
};
|
||
}
|
||
|
||
const clean = (s) => s.replace(/\s+/g, ' ').trim();
|
||
const stripComments = (s, scss) => (scss ? s.replace(/\/\/[^\n]*/g, '') : s).replace(/\/\*[\s\S]*?\*\//g, '');
|
||
|
||
// reading the tree ---------------------------------------------------------------------------------------------------
|
||
|
||
/** every node of the tree, depth first, in source order */
|
||
export function* walk(node) {
|
||
for (const child of node.children || []) {
|
||
yield child;
|
||
if (child.children) yield* walk(child);
|
||
}
|
||
}
|
||
|
||
/** the blocks of the tree (rules and at-rules, with or without a block), for the rules panel: [{node, depth}] */
|
||
export function outline(model) {
|
||
const out = [];
|
||
const visit = (node, depth) => {
|
||
for (const child of node.children) {
|
||
if (child.type === 'rule' || child.type === 'atrule') {
|
||
out.push({ node: child, depth });
|
||
if (child.children) visit(child, depth + 1);
|
||
}
|
||
}
|
||
};
|
||
visit(model.root, 0);
|
||
return out;
|
||
}
|
||
|
||
/** the direct declarations of a block */
|
||
export const declarations = (block) => (block.children || []).filter((n) => n.type === 'decl');
|
||
|
||
/** the last declaration of a property in a block (the one that applies), or null */
|
||
export function declarationOf(block, prop) {
|
||
const p = prop.toLowerCase();
|
||
const list = declarations(block).filter((d) => (d.prop.startsWith('--') ? d.prop === prop : d.prop.toLowerCase() === p));
|
||
return list[list.length - 1] || null;
|
||
}
|
||
|
||
/** the path of a node: its index among its parent's children, up to the top (a node found again after a new parse) */
|
||
export function pathOf(node) {
|
||
const path = [];
|
||
for (let n = node; n.parent; n = n.parent) path.unshift(n.parent.children.indexOf(n));
|
||
return path;
|
||
}
|
||
|
||
/** the node at a path in a new parse, or, when the text moved, the block with the same label nearest to it */
|
||
export function findByPath(model, path, label = null) {
|
||
let node = model.root;
|
||
for (const index of path) {
|
||
node = node?.children?.[index];
|
||
if (!node) break;
|
||
}
|
||
if (node && node !== model.root && (!label || labelOf(node) === label)) return node;
|
||
if (!label) return node && node !== model.root ? node : null;
|
||
return outline(model).map((o) => o.node).find((n) => labelOf(n) === label) || null;
|
||
}
|
||
|
||
/** the block holding a text offset (the innermost), or null */
|
||
export function blockAt(model, offset) {
|
||
let found = null;
|
||
for (const { node } of outline(model)) if (node.start <= offset && offset <= node.end && (!found || node.start >= found.start)) found = node;
|
||
return found;
|
||
}
|
||
|
||
/** what the rules panel shows for a block: its selector, or "@media (...)" */
|
||
export const labelOf = (node) => (node.type === 'rule' ? node.selector : node.type === 'atrule' ? `@${node.name}${node.params ? ' ' + node.params : ''}` : node.type === 'decl' ? node.prop : '');
|
||
|
||
/** the at-rules around a block ("@media (max-width: 600px)", ...), outermost first */
|
||
export function contextOf(node) {
|
||
const out = [];
|
||
for (let n = node.parent; n && n.type !== 'root'; n = n.parent) if (n.type === 'atrule') out.unshift(labelOf(n));
|
||
return out;
|
||
}
|
||
|
||
/** a selector list split at its top-level commas */
|
||
export function splitList(selector) {
|
||
const out = [];
|
||
let depth = 0;
|
||
let from = 0;
|
||
for (let i = 0; i < selector.length; i++) {
|
||
const c = selector[i];
|
||
if (c === '(' || c === '[') depth++;
|
||
else if (c === ')' || c === ']') depth--;
|
||
else if (c === '"' || c === "'") { const e = skipString(selector, i, selector.length); if (e > 0) i = e; }
|
||
else if (c === ',' && depth === 0) { out.push(selector.slice(from, i).trim()); from = i + 1; }
|
||
}
|
||
out.push(selector.slice(from).trim());
|
||
return out.filter(Boolean);
|
||
}
|
||
|
||
/**
|
||
* The full selector of a rule, SCSS nesting resolved ("&" = the parent, else "parent child"): ".card .title, .card:hover";
|
||
* the rules of @keyframes give null (frames, not selectors).
|
||
*/
|
||
export function resolvedSelector(rule) {
|
||
if (rule.type !== 'rule') return null;
|
||
for (let n = rule.parent; n && n.type !== 'root'; n = n.parent) if (n.type === 'atrule' && /keyframes$/.test(n.name)) return null;
|
||
let parents = null;
|
||
for (let n = rule.parent; n && n.type !== 'root'; n = n.parent) {
|
||
if (n.type === 'atrule' && n.name === 'at-root') break;
|
||
if (n.type === 'rule') { parents = splitList(resolvedSelector(n) || ''); break; }
|
||
}
|
||
const own = splitList(rule.selector);
|
||
if (!parents || !parents.length) return own.map((s) => s.replace(/&/g, ':root')).join(', ');
|
||
const out = [];
|
||
for (const p of parents) for (const s of own) out.push(s.includes('&') ? s.replace(/&/g, p) : `${p} ${s}`);
|
||
return out.join(', ');
|
||
}
|
||
|
||
/** a selector without what an element cannot match by itself (pseudo-states, pseudo-elements): for highlighting */
|
||
export function matchableSelector(selector) {
|
||
return splitList(selector).map((s) => s
|
||
.replace(/::?(before|after|first-line|first-letter|marker|placeholder|selection|backdrop|file-selector-button|-webkit-[\w-]+|-moz-[\w-]+)(\([^)]*\))?/gi, '')
|
||
.replace(/:(hover|focus|focus-visible|focus-within|active|visited|target|checked|disabled|enabled|invalid|valid|placeholder-shown|autofill|open)\b/gi, '')
|
||
.trim()).filter((s) => s && !s.includes('%') && !s.includes('#{')).map((s) => (/[>+~]$/.test(s) ? s + ' *' : s)).join(', ');
|
||
}
|
||
|
||
/** [ids, classes / attributes / pseudo-classes, types / pseudo-elements] of ONE complex selector */
|
||
export function specificity(selector) {
|
||
let a = 0, b = 0, c = 0;
|
||
const s = selector;
|
||
const ident = (i) => { while (i < s.length && /[\w\-\\ -]/.test(s[i])) i += s[i] === '\\' ? 2 : 1; return i; };
|
||
const parens = (i) => { let d = 0; for (let j = i; j < s.length; j++) { if (s[j] === '(') d++; else if (s[j] === ')' && --d === 0) return j; } return s.length - 1; };
|
||
let i = 0;
|
||
while (i < s.length) {
|
||
const ch = s[i];
|
||
if (ch === '#') { a++; i = ident(i + 1); }
|
||
else if (ch === '.') { b++; i = ident(i + 1); }
|
||
else if (ch === '[') { b++; const e = s.indexOf(']', i); i = e < 0 ? s.length : e + 1; }
|
||
else if (ch === ':') {
|
||
if (s[i + 1] === ':') { c++; i = ident(i + 2); if (s[i] === '(') i = parens(i) + 1; continue; }
|
||
const end = ident(i + 1);
|
||
const name = s.slice(i + 1, end).toLowerCase();
|
||
i = end;
|
||
let args = null;
|
||
if (s[i] === '(') { const close = parens(i); args = s.slice(i + 1, close); i = close + 1; }
|
||
if (['before', 'after', 'first-line', 'first-letter'].includes(name)) c++;
|
||
else if (name === 'where') { /* nothing */ }
|
||
else if (['is', 'not', 'has', 'matches', '-webkit-any', '-moz-any'].includes(name) && args !== null) {
|
||
const best = splitList(args).map(specificity).sort(compareSpecificity).pop() || [0, 0, 0];
|
||
a += best[0]; b += best[1]; c += best[2];
|
||
} else if (/^nth-(last-)?child$/.test(name) && args && / of /i.test(args)) {
|
||
b++;
|
||
const best = splitList(args.split(/ of /i)[1]).map(specificity).sort(compareSpecificity).pop() || [0, 0, 0];
|
||
a += best[0]; b += best[1]; c += best[2];
|
||
} else b++;
|
||
} else if (/[a-zA-Z_ -]/.test(ch) || (ch === '-' && /[a-zA-Z_-]/.test(s[i + 1] || ''))) { c++; i = ident(i); }
|
||
else if (ch === '"' || ch === "'") { const e = skipString(s, i, s.length); i = e < 0 ? s.length : e + 1; }
|
||
else i++;
|
||
}
|
||
return [a, b, c];
|
||
}
|
||
|
||
export const compareSpecificity = (x, y) => x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
|
||
|
||
/** the highest specificity of a selector list */
|
||
export const maxSpecificity = (selector) => splitList(selector).map(specificity).sort(compareSpecificity).pop() || [0, 0, 0];
|
||
|
||
/** variables: custom properties (--x) and SCSS variables ($x) of the text -> their last value */
|
||
export function variablesOf(model) {
|
||
const vars = new Map();
|
||
for (const node of walk(model.root)) if (node.type === 'decl' && (node.prop.startsWith('--') || node.prop.startsWith('$'))) vars.set(node.prop, node.value.replace(/\s*!(default|global)\s*/g, '').trim());
|
||
return vars;
|
||
}
|
||
|
||
/** a line / column (1-based) of an offset */
|
||
export function lineCol(text, offset) {
|
||
let line = 1, last = -1;
|
||
for (let i = 0; i < offset && i < text.length; i++) if (text[i] === '\n') { line++; last = i; }
|
||
return { line, col: offset - last };
|
||
}
|
||
|
||
// edits: each one {start, end, text}: replace text.slice(start, end) by text --------------------------------------
|
||
|
||
/** the indentation of the line an offset is on */
|
||
export function indentAt(text, offset) {
|
||
const lineStart = text.lastIndexOf('\n', offset - 1) + 1;
|
||
return /^[ \t]*/.exec(text.slice(lineStart))[0];
|
||
}
|
||
|
||
/** the indent unit of a text: a tab, or its smallest indentation in spaces (2 by default) */
|
||
export function indentUnit(text) {
|
||
if (/^\t/m.test(text)) return '\t';
|
||
let best = 0;
|
||
for (const m of text.matchAll(/^( +)\S/gm)) if (!best || m[1].length < best) best = m[1].length;
|
||
return ' '.repeat(best || 2);
|
||
}
|
||
|
||
/** the indentation of the declarations of a block: that of its first one, else its own + one unit */
|
||
export function bodyIndent(text, block) {
|
||
const first = declarations(block)[0] || (block.children || []).find((n) => n.type !== 'comment');
|
||
if (first && text.slice(block.open, first.start).includes('\n')) return indentAt(text, first.start);
|
||
return (block.type === 'root' ? '' : indentAt(text, block.start)) + indentUnit(text);
|
||
}
|
||
|
||
/**
|
||
* The edit that sets a declaration of a block: its value replaced (formatting and comments around kept), or a new line
|
||
* after the last declaration, or (value null) the declaration removed. important: true / false, or undefined = as it is.
|
||
*/
|
||
export function setDeclaration(text, block, prop, value, important) {
|
||
const decl = declarationOf(block, prop);
|
||
if (value === null || value === undefined) return decl ? removeNode(text, decl) : null;
|
||
const imp = important === undefined ? !!decl?.important : important;
|
||
const full = String(value).trim() + (imp ? ' !important' : '');
|
||
if (decl) return { start: decl.valueStart, end: decl.valueEnd, text: full };
|
||
return insertDeclaration(text, block, `${prop}: ${full};`);
|
||
}
|
||
|
||
/** a new declaration line ("prop: value;") at the end of the block's declarations */
|
||
export function insertDeclaration(text, block, line) {
|
||
const decls = declarations(block);
|
||
const last = decls[decls.length - 1];
|
||
const inline = !text.slice(block.open, block.close).includes('\n');
|
||
if (inline) {
|
||
if (last) return { start: last.end, end: last.end, text: (last.semicolon ? '' : ';') + ' ' + line };
|
||
const pad = /\s/.test(text[block.close - 1]) ? '' : ' ';
|
||
return { start: block.open + 1, end: block.open + 1, text: ' ' + line + pad };
|
||
}
|
||
const indent = bodyIndent(text, block);
|
||
if (last) return { start: last.end, end: last.end, text: (last.semicolon ? '' : ';') + '\n' + indent + line };
|
||
return { start: block.open + 1, end: block.open + 1, text: '\n' + indent + line };
|
||
}
|
||
|
||
/** renames the property of a declaration */
|
||
export const renameDeclaration = (decl, prop) => ({ start: decl.propStart, end: decl.propEnd, text: prop.trim() });
|
||
|
||
/** a node removed with its line when it is alone on it (and one blank line around it at most) */
|
||
export function removeNode(text, node) {
|
||
let start = node.start;
|
||
let end = node.end;
|
||
const lineStart = text.lastIndexOf('\n', start - 1) + 1;
|
||
let lineEnd = text.indexOf('\n', end);
|
||
if (lineEnd < 0) lineEnd = text.length;
|
||
const before = text.slice(lineStart, start);
|
||
const after = text.slice(end, lineEnd);
|
||
if (/^\s*$/.test(before) && /^\s*$/.test(after)) {
|
||
start = lineStart;
|
||
end = Math.min(text.length, lineEnd + 1);
|
||
// two blank lines left around it: one goes
|
||
if (/\n[ \t]*\n[ \t]*$/.test(text.slice(0, start)) && /^[ \t]*\n/.test(text.slice(end))) end = text.indexOf('\n', end) + 1;
|
||
} else {
|
||
while (end < text.length && (text[end] === ' ' || text[end] === '\t')) end++;
|
||
}
|
||
return { start, end, text: '' };
|
||
}
|
||
|
||
/** a copy of a block, just after it (a blank line between them when the file has some) */
|
||
export function duplicateNode(text, node) {
|
||
const indent = indentAt(text, node.start);
|
||
const sep = /\n[ \t]*\n/.test(text.slice(Math.max(0, node.start - 400), node.start)) ? '\n\n' : '\n';
|
||
return { start: node.end, end: node.end, text: sep + indent + text.slice(node.start, node.end) };
|
||
}
|
||
|
||
/** a new empty rule, after a node (or at the end of a block / the file) */
|
||
export function insertRule(text, selector, after = null, parent = null) {
|
||
const unit = indentUnit(text);
|
||
if (after) {
|
||
const indent = indentAt(text, after.start);
|
||
return { start: after.end, end: after.end, text: `\n\n${indent}${selector} {\n${indent}${unit}\n${indent}}` };
|
||
}
|
||
if (parent && parent.type !== 'root') {
|
||
const indent = bodyIndent(text, parent);
|
||
const close = text.lastIndexOf('\n', parent.close - 1) >= parent.open ? text.lastIndexOf('\n', parent.close - 1) : parent.close;
|
||
return { start: close, end: close, text: `\n\n${indent}${selector} {\n${indent}${unit}\n${indent}}` };
|
||
}
|
||
const trimmed = text.replace(/\s+$/, '');
|
||
return { start: trimmed.length, end: text.length, text: `${trimmed ? '\n\n' : ''}${selector} {\n${unit}\n}\n` };
|
||
}
|
||
|
||
/** the selector (or at-rule prelude) of a block replaced */
|
||
export function setSelector(node, selector) {
|
||
return { start: node.start, end: node.preludeEnd, text: node.type === 'atrule' && !selector.startsWith('@') ? `@${node.name} ${selector}` : selector.trim() };
|
||
}
|
||
|
||
/** a block swapped with its previous (-1) or next (+1) sibling block (comments stay where they are) */
|
||
export function moveNode(text, node, direction) {
|
||
const siblings = node.parent.children.filter((n) => n.type === 'rule' || n.type === 'atrule' || n.type === 'decl');
|
||
const index = siblings.indexOf(node);
|
||
const other = siblings[index + direction];
|
||
if (!other) return null;
|
||
const [a, b] = direction < 0 ? [other, node] : [node, other];
|
||
return { start: a.start, end: b.end, text: text.slice(b.start, b.end) + text.slice(a.end, b.start) + text.slice(a.start, a.end) };
|
||
}
|
||
|
||
/** an edit applied to a text */
|
||
export const applyEdit = (text, edit) => (edit ? text.slice(0, edit.start) + edit.text + text.slice(edit.end) : text);
|
||
|
||
// values -------------------------------------------------------------------------------------------------------------
|
||
|
||
/** a value split at its top-level spaces (and commas kept as their own tokens when asked) */
|
||
export function splitValue(value, commas = false) {
|
||
const out = [];
|
||
let depth = 0, cur = '';
|
||
for (const ch of String(value)) {
|
||
if (ch === '(') depth++;
|
||
if (ch === ')') depth--;
|
||
if (depth === 0 && /\s/.test(ch)) { if (cur) out.push(cur); cur = ''; continue; }
|
||
if (depth === 0 && ch === ',' && commas) { if (cur) out.push(cur); out.push(','); cur = ''; continue; }
|
||
cur += ch;
|
||
}
|
||
if (cur) out.push(cur);
|
||
return out;
|
||
}
|
||
|
||
/** a value split at its top-level commas */
|
||
export function splitCommas(value) { return splitList(String(value)); }
|
||
|
||
/** "12.5px" -> {number: 12.5, unit: 'px'}, null when it is not a number */
|
||
export function parseNumber(value) {
|
||
const m = /^(-?(?:\d+\.?\d*|\.\d+))([a-z%]*)$/i.exec(String(value).trim());
|
||
return m ? { number: parseFloat(m[1]), unit: m[2] } : null;
|
||
}
|
||
|
||
/** a number written back short: 12, 1.25, 0.5 */
|
||
export const formatNumber = (n) => String(Math.round(n * 1000) / 1000);
|
||
|
||
/** margin / padding / inset / border-width shorthand -> its four sides [top, right, bottom, left] */
|
||
export function expandBox(value) {
|
||
const v = splitValue(value);
|
||
if (!v.length) return ['', '', '', ''];
|
||
const [t, r = t, b = t, l = r] = v;
|
||
return [t, r, b, l];
|
||
}
|
||
|
||
/** four sides -> the shortest shorthand */
|
||
export function compactBox([t, r, b, l]) {
|
||
if (l === r) {
|
||
if (b === t) return r === t ? t : `${t} ${r}`;
|
||
return `${t} ${r} ${b}`;
|
||
}
|
||
return `${t} ${r} ${b} ${l}`;
|
||
}
|
||
|
||
/** box-shadow / text-shadow -> [{inset, x, y, blur, spread, color}] */
|
||
export function parseShadows(value) {
|
||
if (!value || /^none$/i.test(value.trim())) return [];
|
||
return splitCommas(value).map((one) => {
|
||
const s = { inset: false, x: '0', y: '0', blur: '', spread: '', color: '' };
|
||
const lengths = [];
|
||
for (const tok of splitValue(one)) {
|
||
if (/^inset$/i.test(tok)) s.inset = true;
|
||
else if (parseNumber(tok) || /^(calc|var|min|max|clamp)\(/i.test(tok) && !isColorLike(tok)) lengths.push(tok);
|
||
else s.color = s.color ? s.color + ' ' + tok : tok;
|
||
}
|
||
[s.x = '0', s.y = '0', s.blur = '', s.spread = ''] = lengths;
|
||
return s;
|
||
});
|
||
}
|
||
|
||
const isColorLike = (tok) => parseColor(tok) !== null || /^var\(--[\w-]*(col|bg|fg|shadow)/i.test(tok);
|
||
|
||
export function formatShadows(list, text = false) {
|
||
if (!list.length) return 'none';
|
||
return list.map((s) => [s.inset && !text ? 'inset' : '', s.x || '0', s.y || '0', s.blur, text ? '' : s.spread, s.color].filter((x) => x !== '' && x !== undefined).join(' ')).join(', ');
|
||
}
|
||
|
||
/** linear-gradient(...) / radial-gradient(...) -> {type, repeating, head (angle, shape...), stops: [{color, pos}]}, null otherwise */
|
||
export function parseGradient(value) {
|
||
const m = /^\s*(repeating-)?(linear|radial|conic)-gradient\(([\s\S]*)\)\s*$/i.exec(value || '');
|
||
if (!m) return null;
|
||
const parts = splitCommas(m[3]);
|
||
let head = '';
|
||
if (parts.length && !startsWithColor(parts[0])) head = parts.shift();
|
||
const stops = parts.map((p) => {
|
||
const toks = splitValue(p);
|
||
const colorToks = [];
|
||
const pos = [];
|
||
for (const tok of toks) (parseNumber(tok) && !parseColor(tok) ? pos : colorToks).push(tok);
|
||
return { color: colorToks.join(' '), pos: pos.join(' ') };
|
||
});
|
||
return { type: m[2].toLowerCase(), repeating: !!m[1], head, stops };
|
||
}
|
||
|
||
const startsWithColor = (part) => { const first = splitValue(part)[0] || ''; return parseColor(first) !== null || /^(var\(|\$)/.test(first); };
|
||
|
||
export function formatGradient(g) {
|
||
const stops = g.stops.map((s) => [s.color, s.pos].filter(Boolean).join(' '));
|
||
return `${g.repeating ? 'repeating-' : ''}${g.type}-gradient(${[g.head, ...stops].filter(Boolean).join(', ')})`;
|
||
}
|
||
|
||
// colours ------------------------------------------------------------------------------------------------------------
|
||
|
||
export const NAMED_COLORS = {
|
||
aliceblue: 'f0f8ff', antiquewhite: 'faebd7', aqua: '00ffff', aquamarine: '7fffd4', azure: 'f0ffff', beige: 'f5f5dc', bisque: 'ffe4c4', black: '000000',
|
||
blanchedalmond: 'ffebcd', blue: '0000ff', blueviolet: '8a2be2', brown: 'a52a2a', burlywood: 'deb887', cadetblue: '5f9ea0', chartreuse: '7fff00',
|
||
chocolate: 'd2691e', coral: 'ff7f50', cornflowerblue: '6495ed', cornsilk: 'fff8dc', crimson: 'dc143c', cyan: '00ffff', darkblue: '00008b',
|
||
darkcyan: '008b8b', darkgoldenrod: 'b8860b', darkgray: 'a9a9a9', darkgreen: '006400', darkgrey: 'a9a9a9', darkkhaki: 'bdb76b', darkmagenta: '8b008b',
|
||
darkolivegreen: '556b2f', darkorange: 'ff8c00', darkorchid: '9932cc', darkred: '8b0000', darksalmon: 'e9967a', darkseagreen: '8fbc8f',
|
||
darkslateblue: '483d8b', darkslategray: '2f4f4f', darkslategrey: '2f4f4f', darkturquoise: '00ced1', darkviolet: '9400d3', deeppink: 'ff1493',
|
||
deepskyblue: '00bfff', dimgray: '696969', dimgrey: '696969', dodgerblue: '1e90ff', firebrick: 'b22222', floralwhite: 'fffaf0', forestgreen: '228b22',
|
||
fuchsia: 'ff00ff', gainsboro: 'dcdcdc', ghostwhite: 'f8f8ff', gold: 'ffd700', goldenrod: 'daa520', gray: '808080', green: '008000',
|
||
greenyellow: 'adff2f', grey: '808080', honeydew: 'f0fff0', hotpink: 'ff69b4', indianred: 'cd5c5c', indigo: '4b0082', ivory: 'fffff0', khaki: 'f0e68c',
|
||
lavender: 'e6e6fa', lavenderblush: 'fff0f5', lawngreen: '7cfc00', lemonchiffon: 'fffacd', lightblue: 'add8e6', lightcoral: 'f08080', lightcyan: 'e0ffff',
|
||
lightgoldenrodyellow: 'fafad2', lightgray: 'd3d3d3', lightgreen: '90ee90', lightgrey: 'd3d3d3', lightpink: 'ffb6c1', lightsalmon: 'ffa07a',
|
||
lightseagreen: '20b2aa', lightskyblue: '87cefa', lightslategray: '778899', lightslategrey: '778899', lightsteelblue: 'b0c4de', lightyellow: 'ffffe0',
|
||
lime: '00ff00', limegreen: '32cd32', linen: 'faf0e6', magenta: 'ff00ff', maroon: '800000', mediumaquamarine: '66cdaa', mediumblue: '0000cd',
|
||
mediumorchid: 'ba55d3', mediumpurple: '9370db', mediumseagreen: '3cb371', mediumslateblue: '7b68ee', mediumspringgreen: '00fa9a',
|
||
mediumturquoise: '48d1cc', mediumvioletred: 'c71585', midnightblue: '191970', mintcream: 'f5fffa', mistyrose: 'ffe4e1', moccasin: 'ffe4b5',
|
||
navajowhite: 'ffdead', navy: '000080', oldlace: 'fdf5e6', olive: '808000', olivedrab: '6b8e23', orange: 'ffa500', orangered: 'ff4500', orchid: 'da70d6',
|
||
palegoldenrod: 'eee8aa', palegreen: '98fb98', paleturquoise: 'afeeee', palevioletred: 'db7093', papayawhip: 'ffefd5', peachpuff: 'ffdab9', peru: 'cd853f',
|
||
pink: 'ffc0cb', plum: 'dda0dd', powderblue: 'b0e0e6', purple: '800080', rebeccapurple: '663399', red: 'ff0000', rosybrown: 'bc8f8f', royalblue: '4169e1',
|
||
saddlebrown: '8b4513', salmon: 'fa8072', sandybrown: 'f4a460', seagreen: '2e8b57', seashell: 'fff5ee', sienna: 'a0522d', silver: 'c0c0c0',
|
||
skyblue: '87ceeb', slateblue: '6a5acd', slategray: '708090', slategrey: '708090', snow: 'fffafa', springgreen: '00ff7f', steelblue: '4682b4', tan: 'd2b48c',
|
||
teal: '008080', thistle: 'd8bfd8', tomato: 'ff6347', turquoise: '40e0d0', violet: 'ee82ee', wheat: 'f5deb3', white: 'ffffff', whitesmoke: 'f5f5f5',
|
||
yellow: 'ffff00', yellowgreen: '9acd32',
|
||
};
|
||
|
||
const clamp = (x, lo = 0, hi = 1) => Math.min(hi, Math.max(lo, x));
|
||
|
||
/** a CSS colour -> {r, g, b, a} (0..255, alpha 0..1), null when it is not one (variables are not resolved here) */
|
||
export function parseColor(input) {
|
||
const s = String(input || '').trim().toLowerCase();
|
||
if (!s) return null;
|
||
if (s === 'transparent') return { r: 0, g: 0, b: 0, a: 0 };
|
||
if (NAMED_COLORS[s]) return hexToRgb(NAMED_COLORS[s]);
|
||
if (/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(s)) return hexToRgb(s.slice(1));
|
||
const m = /^(rgba?|hsla?|hwb|oklch|oklab)\(\s*([^)]*)\)$/.exec(s);
|
||
if (!m) return null;
|
||
const parts = m[2].split(/\s*[,/]\s*|\s+/).filter(Boolean);
|
||
if (parts.length < 3 || parts.some((p) => !/^[-+]?(\d+\.?\d*|\.\d+)(%|deg|rad|turn|grad)?$|^none$/.test(p))) return null;
|
||
const num = (p) => (p === 'none' ? 0 : parseFloat(p));
|
||
const alpha = parts[3] === undefined ? 1 : parts[3].endsWith('%') ? num(parts[3]) / 100 : num(parts[3]);
|
||
const fn = m[1];
|
||
let rgb;
|
||
if (fn.startsWith('rgb')) {
|
||
rgb = parts.slice(0, 3).map((p) => (p.endsWith('%') ? num(p) * 2.55 : num(p)));
|
||
} else if (fn.startsWith('hsl')) {
|
||
rgb = hslToRgb(angle(parts[0]), num(parts[1]) / 100, num(parts[2]) / 100);
|
||
} else if (fn === 'hwb') {
|
||
const w = num(parts[1]) / 100, bl = num(parts[2]) / 100;
|
||
const base = hslToRgb(angle(parts[0]), 1, 0.5);
|
||
const sum = w + bl;
|
||
rgb = base.map((c) => (sum >= 1 ? (w / sum) * 255 : (c / 255) * (1 - w - bl) * 255 + w * 255));
|
||
} else {
|
||
const L = parts[0].endsWith('%') ? num(parts[0]) / 100 : num(parts[0]);
|
||
let A, B;
|
||
if (fn === 'oklch') {
|
||
const C = parts[1].endsWith('%') ? num(parts[1]) * 0.004 : num(parts[1]);
|
||
const h = (angle(parts[2]) * Math.PI) / 180;
|
||
A = C * Math.cos(h); B = C * Math.sin(h);
|
||
} else {
|
||
A = parts[1].endsWith('%') ? num(parts[1]) * 0.004 : num(parts[1]);
|
||
B = parts[2].endsWith('%') ? num(parts[2]) * 0.004 : num(parts[2]);
|
||
}
|
||
rgb = oklabToRgb(L, A, B);
|
||
}
|
||
const [r, g, b] = rgb.map((c) => Math.round(clamp(c, 0, 255)));
|
||
return { r, g, b, a: clamp(Math.round(alpha * 1000) / 1000) };
|
||
}
|
||
|
||
function angle(p) {
|
||
const n = parseFloat(p);
|
||
if (p.endsWith('rad')) return (n * 180) / Math.PI;
|
||
if (p.endsWith('turn')) return n * 360;
|
||
if (p.endsWith('grad')) return n * 0.9;
|
||
return n;
|
||
}
|
||
|
||
function hexToRgb(hex) {
|
||
const h = hex.length <= 4 ? [...hex].map((c) => c + c).join('') : hex;
|
||
return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16), a: h.length === 8 ? Math.round((parseInt(h.slice(6, 8), 16) / 255) * 1000) / 1000 : 1 };
|
||
}
|
||
|
||
function hslToRgb(h, s, l) {
|
||
h = ((h % 360) + 360) % 360;
|
||
const k = (n) => (n + h / 30) % 12;
|
||
const f = (n) => l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
|
||
return [f(0) * 255, f(8) * 255, f(4) * 255];
|
||
}
|
||
|
||
export function rgbToHsl({ r, g, b }) {
|
||
const [R, G, B] = [r / 255, g / 255, b / 255];
|
||
const max = Math.max(R, G, B), min = Math.min(R, G, B);
|
||
const l = (max + min) / 2;
|
||
if (max === min) return { h: 0, s: 0, l };
|
||
const d = max - min;
|
||
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||
const h = max === R ? (G - B) / d + (G < B ? 6 : 0) : max === G ? (B - R) / d + 2 : (R - G) / d + 4;
|
||
return { h: h * 60, s, l };
|
||
}
|
||
|
||
export function rgbToHsv({ r, g, b }) {
|
||
const [R, G, B] = [r / 255, g / 255, b / 255];
|
||
const max = Math.max(R, G, B), min = Math.min(R, G, B);
|
||
const d = max - min;
|
||
let h = 0;
|
||
if (d) h = (max === R ? (G - B) / d + (G < B ? 6 : 0) : max === G ? (B - R) / d + 2 : (R - G) / d + 4) * 60;
|
||
return { h, s: max ? d / max : 0, v: max };
|
||
}
|
||
|
||
export function hsvToRgb(h, s, v) {
|
||
const f = (n) => { const k = (n + h / 60) % 6; return v - v * s * Math.max(0, Math.min(k, 4 - k, 1)); };
|
||
return { r: Math.round(f(5) * 255), g: Math.round(f(3) * 255), b: Math.round(f(1) * 255) };
|
||
}
|
||
|
||
const toLinear = (c) => { c /= 255; return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; };
|
||
const fromLinear = (c) => 255 * (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055);
|
||
|
||
function oklabToRgb(L, a, b) {
|
||
const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
|
||
const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
|
||
const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
|
||
return [
|
||
fromLinear(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
|
||
fromLinear(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
|
||
fromLinear(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),
|
||
];
|
||
}
|
||
|
||
export function rgbToOklch({ r, g, b }) {
|
||
const [R, G, B] = [toLinear(r), toLinear(g), toLinear(b)];
|
||
const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B);
|
||
const m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B);
|
||
const s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B);
|
||
const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
|
||
const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
|
||
const Bb = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
|
||
const C = Math.sqrt(A * A + Bb * Bb);
|
||
let H = (Math.atan2(Bb, A) * 180) / Math.PI;
|
||
if (H < 0) H += 360;
|
||
return { l: L, c: C, h: C < 0.0001 ? 0 : H };
|
||
}
|
||
|
||
/** the format a colour is written in: hex, rgb, hsl, hwb, oklch, oklab, name */
|
||
export function colorFormat(text) {
|
||
const s = String(text).trim().toLowerCase();
|
||
if (s.startsWith('#')) return 'hex';
|
||
const m = /^(rgb|hsl|hwb|oklch|oklab)a?\(/.exec(s);
|
||
if (m) return m[1];
|
||
return NAMED_COLORS[s] || s === 'transparent' ? 'name' : 'hex';
|
||
}
|
||
|
||
const hex2 = (n) => Math.round(n).toString(16).padStart(2, '0');
|
||
const round = (n, d = 0) => { const k = 10 ** d; return Math.round(n * k) / k; };
|
||
|
||
/** {r, g, b, a} written as hex / rgb / hsl / oklch / name (a name only when one is exact, else hex) */
|
||
export function formatColor(c, format = 'hex') {
|
||
const a = c.a ?? 1;
|
||
if (format === 'name') {
|
||
if (a === 0) return 'transparent';
|
||
const hex = hex2(c.r) + hex2(c.g) + hex2(c.b);
|
||
const name = a === 1 && Object.keys(NAMED_COLORS).find((n) => NAMED_COLORS[n] === hex && !/grey/.test(n));
|
||
if (name) return name;
|
||
format = 'hex';
|
||
}
|
||
if (format === 'rgb') return a < 1 ? `rgba(${c.r}, ${c.g}, ${c.b}, ${round(a, 3)})` : `rgb(${c.r}, ${c.g}, ${c.b})`;
|
||
if (format === 'hsl' || format === 'hwb') {
|
||
const { h, s, l } = rgbToHsl(c);
|
||
return a < 1 ? `hsla(${round(h)}, ${round(s * 100, 1)}%, ${round(l * 100, 1)}%, ${round(a, 3)})` : `hsl(${round(h)}, ${round(s * 100, 1)}%, ${round(l * 100, 1)}%)`;
|
||
}
|
||
if (format === 'oklch' || format === 'oklab') {
|
||
const { l, c: C, h } = rgbToOklch(c);
|
||
return `oklch(${round(l * 100, 2)}% ${round(C, 4)} ${round(h, 2)}${a < 1 ? ` / ${round(a, 3)}` : ''})`;
|
||
}
|
||
return '#' + hex2(c.r) + hex2(c.g) + hex2(c.b) + (a < 1 ? hex2(a * 255) : '');
|
||
}
|
||
|
||
/** a colour value with its variables resolved (var(--x, fallback), $x), up to a few levels; null when it is not a colour */
|
||
export function resolveColor(value, vars, depth = 0) {
|
||
const v = String(value || '').trim();
|
||
const direct = parseColor(v);
|
||
if (direct || depth > 6 || !vars) return direct;
|
||
let m = /^var\(\s*(--[\w-]+)\s*(?:,\s*([\s\S]+))?\)$/.exec(v);
|
||
if (m) return (vars.has(m[1]) ? resolveColor(vars.get(m[1]), vars, depth + 1) : null) || (m[2] ? resolveColor(m[2], vars, depth + 1) : null);
|
||
m = /^\$[\w-]+$/.exec(v);
|
||
if (m && vars.has(v)) return resolveColor(vars.get(v), vars, depth + 1);
|
||
return null;
|
||
}
|
||
|
||
const COLOR_FN = /\b(?:rgba?|hsla?|hwb|oklch|oklab)\([^()]*\)/gi;
|
||
const HEX = /#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})\b/gi;
|
||
const WORD = /(?<![\w$@.#-])[a-z]+(?![\w(-])/gi;
|
||
const VAR = /var\(\s*--[\w-]+\s*(?:,[^()]*)?\)|(?<![\w-])\$[\w-]+/g;
|
||
|
||
/**
|
||
* The colours written in a stylesheet's declarations (the swatches of the code): [{start, end, color, text, variable}]
|
||
* variable: the reference (var(--x) / $x) of a colour defined elsewhere, resolved with `vars`.
|
||
*/
|
||
export function findColors(model, vars = variablesOf(model)) {
|
||
const out = [];
|
||
const { text } = model;
|
||
for (const node of walk(model.root)) {
|
||
if (node.type !== 'decl') continue;
|
||
const value = text.slice(node.valueStart, node.valueEnd);
|
||
if (/^\s*url\(/i.test(value) && !/,/.test(value)) continue;
|
||
const taken = [];
|
||
const add = (start, len, color, variable) => {
|
||
if (taken.some(([a, b]) => start < b && start + len > a)) return;
|
||
taken.push([start, start + len]);
|
||
out.push({ start: node.valueStart + start, end: node.valueStart + start + len, color, text: value.slice(start, start + len), variable });
|
||
};
|
||
const urls = [...value.matchAll(/url\([^)]*\)/gi)].map((m) => [m.index, m.index + m[0].length]);
|
||
const inUrl = (i) => urls.some(([a, b]) => i >= a && i < b);
|
||
for (const m of value.matchAll(COLOR_FN)) { const c = parseColor(m[0]); if (c && !inUrl(m.index)) add(m.index, m[0].length, c, false); }
|
||
for (const m of value.matchAll(HEX)) { const c = parseColor(m[0]); if (c && !inUrl(m.index)) add(m.index, m[0].length, c, false); }
|
||
for (const m of value.matchAll(VAR)) { const c = resolveColor(m[0], vars); if (c && !inUrl(m.index)) add(m.index, m[0].length, c, true); }
|
||
if (/^(font|grid|animation|transition|counter|content|list-style-type|will-change)/i.test(node.prop)) continue;
|
||
for (const m of value.matchAll(WORD)) {
|
||
const w = m[0].toLowerCase();
|
||
if ((NAMED_COLORS[w] || w === 'transparent') && !inUrl(m.index)) add(m.index, m[0].length, parseColor(w), false);
|
||
}
|
||
}
|
||
return out.sort((a, b) => a.start - b.start);
|
||
}
|
||
|
||
// SCSS without Sass: the preview's first draw (nesting and $variables), until the real compiler answers ---------------
|
||
|
||
/** a rough CSS of an SCSS model: nested rules flattened, @media kept around them, $variables replaced; mixins left out */
|
||
export function flattenScss(model) {
|
||
const vars = variablesOf(model);
|
||
const sub = (v) => v.replace(/\$[\w-]+/g, (m) => (vars.has(m) ? sub(vars.get(m)) : m)).replace(/#\{([^}]*)\}/g, '$1');
|
||
const out = [];
|
||
const visit = (node, media) => {
|
||
for (const child of node.children || []) {
|
||
if (child.type === 'rule') {
|
||
const selector = resolvedSelector(child);
|
||
const decls = declarations(child).filter((d) => !d.prop.startsWith('$')).map((d) => ` ${d.prop}: ${sub(d.value)}${d.important ? ' !important' : ''};`);
|
||
if (selector && decls.length && !selector.includes('%')) {
|
||
const block = `${sub(selector)} {\n${decls.join('\n')}\n}`;
|
||
out.push(media.length ? media.map((m) => `${m} {`).join(' ') + '\n' + block + '\n' + media.map(() => '}').join('') : block);
|
||
}
|
||
visit(child, media);
|
||
} else if (child.type === 'atrule' && child.children) {
|
||
if (['media', 'supports', 'container', 'layer'].includes(child.name)) {
|
||
// @media inside a rule: its declarations belong to the rule around it
|
||
const owner = (() => { for (let n = child.parent; n && n.type !== 'root'; n = n.parent) if (n.type === 'rule') return n; return null; })();
|
||
const decls = declarations(child).filter((d) => !d.prop.startsWith('$')).map((d) => ` ${d.prop}: ${sub(d.value)};`);
|
||
const inner = [...media, `@${child.name} ${sub(child.params)}`];
|
||
if (owner && decls.length) out.push(inner.map((m) => `${m} {`).join(' ') + `\n${sub(resolvedSelector(owner))} {\n${decls.join('\n')}\n}\n` + inner.map(() => '}').join(''));
|
||
visit(child, inner);
|
||
} else if (['font-face', 'page'].includes(child.name) || /keyframes$/.test(child.name)) {
|
||
out.push(sub(model.text.slice(child.start, child.end)));
|
||
} else if (!['mixin', 'function', 'include', 'each', 'for', 'while', 'if', 'else'].includes(child.name)) {
|
||
visit(child, media);
|
||
}
|
||
} else if (child.type === 'atrule' && child.name === 'import' && !/\.s[ac]ss/.test(child.params)) {
|
||
out.unshift(model.text.slice(child.start, child.end));
|
||
}
|
||
}
|
||
};
|
||
visit(model.root, []);
|
||
return out.join('\n\n') + '\n';
|
||
}
|