feat: option to overlay remote themes

This commit is contained in:
AdenMGB committed 2026-11-01 09:10:55 +10:30
1 parent fc72d5ac5e
commit ee334c901b
7 files changed
+253 -139

No files matched your search

@@ -14,8 +14,9 @@
import { getRemoteConfigSnapshot, resolveEffectiveRemoteTheme } from '@/seqta/utils/remoteConfig/runtime' import { getRemoteConfigSnapshot, resolveEffectiveRemoteTheme } from '@/seqta/utils/remoteConfig/runtime'
const themeManager = ThemeManager.getInstance(); const themeManager = ThemeManager.getInstance();
const remoteDirective = $derived(resolveEffectiveRemoteTheme(getRemoteConfigSnapshot()));
const remoteThemeForced = $derived( const remoteThemeForced = $derived(
resolveEffectiveRemoteTheme(getRemoteConfigSnapshot())?.mode === "forced", remoteDirective?.mode === 'forced' && (remoteDirective.applicationMode ?? 'replace') === 'replace',
); );
let themes = $state<ThemeList | null>(null); let themes = $state<ThemeList | null>(null);
+25 -8
View File
@@ -14,8 +14,11 @@ export type ThemePageSyncInput = {
images?: Array<{ variableName: string; blob: Blob }>; images?: Array<{ variableName: string; blob: Blob }>;
customCss?: string; customCss?: string;
previewCss?: string; previewCss?: string;
overlayCss?: string;
overlayImages?: Array<{ variableName: string; blob: Blob }>;
clear?: boolean; clear?: boolean;
clearPreview?: boolean; clearPreview?: boolean;
clearOverlay?: boolean;
}; };
export function installThemeImagePagePatch(): void { export function installThemeImagePagePatch(): void {
@@ -59,7 +62,22 @@ function preserveCustomSidebarActive(css: string): string {
return css.replace(/\.active(?![\w-])/g, ":is(.active, .bsplus-active)"); return css.replace(/\.active(?![\w-])/g, ":is(.active, .bsplus-active)");
} }
async function encodeImages(images?: Array<{ variableName: string; blob: Blob }>) {
if (images === undefined) return undefined;
return Promise.all(
images.map(async (image) => ({
variableName: image.variableName,
data: await blobToBase64Data(image.blob),
mime: image.blob.type || "image/png",
})),
);
}
export async function syncThemeToPage(input: ThemePageSyncInput): Promise<void> { export async function syncThemeToPage(input: ThemePageSyncInput): Promise<void> {
if (input.clearOverlay) {
sendPayload({ clearOverlay: true });
return;
}
if (input.clear) { if (input.clear) {
sendPayload({ clear: true }); sendPayload({ clear: true });
return; return;
@@ -73,16 +91,15 @@ export async function syncThemeToPage(input: ThemePageSyncInput): Promise<void>
if (input.previewCss !== undefined) { if (input.previewCss !== undefined) {
payload.previewCss = preserveCustomSidebarActive(input.previewCss); payload.previewCss = preserveCustomSidebarActive(input.previewCss);
} }
if (input.images !== undefined) { if (input.overlayCss !== undefined) {
payload.images = await Promise.all( payload.overlayCss = preserveCustomSidebarActive(input.overlayCss);
input.images.map(async (image) => ({
variableName: image.variableName,
data: await blobToBase64Data(image.blob),
mime: image.blob.type || "image/png",
})),
);
} }
const images = await encodeImages(input.images);
if (images !== undefined) payload.images = images;
const overlayImages = await encodeImages(input.overlayImages);
if (overlayImages !== undefined) payload.overlayImages = overlayImages;
if (Object.keys(payload).length === 0) return; if (Object.keys(payload).length === 0) return;
sendPayload(payload); sendPayload(payload);
} }
@@ -41,6 +41,18 @@ describe("normalizeRemoteConfigSnapshot", () => {
}); });
expect(snap.remoteTheme).toBeNull(); expect(snap.remoteTheme).toBeNull();
}); });
it("normalizes applicationMode overlay", () => {
const snap = normalizeRemoteConfigSnapshot({
remoteTheme: {
packageId: "p",
packageVersion: "1",
mode: "optional",
applicationMode: "overlay",
},
});
expect(snap.remoteTheme?.applicationMode).toBe("overlay");
});
}); });
describe("mergeGithubConfigFiles", () => { describe("mergeGithubConfigFiles", () => {
@@ -104,6 +104,7 @@ function normalizeRemoteTheme(raw: unknown): RemoteThemeDirective | null {
packageId, packageId,
packageVersion, packageVersion,
mode, mode,
applicationMode: r.applicationMode === "overlay" ? "overlay" : "replace",
activeFrom: typeof r.activeFrom === "string" ? r.activeFrom : undefined, activeFrom: typeof r.activeFrom === "string" ? r.activeFrom : undefined,
activeTo: typeof r.activeTo === "string" ? r.activeTo : undefined, activeTo: typeof r.activeTo === "string" ? r.activeTo : undefined,
allowUserOptOut: r.allowUserOptOut !== false, allowUserOptOut: r.allowUserOptOut !== false,
+148 -98
View File
@@ -1,9 +1,12 @@
import browser from "webextension-polyfill"; import browser from "webextension-polyfill";
import localforage from "localforage";
import type { CustomTheme } from "@/types/CustomThemes";
import { import {
applyLocalSettingsRecord, applyLocalSettingsRecord,
captureSyncableSettingsSnapshot, captureSyncableSettingsSnapshot,
} from "@/seqta/utils/cloudSettingsSync"; } from "@/seqta/utils/cloudSettingsSync";
import { settingsState, initializeSettingsState } from "@/seqta/utils/listeners/SettingsState"; import { settingsState, initializeSettingsState } from "@/seqta/utils/listeners/SettingsState";
import { syncThemeToPage } from "@/seqta/utils/patchThemeImagesPageContext";
import type { RemoteConfigSnapshot, RemoteThemeDirective } from "./types"; import type { RemoteConfigSnapshot, RemoteThemeDirective } from "./types";
import { import {
BSPLUS_REMOTE_THEME_BEFORE_V1_KEY, BSPLUS_REMOTE_THEME_BEFORE_V1_KEY,
@@ -20,35 +23,29 @@ type BeforeSnapshot = {
type ActiveThemeState = { type ActiveThemeState = {
directiveKey: string; directiveKey: string;
packageId: string; layerIds: string[];
installedThemeId: string;
mode: "optional" | "forced"; mode: "optional" | "forced";
applicationMode: "replace" | "overlay";
}; };
export type RemoteThemePackageResponse = { type RemotePackage = {
packageId: string;
version: string;
theme?: Record<string, unknown>; theme?: Record<string, unknown>;
overlayLayers?: Record<string, unknown>[];
downloadUrl?: string; downloadUrl?: string;
}; };
let reconcileChain: Promise<void> = Promise.resolve(); let reconcileChain: Promise<void> = Promise.resolve();
function remoteThemeDirectiveKey( function directiveKey(snapshot: RemoteConfigSnapshot, d: RemoteThemeDirective): string {
snapshot: RemoteConfigSnapshot, return `${snapshot.configVersion}|${d.packageId}|${d.packageVersion}|${d.mode}|${d.applicationMode ?? "replace"}`;
directive: RemoteThemeDirective,
): string {
return `${snapshot.configVersion}|${directive.packageId}|${directive.packageVersion}|${directive.mode}`;
} }
function isWithinWindow(directive: RemoteThemeDirective, now = Date.now()): boolean { function isWithinWindow(d: RemoteThemeDirective, now = Date.now()): boolean {
if (directive.activeFrom) { if (d.activeFrom && !Number.isNaN(Date.parse(d.activeFrom)) && now < Date.parse(d.activeFrom)) {
const from = Date.parse(directive.activeFrom); return false;
if (!Number.isNaN(from) && now < from) return false;
} }
if (directive.activeTo) { if (d.activeTo && !Number.isNaN(Date.parse(d.activeTo)) && now > Date.parse(d.activeTo)) {
const until = Date.parse(directive.activeTo); return false;
if (!Number.isNaN(until) && now > until) return false;
} }
return true; return true;
} }
@@ -57,32 +54,29 @@ export function resolveEffectiveRemoteTheme(
snapshot: RemoteConfigSnapshot, snapshot: RemoteConfigSnapshot,
): RemoteThemeDirective | null { ): RemoteThemeDirective | null {
const d = snapshot.remoteTheme; const d = snapshot.remoteTheme;
if (!d || d.mode === "off") return null; if (!d || d.mode === "off" || !isWithinWindow(d)) return null;
if (!isWithinWindow(d)) return null;
return d; return d;
} }
async function readJson<T>(key: string): Promise<T | null> {
const stored = await browser.storage.local.get(key);
const raw = stored[key];
return raw && typeof raw === "object" ? (raw as T) : null;
}
async function loadBeforeSnapshot(): Promise<BeforeSnapshot | null> { async function loadBeforeSnapshot(): Promise<BeforeSnapshot | null> {
const stored = await browser.storage.local.get(BSPLUS_REMOTE_THEME_BEFORE_V1_KEY); const b = await readJson<BeforeSnapshot>(BSPLUS_REMOTE_THEME_BEFORE_V1_KEY);
const raw = stored[BSPLUS_REMOTE_THEME_BEFORE_V1_KEY]; if (!b?.directiveKey || !b.storage) return null;
if (!raw || typeof raw !== "object") return null;
const b = raw as BeforeSnapshot;
if (!b.directiveKey || !b.storage || typeof b.storage !== "object") return null;
return b; return b;
} }
async function captureBeforeSnapshot(directiveKey: string): Promise<void> { async function loadActiveState(): Promise<ActiveThemeState | null> {
const existing = await loadBeforeSnapshot(); return readJson<ActiveThemeState>(BSPLUS_REMOTE_THEME_STATE_V1_KEY);
if (existing?.directiveKey === directiveKey) return; }
const storage = await captureSyncableSettingsSnapshot(); async function loadUserOffKey(): Promise<string | null> {
const before: BeforeSnapshot = { const raw = await readJson<{ directiveKey?: string }>(BSPLUS_REMOTE_THEME_USER_OFF_KEY);
capturedAt: new Date().toISOString(), return typeof raw?.directiveKey === "string" ? raw.directiveKey : null;
directiveKey,
storage,
selectedTheme: settingsState.selectedTheme ?? "",
};
await browser.storage.local.set({ [BSPLUS_REMOTE_THEME_BEFORE_V1_KEY]: before });
} }
async function clearRemoteThemeLocalState(): Promise<void> { async function clearRemoteThemeLocalState(): Promise<void> {
@@ -93,123 +87,179 @@ async function clearRemoteThemeLocalState(): Promise<void> {
]); ]);
} }
async function loadUserOffKey(): Promise<string | null> { async function clearRemoteThemeOverlay(state?: ActiveThemeState | null): Promise<void> {
const stored = await browser.storage.local.get(BSPLUS_REMOTE_THEME_USER_OFF_KEY); const active = state ?? (await loadActiveState());
const raw = stored[BSPLUS_REMOTE_THEME_USER_OFF_KEY]; await syncThemeToPage({ clearOverlay: true });
if (!raw || typeof raw !== "object") return null; if (!active?.layerIds?.length) return;
const key = (raw as { directiveKey?: string }).directiveKey; const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager");
return typeof key === "string" ? key : null; const tm = ThemeManager.getInstance();
for (const id of active.layerIds) {
await tm.deleteTheme(id).catch(() => {});
}
} }
export async function dismissOptionalRemoteTheme(snapshot: RemoteConfigSnapshot): Promise<void> { export async function dismissOptionalRemoteTheme(snapshot: RemoteConfigSnapshot): Promise<void> {
const directive = resolveEffectiveRemoteTheme(snapshot); const d = resolveEffectiveRemoteTheme(snapshot);
if (!directive || directive.mode !== "optional") return; if (!d || d.mode !== "optional") return;
const key = remoteThemeDirectiveKey(snapshot, directive);
await browser.storage.local.set({ await browser.storage.local.set({
[BSPLUS_REMOTE_THEME_USER_OFF_KEY]: { directiveKey: key }, [BSPLUS_REMOTE_THEME_USER_OFF_KEY]: { directiveKey: directiveKey(snapshot, d) },
}); });
await restoreRemoteThemeSnapshot(); await restoreRemoteThemeSnapshot();
} }
async function restoreRemoteThemeSnapshot(): Promise<void> { async function restoreRemoteThemeSnapshot(): Promise<void> {
const state = await loadActiveState();
if (state?.applicationMode === "overlay") {
await clearRemoteThemeOverlay(state);
await clearRemoteThemeLocalState();
return;
}
const before = await loadBeforeSnapshot(); const before = await loadBeforeSnapshot();
if (before) { if (before) {
await applyLocalSettingsRecord(before.storage); await applyLocalSettingsRecord(before.storage);
await initializeSettingsState(); await initializeSettingsState();
const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager"); const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager");
const tm = ThemeManager.getInstance(); const tm = ThemeManager.getInstance();
if (before.selectedTheme) { if (before.selectedTheme) await tm.setTheme(before.selectedTheme, false);
await tm.setTheme(before.selectedTheme, false); else await tm.disableTheme();
} else {
await tm.disableTheme();
}
} }
await clearRemoteThemeLocalState(); await clearRemoteThemeLocalState();
} }
async function fetchPackage(packageId: string): Promise<RemoteThemePackageResponse | null> { async function fetchPackage(packageId: string): Promise<RemotePackage | null> {
try { try {
const res = (await browser.runtime.sendMessage({ const res = (await browser.runtime.sendMessage({
type: "fetchRemoteThemePackage", type: "fetchRemoteThemePackage",
packageId, packageId,
})) as { package?: RemoteThemePackageResponse; error?: string } | undefined; })) as { package?: RemotePackage; error?: string };
if (res?.error || !res?.package) return null; return res?.package && !res.error ? res.package : null;
return res.package;
} catch { } catch {
return null; return null;
} }
} }
async function resolveThemeContent( async function fetchDownload(url: string): Promise<Record<string, unknown> | null> {
pkg: RemoteThemePackageResponse,
): Promise<Record<string, unknown> | null> {
if (pkg.theme && typeof pkg.theme === "object") return pkg.theme;
if (!pkg.downloadUrl) return null;
try { try {
const res = (await browser.runtime.sendMessage({ const res = (await browser.runtime.sendMessage({
type: "fetchRemoteThemePackageUrl", type: "fetchRemoteThemePackageUrl",
url: pkg.downloadUrl, url,
})) as { theme?: Record<string, unknown>; error?: string }; })) as { theme?: Record<string, unknown> };
if (res?.theme && typeof res.theme === "object") return res.theme; return res?.theme && typeof res.theme === "object" ? res.theme : null;
} catch { } catch {
/* ignore */ return null;
} }
return null;
} }
async function applyRemoteThemePackage( async function resolveLayers(pkg: RemotePackage): Promise<Record<string, unknown>[]> {
if (Array.isArray(pkg.overlayLayers) && pkg.overlayLayers.length) {
return pkg.overlayLayers.filter((l) => l && typeof l === "object") as Record<string, unknown>[];
}
if (pkg.theme && typeof pkg.theme === "object") return [pkg.theme];
if (!pkg.downloadUrl) return [];
const dl = await fetchDownload(pkg.downloadUrl);
if (!dl) return [];
if (Array.isArray((dl as { overlayLayers?: unknown }).overlayLayers)) {
return (dl as { overlayLayers: Record<string, unknown>[] }).overlayLayers;
}
return [dl];
}
async function saveActiveState(state: ActiveThemeState): Promise<void> {
await browser.storage.local.set({ [BSPLUS_REMOTE_THEME_STATE_V1_KEY]: state });
await browser.storage.local.remove(BSPLUS_REMOTE_THEME_USER_OFF_KEY);
}
async function applyRemoteTheme(
snapshot: RemoteConfigSnapshot, snapshot: RemoteConfigSnapshot,
directive: RemoteThemeDirective, directive: RemoteThemeDirective,
): Promise<void> { ): Promise<void> {
const directiveKey = remoteThemeDirectiveKey(snapshot, directive); const key = directiveKey(snapshot, directive);
const stored = await browser.storage.local.get(BSPLUS_REMOTE_THEME_STATE_V1_KEY); const prior = await loadActiveState();
const state = stored[BSPLUS_REMOTE_THEME_STATE_V1_KEY] as ActiveThemeState | undefined; if (prior?.directiveKey === key) return;
if (state?.directiveKey === directiveKey) return;
await captureBeforeSnapshot(directiveKey); const overlay = (directive.applicationMode ?? "replace") === "overlay";
if (prior?.applicationMode === "overlay") await clearRemoteThemeOverlay(prior);
const pkg = await fetchPackage(directive.packageId); const pkg = await fetchPackage(directive.packageId);
if (!pkg) return; if (!pkg) return;
const themeContent = await resolveThemeContent(pkg); const layers = await resolveLayers(pkg);
if (!themeContent || typeof themeContent.id !== "string") return;
const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager"); const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager");
const tm = ThemeManager.getInstance(); const tm = ThemeManager.getInstance();
await tm.installTheme(themeContent as Parameters<typeof tm.installTheme>[0], {
if (overlay) {
if (!layers.length) return;
for (const layer of layers) {
if (typeof layer.id !== "string" || !layer.name) continue;
await tm.installTheme(layer as Parameters<typeof tm.installTheme>[0], { fromStore: false });
}
if (settingsState.selectedTheme) await tm.setTheme(settingsState.selectedTheme, false);
const css: string[] = [];
const images = new Map<string, { variableName: string; blob: Blob }>();
const layerIds: string[] = [];
for (const layer of layers) {
if (typeof layer.id === "string") layerIds.push(layer.id);
if (typeof layer.CustomCSS === "string") css.push(layer.CustomCSS);
const stored = typeof layer.id === "string"
? ((await localforage.getItem(layer.id)) as CustomTheme | null)
: null;
for (const img of stored?.CustomImages ?? []) {
if (img.variableName && img.blob) images.set(img.variableName, img);
}
}
await syncThemeToPage({
overlayCss: css.join("\n"),
overlayImages: [...images.values()],
});
await saveActiveState({
directiveKey: key,
layerIds,
mode: directive.mode,
applicationMode: "overlay",
});
return;
}
const theme = layers[0];
if (!theme || typeof theme.id !== "string") return;
await captureBeforeSnapshot(key);
await tm.installTheme(theme as Parameters<typeof tm.installTheme>[0], {
fromStore: false, fromStore: false,
forceTheme: directive.mode === "forced", forceTheme: directive.mode === "forced",
}); });
await tm.setTheme(String(themeContent.id), false); await tm.setTheme(String(theme.id), false);
await saveActiveState({
const active: ActiveThemeState = { directiveKey: key,
directiveKey, layerIds: [String(theme.id)],
packageId: directive.packageId,
installedThemeId: String(themeContent.id),
mode: directive.mode, mode: directive.mode,
}; applicationMode: "replace",
await browser.storage.local.set({ [BSPLUS_REMOTE_THEME_STATE_V1_KEY]: active }); });
await browser.storage.local.remove(BSPLUS_REMOTE_THEME_USER_OFF_KEY); }
async function captureBeforeSnapshot(directiveKey: string): Promise<void> {
const existing = await loadBeforeSnapshot();
if (existing?.directiveKey === directiveKey) return;
await browser.storage.local.set({
[BSPLUS_REMOTE_THEME_BEFORE_V1_KEY]: {
capturedAt: new Date().toISOString(),
directiveKey,
storage: await captureSyncableSettingsSnapshot(),
selectedTheme: settingsState.selectedTheme ?? "",
},
});
} }
async function reconcileRemoteThemeInner(snapshot: RemoteConfigSnapshot): Promise<void> { async function reconcileRemoteThemeInner(snapshot: RemoteConfigSnapshot): Promise<void> {
const directive = resolveEffectiveRemoteTheme(snapshot); const d = resolveEffectiveRemoteTheme(snapshot);
const userOff = await loadUserOffKey(); if (!d) {
if (await loadActiveState()) await restoreRemoteThemeSnapshot();
if (!directive) {
const stateRaw = await browser.storage.local.get(BSPLUS_REMOTE_THEME_STATE_V1_KEY);
if (stateRaw[BSPLUS_REMOTE_THEME_STATE_V1_KEY]) {
await restoreRemoteThemeSnapshot();
}
return; return;
} }
const key = directiveKey(snapshot, d);
const directiveKey = remoteThemeDirectiveKey(snapshot, directive); if (d.mode === "optional" && (await loadUserOffKey()) === key) return;
if (directive.mode === "optional" && userOff === directiveKey) { await applyRemoteTheme(snapshot, d);
return;
}
await applyRemoteThemePackage(snapshot, directive);
} }
export function scheduleReconcileRemoteTheme(snapshot: RemoteConfigSnapshot): void { export function scheduleReconcileRemoteTheme(snapshot: RemoteConfigSnapshot): void {
+2
View File
@@ -50,11 +50,13 @@ export type RemoteCampaign = {
}; };
export type RemoteThemeMode = "off" | "optional" | "forced"; export type RemoteThemeMode = "off" | "optional" | "forced";
export type RemoteThemeApplicationMode = "replace" | "overlay";
export type RemoteThemeDirective = { export type RemoteThemeDirective = {
packageId: string; packageId: string;
packageVersion: string; packageVersion: string;
mode: RemoteThemeMode; mode: RemoteThemeMode;
applicationMode?: RemoteThemeApplicationMode;
activeFrom?: string; activeFrom?: string;
activeTo?: string; activeTo?: string;
message?: { title?: string; body?: string }; message?: { title?: string; body?: string };
+63 -32
View File
@@ -13,7 +13,10 @@
var IMAGES_STYLE_ID = "bsplus-theme-images"; var IMAGES_STYLE_ID = "bsplus-theme-images";
var THEME_STYLE_ID = "custom-theme"; var THEME_STYLE_ID = "custom-theme";
var PREVIEW_STYLE_ID = "custom-theme-preview"; var PREVIEW_STYLE_ID = "custom-theme-preview";
var OVERLAY_STYLE_ID = "bsplus-remote-theme-overlay";
var OVERLAY_IMAGES_STYLE_ID = "bsplus-remote-theme-overlay-images";
var urlCache = {}; var urlCache = {};
var overlayUrlCache = {};
var headObserver = null; var headObserver = null;
function log(event, detail) { function log(event, detail) {
@@ -29,14 +32,16 @@
return new Blob([ab], { type: mime || "image/png" }); return new Blob([ab], { type: mime || "image/png" });
} }
function releaseCachedUrls() { function releaseCache(cache) {
for (var key in urlCache) { for (var key in cache) {
if (!Object.prototype.hasOwnProperty.call(urlCache, key)) continue; if (!Object.prototype.hasOwnProperty.call(cache, key)) continue;
try { try {
URL.revokeObjectURL(urlCache[key]); URL.revokeObjectURL(cache[key]);
} catch (e) {} } catch (e) {}
} }
urlCache = {}; for (key in cache) {
if (Object.prototype.hasOwnProperty.call(cache, key)) delete cache[key];
}
} }
function styleEl(id) { function styleEl(id) {
@@ -49,11 +54,23 @@
return el; return el;
} }
function keepOverlayStylesLast() {
var overlayImages = document.getElementById(OVERLAY_IMAGES_STYLE_ID);
var overlayCss = document.getElementById(OVERLAY_STYLE_ID);
if (overlayImages && document.head.contains(overlayImages)) {
document.head.appendChild(overlayImages);
}
if (overlayCss && document.head.contains(overlayCss)) {
document.head.appendChild(overlayCss);
}
}
function keepThemeStyleLast() { function keepThemeStyleLast() {
var themeStyle = document.getElementById(THEME_STYLE_ID); var themeStyle = document.getElementById(THEME_STYLE_ID);
if (themeStyle && document.head.contains(themeStyle) && document.head.lastElementChild !== themeStyle) { if (themeStyle && document.head.contains(themeStyle) && document.head.lastElementChild !== themeStyle) {
document.head.appendChild(themeStyle); document.head.appendChild(themeStyle);
} }
keepOverlayStylesLast();
} }
function watchHead() { function watchHead() {
@@ -74,38 +91,45 @@
} }
} }
function clearAll() { function applyRootImages(images, styleId, cache, afterApply) {
releaseCachedUrls(); releaseCache(cache);
setStyleText(IMAGES_STYLE_ID, "");
document.getElementById(THEME_STYLE_ID)?.remove();
document.getElementById(PREVIEW_STYLE_ID)?.remove();
headObserver?.disconnect();
headObserver = null;
log("cleared");
}
function applyThemeImages(images) {
releaseCachedUrls();
if (!images?.length) { if (!images?.length) {
setStyleText(IMAGES_STYLE_ID, ""); document.getElementById(styleId)?.remove();
return; return;
} }
var lines = [":root {"]; var lines = [":root {"];
for (var i = 0; i < images.length; i++) { for (var i = 0; i < images.length; i++) {
var img = images[i]; var img = images[i];
if (!img?.variableName || !img.data) continue; if (!img?.variableName || !img.data) continue;
try { try {
var url = URL.createObjectURL(base64ToBlob(img.data, img.mime)); var url = URL.createObjectURL(base64ToBlob(img.data, img.mime));
urlCache[img.variableName] = url; cache[img.variableName] = url;
lines.push(' --' + img.variableName + ': url("' + url + '");'); lines.push(' --' + img.variableName + ': url("' + url + '");');
} catch (e) { } catch (e) {
console.warn(LOG, "skip image", img.variableName, e); console.warn(LOG, "skip image", img.variableName, e);
} }
} }
lines.push("}"); lines.push("}");
styleEl(IMAGES_STYLE_ID).textContent = lines.join("\n"); styleEl(styleId).textContent = lines.join("\n");
log("images applied", { count: images.length }); if (afterApply) afterApply();
log("images applied", { styleId: styleId, count: images.length });
}
function clearOverlayOnly() {
releaseCache(overlayUrlCache);
document.getElementById(OVERLAY_STYLE_ID)?.remove();
document.getElementById(OVERLAY_IMAGES_STYLE_ID)?.remove();
log("overlay cleared");
}
function clearAll() {
releaseCache(urlCache);
setStyleText(IMAGES_STYLE_ID, "");
document.getElementById(THEME_STYLE_ID)?.remove();
document.getElementById(PREVIEW_STYLE_ID)?.remove();
headObserver?.disconnect();
headObserver = null;
log("cleared");
} }
function processPayload() { function processPayload() {
@@ -121,25 +145,32 @@
clearAll(); clearAll();
return; return;
} }
if (payload.clearOverlay) {
clearOverlayOnly();
return;
}
if (payload.images !== undefined) applyThemeImages(payload.images); if (payload.images !== undefined) {
applyRootImages(payload.images, IMAGES_STYLE_ID, urlCache);
}
if (payload.customCss !== undefined) { if (payload.customCss !== undefined) {
setStyleText(THEME_STYLE_ID, payload.customCss || "", true); setStyleText(THEME_STYLE_ID, payload.customCss || "", true);
log("custom css applied"); log("custom css applied");
} }
if (payload.overlayImages !== undefined) {
applyRootImages(payload.overlayImages, OVERLAY_IMAGES_STYLE_ID, overlayUrlCache, keepOverlayStylesLast);
}
if (payload.overlayCss !== undefined) {
setStyleText(OVERLAY_STYLE_ID, payload.overlayCss || "", false);
keepOverlayStylesLast();
log("overlay css applied");
}
if (payload.previewCss !== undefined) { if (payload.previewCss !== undefined) {
setStyleText(PREVIEW_STYLE_ID, payload.previewCss || ""); setStyleText(PREVIEW_STYLE_ID, payload.previewCss || "");
var previewStyle = document.getElementById(PREVIEW_STYLE_ID); var previewStyle = document.getElementById(PREVIEW_STYLE_ID);
if (previewStyle) { if (previewStyle) document.head.appendChild(previewStyle);
document.head.appendChild(previewStyle);
}
}
if (payload.clearPreview) {
setStyleText(PREVIEW_STYLE_ID, "");
} }
if (payload.clearPreview) setStyleText(PREVIEW_STYLE_ID, "");
} catch (e) { } catch (e) {
console.warn(LOG, "invalid payload", e); console.warn(LOG, "invalid payload", e);
} }