package file→ .shtukbase/packages/icons/lib/render.js
lib/render.js
321 lines, 18.1 KB.
- // The icon renderer: turns a flat drawing into an icon style. Pure (text in, text out), no DOM, no dependencies, so the
- // same file runs under Bun (the `build` of a set package, the checks) and in the icon lens (copied to
- // lib/design/icon-render.js, where it sets window.SBIconRender).
- //
- // A port of `themed` from the Shtukbase package-map mock (shtuks/projects/shtukbase/assets/logo/package-map/page.tpl.html):
- // the outline in a colour of the detail's hue, the rim (a silhouette in the rim colour), the soft shadow (a black
- // silhouette, shifted, with opacity) and the scale around the centre.
- //
- // A flat drawing is canonical: one <svg> root with xmlns and a square viewBox, and inside only drawing elements
- // (path, rect, circle, ellipse, polygon, polyline, line) with their paint as attributes; no groups, no style
- // attributes. `canonical` (in the set package's import) brings an outside drawing to this form.
- //
- // The render parameters (the `render:` block of an IconStyle page):
- // outline 'ink' | 'deep' | 'hueink' | '#rrggbb' | null the outline colour: ink, a deep step of the
- // detail's hue (main mixed 55% to its dark step), the dark step of the hue, or a fixed colour
- // outlineWidth number on the 96 grid
- // rim number the rim width (a silhouette under the drawing); 0 or absent: no rim
- // rimColor '#rrggbb'
- // shadow number the shadow opacity; 0 or absent: no shadow
- // offset [x, y] the shadow offset (default [1.5, 3])
- // shadowOnly number extra shadow spread where there is no rim (style 81)
- // scale number the drawing's scale around the centre
- // ink '#rrggbb' the ink colour (default #2B2B2E)
- (function (root) {
- 'use strict';
- const DRAW = new Set(['path', 'rect', 'circle', 'ellipse', 'polygon', 'polyline', 'line']);
- const INK = '#2B2B2E';
- // ---------- colour ----------
- function hex(c) {
- let s = String(c).replace('#', '');
- if (s.length === 3) s = s.split('').map((x) => x + x).join('');
- return [0, 2, 4].map((i) => parseInt(s.slice(i, i + 2), 16));
- }
- const toHex = (a) => '#' + a.map((v) => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, '0')).join('').toUpperCase();
- const mix = (a, b, t) => { const A = hex(a), B = hex(b); return toHex(A.map((v, i) => v + (B[i] - v) * t)); };
- const norm = (c) => { let s = String(c || '').trim().toUpperCase(); if (/^#[0-9A-F]{3}$/.test(s)) s = '#' + [...s.slice(1)].map((x) => x + x).join(''); return s; };
- function hsl(c) {
- const [r, g, b] = hex(c).map((v) => v / 255);
- const mx = Math.max(r, g, b), mn = Math.min(r, g, b), l = (mx + mn) / 2;
- let h = 0, s = 0;
- if (mx !== mn) {
- const d = mx - mn;
- s = l > 0.5 ? d / (2 - mx - mn) : d / (mx + mn);
- h = mx === r ? (g - b) / d + (g < b ? 6 : 0) : mx === g ? (b - r) / d + 2 : (r - g) / d + 4;
- h *= 60;
- }
- return [h, s, l];
- }
- /** The hues of a palette: an entry that is a list [main, dark, light, ...] is a hue. */
- function huesOf(palette) {
- const out = {};
- for (const [k, v] of Object.entries(palette || {})) if (Array.isArray(v) && v.length >= 2) out[k] = v.map(norm);
- return out;
- }
- /** The neutrals of a palette, with the defaults of the Shtukbase palette. */
- function neutralsOf(palette) {
- const p = palette || {};
- const one = (v, d) => norm(Array.isArray(v) ? v[0] : v || d);
- return { ink: one(p.ink, INK), white: one(p.white, '#FFFFFF'), grey: one(p.grey, '#8A8680'), greyLight: one(p.greyLight, '#C9C6BF') };
- }
- /**
- * Snaps any colour to the palette (the rule of the package-map mock): very light to white, greys to ink or grey,
- * else the nearest hue by angle and a step by lightness (light, main, deep = main mixed 42% to dark, dark).
- * Returns {fill, hue, tone} or null for none / transparent / url().
- */
- function snap(c, palette) {
- if (!c) return null;
- let s = String(c).trim().toLowerCase();
- if (s === 'none' || s === 'transparent' || s.startsWith('url')) return null;
- if (s === 'white') s = '#ffffff';
- if (s === 'black') s = '#000000';
- const H = huesOf(palette), N = neutralsOf(palette);
- if (!s.startsWith('#')) return { fill: s, hue: null, tone: 'grey' };
- const exact = toneOf(s, palette);
- if (exact) return exact;
- const [h, sat, l] = hsl(s);
- if (l >= 0.9) return { fill: N.white, hue: null, tone: 'white' };
- if (sat < 0.16 || l < 0.12) {
- if (l < 0.32) return { fill: N.ink, hue: null, tone: 'ink' };
- return { fill: l > 0.66 ? N.greyLight : N.grey, hue: null, tone: 'grey' };
- }
- let best = null, bd = 999;
- for (const [k, v] of Object.entries(H)) {
- const ph = hsl(v[0])[0];
- const d = Math.min(Math.abs(h - ph), 360 - Math.abs(h - ph));
- if (d < bd) { bd = d; best = k; }
- }
- if (!best) return { fill: norm(s), hue: null, tone: 'grey' };
- const P = H[best];
- if (l >= 0.74) return { fill: P[2] || P[0], hue: best, tone: 'light' };
- if (l < 0.3) return { fill: P[1], hue: best, tone: 'ink' };
- if (l < 0.4) return { fill: mix(P[0], P[1], 0.42), hue: best, tone: 'deep' };
- return { fill: P[0], hue: best, tone: 'main' };
- }
- /** The tone of a colour that is already in the palette (exactly), or null. */
- function toneOf(c, palette) {
- const s = norm(c), H = huesOf(palette), N = neutralsOf(palette);
- for (const [k, v] of Object.entries(H)) {
- if (s === v[0]) return { fill: s, hue: k, tone: 'main' };
- if (s === v[1]) return { fill: s, hue: k, tone: 'ink' };
- if (s === v[2]) return { fill: s, hue: k, tone: 'light' };
- if (s === mix(v[0], v[1], 0.42) || s === v[3]) return { fill: s, hue: k, tone: 'deep' };
- }
- if (s === N.white) return { fill: s, hue: null, tone: 'white' };
- if (s === N.ink) return { fill: s, hue: null, tone: 'ink' };
- if (s === N.grey || s === N.greyLight) return { fill: s, hue: null, tone: 'grey' };
- return null;
- }
- /** Every colour a flat drawing may use: each hue's main, dark, light and deep steps, ink, the greys and white. */
- function flatColors(palette) {
- const H = huesOf(palette), N = neutralsOf(palette);
- const out = new Set([N.ink, N.white, N.grey, N.greyLight]);
- for (const v of Object.values(H)) { out.add(v[0]); out.add(v[1]); if (v[2]) out.add(v[2]); out.add(v[3] || mix(v[0], v[1], 0.42)); }
- return [...out];
- }
- // ---------- the flat form ----------
- const TAG = /<(\/?)([A-Za-z][\w:.-]*)((?:\s+[^\s=/>]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>/g;
- const ATTR = /([^\s=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
- function attrsOf(s) { const out = []; let m; ATTR.lastIndex = 0; while ((m = ATTR.exec(s))) out.push([m[1], m[2] !== undefined ? m[2] : m[3]]); return out; }
- /** Parses a flat drawing: {root: [[name, value]...], els: [{tag, attrs}]}. Throws on what is not the flat form. */
- function parse(src) {
- const text = String(src).replace(/<\?xml[\s\S]*?\?>/g, '').replace(/<!--[\s\S]*?-->/g, '');
- let rootAttrs = null; const els = []; let m;
- TAG.lastIndex = 0;
- while ((m = TAG.exec(text))) {
- const [, close, tag, attrs, self] = m;
- const t = tag.toLowerCase();
- if (close) { if (t === 'svg') break; continue; }
- if (t === 'svg' && !rootAttrs) { rootAttrs = attrsOf(attrs); continue; }
- if (t === 'title' || t === 'desc') { if (!self) { const end = text.indexOf('</' + tag, TAG.lastIndex); TAG.lastIndex = end < 0 ? text.length : end + tag.length + 3; } continue; }
- if (!DRAW.has(t)) throw new Error(`<${tag}> is not a drawing element of the flat form`);
- els.push({ tag, attrs: attrsOf(attrs) });
- }
- if (!rootAttrs) throw new Error('no <svg> root');
- return { root: rootAttrs, els };
- }
- const get = (el, k) => { const a = el.attrs.find(([n]) => n === k); return a ? a[1] : null; };
- function set(el, o) {
- for (const [k, v] of Object.entries(o)) {
- const i = el.attrs.findIndex(([n]) => n === k);
- if (v === null || v === undefined) { if (i >= 0) el.attrs.splice(i, 1); }
- else if (i >= 0) el.attrs[i][1] = String(v);
- else el.attrs.push([k, String(v)]);
- }
- return el;
- }
- const clone = (el) => ({ tag: el.tag, attrs: el.attrs.map(([k, v]) => [k, v]) });
- const esc = (v) => String(v).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
- const out1 = (el) => `<${el.tag}${el.attrs.map(([k, v]) => ` ${k}="${esc(v)}"`).join('')}/>`;
- const num = (n) => String(Math.round(n * 1000) / 1000);
- /** Writes a flat drawing in the canonical text form. */
- function serialize(doc) {
- const root = doc.root.filter(([k]) => k !== 'width' && k !== 'height');
- return `<svg${root.map(([k, v]) => ` ${k}="${esc(v)}"`).join('')}>\n${doc.els.map(out1).join('\n')}\n</svg>\n`;
- }
- const PAINT_ALL = new Set(['fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-miterlimit', 'opacity', 'fill-opacity', 'stroke-opacity', 'fill-rule', 'clip-rule']);
- const PAINT = ['fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'stroke-dasharray', 'opacity', 'fill-opacity', 'stroke-opacity', 'fill-rule'];
- /**
- * Brings an outside drawing to the flat form in a palette, without redrawing it: groups are dissolved (their paint
- * goes down to the shapes that do not set their own; a group transform is refused), `style` attributes become
- * attributes, an app-tile background (a rect over 70% of the canvas) is dropped, every colour is snapped to the
- * palette, width, height, title and desc go. Returns {svg, notes}.
- */
- function canonical(src, palette) {
- const text = String(src).replace(/<\?xml[\s\S]*?\?>/g, '').replace(/<!--[\s\S]*?-->/g, '').replace(/<(title|desc)\b[\s\S]*?<\/\1>/g, '');
- const notes = [];
- let rootAttrs = null; const els = []; const stack = [{}]; let m;
- const fromStyle = (attrs) => {
- const st = attrs.find(([k]) => k === 'style');
- const out = attrs.filter(([k]) => k !== 'style');
- if (st) for (const decl of st[1].split(';')) { const i = decl.indexOf(':'); if (i > 0) { const k = decl.slice(0, i).trim(), v = decl.slice(i + 1).trim(); if (!out.some(([n]) => n === k)) out.push([k, v]); } }
- return out;
- };
- TAG.lastIndex = 0;
- while ((m = TAG.exec(text))) {
- const [, close, tag, attrs, self] = m;
- const t = tag.toLowerCase();
- if (close) { if (t === 'g') stack.pop(); if (t === 'svg') break; continue; }
- if (t === 'svg' && !rootAttrs) { rootAttrs = attrsOf(attrs).filter(([k]) => k === 'xmlns' || k === 'viewBox'); continue; }
- const a = fromStyle(attrsOf(attrs));
- if (t === 'g') {
- if (a.some(([k]) => k === 'transform')) throw new Error('a group with a transform: move the transform onto its shapes first');
- const inh = { ...stack[stack.length - 1] };
- for (const [k, v] of a) if (PAINT.includes(k)) inh[k] = k === 'opacity' && inh.opacity ? String(+inh.opacity * +v) : v;
- if (!self) stack.push(inh);
- continue;
- }
- if (!DRAW.has(t)) { notes.push(`<${tag}> dropped: not a drawing element`); continue; }
- const inh = stack[stack.length - 1];
- for (const [k, v] of Object.entries(inh)) if (!a.some(([n]) => n === k)) a.push([k, v]);
- els.push({ tag: t, attrs: a });
- }
- if (!rootAttrs) throw new Error('no <svg> root');
- if (!rootAttrs.some(([k]) => k === 'xmlns')) rootAttrs.unshift(['xmlns', 'http://www.w3.org/2000/svg']);
- const vb = (rootAttrs.find(([k]) => k === 'viewBox') || [, '0 0 96 96'])[1].split(/[\s,]+/).map(Number);
- // a tile is the backmost shape: a big rect drawn behind everything else (a calendar body over its rings is not one)
- const tile = els.length > 1 && els[0].tag === 'rect' && +get(els[0], 'width') >= vb[2] * 0.7 && +get(els[0], 'height') >= vb[3] * 0.7 ? 0 : -1;
- if (tile >= 0) {
- // the thing stood on a tile: white lines drawn on it would vanish on a light surface, so they take the tile's colour
- const tc = get(els[tile], 'fill');
- els.splice(tile, 1);
- notes.push('an app-tile background dropped (no plate under an icon)');
- const white = (v) => v && snap(v, palette) && snap(v, palette).tone === 'white';
- if (tc && tc !== 'none') for (const el of els) if (white(get(el, 'stroke')) && (get(el, 'fill') || 'none') === 'none') { set(el, { stroke: tc }); notes.push('a white line on the tile takes the tile colour'); }
- }
- for (const el of els) {
- for (const k of ['fill', 'stroke']) {
- const v = get(el, k);
- if (v === null || v === 'none') continue;
- const s = snap(v, palette);
- if (!s) { set(el, { [k]: 'none' }); continue; }
- if (norm(v) !== s.fill) notes.push(`${v} → ${s.fill} (${s.hue || s.tone})`);
- set(el, { [k]: s.fill });
- }
- if (get(el, 'fill') === null && el.tag !== 'line' && el.tag !== 'polyline' && !get(el, 'stroke')) set(el, { fill: neutralsOf(palette).ink });
- }
- return { svg: serialize({ root: rootAttrs, els }), notes };
- }
- // ---------- render ----------
- /** Renders a flat drawing in a style. params: the `render:` block; palette: the IconStyle palette; opts.idPrefix: the
- * prefix of the ids in <defs> (give each icon its own when several are inlined into one page). */
- function render(src, params, palette, opts) {
- const T = params || {};
- const doc = parse(src);
- const vb = (doc.root.find(([k]) => k === 'viewBox') || [, '0 0 96 96'])[1].split(/[\s,]+/).map(Number);
- const W = vb[2], H = vb[3], cx = vb[0] + W / 2, cy = vb[1] + H / 2;
- const Hs = huesOf(palette), N = neutralsOf(palette);
- const ink = norm(T.ink || N.ink);
- const info = new Map();
- const els = doc.els;
- for (const el of els) {
- const tag = el.tag.toLowerCase();
- let f = get(el, 'fill');
- if (f === null && tag !== 'line' && tag !== 'polyline' && !get(el, 'stroke')) f = '#000000';
- if (tag === 'line') f = 'none';
- const s = get(el, 'stroke');
- const sw = parseFloat(get(el, 'stroke-width') || (s && s !== 'none' ? '1' : '0')) || 0;
- const F = f && f !== 'none' ? snap(f, palette) : null;
- const S = s && s !== 'none' ? snap(s, palette) : null;
- info.set(el, { F, S, sw });
- set(el, { fill: F ? F.fill : 'none', stroke: S ? S.fill : null });
- }
- const ocol = (i) => {
- const h = (i.F && i.F.hue) || (i.S && i.S.hue);
- if (T.outline === 'ink') return ink;
- if (T.outline === 'deep') return h && Hs[h] ? mix(Hs[h][0], Hs[h][1], 0.55) : '#5F5E5B';
- if (T.outline === 'hueink') return h && Hs[h] ? Hs[h][1] : '#4A4945';
- return norm(T.outline);
- };
- let body = [];
- // a shape and its outline twin make one silhouette: the twin's (it is wider, and it takes the shape's fill)
- const skip = new Set(), filled = new Set();
- if (T.outline) {
- for (const el of els) {
- const i = info.get(el);
- const whiteStroke = !i.F && i.S && i.S.tone === 'white';
- if (whiteStroke) { body.push(el); continue; }
- if (i.F && !i.S) {
- const o = set(clone(el), { fill: 'none', stroke: ocol(i), 'stroke-width': num(T.outlineWidth || 1.5), 'stroke-linejoin': 'round', opacity: null });
- body.push(el, o);
- skip.add(el); filled.add(o);
- } else if (i.S) {
- const o = set(clone(el), { fill: i.F ? ocol(i) : 'none', stroke: ocol(i), 'stroke-width': num(i.sw + (T.outlineWidth || 1.5) * 2), 'stroke-linejoin': 'round', opacity: null });
- if (!get(o, 'stroke-linecap')) set(o, { 'stroke-linecap': 'round' });
- body.push(o, el);
- skip.add(el);
- } else body.push(el);
- }
- } else body = els.slice();
- // Each shape is drawn up to five times (shadow, rim, outline, fill). To stay small, its geometry goes once into
- // <defs> and every drawing is a <use> that carries only the paint; the paint of a silhouette sits on its group.
- const defs = new Map(); // geometry text -> id
- const pre = opts && opts.idPrefix ? String(opts.idPrefix) : 'g';
- const ref = (e) => {
- const tag = e.tag.toLowerCase();
- const geom = e.attrs.filter(([k]) => !PAINT_ALL.has(k));
- const key = tag + geom.map(([k, v]) => ` ${k}="${esc(v)}"`).join('');
- if (!defs.has(key)) defs.set(key, pre + defs.size);
- return defs.get(key);
- };
- const paintOf = (e) => e.attrs.filter(([k]) => PAINT_ALL.has(k));
- const use = (e, paint) => `<use href="#${ref(e)}"${paint.map(([k, v]) => ` ${k}="${esc(v)}"`).join('')}/>`;
- const silhouette = (extra) => body.filter((e) => !skip.has(e)).map((e) => {
- const sw = parseFloat(get(e, 'stroke-width') || '0') || 0;
- const hasF = filled.has(e) || (get(e, 'fill') || 'none') !== 'none';
- const st = get(e, 'stroke');
- const p = [['stroke-width', num((st && st !== 'none' ? sw : 0) + extra)]];
- if (!hasF) p.unshift(['fill', 'none']);
- const dash = get(e, 'stroke-dasharray');
- if (dash) p.push(['stroke-dasharray', dash]);
- return use(e, p);
- }).join('');
- const sil = (col) => `fill="${col}" stroke="${col}" stroke-linejoin="round" stroke-linecap="round"`;
- const parts = [];
- if (T.shadow) {
- const off = Array.isArray(T.offset) ? T.offset : [1.5, 3];
- parts.push(`<g transform="translate(${num(off[0])} ${num(off[1])})" opacity="${num(T.shadow)}" ${sil('#000000')}>${silhouette((T.rim || 0) + (T.shadowOnly || 0) + 0.5)}</g>`);
- }
- if (T.rim) parts.push(`<g ${sil(norm(T.rimColor || '#FFFFFF'))}>${silhouette(T.rim)}</g>`);
- parts.push(body.map((e) => use(e, paintOf(e))).join(''));
- const sc = T.scale || 1;
- const root = doc.root.filter(([k]) => k !== 'width' && k !== 'height');
- const d = `<defs>${[...defs].map(([key, id]) => { const sp = key.indexOf(' '); return sp < 0 ? `<${key} id="${id}"/>` : `<${key.slice(0, sp)} id="${id}"${key.slice(sp)}/>`; }).join('')}</defs>`;
- const inner = sc === 1 ? parts.join('') : `<g transform="translate(${num(cx)} ${num(cy)}) scale(${num(sc)}) translate(${num(-cx)} ${num(-cy)})">${parts.join('')}</g>`;
- return `<svg${root.map(([k, v]) => ` ${k}="${esc(v)}"`).join('')}>${d}${inner}</svg>\n`;
- }
- const api = { render, canonical, parse, serialize, snap, toneOf, flatColors, huesOf, neutralsOf, mix, hsl, norm, DRAW: [...DRAW] };
- if (typeof module === 'object' && module && module.exports) module.exports = api;
- else root.SBIconRender = api;
- })(typeof globalThis !== 'undefined' ? globalThis : this);