notes/quartz/util/resources.tsx

75 lines
1.9 KiB
TypeScript
Raw Permalink Normal View History

2023-06-12 22:41:42 -07:00
import { randomUUID } from "crypto"
import { JSX } from "preact/jsx-runtime"
import { QuartzPluginData } from "../plugins/vfile"
2023-06-12 22:41:42 -07:00
export type JSResource = {
2023-07-22 17:27:41 -07:00
loadTime: "beforeDOMReady" | "afterDOMReady"
moduleType?: "module"
2023-07-02 13:08:29 -07:00
spaPreserve?: boolean
2023-07-22 17:27:41 -07:00
} & (
| {
src: string
contentType: "external"
}
| {
script: string
contentType: "inline"
}
)
2023-06-12 22:41:42 -07:00
export type CSSResource = {
content: string
inline?: boolean
spaPreserve?: boolean
}
2023-06-12 22:41:42 -07:00
export function JSResourceToScriptElement(resource: JSResource, preserve?: boolean): JSX.Element {
2023-07-22 17:27:41 -07:00
const scriptType = resource.moduleType ?? "application/javascript"
2023-07-02 13:08:29 -07:00
const spaPreserve = preserve ?? resource.spaPreserve
2023-07-22 17:27:41 -07:00
if (resource.contentType === "external") {
return (
<script key={resource.src} src={resource.src} type={scriptType} spa-preserve={spaPreserve} />
)
2023-06-12 22:41:42 -07:00
} else {
const content = resource.script
2023-07-22 17:27:41 -07:00
return (
<script
key={randomUUID()}
type={scriptType}
spa-preserve={spaPreserve}
dangerouslySetInnerHTML={{ __html: content }}
></script>
2023-07-22 17:27:41 -07:00
)
2023-06-12 22:41:42 -07:00
}
}
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"
spa-preserve={spaPreserve}
/>
)
}
}
2023-06-12 22:41:42 -07:00
export interface StaticResources {
css: CSSResource[]
2023-06-12 22:41:42 -07:00
js: JSResource[]
additionalHead: (JSX.Element | ((pageData: QuartzPluginData) => JSX.Element))[]
2023-06-12 22:41:42 -07:00
}
2025-03-10 15:13:04 -07:00
export type StringResource = string | string[] | undefined
export function concatenateResources(...resources: StringResource[]): StringResource {
return resources
.filter((resource): resource is string | string[] => resource !== undefined)
.flat()
}