rob-revisited/ide/ui/js/css-colors.js

125 lines
6.1 KiB
JavaScript

// Colours of stylesheets in the code editor and in the visual stylesheet editor (css-designer.js): Monaco's colour
// provider for CSS / SCSS / Less (a swatch beside each colour, named ones too, and beside var(--x) / $x when the
// variable holds a colour, defined in this file or another stylesheet of the project), and the palette of every colour
// the project's stylesheets use.
import { parseStylesheet, findColors, variablesOf, parseColor, formatColor, colorFormat, walk } from './css-model.js';
const STYLESHEET = /\.(css|scss|sass|less)$/i;
const SKIP = /(^|\/)(node_modules|vendor|var|dist|\.git|\.jumphp|public\/build|public\/bundles|build)\//;
/** where the project's stylesheets come from: set by the editor (the file tree and a reader that sees unsaved text) */
const source = { files: () => [], readText: async () => null };
let scan = null;
let scannedAt = 0;
export function configureCssProject({ files, readText }) {
if (files) source.files = files;
if (readText) source.readText = readText;
}
/** the project's stylesheets (at most 300) */
export const projectStylesheets = () => source.files().filter((p) => STYLESHEET.test(p) && !SKIP.test(p)).slice(0, 300);
/**
* Every colour of the project's stylesheets: {colors: [{hex, color, count, files}], vars: Map(name -> value)}, read again
* after 30 seconds (or when forced).
*/
export function scanProject(force = false) {
if (scan && !force && Date.now() - scannedAt < 30000) return scan;
scannedAt = Date.now();
scan = (async () => {
const colors = new Map();
const vars = new Map();
for (const path of projectStylesheets()) {
let text = null;
try { text = await source.readText(path); } catch { text = null; }
if (!text || text.length > 400000) continue;
const model = parseStylesheet(text, { scss: !/\.css$/i.test(path) });
for (const [k, v] of variablesOf(model)) vars.set(k, v);
for (const found of findColors(model)) {
if (found.color.a === 0) continue;
const hex = formatColor(found.color, 'hex');
const entry = colors.get(hex) || { hex, color: found.color, count: 0, files: new Set(), texts: new Set() };
entry.count++;
entry.files.add(path);
entry.texts.add(found.text);
colors.set(hex, entry);
}
}
return { colors: [...colors.values()].sort((a, b) => b.count - a.count), vars };
})();
return scan;
}
/** the variables known without waiting (the last scan's), for the swatches of the code */
let knownVars = new Map();
const refreshVars = () => scanProject().then((r) => { knownVars = r.vars; }, () => {});
/** the colour variables of the project: [{name, value, color}] (custom properties and SCSS variables) */
export async function colorVariables(extra = null) {
const { vars } = await scanProject();
const all = new Map([...vars, ...(extra || [])]);
const out = [];
for (const [name, value] of all) {
const color = resolve(value, all);
if (color) out.push({ name, value, color });
}
return out;
}
function resolve(value, vars, depth = 0) {
const direct = parseColor(value);
if (direct || depth > 6) return direct;
const m = /^var\(\s*(--[\w-]+)\s*(?:,\s*([\s\S]+))?\)$/.exec(String(value).trim()) || /^(\$[\w-]+)$/.exec(String(value).trim());
if (!m) return null;
return (vars.has(m[1]) ? resolve(vars.get(m[1]), vars, depth + 1) : null) || (m[2] ? resolve(m[2], vars, depth + 1) : null);
}
const FORMATS = ['hex', 'rgb', 'hsl', 'oklch'];
/** Monaco's colour provider for the stylesheets (the built-in one turned off: it shows no swatch for variables) */
export function registerCssColors(monaco) {
for (const name of ['cssDefaults', 'scssDefaults', 'lessDefaults']) {
try {
const d = monaco.languages.css?.[name];
if (d?.setModeConfiguration) d.setModeConfiguration({ ...d.modeConfiguration, colors: false });
} catch { /* an older Monaco */ }
}
monaco.languages.registerColorProvider(['css', 'scss', 'less'], {
provideDocumentColors(model) {
const text = model.getValue();
if (text.length > 600000) return [];
if (!knownVars.size) refreshVars();
const parsed = parseStylesheet(text, { scss: model.getLanguageId() !== 'css' });
const vars = new Map([...knownVars, ...variablesOf(parsed)]);
return findColors(parsed, vars).map((f) => {
const a = model.getPositionAt(f.start);
const b = model.getPositionAt(f.end);
return { range: { startLineNumber: a.lineNumber, startColumn: a.column, endLineNumber: b.lineNumber, endColumn: b.column },
color: { red: f.color.r / 255, green: f.color.g / 255, blue: f.color.b / 255, alpha: f.color.a } };
});
},
provideColorPresentations(model, info) {
const c = { r: Math.round(info.color.red * 255), g: Math.round(info.color.green * 255), b: Math.round(info.color.blue * 255), a: Math.round(info.color.alpha * 1000) / 1000 };
const text = model.getValueInRange(info.range);
const ref = /^var\(\s*(--[\w-]+)/.exec(text)?.[1] || (/^\$[\w-]+$/.test(text) ? text : null);
if (ref) {
// a variable: its definition in this file takes the colour, the reference stays
const parsed = parseStylesheet(model.getValue(), { scss: model.getLanguageId() !== 'css' });
let def = null;
for (const node of walk(parsed.root)) if (node.type === 'decl' && node.prop === ref && parseColor(node.value)) def = node;
if (!def) return [{ label: text }];
const label = formatColor(c, colorFormat(def.value));
const a = model.getPositionAt(def.valueStart);
const b = model.getPositionAt(def.valueStart + def.value.length);
return [{ label: `${ref}: ${label}`, textEdit: { range: info.range, text },
additionalTextEdits: [{ range: { startLineNumber: a.lineNumber, startColumn: a.column, endLineNumber: b.lineNumber, endColumn: b.column }, text: label }] }];
}
const first = colorFormat(text);
const order = [first === 'name' ? 'name' : first, ...FORMATS.filter((f) => f !== first)];
const labels = [...new Set(order.map((f) => formatColor(c, f)))];
return labels.map((label) => ({ label, textEdit: { range: info.range, text: label } }));
},
});
}