Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import React from 'react';
import { labels } from '@monkvision/sights';
import clsx from 'clsx';
import styles from './LabelTable.module.css';
Expand Down
3 changes: 2 additions & 1 deletion documentation/src/components/Sights/SightCard/SightCard.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { Fragment, useMemo, useRef } from 'react';
import { Fragment, useMemo, useRef } from 'react';
import { useColorMode } from '@docusaurus/theme-common';
import { labels, sights } from '@monkvision/sights';
import { Sight, VehicleDetails, VehicleModel } from '@monkvision/types';
Expand All @@ -25,6 +25,7 @@ const vehicleModelDisplayOverlays: Record<
[VehicleModel.TESLAMY]: sights['teslamy-F9Nr3VtK'].overlay,
[VehicleModel.TESLAMX]: sights['teslamx-aT9LpF7y'].overlay,
[VehicleModel.TESLAMS]: sights['teslams-Km9XrLp5'].overlay,
[VehicleModel.TESLAC]: sights['teslac-Rx8SpL6m'].overlay,
};

export interface SightCardProps {
Expand Down
2 changes: 1 addition & 1 deletion documentation/src/components/Sights/TopBar/TopBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { labels, sights, vehicles } from '@monkvision/sights';
import { SearchBar } from '@site/src/components';
import { SightCard } from '@site/src/components/Sights/SightCard';
import clsx from 'clsx';
import React, { ReactElement, useRef } from 'react';
import { ReactElement, useRef } from 'react';
import styles from './TopBar.module.css';

export interface ListItem {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { SVGProps, useMemo } from 'react';
import { DynamicSVGCustomizationFunctions, useXMLParser } from './hooks';
import { DynamicSVGCustomizationFunctions, useSVGUniqueIds, useXMLParser } from './hooks';
import { SVGElement } from './SVGElement';

/**
Expand Down Expand Up @@ -48,15 +48,16 @@ export interface DynamicSVGProps
*/
export function DynamicSVG({ svg, ...passThroughProps }: DynamicSVGProps) {
const doc = useXMLParser(svg);
const uniqueDoc = useSVGUniqueIds(doc);
const svgEl = useMemo(() => {
const element = doc.children[0] as SVGSVGElement;
const element = uniqueDoc.children[0] as SVGSVGElement;
if (element.tagName !== 'svg') {
throw new Error(
`Invalid SVG string provided to the DynamicSVG component: expected <svg> tag as the first children of XML document but got <${element.tagName}>.`,
);
}
return element;
}, [doc]);
}, [uniqueDoc]);

return <SVGElement element={svgEl} {...passThroughProps} />;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './useCustomAttributes';
export * from './useInnerHTML';
export * from './useJSXTransformAttributes';
export * from './useXMLParser';
export * from './useSVGUniqueIds';
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { useMemo } from 'react';

let idCounter = 0;

/**
* Attributes that can contain URL references to SVG IDs
*/
const URL_ATTRIBUTES = [
'mask',
'clip-path',
'clipPath',
'fill',
'stroke',
'filter',
'marker-start',
'marker-mid',
'marker-end',
'href',
'xlink:href',
];

/**
* Makes all IDs in an SVG document unique by adding a prefix.
* This prevents ID collisions when multiple SVGs are rendered on the same page.
*
* @param doc - The parsed SVG document
* @param prefix - A unique prefix to add to all IDs
*/
function makeIdsUnique(doc: Document, prefix: string): void {
const idMap = new Map<string, string>();

const elementsWithId = doc.querySelectorAll('[id]');
elementsWithId.forEach((element) => {
const oldId = element.getAttribute('id');
if (oldId) {
const newId = `${prefix}-${oldId}`;
idMap.set(oldId, newId);
element.setAttribute('id', newId);
}
});

const allElements = doc.querySelectorAll('*');
allElements.forEach((element) => {
URL_ATTRIBUTES.forEach((attr) => {
const value = element.getAttribute(attr);
if (value) {
let newValue = value;
const urlPattern = /url\(#([^)]+)\)/g;
newValue = newValue.replace(urlPattern, (match, id) => {
const newId = idMap.get(id);
return newId ? `url(#${newId})` : match;
});

if (newValue.startsWith('#')) {
const id = newValue.substring(1);
const newId = idMap.get(id);
if (newId) {
newValue = `#${newId}`;
}
}
if (newValue !== value) {
element.setAttribute(attr, newValue);
}
}
});

const style = element.getAttribute('style');
if (style) {
let newStyle = style;
const urlPattern = /url\(#([^)]+)\)/g;
newStyle = newStyle.replace(urlPattern, (match, id) => {
const newId = idMap.get(id);
return newId ? `url(#${newId})` : match;
});
if (newStyle !== style) {
element.setAttribute('style', newStyle);
}
}
});
}

/**
* Hook that ensures all IDs within an SVG document are unique by adding a prefix.
* This prevents ID collisions when multiple SVGs with the same internal IDs are rendered on the same page.
*
* @param doc - The parsed SVG document
* @returns The same document with unique IDs
*/
export function useSVGUniqueIds(doc: Document): Document {
return useMemo(() => {
const uniquePrefix = `svg-${idCounter}`;
idCounter += 1;
makeIdsUnique(doc, uniquePrefix);
return doc;
}, [doc]);
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
jest.mock('../../../src/components/DynamicSVG/hooks', () => ({
useXMLParser: jest.fn(() => ({ children: [{ tagName: 'svg' }] })),
useSVGUniqueIds: jest.fn((doc) => doc),
}));

jest.mock('../../../src/components/DynamicSVG/SVGElement.tsx', () => ({
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { renderHook } from '@testing-library/react';
import { useSVGUniqueIds } from '../../../../src/components/DynamicSVG/hooks';

describe('useSVGUniqueIds hook', () => {
it('should make all IDs in an SVG unique', () => {
const svg = `
<svg>
<defs>
<clipPath id="a"><rect/></clipPath>
<mask id="b"><rect/></mask>
</defs>
<g clip-path="url(#a)">
<rect mask="url(#b)"/>
</g>
</svg>
`;
const doc = new DOMParser().parseFromString(svg, 'text/xml');

const { result } = renderHook(() => useSVGUniqueIds(doc));
const uniqueDoc = result.current;

const clipPath = uniqueDoc.querySelector('clipPath');
const mask = uniqueDoc.querySelector('mask');
expect(clipPath?.getAttribute('id')).toMatch(/^svg-\d+-a$/);
expect(mask?.getAttribute('id')).toMatch(/^svg-\d+-b$/);

const g = uniqueDoc.querySelector('g');
const rect = uniqueDoc.querySelector('rect[mask]');
expect(g?.getAttribute('clip-path')).toMatch(/^url\(#svg-\d+-a\)$/);
expect(rect?.getAttribute('mask')).toMatch(/^url\(#svg-\d+-b\)$/);
});

it('should handle multiple SVGs with same IDs independently', () => {
const svg1 = '<svg><mask id="a"><rect/></mask></svg>';
const svg2 = '<svg><mask id="a"><rect/></mask></svg>';

const doc1 = new DOMParser().parseFromString(svg1, 'text/xml');
const doc2 = new DOMParser().parseFromString(svg2, 'text/xml');

const { result: result1 } = renderHook(() => useSVGUniqueIds(doc1));
const { result: result2 } = renderHook(() => useSVGUniqueIds(doc2));

const id1 = result1.current.querySelector('mask')?.getAttribute('id');
const id2 = result2.current.querySelector('mask')?.getAttribute('id');

expect(id1).toBeTruthy();
expect(id2).toBeTruthy();
expect(id1).not.toBe(id2);
});

it('should handle href and xlink:href attributes', () => {
const svg = `
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<linearGradient id="grad1"><stop/></linearGradient>
</defs>
<use href="#grad1"/>
<use xlink:href="#grad1"/>
</svg>
`;
const doc = new DOMParser().parseFromString(svg, 'text/xml');

const { result } = renderHook(() => useSVGUniqueIds(doc));
const uniqueDoc = result.current;

const gradient = uniqueDoc.querySelector('linearGradient');
const gradientId = gradient?.getAttribute('id');

if (gradientId) {
expect(gradientId).toMatch(/^svg-\d+-grad1$/);

const uses = uniqueDoc.querySelectorAll('use');
uses.forEach((use) => {
const href = use.getAttribute('href') || use.getAttribute('xlink:href');
if (href) {
expect(href).toBe(`#${gradientId}`);
}
});
} else {
expect(uniqueDoc).toBeTruthy();
}
});

it('should handle style attribute with url() references', () => {
const svg = `
<svg>
<defs>
<filter id="blur"><feGaussianBlur/></filter>
</defs>
<rect style="filter: url(#blur)"/>
</svg>
`;
const doc = new DOMParser().parseFromString(svg, 'text/xml');

const { result } = renderHook(() => useSVGUniqueIds(doc));
const uniqueDoc = result.current;

const filter = uniqueDoc.querySelector('filter');
const filterId = filter?.getAttribute('id');
expect(filterId).toMatch(/^svg-\d+-blur$/);

const rect = uniqueDoc.querySelector('rect');
const style = rect?.getAttribute('style');
expect(style).toBe(`filter: url(#${filterId})`);
});
});
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading