Skip to content

Commit

Permalink
feat: [RichText] set a element owning target to target=_blank
Browse files Browse the repository at this point in the history
  • Loading branch information
akai committed Jan 18, 2021
1 parent 53b3802 commit cb83871
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/components/RichText/configDOMPurify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import DOMPurify from 'dompurify';

function getLinkAttr(node: Element, attr: string) {
return (node.nodeName === 'A' && node.getAttribute(attr)) || '';
}

// set `a` element owning target to `target=_blank`
// https://github.com/cure53/DOMPurify/issues/317
DOMPurify.addHook('beforeSanitizeAttributes', (node: Element) => {
if (getLinkAttr(node, 'target')) {
node.setAttribute('rel', 'noopener');
}
});

DOMPurify.addHook('afterSanitizeAttributes', (node: Element) => {
if (getLinkAttr(node, 'rel') === 'noopener') {
node.setAttribute('target', '_blank');
}
});
1 change: 1 addition & 0 deletions src/components/RichText/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import clsx from 'clsx';
import DOMPurify from 'dompurify';
import './configDOMPurify';

export type RichTextProps = {
className?: string;
Expand Down
26 changes: 26 additions & 0 deletions storybook/stories/RichText.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import React from 'react';
import { Story, Meta } from '@storybook/react/types-6-0';

import { RichText, RichTextProps } from '../../src';

export default {
title: 'RichText',
component: RichText,
} as Meta;

const Template: Story<RichTextProps> = (args) => <RichText {...args} />;

export const Default = Template.bind({});
Default.args = {
content: '<h1>rich</h1>',
};

export const Anchor = () => {
const content = `
<div>
<p>Link to <a href="http://chatui.io/">ChatUI1</a></p>
<p>Link to <a href="http://chatui.io/" target="_blank">ChatUI2</a> (new window)</p>
</div>
`;
return <RichText content={content} />;
};

0 comments on commit cb83871

Please sign in to comment.