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,1524 @@
1
+ import {
2
+ DEFAULT_SETTINGS,
3
+ SCENES,
4
+ SCENE_IDS,
5
+ WALLPAPER_MAX_BYTES,
6
+ } from '../../shared/constants';
7
+ import { clamp, finiteNum } from '../../shared/sanitize';
8
+ import type {
9
+ AppearanceSettings,
10
+ SceneField,
11
+ SceneParamMap,
12
+ SurfaceRegionKey,
13
+ WallpaperItem,
14
+ } from '../../shared/types';
15
+ import { apiPostJson, schemaOf, uploadWallpaper } from '../api';
16
+ import { getLayer, resolveSceneLayerBg } from '../background/layer';
17
+ import { ensurePsEditor, getPsEditor, isPsActive, isPsPaused } from '../background/pixel-sculpt';
18
+ import {
19
+ getBgInstance,
20
+ getBgSceneId,
21
+ pushLiveSettings,
22
+ renderScene,
23
+ replayActiveScene,
24
+ writeSceneSetting,
25
+ } from '../background/scene-runner';
26
+ import { getShallowOceanController } from '../background/shallow-ocean';
27
+ import { registry } from '../background/vendor-loader';
28
+ import { REGION_ROWS, applySurfaceVars } from '../surfaces/surface-css';
29
+ import { draftDeltaObj, escapeHtml, fmtFieldVal, mergeSceneDraft, sanitizeDraft } from './draft';
30
+ import { CLOSE_SVG, GEAR_SVG, cardIconMarkup } from './icons';
31
+ import {
32
+ bindShallowOceanEvents,
33
+ renderShallowOceanBodyHtml,
34
+ renderShallowOceanHeaderHtml,
35
+ } from './shallow-ocean-panel';
36
+ import { PANEL_CSS } from './styles';
37
+
38
+ const PANEL_ID = 'dsh-ap-panel';
39
+ const TRIGGER_ID = 'dsh-ap-trigger';
40
+ const LIB_PAGE_SIZE = 12;
41
+
42
+ const PARAM_ROWS = [
43
+ { key: 'dim' as const, zh: '背景压暗', min: 0, max: 80, step: 1, scale: 100 },
44
+ { key: 'blur' as const, zh: '背景模糊', min: 0, max: 20, step: 0.5, scale: 1 },
45
+ ];
46
+
47
+ interface CardDescriptor {
48
+ id: string;
49
+ kind: 'wallpaper' | 'surface' | 'scene';
50
+ title: string;
51
+ ext: string;
52
+ }
53
+
54
+ const CARD_TITLES: Record<string, string> = {
55
+ 'milky-way': 'Milky Way Background',
56
+ 'glow-horizon': 'Glow Horizon Background',
57
+ mountain: 'Layered Mountain Background',
58
+ 'heavenly-cloud': 'Heavenly Cloud Background',
59
+ 'aurora-ionosphere': 'Aurora Ionosphere Background',
60
+ 'black-hole': 'Black Hole Background',
61
+ 'cloud-train': 'Cloud Train Background',
62
+ 'particle-image': 'Particle Image Background',
63
+ 'pixel-sculpt': 'Pixel Sculpt Background',
64
+ 'blinking-squares': 'Blinking Squares Background',
65
+ 'ascii-tiles': 'ASCII Tiles Background',
66
+ 'shallow-ocean': 'Shallow Ocean Letters Background',
67
+ 'spectral-drape': 'Spectral Drape Background',
68
+ };
69
+
70
+ const SCENE_EXT_CLASSES: Record<string, string> = {
71
+ 'glow-horizon': 'ext-glowhorizon',
72
+ 'heavenly-cloud': 'ext-heavenlycloud',
73
+ 'black-hole': 'ext-blackhole',
74
+ 'particle-image': 'ext-particle',
75
+ 'shallow-ocean': 'ext-shallowocean',
76
+ 'ascii-tiles': 'ext-asciitiles',
77
+ 'spectral-drape': 'ext-spectraldrape',
78
+ };
79
+
80
+ const CARDS: CardDescriptor[] = [
81
+ { id: 'custom', kind: 'wallpaper', title: 'Custom Background', ext: '' },
82
+ { id: 'surface', kind: 'surface', title: 'UI Surface Opacity', ext: '' },
83
+ ...SCENES.map((s) => ({
84
+ id: s.id,
85
+ kind: 'scene' as const,
86
+ title: CARD_TITLES[s.id] || s.en,
87
+ ext: SCENE_EXT_CLASSES[s.id] || '',
88
+ })),
89
+ ];
90
+
91
+ const GROUP_LEGENDS: Record<string, string> = {
92
+ particles: '粒子',
93
+ flow: '流动',
94
+ source: '来源',
95
+ pointer: '指针',
96
+ render: '渲染',
97
+ camera: '相机',
98
+ disc: '吸积盘',
99
+ light: '光线',
100
+ input: '输入',
101
+ downward: '下滑动态',
102
+ upward: '上滑动态',
103
+ release: '释放回弹',
104
+ entrance: '开场画面',
105
+ opening: '开场动画',
106
+ interaction: '交互',
107
+ };
108
+
109
+ const FIELD_GROUP_OVERRIDES: Record<string, Record<string, string>> = {
110
+ 'heavenly-cloud': { field: '云场', opening: '开场画面' },
111
+ 'aurora-ionosphere': { field: '电离层', opening: '开场画面' },
112
+ 'milky-way': { field: '运动与形态', opening: '开场画面' },
113
+ };
114
+
115
+ const TUPLE_MAIN_LEGENDS: Record<string, string> = {
116
+ mountain: '山峦与氛围',
117
+ 'cloud-train': '列车与云海',
118
+ 'blinking-squares': '参数',
119
+ };
120
+
121
+ const TINT_LABELS: Record<string, string> = {
122
+ skyTint: '天空色',
123
+ smokeTint: '烟雾色',
124
+ trainTint: '列车色',
125
+ };
126
+
127
+ const COLOR_SECTION_LEGENDS: Record<string, string> = {
128
+ 'milky-way': '五色调色板',
129
+ 'glow-horizon': '光效配色',
130
+ };
131
+
132
+ const QUALITY_TOOLBARS: Record<
133
+ string,
134
+ { mode: 'quality' | 'steps'; items: ReadonlyArray<readonly [string, string, string]> }
135
+ > = {
136
+ 'milky-way': {
137
+ mode: 'quality',
138
+ items: [
139
+ ['low', '1×', '轻量'],
140
+ ['medium', '2×', '均衡'],
141
+ ['high', '3×', '精细'],
142
+ ],
143
+ },
144
+ 'heavenly-cloud': {
145
+ mode: 'quality',
146
+ items: [
147
+ ['low', '56', '低'],
148
+ ['medium', '76', '中'],
149
+ ['high', '100', '高'],
150
+ ],
151
+ },
152
+ 'aurora-ionosphere': {
153
+ mode: 'quality',
154
+ items: [
155
+ ['low', '32', '轻量'],
156
+ ['medium', '50', '均衡'],
157
+ ['high', '72', '精细'],
158
+ ],
159
+ },
160
+ mountain: {
161
+ mode: 'steps',
162
+ items: [
163
+ ['28', '28', '流畅'],
164
+ ['42', '42', '均衡'],
165
+ ['57', '57', '完整'],
166
+ ],
167
+ },
168
+ };
169
+
170
+ const BH_PRESETS: ReadonlyArray<readonly [string, string]> = [
171
+ ['cinema', '电影'],
172
+ ['lens', '透镜'],
173
+ ['ember', '余烬'],
174
+ ];
175
+
176
+ const BLINK_DIRECTIONS: ReadonlyArray<readonly [string, string]> = [
177
+ ['right', '右'],
178
+ ['left', '左'],
179
+ ['top', '上'],
180
+ ['bottom', '下'],
181
+ ];
182
+
183
+ export interface PanelCallbacks {
184
+ getState: () => AppearanceSettings | null;
185
+ getWallpapers: () => WallpaperItem[];
186
+ setWallpapers: (list: WallpaperItem[]) => void;
187
+ scheduleSave: () => void;
188
+ applyAll: () => void;
189
+ onStatus: (text: string, isError?: boolean) => void;
190
+ }
191
+
192
+ interface UiRefs {
193
+ host: HTMLDivElement;
194
+ shadow: ShadowRoot;
195
+ trigger: HTMLButtonElement;
196
+ market: HTMLDivElement;
197
+ settings: HTMLDivElement;
198
+ cardsWrap: HTMLDivElement;
199
+ emptyNotice: HTMLParagraphElement;
200
+ }
201
+
202
+ let callbacks: PanelCallbacks | null = null;
203
+ let ui: UiRefs | null = null;
204
+ let marketOpen = false;
205
+ let settingsOpen = false;
206
+ let settingsId: string | null = null;
207
+ let activeCategory: 'all' | 'enabled' | 'custom' = 'all';
208
+ let libPage = 0;
209
+ let draft: SceneParamMap | null = null;
210
+ let draftScene: string | null = null;
211
+ let cleanOceanUi: (() => void) | null = null;
212
+ let lastRenderedCardIds = '';
213
+
214
+ export function isSettingsOpen(): boolean {
215
+ return settingsOpen;
216
+ }
217
+
218
+ export function getSettingsId(): string | null {
219
+ return settingsId;
220
+ }
221
+
222
+ export function setPanelStatus(text: string, isError = false): void {
223
+ if (text) console.info('[dsh-ccx]', text);
224
+ if (isError && ui && settingsOpen) {
225
+ const err = ui.settings.querySelector<HTMLElement>('.particle-plugin-error');
226
+ if (err) {
227
+ err.hidden = false;
228
+ err.textContent = text;
229
+ }
230
+ }
231
+ }
232
+
233
+ export function syncPanelTheme(): void {
234
+ if (!ui) return;
235
+ const isDark =
236
+ document.body?.hasAttribute('data-ds-dark-theme') ||
237
+ document.documentElement.classList.contains('dark');
238
+ ui.host.setAttribute('data-theme', isDark ? 'dark' : 'light');
239
+ }
240
+
241
+ export function syncSidebarCollapsed(): void {
242
+ if (!ui) return;
243
+ const sidebarSlot = document.querySelector('[data-slot="sidebar"]');
244
+ const sidebarContainer = sidebarSlot?.parentElement;
245
+ let collapsed = false;
246
+ if (sidebarContainer) {
247
+ const rect = sidebarContainer.getBoundingClientRect();
248
+ collapsed = rect.width < 48 || getComputedStyle(sidebarContainer).display === 'none';
249
+ } else {
250
+ collapsed = true;
251
+ }
252
+ if (collapsed) {
253
+ ui.host.setAttribute('data-sidebar-collapsed', 'true');
254
+ } else {
255
+ ui.host.removeAttribute('data-sidebar-collapsed');
256
+ }
257
+ }
258
+
259
+ function cardEnabled(card: CardDescriptor): boolean {
260
+ const state = callbacks?.getState();
261
+ if (!state) return false;
262
+ if (card.id === 'surface') return Boolean(state.surfaces?.enabled);
263
+ if (!state.enabled) return false;
264
+ if (card.id === 'custom') return state.mode === 'wallpaper';
265
+ return state.mode === 'scene' && state.scene === card.id;
266
+ }
267
+
268
+ function visibleCards(): CardDescriptor[] {
269
+ if (activeCategory === 'all') return CARDS;
270
+ if (activeCategory === 'enabled') return CARDS.filter(cardEnabled);
271
+ return CARDS.filter((c) => c.kind !== 'scene');
272
+ }
273
+
274
+ function renderCardMarkup(card: CardDescriptor, on: boolean): string {
275
+ return (
276
+ `<article class="preview-extension${card.ext ? ` ${card.ext}` : ''}" data-card="${card.id}">` +
277
+ `<span class="preview-extension-icon" aria-hidden="true">${cardIconMarkup(card.id)}</span>` +
278
+ '<div class="preview-extension-copy"><div class="preview-extension-title-row">' +
279
+ `<h4>${escapeHtml(card.title)}</h4>` +
280
+ `<span class="preview-extension-status" data-enabled="${on}">${on ? '已启用' : '未启用'}</span>` +
281
+ '</div></div>' +
282
+ '<div class="preview-extension-actions">' +
283
+ `<button type="button" class="preview-extension-action" data-toggle-card="${card.id}" data-enabled="${on}" aria-pressed="${on}">${on ? '停用' : '启用'}</button>` +
284
+ `<button type="button" class="particle-settings-trigger" data-open-settings="${card.id}" aria-expanded="${settingsOpen && settingsId === card.id}" aria-label="设置 ${escapeHtml(card.title)}" title="设置">${cardIconMarkup('surface').includes('viewBox') ? '<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path d="M2 4h3M9 4h5M2 8h7M13 8h1M2 12h1M7 12h7"/><circle cx="7" cy="4" r="2"/><circle cx="11" cy="8" r="2"/><circle cx="5" cy="12" r="2"/></svg>' : ''}</button>` +
285
+ '</div></article>'
286
+ );
287
+ }
288
+
289
+ export function buildCards(): void {
290
+ if (!ui) return;
291
+ const list = visibleCards();
292
+ const idSig = list.map((c) => c.id).join('|');
293
+ ui.emptyNotice.hidden = list.length > 0;
294
+
295
+ if (idSig === lastRenderedCardIds && ui.cardsWrap.childElementCount === list.length) {
296
+ for (const card of list) {
297
+ const el = ui.cardsWrap.querySelector<HTMLElement>(`[data-card="${card.id}"]`);
298
+ if (!el) continue;
299
+ const on = cardEnabled(card);
300
+ const badge = el.querySelector<HTMLElement>('.preview-extension-status');
301
+ if (badge) {
302
+ badge.setAttribute('data-enabled', String(on));
303
+ badge.textContent = on ? '已启用' : '未启用';
304
+ }
305
+ const toggleBtn = el.querySelector<HTMLButtonElement>('[data-toggle-card]');
306
+ if (toggleBtn) {
307
+ toggleBtn.setAttribute('data-enabled', String(on));
308
+ toggleBtn.setAttribute('aria-pressed', String(on));
309
+ toggleBtn.textContent = on ? '停用' : '启用';
310
+ }
311
+ const setBtn = el.querySelector<HTMLButtonElement>('[data-open-settings]');
312
+ if (setBtn) {
313
+ setBtn.setAttribute('aria-expanded', String(settingsOpen && settingsId === card.id));
314
+ }
315
+ }
316
+ return;
317
+ }
318
+
319
+ const prevScroll = ui.market.querySelector('.preview-market-list')?.scrollTop || 0;
320
+ ui.cardsWrap.innerHTML = list.map((c) => renderCardMarkup(c, cardEnabled(c))).join('');
321
+ lastRenderedCardIds = idSig;
322
+ const scrollContainer = ui.market.querySelector('.preview-market-list');
323
+ if (scrollContainer && prevScroll > 0) {
324
+ scrollContainer.scrollTop = prevScroll;
325
+ }
326
+ }
327
+
328
+ function groupStart(legendText: string, resetGroupKey?: string): string {
329
+ if (resetGroupKey) {
330
+ return (
331
+ '<fieldset class="particle-settings-group">' +
332
+ '<div class="particle-group-head">' +
333
+ `<span class="particle-group-title">${escapeHtml(legendText)}</span>` +
334
+ `<button type="button" class="particle-group-reset" data-group-reset="${escapeHtml(resetGroupKey)}">重置</button>` +
335
+ '</div>'
336
+ );
337
+ }
338
+ return `<fieldset class="particle-settings-group"><legend>${escapeHtml(legendText)}</legend>`;
339
+ }
340
+
341
+ function rangeRow(f: SceneField, val: number): string {
342
+ return (
343
+ `<div class="particle-control-row"><label for="ccx-f-${f.key}">${escapeHtml(f.zh)}</label>` +
344
+ `<input id="ccx-f-${f.key}" type="range" min="${f.min}" max="${f.max}" step="${f.step}" value="${val}" data-field="${f.key}" aria-label="${escapeHtml(f.zh)}">` +
345
+ `<span class="particle-control-value"><output data-fieldval="${f.key}" title="双击直接输入数值">${escapeHtml(fmtFieldVal(f, val))}</output></span></div>`
346
+ );
347
+ }
348
+
349
+ function toggleRow(key: string, zh: string, checked: boolean): string {
350
+ return `<label class="particle-toggle-row">${escapeHtml(zh)}<input type="checkbox" data-toggle="${key}"${checked ? ' checked' : ''}></label>`;
351
+ }
352
+
353
+ function colorRow(key: string, zh: string, val: string): string {
354
+ const clean = /^#[\da-fA-F]{6}$/.test(val || '') ? val : '#ffffff';
355
+ return `<label class="particle-color-row">${escapeHtml(zh)}<input type="color" value="${escapeHtml(clean)}" data-colorkey="${key}"></label>`;
356
+ }
357
+
358
+ const REPLAY_SCENES = new Set([
359
+ 'glow-horizon',
360
+ 'black-hole',
361
+ 'particle-image',
362
+ 'ascii-tiles',
363
+ 'shallow-ocean',
364
+ 'spectral-drape',
365
+ ]);
366
+
367
+ function sceneActionsHtml(sceneId: string): string {
368
+ const hasReplay = REPLAY_SCENES.has(sceneId);
369
+ const canReplay = Boolean(getBgInstance() && getBgSceneId() === sceneId) && hasReplay;
370
+ if (!hasReplay) {
371
+ return '<div class="glow-horizon-actions single"><button type="button" data-act="draftreset">重置全部</button></div>';
372
+ }
373
+ return (
374
+ '<div class="glow-horizon-actions">' +
375
+ `<button type="button" data-act="replay"${canReplay ? '' : ' disabled'}>重播开场</button>` +
376
+ '<button type="button" data-act="draftreset">重置全部</button></div>'
377
+ );
378
+ }
379
+
380
+ interface FieldSection {
381
+ group: string;
382
+ legend: string;
383
+ fields: SceneField[];
384
+ resetGroupKey?: string;
385
+ }
386
+
387
+ function sectionsFor(sceneId: string): FieldSection[] {
388
+ const sch = schemaOf(sceneId);
389
+ if (!sch) return [];
390
+ if (Array.isArray(sch.groups) && sch.groups.length > 0) {
391
+ const fMap = new Map((sch.fields || []).map((f) => [f.key, f]));
392
+ return sch.groups.map((g) => ({
393
+ group: g.key,
394
+ legend: g.zh,
395
+ fields: g.keys.map((k) => fMap.get(k)).filter((x): x is SceneField => Boolean(x)),
396
+ resetGroupKey: g.key,
397
+ }));
398
+ }
399
+
400
+ const groups: FieldSection[] = [];
401
+ const byKey: Record<string, FieldSection> = {};
402
+ const ov = FIELD_GROUP_OVERRIDES[sceneId] || {};
403
+ for (const f of sch.fields || []) {
404
+ const gk = f.group || '_';
405
+ if (!byKey[gk]) {
406
+ const legend = ov[gk] || GROUP_LEGENDS[gk] || TUPLE_MAIN_LEGENDS[sceneId] || '参数';
407
+ byKey[gk] = { group: gk, legend, fields: [] };
408
+ groups.push(byKey[gk]);
409
+ }
410
+ byKey[gk].fields.push(f);
411
+ }
412
+ return groups;
413
+ }
414
+
415
+ function galleryHtml(sceneId: string): string {
416
+ const win = window as unknown as Record<symbol, Map<string, { images?: Map<string, { id: string; name?: string; type?: string; thumbnail?: string }> }> | undefined>;
417
+ const gReg = win[Symbol.for('code-codex:default-galleries:v1')];
418
+ const meta = gReg?.get(sceneId);
419
+ const count = meta?.images?.size ?? 0;
420
+ let items = '';
421
+ if (meta?.images) {
422
+ meta.images.forEach((img) => {
423
+ const thumb = img.thumbnail
424
+ ? `<img loading="lazy" src="data:${img.type || 'image/png'};base64,${img.thumbnail}" alt="">`
425
+ : '<span class="vthumb">🖼</span>';
426
+ items += `<span class="wallitem"><span class="wpick">${thumb}<span class="wname">${escapeHtml(img.name || img.id)}</span></span></span>`;
427
+ });
428
+ }
429
+ return (
430
+ '<details class="particle-source-details" open><summary class="particle-source-summary">图片库' +
431
+ `<span class="particle-source-count">${count} 个已保存</span></summary>` +
432
+ `<div class="particle-library-grid">${items || '<p class="particle-library-empty">图库尚未就绪,启用场景后自动载入默认图。</p>'}</div>` +
433
+ '</details>'
434
+ );
435
+ }
436
+
437
+ function sceneSettingsHtml(sceneId: string): string {
438
+ const sch = schemaOf(sceneId);
439
+ const d = draft || {};
440
+ const state = callbacks?.getState() || null;
441
+
442
+ if (sceneId === 'shallow-ocean') {
443
+ if (!sch) return '<div class="particle-settings-scroll"><p class="panel-note">场景 schema 尚未加载…</p></div>';
444
+ const active = Boolean(state && state.enabled && state.mode === 'scene' && state.scene === 'shallow-ocean');
445
+ return renderShallowOceanBodyHtml(sch, d, active);
446
+ }
447
+
448
+ let html = '<div class="particle-settings-scroll">';
449
+ const inlineToggles: Record<string, boolean> = {};
450
+
451
+ if (sceneId === 'pixel-sculpt') {
452
+ const active = isPsActive(state);
453
+ const paused = isPsPaused(state);
454
+ const ps = getPsEditor();
455
+ html += `<p class="pixelSculpt-disabled" data-psnote${active ? ' hidden' : ''}>插件尚未启用;这里的设置会在下次启用时生效。</p>`;
456
+ html += '<div class="pixelSculpt-controls-host" data-pshost></div>';
457
+ html += `<label class="particle-toggle-row pixelSculpt-paused-row">暂停动画<input type="checkbox" data-toggle="__pspaused"${paused ? ' checked' : ''}${active ? '' : ' disabled'}></label>`;
458
+ html += `<div class="glow-horizon-actions single pixelSculpt-actions"><button type="button" data-act="psreset"${ps?.inst ? '' : ' disabled'}>重置参数</button></div>`;
459
+ html += '<p class="particle-plugin-error" role="status" hidden></p></div>';
460
+ return html;
461
+ }
462
+
463
+ if (!sch) {
464
+ return '<div class="particle-settings-scroll"><p class="panel-note">场景 schema 尚未加载…</p></div>';
465
+ }
466
+
467
+ if (sceneId === 'blinking-squares') {
468
+ html += groupStart('渐隐方向');
469
+ html += '<div class="heavenly-cloud-quality-toolbar dir4" role="group" aria-label="渐隐方向">';
470
+ for (const [val, zh] of BLINK_DIRECTIONS) {
471
+ html += `<button type="button" data-blinkdir="${val}" aria-pressed="${(d.direction || 'right') === val}">${zh}</button>`;
472
+ }
473
+ html += '</div></fieldset>';
474
+ const bl = sch.fields;
475
+ html += groupStart('方块与闪烁');
476
+ for (let i = 0; i < Math.min(10, bl.length); i++) html += rangeRow(bl[i], finiteNum(d[bl[i].key], bl[i].min));
477
+ html += '</fieldset>';
478
+ html += groupStart('交互与脉冲');
479
+ for (let i = 10; i < Math.min(20, bl.length); i++) html += rangeRow(bl[i], finiteNum(d[bl[i].key], bl[i].min));
480
+ html += toggleRow('mouseInteraction', '鼠标交互', Boolean(d.mouseInteraction));
481
+ html += toggleRow('keyboardInteraction', '键盘随机波纹', Boolean(d.keyboardInteraction));
482
+ for (let i = 20; i < Math.min(22, bl.length); i++) html += rangeRow(bl[i], finiteNum(d[bl[i].key], bl[i].min));
483
+ html += '</fieldset>';
484
+ html += groupStart('开场与画质');
485
+ for (let i = 22; i < bl.length; i++) html += rangeRow(bl[i], finiteNum(d[bl[i].key], bl[i].min));
486
+ html += toggleRow('introEnabled', '启用开场', Boolean(d.introEnabled));
487
+ html += toggleRow('paused', '暂停动画', Boolean(d.paused));
488
+ html += '</fieldset>';
489
+ html += groupStart('颜色');
490
+ for (const cf of sch.colorFields || []) {
491
+ html += colorRow(cf.key, cf.zh, String(d[cf.key] || sch.defaults[cf.key] || '#ffffff'));
492
+ }
493
+ html += '</fieldset>';
494
+ html += sceneActionsHtml(sceneId);
495
+ html += '<p class="particle-plugin-error" role="status" hidden></p></div>';
496
+ return html;
497
+ }
498
+
499
+ if (sceneId === 'black-hole') {
500
+ html += '<div class="black-hole-preset-toolbar" role="group" aria-label="黑洞场景预设">';
501
+ for (const [id, zh] of BH_PRESETS) {
502
+ html += `<button type="button" data-bhpreset="${id}">${zh}</button>`;
503
+ }
504
+ html += '<button type="button" class="black-hole-reset" data-act="draftreset">重置</button></div>';
505
+ }
506
+
507
+ if (sceneId === 'glow-horizon') {
508
+ html += '<div class="glow-horizon-direction-toolbar" role="group" aria-label="地平线方向">';
509
+ const dirs: Array<[string, string, string]> = [
510
+ ['top', '↑', '上'],
511
+ ['bottom', '↓', '下'],
512
+ ['left', '←', '左'],
513
+ ['right', '→', '右'],
514
+ ];
515
+ for (const [id, sym, zh] of dirs) {
516
+ html += `<button type="button" data-direction="${id}" aria-pressed="${d.variant === id}"><span class="glow-horizon-direction-symbol">${sym}</span>${zh}</button>`;
517
+ }
518
+ html += '</div>';
519
+ }
520
+
521
+ const qt = QUALITY_TOOLBARS[sceneId];
522
+ const qualityGroupHtml = () => {
523
+ if (!qt) return '';
524
+ let out = groupStart('渲染质量');
525
+ out += '<div class="heavenly-cloud-quality-toolbar" role="group" aria-label="渲染质量">';
526
+ for (const [val, badge, zh] of qt.items) {
527
+ const cur =
528
+ qt.mode === 'steps'
529
+ ? String(finiteNum(d.steps, 57))
530
+ : String(d.quality || sch.qualityDefault || 'high');
531
+ out += `<button type="button" data-${qt.mode}="${val}" aria-pressed="${cur === val}"><strong>${badge}</strong>${zh}</button>`;
532
+ }
533
+ out += '</div>';
534
+ if (qt.mode === 'steps') {
535
+ const resField = sch.fields.find((f) => f.key === 'resolution');
536
+ if (resField) out += rangeRow(resField, finiteNum(d.resolution, resField.min));
537
+ }
538
+ return `${out}</fieldset>`;
539
+ };
540
+
541
+ if (qt && sceneId !== 'mountain') html += qualityGroupHtml();
542
+
543
+ const sections = sectionsFor(sceneId);
544
+ if (sceneId === 'mountain' && sections.length) {
545
+ sections[0].fields = sections[0].fields.filter((f) => f.key !== 'resolution');
546
+ }
547
+
548
+ const groupSchemasByKey = new Map((sch.groups || []).map((g) => [g.key, g]));
549
+ const toggleByKey = new Map((sch.toggles || []).map((t) => [t.key, t]));
550
+ const colorFieldByKey = new Map((sch.colorFields || []).map((c) => [c.key, c]));
551
+
552
+ for (const sec of sections) {
553
+ html += groupStart(sec.legend, sec.resetGroupKey);
554
+ for (const f of sec.fields) {
555
+ html += rangeRow(f, finiteNum(d[f.key], f.min));
556
+ }
557
+
558
+ // Schemas with explicit groups (`ascii-tiles`, `spectral-drape`) place color/toggle controls inside matching groups
559
+ const gDef = groupSchemasByKey.get(sec.group);
560
+ if (gDef) {
561
+ for (const key of gDef.keys) {
562
+ const cf = colorFieldByKey.get(key);
563
+ if (cf) {
564
+ html += colorRow(cf.key, cf.zh, String(d[cf.key] || sch.defaults[cf.key] || '#ffffff'));
565
+ }
566
+ const tg = toggleByKey.get(key);
567
+ if (tg) {
568
+ inlineToggles[tg.key] = true;
569
+ html += toggleRow(tg.key, tg.zh, Boolean(d[tg.key]));
570
+ }
571
+ }
572
+ }
573
+
574
+ if (sceneId === 'black-hole' && sec.group === 'light') {
575
+ for (const cf of sch.colorFields || []) {
576
+ html += colorRow(cf.key, cf.zh, String(d[cf.key] || sch.defaults[cf.key] || '#ffffff'));
577
+ }
578
+ }
579
+ if (sceneId === 'black-hole' && sec.group === 'renderer') {
580
+ html += toggleRow('paused', '暂停动画', Boolean(d.paused));
581
+ inlineToggles.paused = true;
582
+ }
583
+ if (sceneId === 'glow-horizon' && sec.group === 'input') {
584
+ html += toggleRow('inertialWheel', '滚轮惯性', Boolean(d.inertialWheel));
585
+ inlineToggles.inertialWheel = true;
586
+ }
587
+ if (sceneId === 'particle-image' && sec.group === 'source') {
588
+ html += galleryHtml(sceneId);
589
+ html += colorRow('backgroundColor', '背景', String(d.backgroundColor || '#000000'));
590
+ html += toggleRow('autoSwitch', '自动切换', d.autoSwitch !== false);
591
+ inlineToggles.autoSwitch = true;
592
+ }
593
+ if (sceneId === 'particle-image' && sec.group === 'opening') {
594
+ html += toggleRow('introEnabled', '粒子汇聚', Boolean(d.introEnabled));
595
+ inlineToggles.introEnabled = true;
596
+ const replayDisabled = !(getBgInstance() && getBgSceneId() === sceneId);
597
+ html += `<button type="button" class="particle-library-add" data-act="replay" style="margin:2px 4px 0;justify-self:start"${replayDisabled ? ' disabled' : ''}>重播开场</button>`;
598
+ }
599
+ if (sceneId === 'particle-image' && sec.group === 'pointer') {
600
+ html += toggleRow('cursorInteraction', '鼠标交互', Boolean(d.cursorInteraction));
601
+ inlineToggles.cursorInteraction = true;
602
+ }
603
+ if (sceneId === 'cloud-train') {
604
+ for (const cf of sch.colorFields || []) {
605
+ html += colorRow(cf.key, TINT_LABELS[cf.key] || cf.zh, String(d[cf.key] || '#ffffff'));
606
+ }
607
+ }
608
+ html += '</fieldset>';
609
+ }
610
+
611
+ if (qt && sceneId === 'mountain') html += qualityGroupHtml();
612
+
613
+ const sortedToggles = [...(sch.toggles || [])].sort(
614
+ (a, b) => (a.key === 'paused' ? -1 : 0) - (b.key === 'paused' ? -1 : 0),
615
+ );
616
+ for (const tg of sortedToggles) {
617
+ if (inlineToggles[tg.key]) continue;
618
+ if (sceneId === 'particle-image' && tg.key === 'showSourceImage') {
619
+ html += toggleRow('showSourceImage', '显示源图', d.showSourceImage !== false);
620
+ continue;
621
+ }
622
+ html += toggleRow(tg.key, tg.zh, Boolean(d[tg.key]));
623
+ }
624
+
625
+ if (sch.colors) {
626
+ html += groupStart(COLOR_SECTION_LEGENDS[sceneId] || '颜色');
627
+ const cols = Array.isArray(d.colors) && d.colors.length === sch.colors.length ? d.colors : sch.colors;
628
+ for (let i = 0; i < sch.colors.length; i++) {
629
+ html += colorRow(`color${i}`, `颜色 ${i + 1}`, String(cols[i] || sch.colors[i]));
630
+ }
631
+ html += '</fieldset>';
632
+ }
633
+
634
+ html += sceneActionsHtml(sceneId);
635
+ html += '<p class="particle-plugin-error" role="status" hidden></p></div>';
636
+ return html;
637
+ }
638
+
639
+ function customSettingsHtml(): string {
640
+ const state = callbacks?.getState();
641
+ const wallpapers = callbacks?.getWallpapers() || [];
642
+ const pages = Math.max(1, Math.ceil(wallpapers.length / LIB_PAGE_SIZE));
643
+ if (libPage >= pages) libPage = pages - 1;
644
+ const slice = wallpapers.slice(libPage * LIB_PAGE_SIZE, (libPage + 1) * LIB_PAGE_SIZE);
645
+
646
+ const items = slice
647
+ .map((w) => {
648
+ const isVideo = /^video\//.test(w.mime || '');
649
+ const thumb = isVideo
650
+ ? '<span class="vthumb">▶</span>'
651
+ : `<img loading="lazy" src="${escapeHtml(w.url)}" alt="">`;
652
+ const selected = state && w.id === state.wallpaperId ? ' on' : '';
653
+ return (
654
+ `<span class="wallitem${selected}">` +
655
+ `<button type="button" class="wpick" data-wall="${escapeHtml(w.id)}" title="${escapeHtml(w.name)}">${thumb}<span class="wname">${escapeHtml(w.name)}</span></button>` +
656
+ `<button type="button" class="wdel" data-wdel="${escapeHtml(w.id)}" title="删除" aria-label="删除 ${escapeHtml(w.name)}">✕</button></span>`
657
+ );
658
+ })
659
+ .join('');
660
+
661
+ const pagerHtml =
662
+ pages > 1
663
+ ? '<div class="wall-pager">' +
664
+ `<button type="button" data-wallpage="prev"${libPage <= 0 ? ' disabled' : ''}>‹</button>` +
665
+ `<output>${libPage + 1} / ${pages}</output>` +
666
+ `<button type="button" data-wallpage="next"${libPage >= pages - 1 ? ' disabled' : ''}>›</button>` +
667
+ '</div>'
668
+ : '';
669
+
670
+ const posOptions = [
671
+ ['center', '居中'],
672
+ ['top', '顶部'],
673
+ ['bottom', '底部'],
674
+ ['left', '左侧'],
675
+ ['right', '右侧'],
676
+ ];
677
+
678
+ return (
679
+ '<div class="particle-settings-scroll">' +
680
+ '<details class="particle-source-details" open><summary class="particle-source-summary">图片库' +
681
+ `<span class="particle-source-count">${wallpapers.length} 个已保存</span></summary>` +
682
+ '<div class="particle-library-toolbar"><span class="particle-library-add" data-act="wallimport">添加图片' +
683
+ '<input type="file" data-act="wallfile" accept="image/*,video/mp4,video/webm" hidden></span>' +
684
+ `<button type="button" class="particle-library-clear" data-act="wallclear"${wallpapers.length ? '' : ' disabled'}>清空</button></div>` +
685
+ `<div class="particle-library-grid">${items || '<p class="particle-library-empty">还没有壁纸,点「添加图片」导入图片或视频。</p>'}</div>` +
686
+ pagerHtml +
687
+ '</details>' +
688
+ groupStart('素材属性') +
689
+ '<div class="particle-control-row"><label for="ccx-fit">画面适配</label>' +
690
+ '<select id="ccx-fit" data-act="fit">' +
691
+ `<option value="cover"${state?.wallpaperFit === 'cover' ? ' selected' : ''}>铺满</option>` +
692
+ `<option value="contain"${state?.wallpaperFit === 'contain' ? ' selected' : ''}>完整显示</option>` +
693
+ `<option value="tile"${state?.wallpaperFit === 'tile' ? ' selected' : ''}>平铺</option></select>` +
694
+ '<span class="particle-control-value"></span></div>' +
695
+ '<div class="particle-control-row"><label for="ccx-pos">位置</label>' +
696
+ '<select id="ccx-pos" data-act="pos">' +
697
+ posOptions
698
+ .map(
699
+ ([v, label]) =>
700
+ `<option value="${v}"${state?.wallpaperPosition === v ? ' selected' : ''}>${label}</option>`,
701
+ )
702
+ .join('') +
703
+ '</select><span class="particle-control-value"></span></div>' +
704
+ '</fieldset>' +
705
+ '<div class="glow-horizon-actions single"><button type="button" data-act="customreset">重置参数</button></div>' +
706
+ '<p class="particle-plugin-error" role="status" hidden></p></div>'
707
+ );
708
+ }
709
+
710
+ function surfaceSettingsHtml(): string {
711
+ const state = callbacks?.getState();
712
+ let html = '<div class="particle-settings-scroll">';
713
+ html += '<p class="panel-note">只调节底色,文字和图标保持清晰。0% 完全透明,100% 完全遮挡背景。</p>';
714
+ html += groupStart('分区不透明度');
715
+ for (const r of REGION_ROWS) {
716
+ const v = clamp(finiteNum(state?.surfaces?.[r.key], DEFAULT_SETTINGS.surfaces[r.key]), 0, 100);
717
+ html +=
718
+ `<div class="particle-control-row surface-opacity-row"><label for="ccx-r-${r.key}">${escapeHtml(r.zh)}</label>` +
719
+ `<input id="ccx-r-${r.key}" type="range" min="0" max="100" step="1" value="${v}" data-region="${r.key}" aria-label="${escapeHtml(r.zh)}">` +
720
+ `<span class="particle-control-value"><output data-regionval="${r.key}" title="双击直接输入数值">${Math.round(v)}%</output></span>` +
721
+ `<button type="button" data-rowreset="${r.key}" title="恢复此项默认值" aria-label="恢复${escapeHtml(r.zh)}默认值">↺</button></div>`;
722
+ }
723
+ html += '</fieldset>';
724
+ html += groupStart('背景调节');
725
+ for (const row of PARAM_ROWS) {
726
+ const vv = finiteNum(state?.[row.key], DEFAULT_SETTINGS[row.key]) * row.scale;
727
+ const formatted = row.scale === 100 ? `${Math.round(vv)}%` : `${vv.toFixed(1)}px`;
728
+ html +=
729
+ `<div class="particle-control-row"><label for="ccx-p-${row.key}">${row.zh}</label>` +
730
+ `<input id="ccx-p-${row.key}" type="range" min="${row.min}" max="${row.max}" step="${row.step}" value="${vv}" data-slider="${row.key}" aria-label="${row.zh}">` +
731
+ `<span class="particle-control-value"><output data-sliderval="${row.key}" title="双击直接输入数值">${formatted}</output></span></div>`;
732
+ }
733
+ html += '</fieldset>';
734
+ html += '<button type="button" class="particle-library-clear" data-act="surfacereset" style="justify-self:stretch;margin:0">恢复全部默认值</button>';
735
+ html += '<p class="particle-plugin-error" role="status" hidden></p></div>';
736
+ return html;
737
+ }
738
+
739
+ function mountPsControls(): void {
740
+ const state = callbacks?.getState() || null;
741
+ if (!ui || !settingsOpen || settingsId !== 'pixel-sculpt') return;
742
+ ensurePsEditor(() => callbacks?.getState() || null, setPanelStatus)
743
+ .then((ed) => {
744
+ if (!ui || !settingsOpen || settingsId !== 'pixel-sculpt') return;
745
+ const host = ui.settings.querySelector<HTMLElement>('[data-pshost]');
746
+ if (host && ed.inst) {
747
+ try {
748
+ ed.inst.mountControls(host, 'zh');
749
+ } catch {
750
+ // Ignore
751
+ }
752
+ }
753
+ syncPsPanel(state);
754
+ })
755
+ .catch((err) => {
756
+ setPanelStatus(`Pixel Sculpt 设置加载失败:${String((err as Error)?.message || err).slice(0, 50)}`, true);
757
+ });
758
+ }
759
+
760
+ export function syncPsPanel(state: AppearanceSettings | null): void {
761
+ if (!ui || !settingsOpen || settingsId !== 'pixel-sculpt') return;
762
+ const active = isPsActive(state);
763
+ const note = ui.settings.querySelector<HTMLElement>('[data-psnote]');
764
+ if (note) note.hidden = active;
765
+ const pausedEl = ui.settings.querySelector<HTMLInputElement>('[data-toggle="__pspaused"]');
766
+ if (pausedEl) {
767
+ pausedEl.checked = isPsPaused(state);
768
+ pausedEl.disabled = !active;
769
+ }
770
+ const rst = ui.settings.querySelector<HTMLButtonElement>('[data-act="psreset"]');
771
+ if (rst) rst.disabled = !getPsEditor()?.inst;
772
+ }
773
+
774
+ function commitLive(sceneId: string): void {
775
+ const state = callbacks?.getState();
776
+ if (!state || !draft || draftScene !== sceneId) return;
777
+ const sch = schemaOf(sceneId);
778
+ const dd = draftDeltaObj(sch, draft);
779
+ if (Object.keys(dd.delta).length > 0) {
780
+ state.sceneParams[sceneId] = dd.delta;
781
+ } else {
782
+ delete state.sceneParams[sceneId];
783
+ }
784
+ writeSceneSetting(sceneId, dd.full);
785
+ callbacks?.scheduleSave();
786
+
787
+ const layer = getLayer()?.layer;
788
+ if (
789
+ layer &&
790
+ (sceneId === 'particle-image' ||
791
+ sceneId === 'blinking-squares' ||
792
+ sceneId === 'ascii-tiles' ||
793
+ sceneId === 'spectral-drape')
794
+ ) {
795
+ layer.style.setProperty('--ap-layer-bg', resolveSceneLayerBg(sceneId, state));
796
+ }
797
+
798
+ let pushed = false;
799
+ const inst = getBgInstance();
800
+ if (state.enabled && state.mode === 'scene' && state.scene === sceneId && inst && getBgSceneId() === sceneId) {
801
+ pushed = pushLiveSettings(inst, dd.full);
802
+ }
803
+ if (!pushed && state.enabled && state.mode === 'scene' && state.scene === sceneId && callbacks) {
804
+ renderScene({
805
+ getState: callbacks.getState,
806
+ onStatus: setPanelStatus,
807
+ });
808
+ }
809
+ }
810
+
811
+ export function renderSettings(id: string): void {
812
+ if (!ui || !callbacks) return;
813
+ const state = callbacks.getState();
814
+ const isScene = SCENE_IDS.includes(id);
815
+
816
+ if (id === 'shallow-ocean') {
817
+ ui.settings.classList.add('shallow-ocean-panel');
818
+ } else {
819
+ ui.settings.classList.remove('shallow-ocean-panel');
820
+ }
821
+
822
+ if (isScene) {
823
+ if (!draftScene || draftScene !== id) {
824
+ draft = mergeSceneDraft(schemaOf(id), state?.sceneParams?.[id]);
825
+ draftScene = id;
826
+ }
827
+ }
828
+
829
+ const bodyHtml = !isScene
830
+ ? id === 'custom'
831
+ ? customSettingsHtml()
832
+ : surfaceSettingsHtml()
833
+ : sceneSettingsHtml(id);
834
+
835
+ const headerHtml =
836
+ id === 'shallow-ocean'
837
+ ? renderShallowOceanHeaderHtml(
838
+ finiteNum(draft?.performanceMode, 0),
839
+ getShallowOceanController().developerMode,
840
+ CLOSE_SVG,
841
+ )
842
+ : '<header class="particle-settings-header"><div class="particle-settings-heading">' +
843
+ `<p>外观</p><h3>${escapeHtml(CARD_TITLES[id] || (id === 'custom' ? 'Custom Background' : 'UI Surface Opacity'))}</h3></div>` +
844
+ `<div class="particle-settings-header-actions"><button class="particle-settings-close" type="button" data-act="settingsclose" title="关闭设置 (Esc)" aria-label="关闭设置">${CLOSE_SVG}</button></div></header>`;
845
+
846
+ ui.settings.innerHTML = headerHtml + bodyHtml;
847
+
848
+ if (id === 'pixel-sculpt') {
849
+ mountPsControls();
850
+ }
851
+ }
852
+
853
+ export function positionSettingsPanel(): void {
854
+ if (!ui || !settingsOpen) return;
855
+ const marketRect = ui.market.getBoundingClientRect();
856
+ const panel = ui.settings;
857
+ const edge = 12;
858
+ const w = panel.getBoundingClientRect().width || (settingsId === 'shallow-ocean' ? 680 : 352);
859
+ let left = marketRect.right + 10;
860
+ if (left + w + edge > window.innerWidth) {
861
+ left = Math.max(edge, window.innerWidth - w - edge);
862
+ }
863
+ const triggerBtn = settingsId
864
+ ? ui.market.querySelector<HTMLElement>(`[data-open-settings="${settingsId}"]`)
865
+ : null;
866
+ const anchorY = triggerBtn
867
+ ? triggerBtn.getBoundingClientRect().top + triggerBtn.getBoundingClientRect().height / 2
868
+ : marketRect.top + 36;
869
+ const h = panel.getBoundingClientRect().height || 380;
870
+ const top = clamp(anchorY - 28, edge, Math.max(edge, window.innerHeight - h - edge));
871
+
872
+ panel.style.left = `${Math.round(left)}px`;
873
+ panel.style.top = `${Math.round(top)}px`;
874
+ panel.style.setProperty('--cle-anchor-y', `${Math.round(clamp(anchorY - top, 20, Math.max(20, h - 20)))}px`);
875
+ panel.setAttribute('data-side', 'right');
876
+ }
877
+
878
+ function closeSettings(): void {
879
+ if (!ui) return;
880
+ settingsOpen = false;
881
+ settingsId = null;
882
+ draft = null;
883
+ draftScene = null;
884
+ ui.settings.hidden = true;
885
+ buildCards();
886
+ }
887
+
888
+ function openSettings(id: string): void {
889
+ if (!ui) return;
890
+ if (settingsOpen && settingsId === id) {
891
+ closeSettings();
892
+ return;
893
+ }
894
+ settingsOpen = true;
895
+ settingsId = id;
896
+ draftScene = null;
897
+ draft = null;
898
+ renderSettings(id);
899
+ ui.settings.hidden = false;
900
+ positionSettingsPanel();
901
+ buildCards();
902
+ }
903
+
904
+ function closeMarket(): void {
905
+ if (!ui) return;
906
+ marketOpen = false;
907
+ ui.market.hidden = true;
908
+ ui.trigger.setAttribute('aria-expanded', 'false');
909
+ closeSettings();
910
+ }
911
+
912
+ function toggleMarket(): void {
913
+ if (!ui) return;
914
+ marketOpen = !marketOpen;
915
+ ui.market.hidden = !marketOpen;
916
+ ui.trigger.setAttribute('aria-expanded', String(marketOpen));
917
+ if (marketOpen) {
918
+ syncPanelTheme();
919
+ syncSidebarCollapsed();
920
+ buildCards();
921
+ } else {
922
+ closeSettings();
923
+ }
924
+ }
925
+
926
+ function openInlineValueEditor(outputEl: HTMLElement): void {
927
+ const row = outputEl.closest('.particle-control-row');
928
+ const rangeInput = row?.querySelector<HTMLInputElement>('input[type="range"]');
929
+ if (!rangeInput) return;
930
+
931
+ const isPercentText = outputEl.textContent?.includes('%') ?? false;
932
+ const fieldKey = outputEl.dataset.fieldval;
933
+ const field = fieldKey && draftScene ? schemaOf(draftScene)?.fields.find((f) => f.key === fieldKey) : null;
934
+ const isPercentField = Boolean(field?.percent) || isPercentText;
935
+
936
+ const minVal = isPercentField && Number(rangeInput.max) <= 1 ? Number(rangeInput.min) * 100 : Number(rangeInput.min);
937
+ const maxVal = isPercentField && Number(rangeInput.max) <= 1 ? Number(rangeInput.max) * 100 : Number(rangeInput.max);
938
+ const curVal =
939
+ isPercentField && Number(rangeInput.max) <= 1
940
+ ? Math.round(Number(rangeInput.value) * 100)
941
+ : Number(rangeInput.value);
942
+
943
+ const editor = document.createElement('input');
944
+ editor.type = 'number';
945
+ editor.className = 'particle-value-editor';
946
+ editor.min = String(minVal);
947
+ editor.max = String(maxVal);
948
+ editor.step = isPercentField && Number(rangeInput.max) <= 1 ? '1' : rangeInput.step || 'any';
949
+ editor.value = String(curVal);
950
+
951
+ outputEl.hidden = true;
952
+ outputEl.parentElement?.appendChild(editor);
953
+ editor.focus();
954
+ editor.select();
955
+
956
+ let committed = false;
957
+ const finish = (apply: boolean) => {
958
+ if (committed) return;
959
+ committed = true;
960
+ if (apply) {
961
+ const parsed = Number(editor.value);
962
+ if (Number.isFinite(parsed)) {
963
+ const rawRangeVal =
964
+ isPercentField && Number(rangeInput.max) <= 1 ? parsed / 100 : parsed;
965
+ const clamped = clamp(rawRangeVal, Number(rangeInput.min), Number(rangeInput.max));
966
+ rangeInput.value = String(clamped);
967
+ rangeInput.dispatchEvent(new Event('input', { bubbles: true }));
968
+ }
969
+ }
970
+ editor.remove();
971
+ outputEl.hidden = false;
972
+ };
973
+
974
+ editor.addEventListener('keydown', (ev) => {
975
+ if (ev.key === 'Enter') {
976
+ ev.preventDefault();
977
+ finish(true);
978
+ } else if (ev.key === 'Escape') {
979
+ ev.preventDefault();
980
+ finish(false);
981
+ }
982
+ });
983
+ editor.addEventListener('blur', () => finish(true));
984
+ }
985
+
986
+ function toggleCardActivation(cardId: string): void {
987
+ const state = callbacks?.getState();
988
+ if (!state || !callbacks) return;
989
+
990
+ if (cardId === 'surface') {
991
+ state.surfaces.enabled = !state.surfaces.enabled;
992
+ } else if (cardId === 'custom') {
993
+ const isCurrentlyWallpaper = state.enabled && state.mode === 'wallpaper';
994
+ if (isCurrentlyWallpaper) {
995
+ state.enabled = false;
996
+ } else {
997
+ state.enabled = true;
998
+ state.mode = 'wallpaper';
999
+ }
1000
+ } else {
1001
+ const isCurrentScene = state.enabled && state.mode === 'scene' && state.scene === cardId;
1002
+ if (isCurrentScene) {
1003
+ state.enabled = false;
1004
+ } else {
1005
+ state.enabled = true;
1006
+ state.mode = 'scene';
1007
+ state.scene = cardId;
1008
+ }
1009
+ }
1010
+
1011
+ callbacks.scheduleSave();
1012
+ callbacks.applyAll();
1013
+ if (settingsOpen && settingsId === 'shallow-ocean') {
1014
+ renderSettings('shallow-ocean');
1015
+ }
1016
+ }
1017
+
1018
+ function onDocClick(e: MouseEvent): void {
1019
+ if (!ui || (!marketOpen && !settingsOpen)) return;
1020
+ const path = e.composedPath ? e.composedPath() : [];
1021
+ if (path.includes(ui.host)) return;
1022
+ closeMarket();
1023
+ }
1024
+
1025
+ function onDocKey(e: KeyboardEvent): void {
1026
+ if (e.key !== 'Escape') return;
1027
+ if (settingsOpen) {
1028
+ closeSettings();
1029
+ return;
1030
+ }
1031
+ if (marketOpen) closeMarket();
1032
+ }
1033
+
1034
+ function bindEvents(): void {
1035
+ if (!ui) return;
1036
+ const { trigger, market, settings, shadow } = ui;
1037
+
1038
+ trigger.addEventListener('click', (e) => {
1039
+ e.stopPropagation();
1040
+ toggleMarket();
1041
+ });
1042
+
1043
+ market.addEventListener('click', (e) => {
1044
+ const t = e.target as Element;
1045
+ if (t.closest('[data-act="marketclose"]')) {
1046
+ closeMarket();
1047
+ return;
1048
+ }
1049
+ const catBtn = t.closest<HTMLButtonElement>('[data-cat]');
1050
+ if (catBtn && catBtn.dataset.cat) {
1051
+ activeCategory = catBtn.dataset.cat as 'all' | 'enabled' | 'custom';
1052
+ const tabs = market.querySelectorAll<HTMLButtonElement>('[data-cat]');
1053
+ for (let i = 0; i < tabs.length; i++) {
1054
+ tabs[i].setAttribute('aria-selected', String(tabs[i] === catBtn));
1055
+ }
1056
+ buildCards();
1057
+ return;
1058
+ }
1059
+ const tog = t.closest<HTMLButtonElement>('[data-toggle-card]');
1060
+ if (tog?.dataset.toggleCard) {
1061
+ toggleCardActivation(tog.dataset.toggleCard);
1062
+ return;
1063
+ }
1064
+ const openBtn = t.closest<HTMLButtonElement>('[data-open-settings]');
1065
+ if (openBtn?.dataset.openSettings) {
1066
+ openSettings(openBtn.dataset.openSettings);
1067
+ }
1068
+ });
1069
+
1070
+ settings.addEventListener('dblclick', (e) => {
1071
+ const out = (e.target as Element).closest<HTMLElement>('output');
1072
+ if (out && out.closest('.particle-control-value')) {
1073
+ openInlineValueEditor(out);
1074
+ }
1075
+ });
1076
+
1077
+ settings.addEventListener('click', (e) => {
1078
+ const t = e.target as Element;
1079
+ const state = callbacks?.getState();
1080
+ if (!state || !callbacks) return;
1081
+
1082
+ if (t.closest('[data-act="settingsclose"]')) {
1083
+ closeSettings();
1084
+ return;
1085
+ }
1086
+
1087
+ if (t.closest('[data-act="psreset"]')) {
1088
+ const ps = getPsEditor();
1089
+ if (ps?.inst) {
1090
+ try {
1091
+ ps.inst.reset();
1092
+ } catch {
1093
+ // Ignore
1094
+ }
1095
+ delete state.sceneParams['pixel-sculpt'];
1096
+ writeSceneSetting('pixel-sculpt', { paused: false });
1097
+ callbacks.scheduleSave();
1098
+ syncPsPanel(state);
1099
+ setPanelStatus('Pixel Sculpt 参数已重置');
1100
+ }
1101
+ return;
1102
+ }
1103
+
1104
+ const groupResetBtn = t.closest<HTMLButtonElement>('[data-group-reset]');
1105
+ if (groupResetBtn && draftScene && draft) {
1106
+ const gk = groupResetBtn.dataset.groupReset;
1107
+ const sch = schemaOf(draftScene);
1108
+ const g = sch?.groups?.find((x) => x.key === gk);
1109
+ if (sch && g) {
1110
+ for (const key of g.keys) {
1111
+ if (key in sch.defaults) draft[key] = sch.defaults[key];
1112
+ }
1113
+ draft = sanitizeDraft(sch, draft);
1114
+ renderSettings(draftScene);
1115
+ commitLive(draftScene);
1116
+ }
1117
+ return;
1118
+ }
1119
+
1120
+ if (t.closest('[data-act="draftreset"]')) {
1121
+ if (!draftScene) return;
1122
+ const sch = schemaOf(draftScene);
1123
+ draft = sch?.defaults ? sanitizeDraft(sch, sch.defaults) : {};
1124
+ if (draftScene === 'shallow-ocean') {
1125
+ getShallowOceanController().resetPopulation();
1126
+ }
1127
+ renderSettings(draftScene);
1128
+ commitLive(draftScene);
1129
+ return;
1130
+ }
1131
+
1132
+ if (t.closest('[data-act="replay"]')) {
1133
+ if (draftScene) replayActiveScene(draftScene);
1134
+ return;
1135
+ }
1136
+
1137
+ if (t.closest('[data-act="surfacereset"]')) {
1138
+ state.surfaces = { ...DEFAULT_SETTINGS.surfaces };
1139
+ state.dim = DEFAULT_SETTINGS.dim;
1140
+ state.blur = DEFAULT_SETTINGS.blur;
1141
+ callbacks.scheduleSave();
1142
+ callbacks.applyAll();
1143
+ renderSettings('surface');
1144
+ return;
1145
+ }
1146
+
1147
+ if (t.closest('[data-act="customreset"]')) {
1148
+ state.wallpaperFit = DEFAULT_SETTINGS.wallpaperFit;
1149
+ state.wallpaperPosition = DEFAULT_SETTINGS.wallpaperPosition;
1150
+ callbacks.scheduleSave();
1151
+ callbacks.applyAll();
1152
+ renderSettings('custom');
1153
+ return;
1154
+ }
1155
+
1156
+ const rr = t.closest<HTMLElement>('[data-rowreset]');
1157
+ if (rr?.dataset.rowreset) {
1158
+ const rk = rr.dataset.rowreset as SurfaceRegionKey;
1159
+ const dflt = clamp(finiteNum(DEFAULT_SETTINGS.surfaces[rk], 66), 0, 100);
1160
+ state.surfaces[rk] = dflt;
1161
+ const rin = settings.querySelector<HTMLInputElement>(`[data-region="${rk}"]`);
1162
+ if (rin) rin.value = String(dflt);
1163
+ const rout = settings.querySelector<HTMLElement>(`[data-regionval="${rk}"]`);
1164
+ if (rout) rout.textContent = `${Math.round(dflt)}%`;
1165
+ applySurfaceVars(state, getLayer()?.layer || null);
1166
+ callbacks.scheduleSave();
1167
+ return;
1168
+ }
1169
+
1170
+ const qBtn = t.closest<HTMLElement>('[data-quality]');
1171
+ if (qBtn?.dataset.quality && draft && draftScene) {
1172
+ draft.quality = qBtn.dataset.quality;
1173
+ renderSettings(draftScene);
1174
+ commitLive(draftScene);
1175
+ return;
1176
+ }
1177
+
1178
+ const stepsBtn = t.closest<HTMLElement>('[data-steps]');
1179
+ if (stepsBtn?.dataset.steps && draft && draftScene) {
1180
+ draft.steps = Number(stepsBtn.dataset.steps);
1181
+ renderSettings(draftScene);
1182
+ commitLive(draftScene);
1183
+ return;
1184
+ }
1185
+
1186
+ const dirBtn = t.closest<HTMLElement>('[data-direction]');
1187
+ if (dirBtn?.dataset.direction && draft && draftScene) {
1188
+ draft.variant = dirBtn.dataset.direction;
1189
+ renderSettings(draftScene);
1190
+ commitLive(draftScene);
1191
+ return;
1192
+ }
1193
+
1194
+ const blinkDir = t.closest<HTMLElement>('[data-blinkdir]');
1195
+ if (blinkDir?.dataset.blinkdir && draft && draftScene) {
1196
+ draft.direction = blinkDir.dataset.blinkdir;
1197
+ renderSettings(draftScene);
1198
+ commitLive(draftScene);
1199
+ return;
1200
+ }
1201
+
1202
+ const bhPreset = t.closest<HTMLElement>('[data-bhpreset]');
1203
+ if (bhPreset?.dataset.bhpreset && draft && draftScene) {
1204
+ const sch = schemaOf(draftScene);
1205
+ const pVals = sch?.presets?.[bhPreset.dataset.bhpreset];
1206
+ if (pVals) {
1207
+ draft = sanitizeDraft(sch, { ...draft, ...pVals });
1208
+ renderSettings(draftScene);
1209
+ commitLive(draftScene);
1210
+ }
1211
+ return;
1212
+ }
1213
+
1214
+ const wPageBtn = t.closest<HTMLButtonElement>('[data-wallpage]');
1215
+ if (wPageBtn?.dataset.wallpage) {
1216
+ libPage += wPageBtn.dataset.wallpage === 'prev' ? -1 : 1;
1217
+ renderSettings('custom');
1218
+ return;
1219
+ }
1220
+
1221
+ if (t.closest('[data-act="wallimport"]')) {
1222
+ settings.querySelector<HTMLInputElement>('[data-act="wallfile"]')?.click();
1223
+ return;
1224
+ }
1225
+
1226
+ if (t.closest('[data-act="wallclear"]')) {
1227
+ void apiPostJson<{ ok?: boolean }>('/wallpaper-clear.json', {})
1228
+ .then((r) => {
1229
+ if (!r?.ok) return;
1230
+ callbacks?.setWallpapers([]);
1231
+ libPage = 0;
1232
+ state.wallpaperId = null;
1233
+ if (state.mode === 'wallpaper') state.enabled = false;
1234
+ callbacks?.scheduleSave();
1235
+ callbacks?.applyAll();
1236
+ renderSettings('custom');
1237
+ })
1238
+ .catch((err) => setPanelStatus(`清空失败:${String(err)}`, true));
1239
+ return;
1240
+ }
1241
+
1242
+ const wPick = t.closest<HTMLElement>('[data-wall]');
1243
+ if (wPick?.dataset.wall) {
1244
+ state.wallpaperId = wPick.dataset.wall;
1245
+ state.mode = 'wallpaper';
1246
+ state.enabled = true;
1247
+ callbacks.scheduleSave();
1248
+ callbacks.applyAll();
1249
+ renderSettings('custom');
1250
+ return;
1251
+ }
1252
+
1253
+ const wDel = t.closest<HTMLElement>('[data-wdel]');
1254
+ if (wDel?.dataset.wdel) {
1255
+ const id = wDel.dataset.wdel;
1256
+ void apiPostJson<{ ok?: boolean; wallpapers?: WallpaperItem[] }>('/wallpaper-delete.json', { id })
1257
+ .then((r) => {
1258
+ if (!r?.ok) return;
1259
+ callbacks?.setWallpapers(r.wallpapers || []);
1260
+ if (state.wallpaperId === id) {
1261
+ state.wallpaperId = r.wallpapers?.[0]?.id || null;
1262
+ }
1263
+ callbacks?.scheduleSave();
1264
+ callbacks?.applyAll();
1265
+ renderSettings('custom');
1266
+ })
1267
+ .catch((err) => setPanelStatus(`删除失败:${String(err)}`, true));
1268
+ }
1269
+ });
1270
+
1271
+ settings.addEventListener('input', (e) => {
1272
+ const t = e.target as HTMLInputElement;
1273
+ const state = callbacks?.getState();
1274
+ if (!t || !state || !callbacks) return;
1275
+
1276
+ if (t.dataset.field && draft && draftScene) {
1277
+ const k = t.dataset.field;
1278
+ const v = Number(t.value);
1279
+ draft[k] = v;
1280
+ const f = schemaOf(draftScene)?.fields.find((item) => item.key === k);
1281
+ const out = settings.querySelector<HTMLElement>(`[data-fieldval="${k}"]`);
1282
+ if (out) out.textContent = f ? fmtFieldVal(f, v) : String(v);
1283
+ commitLive(draftScene);
1284
+ return;
1285
+ }
1286
+
1287
+ if (t.dataset.region) {
1288
+ const rk = t.dataset.region as SurfaceRegionKey;
1289
+ const val = clamp(Number(t.value), 0, 100);
1290
+ state.surfaces[rk] = val;
1291
+ const out = settings.querySelector<HTMLElement>(`[data-regionval="${rk}"]`);
1292
+ if (out) out.textContent = `${Math.round(val)}%`;
1293
+ applySurfaceVars(state, getLayer()?.layer || null);
1294
+ callbacks.scheduleSave();
1295
+ return;
1296
+ }
1297
+
1298
+ if (t.dataset.slider) {
1299
+ const sk = t.dataset.slider as 'dim' | 'blur';
1300
+ const row = PARAM_ROWS.find((r) => r.key === sk);
1301
+ if (!row) return;
1302
+ const numVal = Number(t.value);
1303
+ state[sk] = numVal / row.scale;
1304
+ const out = settings.querySelector<HTMLElement>(`[data-sliderval="${sk}"]`);
1305
+ if (out) out.textContent = row.scale === 100 ? `${Math.round(numVal)}%` : `${numVal.toFixed(1)}px`;
1306
+ callbacks.scheduleSave();
1307
+ callbacks.applyAll();
1308
+ return;
1309
+ }
1310
+
1311
+ if (t.dataset.colorkey && draft && draftScene) {
1312
+ const ck = t.dataset.colorkey;
1313
+ if (/^color\d+$/.test(ck)) {
1314
+ const schColors = schemaOf(draftScene)?.colors || [];
1315
+ if (!Array.isArray(draft.colors)) draft.colors = [...schColors];
1316
+ (draft.colors as string[])[Number(ck.slice(5))] = t.value;
1317
+ } else {
1318
+ draft[ck] = t.value;
1319
+ }
1320
+ commitLive(draftScene);
1321
+ }
1322
+ });
1323
+
1324
+ settings.addEventListener('change', (e) => {
1325
+ const t = e.target as HTMLInputElement;
1326
+ const state = callbacks?.getState();
1327
+ if (!t || !state || !callbacks) return;
1328
+
1329
+ if (t.dataset.toggle === '__pspaused') {
1330
+ const on = Boolean(t.checked);
1331
+ if (on) state.sceneParams['pixel-sculpt'] = { paused: true };
1332
+ else delete state.sceneParams['pixel-sculpt'];
1333
+ writeSceneSetting('pixel-sculpt', { paused: on });
1334
+ callbacks.scheduleSave();
1335
+ try {
1336
+ getPsEditor()?.inst?.setSettings({ paused: on });
1337
+ } catch {
1338
+ // Ignore
1339
+ }
1340
+ return;
1341
+ }
1342
+
1343
+ if (t.dataset.toggle && draft && draftScene) {
1344
+ const tk = t.dataset.toggle;
1345
+ const defaultVal = schemaOf(draftScene)?.defaults?.[tk];
1346
+ draft[tk] = typeof defaultVal === 'number' ? (t.checked ? 1 : 0) : Boolean(t.checked);
1347
+ commitLive(draftScene);
1348
+ return;
1349
+ }
1350
+
1351
+ if (t.dataset.act === 'fit') {
1352
+ state.wallpaperFit = (t.value as AppearanceSettings['wallpaperFit']) || 'cover';
1353
+ callbacks.scheduleSave();
1354
+ callbacks.applyAll();
1355
+ return;
1356
+ }
1357
+
1358
+ if (t.dataset.act === 'pos') {
1359
+ state.wallpaperPosition = (t.value as AppearanceSettings['wallpaperPosition']) || 'center';
1360
+ callbacks.scheduleSave();
1361
+ callbacks.applyAll();
1362
+ return;
1363
+ }
1364
+
1365
+ if (t.dataset.act === 'wallfile' && t.files?.[0]) {
1366
+ const file = t.files[0];
1367
+ t.value = '';
1368
+ if (file.size > WALLPAPER_MAX_BYTES) {
1369
+ setPanelStatus('文件超过 200MB 上限', true);
1370
+ return;
1371
+ }
1372
+ void file
1373
+ .arrayBuffer()
1374
+ .then((buf) => uploadWallpaper(file.name, buf))
1375
+ .then((r) => {
1376
+ if (r?.ok && r.wallpaper) {
1377
+ callbacks?.setWallpapers(r.wallpapers || []);
1378
+ libPage = 0;
1379
+ state.wallpaperId = r.wallpaper.id;
1380
+ state.mode = 'wallpaper';
1381
+ state.enabled = true;
1382
+ callbacks?.scheduleSave();
1383
+ callbacks?.applyAll();
1384
+ renderSettings('custom');
1385
+ } else {
1386
+ setPanelStatus(`导入失败:${r?.error || '?'}`, true);
1387
+ }
1388
+ })
1389
+ .catch((err) => setPanelStatus(`导入失败:${String(err)}`, true));
1390
+ }
1391
+ });
1392
+
1393
+ cleanOceanUi = bindShallowOceanEvents(
1394
+ shadow,
1395
+ {
1396
+ panel: settings,
1397
+ state: () => callbacks?.getState() || null,
1398
+ draft: () => draft,
1399
+ schema: () => (draftScene ? schemaOf(draftScene) : null),
1400
+ commit: (sceneId) => commitLive(sceneId),
1401
+ onResetAll: () => {
1402
+ if (!draftScene) return;
1403
+ const sch = schemaOf(draftScene);
1404
+ draft = sch?.defaults ? sanitizeDraft(sch, sch.defaults) : {};
1405
+ getShallowOceanController().resetPopulation();
1406
+ renderSettings(draftScene);
1407
+ commitLive(draftScene);
1408
+ },
1409
+ onReplay: () => replayActiveScene('shallow-ocean'),
1410
+ onClose: closeSettings,
1411
+ onStatus: setPanelStatus,
1412
+ },
1413
+ () => {
1414
+ if (settingsOpen && settingsId === 'shallow-ocean') {
1415
+ renderSettings('shallow-ocean');
1416
+ }
1417
+ },
1418
+ );
1419
+
1420
+ // Sync shallow-ocean diagnostics count updates into persistent sceneParams
1421
+ getShallowOceanController().setSyncCallback((patch) => {
1422
+ const state = callbacks?.getState();
1423
+ if (!state) return;
1424
+ const sch = schemaOf('shallow-ocean');
1425
+ const cur = mergeSceneDraft(sch, state.sceneParams['shallow-ocean']);
1426
+ const next = { ...cur, ...patch };
1427
+ if (draft && draftScene === 'shallow-ocean') {
1428
+ Object.assign(draft, patch);
1429
+ }
1430
+ const dd = draftDeltaObj(sch, next);
1431
+ if (Object.keys(dd.delta).length > 0) state.sceneParams['shallow-ocean'] = dd.delta;
1432
+ else delete state.sceneParams['shallow-ocean'];
1433
+ writeSceneSetting('shallow-ocean', dd.full);
1434
+ callbacks?.scheduleSave();
1435
+ });
1436
+
1437
+ document.addEventListener('click', onDocClick, true);
1438
+ document.addEventListener('keydown', onDocKey, true);
1439
+ }
1440
+
1441
+ export function ensurePanel(cb: PanelCallbacks): void {
1442
+ callbacks = cb;
1443
+ if (ui && document.documentElement.contains(ui.host)) return;
1444
+
1445
+ const host = document.createElement('div');
1446
+ host.id = PANEL_ID;
1447
+ host.setAttribute('data-dsh-ccx', 'panel');
1448
+ const shadow = host.attachShadow({ mode: 'open' });
1449
+
1450
+ const styleEl = document.createElement('style');
1451
+ styleEl.textContent = PANEL_CSS;
1452
+ shadow.appendChild(styleEl);
1453
+
1454
+ const trigger = document.createElement('button');
1455
+ trigger.type = 'button';
1456
+ trigger.id = TRIGGER_ID;
1457
+ trigger.className = 'trigger';
1458
+ trigger.title = '外观与动态背景 (dsh-ccx)';
1459
+ trigger.setAttribute('aria-expanded', 'false');
1460
+ trigger.innerHTML = GEAR_SVG;
1461
+ shadow.appendChild(trigger);
1462
+
1463
+ const market = document.createElement('div');
1464
+ market.className = 'preview-market-popover';
1465
+ market.hidden = true;
1466
+ market.innerHTML =
1467
+ `<header class="preview-market-header"><h3>Plugin Market</h3><button class="preview-market-close" type="button" data-act="marketclose" title="关闭" aria-label="关闭">${CLOSE_SVG}</button></header>` +
1468
+ '<div class="preview-market-list">' +
1469
+ '<div class="preview-market-categories" role="tablist">' +
1470
+ '<button type="button" class="preview-market-category" data-cat="all" aria-selected="true">全部</button>' +
1471
+ '<button type="button" class="preview-market-category" data-cat="enabled" aria-selected="false">已启用</button>' +
1472
+ '<button type="button" class="preview-market-category" data-cat="custom" aria-selected="false">自定义</button>' +
1473
+ '</div>' +
1474
+ '<section class="preview-market-section"><div class="preview-market-section-list"></div>' +
1475
+ '<p class="cat-empty" hidden>此分类下没有项目。</p></section></div>';
1476
+ shadow.appendChild(market);
1477
+
1478
+ const settings = document.createElement('div');
1479
+ settings.className = 'particle-settings-panel';
1480
+ settings.hidden = true;
1481
+ shadow.appendChild(settings);
1482
+
1483
+ const cardsWrap = market.querySelector<HTMLDivElement>('.preview-market-section-list')!;
1484
+ const emptyNotice = market.querySelector<HTMLParagraphElement>('.cat-empty')!;
1485
+
1486
+ ui = { host, shadow, trigger, market, settings, cardsWrap, emptyNotice };
1487
+ (document.body || document.documentElement).appendChild(host);
1488
+ syncPanelTheme();
1489
+ syncSidebarCollapsed();
1490
+ bindEvents();
1491
+ }
1492
+
1493
+ export function refreshPanel(state: AppearanceSettings | null): void {
1494
+ if (!ui || !state) return;
1495
+ syncPanelTheme();
1496
+ syncSidebarCollapsed();
1497
+ buildCards();
1498
+ if (settingsOpen && settingsId === 'pixel-sculpt') syncPsPanel(state);
1499
+ if (settingsOpen && settingsId === 'shallow-ocean') renderSettings('shallow-ocean');
1500
+ }
1501
+
1502
+ export function teardownPanel(): void {
1503
+ document.removeEventListener('click', onDocClick, true);
1504
+ document.removeEventListener('keydown', onDocKey, true);
1505
+ if (cleanOceanUi) {
1506
+ cleanOceanUi();
1507
+ cleanOceanUi = null;
1508
+ }
1509
+ if (ui?.host.parentNode) {
1510
+ try {
1511
+ ui.host.parentNode.removeChild(ui.host);
1512
+ } catch {
1513
+ // Ignore
1514
+ }
1515
+ }
1516
+ ui = null;
1517
+ callbacks = null;
1518
+ marketOpen = false;
1519
+ settingsOpen = false;
1520
+ settingsId = null;
1521
+ draft = null;
1522
+ draftScene = null;
1523
+ lastRenderedCardIds = '';
1524
+ }