dsh-ccx 0.8.9 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -21
  2. package/NOTICE +23 -23
  3. package/README.md +151 -143
  4. package/assets/icon.svg +27 -27
  5. package/cordis.patch.yml +16 -16
  6. package/lib/client.js +1481 -2244
  7. package/lib/index.js +716 -449
  8. package/lib/vendor/code-codex/ascii-tiles.js +145 -0
  9. package/lib/vendor/code-codex/aurora-ionosphere.js +7 -6
  10. package/lib/vendor/code-codex/black-hole.js +10 -7
  11. package/lib/vendor/code-codex/blinking-squares.js +6 -13
  12. package/lib/vendor/code-codex/cloud-train.js +9 -8
  13. package/lib/vendor/code-codex/galleries.json +100 -100
  14. package/lib/vendor/code-codex/glow-horizon.js +1 -1
  15. package/lib/vendor/code-codex/heavenly-cloud.js +5 -4
  16. package/lib/vendor/code-codex/milky-way.js +3 -2
  17. package/lib/vendor/code-codex/mountain.js +5 -4
  18. package/lib/vendor/code-codex/particle-image.js +435 -14
  19. package/lib/vendor/code-codex/pixel-sculpt.js +85 -5
  20. package/lib/vendor/code-codex/scene-defaults.json +94 -1
  21. package/lib/vendor/code-codex/scene-schemas.json +1008 -0
  22. package/lib/vendor/code-codex/shallow-ocean-thumbnails.json +12 -0
  23. package/lib/vendor/code-codex/shallow-ocean.js +5094 -0
  24. package/lib/vendor/code-codex/spectral-drape.js +172 -0
  25. package/package.json +70 -59
  26. package/src/client/api.ts +90 -0
  27. package/src/client/background/layer.ts +187 -0
  28. package/src/client/background/pixel-sculpt.ts +167 -0
  29. package/src/client/background/scene-runner.ts +317 -0
  30. package/src/client/background/shallow-ocean.ts +344 -0
  31. package/src/client/background/vendor-loader.ts +297 -0
  32. package/src/client/background/wallpaper.ts +87 -0
  33. package/src/client/index.ts +247 -0
  34. package/src/client/surfaces/corner-patch.ts +100 -0
  35. package/src/client/surfaces/surface-css.ts +155 -0
  36. package/src/client/ui/draft.ts +105 -0
  37. package/src/client/ui/icons.ts +47 -0
  38. package/src/client/ui/panel.ts +1524 -0
  39. package/src/client/ui/shallow-ocean-panel.ts +376 -0
  40. package/src/client/ui/styles.ts +1471 -0
  41. package/src/host/fence.ts +78 -0
  42. package/src/host/index.ts +26 -0
  43. package/src/host/routes.ts +367 -0
  44. package/src/host/storage.ts +109 -0
  45. package/src/host/window-chrome.ts +53 -0
  46. package/src/shared/constants.ts +239 -0
  47. package/src/shared/sanitize.ts +110 -0
  48. package/src/shared/types.ts +145 -0
  49. package/tsconfig.json +16 -0
