Skip to content

Commit

Permalink
add hash to any svg ids and id references
Browse files Browse the repository at this point in the history
  • Loading branch information
dmca-glasgow committed Apr 8, 2022
1 parent e00896e commit 12e9156
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
6 changes: 4 additions & 2 deletions compiler/src/hast/embed-assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { VFile } from 'vfile';
import { Context } from '../context';
// import { pdfToSvg } from '../pdf/pdf-to-svg';
import { cacheToFile } from '../utils/cache-to-file';
import { getAssetHast } from '../utils/get-asset-hast';
import { getSvgHast } from '../utils/get-svg-hast';
import { failMessage } from '../utils/message';
import { readFile, rehypeParser } from '../utils/utils';

Expand Down Expand Up @@ -81,7 +81,9 @@ async function embedSvg(imgNode: Element, ctx: Context) {
const idx = contents.indexOf('<svg');
const svg = idx === -1 ? contents : contents.slice(idx);
// const optimised = optimize(svg, { multipass: true }).data;
const svgNode = getAssetHast(svg) as Element;
// const svgNode = getAssetHast(svg) as Element;

const svgNode = getSvgHast(svg);

const className = 'knitr-svg';
const properties = {
Expand Down
46 changes: 46 additions & 0 deletions compiler/src/utils/get-svg-hast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import hashSum from 'hash-sum';
import { Element } from 'hast';
import { visit } from 'unist-util-visit';

import { getAssetHast } from './get-asset-hast';

// ensure SVG ids will not collide when inlined
export function getSvgHast(svg: string) {
const svgNode = getAssetHast(svg) as Element;

const hash = hashSum(svg);

visit(svgNode, 'element', (node) => {
if (!node.properties) {
return;
}

if (node.properties.id) {
node.properties.id = `${node.properties.id}-${hash}`;
}

for (const [key, value] of Object.entries(node.properties)) {
const valueStr = String(value);
if (isIdRef(valueStr)) {
node.properties[key] = `${value}-${hash}`;
} else if (isUrlIdRef(valueStr)) {
node.properties[key] = `url(${extractUrlIdRef(valueStr)}-${hash})`;
}
}
});

return svgNode;
}

function isIdRef(value: string) {
return /^#[\w\d-_]+$/.test(value);
}

function isUrlIdRef(value: string) {
return /^url\(#[\w\d-_]+\)$/.test(value);
}

function extractUrlIdRef(value: string) {
const match = value.match(/^url\((#[\w\d-_]+)\)$/);
return match && match[1];
}

0 comments on commit 12e9156

Please sign in to comment.