clipper: create & use addStylesToHead()

Signed-off-by: 01zulfi <85733202+01zulfi@users.noreply.github.com>
This commit is contained in:
01zulfi
2025-06-11 11:30:59 +05:00
committed by Abdullah Atta
parent 2d6142381b
commit 4fb056095c
2 changed files with 26 additions and 22 deletions

View File

@@ -23,7 +23,7 @@ import { app, h, text } from "hyperapp";
import { getInlinedNode, toBlob, toJpeg, toPng } from "./domtoimage.js";
import { Config, InlineOptions } from "./types.js";
import { FetchOptions } from "./fetch.js";
import { downloadStylesheet } from "./styles.js";
import { addStylesToHead } from "./styles.js";
type ReadabilityEnhanced = Readability<string> & {
PRESENTATIONAL_ATTRIBUTES: string[];
@@ -478,26 +478,7 @@ async function getPage(
head.appendChild(title);
if (config?.styles) {
for (const sheet of document.styleSheets) {
const node = sheet.ownerNode;
const href =
sheet.href && node instanceof HTMLLinkElement
? node.href
: node instanceof HTMLStyleElement
? node.getAttribute("href")
: null;
if (href) {
const styleNode = await downloadStylesheet(
href,
resolveFetchOptions(config)
);
if (styleNode) {
head.appendChild(styleNode);
}
} else if (node instanceof HTMLStyleElement) {
head.appendChild(node.cloneNode(true));
}
}
await addStylesToHead(head, resolveFetchOptions(config));
}
return {

View File

@@ -100,7 +100,7 @@ async function resolveImports(options?: FetchOptions) {
}
}
export async function downloadStylesheet(href: string, options?: FetchOptions) {
async function downloadStylesheet(href: string, options?: FetchOptions) {
try {
const style = document.createElement("style");
const response = await fetch(constructUrl(href, options));
@@ -428,3 +428,26 @@ function parsePseudoSelector(selector: string) {
}
return output;
}
export async function addStylesToHead(
head: HTMLHeadElement,
options?: FetchOptions
) {
for (const sheet of document.styleSheets) {
const node = sheet.ownerNode;
const href =
sheet.href && node instanceof HTMLLinkElement
? node.href
: node instanceof HTMLStyleElement
? node.getAttribute("href")
: null;
if (href) {
const styleNode = await downloadStylesheet(href, options);
if (styleNode) {
head.appendChild(styleNode);
}
} else if (node instanceof HTMLStyleElement) {
head.appendChild(node.cloneNode(true));
}
}
}