ShtukbaseStandard
файл пакета→ .shtukbase/packages/icons/lib/svg.ts

lib/svg.ts

233 строки, 12.1 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // The SVG contract of page icons: validate and sanitize. Pure: text in, findings or text out; no file IO.
  2. // An icon is shown through <img>, so a script would not run there anyway; the contract is stricter on purpose:
  3. // the same file may be opened directly, inlined by another front or sent to a model, and it must be safe and
  4. // small everywhere. The parser is a small tokenizer, enough for the flat drawings the contract allows.
  5. export type Finding = { level: 'error' | 'warn'; text: string };
  6. /** What a style adds to the contract (from an IconStyle page); all optional. */
  7. export type StyleRules = { viewBox?: string; colors?: string[]; gradients?: boolean };
  8. /** The elements an icon may use. Everything else (script, style, text, image, foreignObject, animate, filter...) is refused. */
  9. export const ELEMENT_NAMES = [
  10. 'svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon',
  11. 'defs', 'linearGradient', 'radialGradient', 'stop', 'clipPath', 'mask', 'use', 'symbol', 'title', 'desc',
  12. ];
  13. export const ELEMENTS = new Set(ELEMENT_NAMES.map((n) => n.toLowerCase()));
  14. /** Elements sanitize removes but keeps the children of (a link around a shape). The rest is dropped whole. */
  15. const UNWRAP = new Set(['a', 'switch']);
  16. const GRADIENTS = new Set(['lineargradient', 'radialgradient', 'stop']);
  17. const COLOR_ATTRS = new Set(['fill', 'stroke', 'stop-color', 'color', 'flood-color', 'lighting-color']);
  18. const NAMED_OK = new Set(['none', 'transparent']);
  19. export const PROVENANCE = /^<!--\s*icon:/;
  20. type Tok =
  21. | { t: 'open'; name: string; attrs: [string, string][]; self: boolean; raw: string }
  22. | { t: 'close'; name: string; raw: string }
  23. | { t: 'comment'; raw: string }
  24. | { t: 'pi'; raw: string }
  25. | { t: 'decl'; raw: string }
  26. | { t: 'text'; raw: string }
  27. | { t: 'bad'; raw: string };
  28. const ATTR_RE = /([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+)))?/g;
  29. const OPEN_RE = /^<([A-Za-z_][\w:.-]*)((?:\s+[^\s=/>]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>"']+))?)*)\s*(\/?)>/;
  30. export function tokenize(src: string): Tok[] {
  31. const out: Tok[] = [];
  32. let i = 0;
  33. while (i < src.length) {
  34. const lt = src.indexOf('<', i);
  35. if (lt < 0) { out.push({ t: 'text', raw: src.slice(i) }); break; }
  36. if (lt > i) out.push({ t: 'text', raw: src.slice(i, lt) });
  37. const rest = src.slice(lt);
  38. let m: RegExpExecArray | null;
  39. let end = -1;
  40. if (rest.startsWith('<!--')) {
  41. end = rest.indexOf('-->');
  42. if (end < 0) { out.push({ t: 'bad', raw: rest }); break; }
  43. out.push({ t: 'comment', raw: rest.slice(0, end + 3) });
  44. i = lt + end + 3;
  45. } else if (rest.startsWith('<?')) {
  46. end = rest.indexOf('?>');
  47. if (end < 0) { out.push({ t: 'bad', raw: rest }); break; }
  48. out.push({ t: 'pi', raw: rest.slice(0, end + 2) });
  49. i = lt + end + 2;
  50. } else if (rest.startsWith('<!')) {
  51. const sub = /^<!DOCTYPE[^>\[]*\[/i.test(rest) ? rest.indexOf(']') : 0;
  52. end = sub < 0 ? -1 : rest.indexOf('>', sub);
  53. if (end < 0) { out.push({ t: 'bad', raw: rest }); break; }
  54. out.push({ t: 'decl', raw: rest.slice(0, end + 1) });
  55. i = lt + end + 1;
  56. } else if ((m = /^<\/\s*([A-Za-z_][\w:.-]*)\s*>/.exec(rest))) {
  57. out.push({ t: 'close', name: m[1], raw: m[0] });
  58. i = lt + m[0].length;
  59. } else if ((m = OPEN_RE.exec(rest))) {
  60. const attrs: [string, string][] = [];
  61. for (const a of m[2].matchAll(ATTR_RE)) attrs.push([a[1], a[2] ?? a[3] ?? a[4] ?? '']);
  62. out.push({ t: 'open', name: m[1], attrs, self: m[3] === '/', raw: m[0] });
  63. i = lt + m[0].length;
  64. } else {
  65. out.push({ t: 'bad', raw: rest.slice(0, 40) });
  66. break;
  67. }
  68. }
  69. return out;
  70. }
  71. const local = (name: string) => name.toLowerCase().replace(/^svg:/, '');
  72. const short = (s: string, n = 40) => (s.length > n ? s.slice(0, n - 1) + '…' : s);
  73. /** Why an attribute is unsafe, or null. Keeps only local references (#id) and no event handlers. */
  74. function unsafeAttr(name: string, value: string): string | null {
  75. const n = name.toLowerCase();
  76. const v = value.trim().toLowerCase();
  77. if (n.startsWith('on')) return `an event handler (${name})`;
  78. if (n === 'href' || n.endsWith(':href')) return v.startsWith('#') ? null : `a link out of the file (${name}="${short(value)}")`;
  79. if (/javascript:|vbscript:|data:/.test(v)) return `a script or data address in ${name}`;
  80. if (/url\(\s*['"]?(?!#)/.test(v)) return `an external url() in ${name}`;
  81. if (/@import|expression\s*\(/.test(v)) return `a CSS import or expression in ${name}`;
  82. return null;
  83. }
  84. /** An attribute that only editors need (inkscape:*, sodipodi:*, data-*): dropped by sanitize. */
  85. const editorAttr = (name: string) => /^(inkscape|sodipodi|sketch|serif|figma|data-)/i.test(name) || /^xmlns:(inkscape|sodipodi|sketch|serif|figma|rdf|cc|dc)$/i.test(name);
  86. /** Colours an attribute or a style declaration uses: hex in upper case, or a name. */
  87. function colorsOf(name: string, value: string): string[] {
  88. const out: string[] = [];
  89. const add = (v: string) => {
  90. const s = v.trim();
  91. if (!s || NAMED_OK.has(s.toLowerCase()) || s.toLowerCase().startsWith('url(')) return;
  92. out.push(/^#[0-9a-f]{3,8}$/i.test(s) ? normHex(s) : s);
  93. };
  94. if (COLOR_ATTRS.has(name.toLowerCase())) add(value);
  95. else if (name.toLowerCase() === 'style') {
  96. for (const decl of value.split(';')) {
  97. const [k, ...v] = decl.split(':');
  98. if (k && COLOR_ATTRS.has(k.trim().toLowerCase())) add(v.join(':'));
  99. }
  100. }
  101. return out;
  102. }
  103. export function normHex(h: string): string {
  104. let s = h.trim().toUpperCase();
  105. if (/^#[0-9A-F]{3}$/.test(s)) s = '#' + [...s.slice(1)].map((c) => c + c).join('');
  106. return s;
  107. }
  108. /** Checks the text of an SVG icon against the contract. maxBytes: the size budget. */
  109. export function validate(src: string, maxBytes: number, style: StyleRules = {}): Finding[] {
  110. const f: Finding[] = [];
  111. const err = (text: string) => f.push({ level: 'error', text });
  112. const warn = (text: string) => f.push({ level: 'warn', text });
  113. const bytes = new TextEncoder().encode(src).length;
  114. if (bytes > maxBytes) err(`${bytes} bytes, the budget is ${maxBytes}`);
  115. const palette = style.colors && style.colors.length ? new Set(style.colors.map(normHex)) : null;
  116. const stack: string[] = [];
  117. let roots = 0;
  118. let root: Tok | null = null;
  119. const seen = new Set<string>();
  120. for (const tk of tokenize(src)) {
  121. if (tk.t === 'bad') { err(`not well-formed near "${short(tk.raw.replace(/\s+/g, ' '))}"`); break; }
  122. if (tk.t === 'decl') { err(`a declaration ${short(tk.raw)} (DOCTYPE and ENTITY are refused)`); continue; }
  123. if (tk.t === 'pi') { if (!/^<\?xml\s/.test(tk.raw)) err(`a processing instruction ${short(tk.raw)}`); continue; }
  124. if (tk.t === 'comment') continue;
  125. if (tk.t === 'text') {
  126. const top = stack[stack.length - 1] ?? '';
  127. if (tk.raw.trim() && (!top || ELEMENTS.has(top)) && !['title', 'desc'].includes(top)) err(`text outside <title>/<desc>: "${short(tk.raw.trim())}"`);
  128. continue;
  129. }
  130. const name = local(tk.name);
  131. if (tk.t === 'close') {
  132. if (stack.pop() !== name) { err(`</${tk.name}> does not close the open element`); break; }
  133. continue;
  134. }
  135. if (stack.length === 0) { roots++; root = tk; if (roots > 1) err('more than one root element'); }
  136. if (!ELEMENTS.has(name)) {
  137. const why = name === 'text' || name === 'tspan' ? 'text in an icon (it is unreadable at 16 px and needs fonts)'
  138. : name === 'image' ? 'a raster or an external picture' : name === 'script' ? 'a script' : name === 'style' ? 'a <style> sheet (use attributes)'
  139. : name === 'foreignobject' ? 'foreign HTML' : 'an element outside the contract';
  140. if (!seen.has(name)) err(`<${tk.name}>: ${why}`);
  141. seen.add(name);
  142. }
  143. if (GRADIENTS.has(name) && style.gradients === false && !seen.has('gradient')) { err('a gradient: the style draws flat'); seen.add('gradient'); }
  144. for (const [an, av] of tk.attrs) {
  145. const bad = unsafeAttr(an, av);
  146. if (bad) err(`<${tk.name}>: ${bad}`);
  147. if (/currentcolor/i.test(av)) { if (!seen.has('cc')) err('currentColor: it is black inside <img>; give the colour'); seen.add('cc'); }
  148. for (const c of colorsOf(an, av)) {
  149. if (/^currentcolor$/i.test(c)) continue;
  150. if (!c.startsWith('#')) { if (!seen.has('n' + c)) err(`colour "${c}" by name: write it as hex`); seen.add('n' + c); }
  151. else if (palette && !palette.has(c) && !seen.has(c)) { err(`colour ${c} is not in the style's palette`); seen.add(c); }
  152. }
  153. if (editorAttr(an) && !seen.has('ed')) { warn(`editor attributes (${an}): sanitize drops them`); seen.add('ed'); }
  154. }
  155. if (!tk.self) stack.push(name);
  156. }
  157. if (stack.length) err(`<${stack[stack.length - 1]}> is not closed`);
  158. if (!root || root.t !== 'open' || local(root.name) !== 'svg') err('the root element is not <svg>');
  159. else {
  160. const vb = root.attrs.find(([k]) => k === 'viewBox')?.[1];
  161. const n = (vb ?? '').trim().split(/[\s,]+/).map(Number);
  162. if (!vb) err('no viewBox');
  163. else if (n.length !== 4 || n.some((x) => !Number.isFinite(x)) || n[2] <= 0) err(`viewBox "${vb}" is not four numbers`);
  164. else if (n[2] !== n[3]) err(`viewBox "${vb}" is not square`);
  165. else if (style.viewBox && vb.trim().replace(/\s+/g, ' ') !== style.viewBox) warn(`viewBox "${vb}", the style draws on "${style.viewBox}"`);
  166. if (!root.attrs.some(([k, v]) => k === 'xmlns' && v === 'http://www.w3.org/2000/svg')) err('no xmlns="http://www.w3.org/2000/svg" (an <img> will not show it)');
  167. }
  168. return f;
  169. }
  170. /** Makes an SVG fit the contract where that is safe to do: drops what is refused, keeps the drawing. */
  171. export function sanitize(src: string): string {
  172. const out: string[] = [];
  173. let skip = 0; // depth inside a dropped element
  174. const stack: string[] = [];
  175. for (const tk of tokenize(src)) {
  176. if (tk.t === 'bad') break;
  177. if (tk.t === 'decl' || tk.t === 'pi') continue;
  178. if (tk.t === 'comment') { if (!skip && PROVENANCE.test(tk.raw)) out.push(tk.raw); continue; }
  179. if (tk.t === 'text') {
  180. if (!skip && ['title', 'desc'].includes(stack[stack.length - 1] ?? '')) out.push(tk.raw.trim());
  181. continue;
  182. }
  183. const name = local(tk.name);
  184. if (tk.t === 'close') {
  185. if (skip) { skip--; if (skip) continue; stack.pop(); continue; }
  186. if (stack.pop()?.startsWith('#')) continue; // an unwrapped element: its children stay
  187. out.push(`</${tk.name}>`);
  188. continue;
  189. }
  190. if (!skip && UNWRAP.has(name)) { if (!tk.self) stack.push('#' + name); continue; }
  191. if (skip || !ELEMENTS.has(name)) { if (!tk.self) skip++; if (!tk.self && skip === 1) stack.push(name); continue; }
  192. const attrs: string[] = [];
  193. let hasNs = false;
  194. for (const [an, av] of tk.attrs) {
  195. if (unsafeAttr(an, av) || editorAttr(an)) continue;
  196. if (/currentcolor/i.test(av)) continue;
  197. if (an === 'xmlns') hasNs = true;
  198. attrs.push(`${an}="${av.replace(/"/g, '&quot;')}"`);
  199. }
  200. if (name === 'svg' && stack.length === 0) {
  201. if (!hasNs) attrs.unshift('xmlns="http://www.w3.org/2000/svg"');
  202. if (!tk.attrs.some(([k]) => k === 'viewBox')) {
  203. const w = Number(tk.attrs.find(([k]) => k === 'width')?.[1]), hh = Number(tk.attrs.find(([k]) => k === 'height')?.[1]);
  204. if (w > 0 && w === hh) attrs.push(`viewBox="0 0 ${w} ${hh}"`);
  205. }
  206. }
  207. out.push(`<${tk.name}${attrs.length ? ' ' + attrs.join(' ') : ''}${tk.self ? '/' : ''}>`);
  208. if (!tk.self) stack.push(name);
  209. }
  210. return out.join('\n').replace(/\n(?=<\/(title|desc)>)/g, '').replace(/(<(title|desc)[^>]*>)\n/g, '$1') + '\n';
  211. }
  212. /** A short icon that is not a path: an emoji (or a few symbols), no letters, at most 4 graphemes. */
  213. export function isGlyph(v: string): boolean {
  214. const s = v.trim();
  215. // letters, spaces and path characters are text, not an icon; plain ASCII ("1", "->") is not an emoji, a keycap "1️⃣" is
  216. if (!s || /[\p{L}\s/\\<>]/u.test(s) || !/[^\x00-\x7F]/.test(s)) return false;
  217. const seg = typeof Intl !== 'undefined' && 'Segmenter' in Intl ? [...new Intl.Segmenter().segment(s)].length : [...s].length;
  218. return seg <= 4;
  219. }
  220. /** A path to an SVG file (root-absolute "/assets/icons/x.svg" or relative to the page). */
  221. export const isSvgPath = (v: unknown): v is string => typeof v === 'string' && /^[^\s<>:]+\.svg$/i.test(v.trim());