feat: cozify to prefetch links and open in cozy

This commit is contained in:
Ayo 2023-10-01 08:48:33 +02:00
parent 8470e5bee6
commit 9c1627b3e5
2 changed files with 19 additions and 5 deletions

View file

@ -1,6 +1,6 @@
---
import { ArticleData } from "@extractus/article-extractor";
import clean from '../utils/sanitizer';
import { cozify } from "../utils/sanitizer"
export interface Props {
article: ArticleData | null;
}
@ -14,7 +14,7 @@ article ??= error;
const datePublished =
article?.published && new Date(article.published).toDateString();
const cleanContent = clean(article.content ?? '')
const cleanContent = await cozify(article.content ?? '', Astro.url.origin)
---
<!--

View file

@ -1,11 +1,25 @@
import { transform } from 'ultrahtml'
import { parse, render, transform, walkSync } from 'ultrahtml'
import sanitize from 'ultrahtml/transformers/sanitize'
export default function clean(html: string) {
export async function cozify(html: string, baseUrl: string): Promise<string> {
return transform(html, [
// remove target="_blank" from links
const ast = parse(html)
walkSync(ast, (node) => {
if (node.name === 'a') {
node.attributes.href = `${baseUrl}?url=${node.attributes.href}`
node.attributes.prefetch = true
}
})
const newHtml = await render(ast);
return transform(newHtml, [
sanitize({
dropElements: ['script'],
dropAttributes: {
target: ['a']
}
})
])
}