@eum-agent/personalization 1.0.0 → 1.2.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/ui/ui.js CHANGED
@@ -1,6 +1,6 @@
1
- import { Dialog, DialogContent, DialogHeader, DialogTitle, FALLBACK_LANGUAGE, LANGUAGES, LANGUAGE_FLAGS, Picker, Segmented, SlotOutlet, ThemeColorPicker, i18next, localeLeaves, themeSwatchColor, useTranslation } from "@eum-agent/host/framework";
2
- import React, { useId } from "react";
3
- import { jsx, jsxs } from "react/jsx-runtime";
1
+ import { AlertDialog, Button, ColorPicker, Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, FALLBACK_LANGUAGE, Field, FontPicker, Input, InputNumber, LANGUAGES, LANGUAGE_FLAGS, PLUGIN_ICONS, Picker, Segmented, Select, SettingsPreview, SlotOutlet, cn, colorToHex, contributionsIn, i18next, localeLeaves, notifyReadingLayout, parseColorHex, readableForeground, resolveLabel, useDeviceFonts, usePlugins, useTranslation } from "@eum-agent/host/framework";
2
+ import React, { createContext, createElement, forwardRef, useCallback, useContext, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from "react";
3
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
4
  //#region ui-src/i18n.ts
5
5
  /** Platform browser strings share the host's language and React translation runtime. */
6
6
  var translations;
@@ -30,7 +30,40 @@ var en_US_default = {
30
30
  "contentWidthDefault": "Default",
31
31
  "contentWidthWide": "Wide",
32
32
  "contentWidthFull": "Full",
33
- "interfaceLanguage": "Interface language"
33
+ "interfaceLanguage": "Interface language",
34
+ "interfaceCategory": "Interface",
35
+ "readingCategory": "Reading",
36
+ "personalizationCategories": "Personalization categories",
37
+ "personalizationEmpty": "No personalization settings are available",
38
+ "preview": "Preview",
39
+ "previewInfo": "Preview information",
40
+ "previewReading": "Reading text",
41
+ "previewDescription": "This fixed sample updates with your font and size choices, using system fallbacks for missing fonts. It previews typography only; content width applies to actual reading surfaces. It sends no messages and runs no commands.",
42
+ "resetCategory": "Reset to defaults",
43
+ "theme": "Theme",
44
+ "themeHint": "One palette: surfaces, text, borders and the accent, in both light and dark. Editing any of them makes it a custom theme.",
45
+ "themeNeutral": "Neutral",
46
+ "themeCool": "Cool",
47
+ "themeWarm": "Warm",
48
+ "themeCustom": "Custom",
49
+ "themeBackground": "Background",
50
+ "themeForeground": "Text",
51
+ "themeBrand": "Accent",
52
+ "themeEdit": "Edit {{name}} theme",
53
+ "themeBack": "Back to themes",
54
+ "themeEditor": "Edit theme",
55
+ "themePreview": "Theme preview",
56
+ "themePreviewMode": "Preview mode",
57
+ "themePreviewHint": "This illustration previews colors without changing the current theme.",
58
+ "themeCancel": "Cancel",
59
+ "themePickColor": "Choose {{name}} color",
60
+ "themeSave": "Save",
61
+ "themeDiscardTitle": "Discard theme changes?",
62
+ "themeKeepEditing": "Keep editing",
63
+ "themeDiscard": "Discard changes",
64
+ "themeDiscardHint": "Unsaved colors will be lost. Your current theme stays unchanged.",
65
+ "themeInvalidColor": "Enter a valid opaque hexadecimal color, such as #2563eb.",
66
+ "themeSaveError": "Could not save. Your current theme is unchanged. Retry or check browser storage permissions."
34
67
  },
35
68
  brand: {
36
69
  "violet": "Violet",
@@ -58,7 +91,40 @@ var zh_CN_default = {
58
91
  "contentWidthDefault": "默认",
59
92
  "contentWidthWide": "宽屏",
60
93
  "contentWidthFull": "全宽",
61
- "interfaceLanguage": "界面语言"
94
+ "interfaceLanguage": "界面语言",
95
+ "interfaceCategory": "界面",
96
+ "readingCategory": "阅读",
97
+ "personalizationCategories": "个性化分类",
98
+ "personalizationEmpty": "暂无可用的个性化设置",
99
+ "preview": "预览",
100
+ "previewInfo": "预览说明",
101
+ "previewReading": "阅读文本",
102
+ "previewDescription": "固定示例会随字体与字号即时更新,字体缺失时使用系统回退。阅读示例仅预览字体与字号;内容宽度作用于实际阅读区域。不会发送消息或执行命令。",
103
+ "resetCategory": "恢复默认",
104
+ "theme": "主题",
105
+ "themeHint": "一套配色方案:表面、文字、边界与品牌色,浅色与深色各一套。改任何一项就成为自定义主题。",
106
+ "themeNeutral": "中性",
107
+ "themeCool": "冷调",
108
+ "themeWarm": "暖调",
109
+ "themeCustom": "自定义",
110
+ "themeBackground": "背景",
111
+ "themeForeground": "正文",
112
+ "themeBrand": "品牌色",
113
+ "themeEdit": "编辑{{name}}主题",
114
+ "themeBack": "返回主题",
115
+ "themeEditor": "编辑主题",
116
+ "themePreview": "主题预览",
117
+ "themePreviewMode": "预览模式",
118
+ "themePreviewHint": "示意图仅预览配色,不会更改当前主题。",
119
+ "themeCancel": "取消",
120
+ "themePickColor": "选择{{name}}颜色",
121
+ "themeSave": "保存",
122
+ "themeDiscardTitle": "放弃主题修改?",
123
+ "themeKeepEditing": "继续编辑",
124
+ "themeDiscard": "放弃修改",
125
+ "themeDiscardHint": "尚未保存的配色将丢失,当前主题保持不变。",
126
+ "themeInvalidColor": "请输入有效的不透明十六进制颜色(如 #2563eb)。",
127
+ "themeSaveError": "保存失败,当前主题未更改。请重试,或检查浏览器的存储权限。"
62
128
  },
63
129
  brand: {
64
130
  "violet": "鸢紫",
@@ -84,6 +150,569 @@ function registerTranslations(ctx) {
84
150
  }, "zh-CN");
85
151
  }
86
152
  //#endregion
153
+ //#region ../../../node_modules/.pnpm/lucide-react@1.40.0_react@19.2.8/node_modules/lucide-react/dist/esm/shared/src/utils/mergeClasses.mjs
154
+ /**
155
+ * @license lucide-react v1.40.0 - ISC
156
+ *
157
+ * This source code is licensed under the ISC license.
158
+ * See the LICENSE file in the root directory of this source tree.
159
+ */
160
+ var mergeClasses = (...classes) => classes.filter((className, index, array) => {
161
+ return Boolean(className) && className.trim() !== "" && array.indexOf(className) === index;
162
+ }).join(" ").trim();
163
+ //#endregion
164
+ //#region ../../../node_modules/.pnpm/lucide-react@1.40.0_react@19.2.8/node_modules/lucide-react/dist/esm/shared/src/utils/toKebabCase.mjs
165
+ /**
166
+ * @license lucide-react v1.40.0 - ISC
167
+ *
168
+ * This source code is licensed under the ISC license.
169
+ * See the LICENSE file in the root directory of this source tree.
170
+ */
171
+ var toKebabCase = (string) => string.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
172
+ //#endregion
173
+ //#region ../../../node_modules/.pnpm/lucide-react@1.40.0_react@19.2.8/node_modules/lucide-react/dist/esm/shared/src/utils/toCamelCase.mjs
174
+ /**
175
+ * @license lucide-react v1.40.0 - ISC
176
+ *
177
+ * This source code is licensed under the ISC license.
178
+ * See the LICENSE file in the root directory of this source tree.
179
+ */
180
+ var toCamelCase = (string) => string.replace(/^([A-Z])|[\s-_]+(\w)/g, (match, p1, p2) => p2 ? p2.toUpperCase() : p1.toLowerCase());
181
+ //#endregion
182
+ //#region ../../../node_modules/.pnpm/lucide-react@1.40.0_react@19.2.8/node_modules/lucide-react/dist/esm/shared/src/utils/toPascalCase.mjs
183
+ /**
184
+ * @license lucide-react v1.40.0 - ISC
185
+ *
186
+ * This source code is licensed under the ISC license.
187
+ * See the LICENSE file in the root directory of this source tree.
188
+ */
189
+ var toPascalCase = (string) => {
190
+ const camelCase = toCamelCase(string);
191
+ return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
192
+ };
193
+ //#endregion
194
+ //#region ../../../node_modules/.pnpm/lucide-react@1.40.0_react@19.2.8/node_modules/lucide-react/dist/esm/defaultAttributes.mjs
195
+ /**
196
+ * @license lucide-react v1.40.0 - ISC
197
+ *
198
+ * This source code is licensed under the ISC license.
199
+ * See the LICENSE file in the root directory of this source tree.
200
+ */
201
+ var defaultAttributes = {
202
+ xmlns: "http://www.w3.org/2000/svg",
203
+ width: 24,
204
+ height: 24,
205
+ viewBox: "0 0 24 24",
206
+ fill: "none",
207
+ stroke: "currentColor",
208
+ strokeWidth: 2,
209
+ strokeLinecap: "round",
210
+ strokeLinejoin: "round"
211
+ };
212
+ //#endregion
213
+ //#region ../../../node_modules/.pnpm/lucide-react@1.40.0_react@19.2.8/node_modules/lucide-react/dist/esm/shared/src/utils/hasA11yProp.mjs
214
+ /**
215
+ * @license lucide-react v1.40.0 - ISC
216
+ *
217
+ * This source code is licensed under the ISC license.
218
+ * See the LICENSE file in the root directory of this source tree.
219
+ */
220
+ var hasA11yProp = (props) => {
221
+ for (const prop in props) if (prop.startsWith("aria-") || prop === "role" || prop === "title") return true;
222
+ return false;
223
+ };
224
+ //#endregion
225
+ //#region ../../../node_modules/.pnpm/lucide-react@1.40.0_react@19.2.8/node_modules/lucide-react/dist/esm/context.mjs
226
+ /**
227
+ * @license lucide-react v1.40.0 - ISC
228
+ *
229
+ * This source code is licensed under the ISC license.
230
+ * See the LICENSE file in the root directory of this source tree.
231
+ */
232
+ var LucideContext = createContext({});
233
+ var useLucideContext = () => useContext(LucideContext);
234
+ //#endregion
235
+ //#region ../../../node_modules/.pnpm/lucide-react@1.40.0_react@19.2.8/node_modules/lucide-react/dist/esm/Icon.mjs
236
+ /**
237
+ * @license lucide-react v1.40.0 - ISC
238
+ *
239
+ * This source code is licensed under the ISC license.
240
+ * See the LICENSE file in the root directory of this source tree.
241
+ */
242
+ var Icon = forwardRef(({ color, size, strokeWidth, absoluteStrokeWidth, className = "", children, iconNode, ...rest }, ref) => {
243
+ const { size: contextSize = 24, strokeWidth: contextStrokeWidth = 2, absoluteStrokeWidth: contextAbsoluteStrokeWidth = false, color: contextColor = "currentColor", className: contextClass = "" } = useLucideContext() ?? {};
244
+ const calculatedStrokeWidth = absoluteStrokeWidth ?? contextAbsoluteStrokeWidth ? Number(strokeWidth ?? contextStrokeWidth) * 24 / Number(size ?? contextSize) : strokeWidth ?? contextStrokeWidth;
245
+ return createElement("svg", {
246
+ ref,
247
+ ...defaultAttributes,
248
+ width: size ?? contextSize ?? defaultAttributes.width,
249
+ height: size ?? contextSize ?? defaultAttributes.height,
250
+ stroke: color ?? contextColor,
251
+ strokeWidth: calculatedStrokeWidth,
252
+ className: mergeClasses("lucide", contextClass, className),
253
+ ...!children && !hasA11yProp(rest) && { "aria-hidden": "true" },
254
+ ...rest
255
+ }, [...iconNode.map(([tag, attrs]) => createElement(tag, attrs)), ...Array.isArray(children) ? children : [children]]);
256
+ });
257
+ //#endregion
258
+ //#region ../../../node_modules/.pnpm/lucide-react@1.40.0_react@19.2.8/node_modules/lucide-react/dist/esm/createLucideIcon.mjs
259
+ /**
260
+ * @license lucide-react v1.40.0 - ISC
261
+ *
262
+ * This source code is licensed under the ISC license.
263
+ * See the LICENSE file in the root directory of this source tree.
264
+ */
265
+ var createLucideIcon = (iconName, iconNode) => {
266
+ const Component = forwardRef(({ className, ...props }, ref) => createElement(Icon, {
267
+ ref,
268
+ iconNode,
269
+ className: mergeClasses(`lucide-${toKebabCase(toPascalCase(iconName))}`, `lucide-${iconName}`, className),
270
+ ...props
271
+ }));
272
+ Component.displayName = toPascalCase(iconName);
273
+ return Component;
274
+ };
275
+ /**
276
+ * @license lucide-react v1.40.0 - ISC
277
+ *
278
+ * This source code is licensed under the ISC license.
279
+ * See the LICENSE file in the root directory of this source tree.
280
+ */
281
+ var ArrowLeft = createLucideIcon("arrow-left", [["path", {
282
+ d: "m12 19-7-7 7-7",
283
+ key: "1l729n"
284
+ }], ["path", {
285
+ d: "M19 12H5",
286
+ key: "x3x0zl"
287
+ }]]);
288
+ /**
289
+ * @license lucide-react v1.40.0 - ISC
290
+ *
291
+ * This source code is licensed under the ISC license.
292
+ * See the LICENSE file in the root directory of this source tree.
293
+ */
294
+ var ArrowUp = createLucideIcon("arrow-up", [["path", {
295
+ d: "m5 12 7-7 7 7",
296
+ key: "hav0vg"
297
+ }], ["path", {
298
+ d: "M12 19V5",
299
+ key: "x0mq9r"
300
+ }]]);
301
+ /**
302
+ * @license lucide-react v1.40.0 - ISC
303
+ *
304
+ * This source code is licensed under the ISC license.
305
+ * See the LICENSE file in the root directory of this source tree.
306
+ */
307
+ var Pencil = createLucideIcon("pencil", [["path", {
308
+ d: "M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",
309
+ key: "1a8usu"
310
+ }], ["path", {
311
+ d: "m15 5 4 4",
312
+ key: "1mk7zo"
313
+ }]]);
314
+ //#endregion
315
+ //#region ui-src/fonts/manifest.json
316
+ var manifest_default = [
317
+ {
318
+ "id": "wenkai",
319
+ "file": "wenkai.ttf",
320
+ "revision": "v1.522",
321
+ "source": "https://github.com/lxgw/LxgwWenKai-Screen/releases/download/v1.522/LXGWWenKaiScreen.ttf",
322
+ "license": "wenkai-LICENSE.txt",
323
+ "weight": "400",
324
+ "bytes": 25673994,
325
+ "sha256": "cd1a6fa39c4ea42fd8f4e289945789b0e510cf7016435640f8893cdad9b220f3"
326
+ },
327
+ {
328
+ "id": "source-han-serif",
329
+ "file": "source-han-serif.otf",
330
+ "revision": "7889f11bf31170b5d092a083b357c8c8130f89e0",
331
+ "source": "https://raw.githubusercontent.com/adobe-fonts/source-han-serif/7889f11bf31170b5d092a083b357c8c8130f89e0/SubsetOTF/CN/SourceHanSerifCN-Regular.otf",
332
+ "license": "source-han-serif-LICENSE.txt",
333
+ "weight": "400",
334
+ "bytes": 11626108,
335
+ "sha256": "3754ea669c530e2473354f8f6d9f79680a44d7e26ec7d00eeabee4a7e0753c5d"
336
+ },
337
+ {
338
+ "id": "source-han-sans",
339
+ "file": "source-han-sans.otf",
340
+ "revision": "6c709ca72d3d7c46ab42ebecc1a26e7d69595a37",
341
+ "source": "https://raw.githubusercontent.com/adobe-fonts/source-han-sans/6c709ca72d3d7c46ab42ebecc1a26e7d69595a37/SubsetOTF/CN/SourceHanSansCN-Regular.otf",
342
+ "license": "source-han-sans-LICENSE.txt",
343
+ "weight": "400",
344
+ "bytes": 8429224,
345
+ "sha256": "e2bc8a2e7f37474b774fff8db758681ece40bb6947a90d571bce9dd60671a8e4"
346
+ },
347
+ {
348
+ "id": "source-serif",
349
+ "file": "source-serif.woff2",
350
+ "revision": "2823e993c53fca27c5c8749f529b56a5a7c77b6b",
351
+ "source": "https://raw.githubusercontent.com/adobe-fonts/source-serif/2823e993c53fca27c5c8749f529b56a5a7c77b6b/WOFF2/VAR/SourceSerif4Variable-Roman.otf.woff2",
352
+ "license": "source-serif-LICENSE.txt",
353
+ "weight": "200 900",
354
+ "bytes": 426716,
355
+ "sha256": "f146ee102dddcc5bc7a2cf4af5bcf129832195941b92bd0a512626f390688c1e"
356
+ },
357
+ {
358
+ "id": "source-sans",
359
+ "file": "source-sans.woff2",
360
+ "revision": "ed1808970eb3c7301c9a523bee26473ba0bb62fa",
361
+ "source": "https://raw.githubusercontent.com/adobe-fonts/source-sans/ed1808970eb3c7301c9a523bee26473ba0bb62fa/WOFF2/OTF/SourceSans3-Regular.otf.woff2",
362
+ "license": "source-sans-LICENSE.txt",
363
+ "weight": "400",
364
+ "bytes": 153800,
365
+ "sha256": "63de0da0cc05298e2e9c6e5cef506d8454ca665f6e668a99d94f51174b9256ed"
366
+ },
367
+ {
368
+ "id": "atkinson",
369
+ "file": "atkinson.woff2",
370
+ "revision": "7925f50f649b3813257faf2f4c0b381011f434f1",
371
+ "source": "https://raw.githubusercontent.com/googlefonts/atkinson-hyperlegible-next/7925f50f649b3813257faf2f4c0b381011f434f1/fonts/webfonts/AtkinsonHyperlegibleNext%5Bwght%5D.woff2",
372
+ "license": "atkinson-LICENSE.txt",
373
+ "weight": "200 800",
374
+ "bytes": 48188,
375
+ "sha256": "abde1ad5cf78b9ac575ef90d991f2e9101eb0b3b6668bde9a00e2e1e27d99afd"
376
+ },
377
+ {
378
+ "id": "literata",
379
+ "file": "literata.woff2",
380
+ "revision": "0c2761b727a1b3a7cffd313c37f0f5163dfc7a63",
381
+ "source": "https://raw.githubusercontent.com/googlefonts/literata/0c2761b727a1b3a7cffd313c37f0f5163dfc7a63/fonts/webfonts/Literata%5Bopsz%2Cwght%5D.woff2",
382
+ "license": "literata-LICENSE.txt",
383
+ "weight": "200 900",
384
+ "bytes": 396224,
385
+ "sha256": "5e50643479bee69e0204164602f830502b0db42bbc29da83edc9980df17e34df"
386
+ }
387
+ ];
388
+ //#endregion
389
+ //#region ui-src/font-assets.ts
390
+ /** Immutable packaged fonts with exact upstream revision, size, license and digest. */
391
+ var READING_FONT_ASSETS = manifest_default;
392
+ /** Returns an owner-specific CSS alias independent of an installed device font name. */
393
+ function readingFontAlias(id) {
394
+ if (!manifest_default.some((asset) => asset.id === id)) throw new Error("Unknown reading font");
395
+ return `yaoguang-personalization-${id}`;
396
+ }
397
+ //#endregion
398
+ //#region ui-src/store/reading-typography.ts
399
+ /** Storage identifier independent of theme and terminal preferences. */
400
+ var READING_TYPOGRAPHY_KEY = "yaoguang.readingTypography";
401
+ /** Initial reading appearance shared by restoration and reset. */
402
+ var DEFAULT_READING_TYPOGRAPHY = {
403
+ chinese: {
404
+ kind: "builtin",
405
+ value: "wenkai"
406
+ },
407
+ western: {
408
+ kind: "builtin",
409
+ value: "wenkai"
410
+ },
411
+ bodySize: 14
412
+ };
413
+ var chineseFonts = /* @__PURE__ */ new Set([
414
+ "wenkai",
415
+ "source-han-serif",
416
+ "source-han-sans"
417
+ ]);
418
+ var westernFonts = /* @__PURE__ */ new Set([
419
+ "wenkai",
420
+ "source-serif",
421
+ "source-sans",
422
+ "atkinson",
423
+ "literata"
424
+ ]);
425
+ /** Creates isolated preferences without acquiring browser listeners or gateway state. */
426
+ function createReadingTypography(options) {
427
+ function font(value, allowed) {
428
+ if (!value || typeof value !== "object") return void 0;
429
+ const candidate = value;
430
+ if (candidate.kind === "system") return { kind: "system" };
431
+ if (typeof candidate.value !== "string") return void 0;
432
+ if (candidate.kind === "builtin" && allowed.has(candidate.value)) return {
433
+ kind: "builtin",
434
+ value: candidate.value
435
+ };
436
+ if (candidate.kind === "custom" && candidate.value.trim() && candidate.value.length <= 512 && options.validFamily(candidate.value)) return {
437
+ kind: "custom",
438
+ value: candidate.value
439
+ };
440
+ }
441
+ function parse(raw) {
442
+ let value = {};
443
+ try {
444
+ const parsed = raw === null ? null : JSON.parse(raw);
445
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) value = parsed;
446
+ } catch {}
447
+ return {
448
+ chinese: font(value.chinese, chineseFonts) ?? DEFAULT_READING_TYPOGRAPHY.chinese,
449
+ western: font(value.western, westernFonts) ?? DEFAULT_READING_TYPOGRAPHY.western,
450
+ bodySize: typeof value.bodySize === "number" && Number.isInteger(value.bodySize) && value.bodySize >= 14 && value.bodySize <= 22 ? value.bodySize : DEFAULT_READING_TYPOGRAPHY.bodySize
451
+ };
452
+ }
453
+ let initial = null;
454
+ try {
455
+ initial = options.storage.getItem(READING_TYPOGRAPHY_KEY);
456
+ } catch {}
457
+ let snapshot = {
458
+ preferences: parse(initial),
459
+ saveFailed: false
460
+ };
461
+ const listeners = /* @__PURE__ */ new Set();
462
+ function publish(preferences, persist) {
463
+ let saveFailed = false;
464
+ if (persist) try {
465
+ options.storage.setItem(READING_TYPOGRAPHY_KEY, JSON.stringify(preferences));
466
+ } catch {
467
+ saveFailed = true;
468
+ }
469
+ snapshot = {
470
+ preferences,
471
+ saveFailed
472
+ };
473
+ for (const listener of listeners) listener();
474
+ }
475
+ return {
476
+ /** Returns a stable snapshot until the next preference change. */
477
+ getSnapshot: () => snapshot,
478
+ /** Observes memory changes, including failed persistence. */
479
+ subscribe(listener) {
480
+ listeners.add(listener);
481
+ return () => {
482
+ listeners.delete(listener);
483
+ };
484
+ },
485
+ /** Validates all supplied fields atomically before applying and attempting persistence. */
486
+ update(patch) {
487
+ if (patch.chinese !== void 0 && !font(patch.chinese, chineseFonts)) return false;
488
+ if (patch.western !== void 0 && !font(patch.western, westernFonts)) return false;
489
+ if (patch.bodySize !== void 0 && (!Number.isInteger(patch.bodySize) || patch.bodySize < 14 || patch.bodySize > 22)) return false;
490
+ publish({
491
+ chinese: patch.chinese === void 0 ? snapshot.preferences.chinese : font(patch.chinese, chineseFonts),
492
+ western: patch.western === void 0 ? snapshot.preferences.western : font(patch.western, westernFonts),
493
+ bodySize: patch.bodySize ?? snapshot.preferences.bodySize
494
+ }, true);
495
+ return true;
496
+ },
497
+ /** Restores a storage event without echoing it to other pages. */
498
+ restore(raw) {
499
+ publish(parse(raw), false);
500
+ },
501
+ /** Resets only reading preferences, leaving other local settings intact. */
502
+ reset() {
503
+ publish(DEFAULT_READING_TYPOGRAPHY, true);
504
+ }
505
+ };
506
+ }
507
+ //#endregion
508
+ //#region ui-src/lib/font-resource.ts
509
+ /** Resolves a fixed packaged font through the host's native URL mapping. */
510
+ function resourceFontFace(ctx, id) {
511
+ const asset = READING_FONT_ASSETS.find((asset) => asset.id === id);
512
+ if (!asset) throw new Error("Unknown reading font");
513
+ const controller = new AbortController();
514
+ const signal = AbortSignal.any([ctx.signal, controller.signal]);
515
+ const entry = {
516
+ cancel: () => controller.abort(),
517
+ async load() {
518
+ signal.throwIfAborted();
519
+ const url = ctx.packageFiles.url(`fonts/${asset.file}`);
520
+ const face = new FontFace(readingFontAlias(id), `url(${JSON.stringify(url)})`, { weight: asset.weight });
521
+ await face.load();
522
+ signal.throwIfAborted();
523
+ entry.face = face;
524
+ }
525
+ };
526
+ return entry;
527
+ }
528
+ //#endregion
529
+ //#region ui-src/lib/reading-fonts.ts
530
+ /** Loads selected faces only and prevents late completion from restoring a withdrawn owner. */
531
+ function createReadingFonts(host) {
532
+ const entries = /* @__PURE__ */ new Map();
533
+ let wanted = /* @__PURE__ */ new Set();
534
+ let disposed = false;
535
+ return {
536
+ /** Returns failed asset IDs; callers keep readable fallback families until a later retry. */
537
+ async select(ids) {
538
+ if (disposed) return [];
539
+ wanted = new Set(ids);
540
+ for (const [id, entry] of entries) if (!wanted.has(id)) {
541
+ entry.face.cancel?.();
542
+ if (entry.installed) host.remove(entry.face);
543
+ entries.delete(id);
544
+ }
545
+ return (await Promise.all([...wanted].map(async (id) => {
546
+ let entry = entries.get(id);
547
+ if (!entry) {
548
+ const face = host.create(id);
549
+ const next = {
550
+ face,
551
+ installed: false,
552
+ work: Promise.resolve(false)
553
+ };
554
+ entries.set(id, next);
555
+ next.work = face.load().then(() => {
556
+ if (disposed || !wanted.has(id) || entries.get(id) !== next) return false;
557
+ host.add(face);
558
+ next.installed = true;
559
+ return true;
560
+ }, () => {
561
+ if (entries.get(id) === next) entries.delete(id);
562
+ return false;
563
+ });
564
+ entry = next;
565
+ }
566
+ return await entry.work ? void 0 : id;
567
+ }))).filter((id) => id !== void 0);
568
+ },
569
+ /** Withdraws loaded faces and ignores unresolved browser loads. */
570
+ dispose() {
571
+ disposed = true;
572
+ wanted.clear();
573
+ for (const entry of entries.values()) {
574
+ entry.face.cancel?.();
575
+ if (entry.installed) host.remove(entry.face);
576
+ }
577
+ entries.clear();
578
+ }
579
+ };
580
+ }
581
+ //#endregion
582
+ //#region ui-src/lib/reading-typography.ts
583
+ /** Validates a complete font-family list without interpreting it as stylesheet text. */
584
+ function validReadingFontFamily(value) {
585
+ if (typeof document === "undefined") return false;
586
+ const style = document.createElement("span").style;
587
+ style.fontFamily = value;
588
+ return style.fontFamily !== "";
589
+ }
590
+ /** Browser-local preference owner; storage failures remain visible in its snapshot. */
591
+ var readingTypography = createReadingTypography({
592
+ storage: {
593
+ getItem: (key) => localStorage.getItem(key),
594
+ setItem: (key, value) => localStorage.setItem(key, value)
595
+ },
596
+ validFamily: validReadingFontFamily
597
+ });
598
+ /** Resolves the selected reading family with the same asset alias and fallback used by live text. */
599
+ function readingFontFamily(choice) {
600
+ if (choice.kind === "system") return "var(--font-sans)";
601
+ if (choice.kind === "custom") return choice.value;
602
+ return `"${readingFontAlias(choice.value)}", var(--font-sans)`;
603
+ }
604
+ var fontStatus = {
605
+ loading: false,
606
+ failed: []
607
+ };
608
+ var fontListeners = /* @__PURE__ */ new Set();
609
+ /** Reads the stable current asset-loading snapshot. */
610
+ function getReadingFontStatus() {
611
+ return fontStatus;
612
+ }
613
+ /** Observes selected-font loading without exposing browser FontFace objects. */
614
+ function subscribeReadingFontStatus(listener) {
615
+ fontListeners.add(listener);
616
+ return () => {
617
+ fontListeners.delete(listener);
618
+ };
619
+ }
620
+ function publishFontStatus(next) {
621
+ fontStatus = next;
622
+ for (const listener of fontListeners) listener();
623
+ }
624
+ var activation;
625
+ var fontContext;
626
+ var fallbackDiscoverySignal = new AbortController().signal;
627
+ /** Returns the active owner's discovery lifetime and optional native metadata source. */
628
+ function readingFontDiscoveryContext() {
629
+ return {
630
+ signal: fontContext?.signal ?? fallbackDiscoverySignal,
631
+ native: fontContext?.services.get("native-device-fonts")
632
+ };
633
+ }
634
+ /** Owns reading-only tokens, selected FontFaces and same-origin storage synchronization. */
635
+ function initReadingTypography(ctx) {
636
+ const owner = Symbol();
637
+ activation = owner;
638
+ fontContext = ctx;
639
+ const root = document.documentElement;
640
+ const style = document.createElement("style");
641
+ style.dataset.readingTypography = "";
642
+ style.textContent = `
643
+ [data-reading-body] [data-reading-script] { font-size: var(--reading-text-size, var(--reading-body-size)); }
644
+ [data-reading-body] [data-reading-script="chinese"] { font-family: var(--reading-chinese); }
645
+ [data-reading-body] [data-reading-script="western"] { font-family: var(--reading-western); }
646
+ [data-reading-body] h1 { --reading-text-size: calc(var(--reading-body-size) * 1.7); }
647
+ [data-reading-body] h2 { --reading-text-size: calc(var(--reading-body-size) * 1.4); }
648
+ [data-reading-body] h3 { --reading-text-size: calc(var(--reading-body-size) * 1.2); }
649
+ [data-reading-body] :is(p,li,td,th,blockquote):not([data-slot="widget"] *) { line-height: 1.8; }
650
+ `;
651
+ document.head.append(style);
652
+ const fonts = typeof FontFace === "undefined" ? void 0 : createReadingFonts({
653
+ create: (id) => resourceFontFace(ctx, id),
654
+ add: (entry) => {
655
+ if (entry.face) {
656
+ document.fonts.add(entry.face);
657
+ notifyReadingLayout();
658
+ }
659
+ },
660
+ remove: (entry) => {
661
+ if (entry.face) document.fonts.delete(entry.face);
662
+ }
663
+ });
664
+ let loadingTicket = 0;
665
+ const apply = () => {
666
+ if (activation !== owner) return;
667
+ const { preferences } = readingTypography.getSnapshot();
668
+ root.style.setProperty("--reading-chinese", readingFontFamily(preferences.chinese));
669
+ root.style.setProperty("--reading-western", readingFontFamily(preferences.western));
670
+ root.style.setProperty("--reading-body-size", `${preferences.bodySize}px`);
671
+ notifyReadingLayout();
672
+ const selected = [preferences.chinese, preferences.western].flatMap((choice) => choice.kind === "builtin" ? [choice.value] : []);
673
+ const ticket = ++loadingTicket;
674
+ publishFontStatus({
675
+ loading: selected.length > 0,
676
+ failed: []
677
+ });
678
+ (fonts ? fonts.select(selected) : Promise.resolve(selected)).then((failed) => {
679
+ if (activation === owner && ticket === loadingTicket) publishFontStatus({
680
+ loading: false,
681
+ failed
682
+ });
683
+ }, () => {
684
+ if (activation === owner && ticket === loadingTicket) publishFontStatus({
685
+ loading: false,
686
+ failed: selected
687
+ });
688
+ });
689
+ };
690
+ const stop = readingTypography.subscribe(apply);
691
+ const storage = (event) => {
692
+ if (activation === owner && (event.key === "yaoguang.readingTypography" || event.key === null)) readingTypography.restore(event.newValue);
693
+ };
694
+ window.addEventListener("storage", storage);
695
+ apply();
696
+ return () => {
697
+ stop();
698
+ window.removeEventListener("storage", storage);
699
+ fonts?.dispose();
700
+ style.remove();
701
+ if (activation !== owner) return;
702
+ activation = void 0;
703
+ fontContext = void 0;
704
+ publishFontStatus({
705
+ loading: false,
706
+ failed: []
707
+ });
708
+ for (const key of [
709
+ "--reading-chinese",
710
+ "--reading-western",
711
+ "--reading-body-size"
712
+ ]) root.style.removeProperty(key);
713
+ };
714
+ }
715
+ //#endregion
87
716
  //#region ../../../node_modules/.pnpm/zustand@5.0.15_@types+react@19.2.18_react@19.2.8_use-sync-external-store@1.7.0_react@19.2.8_/node_modules/zustand/esm/vanilla.mjs
