// A small, tolerant CSS parser: enough for stylesheets embedded in SVG.
// Produces { rules: [ {type:'rule', selector, decls:[{name,value,important}]}
// | {type:'at', name, prelude, rules|decls|raw} | {type:'comment', text} ] }
export function parseCSS (text) {
const src = String(text || '');
let i = 0;
const n = src.length;
const ws = () => { while (i < n && /\s/.test(src[i])) i++; };
const readUntil = (stops) => {
let out = '';
let depth = 0, quote = null;
while (i < n) {
const c = src[i];
if (quote) { out += c; if (c === '\\') { out += src[++i] || ''; } else if (c === quote) quote = null; i++; continue; }
if (c === '"' || c === "'") { quote = c; out += c; i++; continue; }
if (c === '/' && src[i + 1] === '*') { const e = src.indexOf('*/', i + 2); i = e < 0 ? n : e + 2; continue; }
if (c === '(') depth++;
if (c === ')') depth = Math.max(0, depth - 1);
if (!depth && stops.includes(c)) return out;
out += c; i++;
}
return out;
};
const readBlock = () => {
// assumes src[i] === '{'; returns raw inner text with balanced braces
let depth = 0, out = '', quote = null;
while (i < n) {
const c = src[i];
if (quote) { out += c; if (c === '\\') out += src[++i] || ''; else if (c === quote) quote = null; i++; continue; }
if (c === '"' || c === "'") { quote = c; out += c; i++; continue; }
if (c === '{') { depth++; if (depth === 1) { i++; continue; } }
if (c === '}') { depth--; if (depth === 0) { i++; return out; } }
out += c; i++;
}
return out;
};
const parseDecls = (body) => {
const decls = [];
let j = 0;
const m = body.length;
while (j < m) {
// skip ws and comments
while (j < m && /\s/.test(body[j])) j++;
if (body.startsWith('/*', j)) { const e = body.indexOf('*/', j + 2); j = e < 0 ? m : e + 2; continue; }
if (j >= m) break;
let k = j, depth = 0, quote = null;
while (k < m) {
const c = body[k];
if (quote) { if (c === '\\') k++; else if (c === quote) quote = null; k++; continue; }
if (c === '"' || c === "'") { quote = c; k++; continue; }
if (c === '(') depth++;
if (c === ')') depth--;
if (c === ';' && !depth) break;
k++;
}
const chunk = body.slice(j, k).trim();
j = k + 1;
if (!chunk) continue;
const colon = chunk.indexOf(':');
if (colon < 0) { decls.push({ name: chunk, value: '', important: false, invalid: true }); continue; }
const name = chunk.slice(0, colon).trim();
let value = chunk.slice(colon + 1).trim();
let important = false;
if (/!\s*important$/i.test(value)) { important = true; value = value.replace(/\s*!\s*important$/i, '').trim(); }
decls.push({ name, value, important });
}
return decls;
};
const parseRules = () => {
const rules = [];
for (;;) {
ws();
if (i >= n) break;
if (src.startsWith('/*', i)) {
const e = src.indexOf('*/', i + 2);
const text = src.slice(i + 2, e < 0 ? n : e).trim();
i = e < 0 ? n : e + 2;
rules.push({ type: 'comment', text });
continue;
}
if (src[i] === '}') { i++; return rules; }
if (src[i] === '@') {
i++;
const nameM = src.slice(i).match(/^[a-zA-Z-]+/);
const name = nameM ? nameM[0] : '';
i += name.length;
const prelude = readUntil(['{', ';']).trim();
if (src[i] === ';' || i >= n) { i++; rules.push({ type: 'at', name, prelude, raw: null }); continue; }
if (['media', 'supports', 'container', 'layer', 'document'].includes(name)) {
i++; // {
const inner = parseRules();
rules.push({ type: 'at', name, prelude, rules: inner });
} else if (['font-face', 'page', 'property', 'counter-style'].includes(name)) {
const body = readBlock();
rules.push({ type: 'at', name, prelude, decls: parseDecls(body) });
} else {
const body = readBlock();
rules.push({ type: 'at', name, prelude, raw: body.trim() });
}
continue;
}
const selector = readUntil(['{', '}']).trim();
if (src[i] !== '{') { i++; if (selector) rules.push({ type: 'garbage', text: selector }); continue; }
const body = readBlock();
// A rule body could contain nested rules (CSS nesting); keep decls only.
rules.push({ type: 'rule', selector, decls: parseDecls(body) });
}
return rules;
};
return { rules: parseRules() };
}
export function serializeCSS (sheet, { indent = ' ' } = {}) {
const decl = (d, ind) => `${ind}${d.name}: ${d.value}${d.important ? ' !important' : ''};`;
const rule = (r, ind = '') => {
if (r.type === 'comment') return `${ind}/* ${r.text} */`;
if (r.type === 'garbage') return `${ind}${r.text}`;
if (r.type === 'at') {
const head = `${ind}@${r.name}${r.prelude ? ' ' + r.prelude : ''}`;
if (r.rules) return `${head} {\n${r.rules.map(x => rule(x, ind + indent)).join('\n')}\n${ind}}`;
if (r.decls) return `${head} {\n${r.decls.map(d => decl(d, ind + indent)).join('\n')}\n${ind}}`;
if (r.raw != null) return `${head} {\n${r.raw.split('\n').map(l => ind + indent + l.trim()).join('\n')}\n${ind}}`;
return `${head};`;
}
return `${ind}${r.selector} {\n${r.decls.map(d => decl(d, ind + indent)).join('\n')}\n${ind}}`;
};
return sheet.rules.map(r => rule(r)).join('\n\n') + (sheet.rules.length ? '\n' : '');
}
// Parse a style="" attribute into [{name, value, important}]
export function parseStyleAttr (s) {
return parseCSS(`x{${s || ''}}`).rules[0]?.decls || [];
}
export function serializeStyleAttr (decls) {
return decls.filter(d => d.name).map(d => `${d.name}: ${d.value}${d.important ? ' !important' : ''}`).join('; ');
}
// Collect @font-face families across a sheet.
export function fontFaces (sheet) {
const out = [];
const walk = rules => {
for (const r of rules) {
if (r.type === 'at' && r.name === 'font-face' && r.decls) {
const get = k => r.decls.find(d => d.name === k)?.value;
out.push({ family: (get('font-family') || '').replace(/^["']|["']$/g, ''), weight: get('font-weight') || '400', style: get('font-style') || 'normal', src: get('src') || '', rule: r });
} else if (r.type === 'at' && r.rules) walk(r.rules);
}
};
walk(sheet.rules);
return out;
}
// Highlight CSS into HTML spans (for the code editor overlay).
export function highlightCSS (text) {
const esc = s => s.replace(/[&<>]/g, c => ({ '&': '&', '<': '<', '>': '>' }[c]));
let out = '';
const re = /(\/\*[\s\S]*?\*\/)|("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')|(@[a-zA-Z-]+)|([{};:])|(#[0-9a-fA-F]{3,8}\b)|(-?\d*\.?\d+(?:px|em|rem|%|deg|s|ms|pt|vw|vh)?)|([a-zA-Z-]+(?=\s*:))|([.#]?[a-zA-Z_][\w-]*(?=[^:{}]*\{))|([^\s]+)|(\s+)/g;
let m;
while ((m = re.exec(text))) {
const [tok, comment, str, at, punct, hex, num, prop, sel] = m;
if (comment) out += ``;
else if (str) out += `${esc(tok)}`;
else if (at) out += `${esc(tok)}`;
else if (punct) out += `${esc(tok)}`;
else if (hex) out += `${esc(tok)}`;
else if (num) out += `${esc(tok)}`;
else if (prop) out += `${esc(tok)}`;
else if (sel) out += `${esc(tok)}`;
else out += esc(tok);
}
return out;
}
// Highlight XML/SVG source into HTML spans.
export function highlightXML (text) {
const esc = s => s.replace(/[&<>]/g, c => ({ '&': '&', '<': '<', '>': '>' }[c]));
let out = '';
const re = /()|()|(<\?[\s\S]*?\?>)|(<\/?)([a-zA-Z_][\w:.-]*)|(\/?>)|([a-zA-Z_][\w:.-]*)(=)("(?:[^"]*)"|'(?:[^']*)')|([^<]+)|(.)/g;
let m;
let inTag = false;
while ((m = re.exec(text))) {
const [tok, comment, cdata, pi, open, name, close, aname, eq, aval, txt] = m;
if (comment) out += ``;
else if (cdata) out += `${esc(tok)}`;
else if (pi) out += `${esc(tok)}`;
else if (open) { inTag = true; out += `${esc(open)}${esc(name)}`; }
else if (close) { inTag = false; out += `${esc(close)}`; }
else if (aname) out += `${esc(aname)}${eq}${esc(aval)}`;
else if (txt) out += inTag ? esc(tok) : `${esc(tok)}`;
else out += esc(tok);
}
return out;
}