inject sakura css into cached html

This commit is contained in:
2025-05-13 11:55:50 +01:00
parent 83f0625843
commit 7f8b38e218
7 changed files with 141 additions and 72 deletions

View File

@@ -1,8 +1,17 @@
import type { User } from "@markone/core/user"
import type { Bookmark } from "@markone/core/bookmark"
import { Readability } from "@mozilla/readability"
import { JSDOM } from "jsdom"
import { db } from "~/database.ts"
import { DEMO_BOOKMARKS } from "./demo-bookmarks.ts"
class LinkUnreachable {}
class UnsupportedLink {}
interface CachedPage {
title: string
readableHtml: string
}
function insertDemoBookmarks(user: User) {
const query = db.query(`
INSERT OR IGNORE INTO bookmarks (id, user_id, kind, title, url)
@@ -32,4 +41,49 @@ function findBookmarkHtml(id: string, user: User): string | null {
return content_html
}
export { insertDemoBookmarks, findBookmarkHtml }
async function cacheWebsite(url: string): Promise<CachedPage | null> {
const websiteText = await fetch(url)
.catch(() => {
throw new LinkUnreachable()
})
.then((res) => res.text())
.catch(() => {
throw new UnsupportedLink()
})
const dom = new JSDOM(websiteText, { url })
const reader = new Readability(dom.window.document)
const article = reader.parse()
if (!article) {
return null
}
if (article.content) {
const newDom = new JSDOM(article.content, { url })
const doc = newDom.window.document
const lightStyleLink = doc.createElement("link")
lightStyleLink.rel = "stylesheet"
lightStyleLink.href = "/reader-styles/sakura.css"
lightStyleLink.media = "screen"
const darkStyleLink = doc.createElement("link")
darkStyleLink.rel = "stylesheet"
darkStyleLink.href = "/reader-styles/sakura-dark.css"
darkStyleLink.media = "screen and (prefers-color-scheme: dark)"
doc.head.appendChild(lightStyleLink)
doc.head.appendChild(darkStyleLink)
article.content = newDom.serialize()
}
return {
title: article.title || "Untitled",
readableHtml: article.content || "",
}
}
export { insertDemoBookmarks, findBookmarkHtml, cacheWebsite }
export { LinkUnreachable, UnsupportedLink }