88
717
  var createStoreImpl = (createState) => {
89
718
  let state;
@@ -287,13 +916,75 @@ var persist = persistImpl;
287
916
  //#endregion
288
917
  //#region ui-src/lib/theme.ts
289
918
  /** Applies a palette atomically, including portals and pseudo-elements, without persisting it. */
290
- function applyDocumentTheme(mode, brand) {
919
+ /** Converts an opaque computed RGB or OKLCH color to its displayed sRGB hex value. */
920
+ function colorHexFromCss(color) {
921
+ if (color.startsWith("oklch(")) {
922
+ const [lightness, chroma, hue] = color.slice(6).match(/[+-]?(?:\d*\.)?\d+(?:e[+-]?\d+)?/gi)?.map(Number) ?? [];
923
+ if (lightness === void 0 || chroma === void 0 || hue === void 0) throw new Error("Invalid computed OKLCH color");
924
+ const radians = hue * Math.PI / 180;
925
+ const a = chroma * Math.cos(radians);
926
+ const b = chroma * Math.sin(radians);
927
+ const l = (lightness + .3963377774 * a + .2158037573 * b) ** 3;
928
+ const m = (lightness - .1055613458 * a - .0638541728 * b) ** 3;
929
+ const s = (lightness - .0894841775 * a - 1.291485548 * b) ** 3;
930
+ const channel = (linear) => 255 * (linear <= .0031308 ? 12.92 * linear : 1.055 * linear ** (1 / 2.4) - .055);
931
+ return colorToHex({
932
+ r: channel(4.0767416621 * l - 3.3077115913 * m + .2309699292 * s),
933
+ g: channel(-1.2684380046 * l + 2.6097574011 * m - .3413193965 * s),
934
+ b: channel(-.0041960863 * l - .7034186147 * m + 1.707614701 * s),
935
+ a: 1
936
+ });
937
+ }
938
+ const [r = 0, g = 0, b = 0] = color.match(/[\d.]+/g)?.map(Number) ?? [];
939
+ return colorToHex({
940
+ r,
941
+ g,
942
+ b,
943
+ a: 1
944
+ });
945
+ }
946
+ /**
947
+ * A preset's surface and text colours, read from the same rules the appearance
948
+ * page's preview paints, so a custom theme starts from what the preview shows.
949
+ */
950
+ function presetColors(preset, mode) {
951
+ const probe = document.createElement("div");
952
+ probe.className = `palette-${preset} palette-preview-${mode}`;
953
+ probe.style.position = "absolute";
954
+ probe.style.visibility = "hidden";
955
+ (document.body ?? document.documentElement).append(probe);
956
+ const style = getComputedStyle(probe);
957
+ const colors = {
958
+ background: colorHexFromCss(style.backgroundColor),
959
+ foreground: colorHexFromCss(style.color)
960
+ };
961
+ probe.remove();
962
+ return colors;
963
+ }
964
+ function applyDocumentTheme(mode, brand, selection) {
291
965
  const root = document.documentElement;
292
- if (!(root.dataset.uiTheme !== mode || brand !== void 0 && (root.style.getPropertyValue("--brand-h") !== String(brand.hue) || root.style.getPropertyValue("--brand-c") !== String(brand.chroma)))) return;
966
+ const custom = selection?.custom ?? null;
967
+ if (!(root.dataset.uiTheme !== mode || selection !== void 0 && root.dataset.palette !== selection.palette || (custom === null ? root.hasAttribute("data-theme-custom") : !root.hasAttribute("data-theme-custom") || root.style.getPropertyValue("--custom-background") !== custom.background || root.style.getPropertyValue("--custom-foreground") !== custom.foreground || root.style.getPropertyValue("--custom-brand") !== custom.brand || root.style.getPropertyValue("--custom-brand-foreground") !== custom.brandForeground) || brand !== void 0 && (root.style.getPropertyValue("--brand-h") !== String(brand.hue) || root.style.getPropertyValue("--brand-c") !== String(brand.chroma)))) return;
293
968
  root.dataset.themeChanging = "";
294
969
  try {
295
970
  root.dataset.uiTheme = mode;
296
971
  root.classList.toggle("dark", mode === "dark");
972
+ if (selection !== void 0) {
973
+ root.dataset.palette = selection.palette;
974
+ if (custom === null) {
975
+ delete root.dataset.themeCustom;
976
+ root.style.removeProperty("--custom-background");
977
+ root.style.removeProperty("--custom-foreground");
978
+ root.style.removeProperty("--custom-brand");
979
+ root.style.removeProperty("--custom-brand-foreground");
980
+ } else {
981
+ root.dataset.themeCustom = "";
982
+ root.style.setProperty("--custom-background", custom.background);
983
+ root.style.setProperty("--custom-foreground", custom.foreground);
984
+ root.style.setProperty("--custom-brand", custom.brand);
985
+ root.style.setProperty("--custom-brand-foreground", custom.brandForeground);
986
+ }
987
+ }
297
988
  if (brand) {
298
989
  root.style.setProperty("--brand-h", String(brand.hue));
299
990
  root.style.setProperty("--brand-c", String(brand.chroma));
@@ -305,7 +996,7 @@ function applyDocumentTheme(mode, brand) {
305
996
  }
306
997
  //#endregion
307
998
  //#region ui-src/store/theme.ts
308
- /** Browser-local solid color scheme and brand preferences. */
999
+ /** Browser-local language, color scheme and brand preferences. */
309
1000
  /** 瑶光 is Alkaid, the star at the end of the Plough's handle, and a B-type
310
1001
  * star is blue-white — which is where the default hue comes from. */
311
1002
  var ALKAID = {
@@ -314,91 +1005,281 @@ var ALKAID = {
314
1005
  hue: 255,
315
1006
  chroma: .15
316
1007
  };
317
- /** Ordered brand presets; Alkaid supplies the default presentation. */
318
- var BRANDS = [
319
- ALKAID,
320
- {
321
- id: "violet",
322
- labelKey: "brand.violet",
323
- hue: 295,
1008
+ /** The presets, by name: a theme always has one. */
1009
+ var PRESETS = {
1010
+ neutral: {
1011
+ id: "neutral",
1012
+ hue: 255,
324
1013
  chroma: .15
325
1014
  },
326
- {
327
- id: "celadon",
328
- labelKey: "brand.celadon",
329
- hue: 185,
330
- chroma: .095
331
- },
332
- {
333
- id: "moss",
334
- labelKey: "brand.moss",
335
- hue: 150,
336
- chroma: .12
1015
+ cool: {
1016
+ id: "cool",
1017
+ hue: 295,
1018
+ chroma: .15
337
1019
  },
338
- {
339
- id: "honey",
340
- labelKey: "brand.honey",
1020
+ warm: {
1021
+ id: "warm",
341
1022
  hue: 70,
342
1023
  chroma: .12
343
- },
344
- {
345
- id: "lotus",
346
- labelKey: "brand.lotus",
347
- hue: 355,
348
- chroma: .15
349
1024
  }
1025
+ };
1026
+ /** The presets the appearance page offers, in the order it lists them. */
1027
+ var THEME_PRESETS = [
1028
+ PRESETS.neutral,
1029
+ PRESETS.cool,
1030
+ PRESETS.warm
350
1031
  ];
351
- /** Resolves persisted color values to a preset, selecting Alkaid for unmatched values. */
352
- function resolveBrand(stored) {
353
- return BRANDS.find((one) => one.hue === stored.hue && one.chroma === stored.chroma) ?? ALKAID;
1032
+ /** The theme an installation starts from, and the one unknown values fall back to. */
1033
+ var DEFAULT_THEME = "neutral";
1034
+ /** The brand renders at a different lightness in each mode; these are those two. */
1035
+ var BRAND_LIGHTNESS = {
1036
+ light: .52,
1037
+ dark: .76
1038
+ };
1039
+ var BRAND_CHROMA_FACTOR = {
1040
+ light: 1,
1041
+ dark: .8
1042
+ };
1043
+ /** The colour a brand renders as in one mode. */
1044
+ function brandColor(brand, mode) {
1045
+ return colorHexFromCss(`oklch(${BRAND_LIGHTNESS[mode]} ${brand.chroma * BRAND_CHROMA_FACTOR[mode]} ${brand.hue})`);
1046
+ }
1047
+ /** The colour that reads on a brand colour. */
1048
+ function brandForeground(color) {
1049
+ const parsed = parseColorHex(color);
1050
+ return parsed === null ? "#ffffff" : colorToHex(readableForeground(parsed));
1051
+ }
1052
+ /** A custom theme that starts from a preset's own colours. */
1053
+ function customFromPreset(base) {
1054
+ const preset = PRESETS[base];
1055
+ const light = presetColors(base, "light");
1056
+ const dark = presetColors(base, "dark");
1057
+ return {
1058
+ base,
1059
+ light: {
1060
+ background: light.background,
1061
+ foreground: light.foreground,
1062
+ brand: brandColor(preset, "light")
1063
+ },
1064
+ dark: {
1065
+ background: dark.background,
1066
+ foreground: dark.foreground,
1067
+ brand: brandColor(preset, "dark")
1068
+ }
1069
+ };
1070
+ }
1071
+ /** Returns an isolated editing draft without changing applied or saved preferences. */
1072
+ function createThemeDraft(source) {
1073
+ if (source !== "custom") return customFromPreset(source);
1074
+ const state = useTheme.getState();
1075
+ const custom = state.custom;
1076
+ if (custom !== null) return {
1077
+ base: custom.base,
1078
+ light: { ...custom.light },
1079
+ dark: { ...custom.dark }
1080
+ };
1081
+ return customFromPreset(state.theme === "custom" ? DEFAULT_THEME : state.theme);
1082
+ }
1083
+ /**
1084
+ * A stored or typed opaque hex colour in canonical `#rrggbb` form, accepting surrounding space,
1085
+ * a missing `#` and short form; null for anything else, alpha included.
1086
+ */
1087
+ function opaqueHex(value) {
1088
+ if (typeof value !== "string") return null;
1089
+ const parsed = parseColorHex(value);
1090
+ return parsed !== null && parsed.a === 1 ? colorToHex(parsed) : null;
1091
+ }
1092
+ /** The three colours of one mode in canonical CSS form, when they are usable; otherwise nothing. */
1093
+ function readColors(stored) {
1094
+ if (typeof stored !== "object" || stored === null) return null;
1095
+ const candidate = stored;
1096
+ const background = opaqueHex(candidate.background);
1097
+ const foreground = opaqueHex(candidate.foreground);
1098
+ const brand = opaqueHex(candidate.brand);
1099
+ if (!background || !foreground || !brand) return null;
1100
+ return {
1101
+ background,
1102
+ foreground,
1103
+ brand
1104
+ };
1105
+ }
1106
+ /**
1107
+ * The custom theme as it was stored. A mode that is missing or unusable is
1108
+ * filled from the base preset, so a half-written custom still works; a value
1109
+ * that is not a custom theme at all reads as nothing.
1110
+ */
1111
+ function readCustomTheme(stored) {
1112
+ if (typeof stored !== "object" || stored === null) return null;
1113
+ const candidate = stored;
1114
+ const base = candidate.base === "cool" || candidate.base === "warm" ? candidate.base : DEFAULT_THEME;
1115
+ const fallback = customFromPreset(base);
1116
+ return {
1117
+ base,
1118
+ light: readColors(candidate.light) ?? fallback.light,
1119
+ dark: readColors(candidate.dark) ?? fallback.dark
1120
+ };
354
1121
  }
355
1122
  var CONTENT_WIDTHS = [
356
1123
  "default",
357
1124
  "wide",
358
1125
  "full"
359
1126
  ];
360
- var useTheme = create()(persist((set) => ({
1127
+ function themePreferences({ theme, custom, mode, contentWidth }) {
1128
+ return {
1129
+ theme,
1130
+ custom,
1131
+ mode,
1132
+ contentWidth
1133
+ };
1134
+ }
1135
+ var createThemeState = (publish, get, api) => persist((set, get) => ({
361
1136
  mode: "system",
362
1137
  setMode: (mode) => set({ mode }),
363
- hue: ALKAID.hue,
364
- chroma: ALKAID.chroma,
365
- setBrand: ({ hue, chroma }) => set({
366
- hue,
367
- chroma
1138
+ theme: DEFAULT_THEME,
1139
+ setTheme: (theme) => {
1140
+ if (theme === "custom" && get().custom === null) {
1141
+ const inForce = get().theme;
1142
+ set({
1143
+ theme,
1144
+ custom: customFromPreset(inForce === "custom" ? DEFAULT_THEME : inForce)
1145
+ });
1146
+ return;
1147
+ }
1148
+ set({ theme });
1149
+ },
1150
+ custom: null,
1151
+ setCustomColor: (mode, role, value) => {
1152
+ const state = get();
1153
+ const base = state.custom?.base ?? (state.theme === "custom" ? "neutral" : state.theme);
1154
+ const custom = state.custom ?? customFromPreset(base);
1155
+ set({
1156
+ theme: "custom",
1157
+ custom: {
1158
+ ...custom,
1159
+ [mode]: {
1160
+ ...custom[mode],
1161
+ [role]: value
1162
+ }
1163
+ }
1164
+ });
1165
+ },
1166
+ copyCustomFrom: (base) => set({
1167
+ theme: "custom",
1168
+ custom: customFromPreset(base)
368
1169
  }),
1170
+ saveCustomTheme: (draft) => {
1171
+ const light = readColors(draft.light);
1172
+ const dark = readColors(draft.dark);
1173
+ if (!THEME_PRESETS.some((preset) => preset.id === draft.base) || !light || !dark) throw new Error("Invalid custom theme");
1174
+ const custom = {
1175
+ base: draft.base,
1176
+ light,
1177
+ dark
1178
+ };
1179
+ const options = useTheme.persist.getOptions();
1180
+ if (options.storage === void 0) throw new Error("Theme storage is unavailable");
1181
+ options.storage.setItem(options.name ?? "yaoguang.theme", {
1182
+ state: themePreferences({
1183
+ ...get(),
1184
+ theme: "custom",
1185
+ custom
1186
+ }),
1187
+ version: options.version ?? 0
1188
+ });
1189
+ publish({
1190
+ theme: "custom",
1191
+ custom
1192
+ });
1193
+ },
369
1194
  contentWidth: "default",
370
1195
  setContentWidth: (contentWidth) => set({ contentWidth })
371
1196
  }), {
372
1197
  name: "yaoguang.theme",
373
- partialize: ({ hue, chroma, mode, contentWidth }) => ({
374
- hue,
375
- chroma,
376
- mode,
377
- contentWidth
378
- }),
1198
+ partialize: themePreferences,
379
1199
  merge: (persisted, current) => {
380
1200
  const stored = persisted;
381
- const brand = resolveBrand({
382
- hue: stored?.hue ?? current.hue,
383
- chroma: stored?.chroma ?? current.chroma
384
- });
1201
+ const mode = stored?.mode === "dark" || stored?.mode === "light" ? stored.mode : "system";
1202
+ const contentWidth = CONTENT_WIDTHS.find((width) => width === stored?.contentWidth) ?? "default";
1203
+ const custom = readCustomTheme(stored?.custom);
1204
+ const theme = stored?.theme;
1205
+ if (theme === "neutral" || theme === "cool" || theme === "warm") return {
1206
+ ...current,
1207
+ mode,
1208
+ theme,
1209
+ custom,
1210
+ contentWidth
1211
+ };
1212
+ if (theme === "custom" && custom !== null) return {
1213
+ ...current,
1214
+ mode,
1215
+ theme: "custom",
1216
+ custom,
1217
+ contentWidth
1218
+ };
1219
+ const hue = stored?.hue ?? ALKAID.hue;
1220
+ const chroma = stored?.chroma ?? ALKAID.chroma;
1221
+ if (hue === ALKAID.hue && chroma === ALKAID.chroma) return {
1222
+ ...current,
1223
+ mode,
1224
+ theme: DEFAULT_THEME,
1225
+ custom,
1226
+ contentWidth
1227
+ };
1228
+ const migrated = customFromPreset(DEFAULT_THEME);
385
1229
  return {
386
1230
  ...current,
387
- hue: brand.hue,
388
- chroma: brand.chroma,
389
- mode: stored?.mode === "dark" || stored?.mode === "light" ? stored.mode : "system",
390
- contentWidth: CONTENT_WIDTHS.find((width) => width === stored?.contentWidth) ?? "default"
1231
+ mode,
1232
+ theme: "custom",
1233
+ custom: {
1234
+ ...migrated,
1235
+ light: {
1236
+ ...migrated.light,
1237
+ brand: brandColor({
1238
+ hue,
1239
+ chroma
1240
+ }, "light")
1241
+ },
1242
+ dark: {
1243
+ ...migrated.dark,
1244
+ brand: brandColor({
1245
+ hue,
1246
+ chroma
1247
+ }, "dark")
1248
+ }
1249
+ },
1250
+ contentWidth
391
1251
  };
392
1252
  }
393
- }));
394
- /** Applies the scheme, brand and content width to the document, including portalled components. */
1253
+ })(publish, get, api);
1254
+ /** Browser-local appearance state, persisted under its existing preference key. */
1255
+ var useTheme = create()(createThemeState);
1256
+ /** The mode in force, resolving "system" against the operating system. */
1257
+ function resolveMode(mode) {
1258
+ if (mode !== "system") return mode;
1259
+ return window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
1260
+ }
1261
+ /** Applies the scheme, theme and content width to the document, including portalled components. */
395
1262
  function applyTheme(state) {
396
1263
  document.documentElement.dataset.contentWidth = state.contentWidth ?? "default";
397
- applyDocumentTheme(state.mode === "system" ? window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light" : state.mode, state);
1264
+ const mode = resolveMode(state.mode);
1265
+ const custom = state.theme === "custom" ? state.custom : null;
1266
+ const base = custom?.base ?? (state.theme === "custom" ? "neutral" : state.theme);
1267
+ const preset = PRESETS[base];
1268
+ const values = custom === null ? null : {
1269
+ ...custom[mode],
1270
+ brandForeground: brandForeground(custom[mode].brand)
1271
+ };
1272
+ applyDocumentTheme(mode, {
1273
+ hue: preset.hue,
1274
+ chroma: preset.chroma
1275
+ }, {
1276
+ palette: base,
1277
+ custom: values
1278
+ });
398
1279
  }
399
1280
  var themeActivation;
400
1281
  /**
401
- * Applies the stored brand once and keeps it applied. Called before the first
1282
+ * Applies the stored theme once and keeps it applied. Called before the first
402
1283
  * feature renders. Withdrawal removes its listeners and restores the host defaults
403
1284
  * while retaining stored preferences for the next activation.
404
1285
  */
@@ -423,10 +1304,257 @@ function initTheme() {
423
1304
  document.documentElement.dataset.contentWidth = "default";
424
1305
  document.documentElement.style.removeProperty("--brand-h");
425
1306
  document.documentElement.style.removeProperty("--brand-c");
1307
+ document.documentElement.style.removeProperty("--custom-background");
1308
+ document.documentElement.style.removeProperty("--custom-foreground");
1309
+ document.documentElement.style.removeProperty("--custom-brand");
1310
+ document.documentElement.style.removeProperty("--custom-brand-foreground");
1311
+ delete document.documentElement.dataset.palette;
1312
+ delete document.documentElement.dataset.themeCustom;
426
1313
  applyDocumentTheme("light");
427
1314
  };
428
1315
  }
429
1316
  //#endregion
1317
+ //#region ui-src/components/personalization-navigation.tsx
1318
+ /** Shares preferences navigation through contributed category components. */
1319
+ var PersonalizationNavigationContext = createContext(null);
1320
+ /** Returns the enclosing preferences navigation, if the category has a shell. */
1321
+ function usePersonalizationNavigation() {
1322
+ return useContext(PersonalizationNavigationContext);
1323
+ }
1324
+ //#endregion
1325
+ //#region ui-src/components/settings/reading-typography.tsx
1326
+ var families = [
1327
+ {
1328
+ id: "wenkai",
1329
+ family: "LXGW WenKai Screen",
1330
+ chinese: "霞鹜文楷屏幕阅读版",
1331
+ scope: "both"
1332
+ },
1333
+ {
1334
+ id: "source-han-serif",
1335
+ family: "Source Han Serif CN",
1336
+ chinese: "思源宋体",
1337
+ scope: "chinese"
1338
+ },
1339
+ {
1340
+ id: "source-han-sans",
1341
+ family: "Source Han Sans CN",
1342
+ chinese: "思源黑体",
1343
+ scope: "chinese"
1344
+ },
1345
+ {
1346
+ id: "source-serif",
1347
+ family: "Source Serif 4",
1348
+ chinese: "Source Serif 4",
1349
+ scope: "western"
1350
+ },
1351
+ {
1352
+ id: "source-sans",
1353
+ family: "Source Sans 3",
1354
+ chinese: "Source Sans 3",
1355
+ scope: "western"
1356
+ },
1357
+ {
1358
+ id: "atkinson",
1359
+ family: "Atkinson Hyperlegible Next",
1360
+ chinese: "Atkinson Hyperlegible Next",
1361
+ scope: "western"
1362
+ },
1363
+ {
1364
+ id: "literata",
1365
+ family: "Literata",
1366
+ chinese: "Literata",
1367
+ scope: "western"
1368
+ }
1369
+ ];
1370
+ function display(choice) {
1371
+ if (choice.kind === "system") return "system-ui";
1372
+ if (choice.kind === "custom") return choice.value;
1373
+ return families.find((font) => font.id === choice.value)?.family ?? "";
1374
+ }
1375
+ function FontPreference({ script, choice, revision }) {
1376
+ const { i18n } = useTranslation$1();
1377
+ const chinese = i18n.language.startsWith("zh");
1378
+ const context = readingFontDiscoveryContext();
1379
+ const device = useDeviceFonts(context.signal, context.native);
1380
+ const [draft, setDraft] = useState();
1381
+ const invalid = draft?.revision === revision;
1382
+ const label = script === "chinese" ? chinese ? "中文字体" : "Chinese font" : chinese ? "西文字体" : "Western font";
1383
+ const options = families.filter((font) => font.scope === "both" || font.scope === script);
1384
+ return /* @__PURE__ */ jsx(Field, {
1385
+ label,
1386
+ inline: true,
1387
+ className: "settings-field-row flex flex-row flex-wrap items-center justify-between [&>div:nth-child(2)]:ml-auto",
1388
+ error: invalid ? chinese ? "请输入有效的字体名称或完整字体列表。" : "Enter a valid font name or complete font-family list." : void 0,
1389
+ children: (binding) => /* @__PURE__ */ jsx("div", {
1390
+ className: "flex min-w-0 justify-end",
1391
+ children: /* @__PURE__ */ jsx(FontPicker, {
1392
+ ...binding,
1393
+ className: "w-72 max-w-full",
1394
+ label,
1395
+ onLoadFonts: device.available ? device.load : void 0,
1396
+ loading: device.loading,
1397
+ loadError: device.failed ? chinese ? "未能读取本机字体" : "Could not read device fonts" : void 0,
1398
+ loadUnavailable: !device.available ? chinese ? "当前环境不支持读取字体" : "Device fonts unavailable" : void 0,
1399
+ value: invalid ? draft.value : display(choice),
1400
+ "aria-invalid": invalid,
1401
+ onValueChange: (value) => {
1402
+ const builtin = options.find((font) => font.family === value);
1403
+ const next = value === "system-ui" ? { kind: "system" } : builtin ? {
1404
+ kind: "builtin",
1405
+ value: builtin.id
1406
+ } : {
1407
+ kind: "custom",
1408
+ value
1409
+ };
1410
+ const accepted = readingTypography.update({ [script]: next });
1411
+ setDraft(accepted ? void 0 : {
1412
+ value,
1413
+ revision
1414
+ });
1415
+ },
1416
+ options: [
1417
+ ...device.options,
1418
+ {
1419
+ value: "system-ui",
1420
+ label: chinese ? "系统默认" : "System default",
1421
+ group: "system"
1422
+ },
1423
+ ...options.map((font) => ({
1424
+ value: font.family,
1425
+ label: chinese ? font.chinese : font.family,
1426
+ previewFamily: "var(--font-sans)",
1427
+ group: "builtin",
1428
+ note: chinese ? "内置字体,选择后加载;此处使用系统字体预览。" : "Bundled; loads when selected. Preview uses the system font."
1429
+ }))
1430
+ ]
1431
+ })
1432
+ })
1433
+ });
1434
+ }
1435
+ /** Local reading controls apply independently of theme, terminal and gateway settings. */
1436
+ function ReadingTypographySettings() {
1437
+ const { i18n } = useTranslation$1();
1438
+ const chinese = i18n.language.startsWith("zh");
1439
+ const fonts = useSyncExternalStore(subscribeReadingFontStatus, getReadingFontStatus);
1440
+ const state = useSyncExternalStore(readingTypography.subscribe, readingTypography.getSnapshot);
1441
+ const [sizeDraft, setSizeDraft] = useState();
1442
+ const editingSize = sizeDraft?.revision === state;
1443
+ return /* @__PURE__ */ jsxs("section", {
1444
+ className: "space-y-4",
1445
+ "aria-label": chinese ? "阅读字体" : "Reading typography",
1446
+ children: [
1447
+ /* @__PURE__ */ jsx("h3", {
1448
+ className: "text-sm font-medium",
1449
+ children: chinese ? "阅读字体" : "Reading typography"
1450
+ }),
1451
+ /* @__PURE__ */ jsx(FontPreference, {
1452
+ script: "chinese",
1453
+ choice: state.preferences.chinese,
1454
+ revision: state
1455
+ }),
1456
+ /* @__PURE__ */ jsx(FontPreference, {
1457
+ script: "western",
1458
+ choice: state.preferences.western,
1459
+ revision: state
1460
+ }),
1461
+ /* @__PURE__ */ jsx(Field, {
1462
+ label: chinese ? "正文字号" : "Body size",
1463
+ inline: true,
1464
+ className: "settings-field-row flex flex-row flex-wrap items-center justify-between [&>div:nth-child(2)]:ml-auto",
1465
+ children: (binding) => /* @__PURE__ */ jsx("fieldset", {
1466
+ "aria-label": chinese ? "正文字号调整" : "Body size adjustment",
1467
+ className: "flex min-w-0 justify-end border-0 p-0",
1468
+ onBlur: (event) => {
1469
+ if (!event.currentTarget.contains(event.relatedTarget)) setSizeDraft(void 0);
1470
+ },
1471
+ children: /* @__PURE__ */ jsx(InputNumber, {
1472
+ ...binding,
1473
+ label: chinese ? "正文字号" : "Body size",
1474
+ incrementLabel: chinese ? "增大正文字号" : "Increase body size",
1475
+ decrementLabel: chinese ? "减小正文字号" : "Decrease body size",
1476
+ min: 14,
1477
+ max: 22,
1478
+ step: 1,
1479
+ allowOutOfRange: true,
1480
+ value: editingSize ? sizeDraft.value : state.preferences.bodySize,
1481
+ "aria-invalid": editingSize && sizeDraft.value !== null,
1482
+ className: "w-36 max-w-full",
1483
+ onValueChange: (value) => {
1484
+ const accepted = value !== null && readingTypography.update({ bodySize: value });
1485
+ setSizeDraft(accepted ? void 0 : {
1486
+ value,
1487
+ revision: state
1488
+ });
1489
+ }
1490
+ })
1491
+ })
1492
+ }),
1493
+ fonts.loading && /* @__PURE__ */ jsx("p", {
1494
+ role: "status",
1495
+ className: "text-xs text-muted-foreground",
1496
+ children: chinese ? "正在加载阅读字体…" : "Loading reading fonts…"
1497
+ }),
1498
+ fonts.failed.length > 0 && /* @__PURE__ */ jsx("p", {
1499
+ role: "status",
1500
+ className: "text-xs text-muted-foreground",
1501
+ children: chinese ? "部分字体未能加载,当前使用系统回退字体。重新选择可重试。" : "Some fonts could not load. System fallback is active; select a font again to retry."
1502
+ }),
1503
+ state.saveFailed && /* @__PURE__ */ jsx("p", {
1504
+ role: "status",
1505
+ className: "text-xs text-destructive",
1506
+ children: chinese ? "设置已应用,但未能保存到此浏览器。" : "Applied, but could not save in this browser."
1507
+ })
1508
+ ]
1509
+ });
1510
+ }
1511
+ //#endregion
1512
+ //#region ui-src/components/settings/theme-preview.tsx
1513
+ /** A decorative conversation specimen using the selected palette without changing the document. */
1514
+ function ThemePreview({ base, mode, colors, large = false }) {
1515
+ const preset = THEME_PRESETS.find((entry) => entry.id === base);
1516
+ if (!preset) throw new Error("Unknown theme preset");
1517
+ const brand = colors?.brand ?? `oklch(${mode === "light" ? .52 : .76} ${preset.chroma * (mode === "light" ? 1 : .8)} ${preset.hue})`;
1518
+ return /* @__PURE__ */ jsxs("span", {
1519
+ "aria-hidden": "true",
1520
+ className: cn(`palette-${base} palette-preview-${mode} flex min-w-0 flex-col overflow-hidden rounded-control p-3`, large ? "h-60 gap-5 p-6" : "h-36 gap-3"),
1521
+ style: colors ? {
1522
+ background: colors.background,
1523
+ color: colors.foreground
1524
+ } : void 0,
1525
+ children: [
1526
+ /* @__PURE__ */ jsxs("span", {
1527
+ className: "flex items-center gap-2",
1528
+ children: [/* @__PURE__ */ jsx("span", { className: cn("shrink-0 rounded-full bg-current opacity-25", large ? "size-5" : "size-3") }), /* @__PURE__ */ jsx("span", { className: "h-1 w-1/3 rounded-full bg-current opacity-30" })]
1529
+ }),
1530
+ /* @__PURE__ */ jsx("span", {
1531
+ className: cn("flex flex-1 flex-col gap-1.5", large ? "ml-7 gap-2.5" : "ml-5"),
1532
+ children: [
1533
+ 100,
1534
+ 82,
1535
+ 60,
1536
+ 92,
1537
+ 67
1538
+ ].map((width, index) => /* @__PURE__ */ jsx("span", {
1539
+ className: cn("h-1 rounded-full bg-current opacity-35", index === 3 && "mt-2"),
1540
+ style: { width: `${width}%` }
1541
+ }, width))
1542
+ }),
1543
+ /* @__PURE__ */ jsxs("span", {
1544
+ className: cn("flex items-center justify-between gap-2 rounded-control border border-current/20 px-2", large ? "h-10" : "h-7"),
1545
+ children: [/* @__PURE__ */ jsx("span", { className: "h-1 w-2/5 rounded-full bg-current opacity-20" }), /* @__PURE__ */ jsx("span", {
1546
+ className: cn("flex items-center justify-center rounded-control", large ? "size-6" : "size-4"),
1547
+ style: { background: brand },
1548
+ children: /* @__PURE__ */ jsx(ArrowUp, {
1549
+ className: large ? "size-4" : "size-3",
1550
+ style: { color: colors?.background ?? (mode === "light" ? "#ffffff" : "#202020") }
1551
+ })
1552
+ })]
1553
+ })
1554
+ ]
1555
+ });
1556
+ }
1557
+ //#endregion
430
1558
  //#region ui-src/components/settings/appearance.tsx
431
1559
  /** Browser-local language, color scheme and brand preferences. */
432
1560
  function PreferenceRow({ id, label, children }) {
@@ -437,20 +1565,114 @@ function PreferenceRow({ id, label, children }) {
437
1565
  className: "min-w-0 text-sm font-normal",
438
1566
  children: label
439
1567
  }), /* @__PURE__ */ jsx("div", {
440
- className: "flex min-w-0 max-w-full items-center justify-end",
1568
+ className: "ml-auto flex min-w-0 max-w-full items-center justify-end",
441
1569
  children
442
1570
  })]
443
1571
  });
444
1572
  }
1573
+ /** The mode a colour belongs to right now: the chosen one, or the system's. */
1574
+ function useResolvedMode(mode) {
1575
+ const [system, setSystem] = useState(() => window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light");
1576
+ useEffect(() => {
1577
+ const query = window.matchMedia?.("(prefers-color-scheme: dark)");
1578
+ if (!query) return;
1579
+ const onChange = () => setSystem(query.matches ? "dark" : "light");
1580
+ query.addEventListener("change", onChange);
1581
+ return () => query.removeEventListener("change", onChange);
1582
+ }, []);
1583
+ return mode === "system" ? system : mode;
1584
+ }
1585
+ /** The existing three presets and one custom palette share compact conversation previews. */
1586
+ function ThemeCards() {
1587
+ const { t } = useTranslation$1();
1588
+ const { theme, setTheme, custom, mode } = useTheme();
1589
+ const editing = useResolvedMode(mode);
1590
+ const navigation = usePersonalizationNavigation();
1591
+ const choices = [...THEME_PRESETS.map((preset) => preset.id), "custom"];
1592
+ return /* @__PURE__ */ jsxs("div", {
1593
+ className: "@container flex min-w-0 flex-col gap-3",
1594
+ children: [
1595
+ /* @__PURE__ */ jsx("p", {
1596
+ className: "text-sm font-medium",
1597
+ children: t("settings.theme")
1598
+ }),
1599
+ /* @__PURE__ */ jsx("p", {
1600
+ className: "text-xs text-muted-foreground",
1601
+ children: t("settings.themeHint")
1602
+ }),
1603
+ /* @__PURE__ */ jsx("div", {
1604
+ className: "grid grid-cols-1 gap-3 @min-[24rem]:grid-cols-2 @min-[40rem]:grid-cols-4",
1605
+ children: choices.map((choice) => {
1606
+ const label = t(`settings.theme${choice.charAt(0).toUpperCase()}${choice.slice(1)}`);
1607
+ const base = choice === "custom" ? custom?.base ?? (theme === "custom" ? "neutral" : theme) : choice;
1608
+ const selected = theme === choice;
1609
+ return /* @__PURE__ */ jsxs("div", {
1610
+ "data-theme-card": true,
1611
+ className: "relative min-w-0",
1612
+ children: [/* @__PURE__ */ jsxs("button", {
1613
+ type: "button",
1614
+ "aria-label": label,
1615
+ "aria-pressed": selected,
1616
+ className: `flex w-full min-w-0 flex-col gap-3 rounded-surface border p-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring ${selected ? "border-primary bg-primary/5" : "border-border hover:bg-muted/30"}`,
1617
+ onClick: () => setTheme(choice),
1618
+ children: [/* @__PURE__ */ jsx("span", {
1619
+ className: "flex min-w-0 items-center gap-2 pr-6 text-sm font-medium",
1620
+ children: /* @__PURE__ */ jsx("span", {
1621
+ className: "truncate",
1622
+ children: label
1623
+ })
1624
+ }), /* @__PURE__ */ jsx(ThemePreview, {
1625
+ base,
1626
+ mode: editing,
1627
+ colors: choice === "custom" ? custom?.[editing] : void 0
1628
+ })]
1629
+ }), /* @__PURE__ */ jsx("button", {
1630
+ type: "button",
1631
+ "data-theme-edit": choice,
1632
+ ref: (entry) => {
1633
+ if (entry) navigation?.themeEntryMounted(choice, entry);
1634
+ },
1635
+ "aria-label": t("settings.themeEdit", { name: label }),
1636
+ title: t("settings.themeEdit", { name: label }),
1637
+ className: "absolute top-2 right-2 flex size-7 items-center justify-center rounded-control text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",
1638
+ onClick: () => navigation?.editTheme(choice),
1639
+ children: /* @__PURE__ */ jsx(Pencil, {
1640
+ "aria-hidden": "true",
1641
+ className: "size-3.5"
1642
+ })
1643
+ })]
1644
+ }, choice);
1645
+ })
1646
+ })
1647
+ ]
1648
+ });
1649
+ }
445
1650
  /** Preferences apply immediately and persist in this browser without gateway writes. */
446
- function AppearancePanel() {
1651
+ function InterfacePreferences() {
447
1652
  const { t, i18n } = useTranslation$1();
448
1653
  const languageLabel = useId();
449
1654
  const current = i18n.resolvedLanguage ?? i18n.language;
450
- const { mode, setMode, hue, setBrand, contentWidth, setContentWidth } = useTheme();
1655
+ const { mode, setMode } = useTheme();
451
1656
  return /* @__PURE__ */ jsxs("div", {
452
1657
  className: "flex min-w-0 flex-col gap-6",
453
1658
  children: [
1659
+ /* @__PURE__ */ jsx(PreferenceRow, {
1660
+ id: languageLabel,
1661
+ label: t("settings.interfaceLanguage"),
1662
+ children: /* @__PURE__ */ jsx(Picker, {
1663
+ labelledBy: languageLabel,
1664
+ slot: "language-picker",
1665
+ value: current,
1666
+ options: LANGUAGES.map((language) => ({
1667
+ value: language,
1668
+ label: t(language === "en-US" ? "language.en-US" : "language.zh-CN"),
1669
+ prefix: LANGUAGE_FLAGS[language]
1670
+ })),
1671
+ onSelect: (language) => {
1672
+ i18n.changeLanguage(language);
1673
+ }
1674
+ })
1675
+ }),
454
1676
  /* @__PURE__ */ jsx(PreferenceRow, {
455
1677
  label: t("settings.colorMode"),
456
1678
  children: /* @__PURE__ */ jsx(Segmented, {
@@ -473,81 +1695,474 @@ function AppearancePanel() {
473
1695
  ]
474
1696
  })
475
1697
  }),
476
- /* @__PURE__ */ jsx(PreferenceRow, {
477
- label: t("settings.brand"),
478
- children: /* @__PURE__ */ jsx(ThemeColorPicker, {
479
- label: t("settings.brand"),
480
- value: BRANDS.find((brand) => brand.hue === hue)?.id ?? "alkaid",
481
- options: BRANDS.map((brand) => ({
482
- value: brand.id,
483
- label: t(brand.labelKey),
484
- color: themeSwatchColor(brand)
485
- })),
486
- onValueChange: (value) => {
487
- const brand = BRANDS.find((brand) => brand.id === value);
488
- if (brand) setBrand(brand);
489
- }
490
- })
491
- }),
492
- /* @__PURE__ */ jsx(PreferenceRow, {
1698
+ /* @__PURE__ */ jsx(ThemeCards, {})
1699
+ ]
1700
+ });
1701
+ }
1702
+ /** Restores the reading category's typography and content width through their owner stores. */
1703
+ function resetReadingPreferences() {
1704
+ readingTypography.reset();
1705
+ useTheme.getState().setContentWidth("default");
1706
+ }
1707
+ /** Reading preferences apply immediately through the existing typography and theme stores. */
1708
+ function ReadingPreferences() {
1709
+ const { t } = useTranslation$1();
1710
+ const { contentWidth, setContentWidth } = useTheme();
1711
+ const { preferences } = useSyncExternalStore(readingTypography.subscribe, readingTypography.getSnapshot);
1712
+ return /* @__PURE__ */ jsxs("div", {
1713
+ className: "@container flex min-w-0 flex-1 flex-col gap-6",
1714
+ children: [/* @__PURE__ */ jsxs("div", {
1715
+ className: "flex min-w-0 flex-col gap-4",
1716
+ children: [/* @__PURE__ */ jsx(ReadingTypographySettings, {}), /* @__PURE__ */ jsx(Field, {
493
1717
  label: t("settings.contentWidth"),
494
- children: /* @__PURE__ */ jsx(Segmented, {
495
- label: t("settings.contentWidth"),
496
- value: contentWidth,
497
- onSelect: setContentWidth,
498
- options: [
499
- {
500
- value: "default",
501
- label: t("settings.contentWidthDefault")
502
- },
503
- {
504
- value: "wide",
505
- label: t("settings.contentWidthWide")
506
- },
507
- {
508
- value: "full",
509
- label: t("settings.contentWidthFull")
510
- }
511
- ]
512
- })
513
- }),
514
- /* @__PURE__ */ jsx(SlotOutlet, {
515
- slot: "shell.personalization.section",
516
- props: {}
517
- }),
518
- /* @__PURE__ */ jsx(PreferenceRow, {
519
- id: languageLabel,
520
- label: t("settings.interfaceLanguage"),
521
- children: /* @__PURE__ */ jsx(Picker, {
522
- labelledBy: languageLabel,
523
- slot: "language-picker",
524
- value: current,
525
- options: LANGUAGES.map((language) => ({
526
- value: language,
527
- label: t(language === "en-US" ? "language.en-US" : "language.zh-CN"),
528
- prefix: LANGUAGE_FLAGS[language]
529
- })),
530
- onSelect: (language) => {
531
- i18n.changeLanguage(language);
532
- }
1718
+ inline: true,
1719
+ className: "settings-field-row flex flex-row flex-wrap items-center justify-between [&>div:nth-child(2)]:ml-auto",
1720
+ children: () => /* @__PURE__ */ jsx("div", {
1721
+ className: "flex min-w-0 justify-end",
1722
+ children: /* @__PURE__ */ jsx(Segmented, {
1723
+ className: "flex",
1724
+ label: t("settings.contentWidth"),
1725
+ value: contentWidth,
1726
+ onSelect: setContentWidth,
1727
+ options: [
1728
+ {
1729
+ value: "default",
1730
+ label: t("settings.contentWidthDefault")
1731
+ },
1732
+ {
1733
+ value: "wide",
1734
+ label: t("settings.contentWidthWide")
1735
+ },
1736
+ {
1737
+ value: "full",
1738
+ label: t("settings.contentWidthFull")
1739
+ }
1740
+ ]
1741
+ })
533
1742
  })
1743
+ })]
1744
+ }), /* @__PURE__ */ jsx(SettingsPreview, {
1745
+ title: t("settings.preview"),
1746
+ infoLabel: t("settings.previewInfo"),
1747
+ description: t("settings.previewDescription"),
1748
+ kind: t("settings.previewReading"),
1749
+ canvasClassName: "bg-muted/30 leading-[1.8]",
1750
+ canvasStyle: { fontSize: preferences.bodySize },
1751
+ children: /* @__PURE__ */ jsxs("div", {
1752
+ "data-reading-body": true,
1753
+ className: "space-y-2",
1754
+ children: [
1755
+ /* @__PURE__ */ jsx("p", {
1756
+ "data-reading-script": "chinese",
1757
+ className: "font-semibold",
1758
+ style: { fontFamily: readingFontFamily(preferences.chinese) },
1759
+ children: "让文字读起来更舒服"
1760
+ }),
1761
+ /* @__PURE__ */ jsx("p", {
1762
+ "data-reading-script": "chinese",
1763
+ style: { fontFamily: readingFontFamily(preferences.chinese) },
1764
+ children: "天地玄黄,宇宙洪荒。选一种合适的字体,让每一次阅读都自然、清晰。"
1765
+ }),
1766
+ /* @__PURE__ */ jsx("p", {
1767
+ "data-reading-script": "western",
1768
+ style: { fontFamily: readingFontFamily(preferences.western) },
1769
+ children: "The quick brown fox jumps over the lazy dog."
1770
+ }),
1771
+ /* @__PURE__ */ jsxs("p", { children: [
1772
+ /* @__PURE__ */ jsxs("span", {
1773
+ "data-reading-script": "western",
1774
+ style: { fontFamily: readingFontFamily(preferences.western) },
1775
+ children: ["0123456789 · Aa Bb Cc ·", " "]
1776
+ }),
1777
+ /* @__PURE__ */ jsxs("span", {
1778
+ "data-reading-script": "chinese",
1779
+ style: { fontFamily: readingFontFamily(preferences.chinese) },
1780
+ children: ["中文与", " "]
1781
+ }),
1782
+ /* @__PURE__ */ jsx("span", {
1783
+ "data-reading-script": "western",
1784
+ style: { fontFamily: readingFontFamily(preferences.western) },
1785
+ children: "English"
1786
+ })
1787
+ ] })
1788
+ ]
534
1789
  })
535
- ]
1790
+ })]
1791
+ });
1792
+ }
1793
+ //#endregion
1794
+ //#region ui-src/components/settings/theme-editor.tsx
1795
+ /** Edits both color modes in a detached draft; navigation remains owned by the preferences shell. */
1796
+ function ThemeEditor({ source, onCancel, onSaved, onDirtyChange }) {
1797
+ const { t } = useTranslation$1();
1798
+ const [initial] = useState(() => createThemeDraft(source));
1799
+ const [draft, setDraft] = useState(initial);
1800
+ const [preview, setPreview] = useState(initial);
1801
+ const saving = useRef(false);
1802
+ const dirty = JSON.stringify(draft) !== JSON.stringify(initial);
1803
+ useEffect(() => {
1804
+ onDirtyChange(dirty);
1805
+ return () => onDirtyChange(false);
1806
+ }, [dirty, onDirtyChange]);
1807
+ const [mode, setMode] = useState(() => {
1808
+ const selected = useTheme.getState().mode;
1809
+ if (selected !== "system") return selected;
1810
+ return window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
1811
+ });
1812
+ const fieldId = useId();
1813
+ const [invalid, setInvalid] = useState(false);
1814
+ const [error, setError] = useState(null);
1815
+ const updateColor = (role, value) => {
1816
+ setError(null);
1817
+ setDraft((current) => ({
1818
+ ...current,
1819
+ [mode]: {
1820
+ ...current[mode],
1821
+ [role]: value
1822
+ }
1823
+ }));
1824
+ const parsed = parseColorHex(value);
1825
+ if (parsed !== null && parsed.a === 1) setPreview((current) => ({
1826
+ ...current,
1827
+ [mode]: {
1828
+ ...current[mode],
1829
+ [role]: colorToHex(parsed)
1830
+ }
1831
+ }));
1832
+ };
1833
+ const valid = (value) => {
1834
+ const parsed = parseColorHex(value);
1835
+ return parsed !== null && parsed.a === 1;
1836
+ };
1837
+ const save = () => {
1838
+ if (saving.current) return;
1839
+ const invalidMode = ["light", "dark"].find((candidate) => roles.some((role) => !valid(draft[candidate][role])));
1840
+ if (invalidMode) {
1841
+ setInvalid(true);
1842
+ setMode(invalidMode);
1843
+ setError(t("settings.themeInvalidColor"));
1844
+ return;
1845
+ }
1846
+ saving.current = true;
1847
+ try {
1848
+ useTheme.getState().saveCustomTheme(draft);
1849
+ onSaved();
1850
+ } catch {
1851
+ setError(t("settings.themeSaveError"));
1852
+ } finally {
1853
+ saving.current = false;
1854
+ }
1855
+ };
1856
+ const roles = [
1857
+ "background",
1858
+ "foreground",
1859
+ "brand"
1860
+ ];
1861
+ return /* @__PURE__ */ jsxs("div", {
1862
+ className: "@container flex min-h-0 min-w-0 flex-1 flex-col",
1863
+ children: [/* @__PURE__ */ jsxs("div", {
1864
+ className: "flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto px-6 pt-1 pb-6",
1865
+ children: [
1866
+ /* @__PURE__ */ jsx("div", {
1867
+ className: "flex shrink-0 justify-end",
1868
+ children: /* @__PURE__ */ jsx(Segmented, {
1869
+ label: t("settings.themePreviewMode"),
1870
+ value: mode,
1871
+ onSelect: setMode,
1872
+ options: [{
1873
+ value: "light",
1874
+ label: t("settings.lightMode")
1875
+ }, {
1876
+ value: "dark",
1877
+ label: t("settings.darkMode")
1878
+ }]
1879
+ })
1880
+ }),
1881
+ error && /* @__PURE__ */ jsx("p", {
1882
+ id: `${fieldId}-error`,
1883
+ role: "alert",
1884
+ className: "rounded-control border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive",
1885
+ children: error
1886
+ }),
1887
+ /* @__PURE__ */ jsxs("div", {
1888
+ className: "grid min-w-0 shrink-0 gap-6 @min-[36rem]:grid-cols-[minmax(0,1fr)_14rem]",
1889
+ children: [/* @__PURE__ */ jsxs("section", {
1890
+ "aria-label": t("settings.themePreview"),
1891
+ className: "min-w-0 rounded-surface border border-border bg-muted/20 p-4",
1892
+ children: [/* @__PURE__ */ jsx(ThemePreview, {
1893
+ large: true,
1894
+ base: draft.base,
1895
+ mode,
1896
+ colors: preview[mode]
1897
+ }), /* @__PURE__ */ jsx("p", {
1898
+ className: "mt-3 text-xs text-muted-foreground",
1899
+ children: t("settings.themePreviewHint")
1900
+ })]
1901
+ }), /* @__PURE__ */ jsx("div", {
1902
+ className: "flex min-w-0 flex-col gap-5 rounded-surface border border-border p-4",
1903
+ children: roles.map((role) => /* @__PURE__ */ jsxs("div", {
1904
+ className: "flex min-w-0 flex-col gap-2 text-sm",
1905
+ children: [/* @__PURE__ */ jsx("label", {
1906
+ htmlFor: `${fieldId}-${role}`,
1907
+ children: t(`settings.theme${role.charAt(0).toUpperCase()}${role.slice(1)}`)
1908
+ }), /* @__PURE__ */ jsxs("div", {
1909
+ className: "flex min-w-0 items-center gap-2",
1910
+ children: [/* @__PURE__ */ jsx(ColorPicker, {
1911
+ label: t("settings.themePickColor", { name: t(`settings.theme${role.charAt(0).toUpperCase()}${role.slice(1)}`) }),
1912
+ alpha: false,
1913
+ className: "size-8 shrink-0 justify-center p-0 [&>span:last-child]:hidden",
1914
+ value: parseColorHex(preview[mode][role]) ?? void 0,
1915
+ onChange: (value) => updateColor(role, colorToHex(value))
1916
+ }), /* @__PURE__ */ jsx(Input, {
1917
+ id: `${fieldId}-${role}`,
1918
+ "aria-invalid": invalid && !valid(draft[mode][role]) || void 0,
1919
+ "aria-describedby": invalid && !valid(draft[mode][role]) ? `${fieldId}-error` : void 0,
1920
+ value: draft[mode][role],
1921
+ onChange: (event) => updateColor(role, event.target.value),
1922
+ className: "font-mono text-xs"
1923
+ })]
1924
+ })]
1925
+ }, role))
1926
+ })]
1927
+ })
1928
+ ]
1929
+ }), /* @__PURE__ */ jsxs("div", {
1930
+ className: "grid shrink-0 grid-cols-2 gap-2 px-6 pt-4 pb-6",
1931
+ children: [/* @__PURE__ */ jsx(Button, {
1932
+ variant: "outline",
1933
+ onClick: onCancel,
1934
+ children: t("settings.themeCancel")
1935
+ }), /* @__PURE__ */ jsx(Button, {
1936
+ variant: "primary",
1937
+ icon: "save",
1938
+ onClick: save,
1939
+ children: t("settings.themeSave")
1940
+ })]
1941
+ })]
536
1942
  });
537
1943
  }
538
1944
  //#endregion
539
1945
  //#region ui-src/components/personalization-dialog.tsx
540
- /** Compact browser-local preferences, independent of gateway settings and their drafts. */
1946
+ /** Owner-contributed preferences share the system settings geometry and content boundaries. */
541
1947
  function PersonalizationDialog({ open, onOpenChange: setOpen }) {
542
1948
  const { t } = useTranslation$1();
543
- return /* @__PURE__ */ jsx(Dialog, {
1949
+ const contributions = usePlugins((state) => state.contributions);
1950
+ const crashed = usePlugins((state) => state.crashed);
1951
+ const categories = useMemo(() => contributionsIn({
1952
+ contributions,
1953
+ crashed
1954
+ }, "shell.personalization.category"), [contributions, crashed]);
1955
+ const roots = categories.filter((entry) => !entry.contribution.parent);
1956
+ const [selected, setSelected] = useState();
1957
+ const [editor, setEditor] = useState();
1958
+ const dirty = useRef(false);
1959
+ const pageHeading = useRef(null);
1960
+ const focusSource = useRef(void 0);
1961
+ const restoreSource = useRef(void 0);
1962
+ const [pending, setPending] = useState(null);
1963
+ const setDirty = useCallback((next) => {
1964
+ dirty.current = next;
1965
+ }, []);
1966
+ const closeEditor = useCallback(() => {
1967
+ dirty.current = false;
1968
+ setEditor(void 0);
1969
+ const source = focusSource.current;
1970
+ focusSource.current = void 0;
1971
+ if (source) restoreSource.current = source;
1972
+ }, []);
1973
+ const themeEntryMounted = useCallback((source, entry) => {
1974
+ if (restoreSource.current !== source) return;
1975
+ restoreSource.current = void 0;
1976
+ requestAnimationFrame(() => {
1977
+ requestAnimationFrame(() => {
1978
+ if (!entry.isConnected) return;
1979
+ const active = entry.ownerDocument.activeElement;
1980
+ const popup = entry.closest("[role=\"dialog\"]");
1981
+ if (active !== entry.ownerDocument.body && active !== popup && active !== entry) return;
1982
+ entry.focus({ preventScroll: true });
1983
+ entry.closest("[data-theme-card]")?.scrollIntoView?.({
1984
+ block: "nearest",
1985
+ inline: "nearest"
1986
+ });
1987
+ });
1988
+ });
1989
+ }, []);
1990
+ const requestLeave = useCallback((next) => {
1991
+ const proceed = () => {
1992
+ closeEditor();
1993
+ next();
1994
+ };
1995
+ if (dirty.current) setPending(() => proceed);
1996
+ else proceed();
1997
+ }, [closeEditor]);
1998
+ useEffect(() => {
1999
+ if (editor) pageHeading.current?.focus();
2000
+ }, [editor]);
2001
+ const current = roots.find((entry) => entry.key === selected) ?? roots[0];
2002
+ useEffect(() => {
2003
+ const next = open ? current?.key : void 0;
2004
+ if (selected !== next) setSelected(next);
2005
+ }, [
544
2006
  open,
545
- onOpenChange: setOpen,
546
- children: /* @__PURE__ */ jsxs(DialogContent, {
547
- closeLabel: t("settings.close"),
548
- className: "personalization-dialog max-h-[calc(100dvh-4rem)] max-w-lg gap-5 overflow-y-auto p-6 sm:max-w-lg",
549
- children: [/* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: t("settings.personalization") }) }), /* @__PURE__ */ jsx(AppearancePanel, {})]
550
- })
2007
+ current?.key,
2008
+ selected
2009
+ ]);
2010
+ useEffect(() => {
2011
+ closeEditor();
2012
+ restoreSource.current = void 0;
2013
+ setPending(null);
2014
+ }, [
2015
+ open,
2016
+ current?.key,
2017
+ closeEditor
2018
+ ]);
2019
+ const children = categories.filter((entry) => entry.contribution.parent === current?.key);
2020
+ const resettable = current ? [current, ...children].filter((entry) => entry.contribution.onReset) : [];
2021
+ const title = current ? resolveLabel(current.contribution.label, current.contribution.id) : t("settings.personalization");
2022
+ return /* @__PURE__ */ jsxs(PersonalizationNavigationContext.Provider, {
2023
+ value: {
2024
+ themeEntryMounted,
2025
+ editTheme: (source) => requestLeave(() => {
2026
+ focusSource.current = source;
2027
+ setEditor(source);
2028
+ })
2029
+ },
2030
+ children: [/* @__PURE__ */ jsx(Dialog, {
2031
+ open,
2032
+ onOpenChange: (next) => next ? setOpen(true) : requestLeave(() => setOpen(false)),
2033
+ children: /* @__PURE__ */ jsxs(DialogContent, {
2034
+ closeLabel: t("settings.close"),
2035
+ className: "settings-dialog personalization-dialog h-dialog max-w-5xl grid-cols-[12.5rem_minmax(0,1fr)] gap-0 overflow-hidden sm:max-w-5xl",
2036
+ children: [/* @__PURE__ */ jsxs("nav", {
2037
+ "aria-label": t("settings.personalizationCategories"),
2038
+ "data-slot": "settings-contents",
2039
+ className: "settings-navigation surface-column flex min-h-0 flex-col overflow-hidden bg-muted/30 px-3 pb-4",
2040
+ children: [
2041
+ /* @__PURE__ */ jsx(DialogHeader, {
2042
+ className: "flex h-16 shrink-0 justify-center px-3 pr-0",
2043
+ children: /* @__PURE__ */ jsx(DialogTitle, { children: t("settings.personalization") })
2044
+ }),
2045
+ /* @__PURE__ */ jsx("div", {
2046
+ className: "settings-category-list flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto",
2047
+ children: roots.map((entry) => {
2048
+ const Icon = PLUGIN_ICONS[entry.contribution.icon ?? "puzzle"];
2049
+ return /* @__PURE__ */ jsxs(Button, {
2050
+ variant: "plain",
2051
+ "data-plugin": entry.owner,
2052
+ "aria-current": entry.key === current?.key,
2053
+ onClick: () => requestLeave(() => setSelected(entry.key)),
2054
+ className: cn("flex min-h-9 shrink-0 items-center gap-2.5 rounded-control px-3 py-2 text-left text-sm outline-none transition-colors duration-150", entry.key === current?.key ? "bg-accent font-medium text-accent-foreground" : "text-muted-foreground hover:bg-muted hover:text-foreground"),
2055
+ children: [/* @__PURE__ */ jsx(Icon, {
2056
+ "aria-hidden": "true",
2057
+ className: "size-4 shrink-0"
2058
+ }), resolveLabel(entry.contribution.label, entry.contribution.id)]
2059
+ }, entry.key);
2060
+ })
2061
+ }),
2062
+ current && /* @__PURE__ */ jsx("div", {
2063
+ className: "settings-category-select hidden pb-3",
2064
+ children: /* @__PURE__ */ jsx(Select, {
2065
+ "aria-label": t("settings.personalizationCategories"),
2066
+ value: current.key,
2067
+ onValueChange: (next) => requestLeave(() => setSelected(next)),
2068
+ children: roots.map((entry) => /* @__PURE__ */ jsx("option", {
2069
+ value: entry.key,
2070
+ children: resolveLabel(entry.contribution.label, entry.contribution.id)
2071
+ }, entry.key))
2072
+ })
2073
+ })
2074
+ ]
2075
+ }), /* @__PURE__ */ jsxs("div", {
2076
+ className: "flex min-h-0 min-w-0 flex-col overflow-hidden bg-card",
2077
+ children: [
2078
+ /* @__PURE__ */ jsx(DialogDescription, {
2079
+ className: "sr-only",
2080
+ children: title
2081
+ }),
2082
+ /* @__PURE__ */ jsxs("header", {
2083
+ "data-slot": "settings-page-header",
2084
+ className: "flex h-16 shrink-0 items-center justify-between gap-3 px-6 pr-14",
2085
+ children: [/* @__PURE__ */ jsxs("div", {
2086
+ className: "flex min-w-0 items-center gap-2",
2087
+ children: [editor && /* @__PURE__ */ jsx(Button, {
2088
+ variant: "plain",
2089
+ "aria-label": t("settings.themeBack"),
2090
+ onClick: () => requestLeave(() => {}),
2091
+ className: "flex size-8 shrink-0 items-center justify-center rounded-control",
2092
+ children: /* @__PURE__ */ jsx(ArrowLeft, { className: "size-4" })
2093
+ }), /* @__PURE__ */ jsx("h2", {
2094
+ ref: pageHeading,
2095
+ tabIndex: -1,
2096
+ className: "min-w-0 text-lg font-semibold outline-none",
2097
+ children: editor ? t("settings.themeEditor") : title
2098
+ })]
2099
+ }), !editor && resettable.length > 0 && /* @__PURE__ */ jsx(Button, {
2100
+ variant: "text",
2101
+ className: "shrink-0",
2102
+ onClick: () => requestLeave(() => {
2103
+ for (const entry of resettable) entry.contribution.onReset?.();
2104
+ }),
2105
+ children: t("settings.resetCategory")
2106
+ })]
2107
+ }),
2108
+ /* @__PURE__ */ jsx("div", {
2109
+ "data-slot": "settings-scroll",
2110
+ className: cn("flex min-h-0 min-w-0 flex-1 flex-col", editor ? "overflow-hidden" : "gap-8 overflow-y-auto px-6 pt-1 pb-6"),
2111
+ children: editor ? /* @__PURE__ */ jsx(ThemeEditor, {
2112
+ source: editor,
2113
+ onCancel: () => requestLeave(() => {}),
2114
+ onSaved: closeEditor,
2115
+ onDirtyChange: setDirty
2116
+ }, editor) : current ? /* @__PURE__ */ jsxs("div", {
2117
+ className: "flex min-w-0 flex-1 flex-col gap-8",
2118
+ children: [/* @__PURE__ */ jsx(SlotOutlet, {
2119
+ slot: "shell.personalization.category",
2120
+ only: current.key,
2121
+ props: {}
2122
+ }), children.map((entry) => {
2123
+ const label = resolveLabel(entry.contribution.label, entry.contribution.id);
2124
+ return /* @__PURE__ */ jsxs("section", {
2125
+ "aria-label": label,
2126
+ className: "space-y-4 border-t border-border pt-6",
2127
+ children: [/* @__PURE__ */ jsx("h3", {
2128
+ className: "text-sm font-medium",
2129
+ children: label
2130
+ }), /* @__PURE__ */ jsx(SlotOutlet, {
2131
+ slot: "shell.personalization.category",
2132
+ only: entry.key,
2133
+ props: {}
2134
+ })]
2135
+ }, entry.key);
2136
+ })]
2137
+ }, current.key) : /* @__PURE__ */ jsx("p", {
2138
+ className: "text-sm text-muted-foreground",
2139
+ children: t("settings.personalizationEmpty")
2140
+ })
2141
+ })
2142
+ ]
2143
+ })]
2144
+ })
2145
+ }), /* @__PURE__ */ jsx(AlertDialog, {
2146
+ open: pending !== null,
2147
+ onOpenChange: (next) => {
2148
+ if (!next) setPending(null);
2149
+ },
2150
+ title: t("settings.themeDiscardTitle"),
2151
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
2152
+ variant: "ghost",
2153
+ onClick: () => setPending(null),
2154
+ children: t("settings.themeKeepEditing")
2155
+ }), /* @__PURE__ */ jsx(Button, {
2156
+ variant: "destructive",
2157
+ onClick: () => {
2158
+ const next = pending;
2159
+ setPending(null);
2160
+ next?.();
2161
+ },
2162
+ children: t("settings.themeDiscard")
2163
+ })] }),
2164
+ children: /* @__PURE__ */ jsx("p", { children: t("settings.themeDiscardHint") })
2165
+ })]
551
2166
  });
552
2167
  }
553
2168
  //#endregion
@@ -593,7 +2208,26 @@ var provides = [];
593
2208
  /** Applies preferences and owns their settings, listeners and document presentation. */
594
2209
  function register(ctx) {
595
2210
  registerTranslations(ctx);
596
- const stops = [initLanguage(), initTheme()];
2211
+ const stops = [
2212
+ initLanguage(),
2213
+ initTheme(),
2214
+ initReadingTypography(ctx)
2215
+ ];
2216
+ ctx.slots.register("shell.personalization.category", {
2217
+ id: "interface",
2218
+ label: () => ctx.i18n.t("settings.interfaceCategory"),
2219
+ icon: "palette",
2220
+ order: 0,
2221
+ component: InterfacePreferences
2222
+ });
2223
+ ctx.slots.register("shell.personalization.category", {
2224
+ id: "reading",
2225
+ onReset: resetReadingPreferences,
2226
+ label: () => ctx.i18n.t("settings.readingCategory"),
2227
+ icon: "notebook",
2228
+ order: 10,
2229
+ component: ReadingPreferences
2230
+ });
597
2231
  ctx.slots.register("shell.dialog.surface", {
598
2232
  id: "personalization",
599
2233
  component: PersonalizationDialog