forked from Fei-Away/Codex-Dream-Skin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer-inject.js
More file actions
420 lines (403 loc) · 17.1 KB
/
Copy pathrenderer-inject.js
File metadata and controls
420 lines (403 loc) · 17.1 KB
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
((cssText, artDataUrl, rawConfig) => {
const STATE_KEY = "__CODEX_DREAM_SKIN_STATE__";
const STYLE_ID = "codex-dream-skin-style";
const CHROME_ID = "codex-dream-skin-chrome";
const ROOT_CLASSES = [
"codex-dream-skin",
"dream-theme-light",
"dream-theme-dark",
"dream-art-wide",
"dream-art-standard",
"dream-focus-left",
"dream-focus-center",
"dream-focus-right",
"dream-safe-left",
"dream-safe-center",
"dream-safe-right",
"dream-safe-none",
"dream-task-ambient",
"dream-task-banner",
"dream-task-off",
];
const ROOT_PROPERTIES = [
"--dream-art",
"--dream-art-position",
"--dream-focus-x",
"--dream-focus-y",
"--dream-accent",
"--dream-accent-ink",
"--dream-image-luma",
"--dream-overlay-opacity",
];
const HOME_UTILITY_CLASS = "dream-home-utility";
const installToken = {};
let samplingNativeShell = false;
let observer = null;
window.__CODEX_DREAM_SKIN_DISABLED__ = false;
const clamp = (value, min = 0, max = 1) => Math.min(max, Math.max(min, Number(value)));
const luminance = (red, green, blue) => {
const linear = [red, green, blue].map((value) => {
const channel = value / 255;
return channel <= .04045 ? channel / 12.92 : ((channel + .055) / 1.055) ** 2.4;
});
return .2126 * linear[0] + .7152 * linear[1] + .0722 * linear[2];
};
const defaultProfile = {
appearance: "dark",
accent: [108, 131, 142],
focusX: .5,
focusY: .5,
aspect: 1.6,
luma: .32,
safeArea: "center",
};
const normalizeConfig = (value) => {
const config = value && typeof value === "object" ? value : {};
const art = config.art && typeof config.art === "object" ? config.art : {};
const hasNumber = (candidate) =>
(typeof candidate === "number" || (typeof candidate === "string" && candidate.trim() !== "")) &&
Number.isFinite(Number(candidate));
const requestedAccent = typeof config?.palette?.accent === "string"
? config.palette.accent.trim()
: "";
const safeAccent = /^(?:#[\da-f]{3,8}|(?:rgb|hsl|oklch|oklab)\([^;{}]{1,96}\))$/i.test(requestedAccent)
? requestedAccent
: null;
const appearance = ["auto", "light", "dark"].includes(config.appearance)
? config.appearance
: "auto";
const safeArea = ["auto", "left", "right", "center", "none"].includes(art.safeArea)
? art.safeArea
: "auto";
const taskMode = ["auto", "ambient", "banner", "off"].includes(art.taskMode)
? art.taskMode
: "auto";
const metadataRatio = Number(config?.artMetadata?.ratio);
return {
appearance,
safeArea,
taskMode,
focusX: hasNumber(art.focusX) ? clamp(art.focusX) : null,
focusY: hasNumber(art.focusY) ? clamp(art.focusY) : null,
accent: safeAccent,
overlayOpacity: hasNumber(config.overlayOpacity) ? clamp(config.overlayOpacity) : .58,
initialAspect: Number.isFinite(metadataRatio) && metadataRatio > 0 ? metadataRatio : null,
};
};
const previous = window[STATE_KEY];
if (previous?.observer) previous.observer.disconnect();
if (previous?.timer) clearInterval(previous.timer);
if (previous?.scheduler?.timeout) clearTimeout(previous.scheduler.timeout);
if (previous?.artUrl) URL.revokeObjectURL(previous.artUrl);
const artUrl = (() => {
const comma = artDataUrl.indexOf(",");
const binary = atob(artDataUrl.slice(comma + 1));
const bytes = new Uint8Array(binary.length);
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
const mime = /^data:([^;,]+)/.exec(artDataUrl)?.[1] || "image/png";
return URL.createObjectURL(new Blob([bytes], { type: mime }));
})();
const config = normalizeConfig(rawConfig);
let profile = {
...defaultProfile,
aspect: config.initialAspect ?? defaultProfile.aspect,
};
const existingStyle = document.getElementById(STYLE_ID);
if (existingStyle) {
existingStyle.textContent = cssText;
existingStyle.dataset.dreamVersion = "3";
}
const analyzeArt = () => new Promise((resolve) => {
if (typeof Image !== "function") {
resolve(defaultProfile);
return;
}
const image = new Image();
image.onload = () => {
try {
const width = 48;
const height = Math.max(12, Math.round(width * image.naturalHeight / image.naturalWidth));
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext?.("2d", { willReadFrequently: true });
if (!context) throw new Error("Canvas is unavailable");
context.drawImage(image, 0, 0, width, height);
const pixels = context.getImageData(0, 0, width, height).data;
let count = 0;
let totalRed = 0;
let totalGreen = 0;
let totalBlue = 0;
let totalBrightness = 0;
const samples = [];
const sampleMap = new Array(width * height);
for (let offset = 0; offset < pixels.length; offset += 4) {
if (pixels[offset + 3] < 96) continue;
const red = pixels[offset];
const green = pixels[offset + 1];
const blue = pixels[offset + 2];
const light = (.2126 * red + .7152 * green + .0722 * blue) / 255;
const sample = { red, green, blue, light, index: offset / 4 };
samples.push(sample);
sampleMap[sample.index] = sample;
totalRed += red;
totalGreen += green;
totalBlue += blue;
totalBrightness += light;
count += 1;
}
if (!count) throw new Error("Image contains no opaque pixels");
const average = [totalRed / count, totalGreen / count, totalBlue / count];
const averageBrightness = totalBrightness / count;
const information = (start, end) => {
let total = 0;
let totalSquared = 0;
let edges = 0;
let edgeCount = 0;
let sampleCount = 0;
for (let y = 0; y < height; y += 1) {
for (let x = start; x < end; x += 1) {
const sample = sampleMap[y * width + x];
if (!sample) continue;
total += sample.light;
totalSquared += sample.light * sample.light;
sampleCount += 1;
const previousSample = x > start ? sampleMap[y * width + x - 1] : null;
const above = y > 0 ? sampleMap[(y - 1) * width + x] : null;
if (previousSample) { edges += Math.abs(sample.light - previousSample.light); edgeCount += 1; }
if (above) { edges += Math.abs(sample.light - above.light); edgeCount += 1; }
}
}
const mean = sampleCount ? total / sampleCount : 0;
const variance = sampleCount ? Math.max(0, totalSquared / sampleCount - mean * mean) : 1;
return Math.sqrt(variance) * .58 + (edgeCount ? edges / edgeCount : 1) * .42;
};
const zoneWidth = Math.max(1, Math.floor(width * .38));
const leftInformation = information(0, zoneWidth);
const rightInformation = information(width - zoneWidth, width);
let safeArea = "center";
if (leftInformation < rightInformation * .86) safeArea = "left";
else if (rightInformation < leftInformation * .86) safeArea = "right";
let focusWeight = 0;
let focusX = 0;
let focusY = 0;
let accentWeight = 0;
let accent = [0, 0, 0];
for (const sample of samples) {
const x = sample.index % width;
const y = Math.floor(sample.index / width);
const difference = Math.sqrt(
(sample.red - average[0]) ** 2 +
(sample.green - average[1]) ** 2 +
(sample.blue - average[2]) ** 2,
) / 441.7;
const saliency = .03 + difference ** 1.35;
focusX += (x / Math.max(1, width - 1)) * saliency;
focusY += (y / Math.max(1, height - 1)) * saliency;
focusWeight += saliency;
const max = Math.max(sample.red, sample.green, sample.blue);
const min = Math.min(sample.red, sample.green, sample.blue);
const saturation = max ? (max - min) / max : 0;
const usableLight = 1 - Math.min(1, Math.abs(sample.light - .46) / .54);
const weight = saturation ** 2 * (.15 + usableLight);
accent[0] += sample.red * weight;
accent[1] += sample.green * weight;
accent[2] += sample.blue * weight;
accentWeight += weight;
}
const resolvedAccent = accentWeight > 1
? accent.map((channel) => Math.round(channel / accentWeight))
: average.map((channel) => Math.round(channel));
let resolvedFocusX = clamp(focusX / focusWeight);
if (safeArea === "left") resolvedFocusX = Math.max(.64, resolvedFocusX);
if (safeArea === "right") resolvedFocusX = Math.min(.36, resolvedFocusX);
resolve({
appearance: averageBrightness >= .58 ? "light" : "dark",
accent: resolvedAccent,
focusX: resolvedFocusX,
focusY: clamp(focusY / focusWeight),
aspect: image.naturalWidth / Math.max(1, image.naturalHeight),
luma: clamp(averageBrightness),
safeArea,
});
} catch {
resolve(defaultProfile);
}
};
image.onerror = () => resolve(defaultProfile);
image.src = artUrl;
});
const detectShellAppearance = () => {
const root = document.documentElement;
const body = document.body;
const classes = `${root?.className || ""} ${body?.className || ""}`
.toLowerCase()
.replace(/\bdream-theme-(?:dark|light)\b/g, "");
if (/\b(dark|electron-dark|theme-dark|appearance-dark)\b/.test(classes)) return "dark";
if (/\b(light|electron-light|theme-light|appearance-light)\b/.test(classes)) return "light";
const dataTheme = (
root?.getAttribute?.("data-theme") ||
root?.getAttribute?.("data-appearance") ||
root?.getAttribute?.("data-color-mode") ||
body?.getAttribute?.("data-theme") ||
body?.getAttribute?.("data-appearance") ||
""
).toLowerCase();
if (dataTheme.includes("dark")) return "dark";
if (dataTheme.includes("light")) return "light";
try {
const hadSkin = root?.classList?.contains?.("codex-dream-skin");
const savedSkinClasses = hadSkin
? ROOT_CLASSES.filter((className) => root.classList.contains(className))
: [];
samplingNativeShell = true;
if (hadSkin) root.classList.remove(...ROOT_CLASSES);
try {
const colorScheme = getComputedStyle(root).colorScheme || "";
if (colorScheme.includes("dark") && !colorScheme.includes("light")) return "dark";
if (colorScheme.includes("light") && !colorScheme.includes("dark")) return "light";
} finally {
if (hadSkin) root.classList.add(...savedSkinClasses);
observer?.takeRecords?.();
samplingNativeShell = false;
}
} catch {
samplingNativeShell = false;
}
try {
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
} catch {}
return "light";
};
const clearSkinDom = () => {
const root = document.documentElement;
root?.classList.remove(...ROOT_CLASSES);
for (const property of ROOT_PROPERTIES) root?.style.removeProperty(property);
document.querySelectorAll(".dream-home").forEach((node) => node.classList.remove("dream-home"));
document.querySelectorAll(".dream-task").forEach((node) => node.classList.remove("dream-task"));
document.querySelectorAll(".dream-home-shell").forEach((node) => node.classList.remove("dream-home-shell"));
document.querySelectorAll(`.${HOME_UTILITY_CLASS}`).forEach((node) => node.classList.remove(HOME_UTILITY_CLASS));
document.getElementById(STYLE_ID)?.remove();
document.getElementById(CHROME_ID)?.remove();
};
const applyProfile = (root) => {
const focusX = config.focusX ?? profile.focusX;
const focusY = config.focusY ?? profile.focusY;
const appearance = config.appearance === "auto" ? detectShellAppearance() : config.appearance;
const focus = focusX < .4 ? "left" : focusX > .6 ? "right" : "center";
const safeArea = config.safeArea === "auto" ? (profile.safeArea ||
(focus === "left" ? "right" : focus === "right" ? "left" : "center")) : config.safeArea;
const taskMode = config.taskMode === "auto"
? profile.aspect >= 2.25 ? "banner" : "ambient"
: config.taskMode;
const accent = config.accent || `rgb(${profile.accent.join(" ")})`;
const accentInk = luminance(...profile.accent) > .42 ? "rgb(26 24 28)" : "rgb(250 248 251)";
root.classList.toggle("dream-theme-light", appearance === "light");
root.classList.toggle("dream-theme-dark", appearance === "dark");
root.classList.toggle("dream-art-wide", profile.aspect >= 1.75);
root.classList.toggle("dream-art-standard", profile.aspect < 1.75);
for (const value of ["left", "center", "right"]) {
root.classList.toggle(`dream-focus-${value}`, focus === value);
}
for (const value of ["left", "center", "right", "none"]) {
root.classList.toggle(`dream-safe-${value}`, safeArea === value);
}
for (const value of ["ambient", "banner", "off"]) {
root.classList.toggle(`dream-task-${value}`, taskMode === value);
}
root.style.setProperty("--dream-art", `url("${artUrl}")`);
root.style.setProperty("--dream-art-position", `${Math.round(focusX * 100)}% ${Math.round(focusY * 100)}%`);
root.style.setProperty("--dream-focus-x", String(focusX));
root.style.setProperty("--dream-focus-y", String(focusY));
root.style.setProperty("--dream-accent", accent);
root.style.setProperty("--dream-accent-ink", accentInk);
root.style.setProperty("--dream-image-luma", profile.luma.toFixed(3));
root.style.setProperty("--dream-overlay-opacity", `${Math.round(config.overlayOpacity * 100)}%`);
};
const ensure = () => {
if (window.__CODEX_DREAM_SKIN_DISABLED__) return;
const root = document.documentElement;
if (!root || !document.body) return;
const shellMain = document.querySelector("main.main-surface");
const shellSidebar = document.querySelector("aside.app-shell-left-panel");
if (!shellMain || !shellSidebar) {
clearSkinDom();
return;
}
root.classList.add("codex-dream-skin");
applyProfile(root);
let style = document.getElementById(STYLE_ID);
if (!style) {
style = document.createElement("style");
style.id = STYLE_ID;
(document.head || root).appendChild(style);
}
if (style.dataset.dreamVersion !== "3") {
style.textContent = cssText;
style.dataset.dreamVersion = "3";
}
const home = document.querySelector('[role="main"]:has([data-testid="home-icon"])');
for (const candidate of document.querySelectorAll('[role="main"]')) {
candidate.classList.toggle("dream-home", candidate === home);
candidate.classList.toggle("dream-task", candidate !== home);
}
const utilityBars = new Set(home ? home.querySelectorAll('[class*="_homeUtilityBar_"]') : []);
for (const candidate of document.querySelectorAll(`.${HOME_UTILITY_CLASS}`)) {
if (!utilityBars.has(candidate)) candidate.classList.remove(HOME_UTILITY_CLASS);
}
for (const candidate of utilityBars) candidate.classList.add(HOME_UTILITY_CLASS);
shellMain.classList.toggle("dream-home-shell", Boolean(home));
let chrome = document.getElementById(CHROME_ID);
if (!chrome || chrome.parentElement !== document.body) {
chrome?.remove();
chrome = document.createElement("div");
chrome.id = CHROME_ID;
chrome.setAttribute("aria-hidden", "true");
document.body.appendChild(chrome);
}
chrome.classList.toggle("dream-home-shell", Boolean(home));
};
const cleanup = () => {
const state = window[STATE_KEY];
if (state?.installToken !== installToken) return false;
window.__CODEX_DREAM_SKIN_DISABLED__ = true;
clearSkinDom();
state?.observer?.disconnect();
if (state?.timer) clearInterval(state.timer);
if (state?.scheduler?.timeout) clearTimeout(state.scheduler.timeout);
if (state?.artUrl) URL.revokeObjectURL(state.artUrl);
delete window[STATE_KEY];
return true;
};
const scheduler = { timeout: null };
const scheduleEnsure = () => {
if (scheduler.timeout) clearTimeout(scheduler.timeout);
scheduler.timeout = setTimeout(() => {
scheduler.timeout = null;
ensure();
}, 180);
};
observer = new MutationObserver(() => {
if (samplingNativeShell) return;
scheduleEnsure();
});
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["class", "data-theme", "data-appearance", "data-color-mode"],
});
const timer = setInterval(ensure, 5000);
window[STATE_KEY] = {
ensure, cleanup, observer, timer, scheduler, artUrl, profile, config, installToken, version: "1.2.0",
};
ensure();
analyzeArt().then((result) => {
const state = window[STATE_KEY];
if (state?.installToken !== installToken || window.__CODEX_DREAM_SKIN_DISABLED__) return;
profile = result;
state.profile = result;
ensure();
});
return { installed: true, version: "1.2.0", adaptive: true };
})(__DREAM_CSS_JSON__, __DREAM_ART_JSON__, __DREAM_THEME_JSON__)