Spaces:
Running
Running
| 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); | |
| } | |