inject sakura css into cached html
This commit is contained in:
@@ -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 }
|
||||
|
Reference in New Issue
Block a user