File size: 1,718 Bytes
d7da259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { getOwnColor, getEffectiveColor } from './colorUtils';

export function filterSvgByColors(svgEl, groupColors) {
  // Phase 1: resolve effective colors BEFORE modifying DOM
  const allElements = svgEl.querySelectorAll('*');
  const resolved = new Map();
  for (const el of allElements) {
    if (el.tagName === 'svg' || el.tagName === 'defs' || el.tagName === 'g') continue;
    resolved.set(el, {
      fill: getEffectiveColor(el, 'fill'),
      stroke: getEffectiveColor(el, 'stroke'),
    });
  }

  // Phase 2: apply visibility changes
  for (const el of allElements) {
    if (el.tagName === 'svg' || el.tagName === 'defs') continue;

    if (el.tagName === 'g') {
      const ownFill = getOwnColor(el, 'fill');
      if (ownFill && !groupColors.has(ownFill)) {
        el.setAttribute('fill', 'none');
      }
      const ownStroke = getOwnColor(el, 'stroke');
      if (ownStroke && !groupColors.has(ownStroke)) {
        el.setAttribute('stroke', 'none');
      }
      continue;
    }

    const r = resolved.get(el);
    if (!r) continue;
    const fillInGroup = r.fill && groupColors.has(r.fill);
    const strokeInGroup = r.stroke && groupColors.has(r.stroke);

    if (!fillInGroup && !strokeInGroup) {
      el.setAttribute('fill', 'none');
      el.setAttribute('stroke', 'none');
    } else {
      if (!fillInGroup) {
        el.setAttribute('fill', 'none');
      }
      if (r.stroke && !strokeInGroup) {
        el.setAttribute('stroke', 'none');
      }
    }
  }
}

export function buildFilteredSvgHtml(svgDoc, groupColorSet) {
  const svgEl = svgDoc.querySelector('svg').cloneNode(true);
  filterSvgByColors(svgEl, groupColorSet);
  return new XMLSerializer().serializeToString(svgEl);
}