@@ -0,0 +1,87 @@
1
+ import { API_BASE } from '../../shared/constants';
2
+ import type { AppearanceSettings, WallpaperPosition } from '../../shared/types';
3
+ import { activeStage, paintFallback, releaseMediaInStage } from './layer';
4
+
5
+ const POS_MAP: Record<WallpaperPosition, string> = {
6
+ center: 'center',
7
+ top: 'center top',
8
+ bottom: 'center bottom',
9
+ left: 'left center',
10
+ right: 'right center',
11
+ };
12
+
13
+ function createWallpaperVideo(
14
+ url: string,
15
+ fit: 'cover' | 'contain',
16
+ pos: string,
17
+ stage: HTMLDivElement,
18
+ ): HTMLVideoElement {
19
+ const v = document.createElement('video');
20
+ v.src = url;
21
+ v.loop = true;
22
+ v.muted = true;
23
+ v.autoplay = true;
24
+ v.playsInline = true;
25
+ v.style.cssText = `position:absolute;inset:0;width:100%;height:100%;object-fit:${fit};object-position:${pos};`;
26
+ v.onerror = () => {
27
+ releaseMediaInStage(stage);
28
+ stage.textContent = '';
29
+ };
30
+ return v;
31
+ }
32
+
33
+ export function renderWallpaper(state: AppearanceSettings | null): void {
34
+ const stage = activeStage();
35
+ releaseMediaInStage(stage);
36
+ stage.textContent = '';
37
+
38
+ if (!(state && state.enabled && state.mode === 'wallpaper')) {
39
+ return;
40
+ }
41
+ if (!state.wallpaperId) {
42
+ paintFallback('从设置面板的素材库选择一张壁纸');
43
+ return;
44
+ }
45
+
46
+ const url = `${API_BASE}/wallpaper?id=${encodeURIComponent(state.wallpaperId)}`;
47
+ const fit =
48
+ state.wallpaperFit === 'contain'
49
+ ? 'contain'
50
+ : state.wallpaperFit === 'tile'
51
+ ? 'tile'
52
+ : 'cover';
53
+ const pos = POS_MAP[state.wallpaperPosition] || 'center';
54
+
55
+ if (fit === 'tile') {
56
+ const tile = document.createElement('div');
57
+ tile.style.cssText =
58
+ 'position:absolute;inset:0;background-repeat:repeat;' +
59
+ `background-size:auto;background-position:${pos};`;
60
+ tile.style.backgroundImage = `url("${url}")`;
61
+
62
+ const probe = document.createElement('img');
63
+ probe.style.display = 'none';
64
+ probe.onerror = () => {
65
+ const video = createWallpaperVideo(url, 'cover', pos, stage);
66
+ stage.textContent = '';
67
+ stage.appendChild(video);
68
+ void video.play().catch(() => {});
69
+ };
70
+ stage.appendChild(tile);
71
+ stage.appendChild(probe);
72
+ probe.src = url;
73
+ return;
74
+ }
75
+
76
+ const img = document.createElement('img');
77
+ img.decoding = 'async';
78
+ img.style.cssText = `position:absolute;inset:0;width:100%;height:100%;object-fit:${fit};object-position:${pos};`;
79
+ img.onerror = () => {
80
+ const video = createWallpaperVideo(url, fit, pos, stage);
81
+ stage.textContent = '';
82
+ stage.appendChild(video);
83
+ void video.play().catch(() => {});
84
+ };
85
+ img.src = url;
86
+ stage.appendChild(img);
87
+ }
@@ -0,0 +1,247 @@
1
+ import { PLUGIN_ID, SCENE_IDS } from '../shared/constants';
2
+ import { finiteNum, pickVisual, sanitizeSettings } from '../shared/sanitize';
3
+ import type { AppearanceSettings, WallpaperItem } from '../shared/types';
4
+ import { apiPostJson, ensureSchemas, fetchState } from './api';
5
+ import { applyLayerAdjustments, disposeLayer, ensureLayer } from './background/layer';
6
+ import { disposeAllRunners, migratePoisonedStores, syncBackgroundRunner } from './background/scene-runner';
7
+ import { disposeCornerPatch, syncCornerPatch } from './surfaces/corner-patch';
8
+ import { applySurfaceStyles, clearSurfaceStyles } from './surfaces/surface-css';
9
+ import {
10
+ ensurePanel,
11
+ getSettingsId,
12
+ isSettingsOpen,
13
+ positionSettingsPanel,
14
+ refreshPanel,
15
+ renderSettings,
16
+ setPanelStatus,
17
+ syncPanelTheme,
18
+ syncSidebarCollapsed,
19
+ teardownPanel,
20
+ } from './ui/panel';
21
+
22
+ interface CordisClientContext {
23
+ effect: (fn: () => () => void, label?: string) => void;
24
+ }
25
+
26
+ const POLL_INTERVAL_MS = 8000;
27
+ const SAVE_DEBOUNCE_MS = 280;
28
+
29
+ let state: AppearanceSettings | null = null;
30
+ let wallpapersCache: WallpaperItem[] = [];
31
+ let savedAtLocal = 0;
32
+ let saveSeq = 0;
33
+ let saveTimer: ReturnType<typeof setTimeout> | null = null;
34
+ let pollTimer: ReturnType<typeof setInterval> | null = null;
35
+ let resizeTimer: ReturnType<typeof setTimeout> | null = null;
36
+ let themeObserver: MutationObserver | null = null;
37
+ let layoutObserver: MutationObserver | null = null;
38
+ let layoutRaf = 0;
39
+ let started = false;
40
+
41
+ function scheduleSave(): void {
42
+ if (!state) return;
43
+ if (saveTimer) clearTimeout(saveTimer);
44
+ saveTimer = setTimeout(() => {
45
+ saveTimer = null;
46
+ if (!state) return;
47
+ const seq = ++saveSeq;
48
+ const payload = sanitizeSettings(state);
49
+ void apiPostJson<{ ok?: boolean; settings?: AppearanceSettings; error?: string }>('/state-save.json', {
50
+ settings: payload,
51
+ })
52
+ .then((res) => {
53
+ if (seq !== saveSeq) return;
54
+ if (res?.ok && res.settings) {
55
+ state = sanitizeSettings(res.settings);
56
+ savedAtLocal = finiteNum(state.savedAt, 0);
57
+ }
58
+ })
59
+ .catch((err) => {
60
+ if (seq !== saveSeq) return;
61
+ setPanelStatus(`保存失败:${String((err as Error)?.message || err)}`, true);
62
+ });
63
+ }, SAVE_DEBOUNCE_MS);
64
+ }
65
+
66
+ function applyAll(): void {
67
+ if (!state) return;
68
+ const { layer } = ensureLayer();
69
+
70
+ ensurePanel({
71
+ getState: () => state,
72
+ getWallpapers: () => wallpapersCache,
73
+ setWallpapers: (list) => {
74
+ wallpapersCache = list;
75
+ },
76
+ scheduleSave,
77
+ applyAll,
78
+ onStatus: setPanelStatus,
79
+ });
80
+
81
+ applyLayerAdjustments(state);
82
+ syncBackgroundRunner({
83
+ getState: () => state,
84
+ onStatus: setPanelStatus,
85
+ });
86
+ applySurfaceStyles(state, layer);
87
+ syncCornerPatch(state, layer);
88
+ refreshPanel(state);
89
+ }
90
+
91
+ function startPolling(): void {
92
+ if (pollTimer) return;
93
+ pollTimer = setInterval(() => {
94
+ if (document.hidden) return;
95
+ void fetchState()
96
+ .then((data) => {
97
+ if (!data?.settings) return;
98
+ const remote = sanitizeSettings(data.settings);
99
+ const remoteAt = finiteNum(remote.savedAt, 0);
100
+ if (remoteAt && remoteAt !== savedAtLocal) {
101
+ const before = state ? JSON.stringify(pickVisual(state)) : '';
102
+ state = remote;
103
+ savedAtLocal = remoteAt;
104
+ if (Array.isArray(data.wallpapers)) {
105
+ wallpapersCache = data.wallpapers;
106
+ }
107
+ if (before !== JSON.stringify(pickVisual(state))) {
108
+ applyAll();
109
+ }
110
+ }
111
+ })
112
+ .catch(() => {});
113
+ }, POLL_INTERVAL_MS);
114
+ }
115
+
116
+ function scheduleLayoutSync(): void {
117
+ if (layoutRaf) return;
118
+ layoutRaf = requestAnimationFrame(() => {
119
+ layoutRaf = 0;
120
+ if (!started) return;
121
+ syncSidebarCollapsed();
122
+ if (state) {
123
+ const layer = ensureLayer().layer;
124
+ syncCornerPatch(state, layer);
125
+ }
126
+ if (isSettingsOpen()) {
127
+ positionSettingsPanel();
128
+ }
129
+ });
130
+ }
131
+
132
+ function startObservers(): void {
133
+ if (!themeObserver && document.body) {
134
+ themeObserver = new MutationObserver(() => {
135
+ syncPanelTheme();
136
+ if (state) {
137
+ applySurfaceStyles(state, ensureLayer().layer);
138
+ }
139
+ });
140
+ themeObserver.observe(document.body, {
141
+ attributes: true,
142
+ attributeFilter: ['data-ds-dark-theme', 'class'],
143
+ });
144
+ }
145
+
146
+ const rootEl = document.getElementById('root') || document.body;
147
+ if (!layoutObserver && rootEl) {
148
+ layoutObserver = new MutationObserver(() => {
149
+ scheduleLayoutSync();
150
+ });
151
+ layoutObserver.observe(rootEl, {
152
+ attributes: true,
153
+ attributeFilter: ['class', 'style', 'data-collapsed'],
154
+ subtree: false,
155
+ childList: true,
156
+ });
157
+ }
158
+ }
159
+
160
+ function onResize(): void {
161
+ if (resizeTimer) clearTimeout(resizeTimer);
162
+ resizeTimer = setTimeout(() => {
163
+ resizeTimer = null;
164
+ scheduleLayoutSync();
165
+ }, 120);
166
+ }
167
+
168
+ function teardown(): void {
169
+ if (saveTimer) {
170
+ clearTimeout(saveTimer);
171
+ saveTimer = null;
172
+ }
173
+ if (pollTimer) {
174
+ clearInterval(pollTimer);
175
+ pollTimer = null;
176
+ }
177
+ if (resizeTimer) {
178
+ clearTimeout(resizeTimer);
179
+ resizeTimer = null;
180
+ }
181
+ if (layoutRaf) {
182
+ cancelAnimationFrame(layoutRaf);
183
+ layoutRaf = 0;
184
+ }
185
+ if (themeObserver) {
186
+ themeObserver.disconnect();
187
+ themeObserver = null;
188
+ }
189
+ if (layoutObserver) {
190
+ layoutObserver.disconnect();
191
+ layoutObserver = null;
192
+ }
193
+ window.removeEventListener('resize', onResize);
194
+
195
+ disposeCornerPatch();
196
+ clearSurfaceStyles();
197
+ disposeAllRunners();
198
+ disposeLayer();
199
+ teardownPanel();
200
+ state = null;
201
+ wallpapersCache = [];
202
+ savedAtLocal = 0;
203
+ }
204
+
205
+ export function apply(ctx: CordisClientContext): void {
206
+ if (started) return;
207
+ started = true;
208
+
209
+ ctx.effect(() => {
210
+ return () => {
211
+ started = false;
212
+ teardown();
213
+ };
214
+ }, `${PLUGIN_ID}: reset apply guard`);
215
+
216
+ migratePoisonedStores();
217
+ ensureLayer();
218
+ void ensureSchemas().then(() => {
219
+ const sid = getSettingsId();
220
+ if (isSettingsOpen() && sid && SCENE_IDS.includes(sid)) {
221
+ renderSettings(sid);
222
+ }
223
+ });
224
+
225
+ void fetchState()
226
+ .then((data) => {
227
+ if (!started) return;
228
+ state = sanitizeSettings(data?.settings);
229
+ if (Array.isArray(data?.wallpapers)) {
230
+ wallpapersCache = data.wallpapers;
231
+ }
232
+ savedAtLocal = finiteNum(state.savedAt, 0);
233
+ applyAll();
234
+ startPolling();
235
+ startObservers();
236
+ })
237
+ .catch(() => {
238
+ if (!started) return;
239
+ state = sanitizeSettings(null);
240
+ applyAll();
241
+ startObservers();
242
+ });
243
+
244
+ window.addEventListener('resize', onResize);
245
+ }
246
+
247
+ export const inject: string[] = [];
@@ -0,0 +1,100 @@
1
+ import { clamp, finiteNum } from '../../shared/sanitize';
2
+ import type { AppearanceSettings } from '../../shared/types';
3
+
4
+ let cornerEl: HTMLDivElement | null = null;
5
+ let cornerRO: ResizeObserver | null = null;
6
+ let cornerROTarget: Element | null = null;
7
+ let cornerRetryTimer: ReturnType<typeof setTimeout> | null = null;
8
+ let cornerRetries = 0;
9
+
10
+ /**
11
+ * 在 DSH 0.2.2-rc.5 中,`[data-slot="main"]` 的直接父级是 `.mainPanel`(无圆角),
12
+ * 而带 `border-radius: 16px 0 0 0` 的 `.centerCol` 是其祖父级。
13
+ * 向上查找最多 4 层,兼容 0.2.1 与 0.2.2-rc.5。
14
+ */
15
+ function findRoundedMainColumn(): { col: HTMLElement; radius: number } | null {
16
+ const slot = document.querySelector('[data-slot="main"]');
17
+ let cur: HTMLElement | null = slot ? slot.parentElement : null;
18
+ for (let depth = 0; depth < 4 && cur; depth++) {
19
+ const r = parseFloat(getComputedStyle(cur).borderTopLeftRadius);
20
+ if (Number.isFinite(r) && r > 0) {
21
+ return { col: cur, radius: r };
22
+ }
23
+ cur = cur.parentElement;
24
+ }
25
+ return null;
26
+ }
27
+
28
+ export function syncCornerPatch(state: AppearanceSettings | null, layer: HTMLElement | null): void {
29
+ if (cornerRetryTimer) {
30
+ clearTimeout(cornerRetryTimer);
31
+ cornerRetryTimer = null;
32
+ }
33
+ const masksOn = Boolean(
34
+ state && state.enabled && state.mode !== 'off' && state.surfaces && state.surfaces.enabled,
35
+ );
36
+ if (!masksOn || !layer) {
37
+ if (cornerEl) cornerEl.style.display = 'none';
38
+ return;
39
+ }
40
+
41
+ const found = findRoundedMainColumn();
42
+ if (!found) {
43
+ if (cornerEl) cornerEl.style.display = 'none';
44
+ if (cornerRetries < 30) {
45
+ cornerRetries++;
46
+ cornerRetryTimer = setTimeout(() => syncCornerPatch(state, layer), 1000);
47
+ }
48
+ return;
49
+ }
50
+
51
+ cornerRetries = 0;
52
+ const { col, radius: r } = found;
53
+ if (!cornerEl || !layer.contains(cornerEl)) {
54
+ cornerEl = document.createElement('div');
55
+ cornerEl.id = 'dsh-ap-corner';
56
+ cornerEl.style.cssText = 'position:absolute;left:0;top:0;pointer-events:none;corner-shape:round;';
57
+ layer.appendChild(cornerEl);
58
+ }
59
+
60
+ const rect = col.getBoundingClientRect();
61
+ const a = clamp(finiteNum(state?.surfaces?.sidebar, 66), 0, 100) / 100;
62
+ const isDark = document.body?.hasAttribute('data-ds-dark-theme') ?? true;
63
+ const baseRgb = isDark ? '16,17,20' : '249,250,251';
64
+ const mask = `radial-gradient(circle ${r}px at 100% 100%, transparent 0, transparent ${(r - 0.6).toFixed(1)}px, #000 ${r}px)`;
65
+
66
+ cornerEl.style.display = 'block';
67
+ cornerEl.style.left = `${rect.x}px`;
68
+ cornerEl.style.top = `${rect.y}px`;
69
+ cornerEl.style.width = `${r}px`;
70
+ cornerEl.style.height = `${r}px`;
71
+ cornerEl.style.background = `rgba(${baseRgb},${a.toFixed(3)})`;
72
+ cornerEl.style.webkitMaskImage = mask;
73
+ cornerEl.style.maskImage = mask;
74
+
75
+ if (cornerRO && cornerROTarget !== col) {
76
+ cornerRO.disconnect();
77
+ cornerRO = null;
78
+ }
79
+ if (!cornerRO) {
80
+ cornerRO = new ResizeObserver(() => syncCornerPatch(state, layer));
81
+ cornerRO.observe(col);
82
+ cornerROTarget = col;
83
+ }
84
+ }
85
+
86
+ export function disposeCornerPatch(): void {
87
+ if (cornerRetryTimer) {
88
+ clearTimeout(cornerRetryTimer);
89
+ cornerRetryTimer = null;
90
+ }
91
+ if (cornerRO) {
92
+ cornerRO.disconnect();
93
+ cornerRO = null;
94
+ }
95
+ cornerROTarget = null;
96
+ cornerRetries = 0;
97
+ if (cornerEl) {
98
+ cornerEl.style.display = 'none';
99
+ }
100
+ }
@@ -0,0 +1,155 @@
1
+ import { SURFACE_REGIONS } from '../../shared/constants';
2
+ import { clamp, finiteNum } from '../../shared/sanitize';
3
+ import type { AppearanceSettings, SurfaceRegionKey } from '../../shared/types';
4
+ import { syncCornerPatch, disposeCornerPatch } from './corner-patch';
5
+
6
+ export const LAYER_ID = 'dsh-ap-layer';
7
+ export const DIM_ID = 'dsh-ap-dim';
8
+ export const BG_STYLE_ID = 'dsh-ap-surface-style';
9
+
10
+ export interface RegionRowMeta {
11
+ key: SurfaceRegionKey;
12
+ zh: string;
13
+ en: string;
14
+ selector: string;
15
+ baseVar: '--ap-base-sidebar' | '--ap-base-main';
16
+ }
17
+
18
+ export const REGION_ROWS: readonly RegionRowMeta[] = [
19
+ {
20
+ key: 'sidebar',
21
+ zh: '会话侧栏',
22
+ en: 'Sidebar',
23
+ selector: 'div:has(> [data-slot="sidebar"])',
24
+ baseVar: '--ap-base-sidebar',
25
+ },
26
+ {
27
+ key: 'conversation',
28
+ zh: '对话区',
29
+ en: 'Conversation',
30
+ selector: 'div:has(> [data-slot="main"])',
31
+ baseVar: '--ap-base-main',
32
+ },
33
+ {
34
+ key: 'composer',
35
+ zh: '消息输入区',
36
+ en: 'Composer',
37
+ selector: '[data-composer-card]',
38
+ baseVar: '--ap-base-main',
39
+ },
40
+ {
41
+ key: 'right',
42
+ zh: '右侧栏',
43
+ en: 'Right panel',
44
+ selector: ':is([data-rightbar-col], div:has(> [data-slot="rightbar"]))',
45
+ baseVar: '--ap-base-sidebar',
46
+ },
47
+ ];
48
+
49
+ let surfaceStyleEl: HTMLStyleElement | null = null;
50
+ let cachedCss = '';
51
+
52
+ /**
53
+ * 构建级联层表面 CSS(适配 DSH 0.2.2-rc.5 与 0.2.1):
54
+ * 1. 将通配清除限定在 `body > #root` 子树内:
55
+ * - Settings 弹窗 / Onboarding / Model 菜单 / Tooltip / Lightbox 均 portal 到 `body` 旁(#root 之外),
56
+ * 天然豁免并保持原生清晰样式,同时避免对 2000+ 聊天节点执行祖先 `[class*="_panel"] *` 扫描。
57
+ * - 背景层 `#dsh-ap-layer` 挂载于 `body` 首位(#root 之外),天然不被通配透明破坏。
58
+ * 2. Windows DSH 0.2.2-rc.5 自定义标题栏(`html[data-windows-titlebar]`):
59
+ * - `.frame::before`(40px 顶部条)随侧栏透明度同步透明或上色。
60
+ * - `preload-app.cjs` 的 `titleBarOverlay` probe(`body > span[style*="--dsw-specific-sidebar-fill"]`)
61
+ * 在背景启用时置透明,防止右上角窗口控制按钮背后出现不透明实心矩形块。
62
+ */
63
+ export function buildSurfaceCss(): string {
64
+ if (cachedCss) return cachedCss;
65
+
66
+ const clearElements =
67
+ 'body > #root :where(div,main,aside,section,article,header,footer,nav,form,dialog,ul,ol,li,button,input,textarea,select)' +
68
+ ':not([role="img"]):not([data-icon]):not([class*="icon" i])';
69
+ const clearDecl =
70
+ 'background-color:transparent !important;-webkit-backdrop-filter:none !important;backdrop-filter:none !important';
71
+ const composerKeep = ':not([data-composer-card]):not([data-composer-card] *)';
72
+
73
+ const lines: string[] = [
74
+ '@layer dsh-ap-clear, dsh-ap-masks, dsh-ap-assert;',
75
+ '@layer dsh-ap-clear {',
76
+ 'html[data-ap-bg]{background-color:transparent !important;--ap-base-sidebar:249,250,251;--ap-base-main:255,255,255}',
77
+ 'html[data-ap-bg] body:has([data-ds-dark-theme]),html[data-ap-bg] body[data-ds-dark-theme]{--ap-base-sidebar:16,17,20;--ap-base-main:11,12,15}',
78
+ 'html[data-ap-bg] body,html[data-ap-bg] body > #root{isolation:isolate;background-color:transparent !important}',
79
+ `html[data-ap-bg][data-ap-masks] ${clearElements}{${clearDecl}}`,
80
+ `html[data-ap-bg]:not([data-ap-masks]) ${clearElements}${composerKeep}{${clearDecl}}`,
81
+ 'html[data-ap-bg][data-windows-titlebar] body > #root > div::before{background:transparent !important}',
82
+ 'html[data-ap-bg][data-windows-titlebar] body > span[style*="--dsw-specific-sidebar-fill"]{background-color:transparent !important}',
83
+ 'html[data-ap-bg] body > #root [data-composer-seat],html[data-ap-bg] body > #root div:has(> [data-slot="conversation.input.dock"]){background:none !important;background-image:none !important}',
84
+ 'html[data-ap-bg] body > #root :is([class*="bg-gradient"],[class*="TopFade"],[class*="fade" i]){background-image:none !important}',
85
+ '}',
86
+ '@layer dsh-ap-masks {',
87
+ ];
88
+
89
+ for (const r of REGION_ROWS) {
90
+ lines.push(
91
+ `html[data-ap-masks] body > #root ${r.selector}{background-color:rgba(var(${r.baseVar}),var(--ap-mask-${r.key})) !important}`,
92
+ );
93
+ }
94
+ lines.push(
95
+ 'html[data-ap-masks][data-windows-titlebar] body > #root > div::before{background-color:rgba(var(--ap-base-sidebar),var(--ap-mask-sidebar)) !important}',
96
+ 'html[data-ap-masks] body > #root [data-composer-card]{box-shadow:none !important}',
97
+ '}',
98
+ '@layer dsh-ap-assert {',
99
+ `html[data-ap-bg] body > div#${LAYER_ID}{background:var(--ap-layer-bg,#000) !important}`,
100
+ `html[data-ap-bg] body > div#${LAYER_ID} > div#${DIM_ID}{background:var(--ap-dim-bg,transparent) !important}`,
101
+ '}',
102
+ );
103
+
104
+ cachedCss = lines.join('\n');
105
+ return cachedCss;
106
+ }
107
+
108
+ export function applySurfaceVars(state: AppearanceSettings | null, layer: HTMLElement | null): void {
109
+ const html = document.documentElement;
110
+ for (const key of SURFACE_REGIONS) {
111
+ const v = state?.surfaces ? clamp(finiteNum(state.surfaces[key], 66), 0, 100) / 100 : 0;
112
+ html.style.setProperty(`--ap-mask-${key}`, v.toFixed(3));
113
+ }
114
+ syncCornerPatch(state, layer);
115
+ }
116
+
117
+ export function applySurfaceStyles(state: AppearanceSettings | null, layer: HTMLElement | null): void {
118
+ const on = Boolean(state && state.enabled && state.mode !== 'off');
119
+ const masksOn = on && Boolean(state?.surfaces?.enabled);
120
+ const html = document.documentElement;
121
+
122
+ if (!on) {
123
+ clearSurfaceStyles();
124
+ return;
125
+ }
126
+
127
+ if (!surfaceStyleEl || !document.head.contains(surfaceStyleEl)) {
128
+ surfaceStyleEl = document.createElement('style');
129
+ surfaceStyleEl.id = BG_STYLE_ID;
130
+ surfaceStyleEl.setAttribute('data-dsh-ccx', 'surface');
131
+ (document.head || document.documentElement).appendChild(surfaceStyleEl);
132
+ }
133
+
134
+ const css = buildSurfaceCss();
135
+ if (surfaceStyleEl.textContent !== css) surfaceStyleEl.textContent = css;
136
+
137
+ html.setAttribute('data-ap-bg', 'true');
138
+ applySurfaceVars(state, layer);
139
+ if (masksOn) html.setAttribute('data-ap-masks', 'true');
140
+ else html.removeAttribute('data-ap-masks');
141
+ }
142
+
143
+ export function clearSurfaceStyles(): void {
144
+ const html = document.documentElement;
145
+ html.removeAttribute('data-ap-bg');
146
+ html.removeAttribute('data-ap-masks');
147
+ for (const key of SURFACE_REGIONS) {
148
+ try {
149
+ html.style.removeProperty(`--ap-mask-${key}`);
150
+ } catch {
151
+ /* ignore */
152
+ }
153
+ }
154
+ disposeCornerPatch();
155
+ }
@@ -0,0 +1,105 @@
1
+ import { clamp, finiteNum } from '../../shared/sanitize';
2
+ import type { SceneField, SceneParamMap, SceneSchema } from '../../shared/types';
3
+
4
+ const HEX6_RE = /^#[\da-fA-F]{6}$/;
5
+
6
+ export function escapeHtml(str: unknown): string {
7
+ return String(str)
8
+ .replace(/&/g, '&amp;')
9
+ .replace(/</g, '&lt;')
10
+ .replace(/>/g, '&gt;')
11
+ .replace(/"/g, '&quot;');
12
+ }
13
+
14
+ export function sanitizeDraft(sch: SceneSchema | null, input: unknown): SceneParamMap {
15
+ const out: SceneParamMap =
16
+ input && typeof input === 'object' ? { ...(input as SceneParamMap) } : {};
17
+ if (!sch) return out;
18
+
19
+ if (typeof sch.qualityDefault === 'string') {
20
+ const q = out.quality;
21
+ if (q !== 'low' && q !== 'medium' && q !== 'high') {
22
+ out.quality = sch.qualityDefault;
23
+ }
24
+ }
25
+
26
+ if (typeof sch.defaults?.performanceMode === 'number') {
27
+ const pm = Number(out.performanceMode);
28
+ out.performanceMode = Number.isFinite(pm)
29
+ ? clamp(Math.round(pm), 0, 3)
30
+ : sch.defaults.performanceMode;
31
+ }
32
+
33
+ for (const f of sch.fields || []) {
34
+ const n = Number(out[f.key]);
35
+ if (!Number.isFinite(n)) {
36
+ out[f.key] = finiteNum(sch.defaults?.[f.key], f.min);
37
+ } else {
38
+ out[f.key] = clamp(n, f.min, f.max);
39
+ }
40
+ }
41
+
42
+ if (Array.isArray(sch.colors)) {
43
+ const cols = Array.isArray(out.colors) ? out.colors : sch.colors;
44
+ out.colors = sch.colors.map((c, idx) =>
45
+ typeof cols[idx] === 'string' && HEX6_RE.test(cols[idx]) ? cols[idx] : c,
46
+ );
47
+ }
48
+
49
+ for (const cf of sch.colorFields || []) {
50
+ const cv = out[cf.key];
51
+ out[cf.key] =
52
+ typeof cv === 'string' && HEX6_RE.test(cv)
53
+ ? cv
54
+ : (typeof sch.defaults?.[cf.key] === 'string' ? (sch.defaults[cf.key] as string) : '#ffffff');
55
+ }
56
+
57
+ for (const tg of sch.toggles || []) {
58
+ const defaultVal = sch.defaults?.[tg.key];
59
+ const rawVal = out[tg.key];
60
+ if (typeof defaultVal === 'number') {
61
+ out[tg.key] = Number(rawVal) === 1 || rawVal === true ? 1 : 0;
62
+ } else {
63
+ out[tg.key] = Boolean(rawVal);
64
+ }
65
+ }
66
+
67
+ return out;
68
+ }
69
+
70
+ export function mergeSceneDraft(
71
+ sch: SceneSchema | null,
72
+ savedOverrides: SceneParamMap | undefined,
73
+ ): SceneParamMap {
74
+ const base: SceneParamMap = sch?.defaults ? { ...sch.defaults } : {};
75
+ if (savedOverrides && typeof savedOverrides === 'object') {
76
+ for (const k of Object.keys(savedOverrides)) {
77
+ base[k] = savedOverrides[k];
78
+ }
79
+ }
80
+ return sanitizeDraft(sch, base);
81
+ }
82
+
83
+ export function fmtFieldVal(f: Pick<SceneField, 'percent' | 'precision' | 'step' | 'unit'>, value: number): string {
84
+ if (f.percent) return `${Math.round(value * 100)}%`;
85
+ const stepStr = String(f.step);
86
+ const inferredDec = stepStr.includes('.') ? (stepStr.split('.')[1] || '').length : 0;
87
+ const dec = f.precision != null ? f.precision : inferredDec;
88
+ return `${Number(value).toFixed(dec)}${f.unit || ''}`;
89
+ }
90
+
91
+ export function draftDeltaObj(
92
+ sch: SceneSchema | null,
93
+ draft: SceneParamMap | null,
94
+ ): { delta: SceneParamMap; full: SceneParamMap; base: SceneParamMap } {
95
+ const base: SceneParamMap = sch?.defaults ? { ...sch.defaults } : {};
96
+ const full = sanitizeDraft(sch, draft);
97
+ const delta: SceneParamMap = {};
98
+ for (const k of Object.keys(full)) {
99
+ if (k === 'quality' && !(k in base)) continue;
100
+ if (JSON.stringify(full[k]) !== JSON.stringify(base[k])) {
101
+ delta[k] = full[k];
102
+ }
103
+ }
104
+ return { delta, full, base };
105
+ }