Skip to content

Commit cb83871

Browse files
committed
feat: [RichText] set a element owning target to target=_blank
1 parent 53b3802 commit cb83871

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import DOMPurify from 'dompurify';
2+
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
9+
DOMPurify.addHook('beforeSanitizeAttributes', (node: Element) => {
10+
if (getLinkAttr(node, 'target')) {
11+
node.setAttribute('rel', 'noopener');
12+
}
13+
});
14+
15+
DOMPurify.addHook('afterSanitizeAttributes', (node: Element) => {
16+
if (getLinkAttr(node, 'rel') === 'noopener') {
17+
node.setAttribute('target', '_blank');
18+
}
19+
});

src/components/RichText/index.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import React from 'react';
22
import clsx from 'clsx';
33
import DOMPurify from 'dompurify';
4+
import './configDOMPurify';
45

56
export type RichTextProps = {
67
className?: string;
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import React from 'react';
2+
import { Story, Meta } from '@storybook/react/types-6-0';
3+
4+
import { RichText, RichTextProps } from '../../src';
5+
6+
export default {
7+
title: 'RichText',
8+
component: RichText,
9+
} as Meta;
10+
11+
const Template: Story<RichTextProps> = (args) => <RichText {...args} />;
12+
13+
export const Default = Template.bind({});
14+
Default.args = {
15+
content: '<h1>rich</h1>',
16+
};
17+
18+
export const Anchor = () => {
19+
const content = `
20+
<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>
23+
</div>
24+
`;
25+
return <RichText content={content} />;
26+
};

0 commit comments

Comments
 (0)