1215 lines
78 KiB
JavaScript
1215 lines
78 KiB
JavaScript
// The visual stylesheet editor (.css / .scss, the editor's Design and Split modes): the rules of the file (a tree:
|
||
// @media groups, SCSS nesting, @font-face, @keyframes...), an inspector of the selected rule grouped like a design tool
|
||
// (layout, box, size, position, typography, colours, effects, the rest), and the live preview of a page with the
|
||
// elements the rule matches outlined (a click on one selects the rules that apply to it, by specificity).
|
||
// The text is the source of truth: each change is ONE edit of the Monaco model (Ctrl+Z undoes it, nothing else of the
|
||
// file moves), and the panels are drawn again from the text after every change, typed in the code or made here.
|
||
import {
|
||
parseStylesheet, outline, declarations, declarationOf, setDeclaration, insertDeclaration, removeNode, duplicateNode, insertRule, moveNode,
|
||
setSelector, renameDeclaration, resolvedSelector, matchableSelector, maxSpecificity, specificity, splitList, contextOf, labelOf, pathOf,
|
||
findByPath, blockAt, lineCol, variablesOf, resolveColor, parseColor, formatColor, colorFormat, rgbToHsv, hsvToRgb, NAMED_COLORS,
|
||
expandBox, compactBox, parseNumber, formatNumber, parseShadows, formatShadows, parseGradient, formatGradient, flattenScss, splitValue, walk,
|
||
} from './css-model.js';
|
||
import { scanProject, colorVariables } from './css-colors.js';
|
||
import { HtmlPreview } from './html-preview.js';
|
||
import { el, clear, t, prefs, icon } from './ui.js';
|
||
|
||
const debounce = (fn, ms) => { let id; const f = (...a) => { clearTimeout(id); id = setTimeout(() => fn(...a), ms); }; f.cancel = () => clearTimeout(id); return f; };
|
||
|
||
const UNITLESS = new Set(['opacity', 'z-index', 'flex-grow', 'flex-shrink', 'order', 'font-weight', 'line-height', 'zoom', 'orphans', 'widows', 'fill-opacity', 'stroke-opacity', 'aspect-ratio']);
|
||
|
||
/** the inspector's groups: [id, title, the properties it covers (the rest goes to Other)] */
|
||
const GROUPS = [
|
||
['layout', 'Layout', ['display', 'flex-direction', 'flex-wrap', 'flex-flow', 'justify-content', 'align-items', 'align-content', 'gap', 'row-gap', 'column-gap',
|
||
'grid-template-columns', 'grid-template-rows', 'grid-template-areas', 'grid-auto-flow', 'grid-auto-columns', 'grid-auto-rows', 'place-items', 'place-content',
|
||
'flex', 'flex-grow', 'flex-shrink', 'flex-basis', 'order', 'align-self', 'justify-self', 'justify-items', 'grid-column', 'grid-row', 'grid-area', 'float', 'clear', 'visibility', 'box-sizing']],
|
||
['box', 'Box', ['margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left', 'padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
|
||
'border', 'border-width', 'border-style', 'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width', 'border-radius',
|
||
'border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius', 'outline', 'outline-offset']],
|
||
['size', 'Size', ['width', 'height', 'min-width', 'max-width', 'min-height', 'max-height', 'aspect-ratio', 'overflow', 'overflow-x', 'overflow-y', 'object-fit', 'object-position']],
|
||
['position', 'Position', ['position', 'top', 'right', 'bottom', 'left', 'inset', 'z-index']],
|
||
['type', 'Typography', ['font', 'font-family', 'font-size', 'font-weight', 'font-style', 'line-height', 'letter-spacing', 'word-spacing', 'text-align', 'text-transform',
|
||
'text-decoration', 'text-decoration-line', 'text-indent', 'white-space', 'word-break', 'overflow-wrap', 'text-overflow', 'vertical-align', 'font-variant', 'list-style']],
|
||
['colors', 'Colours & backgrounds', ['color', 'background', 'background-color', 'background-image', 'background-size', 'background-position', 'background-repeat',
|
||
'background-attachment', 'background-clip', 'border-color', 'outline-color', 'accent-color', 'caret-color', 'fill', 'stroke', 'text-decoration-color']],
|
||
['effects', 'Effects', ['box-shadow', 'text-shadow', 'opacity', 'filter', 'backdrop-filter', 'transform', 'transform-origin', 'transition', 'animation', 'cursor', 'mix-blend-mode', 'pointer-events', 'will-change']],
|
||
];
|
||
const COVERED = new Set(GROUPS.flatMap((g) => g[2]));
|
||
|
||
const SHORTHANDS = ['margin', 'padding', 'border', 'border-top', 'border-right', 'border-bottom', 'border-left', 'border-width', 'border-style', 'border-color', 'border-radius',
|
||
'background', 'font', 'flex', 'flex-flow', 'grid', 'grid-template', 'grid-area', 'grid-row', 'grid-column', 'gap', 'inset', 'outline', 'list-style', 'overflow', 'place-items',
|
||
'place-content', 'place-self', 'transition', 'animation', 'text-decoration', 'columns', 'mask', 'container'];
|
||
const KEYWORDS = ['auto', 'none', 'inherit', 'initial', 'unset', 'revert', 'block', 'inline', 'inline-block', 'flex', 'inline-flex', 'grid', 'inline-grid', 'contents', 'hidden',
|
||
'visible', 'scroll', 'clip', 'relative', 'absolute', 'fixed', 'sticky', 'static', 'center', 'start', 'end', 'flex-start', 'flex-end', 'space-between', 'space-around',
|
||
'space-evenly', 'stretch', 'baseline', 'normal', 'bold', 'bolder', 'lighter', 'italic', 'oblique', 'uppercase', 'lowercase', 'capitalize', 'nowrap', 'wrap', 'pre', 'pre-wrap',
|
||
'pre-line', 'break-word', 'break-all', 'ellipsis', 'solid', 'dashed', 'dotted', 'double', 'groove', 'pointer', 'default', 'text', 'move', 'not-allowed', 'grab', 'cover',
|
||
'contain', 'no-repeat', 'repeat', 'repeat-x', 'repeat-y', 'left', 'right', 'top', 'bottom', 'row', 'column', 'row-reverse', 'column-reverse', 'dense', 'ease', 'ease-in',
|
||
'ease-out', 'ease-in-out', 'linear', 'transparent', 'currentColor', 'border-box', 'content-box', 'padding-box', 'underline', 'line-through', 'overline', 'collapse',
|
||
'both', 'min-content', 'max-content', 'fit-content', 'all', 'sans-serif', 'serif', 'monospace', 'system-ui', 'multiply', 'screen', 'overlay', 'fill', 'scale-down',
|
||
'0', '1', '100%', '1fr', 'repeat(3, 1fr)', 'repeat(auto-fill, minmax(200px, 1fr))', 'blur(4px)', 'brightness(1.2)', 'grayscale(1)', 'drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3))',
|
||
'translate(0, 0)', 'rotate(45deg)', 'scale(1.1)', 'all 0.2s ease', 'opacity 0.3s ease-in-out', 'transform 0.2s ease'];
|
||
|
||
const STYLE = `
|
||
.cssd { position: absolute; inset: 0; display: grid; grid-template-columns: var(--cssd-rules, 250px) var(--cssd-insp, 360px) 1fr; grid-template-rows: auto 1fr; background: var(--bg); color: var(--text); font-size: 12px; }
|
||
.cssd.no-preview { grid-template-columns: var(--cssd-rules, 250px) 1fr; }
|
||
.cssd.no-preview .cssd-prev { display: none; }
|
||
.cssd.narrow { grid-template-columns: 1fr; grid-template-rows: auto minmax(170px, 42%) 1fr; }
|
||
.cssd.narrow .cssd-vars { max-height: 22%; }
|
||
.cssd.narrow .cssd-prev { display: none; }
|
||
.cssd.only-preview { grid-template-columns: 1fr; }
|
||
.cssd.only-preview .cssd-rules, .cssd.only-preview .cssd-insp { display: none; }
|
||
.cssd-msgs { grid-column: 1 / -1; display: flex; flex-direction: column; max-height: 96px; overflow: auto; }
|
||
.cssd-msgs:empty { display: none; }
|
||
.cssd-msg { display: flex; gap: 6px; padding: 3px 10px; cursor: pointer; border-bottom: 1px solid var(--border-2); background: rgba(219, 92, 92, .14); }
|
||
.cssd-msg.warn { background: rgba(229, 192, 123, .12); }
|
||
.cssd-msg.info { background: transparent; color: var(--text-2); cursor: default; }
|
||
.cssd-msg b { color: #e06c75; white-space: nowrap; }
|
||
.cssd-msg.warn b { color: #d19a66; }
|
||
.cssd-rules, .cssd-insp { min-height: 0; overflow: auto; border-right: 1px solid var(--border-2); }
|
||
.cssd-rules { display: flex; flex-direction: column; overflow: hidden; }
|
||
.cssd-tools { display: flex; gap: 2px; padding: 6px; border-bottom: 1px solid var(--border-2); align-items: center; flex-wrap: wrap; }
|
||
.cssd-tools input { flex: 1 1 100%; min-width: 60px; margin-bottom: 2px; }
|
||
.cssd button.cssd-b { font: inherit; color: inherit; background: transparent; border: 1px solid transparent; border-radius: 4px; padding: 2px 6px; cursor: pointer; min-width: 22px; }
|
||
.cssd button.cssd-b:hover { border-color: var(--border-2); background: var(--bg-2, rgba(127,127,127,.12)); }
|
||
.cssd button.cssd-b.on { background: var(--accent); color: #fff; }
|
||
.cssd button.cssd-b:disabled { opacity: .4; cursor: default; }
|
||
.cssd-list { flex: 1; overflow: auto; padding: 4px 0; }
|
||
.cssd-row { display: flex; align-items: center; gap: 6px; padding: 2px 8px; cursor: pointer; white-space: nowrap; }
|
||
.cssd-row:hover { background: rgba(127, 127, 127, .1); }
|
||
.cssd-row.on { background: var(--accent); color: #fff; }
|
||
.cssd-row.match .cssd-sel { text-decoration: underline dotted #ffaa00; }
|
||
.cssd-row .cssd-kind { font-family: var(--mono); font-size: 10px; opacity: .65; width: 18px; text-align: center; flex: none; }
|
||
.cssd-row .cssd-sel { overflow: hidden; text-overflow: ellipsis; font-family: var(--mono); }
|
||
.cssd-row .cssd-n { margin-left: auto; opacity: .55; font-size: 10px; }
|
||
.cssd-row.at .cssd-sel { color: #c678dd; }
|
||
.cssd-row.on .cssd-sel { color: #fff; }
|
||
.cssd-vars { border-top: 1px solid var(--border-2); max-height: 30%; overflow: auto; padding: 4px 0; }
|
||
.cssd-h { padding: 4px 8px; font-size: 10px; text-transform: uppercase; letter-spacing: .06em; color: var(--text-2); display: flex; gap: 6px; align-items: center; }
|
||
.cssd-match { margin: 6px; padding: 6px 8px; border: 1px solid #ffaa00; border-radius: 6px; display: flex; flex-direction: column; gap: 3px; }
|
||
.cssd-match .cssd-chain { font-family: var(--mono); font-size: 10px; opacity: .7; white-space: normal; }
|
||
.cssd-insp { padding-bottom: 40px; }
|
||
.cssd-head { padding: 8px 10px; border-bottom: 1px solid var(--border-2); display: flex; flex-direction: column; gap: 4px; position: sticky; top: 0; background: var(--bg); z-index: 2; }
|
||
.cssd-head input.cssd-selector { font-family: var(--mono); font-size: 13px; font-weight: 600; }
|
||
.cssd-ctx { font-family: var(--mono); font-size: 11px; color: #c678dd; }
|
||
.cssd-meta { display: flex; gap: 8px; flex-wrap: wrap; color: var(--text-2); font-size: 11px; align-items: center; }
|
||
.cssd-spec { font-family: var(--mono); border: 1px solid var(--border-2); border-radius: 4px; padding: 0 4px; }
|
||
.cssd-sec > summary { padding: 6px 10px; cursor: pointer; font-weight: 600; border-bottom: 1px solid var(--border-2); list-style: none; display: flex; gap: 6px; align-items: center; }
|
||
.cssd-sec > summary::before { content: '▸'; opacity: .6; }
|
||
.cssd-sec[open] > summary::before { content: '▾'; }
|
||
.cssd-sec > summary .cssd-count { margin-left: auto; font-weight: normal; opacity: .6; font-size: 11px; }
|
||
.cssd-body { padding: 6px 10px 10px; display: flex; flex-direction: column; gap: 5px; }
|
||
.cssd-f { display: grid; grid-template-columns: 96px 1fr auto; gap: 4px; align-items: center; }
|
||
.cssd-f > label { color: var(--text-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; user-select: none; }
|
||
.cssd-f.set > label { color: var(--accent-text, #6ea8fe); font-weight: 600; }
|
||
.cssd-f.num > label { cursor: ew-resize; }
|
||
.cssd-f .cssd-x { display: flex; gap: 1px; }
|
||
.cssd-in { font: inherit; font-family: var(--mono); font-size: 12px; width: 100%; min-width: 0; box-sizing: border-box; background: var(--input-bg, rgba(127,127,127,.08)); color: inherit; border: 1px solid var(--border-2); border-radius: 4px; padding: 2px 5px; }
|
||
.cssd-in:focus { outline: 1px solid var(--accent); border-color: var(--accent); }
|
||
select.cssd-in { font-family: inherit; }
|
||
.cssd-imp { font-weight: 700; opacity: .25; }
|
||
.cssd-imp.on { opacity: 1; color: #e06c75; }
|
||
.cssd-seg { display: flex; flex-wrap: wrap; gap: 2px; }
|
||
.cssd-seg button.cssd-b { padding: 1px 4px; display: inline-flex; align-items: center; }
|
||
.cssd-seg svg { width: 22px; height: 14px; display: block; }
|
||
.cssd-color { display: flex; gap: 4px; align-items: center; }
|
||
.cssd-sw { width: 22px; height: 18px; border-radius: 4px; border: 1px solid var(--border-2); cursor: pointer; flex: none; padding: 0; position: relative; overflow: hidden;
|
||
background-image: linear-gradient(45deg, #bbb 25%, transparent 25%, transparent 75%, #bbb 75%), linear-gradient(45deg, #bbb 25%, #fff 25%, #fff 75%, #bbb 75%); background-size: 8px 8px; background-position: 0 0, 4px 4px; }
|
||
.cssd-sw > i { position: absolute; inset: 0; }
|
||
.cssd-boxm { position: relative; margin: 4px 0; font-family: var(--mono); font-size: 11px; }
|
||
.cssd-boxm .lay { border: 1px dashed var(--border-2); border-radius: 4px; padding: 20px 34px; position: relative; }
|
||
.cssd-boxm .lay > .tag { position: absolute; left: 4px; top: 2px; font-size: 9px; text-transform: uppercase; opacity: .6; font-family: inherit; }
|
||
.cssd-boxm .m { background: rgba(249, 204, 157, .16); }
|
||
.cssd-boxm .b { background: rgba(255, 238, 160, .14); border-style: solid; }
|
||
.cssd-boxm .p { background: rgba(195, 222, 183, .16); }
|
||
.cssd-boxm .c { background: rgba(140, 182, 192, .22); text-align: center; padding: 6px; border-radius: 3px; }
|
||
.cssd-boxm input { position: absolute; width: 50px; text-align: center; font: inherit; color: inherit; background: transparent; border: 1px solid transparent; border-radius: 3px; padding: 0; }
|
||
.cssd-boxm input:hover, .cssd-boxm input:focus { border-color: var(--border-2); background: var(--bg); }
|
||
.cssd-boxm input.set { color: var(--accent-text, #6ea8fe); font-weight: 600; }
|
||
.cssd-boxm .s-top { top: 2px; left: calc(50% - 25px); } .cssd-boxm .s-bottom { bottom: 2px; left: calc(50% - 25px); }
|
||
.cssd-boxm .s-left { left: 0; top: calc(50% - 8px); width: 33px; } .cssd-boxm .s-right { right: 0; top: calc(50% - 8px); width: 33px; }
|
||
.cssd-radius { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 3px; align-items: center; }
|
||
.cssd-radius .shape { width: 34px; height: 26px; margin: auto; border: 2px solid var(--text-2); }
|
||
.cssd-fontprev { border: 1px solid var(--border-2); border-radius: 6px; padding: 8px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; background: var(--input-bg, rgba(127,127,127,.06)); }
|
||
.cssd-tracks { display: flex; gap: 2px; height: 18px; }
|
||
.cssd-tracks i { background: rgba(110, 168, 254, .35); border-radius: 2px; min-width: 3px; }
|
||
.cssd-grad { height: 22px; border-radius: 4px; border: 1px solid var(--border-2); }
|
||
.cssd-card { border: 1px solid var(--border-2); border-radius: 6px; padding: 6px; display: flex; flex-direction: column; gap: 4px; }
|
||
.cssd-row4 { display: grid; grid-template-columns: repeat(4, 1fr) auto; gap: 3px; align-items: center; }
|
||
.cssd-kv { display: grid; grid-template-columns: minmax(80px, 40%) 1fr auto; gap: 3px; align-items: center; }
|
||
.cssd-muted { color: var(--text-2); padding: 8px 10px; }
|
||
.cssd-prev { position: relative; min-width: 0; min-height: 0; }
|
||
.cssd-count { font-size: 11px; color: var(--text-2); }
|
||
.cssd-picker { position: fixed; z-index: 10000; width: 248px; background: var(--bg-2, var(--bg)); color: var(--text); border: 1px solid var(--border-2); border-radius: 8px; box-shadow: 0 8px 30px rgba(0,0,0,.45); padding: 8px; display: flex; flex-direction: column; gap: 6px; font-size: 12px; }
|
||
.cssd-picker .sv { position: relative; height: 150px; border-radius: 4px; cursor: crosshair; }
|
||
.cssd-picker .sv i, .cssd-picker .bar i { position: absolute; width: 10px; height: 10px; border: 2px solid #fff; border-radius: 50%; box-shadow: 0 0 0 1px #000; transform: translate(-50%, -50%); pointer-events: none; }
|
||
.cssd-picker .bar { position: relative; height: 12px; border-radius: 6px; cursor: pointer; }
|
||
.cssd-picker .bar i { top: 50%; }
|
||
.cssd-picker .hue { background: linear-gradient(to right, red, #ff0, lime, cyan, blue, #f0f, red); }
|
||
.cssd-picker .alpha { background-image: linear-gradient(45deg, #bbb 25%, transparent 25%, transparent 75%, #bbb 75%), linear-gradient(45deg, #bbb 25%, #fff 25%, #fff 75%, #bbb 75%); background-size: 8px 8px; background-position: 0 0, 4px 4px; }
|
||
.cssd-picker .alpha > b { position: absolute; inset: 0; border-radius: 6px; }
|
||
.cssd-picker .fmts { display: flex; gap: 2px; }
|
||
.cssd-picker .sws { display: flex; flex-wrap: wrap; gap: 3px; max-height: 92px; overflow: auto; }
|
||
.cssd-picker .sws .cssd-sw { width: 16px; height: 16px; }
|
||
.cssd-picker .lbl { font-size: 10px; text-transform: uppercase; color: var(--text-2); letter-spacing: .05em; }
|
||
`;
|
||
|
||
function addStyle() {
|
||
if (document.getElementById('cssd-style')) return;
|
||
document.head.append(el('style', { id: 'cssd-style' }, STYLE));
|
||
}
|
||
|
||
/** every property name the browser knows (and the usual shorthands), for completion */
|
||
let propertyNames = null;
|
||
function properties() {
|
||
if (propertyNames) return propertyNames;
|
||
const set = new Set(SHORTHANDS);
|
||
try { for (const p of getComputedStyle(document.documentElement)) if (!p.startsWith('-webkit-') || p === '-webkit-line-clamp') set.add(p); } catch { /* no DOM */ }
|
||
propertyNames = [...set].sort();
|
||
return propertyNames;
|
||
}
|
||
|
||
/** the keywords that make sense for a property (asked to the browser) */
|
||
function keywordsOf(prop) {
|
||
if (!globalThis.CSS?.supports || prop.startsWith('--') || prop.startsWith('$')) return [];
|
||
return KEYWORDS.filter((k) => { try { return CSS.supports(prop, k); } catch { return false; } });
|
||
}
|
||
|
||
/** a small picture of a flex / grid alignment value */
|
||
function mini(kind, value) {
|
||
const xs = { start: [2, 7, 12], 'flex-start': [2, 7, 12], left: [2, 7, 12], center: [5, 10, 15], end: [8, 13, 18], 'flex-end': [8, 13, 18], right: [8, 13, 18],
|
||
'space-between': [1, 10, 19], 'space-around': [3, 10, 17], 'space-evenly': [4.5, 10, 15.5], stretch: [1, 8, 15], normal: [2, 7, 12] };
|
||
const rects = [];
|
||
if (kind === 'justify') {
|
||
const w = value === 'stretch' ? 6 : 4;
|
||
for (const x of xs[value] || xs.start) rects.push([x, 3, w, 8]);
|
||
} else if (kind === 'align') {
|
||
const ys = { start: [1, 1, 1], 'flex-start': [1, 1, 1], center: [4, 3, 5], end: [7, 5, 9], 'flex-end': [7, 5, 9], stretch: [1, 1, 1], baseline: [3, 1, 4], normal: [1, 1, 1] };
|
||
const hs = value === 'stretch' || value === 'normal' ? [12, 12, 12] : [6, 8, 4];
|
||
(ys[value] || ys.start).forEach((y, i) => rects.push([2 + i * 7, y, 5, hs[i]]));
|
||
} else if (kind === 'direction') {
|
||
const col = /column/.test(value);
|
||
const rev = /reverse/.test(value);
|
||
const shades = rev ? [0.35, 0.6, 1] : [1, 0.6, 0.35];
|
||
for (let i = 0; i < 3; i++) rects.push(col ? [8, 1 + i * 4.3, 6, 3.3, shades[i]] : [2 + i * 7, 4, 5, 6, shades[i]]);
|
||
}
|
||
const svg = `<svg viewBox="0 0 24 14"><rect x=".5" y=".5" width="23" height="13" rx="2" fill="none" stroke="currentColor" stroke-opacity=".35"/>${rects.map(([x, y, w, h, o = 1]) => `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="1" fill="currentColor" fill-opacity="${o}"/>`).join('')}</svg>`;
|
||
const span = el('span');
|
||
span.innerHTML = svg;
|
||
return span;
|
||
}
|
||
|
||
export class CssDesigner {
|
||
/**
|
||
* @param {HTMLElement} host
|
||
* @param {{model: object, monaco: object, path: string, scss?: boolean, layout?: 'full'|'side'|'preview', editor?: object,
|
||
* readText: (p: string) => Promise<?string>, readDataUrl: (p: string) => Promise<?string>, htmlFiles: () => string[],
|
||
* compile?: (text: string) => Promise<object>, reveal?: (offset: number) => void, readOnly?: boolean}} o
|
||
*/
|
||
constructor(host, o) {
|
||
addStyle();
|
||
this.o = o;
|
||
this.scss = !!o.scss;
|
||
this.layout = o.layout || 'full';
|
||
this.filter = '';
|
||
this.matching = null; // a clicked element of the preview: {label, chain, ids}
|
||
this.compiled = null; // SCSS: the CSS of the last good compile
|
||
this.problems = []; // SCSS: Sass's errors / warnings
|
||
this.compiling = false;
|
||
this.showPreview = this.layout === 'preview' || (this.layout === 'full' ? prefs.get('cssDesignPreview', true) : prefs.get('cssSplitPreview', false));
|
||
this.node = el('div.cssd');
|
||
this.msgs = el('div.cssd-msgs');
|
||
this.rulesNode = el('div.cssd-rules');
|
||
this.insp = el('div.cssd-insp');
|
||
this.prevNode = el('div.cssd-prev');
|
||
this.node.append(this.msgs, this.rulesNode, this.insp, this.prevNode);
|
||
this.node.addEventListener('keydown', (e) => this.keys(e));
|
||
host.append(this.node);
|
||
this.resize = new ResizeObserver(() => this.fitLayout());
|
||
this.resize.observe(this.node);
|
||
this.parse();
|
||
const first = outline(this.parsed).find((x) => x.node.type === 'rule');
|
||
const saved = prefs.get('cssSel:' + o.path, null);
|
||
const again = saved ? findByPath(this.parsed, saved.path, saved.label) : null;
|
||
this.select(again || first?.node || null, { quiet: true });
|
||
this.sub = o.model.onDidChangeContent(() => this.changedSoon());
|
||
this.changedSoon = debounce(() => this.changed(), 90);
|
||
if (o.editor) this.cursorSub = o.editor.onDidChangeCursorPosition((e) => this.followCursor(e));
|
||
this.compileSoon = debounce(() => this.compile(), 700);
|
||
this.makePreview();
|
||
this.render();
|
||
if (this.scss) this.compile();
|
||
scanProject().then((r) => { this.palette = r.colors; this.projectVars = r.vars; this.renderInspector(); }, () => {});
|
||
this.loadFonts();
|
||
}
|
||
|
||
destroy() {
|
||
this.sub?.dispose();
|
||
this.cursorSub?.dispose();
|
||
this.resize.disconnect();
|
||
this.preview?.destroy();
|
||
this.closePicker();
|
||
this.node.remove();
|
||
}
|
||
|
||
fitLayout() {
|
||
const w = this.node.clientWidth;
|
||
this.node.classList.toggle('narrow', this.layout !== 'preview' && w > 0 && w < 560);
|
||
this.node.classList.toggle('no-preview', !this.showPreview && this.layout !== 'preview');
|
||
this.node.classList.toggle('only-preview', this.layout === 'preview');
|
||
if (this.layout === 'side' && w && this.showPreview) this.node.style.setProperty('--cssd-insp', Math.max(260, Math.min(360, w * 0.36)) + 'px');
|
||
}
|
||
|
||
// the text ----------------------------------------------------------------------------------------------------------
|
||
|
||
text() { return this.o.model.getValue(); }
|
||
|
||
parse() {
|
||
this.version = this.o.model.getVersionId();
|
||
this.parsed = parseStylesheet(this.text(), { scss: this.scss });
|
||
this.vars = variablesOf(this.parsed);
|
||
}
|
||
|
||
/** the text changed (here or in the code): parsed again, the same rule kept selected, everything drawn again */
|
||
changed() {
|
||
if (this.version === this.o.model.getVersionId()) return;
|
||
const path = this.selected ? pathOf(this.selected) : null;
|
||
const label = this.selected ? labelOf(this.selected) : null;
|
||
const wasRoot = this.selected?.type === 'root';
|
||
this.parse();
|
||
this.selected = wasRoot ? this.parsed.root : path ? findByPath(this.parsed, path, label) || findByPath(this.parsed, path) : null;
|
||
this.render();
|
||
if (this.scss) this.compileSoon();
|
||
this.previewSoon();
|
||
}
|
||
|
||
/**
|
||
* One edit of the text as one step of Ctrl+Z (merge: part of the same gesture as the edit before it, a drag or a colour
|
||
* being picked: one step for all).
|
||
*/
|
||
apply(edit, merge = false) {
|
||
if (!edit || this.o.readOnly) return;
|
||
const m = this.o.model;
|
||
const a = m.getPositionAt(edit.start);
|
||
const b = m.getPositionAt(edit.end);
|
||
if (!merge) m.pushStackElement();
|
||
m.pushEditOperations([], [{ range: { startLineNumber: a.lineNumber, startColumn: a.column, endLineNumber: b.lineNumber, endColumn: b.column }, text: edit.text }], () => null);
|
||
if (!merge) m.pushStackElement();
|
||
this.changedNow();
|
||
}
|
||
|
||
/** after an edit made here: parsed at once (the next edit needs the new positions), drawn again keeping the focus */
|
||
changedNow() {
|
||
this.changedSoon.cancel();
|
||
this.changed();
|
||
}
|
||
|
||
keys(e) {
|
||
const inInput = /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName);
|
||
const mod = e.ctrlKey || e.metaKey;
|
||
if (mod && !inInput && e.key.toLowerCase() === 'z') { e.preventDefault(); (e.shiftKey ? this.o.model.redo() : this.o.model.undo()); this.changedNow(); }
|
||
else if (mod && !inInput && e.key.toLowerCase() === 'y') { e.preventDefault(); this.o.model.redo(); this.changedNow(); }
|
||
else if (!inInput && (e.key === 'Delete') && this.selected && this.selected.type !== 'root') { e.preventDefault(); this.remove(); }
|
||
else if (!inInput && e.altKey && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) { e.preventDefault(); this.move(e.key === 'ArrowUp' ? -1 : 1); }
|
||
}
|
||
|
||
// selection -----------------------------------------------------------------------------------------------------------
|
||
|
||
select(node, { quiet = false, reveal = true } = {}) {
|
||
this.selected = node;
|
||
if (node && node.type !== 'root') prefs.set('cssSel:' + this.o.path, { path: pathOf(node), label: labelOf(node) });
|
||
if (quiet) return;
|
||
this.render();
|
||
this.highlight(true);
|
||
if (reveal && node && this.o.editor && node.type !== 'root') {
|
||
const pos = this.o.model.getPositionAt(node.start);
|
||
this.ignoreCursor = true;
|
||
this.o.editor.revealLineInCenterIfOutsideViewport(pos.lineNumber);
|
||
this.o.editor.setPosition(pos);
|
||
setTimeout(() => { this.ignoreCursor = false; }, 50);
|
||
}
|
||
}
|
||
|
||
/** Split: the rule under the cursor of the code becomes the selected one */
|
||
followCursor(e) {
|
||
if (this.ignoreCursor || !this.o.editor.hasTextFocus()) return;
|
||
const node = blockAt(this.parsed, this.o.model.getOffsetAt(e.position));
|
||
if (node && node !== this.selected) {
|
||
this.selected = node;
|
||
this.render();
|
||
this.highlight(true);
|
||
}
|
||
}
|
||
|
||
/** the selected rule's selector for the preview (SCSS nesting resolved, pseudo-states taken away) */
|
||
selectorOf(node) {
|
||
if (!node || node.type !== 'rule') return '';
|
||
const full = resolvedSelector(node);
|
||
return full ? matchableSelector(full) : '';
|
||
}
|
||
|
||
// the rules panel ---------------------------------------------------------------------------------------------------
|
||
|
||
render() {
|
||
this.fitLayout();
|
||
this.renderMessages();
|
||
if (this.layout === 'preview') return;
|
||
this.renderRules();
|
||
this.renderInspector();
|
||
}
|
||
|
||
renderMessages() {
|
||
const items = [];
|
||
const text = this.parsed.text;
|
||
for (const e of this.parsed.errors.slice(0, 20)) {
|
||
const at = lineCol(text, e.offset);
|
||
items.push(el('div.cssd-msg', { title: t('Show it in the code'), onclick: () => this.o.reveal?.(e.offset) }, el('b', {}, t('Line {line}', { line: at.line })), t(e.message)));
|
||
}
|
||
for (const p of this.problems.slice(0, 20)) {
|
||
items.push(el(`div.cssd-msg${p.severity === 'error' ? '' : '.warn'}`, { title: t('Show it in the code'), onclick: () => this.o.reveal?.(this.o.model.getOffsetAt({ lineNumber: p.line, column: p.col })) },
|
||
el('b', {}, `Sass · ${t('Line {line}', { line: p.line })}`), p.message));
|
||
}
|
||
if (this.compileError) items.push(el('div.cssd-msg.warn', {}, el('b', {}, 'Sass'), this.compileError));
|
||
this.msgs.replaceChildren(...items);
|
||
}
|
||
|
||
renderRules() {
|
||
const keep = this.rulesNode.querySelector('.cssd-list')?.scrollTop || 0;
|
||
const focusSearch = document.activeElement === this.search;
|
||
const caret = focusSearch ? this.search.selectionStart : 0;
|
||
const list = el('div.cssd-list');
|
||
this.search = el('input.cssd-in', { type: 'search', placeholder: t('Filter selectors'), value: this.filter, spellcheck: false,
|
||
oninput: (e) => { this.filter = e.target.value; this.renderRules(); } });
|
||
const sel = this.selected;
|
||
const isBlock = sel && sel.type !== 'root';
|
||
const tools = el('div.cssd-tools', {}, this.search,
|
||
el('button.cssd-b', { title: t('Add a rule'), onclick: () => this.addRule() }, icon('plus')),
|
||
el('button.cssd-b', { title: t('Duplicate'), disabled: !isBlock, onclick: () => this.duplicate() }, icon('copy')),
|
||
el('button.cssd-b', { title: t('Delete') + ' (Del)', disabled: !isBlock, onclick: () => this.remove() }, icon('trash')),
|
||
el('button.cssd-b', { title: t('Move up') + ' (Alt+↑)', disabled: !isBlock, onclick: () => this.move(-1) }, '↑'),
|
||
el('button.cssd-b', { title: t('Move down') + ' (Alt+↓)', disabled: !isBlock, onclick: () => this.move(1) }, '↓'),
|
||
this.layout !== 'preview' ? el(`button.cssd-b${this.showPreview ? '.on' : ''}`, { title: t('Show the preview'), onclick: () => this.togglePreview() }, icon('eye')) : null);
|
||
const filter = this.filter.trim().toLowerCase();
|
||
const rows = outline(this.parsed);
|
||
const matchIds = this.matching ? new Set(this.matching.ids) : null;
|
||
if (this.matching) {
|
||
// the rules a clicked element matches, the one that wins first (specificity, then the later one)
|
||
const matched = rows.filter((r, i) => matchIds.has(i)).map((r) => ({ ...r, spec: maxMatching(r.node, this.matching) }));
|
||
matched.sort((a, b) => b.spec[0] - a.spec[0] || b.spec[1] - a.spec[1] || b.spec[2] - a.spec[2] || b.node.start - a.node.start);
|
||
list.append(el('div.cssd-match', {},
|
||
el('div', {}, el('b', {}, t('Rules for {element}', { element: this.matching.label })), ' ', el('button.cssd-b', { title: t('Show every rule'), onclick: () => { this.matching = null; this.renderRules(); } }, '✕')),
|
||
el('div.cssd-chain', {}, this.matching.chain.join(' › ')),
|
||
matched.length ? null : el('div.cssd-count', {}, t('No rule of this file applies to it.'))));
|
||
for (const r of matched) list.append(this.ruleRow(r.node, 0, r.spec));
|
||
} else {
|
||
list.append(el('div.cssd-row' + (sel?.type === 'root' ? '.on' : ''), { onclick: () => this.select(this.parsed.root) },
|
||
el('span.cssd-kind', {}, '⌂'), el('span.cssd-sel', {}, this.scss ? t('File (variables, @use)') : t('File'))));
|
||
for (const r of rows) {
|
||
if (filter && !labelOf(r.node).toLowerCase().includes(filter) && !(resolvedSelector(r.node) || '').toLowerCase().includes(filter)) continue;
|
||
list.append(this.ruleRow(r.node, filter ? 0 : r.depth, null));
|
||
}
|
||
}
|
||
// variables of the file
|
||
const varRows = [];
|
||
for (const node of walk(this.parsed.root)) {
|
||
if (node.type !== 'decl' || !(node.prop.startsWith('--') || node.prop.startsWith('$'))) continue;
|
||
if (filter && !node.prop.toLowerCase().includes(filter)) continue;
|
||
const color = resolveColor(node.value, this.vars);
|
||
varRows.push(el('div.cssd-row', { title: node.value, onclick: () => this.select(node.parent.type === 'root' ? this.parsed.root : node.parent) },
|
||
color ? swatch(color) : el('span.cssd-kind', {}, node.prop[0]), el('span.cssd-sel', {}, node.prop), el('span.cssd-n', {}, shorten(node.value, 22))));
|
||
}
|
||
const vars = varRows.length ? el('div.cssd-vars', {}, el('div.cssd-h', {}, t('Variables'), el('span.cssd-n', {}, String(varRows.length))), ...varRows) : null;
|
||
this.rulesNode.replaceChildren(tools, list, ...(vars ? [vars] : []));
|
||
list.scrollTop = keep;
|
||
if (focusSearch) { this.search.focus(); this.search.setSelectionRange(caret, caret); }
|
||
// a rule selected elsewhere (the code, the preview): its row comes into view
|
||
if (this.scrolledTo !== sel) { this.scrolledTo = sel; requestAnimationFrame(() => list.querySelector('.cssd-row.on')?.scrollIntoView({ block: 'nearest' })); }
|
||
}
|
||
|
||
ruleRow(node, depth, spec) {
|
||
const kind = node.type === 'rule' ? (node.selector.startsWith('%') ? '%' : '{}') : { media: '@m', supports: '@s', container: '@c', layer: '@l', 'font-face': 'Aa',
|
||
keyframes: '⏱', import: '⇣', use: '⇣', forward: '⇢', mixin: 'ƒ', include: '+', function: 'ƒ', 'at-root': '⤒', each: '∀', for: '∀', if: '?', else: '?' }[node.name] || '@';
|
||
const count = declarations(node).length;
|
||
const rowSpec = spec || (node.type === 'rule' && resolvedSelector(node) ? maxSpecificity(resolvedSelector(node)) : null);
|
||
return el(`div.cssd-row${node === this.selected ? '.on' : ''}${node.type === 'atrule' ? '.at' : ''}${this.matching ? '.match' : ''}`, {
|
||
style: { paddingLeft: 8 + depth * 14 + 'px' }, title: (resolvedSelector(node) || labelOf(node)) + (contextOf(node).length ? '\n' + contextOf(node).join('\n') : ''),
|
||
onclick: () => this.select(node),
|
||
}, el('span.cssd-kind', {}, kind), el('span.cssd-sel', {}, labelOf(node)),
|
||
el('span.cssd-n', {}, spec ? spec.join(',') : count ? String(count) : rowSpec && this.filter ? rowSpec.join(',') : ''));
|
||
}
|
||
|
||
togglePreview() {
|
||
this.showPreview = !this.showPreview;
|
||
prefs.set(this.layout === 'full' ? 'cssDesignPreview' : 'cssSplitPreview', this.showPreview);
|
||
this.makePreview();
|
||
this.render();
|
||
}
|
||
|
||
addRule() {
|
||
const sel = this.selected;
|
||
const base = sel?.type === 'rule' ? (this.scss ? '&__new' : `${splitList(sel.selector)[0]} .new`) : '.new-rule';
|
||
const name = prompt(t('Selector of the new rule'), base);
|
||
if (!name || /[{}]/.test(name)) return;
|
||
// SCSS: "&..." goes inside the selected rule; otherwise after the selected block, or at the end
|
||
const inside = this.scss && sel?.type === 'rule' && name.includes('&');
|
||
const edit = inside ? insertRule(this.text(), name, null, sel) : insertRule(this.text(), name, sel && sel.type !== 'root' ? topOf(sel) : null);
|
||
this.apply(edit);
|
||
const offset = edit.start + edit.text.indexOf(name.trim());
|
||
const node = outline(this.parsed).map((o) => o.node).find((n) => n.start === offset) || blockAt(this.parsed, offset);
|
||
if (node) this.select(node);
|
||
}
|
||
|
||
duplicate() {
|
||
if (!this.selected || this.selected.type === 'root') return;
|
||
const edit = duplicateNode(this.text(), this.selected);
|
||
this.apply(edit);
|
||
const offset = edit.start + edit.text.length - (this.selected.end - this.selected.start);
|
||
this.select(outline(this.parsed).map((o) => o.node).find((n) => n.start === offset) || this.selected);
|
||
}
|
||
|
||
remove() {
|
||
if (!this.selected || this.selected.type === 'root') return;
|
||
const parent = this.selected.parent;
|
||
const index = parent.children.indexOf(this.selected);
|
||
this.apply(removeNode(this.text(), this.selected));
|
||
const p = findByPath(this.parsed, pathOf(parent).length ? pathOf(parent) : []) || this.parsed.root;
|
||
const blocks = (p.children || this.parsed.root.children).filter((n) => n.type === 'rule' || n.type === 'atrule');
|
||
this.select(blocks.find((n) => p.children.indexOf(n) >= index) || blocks[blocks.length - 1] || (p.type === 'root' ? null : p));
|
||
}
|
||
|
||
move(direction) {
|
||
if (!this.selected || this.selected.type === 'root') return;
|
||
const edit = moveNode(this.text(), this.selected, direction);
|
||
if (!edit) return;
|
||
const length = this.selected.end - this.selected.start;
|
||
const offset = direction < 0 ? edit.start : edit.start + edit.text.length - length;
|
||
this.apply(edit);
|
||
this.select(outline(this.parsed).map((o) => o.node).find((n) => n.start === offset) || this.selected);
|
||
}
|
||
|
||
// the inspector -----------------------------------------------------------------------------------------------------
|
||
|
||
renderInspector() {
|
||
// the field being typed in keeps its focus and caret through the new drawing
|
||
const active = document.activeElement;
|
||
const key = this.insp.contains(active) ? active.dataset.key : null;
|
||
const caret = key && typeof active.selectionStart === 'number' ? [active.selectionStart, active.selectionEnd] : null;
|
||
const scroll = this.insp.scrollTop;
|
||
const block = this.selected;
|
||
if (!block) {
|
||
this.insp.replaceChildren(el('div.cssd-muted', {}, t('Choose a rule on the left, or add one.')));
|
||
return;
|
||
}
|
||
const parts = [this.header(block)];
|
||
if (block.type === 'atrule' && !block.children) {
|
||
parts.push(el('div.cssd-muted', {}, t('This statement has no declarations: edit its text in the code.')));
|
||
} else {
|
||
const decls = declarations(block);
|
||
const isFrames = block.type === 'atrule' && /keyframes$/.test(block.name);
|
||
const varDecls = decls.filter((d) => d.prop.startsWith('--') || d.prop.startsWith('$'));
|
||
if (varDecls.length || block.type === 'root' || block.selector === ':root') parts.push(this.section('vars', t('Variables'), varDecls.length, () => this.variablesBody(block, varDecls)));
|
||
if (block.type !== 'root' && !isFrames) {
|
||
for (const [id, title, props] of GROUPS) {
|
||
const count = decls.filter((d) => props.includes(d.prop.toLowerCase())).length;
|
||
parts.push(this.section(id, t(title), count, () => this[id + 'Body'](block)));
|
||
}
|
||
}
|
||
const others = decls.filter((d) => !COVERED.has(d.prop.toLowerCase()) && !d.prop.startsWith('--') && !d.prop.startsWith('$'));
|
||
if (block.type !== 'root') parts.push(this.section('other', t('Other declarations'), others.length, () => this.otherBody(block, others), true));
|
||
if (isFrames) parts.push(el('div.cssd-muted', {}, t('Select a frame (from, to, 50%...) on the left to edit it.')));
|
||
}
|
||
this.insp.replaceChildren(...parts);
|
||
this.insp.scrollTop = scroll;
|
||
if (key) {
|
||
const again = this.insp.querySelector(`[data-key="${CSS.escape(key)}"]`);
|
||
if (again) { again.focus(); if (caret && typeof again.setSelectionRange === 'function') try { again.setSelectionRange(...caret); } catch { /* not a text field */ } }
|
||
}
|
||
}
|
||
|
||
header(block) {
|
||
if (block.type === 'root') {
|
||
return el('div.cssd-head', {}, el('b', {}, this.scss ? t('File (variables, @use)') : t('File')), el('div.cssd-meta', {}, t('The variables written outside the rules.')));
|
||
}
|
||
const input = el('input.cssd-in.cssd-selector', { value: block.type === 'rule' ? block.selector : labelOf(block), spellcheck: false, dataset: { key: '@selector' },
|
||
title: t('Press Enter to rename'),
|
||
onkeydown: (e) => {
|
||
if (e.key === 'Enter') { e.preventDefault(); const v = e.target.value.trim(); if (v && !/[{};]/.test(v) && v !== labelOf(block)) this.apply(setSelector(block, v)); }
|
||
if (e.key === 'Escape') e.target.value = block.type === 'rule' ? block.selector : labelOf(block);
|
||
} });
|
||
const meta = [];
|
||
const full = resolvedSelector(block);
|
||
if (block.type === 'rule' && full) {
|
||
const specs = splitList(full).map((s) => [s, specificity(s)]);
|
||
meta.push(el('span', { title: t('Specificity (ids, classes, elements)') }, t('Specificity'), ' ', ...specs.slice(0, 4).map(([s, sp]) => el('span.cssd-spec', { title: s }, sp.join(',')))));
|
||
if (this.scss && full !== block.selector) meta.push(el('span', { title: full, style: { fontFamily: 'var(--mono)' } }, '→ ' + shorten(full, 60)));
|
||
if (this.showPreview) meta.push(this.countNode = el('span.cssd-count', {}, this.lastCount === undefined ? '' : t('Matched in the preview: {n}', { n: this.lastCount })));
|
||
}
|
||
const at = lineCol(this.parsed.text, block.start);
|
||
meta.push(el('span', {}, t('Line {line}', { line: at.line })));
|
||
const ctx = contextOf(block);
|
||
return el('div.cssd-head', {}, input, ctx.length ? el('div.cssd-ctx', {}, ctx.join(' › ')) : null, el('div.cssd-meta', {}, ...meta));
|
||
}
|
||
|
||
section(id, title, count, body, closedByDefault = false) {
|
||
const open = prefs.get('cssdOpen:' + id, !closedByDefault);
|
||
const details = el('details.cssd-sec', { open }, el('summary', {}, title, count ? el('span.cssd-count', {}, String(count)) : null));
|
||
let filled = false;
|
||
const fill = () => { if (!filled && details.open) { filled = true; details.append(el('div.cssd-body', {}, ...[body()].flat().filter(Boolean))); } };
|
||
details.addEventListener('toggle', () => { prefs.set('cssdOpen:' + id, details.open); fill(); });
|
||
fill();
|
||
return details;
|
||
}
|
||
|
||
// reading and writing declarations of the selected block
|
||
get(block, prop) { return declarationOf(block, prop); }
|
||
value(block, prop) { return this.get(block, prop)?.value ?? ''; }
|
||
|
||
set(block, prop, value, { merge = false, important } = {}) {
|
||
const v = value === null || value === undefined ? null : String(value).trim();
|
||
if (v === '' || v === null) {
|
||
if (!this.get(block, prop)) return;
|
||
this.apply(setDeclaration(this.text(), block, prop, null), merge);
|
||
} else if (block.type === 'root' && !this.get(block, prop)) {
|
||
// a new variable of the file: after the last one, else after @use / @import, else at the top
|
||
const text = this.text();
|
||
const last = [...block.children].reverse().find((n) => n.type === 'decl' || (n.type === 'atrule' && !n.children && ['use', 'forward', 'import', 'charset'].includes(n.name)));
|
||
this.apply(last ? { start: last.end, end: last.end, text: `\n${prop}: ${v};` } : { start: 0, end: 0, text: `${prop}: ${v};\n${text.startsWith('\n') ? '' : '\n'}` }, merge);
|
||
} else {
|
||
const edit = setDeclaration(this.text(), block, prop, v, important);
|
||
if (edit && this.text().slice(edit.start, edit.end) === edit.text) return;
|
||
this.apply(edit, merge);
|
||
}
|
||
this.highlight(false);
|
||
}
|
||
|
||
/** the selected block as it is now (after an edit, `this.selected` is the new parse's node) */
|
||
get block() { return this.selected; }
|
||
|
||
/** a labelled field: [label, control, !important toggle, ✕] */
|
||
field(block, prop, control, { label = prop, num = false } = {}) {
|
||
const decl = this.get(block, prop);
|
||
const lab = el('label', { title: prop }, label);
|
||
if (num) this.dragNumber(lab, () => this.block, prop);
|
||
const tools = el('span.cssd-x', {},
|
||
decl ? el(`button.cssd-b.cssd-imp${decl.important ? '.on' : ''}`, { title: '!important', onclick: () => this.set(this.block, prop, decl.value, { important: !decl.important }) }, '!') : null,
|
||
decl ? el('button.cssd-b', { title: t('Remove {name}', { name: prop }), onclick: () => this.set(this.block, prop, null) }, '✕') : null);
|
||
return el(`div.cssd-f${decl ? '.set' : ''}${num ? '.num' : ''}`, {}, lab, control, tools);
|
||
}
|
||
|
||
/** a free text field (completion of the property's keywords and of the variables) */
|
||
textInput(block, prop, { placeholder = '', list = null } = {}) {
|
||
const decl = this.get(block, prop);
|
||
const id = 'cssd-dl-' + prop.replace(/[^\w-]/g, '_');
|
||
const input = el('input.cssd-in', { value: decl?.value ?? '', placeholder, spellcheck: false, dataset: { key: prop }, list: id,
|
||
onfocus: () => this.datalist(id, list || [...keywordsOf(prop), ...this.varNames()]),
|
||
onkeydown: (e) => { if (e.key === 'Enter') { e.preventDefault(); this.set(this.block, prop, e.target.value); } if (e.key === 'ArrowUp' || e.key === 'ArrowDown') this.step(e, prop); },
|
||
onchange: (e) => this.set(this.block, prop, e.target.value) });
|
||
input.setAttribute('list', id);
|
||
return input;
|
||
}
|
||
|
||
numberField(block, prop, label = prop, placeholder = '') {
|
||
return this.field(block, prop, this.textInput(block, prop, { placeholder }), { label, num: true });
|
||
}
|
||
|
||
selectField(block, prop, options, label = prop) {
|
||
const value = this.value(block, prop);
|
||
const select = el('select.cssd-in', { dataset: { key: prop }, onchange: (e) => this.set(this.block, prop, e.target.value) },
|
||
el('option', { value: '' }, '—'), ...options.map((o) => el('option', { value: o, selected: o === value }, o)),
|
||
value && !options.includes(value) ? el('option', { value, selected: true }, value) : null);
|
||
return this.field(block, prop, select, { label });
|
||
}
|
||
|
||
/** buttons for the values of a property (a picture each for flex alignment) */
|
||
segField(block, prop, options, { label = prop, pictures = null } = {}) {
|
||
const value = this.value(block, prop);
|
||
const seg = el('div.cssd-seg', {}, options.map((o) => el(`button.cssd-b${o === value ? '.on' : ''}`, { title: o, onclick: () => this.set(this.block, prop, o === value ? null : o) },
|
||
pictures ? mini(pictures, o) : o)));
|
||
return this.field(block, prop, seg, { label });
|
||
}
|
||
|
||
colorField(block, prop, label = prop) {
|
||
const decl = this.get(block, prop);
|
||
const input = this.textInput(block, prop, { list: [...this.colorVarNames(), 'transparent', 'currentColor', ...Object.keys(NAMED_COLORS)] });
|
||
const color = decl ? resolveColor(decl.value, this.vars) || resolveColor(decl.value, this.allVars()) : null;
|
||
const sw = swatch(color);
|
||
sw.title = t('Choose a colour');
|
||
sw.onclick = () => this.openPicker(sw, decl?.value || '', (v, merge) => this.set(this.block, prop, v, { merge }));
|
||
return this.field(block, prop, el('div.cssd-color', {}, sw, input), { label });
|
||
}
|
||
|
||
/** arrows in a number field: +1 / -1 (Shift: 10, Alt: 0.1), the unit kept */
|
||
step(e, prop) {
|
||
const n = parseNumber(e.target.value);
|
||
if (!n) return;
|
||
e.preventDefault();
|
||
const d = (e.key === 'ArrowUp' ? 1 : -1) * (e.shiftKey ? 10 : e.altKey ? 0.1 : 1);
|
||
const v = formatNumber(n.number + d) + n.unit;
|
||
e.target.value = v;
|
||
this.set(this.block, prop, v, { merge: true });
|
||
}
|
||
|
||
/** a label dragged sideways changes the number of its field (Shift: x10, Alt: x0.1); one undo step for the whole drag */
|
||
dragNumber(label, block, prop, read = null, write = null) {
|
||
label.addEventListener('mousedown', (e) => {
|
||
if (e.button !== 0) return;
|
||
e.preventDefault();
|
||
const current = read ? read() : this.value(block(), prop);
|
||
const n = parseNumber(current || '0') || { number: 0, unit: '' };
|
||
const unit = n.unit || (UNITLESS.has(prop) || prop.startsWith('--') ? '' : 'px');
|
||
const x0 = e.clientX;
|
||
let first = true;
|
||
const move = (ev) => {
|
||
const k = ev.shiftKey ? 10 : ev.altKey ? 0.1 : unit === 'em' || unit === 'rem' || UNITLESS.has(prop) && prop !== 'z-index' && prop !== 'order' ? 0.05 : 1;
|
||
const v = formatNumber(n.number + Math.round((ev.clientX - x0) / 2) * k) + unit;
|
||
if (write) write(v, !first); else this.set(block(), prop, v, { merge: !first });
|
||
first = false;
|
||
};
|
||
const up = () => { removeEventListener('mousemove', move); removeEventListener('mouseup', up); this.o.model.pushStackElement(); };
|
||
addEventListener('mousemove', move);
|
||
addEventListener('mouseup', up);
|
||
});
|
||
}
|
||
|
||
datalist(id, values) {
|
||
let list = document.getElementById(id);
|
||
if (!list) { list = el('datalist', { id }); this.node.append(list); }
|
||
list.replaceChildren(...[...new Set(values)].slice(0, 400).map((v) => el('option', { value: v })));
|
||
}
|
||
|
||
varNames() {
|
||
return [...this.allVars().keys()].map((k) => (k.startsWith('--') ? `var(${k})` : k));
|
||
}
|
||
|
||
colorVarNames() {
|
||
const all = this.allVars();
|
||
return [...all].filter(([, v]) => resolveColor(v, all)).map(([k]) => (k.startsWith('--') ? `var(${k})` : k));
|
||
}
|
||
|
||
allVars() { return new Map([...(this.projectVars || []), ...this.vars]); }
|
||
|
||
// the groups ----------------------------------------------------------------------------------------------------------
|
||
|
||
variablesBody(block, decls) {
|
||
const rows = decls.map((d) => {
|
||
const color = resolveColor(d.value, this.allVars());
|
||
const input = el('input.cssd-in', { value: d.value, spellcheck: false, dataset: { key: d.prop },
|
||
onkeydown: (e) => { if (e.key === 'Enter') { e.preventDefault(); this.set(this.block, d.prop, e.target.value); } },
|
||
onchange: (e) => this.set(this.block, d.prop, e.target.value) });
|
||
const sw = color ? swatch(color) : null;
|
||
if (sw) sw.onclick = () => this.openPicker(sw, d.value, (v, merge) => this.set(this.block, d.prop, v, { merge }));
|
||
const lab = el('label', { title: d.prop }, d.prop);
|
||
if (parseNumber(d.value)) this.dragNumber(lab, () => this.block, d.prop);
|
||
return el(`div.cssd-f.set${parseNumber(d.value) ? '.num' : ''}`, {}, lab, sw ? el('div.cssd-color', {}, sw, input) : input,
|
||
el('span.cssd-x', {}, el('button.cssd-b', { title: t('Remove {name}', { name: d.prop }), onclick: () => this.set(this.block, d.prop, null) }, '✕')));
|
||
});
|
||
const prefix = this.scss && (block.type === 'root' || block.selector !== ':root') ? '$' : '--';
|
||
rows.push(this.addRow(block, prefix === '$' ? '$name' : '--name', prefix));
|
||
return rows;
|
||
}
|
||
|
||
layoutBody(block) {
|
||
const display = this.value(block, 'display');
|
||
const out = [this.segField(block, 'display', ['block', 'flex', 'grid', 'inline', 'inline-block', 'inline-flex', 'none', 'contents'])];
|
||
if (/flex/.test(display)) {
|
||
out.push(this.segField(block, 'flex-direction', ['row', 'column', 'row-reverse', 'column-reverse'], { label: 'direction', pictures: 'direction' }));
|
||
out.push(this.segField(block, 'flex-wrap', ['nowrap', 'wrap', 'wrap-reverse'], { label: 'wrap' }));
|
||
out.push(this.segField(block, 'justify-content', ['flex-start', 'center', 'flex-end', 'space-between', 'space-around', 'space-evenly'], { label: 'justify', pictures: 'justify' }));
|
||
out.push(this.segField(block, 'align-items', ['stretch', 'flex-start', 'center', 'flex-end', 'baseline'], { label: 'align', pictures: 'align' }));
|
||
out.push(this.numberField(block, 'gap', 'gap', '0'));
|
||
} else if (/grid/.test(display)) {
|
||
const cols = this.value(block, 'grid-template-columns');
|
||
const presets = el('div.cssd-seg', {}, [['1', '1fr'], ['2', 'repeat(2, 1fr)'], ['3', 'repeat(3, 1fr)'], ['4', 'repeat(4, 1fr)'], ['1:2', '1fr 2fr'], ['auto', 'repeat(auto-fill, minmax(200px, 1fr))']]
|
||
.map(([l, v]) => el(`button.cssd-b${cols === v ? '.on' : ''}`, { title: v, onclick: () => this.set(this.block, 'grid-template-columns', v) }, l)));
|
||
out.push(this.field(block, 'grid-template-columns', el('div', { style: { display: 'flex', flexDirection: 'column', gap: '3px' } },
|
||
this.textInput(block, 'grid-template-columns', { placeholder: '1fr 1fr' }), presets, tracks(cols)), { label: 'columns' }));
|
||
out.push(this.field(block, 'grid-template-rows', this.textInput(block, 'grid-template-rows', { placeholder: 'auto' }), { label: 'rows' }));
|
||
out.push(this.segField(block, 'grid-auto-flow', ['row', 'column', 'dense', 'row dense'], { label: 'auto-flow' }));
|
||
out.push(this.segField(block, 'justify-items', ['start', 'center', 'end', 'stretch'], { label: 'justify-items', pictures: 'justify' }));
|
||
out.push(this.segField(block, 'align-items', ['start', 'center', 'end', 'stretch'], { label: 'align-items', pictures: 'align' }));
|
||
out.push(this.numberField(block, 'gap', 'gap', '0'));
|
||
}
|
||
// a child of a flex / grid container
|
||
for (const p of ['flex', 'align-self', 'order', 'grid-column', 'grid-row']) if (this.get(block, p)) out.push(this.field(block, p, this.textInput(block, p), { num: p === 'order' }));
|
||
out.push(this.selectField(block, 'box-sizing', ['border-box', 'content-box']));
|
||
for (const p of ['float', 'clear', 'visibility']) if (this.get(block, p)) out.push(this.field(block, p, this.textInput(block, p)));
|
||
return out;
|
||
}
|
||
|
||
/** a side of margin / padding / border-width: its longhand, or its part of the shorthand */
|
||
sideValue(block, base, side, i) {
|
||
const long = base === 'border-width' ? `border-${side}-width` : `${base}-${side}`;
|
||
const d = this.get(block, long);
|
||
if (d) return { value: d.value, set: true };
|
||
const short = this.get(block, base);
|
||
if (short) return { value: expandBox(short.value)[i], set: true };
|
||
if (base === 'border-width') {
|
||
const border = this.get(block, 'border') || this.get(block, `border-${side}`);
|
||
const width = border && splitValue(border.value).find((x) => parseNumber(x) || /^(thin|medium|thick)$/.test(x));
|
||
if (width) return { value: width, set: false };
|
||
}
|
||
return { value: '', set: false };
|
||
}
|
||
|
||
setSide(base, side, i, value, merge = false) {
|
||
const block = this.block;
|
||
const long = base === 'border-width' ? `border-${side}-width` : `${base}-${side}`;
|
||
const short = this.get(block, base);
|
||
let v = String(value).trim();
|
||
if (parseNumber(v) && !parseNumber(v).unit && parseNumber(v).number !== 0) v += 'px';
|
||
if (short && !this.get(block, long) && splitValue(short.value).length <= 4) {
|
||
const sides = expandBox(short.value);
|
||
sides[i] = v || '0';
|
||
this.set(block, base, compactBox(sides), { merge });
|
||
} else {
|
||
this.set(block, long, v, { merge });
|
||
}
|
||
}
|
||
|
||
boxBody(block) {
|
||
const sides = ['top', 'right', 'bottom', 'left'];
|
||
const layer = (base, cls, tag, inner) => {
|
||
const node = el(`div.lay.${cls}`, {}, el('span.tag', {}, tag));
|
||
sides.forEach((side, i) => {
|
||
const cur = this.sideValue(block, base, side, i);
|
||
const input = el(`input.s-${side}${cur.set ? '.set' : ''}`, { value: cur.value, placeholder: '-', spellcheck: false, title: `${base} ${side}`, dataset: { key: `${base}:${side}` },
|
||
onkeydown: (e) => {
|
||
if (e.key === 'Enter') { e.preventDefault(); this.setSide(base, side, i, e.target.value); }
|
||
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
|
||
const n = parseNumber(e.target.value || '0');
|
||
if (!n) return;
|
||
e.preventDefault();
|
||
const v = formatNumber(n.number + (e.key === 'ArrowUp' ? 1 : -1) * (e.shiftKey ? 10 : 1)) + (n.unit || (n.number ? '' : 'px'));
|
||
e.target.value = v;
|
||
this.setSide(base, side, i, v, true);
|
||
}
|
||
},
|
||
onchange: (e) => this.setSide(base, side, i, e.target.value) });
|
||
node.append(input);
|
||
});
|
||
node.append(inner);
|
||
return node;
|
||
};
|
||
const w = this.value(block, 'width') || 'auto';
|
||
const h = this.value(block, 'height') || 'auto';
|
||
const model = el('div.cssd-boxm', {}, layer('margin', 'm', 'margin', layer('border-width', 'b', 'border', layer('padding', 'p', 'padding', el('div.c', {}, `${shorten(w, 10)} × ${shorten(h, 10)}`)))));
|
||
const radius = this.value(block, 'border-radius');
|
||
const corners = expandBox(radius);
|
||
const corner = (i, title) => el('input.cssd-in', { value: this.get(block, 'border-radius') ? corners[i] : '', placeholder: '0', title, dataset: { key: 'radius:' + i },
|
||
onchange: (e) => { const c = expandBox(radius || '0'); let v = e.target.value.trim() || '0'; if (parseNumber(v) && !parseNumber(v).unit && v !== '0') v += 'px'; c[i] = v; this.set(this.block, 'border-radius', compactBox(c)); } });
|
||
const shape = el('div.shape', { style: { borderRadius: radius ? radius.replace(/\$[\w-]+|var\([^)]*\)/g, '6px') : '0' } });
|
||
const radiusGrid = el('div.cssd-radius', {}, corner(0, 'top left'), el('span'), corner(1, 'top right'), el('span'), shape, el('span'), corner(3, 'bottom left'), el('span'), corner(2, 'bottom right'));
|
||
return [model,
|
||
this.numberField(block, 'border-radius', 'radius', '0'), radiusGrid,
|
||
this.field(block, 'border', this.textInput(block, 'border', { placeholder: '1px solid #ccc' })),
|
||
this.segField(block, 'border-style', ['solid', 'dashed', 'dotted', 'double', 'none'], { label: 'style' }),
|
||
this.colorField(block, 'border-color', 'border colour'),
|
||
this.field(block, 'outline', this.textInput(block, 'outline', { placeholder: 'none' }))];
|
||
}
|
||
|
||
sizeBody(block) {
|
||
return [...['width', 'height', 'min-width', 'max-width', 'min-height', 'max-height'].map((p) => this.numberField(block, p, p, 'auto')),
|
||
this.field(block, 'aspect-ratio', this.textInput(block, 'aspect-ratio', { placeholder: 'auto', list: ['auto', '1', '1 / 1', '4 / 3', '16 / 9', '3 / 2', '9 / 16'] })),
|
||
this.segField(block, 'overflow', ['visible', 'hidden', 'auto', 'scroll', 'clip']),
|
||
this.get(block, 'object-fit') || /img|video|picture/.test(block.selector || '') ? this.segField(block, 'object-fit', ['fill', 'contain', 'cover', 'none', 'scale-down']) : null].filter(Boolean);
|
||
}
|
||
|
||
positionBody(block) {
|
||
const pos = this.value(block, 'position');
|
||
const out = [this.segField(block, 'position', ['static', 'relative', 'absolute', 'fixed', 'sticky'])];
|
||
if (pos && pos !== 'static' || ['top', 'right', 'bottom', 'left', 'inset'].some((p) => this.get(block, p))) {
|
||
for (const p of ['top', 'right', 'bottom', 'left']) out.push(this.numberField(block, p, p, 'auto'));
|
||
if (this.get(block, 'inset')) out.push(this.field(block, 'inset', this.textInput(block, 'inset')));
|
||
}
|
||
out.push(this.numberField(block, 'z-index', 'z-index', 'auto'));
|
||
return out;
|
||
}
|
||
|
||
typeBody(block) {
|
||
const families = new Set(['system-ui, sans-serif', 'sans-serif', 'serif', 'monospace', 'Georgia, serif', '"Helvetica Neue", Arial, sans-serif', 'ui-monospace, monospace']);
|
||
for (const n of walk(this.parsed.root)) if (n.type === 'atrule' && n.name === 'font-face') { const f = declarationOf(n, 'font-family'); if (f) families.add(f.value); }
|
||
const preview = el('div.cssd-fontprev', {}, t('The quick brown fox jumps over the lazy dog'), ' 0123');
|
||
const v = (p) => this.value(block, p);
|
||
const css = (x) => (/\$|#\{/.test(x) ? this.subst(x) : x);
|
||
Object.assign(preview.style, { fontFamily: css(v('font-family')) || 'inherit', fontWeight: css(v('font-weight')), fontStyle: css(v('font-style')),
|
||
letterSpacing: css(v('letter-spacing')), textTransform: v('text-transform'), lineHeight: css(v('line-height')), color: resolveColor(v('color'), this.allVars()) ? formatColor(resolveColor(v('color'), this.allVars()), 'rgb') : '' });
|
||
const size = parseNumber(css(v('font-size')));
|
||
preview.style.fontSize = size ? (size.unit === 'px' ? Math.min(40, size.number) + 'px' : size.unit === 'rem' || size.unit === 'em' ? Math.min(40, size.number * 16) + 'px' : css(v('font-size'))) : '';
|
||
return [
|
||
this.field(block, 'font-family', this.textInput(block, 'font-family', { list: [...families] }), { label: 'family' }),
|
||
this.numberField(block, 'font-size', 'size', '16px'),
|
||
this.field(block, 'font-weight', this.textInput(block, 'font-weight', { list: ['100', '200', '300', '400', '500', '600', '700', '800', '900', 'normal', 'bold', 'lighter', 'bolder'] }), { label: 'weight', num: true }),
|
||
this.numberField(block, 'line-height', 'line-height', 'normal'),
|
||
this.numberField(block, 'letter-spacing', 'letter-spacing', 'normal'),
|
||
this.segField(block, 'font-style', ['normal', 'italic'], { label: 'style' }),
|
||
this.segField(block, 'text-align', ['left', 'center', 'right', 'justify'], { label: 'align' }),
|
||
this.segField(block, 'text-transform', ['none', 'uppercase', 'lowercase', 'capitalize'], { label: 'transform' }),
|
||
this.field(block, 'text-decoration', this.textInput(block, 'text-decoration', { list: ['none', 'underline', 'line-through', 'underline dotted'] }), { label: 'decoration' }),
|
||
this.get(block, 'white-space') ? this.field(block, 'white-space', this.textInput(block, 'white-space')) : null,
|
||
preview,
|
||
].filter(Boolean);
|
||
}
|
||
|
||
colorsBody(block) {
|
||
const out = [this.colorField(block, 'color', 'text colour'), this.colorField(block, 'background-color', 'background')];
|
||
const bgProp = this.get(block, 'background-image') ? 'background-image' : this.get(block, 'background') && parseGradient(this.value(block, 'background')) ? 'background' : 'background-image';
|
||
const grad = parseGradient(this.value(block, bgProp));
|
||
if (this.get(block, 'background')) out.push(this.field(block, 'background', this.textInput(block, 'background')));
|
||
if (grad) out.push(this.gradientEditor(block, bgProp, grad));
|
||
else {
|
||
out.push(this.field(block, 'background-image', this.textInput(block, 'background-image', { placeholder: 'none' }), { label: 'image' }));
|
||
out.push(el('button.cssd-b', { onclick: () => this.set(this.block, 'background-image', 'linear-gradient(180deg, #ffffff, #87ceeb)') }, '+ ' + t('Gradient')));
|
||
}
|
||
for (const p of ['background-size', 'background-position', 'background-repeat']) if (this.get(block, p) || this.get(block, 'background-image')) out.push(this.field(block, p, this.textInput(block, p), { label: p.replace('background-', 'bg ') }));
|
||
for (const p of ['outline-color', 'accent-color', 'fill', 'stroke', 'caret-color']) if (this.get(block, p)) out.push(this.colorField(block, p));
|
||
out.push(this.paletteStrip(block));
|
||
return out;
|
||
}
|
||
|
||
/** the colours of the project, a click puts one on the text colour (Shift: on the background) */
|
||
paletteStrip() {
|
||
const colors = (this.palette || []).slice(0, 48);
|
||
if (!colors.length) return null;
|
||
return el('div', {}, el('div.cssd-h', { style: { padding: '4px 0' } }, t('Colours of the project'), el('span.cssd-n', {}, t('Click: text · Shift+click: background'))),
|
||
el('div.cssd-seg', {}, colors.map((c) => {
|
||
const sw = swatch(c.color);
|
||
sw.title = `${[...c.texts].slice(0, 3).join(', ')} · ${c.count}× · ${[...c.files].slice(0, 2).join(', ')}`;
|
||
sw.onclick = (e) => this.set(this.block, e.shiftKey ? 'background-color' : 'color', [...c.texts][0]);
|
||
return sw;
|
||
})));
|
||
}
|
||
|
||
gradientEditor(block, prop, g) {
|
||
const write = (merge = false) => this.set(this.block, prop, formatGradient(g), { merge });
|
||
const bar = el('div.cssd-grad', { style: { background: this.subst(formatGradient({ ...g, type: 'linear', head: '90deg' })) } });
|
||
const head = el('input.cssd-in', { value: g.head, placeholder: g.type === 'linear' ? '180deg' : 'circle', dataset: { key: prop + ':head' },
|
||
onchange: (e) => { g.head = e.target.value.trim(); write(); } });
|
||
const type = el('select.cssd-in', { onchange: (e) => { g.type = e.target.value; g.head = ''; write(); } }, ['linear', 'radial', 'conic'].map((x) => el('option', { value: x, selected: x === g.type }, x)));
|
||
const stops = g.stops.map((s, i) => {
|
||
const color = resolveColor(s.color, this.allVars());
|
||
const sw = swatch(color);
|
||
sw.onclick = () => this.openPicker(sw, s.color, (v, merge) => { s.color = v; write(merge); });
|
||
return el('div.cssd-kv', {}, el('div.cssd-color', {}, sw, el('input.cssd-in', { value: s.color, dataset: { key: `${prop}:stop${i}` }, onchange: (e) => { s.color = e.target.value.trim(); write(); } })),
|
||
el('input.cssd-in', { value: s.pos, placeholder: '%', dataset: { key: `${prop}:pos${i}` }, onchange: (e) => { s.pos = e.target.value.trim(); write(); } }),
|
||
el('button.cssd-b', { title: t('Remove'), disabled: g.stops.length <= 2, onclick: () => { g.stops.splice(i, 1); write(); } }, '✕'));
|
||
});
|
||
return this.field(block, prop, el('div.cssd-card', {}, bar, el('div.cssd-kv', {}, type, head, el('span')), ...stops,
|
||
el('button.cssd-b', { onclick: () => { g.stops.push({ color: g.stops[g.stops.length - 1]?.color || '#000', pos: '' }); write(); } }, '+ ' + t('Colour stop'))), { label: t('Gradient') });
|
||
}
|
||
|
||
effectsBody(block) {
|
||
const opacity = this.value(block, 'opacity');
|
||
const slider = el('input', { type: 'range', min: 0, max: 1, step: 0.01, value: opacity === '' ? 1 : parseFloat(opacity) || 0, dataset: { key: 'opacity:range' } });
|
||
let first = true;
|
||
slider.addEventListener('input', () => { this.set(this.block, 'opacity', formatNumber(+slider.value), { merge: !first }); first = false; });
|
||
slider.addEventListener('change', () => { first = true; this.o.model.pushStackElement(); });
|
||
return [
|
||
this.shadowEditor(block, 'box-shadow', false),
|
||
this.shadowEditor(block, 'text-shadow', true),
|
||
this.field(block, 'opacity', el('div', { style: { display: 'flex', gap: '4px' } }, slider, this.textInput(block, 'opacity', { placeholder: '1' })), { num: true }),
|
||
this.field(block, 'filter', this.textInput(block, 'filter', { placeholder: 'none', list: ['none', 'blur(4px)', 'brightness(1.2)', 'contrast(1.2)', 'grayscale(1)', 'saturate(1.5)', 'sepia(1)', 'hue-rotate(90deg)', 'invert(1)', 'drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3))'] })),
|
||
this.field(block, 'transform', this.textInput(block, 'transform', { placeholder: 'none', list: ['none', 'translateY(-2px)', 'translate(-50%, -50%)', 'rotate(45deg)', 'scale(1.05)', 'skewX(-10deg)'] })),
|
||
this.field(block, 'transition', this.textInput(block, 'transition', { placeholder: 'none', list: ['all 0.2s ease', 'opacity 0.3s ease-in-out', 'transform 0.2s ease', 'color 0.15s, background-color 0.15s', 'none'] })),
|
||
this.get(block, 'animation') ? this.field(block, 'animation', this.textInput(block, 'animation', { list: this.keyframeNames().map((k) => `${k} 1s linear infinite`) })) : null,
|
||
this.field(block, 'cursor', this.textInput(block, 'cursor', { list: ['pointer', 'default', 'text', 'move', 'not-allowed', 'grab', 'help', 'wait', 'crosshair'] })),
|
||
].filter(Boolean);
|
||
}
|
||
|
||
keyframeNames() { const out = []; for (const n of walk(this.parsed.root)) if (n.type === 'atrule' && /keyframes$/.test(n.name)) out.push(n.params); return out; }
|
||
|
||
shadowEditor(block, prop, textShadow) {
|
||
const list = parseShadows(this.value(block, prop));
|
||
const write = (merge = false) => this.set(this.block, prop, list.length ? formatShadows(list, textShadow) : null, { merge });
|
||
const cards = list.map((s, i) => {
|
||
const num = (key, ph) => {
|
||
const input = el('input.cssd-in', { value: s[key], placeholder: ph, title: key, dataset: { key: `${prop}:${i}:${key}` },
|
||
onchange: (e) => { let v = e.target.value.trim(); if (parseNumber(v) && !parseNumber(v).unit && v !== '0') v += 'px'; s[key] = v; write(); },
|
||
onkeydown: (e) => { if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return; const n = parseNumber(e.target.value || '0'); if (!n) return; e.preventDefault();
|
||
s[key] = formatNumber(n.number + (e.key === 'ArrowUp' ? 1 : -1) * (e.shiftKey ? 10 : 1)) + (n.unit || 'px'); e.target.value = s[key]; write(true); } });
|
||
return input;
|
||
};
|
||
const color = resolveColor(s.color, this.allVars());
|
||
const sw = swatch(color);
|
||
sw.onclick = () => this.openPicker(sw, s.color || 'rgba(0, 0, 0, 0.3)', (v, merge) => { s.color = v; write(merge); });
|
||
return el('div.cssd-card', {},
|
||
el('div.cssd-row4', {}, num('x', 'x'), num('y', 'y'), num('blur', 'blur'), textShadow ? el('span') : num('spread', 'spread'),
|
||
el('button.cssd-b', { title: t('Remove'), onclick: () => { list.splice(i, 1); write(); } }, '✕')),
|
||
el('div.cssd-color', {}, sw, el('input.cssd-in', { value: s.color, placeholder: 'rgba(0, 0, 0, 0.3)', dataset: { key: `${prop}:${i}:color` }, onchange: (e) => { s.color = e.target.value.trim(); write(); } }),
|
||
textShadow ? null : el('label', { style: { display: 'flex', gap: '3px', alignItems: 'center', whiteSpace: 'nowrap' } },
|
||
el('input', { type: 'checkbox', checked: s.inset, onchange: (e) => { s.inset = e.target.checked; write(); } }), 'inset')));
|
||
});
|
||
const add = el('button.cssd-b', { onclick: () => { list.push({ inset: false, x: '0', y: textShadow ? '1px' : '2px', blur: textShadow ? '2px' : '8px', spread: '', color: 'rgba(0, 0, 0, 0.25)' }); write(); } }, '+ ' + t('Shadow'));
|
||
return this.field(block, prop, el('div', { style: { display: 'flex', flexDirection: 'column', gap: '4px' } }, ...cards, add), { label: prop });
|
||
}
|
||
|
||
otherBody(block, decls) {
|
||
const rows = decls.map((d, i) => {
|
||
const name = el('input.cssd-in', { value: d.prop, spellcheck: false, dataset: { key: `other:${i}:name` }, list: 'cssd-props',
|
||
onfocus: () => this.datalist('cssd-props', properties()),
|
||
onchange: (e) => { const v = e.target.value.trim(); if (v && v !== d.prop && /^[\w$-]+$/.test(v)) this.apply(renameDeclaration(this.get(this.block, d.prop) || d, v)); } });
|
||
name.setAttribute('list', 'cssd-props');
|
||
const value = el('input.cssd-in', { value: d.value, spellcheck: false, dataset: { key: `other:${i}:value` },
|
||
onfocus: () => this.datalist('cssd-vals', [...keywordsOf(d.prop), ...this.varNames()]),
|
||
onkeydown: (e) => { if (e.key === 'Enter') { e.preventDefault(); this.set(this.block, d.prop, e.target.value); } if (e.key === 'ArrowUp' || e.key === 'ArrowDown') this.step(e, d.prop); },
|
||
onchange: (e) => this.set(this.block, d.prop, e.target.value) });
|
||
value.setAttribute('list', 'cssd-vals');
|
||
return el('div.cssd-kv', {}, name, value, el('span.cssd-x', {},
|
||
el(`button.cssd-b.cssd-imp${d.important ? '.on' : ''}`, { title: '!important', onclick: () => this.set(this.block, d.prop, d.value, { important: !d.important }) }, '!'),
|
||
el('button.cssd-b', { title: t('Remove {name}', { name: d.prop }), onclick: () => this.apply(removeNode(this.text(), d)) }, '✕')));
|
||
});
|
||
rows.push(this.addRow(block, 'property', ''));
|
||
return rows;
|
||
}
|
||
|
||
/** a new declaration: name + value, Enter adds it */
|
||
addRow(block, placeholder, prefix) {
|
||
const name = el('input.cssd-in', { placeholder, spellcheck: false, dataset: { key: 'new:name:' + prefix }, value: prefix, onfocus: () => this.datalist('cssd-props', properties()) });
|
||
if (!prefix) name.setAttribute('list', 'cssd-props');
|
||
const value = el('input.cssd-in', { placeholder: t('value'), spellcheck: false, dataset: { key: 'new:value:' + prefix } });
|
||
const add = () => {
|
||
const n = name.value.trim();
|
||
const v = value.value.trim();
|
||
if (!n || !v || n === prefix || !/^[\w$-]+$/.test(n)) return;
|
||
if (this.selected.type === 'root') this.set(this.block, n, v);
|
||
else this.apply(insertDeclaration(this.text(), this.block, `${n}: ${v};`));
|
||
const again = this.insp.querySelector(`[data-key="${CSS.escape('new:name:' + prefix)}"]`);
|
||
again?.focus();
|
||
};
|
||
value.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); add(); } });
|
||
name.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); value.focus(); } });
|
||
return el('div.cssd-kv', {}, name, value, el('button.cssd-b', { title: t('Add'), onclick: add }, '+'));
|
||
}
|
||
|
||
/** $variables of SCSS replaced by their values (for what the IDE itself draws: the font preview, the gradient bar) */
|
||
subst(value) {
|
||
const vars = this.allVars();
|
||
let v = String(value);
|
||
for (let i = 0; i < 5 && /\$[\w-]+/.test(v); i++) v = v.replace(/\$[\w-]+/g, (m) => vars.get(m) ?? m);
|
||
return v.replace(/var\(\s*(--[\w-]+)\s*(?:,\s*([^)]*))?\)/g, (m, name, fb) => vars.get(name) ?? fb ?? m);
|
||
}
|
||
|
||
// colour picker -----------------------------------------------------------------------------------------------------
|
||
|
||
/**
|
||
* A colour chooser under `anchor`: saturation / value, hue, alpha, the format (hex, rgb, hsl, oklch, name), the
|
||
* project's colours and colour variables, the named colours. onChange(value, merge): merge for the moves after the
|
||
* first one (one undo step per opening).
|
||
*/
|
||
async openPicker(anchor, value, onChange) {
|
||
this.closePicker();
|
||
const vars = await colorVariables(this.vars).catch(() => []);
|
||
const start = resolveColor(value, this.allVars()) || { r: 135, g: 206, b: 235, a: 1 };
|
||
let fmt = /^(var\(|\$)/.test(String(value).trim()) ? 'hex' : colorFormat(value || '#000');
|
||
let hsv = rgbToHsv(start);
|
||
let alpha = start.a;
|
||
let first = true;
|
||
const node = el('div.cssd-picker');
|
||
const sv = el('div.sv', {}, el('i'));
|
||
const hue = el('div.bar.hue', {}, el('i'));
|
||
const alphaBar = el('div.bar.alpha', {}, el('b'), el('i'));
|
||
const text = el('input.cssd-in', { spellcheck: false });
|
||
const fmts = el('div.fmts', {}, ['hex', 'rgb', 'hsl', 'oklch', 'name'].map((f) => el(`button.cssd-b${f === fmt ? '.on' : ''}`, { onclick: (e) => {
|
||
fmt = f;
|
||
for (const b of fmts.children) b.classList.toggle('on', b === e.currentTarget);
|
||
emit();
|
||
} }, f.toUpperCase())));
|
||
const rgb = () => ({ ...hsvToRgb(hsv.h, hsv.s, hsv.v), a: Math.round(alpha * 1000) / 1000 });
|
||
const paint = () => {
|
||
const c = rgb();
|
||
sv.style.background = `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, hsl(${hsv.h}, 100%, 50%))`;
|
||
Object.assign(sv.firstChild.style, { left: hsv.s * 100 + '%', top: (1 - hsv.v) * 100 + '%' });
|
||
hue.firstChild.style.left = (hsv.h / 360) * 100 + '%';
|
||
alphaBar.firstChild.style.background = `linear-gradient(to right, transparent, rgb(${c.r}, ${c.g}, ${c.b}))`;
|
||
alphaBar.lastChild.style.left = alpha * 100 + '%';
|
||
};
|
||
const emit = (literal = null) => {
|
||
const v = literal ?? formatColor(rgb(), fmt);
|
||
text.value = v;
|
||
paint();
|
||
onChange(v, !first);
|
||
first = false;
|
||
};
|
||
const drag = (target, fn) => target.addEventListener('mousedown', (e) => {
|
||
e.preventDefault();
|
||
const move = (ev) => { const r = target.getBoundingClientRect(); fn(Math.min(1, Math.max(0, (ev.clientX - r.left) / r.width)), Math.min(1, Math.max(0, (ev.clientY - r.top) / r.height))); emit(); };
|
||
const up = () => { removeEventListener('mousemove', move); removeEventListener('mouseup', up); };
|
||
addEventListener('mousemove', move);
|
||
addEventListener('mouseup', up);
|
||
move(e);
|
||
});
|
||
drag(sv, (x, y) => { hsv = { ...hsv, s: x, v: 1 - y }; });
|
||
drag(hue, (x) => { hsv = { ...hsv, h: x * 360 }; });
|
||
drag(alphaBar, (x) => { alpha = Math.round(x * 100) / 100; });
|
||
text.value = value || formatColor(start, fmt);
|
||
text.addEventListener('keydown', (e) => {
|
||
if (e.key === 'Enter') {
|
||
const c = resolveColor(text.value, this.allVars());
|
||
if (c) { hsv = rgbToHsv(c); alpha = c.a; }
|
||
emit(text.value.trim());
|
||
}
|
||
if (e.key === 'Escape') this.closePicker();
|
||
});
|
||
const pick = (literal) => { const c = resolveColor(literal, this.allVars()); if (c) { hsv = rgbToHsv(c); alpha = c.a; } emit(literal); };
|
||
const swatches = (title, items) => (items.length ? [el('div.lbl', {}, title), el('div.sws', {}, items.map(([color, literal, tip]) => {
|
||
const s = swatch(color);
|
||
s.title = tip || literal;
|
||
s.onclick = () => pick(literal);
|
||
return s;
|
||
}))] : []);
|
||
const palette = (this.palette || (await scanProject().catch(() => ({ colors: [] }))).colors || []).slice(0, 40);
|
||
node.append(sv, hue, alphaBar, fmts, text,
|
||
...swatches(t('Variables'), vars.slice(0, 40).map((v) => [v.color, v.name.startsWith('--') ? `var(${v.name})` : v.name, `${v.name}: ${v.value}`])),
|
||
...swatches(t('Colours of the project'), palette.map((c) => [c.color, [...c.texts][0], `${[...c.texts].slice(0, 3).join(', ')} · ${c.count}×`])),
|
||
...swatches(t('Named colours'), Object.keys(NAMED_COLORS).filter((n) => !/grey/.test(n)).map((n) => [parseColor(n), n])));
|
||
document.body.append(node);
|
||
const r = anchor.getBoundingClientRect();
|
||
const h = node.offsetHeight;
|
||
node.style.left = Math.max(8, Math.min(innerWidth - 260, r.left)) + 'px';
|
||
node.style.top = (r.bottom + h + 8 > innerHeight ? Math.max(8, r.top - h - 4) : r.bottom + 4) + 'px';
|
||
paint();
|
||
this.picker = node;
|
||
this.pickerAway = (e) => { if (!node.contains(e.target) && e.target !== anchor) this.closePicker(); };
|
||
setTimeout(() => addEventListener('mousedown', this.pickerAway, true), 0);
|
||
this.pickerKeys = (e) => { if (e.key === 'Escape') this.closePicker(); };
|
||
addEventListener('keydown', this.pickerKeys);
|
||
}
|
||
|
||
closePicker() {
|
||
if (!this.picker) return;
|
||
this.picker.remove();
|
||
this.picker = null;
|
||
removeEventListener('mousedown', this.pickerAway, true);
|
||
removeEventListener('keydown', this.pickerKeys);
|
||
this.o.model.pushStackElement();
|
||
}
|
||
|
||
// the preview -------------------------------------------------------------------------------------------------------
|
||
|
||
makePreview() {
|
||
if (!this.showPreview) { this.preview?.destroy(); this.preview = null; return; }
|
||
if (this.preview) return;
|
||
clear(this.prevNode);
|
||
this.preview = new HtmlPreview(this.prevNode, {
|
||
path: this.o.path,
|
||
kind: 'css',
|
||
prefix: 'cssDesign',
|
||
inspect: true,
|
||
text: () => (this.scss ? this.compiled ?? flattenScss(this.parsed) : this.text()),
|
||
readText: this.o.readText,
|
||
readDataUrl: this.o.readDataUrl,
|
||
htmlFiles: this.o.htmlFiles,
|
||
onPick: (data) => this.picked(data),
|
||
onCount: (n) => { this.lastCount = n; if (this.countNode) this.countNode.textContent = t('Matched in the preview: {n}', { n }); },
|
||
});
|
||
this.previewSoon = debounce(() => this.preview?.update(), 350);
|
||
setTimeout(() => this.highlight(false), 400);
|
||
}
|
||
|
||
previewSoon() { /* replaced when the preview exists */ }
|
||
|
||
/** the preview outlines what the selected rule matches; the rules are sent along for the clicks */
|
||
highlight(scroll) {
|
||
if (!this.preview) return;
|
||
this.lastCount = undefined;
|
||
const rules = outline(this.parsed).map((o, id) => ({ id, selector: this.selectorOf(o.node) })).filter((r) => r.selector);
|
||
this.preview.highlight(this.selectorOf(this.selected), rules, scroll);
|
||
}
|
||
|
||
/** an element clicked in the preview: the rules that apply to it, the strongest selected */
|
||
picked(data) {
|
||
const rows = outline(this.parsed);
|
||
this.matching = { ...data, ids: data.ids || [] };
|
||
const best = (data.ids || []).map((id) => rows[id]?.node).filter(Boolean)
|
||
.map((node) => ({ node, spec: maxMatching(node, this.matching) }))
|
||
.sort((a, b) => b.spec[0] - a.spec[0] || b.spec[1] - a.spec[1] || b.spec[2] - a.spec[2] || b.node.start - a.node.start)[0];
|
||
if (best) this.select(best.node);
|
||
else this.render();
|
||
}
|
||
|
||
// SCSS ----------------------------------------------------------------------------------------------------------------
|
||
|
||
async compile() {
|
||
if (!this.o.compile || this.compiling) { if (this.compiling) this.compileAgain = true; return; }
|
||
this.compiling = true;
|
||
const text = this.text();
|
||
try {
|
||
const r = await this.o.compile(text);
|
||
this.compileError = r.ok || r.problems?.length ? '' : (r.detail || t('Sass failed'));
|
||
this.problems = r.problems || [];
|
||
if (r.ok) this.compiled = r.css;
|
||
this.setMarkers();
|
||
this.renderMessages();
|
||
this.preview?.update();
|
||
} catch (e) {
|
||
this.compileError = t('Sass is not available ({detail}): the preview shows the nesting and $variables only', { detail: String(e.message || e).slice(0, 200) });
|
||
this.renderMessages();
|
||
} finally {
|
||
this.compiling = false;
|
||
if (this.compileAgain) { this.compileAgain = false; this.compileSoon(); }
|
||
}
|
||
}
|
||
|
||
setMarkers() {
|
||
const monaco = this.o.monaco;
|
||
if (!monaco) return;
|
||
monaco.editor.setModelMarkers(this.o.model, 'sass', this.problems.map((p) => ({
|
||
severity: p.severity === 'error' ? monaco.MarkerSeverity.Error : monaco.MarkerSeverity.Warning,
|
||
message: 'Sass: ' + p.message, startLineNumber: p.line, startColumn: p.col, endLineNumber: p.line, endColumn: p.col + 1, source: 'sass',
|
||
})));
|
||
}
|
||
|
||
/** the @font-face of the file loaded into the IDE, so the typography preview shows them */
|
||
async loadFonts() {
|
||
if (!this.o.readDataUrl || !document.fonts) return;
|
||
const dir = this.o.path.includes('/') ? this.o.path.slice(0, this.o.path.lastIndexOf('/')) : '';
|
||
for (const n of walk(this.parsed.root)) {
|
||
if (n.type !== 'atrule' || n.name !== 'font-face') continue;
|
||
const family = declarationOf(n, 'font-family')?.value.replace(/^["']|["']$/g, '');
|
||
const url = /url\(\s*["']?([^"')]+)["']?\s*\)/.exec(declarationOf(n, 'src')?.value || '')?.[1];
|
||
if (!family || !url || /^(https?:|data:|\/\/)/.test(url)) continue;
|
||
const file = (url.startsWith('/') ? url.slice(1) : (dir ? dir + '/' : '') + url).split('/').reduce((a, p) => (p === '..' ? a.slice(0, -1) : p === '.' ? a : [...a, p]), []).join('/');
|
||
try {
|
||
const data = await this.o.readDataUrl(file);
|
||
if (data) document.fonts.add(await new FontFace(family, `url(${data})`).load());
|
||
} catch { /* not a font the IDE can read */ }
|
||
}
|
||
}
|
||
}
|
||
|
||
/** the highest specificity among the parts of a rule's selector (a clicked element: the parts it matches are not known here) */
|
||
function maxMatching(node) {
|
||
const full = resolvedSelector(node);
|
||
return full ? maxSpecificity(full) : [0, 0, 0];
|
||
}
|
||
|
||
/** the top-level block a node is in (a new rule goes after it) */
|
||
function topOf(node) {
|
||
let n = node;
|
||
while (n.parent && n.parent.type !== 'root' && !(n.parent.type === 'atrule' && ['media', 'supports', 'container', 'layer'].includes(n.parent.name))) n = n.parent;
|
||
return n;
|
||
}
|
||
|
||
function swatch(color) {
|
||
const fill = el('i');
|
||
if (color) fill.style.background = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})`;
|
||
else fill.style.background = 'linear-gradient(135deg, transparent 45%, #e06c75 45%, #e06c75 55%, transparent 55%), #fff';
|
||
return el('button.cssd-sw', { type: 'button' }, fill);
|
||
}
|
||
|
||
const shorten = (s, n) => (String(s).length > n ? String(s).slice(0, n - 1) + '…' : String(s));
|
||
|
||
/** the tracks of a grid-template-columns value, drawn as boxes in proportion */
|
||
function tracks(value) {
|
||
const out = el('div.cssd-tracks');
|
||
let parts = [];
|
||
const m = /^repeat\(\s*(\d+)\s*,\s*([^)]*\)?)\s*\)$/.exec((value || '').trim());
|
||
if (m) parts = Array(Math.min(24, +m[1])).fill(m[2]);
|
||
else if (/auto-(fill|fit)/.test(value || '')) parts = Array(4).fill('1fr');
|
||
else parts = splitValue(value || '');
|
||
for (const p of parts.slice(0, 24)) {
|
||
const n = parseNumber(p);
|
||
const i = el('i');
|
||
i.style.flex = n?.unit === 'fr' ? String(n.number) : '0 0 ' + (n?.unit === 'px' ? Math.min(80, n.number / 4) : 20) + 'px';
|
||
out.append(i);
|
||
}
|
||
return out;
|
||
}
|