Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | 32x 32x 32x 36x 36x 36x 31x 31x 1x 1x 30x 30x 36x 36x 27x 3x 18x 18x 18x 18x 1x 1x 18x 15x 15x 15x 18x 2x 2x 2x 19x 4x 19x 2x 19x 19x 19x 19x 18x 18x 18x 18x 18x 18x 18x 3x 3x 15x 15x 15x 1x 16x 4x 4x 1x | // SPDX-License-Identifier: MIT
/**
* Theme CSS loading utilities
*/
import { DOM_SELECTORS } from './constants.js';
import { ThemeErrors, logThemeError } from './errors.js';
export interface ThemeInfo {
id: string;
cssFile: string;
icon?: string | undefined;
}
/**
* Resolves an asset path relative to the site's base URL.
*/
export function resolveAssetPath(assetPath: string, baseUrl: string): string {
// Normalize baseUrl - remove trailing slash if present, then add one
const normalizedBase = baseUrl.replace(/\/$/, '');
const base = normalizedBase ? `${window.location.origin}${normalizedBase}/` : `${window.location.origin}/`;
return new URL(assetPath, base).pathname;
}
/**
* Gets the base URL from the document's data-baseurl attribute.
* Validates the URL to prevent injection attacks:
* - Rejects protocol-relative URLs (//example.com)
* - Rejects non-HTTPS absolute URLs (except localhost)
* - Only allows same-origin or relative paths
*/
export function getBaseUrl(doc: Document): string {
const baseElement = doc.documentElement;
const raw = baseElement?.getAttribute('data-baseurl') || '';
// Empty base URL is valid (use site root)
if (!raw) return '';
// Reject protocol-relative URLs (security risk)
Iif (raw.startsWith('//')) {
logThemeError(ThemeErrors.PROTOCOL_REJECTED());
return '';
}
// Reject non-HTTPS absolute URLs (except localhost for development)
if (raw.startsWith('http://') && !raw.startsWith('http://localhost')) {
logThemeError(ThemeErrors.INSECURE_HTTP_REJECTED());
return '';
}
try {
// Parse relative to current origin to validate
const currentOrigin = typeof window !== 'undefined' ? window.location.origin : 'http://localhost';
const u = new URL(raw, currentOrigin);
// Only allow same-origin URLs or relative paths
Iif (u.origin !== currentOrigin) {
logThemeError(ThemeErrors.CROSS_ORIGIN_REJECTED(u.origin));
return '';
}
return u.pathname.replace(/\/$/, '');
} catch {
return '';
}
}
/**
* Clears onload/onerror handlers from a link element to prevent memory leaks.
*/
function clearLinkHandlers(link: HTMLLinkElement): void {
link.onload = null;
link.onerror = null;
}
/**
* Loads a CSS file with a timeout, returning a promise that resolves when loaded.
*/
export function loadCSSWithTimeout(
link: HTMLLinkElement,
themeId: string,
timeoutMs = 10000
): Promise<void> {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
clearLinkHandlers(link);
reject(new Error(`Theme ${themeId} load timeout`));
}, timeoutMs);
link.onload = () => {
clearTimeout(timeoutId);
clearLinkHandlers(link);
resolve();
};
link.onerror = () => {
clearTimeout(timeoutId);
clearLinkHandlers(link);
reject(new Error(`Failed to load theme ${themeId}`));
};
});
}
/**
* Gets the current theme from document element classes
*/
export function getCurrentThemeFromClasses(element: HTMLElement): string | null {
const classList = Array.from(element.classList);
for (const className of classList) {
if (className.startsWith('theme-')) {
return className.substring(6); // Remove 'theme-' prefix
}
}
return null;
}
/**
* Applies theme class to document element
*/
export function applyThemeClass(doc: Document, themeId: string): void {
// Remove existing theme classes in a single batch operation
const themeClasses = Array.from(doc.documentElement.classList).filter((className) =>
className.startsWith('theme-'),
);
if (themeClasses.length > 0) {
doc.documentElement.classList.remove(...themeClasses);
}
// Add the new theme class
doc.documentElement.classList.add(`theme-${themeId}`);
}
/**
* Loads theme CSS file if not already loaded
*/
export async function loadThemeCSS(
doc: Document,
theme: ThemeInfo,
baseUrl: string
): Promise<void> {
const themeLinkId = `theme-${theme.id}-css`;
let themeLink = doc.getElementById(themeLinkId) as HTMLLinkElement | null;
if (!themeLink) {
themeLink = doc.createElement('link');
themeLink.id = themeLinkId;
themeLink.rel = 'stylesheet';
themeLink.type = 'text/css';
themeLink.setAttribute('data-theme-id', theme.id);
try {
themeLink.href = resolveAssetPath(theme.cssFile, baseUrl);
} catch {
logThemeError(ThemeErrors.INVALID_CSS_PATH(theme.id));
return;
}
doc.head.appendChild(themeLink);
// Wait for CSS to load (but don't fail if it doesn't load)
try {
await loadCSSWithTimeout(themeLink, theme.id);
} catch (error) {
logThemeError(ThemeErrors.CSS_LOAD_FAILED(theme.id, error));
}
}
// Clean up old theme CSS links (keep current and base themes)
doc.querySelectorAll(DOM_SELECTORS.THEME_CSS_LINKS).forEach((link) => {
const linkThemeId = link.id.replace('theme-', '').replace('-css', '');
if (linkThemeId !== theme.id && linkThemeId !== 'base') {
link.remove();
}
});
}
|