@lieakks/dsh-skins 0.0.0-stage → 1.0.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.
package/client.js ADDED
@@ -0,0 +1,1648 @@
1
+ window.__ModuleLoader__.load({
2
+ id: '@lieakks/dsh-skins',
3
+ factory(require) {
4
+ const React = require('react');
5
+ const h = React.createElement;
6
+
7
+ const NS = 'skins';
8
+ const STORE_KEY = 'dsh-skins:state:v1';
9
+ /** Longest edge a chosen file is downscaled to before it is stored. */
10
+ const MAX_SIDE = 2560;
11
+ /** Refuse a wallpaper larger than this; IndexedDB is roomy but not unlimited. */
12
+ const MAX_BLOB_BYTES = 12 * 1024 * 1024;
13
+ /** IndexedDB database and object store holding the wallpaper binary. */
14
+ const DB_NAME = 'dsh-skins';
15
+ const DB_STORE = 'assets';
16
+ const WALLPAPER_KEY = 'wallpaper';
17
+ /** Alpha below this marks a sampled pixel as transparent. */
18
+ const ALPHA_THRESHOLD = 250;
19
+
20
+ const DICT = {
21
+ en: {
22
+ section: 'Skins',
23
+ lead: 'A skin recolors the interface on top of the light or dark appearance you chose. Your selection and wallpaper are stored in this browser.',
24
+ palettes: 'Color skins',
25
+ defaultSkin: 'Default',
26
+ wallpaper: 'Background image',
27
+ wallpaperHint: 'Fills the canvas behind panels and messages.',
28
+ choose: 'Choose image…',
29
+ processing: 'Processing…',
30
+ urlPlaceholder: 'Paste an image URL',
31
+ applyUrl: 'Apply',
32
+ remove: 'Remove',
33
+ dim: 'Dim',
34
+ panel: 'Panel transparency',
35
+ veil: 'Backdrop veil',
36
+ panelShade: 'Panel shade',
37
+ auto: 'Auto',
38
+ darkGlass: 'Dark',
39
+ lightGlass: 'Light',
40
+ textTheme: 'Text colors',
41
+ contrast: 'High contrast',
42
+ soft: 'Soft',
43
+ custom: 'Custom',
44
+ primaryText: 'Body text',
45
+ mutedText: 'Muted text',
46
+ preview: 'Preview',
47
+ note: 'Settings are stored in this browser only; images are downscaled before they are saved.',
48
+ storageFull: 'That image is too large to store locally. Downscale it or paste a URL instead.',
49
+ tooLarge: 'That image is larger than 12 MB after encoding. Pick a smaller one.',
50
+ storageUnavailable: 'Browser storage is unavailable, so the image cannot be saved.',
51
+ invalidUrl: 'Enter an http(s) image URL or a data image.',
52
+ localPath: 'The browser cannot open a local file path. Use Choose image… instead.',
53
+ decodeFailed: 'That file could not be read as an image.',
54
+ readFailed: 'The image could not be read.',
55
+ selected: 'Selected',
56
+ },
57
+ zh: {
58
+ section: '皮肤',
59
+ lead: '皮肤会叠加在你已选择的浅色/深色外观之上重新着色。所选皮肤与背景图保存在本机浏览器中。',
60
+ palettes: '配色皮肤',
61
+ defaultSkin: '默认',
62
+ wallpaper: '背景图',
63
+ wallpaperHint: '铺在面板与消息下方的画布上。',
64
+ choose: '选择图片…',
65
+ processing: '处理中…',
66
+ urlPlaceholder: '粘贴图片链接',
67
+ applyUrl: '应用',
68
+ remove: '移除',
69
+ dim: '暗化',
70
+ panel: '面板通透度',
71
+ veil: '遮罩浓度',
72
+ panelShade: '面板明暗',
73
+ auto: '自动',
74
+ darkGlass: '深色',
75
+ lightGlass: '浅色',
76
+ textTheme: '文字配色',
77
+ contrast: '高对比',
78
+ soft: '柔和',
79
+ custom: '自定义',
80
+ primaryText: '正文',
81
+ mutedText: '次级文字',
82
+ preview: '预览',
83
+ note: '设置仅保存在本机浏览器;图片保存前会自动压缩。',
84
+ storageFull: '图片太大,无法保存在本地。请先压缩,或改用图片链接。',
85
+ tooLarge: '图片编码后超过 12 MB,请换一张更小的。',
86
+ storageUnavailable: '浏览器存储不可用,图片无法保存。',
87
+ invalidUrl: '请输入 http(s) 图片链接或 data 图片。',
88
+ localPath: '浏览器无法直接读取本地文件路径,请改用“选择图片…”。',
89
+ decodeFailed: '无法把该文件解析为图片。',
90
+ readFailed: '图片读取失败。',
91
+ selected: '已选用',
92
+ },
93
+ };
94
+
95
+ /** Token names a skin may recolor, in the alias layer the theme service exposes. */
96
+ const TOKEN = {
97
+ base: '--dsw-alias-bg-base',
98
+ layer1: '--dsw-alias-bg-layer-1',
99
+ layer2: '--dsw-alias-bg-layer-2',
100
+ overlay: '--dsw-alias-bg-overlay',
101
+ border1: '--dsw-alias-border-l1',
102
+ border2: '--dsw-alias-border-l2',
103
+ brand: '--dsw-alias-brand-primary',
104
+ text: '--dsw-alias-label-primary',
105
+ muted: '--dsw-alias-label-secondary',
106
+ // Extra muted aliases some components use; harmless when a deployment never reads them.
107
+ tertiary: '--dsw-alias-label-tertiary',
108
+ disabled: '--dsw-alias-label-disabled',
109
+ success: '--dsw-alias-state-success-primary',
110
+ warn: '--dsw-alias-state-warn-primary',
111
+ error: '--dsw-alias-state-error-primary',
112
+ idle: '--dsw-alias-state-idle-primary',
113
+ sidebar: '--dsw-specific-sidebar-fill',
114
+ };
115
+
116
+ /**
117
+ * Glass surfaces used while a wallpaper is set. Surfaces and labels switch
118
+ * together with the wallpaper's brightness rather than with light/dark, because
119
+ * the text sits on the image: a dark wall takes light labels on dark glass, a
120
+ * bright wall the opposite. The skin then contributes only its accents.
121
+ */
122
+ const GLASS = {
123
+ lightText: {
124
+ layer1: '#0f1316',
125
+ layer2: '#0a0d0f',
126
+ overlay: '#121619',
127
+ sidebar: '#0c0f12',
128
+ border1: 'rgba(255, 255, 255, 0.16)',
129
+ border2: 'rgba(255, 255, 255, 0.28)',
130
+ text: '#f5f8f9',
131
+ muted: '#c6cfd4',
132
+ },
133
+ darkText: {
134
+ layer1: '#ffffff',
135
+ layer2: '#f3f5f6',
136
+ overlay: '#ffffff',
137
+ sidebar: '#f7f8f9',
138
+ border1: 'rgba(0, 0, 0, 0.12)',
139
+ border2: 'rgba(0, 0, 0, 0.22)',
140
+ text: '#11161a',
141
+ muted: '#4b555b',
142
+ },
143
+ };
144
+
145
+ /**
146
+ * Surface alpha per layer while a wallpaper is set: `1 - transparency * factor`.
147
+ * The factors keep popovers (overlay) more solid than the canvas, and the single
148
+ * hard floor sits far enough out that the whole 0–95% slider range stays monotonic.
149
+ */
150
+ const SURFACE_FACTORS = { layer1: 0.95, layer2: 0.9, overlay: 0.6, sidebar: 0.95 };
151
+ /** Absolute minimum surface alpha, reached only at the very top of the range. */
152
+ const SURFACE_FLOOR = 0.06;
153
+ /** Upper bound of the panel-transparency setting. */
154
+ const MAX_PANEL = 0.95;
155
+
156
+ /**
157
+ * Text palettes layered on the glass. `contrast` pushes muted copy close to the
158
+ * body colour, because secondary labels are the first thing a photo swallows.
159
+ */
160
+ const TEXT_PRESETS = {
161
+ contrast: {
162
+ lightText: { primary: '#ffffff', muted: '#e3eaed' },
163
+ darkText: { primary: '#000000', muted: '#2a3238' },
164
+ },
165
+ soft: {
166
+ lightText: { primary: '#e6edef', muted: '#a7b4ba' },
167
+ darkText: { primary: '#26303a', muted: '#5f6a70' },
168
+ },
169
+ };
170
+
171
+ /** Text colours for one state: the preset, or the two colours the user picked. */
172
+ function resolveTextColors(state, direction) {
173
+ const glass = GLASS[direction] ?? GLASS.darkText;
174
+ const preset = state.textTheme === 'contrast' || state.textTheme === 'soft' ? TEXT_PRESETS[state.textTheme] : null;
175
+ const base = preset === null ? { primary: glass.text, muted: glass.muted } : preset[direction] ?? preset.darkText;
176
+ if (state.textTheme !== 'custom') return base;
177
+ const primary = typeof state.textPrimary === 'string' && /^#[0-9a-f]{6}$/i.test(state.textPrimary) ? state.textPrimary : base.primary;
178
+ const muted = typeof state.textMuted === 'string' && /^#[0-9a-f]{6}$/i.test(state.textMuted) ? state.textMuted : base.muted;
179
+ return { primary, muted };
180
+ }
181
+
182
+ /** Relative brightness of a `#rrggbb` colour, or `null` when the value is unusable. */
183
+ function hexLuminance(color) {
184
+ const value = String(color).trim().replace('#', '');
185
+ if (!/^[0-9a-fA-F]{6}$/.test(value)) return null;
186
+ const red = parseInt(value.slice(0, 2), 16) / 255;
187
+ const green = parseInt(value.slice(2, 4), 16) / 255;
188
+ const blue = parseInt(value.slice(4, 6), 16) / 255;
189
+ return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
190
+ }
191
+
192
+ /** A `null` palette leaves the built-in appearance untouched. */
193
+ const SKINS = [
194
+ { id: 'default', label: 'defaultSkin', light: null, dark: null },
195
+ {
196
+ id: 'aurora',
197
+ label: { en: 'Aurora', zh: '极光青' },
198
+ light: {
199
+ base: '#f3f9fa',
200
+ layer1: '#ffffff',
201
+ layer2: '#e6f1f2',
202
+ overlay: '#ffffff',
203
+ border1: '#d5e6e8',
204
+ border2: '#b5d2d5',
205
+ brand: '#0d8f86',
206
+ text: '#0a2b2c',
207
+ muted: '#4c6b6c',
208
+ success: '#12855b',
209
+ warn: '#b7791f',
210
+ error: '#c0392b',
211
+ idle: '#8aa3a4',
212
+ sidebar: '#edf6f7',
213
+ },
214
+ dark: {
215
+ base: '#071417',
216
+ layer1: '#0e2429',
217
+ layer2: '#153138',
218
+ overlay: '#102a30',
219
+ border1: '#1d3b41',
220
+ border2: '#2a4f57',
221
+ brand: '#3fd6c4',
222
+ text: '#e6f6f5',
223
+ muted: '#9cb9b8',
224
+ success: '#3ddc97',
225
+ warn: '#e2b25a',
226
+ error: '#ff7b72',
227
+ idle: '#6b8a8b',
228
+ sidebar: '#0a1d21',
229
+ },
230
+ },
231
+ {
232
+ id: 'sand',
233
+ label: { en: 'Warm sand', zh: '暖沙' },
234
+ light: {
235
+ base: '#faf6ef',
236
+ layer1: '#fffdf8',
237
+ layer2: '#f2e9db',
238
+ overlay: '#fffdf8',
239
+ border1: '#e6d9c5',
240
+ border2: '#d3c0a4',
241
+ brand: '#b2662f',
242
+ text: '#2e2318',
243
+ muted: '#6b5a47',
244
+ success: '#2f7d4f',
245
+ warn: '#b7791f',
246
+ error: '#b93a2f',
247
+ idle: '#a99a86',
248
+ sidebar: '#f6efe4',
249
+ },
250
+ dark: {
251
+ base: '#16110c',
252
+ layer1: '#221a13',
253
+ layer2: '#2c2218',
254
+ overlay: '#241b13',
255
+ border1: '#3a2c20',
256
+ border2: '#4e3b2a',
257
+ brand: '#e0a06a',
258
+ text: '#f5e9dc',
259
+ muted: '#bda78f',
260
+ success: '#6dcf8f',
261
+ warn: '#e2b25a',
262
+ error: '#ff8a7a',
263
+ idle: '#8a7761',
264
+ sidebar: '#120d09',
265
+ },
266
+ },
267
+ {
268
+ id: 'forest',
269
+ label: { en: 'Forest', zh: '森林' },
270
+ light: {
271
+ base: '#f2f8f3',
272
+ layer1: '#ffffff',
273
+ layer2: '#e5f0e6',
274
+ overlay: '#ffffff',
275
+ border1: '#d3e4d5',
276
+ border2: '#b2cfb7',
277
+ brand: '#2f7d4f',
278
+ text: '#0f2717',
279
+ muted: '#4b6b55',
280
+ success: '#2f7d4f',
281
+ warn: '#b7791f',
282
+ error: '#bf4133',
283
+ idle: '#8ba394',
284
+ sidebar: '#edf5ee',
285
+ },
286
+ dark: {
287
+ base: '#0a130e',
288
+ layer1: '#112019',
289
+ layer2: '#182c21',
290
+ overlay: '#12271c',
291
+ border1: '#234032',
292
+ border2: '#315544',
293
+ brand: '#6dcf8f',
294
+ text: '#e6f5ea',
295
+ muted: '#9fb8a8',
296
+ success: '#6dcf8f',
297
+ warn: '#e2b25a',
298
+ error: '#ff8a7a',
299
+ idle: '#6f8a7b',
300
+ sidebar: '#08110c',
301
+ },
302
+ },
303
+ {
304
+ id: 'violet',
305
+ label: { en: 'Neon violet', zh: '霓虹紫' },
306
+ light: {
307
+ base: '#f7f4fc',
308
+ layer1: '#ffffff',
309
+ layer2: '#efe8f9',
310
+ overlay: '#ffffff',
311
+ border1: '#e0d6f2',
312
+ border2: '#c6b4e4',
313
+ brand: '#6d3fe0',
314
+ text: '#1d1430',
315
+ muted: '#5d4b7a',
316
+ success: '#2f7d4f',
317
+ warn: '#b7791f',
318
+ error: '#c0392b',
319
+ idle: '#a095b5',
320
+ sidebar: '#f3eefb',
321
+ },
322
+ dark: {
323
+ base: '#0b0816',
324
+ layer1: '#151024',
325
+ layer2: '#1f1735',
326
+ overlay: '#181229',
327
+ border1: '#2e2447',
328
+ border2: '#413262',
329
+ brand: '#b18cff',
330
+ text: '#efe9ff',
331
+ muted: '#a99bc7',
332
+ success: '#6dcf8f',
333
+ warn: '#e2b25a',
334
+ error: '#ff8a7a',
335
+ idle: '#7a6d94',
336
+ sidebar: '#090613',
337
+ },
338
+ },
339
+ ];
340
+
341
+ function findSkin(id) {
342
+ return SKINS.find((skin) => skin.id === id) ?? SKINS[0];
343
+ }
344
+
345
+ function clamp(value, min, max) {
346
+ const number = Number(value);
347
+ if (!Number.isFinite(number)) return min;
348
+ return Math.min(max, Math.max(min, number));
349
+ }
350
+
351
+ /** `#rrggbb` → `rgba(r, g, b, a)`; other notations pass through unchanged. */
352
+ function withAlpha(color, alpha) {
353
+ const value = String(color).trim().replace('#', '');
354
+ if (!/^[0-9a-fA-F]{6}$/.test(value)) return color;
355
+ const red = parseInt(value.slice(0, 2), 16);
356
+ const green = parseInt(value.slice(2, 4), 16);
357
+ const blue = parseInt(value.slice(4, 6), 16);
358
+ return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
359
+ }
360
+
361
+ /**
362
+ * Build the token override layer.
363
+ *
364
+ * Without a wallpaper a skin replaces the palette outright. With one, the canvas
365
+ * becomes transparent, surfaces become glass, and labels come from `textColors`,
366
+ * so a dark wall gets light text (and dark glass) whatever the light/dark
367
+ * appearance is, while the text palette stays independently selectable.
368
+ */
369
+ function buildTokens(skin, wallpaper, panel, direction, textColors) {
370
+ const isDefault = skin.light === null || skin.dark === null;
371
+ if (!wallpaper) {
372
+ if (isDefault) return null;
373
+ const plain = {};
374
+ for (const [key, token] of Object.entries(TOKEN)) {
375
+ const light = skin.light[key];
376
+ const dark = skin.dark[key];
377
+ if (typeof light !== 'string' || typeof dark !== 'string') continue;
378
+ plain[token] = { light, dark };
379
+ }
380
+ return plain;
381
+ }
382
+
383
+ const glass = GLASS[direction] ?? GLASS.darkText;
384
+ const text = textColors === undefined || textColors === null ? { primary: glass.text, muted: glass.muted } : textColors;
385
+ const transparency = clamp(panel, 0, MAX_PANEL);
386
+ const tokens = {
387
+ [TOKEN.base]: { light: 'transparent', dark: 'transparent' },
388
+ // Both scheme slots carry the same value: the text answers to the wallpaper.
389
+ [TOKEN.text]: { light: text.primary, dark: text.primary },
390
+ [TOKEN.muted]: { light: text.muted, dark: text.muted },
391
+ [TOKEN.border1]: { light: glass.border1, dark: glass.border1 },
392
+ [TOKEN.border2]: { light: glass.border2, dark: glass.border2 },
393
+ // Tertiary and disabled labels are not in the documented token set, but the
394
+ // sparse grey copy under plugin rows uses them; pin them to the muted colour
395
+ // so the text palette really covers every grey the UI draws.
396
+ [TOKEN.tertiary]: { light: text.muted, dark: text.muted },
397
+ [TOKEN.disabled]: { light: text.muted, dark: text.muted },
398
+ };
399
+
400
+ for (const key of ['layer1', 'layer2', 'overlay', 'sidebar']) {
401
+ const alpha = clamp(1 - transparency * SURFACE_FACTORS[key], SURFACE_FLOOR, 0.98);
402
+ tokens[TOKEN[key]] = { light: withAlpha(glass[key], alpha), dark: withAlpha(glass[key], alpha) };
403
+ }
404
+
405
+ if (!isDefault) {
406
+ const accent = direction === 'lightText' ? skin.dark : skin.light;
407
+ for (const key of ['brand', 'success', 'warn', 'error', 'idle']) {
408
+ tokens[TOKEN[key]] = { light: accent[key], dark: accent[key] };
409
+ }
410
+ }
411
+ return tokens;
412
+ }
413
+
414
+ /** Escape a URL for a CSS `url("…")` string. */
415
+ function cssUrl(value) {
416
+ return String(value)
417
+ .replace(/\\/g, '\\\\')
418
+ .replace(/"/g, '\\"')
419
+ .replace(/[\r\n]+/g, '');
420
+ }
421
+
422
+ function isImageSource(value) {
423
+ return /^(https?:\/\/|data:image\/)/i.test(String(value).trim());
424
+ }
425
+
426
+ /**
427
+ * Average brightness of a wallpaper, 0 (black) to 1 (white), reduced to one
428
+ * pixel. Cross-origin images without CORS headers taint the canvas, so the
429
+ * result is `null` there and the caller falls back to the appearance scheme.
430
+ */
431
+ function measureLuminance(src) {
432
+ return new Promise((resolve) => {
433
+ const image = new Image();
434
+ image.crossOrigin = 'anonymous';
435
+ image.onload = () => {
436
+ try {
437
+ const canvas = document.createElement('canvas');
438
+ canvas.width = 1;
439
+ canvas.height = 1;
440
+ const context = canvas.getContext('2d');
441
+ if (context === null) {
442
+ resolve(null);
443
+ return;
444
+ }
445
+ context.drawImage(image, 0, 0, 1, 1);
446
+ const data = context.getImageData(0, 0, 1, 1).data;
447
+ resolve((0.2126 * data[0] + 0.7152 * data[1] + 0.0722 * data[2]) / 255);
448
+ } catch (error) {
449
+ resolve(null);
450
+ }
451
+ };
452
+ image.onerror = () => resolve(null);
453
+ image.src = src;
454
+ });
455
+ }
456
+
457
+ /**
458
+ * Which way the glass reads: `lightText` on a dark wall, `darkText` on a bright
459
+ * one. `shade` is the explicit panel choice; otherwise the measured brightness
460
+ * decides, and an unmeasurable image falls back to the appearance scheme.
461
+ */
462
+ function resolveDirection(shade, luminance, scheme) {
463
+ if (shade === 'dark') return 'lightText';
464
+ if (shade === 'light') return 'darkText';
465
+ if (typeof luminance === 'number' && Number.isFinite(luminance)) {
466
+ return luminance < 0.5 ? 'lightText' : 'darkText';
467
+ }
468
+ return scheme === 'dark' ? 'lightText' : 'darkText';
469
+ }
470
+
471
+ /** Decode a picked file, honouring EXIF orientation where the browser supports it. */
472
+ async function decodeImage(file) {
473
+ if (typeof createImageBitmap === 'function') {
474
+ try {
475
+ const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' });
476
+ return {
477
+ source: bitmap,
478
+ width: bitmap.width,
479
+ height: bitmap.height,
480
+ close: () => {
481
+ try {
482
+ bitmap.close();
483
+ } catch (error) {
484
+ // Already detached; nothing to release.
485
+ }
486
+ },
487
+ };
488
+ } catch (error) {
489
+ // Fall through to the <img> path for formats createImageBitmap rejects.
490
+ }
491
+ }
492
+ const url = URL.createObjectURL(file);
493
+ try {
494
+ const element = await new Promise((resolve, reject) => {
495
+ const image = new Image();
496
+ image.onload = () => resolve(image);
497
+ image.onerror = () => reject(new Error('decodeFailed'));
498
+ image.src = url;
499
+ });
500
+ return {
501
+ source: element,
502
+ width: element.naturalWidth || element.width,
503
+ height: element.naturalHeight || element.height,
504
+ close: () => {},
505
+ };
506
+ } finally {
507
+ URL.revokeObjectURL(url);
508
+ }
509
+ }
510
+
511
+ /** Whether the scaled image keeps any pixel that is not fully opaque. */
512
+ function hasTransparency(source, width, height) {
513
+ try {
514
+ const limit = 64;
515
+ const scale = Math.min(1, limit / Math.max(width, height));
516
+ const canvas = document.createElement('canvas');
517
+ canvas.width = Math.max(1, Math.round(width * scale));
518
+ canvas.height = Math.max(1, Math.round(height * scale));
519
+ const context = canvas.getContext('2d');
520
+ if (context === null) return false;
521
+ context.drawImage(source, 0, 0, canvas.width, canvas.height);
522
+ const data = context.getImageData(0, 0, canvas.width, canvas.height).data;
523
+ for (let index = 3; index < data.length; index += 4) {
524
+ if (data[index] < ALPHA_THRESHOLD) return true;
525
+ }
526
+ return false;
527
+ } catch (error) {
528
+ return false;
529
+ }
530
+ }
531
+
532
+ function canvasToBlob(canvas, type, quality) {
533
+ return new Promise((resolve) => {
534
+ if (typeof canvas.toBlob !== 'function') {
535
+ resolve(null);
536
+ return;
537
+ }
538
+ canvas.toBlob((blob) => resolve(blob ?? null), type, quality);
539
+ });
540
+ }
541
+
542
+ /**
543
+ * Downscale a picked file and encode it for storage. Images that use transparency
544
+ * keep their alpha (WebP when the browser can produce it, PNG otherwise); every
545
+ * other image becomes a high-quality JPEG. The longest edge is capped at
546
+ * `MAX_SIDE`, and pixels are never upscaled.
547
+ */
548
+ async function prepareWallpaper(file) {
549
+ const decoded = await decodeImage(file);
550
+ try {
551
+ const scale = Math.min(1, MAX_SIDE / Math.max(decoded.width, decoded.height));
552
+ const width = Math.max(1, Math.round(decoded.width * scale));
553
+ const height = Math.max(1, Math.round(decoded.height * scale));
554
+ const transparent = hasTransparency(decoded.source, decoded.width, decoded.height);
555
+ const canvas = document.createElement('canvas');
556
+ canvas.width = width;
557
+ canvas.height = height;
558
+ const context = canvas.getContext('2d');
559
+ if (context === null) throw new Error('decodeFailed');
560
+ context.drawImage(decoded.source, 0, 0, width, height);
561
+
562
+ let blob = null;
563
+ if (transparent) {
564
+ blob = await canvasToBlob(canvas, 'image/webp', 0.92);
565
+ if (blob !== null && blob.type !== 'image/webp') blob = null;
566
+ if (blob === null) blob = await canvasToBlob(canvas, 'image/png');
567
+ } else {
568
+ blob = await canvasToBlob(canvas, 'image/jpeg', 0.92);
569
+ }
570
+ if (blob === null) throw new Error('decodeFailed');
571
+ if (blob.size > MAX_BLOB_BYTES) throw new Error('tooLarge');
572
+ return { blob, width, height, transparent };
573
+ } finally {
574
+ decoded.close();
575
+ }
576
+ }
577
+
578
+ /** Open (and lazily create) the wallpaper database. */
579
+ function openWallpaperDb() {
580
+ return new Promise((resolve, reject) => {
581
+ if (typeof indexedDB === 'undefined') {
582
+ reject(new Error('storageUnavailable'));
583
+ return;
584
+ }
585
+ const request = indexedDB.open(DB_NAME, 1);
586
+ request.onupgradeneeded = () => {
587
+ const db = request.result;
588
+ if (!db.objectStoreNames.contains(DB_STORE)) db.createObjectStore(DB_STORE);
589
+ };
590
+ request.onsuccess = () => resolve(request.result);
591
+ request.onerror = () => reject(request.error ?? new Error('storageUnavailable'));
592
+ });
593
+ }
594
+
595
+ /** Run one object-store operation and settle with the request's result. */
596
+ function runWallpaperStore(mode, operation) {
597
+ return openWallpaperDb().then(
598
+ (db) =>
599
+ new Promise((resolve, reject) => {
600
+ const transaction = db.transaction(DB_STORE, mode);
601
+ let request;
602
+ try {
603
+ request = operation(transaction.objectStore(DB_STORE));
604
+ } catch (error) {
605
+ db.close();
606
+ reject(error);
607
+ return;
608
+ }
609
+ transaction.oncomplete = () => {
610
+ db.close();
611
+ resolve(request === undefined ? undefined : request.result);
612
+ };
613
+ transaction.onerror = () => {
614
+ db.close();
615
+ reject(transaction.error ?? new Error('storageUnavailable'));
616
+ };
617
+ transaction.onabort = () => {
618
+ db.close();
619
+ reject(transaction.error ?? new Error('storageUnavailable'));
620
+ };
621
+ }),
622
+ );
623
+ }
624
+
625
+ const readWallpaperBlob = () => runWallpaperStore('readonly', (store) => store.get(WALLPAPER_KEY));
626
+ const writeWallpaperBlob = (blob) => runWallpaperStore('readwrite', (store) => store.put(blob, WALLPAPER_KEY));
627
+ const deleteWallpaperBlob = () => runWallpaperStore('readwrite', (store) => store.delete(WALLPAPER_KEY));
628
+
629
+ function defaultState() {
630
+ return {
631
+ skin: 'default',
632
+ wallpaper: null,
633
+ /** True when localStorage expects a wallpaper blob that has not been read yet. */
634
+ wallpaperPending: false,
635
+ dim: 0.18,
636
+ panel: 0.35,
637
+ veil: 0.55,
638
+ shade: 'auto',
639
+ textTheme: 'auto',
640
+ textPrimary: null,
641
+ textMuted: null,
642
+ luminance: null,
643
+ message: null,
644
+ };
645
+ }
646
+
647
+ function loadState() {
648
+ try {
649
+ const raw = window.localStorage.getItem(STORE_KEY);
650
+ if (raw === null) return defaultState();
651
+ const parsed = JSON.parse(raw);
652
+ if (parsed === null || typeof parsed !== 'object') return defaultState();
653
+ const skin =
654
+ typeof parsed.skin === 'string' && SKINS.some((entry) => entry.id === parsed.skin)
655
+ ? parsed.skin
656
+ : 'default';
657
+ const stored = parsed.wallpaper !== null && typeof parsed.wallpaper === 'object' ? parsed.wallpaper : null;
658
+ // Inline data URLs come from the pre-IndexedDB release and are migrated on boot.
659
+ const wallpaper =
660
+ stored !== null && typeof stored.value === 'string' && isImageSource(stored.value)
661
+ ? { kind: stored.kind === 'url' ? 'url' : 'data', value: stored.value }
662
+ : null;
663
+ const wallpaperPending = wallpaper === null && stored !== null && stored.kind === 'blob';
664
+ const legacy = parsed.panel === undefined;
665
+ const storedDim = parsed.dim === undefined ? 0.18 : clamp(parsed.dim, 0, 0.85);
666
+ // The old `text` field chose a text colour; its glass shade is the opposite one.
667
+ const migratedShade = parsed.text === 'light' ? 'dark' : parsed.text === 'dark' ? 'light' : 'auto';
668
+ const shade = parsed.shade === 'dark' || parsed.shade === 'light' ? parsed.shade : migratedShade;
669
+ const textTheme =
670
+ parsed.textTheme === 'contrast' || parsed.textTheme === 'soft' || parsed.textTheme === 'custom'
671
+ ? parsed.textTheme
672
+ : 'auto';
673
+ const color = (value) => (typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value) ? value : null);
674
+ const luminance =
675
+ typeof parsed.luminance === 'number' && Number.isFinite(parsed.luminance)
676
+ ? Math.min(1, Math.max(0, parsed.luminance))
677
+ : null;
678
+ return {
679
+ skin,
680
+ wallpaper,
681
+ wallpaperPending,
682
+ // A wallpaper saved before the panel slider existed was veiled by the old
683
+ // defaults; start it lighter so the image reads, and let the slider raise it.
684
+ dim: legacy ? Math.min(storedDim, 0.18) : storedDim,
685
+ panel: legacy ? 0.35 : clamp(parsed.panel, 0, MAX_PANEL),
686
+ veil: parsed.veil === undefined ? 0.55 : clamp(parsed.veil, 0, 0.9),
687
+ shade,
688
+ textTheme,
689
+ textPrimary: color(parsed.textPrimary),
690
+ textMuted: color(parsed.textMuted),
691
+ luminance,
692
+ message: null,
693
+ };
694
+ } catch (error) {
695
+ return defaultState();
696
+ }
697
+ }
698
+
699
+ /**
700
+ * localStorage keeps only small values: a stored wallpaper is recorded by kind,
701
+ * because the pixels themselves live in IndexedDB as a Blob.
702
+ */
703
+ function serializeState(state) {
704
+ const wallpaper = state.wallpaper;
705
+ return {
706
+ skin: state.skin,
707
+ wallpaper:
708
+ wallpaper === null
709
+ ? null
710
+ : wallpaper.kind === 'url'
711
+ ? { kind: 'url', value: wallpaper.value }
712
+ : wallpaper.kind === 'data'
713
+ ? { kind: 'data', value: wallpaper.value }
714
+ : { kind: 'blob' },
715
+ dim: state.dim,
716
+ panel: state.panel,
717
+ veil: state.veil,
718
+ shade: state.shade,
719
+ textTheme: state.textTheme,
720
+ textPrimary: state.textPrimary,
721
+ textMuted: state.textMuted,
722
+ luminance: state.luminance,
723
+ };
724
+ }
725
+
726
+ function saveState(state) {
727
+ try {
728
+ window.localStorage.setItem(STORE_KEY, JSON.stringify(serializeState(state)));
729
+ return true;
730
+ } catch (error) {
731
+ return false;
732
+ }
733
+ }
734
+
735
+ function createStore(initial) {
736
+ let state = initial;
737
+ const listeners = new Set();
738
+ return {
739
+ get: () => state,
740
+ set(next) {
741
+ if (next === state) return;
742
+ state = next;
743
+ for (const listener of [...listeners]) listener(state);
744
+ },
745
+ subscribe(listener) {
746
+ listeners.add(listener);
747
+ return () => {
748
+ listeners.delete(listener);
749
+ };
750
+ },
751
+ };
752
+ }
753
+
754
+ const STYLE = `
755
+ .dsh-skins { display: flex; flex-direction: column; gap: 16px; }
756
+ .dsh-skins__lead { margin: 0; font-size: 13px; line-height: 1.65; color: var(--dsw-alias-label-secondary); }
757
+ .dsh-skins__card {
758
+ display: flex; flex-direction: column; gap: 12px;
759
+ padding: 16px; border-radius: 12px;
760
+ border: 1px solid var(--dsw-alias-border-l1);
761
+ background: var(--dsw-alias-bg-layer-1);
762
+ }
763
+ .dsh-skins__title { margin: 0; font-size: 14px; font-weight: 600; color: var(--dsw-alias-label-primary); }
764
+ .dsh-skins__grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(148px, 1fr)); gap: 10px; }
765
+ .dsh-skins__tile {
766
+ position: relative; display: flex; flex-direction: column; gap: 8px;
767
+ padding: 10px; border-radius: 10px; cursor: pointer; text-align: left;
768
+ border: 1px solid var(--dsw-alias-border-l1);
769
+ background: var(--dsw-alias-bg-layer-2);
770
+ color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px;
771
+ transition: border-color 160ms ease, box-shadow 160ms ease, transform 160ms ease;
772
+ }
773
+ .dsh-skins__tile:hover { transform: translateY(-1px); border-color: var(--dsw-alias-border-l2); }
774
+ .dsh-skins__tile:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
775
+ .dsh-skins__tile[aria-pressed='true'] {
776
+ border-color: var(--dsw-alias-brand-primary);
777
+ box-shadow: inset 0 0 0 1px var(--dsw-alias-brand-primary);
778
+ }
779
+ .dsh-skins__preview { display: grid; grid-template-columns: 1fr 1fr; gap: 2px; height: 42px; border-radius: 8px; overflow: hidden; }
780
+ .dsh-skins__preview span { display: block; }
781
+ .dsh-skins__row { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
782
+ .dsh-skins__label { font-size: 13px; color: var(--dsw-alias-label-primary); }
783
+ .dsh-skins__hint { font-size: 12px; color: var(--dsw-alias-label-secondary); }
784
+ .dsh-skins__controls { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-width: 0; }
785
+ .dsh-skins__btn {
786
+ position: relative; display: inline-flex; align-items: center; justify-content: center;
787
+ height: 28px; padding: 0 10px; border-radius: 8px; font: inherit; font-size: 12px; cursor: pointer;
788
+ border: 1px solid var(--dsw-alias-border-l2);
789
+ background: var(--dsw-alias-bg-layer-2);
790
+ color: var(--dsw-alias-label-primary);
791
+ user-select: none;
792
+ transition: border-color 160ms ease, background-color 160ms ease, opacity 160ms ease;
793
+ }
794
+ .dsh-skins__btn:hover { border-color: var(--dsw-alias-brand-primary); }
795
+ .dsh-skins__btn:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
796
+ .dsh-skins__btn:focus-within { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
797
+ .dsh-skins__btn[disabled], .dsh-skins__btn[data-busy='true'] { opacity: 0.55; cursor: default; }
798
+ .dsh-skins__file {
799
+ position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; border: 0;
800
+ overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; opacity: 0;
801
+ }
802
+ .dsh-skins__input {
803
+ flex: 1 1 190px; min-width: 0; height: 28px; padding: 0 8px; border-radius: 8px;
804
+ border: 1px solid var(--dsw-alias-border-l2);
805
+ background: var(--dsw-alias-bg-layer-2);
806
+ color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px;
807
+ }
808
+ .dsh-skins__input:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
809
+ .dsh-skins__range { width: 132px; accent-color: var(--dsw-alias-brand-primary); }
810
+ .dsh-skins__seg {
811
+ display: inline-flex; border: 1px solid var(--dsw-alias-border-l2);
812
+ border-radius: 8px; overflow: hidden;
813
+ }
814
+ .dsh-skins__seg-btn {
815
+ height: 26px; padding: 0 10px; border: 0; background: transparent;
816
+ color: var(--dsw-alias-label-secondary); font: inherit; font-size: 12px; cursor: pointer;
817
+ transition: background-color 160ms ease, color 160ms ease;
818
+ }
819
+ .dsh-skins__seg-btn + .dsh-skins__seg-btn { border-left: 1px solid var(--dsw-alias-border-l1); }
820
+ .dsh-skins__seg-btn[aria-pressed='true'] {
821
+ background: var(--dsw-alias-bg-layer-2);
822
+ color: var(--dsw-alias-label-primary);
823
+ font-weight: 500;
824
+ }
825
+ .dsh-skins__seg-btn:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: -2px; }
826
+ .dsh-skins__color {
827
+ width: 44px; height: 26px; padding: 0;
828
+ border: 1px solid var(--dsw-alias-border-l2);
829
+ border-radius: 8px; background: var(--dsw-alias-bg-layer-2); cursor: pointer;
830
+ }
831
+ .dsh-skins__color::-webkit-color-swatch-wrapper { padding: 2px; }
832
+ .dsh-skins__color::-webkit-color-swatch { border: 0; border-radius: 6px; }
833
+ .dsh-skins__color:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
834
+ .dsh-skins__value { font-size: 12px; color: var(--dsw-alias-label-secondary); font-variant-numeric: tabular-nums; min-width: 34px; text-align: right; }
835
+ .dsh-skins__stack { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; }
836
+ .dsh-skins__sliders { display: flex; flex-direction: column; gap: 8px; flex: 1 1 240px; min-width: 0; }
837
+ .dsh-skins__slider-row { display: flex; align-items: center; gap: 8px; }
838
+ .dsh-skins__slider-row .dsh-skins__label { min-width: 76px; }
839
+ .dsh-skins__thumb {
840
+ width: 84px; height: 48px; border-radius: 8px; border: 1px solid var(--dsw-alias-border-l1);
841
+ background-color: var(--dsw-alias-bg-layer-2); background-size: cover; background-position: center;
842
+ }
843
+ .dsh-skins__alert {
844
+ margin: 0; padding: 8px 10px; border-radius: 8px; font-size: 12px;
845
+ border: 1px solid var(--dsw-alias-state-error-primary);
846
+ color: var(--dsw-alias-state-error-primary);
847
+ background: var(--dsw-alias-bg-layer-2);
848
+ }
849
+ .dsh-skins__note { margin: 0; font-size: 12px; color: var(--dsw-alias-label-secondary); }
850
+ `;
851
+
852
+ function apply(ctx) {
853
+ ctx.effect(() => ctx.locale.register(NS, { en: DICT.en, zh: DICT.zh }), 'skins: dictionaries');
854
+ const t = ctx.locale.bind(NS);
855
+
856
+ const store = createStore(loadState());
857
+ let layerOff = null;
858
+ let styleElement = null;
859
+ let persistTimer = null;
860
+
861
+ const scheme = () => {
862
+ const snapshot = ctx.theme.getTheme();
863
+ const active = snapshot === null || snapshot === undefined ? null : snapshot.active;
864
+ return active !== null && active !== undefined && active.colorScheme === 'dark' ? 'dark' : 'light';
865
+ };
866
+
867
+ /** Which way the glass reads for this state: light labels on dark glass, or the reverse. */
868
+ const directionOf = (state) => resolveDirection(state.shade, state.luminance, scheme());
869
+
870
+ /**
871
+ * Backdrop layers — the modal mask and the panel surface sitting on it — get a
872
+ * frosted fill. Detecting the backdrop (a viewport-sized layer that already
873
+ * paints a scrim) turned out to be far more reliable than guessing which
874
+ * element is "the panel": the settings panel can be nearly viewport-sized.
875
+ */
876
+ const BACKDROP_ATTR = 'data-dsh-skins-backdrop';
877
+ let scanTimer = null;
878
+ let lastScanAt = 0;
879
+ /**
880
+ * Markers are sticky: once a layer is frosted it keeps the frost until it leaves
881
+ * the document. A modal reveals itself with an opacity/scale animation, so a
882
+ * fresh match each scan would add and drop the blur frame by frame — the
883
+ * "shimmering between see-through and blurred" this replaced.
884
+ */
885
+ const markedBackdrops = new Set();
886
+
887
+ const stripBackdrops = () => {
888
+ for (const element of document.querySelectorAll(`[${BACKDROP_ATTR}]`)) {
889
+ element.removeAttribute(BACKDROP_ATTR);
890
+ }
891
+ markedBackdrops.clear();
892
+ };
893
+
894
+ /** Alpha of a computed CSS colour; `1` when it cannot be parsed. */
895
+ const colorAlpha = (color) => {
896
+ const match = /^rgba?\(([^)]+)\)$/i.exec(String(color).trim());
897
+ if (match === null) return 1;
898
+ const parts = match[1].split(',').map((part) => part.trim());
899
+ return parts.length >= 4 ? Number(parts[3]) : 1;
900
+ };
901
+
902
+ /**
903
+ * A backdrop: fixed or absolute, covering at least 90% of the viewport in both
904
+ * directions, still taking pointer events, and already painting some scrim of
905
+ * its own. That excludes app shells (transparent), toast regions (no pointer
906
+ * events), and ordinary panels that are smaller than the window.
907
+ */
908
+ const looksLikeBackdrop = (element) => {
909
+ if (!(element instanceof HTMLElement)) return false;
910
+ const style = getComputedStyle(element);
911
+ if (style.position !== 'fixed' && style.position !== 'absolute') return false;
912
+ if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') return false;
913
+ if (style.pointerEvents === 'none') return false;
914
+ const rect = element.getBoundingClientRect();
915
+ if (rect.width < window.innerWidth * 0.9 || rect.height < window.innerHeight * 0.9) return false;
916
+ return colorAlpha(style.backgroundColor) > 0.05;
917
+ };
918
+
919
+ /** Collect a portal root and two levels below it, where masks and panels sit. */
920
+ const collectCandidates = (root, depth, out) => {
921
+ if (depth > 2) return;
922
+ for (const child of root.children) {
923
+ out.push(child);
924
+ collectCandidates(child, depth + 1, out);
925
+ }
926
+ };
927
+
928
+ /**
929
+ * Frost at most the largest backdrop of each portal: two stacked frosting layers
930
+ * would double the veil, and a second layer arriving a frame later reads as a jump.
931
+ */
932
+ const scanBackdrops = () => {
933
+ if (styleElement === null) return;
934
+ if (store.get().wallpaper === null) {
935
+ stripBackdrops();
936
+ return;
937
+ }
938
+ for (const element of [...markedBackdrops]) {
939
+ if (element.isConnected) continue;
940
+ element.removeAttribute(BACKDROP_ATTR);
941
+ markedBackdrops.delete(element);
942
+ }
943
+ for (const root of document.body.children) {
944
+ if (root.id === 'root' || root === styleElement) continue;
945
+ const nodes = [root];
946
+ collectCandidates(root, 1, nodes);
947
+ let best = null;
948
+ let bestArea = 0;
949
+ for (const element of nodes) {
950
+ if (!looksLikeBackdrop(element)) continue;
951
+ const rect = element.getBoundingClientRect();
952
+ const area = rect.width * rect.height;
953
+ if (area <= bestArea) continue;
954
+ bestArea = area;
955
+ best = element;
956
+ }
957
+ if (best === null) continue;
958
+ if (!best.hasAttribute(BACKDROP_ATTR)) best.setAttribute(BACKDROP_ATTR, '');
959
+ markedBackdrops.add(best);
960
+ }
961
+ };
962
+
963
+ /**
964
+ * Scans are throttled, but the first one after an idle period runs immediately so
965
+ * a modal that just opened is frosted on its first frame instead of 180ms later.
966
+ */
967
+ const scheduleScan = () => {
968
+ if (scanTimer !== null) return;
969
+ const idle = performance.now() - lastScanAt > 500;
970
+ scanTimer = setTimeout(
971
+ () => {
972
+ scanTimer = null;
973
+ lastScanAt = performance.now();
974
+ scanBackdrops();
975
+ },
976
+ idle ? 0 : 150,
977
+ );
978
+ };
979
+
980
+ /**
981
+ * Rewrite the wallpaper stylesheet. The scrim follows the text colour, text
982
+ * over the image gets a matching halo, and every open backdrop layer becomes a
983
+ * frosted surface so Settings cannot blend into the page behind it.
984
+ */
985
+ const paint = (state) => {
986
+ if (styleElement === null) return;
987
+ const wallpaper = state.wallpaper;
988
+ if (wallpaper === null) {
989
+ styleElement.textContent = '';
990
+ stripBackdrops();
991
+ return;
992
+ }
993
+ const direction = directionOf(state);
994
+ const text = resolveTextColors(state, direction);
995
+ const primaryLuminance = hexLuminance(text.primary);
996
+ // The scrim and halo answer to the text colour, the frost to the glass shade.
997
+ const lightText = primaryLuminance === null ? direction === 'lightText' : primaryLuminance > 0.55;
998
+ const glassDark = direction === 'lightText';
999
+ const dim = clamp(state.dim, 0, 0.85);
1000
+ const tint = lightText ? '0, 0, 0' : '255, 255, 255';
1001
+ const halo = lightText
1002
+ ? '0 1px 2px rgba(0, 0, 0, 0.5), 0 0 10px rgba(0, 0, 0, 0.22)'
1003
+ : '0 1px 2px rgba(255, 255, 255, 0.55), 0 0 10px rgba(255, 255, 255, 0.3)';
1004
+ // A veil, not a paint-over: enough fill to calm the page behind a modal,
1005
+ // low enough that the app is still recognisable through the blur. The user
1006
+ // can dial it down to zero and keep only the blur.
1007
+ const veil = clamp(state.veil, 0, 0.9);
1008
+ const frost = glassDark ? `rgba(14, 18, 22, ${veil})` : `rgba(250, 250, 251, ${veil})`;
1009
+ styleElement.textContent = `
1010
+ html, body {
1011
+ background-image: linear-gradient(rgba(${tint}, ${dim}), rgba(${tint}, ${dim})), url("${cssUrl(wallpaper.value)}") !important;
1012
+ background-size: cover !important;
1013
+ background-position: center !important;
1014
+ background-repeat: no-repeat !important;
1015
+ background-attachment: fixed !important;
1016
+ }
1017
+ body { text-shadow: ${halo}; }
1018
+ [${BACKDROP_ATTR}] {
1019
+ background-color: ${frost} !important;
1020
+ backdrop-filter: blur(22px) saturate(1.06);
1021
+ transition: background-color 200ms ease, backdrop-filter 200ms ease;
1022
+ }
1023
+ [${BACKDROP_ATTR}], [${BACKDROP_ATTR}] * { text-shadow: none; }
1024
+ /*
1025
+ * A fullscreen right panel hangs over the centre column, and the panel paints
1026
+ * the canvas colour we made transparent — so the conversation and its composer
1027
+ * would read straight through it. Hide the column underneath instead of
1028
+ * painting over it: the frame marks the mode, the column class carries the
1029
+ * stable "centerCol" suffix, and visibility keeps DOM, drafts and scroll.
1030
+ */
1031
+ [data-rightbar-fullscreen] [class*='_centerCol'] {
1032
+ visibility: hidden;
1033
+ }
1034
+ `;
1035
+ scheduleScan();
1036
+ };
1037
+
1038
+ const applyLayer = (state) => {
1039
+ if (layerOff !== null) {
1040
+ layerOff();
1041
+ layerOff = null;
1042
+ }
1043
+ const direction = directionOf(state);
1044
+ const tokens = buildTokens(
1045
+ findSkin(state.skin),
1046
+ state.wallpaper !== null,
1047
+ state.panel,
1048
+ direction,
1049
+ resolveTextColors(state, direction),
1050
+ );
1051
+ if (tokens === null) return;
1052
+ layerOff = ctx.theme.overrideTokens('dsh-skins', tokens);
1053
+ };
1054
+
1055
+ const applyAll = (state) => {
1056
+ applyLayer(state);
1057
+ paint(state);
1058
+ };
1059
+
1060
+ /**
1061
+ * Slider drags repaint the wallpaper immediately but rebuild the token layer
1062
+ * only once the drag pauses, so a gesture does not restack the layer per pixel.
1063
+ */
1064
+ let layerTimer = null;
1065
+ const scheduleLayer = () => {
1066
+ if (layerTimer !== null) clearTimeout(layerTimer);
1067
+ layerTimer = setTimeout(() => {
1068
+ layerTimer = null;
1069
+ applyLayer(store.get());
1070
+ }, 120);
1071
+ };
1072
+
1073
+ const persistSoon = (state) => {
1074
+ if (persistTimer !== null) clearTimeout(persistTimer);
1075
+ persistTimer = setTimeout(() => {
1076
+ persistTimer = null;
1077
+ saveState(state);
1078
+ }, 320);
1079
+ };
1080
+
1081
+ /**
1082
+ * Commit one change. Wallpaper changes persist immediately so a full storage
1083
+ * quota is reported instead of silently lost; slider drags defer the write.
1084
+ * Returns whether the change was stored.
1085
+ */
1086
+ const commit = (patch, options) => {
1087
+ const previous = store.get();
1088
+ const next = { ...previous, ...patch };
1089
+ const defer = options !== undefined && options.deferPersist === true;
1090
+ if (!defer && !saveState(next)) {
1091
+ store.set({ ...previous, message: 'storageFull' });
1092
+ return false;
1093
+ }
1094
+ store.set(next);
1095
+ if (options !== undefined && options.layer === false) {
1096
+ paint(next);
1097
+ if (options.rebuildLayer === true) scheduleLayer();
1098
+ } else {
1099
+ applyAll(next);
1100
+ }
1101
+ if (defer) persistSoon(next);
1102
+ return true;
1103
+ };
1104
+
1105
+ /** One live object URL for the stored wallpaper; older ones are revoked. */
1106
+ let wallpaperUrl = null;
1107
+
1108
+ const releaseWallpaperUrl = () => {
1109
+ if (wallpaperUrl !== null) {
1110
+ URL.revokeObjectURL(wallpaperUrl);
1111
+ wallpaperUrl = null;
1112
+ }
1113
+ };
1114
+
1115
+ /** Show a stored Blob, then measure it so the glass direction fits the new image. */
1116
+ const applyWallpaperBlob = (blob) => {
1117
+ releaseWallpaperUrl();
1118
+ wallpaperUrl = URL.createObjectURL(blob);
1119
+ const url = wallpaperUrl;
1120
+ // A different image invalidates the previous brightness reading.
1121
+ const next = {
1122
+ ...store.get(),
1123
+ wallpaper: { kind: 'blob', value: url },
1124
+ wallpaperPending: false,
1125
+ luminance: null,
1126
+ };
1127
+ store.set(next);
1128
+ applyAll(next);
1129
+ saveState(next);
1130
+ void measureLuminance(url).then((luminance) => {
1131
+ if (luminance === null) return;
1132
+ const current = store.get();
1133
+ if (current.wallpaper === null || current.wallpaper.value !== url) return;
1134
+ commit({ luminance }, { deferPersist: true });
1135
+ });
1136
+ };
1137
+
1138
+ /**
1139
+ * Wallpaper pixels live in IndexedDB, so they arrive after the first paint. Read
1140
+ * them once, or migrate a legacy inline data URL out of localStorage first.
1141
+ */
1142
+ const hydrateWallpaper = async () => {
1143
+ const initial = store.get();
1144
+ if (initial.wallpaper !== null && initial.wallpaper.kind !== 'data' && !initial.wallpaperPending) return;
1145
+ try {
1146
+ if (initial.wallpaper !== null && initial.wallpaper.kind === 'data') {
1147
+ const response = await fetch(initial.wallpaper.value);
1148
+ const blob = await response.blob();
1149
+ if (blob.size > 0) {
1150
+ await writeWallpaperBlob(blob);
1151
+ applyWallpaperBlob(blob);
1152
+ return;
1153
+ }
1154
+ store.set({ ...store.get(), wallpaper: null, message: null });
1155
+ saveState(store.get());
1156
+ return;
1157
+ }
1158
+ if (!initial.wallpaperPending) return;
1159
+ const blob = await readWallpaperBlob();
1160
+ if (blob instanceof Blob && blob.size > 0) {
1161
+ applyWallpaperBlob(blob);
1162
+ return;
1163
+ }
1164
+ // The flag promised pixels that are gone; drop it so the UI stops waiting.
1165
+ const cleared = { ...store.get(), wallpaper: null, wallpaperPending: false };
1166
+ store.set(cleared);
1167
+ saveState(cleared);
1168
+ } catch (error) {
1169
+ store.set({ ...store.get(), message: 'storageUnavailable' });
1170
+ }
1171
+ };
1172
+
1173
+ // Our own layer rebuilds also emit theme/change, so only an actual light/dark
1174
+ // switch may rebuild the layer; every emission still repaints the stylesheet.
1175
+ let lastScheme = scheme();
1176
+ ctx.effect(
1177
+ () =>
1178
+ ctx.on('theme/change', () => {
1179
+ const next = scheme();
1180
+ const switched = next !== lastScheme;
1181
+ lastScheme = next;
1182
+ paint(store.get());
1183
+ if (switched) applyLayer(store.get());
1184
+ }),
1185
+ 'skins: scheme follow',
1186
+ );
1187
+
1188
+ /**
1189
+ * A wallpaper saved before the text mode existed has no brightness reading.
1190
+ * Measure it once at boot so the glass direction follows the image.
1191
+ */
1192
+ const backfillLuminance = () => {
1193
+ const state = store.get();
1194
+ if (state.wallpaper === null || state.luminance !== null) return;
1195
+ const source = state.wallpaper.value;
1196
+ void measureLuminance(source).then((luminance) => {
1197
+ if (luminance === null) return;
1198
+ const current = store.get();
1199
+ if (current.wallpaper === null || current.wallpaper.value !== source) return;
1200
+ commit({ luminance }, { deferPersist: true });
1201
+ });
1202
+ };
1203
+
1204
+ ctx.effect(() => {
1205
+ const element = document.createElement('style');
1206
+ element.setAttribute('data-dsh-skins', 'wallpaper');
1207
+ document.head.appendChild(element);
1208
+ styleElement = element;
1209
+ applyAll(store.get());
1210
+ backfillLuminance();
1211
+ void hydrateWallpaper();
1212
+ return () => {
1213
+ element.remove();
1214
+ styleElement = null;
1215
+ releaseWallpaperUrl();
1216
+ if (persistTimer !== null) {
1217
+ clearTimeout(persistTimer);
1218
+ persistTimer = null;
1219
+ }
1220
+ if (layerTimer !== null) {
1221
+ clearTimeout(layerTimer);
1222
+ layerTimer = null;
1223
+ }
1224
+ if (layerOff !== null) {
1225
+ layerOff();
1226
+ layerOff = null;
1227
+ }
1228
+ if (scanTimer !== null) {
1229
+ clearTimeout(scanTimer);
1230
+ scanTimer = null;
1231
+ }
1232
+ stripBackdrops();
1233
+ };
1234
+ }, 'skins: wallpaper stylesheet');
1235
+
1236
+ /**
1237
+ * Backdrop layers open and close as portals appended beside `#root`, so the
1238
+ * scan follows document mutations rather than only mount time. Scans are
1239
+ * throttled (first one after idle runs at once), and markings are sticky, so a
1240
+ * modal's reveal animation cannot add and drop the frost frame by frame.
1241
+ */
1242
+ ctx.effect(() => {
1243
+ if (typeof MutationObserver !== 'function') return undefined;
1244
+ const observer = new MutationObserver(() => {
1245
+ if (store.get().wallpaper !== null) scheduleScan();
1246
+ });
1247
+ observer.observe(document.body, {
1248
+ childList: true,
1249
+ subtree: true,
1250
+ attributes: true,
1251
+ attributeFilter: ['style', 'class', 'hidden', 'aria-hidden'],
1252
+ });
1253
+ return () => observer.disconnect();
1254
+ }, 'skins: overlay observer');
1255
+
1256
+ function SkinIcon(props) {
1257
+ const size = typeof props.size === 'number' && props.size > 0 ? props.size : 18;
1258
+ return h(
1259
+ 'svg',
1260
+ { viewBox: '0 0 16 16', width: size, height: size, fill: 'none', 'aria-hidden': true, focusable: false },
1261
+ h('rect', {
1262
+ x: 1.6,
1263
+ y: 1.6,
1264
+ width: 12.8,
1265
+ height: 12.8,
1266
+ rx: 3.4,
1267
+ stroke: 'currentColor',
1268
+ strokeWidth: 1.3,
1269
+ }),
1270
+ h('circle', { cx: 5.6, cy: 5.6, r: 1.45, fill: 'currentColor' }),
1271
+ h('path', {
1272
+ d: 'M2.4 11.4l3.3-3.2a1.5 1.5 0 0 1 2.1 0l1.6 1.6 1.4-1.3a1.5 1.5 0 0 1 2 0l1.2 1.1',
1273
+ stroke: 'currentColor',
1274
+ strokeWidth: 1.3,
1275
+ strokeLinecap: 'round',
1276
+ strokeLinejoin: 'round',
1277
+ }),
1278
+ );
1279
+ }
1280
+
1281
+ function skinLabel(skin) {
1282
+ if (typeof skin.label === 'string') return t(skin.label);
1283
+ const active = ctx.locale.getSnapshot().active;
1284
+ return active.startsWith('zh') ? skin.label.zh : skin.label.en;
1285
+ }
1286
+
1287
+ function SkinsSection() {
1288
+ const [state, setState] = React.useState(() => store.get());
1289
+ const [url, setUrl] = React.useState('');
1290
+ const [busy, setBusy] = React.useState(false);
1291
+ const [, setLocaleRevision] = React.useState(0);
1292
+ React.useEffect(() => store.subscribe(setState), []);
1293
+ React.useEffect(() => ctx.locale.subscribe(() => setLocaleRevision((value) => value + 1)), []);
1294
+
1295
+ const wallpaper = state.wallpaper;
1296
+
1297
+ const chooseFile = async (event) => {
1298
+ const input = event.currentTarget;
1299
+ const list = input.files;
1300
+ const file = list !== null && list !== undefined && list.length > 0 ? list[0] : null;
1301
+ input.value = '';
1302
+ if (file === null) return;
1303
+ setBusy(true);
1304
+ try {
1305
+ const prepared = await prepareWallpaper(file);
1306
+ await writeWallpaperBlob(prepared.blob);
1307
+ releaseWallpaperUrl();
1308
+ applyWallpaperBlob(prepared.blob);
1309
+ setUrl('');
1310
+ } catch (error) {
1311
+ const code = error !== null && error !== undefined ? String(error.message ?? '') : '';
1312
+ const quota = error !== null && error !== undefined && error.name === 'QuotaExceededError';
1313
+ let reason = 'readFailed';
1314
+ if (quota || code === 'storageFull') reason = 'storageFull';
1315
+ else if (code === 'tooLarge') reason = 'tooLarge';
1316
+ else if (code === 'decodeFailed') reason = 'decodeFailed';
1317
+ else if (code === 'storageUnavailable') reason = 'storageUnavailable';
1318
+ commit({ message: reason });
1319
+ } finally {
1320
+ setBusy(false);
1321
+ }
1322
+ };
1323
+
1324
+ const applyUrl = () => {
1325
+ const value = url.trim();
1326
+ if (value === '') return;
1327
+ const looksLikePath =
1328
+ /^[a-zA-Z]:[\\/]/.test(value) || /^\\\\/.test(value) || /^file:/i.test(value) || /^\/(?!\/)/.test(value);
1329
+ if (looksLikePath) {
1330
+ commit({ message: 'localPath' });
1331
+ return;
1332
+ }
1333
+ if (!isImageSource(value)) {
1334
+ commit({ message: 'invalidUrl' });
1335
+ return;
1336
+ }
1337
+ // A remote URL replaces any stored blob, so release both the object URL and
1338
+ // the IndexedDB record before committing the new source.
1339
+ releaseWallpaperUrl();
1340
+ void deleteWallpaperBlob().catch(() => {});
1341
+ // Remote images without CORS cannot be measured; the auto mode then follows
1342
+ // the appearance scheme until a measurable image arrives.
1343
+ if (commit({ wallpaper: { kind: 'url', value }, wallpaperPending: false, luminance: null, message: null })) {
1344
+ setUrl('');
1345
+ void measureLuminance(value).then((luminance) => {
1346
+ const current = store.get();
1347
+ if (luminance === null) return;
1348
+ if (current.wallpaper === null || current.wallpaper.value !== value) return;
1349
+ commit({ luminance }, { deferPersist: true });
1350
+ });
1351
+ }
1352
+ };
1353
+
1354
+ return h(
1355
+ React.Fragment,
1356
+ null,
1357
+ h('style', { key: 'style' }, STYLE),
1358
+ h(
1359
+ 'div',
1360
+ { key: 'page', className: 'dsh-skins' },
1361
+ h('p', { key: 'lead', className: 'dsh-skins__lead' }, t('lead')),
1362
+ h(
1363
+ 'section',
1364
+ { key: 'palettes', className: 'dsh-skins__card' },
1365
+ h('h3', { key: 'title', className: 'dsh-skins__title' }, t('palettes')),
1366
+ h(
1367
+ 'div',
1368
+ { key: 'grid', className: 'dsh-skins__grid' },
1369
+ SKINS.map((entry) => {
1370
+ const selected = entry.id === findSkin(state.skin).id;
1371
+ const lightPalette = entry.light;
1372
+ const darkPalette = entry.dark;
1373
+ return h(
1374
+ 'button',
1375
+ {
1376
+ key: entry.id,
1377
+ type: 'button',
1378
+ className: 'dsh-skins__tile',
1379
+ 'aria-pressed': selected,
1380
+ onClick: () => commit({ skin: entry.id, message: null }),
1381
+ },
1382
+ h(
1383
+ 'span',
1384
+ { key: 'preview', className: 'dsh-skins__preview', 'aria-hidden': true },
1385
+ h('span', {
1386
+ style: { background: lightPalette === null ? 'var(--dsw-alias-bg-layer-2)' : lightPalette.base },
1387
+ }),
1388
+ h('span', {
1389
+ style: { background: lightPalette === null ? 'var(--dsw-alias-border-l1)' : lightPalette.brand },
1390
+ }),
1391
+ h('span', {
1392
+ style: { background: darkPalette === null ? 'var(--dsw-alias-bg-base)' : darkPalette.base },
1393
+ }),
1394
+ h('span', {
1395
+ style: {
1396
+ background: darkPalette === null ? 'var(--dsw-alias-brand-primary)' : darkPalette.brand,
1397
+ },
1398
+ }),
1399
+ ),
1400
+ h('span', { key: 'label' }, skinLabel(entry)),
1401
+ selected ? h('span', { key: 'mark', className: 'dsh-skins__hint' }, t('selected')) : null,
1402
+ );
1403
+ }),
1404
+ ),
1405
+ ),
1406
+ h(
1407
+ 'section',
1408
+ { key: 'wallpaper', className: 'dsh-skins__card' },
1409
+ h('h3', { key: 'title', className: 'dsh-skins__title' }, t('wallpaper')),
1410
+ h('p', { key: 'hint', className: 'dsh-skins__hint' }, t('wallpaperHint')),
1411
+ h(
1412
+ 'div',
1413
+ { key: 'actions', className: 'dsh-skins__controls' },
1414
+ h(
1415
+ 'label',
1416
+ { key: 'choose', className: 'dsh-skins__btn', 'data-busy': busy ? 'true' : 'false' },
1417
+ busy ? t('processing') : t('choose'),
1418
+ h('input', {
1419
+ type: 'file',
1420
+ accept: 'image/*',
1421
+ className: 'dsh-skins__file',
1422
+ onChange: chooseFile,
1423
+ }),
1424
+ ),
1425
+ h('input', {
1426
+ key: 'url',
1427
+ type: 'text',
1428
+ className: 'dsh-skins__input',
1429
+ placeholder: t('urlPlaceholder'),
1430
+ value: url,
1431
+ onChange: (event) => setUrl(event.target.value),
1432
+ onKeyDown: (event) => {
1433
+ if (event.key === 'Enter') applyUrl();
1434
+ },
1435
+ }),
1436
+ h(
1437
+ 'button',
1438
+ {
1439
+ key: 'apply',
1440
+ type: 'button',
1441
+ className: 'dsh-skins__btn',
1442
+ disabled: busy || url.trim() === '',
1443
+ onClick: applyUrl,
1444
+ },
1445
+ t('applyUrl'),
1446
+ ),
1447
+ wallpaper !== null
1448
+ ? h(
1449
+ 'button',
1450
+ {
1451
+ key: 'remove',
1452
+ type: 'button',
1453
+ className: 'dsh-skins__btn',
1454
+ onClick: () => {
1455
+ releaseWallpaperUrl();
1456
+ void deleteWallpaperBlob().catch(() => {});
1457
+ commit({ wallpaper: null, wallpaperPending: false, luminance: null, message: null });
1458
+ },
1459
+ },
1460
+ t('remove'),
1461
+ )
1462
+ : null,
1463
+ ),
1464
+ wallpaper !== null
1465
+ ? h(
1466
+ 'div',
1467
+ { key: 'current', className: 'dsh-skins__stack' },
1468
+ h('span', {
1469
+ className: 'dsh-skins__thumb',
1470
+ style: { backgroundImage: `url("${cssUrl(wallpaper.value)}")` },
1471
+ title: t('preview'),
1472
+ }),
1473
+ h(
1474
+ 'div',
1475
+ { key: 'sliders', className: 'dsh-skins__sliders' },
1476
+ h(
1477
+ 'div',
1478
+ { key: 'dim', className: 'dsh-skins__slider-row' },
1479
+ h('span', { className: 'dsh-skins__label' }, t('dim')),
1480
+ h('input', {
1481
+ type: 'range',
1482
+ className: 'dsh-skins__range',
1483
+ min: 0,
1484
+ max: 85,
1485
+ step: 1,
1486
+ value: Math.round(state.dim * 100),
1487
+ 'aria-label': t('dim'),
1488
+ onChange: (event) =>
1489
+ commit(
1490
+ { dim: clamp(Number(event.target.value) / 100, 0, 0.85) },
1491
+ { deferPersist: true, layer: false },
1492
+ ),
1493
+ }),
1494
+ h('span', { className: 'dsh-skins__value' }, Math.round(state.dim * 100) + '%'),
1495
+ ),
1496
+ h(
1497
+ 'div',
1498
+ { key: 'panel', className: 'dsh-skins__slider-row' },
1499
+ h('span', { className: 'dsh-skins__label' }, t('panel')),
1500
+ h('input', {
1501
+ type: 'range',
1502
+ className: 'dsh-skins__range',
1503
+ min: 0,
1504
+ max: 95,
1505
+ step: 1,
1506
+ value: Math.round(state.panel * 100),
1507
+ 'aria-label': t('panel'),
1508
+ onChange: (event) =>
1509
+ commit(
1510
+ { panel: clamp(Number(event.target.value) / 100, 0, MAX_PANEL) },
1511
+ { deferPersist: true, layer: false, rebuildLayer: true },
1512
+ ),
1513
+ }),
1514
+ h('span', { className: 'dsh-skins__value' }, Math.round(state.panel * 100) + '%'),
1515
+ ),
1516
+ h(
1517
+ 'div',
1518
+ { key: 'veil', className: 'dsh-skins__slider-row' },
1519
+ h('span', { className: 'dsh-skins__label' }, t('veil')),
1520
+ h('input', {
1521
+ type: 'range',
1522
+ className: 'dsh-skins__range',
1523
+ min: 0,
1524
+ max: 90,
1525
+ step: 1,
1526
+ value: Math.round(state.veil * 100),
1527
+ 'aria-label': t('veil'),
1528
+ onChange: (event) =>
1529
+ commit(
1530
+ { veil: clamp(Number(event.target.value) / 100, 0, 0.9) },
1531
+ { deferPersist: true, layer: false },
1532
+ ),
1533
+ }),
1534
+ h('span', { className: 'dsh-skins__value' }, Math.round(state.veil * 100) + '%'),
1535
+ ),
1536
+ h(
1537
+ 'div',
1538
+ { key: 'shade', className: 'dsh-skins__slider-row' },
1539
+ h('span', { className: 'dsh-skins__label' }, t('panelShade')),
1540
+ h(
1541
+ 'div',
1542
+ { className: 'dsh-skins__seg', role: 'group', 'aria-label': t('panelShade') },
1543
+ [
1544
+ ['auto', 'auto'],
1545
+ ['dark', 'darkGlass'],
1546
+ ['light', 'lightGlass'],
1547
+ ].map(([value, label]) =>
1548
+ h(
1549
+ 'button',
1550
+ {
1551
+ key: value,
1552
+ type: 'button',
1553
+ className: 'dsh-skins__seg-btn',
1554
+ 'aria-pressed': state.shade === value,
1555
+ onClick: () => commit({ shade: value }),
1556
+ },
1557
+ t(label),
1558
+ ),
1559
+ ),
1560
+ ),
1561
+ ),
1562
+ h(
1563
+ 'div',
1564
+ { key: 'textTheme', className: 'dsh-skins__slider-row' },
1565
+ h('span', { className: 'dsh-skins__label' }, t('textTheme')),
1566
+ h(
1567
+ 'div',
1568
+ { className: 'dsh-skins__seg', role: 'group', 'aria-label': t('textTheme') },
1569
+ [
1570
+ ['auto', 'auto'],
1571
+ ['contrast', 'contrast'],
1572
+ ['soft', 'soft'],
1573
+ ['custom', 'custom'],
1574
+ ].map(([value, label]) =>
1575
+ h(
1576
+ 'button',
1577
+ {
1578
+ key: value,
1579
+ type: 'button',
1580
+ className: 'dsh-skins__seg-btn',
1581
+ 'aria-pressed': state.textTheme === value,
1582
+ onClick: () => commit({ textTheme: value }),
1583
+ },
1584
+ t(label),
1585
+ ),
1586
+ ),
1587
+ ),
1588
+ ),
1589
+ state.textTheme === 'custom'
1590
+ ? h(
1591
+ 'div',
1592
+ { key: 'custom-colors', className: 'dsh-skins__slider-row' },
1593
+ h('span', { className: 'dsh-skins__label' }, t('primaryText')),
1594
+ h('input', {
1595
+ type: 'color',
1596
+ className: 'dsh-skins__color',
1597
+ 'aria-label': t('primaryText'),
1598
+ value: resolveTextColors(state, directionOf(state)).primary,
1599
+ onChange: (event) =>
1600
+ commit(
1601
+ { textPrimary: event.target.value },
1602
+ { deferPersist: true, layer: false, rebuildLayer: true },
1603
+ ),
1604
+ }),
1605
+ h('span', { className: 'dsh-skins__label' }, t('mutedText')),
1606
+ h('input', {
1607
+ type: 'color',
1608
+ className: 'dsh-skins__color',
1609
+ 'aria-label': t('mutedText'),
1610
+ value: resolveTextColors(state, directionOf(state)).muted,
1611
+ onChange: (event) =>
1612
+ commit(
1613
+ { textMuted: event.target.value },
1614
+ { deferPersist: true, layer: false, rebuildLayer: true },
1615
+ ),
1616
+ }),
1617
+ )
1618
+ : null,
1619
+ ),
1620
+ )
1621
+ : null,
1622
+ state.message !== null
1623
+ ? h('p', { key: 'alert', className: 'dsh-skins__alert', role: 'alert' }, t(state.message))
1624
+ : null,
1625
+ ),
1626
+ h('p', { key: 'note', className: 'dsh-skins__note' }, t('note')),
1627
+ ),
1628
+ );
1629
+ }
1630
+
1631
+ ctx.slots.inject('settings.section', () =>
1632
+ ctx.slots.register(
1633
+ { name: 'settings.section', id: 'skins', order: 5, label: () => t('section') },
1634
+ SkinsSection,
1635
+ ),
1636
+ );
1637
+
1638
+ ctx.slots.inject('settings.section.icon', () =>
1639
+ ctx.slots.register({ name: 'settings.section.icon', id: 'skins' }, SkinIcon),
1640
+ );
1641
+ }
1642
+
1643
+ return {
1644
+ inject: ['slots', 'locale', 'theme'],
1645
+ apply,
1646
+ };
1647
+ },
1648
+ });