Load light theme prior to HTML export to ensure it is present (#7643)

This commit is contained in:
Michael Telatynski 2022-01-26 16:04:25 +00:00 committed by GitHub
parent 79d9a0c0f7
commit 00912c0b50
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -14,8 +14,6 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
/* eslint-disable max-len, camelcase */
import customCSS from "!!raw-loader!./exportCustomCSS.css"; import customCSS from "!!raw-loader!./exportCustomCSS.css";
const cssSelectorTextClassesRegex = /\.[\w-]+/g; const cssSelectorTextClassesRegex = /\.[\w-]+/g;
@ -34,15 +32,36 @@ function mutateCssText(css: string): string {
); );
} }
function isLightTheme(sheet: CSSStyleSheet): boolean {
return (<HTMLStyleElement>sheet.ownerNode).dataset.mxTheme?.toLowerCase() === "light";
}
async function getRulesFromCssFile(path: string): Promise<CSSStyleSheet> {
const doc = document.implementation.createHTMLDocument("");
const styleElement = document.createElement("style");
const res = await fetch(path);
styleElement.textContent = await res.text();
// the style will only be parsed once it is added to a document
doc.body.appendChild(styleElement);
return styleElement.sheet;
}
// naively culls unused css rules based on which classes are present in the html, // naively culls unused css rules based on which classes are present in the html,
// doesn't cull rules which won't apply due to the full selector not matching but gets rid of a LOT of cruft anyway. // doesn't cull rules which won't apply due to the full selector not matching but gets rid of a LOT of cruft anyway.
const getExportCSS = async (usedClasses: Set<string>): Promise<string> => { const getExportCSS = async (usedClasses: Set<string>): Promise<string> => {
// only include bundle.css and the data-mx-theme=light styling // only include bundle.css and the data-mx-theme=light styling
const stylesheets = Array.from(document.styleSheets).filter(s => { const stylesheets = Array.from(document.styleSheets).filter(s => {
return s.href?.endsWith("bundle.css") || return s.href?.endsWith("bundle.css") || isLightTheme(s);
(s.ownerNode as HTMLStyleElement).dataset.mxTheme?.toLowerCase() === "light";
}); });
// If the light theme isn't loaded we will have to fetch & parse it manually
if (!stylesheets.some(isLightTheme)) {
const href = document.querySelector<HTMLLinkElement>('link[rel="stylesheet"][href$="theme-light.css"]').href;
stylesheets.push(await getRulesFromCssFile(href));
}
let css = ""; let css = "";
for (const stylesheet of stylesheets) { for (const stylesheet of stylesheets) {
for (const rule of stylesheet.cssRules) { for (const rule of stylesheet.cssRules) {