86 lines
2.4 KiB
JavaScript
86 lines
2.4 KiB
JavaScript
import { readFileSync } from "fs";
|
|
// TODO import.meta.resolve is supposed to accomplish this without "path"
|
|
import path from "path";
|
|
import { stringify, parse } from "css";
|
|
export { stringify, parse };
|
|
|
|
export const CORE = parse(
|
|
readFileSync(
|
|
path.resolve(path.dirname(new URL(import.meta.url).pathname), "./core.css"),
|
|
"utf-8"
|
|
)
|
|
);
|
|
|
|
export const FULL = parse(
|
|
readFileSync(
|
|
path.resolve(path.dirname(new URL(import.meta.url).pathname), "./gmi.css"),
|
|
"utf-8"
|
|
)
|
|
);
|
|
|
|
export function rootVariables({ stylesheet }) {
|
|
return stylesheet.rules
|
|
.find(
|
|
({ type, selectors }) => type === "rule" && selectors.includes(":root")
|
|
)
|
|
.declarations.reduce(
|
|
(obj, { property, value }) =>
|
|
!/^\-\-/.test(property)
|
|
? obj
|
|
: Object.assign(obj, { [property.replace("--", "")]: value }),
|
|
{}
|
|
);
|
|
}
|
|
|
|
export function override(options) {
|
|
if (options.css !== "full") return "";
|
|
const vars = rootVariables(FULL);
|
|
|
|
return Object.keys(vars).reduce((styles, key) => {
|
|
if (typeof options[key] !== undefined && options[key] !== vars[key]) {
|
|
let value = options[key];
|
|
if (["a-prefix", "ul-bullet"].includes(key) && value !== "none") {
|
|
value = `"${value}"`;
|
|
}
|
|
styles += `--${key}:${value};`;
|
|
}
|
|
return styles;
|
|
}, " ");
|
|
}
|
|
|
|
export function style({ inline, css }) {
|
|
if (inline || css === "none") return "";
|
|
if (css === "core")
|
|
return `<style>${stringify(CORE, { compress: true })}</style>`;
|
|
if (css === "full")
|
|
return `<meta name="color-scheme" content="dark light">\n<style>${stringify(
|
|
FULL,
|
|
{ compress: true }
|
|
)}</style>`;
|
|
|
|
return `<style>${stringify(load(css, { compress: true }))}</style>`;
|
|
}
|
|
|
|
export function inline(tag, { inline, css }) {
|
|
if (!inline || css === "full") return "";
|
|
const { stylesheet } = css === "core" ? CORE : load(css);
|
|
const styles = stylesheet.rules
|
|
.filter(({ type, selectors }) => type === "rule" && selectors.includes(tag))
|
|
.reduce((style, { declarations }) => {
|
|
declarations.forEach(({ property, value }) => {
|
|
style = `${style}${property}:${value};`;
|
|
});
|
|
return style;
|
|
}, "");
|
|
|
|
return styles !== "" ? ` style="${styles}"` : "";
|
|
}
|
|
|
|
export function load(file, options) {
|
|
if (fs.existsSync(file)) {
|
|
return parse(readFileSync(path.resolve(file), "utf-8"));
|
|
} else {
|
|
throw new Error(`Cannot find file ${file}.`);
|
|
}
|
|
}
|