ShtukbaseStandard
package file→ .shtukbase/packages/icons/lib/render.js

lib/render.js

321 lines, 18.1 KB.

  1. // The icon renderer: turns a flat drawing into an icon style. Pure (text in, text out), no DOM, no dependencies, so the
  2. // same file runs under Bun (the `build` of a set package, the checks) and in the icon lens (copied to
  3. // lib/design/icon-render.js, where it sets window.SBIconRender).
  4. //
  5. // A port of `themed` from the Shtukbase package-map mock (shtuks/projects/shtukbase/assets/logo/package-map/page.tpl.html):
  6. // the outline in a colour of the detail's hue, the rim (a silhouette in the rim colour), the soft shadow (a black
  7. // silhouette, shifted, with opacity) and the scale around the centre.
  8. //
  9. // A flat drawing is canonical: one <svg> root with xmlns and a square viewBox, and inside only drawing elements
  10. // (path, rect, circle, ellipse, polygon, polyline, line) with their paint as attributes; no groups, no style
  11. // attributes. `canonical` (in the set package's import) brings an outside drawing to this form.
  12. //
  13. // The render parameters (the `render:` block of an IconStyle page):
  14. // outline 'ink' | 'deep' | 'hueink' | '#rrggbb' | null the outline colour: ink, a deep step of the
  15. // detail's hue (main mixed 55% to its dark step), the dark step of the hue, or a fixed colour
  16. // outlineWidth number on the 96 grid
  17. // rim number the rim width (a silhouette under the drawing); 0 or absent: no rim
  18. // rimColor '#rrggbb'
  19. // shadow number the shadow opacity; 0 or absent: no shadow
  20. // offset [x, y] the shadow offset (default [1.5, 3])
  21. // shadowOnly number extra shadow spread where there is no rim (style 81)
  22. // scale number the drawing's scale around the centre
  23. // ink '#rrggbb' the ink colour (default #2B2B2E)
  24. (function (root) {
  25. 'use strict';
  26. const DRAW = new Set(['path', 'rect', 'circle', 'ellipse', 'polygon', 'polyline', 'line']);
  27. const INK = '#2B2B2E';
  28. // ---------- colour ----------
  29. function hex(c) {
  30. let s = String(c).replace('#', '');
  31. if (s.length === 3) s = s.split('').map((x) => x + x).join('');
  32. return [0, 2, 4].map((i) => parseInt(s.slice(i, i + 2), 16));
  33. }
  34. const toHex = (a) => '#' + a.map((v) => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, '0')).join('').toUpperCase();
  35. const mix = (a, b, t) => { const A = hex(a), B = hex(b); return toHex(A.map((v, i) => v + (B[i] - v) * t)); };
  36. 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; };
  37. function hsl(c) {
  38. const [r, g, b] = hex(c).map((v) => v / 255);
  39. const mx = Math.max(r, g, b), mn = Math.min(r, g, b), l = (mx + mn) / 2;
  40. let h = 0, s = 0;
  41. if (mx !== mn) {
  42. const d = mx - mn;
  43. s = l > 0.5 ? d / (2 - mx - mn) : d / (mx + mn);
  44. h = mx === r ? (g - b) / d + (g < b ? 6 : 0) : mx === g ? (b - r) / d + 2 : (r - g) / d + 4;
  45. h *= 60;
  46. }
  47. return [h, s, l];
  48. }
  49. /** The hues of a palette: an entry that is a list [main, dark, light, ...] is a hue. */
  50. function huesOf(palette) {
  51. const out = {};
  52. for (const [k, v] of Object.entries(palette || {})) if (Array.isArray(v) && v.length >= 2) out[k] = v.map(norm);
  53. return out;
  54. }
  55. /** The neutrals of a palette, with the defaults of the Shtukbase palette. */
  56. function neutralsOf(palette) {
  57. const p = palette || {};
  58. const one = (v, d) => norm(Array.isArray(v) ? v[0] : v || d);
  59. return { ink: one(p.ink, INK), white: one(p.white, '#FFFFFF'), grey: one(p.grey, '#8A8680'), greyLight: one(p.greyLight, '#C9C6BF') };
  60. }
  61. /**
  62. * Snaps any colour to the palette (the rule of the package-map mock): very light to white, greys to ink or grey,
  63. * else the nearest hue by angle and a step by lightness (light, main, deep = main mixed 42% to dark, dark).
  64. * Returns {fill, hue, tone} or null for none / transparent / url().
  65. */
  66. function snap(c, palette) {
  67. if (!c) return null;
  68. let s = String(c).trim().toLowerCase();
  69. if (s === 'none' || s === 'transparent' || s.startsWith('url')) return null;
  70. if (s === 'white') s = '#ffffff';
  71. if (s === 'black') s = '#000000';
  72. const H = huesOf(palette), N = neutralsOf(palette);
  73. if (!s.startsWith('#')) return { fill: s, hue: null, tone: 'grey' };
  74. const exact = toneOf(s, palette);
  75. if (exact) return exact;
  76. const [h, sat, l] = hsl(s);
  77. if (l >= 0.9) return { fill: N.white, hue: null, tone: 'white' };
  78. if (sat < 0.16 || l < 0.12) {
  79. if (l < 0.32) return { fill: N.ink, hue: null, tone: 'ink' };
  80. return { fill: l > 0.66 ? N.greyLight : N.grey, hue: null, tone: 'grey' };
  81. }
  82. let best = null, bd = 999;
  83. for (const [k, v] of Object.entries(H)) {
  84. const ph = hsl(v[0])[0];
  85. const d = Math.min(Math.abs(h - ph), 360 - Math.abs(h - ph));
  86. if (d < bd) { bd = d; best = k; }
  87. }
  88. if (!best) return { fill: norm(s), hue: null, tone: 'grey' };
  89. const P = H[best];
  90. if (l >= 0.74) return { fill: P[2] || P[0], hue: best, tone: 'light' };
  91. if (l < 0.3) return { fill: P[1], hue: best, tone: 'ink' };
  92. if (l < 0.4) return { fill: mix(P[0], P[1], 0.42), hue: best, tone: 'deep' };
  93. return { fill: P[0], hue: best, tone: 'main' };
  94. }
  95. /** The tone of a colour that is already in the palette (exactly), or null. */
  96. function toneOf(c, palette) {
  97. const s = norm(c), H = huesOf(palette), N = neutralsOf(palette);
  98. for (const [k, v] of Object.entries(H)) {
  99. if (s === v[0]) return { fill: s, hue: k, tone: 'main' };
  100. if (s === v[1]) return { fill: s, hue: k, tone: 'ink' };
  101. if (s === v[2]) return { fill: s, hue: k, tone: 'light' };
  102. if (s === mix(v[0], v[1], 0.42) || s === v[3]) return { fill: s, hue: k, tone: 'deep' };
  103. }
  104. if (s === N.white) return { fill: s, hue: null, tone: 'white' };
  105. if (s === N.ink) return { fill: s, hue: null, tone: 'ink' };
  106. if (s === N.grey || s === N.greyLight) return { fill: s, hue: null, tone: 'grey' };
  107. return null;
  108. }
  109. /** Every colour a flat drawing may use: each hue's main, dark, light and deep steps, ink, the greys and white. */
  110. function flatColors(palette) {
  111. const H = huesOf(palette), N = neutralsOf(palette);
  112. const out = new Set([N.ink, N.white, N.grey, N.greyLight]);
  113. 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)); }
  114. return [...out];
  115. }
  116. // ---------- the flat form ----------
  117. const TAG = /<(\/?)([A-Za-z][\w:.-]*)((?:\s+[^\s=/>]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>/g;
  118. const ATTR = /([^\s=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
  119. 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; }
  120. /** Parses a flat drawing: {root: [[name, value]...], els: [{tag, attrs}]}. Throws on what is not the flat form. */
  121. function parse(src) {
  122. const text = String(src).replace(/<\?xml[\s\S]*?\?>/g, '').replace(/<!--[\s\S]*?-->/g, '');
  123. let rootAttrs = null; const els = []; let m;
  124. TAG.lastIndex = 0;
  125. while ((m = TAG.exec(text))) {
  126. const [, close, tag, attrs, self] = m;
  127. const t = tag.toLowerCase();
  128. if (close) { if (t === 'svg') break; continue; }
  129. if (t === 'svg' && !rootAttrs) { rootAttrs = attrsOf(attrs); continue; }
  130. 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; }
  131. if (!DRAW.has(t)) throw new Error(`<${tag}> is not a drawing element of the flat form`);
  132. els.push({ tag, attrs: attrsOf(attrs) });
  133. }
  134. if (!rootAttrs) throw new Error('no <svg> root');
  135. return { root: rootAttrs, els };
  136. }
  137. const get = (el, k) => { const a = el.attrs.find(([n]) => n === k); return a ? a[1] : null; };
  138. function set(el, o) {
  139. for (const [k, v] of Object.entries(o)) {
  140. const i = el.attrs.findIndex(([n]) => n === k);
  141. if (v === null || v === undefined) { if (i >= 0) el.attrs.splice(i, 1); }
  142. else if (i >= 0) el.attrs[i][1] = String(v);
  143. else el.attrs.push([k, String(v)]);
  144. }
  145. return el;
  146. }
  147. const clone = (el) => ({ tag: el.tag, attrs: el.attrs.map(([k, v]) => [k, v]) });
  148. const esc = (v) => String(v).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
  149. const out1 = (el) => `<${el.tag}${el.attrs.map(([k, v]) => ` ${k}="${esc(v)}"`).join('')}/>`;
  150. const num = (n) => String(Math.round(n * 1000) / 1000);
  151. /** Writes a flat drawing in the canonical text form. */
  152. function serialize(doc) {
  153. const root = doc.root.filter(([k]) => k !== 'width' && k !== 'height');
  154. return `<svg${root.map(([k, v]) => ` ${k}="${esc(v)}"`).join('')}>\n${doc.els.map(out1).join('\n')}\n</svg>\n`;
  155. }
  156. 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']);
  157. const PAINT = ['fill', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'stroke-dasharray', 'opacity', 'fill-opacity', 'stroke-opacity', 'fill-rule'];
  158. /**
  159. * Brings an outside drawing to the flat form in a palette, without redrawing it: groups are dissolved (their paint
  160. * goes down to the shapes that do not set their own; a group transform is refused), `style` attributes become
  161. * attributes, an app-tile background (a rect over 70% of the canvas) is dropped, every colour is snapped to the
  162. * palette, width, height, title and desc go. Returns {svg, notes}.
  163. */
  164. function canonical(src, palette) {
  165. const text = String(src).replace(/<\?xml[\s\S]*?\?>/g, '').replace(/<!--[\s\S]*?-->/g, '').replace(/<(title|desc)\b[\s\S]*?<\/\1>/g, '');
  166. const notes = [];
  167. let rootAttrs = null; const els = []; const stack = [{}]; let m;
  168. const fromStyle = (attrs) => {
  169. const st = attrs.find(([k]) => k === 'style');
  170. const out = attrs.filter(([k]) => k !== 'style');
  171. 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]); } }
  172. return out;
  173. };
  174. TAG.lastIndex = 0;
  175. while ((m = TAG.exec(text))) {
  176. const [, close, tag, attrs, self] = m;
  177. const t = tag.toLowerCase();
  178. if (close) { if (t === 'g') stack.pop(); if (t === 'svg') break; continue; }
  179. if (t === 'svg' && !rootAttrs) { rootAttrs = attrsOf(attrs).filter(([k]) => k === 'xmlns' || k === 'viewBox'); continue; }
  180. const a = fromStyle(attrsOf(attrs));
  181. if (t === 'g') {
  182. if (a.some(([k]) => k === 'transform')) throw new Error('a group with a transform: move the transform onto its shapes first');
  183. const inh = { ...stack[stack.length - 1] };
  184. for (const [k, v] of a) if (PAINT.includes(k)) inh[k] = k === 'opacity' && inh.opacity ? String(+inh.opacity * +v) : v;
  185. if (!self) stack.push(inh);
  186. continue;
  187. }
  188. if (!DRAW.has(t)) { notes.push(`<${tag}> dropped: not a drawing element`); continue; }
  189. const inh = stack[stack.length - 1];
  190. for (const [k, v] of Object.entries(inh)) if (!a.some(([n]) => n === k)) a.push([k, v]);
  191. els.push({ tag: t, attrs: a });
  192. }
  193. if (!rootAttrs) throw new Error('no <svg> root');
  194. if (!rootAttrs.some(([k]) => k === 'xmlns')) rootAttrs.unshift(['xmlns', 'http://www.w3.org/2000/svg']);
  195. const vb = (rootAttrs.find(([k]) => k === 'viewBox') || [, '0 0 96 96'])[1].split(/[\s,]+/).map(Number);
  196. // a tile is the backmost shape: a big rect drawn behind everything else (a calendar body over its rings is not one)
  197. 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;
  198. if (tile >= 0) {
  199. // the thing stood on a tile: white lines drawn on it would vanish on a light surface, so they take the tile's colour
  200. const tc = get(els[tile], 'fill');
  201. els.splice(tile, 1);
  202. notes.push('an app-tile background dropped (no plate under an icon)');
  203. const white = (v) => v && snap(v, palette) && snap(v, palette).tone === 'white';
  204. 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'); }
  205. }
  206. for (const el of els) {
  207. for (const k of ['fill', 'stroke']) {
  208. const v = get(el, k);
  209. if (v === null || v === 'none') continue;
  210. const s = snap(v, palette);
  211. if (!s) { set(el, { [k]: 'none' }); continue; }
  212. if (norm(v) !== s.fill) notes.push(`${v} → ${s.fill} (${s.hue || s.tone})`);
  213. set(el, { [k]: s.fill });
  214. }
  215. if (get(el, 'fill') === null && el.tag !== 'line' && el.tag !== 'polyline' && !get(el, 'stroke')) set(el, { fill: neutralsOf(palette).ink });
  216. }
  217. return { svg: serialize({ root: rootAttrs, els }), notes };
  218. }
  219. // ---------- render ----------
  220. /** Renders a flat drawing in a style. params: the `render:` block; palette: the IconStyle palette; opts.idPrefix: the
  221. * prefix of the ids in <defs> (give each icon its own when several are inlined into one page). */
  222. function render(src, params, palette, opts) {
  223. const T = params || {};
  224. const doc = parse(src);
  225. const vb = (doc.root.find(([k]) => k === 'viewBox') || [, '0 0 96 96'])[1].split(/[\s,]+/).map(Number);
  226. const W = vb[2], H = vb[3], cx = vb[0] + W / 2, cy = vb[1] + H / 2;
  227. const Hs = huesOf(palette), N = neutralsOf(palette);
  228. const ink = norm(T.ink || N.ink);
  229. const info = new Map();
  230. const els = doc.els;
  231. for (const el of els) {
  232. const tag = el.tag.toLowerCase();
  233. let f = get(el, 'fill');
  234. if (f === null && tag !== 'line' && tag !== 'polyline' && !get(el, 'stroke')) f = '#000000';
  235. if (tag === 'line') f = 'none';
  236. const s = get(el, 'stroke');
  237. const sw = parseFloat(get(el, 'stroke-width') || (s && s !== 'none' ? '1' : '0')) || 0;
  238. const F = f && f !== 'none' ? snap(f, palette) : null;
  239. const S = s && s !== 'none' ? snap(s, palette) : null;
  240. info.set(el, { F, S, sw });
  241. set(el, { fill: F ? F.fill : 'none', stroke: S ? S.fill : null });
  242. }
  243. const ocol = (i) => {
  244. const h = (i.F && i.F.hue) || (i.S && i.S.hue);
  245. if (T.outline === 'ink') return ink;
  246. if (T.outline === 'deep') return h && Hs[h] ? mix(Hs[h][0], Hs[h][1], 0.55) : '#5F5E5B';
  247. if (T.outline === 'hueink') return h && Hs[h] ? Hs[h][1] : '#4A4945';
  248. return norm(T.outline);
  249. };
  250. let body = [];
  251. // a shape and its outline twin make one silhouette: the twin's (it is wider, and it takes the shape's fill)
  252. const skip = new Set(), filled = new Set();
  253. if (T.outline) {
  254. for (const el of els) {
  255. const i = info.get(el);
  256. const whiteStroke = !i.F && i.S && i.S.tone === 'white';
  257. if (whiteStroke) { body.push(el); continue; }
  258. if (i.F && !i.S) {
  259. const o = set(clone(el), { fill: 'none', stroke: ocol(i), 'stroke-width': num(T.outlineWidth || 1.5), 'stroke-linejoin': 'round', opacity: null });
  260. body.push(el, o);
  261. skip.add(el); filled.add(o);
  262. } else if (i.S) {
  263. 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 });
  264. if (!get(o, 'stroke-linecap')) set(o, { 'stroke-linecap': 'round' });
  265. body.push(o, el);
  266. skip.add(el);
  267. } else body.push(el);
  268. }
  269. } else body = els.slice();
  270. // Each shape is drawn up to five times (shadow, rim, outline, fill). To stay small, its geometry goes once into
  271. // <defs> and every drawing is a <use> that carries only the paint; the paint of a silhouette sits on its group.
  272. const defs = new Map(); // geometry text -> id
  273. const pre = opts && opts.idPrefix ? String(opts.idPrefix) : 'g';
  274. const ref = (e) => {
  275. const tag = e.tag.toLowerCase();
  276. const geom = e.attrs.filter(([k]) => !PAINT_ALL.has(k));
  277. const key = tag + geom.map(([k, v]) => ` ${k}="${esc(v)}"`).join('');
  278. if (!defs.has(key)) defs.set(key, pre + defs.size);
  279. return defs.get(key);
  280. };
  281. const paintOf = (e) => e.attrs.filter(([k]) => PAINT_ALL.has(k));
  282. const use = (e, paint) => `<use href="#${ref(e)}"${paint.map(([k, v]) => ` ${k}="${esc(v)}"`).join('')}/>`;
  283. const silhouette = (extra) => body.filter((e) => !skip.has(e)).map((e) => {
  284. const sw = parseFloat(get(e, 'stroke-width') || '0') || 0;
  285. const hasF = filled.has(e) || (get(e, 'fill') || 'none') !== 'none';
  286. const st = get(e, 'stroke');
  287. const p = [['stroke-width', num((st && st !== 'none' ? sw : 0) + extra)]];
  288. if (!hasF) p.unshift(['fill', 'none']);
  289. const dash = get(e, 'stroke-dasharray');
  290. if (dash) p.push(['stroke-dasharray', dash]);
  291. return use(e, p);
  292. }).join('');
  293. const sil = (col) => `fill="${col}" stroke="${col}" stroke-linejoin="round" stroke-linecap="round"`;
  294. const parts = [];
  295. if (T.shadow) {
  296. const off = Array.isArray(T.offset) ? T.offset : [1.5, 3];
  297. 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>`);
  298. }
  299. if (T.rim) parts.push(`<g ${sil(norm(T.rimColor || '#FFFFFF'))}>${silhouette(T.rim)}</g>`);
  300. parts.push(body.map((e) => use(e, paintOf(e))).join(''));
  301. const sc = T.scale || 1;
  302. const root = doc.root.filter(([k]) => k !== 'width' && k !== 'height');
  303. 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>`;
  304. const inner = sc === 1 ? parts.join('') : `<g transform="translate(${num(cx)} ${num(cy)}) scale(${num(sc)}) translate(${num(-cx)} ${num(-cy)})">${parts.join('')}</g>`;
  305. return `<svg${root.map(([k, v]) => ` ${k}="${esc(v)}"`).join('')}>${d}${inner}</svg>\n`;
  306. }
  307. const api = { render, canonical, parse, serialize, snap, toneOf, flatColors, huesOf, neutralsOf, mix, hsl, norm, DRAW: [...DRAW] };
  308. if (typeof module === 'object' && module && module.exports) module.exports = api;
  309. else root.SBIconRender = api;
  310. })(typeof globalThis !== 'undefined' ? globalThis : this);