import { Styles, Tags } from "./types/types";
// Valid styles for storing, we may want to use a TS interface converter at
// some point so that we don't have to update items from two places at once.
export const STYLES = {
'color': ["black", "blue", "red", "green", "white", "gray", "lightblue", "lightyellow", "initial"],
'line-height': ["1", "1.5", "2", "3.5", "initial"],
'word-spacing': ["normal", "10px", "-2px", "initial"],
'font-family': ["'Roboto'", "sans-serif", "serif", "monospace", "'Hind', sans-serif", "'Lato', sans-serif", "'Merriweather', serif", "'Oswald', sans-serif", "initial"],
'background-color': ["white", "black", "ghostwhite", "peachpuff", "khaki", "gray", "lightgray", "initial"],
'font-size': ["10%", "25%", "50%", "75%", "100%", "125%", "150%", "200%", "300%", "initial"],
'text-align': ["left" , "right" , "center" , "justify" , "initial"]
}
export const injectStyles = async (styleMap: Styles, tags?: Tags[]) => {
//await new Promise((res, rej) => setTimeout(() => res("1"), 300));
// Convert the JSON object to a valid CSS object.
const css = JSON.stringify(styleMap)
.replace(/[^A-Za-z0-9- {}:,'.% ]/g, "")
.replace(/,/g, " !important;")
.replace(/\}/g, " !important;}");
// TODO: Default tags should be all of the standard markdown ones
if (!tags) tags = [Tags.p, Tags.div];
// Create a child node with the style injections
const createStyleNode = (document: Document, iframe: boolean) => {
const style = document.createElement('style');
style.setAttribute("id", "ol-styles");
style.innerHTML = tags?.map((tag) => `${!iframe ? "ol-provider " : ""}${tag} ${css}`).join(' ') || ""
return style
}
const removeAndInject = (document: Document | null, iframe: boolean) => {
if (!document || !document.head) return;
// If there are previous styles make sure to remove them
const prevStyles = document.head.querySelector("#ol-styles");
if (prevStyles) document.head.removeChild(prevStyles);
// Append the created style node to the head of the document
document.head.appendChild(createStyleNode(document, iframe));
}
removeAndInject(document, false);
const iframes = document.querySelectorAll("iframe");
iframes.forEach((frame) => {
// Handle waterfall loading
frame.addEventListener('load', () => removeAndInject(frame.contentDocument, true));
removeAndInject(frame.contentDocument, true);
})
}
export const injectFontStyles = () => {
const inject = (document: Document | null) => {
if (!document || document.querySelector("#ol-fonts")) return;
const fonts = document.createElement('template');
fonts.innerHTML = `
`;
document.head.appendChild(fonts.content);
}
inject(document);
const iframes = document.querySelectorAll("iframe");
iframes.forEach((frame) => {
// Handle waterfall loading
frame.addEventListener('load', () => inject(frame.contentDocument));
})
}