dsh-nook 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +36 -0
  2. package/README.md +66 -2
  3. package/client.js +1004 -0
  4. package/cordis.patch.yml +23 -0
  5. package/icon.svg +11 -0
  6. package/index.js +190 -0
  7. package/locale/en.json +6 -0
  8. package/locale/ja.json +6 -0
  9. package/locale/zh.json +6 -0
  10. package/package.json +70 -4
  11. package/scenes/L2_2529_D3_Towns_Plazas.html +1097 -0
  12. package/scenes/L2_6206_D5_Markets_Shops.html +822 -0
  13. package/scenes/L2_6834_D6_Courtyards_Gardens.html +735 -0
  14. package/scenes/L2_7180_D7_NightSky_DeepSea.html +819 -0
  15. package/scenes/L3_1356_D2_Waterside_HotSprings.html +2726 -0
  16. package/scenes/L3_171_D1_Nature_Terrain.html +750 -0
  17. package/scenes/L3_1966_D4_Travel_Transit.html +1590 -0
  18. package/scenes/L3_2464_D1_Nature_Terrain.html +867 -0
  19. package/scenes/L3_2559_D3_Towns_Plazas.html +1099 -0
  20. package/scenes/L3_2869_D3_Towns_Plazas.html +2677 -0
  21. package/scenes/L3_3241_D2_Waterside_HotSprings.html +1821 -0
  22. package/scenes/L3_3557_D4_Travel_Transit.html +1872 -0
  23. package/scenes/L3_6122_D5_Markets_Shops.html +1084 -0
  24. package/scenes/L3_6184_D5_Markets_Shops.html +1479 -0
  25. package/scenes/L3_6362_D5_Markets_Shops.html +993 -0
  26. package/scenes/L3_6656_D6_Courtyards_Gardens.html +916 -0
  27. package/scenes/L3_6754_D6_Courtyards_Gardens.html +1013 -0
  28. package/scenes/L4_179_D1_Nature_Terrain.html +1628 -0
  29. package/scenes/L4_2585_D3_Towns_Plazas.html +1369 -0
  30. package/scenes/L4_3186_D2_Waterside_HotSprings.html +1669 -0
  31. package/scenes/L4_3679_D4_Travel_Transit.html +1256 -0
  32. package/scenes/L4_7283_D7_NightSky_DeepSea.html +1400 -0
  33. package/scenes/L4_7698_D8_Interiors_Workshops.html +760 -0
  34. package/scenes/L4_7733_D8_Interiors_Workshops.html +697 -0
  35. package/scenes/L5_1297_D2_Waterside_HotSprings.html +1018 -0
  36. package/scenes/L5_2090_D1_Nature_Terrain.html +1630 -0
  37. package/scenes/L5_3999_D4_Travel_Transit.html +2318 -0
  38. package/scenes/L5_6993_D6_Courtyards_Gardens.html +1732 -0
  39. package/scenes/L5_7365_D7_NightSky_DeepSea.html +1569 -0
  40. package/scenes/L5_7381_D7_NightSky_DeepSea.html +1779 -0
  41. package/scenes/L5_7874_D8_Interiors_Workshops.html +1488 -0
  42. package/scenes/L5_7993_D8_Interiors_Workshops.html +1367 -0
  43. package/scenes/catalog.json +197 -0
  44. package/scenes/three.module.min.js +6 -0
  45. package/scripts/build-scenes.mjs +184 -0
  46. package/scripts/check-scenes.mjs +296 -0
