|
| 1 | +// https://github.com/rehypejs/rehype-external-links |
| 2 | + |
| 3 | +import type { Element, ElementContent, Root } from 'hast' |
| 4 | +import { visit } from 'unist-util-visit' |
| 5 | + |
| 6 | +import isAbsoluteUrl from '../utils/is-absolute-url' |
| 7 | + |
| 8 | +export interface ExternalLinkOptions { |
| 9 | + content?: ElementContent | ElementContent[] |
| 10 | + contentProperties?: Record<string, unknown> |
| 11 | + protocols?: string[] |
| 12 | +} |
| 13 | + |
| 14 | +const defaultProtocols = ['http', 'https'] |
| 15 | + |
| 16 | +/** |
| 17 | + * Automatically add `rel` (and `target`?) to external links. |
| 18 | + * |
| 19 | + * ###### Notes |
| 20 | + * |
| 21 | + * You should [likely not configure `target`][css-tricks]. |
| 22 | + * |
| 23 | + * You should at least set `rel` to `['nofollow']`. |
| 24 | + * When using a `target`, add `noopener` and `noreferrer` to avoid exploitation |
| 25 | + * of the `window.opener` API. |
| 26 | + * |
| 27 | + * When using a `target`, you should set `content` to adhere to accessibility |
| 28 | + * guidelines by giving users advanced warning when opening a new window. |
| 29 | + * |
| 30 | + * [css-tricks]: https://css-tricks.com/use-target_blank/ |
| 31 | + * |
| 32 | + * @param {Readonly<Options> | null | undefined} [options] |
| 33 | + * Configuration (optional). |
| 34 | + * @returns |
| 35 | + * Transform. |
| 36 | + */ |
| 37 | +export default function rehypeExternalLinks(options: ExternalLinkOptions = {}) { |
| 38 | + const { content, contentProperties = {}, protocols = defaultProtocols } = options |
| 39 | + |
| 40 | + return function transformer(tree: Root): void { |
| 41 | + visit(tree, 'element', (node: Element) => { |
| 42 | + if (node.tagName === 'a' && typeof node.properties?.href === 'string') { |
| 43 | + const href = node.properties.href |
| 44 | + const protocol = href.startsWith('//') |
| 45 | + ? 'http' // treat protocol-relative as http |
| 46 | + : href.slice(0, href.indexOf(':')) |
| 47 | + |
| 48 | + if (href.startsWith('//') || (isAbsoluteUrl(href) && protocols.includes(protocol))) { |
| 49 | + node.properties = { |
| 50 | + ...node.properties, |
| 51 | + rel: 'nofollow noopener noreferrer', |
| 52 | + target: '_blank' |
| 53 | + } |
| 54 | + |
| 55 | + if (content) { |
| 56 | + const spanNode: Element = { |
| 57 | + type: 'element', |
| 58 | + tagName: 'span', |
| 59 | + properties: { |
| 60 | + ...(contentProperties as Record< |
| 61 | + string, |
| 62 | + string | number | boolean | (string | number)[] | null | undefined |
| 63 | + >) |
| 64 | + }, |
| 65 | + children: Array.isArray(content) ? content : [content] |
| 66 | + } |
| 67 | + |
| 68 | + node.children.push(spanNode) |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | + }) |
| 73 | + } |
| 74 | +} |
0 commit comments