Files
quartz/quartz/util/resources.tsx
Adam Laycock 87f7f4804e
Some checks failed
Build and Test / build-and-test (ubuntu-latest) (push) Has been skipped
Build and Test / publish-tag (push) Has been skipped
Build and Test / build-and-test (windows-latest) (push) Has been cancelled
Build and Test / build-and-test (macos-latest) (push) Has been cancelled
Prevent double-loading of afterDOMReady scripts (#2213)
Co-authored-by: Adam <adam@canny.io>
2025-11-27 14:51:56 -08:00

76 lines
1.9 KiB
TypeScript

import { randomUUID } from "crypto"
import { JSX } from "preact/jsx-runtime"
import { QuartzPluginData } from "../plugins/vfile"
export type JSResource = {
loadTime: "beforeDOMReady" | "afterDOMReady"
moduleType?: "module"
spaPreserve?: boolean
} & (
| {
src: string
contentType: "external"
}
| {
script: string
contentType: "inline"
}
)
export type CSSResource = {
content: string
inline?: boolean
spaPreserve?: boolean
}
export function JSResourceToScriptElement(resource: JSResource, preserve?: boolean): JSX.Element {
const scriptType = resource.moduleType ?? "application/javascript"
const spaPreserve = preserve ?? resource.spaPreserve
if (resource.contentType === "external") {
return (
<script key={resource.src} src={resource.src} type={scriptType} data-persist={spaPreserve} />
)
} else {
const content = resource.script
return (
<script
key={randomUUID()}
type={scriptType}
data-persist={spaPreserve}
dangerouslySetInnerHTML={{ __html: content }}
></script>
)
}
}
export function CSSResourceToStyleElement(resource: CSSResource, preserve?: boolean): JSX.Element {
const spaPreserve = preserve ?? resource.spaPreserve
if (resource.inline ?? false) {
return <style>{resource.content}</style>
} else {
return (
<link
key={resource.content}
href={resource.content}
rel="stylesheet"
type="text/css"
data-persist={spaPreserve}
/>
)
}
}
export interface StaticResources {
css: CSSResource[]
js: JSResource[]
additionalHead: (JSX.Element | ((pageData: QuartzPluginData) => JSX.Element))[]
}
export type StringResource = string | string[] | undefined
export function concatenateResources(...resources: StringResource[]): StringResource {
return resources
.filter((resource): resource is string | string[] => resource !== undefined)
.flat()
}