Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198// 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 += `<span class="c-comment">${esc(tok)}</span>`; else if (str) out += `<span class="c-string">${esc(tok)}</span>`; else if (at) out += `<span class="c-at">${esc(tok)}</span>`; else if (punct) out += `<span class="c-punct">${esc(tok)}</span>`; else if (hex) out += `<span class="c-color" style="--c:${esc(tok)}">${esc(tok)}</span>`; else if (num) out += `<span class="c-num">${esc(tok)}</span>`; else if (prop) out += `<span class="c-prop">${esc(tok)}</span>`; else if (sel) out += `<span class="c-sel">${esc(tok)}</span>`; 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]*?-->)|(<!\[CDATA\[[\s\S]*?\]\]>)|(<\?[\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 += `<span class="x-comment">${esc(tok)}</span>`; else if (cdata) out += `<span class="x-cdata">${esc(tok)}</span>`; else if (pi) out += `<span class="x-pi">${esc(tok)}</span>`; else if (open) { inTag = true; out += `<span class="x-punct">${esc(open)}</span><span class="x-tag">${esc(name)}</span>`; } else if (close) { inTag = false; out += `<span class="x-punct">${esc(close)}</span>`; } else if (aname) out += `<span class="x-attr">${esc(aname)}</span><span class="x-punct">${eq}</span><span class="x-val">${esc(aval)}</span>`; else if (txt) out += inTag ? esc(tok) : `<span class="x-text">${esc(tok)}</span>`; else out += esc(tok); } return out;}