Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Canvas: Avoid conflicting stylesheets when loading SVG icons #74461

Merged
merged 13 commits into from
Sep 18, 2023
35 changes: 33 additions & 2 deletions public/app/core/components/SVG/SanitizedSVG.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import React from 'react';
import SVG, { Props } from 'react-inlinesvg';
import { v4 as uuidv4 } from 'uuid';

import { textUtil } from '@grafana/data';

export const SanitizedSVG = (props: Props) => {
return <SVG {...props} cacheRequests={true} preProcessor={getCleanSVG} />;
type SanitizedSVGProps = Props & { cleanStyle?: boolean };
let shouldCleanSvgStyle = false;

export const SanitizedSVG = (props: SanitizedSVGProps) => {
const { cleanStyle, ...inlineSvgProps } = props;
shouldCleanSvgStyle = cleanStyle ?? false;
adela-almasan marked this conversation as resolved.
Show resolved Hide resolved

return <SVG {...inlineSvgProps} cacheRequests={true} preProcessor={getCleanSVG} />;
};

let cache = new Map<string, string>();
Expand All @@ -13,7 +20,31 @@ function getCleanSVG(code: string): string {
let clean = cache.get(code);
if (!clean) {
clean = textUtil.sanitizeSVGContent(code);

if (shouldCleanSvgStyle && clean.indexOf('<style type="text/css">') > -1) {
clean = svgStyleCleanup(clean);
}

cache.set(code, clean);
}

return clean;
}

function svgStyleCleanup(elementCode: string) {
adela-almasan marked this conversation as resolved.
Show resolved Hide resolved
let svgId = elementCode.match(new RegExp('<svg.*id\\s*=\\s*([\'"])(.*?)\\1'))?.[2];
if (!svgId) {
svgId = `x${uuidv4()}`;
const pos = elementCode.indexOf('<svg') + 5;
elementCode = elementCode.substring(0, pos) + `id="${svgId}" ` + elementCode.substring(pos);
}

const matchStyle = elementCode.match(new RegExp('<style type="text/css">([\\s\\S]*?)<\\/style>'));
if (matchStyle) {
let svgStyle = matchStyle[0];
let replacedId = svgStyle.replace(/(#(.*?))?\./g, `#${svgId} .`);
elementCode = elementCode.replace(svgStyle, replacedId);
}

return elementCode;
}
1 change: 1 addition & 0 deletions public/app/features/canvas/elements/icon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export function IconDisplay(props: CanvasElementProps) {
src={data.path}
style={svgStyle}
className={svgStyle.strokeWidth ? svgStrokePathClass : undefined}
cleanStyle={true}
adela-almasan marked this conversation as resolved.
Show resolved Hide resolved
/>
);
}
Expand Down