Skip to content

Commit

Permalink
feat: open external links in a new tab
Browse files Browse the repository at this point in the history
  • Loading branch information
daniele-salvagni committed Jul 11, 2024
1 parent b557754 commit eb0bb0b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
2 changes: 2 additions & 0 deletions astro.config.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { defineConfig } from 'astro/config';
import { targetBlank } from './src/plugins/targetBlank';
import mdx from '@astrojs/mdx';
import sitemap from '@astrojs/sitemap';
import theme from 'shiki/themes/github-light.json';
Expand All @@ -25,6 +26,7 @@ export default defineConfig({
// Enable word wrap to prevent horizontal scrolling
wrap: false,
},
rehypePlugins: [[targetBlank, { domain: 'dan.salvagni.io' }]],
},
site: 'https://dan.salvagni.io',
integrations: [mdx(), sitemap(), alpinejs()],
Expand Down
20 changes: 20 additions & 0 deletions src/plugins/targetBlank.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import type { RehypePlugin } from '@astrojs/markdown-remark';
import { visit } from 'unist-util-visit';
import type { Element } from 'hast';

export const targetBlank: RehypePlugin = ({ domain = '' } = {}) => {
return (tree) => {
visit(tree, 'element', (e: Element) => {
if (
e.tagName === 'a' &&
e.properties?.href &&
isExternal(e.properties.href.toString(), domain)
) {
e.properties!['target'] = '_blank';
}
});
};
};

const isExternal = (url: string, domain: string) =>
url.startsWith('http') && !url.includes(domain);

0 comments on commit eb0bb0b

Please sign in to comment.