-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add hash to any svg ids and id references
- Loading branch information
1 parent
e00896e
commit 12e9156
Showing
2 changed files
with
50 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | ||
} |