gmi-web/css.js
Talon Poole b172d16ca9 add --inline
refactor css.js and html.js
2021-02-18 16:43:25 +00:00

91 lines
2.4 KiB
JavaScript

import { readFileSync } from "fs";
import path from "path";
import { stringify, parse } from "css";
export { stringify, parse };
export const CORE = parse(`p, pre, ul, blockquote, h1, h2, h3 {
margin-top: 0;
margin-bottom: 0;
overflow-wrap: break-word;
hyphens: auto;
}
a { display: block; }
img, audio, video {
display: block;
max-width: 100%;
}
`);
// TODO import.meta.resolve is supposed to accomplish this without "path"
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({ css }) {
if (css === "none") return "";
if (css === "core")
return `<style>${stringify(CORE, { compress: true })}</style>`;
if (css === "full")
return `<style>${stringify(FULL, { compress: true })}</style>`;
return `<style>${stringify(resolve(css, { compress: true }))}</style>`;
}
export function inline(tag, css) {
const { stylesheet } =
css === "full" ? FULL : css === "core" ? CORE : resolve(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(mode)) {
return parse(readFileSync(path.resolve(file), "utf-8"));
} else {
throw new Error(`Cannot find file ${mode}.`);
}
}