package/client.js ADDED
@@ -0,0 +1,1004 @@
1
+ /* dsh-nook — Client half.
2
+ *
3
+ * Renders one kawaii 3D diorama from the Fable-Kawaii-3D-ThreeJS dataset as the
4
+ * backdrop of the conversation body (behind the transcript, above the panel
5
+ * fill) and offers a compact picker in the composer tool row.
6
+ *
7
+ * The scene is a self-contained WebGL document, so it runs in its own iframe.
8
+ * The frame sits at z-index 0 inside an isolated wrapper and the conversation
9
+ * body rides z-index 1 above it, which keeps every host control and message
10
+ * clickable while the diorama animates underneath.
11
+ */
12
+ window.__ModuleLoader__.load({
13
+ id: 'dsh-nook',
14
+ factory(require) {
15
+ const React = require('react')
16
+ const ReactDOM = require('react-dom')
17
+ const h = React.createElement
18
+
19
+ const ROUTE = 'nook-scenes'
20
+ const NAMESPACE = 'nook'
21
+ const STORAGE_KEY = 'dsh.nook.v1'
22
+ /** Older builds stored the same choice under the pre-rename key. */
23
+ const LEGACY_STORAGE_KEY = 'dsh.fable-scene-bg.v2'
24
+ const PRESENCE_MIN = 0.35
25
+ const PRESENCE_MAX = 1
26
+ const PRESENCE_STEP = 0.15
27
+ const MANIFEST_TIMEOUT_MS = 15000
28
+ const REDUCED_MOTION_FREEZE_MS = 1600
29
+
30
+ const DICT_EN = {
31
+ trigger: 'Scene background',
32
+ title: 'Scene background',
33
+ enabled: 'Diorama in the corner',
34
+ shuffle: 'Another scene',
35
+ scenes: 'Scenes',
36
+ presence: 'Presence',
37
+ unavailable: 'Scene background could not load',
38
+ decrease: 'Fainter',
39
+ increase: 'Stronger',
40
+ 'domain.D1': 'Nature',
41
+ 'domain.D2': 'Waterside',
42
+ 'domain.D3': 'Towns',
43
+ 'domain.D4': 'Transit',
44
+ 'domain.D5': 'Markets',
45
+ 'domain.D6': 'Gardens',
46
+ 'domain.D7': 'Night sky',
47
+ 'domain.D8': 'Interiors',
48
+ expand: 'Fill the panel',
49
+ collapse: 'Back to the corner',
50
+ reload: 'Reload scene',
51
+ }
52
+
53
+ const DICT_ZH = {
54
+ trigger: '场景背景',
55
+ title: '场景背景',
56
+ enabled: '右下角摆放 3D 微缩沙盘',
57
+ shuffle: '换一个场景',
58
+ scenes: '场景',
59
+ presence: '画面浓度',
60
+ unavailable: '场景背景加载失败',
61
+ decrease: '更淡一些',
62
+ increase: '更浓一些',
63
+ 'domain.D1': '自然地貌',
64
+ 'domain.D2': '水畔温泉',
65
+ 'domain.D3': '城镇广场',
66
+ 'domain.D4': '旅途交通',
67
+ 'domain.D5': '集市小店',
68
+ 'domain.D6': '庭院花园',
69
+ 'domain.D7': '夜空深海',
70
+ 'domain.D8': '室内工坊',
71
+ expand: '放大到全屏',
72
+ collapse: '收回右下角',
73
+ reload: '重新加载场景',
74
+ }
75
+
76
+ const DICT_JA = {
77
+ trigger: 'シーン背景',
78
+ title: 'シーン背景',
79
+ enabled: '右下に 3D ジオラマを置く',
80
+ shuffle: '別のシーン',
81
+ scenes: 'シーン',
82
+ presence: '濃さ',
83
+ unavailable: 'シーン背景を読み込めませんでした',
84
+ decrease: '薄く',
85
+ increase: '濃く',
86
+ 'domain.D1': '自然',
87
+ 'domain.D2': '水辺',
88
+ 'domain.D3': '街',
89
+ 'domain.D4': '移動',
90
+ 'domain.D5': '市場',
91
+ 'domain.D6': '庭',
92
+ 'domain.D7': '夜空',
93
+ 'domain.D8': '室内',
94
+ expand: 'パネルいっぱいに表示',
95
+ collapse: '右下に戻す',
96
+ reload: 'シーンを再読み込み',
97
+ }
98
+
99
+ /**
100
+ * The stack is one stacking context at the conversation body's own level:
101
+ * isolating it keeps the diorama (z-index 0) under the transcript
102
+ * (z-index 1) without lifting either above the host's positioned siblings,
103
+ * such as the conversation-width drag handles that live in the same box.
104
+ */
105
+ const STACK_STYLE = {
106
+ position: 'relative',
107
+ isolation: 'isolate',
108
+ display: 'flex',
109
+ flexDirection: 'column',
110
+ flex: '1 1 auto',
111
+ minHeight: 0,
112
+ minWidth: 0,
113
+ }
114
+
115
+ /**
116
+ * Edge melt, painted with the panel's own fill instead of an alpha mask:
117
+ * an inscribed ellipse of the diorama fades out through the exact
118
+ * `--dsw-alias-bg-base` the conversation panel paints, so the window has no
119
+ * visible boundary in either theme and no color cast of its own at the
120
+ * rim. Coming from the panel's own token is what makes the white (or dark)
121
+ * background read as a continuous gradient rather than a vignette.
122
+ */
123
+ const FADE_IMAGE = 'radial-gradient(ellipse 53% 53% at 50% 50%, transparent 70%, var(--dsw-alias-bg-base) 94%)'
124
+
125
+ /**
126
+ * One feathered diorama window in the free band right of the transcript.
127
+ *
128
+ * `--dsh-chat-content-width` is the live transcript column width published
129
+ * on the Conversation body, which this stack inherits, so the window is
130
+ * exactly the empty gutter beside the text and follows the column when the
131
+ * conversation width changes. Below the comfortable minimum (narrow
132
+ * windows, where there is no gutter at all) it falls back to that minimum
133
+ * instead of disappearing. `bottom` clears a one-line composer card.
134
+ */
135
+ const CARD_STYLE = {
136
+ position: 'absolute',
137
+ right: 10,
138
+ bottom: 108,
139
+ width: 'clamp(180px, calc((100% - var(--dsh-chat-content-width, 920px)) / 2 - 24px), 560px)',
140
+ aspectRatio: '5 / 4',
141
+ zIndex: 0,
142
+ overflow: 'hidden',
143
+ pointerEvents: 'none',
144
+ }
145
+
146
+ /**
147
+ * The click target for the corner window. It repeats the window's geometry
148
+ * one layer above the transcript, so the picture itself can stay under the
149
+ * text (readable where they overlap) while a click on it still reaches us.
150
+ */
151
+ const HIT_STYLE = {
152
+ ...CARD_STYLE,
153
+ zIndex: 2,
154
+ pointerEvents: 'auto',
155
+ cursor: 'zoom-in',
156
+ background: 'transparent',
157
+ }
158
+
159
+ const IFRAME_STYLE = {
160
+ position: 'absolute',
161
+ inset: 0,
162
+ width: '100%',
163
+ height: '100%',
164
+ border: 0,
165
+ display: 'block',
166
+ pointerEvents: 'none',
167
+ transition: 'opacity 700ms ease',
168
+ }
169
+
170
+ /**
171
+ * Immersive state: the diorama fills the conversation body outright, from
172
+ * the header edge to just above the composer, and its lower edge melts into
173
+ * the panel fill so the composer never meets a hard line. No mask here: the
174
+ * same panel-color wash used in the corner keeps both states on one
175
+ * compositing path, so switching between them cannot flicker.
176
+ */
177
+ const EXPANDED_FADE_IMAGE = 'linear-gradient(to bottom, transparent calc(100% - 72px), var(--dsw-alias-bg-base) 100%)'
178
+
179
+ const EXPANDED_STYLE = {
180
+ position: 'absolute',
181
+ top: 0,
182
+ right: 0,
183
+ bottom: 108,
184
+ left: 0,
185
+ zIndex: 2,
186
+ overflow: 'hidden',
187
+ pointerEvents: 'auto',
188
+ }
189
+
190
+ /** Paints the panel fill back over the diorama's rim, above the faded frame. */
191
+ const FADE_STYLE = {
192
+ position: 'absolute',
193
+ inset: 0,
194
+ pointerEvents: 'none',
195
+ background: FADE_IMAGE,
196
+ }
197
+
198
+ /** Conversation body keeps its own flex behaviour above the scene. */
199
+ const CONTENT_STYLE = {
200
+ position: 'relative',
201
+ zIndex: 1,
202
+ display: 'flex',
203
+ flexDirection: 'column',
204
+ flex: '1 1 auto',
205
+ minHeight: 0,
206
+ minWidth: 0,
207
+ }
208
+
209
+ const CSS = `
210
+ .nook-trigger{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border:0;border-radius:var(--dsw-radius-md,8px);background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;transition:background 120ms ease,color 120ms ease}
211
+ .nook-trigger:hover,.nook-trigger[aria-expanded="true"]{background:color-mix(in srgb,var(--dsw-alias-label-primary) 10%,transparent);color:var(--dsw-alias-label-primary)}
212
+ .nook-trigger:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
213
+ .nook-trigger svg{width:17px;height:17px;display:block}
214
+ .nook-hit:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-3px}
215
+ .nook-min{position:absolute;z-index:3;display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;padding:0;border:0;border-radius:10px;background:color-mix(in srgb,var(--dsw-alias-bg-base) 74%,transparent);color:var(--dsw-alias-label-primary);cursor:pointer;box-shadow:0 6px 18px -6px rgba(0,0,0,.35);transition:opacity 160ms ease,background 140ms ease}
216
+ .nook-min:hover{background:color-mix(in srgb,var(--dsw-alias-bg-base) 92%,transparent)}
217
+ .nook-min:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px}
218
+ .nook-min svg{width:16px;height:16px;display:block}
219
+ .nook-retry{position:absolute;right:10px;bottom:10px;z-index:2;padding:5px 10px;border:1px solid var(--dsw-alias-border-l2);border-radius:8px;background:color-mix(in srgb,var(--dsw-alias-bg-base) 84%,transparent);color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;line-height:18px;cursor:pointer;pointer-events:auto}
220
+ .nook-retry:hover{background:color-mix(in srgb,var(--dsw-alias-bg-base) 96%,transparent)}
221
+ .nook-retry:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px}
222
+ .nook-menu{position:fixed;z-index:2147483000;width:312px;max-width:calc(100vw - 24px);max-height:calc(100dvh - 24px);overflow-y:auto;box-sizing:border-box;padding:8px;border-radius:var(--dsw-radius-lg,14px);border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-overlay);box-shadow:0 18px 48px -12px rgba(0,0,0,.42);color:var(--dsw-alias-label-primary);font-size:13px;line-height:20px;display:flex;flex-direction:column;gap:2px}
223
+ .nook-caption{padding:4px 8px 6px;font-size:12px;color:var(--dsw-alias-label-secondary)}
224
+ .nook-row{display:flex;align-items:center;gap:8px;width:100%;box-sizing:border-box;padding:7px 8px;border:0;border-radius:var(--dsw-radius-md,8px);background:transparent;color:inherit;text-align:left;font:inherit;cursor:pointer}
225
+ .nook-row:hover{background:color-mix(in srgb,var(--dsw-alias-label-primary) 9%,transparent)}
226
+ .nook-row:focus-visible,.nook-item:focus-visible,.nook-step:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:-1px}
227
+ .nook-row svg{width:15px;height:15px;flex:none;color:var(--dsw-alias-label-secondary)}
228
+ .nook-switch{position:relative;flex:none;width:34px;height:20px;margin-left:auto;border-radius:999px;background:color-mix(in srgb,var(--dsw-alias-label-primary) 20%,transparent);transition:background 140ms ease}
229
+ .nook-switch::after{content:"";position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:var(--dsw-alias-bg-base);transition:transform 140ms ease}
230
+ .nook-row[aria-checked="true"] .nook-switch{background:var(--dsw-alias-brand-primary)}
231
+ .nook-row[aria-checked="true"] .nook-switch::after{transform:translateX(14px)}
232
+ .nook-sections{margin-top:2px;padding-top:4px;border-top:1px solid var(--dsw-alias-border-l1)}
233
+ .nook-list{display:flex;flex-direction:column;gap:1px;max-height:min(252px,32vh);overflow-y:auto;padding:2px 0}
234
+ .nook-group{padding:6px 8px 2px;font-size:11px;color:var(--dsw-alias-label-secondary)}
235
+ .nook-item{display:flex;align-items:center;gap:8px;width:100%;box-sizing:border-box;padding:6px 8px;border:0;border-radius:var(--dsw-radius-md,8px);background:transparent;color:inherit;text-align:left;font:inherit;cursor:pointer}
236
+ .nook-item:hover{background:color-mix(in srgb,var(--dsw-alias-label-primary) 9%,transparent)}
237
+ .nook-item[data-active="true"]{background:color-mix(in srgb,var(--dsw-alias-brand-primary) 14%,transparent)}
238
+ .nook-check{flex:none;width:14px;height:14px;color:var(--dsw-alias-brand-primary);opacity:0}
239
+ .nook-item[data-active="true"] .nook-check{opacity:1}
240
+ .nook-item-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
241
+ .nook-item-domain{flex:none;margin-left:auto;font-size:11px;color:var(--dsw-alias-label-secondary)}
242
+ .nook-presence{display:flex;align-items:center;gap:6px;padding:6px 8px 4px;margin-top:2px;border-top:1px solid var(--dsw-alias-border-l1)}
243
+ .nook-presence-label{font-size:12px;color:var(--dsw-alias-label-secondary)}
244
+ .nook-presence-value{margin-left:auto;font-size:12px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary)}
245
+ .nook-step{flex:none;width:24px;height:24px;padding:0;border:1px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-sm,6px);background:transparent;color:var(--dsw-alias-label-primary);font:inherit;line-height:1;cursor:pointer}
246
+ .nook-step:hover:not(:disabled){background:color-mix(in srgb,var(--dsw-alias-label-primary) 9%,transparent)}
247
+ .nook-step:disabled{opacity:.4;cursor:default}
248
+ @media (prefers-reduced-motion: reduce){.nook-switch,.nook-switch::after,.nook-trigger{transition:none}}
249
+ `
250
+
251
+ function iconTrigger() {
252
+ return h('svg', {
253
+ viewBox: '0 0 24 24',
254
+ fill: 'none',
255
+ stroke: 'currentColor',
256
+ strokeWidth: 1.6,
257
+ strokeLinecap: 'round',
258
+ strokeLinejoin: 'round',
259
+ 'aria-hidden': true,
260
+ },
261
+ h('rect', { x: 3, y: 4.5, width: 18, height: 15, rx: 3 }),
262
+ h('path', { d: 'M3.5 16.2l4.6-4.4 3.4 3.2 3-2.4 5 4.2' }),
263
+ h('circle', { cx: 8.4, cy: 9.4, r: 1.3, fill: 'currentColor', stroke: 'none' }),
264
+ )
265
+ }
266
+
267
+ function iconShuffle() {
268
+ return h('svg', {
269
+ viewBox: '0 0 24 24',
270
+ fill: 'none',
271
+ stroke: 'currentColor',
272
+ strokeWidth: 1.7,
273
+ strokeLinecap: 'round',
274
+ strokeLinejoin: 'round',
275
+ 'aria-hidden': true,
276
+ },
277
+ h('path', { d: 'M20.5 11.2a8.5 8.5 0 1 0-2.6 6' }),
278
+ h('path', { d: 'M20.5 5.2v6h-6' }),
279
+ )
280
+ }
281
+
282
+ function iconCollapse() {
283
+ return h('svg', {
284
+ viewBox: '0 0 24 24',
285
+ fill: 'none',
286
+ stroke: 'currentColor',
287
+ strokeWidth: 1.8,
288
+ strokeLinecap: 'round',
289
+ strokeLinejoin: 'round',
290
+ 'aria-hidden': true,
291
+ },
292
+ h('path', { d: 'M6 6.5 16.5 17' }),
293
+ h('path', { d: 'M16.5 9.5V17H9' }),
294
+ )
295
+ }
296
+
297
+ function iconCheck() {
298
+ return h('svg', {
299
+ className: 'nook-check',
300
+ viewBox: '0 0 24 24',
301
+ fill: 'none',
302
+ stroke: 'currentColor',
303
+ strokeWidth: 2.2,
304
+ strokeLinecap: 'round',
305
+ strokeLinejoin: 'round',
306
+ 'aria-hidden': true,
307
+ }, h('path', { d: 'M5 12.6l4.4 4.4L19 7.2' }))
308
+ }
309
+
310
+ function clampPresence(value) {
311
+ const number = Number(value)
312
+ if (!Number.isFinite(number)) return PRESENCE_MAX
313
+ return Math.min(PRESENCE_MAX, Math.max(PRESENCE_MIN, Math.round(number * 100) / 100))
314
+ }
315
+
316
+ function readSaved() {
317
+ for (const key of [STORAGE_KEY, LEGACY_STORAGE_KEY]) {
318
+ try {
319
+ const raw = window.localStorage.getItem(key)
320
+ if (raw === null) continue
321
+ const parsed = JSON.parse(raw)
322
+ if (parsed !== null && typeof parsed === 'object') return parsed
323
+ } catch {
324
+ /* unreadable entry: fall through to the next key */
325
+ }
326
+ }
327
+ return {}
328
+ }
329
+
330
+ function writeSaved(value) {
331
+ try {
332
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(value))
333
+ } catch {
334
+ /* private mode or a full quota: the session keeps working in memory */
335
+ }
336
+ }
337
+
338
+ function pickRandomId(scenes, excludeId) {
339
+ if (scenes.length === 0) return null
340
+ if (scenes.length === 1) return scenes[0].id
341
+ for (let attempt = 0; attempt < 16; attempt += 1) {
342
+ const candidate = scenes[Math.floor(Math.random() * scenes.length)]
343
+ if (candidate.id !== excludeId) return candidate.id
344
+ }
345
+ const other = scenes.find(scene => scene.id !== excludeId)
346
+ return other === undefined ? scenes[0].id : other.id
347
+ }
348
+
349
+ function imageOf(store) {
350
+ const snapshot = store.get()
351
+ const scenes = snapshot.scenes
352
+ const current = scenes.find(scene => scene.id === snapshot.currentId)
353
+ return { snapshot, current: current === undefined ? null : current }
354
+ }
355
+
356
+ return {
357
+ inject: ['slots', 'locale'],
358
+ apply(ctx) {
359
+ /** One tiny external store shared by the backdrop and the picker. */
360
+ let snapshot = {
361
+ status: 'idle',
362
+ scenes: [],
363
+ config: null,
364
+ enabled: true,
365
+ fixedId: null,
366
+ currentId: null,
367
+ presence: PRESENCE_MAX,
368
+ rotateSeconds: 0,
369
+ reloads: 0,
370
+ expanded: false,
371
+ controls: 0,
372
+ localeRevision: 0,
373
+ }
374
+ const listeners = new Set()
375
+ const emit = () => {
376
+ for (const listener of Array.from(listeners)) listener()
377
+ }
378
+ const store = {
379
+ get: () => snapshot,
380
+ patch(next) {
381
+ let changed = false
382
+ for (const key of Object.keys(next)) {
383
+ if (snapshot[key] !== next[key]) changed = true
384
+ }
385
+ if (!changed) return
386
+ snapshot = { ...snapshot, ...next }
387
+ emit()
388
+ },
389
+ subscribe(listener) {
390
+ listeners.add(listener)
391
+ return () => listeners.delete(listener)
392
+ },
393
+ }
394
+
395
+ const t = ctx.locale.bind(NAMESPACE)
396
+
397
+ let manifestUrl = null
398
+ let loading = null
399
+ const ensureLoaded = () => {
400
+ if (loading !== null) return loading
401
+ manifestUrl = new URL(`${ROUTE}/manifest.json`, document.baseURI).href
402
+ const controller = typeof AbortController === 'function' ? new AbortController() : null
403
+ const timer = controller === null
404
+ ? null
405
+ : window.setTimeout(() => controller.abort(), MANIFEST_TIMEOUT_MS)
406
+ loading = fetch(manifestUrl, {
407
+ credentials: 'same-origin',
408
+ cache: 'no-store',
409
+ signal: controller === null ? undefined : controller.signal,
410
+ })
411
+ .then(response => {
412
+ if (!response.ok) throw new Error(`scene manifest answered ${response.status}`)
413
+ return response.json()
414
+ })
415
+ .then(manifest => {
416
+ const scenes = Array.isArray(manifest?.scenes)
417
+ ? manifest.scenes.filter(scene => typeof scene?.id === 'string'
418
+ && typeof scene?.file === 'string'
419
+ && typeof scene?.title === 'string')
420
+ : []
421
+ if (scenes.length === 0) throw new Error('scene manifest lists no scenes')
422
+ const config = manifest !== null && typeof manifest.config === 'object' && manifest.config !== null
423
+ ? manifest.config
424
+ : {}
425
+ const saved = readSaved()
426
+ const enabled = typeof saved.enabled === 'boolean' ? saved.enabled : config.enabled !== false
427
+ const presence = clampPresence(typeof saved.presence === 'number' ? saved.presence : config.opacity)
428
+ const requested = typeof saved.sceneId === 'string' && saved.sceneId !== ''
429
+ ? saved.sceneId
430
+ : (typeof config.scene === 'string' ? config.scene : 'random')
431
+ const fixedId = requested !== 'random' && scenes.some(scene => scene.id === requested)
432
+ ? requested
433
+ : null
434
+ store.patch({
435
+ status: 'ready',
436
+ scenes,
437
+ config,
438
+ enabled,
439
+ fixedId,
440
+ currentId: fixedId === null ? pickRandomId(scenes, null) : fixedId,
441
+ presence,
442
+ rotateSeconds: Number.isFinite(Number(config.rotateSeconds)) ? Math.max(0, Number(config.rotateSeconds)) : 0,
443
+ })
444
+ return scenes
445
+ })
446
+ .catch(error => {
447
+ store.patch({ status: 'error' })
448
+ console.warn(`[${NAMESPACE}] ${String(error && error.message ? error.message : error)}`)
449
+ loading = null
450
+ return []
451
+ })
452
+ .finally(() => {
453
+ if (timer !== null) window.clearTimeout(timer)
454
+ })
455
+ return loading
456
+ }
457
+
458
+ const persist = () => {
459
+ const current = store.get()
460
+ writeSaved({
461
+ enabled: current.enabled,
462
+ presence: current.presence,
463
+ sceneId: current.fixedId === null ? 'random' : current.fixedId,
464
+ })
465
+ }
466
+
467
+ const sceneUrlOf = scene => new URL(scene.file, manifestUrl).href
468
+
469
+ const useSnapshot = () => {
470
+ if (typeof React.useSyncExternalStore === 'function') {
471
+ return React.useSyncExternalStore(store.subscribe, store.get, store.get)
472
+ }
473
+ const [value, setValue] = React.useState(store.get)
474
+ React.useEffect(() => store.subscribe(() => setValue(store.get())), [])
475
+ return value
476
+ }
477
+
478
+ function SceneFrame(props) {
479
+ const state = useSnapshot()
480
+ const [hovered, setHovered] = React.useState(false)
481
+ const [minimizerFocused, setMinimizerFocused] = React.useState(false)
482
+ const [failed, setFailed] = React.useState(false)
483
+ const cardRef = React.useRef(null)
484
+ const hitRef = React.useRef(null)
485
+ const minimizeRef = React.useRef(null)
486
+ /** Rect measured before a state change, replayed as a FLIP transform. */
487
+ const flipFrom = React.useRef(null)
488
+ const previousExpanded = React.useRef(state.expanded)
489
+ const skipFocusRestore = React.useRef(false)
490
+
491
+ React.useEffect(() => {
492
+ ensureLoaded()
493
+ }, [])
494
+
495
+ // A scene that reported its own failure stays that way until another
496
+ // attempt (reload, or a different scene) replaces it.
497
+ React.useEffect(() => {
498
+ setFailed(false)
499
+ }, [state.currentId, state.reloads])
500
+
501
+ const current = state.scenes.find(scene => scene.id === state.currentId)
502
+ // A decoration with no way to switch it off is a trap: paint only
503
+ // while a picker is mounted (the cold home renders no composer
504
+ // controls, so the diorama stays away there too).
505
+ const live = state.status === 'ready'
506
+ && state.enabled
507
+ && state.controls > 0
508
+ && current !== undefined
509
+
510
+ React.useEffect(() => {
511
+ const seconds = state.rotateSeconds
512
+ if (!live || !(seconds > 0) || state.fixedId !== null || state.scenes.length < 2) return undefined
513
+ const timer = window.setInterval(() => {
514
+ const now = store.get()
515
+ store.patch({ currentId: pickRandomId(now.scenes, now.currentId) })
516
+ }, Math.round(seconds * 1000))
517
+ return () => window.clearInterval(timer)
518
+ }, [live, state.rotateSeconds, state.fixedId, state.scenes])
519
+
520
+ /**
521
+ * Every expand/collapse goes through here: the rect is measured while
522
+ * the card still has its old geometry, and the layout effect below
523
+ * replays the difference. Measuring only on the transition (never on
524
+ * unrelated renders, where a card mid-animation reports a transformed
525
+ * rect) is what keeps the zoom from firing twice.
526
+ */
527
+ const changeExpanded = next => {
528
+ if (store.get().expanded === next) return
529
+ const element = cardRef.current
530
+ flipFrom.current = element === null ? null : element.getBoundingClientRect()
531
+ store.patch({ expanded: next })
532
+ }
533
+
534
+ // The immersive state cannot outlive the diorama it belongs to.
535
+ React.useEffect(() => {
536
+ if (!live && store.get().expanded) changeExpanded(false)
537
+ }, [live])
538
+
539
+ React.useEffect(() => {
540
+ if (!state.expanded) return undefined
541
+ const onKeyDown = event => {
542
+ if (event.key === 'Escape') changeExpanded(false)
543
+ }
544
+ document.addEventListener('keydown', onKeyDown)
545
+ return () => document.removeEventListener('keydown', onKeyDown)
546
+ }, [state.expanded])
547
+
548
+ // Hand focus to the control the new state exposes, except when the
549
+ // user just went back to the composer: that focus must stay put.
550
+ React.useEffect(() => {
551
+ if (previousExpanded.current === state.expanded) return
552
+ previousExpanded.current = state.expanded
553
+ if (!state.expanded && skipFocusRestore.current) {
554
+ skipFocusRestore.current = false
555
+ return
556
+ }
557
+ const target = state.expanded ? minimizeRef.current : hitRef.current
558
+ if (target !== null) target.focus({ preventScroll: true })
559
+ }, [state.expanded])
560
+
561
+ /**
562
+ * FLIP: the card keeps one element across both states, so replaying
563
+ * the pre-swap rect as a transform gives the zoom between the corner
564
+ * window and the immersive view without animating layout properties.
565
+ */
566
+ React.useLayoutEffect(() => {
567
+ const from = flipFrom.current
568
+ flipFrom.current = null
569
+ const element = cardRef.current
570
+ if (from === null || element === null) return
571
+ const next = element.getBoundingClientRect()
572
+ if (from.width === 0 || next.width === 0 || next.height === 0) return
573
+ const dx = from.left - next.left
574
+ const dy = from.top - next.top
575
+ const scaleX = from.width / next.width
576
+ const scaleY = from.height / next.height
577
+ if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5
578
+ && Math.abs(scaleX - 1) < 0.005 && Math.abs(scaleY - 1) < 0.005) return
579
+ if (typeof element.animate !== 'function') return
580
+ if (typeof window.matchMedia === 'function'
581
+ && window.matchMedia('(prefers-reduced-motion: reduce)').matches) return
582
+ element.animate([
583
+ { transformOrigin: 'top left', transform: `translate(${dx}px, ${dy}px) scale(${scaleX}, ${scaleY})` },
584
+ { transformOrigin: 'top left', transform: 'none' },
585
+ ], { duration: 320, easing: 'cubic-bezier(.22,.61,.36,1)' })
586
+ }, [state.expanded])
587
+
588
+ return h('div', {
589
+ style: STACK_STYLE,
590
+ onPointerEnter: () => setHovered(true),
591
+ onPointerLeave: () => setHovered(false),
592
+ onFocus: event => {
593
+ if (!state.expanded) return
594
+ const button = minimizeRef.current
595
+ if (button !== null && (event.target === button || button.contains(event.target))) return
596
+ // Focusing the composer means the user is going back to the
597
+ // conversation, so the immersive view gets out of the way on its
598
+ // own instead of asking for a second click.
599
+ skipFocusRestore.current = true
600
+ changeExpanded(false)
601
+ },
602
+ },
603
+ h('style', null, CSS),
604
+ live
605
+ ? h('div', {
606
+ ref: cardRef,
607
+ key: 'card',
608
+ style: state.expanded ? EXPANDED_STYLE : CARD_STYLE,
609
+ 'data-nook-bg': current.id,
610
+ 'data-expanded': state.expanded ? 'true' : 'false',
611
+ },
612
+ h(SceneDocument, {
613
+ key: `${current.id}:${state.reloads}`,
614
+ url: sceneUrlOf(current),
615
+ presence: state.presence,
616
+ onFail: () => setFailed(true),
617
+ }),
618
+ failed
619
+ ? h('button', {
620
+ key: 'retry',
621
+ type: 'button',
622
+ className: 'nook-retry',
623
+ onClick: () => {
624
+ setFailed(false)
625
+ store.patch({ reloads: store.get().reloads + 1 })
626
+ },
627
+ }, t('reload'))
628
+ : null,
629
+ h('div', {
630
+ key: 'fade',
631
+ style: state.expanded ? { ...FADE_STYLE, background: EXPANDED_FADE_IMAGE } : FADE_STYLE,
632
+ }),
633
+ )
634
+ : null,
635
+ live && !state.expanded && !failed
636
+ ? h('div', {
637
+ key: 'hit',
638
+ ref: hitRef,
639
+ className: 'nook-hit',
640
+ role: 'button',
641
+ tabIndex: 0,
642
+ 'aria-label': t('expand'),
643
+ title: t('expand'),
644
+ style: HIT_STYLE,
645
+ 'data-nook-expand': '',
646
+ onClick: () => changeExpanded(true),
647
+ onKeyDown: event => {
648
+ if (event.key === 'Enter' || event.key === ' ') {
649
+ event.preventDefault()
650
+ changeExpanded(true)
651
+ }
652
+ },
653
+ })
654
+ : null,
655
+ state.expanded
656
+ ? h('button', {
657
+ key: 'minimize',
658
+ ref: minimizeRef,
659
+ type: 'button',
660
+ className: 'nook-min',
661
+ 'aria-label': t('collapse'),
662
+ title: t('collapse'),
663
+ style: {
664
+ top: 22,
665
+ right: 22,
666
+ opacity: hovered || minimizerFocused ? 1 : 0,
667
+ pointerEvents: hovered || minimizerFocused ? 'auto' : 'none',
668
+ },
669
+ 'data-nook-collapse': '',
670
+ onFocus: () => setMinimizerFocused(true),
671
+ onBlur: () => setMinimizerFocused(false),
672
+ onClick: () => changeExpanded(false),
673
+ }, iconCollapse())
674
+ : null,
675
+ h('div', { key: 'content', style: CONTENT_STYLE }, props.children),
676
+ )
677
+ }
678
+
679
+ /**
680
+ * Drop the scene's WebGL context before its iframe leaves the document.
681
+ * Browsers cap live contexts per page (Chrome: ~16) and reclaim them
682
+ * only after a garbage collection, so clicking through scenes could
683
+ * exhaust the pool and make the next scene report a WebGL failure.
684
+ */
685
+ function releaseFrame(frame) {
686
+ if (frame === null) return
687
+ let sceneDocument = null
688
+ try {
689
+ sceneDocument = frame.contentDocument
690
+ } catch {
691
+ return
692
+ }
693
+ if (sceneDocument === null) return
694
+ for (const canvas of sceneDocument.querySelectorAll('canvas')) {
695
+ let context = null
696
+ try {
697
+ context = canvas.getContext('webgl2') ?? canvas.getContext('webgl')
698
+ } catch {
699
+ continue
700
+ }
701
+ const lose = context === null ? null : context.getExtension('WEBGL_lose_context')
702
+ if (lose !== null && lose !== undefined) lose.loseContext()
703
+ }
704
+ }
705
+
706
+ function SceneDocument(props) {
707
+ const frameRef = React.useRef(null)
708
+ /** Held separately because React clears `frameRef` before unmount cleanup. */
709
+ const sceneFrame = React.useRef(null)
710
+ const [painted, setPainted] = React.useState(false)
711
+
712
+ React.useEffect(() => {
713
+ sceneFrame.current = frameRef.current
714
+ }, [])
715
+ React.useEffect(() => () => {
716
+ releaseFrame(sceneFrame.current)
717
+ sceneFrame.current = null
718
+ }, [])
719
+
720
+ /**
721
+ * The vendored pages catch their own start-up failures and unhide an
722
+ * error box (`#error`, `#fault`, `#notice` or `[role="alert"]`). One
723
+ * look after the load tells us whether the diorama actually started,
724
+ * so the card can offer a retry instead of showing a dead picture.
725
+ */
726
+ React.useEffect(() => {
727
+ if (!painted) return undefined
728
+ const timer = window.setTimeout(() => {
729
+ const frame = frameRef.current
730
+ if (frame === null) return
731
+ let sceneDocument = null
732
+ try {
733
+ sceneDocument = frame.contentDocument
734
+ } catch {
735
+ return
736
+ }
737
+ if (sceneDocument === null) return
738
+ const failure = sceneDocument.querySelector(
739
+ '[role="alert"]:not([hidden]), #error:not([hidden]), #fault:not([hidden]), #notice:not([hidden])',
740
+ )
741
+ if (failure !== null) props.onFail()
742
+ }, 1400)
743
+ return () => window.clearTimeout(timer)
744
+ }, [painted, props.url])
745
+
746
+ React.useEffect(() => {
747
+ const element = frameRef.current
748
+ if (element === null) return undefined
749
+ const media = typeof window.matchMedia === 'function'
750
+ ? window.matchMedia('(prefers-reduced-motion: reduce)')
751
+ : null
752
+ if (media === null || !media.matches) return undefined
753
+ const timer = window.setTimeout(() => {
754
+ try {
755
+ const target = element.contentWindow
756
+ if (target !== null) target.postMessage({ __nookScene: true, action: 'pause' }, '*')
757
+ } catch {
758
+ /* a disposed frame: nothing to freeze */
759
+ }
760
+ }, REDUCED_MOTION_FREEZE_MS)
761
+ return () => window.clearTimeout(timer)
762
+ }, [props.url])
763
+
764
+ return h('iframe', {
765
+ ref: frameRef,
766
+ src: props.url,
767
+ title: '',
768
+ tabIndex: -1,
769
+ scrolling: 'no',
770
+ referrerPolicy: 'no-referrer',
771
+ 'aria-hidden': 'true',
772
+ 'data-nook-doc': '',
773
+ style: { ...IFRAME_STYLE, opacity: painted ? props.presence : 0 },
774
+ onLoad: () => setPainted(true),
775
+ })
776
+ }
777
+
778
+ function SceneControl() {
779
+ const state = useSnapshot()
780
+ const [open, setOpen] = React.useState(false)
781
+ const [anchor, setAnchor] = React.useState(null)
782
+ const triggerRef = React.useRef(null)
783
+ const menuRef = React.useRef(null)
784
+
785
+ React.useEffect(() => {
786
+ ensureLoaded()
787
+ store.patch({ controls: store.get().controls + 1 })
788
+ return () => store.patch({ controls: Math.max(0, store.get().controls - 1) })
789
+ }, [])
790
+
791
+ const place = React.useCallback(() => {
792
+ const element = triggerRef.current
793
+ if (element === null) return
794
+ const rect = element.getBoundingClientRect()
795
+ setAnchor({
796
+ right: Math.max(8, window.innerWidth - rect.right),
797
+ bottom: Math.max(8, window.innerHeight - rect.top + 8),
798
+ })
799
+ }, [])
800
+
801
+ React.useEffect(() => {
802
+ if (!open) return undefined
803
+ place()
804
+ const onPointerDown = event => {
805
+ const menu = menuRef.current
806
+ const trigger = triggerRef.current
807
+ if (menu !== null && menu.contains(event.target)) return
808
+ if (trigger !== null && trigger.contains(event.target)) return
809
+ setOpen(false)
810
+ }
811
+ const onKeyDown = event => {
812
+ if (event.key === 'Escape') {
813
+ setOpen(false)
814
+ if (triggerRef.current !== null) triggerRef.current.focus()
815
+ }
816
+ }
817
+ const onResize = () => place()
818
+ document.addEventListener('pointerdown', onPointerDown, true)
819
+ document.addEventListener('keydown', onKeyDown, true)
820
+ window.addEventListener('resize', onResize)
821
+ return () => {
822
+ document.removeEventListener('pointerdown', onPointerDown, true)
823
+ document.removeEventListener('keydown', onKeyDown, true)
824
+ window.removeEventListener('resize', onResize)
825
+ }
826
+ }, [open, place])
827
+
828
+ React.useEffect(() => {
829
+ if (!open) return
830
+ const menu = menuRef.current
831
+ if (menu !== null) menu.focus()
832
+ }, [open, anchor])
833
+
834
+ if (state.status === 'error') {
835
+ return h(React.Fragment, null,
836
+ h('style', null, CSS),
837
+ h('button', {
838
+ type: 'button',
839
+ className: 'nook-trigger',
840
+ 'aria-label': t('unavailable'),
841
+ title: t('unavailable'),
842
+ disabled: true,
843
+ style: { opacity: 0.45, cursor: 'default' },
844
+ 'data-nook-control': '',
845
+ }, iconTrigger()),
846
+ )
847
+ }
848
+
849
+ if (state.status !== 'ready') return null
850
+
851
+ const image = imageOf(store)
852
+ const titleOfCurrent = image.current === null ? t('trigger') : image.current.title
853
+ const toggle = () => {
854
+ store.patch({ enabled: !store.get().enabled })
855
+ persist()
856
+ }
857
+ const shuffle = () => {
858
+ const now = store.get()
859
+ store.patch({ fixedId: null, currentId: pickRandomId(now.scenes, now.currentId), enabled: true })
860
+ persist()
861
+ // The menu hangs over the corner window, so close it to show the
862
+ // scene it just picked.
863
+ setOpen(false)
864
+ }
865
+ const choose = id => {
866
+ const same = store.get().currentId === id
867
+ store.patch({
868
+ fixedId: id,
869
+ currentId: id,
870
+ enabled: true,
871
+ // Picking the scene that is already showing reloads it, which is
872
+ // the retry path for a scene that failed to start.
873
+ reloads: same ? store.get().reloads + 1 : store.get().reloads,
874
+ })
875
+ persist()
876
+ setOpen(false)
877
+ }
878
+ const stepPresence = delta => {
879
+ const next = clampPresence(Math.round((store.get().presence + delta) * 100) / 100)
880
+ if (next === store.get().presence) return
881
+ store.patch({ presence: next })
882
+ persist()
883
+ }
884
+
885
+ const menu = open && anchor !== null
886
+ ? ReactDOM.createPortal(
887
+ h('div', {
888
+ ref: menuRef,
889
+ className: 'nook-menu',
890
+ role: 'dialog',
891
+ 'aria-label': t('title'),
892
+ tabIndex: -1,
893
+ style: { right: anchor.right, bottom: anchor.bottom },
894
+ },
895
+ h('div', { className: 'nook-caption' }, t('title')),
896
+ h('button', {
897
+ type: 'button',
898
+ className: 'nook-row',
899
+ role: 'switch',
900
+ 'aria-checked': state.enabled,
901
+ onClick: toggle,
902
+ },
903
+ h('span', null, t('enabled')),
904
+ h('span', { className: 'nook-switch', 'aria-hidden': 'true' })),
905
+ h('button', { type: 'button', className: 'nook-row', onClick: shuffle },
906
+ iconShuffle(),
907
+ h('span', null, t('shuffle'))),
908
+ h('button', {
909
+ type: 'button',
910
+ className: 'nook-row',
911
+ onClick: () => {
912
+ store.patch({ reloads: store.get().reloads + 1 })
913
+ setOpen(false)
914
+ },
915
+ },
916
+ iconShuffle(),
917
+ h('span', null, t('reload'))),
918
+ h('div', { className: 'nook-sections' },
919
+ h('div', { className: 'nook-caption' }, t('scenes')),
920
+ h('div', { className: 'nook-list', role: 'radiogroup', 'aria-label': t('scenes') },
921
+ state.scenes.map((scene, index) => {
922
+ const previous = index === 0 ? null : state.scenes[index - 1]
923
+ const startsGroup = previous === null || previous.domain !== scene.domain
924
+ return h(React.Fragment, { key: scene.id },
925
+ startsGroup ? h('div', { className: 'nook-group' }, t(`domain.${scene.domain}`)) : null,
926
+ h('button', {
927
+ type: 'button',
928
+ className: 'nook-item',
929
+ role: 'radio',
930
+ 'aria-checked': scene.id === state.currentId,
931
+ 'data-active': scene.id === state.currentId,
932
+ onClick: () => choose(scene.id),
933
+ },
934
+ iconCheck(),
935
+ h('span', { className: 'nook-item-title' }, scene.title),
936
+ ))
937
+ })),
938
+ ),
939
+ h('div', { className: 'nook-presence' },
940
+ h('span', { className: 'nook-presence-label' }, t('presence')),
941
+ h('button', {
942
+ type: 'button',
943
+ className: 'nook-step',
944
+ 'aria-label': t('decrease'),
945
+ title: t('decrease'),
946
+ disabled: state.presence <= PRESENCE_MIN,
947
+ onClick: () => stepPresence(-PRESENCE_STEP),
948
+ }, '\u2212'),
949
+ h('span', { className: 'nook-presence-value' }, `${Math.round(state.presence * 100)}%`),
950
+ h('button', {
951
+ type: 'button',
952
+ className: 'nook-step',
953
+ 'aria-label': t('increase'),
954
+ title: t('increase'),
955
+ disabled: state.presence >= PRESENCE_MAX,
956
+ onClick: () => stepPresence(PRESENCE_STEP),
957
+ }, '+')),
958
+ ),
959
+ document.body,
960
+ )
961
+ : null
962
+
963
+ return h(React.Fragment, null,
964
+ h('style', null, CSS),
965
+ h('button', {
966
+ ref: triggerRef,
967
+ type: 'button',
968
+ className: 'nook-trigger',
969
+ 'aria-haspopup': 'dialog',
970
+ 'aria-expanded': open,
971
+ 'aria-label': t('trigger'),
972
+ title: `${t('trigger')} · ${titleOfCurrent}`,
973
+ 'data-nook-control': '',
974
+ onClick: () => {
975
+ if (!open) place()
976
+ setOpen(!open)
977
+ },
978
+ }, iconTrigger()),
979
+ menu,
980
+ )
981
+ }
982
+
983
+ ctx.effect(() => ctx.locale.register(NAMESPACE, 'en', DICT_EN), 'nook: locale en')
984
+ ctx.effect(() => ctx.locale.register(NAMESPACE, 'zh', DICT_ZH), 'nook: locale zh')
985
+ ctx.effect(() => ctx.locale.register(NAMESPACE, 'ja', DICT_JA), 'nook: locale ja')
986
+ ctx.effect(() => ctx.locale.subscribe(() => {
987
+ store.patch({ localeRevision: store.get().localeRevision + 1 })
988
+ }), 'nook: locale revision')
989
+
990
+ ctx.slots.inject('conversation.hero.frame', () => ctx.slots.register({
991
+ name: 'conversation.hero.frame',
992
+ id: 'nook',
993
+ order: 10,
994
+ }, SceneFrame))
995
+
996
+ ctx.slots.inject('conversation.input.right', () => ctx.slots.register({
997
+ name: 'conversation.input.right',
998
+ id: 'nook',
999
+ order: 20,
1000
+ }, SceneControl))
1001
+ },
1002
+ }
1003
+ },
1004
+ })