Skip to content

Commit 29fde15

Browse files
committed
feat: [RichText] add data-cui-href when the href of the link is removed
1 parent 5d51d25 commit 29fde15

File tree

2 files changed

+24
-12
lines changed

2 files changed

+24
-12
lines changed
Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,27 @@
11
import DOMPurify from 'dompurify';
22

3-
function getLinkAttr(node: Element, attr: string) {
4-
return (node.nodeName === 'A' && node.getAttribute(attr)) || '';
5-
}
6-
7-
// set `a` element owning target to `target=_blank`
8-
// https://github.com/cure53/DOMPurify/issues/317
93
DOMPurify.addHook('beforeSanitizeAttributes', (node: Element) => {
10-
if (getLinkAttr(node, 'target')) {
11-
node.setAttribute('rel', 'noopener');
4+
if (node instanceof HTMLElement && node.hasAttribute('href')) {
5+
const href = node.getAttribute('href');
6+
7+
if (href) {
8+
node.dataset.cuiHref = href;
9+
}
10+
if (node.getAttribute('target') === '_blank') {
11+
node.dataset.cuiTarget = '1';
12+
}
1213
}
1314
});
1415

1516
DOMPurify.addHook('afterSanitizeAttributes', (node: Element) => {
16-
if (getLinkAttr(node, 'rel') === 'noopener') {
17-
node.setAttribute('target', '_blank');
17+
if (node instanceof HTMLElement) {
18+
if (node.dataset.cuiHref && node.hasAttribute('href')) {
19+
node.removeAttribute('data-cui-href');
20+
}
21+
if (node.dataset.cuiTarget) {
22+
node.setAttribute('target', '_blank');
23+
node.setAttribute('rel', 'noopener noreferrer');
24+
node.removeAttribute('data-cui-target');
25+
}
1826
}
1927
});

storybook/stories/RichText.stories.tsx

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,12 @@ Default.args = {
1818
export const Anchor = () => {
1919
const content = `
2020
<div>
21-
<p>Link to <a href="http://chatui.io/">ChatUI1</a></p>
22-
<p>Link to <a href="http://chatui.io/" target="_blank">ChatUI2</a> (new window)</p>
21+
<p>Link to <a href="https://chatui.io/">ChatUI1</a> (no target)</p>
22+
<p>Link to <a href="//chatui.io/" target="_self">ChatUI2</a> (target="_self")</p>
23+
<p>Link to <a href="http://chatui.io/" target="_blank">ChatUI2</a> (target="_blank)</p>
24+
<p>Link to <a href="https://chatui.io/" target="_parent">ChatUI2</a> (target="_parent)</p>
25+
<p>Link to <a href="https://chatui.io/" target="_top">ChatUI2</a> (target="_top)</p>
26+
<p>Open <a href="alipay://home">Alipay</a> App</p>
2327
</div>
2428
`;
2529
return <RichText content={content} />;

0 commit comments

Comments
 (0)