cortico-world-agent-speed 0.2.0 → 0.2.2
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/CHANGELOG.md +64 -0
- package/LICENSE +0 -14
- package/README.md +29 -11
- package/THIRD_PARTY_NOTICES.md +69 -0
- package/activity.d.ts +15 -0
- package/activity.js +88 -3
- package/describe.json +806 -0
- package/dist/webui.css +2 -0
- package/dist/webui.css.map +7 -0
- package/dist/webui.js +2 -0
- package/dist/webui.js.map +7 -0
- package/host/app-store.cjs +68 -0
- package/host/cursor.cjs +67 -0
- package/host/electron-main.cjs +666 -0
- package/host/input-shape.cjs +63 -0
- package/host/mouse-lease.cjs +77 -0
- package/host/overlay.cjs +139 -0
- package/host/portrait.cjs +52 -0
- package/host/preload.cjs +60 -14
- package/host/renderer-gone.cjs +24 -0
- package/host/windows.cjs +251 -0
- package/package.json +27 -7
- package/scripts/build-webui.mjs +40 -0
- package/scripts/speech-bank/build.py +166 -0
- package/scripts/speech-bank/dicts.py +76 -0
- package/src/ENV_PROMPT.en.md +51 -0
- package/src/ENV_PROMPT.md +51 -0
- package/src/asr/address.ts +25 -0
- package/src/asr/hotkey.ts +335 -0
- package/src/asr/result.ts +51 -0
- package/src/asr/segmenter.ts +269 -0
- package/src/asr/sherpa.ts +280 -0
- package/src/asr/simplify.ts +38 -0
- package/src/asr/system-recognizer.ts +292 -0
- package/src/asr/system-sapi.ps1 +173 -0
- package/src/asr/transcription-api.ts +176 -0
- package/src/chat.ts +212 -0
- package/src/config.ts +481 -0
- package/src/cua/ENV_PROMPT.en.md +29 -0
- package/src/cua/ENV_PROMPT.md +29 -0
- package/src/cua/config.ts +88 -0
- package/src/cua/cua.ts +712 -0
- package/src/cua/engine/darwin.ts +410 -0
- package/src/cua/engine/display.ts +55 -0
- package/src/cua/engine/fail.ts +15 -0
- package/src/cua/engine/foreground.ts +8 -0
- package/src/cua/engine/image.ts +57 -0
- package/src/cua/engine/keys.ts +70 -0
- package/src/cua/engine/linux-keys.ts +29 -0
- package/src/cua/engine/linux.ts +343 -0
- package/src/cua/engine/mac-keys.ts +57 -0
- package/src/cua/engine/user-activity.ts +54 -0
- package/src/cua/engine/wait-idle.ts +31 -0
- package/src/cua/engine/win32.ts +299 -0
- package/src/cua/engine-child.ts +274 -0
- package/src/cua/engine-ipc.ts +140 -0
- package/src/cua/i18n/de.ts +53 -0
- package/src/cua/i18n/en.ts +63 -0
- package/src/cua/i18n/es-419.ts +53 -0
- package/src/cua/i18n/fr.ts +53 -0
- package/src/cua/i18n/index.ts +26 -0
- package/src/cua/i18n/it.ts +53 -0
- package/src/cua/i18n/ja.ts +53 -0
- package/src/cua/i18n/ko.ts +53 -0
- package/src/cua/i18n/pt-BR.ts +53 -0
- package/src/cua/i18n/ru.ts +59 -0
- package/src/cua/i18n/zh-Hant.ts +53 -0
- package/src/cua/i18n/zh.ts +59 -0
- package/src/cua/model-text.ts +252 -0
- package/src/cua/terminal.ts +31 -0
- package/src/cua/tools.ts +153 -0
- package/src/definition.ts +146 -0
- package/src/host-reason.ts +32 -0
- package/src/i18n/de.ts +409 -0
- package/src/i18n/en.ts +443 -0
- package/src/i18n/es-419.ts +409 -0
- package/src/i18n/fr.ts +409 -0
- package/src/i18n/index.ts +56 -0
- package/src/i18n/it.ts +409 -0
- package/src/i18n/ja.ts +409 -0
- package/src/i18n/ko.ts +409 -0
- package/src/i18n/pt-BR.ts +409 -0
- package/src/i18n/ru.ts +415 -0
- package/src/i18n/zh-Hant.ts +409 -0
- package/src/i18n/zh.ts +440 -0
- package/src/index.ts +15 -0
- package/src/model-text.ts +344 -0
- package/src/moves.ts +101 -0
- package/src/pack-import.ts +361 -0
- package/src/packs.ts +449 -0
- package/src/runtime/download.ts +29 -0
- package/src/runtime/store.ts +293 -0
- package/src/script.ts +202 -0
- package/src/self.ts +247 -0
- package/src/server.ts +479 -0
- package/src/speech/data/CMUDICT-LICENSE +33 -0
- package/src/speech/data/IPADIC-COPYING +71 -0
- package/src/speech/data/UNICODE-LICENSE +39 -0
- package/src/speech/data/en.tsv.gz +0 -0
- package/src/speech/data/ja-ipadic.tsv.gz +0 -0
- package/src/speech/data/ja-unihan.tsv.gz +0 -0
- package/src/speech/data/zh.json +1 -0
- package/src/speech/index.ts +204 -0
- package/src/speech/ipa.ts +83 -0
- package/src/speech/japanese.ts +105 -0
- package/src/speech/jukujikun.ts +22 -0
- package/src/speech/korean.ts +35 -0
- package/src/speech/lang.ts +151 -0
- package/src/speech/rules.ts +72 -0
- package/src/speech/syllable.ts +76 -0
- package/src/status.ts +164 -0
- package/src/tools.ts +110 -0
- package/src/webui/api-rows.css +2 -0
- package/src/webui/api-rows.ts +44 -0
- package/src/webui/client.ts +451 -0
- package/src/webui/dress-dialog.css +14 -0
- package/src/webui/dress-dialog.ts +117 -0
- package/src/webui/dress-panel.ts +160 -0
- package/src/webui/key-capture.ts +60 -0
- package/src/webui/shared/modal.css +13 -0
- package/src/webui/shared/modal.ts +77 -0
- package/src/webui/shared/problem.css +15 -0
- package/src/webui/shared/problem.ts +217 -0
- package/src/webui/shared/strings.ts +5 -0
- package/src/webui/style.css +50 -0
- package/src/window-host.ts +116 -0
- package/src/world.ts +2926 -0
- package/web/activity-motion.js +117 -0
- package/web/appearance.js +60 -0
- package/web/body-host.js +257 -0
- package/web/coo/coo.js +384 -0
- package/web/coo/figure.js +15 -0
- package/web/coo/figure.json +1224 -0
- package/web/dist/dress-dialog.css +1 -0
- package/web/dist/dress-dialog.js +1 -0
- package/web/drag-row.js +49 -0
- package/web/drag.js +149 -0
- package/web/dress.css +170 -0
- package/web/dress.html +37 -0
- package/web/dress.js +786 -0
- package/web/figure-frame.html +16 -0
- package/web/figure-frame.js +128 -0
- package/web/frame-loop.js +55 -0
- package/web/hints.js +77 -0
- package/web/i18n/de.js +170 -0
- package/web/i18n/en.js +177 -0
- package/web/i18n/es-419.js +170 -0
- package/web/i18n/fr.js +170 -0
- package/web/i18n/it.js +170 -0
- package/web/i18n/ja.js +170 -0
- package/web/i18n/ko.js +170 -0
- package/web/i18n/pt-BR.js +170 -0
- package/web/i18n/ru.js +170 -0
- package/web/i18n/zh-Hant.js +170 -0
- package/web/i18n/zh.js +175 -0
- package/web/i18n.js +54 -0
- package/{renderer/vendor → web}/kit/body.js +31 -58
- package/web/looks.js +70 -0
- package/web/mic-worklet.js +36 -0
- package/web/mic.js +117 -0
- package/web/motion-frames.js +80 -0
- package/web/motion-level.js +40 -0
- package/web/new-year-2027.svg +238 -0
- package/web/overlay.html +16 -0
- package/web/overlay.js +100 -0
- package/web/pet-app.js +3000 -0
- package/web/pet.css +642 -0
- package/web/pet.html +21 -0
- package/web/scale-slider.js +259 -0
- package/web/show-hide.js +49 -0
- package/web/sound.js +245 -0
- package/web/speech/zh.json +1 -0
- package/web/speech/zh.ogg +0 -0
- package/web/speech.js +197 -0
- package/web/stage.js +160 -0
- package/web/swap-motion.js +119 -0
- package/web/ui.js +195 -0
- package/host/launch.js +0 -187
- package/host/library.cjs +0 -638
- package/host/main.cjs +0 -389
- package/index.js +0 -93
- package/renderer/index.html +0 -22
- package/renderer/pet-sandbox.html +0 -11
- package/renderer/pet.css +0 -38
- package/renderer/pet.js +0 -251
- package/renderer/vendor/activity-motion.js +0 -101
- package/renderer/vendor/figure-frame.js +0 -115
- package/renderer/vendor/pack.css +0 -2
- /package/{renderer/vendor → web}/kit/rig.js +0 -0
package/web/pet-app.js
ADDED
|
@@ -0,0 +1,3000 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pet page. Connects to the World over `/socket?role=pet`, runs the body of the figure pack the
|
|
3
|
+
* skin names (Coo's or another, in a sandboxed frame, body-host.js), and turns World orders (say,
|
|
4
|
+
* ask, walk, act, listen, and the steps of an app's conversation) into bubbles and motion. It
|
|
5
|
+
* reports back only what happened on screen: arrivals, answers, touches, typed text, and 16 kHz
|
|
6
|
+
* microphone audio while voice input is on.
|
|
7
|
+
*
|
|
8
|
+
* In the pet window (`window.petHost` from the preload) the page is transparent and the
|
|
9
|
+
* window ignores the mouse except over the figure, a bubble, the menu or the hover buttons.
|
|
10
|
+
* Colors follow the World's `theme` through `data-theme` on the root element, and text the app
|
|
11
|
+
* language (i18n.js): the one stamped on the page, then the one the World's prefs carry.
|
|
12
|
+
*/
|
|
13
|
+
import { applyTheme, balancedWidth, clamp, f, ICONS, layBeside, linked, tailAt, tailLine } from './ui.js';
|
|
14
|
+
import { language, t, useLanguage } from './i18n.js';
|
|
15
|
+
import { createSfx } from './sound.js';
|
|
16
|
+
import { createSpeech, textSteps } from './speech.js';
|
|
17
|
+
import { COO_CSS, PALETTES, normalizeSkin, skinCss } from './coo/coo.js';
|
|
18
|
+
import { loadBody } from './body-host.js';
|
|
19
|
+
import { fetchLooks, lookAvailable, lookPicture, sameLook } from './looks.js';
|
|
20
|
+
import { SIZE, scaleSlider, sizeEcho } from './scale-slider.js';
|
|
21
|
+
import { RESTYLE_MS, SWAP_MS, restyle, springSize, swapIn, swapOut } from './swap-motion.js';
|
|
22
|
+
import { accentColors, announcePainted, bubbleCss, dressFloor, glowColor, lightWall, modeButton, setGlow } from './stage.js';
|
|
23
|
+
import { bindAppearance } from './appearance.js';
|
|
24
|
+
import { createMic } from './mic.js';
|
|
25
|
+
import { runFrames } from './frame-loop.js';
|
|
26
|
+
import { cssMs, growFrom } from './motion-frames.js';
|
|
27
|
+
import { showHide } from './show-hide.js';
|
|
28
|
+
import { motionLevel, setMotionChoice, watchMotion } from './motion-level.js';
|
|
29
|
+
import { mountHints, tipOf, tipWithoutNote } from './hints.js';
|
|
30
|
+
import { createActivityMotion } from './activity-motion.js';
|
|
31
|
+
|
|
32
|
+
const $ = (s) => document.querySelector(s);
|
|
33
|
+
const host = window.petHost || null;
|
|
34
|
+
const windowKey = host ? new URLSearchParams(location.hash.slice(1)).get('key') : null;
|
|
35
|
+
document.body.classList.add(host ? 'desk' : 'tab');
|
|
36
|
+
|
|
37
|
+
const stage = $('#stage');
|
|
38
|
+
const bubble = $('#bubble'), menu = $('#menu');
|
|
39
|
+
const tools = $('#tools'), wheel = $('#wheel');
|
|
40
|
+
// Coo's drawing classes for the look wheel's pictures; the bubbles and buttons take their colours from Coo's palette
|
|
41
|
+
// another pack's body sets the theme color instead (accentStyle, after skinStyle so it wins)
|
|
42
|
+
const cooStyle = document.createElement('style'), skinStyle = document.createElement('style'), accentStyle = document.createElement('style');
|
|
43
|
+
// the bubbles' colours of a pack that names its own (bubbleCss)
|
|
44
|
+
const bubbleStyle = document.createElement('style');
|
|
45
|
+
cooStyle.textContent = COO_CSS;
|
|
46
|
+
document.head.append(cooStyle, skinStyle, accentStyle, bubbleStyle);
|
|
47
|
+
|
|
48
|
+
const prefs = {
|
|
49
|
+
roam: 'calm', sound: true, theme: document.documentElement.dataset.theme, scale: 1, bubbleSize: 1, fontSize: 1, bubbleSpeed: 1, sayBubbleHoldSec: 0, glow: 7, user: '', mic: false, micDevice: '', bot: null,
|
|
50
|
+
/** Voice input: switched on, recognizer ready, why not, how to talk, and the mode in force. */
|
|
51
|
+
voice: { enabled: false, ready: false, detail: null, hint: '', mode: 'hold' },
|
|
52
|
+
/** The actions shown as buttons beside the pet on hover. */
|
|
53
|
+
hoverButtons: ['chat', 'voice'],
|
|
54
|
+
rememberPosition: false,
|
|
55
|
+
/** Double-clicking the pet opens the typing box. */
|
|
56
|
+
doubleClickChat: false,
|
|
57
|
+
statusBubble: true,
|
|
58
|
+
/** What the person typed, said or sent from the chat page stays above Coo (see lines); off, speech shows only while it is heard. */
|
|
59
|
+
saidBubbles: true,
|
|
60
|
+
/** Seconds a settled line stays; 0 = until its reply closes (see lines). */
|
|
61
|
+
saidBubbleHoldSec: 0,
|
|
62
|
+
/** Draw at the moving frame rate while the body rests too. */
|
|
63
|
+
/** Frames a second while the body moves; 0 follows the display. */
|
|
64
|
+
frameRate: 60,
|
|
65
|
+
lockFrameRate: false,
|
|
66
|
+
/** How transparent the body and its bubbles are, in percent, as usual and during full screen (stepFade). */
|
|
67
|
+
fade: 0, fullscreenFade: 0,
|
|
68
|
+
/** Computer use is on; the person confirmed its risks, so the button turns it on too; the app can show its switch. */
|
|
69
|
+
cua: { on: false, confirmed: false, canOpen: false },
|
|
70
|
+
/** Every click passes through the pet (the tray's "click through"): no hover buttons, and a bubble under the cursor does not wait. */
|
|
71
|
+
clickThrough: false,
|
|
72
|
+
};
|
|
73
|
+
// in a tab (the settings window's preview) the page is its own stage: a wall that answers the pointer, a floor with icons, a night/day button
|
|
74
|
+
const modeBtn = host ? null : modeButton(document.body, () => prefs.theme, (theme) => applyPrefs({ theme }));
|
|
75
|
+
if (!host) {
|
|
76
|
+
lightWall(document.body, document.documentElement);
|
|
77
|
+
dressFloor($('.floor'));
|
|
78
|
+
// the settings window lends its theme color (--host-accent): the light's color when the body's pack names none
|
|
79
|
+
bindAppearance(document, window);
|
|
80
|
+
}
|
|
81
|
+
/** The pack on screen, as /api/figures lists it: its colors light the wall in a tab. */
|
|
82
|
+
let shownPack = null;
|
|
83
|
+
const lightFor = (s) => {
|
|
84
|
+
if (!host) setGlow(document.body, glowColor(shownPack, s));
|
|
85
|
+
const a = accentColors(shownPack, s);
|
|
86
|
+
accentStyle.textContent = a ? `html:root{--skin-eye:${a.light}}@media (prefers-color-scheme: dark){html:root:not([data-theme="light"]){--skin-eye:${a.dark}}}html:root[data-theme="dark"]{--skin-eye:${a.dark}}` : '';
|
|
87
|
+
bubbleStyle.textContent = bubbleCss(shownPack, s);
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const sfx = createSfx();
|
|
91
|
+
// on the desktop the hints name the hover buttons, over whatever lies behind: they close on their own
|
|
92
|
+
mountHints(document, { autoClose: !!host });
|
|
93
|
+
// Coo's speech stands in for the babble while it is on; its units move the mouth
|
|
94
|
+
const speech = createSpeech(sfx, { onUnit: () => body?.talk() });
|
|
95
|
+
/** The talk key is listening: no line makes a sound until it lets go. */
|
|
96
|
+
let talkKeyDown = false;
|
|
97
|
+
if (host) sfx.unlock();
|
|
98
|
+
else ['pointerdown', 'keydown'].forEach((ev) => document.addEventListener(ev, () => sfx.unlock(), { capture: true }));
|
|
99
|
+
|
|
100
|
+
/** Page pixels the window reaches below the floor, over a taskbar (the window process says how many); a figure may draw there. */
|
|
101
|
+
let below = 0;
|
|
102
|
+
const floorGap = () => (host ? 2 + below : 48);
|
|
103
|
+
/** The size the body is drawn at: `prefs.scale` reached on a spring (swap-motion.js), so a new size grows or shrinks into place. */
|
|
104
|
+
const drawnScale = springSize(1);
|
|
105
|
+
/** Whether a size has come from the World yet: the first one is taken at once, without the spring. */
|
|
106
|
+
let scaleSeen = false;
|
|
107
|
+
/**
|
|
108
|
+
* In a tab (the settings window's 开始 preview, or the page opened in a browser) the body is drawn at size 1 whatever the
|
|
109
|
+
* size setting, as the dressing page's preview is: the setting is the desktop window's, and a large one would not fit.
|
|
110
|
+
*/
|
|
111
|
+
const bounds = () => ({ W: innerWidth, H: innerHeight, floorY: innerHeight - floorGap(), S: .42 * (host ? drawnScale.value : 1) });
|
|
112
|
+
/**
|
|
113
|
+
* The body on screen (body-host.js), null until the first one is ready, and the words it does (its pack's
|
|
114
|
+
* vocab, by id). `T` is the page's clock, in seconds of frames drawn.
|
|
115
|
+
*/
|
|
116
|
+
let body = null, words = new Map(), T = 0;
|
|
117
|
+
/** Where the body last said it is (body-host.js `layout`), or null. */
|
|
118
|
+
const at = () => body?.layout ?? null;
|
|
119
|
+
/** What the body is told of the page: talking orders hold its roaming off, and these states. */
|
|
120
|
+
const bodyState = { listening: false, thinking: false, thoughtShown: true, dialogOpen: false, still: false, status: null };
|
|
121
|
+
const holdRoam = (seconds) => body?.set({ hold: seconds });
|
|
122
|
+
host?.onFloor?.((px) => { below = px; body?.set({ bounds: bounds() }); });
|
|
123
|
+
// the window reads the windows on its display only while the body on screen asks for them (`watchWindows`)
|
|
124
|
+
host?.onWindows?.((desk) => body?.setWindows(desk));
|
|
125
|
+
let fittedWidth = innerWidth;
|
|
126
|
+
addEventListener('resize', () => {
|
|
127
|
+
body?.set({ bounds: bounds() });
|
|
128
|
+
// a bubble is capped 20px inside the window's width
|
|
129
|
+
if (innerWidth !== fittedWidth) { fittedWidth = innerWidth; refitBubbles(); }
|
|
130
|
+
// the World reads walk targets and drop spots against the stage the pet is on now
|
|
131
|
+
send({ t: 'hello', screen: { w: innerWidth, h: innerHeight } });
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
/* ---------- connection ---------- */
|
|
135
|
+
let ws = null, backoff = 500, watching = false;
|
|
136
|
+
const agentSpeedMotion = createActivityMotion();
|
|
137
|
+
function send(msg) { if (ws && ws.readyState === 1) ws.send(JSON.stringify(msg)); }
|
|
138
|
+
function connect() {
|
|
139
|
+
const params = new URLSearchParams({ role: 'pet', host: host ? 'window' : 'tab' });
|
|
140
|
+
if (windowKey) params.set('key', windowKey);
|
|
141
|
+
ws = new WebSocket(`ws://${location.host}/socket?${params}`);
|
|
142
|
+
ws.binaryType = 'arraybuffer';
|
|
143
|
+
ws.onopen = () => { backoff = 500; watching = false; send({ t: 'hello', screen: { w: innerWidth, h: innerHeight }, host: host ? 'window' : 'tab' }); reportVisibility(); };
|
|
144
|
+
ws.onmessage = (e) => { try { onOrder(JSON.parse(e.data)); } catch (err) { console.error(err); } };
|
|
145
|
+
ws.onclose = (e) => {
|
|
146
|
+
ws = null;
|
|
147
|
+
agentSpeedMotion.receive(null, Date.now());
|
|
148
|
+
stopMic();
|
|
149
|
+
talkKeyDown = false;
|
|
150
|
+
// a key let go of while the World was away never reports its release
|
|
151
|
+
pauseHeld = false;
|
|
152
|
+
// the World gave up on these steps when the page went; it asks again once the page is back
|
|
153
|
+
dropDialogs();
|
|
154
|
+
setStatus(null);
|
|
155
|
+
if (e.code === 4000 && !host) return;
|
|
156
|
+
setTimeout(connect, backoff);
|
|
157
|
+
backoff = Math.min(8000, backoff * 2);
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
/** The pet window says whether it is shown: hidden from its menu or the tray, it stays connected. */
|
|
161
|
+
let windowShown = true;
|
|
162
|
+
function reportVisibility() { if (host) send({ t: 'visibility', hidden: !windowShown }); }
|
|
163
|
+
// the page itself always reads as visible (its window does not throttle it): the window process says when it is hidden
|
|
164
|
+
host?.onShown?.((shown) => { windowShown = shown; sfx.setShown(shown); reportVisibility(); if (!shown) pinSlider(null); });
|
|
165
|
+
/** Clicks pass through because a fullscreen window covers the pet's display and the setting says so; the window process decides. */
|
|
166
|
+
let fullscreenThrough = false;
|
|
167
|
+
host?.onFullscreenThrough?.((on) => { fullscreenThrough = on; });
|
|
168
|
+
/** The click-through pause key is held; the World says when it activates and is let go. */
|
|
169
|
+
let pauseHeld = false;
|
|
170
|
+
/**
|
|
171
|
+
* Clicks reach the pet despite click-through while the click-through pause key is held, and while something begun
|
|
172
|
+
* with the mouse or waiting on the person is under way: the typing box, a question or a confirmation, the right-click
|
|
173
|
+
* menu, the look wheel or a pinned slider open, the body held, a slider or the typing box's scrollbar dragged. Each
|
|
174
|
+
* of those ends on its own, a click elsewhere or the window losing focus included.
|
|
175
|
+
*/
|
|
176
|
+
const openNow = (el) => !el.hidden && !leaving(el);
|
|
177
|
+
const clicksLent = () => pauseHeld || (!!item && item.kind !== 'say') || openNow(menu) || openNow(wheel) || pinned !== null
|
|
178
|
+
|| pressing || barHeld || sliding();
|
|
179
|
+
/** Every click passes through the pet right now, by the tray or the fullscreen setting, unless they are lent. */
|
|
180
|
+
const clicksPass = () => (prefs.clickThrough || fullscreenThrough) && !clicksLent();
|
|
181
|
+
/** Tells the window process each time clicksLent changes; it lifts its click-through lock meanwhile. */
|
|
182
|
+
let lentTold = false;
|
|
183
|
+
function stepLend() {
|
|
184
|
+
const on = clicksLent();
|
|
185
|
+
if (on === lentTold) return;
|
|
186
|
+
lentTold = on;
|
|
187
|
+
host?.lendClicks?.(on);
|
|
188
|
+
}
|
|
189
|
+
/** The transparency during full screen holds: its setting is on and a fullscreen window covers the display; the window process decides. */
|
|
190
|
+
let fullscreenFaded = false;
|
|
191
|
+
host?.onFullscreenFade?.((on) => { fullscreenFaded = on; refreshSlider(); });
|
|
192
|
+
|
|
193
|
+
/* ---------- OBS overlay: while the window streams, each frame drawn is reported with the part it sends, the pet and its bubbles ---------- */
|
|
194
|
+
let overlayOn = false;
|
|
195
|
+
/** The body's box with room for its halo and what floats above its head; null with no body. */
|
|
196
|
+
function bodyRoom() {
|
|
197
|
+
const b = at()?.box;
|
|
198
|
+
if (!b) return null;
|
|
199
|
+
// the halo reaches about 40% of the body's width out; emotes and z's float up to its height above; a pack's effects as far as it says
|
|
200
|
+
const reach = (shownPack?.effects?.reach ?? 0) * 256 * bounds().S;
|
|
201
|
+
const side = Math.max(24, .4 * b.w, reach), top = Math.max(48, b.h, reach);
|
|
202
|
+
return { x: b.x - side, y: b.y - top, width: b.w + 2 * side, height: b.h + top + side };
|
|
203
|
+
}
|
|
204
|
+
/** The rect that holds all of `parts`, cut to the page; null when none of it is on the page. */
|
|
205
|
+
function onPage(parts) {
|
|
206
|
+
const x = Math.max(0, Math.min(...parts.map((r) => r.x))), y = Math.max(0, Math.min(...parts.map((r) => r.y)));
|
|
207
|
+
const right = Math.min(innerWidth, Math.max(...parts.map((r) => r.x + r.width))), bottom = Math.min(innerHeight, Math.max(...parts.map((r) => r.y + r.height)));
|
|
208
|
+
return right > x && bottom > y ? { x, y, width: right - x, height: bottom - y } : null;
|
|
209
|
+
}
|
|
210
|
+
/** The body's room joined with the bubbles shown; null with no body. */
|
|
211
|
+
function overlayRect() {
|
|
212
|
+
const room = bodyRoom();
|
|
213
|
+
if (!room) return null;
|
|
214
|
+
const parts = [room];
|
|
215
|
+
for (const el of [bubble, ...lines.map((l) => l.el)]) if (!el.hidden) parts.push(partRect(el));
|
|
216
|
+
return onPage(parts);
|
|
217
|
+
}
|
|
218
|
+
host?.onOverlay?.((on) => { overlayOn = on; });
|
|
219
|
+
|
|
220
|
+
/* ---------- portrait: a picture of the body alone, which the World asks for when the bot looks at itself ---------- */
|
|
221
|
+
/** What the page draws over the stage: the bubbles, the menu's two sides, the hover buttons, the look wheel, the slider over the head and the hover hint. */
|
|
222
|
+
const OVER_STAGE = '.bubble, .menu > *, .tools, .wheel, .head-slider, .hint';
|
|
223
|
+
/**
|
|
224
|
+
* The longest the picture waits for the page's next frame, and then for the display, in milliseconds each: a dozen
|
|
225
|
+
* display refreshes at 60 a second. A page that gets no refresh (its window wholly covered) goes on after it.
|
|
226
|
+
*/
|
|
227
|
+
const PORTRAIT_FRAME_MS = 200;
|
|
228
|
+
/** Waiting for the page's next frame (the frame loop calls them once it has stepped the orders and the body). */
|
|
229
|
+
const afterFrame = [];
|
|
230
|
+
/** Resolves when `wait` calls back, after PORTRAIT_FRAME_MS at the latest. */
|
|
231
|
+
const soon = (wait) => new Promise((done) => { const timer = setTimeout(done, PORTRAIT_FRAME_MS); wait(() => { clearTimeout(timer); done(); }); });
|
|
232
|
+
const overlaps = (a, b) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;
|
|
233
|
+
/**
|
|
234
|
+
* Answers the World's `portrait` order with the body's room as the window draws it, `{ png, width, height }`,
|
|
235
|
+
* or with `failed` and why: `tab` (a browser tab has no window to take it from), `hidden` (the window is hidden, so
|
|
236
|
+
* the body is not drawn), `no-body` (no figure is on the page) or `capture`.
|
|
237
|
+
*
|
|
238
|
+
* Orders reach the body on the page's frames, so the picture is of the page's next frame: an action ordered just
|
|
239
|
+
* before it is in the picture once the body has started it. What the page draws over the stage and reaches into
|
|
240
|
+
* the room is not drawn in the frame taken, and is back in the next.
|
|
241
|
+
*/
|
|
242
|
+
async function takePortrait(id) {
|
|
243
|
+
const fail = (failed) => send({ t: 'portrait', id, failed });
|
|
244
|
+
if (!host?.portrait) return fail('tab');
|
|
245
|
+
if (!windowShown) return fail('hidden');
|
|
246
|
+
await soon((done) => afterFrame.push(done));
|
|
247
|
+
const room = bodyRoom(), rect = room && onPage([room]);
|
|
248
|
+
if (!rect) return fail('no-body');
|
|
249
|
+
const over = [...document.querySelectorAll(OVER_STAGE)].filter((el) => !el.closest('[hidden]') && overlaps(shadowed(partRect(el)), rect));
|
|
250
|
+
for (const el of over) el.style.visibility = 'hidden';
|
|
251
|
+
// the picture is of the body as it is drawn, whatever its transparency on screen
|
|
252
|
+
stage.style.transition = 'none';
|
|
253
|
+
stage.style.opacity = '1';
|
|
254
|
+
try {
|
|
255
|
+
// by the second refresh the display has what the body drew for that frame, without what was over it
|
|
256
|
+
await soon((done) => requestAnimationFrame(() => requestAnimationFrame(done)));
|
|
257
|
+
const shot = await host.portrait(rect);
|
|
258
|
+
if (shot) send({ t: 'portrait', id, ...shot }); else fail('capture');
|
|
259
|
+
} catch {
|
|
260
|
+
fail('capture');
|
|
261
|
+
} finally {
|
|
262
|
+
for (const el of over) el.style.visibility = '';
|
|
263
|
+
stage.style.opacity = '';
|
|
264
|
+
void stage.offsetWidth;
|
|
265
|
+
stage.style.transition = '';
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
/** One picture at a time: a second order waits until the first has put back what it left out. */
|
|
269
|
+
let portraits = Promise.resolve();
|
|
270
|
+
// the text is in before anything is shown
|
|
271
|
+
void useLanguage().then(() => { document.title = t('pet.title'); host?.setLanguage?.(language()); connect(); });
|
|
272
|
+
|
|
273
|
+
/*
|
|
274
|
+
* ---------- the body: a figure pack (src/packs.ts; Coo is one) run in a sandboxed frame ----------
|
|
275
|
+
* The World hears which body is on screen (`figure`), so the bot is told of a switch, and of a pack that
|
|
276
|
+
* would not load or broke while running (no usable WebGL, a missing texture, a bug in its code): the page
|
|
277
|
+
* then shows Coo instead. A body just loaded also says which words of its vocabulary it knows (`words`,
|
|
278
|
+
* null when it does not say).
|
|
279
|
+
*/
|
|
280
|
+
let skin = normalizeSkin(null), wanted = null;
|
|
281
|
+
function reportFigure(id, ok, reason, scheme, known) {
|
|
282
|
+
send({ t: 'figure', id, ok, ...(scheme ? { scheme } : {}), ...(reason ? { reason } : {}), ...(known !== undefined ? { words: known } : {}) });
|
|
283
|
+
}
|
|
284
|
+
function bodyFailed(id, err) {
|
|
285
|
+
console.error(err);
|
|
286
|
+
reportFigure(id, false, String(err?.message ?? err));
|
|
287
|
+
// Coo stands in; when Coo itself will not run there is nothing left to show
|
|
288
|
+
if (id !== 'coo' && wanted === id) showFigure({ ...skin, figure: 'coo' }).catch((e) => console.error(e));
|
|
289
|
+
}
|
|
290
|
+
/** Where the first body stands: the spot the World remembered (`restorePosition`), facing the middle of the screen; `firstY` for a body off the floor. */
|
|
291
|
+
let firstX = null, firstY = null;
|
|
292
|
+
/** The pack whose body is being loaded: skins that come meanwhile wait for it (`skin` holds the latest). */
|
|
293
|
+
let loading = null;
|
|
294
|
+
async function showFigure(s) {
|
|
295
|
+
wanted = s.figure;
|
|
296
|
+
if (loading === s.figure) return;
|
|
297
|
+
// a pick changed while the same pack is on screen fades in, with a dip; Coo's picks are its skin
|
|
298
|
+
if (body?.pack === s.figure) {
|
|
299
|
+
body.set({ skin: s });
|
|
300
|
+
const look = JSON.stringify(s);
|
|
301
|
+
if (shownLook && look !== shownLook) { restyle(body, stage); smoothFor(RESTYLE_MS); }
|
|
302
|
+
shownLook = look;
|
|
303
|
+
if (s.figure !== 'coo') await body.setScheme(s.scheme, { fade: .45 });
|
|
304
|
+
lightFor(s);
|
|
305
|
+
reportFigure(s.figure, true, null, s.figure === 'coo' ? null : s.scheme);
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
loading = s.figure;
|
|
309
|
+
try { await swapBody(s); } finally { if (loading === s.figure) loading = null; }
|
|
310
|
+
// a pick that came while the body was loading
|
|
311
|
+
if (body?.pack === skin.figure && skin !== s) await showFigure(skin);
|
|
312
|
+
}
|
|
313
|
+
/** The look last put on the body on screen, so a look that comes again (a reconnect's `init`) is not animated. */
|
|
314
|
+
let shownLook = null;
|
|
315
|
+
/** Until when (performance.now(), ms) the page draws at the moving rate though the body stands: a switch is under way. */
|
|
316
|
+
let smoothUntil = -Infinity;
|
|
317
|
+
const smoothFor = (ms) => { smoothUntil = Math.max(smoothUntil, performance.now() + ms); };
|
|
318
|
+
/** Until when (performance.now(), ms) the body has no halo: a figure switch is under way. */
|
|
319
|
+
let haloAfter = -Infinity;
|
|
320
|
+
async function swapBody(s) {
|
|
321
|
+
const pack = (await (await fetch('/api/figures')).json()).find((p) => p.id === s.figure);
|
|
322
|
+
if (!pack) throw new Error(t('figure.notInstalled'));
|
|
323
|
+
const was = at();
|
|
324
|
+
const x = was?.x ?? firstX ?? innerWidth * .7, y = was ? was.y : firstY;
|
|
325
|
+
const holder = {};
|
|
326
|
+
const next = await loadBody({
|
|
327
|
+
layer: $('#figureLayer'), pack, theme: prefs.theme, bounds: bounds(),
|
|
328
|
+
// the new body stands where the old one stood; the first one drops in
|
|
329
|
+
start: { x, ...(typeof y === 'number' ? { y } : {}), facing: was?.facing ?? (x < innerWidth / 2 ? 1 : -1), enter: body ? undefined : 'drop', skin: s, scheme: s.scheme },
|
|
330
|
+
onEvent: (kind, d) => { if (body === holder.body) onBody(kind, d); },
|
|
331
|
+
onSound: (name, kind, ...args) => { if (body === holder.body) sfx.play(name, kind, ...args); },
|
|
332
|
+
onError: (err) => { if (body === holder.body) bodyFailed(pack.id, err); },
|
|
333
|
+
});
|
|
334
|
+
if (wanted !== s.figure) { next.dispose(); return; }
|
|
335
|
+
holder.body = next;
|
|
336
|
+
next.set({ roam: prefs.roam, ...bodyState });
|
|
337
|
+
// the old body fades out as the new one fades in; the first one drops in as it is
|
|
338
|
+
const old = body;
|
|
339
|
+
body = next;
|
|
340
|
+
shownLook = JSON.stringify(s);
|
|
341
|
+
// the new body comes in at the size it is put on at; the switch carries the change of size (swap-motion.js)
|
|
342
|
+
const ratio = host ? prefs.scale / drawnScale.value : 1;
|
|
343
|
+
if (drawnScale.value !== prefs.scale) { drawnScale.jump(prefs.scale); next.set({ bounds: bounds() }); }
|
|
344
|
+
if (old) {
|
|
345
|
+
haloAfter = performance.now() + SWAP_MS;
|
|
346
|
+
next.setHalo(0, 0);
|
|
347
|
+
swapOut(old, stage, ratio);
|
|
348
|
+
swapIn(next, stage, next.layout ?? was, ratio);
|
|
349
|
+
smoothFor(SWAP_MS);
|
|
350
|
+
}
|
|
351
|
+
host?.watchWindows?.(next.needsWindows);
|
|
352
|
+
words = new Map(pack.vocab.map((w) => [w.id, w]));
|
|
353
|
+
shownPack = pack;
|
|
354
|
+
lightFor(s);
|
|
355
|
+
sfx.usePack(pack.base, pack.sounds, pack.voice);
|
|
356
|
+
reportFigure(s.figure, true, null, s.figure === 'coo' ? null : s.scheme, next.words);
|
|
357
|
+
}
|
|
358
|
+
/** Whether another figure is on its way to the screen. */
|
|
359
|
+
const switching = () => !!body && !!wanted && body.pack !== wanted;
|
|
360
|
+
async function applyFigure(s) {
|
|
361
|
+
try { await showFigure(s); } catch (err) { bodyFailed(s.figure, err); }
|
|
362
|
+
// a size that waited for a figure that did not come
|
|
363
|
+
if (!switching() && drawnScale.target !== prefs.scale) toSize(prefs.scale);
|
|
364
|
+
}
|
|
365
|
+
/** Draws the body at `v`: on the spring, or at once when motion is low. */
|
|
366
|
+
function toSize(v) {
|
|
367
|
+
if (!lowMotion()) { drawnScale.set(v); return; }
|
|
368
|
+
drawnScale.jump(v);
|
|
369
|
+
body?.set({ bounds: bounds() });
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* The pet window puts the pet where it stood when the World last stopped (`startX`, a share of the window
|
|
374
|
+
* width, and `startY` of its height for a body that stood off the floor) from the first `init` only; after a reconnect it stays where it is. While `rememberPosition` is on it
|
|
375
|
+
* reports where the pet stands each time the body changes mode, so the World holds the place of its last stop.
|
|
376
|
+
*/
|
|
377
|
+
let restored = false, sentX = null, sentY = null;
|
|
378
|
+
function restorePosition(startX, startY) {
|
|
379
|
+
sentX = null;
|
|
380
|
+
if (restored) return;
|
|
381
|
+
restored = true;
|
|
382
|
+
// She starts facing the middle of the screen, so a pet
|
|
383
|
+
// resting on the right half is not turned away from the likely interaction area.
|
|
384
|
+
if (host && typeof startX === 'number') {
|
|
385
|
+
firstX = startX * innerWidth;
|
|
386
|
+
firstY = typeof startY === 'number' ? startY * innerHeight : null;
|
|
387
|
+
body?.place(firstX, firstX < innerWidth / 2 ? 1 : -1, firstY ?? undefined);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
function reportPosition() {
|
|
391
|
+
const l = at();
|
|
392
|
+
if (!host || !prefs.rememberPosition || !l) return;
|
|
393
|
+
const x = l.x / innerWidth, y = typeof l.y === 'number' ? l.y / innerHeight : null;
|
|
394
|
+
if (sentX !== null && Math.abs(x - sentX) * innerWidth < 1 && (y === null) === (sentY === null) && Math.abs((y ?? 0) - (sentY ?? 0)) * innerHeight < 1) return;
|
|
395
|
+
sentX = x; sentY = y;
|
|
396
|
+
send({ t: 'position', x, ...(y !== null ? { y } : {}) });
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** The skin as the config has it while a dialog card dresses the body in another (`tryOn`); null otherwise. */
|
|
400
|
+
let worn = null;
|
|
401
|
+
function putOn(s) { skin = s; skinStyle.textContent = skinCss(skin); void applyFigure(skin); }
|
|
402
|
+
/** A dialog card's skin on the body, over the config's, until the step ends (`takeOff`). */
|
|
403
|
+
function tryOn(patch) {
|
|
404
|
+
worn ??= skin;
|
|
405
|
+
putOn(normalizeSkin({ ...worn, ...patch }));
|
|
406
|
+
}
|
|
407
|
+
/** Ends a card's try-on: `keep` leaves it on (it was the answer, and the config takes it next), else the config's skin comes back. */
|
|
408
|
+
function takeOff(keep) {
|
|
409
|
+
if (!worn) return;
|
|
410
|
+
const was = worn;
|
|
411
|
+
worn = null;
|
|
412
|
+
if (!keep) putOn(was);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function applyPrefs(p) {
|
|
416
|
+
// while a card is tried on, the config's skin waits until the step ends
|
|
417
|
+
if (p.skin) { if (worn) worn = normalizeSkin(p.skin); else putOn(normalizeSkin(p.skin)); }
|
|
418
|
+
if (p.roam) { prefs.roam = p.roam; body?.set({ roam: p.roam }); }
|
|
419
|
+
if (typeof p.sound === 'boolean') { prefs.sound = p.sound; sfx.set(p.sound); }
|
|
420
|
+
if (p.sounds && typeof p.sounds === 'object') sfx.configure({ kinds: p.sounds, snoreSeconds: p.sounds.snoreSeconds, panByPosition: p.sounds.panByPosition, volume: p.sounds.volume });
|
|
421
|
+
if (p.speech && typeof p.speech === 'object') speech.configure(p.speech);
|
|
422
|
+
if (p.theme === 'dark' || p.theme === 'light') { prefs.theme = p.theme; applyTheme(p.theme); modeBtn?.show(p.theme); body?.set({ theme: p.theme }); }
|
|
423
|
+
if (typeof p.glow === 'number') prefs.glow = p.glow;
|
|
424
|
+
if (typeof p.scale === 'number') {
|
|
425
|
+
if (!scaleSeen) { scaleSeen = true; prefs.scale = p.scale; drawnScale.jump(p.scale); body?.set({ bounds: bounds() }); refreshSlider(); }
|
|
426
|
+
else sizeHeard.heard(p.scale, SLIDERS.size.bar.active || !!sliderState.timers.size);
|
|
427
|
+
}
|
|
428
|
+
for (const key of ['fade', 'fullscreenFade']) if (typeof p[key] === 'number') fadeHeard[key].heard(p[key], fadeKey() === key && (SLIDERS.fade.bar.active || !!sliderState.timers.fade));
|
|
429
|
+
if (typeof p.fadeWhenFullscreen === 'boolean') host?.fadeWhenFullscreen?.(p.fadeWhenFullscreen);
|
|
430
|
+
if (p.cua && typeof p.cua === 'object') prefs.cua = { on: p.cua.on === true, confirmed: p.cua.confirmed === true, canOpen: p.cua.canOpen === true };
|
|
431
|
+
const sized = [prefs.bubbleSize, prefs.fontSize];
|
|
432
|
+
if (typeof p.bubbleSize === 'number') { prefs.bubbleSize = p.bubbleSize; sizeVar('--bubble-size', p.bubbleSize); }
|
|
433
|
+
if (typeof p.fontSize === 'number') { prefs.fontSize = p.fontSize; sizeVar('--bubble-font', p.fontSize); }
|
|
434
|
+
if (item?.kind === 'input') item.fitHint?.();
|
|
435
|
+
if (sized[0] !== prefs.bubbleSize || sized[1] !== prefs.fontSize) refitBubbles();
|
|
436
|
+
if (typeof p.bubbleSpeed === 'number') prefs.bubbleSpeed = p.bubbleSpeed;
|
|
437
|
+
if (typeof p.sayBubbleHoldSec === 'number') prefs.sayBubbleHoldSec = p.sayBubbleHoldSec;
|
|
438
|
+
if (typeof p.rememberPosition === 'boolean') { prefs.rememberPosition = p.rememberPosition; reportPosition(); }
|
|
439
|
+
if (typeof p.user === 'string') prefs.user = p.user;
|
|
440
|
+
if (typeof p.micDevice === 'string' && p.micDevice !== prefs.micDevice) { prefs.micDevice = p.micDevice; stopMic(); }
|
|
441
|
+
if (typeof p.mic === 'boolean') { prefs.mic = p.mic; p.mic && !watching ? startMic() : stopMic(); }
|
|
442
|
+
if (p.voice && typeof p.voice === 'object') prefs.voice = { ...prefs.voice, ...p.voice };
|
|
443
|
+
if (typeof p.doubleClickChat === 'boolean') prefs.doubleClickChat = p.doubleClickChat;
|
|
444
|
+
if (typeof p.statusBubble === 'boolean') { prefs.statusBubble = p.statusBubble; setBody({ thoughtShown: p.statusBubble }); }
|
|
445
|
+
if (typeof p.saidBubbles === 'boolean') { prefs.saidBubbles = p.saidBubbles; if (!p.saidBubbles) for (const line of lines) if (!line.live) fadeLine(line); }
|
|
446
|
+
if (typeof p.saidBubbleHoldSec === 'number') prefs.saidBubbleHoldSec = p.saidBubbleHoldSec;
|
|
447
|
+
if (typeof p.lockFrameRate === 'boolean') prefs.lockFrameRate = p.lockFrameRate;
|
|
448
|
+
if (typeof p.motion === 'string' && globalThis.window?.document) setMotionChoice(globalThis.window, p.motion);
|
|
449
|
+
if (typeof p.frameRate === 'number' && p.frameRate >= 0) prefs.frameRate = p.frameRate;
|
|
450
|
+
// the window process does the hiding and the passing through; the page only passes the settings on
|
|
451
|
+
if (typeof p.hideWhenFullscreen === 'boolean') host?.hideWhenFullscreen?.(p.hideWhenFullscreen);
|
|
452
|
+
if (typeof p.passWhenFullscreen === 'boolean') host?.passWhenFullscreen?.(p.passWhenFullscreen);
|
|
453
|
+
if (typeof p.overTaskbar === 'boolean') host?.overTaskbar?.(p.overTaskbar);
|
|
454
|
+
if (typeof p.hideFromCapture === 'boolean') host?.hideFromCapture?.(p.hideFromCapture);
|
|
455
|
+
if (typeof p.clickThrough === 'boolean') { prefs.clickThrough = p.clickThrough; host?.clickThrough?.(p.clickThrough); }
|
|
456
|
+
if (Array.isArray(p.hoverButtons)) prefs.hoverButtons = p.hoverButtons.filter((id) => typeof id === 'string' && id in ACTIONS);
|
|
457
|
+
if (p.bot) { prefs.bot = p.bot; if (!menu.hidden && !menu.querySelector('.m-rail.confirm')) renderMenuRail(); }
|
|
458
|
+
if (typeof p.language === 'string' && p.language !== language()) void switchLanguage(p.language);
|
|
459
|
+
if ('status' in p) setStatus(p.status);
|
|
460
|
+
refreshButtons();
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** Sets a bubble size factor on the page (pet.css); at 1 it is unset, so the bubbles are drawn exactly as pet.css writes them. */
|
|
464
|
+
function sizeVar(name, k) {
|
|
465
|
+
if (k === 1) document.documentElement.style.removeProperty(name);
|
|
466
|
+
else document.documentElement.style.setProperty(name, String(k));
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** A new app language: what is drawn from the page's own text is drawn again; bubbles already up keep theirs. */
|
|
470
|
+
async function switchLanguage(code) {
|
|
471
|
+
await useLanguage(code);
|
|
472
|
+
document.title = t('pet.title');
|
|
473
|
+
host?.setLanguage?.(code);
|
|
474
|
+
if (!menu.hidden && !menu.querySelector('.m-rail.confirm')) renderMenuRail();
|
|
475
|
+
refreshButtons();
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function onOrder(m) {
|
|
479
|
+
switch (m.t) {
|
|
480
|
+
case 'init': restorePosition(m.startX, m.startY); applyPrefs(m); if (!host) announcePainted(); break;
|
|
481
|
+
case 'prefs': applyPrefs(m); break;
|
|
482
|
+
case 'agent-speed-activity': if (host) agentSpeedMotion.receive(m.snapshot, Date.now()); break;
|
|
483
|
+
case 'watching': watching = true; stopMic(); break;
|
|
484
|
+
// the settings window's 「在桌面上隐藏」: the same as the menu's 「隐藏」
|
|
485
|
+
case 'hide': host?.hide?.(); break;
|
|
486
|
+
case 'type': openTyping(); break;
|
|
487
|
+
case 'throughPause': pauseHeld = m.on === true; stepLend(); break;
|
|
488
|
+
case 'say': dropAsks(); queue.push({ kind: 'say', id: m.id, beats: m.beats, i: -1 }); holdRoam(20); break;
|
|
489
|
+
case 'ask': dropAsks(); queue.push({ kind: 'ask', id: m.id, question: m.question, options: m.options || [], own: m.own !== false }); holdRoam(20); break;
|
|
490
|
+
case 'confirm': dropAsks(); rushLines(); queue.push({ kind: 'ask', confirm: true, id: m.id, question: m.question, options: m.options, own: false }); holdRoam(20); break;
|
|
491
|
+
case 'walk': walk(m); break;
|
|
492
|
+
case 'move': walk(m); break;
|
|
493
|
+
case 'walk-stop': body?.stopWalk(m.id); break;
|
|
494
|
+
case 'ask-close': closeAsk(m.id); break;
|
|
495
|
+
case 'act': acts.push(...m.actions); holdRoam(20); break;
|
|
496
|
+
case 'portrait': portraits = portraits.then(() => takePortrait(m.id)); break;
|
|
497
|
+
case 'listen': onListen(m); break;
|
|
498
|
+
case 'talk-key': hushForTalkKey(m.down === true); break;
|
|
499
|
+
// a message sent from the chat page, once the bot has it, and one taken back before delivery
|
|
500
|
+
case 'said': if (prefs.saidBubbles) addLine('chat', typeof m.text === 'string' ? m.text : '', false, { images: Number(m.images) || 0, cursor: m.cursor ?? null }); break;
|
|
501
|
+
case 'said-withdrawn': withdrawLine(m.cursor); break;
|
|
502
|
+
case 'status': setStatus(m.status); break;
|
|
503
|
+
case 'dialog': queue.push({ kind: 'dialog', id: m.id, d: m }); holdRoam(20); break;
|
|
504
|
+
case 'dialog-update': updateDialog(m); break;
|
|
505
|
+
case 'dialog-close': endDialog(m.id); break;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/** Tells the body of a change in the page's states (listening, thinking, a bubble that wants it to stay put). */
|
|
510
|
+
function setBody(change) {
|
|
511
|
+
if (Object.entries(change).every(([k, v]) => bodyState[k] === v)) return;
|
|
512
|
+
Object.assign(bodyState, change);
|
|
513
|
+
body?.set(change);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/* ---------- body events → World ---------- */
|
|
517
|
+
const walkTargets = new Map();
|
|
518
|
+
function onBody(kind, d) {
|
|
519
|
+
if (kind === 'arrived' || kind === 'interrupted') {
|
|
520
|
+
if (!d.walkId || !walkTargets.has(d.walkId)) return;
|
|
521
|
+
walkTargets.delete(d.walkId);
|
|
522
|
+
const y = typeof d.y === 'number' ? d.y : at()?.y;
|
|
523
|
+
send({ t: kind, walkId: d.walkId, x: (typeof d.x === 'number' ? d.x : at()?.x ?? 0) / innerWidth, ...(typeof y === 'number' ? { y: y / innerHeight } : {}), by: d.by });
|
|
524
|
+
} else if (kind === 'touch') {
|
|
525
|
+
send({ t: 'touch', ...d });
|
|
526
|
+
if (d.kind === 'grab') closeMenu();
|
|
527
|
+
} else if (kind === 'mode') {
|
|
528
|
+
reportPosition();
|
|
529
|
+
} else if (kind === 'done') {
|
|
530
|
+
// a word that ends on its own (a walk across the screen) lets the next one start at once
|
|
531
|
+
if (d.word === actWord) actUntil = T;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** A walk to a default target, or a `move` to one of the pack's own, which the body is handed as the World sent it. */
|
|
536
|
+
function walk(m) {
|
|
537
|
+
holdRoam(20);
|
|
538
|
+
if (!body) { send({ t: 'interrupted', walkId: m.id, x: .5, by: 'none' }); return; }
|
|
539
|
+
walkTargets.set(m.id, true);
|
|
540
|
+
if (m.t === 'move') { body.move(m.move, m.id); return; }
|
|
541
|
+
const x = m.to === 'cursor' ? (pointerSeen ? lastPointer.x : innerWidth / 2) : clamp(Number(m.to), 0, 1) * innerWidth;
|
|
542
|
+
body.walk(x, !!m.run, m.id);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/* ---------- actions: words of the body's vocabulary, one after another ---------- */
|
|
546
|
+
const acts = [];
|
|
547
|
+
/** When the word playing lets the next one start (its `seconds`, or its `done`), and which word it is. */
|
|
548
|
+
let actUntil = 0, actWord = null;
|
|
549
|
+
function stepActs() {
|
|
550
|
+
if (T < actUntil || !acts.length) return;
|
|
551
|
+
const l = at();
|
|
552
|
+
if (!l || l.busy) return;
|
|
553
|
+
const a = acts.shift();
|
|
554
|
+
if (a === FIREWORKS) lightFireworks(l); else body.do(a);
|
|
555
|
+
actWord = a;
|
|
556
|
+
actUntil = T + (words.get(a)?.seconds ?? 1);
|
|
557
|
+
holdRoam(15);
|
|
558
|
+
}
|
|
559
|
+
/** The New Year fireworks, a word `act` orders carry only while the World offers it: a picture above and behind Coo, kept inside the window. */
|
|
560
|
+
const FIREWORKS = 'fireworks_2027', FIREWORKS_W = 520, FIREWORKS_H = 310;
|
|
561
|
+
/** A little past the 6.3 s the picture takes to fade out on its own. */
|
|
562
|
+
const FIREWORKS_MS = 6500;
|
|
563
|
+
function lightFireworks(l) {
|
|
564
|
+
const img = document.createElement('img');
|
|
565
|
+
img.className = 'fireworks';
|
|
566
|
+
img.src = '/web/new-year-2027.svg';
|
|
567
|
+
img.width = FIREWORKS_W;
|
|
568
|
+
img.height = FIREWORKS_H;
|
|
569
|
+
img.style.left = clamp(l.x - FIREWORKS_W / 2, 0, innerWidth - FIREWORKS_W) + 'px';
|
|
570
|
+
img.style.top = clamp(l.box.y + l.box.h / 2 - FIREWORKS_H, 0, innerHeight - FIREWORKS_H) + 'px';
|
|
571
|
+
stage.prepend(img);
|
|
572
|
+
setTimeout(() => img.remove(), FIREWORKS_MS);
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/* ---------- say / ask ---------- */
|
|
576
|
+
const queue = [];
|
|
577
|
+
let item = null;
|
|
578
|
+
/** Where typing pauses: sentence and clause marks, Latin and full-width (Chinese and Japanese share 。、). */
|
|
579
|
+
const PAUSE = /[,.!?;:…,。!?;:、]/, SILENT = /[\s,.!?;:…,。!?;:、「」『』()()]/;
|
|
580
|
+
|
|
581
|
+
/** Lines queued ahead of a World's confirmation type at RUSH times the speed without voice or babble, and stay RUSH_HOLD seconds a beat. */
|
|
582
|
+
const RUSH = 6, RUSH_HOLD = 1;
|
|
583
|
+
function rushLines() {
|
|
584
|
+
for (const q of [item, ...queue]) {
|
|
585
|
+
if (q?.kind !== 'say' || q.rush) continue;
|
|
586
|
+
q.rush = true;
|
|
587
|
+
if (q === item) { speech.stop(); if (q.beatDone) q.holdUntil = Math.min(q.holdUntil, T + RUSH_HOLD); }
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** A newer question replaces the bot's open one; a World's confirmation stays until answered. */
|
|
592
|
+
function dropAsks() {
|
|
593
|
+
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].kind === 'ask' && !queue[i].confirm) queue.splice(i, 1);
|
|
594
|
+
if (item && item.kind === 'ask' && !item.answered && !item.confirm) closeBubble();
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function openBubble(kind, html) {
|
|
598
|
+
item.cursorAt = cursor.at;
|
|
599
|
+
item.cursorHolding = false;
|
|
600
|
+
bubble.className = 'bubble ' + kind;
|
|
601
|
+
bubble.style.maxWidth = '';
|
|
602
|
+
bubble.removeAttribute('aria-label');
|
|
603
|
+
delete bubble.dataset.kind; delete bubble.dataset.icon;
|
|
604
|
+
bubble.innerHTML = html;
|
|
605
|
+
bubble.hidden = false;
|
|
606
|
+
void bubble.offsetWidth;
|
|
607
|
+
bubble.classList.add('pop');
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Coo's bubble for a line of `text`, as narrow as the whole line allows (ui.js balancedWidth): the line types into it,
|
|
611
|
+
* the bubble growing as it goes and wrapping where the whole line wraps; the caret is measured in, so it does not
|
|
612
|
+
* push a word down while typing.
|
|
613
|
+
*/
|
|
614
|
+
function fitLine(text) {
|
|
615
|
+
const p = bubble.querySelector('.b-text');
|
|
616
|
+
p.textContent = text;
|
|
617
|
+
p.append(Object.assign(document.createElement('span'), { className: 'caret' }));
|
|
618
|
+
bubble.style.maxWidth = balancedWidth(bubble) + 'px';
|
|
619
|
+
p.replaceChildren();
|
|
620
|
+
}
|
|
621
|
+
function closeBubble() {
|
|
622
|
+
releaseKeys(item);
|
|
623
|
+
barHeld = false;
|
|
624
|
+
// a step taken off the bubble unanswered puts back the skin a card tried on
|
|
625
|
+
if (item?.kind === 'dialog') { talk.motion = null; takeOff(false); }
|
|
626
|
+
bubble.hidden = true; bubble.innerHTML = '';
|
|
627
|
+
// the lines it answered fade a moment after (stepLines)
|
|
628
|
+
if (item) item.endedAt = T;
|
|
629
|
+
item = null;
|
|
630
|
+
speech.stop();
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* The typing key: the typing box, as a double-click opens it, or the one already open. The pet window
|
|
635
|
+
* takes the keyboard from the window in front and gives it back when the box closes (releaseKeys).
|
|
636
|
+
*/
|
|
637
|
+
function openTyping() {
|
|
638
|
+
if (item?.kind !== 'input') openInput();
|
|
639
|
+
// a question waiting on an answer keeps the bubble
|
|
640
|
+
if (item?.kind !== 'input') return;
|
|
641
|
+
// again for a box already open: the keyboard may have gone back to another window meanwhile
|
|
642
|
+
if (host?.grabFocus) { item.grabbed = true; host.grabFocus(); }
|
|
643
|
+
setTimeout(() => bubble.querySelector('textarea')?.focus(), 30);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* While a question's options are up, the pet window takes the keyboard so 1–9 pick one right
|
|
648
|
+
* away, and gives it back to the window that had it once the question is answered or gone.
|
|
649
|
+
*/
|
|
650
|
+
function grabKeys(it) {
|
|
651
|
+
if (!host?.grabFocus || !it.options.length) return;
|
|
652
|
+
it.grabbed = true;
|
|
653
|
+
host.grabFocus();
|
|
654
|
+
}
|
|
655
|
+
function releaseKeys(it) {
|
|
656
|
+
if (!it?.grabbed) return;
|
|
657
|
+
it.grabbed = false;
|
|
658
|
+
host.releaseFocus();
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* The column that hangs off the right side of a bubble with a close button (pet.css .b-side): a small round × drawn as
|
|
663
|
+
* the hover buttons are, and for the typing box, under it, the text's scrollbar. Every bubble with a × has it. The ×
|
|
664
|
+
* is drawn, not typed: a font's × sits off its line's middle, and so off the button's.
|
|
665
|
+
*/
|
|
666
|
+
const CROSS = '<svg viewBox="0 0 12 12" aria-hidden="true"><path d="M3 3l6 6M9 3l-6 6"/></svg>';
|
|
667
|
+
function sideColumn(label, titled = false, scrollbar = false) {
|
|
668
|
+
const l = esc(label);
|
|
669
|
+
return `<div class="b-side"><button class="b-close" type="button" aria-label="${l}"${titled ? ` title="${l}"` : ''}>${CROSS}</button>${scrollbar ? '<div class="b-track" aria-hidden="true" hidden><i class="b-thumb"></i></div>' : ''}</div>`;
|
|
670
|
+
}
|
|
671
|
+
/** Pixels a bubble's side column (sideColumn) takes past its right edge: its width and the 2.5px border plus 8.5px gap before it (pet.css .b-side). */
|
|
672
|
+
function sideRoom(el) {
|
|
673
|
+
const side = el.querySelector(':scope > .b-side');
|
|
674
|
+
return side ? side.offsetWidth + 11 : 0;
|
|
675
|
+
}
|
|
676
|
+
/** The bubble's rect together with its side column's, which hangs outside it, as a plain object. */
|
|
677
|
+
function bubbleRect() {
|
|
678
|
+
const r = bubble.getBoundingClientRect(), s = bubble.querySelector(':scope > .b-side')?.getBoundingClientRect() ?? r;
|
|
679
|
+
const left = Math.min(r.left, s.left), top = Math.min(r.top, s.top), right = Math.max(r.right, s.right), bottom = Math.max(r.bottom, s.bottom);
|
|
680
|
+
return { left, top, right, bottom, x: left, y: top, width: right - left, height: bottom - top };
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function startItem(it) {
|
|
684
|
+
item = it;
|
|
685
|
+
if (it.kind === 'say' || it.kind === 'ask') answerLines(it);
|
|
686
|
+
if (it.kind === 'dialog') { openDialog(it); return; }
|
|
687
|
+
if (it.kind === 'ask') {
|
|
688
|
+
openBubble('ask', `${sideColumn(t('bubble.close'))}<p class="b-text"></p><div class="b-opts" hidden></div>`);
|
|
689
|
+
bubble.querySelector('.b-close').addEventListener('click', () => dismissAsk());
|
|
690
|
+
it.text = it.question; it.shown = 0; it.acc = 0; it.optsShown = false;
|
|
691
|
+
if (!it.confirm) sfx.pop();
|
|
692
|
+
else {
|
|
693
|
+
sfx.alert();
|
|
694
|
+
// the bubble stays where it opened while Coo moves; the World counts the wait from now
|
|
695
|
+
const a = at()?.bubble ?? { x: innerWidth / 2, y: innerHeight };
|
|
696
|
+
it.pinX = a.x; it.pinY = a.y;
|
|
697
|
+
send({ t: 'confirm-shown', id: it.id });
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* Compare both cursor positions with the same rectangle so the bubble's animation cannot start a hover. A hover
|
|
704
|
+
* starts only from a known position outside the bubble: a frame without one (the window turning click-through
|
|
705
|
+
* reports a pointerleave) keeps the last known position and the hold as they were.
|
|
706
|
+
*/
|
|
707
|
+
function heldByCursor(it) {
|
|
708
|
+
const p = cursor.at;
|
|
709
|
+
if (!p) return false;
|
|
710
|
+
const previous = it.cursorAt;
|
|
711
|
+
it.cursorAt = p;
|
|
712
|
+
if (bubble.hidden || clicksPass()) {
|
|
713
|
+
it.cursorHolding = false;
|
|
714
|
+
return false;
|
|
715
|
+
}
|
|
716
|
+
const r = bubbleRect();
|
|
717
|
+
it.cursorHolding = inRect(p, r) && (it.cursorHolding || (!!previous && !inRect(previous, r)));
|
|
718
|
+
return it.cursorHolding;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** A click on a line's bubble, away from its links, ends the whole line as the person's own lines close: its voice stops and its later beats are dropped. */
|
|
722
|
+
bubble.addEventListener('click', (e) => {
|
|
723
|
+
if (item?.kind !== 'say' || item.skippedAt !== undefined || bubble.hidden || e.target.closest('a')) return;
|
|
724
|
+
item.skippedAt = T;
|
|
725
|
+
send({ t: 'skipped', id: item.id });
|
|
726
|
+
speech.stop();
|
|
727
|
+
sfx.tick();
|
|
728
|
+
bubble.classList.add('fading');
|
|
729
|
+
});
|
|
730
|
+
|
|
731
|
+
/**
|
|
732
|
+
* The place over the head is held by the look wheel or a slider, not folding away: the activity bubble, drawn in the
|
|
733
|
+
* same place, waits for it to go (stepStatus) and shows then if the activity is still going on.
|
|
734
|
+
*/
|
|
735
|
+
const headShown = () => headTaken(null);
|
|
736
|
+
/**
|
|
737
|
+
* The look wheel or a slider over the head is in use: dragged, or the pointer still among the pet's controls. What Coo
|
|
738
|
+
* says, asks or shows waits meanwhile (stepDialog) and comes once the person is done, nothing dropped. One left
|
|
739
|
+
* showing with the pointer gone (a pinned slider) gives way to it as before. A confirmation waits for nothing: with
|
|
740
|
+
* one queued, the lines before it and then it take the place at once, so it is never held past its time.
|
|
741
|
+
*/
|
|
742
|
+
function headInUse() {
|
|
743
|
+
const el = HEAD.find((o) => !o.el.hidden && !leaving(o.el))?.el;
|
|
744
|
+
return !!el && (sliding() || amongControls(cursor.at, el));
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
function stepDialog(dt) {
|
|
748
|
+
if (!item && queue.length && at() && !at().busy && (!headInUse() || queue.some((q) => q.confirm))) startItem(queue.shift());
|
|
749
|
+
const it = item;
|
|
750
|
+
if (!it) return;
|
|
751
|
+
if (it.kind === 'say') {
|
|
752
|
+
if (it.skippedAt !== undefined) { if (T - it.skippedAt >= LINE_FADE) closeBubble(); return; }
|
|
753
|
+
const held = heldByCursor(it);
|
|
754
|
+
if (it.i < 0 || it.beatDone) {
|
|
755
|
+
if (it.beatDone) {
|
|
756
|
+
if (held) it.holdUntil += dt;
|
|
757
|
+
// a question or guide card waiting behind the line ends a fixed hold where the automatic one would
|
|
758
|
+
const cut = !it.rush && queue.some((q) => q.kind === 'ask' || q.kind === 'dialog') ? it.extraHold : 0;
|
|
759
|
+
if (T < it.holdUntil - cut) return;
|
|
760
|
+
}
|
|
761
|
+
it.i++;
|
|
762
|
+
it.beatDone = false;
|
|
763
|
+
if (it.i >= it.beats.length) { closeBubble(); return; }
|
|
764
|
+
const b = it.beats[it.i];
|
|
765
|
+
let lead = 0;
|
|
766
|
+
for (const a of b.actions || []) { acts.push(a); lead = .45; }
|
|
767
|
+
it.shown = 0; it.acc = 0; it.fired = 0; it.startAt = T + lead;
|
|
768
|
+
if (b.text) { openBubble('say', '<p class="b-text"></p>'); fitLine(b.text); sfx.pop(); } else { bubble.hidden = true; }
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
const b = it.beats[it.i];
|
|
772
|
+
if (T < it.startAt) return;
|
|
773
|
+
if (!b.text) { it.beatDone = true; it.holdUntil = T + .8 / prefs.bubbleSpeed; it.extraHold = 0; return; }
|
|
774
|
+
typeText(it, b.text, dt, b.anchors || []);
|
|
775
|
+
if (it.shown >= b.text.length && !it.beatDone) {
|
|
776
|
+
it.beatDone = true;
|
|
777
|
+
const last = it.i === it.beats.length - 1;
|
|
778
|
+
// the lines this answers fade a moment after its last line is written out (stepLines)
|
|
779
|
+
if (last) it.writtenAt ??= T;
|
|
780
|
+
const auto = (last ? 1.6 + b.text.length * .07 : .9 + b.text.length * .03) / prefs.bubbleSpeed;
|
|
781
|
+
it.holdUntil = T + (it.rush ? RUSH_HOLD : prefs.sayBubbleHoldSec || auto);
|
|
782
|
+
it.extraHold = Math.max(0, prefs.sayBubbleHoldSec - auto);
|
|
783
|
+
}
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
if (it.kind === 'ask') {
|
|
787
|
+
if (it.shown < it.text.length) { typeText(it, it.text, dt, []); return; }
|
|
788
|
+
if (!it.optsShown) { it.optsShown = true; showOptions(it); }
|
|
789
|
+
}
|
|
790
|
+
if (it.kind === 'dialog') stepTalk(it, dt);
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/** The talk key starts listening: the sound stops at once, and the lines up or waiting go on without it. */
|
|
794
|
+
function hushForTalkKey(down) {
|
|
795
|
+
talkKeyDown = down;
|
|
796
|
+
if (!down) return;
|
|
797
|
+
speech.stop();
|
|
798
|
+
for (const q of [item, ...queue]) if (q) q.hushed = true;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
function typeText(it, text, dt, anchors) {
|
|
802
|
+
const p = bubble.querySelector('.b-text');
|
|
803
|
+
if (!p || it.shown >= text.length) return;
|
|
804
|
+
if (talkKeyDown) it.hushed = true;
|
|
805
|
+
if (it.spoken !== text && !it.rush && !it.hushed) { it.spoken = text; speech.begin(text); }
|
|
806
|
+
// with speech, each pause mark waits its own time, letters type faster, and the voice makes the sound;
|
|
807
|
+
// estimateSeconds in src/script.ts mirrors these steps, this rate and the holds in stepDialog
|
|
808
|
+
const spoken = speech.active && !it.hushed;
|
|
809
|
+
it.acc += dt * 20 * prefs.bubbleSpeed * (it.rush ? RUSH : 1);
|
|
810
|
+
while (it.acc >= 1 && it.shown < text.length) {
|
|
811
|
+
const ch = text[it.shown++];
|
|
812
|
+
it.acc -= spoken ? textSteps(ch) : PAUSE.test(ch) ? 5 : 1;
|
|
813
|
+
if (spoken) speech.reveal(it.shown - 1);
|
|
814
|
+
else if (!SILENT.test(ch) && !it.rush && !it.hushed) { sfx.babble(ch); body?.talk(); }
|
|
815
|
+
while (it.fired < anchors.length && anchors[it.fired].at <= it.shown) acts.push(...anchors[it.fired++].actions);
|
|
816
|
+
}
|
|
817
|
+
if (it.marks?.length) p.innerHTML = marked(text, it.shown, it.marks);
|
|
818
|
+
else p.replaceChildren(linked(text, it.shown));
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/** The first `n` characters of `text`, escaped, with every one of `words` in it wrapped for the theme color. */
|
|
822
|
+
function marked(text, n, words) {
|
|
823
|
+
const on = new Array(text.length).fill(false);
|
|
824
|
+
for (const w of words) {
|
|
825
|
+
if (!w) continue;
|
|
826
|
+
for (let i = text.indexOf(w); i >= 0; i = text.indexOf(w, i + w.length)) on.fill(true, i, i + w.length);
|
|
827
|
+
}
|
|
828
|
+
let out = '', open = false;
|
|
829
|
+
for (let i = 0; i < n; i++) {
|
|
830
|
+
if (on[i] !== open) { out += on[i] ? '<b class="d-mark">' : '</b>'; open = on[i]; }
|
|
831
|
+
out += esc(text[i]);
|
|
832
|
+
}
|
|
833
|
+
return open ? out + '</b>' : out;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/** The own answer's cap: the bubble's, though the World takes more. */
|
|
837
|
+
const OWN_MAX = 200;
|
|
838
|
+
/**
|
|
839
|
+
* A text field with a cap of `max` characters (of the trimmed text, as the World counts them). Past the cap the text
|
|
840
|
+
* stays in the field, the form gets `over`, `count` shows and the caller does not send. `painted(over, n)` follows
|
|
841
|
+
* each repaint. Returns the repaint, which gives how many characters are over.
|
|
842
|
+
*/
|
|
843
|
+
function capField(form, field, count, max, painted) {
|
|
844
|
+
const paint = () => {
|
|
845
|
+
const n = field.value.trim().length, over = Math.max(0, n - max);
|
|
846
|
+
count.hidden = !over;
|
|
847
|
+
count.textContent = `${n} / ${max}`;
|
|
848
|
+
count.title = over ? t('bubble.tooLong', { over }) : '';
|
|
849
|
+
form.classList.toggle('over', over > 0);
|
|
850
|
+
painted?.(over, n);
|
|
851
|
+
return over;
|
|
852
|
+
};
|
|
853
|
+
field.addEventListener('input', paint);
|
|
854
|
+
paint();
|
|
855
|
+
return paint;
|
|
856
|
+
}
|
|
857
|
+
function shake(form) { form.classList.remove('shake'); void form.offsetWidth; form.classList.add('shake'); }
|
|
858
|
+
|
|
859
|
+
function showOptions(it) {
|
|
860
|
+
const box = bubble.querySelector('.b-opts');
|
|
861
|
+
it.options.forEach((label, i) => {
|
|
862
|
+
const b = document.createElement('button');
|
|
863
|
+
b.type = 'button'; b.className = 'b-opt';
|
|
864
|
+
b.innerHTML = i < 9 ? `<kbd>${i + 1}</kbd><span></span>` : '<span></span>';
|
|
865
|
+
b.querySelector('span').textContent = label;
|
|
866
|
+
b.style.animationDelay = (i * .07) + 's';
|
|
867
|
+
b.addEventListener('click', () => answer(b, { index: i }));
|
|
868
|
+
box.appendChild(b);
|
|
869
|
+
setTimeout(() => sfx.blub(), i * 70);
|
|
870
|
+
});
|
|
871
|
+
if (it.own) {
|
|
872
|
+
const form = document.createElement('form');
|
|
873
|
+
form.className = 'b-own';
|
|
874
|
+
form.innerHTML = `<input type="text" autocomplete="off" placeholder="${esc(t('bubble.ownPlaceholder'))}" aria-label="${esc(t('bubble.ownLabel'))}"><span class="b-count" hidden></span><button type="submit">${esc(t('bubble.send'))}</button>`;
|
|
875
|
+
form.style.animationDelay = (it.options.length * .07) + 's';
|
|
876
|
+
const capped = capField(form, form.querySelector('input'), form.querySelector('.b-count'), OWN_MAX);
|
|
877
|
+
form.addEventListener('submit', (e) => {
|
|
878
|
+
e.preventDefault();
|
|
879
|
+
const input = form.querySelector('input'), v = input.value.trim();
|
|
880
|
+
if (!v) { input.focus(); return; }
|
|
881
|
+
if (capped()) { shake(form); input.focus(); return; }
|
|
882
|
+
answer(form, { text: v });
|
|
883
|
+
});
|
|
884
|
+
box.appendChild(form);
|
|
885
|
+
}
|
|
886
|
+
box.hidden = false;
|
|
887
|
+
grabKeys(it);
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
function answer(node, a) {
|
|
891
|
+
const it = item;
|
|
892
|
+
if (!it || it.kind !== 'ask' || it.answered) return;
|
|
893
|
+
it.answered = true;
|
|
894
|
+
sfx.select();
|
|
895
|
+
node.classList.add('chosen');
|
|
896
|
+
bubble.querySelectorAll('.b-opt, .b-own').forEach((n) => { if (n !== node) n.classList.add('dim'); });
|
|
897
|
+
send(it.confirm ? { t: 'confirmed', id: it.id, index: a.index } : { t: 'answer', askId: it.id, ...a });
|
|
898
|
+
// the bubble stays a moment longer; the keyboard goes back now
|
|
899
|
+
releaseKeys(it);
|
|
900
|
+
body?.cue('cheer');
|
|
901
|
+
setTimeout(() => { if (item === it) closeBubble(); }, 700);
|
|
902
|
+
}
|
|
903
|
+
/** The question was answered elsewhere (the chat page): it leaves the queue or the bubble without an answer from here. */
|
|
904
|
+
function closeAsk(id) {
|
|
905
|
+
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].kind === 'ask' && queue[i].id === id) queue.splice(i, 1);
|
|
906
|
+
if (item && item.kind === 'ask' && item.id === id && !item.answered) { item.answered = true; closeBubble(); }
|
|
907
|
+
}
|
|
908
|
+
function dismissAsk() {
|
|
909
|
+
const it = item;
|
|
910
|
+
if (!it || it.kind !== 'ask' || it.answered) return;
|
|
911
|
+
it.answered = true;
|
|
912
|
+
send(it.confirm ? { t: 'confirmed', id: it.id, index: null } : { t: 'answer', askId: it.id, dismissed: true });
|
|
913
|
+
closeBubble();
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
/* ---------- an app's conversation: one step at a time in Coo's bubble ---------- */
|
|
917
|
+
/** How Coo moves while a step's choice cards are up, around the spot the bubble is pinned to. */
|
|
918
|
+
const talk = { motion: null, next: 0 };
|
|
919
|
+
/** Pixels Coo strays either side of the bubble while showing a motion. */
|
|
920
|
+
const TALK_RANGE = 240;
|
|
921
|
+
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
922
|
+
|
|
923
|
+
function dropDialogs() {
|
|
924
|
+
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].kind === 'dialog') queue.splice(i, 1);
|
|
925
|
+
if (item?.kind === 'dialog') closeBubble();
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
function openDialog(it) {
|
|
929
|
+
const d = it.d;
|
|
930
|
+
const dots = Array.isArray(d.step) ? Array.from({ length: d.step[1] }, (_, i) => `<i class="${i + 1 < d.step[0] ? 'past' : i + 1 === d.step[0] ? 'on' : ''}"></i>`).join('') : '';
|
|
931
|
+
const back = typeof d.back === 'string' && d.back ? `<button class="d-back" type="button">${esc(d.back)}</button>` : '';
|
|
932
|
+
openBubble('talk', `${d.closable ? sideColumn(t('bubble.skip'), true) : ''}${dots || back ? `<div class="d-top">${back}<span class="d-dots">${dots}</span></div>` : ''}<p class="b-text"></p><div class="d-body" hidden></div>`);
|
|
933
|
+
bubble.querySelector('.b-close')?.addEventListener('click', () => settleDialog(it, { closed: true }));
|
|
934
|
+
bubble.querySelector('.d-back')?.addEventListener('click', () => settleDialog(it, { back: true }));
|
|
935
|
+
for (const a of d.actions || []) acts.push(a);
|
|
936
|
+
it.text = d.text || ''; it.shown = 0; it.acc = 0; it.bodyShown = false; it.readUntil = 0;
|
|
937
|
+
it.marks = Array.isArray(d.marks) ? d.marks.filter((w) => typeof w === 'string') : [];
|
|
938
|
+
sfx.pop();
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
function stepTalk(it, dt) {
|
|
942
|
+
if (it.shown < it.text.length) { typeText(it, it.text, dt, []); return; }
|
|
943
|
+
if (it.bodyShown) return;
|
|
944
|
+
it.bodyShown = true;
|
|
945
|
+
if (!it.d.input) { it.readUntil = T + (1.4 + it.text.length * .05) / prefs.bubbleSpeed; return; }
|
|
946
|
+
showDialogInput(it);
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
/** A step with nothing to answer ends once its line has been read; the pointer over it does not hold it, so the guide keeps its pace. */
|
|
950
|
+
function stepTalkRead() {
|
|
951
|
+
const it = item;
|
|
952
|
+
if (it?.kind !== 'dialog' || it.d.input || !it.readUntil) return;
|
|
953
|
+
if (T > it.readUntil) settleDialog(it, { done: true });
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
function showDialogInput(it) {
|
|
957
|
+
const body = bubble.querySelector('.d-body'), input = it.d.input;
|
|
958
|
+
if (!body) return;
|
|
959
|
+
if (input.kind === 'buttons') {
|
|
960
|
+
if (input.keys) body.insertAdjacentHTML('beforeend', `<div class="d-keys"><kbd class="d-key${input.taps > 1 ? ' taps' : ''}">${esc(input.keys)}</kbd>${input.taps > 1 ? `<span class="d-taps">×${Number(input.taps)}</span>` : ''}</div>`);
|
|
961
|
+
const row = Object.assign(document.createElement('div'), { className: 'd-row' });
|
|
962
|
+
input.options.forEach((o, i) => row.appendChild(pill(o.label, o.primary, () => settleDialog(it, { index: i }), o.hover)));
|
|
963
|
+
body.appendChild(row);
|
|
964
|
+
} else if (input.kind === 'choices') {
|
|
965
|
+
const cards = Object.assign(document.createElement('div'), { className: input.list ? 'd-cards list' : 'd-cards' });
|
|
966
|
+
const extra = Array.isArray(input.more?.options) ? input.more.options : [];
|
|
967
|
+
const all = [...input.options, ...extra];
|
|
968
|
+
const pick = (i, speak) => {
|
|
969
|
+
it.value = i;
|
|
970
|
+
cards.querySelectorAll('.d-card').forEach((c) => c.classList.toggle('on', Number(c.dataset.i) === i));
|
|
971
|
+
const o = all[i];
|
|
972
|
+
// the bubble stays put from here on, so the cards do not run off while Coo shows how it moves
|
|
973
|
+
if (it.pinX === undefined) { const a = at()?.bubble ?? { x: innerWidth / 2, y: innerHeight }; it.pinX = a.x; it.pinY = a.y; }
|
|
974
|
+
talk.motion = o?.motion ?? null; talk.next = 0;
|
|
975
|
+
if (o?.skin) tryOn(o.skin);
|
|
976
|
+
if (speak && o?.line) { it.text = o.line; it.shown = 0; it.acc = 0; }
|
|
977
|
+
if (speak && o?.actions) acts.push(...o.actions);
|
|
978
|
+
};
|
|
979
|
+
const card = (o, k, onClick) => {
|
|
980
|
+
const c = document.createElement('button');
|
|
981
|
+
// the card's own colour, else the eye colour of the palette it tries on
|
|
982
|
+
const pal = PALETTES.find((p) => p.id === o.skin?.palette);
|
|
983
|
+
const tint = o.tint ?? (pal ? { light: pal.l[1], dark: pal.d[1] } : null);
|
|
984
|
+
c.type = 'button'; c.className = tint ? 'd-card tint' : 'd-card';
|
|
985
|
+
if (tint) { c.style.setProperty('--tint-l', tint.light); c.style.setProperty('--tint-d', tint.dark); }
|
|
986
|
+
c.style.animationDelay = (k * .07) + 's';
|
|
987
|
+
const image = typeof o.image === 'string' && o.image.startsWith('data:image/') ? `<img class="d-cardimg" alt="" src="${esc(o.image)}">` : '';
|
|
988
|
+
c.innerHTML = `${image || (o.icon && ICONS[o.icon] ? `<span class="d-cardic ic-${esc(o.icon)}">${ICONS[o.icon]}</span>` : '')}<span class="d-cardlbl">${esc(o.label)}</span>${o.note ? `<span class="d-cardnote">${esc(o.note)}</span>` : ''}${o.level ? `<b class="d-level">${esc(o.level)}</b>` : ''}`;
|
|
989
|
+
c.addEventListener('click', () => { sfx.tick(); onClick(); });
|
|
990
|
+
cards.appendChild(c);
|
|
991
|
+
setTimeout(() => sfx.blub(), k * 70);
|
|
992
|
+
return c;
|
|
993
|
+
};
|
|
994
|
+
const add = (from, to, k0) => { for (let i = from; i < to; i++) card(all[i], k0 + i - from, () => pick(i, true)).dataset.i = String(i); };
|
|
995
|
+
const start = typeof input.value === 'number' ? input.value : 0;
|
|
996
|
+
const folded = extra.length > 0 && start < input.options.length;
|
|
997
|
+
add(0, folded ? input.options.length : all.length, 0);
|
|
998
|
+
if (folded) {
|
|
999
|
+
const more = card(input.more, input.options.length, () => {
|
|
1000
|
+
// the "more" card gives its place to the first of the rest, and the cards grow to the new rows instead of jumping there
|
|
1001
|
+
const from = cards.offsetHeight;
|
|
1002
|
+
more.remove();
|
|
1003
|
+
add(input.options.length, all.length, 0);
|
|
1004
|
+
pick(input.options.length, false);
|
|
1005
|
+
const grow = growFrom(cards, { h: from }, { duration: 320, easing: 'cubic-bezier(.3,1.1,.5,1)', overshoots: true });
|
|
1006
|
+
if (grow) {
|
|
1007
|
+
cards.classList.add('unfolding');
|
|
1008
|
+
void grow.finished.finally(() => cards.classList.remove('unfolding'));
|
|
1009
|
+
}
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
body.appendChild(cards);
|
|
1013
|
+
const row = Object.assign(document.createElement('div'), { className: input.hint ? 'd-row d-foot-row' : 'd-row' });
|
|
1014
|
+
if (input.hint) {
|
|
1015
|
+
const h = input.hint, at = h.text.indexOf(h.mark);
|
|
1016
|
+
const mark = `<b>${ICONS[h.icon] ?? ''}${esc(h.mark)}</b>`;
|
|
1017
|
+
row.insertAdjacentHTML('beforeend', `<span class="d-hint">${at < 0 ? esc(h.text) : esc(h.text.slice(0, at)) + mark + esc(h.text.slice(at + h.mark.length))}</span>`);
|
|
1018
|
+
}
|
|
1019
|
+
row.appendChild(pill(input.confirm, true, () => settleDialog(it, { index: it.value ?? 0 })));
|
|
1020
|
+
body.appendChild(row);
|
|
1021
|
+
pick(start, false);
|
|
1022
|
+
} else if (input.kind === 'pick') {
|
|
1023
|
+
// any number of cards lit, from min to max; at max the cards not lit wait until one is put out
|
|
1024
|
+
const cards = Object.assign(document.createElement('div'), { className: 'd-cards pick' });
|
|
1025
|
+
const max = Math.max(1, Number(input.max) || 1), min = Math.max(0, Math.min(max, Number(input.min ?? 1)));
|
|
1026
|
+
const on = new Set((Array.isArray(input.value) ? input.value : []).filter((i) => Number.isInteger(i) && i >= 0 && i < input.options.length).slice(0, max));
|
|
1027
|
+
const row = Object.assign(document.createElement('div'), { className: 'd-row d-foot-row' });
|
|
1028
|
+
const count = Object.assign(document.createElement('span'), { className: 'd-hint' });
|
|
1029
|
+
const ok = pill(input.confirm, true, () => settleDialog(it, { picked: [...on].sort((a, b) => a - b) }));
|
|
1030
|
+
const paint = () => {
|
|
1031
|
+
cards.querySelectorAll('.d-card').forEach((c) => {
|
|
1032
|
+
const lit = on.has(Number(c.dataset.i));
|
|
1033
|
+
c.classList.toggle('on', lit);
|
|
1034
|
+
c.setAttribute('aria-pressed', String(lit));
|
|
1035
|
+
c.disabled = !lit && on.size >= max;
|
|
1036
|
+
});
|
|
1037
|
+
count.textContent = `${on.size}/${max}`;
|
|
1038
|
+
ok.disabled = on.size < min;
|
|
1039
|
+
ok.classList.toggle('need', on.size < min);
|
|
1040
|
+
};
|
|
1041
|
+
input.options.forEach((o, i) => {
|
|
1042
|
+
const c = document.createElement('button');
|
|
1043
|
+
c.type = 'button'; c.className = 'd-card'; c.dataset.i = String(i);
|
|
1044
|
+
c.style.animationDelay = (i * .05) + 's';
|
|
1045
|
+
c.innerHTML = `${o.icon && ICONS[o.icon] ? `<span class="d-cardic ic-${esc(o.icon)}">${ICONS[o.icon]}</span>` : ''}<span class="d-cardlbl">${esc(o.label)}</span>`;
|
|
1046
|
+
c.addEventListener('click', () => {
|
|
1047
|
+
sfx.tick();
|
|
1048
|
+
if (on.has(i)) on.delete(i); else if (on.size < max) on.add(i);
|
|
1049
|
+
paint();
|
|
1050
|
+
});
|
|
1051
|
+
cards.appendChild(c);
|
|
1052
|
+
setTimeout(() => sfx.blub(), i * 50);
|
|
1053
|
+
});
|
|
1054
|
+
body.appendChild(cards);
|
|
1055
|
+
row.append(count, ok);
|
|
1056
|
+
body.appendChild(row);
|
|
1057
|
+
paint();
|
|
1058
|
+
} else if (input.kind === 'text') {
|
|
1059
|
+
const form = Object.assign(document.createElement('form'), { className: 'd-field' });
|
|
1060
|
+
form.innerHTML = `<input type="${input.secret ? 'password' : 'text'}" autocomplete="off" spellcheck="false">${input.secret ? `<button class="d-peek" type="button" aria-label="${esc(t('bubble.peek'))}" title="${esc(t('bubble.peek'))}">${ICONS.eye}</button>` : ''}<span class="b-count" hidden></span><button class="d-send" type="submit"></button>`;
|
|
1061
|
+
const field = form.querySelector('input');
|
|
1062
|
+
field.placeholder = input.placeholder || '';
|
|
1063
|
+
field.value = input.value || '';
|
|
1064
|
+
const capped = capField(form, field, form.querySelector('.b-count'), Number(input.maxLength) || 200);
|
|
1065
|
+
if (Array.isArray(input.suggestions) && input.suggestions.length && !input.secret) {
|
|
1066
|
+
const list = document.createElement('datalist');
|
|
1067
|
+
list.id = `d-list-${it.id}`;
|
|
1068
|
+
for (const s of input.suggestions) list.appendChild(Object.assign(document.createElement('option'), { value: String(s) }));
|
|
1069
|
+
form.appendChild(list);
|
|
1070
|
+
field.setAttribute('list', list.id);
|
|
1071
|
+
}
|
|
1072
|
+
field.setAttribute('aria-label', it.text);
|
|
1073
|
+
form.querySelector('.d-send').textContent = input.submit;
|
|
1074
|
+
form.querySelector('.d-peek')?.addEventListener('click', (e) => {
|
|
1075
|
+
const show = field.type === 'password';
|
|
1076
|
+
field.type = show ? 'text' : 'password';
|
|
1077
|
+
e.currentTarget.innerHTML = show ? ICONS.eyeOff : ICONS.eye;
|
|
1078
|
+
field.focus();
|
|
1079
|
+
});
|
|
1080
|
+
form.addEventListener('submit', (e) => {
|
|
1081
|
+
e.preventDefault();
|
|
1082
|
+
const v = field.value.trim();
|
|
1083
|
+
if (!v || capped()) { shake(form); field.focus(); return; }
|
|
1084
|
+
settleDialog(it, { text: v });
|
|
1085
|
+
});
|
|
1086
|
+
body.appendChild(form);
|
|
1087
|
+
if (input.link || input.alt) {
|
|
1088
|
+
const row = Object.assign(document.createElement('div'), { className: 'd-links' });
|
|
1089
|
+
if (input.link) {
|
|
1090
|
+
const a = Object.assign(document.createElement('a'), { className: 'd-link', href: input.link.url, target: '_blank', rel: 'noopener' });
|
|
1091
|
+
a.innerHTML = `<span></span>${ICONS.external}`;
|
|
1092
|
+
a.querySelector('span').textContent = input.link.label;
|
|
1093
|
+
row.appendChild(a);
|
|
1094
|
+
}
|
|
1095
|
+
if (input.alt) {
|
|
1096
|
+
const b = Object.assign(document.createElement('button'), { type: 'button', className: 'd-alt', textContent: input.alt });
|
|
1097
|
+
b.addEventListener('click', () => settleDialog(it, { alt: true }));
|
|
1098
|
+
row.appendChild(b);
|
|
1099
|
+
}
|
|
1100
|
+
body.appendChild(row);
|
|
1101
|
+
}
|
|
1102
|
+
// the window takes the keyboard so the box can be typed in right away
|
|
1103
|
+
host?.focus?.();
|
|
1104
|
+
setTimeout(() => field.focus(), 30);
|
|
1105
|
+
} else if (input.kind === 'progress') {
|
|
1106
|
+
body.innerHTML = `<div class="d-bar${typeof it.progress === 'number' ? '' : ' wait'}"><i></i></div><div class="d-barlbl"><span></span><b></b></div>`;
|
|
1107
|
+
body.querySelector('.d-barlbl span').textContent = input.label || '';
|
|
1108
|
+
drawProgress(it);
|
|
1109
|
+
}
|
|
1110
|
+
body.hidden = false;
|
|
1111
|
+
body.querySelector('.d-send, .d-pill.primary')?.focus?.({ preventScroll: true });
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/** A button; with `hover`, that label replaces `label` while the button is pointed at or focused, and names it to screen readers. */
|
|
1115
|
+
function pill(label, primary, onClick, hover) {
|
|
1116
|
+
const b = Object.assign(document.createElement('button'), { type: 'button', className: `d-pill${primary ? ' primary' : ''}`, textContent: label });
|
|
1117
|
+
if (hover) {
|
|
1118
|
+
b.classList.add('swap');
|
|
1119
|
+
b.setAttribute('aria-label', hover);
|
|
1120
|
+
b.innerHTML = `<span class="d-pill-rest">${esc(label)}</span><span class="d-pill-hover">${esc(hover)}</span>`;
|
|
1121
|
+
}
|
|
1122
|
+
b.addEventListener('click', onClick);
|
|
1123
|
+
return b;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
function drawProgress(it) {
|
|
1127
|
+
const bar = bubble.querySelector('.d-bar');
|
|
1128
|
+
if (!bar) return;
|
|
1129
|
+
const p = it.progress;
|
|
1130
|
+
bar.classList.toggle('wait', typeof p !== 'number');
|
|
1131
|
+
bar.querySelector('i').style.width = typeof p === 'number' ? `${Math.round(clamp(p, 0, 1) * 100)}%` : '';
|
|
1132
|
+
bubble.querySelector('.d-barlbl b').textContent = typeof p === 'number' ? `${Math.floor(clamp(p, 0, 1) * 100)}%` : '';
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
function updateDialog(m) {
|
|
1136
|
+
const it = item?.kind === 'dialog' && item.id === m.id ? item : queue.find((q) => q.kind === 'dialog' && q.id === m.id);
|
|
1137
|
+
if (!it) return;
|
|
1138
|
+
if ('progress' in m) it.progress = m.progress;
|
|
1139
|
+
if (typeof m.text === 'string') {
|
|
1140
|
+
it.d = { ...it.d, text: m.text };
|
|
1141
|
+
if (it === item) { it.text = m.text; it.shown = 0; it.acc = 0; }
|
|
1142
|
+
}
|
|
1143
|
+
if (it === item) drawProgress(it);
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
function endDialog(id) {
|
|
1147
|
+
const i = queue.findIndex((q) => q.kind === 'dialog' && q.id === id);
|
|
1148
|
+
if (i >= 0) queue.splice(i, 1);
|
|
1149
|
+
if (item?.kind === 'dialog' && item.id === id) closeBubble();
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
function settleDialog(it, answer) {
|
|
1153
|
+
if (item !== it || it.answered) return;
|
|
1154
|
+
it.answered = true;
|
|
1155
|
+
send({ t: 'dialog', id: it.id, ...answer });
|
|
1156
|
+
takeOff('index' in answer);
|
|
1157
|
+
if (answer.done) { closeBubble(); return; }
|
|
1158
|
+
sfx.select();
|
|
1159
|
+
bubble.querySelectorAll('button, input').forEach((n) => { n.disabled = true; });
|
|
1160
|
+
if ('index' in answer) bubble.querySelectorAll('.d-pill')[answer.index]?.classList.add('chosen');
|
|
1161
|
+
// the chosen button shows a moment; the app's next step waits in the queue meanwhile
|
|
1162
|
+
setTimeout(() => { if (item === it) closeBubble(); }, 260);
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
/** Coo shows the picked card's motion near the pinned bubble: standing still, strolling, or running about. */
|
|
1166
|
+
function stepTalkMotion() {
|
|
1167
|
+
const it = item;
|
|
1168
|
+
if (it?.kind !== 'dialog') return;
|
|
1169
|
+
holdRoam(20);
|
|
1170
|
+
const l = at();
|
|
1171
|
+
if (!talk.motion || it.pinX === undefined || !l || l.busy || T < talk.next || l.mode !== 'idle') return;
|
|
1172
|
+
const home = it.pinX, R = Math.min(TALK_RANGE, innerWidth * .25);
|
|
1173
|
+
if (talk.motion === 'still') {
|
|
1174
|
+
if (Math.abs(l.x - home) > 30) body.walk(home, false, 0);
|
|
1175
|
+
talk.next = T + 1;
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
1178
|
+
const run = talk.motion === 'run';
|
|
1179
|
+
if (run && Math.random() < .3 && words.has('hop')) { body.do('hop'); talk.next = T + .5; return; }
|
|
1180
|
+
// to the other side of the bubble each time, so every move is plain to see
|
|
1181
|
+
const x = l.x < home ? home + R * (.4 + Math.random() * .6) : home - R * (.4 + Math.random() * .6);
|
|
1182
|
+
body.walk(clamp(x, 40, innerWidth - 40), run, 0);
|
|
1183
|
+
talk.next = T + (run ? .1 : 1.2 + Math.random() * 1.2);
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
/* ---------- typed input: the hover button, or double-click when switched on ---------- */
|
|
1187
|
+
/**
|
|
1188
|
+
* Pictures pasted into the box are fitted as the chat page fits them (console/base/ui/images.ts): only ever
|
|
1189
|
+
* shrunk, the long edge to IMAGE_EDGE; one still past IMAGE_BYTES is encoded again as JPEG. The box holds
|
|
1190
|
+
* BOX_IMAGES, one row of thumbnails; the chat page takes more.
|
|
1191
|
+
*/
|
|
1192
|
+
const IMAGE_MIMES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
|
|
1193
|
+
const IMAGE_EDGE = 2048, IMAGE_BYTES = 6 * 1024 * 1024, BOX_IMAGES = 4;
|
|
1194
|
+
|
|
1195
|
+
/** One pasted picture as `{ name, mime, base64, bytes, width, height }`; a picture that cannot be used rejects with the note to show. */
|
|
1196
|
+
async function fitImage(file) {
|
|
1197
|
+
let bitmap;
|
|
1198
|
+
try { bitmap = await createImageBitmap(file); } catch { throw new Error(t('bubble.imageUnreadable')); }
|
|
1199
|
+
try {
|
|
1200
|
+
const name = file.name || 'image';
|
|
1201
|
+
const scale = Math.min(1, IMAGE_EDGE / Math.max(bitmap.width, bitmap.height));
|
|
1202
|
+
const width = Math.max(1, Math.round(bitmap.width * scale)), height = Math.max(1, Math.round(bitmap.height * scale));
|
|
1203
|
+
if (scale === 1 && file.size <= IMAGE_BYTES) return { name, mime: file.type, base64: await base64Of(file), bytes: file.size, width, height };
|
|
1204
|
+
const canvas = document.createElement('canvas');
|
|
1205
|
+
canvas.width = width; canvas.height = height;
|
|
1206
|
+
canvas.getContext('2d').drawImage(bitmap, 0, 0, width, height);
|
|
1207
|
+
const encode = (mime, quality) => new Promise((resolve) => canvas.toBlob(resolve, mime, quality));
|
|
1208
|
+
// canvas has no GIF encoder
|
|
1209
|
+
let mime = file.type === 'image/gif' ? 'image/png' : file.type;
|
|
1210
|
+
let blob = await encode(mime);
|
|
1211
|
+
if (blob && blob.size > IMAGE_BYTES && mime !== 'image/jpeg') { mime = 'image/jpeg'; blob = await encode(mime, .85); }
|
|
1212
|
+
if (!blob) throw new Error(t('bubble.imageUnreadable'));
|
|
1213
|
+
if (blob.size > IMAGE_BYTES) throw new Error(t('bubble.imageTooLarge', { mb: IMAGE_BYTES / 1048576 }));
|
|
1214
|
+
return { name, mime, base64: await base64Of(blob), bytes: blob.size, width, height };
|
|
1215
|
+
} finally {
|
|
1216
|
+
bitmap.close();
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
function base64Of(blob) {
|
|
1220
|
+
return new Promise((resolve, reject) => {
|
|
1221
|
+
const reader = new FileReader();
|
|
1222
|
+
reader.onerror = () => reject(new Error(t('bubble.imageUnreadable')));
|
|
1223
|
+
reader.onload = () => { const url = String(reader.result); resolve(url.slice(url.indexOf(',') + 1)); };
|
|
1224
|
+
reader.readAsDataURL(blob);
|
|
1225
|
+
});
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
function openInput() {
|
|
1229
|
+
closeMenu();
|
|
1230
|
+
if (item && item.kind === 'ask' && !item.answered) return;
|
|
1231
|
+
if (item) closeBubble();
|
|
1232
|
+
const it = item = { kind: 'input', images: [], pending: 0, pasted: 0 };
|
|
1233
|
+
const expand = prefs.bot?.buttons?.chat
|
|
1234
|
+
? `<button class="b-expand" type="button" aria-label="${esc(t('bubble.expand'))}" title="${esc(t('bubble.expand'))}">${ICONS.expand}</button>`
|
|
1235
|
+
: '';
|
|
1236
|
+
openBubble('ask', `${sideColumn(t('bubble.close'), false, true)}<div class="b-imgs" hidden></div><form class="b-own"><textarea rows="1" autocomplete="off" placeholder="${esc(t('bubble.typePlaceholder'))}" aria-label="${esc(t('bubble.typeLabel'))}"></textarea><span class="b-count" hidden></span>${expand}<button type="submit">${esc(t('bubble.send'))}</button></form><span class="b-hint b-limit" role="status" hidden></span><span class="b-hint b-note" hidden></span>`);
|
|
1237
|
+
const form = bubble.querySelector('form'), input = form.querySelector('textarea');
|
|
1238
|
+
const tray = bubble.querySelector('.b-imgs'), note = bubble.querySelector('.b-note');
|
|
1239
|
+
// the scrollbar outside the box (pet.css .b-track): its track runs from under the close button to the text's bottom
|
|
1240
|
+
const track = bubble.querySelector('.b-track'), thumb = track.querySelector('.b-thumb');
|
|
1241
|
+
const drawBar = () => {
|
|
1242
|
+
const over = input.scrollHeight - input.clientHeight;
|
|
1243
|
+
track.hidden = over <= 1;
|
|
1244
|
+
// text cut off at an edge fades out there (pet.css `.b-own textarea.scrolls`)
|
|
1245
|
+
input.classList.toggle('scrolls', !track.hidden);
|
|
1246
|
+
input.classList.toggle('more-above', !track.hidden && input.scrollTop > 1);
|
|
1247
|
+
input.classList.toggle('more-below', !track.hidden && input.scrollTop < over - 1);
|
|
1248
|
+
if (track.hidden) return;
|
|
1249
|
+
// the rects are scaled while the bubble pops in (pet.css bubble-in): the gap between them is turned back into pixels
|
|
1250
|
+
const scale = bubble.getBoundingClientRect().width / bubble.offsetWidth || 1;
|
|
1251
|
+
const h = Math.max(24, (input.getBoundingClientRect().bottom - track.getBoundingClientRect().top) / scale);
|
|
1252
|
+
const th = Math.max(16, h * input.clientHeight / input.scrollHeight);
|
|
1253
|
+
track.style.height = `${h}px`;
|
|
1254
|
+
thumb.style.height = `${th}px`;
|
|
1255
|
+
thumb.style.top = `${(h - th) * input.scrollTop / over}px`;
|
|
1256
|
+
};
|
|
1257
|
+
input.addEventListener('scroll', drawBar);
|
|
1258
|
+
bubble.addEventListener('animationend', drawBar, { once: true });
|
|
1259
|
+
// the wheel over the scrollbar scrolls the text, as over the system's own
|
|
1260
|
+
track.addEventListener('wheel', (e) => { e.preventDefault(); input.scrollTop += e.deltaY; }, { passive: false });
|
|
1261
|
+
// dragged, the thumb moves the text with it; a press on the track pages toward it. The window keeps the mouse
|
|
1262
|
+
// while the thumb is held (barHeld), though the pointer leaves the bubble.
|
|
1263
|
+
track.addEventListener('pointerdown', (e) => {
|
|
1264
|
+
if (e.button !== 0) return;
|
|
1265
|
+
e.preventDefault();
|
|
1266
|
+
if (e.target !== thumb) {
|
|
1267
|
+
const r = thumb.getBoundingClientRect();
|
|
1268
|
+
input.scrollTop += (e.clientY < r.top ? -1 : 1) * input.clientHeight * .9;
|
|
1269
|
+
return;
|
|
1270
|
+
}
|
|
1271
|
+
const y0 = e.clientY, top0 = input.scrollTop;
|
|
1272
|
+
const h = track.clientHeight - thumb.offsetHeight, over = input.scrollHeight - input.clientHeight;
|
|
1273
|
+
barHeld = true; track.classList.add('held');
|
|
1274
|
+
track.setPointerCapture(e.pointerId);
|
|
1275
|
+
const move = (m) => { input.scrollTop = top0 + (m.clientY - y0) * (h > 0 ? over / h : 0); };
|
|
1276
|
+
// let go, or the capture lost (the bubble closed under the pointer: closeBubble lets the mouse go as well)
|
|
1277
|
+
const end = () => {
|
|
1278
|
+
barHeld = false; track.classList.remove('held');
|
|
1279
|
+
track.removeEventListener('pointermove', move);
|
|
1280
|
+
track.removeEventListener('lostpointercapture', end);
|
|
1281
|
+
};
|
|
1282
|
+
track.addEventListener('pointermove', move);
|
|
1283
|
+
track.addEventListener('lostpointercapture', end);
|
|
1284
|
+
});
|
|
1285
|
+
// the hint keeps to one row in every language, so the box does not shrink by a row at the first key: the field is
|
|
1286
|
+
// as wide as the hint, and the bubble goes past its usual widest when the hint needs it (sizes that change while
|
|
1287
|
+
// the box is open fit it again, applyPrefs)
|
|
1288
|
+
it.fitHint = () => {
|
|
1289
|
+
// measured on one row, as the empty box shows it: past it the row wraps and has no overflow to read
|
|
1290
|
+
const tall = form.classList.contains('tall');
|
|
1291
|
+
form.classList.remove('tall');
|
|
1292
|
+
const probe = document.createElement('span');
|
|
1293
|
+
probe.style.cssText = `position:absolute; visibility:hidden; white-space:pre; font:${getComputedStyle(input).font}`;
|
|
1294
|
+
probe.textContent = input.placeholder;
|
|
1295
|
+
document.body.append(probe);
|
|
1296
|
+
input.style.minWidth = `${Math.ceil(probe.getBoundingClientRect().width) + 1}px`;
|
|
1297
|
+
probe.remove();
|
|
1298
|
+
bubble.style.removeProperty('max-width');
|
|
1299
|
+
// the row's own overflow: what sticks out of it into the bubble's padding does not widen the bubble's scroll width
|
|
1300
|
+
const over = form.scrollWidth - form.clientWidth;
|
|
1301
|
+
if (over > 0) bubble.style.maxWidth = `min(${bubble.offsetWidth + over}px, calc(100vw - 20px - ${sideRoom(bubble)}px))`;
|
|
1302
|
+
form.classList.toggle('tall', tall);
|
|
1303
|
+
drawBar();
|
|
1304
|
+
};
|
|
1305
|
+
it.fitHint();
|
|
1306
|
+
// past the box's cap the text stays and is not sent; the chat page takes up to its own, longer cap
|
|
1307
|
+
const boxMax = prefs.bot?.textMax?.box ?? 500, chatMax = prefs.bot?.textMax?.chat ?? 4000;
|
|
1308
|
+
const limit = bubble.querySelector('.b-limit'), expandButton = bubble.querySelector('.b-expand');
|
|
1309
|
+
const capped = capField(form, input, form.querySelector('.b-count'), boxMax, (over, n) => {
|
|
1310
|
+
const movable = !!expandButton && n <= chatMax;
|
|
1311
|
+
limit.hidden = !over;
|
|
1312
|
+
limit.textContent = !over ? '' : t(movable ? 'bubble.tooLongForBox' : 'bubble.tooLong', { over });
|
|
1313
|
+
expandButton?.classList.toggle('nudge', over > 0 && movable);
|
|
1314
|
+
if (expandButton) expandButton.disabled = n > chatMax;
|
|
1315
|
+
});
|
|
1316
|
+
const say = (text) => { note.textContent = text || ''; note.hidden = !text; };
|
|
1317
|
+
const draw = () => {
|
|
1318
|
+
tray.hidden = !it.images.length;
|
|
1319
|
+
tray.replaceChildren(...it.images.map((img) => {
|
|
1320
|
+
const cell = document.createElement('span');
|
|
1321
|
+
cell.className = 'b-img';
|
|
1322
|
+
cell.innerHTML = `<img alt="" src="data:${esc(img.mime)};base64,${img.base64}"><button type="button" aria-label="${esc(t('bubble.removeImage'))}" title="${esc(t('bubble.removeImage'))}">×</button>`;
|
|
1323
|
+
cell.querySelector('button').addEventListener('click', () => { it.images.splice(it.images.indexOf(img), 1); say(''); draw(); input.focus(); });
|
|
1324
|
+
return cell;
|
|
1325
|
+
}));
|
|
1326
|
+
drawBar();
|
|
1327
|
+
};
|
|
1328
|
+
// text past one row takes the field's whole width (pet.css `.b-own.tall`), until it is cleared: going back to one row
|
|
1329
|
+
// as soon as it fits beside the buttons would swing the layout to and fro at the edge
|
|
1330
|
+
input.addEventListener('input', () => {
|
|
1331
|
+
if (!input.value) form.classList.remove('tall');
|
|
1332
|
+
// more than a row and a half, with the textarea's 4px padding above and below: a second row has begun
|
|
1333
|
+
else if (input.scrollHeight > parseFloat(getComputedStyle(input).lineHeight) * 1.5 + 8) form.classList.add('tall');
|
|
1334
|
+
drawBar();
|
|
1335
|
+
});
|
|
1336
|
+
// Enter sends, Shift+Enter starts a new line; Enter that confirms an input method's text does neither
|
|
1337
|
+
input.addEventListener('keydown', (e) => {
|
|
1338
|
+
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); form.requestSubmit(); }
|
|
1339
|
+
});
|
|
1340
|
+
// a paste that carries pictures adds them and leaves the text as it was, as the chat page does
|
|
1341
|
+
input.addEventListener('paste', (e) => {
|
|
1342
|
+
const files = [...(e.clipboardData?.files ?? [])].filter((f) => IMAGE_MIMES.includes(f.type));
|
|
1343
|
+
if (!files.length) return;
|
|
1344
|
+
e.preventDefault();
|
|
1345
|
+
if (it.images.length + it.pending + files.length > BOX_IMAGES) { say(t('bubble.tooManyImages', { max: BOX_IMAGES })); return; }
|
|
1346
|
+
say(prefs.bot?.imagesSeen === false ? t('bubble.imagesUnseen', { bot: prefs.bot.name || 'Coo' }) : '');
|
|
1347
|
+
for (const file of files) {
|
|
1348
|
+
// the order is the paste's, though a big picture takes longer to fit
|
|
1349
|
+
const order = ++it.pasted;
|
|
1350
|
+
it.pending++;
|
|
1351
|
+
fitImage(file).then((img) => {
|
|
1352
|
+
if (item !== it) return;
|
|
1353
|
+
it.images.push({ ...img, order });
|
|
1354
|
+
it.images.sort((a, b) => a.order - b.order);
|
|
1355
|
+
draw();
|
|
1356
|
+
}, (err) => {
|
|
1357
|
+
if (item === it) say(err.message);
|
|
1358
|
+
}).finally(() => { it.pending--; });
|
|
1359
|
+
}
|
|
1360
|
+
});
|
|
1361
|
+
bubble.querySelector('.b-close').addEventListener('click', () => closeBubble());
|
|
1362
|
+
// the chat page takes longer text and more images; the draft goes with it
|
|
1363
|
+
bubble.querySelector('.b-expand')?.addEventListener('click', () => {
|
|
1364
|
+
send({ t: 'expand', text: input.value, images: it.images });
|
|
1365
|
+
closeBubble();
|
|
1366
|
+
});
|
|
1367
|
+
form.addEventListener('submit', (e) => {
|
|
1368
|
+
e.preventDefault();
|
|
1369
|
+
const v = input.value.trim();
|
|
1370
|
+
if (it.pending || (!v && !it.images.length)) return;
|
|
1371
|
+
if (capped()) { shake(form); return; }
|
|
1372
|
+
send({ t: 'text', text: v, ...(it.images.length ? { images: it.images.map(({ mime, base64, name }) => ({ mime, base64, name })) } : {}) });
|
|
1373
|
+
sfx.select(); body?.cue('cheer');
|
|
1374
|
+
closeBubble();
|
|
1375
|
+
if (prefs.saidBubbles) addLine('type', v, false, { images: it.images.length });
|
|
1376
|
+
});
|
|
1377
|
+
host?.focus?.();
|
|
1378
|
+
setTimeout(() => input.focus(), 30);
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
/* ---------- listening ---------- */
|
|
1382
|
+
/** `line` is the episode's bubble in the stack (see below) while it is heard; `text` is settled, `interim` still being heard. */
|
|
1383
|
+
const listen = { phase: null, line: null, text: '', interim: '' };
|
|
1384
|
+
function onListen(m) {
|
|
1385
|
+
// the quick tap before a talk key is held: Coo perks up, and the hold that follows starts listening
|
|
1386
|
+
if (m.phase === 'ready') {
|
|
1387
|
+
if (listen.phase) return;
|
|
1388
|
+
sfx.tick();
|
|
1389
|
+
body?.cue('perk');
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
if (m.phase === 'start') {
|
|
1393
|
+
if (!listen.phase) sfx.listenStart();
|
|
1394
|
+
listen.phase = 'hearing';
|
|
1395
|
+
setBody({ listening: true });
|
|
1396
|
+
showHeard();
|
|
1397
|
+
} else if (m.phase === 'transcribing') {
|
|
1398
|
+
listen.phase = listen.phase || 'hearing';
|
|
1399
|
+
showHeard();
|
|
1400
|
+
} else if (m.phase === 'partial') {
|
|
1401
|
+
listen.text = m.text || '';
|
|
1402
|
+
listen.interim = m.interim || '';
|
|
1403
|
+
showHeard();
|
|
1404
|
+
} else if (m.phase === 'recording-text') {
|
|
1405
|
+
// An optional transcript belongs to a recording already delivered. Never reopen a
|
|
1406
|
+
// dismissed bubble, touch the current listening episode, or replay its completion.
|
|
1407
|
+
if (typeof m.recordingId !== 'string') return;
|
|
1408
|
+
const line = lines.find((l) => l.recordingId === m.recordingId && !l.live && l.fadeAt === null);
|
|
1409
|
+
if (line && typeof m.text === 'string' && m.text) {
|
|
1410
|
+
line.text = m.text;
|
|
1411
|
+
drawLine(line);
|
|
1412
|
+
}
|
|
1413
|
+
} else if (m.phase === 'heard') {
|
|
1414
|
+
const line = listen.line ?? addLine('voice', '', true);
|
|
1415
|
+
if (typeof m.recordingId === 'string') line.recordingId = m.recordingId;
|
|
1416
|
+
endListen();
|
|
1417
|
+
settleLine(line, m.text || '');
|
|
1418
|
+
if (!prefs.saidBubbles) fadeLine(line);
|
|
1419
|
+
sfx.listenEnd();
|
|
1420
|
+
body?.cue('heard');
|
|
1421
|
+
} else if (m.phase === 'none') {
|
|
1422
|
+
if (listen.line) dropLine(listen.line);
|
|
1423
|
+
endListen();
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
function endListen() {
|
|
1427
|
+
listen.phase = null; listen.line = null; listen.text = ''; listen.interim = '';
|
|
1428
|
+
setBody({ listening: false });
|
|
1429
|
+
}
|
|
1430
|
+
/**
|
|
1431
|
+
* Draws what is being heard into the episode's bubble, the newest of the stack. `interim`, greyed, may still change.
|
|
1432
|
+
* The bubble is built once and then only updated, so a click on its cancel button is not lost to a redraw.
|
|
1433
|
+
*/
|
|
1434
|
+
function showHeard() {
|
|
1435
|
+
listen.line ??= addLine('voice', '', true);
|
|
1436
|
+
const el = listen.line.el, { text, interim } = listen;
|
|
1437
|
+
// the World drops what this bubble shows and closes it; with the talk key off (always) there is no capture to cancel
|
|
1438
|
+
el.querySelector('.b-cancel').hidden = prefs.voice.mode === 'always';
|
|
1439
|
+
el.querySelector('.fin').textContent = text;
|
|
1440
|
+
// a space only before Latin text that follows Latin text or ASCII punctuation; Chinese sentences run on
|
|
1441
|
+
el.querySelector('.interim').textContent = text && interim && /[A-Za-z0-9.,!?;:]$/.test(text) && /^[A-Za-z0-9]/.test(interim) ? ' ' + interim : interim;
|
|
1442
|
+
el.querySelector('.b-hint').textContent = t(text || interim ? 'heard.more' : 'heard.listening');
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
/*
|
|
1446
|
+
* ---------- what the person said: typed in the box, heard, or sent from the chat page ----------
|
|
1447
|
+
* Each line stays above Coo as a bubble of the heard kind (grey, no tail), the newest at the bottom. A line is
|
|
1448
|
+
* answered by the first speech or question Coo starts after it settled; until that reply's last line is written out
|
|
1449
|
+
* (and, for a line not answered yet, while Coo works or has speech queued) the line and those before it stay, and
|
|
1450
|
+
* they fade REPLIED_FADE seconds after that, before the reply's bubble closes, or after it closes if that comes first.
|
|
1451
|
+
* A line Coo does not answer fades UNANSWERED_FADE seconds after it was said.
|
|
1452
|
+
* With a fixed saidBubbleHoldSec a line fades that many seconds after it settled instead, whatever Coo does.
|
|
1453
|
+
* The stack holds at most MAX_LINES bubbles and MAX_ROWS rows of text: past either the oldest fades, answered
|
|
1454
|
+
* or not, and the newest always stays. A click fades a settled line at once; one still being heard has its cancel button.
|
|
1455
|
+
*/
|
|
1456
|
+
const REPLIED_FADE = .5, UNANSWERED_FADE = 8;
|
|
1457
|
+
const MAX_LINES = 3, MAX_ROWS = 6;
|
|
1458
|
+
/** Seconds a line takes to fade out (pet.css `.bubble.said`). */
|
|
1459
|
+
const LINE_FADE = .4;
|
|
1460
|
+
/** A settled line's mark, the icon of the way it came: the voice button's microphone, the chat page's arrows; typed in the box, none. */
|
|
1461
|
+
const MARKS = { voice: ICONS.mic, chat: ICONS.expand };
|
|
1462
|
+
/**
|
|
1463
|
+
* `src`: 'type' | 'voice' | 'chat'; `live` while being heard; `settledAt` on the page clock; `reply`, the item that
|
|
1464
|
+
* answers it; `fadeAt` once it fades; `ox`, `oy`, its eased offset from Coo's head; `images` and `cursor`, a chat line's.
|
|
1465
|
+
*/
|
|
1466
|
+
const lines = [];
|
|
1467
|
+
|
|
1468
|
+
function addLine(src, text, live = false, extra = {}) {
|
|
1469
|
+
const el = document.createElement('div');
|
|
1470
|
+
el.className = 'bubble heard said pop';
|
|
1471
|
+
el.setAttribute('role', 'status');
|
|
1472
|
+
document.body.append(el);
|
|
1473
|
+
const line = { el, src, text, live, settledAt: live ? null : T, reply: null, fadeAt: null, ox: null, oy: null, images: 0, cursor: null, ...extra };
|
|
1474
|
+
el.addEventListener('click', () => { if (!line.live && line.fadeAt === null) { sfx.tick(); fadeLine(line); } });
|
|
1475
|
+
if (live) {
|
|
1476
|
+
el.innerHTML = '<p class="b-text"><span class="fin"></span><span class="interim"></span><span class="caret" aria-hidden="true"></span></p><div class="b-foot"><span class="b-hint"></span><button class="b-cancel" type="button"></button></div>';
|
|
1477
|
+
el.querySelector('.b-cancel').textContent = t('heard.cancel');
|
|
1478
|
+
el.querySelector('.b-cancel').addEventListener('click', () => { sfx.tick(); send({ t: 'cancel' }); });
|
|
1479
|
+
} else drawLine(line);
|
|
1480
|
+
lines.push(line);
|
|
1481
|
+
return line;
|
|
1482
|
+
}
|
|
1483
|
+
function drawLine(line) {
|
|
1484
|
+
const mark = MARKS[line.src] ? `<span class="said-mark" aria-hidden="true">${MARKS[line.src]}</span>` : '';
|
|
1485
|
+
const images = line.images ? `<span class="b-hint">${line.text ? '' : mark}${esc(t('said.images', { count: line.images }))}</span>` : '';
|
|
1486
|
+
line.el.innerHTML = (line.text || !line.images ? `<p class="b-text">${mark}${esc(line.text)}</p>` : '') + images;
|
|
1487
|
+
fitSaid(line.el);
|
|
1488
|
+
line.el.title = t('bubble.close');
|
|
1489
|
+
}
|
|
1490
|
+
/** A settled line's bubble, as narrow as its text allows (ui.js balancedWidth), measured before `settled` clamps it to six rows. */
|
|
1491
|
+
function fitSaid(el) {
|
|
1492
|
+
el.classList.remove('settled');
|
|
1493
|
+
el.style.maxWidth = balancedWidth(el) + 'px';
|
|
1494
|
+
el.classList.add('settled');
|
|
1495
|
+
}
|
|
1496
|
+
/**
|
|
1497
|
+
* The bubbles up fitted again to the sizes and the window they are drawn at now: their widths were measured at the
|
|
1498
|
+
* sizes they opened at, and kept, a line would wrap into one more row (or stay wider than it needs) once they change.
|
|
1499
|
+
*/
|
|
1500
|
+
function refitBubbles() {
|
|
1501
|
+
for (const line of lines) if (!line.live) fitSaid(line.el);
|
|
1502
|
+
const b = item?.kind === 'say' ? item.beats[item.i] : null;
|
|
1503
|
+
if (b?.text && !bubble.hidden && bubble.classList.contains('say')) {
|
|
1504
|
+
const p = bubble.querySelector('.b-text'), typed = [...p.childNodes];
|
|
1505
|
+
fitLine(b.text);
|
|
1506
|
+
p.replaceChildren(...typed);
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
function settleLine(line, text) {
|
|
1510
|
+
line.live = false; line.text = text; line.settledAt = T;
|
|
1511
|
+
drawLine(line);
|
|
1512
|
+
}
|
|
1513
|
+
function fadeLine(line) {
|
|
1514
|
+
if (line.fadeAt !== null) return;
|
|
1515
|
+
line.fadeAt = T;
|
|
1516
|
+
line.el.classList.add('fading');
|
|
1517
|
+
}
|
|
1518
|
+
function dropLine(line) {
|
|
1519
|
+
line.el.remove();
|
|
1520
|
+
lines.splice(lines.indexOf(line), 1);
|
|
1521
|
+
}
|
|
1522
|
+
/** A chat-page message the person took back before delivery: its line goes. */
|
|
1523
|
+
function withdrawLine(cursor) {
|
|
1524
|
+
const line = lines.find((l) => l.cursor === cursor);
|
|
1525
|
+
if (line) fadeLine(line);
|
|
1526
|
+
}
|
|
1527
|
+
/** Coo starts speaking or asking (`it`): the settled lines not answered yet are answered by it. */
|
|
1528
|
+
function answerLines(it) {
|
|
1529
|
+
for (const line of lines) if (!line.live && !line.reply) line.reply = it;
|
|
1530
|
+
}
|
|
1531
|
+
/** Rows of text a line shows: its text (pet.css clamps it at MAX_ROWS), plus the image line. */
|
|
1532
|
+
function rowsOf(line) {
|
|
1533
|
+
const p = line.el.querySelector('.b-text');
|
|
1534
|
+
const hint = line.images ? 1 : 0;
|
|
1535
|
+
if (!p) return Math.max(1, hint);
|
|
1536
|
+
const lh = parseFloat(getComputedStyle(p).lineHeight) || 20;
|
|
1537
|
+
return Math.max(1, Math.round(p.getBoundingClientRect().height / lh)) + hint;
|
|
1538
|
+
}
|
|
1539
|
+
function stepLines() {
|
|
1540
|
+
// Coo is still on it: working, or with speech queued
|
|
1541
|
+
const busy = !!status.wanted || queue.some((q) => q.kind === 'say' || q.kind === 'ask');
|
|
1542
|
+
let held = -1, answered = -1;
|
|
1543
|
+
lines.forEach((line, i) => {
|
|
1544
|
+
if (line.live) return;
|
|
1545
|
+
const r = line.reply;
|
|
1546
|
+
const done = r && Math.min(r.writtenAt ?? Infinity, r.endedAt ?? Infinity);
|
|
1547
|
+
if (r ? done === Infinity : busy) held = i;
|
|
1548
|
+
else if (r && T >= done + REPLIED_FADE) answered = i;
|
|
1549
|
+
});
|
|
1550
|
+
const hold = prefs.saidBubbleHoldSec;
|
|
1551
|
+
lines.forEach((line, i) => {
|
|
1552
|
+
if (line.fadeAt !== null || line.live) return;
|
|
1553
|
+
if (hold) { if (T >= line.settledAt + hold) fadeLine(line); }
|
|
1554
|
+
else if (i > held && (i <= answered || (!line.reply && T >= line.settledAt + UNANSWERED_FADE))) fadeLine(line);
|
|
1555
|
+
});
|
|
1556
|
+
const up = lines.filter((l) => l.fadeAt === null);
|
|
1557
|
+
let rows = up.reduce((n, l) => n + rowsOf(l), 0);
|
|
1558
|
+
while (up.length > 1 && (up.length > MAX_LINES || rows > MAX_ROWS)) {
|
|
1559
|
+
const line = up.shift();
|
|
1560
|
+
rows -= rowsOf(line);
|
|
1561
|
+
fadeLine(line);
|
|
1562
|
+
}
|
|
1563
|
+
for (const line of [...lines]) if (line.fadeAt !== null && T - line.fadeAt >= LINE_FADE) dropLine(line);
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
/* ---------- activity: the same bubble, with conversation always taking priority ---------- */
|
|
1567
|
+
const status = { wanted: null, since: 0, shown: null, shownAt: 0, fadeAt: null };
|
|
1568
|
+
function setStatus(next) {
|
|
1569
|
+
setBody({ thinking: next?.kind === 'think', status: next?.kind ?? null });
|
|
1570
|
+
const prev = status.wanted;
|
|
1571
|
+
if (prev?.kind === next?.kind && prev?.text === next?.text && prev?.detail === next?.detail && prev?.count === next?.count && prev?.endsAt === next?.endsAt) return;
|
|
1572
|
+
if (prev?.kind !== next?.kind) status.since = T;
|
|
1573
|
+
status.wanted = next;
|
|
1574
|
+
}
|
|
1575
|
+
function drawStatus(next, pop) {
|
|
1576
|
+
const icon = next.kind;
|
|
1577
|
+
if (!bubble.classList.contains('status') || bubble.dataset.icon !== icon) {
|
|
1578
|
+
bubble.className = 'bubble status';
|
|
1579
|
+
bubble.style.maxWidth = '';
|
|
1580
|
+
bubble.dataset.icon = icon;
|
|
1581
|
+
bubble.innerHTML = `<span class="status-icon">${ICONS[`status_${icon}`] || ICONS.status_work}</span><span class="status-text"></span>`;
|
|
1582
|
+
}
|
|
1583
|
+
bubble.dataset.kind = next.kind;
|
|
1584
|
+
const { head, left, tail } = statusParts(next);
|
|
1585
|
+
// the seconds left change every second; hidden from screen readers, the status is read once
|
|
1586
|
+
const seconds = document.createElement('span');
|
|
1587
|
+
seconds.setAttribute('aria-hidden', 'true');
|
|
1588
|
+
seconds.textContent = left;
|
|
1589
|
+
bubble.querySelector('.status-text').replaceChildren(head, seconds, tail);
|
|
1590
|
+
bubble.setAttribute('aria-label', next.kind === 'think' ? t('status.thinking') : head + tail);
|
|
1591
|
+
bubble.classList.remove('fading');
|
|
1592
|
+
bubble.hidden = false;
|
|
1593
|
+
if (pop) { bubble.classList.remove('pop'); void bubble.offsetWidth; bubble.classList.add('pop'); }
|
|
1594
|
+
}
|
|
1595
|
+
/** The status's words around the seconds left: a countdown shows the whole seconds left to `endsAt`, and nothing once they run out. */
|
|
1596
|
+
function statusParts(s) {
|
|
1597
|
+
const seconds = s.endsAt === undefined ? 0 : Math.ceil((s.endsAt - Date.now()) / 1000);
|
|
1598
|
+
return {
|
|
1599
|
+
head: s.text + (s.endsAt === undefined && s.detail ? ` · ${s.detail}` : ''),
|
|
1600
|
+
left: seconds > 0 ? ` · ${t('status.seconds', { seconds })}` : '',
|
|
1601
|
+
tail: s.count > 1 ? t('status.more', { others: s.count - 1 }) : '',
|
|
1602
|
+
};
|
|
1603
|
+
}
|
|
1604
|
+
const statusLabel = (s) => Object.values(statusParts(s)).join('');
|
|
1605
|
+
function stepStatus() {
|
|
1606
|
+
// Never replace dialogue with activity, including while a queued line waits for the body or for the place over the head.
|
|
1607
|
+
if (!prefs.statusBubble || listen.phase || item || queue.length || headShown()) {
|
|
1608
|
+
if (bubble.classList.contains('status')) bubble.hidden = true;
|
|
1609
|
+
status.shown = null; status.fadeAt = null;
|
|
1610
|
+
return;
|
|
1611
|
+
}
|
|
1612
|
+
if (status.fadeAt !== null && T - status.fadeAt >= .2) {
|
|
1613
|
+
bubble.hidden = true;
|
|
1614
|
+
status.shown = null; status.fadeAt = null;
|
|
1615
|
+
}
|
|
1616
|
+
const next = status.wanted, shown = status.shown;
|
|
1617
|
+
if (next?.kind === 'think' && T - status.since < .6) return;
|
|
1618
|
+
if (shown && next && shown.kind === next.kind && shown.text === next.text) {
|
|
1619
|
+
if (shown !== next || status.fadeAt !== null || (next.endsAt !== undefined && bubble.querySelector('.status-text')?.textContent !== statusLabel(next))) drawStatus(next, false);
|
|
1620
|
+
status.shown = next; status.fadeAt = null;
|
|
1621
|
+
} else if (!shown || T - status.shownAt >= 1.2) {
|
|
1622
|
+
if (next) {
|
|
1623
|
+
drawStatus(next, shown?.kind !== next.kind);
|
|
1624
|
+
status.shown = next; status.shownAt = T; status.fadeAt = null;
|
|
1625
|
+
} else if (shown && status.fadeAt === null) {
|
|
1626
|
+
status.fadeAt = T;
|
|
1627
|
+
bubble.classList.add('fading');
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
|
|
1632
|
+
/* ---------- microphone: open while `prefs.mic`, which the World turns on and off with a held talk key in hold mode ---------- */
|
|
1633
|
+
const { start: startMic, stop: stopMic } = createMic({ prefs, send, sendAudio: (data) => { if (ws && ws.readyState === 1) ws.send(data); } });
|
|
1634
|
+
|
|
1635
|
+
/* ---------- actions: the menu's lower zone and the hover buttons draw from one list ---------- */
|
|
1636
|
+
const ROAM_ORDER = ['off', 'calm', 'free'];
|
|
1637
|
+
const roamName = (id) => (ROAM_ORDER.includes(id) ? t(`roam.${id}`) : '');
|
|
1638
|
+
/** The voice button's badge: `auto` when listening all the time, else the talk key (`Alt×2`). */
|
|
1639
|
+
const micBadge = () => (prefs.voice.mode === 'always' ? 'auto' : prefs.voice.key || 'key');
|
|
1640
|
+
/** Most hover buttons shown beside the pet. */
|
|
1641
|
+
const MAX_HOVER = 6;
|
|
1642
|
+
|
|
1643
|
+
/**
|
|
1644
|
+
* Every button the menu and the hover buttons can show, in the menu's order. `icon`, `state` and
|
|
1645
|
+
* `on` read the current prefs: `state` is the line that says what the button does and where it
|
|
1646
|
+
* stands, `on` lights a switch that is on (undefined for plain actions). `keep` leaves the menu
|
|
1647
|
+
* open after a click, so a switch shows its new state there.
|
|
1648
|
+
*/
|
|
1649
|
+
const ACTIONS = {
|
|
1650
|
+
chat: {
|
|
1651
|
+
icon: () => ICONS.chat,
|
|
1652
|
+
state: () => t(prefs.doubleClickChat ? 'action.chatDoubleClick' : 'action.chat'),
|
|
1653
|
+
run: () => openInput(),
|
|
1654
|
+
},
|
|
1655
|
+
voice: {
|
|
1656
|
+
keep: true,
|
|
1657
|
+
icon: () => (prefs.voice.enabled ? ICONS.mic : ICONS.micOff),
|
|
1658
|
+
badge: () => (prefs.voice.enabled ? micBadge() : ''),
|
|
1659
|
+
on: () => prefs.voice.enabled,
|
|
1660
|
+
// on, but the recognizer is not ready yet
|
|
1661
|
+
waiting: () => prefs.voice.enabled && !prefs.voice.ready,
|
|
1662
|
+
state: () => (!prefs.voice.enabled ? t('action.voiceOff')
|
|
1663
|
+
: !prefs.voice.ready ? t('action.voiceNotReady', { detail: prefs.voice.detail || t('action.voiceNoService') })
|
|
1664
|
+
: t('action.voiceOn', { mode: t(prefs.voice.mode === 'always' ? 'action.voiceAlways' : 'action.voiceKey'), hint: prefs.voice.hint || '' })),
|
|
1665
|
+
run: () => toggleVoice(),
|
|
1666
|
+
},
|
|
1667
|
+
roam: {
|
|
1668
|
+
keep: true,
|
|
1669
|
+
icon: () => ICONS[`roam_${prefs.roam}`] ?? ICONS.roam_calm,
|
|
1670
|
+
state: () => {
|
|
1671
|
+
const next = ROAM_ORDER[(ROAM_ORDER.indexOf(prefs.roam) + 1) % ROAM_ORDER.length];
|
|
1672
|
+
return t('action.roam', { name: roamName(prefs.roam), next: roamName(next) });
|
|
1673
|
+
},
|
|
1674
|
+
run: () => cycleRoam(),
|
|
1675
|
+
},
|
|
1676
|
+
// no `on`: both night and day draw a solid ring
|
|
1677
|
+
theme: {
|
|
1678
|
+
keep: true,
|
|
1679
|
+
icon: () => (prefs.theme === 'dark' ? ICONS.moon : ICONS.sun),
|
|
1680
|
+
state: () => t(prefs.theme === 'dark' ? 'action.themeDark' : 'action.themeLight'),
|
|
1681
|
+
run: () => toggleTheme(),
|
|
1682
|
+
},
|
|
1683
|
+
sound: {
|
|
1684
|
+
keep: true,
|
|
1685
|
+
icon: () => (prefs.sound ? ICONS.sound : ICONS.soundOff),
|
|
1686
|
+
on: () => prefs.sound,
|
|
1687
|
+
state: () => t(prefs.sound ? 'action.soundOn' : 'action.soundOff'),
|
|
1688
|
+
run: () => send({ t: 'prefs', sound: !prefs.sound }),
|
|
1689
|
+
},
|
|
1690
|
+
hide: {
|
|
1691
|
+
icon: () => ICONS.eyeOff, available: () => !!host?.hide,
|
|
1692
|
+
state: () => t('action.hide'),
|
|
1693
|
+
// the hint leaves out the note in brackets on bringing it back from the tray
|
|
1694
|
+
tip: () => tipWithoutNote(t('action.hide')),
|
|
1695
|
+
run: () => host.hide(),
|
|
1696
|
+
},
|
|
1697
|
+
// the tray's click-through as a switch: one click turns it on; while it is on, clicks reach this button only
|
|
1698
|
+
// with the click-through pause key held. The World tells the tray.
|
|
1699
|
+
through: {
|
|
1700
|
+
available: () => !!host?.clickThrough,
|
|
1701
|
+
keep: true,
|
|
1702
|
+
icon: () => ICONS.through,
|
|
1703
|
+
on: () => prefs.clickThrough,
|
|
1704
|
+
state: () => t(prefs.clickThrough ? 'action.throughOn' : 'action.throughOff'),
|
|
1705
|
+
tip: () => tipWithoutNote(ACTIONS.through.state()),
|
|
1706
|
+
run: () => send({ t: 'prefs', clickThrough: !prefs.clickThrough }),
|
|
1707
|
+
},
|
|
1708
|
+
size: {
|
|
1709
|
+
// hovering it shows the size slider for a moment (stepSlider); a click, or a tap where nothing hovers, pins it (pinSlider);
|
|
1710
|
+
// only on the desktop: a tab draws the body at one size
|
|
1711
|
+
available: () => !!host,
|
|
1712
|
+
keep: true,
|
|
1713
|
+
icon: () => ICONS.resize,
|
|
1714
|
+
// lit while pinned; no switch state otherwise, so it is not drawn as a switch turned off
|
|
1715
|
+
on: () => pinned === 'size' || undefined,
|
|
1716
|
+
state: () => t('action.size', { pct: Math.round(prefs.scale * 100) }),
|
|
1717
|
+
run: () => pinSlider(pinned === 'size' ? null : 'size'),
|
|
1718
|
+
},
|
|
1719
|
+
// the transparency slider, opened and pinned as the size slider is; it sets the transparency on screen (fadeKey);
|
|
1720
|
+
// only on the desktop, where the body fades
|
|
1721
|
+
fade: {
|
|
1722
|
+
available: () => !!host,
|
|
1723
|
+
keep: true,
|
|
1724
|
+
icon: () => ICONS.fade,
|
|
1725
|
+
on: () => pinned === 'fade' || undefined,
|
|
1726
|
+
state: () => t(fullscreenFaded ? 'action.fadeFullscreen' : 'action.fade', { pct: prefs[fadeKey()] }),
|
|
1727
|
+
run: () => pinSlider(pinned === 'fade' ? null : 'fade'),
|
|
1728
|
+
},
|
|
1729
|
+
dress: {
|
|
1730
|
+
icon: () => ICONS.shirt,
|
|
1731
|
+
state: () => t('action.dress'),
|
|
1732
|
+
// an embedding app that lends dressing shows its own dress page; otherwise the pet's dress window
|
|
1733
|
+
run: () => {
|
|
1734
|
+
if (prefs.bot?.buttons?.dress) send({ t: 'control', action: 'dress' });
|
|
1735
|
+
else if (host?.openDress) host.openDress();
|
|
1736
|
+
else window.open('/dress', '_blank');
|
|
1737
|
+
},
|
|
1738
|
+
},
|
|
1739
|
+
// a switch once the person confirmed the risks (on the 「习惯」 page, turning it on or adding this button); before that,
|
|
1740
|
+
// off, a click opens the settings window's switch, which shows the risks first
|
|
1741
|
+
cua: {
|
|
1742
|
+
available: () => prefs.cua.on || prefs.cua.confirmed || prefs.cua.canOpen,
|
|
1743
|
+
get keep() { return prefs.cua.on || prefs.cua.confirmed; },
|
|
1744
|
+
icon: () => (prefs.cua.on ? ICONS.computer : ICONS.computerOff),
|
|
1745
|
+
on: () => prefs.cua.on,
|
|
1746
|
+
state: () => t(prefs.cua.on ? 'action.cuaOn' : prefs.cua.confirmed ? 'action.cuaOff' : 'action.cuaOffAsk'),
|
|
1747
|
+
run: () => {
|
|
1748
|
+
if (!prefs.cua.on && !prefs.cua.confirmed) { send({ t: 'control', action: 'cua' }); return; }
|
|
1749
|
+
// shown at once; the World's next prefs confirm it
|
|
1750
|
+
const on = !prefs.cua.on;
|
|
1751
|
+
prefs.cua = { ...prefs.cua, on };
|
|
1752
|
+
send({ t: 'prefs', cua: on });
|
|
1753
|
+
},
|
|
1754
|
+
},
|
|
1755
|
+
worlds: {
|
|
1756
|
+
// only where the embedding app has a World list to show
|
|
1757
|
+
available: () => !!prefs.bot?.buttons?.worlds,
|
|
1758
|
+
icon: () => ICONS.boxes,
|
|
1759
|
+
state: () => t('action.worlds'),
|
|
1760
|
+
run: () => send({ t: 'control', action: 'worlds' }),
|
|
1761
|
+
},
|
|
1762
|
+
};
|
|
1763
|
+
const available = (id) => ACTIONS[id] && (ACTIONS[id].available?.() ?? true);
|
|
1764
|
+
|
|
1765
|
+
/** The markup each button's icon was last drawn with (drawAction). */
|
|
1766
|
+
const drawnIcons = new WeakMap();
|
|
1767
|
+
/**
|
|
1768
|
+
* One action as a button, as a hover button and in the menu alike: its icon, the badge, whether a switch is on, and whether
|
|
1769
|
+
* it waits for something not ready. The icon is replaced only when it changes: a press whose icon was swapped before the
|
|
1770
|
+
* release gets no click, and the size and transparency buttons are redrawn as their slider opens, which may be mid-press.
|
|
1771
|
+
*/
|
|
1772
|
+
function drawAction(b, id) {
|
|
1773
|
+
const a = ACTIONS[id], on = a.on?.();
|
|
1774
|
+
const badge = a.badge?.() ?? '';
|
|
1775
|
+
const ic = b.querySelector('.ic'), html = a.icon() + (badge ? `<b class="badge">${badge}</b>` : '');
|
|
1776
|
+
if (drawnIcons.get(ic) !== html) { ic.innerHTML = html; drawnIcons.set(ic, html); }
|
|
1777
|
+
b.classList.toggle('on', on === true);
|
|
1778
|
+
b.classList.toggle('off', on === false);
|
|
1779
|
+
b.classList.toggle('waiting', !!a.waiting?.());
|
|
1780
|
+
b.setAttribute('aria-label', a.state());
|
|
1781
|
+
b.dataset.tip = a.tip?.() ?? tipOf(a.state());
|
|
1782
|
+
if (on !== undefined) b.setAttribute('aria-pressed', String(on));
|
|
1783
|
+
else b.removeAttribute('aria-pressed');
|
|
1784
|
+
}
|
|
1785
|
+
|
|
1786
|
+
function cycleRoam() {
|
|
1787
|
+
const roam = ROAM_ORDER[(ROAM_ORDER.indexOf(prefs.roam) + 1) % ROAM_ORDER.length];
|
|
1788
|
+
applyPrefs({ roam });
|
|
1789
|
+
send({ t: 'prefs', roam });
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
function toggleTheme() {
|
|
1793
|
+
const theme = prefs.theme === 'dark' ? 'light' : 'dark';
|
|
1794
|
+
applyPrefs({ theme });
|
|
1795
|
+
send({ t: 'prefs', theme });
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
function toggleVoice() {
|
|
1799
|
+
const on = !prefs.voice.enabled;
|
|
1800
|
+
// shown at once; the World's next prefs confirm it
|
|
1801
|
+
prefs.voice = { ...prefs.voice, enabled: on };
|
|
1802
|
+
refreshButtons();
|
|
1803
|
+
send({ t: 'prefs', mic: on });
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
/* ---------- menu: the run controls as round buttons on Coo's left, the hover buttons in columns on its right ---------- */
|
|
1807
|
+
/** Most action buttons in one column, of the menu as of the hover buttons. */
|
|
1808
|
+
const MENU_ROWS = 3;
|
|
1809
|
+
/** The actions the menu shows: the hover buttons chosen in settings, the same ones the pointer brings up; none when none are. */
|
|
1810
|
+
function menuActions() {
|
|
1811
|
+
return prefs.hoverButtons.filter(available).slice(0, MAX_HOVER);
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
function openMenu() {
|
|
1815
|
+
const ids = menuActions();
|
|
1816
|
+
// nothing to show: no hover buttons picked, and no run controls lent
|
|
1817
|
+
if (!ids.length && !prefs.bot?.controls) return;
|
|
1818
|
+
pinSlider(null);
|
|
1819
|
+
// the hover buttons showing become the menu's: each slides from where it stood to its tile, and only the rest pop out
|
|
1820
|
+
const was = new Map();
|
|
1821
|
+
if (!tools.hidden && !leaving(tools)) for (const b of tools.children) was.set(b.dataset.action, laidAt(b));
|
|
1822
|
+
toolsShow.hideNow();
|
|
1823
|
+
endHold();
|
|
1824
|
+
menu.innerHTML = '';
|
|
1825
|
+
const rail = Object.assign(document.createElement('div'), { className: 'm-rail' });
|
|
1826
|
+
const grid = Object.assign(document.createElement('div'), { className: 'm-grid' });
|
|
1827
|
+
grid.style.gridTemplateRows = `repeat(${Math.min(MENU_ROWS, Math.max(1, ids.length))}, auto)`;
|
|
1828
|
+
for (const id of ids) {
|
|
1829
|
+
const a = ACTIONS[id];
|
|
1830
|
+
const b = document.createElement('button');
|
|
1831
|
+
b.type = 'button'; b.setAttribute('role', 'menuitem');
|
|
1832
|
+
b.className = 'tool m-tile';
|
|
1833
|
+
b.dataset.action = id;
|
|
1834
|
+
b.innerHTML = '<span class="ic"></span>';
|
|
1835
|
+
drawAction(b, id);
|
|
1836
|
+
b.addEventListener('click', (e) => {
|
|
1837
|
+
if (repeatClick(e)) return;
|
|
1838
|
+
sfx.tick();
|
|
1839
|
+
// as the button was clicked: running it may change whether it keeps the menu open (computer use)
|
|
1840
|
+
const keep = a.keep;
|
|
1841
|
+
if (!keep) closeMenu();
|
|
1842
|
+
a.run();
|
|
1843
|
+
if (keep) drawAction(b, id);
|
|
1844
|
+
});
|
|
1845
|
+
grid.appendChild(b);
|
|
1846
|
+
}
|
|
1847
|
+
grid.hidden = !ids.length;
|
|
1848
|
+
menu.append(rail, grid);
|
|
1849
|
+
renderMenuRail();
|
|
1850
|
+
stagger(grid);
|
|
1851
|
+
// the buttons grow out of the body one after another; a rail redrawn later (settings, the quit question) does not replay it
|
|
1852
|
+
menuShow.show();
|
|
1853
|
+
// focused, so a click anywhere else blurs the window and folds the menu
|
|
1854
|
+
host?.focus?.();
|
|
1855
|
+
const l = at();
|
|
1856
|
+
if (l) placeMenu(l);
|
|
1857
|
+
for (const b of menu.querySelectorAll('.m-tile')) {
|
|
1858
|
+
const r = was.get(b.dataset.action);
|
|
1859
|
+
if (!r) continue;
|
|
1860
|
+
const n = laidAt(b);
|
|
1861
|
+
b.classList.add('from-tool');
|
|
1862
|
+
b.style.setProperty('--fx', r.x - n.x + 'px');
|
|
1863
|
+
b.style.setProperty('--fy', r.y - n.y + 'px');
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
/** Where a button is laid out, in page pixels, leaving out the transforms and scale an animation or hover puts on it. */
|
|
1867
|
+
function laidAt(b) {
|
|
1868
|
+
const p = b.offsetParent;
|
|
1869
|
+
return { x: (p?.offsetLeft ?? 0) + b.offsetLeft, y: (p?.offsetTop ?? 0) + b.offsetTop };
|
|
1870
|
+
}
|
|
1871
|
+
|
|
1872
|
+
/** The run controls on the body's left and the actions on its right; the two swap when the right runs off the screen. */
|
|
1873
|
+
function placeMenu(l) {
|
|
1874
|
+
const rail = menu.querySelector('.m-rail'), grid = menu.querySelector('.m-grid');
|
|
1875
|
+
if (!rail || !grid) return;
|
|
1876
|
+
// as far out from where the body stands as the hover buttons, so those that were showing stay where they were;
|
|
1877
|
+
// from where it stands, not from its box, which narrows and shifts as it turns round
|
|
1878
|
+
const c = l.side, reach = c.reach + 10, R = l.x + reach, L = l.x - reach;
|
|
1879
|
+
const onRight = layBeside(grid, l.x, reach, innerWidth);
|
|
1880
|
+
// whole pixels: the menu rides up and down with the body, and text at a fraction of a pixel snaps on its own, apart from its frame
|
|
1881
|
+
const y = (el) => { el.style.top = Math.round(clamp(c.y - el.offsetHeight / 2, 8, innerHeight - el.offsetHeight - 8)) + 'px'; };
|
|
1882
|
+
y(grid);
|
|
1883
|
+
// the run controls hold their edge next to the body, so the quit question grows away from it
|
|
1884
|
+
// a long quit question (Japanese, Russian) that would run off the left edge stays on the screen
|
|
1885
|
+
if (onRight) { rail.style.left = 'auto'; rail.style.right = f(Math.min(innerWidth - rail.offsetWidth - 8, Math.max(8, innerWidth - L))) + 'px'; }
|
|
1886
|
+
else { rail.style.right = 'auto'; rail.style.left = f(Math.min(innerWidth - rail.offsetWidth - 8, R)) + 'px'; }
|
|
1887
|
+
// the buttons line up on the edge next to the body
|
|
1888
|
+
rail.style.alignItems = onRight ? 'flex-end' : 'flex-start';
|
|
1889
|
+
y(rail);
|
|
1890
|
+
// the run controls grow out of the body and fold back into it, as the grid does
|
|
1891
|
+
rail.style.setProperty('--dx', onRight ? '16px' : '-16px');
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
/**
|
|
1895
|
+
* The run controls the embedding app lends, as in the console's rail foot: settings, pause/resume,
|
|
1896
|
+
* and the power button at the bottom, which asks first.
|
|
1897
|
+
*/
|
|
1898
|
+
function renderMenuRail(confirmQuit = false) {
|
|
1899
|
+
const rail = menu.querySelector('.m-rail'), bot = prefs.bot || {};
|
|
1900
|
+
if (!rail) return;
|
|
1901
|
+
// the power button grows into the quit question and the question shrinks back into it
|
|
1902
|
+
const last = rail.lastElementChild;
|
|
1903
|
+
const was = last && !menu.hidden && rail.classList.contains('confirm') !== confirmQuit
|
|
1904
|
+
? { w: last.offsetWidth, h: last.offsetHeight } : null;
|
|
1905
|
+
fillMenuRail(rail, bot, confirmQuit);
|
|
1906
|
+
if (was && rail.lastElementChild) growFrom(rail.lastElementChild, was, { duration: cssMs(document.documentElement, '--motion-base', 200), easing: 'ease' });
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
function fillMenuRail(rail, bot, confirmQuit) {
|
|
1910
|
+
rail.classList.toggle('confirm', confirmQuit);
|
|
1911
|
+
rail.innerHTML = '';
|
|
1912
|
+
rail.hidden = !bot.controls;
|
|
1913
|
+
const act = (iconHtml, label, fn, cls = 'tool', into = rail) => {
|
|
1914
|
+
const b = document.createElement('button');
|
|
1915
|
+
b.type = 'button'; b.className = cls; b.setAttribute('aria-label', label);
|
|
1916
|
+
// the rail's round buttons have only an icon; the quit question's buttons say what they do
|
|
1917
|
+
if (into === rail) b.dataset.tip = label;
|
|
1918
|
+
b.innerHTML = iconHtml;
|
|
1919
|
+
b.addEventListener('click', (e) => { e.stopPropagation(); sfx.tick(); fn(); });
|
|
1920
|
+
into.appendChild(b);
|
|
1921
|
+
};
|
|
1922
|
+
if (!bot.controls) return;
|
|
1923
|
+
// only the controls the embedding app lent; a server without `buttons` lends all three
|
|
1924
|
+
const has = bot.buttons ?? { pause: true, settings: true, quit: true };
|
|
1925
|
+
if (has.settings) act(ICONS.settings, t('menu.settings'), () => { closeMenu(); send({ t: 'control', action: 'settings' }); });
|
|
1926
|
+
if (has.pause) act(bot.paused ? ICONS.play : ICONS.pause, t(bot.paused ? 'menu.resume' : 'menu.pause'), () => send({ t: 'control', action: bot.paused ? 'resume' : 'pause' }), `tool run${bot.paused ? ' paused' : ''}`);
|
|
1927
|
+
if (!has.quit) return;
|
|
1928
|
+
if (!confirmQuit) { act(ICONS.power, bot.quitLabel, () => renderMenuRail(true), 'tool power'); return; }
|
|
1929
|
+
const ask = Object.assign(document.createElement('div'), { className: 'm-quit' });
|
|
1930
|
+
ask.appendChild(Object.assign(document.createElement('span'), { className: 'm-ask', textContent: bot.quitPrompt || '' }));
|
|
1931
|
+
act(ICONS.power, bot.quitLabel, () => { closeMenu(); send({ t: 'control', action: 'quit' }); }, 'q-act danger', ask);
|
|
1932
|
+
act(`<span>${esc(t('menu.cancel'))}</span>`, t('menu.cancel'), () => renderMenuRail(), 'q-act text', ask);
|
|
1933
|
+
rail.appendChild(ask);
|
|
1934
|
+
stagger(rail);
|
|
1935
|
+
}
|
|
1936
|
+
function closeMenu() {
|
|
1937
|
+
if (menu.hidden || leaving(menu)) return;
|
|
1938
|
+
menuShow.hide(POP_OUT_MS());
|
|
1939
|
+
// the hover buttons stay away until the pointer has left the body and them, and comes back
|
|
1940
|
+
toolsMuted = true;
|
|
1941
|
+
toolsUntil = 0;
|
|
1942
|
+
}
|
|
1943
|
+
|
|
1944
|
+
/**
|
|
1945
|
+
* The second click of a double click on an action button, which does nothing: a quick second press would undo the
|
|
1946
|
+
* first at once (unpinning the slider just pinned, switching a sound back), as a hand that clicks twice by habit does.
|
|
1947
|
+
*/
|
|
1948
|
+
const repeatClick = (e) => e.detail > 1;
|
|
1949
|
+
|
|
1950
|
+
/** Redraws whatever shows an action: the open menu's tiles and the hover buttons. */
|
|
1951
|
+
function refreshButtons() {
|
|
1952
|
+
for (const b of menu.querySelectorAll('.m-tile')) drawAction(b, b.dataset.action);
|
|
1953
|
+
renderTools();
|
|
1954
|
+
}
|
|
1955
|
+
|
|
1956
|
+
/* ---------- hover buttons: the actions chosen in settings (chat and voice by default), beside the pet ---------- */
|
|
1957
|
+
/** Seconds the buttons stay after the pointer leaves both the pet and them. */
|
|
1958
|
+
const TOOLS_LINGER = .8;
|
|
1959
|
+
/** Milliseconds the voice button is held before what was heard goes out. */
|
|
1960
|
+
const HOLD_TO_SEND = 500;
|
|
1961
|
+
let toolsUntil = 0;
|
|
1962
|
+
/** Set when the menu closes; cleared once the pointer is off the body and the hover buttons. */
|
|
1963
|
+
let toolsMuted = false;
|
|
1964
|
+
let toolIds = '';
|
|
1965
|
+
|
|
1966
|
+
function renderTools() {
|
|
1967
|
+
const ids = prefs.hoverButtons.filter(available).slice(0, MAX_HOVER);
|
|
1968
|
+
if (ids.join(',') !== toolIds) {
|
|
1969
|
+
toolIds = ids.join(',');
|
|
1970
|
+
endHold();
|
|
1971
|
+
tools.innerHTML = '';
|
|
1972
|
+
// up to three in a column, then a second column
|
|
1973
|
+
tools.style.gridTemplateRows = `repeat(${Math.min(MENU_ROWS, Math.max(1, ids.length))}, auto)`;
|
|
1974
|
+
for (const id of ids) {
|
|
1975
|
+
const b = document.createElement('button');
|
|
1976
|
+
b.type = 'button'; b.className = 'tool'; b.dataset.action = id;
|
|
1977
|
+
b.innerHTML = '<span class="ic"></span>';
|
|
1978
|
+
if (id === 'voice') wireVoiceTool(b);
|
|
1979
|
+
else b.addEventListener('click', (e) => { if (repeatClick(e)) return; sfx.tick(); if (!ACTIONS[id].keep) toolsUntil = 0; ACTIONS[id].run(); refreshButtons(); });
|
|
1980
|
+
tools.appendChild(b);
|
|
1981
|
+
}
|
|
1982
|
+
stagger(tools);
|
|
1983
|
+
}
|
|
1984
|
+
for (const b of tools.children) drawAction(b, b.dataset.action);
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
/** A press shorter than HOLD_TO_SEND switches voice input; a longer one sends what was heard so far. */
|
|
1988
|
+
const hold = { timer: 0, sent: false, el: null };
|
|
1989
|
+
function endHold() {
|
|
1990
|
+
clearTimeout(hold.timer);
|
|
1991
|
+
hold.timer = 0;
|
|
1992
|
+
hold.el?.classList.remove('holding');
|
|
1993
|
+
}
|
|
1994
|
+
function wireVoiceTool(b) {
|
|
1995
|
+
b.style.setProperty('--hold', HOLD_TO_SEND + 'ms');
|
|
1996
|
+
b.addEventListener('pointerdown', (e) => {
|
|
1997
|
+
if (e.button !== 0) return;
|
|
1998
|
+
hold.sent = false; hold.el = b;
|
|
1999
|
+
if (!prefs.voice.enabled || !prefs.voice.ready) return;
|
|
2000
|
+
b.classList.add('holding');
|
|
2001
|
+
hold.timer = setTimeout(() => {
|
|
2002
|
+
endHold();
|
|
2003
|
+
hold.sent = true;
|
|
2004
|
+
send({ t: 'commit' });
|
|
2005
|
+
sfx.select();
|
|
2006
|
+
b.classList.remove('sent'); void b.offsetWidth; b.classList.add('sent');
|
|
2007
|
+
}, HOLD_TO_SEND);
|
|
2008
|
+
});
|
|
2009
|
+
b.addEventListener('pointerup', (e) => {
|
|
2010
|
+
if (e.button !== 0) return;
|
|
2011
|
+
const sent = hold.sent;
|
|
2012
|
+
endHold();
|
|
2013
|
+
hold.sent = false;
|
|
2014
|
+
if (!sent) { toggleVoice(); sfx.tick(); }
|
|
2015
|
+
});
|
|
2016
|
+
b.addEventListener('pointerleave', () => { endHold(); hold.sent = true; });
|
|
2017
|
+
b.addEventListener('pointercancel', () => { endHold(); hold.sent = true; });
|
|
2018
|
+
// the pointer handlers act on mouse and touch; a click with no pointer is the keyboard
|
|
2019
|
+
b.addEventListener('click', (e) => { if (e.detail === 0) { toggleVoice(); sfx.tick(); } });
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
/** Where the cursor is, in page pixels, or null when it is off the page. */
|
|
2023
|
+
const cursor = { at: null };
|
|
2024
|
+
/** Pixels around the hover buttons that count as on them, as the gaps between them do. */
|
|
2025
|
+
const TOOLS_MARGIN = 6;
|
|
2026
|
+
function overTools(p) {
|
|
2027
|
+
if (tools.hidden || leaving(tools)) return false;
|
|
2028
|
+
const r = tools.getBoundingClientRect(), m = TOOLS_MARGIN;
|
|
2029
|
+
return p.x >= r.left - m && p.x <= r.right + m && p.y >= r.top - m && p.y <= r.bottom + m;
|
|
2030
|
+
}
|
|
2031
|
+
/** Pops the hover buttons out of the body one after another, as the menu does, and folds them back into it before they go. */
|
|
2032
|
+
function showTools(on) {
|
|
2033
|
+
if (on) {
|
|
2034
|
+
// back over them while they fold: they stay, without popping out again
|
|
2035
|
+
toolsShow.stay();
|
|
2036
|
+
if (!tools.hidden) return;
|
|
2037
|
+
toolsShow.show();
|
|
2038
|
+
const l = at();
|
|
2039
|
+
if (l) placeTools(l);
|
|
2040
|
+
return;
|
|
2041
|
+
}
|
|
2042
|
+
if (tools.hidden || leaving(tools)) return;
|
|
2043
|
+
endHold();
|
|
2044
|
+
toolsShow.hide(POP_OUT_MS());
|
|
2045
|
+
}
|
|
2046
|
+
|
|
2047
|
+
/* ---------- popping in and out: the menu, the hover buttons and the look wheel ---------- */
|
|
2048
|
+
/** Milliseconds the menu's buttons and the hover buttons take to fold back into the body (pet.css `--pop-out`; the other leaving animations read `--wheel-out`, `--slider-out` and `--return-time`). */
|
|
2049
|
+
const POP_OUT_MS = () => cssMs(document.documentElement, '--pop-out', 160);
|
|
2050
|
+
/** Longer than the last of the staggered `m-in`s, after which `entering` comes off. */
|
|
2051
|
+
const POP_IN_MS = 600;
|
|
2052
|
+
// the page runs without a window in the tests, where motion counts as full
|
|
2053
|
+
const lowMotion = () => motionLevel(globalThis.window) === 'low';
|
|
2054
|
+
if (globalThis.window?.document) watchMotion(globalThis.window);
|
|
2055
|
+
/** The tails' line follows the width the border is drawn at, which changes with the display's scale (ui.js tailLine). */
|
|
2056
|
+
function watchTailLine() {
|
|
2057
|
+
document.documentElement.style.setProperty('--tail-line', tailLine(devicePixelRatio || 1) + 'px');
|
|
2058
|
+
globalThis.matchMedia?.(`(resolution: ${devicePixelRatio || 1}dppx)`).addEventListener('change', watchTailLine, { once: true });
|
|
2059
|
+
}
|
|
2060
|
+
watchTailLine();
|
|
2061
|
+
const leaving = (el) => el.classList.contains('leaving');
|
|
2062
|
+
/** Numbers an element's buttons (`--i`), so they pop out one after another. */
|
|
2063
|
+
function stagger(el) { [...el.children].forEach((b, i) => b.style.setProperty('--i', String(i))); }
|
|
2064
|
+
/** Each pops in with its `entering` animation and out with `leaving`, taking no clicks meanwhile (show-hide.js). */
|
|
2065
|
+
const menuShow = showHide(menu, { enterMs: () => POP_IN_MS });
|
|
2066
|
+
const toolsShow = showHide(tools, { enterMs: () => POP_IN_MS });
|
|
2067
|
+
/**
|
|
2068
|
+
* What opens over the head, one at a time: the look wheel and each slider, every one its own element with its own
|
|
2069
|
+
* animations. `close` plays its leaving animation.
|
|
2070
|
+
*/
|
|
2071
|
+
const HEAD = [];
|
|
2072
|
+
/** `el` takes the place over the head: every other one there leaves with its animation as `el` enters with its own. */
|
|
2073
|
+
function claimHead(el) { for (const o of HEAD) if (o.el !== el && !o.el.hidden && !leaving(o.el)) o.close(); }
|
|
2074
|
+
/** Something other than `el` is in the place over the head, not leaving it. */
|
|
2075
|
+
const headTaken = (el) => HEAD.some((o) => o.el !== el && !o.el.hidden && !leaving(o.el));
|
|
2076
|
+
function stepTools() {
|
|
2077
|
+
// shown while the cursor is on the pet or on the buttons, and a moment after it leaves; decided
|
|
2078
|
+
// from where the cursor is now, not from the last move event, which may be stale
|
|
2079
|
+
const p = cursor.at;
|
|
2080
|
+
const l = at();
|
|
2081
|
+
const near = sliding() || (!!p && (body?.hit(p) || overTools(p) || overWheel(p) || overSlider(p)));
|
|
2082
|
+
if (!near) toolsMuted = false;
|
|
2083
|
+
if (near && !toolsMuted) toolsUntil = T + TOOLS_LINGER;
|
|
2084
|
+
const confirming = item?.kind === 'ask' && item.confirm && !item.answered;
|
|
2085
|
+
showTools(!clicksPass() && T < toolsUntil && l && !l.pressing && !l.busy && menu.hidden && !confirming && toolIds !== '');
|
|
2086
|
+
tools.querySelector('[data-action="voice"]')?.classList.toggle('live', listen.phase === 'hearing');
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
/* ---------- look wheel: hovering a dress button shows the looks in a row over the body, the one worn in the middle ---------- */
|
|
2090
|
+
/** Seconds the wheel stays after the pointer leaves it and every dress button. */
|
|
2091
|
+
const WHEEL_LINGER = .25;
|
|
2092
|
+
/** Milliseconds the looks take to fold back into the middle (`.wheel.leaving` in pet.css). */
|
|
2093
|
+
const WHEEL_OUT_MS = () => cssMs(document.documentElement, '--wheel-out', 140);
|
|
2094
|
+
/** Pixels between two looks in the row, and how many show on each side of the middle one. */
|
|
2095
|
+
const WHEEL_STEP = 54, WHEEL_SIDE = 3;
|
|
2096
|
+
/** Opacity of a look by its distance from the middle. */
|
|
2097
|
+
const WHEEL_FADE = [1, .55, .3, .12];
|
|
2098
|
+
/** Milliseconds the row rests on a look before Coo puts it on. */
|
|
2099
|
+
const WHEEL_APPLY_MS = 300;
|
|
2100
|
+
/** Wheel delta that turns the row one look (a mouse notch is about 100; a touchpad sends many small ones). */
|
|
2101
|
+
const WHEEL_NOTCH = 40;
|
|
2102
|
+
/** `empty`: the last read found no looks to show; set until the pointer has left the dress buttons, so a hover reads them once. */
|
|
2103
|
+
const wheelState = { items: [], at: 0, until: 0, timer: 0, acc: 0, opening: false, empty: false };
|
|
2104
|
+
const wheelShow = showHide(wheel);
|
|
2105
|
+
|
|
2106
|
+
/**
|
|
2107
|
+
* The look worn, with its size, when the row last opened on one that is not a favourite. It leads the row until a look
|
|
2108
|
+
* outside the favourites is worn again, so the row can always turn back to it: also after the row closed because a
|
|
2109
|
+
* favourite of another size moved the dress button from under the pointer.
|
|
2110
|
+
*/
|
|
2111
|
+
let stash = null;
|
|
2112
|
+
|
|
2113
|
+
/**
|
|
2114
|
+
* The favourite looks to switch between (looks.js), leaving out those whose pack was uninstalled; none, none shown.
|
|
2115
|
+
* `stash` leads the row (dashed) while it is not among them.
|
|
2116
|
+
*/
|
|
2117
|
+
async function wheelItems() {
|
|
2118
|
+
const [saved, figures] = await Promise.all([fetchLooks(), fetch('/api/figures').then((r) => r.json()).catch(() => null)]);
|
|
2119
|
+
const list = Array.isArray(figures) ? figures : [], dark = prefs.theme === 'dark';
|
|
2120
|
+
const items = (saved ?? []).filter((l) => lookAvailable(l.skin, list))
|
|
2121
|
+
.map((l) => ({ skin: l.skin, scale: l.scale, on: wearing(l), html: lookPicture(l.skin, list, dark, l.scale) }));
|
|
2122
|
+
if (!items.length) return [];
|
|
2123
|
+
if (!items.some((i) => i.on)) stash = { skin, scale: prefs.scale };
|
|
2124
|
+
else if (stash && items.some((i) => sameLook(i.skin, stash.skin) && (i.scale ?? stash.scale) === stash.scale)) stash = null;
|
|
2125
|
+
// a pack uninstalled since: the look can no longer be put on
|
|
2126
|
+
if (stash && !lookAvailable(stash.skin, list)) stash = null;
|
|
2127
|
+
if (stash) items.unshift({ ...stash, on: wearing(stash), worn: true, html: lookPicture(stash.skin, list, dark, stash.scale) });
|
|
2128
|
+
return items;
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
/** Whether the pet wears `look` now: its skin, at its size when it keeps one. */
|
|
2132
|
+
const wearing = (look) => sameLook(look.skin, skin) && (typeof look.scale !== 'number' || look.scale === prefs.scale);
|
|
2133
|
+
|
|
2134
|
+
async function openWheel() {
|
|
2135
|
+
// back over a dress button while the row folds away: it fans out again
|
|
2136
|
+
if (leaving(wheel)) { wheelShow.stay(); drawWheel(); return; }
|
|
2137
|
+
if (!wheel.hidden || wheelState.opening) return;
|
|
2138
|
+
// a slider being dragged keeps its place over the head: the row opens once it is let go
|
|
2139
|
+
if (sliding()) return;
|
|
2140
|
+
pinSlider(null);
|
|
2141
|
+
claimHead(wheel);
|
|
2142
|
+
wheelState.opening = true;
|
|
2143
|
+
const items = await wheelItems().catch(() => []);
|
|
2144
|
+
wheelState.opening = false;
|
|
2145
|
+
// something else took the place over the head while the favourites were read: one at a time
|
|
2146
|
+
if (headTaken(wheel)) return;
|
|
2147
|
+
if (!items.length) { wheelState.empty = true; return; }
|
|
2148
|
+
wheelState.items = items;
|
|
2149
|
+
wheelState.at = Math.max(0, items.findIndex((i) => i.on));
|
|
2150
|
+
wheelState.acc = 0;
|
|
2151
|
+
wheel.innerHTML = '';
|
|
2152
|
+
items.forEach((item, i) => {
|
|
2153
|
+
const b = document.createElement('button');
|
|
2154
|
+
b.type = 'button'; b.className = item.worn ? 'w-item worn' : 'w-item';
|
|
2155
|
+
b.innerHTML = item.html;
|
|
2156
|
+
// a press puts the look on at once, the one in the middle too (it may be the only one saved)
|
|
2157
|
+
b.addEventListener('pointerdown', (e) => {
|
|
2158
|
+
if (e.button !== 0) return;
|
|
2159
|
+
e.preventDefault(); e.stopPropagation();
|
|
2160
|
+
spinTo(i, true);
|
|
2161
|
+
});
|
|
2162
|
+
wheel.appendChild(b);
|
|
2163
|
+
});
|
|
2164
|
+
wheel.style.width = (2 * WHEEL_SIDE + 1) * WHEEL_STEP + 'px';
|
|
2165
|
+
wheel.hidden = false;
|
|
2166
|
+
// the looks fan out from the middle one: drawn folded first, then let go to their places
|
|
2167
|
+
foldWheel();
|
|
2168
|
+
void wheel.offsetWidth;
|
|
2169
|
+
drawWheel();
|
|
2170
|
+
const l = at();
|
|
2171
|
+
if (l) placeWheel(l);
|
|
2172
|
+
}
|
|
2173
|
+
|
|
2174
|
+
function closeWheel() {
|
|
2175
|
+
clearTimeout(wheelState.timer);
|
|
2176
|
+
wheelState.timer = 0;
|
|
2177
|
+
if (wheel.hidden || leaving(wheel)) return;
|
|
2178
|
+
// the looks fold back into the middle, then the row goes
|
|
2179
|
+
foldWheel();
|
|
2180
|
+
wheelShow.hide(WHEEL_OUT_MS());
|
|
2181
|
+
}
|
|
2182
|
+
|
|
2183
|
+
HEAD.push({ el: wheel, close: closeWheel });
|
|
2184
|
+
|
|
2185
|
+
/** Every look gathered small and faint in the middle of the row: where it fans out from and folds back into. */
|
|
2186
|
+
function foldWheel() {
|
|
2187
|
+
for (const b of wheel.children) {
|
|
2188
|
+
b.style.transform = 'translate(-50%, -50%) scale(.3)';
|
|
2189
|
+
b.style.opacity = '0';
|
|
2190
|
+
b.style.pointerEvents = 'none';
|
|
2191
|
+
}
|
|
2192
|
+
}
|
|
2193
|
+
|
|
2194
|
+
function drawWheel() {
|
|
2195
|
+
[...wheel.children].forEach((b, i) => {
|
|
2196
|
+
const d = i - wheelState.at, n = Math.abs(d);
|
|
2197
|
+
b.style.transform = `translate(-50%, -50%) translateX(${d * WHEEL_STEP}px) scale(${Math.max(.6, 1 - .14 * n)})`;
|
|
2198
|
+
b.style.opacity = String(WHEEL_FADE[n] ?? 0);
|
|
2199
|
+
b.style.zIndex = String(10 - n);
|
|
2200
|
+
b.style.pointerEvents = n > WHEEL_SIDE ? 'none' : '';
|
|
2201
|
+
b.classList.toggle('on', d === 0);
|
|
2202
|
+
});
|
|
2203
|
+
}
|
|
2204
|
+
|
|
2205
|
+
/** Puts on the look in the middle of the row, unless Coo wears it already. */
|
|
2206
|
+
function wearWheel() {
|
|
2207
|
+
clearTimeout(wheelState.timer);
|
|
2208
|
+
wheelState.timer = 0;
|
|
2209
|
+
const item = wheelState.items[wheelState.at];
|
|
2210
|
+
if (!item || wearing(item)) return;
|
|
2211
|
+
const look = typeof item.scale === 'number' ? { skin: item.skin, scale: item.scale } : { skin: item.skin };
|
|
2212
|
+
void fetch('/api/skin', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(look) }).catch(() => {});
|
|
2213
|
+
}
|
|
2214
|
+
|
|
2215
|
+
/** Turns the row to look `i`; Coo puts it on at once (`now`, a click), or once the row rests there (the mouse wheel). */
|
|
2216
|
+
function spinTo(i, now = false) {
|
|
2217
|
+
const n = clamp(i, 0, wheelState.items.length - 1);
|
|
2218
|
+
if (n === wheelState.at && !now) return;
|
|
2219
|
+
if (n !== wheelState.at) { wheelState.at = n; drawWheel(); }
|
|
2220
|
+
sfx.tick();
|
|
2221
|
+
clearTimeout(wheelState.timer);
|
|
2222
|
+
if (now) { wearWheel(); return; }
|
|
2223
|
+
wheelState.timer = setTimeout(wearWheel, WHEEL_APPLY_MS);
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
/** Centred over the body, just above its head. */
|
|
2227
|
+
function placeWheel(l) {
|
|
2228
|
+
const b = l.box, w = wheel.offsetWidth, h = wheel.offsetHeight;
|
|
2229
|
+
wheel.style.left = f(clamp(b.x + b.w / 2 - w / 2, 8, innerWidth - w - 8)) + 'px';
|
|
2230
|
+
wheel.style.top = f(clamp(b.y - h - 22, 8, innerHeight - h - 8)) + 'px';
|
|
2231
|
+
}
|
|
2232
|
+
|
|
2233
|
+
const inRect = (p, r, m = 0) => p.x >= r.left - m && p.x <= r.right + m && p.y >= r.top - m && p.y <= r.bottom + m;
|
|
2234
|
+
function overWheel(p) { return !wheel.hidden && !leaving(wheel) && inRect(p, wheel.getBoundingClientRect(), 6); }
|
|
2235
|
+
/** A button for action `id` on screen, in the menu or among the hover buttons, is under the pointer; not one folding away after a click. */
|
|
2236
|
+
function overAction(p, id) {
|
|
2237
|
+
for (const b of document.querySelectorAll(`.menu:not(.leaving) [data-action="${id}"], .tools:not(.leaving) [data-action="${id}"]`)) {
|
|
2238
|
+
if (b.offsetParent && inRect(p, b.getBoundingClientRect(), 4)) return true;
|
|
2239
|
+
}
|
|
2240
|
+
return false;
|
|
2241
|
+
}
|
|
2242
|
+
/**
|
|
2243
|
+
* Whether a control a hover opened over the head (`el`, the look wheel or a slider, or none yet) waits on: the pointer is still
|
|
2244
|
+
* among the pet's controls, that is on the hover buttons, on the menu, or in the column the body's box and `el` span
|
|
2245
|
+
* together, `el` itself included. Its short linger counts only once the pointer has left them all, so going from one
|
|
2246
|
+
* button to another, or across a large body to the control over its head, does not close it.
|
|
2247
|
+
*/
|
|
2248
|
+
function amongControls(p, el) {
|
|
2249
|
+
if (!p) return false;
|
|
2250
|
+
if (overTools(p) || overMenu(p)) return true;
|
|
2251
|
+
const l = at();
|
|
2252
|
+
if (!l || !el || el.hidden || leaving(el)) return false;
|
|
2253
|
+
const r = el.getBoundingClientRect(), b = l.box;
|
|
2254
|
+
return inRect(p, { left: Math.min(r.left, b.x), right: Math.max(r.right, b.x + b.w), top: Math.min(r.top, b.y), bottom: Math.max(r.bottom, b.y + b.h) }, 6);
|
|
2255
|
+
}
|
|
2256
|
+
|
|
2257
|
+
function stepWheel() {
|
|
2258
|
+
const p = cursor.at;
|
|
2259
|
+
const dress = !!p && overAction(p, 'dress');
|
|
2260
|
+
if (!dress) wheelState.empty = false;
|
|
2261
|
+
// a bubble over the pet (the typing box, a reply, a question) takes the wheel's place until it closes
|
|
2262
|
+
if (!bubble.hidden && !bubble.classList.contains('status')) { if (!wheel.hidden) closeWheel(); return; }
|
|
2263
|
+
if (amongControls(p, wheel)) wheelState.until = T + WHEEL_LINGER;
|
|
2264
|
+
// a pinned slider keeps the place over the head while the pointer crosses the dress button
|
|
2265
|
+
if (dress && wheel.hidden && !wheelState.empty && !clicksPass() && !pinned) void openWheel();
|
|
2266
|
+
if (!wheel.hidden && T > wheelState.until) closeWheel();
|
|
2267
|
+
}
|
|
2268
|
+
// the mouse wheel turns the row while it shows, over the row or over a dress button
|
|
2269
|
+
document.addEventListener('wheel', (e) => {
|
|
2270
|
+
if (wheel.hidden || !e.target.closest?.('.wheel, [data-action="dress"]')) return;
|
|
2271
|
+
e.preventDefault();
|
|
2272
|
+
wheelState.acc += Math.abs(e.deltaY) >= Math.abs(e.deltaX) ? e.deltaY : e.deltaX;
|
|
2273
|
+
if (Math.abs(wheelState.acc) < WHEEL_NOTCH) return;
|
|
2274
|
+
spinTo(wheelState.at + Math.sign(wheelState.acc));
|
|
2275
|
+
wheelState.acc = 0;
|
|
2276
|
+
wheelState.until = T + WHEEL_LINGER;
|
|
2277
|
+
}, { passive: false });
|
|
2278
|
+
|
|
2279
|
+
/* ---------- sliders over the head: hovering a size or transparency button shows its slider over the body, which follows it at once ---------- */
|
|
2280
|
+
/** Seconds the slider stays after the pointer leaves it and every button of its kind. */
|
|
2281
|
+
const SLIDER_LINGER = .35;
|
|
2282
|
+
/** Milliseconds the slider takes to fold away (`.head-slider.leaving` in pet.css). */
|
|
2283
|
+
const SLIDER_OUT_MS = () => cssMs(document.documentElement, '--slider-out', 140);
|
|
2284
|
+
/** Milliseconds between the values sent to the World while the slider moves. */
|
|
2285
|
+
const SLIDER_SEND_MS = 120;
|
|
2286
|
+
/** The transparency range in percent (src/config.ts FADE_MAX, FADE_STEP). */
|
|
2287
|
+
const FADE = { min: 0, soft: 95, max: 95, step: 5 };
|
|
2288
|
+
/**
|
|
2289
|
+
* The slider a click on its button pinned, `size` or `fade`, or null. It stays until that button is clicked again, the
|
|
2290
|
+
* other slider's button is clicked, the pointer goes down anywhere else, the window loses focus (a click in another
|
|
2291
|
+
* program), Escape, or the menu or a bubble the person opened takes the place. Hovering the other slider's button or a
|
|
2292
|
+
* dress button meanwhile opens nothing.
|
|
2293
|
+
*/
|
|
2294
|
+
let pinned = null;
|
|
2295
|
+
/** Until when the slider waits on; per kind, the send due while it moves; the wheel's travel toward a step. */
|
|
2296
|
+
const sliderState = { until: 0, timers: { size: 0, fade: 0 }, acc: 0 };
|
|
2297
|
+
const bar = (o) => scaleSlider(document, {
|
|
2298
|
+
...o, label: '',
|
|
2299
|
+
widths: { collapsed: { width: 160, main: .86 }, expanded: { width: 240, main: .45 } },
|
|
2300
|
+
room: () => innerWidth - 120,
|
|
2301
|
+
});
|
|
2302
|
+
/**
|
|
2303
|
+
* Each slider: its bar, the value it shows, that value on the knob, and the bar's name. Each gets its own element in
|
|
2304
|
+
* the place over the head (`.head-slider[data-kind]`), so one taking over from another, or from the look wheel, plays
|
|
2305
|
+
* the leaving and entering animations; a slider added here gets a hover button of the same id.
|
|
2306
|
+
*/
|
|
2307
|
+
const SLIDERS = {
|
|
2308
|
+
size: {
|
|
2309
|
+
bar: bar({ ...SIZE, onInput: (v) => setSize(v), onChange: () => sendSlider('size') }),
|
|
2310
|
+
value: () => prefs.scale,
|
|
2311
|
+
text: (v) => `${Math.round(v * 100)}%`,
|
|
2312
|
+
label: () => t('action.sizeLabel'),
|
|
2313
|
+
},
|
|
2314
|
+
fade: {
|
|
2315
|
+
bar: bar({ ...FADE, format: (v) => `${v}%`, onInput: (v) => setFade(v), onChange: () => sendSlider('fade') }),
|
|
2316
|
+
value: () => prefs[fadeKey()],
|
|
2317
|
+
text: (v) => `${v}%`,
|
|
2318
|
+
label: () => t(fullscreenFaded ? 'action.fadeFullscreenLabel' : 'action.fadeLabel'),
|
|
2319
|
+
},
|
|
2320
|
+
};
|
|
2321
|
+
for (const [kind, s] of Object.entries(SLIDERS)) {
|
|
2322
|
+
s.el = Object.assign(document.createElement('div'), { className: 'head-slider', hidden: true });
|
|
2323
|
+
s.el.dataset.kind = kind;
|
|
2324
|
+
s.show = showHide(s.el, { enterMs: () => POP_IN_MS });
|
|
2325
|
+
s.valueEl = Object.assign(document.createElement('span'), { className: 'hs-value' });
|
|
2326
|
+
s.el.append(s.bar.el);
|
|
2327
|
+
s.bar.el.querySelector('.ps-thumb').append(s.valueEl);
|
|
2328
|
+
document.body.insertBefore(s.el, wheel.nextSibling);
|
|
2329
|
+
HEAD.push({ el: s.el, close: () => closeSlider(kind) });
|
|
2330
|
+
}
|
|
2331
|
+
/** The hover buttons that open a slider. */
|
|
2332
|
+
const SLIDER_BUTTONS = Object.keys(SLIDERS).map((k) => `[data-action="${k}"]`).join(', ');
|
|
2333
|
+
/** A slider is being dragged. */
|
|
2334
|
+
const sliding = () => Object.values(SLIDERS).some((s) => s.bar.active);
|
|
2335
|
+
/** The slider in the place over the head and not leaving it, or null. */
|
|
2336
|
+
const shownSlider = () => Object.keys(SLIDERS).find((k) => !SLIDERS[k].el.hidden && !leaving(SLIDERS[k].el)) ?? null;
|
|
2337
|
+
/** Values the World pushes, held while their slider is in use or newer values from it are on their way (scale-slider.js sizeEcho). */
|
|
2338
|
+
const sizeHeard = sizeEcho((v) => { if (v === prefs.scale) return; prefs.scale = v; if (!switching()) toSize(v); refreshSlider(); });
|
|
2339
|
+
const fadeHeard = Object.fromEntries(['fade', 'fullscreenFade'].map((key) => [key, sizeEcho((v) => { prefs[key] = v; refreshSlider(); })]));
|
|
2340
|
+
|
|
2341
|
+
function pinSlider(kind) {
|
|
2342
|
+
if (pinned === kind) return;
|
|
2343
|
+
const was = pinned;
|
|
2344
|
+
pinned = kind;
|
|
2345
|
+
if (kind) openSlider(kind);
|
|
2346
|
+
// unpinned with the pointer on its button, it stays as a hover holds it rather than leaving and coming straight back
|
|
2347
|
+
else if (!(cursor.at && overAction(cursor.at, was))) closeSlider();
|
|
2348
|
+
refreshButtons();
|
|
2349
|
+
}
|
|
2350
|
+
/** Draws the body at `v` now and sends it within SLIDER_SEND_MS. */
|
|
2351
|
+
function setSize(v) {
|
|
2352
|
+
prefs.scale = v;
|
|
2353
|
+
toSize(v);
|
|
2354
|
+
refreshSlider();
|
|
2355
|
+
sliderState.timers.size ||= setTimeout(() => sendSlider('size'), SLIDER_SEND_MS);
|
|
2356
|
+
}
|
|
2357
|
+
/** Shows the transparency on screen at `v` from the next frame (stepFade) and sends it within SLIDER_SEND_MS. */
|
|
2358
|
+
function setFade(v) {
|
|
2359
|
+
prefs[fadeKey()] = v;
|
|
2360
|
+
refreshSlider();
|
|
2361
|
+
sliderState.timers.fade ||= setTimeout(() => sendSlider('fade'), SLIDER_SEND_MS);
|
|
2362
|
+
}
|
|
2363
|
+
function sendSlider(kind) {
|
|
2364
|
+
clearTimeout(sliderState.timers[kind]);
|
|
2365
|
+
sliderState.timers[kind] = 0;
|
|
2366
|
+
if (kind === 'size') { sizeHeard.sent(prefs.scale); send({ t: 'prefs', scale: prefs.scale }); return; }
|
|
2367
|
+
const key = fadeKey();
|
|
2368
|
+
fadeHeard[key].sent(prefs[key]);
|
|
2369
|
+
send({ t: 'prefs', [key]: prefs[key] });
|
|
2370
|
+
}
|
|
2371
|
+
function refreshSlider() {
|
|
2372
|
+
for (const s of Object.values(SLIDERS)) {
|
|
2373
|
+
s.valueEl.textContent = s.text(s.value());
|
|
2374
|
+
s.bar.el.setAttribute('aria-label', s.label());
|
|
2375
|
+
if (!s.bar.active) s.bar.set(s.value());
|
|
2376
|
+
}
|
|
2377
|
+
for (const b of document.querySelectorAll(SLIDER_BUTTONS)) drawAction(b, b.dataset.action);
|
|
2378
|
+
}
|
|
2379
|
+
|
|
2380
|
+
/** Opens the slider of `kind`; whatever else is over the head leaves as it enters (claimHead). */
|
|
2381
|
+
function openSlider(kind) {
|
|
2382
|
+
const s = SLIDERS[kind];
|
|
2383
|
+
claimHead(s.el);
|
|
2384
|
+
refreshSlider();
|
|
2385
|
+
// hidden, or back over its button while it folds away: it enters again rather than jumping back
|
|
2386
|
+
if (s.el.hidden || leaving(s.el)) s.show.show();
|
|
2387
|
+
s.bar.relayout();
|
|
2388
|
+
const l = at();
|
|
2389
|
+
if (l) placeSlider(kind, l);
|
|
2390
|
+
}
|
|
2391
|
+
/** Closes the slider of `kind`, or every slider, unless it is being dragged. */
|
|
2392
|
+
function closeSlider(kind) {
|
|
2393
|
+
for (const k of kind ? [kind] : Object.keys(SLIDERS)) {
|
|
2394
|
+
const s = SLIDERS[k];
|
|
2395
|
+
if (s.el.hidden || leaving(s.el) || s.bar.active) continue;
|
|
2396
|
+
s.show.hide(SLIDER_OUT_MS());
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
/** Centred over the body, just above its head, where the look wheel opens; it follows the head as other controls do (`follow`). */
|
|
2400
|
+
function placeSlider(kind, l) {
|
|
2401
|
+
const el = SLIDERS[kind].el, b = l.box, w = el.offsetWidth, h = el.offsetHeight;
|
|
2402
|
+
el.style.left = f(clamp(b.x + b.w / 2 - w / 2, 8, innerWidth - w - 8)) + 'px';
|
|
2403
|
+
// the slider's box holds the value's bubble over the knob: its bottom sits just over the head
|
|
2404
|
+
el.style.top = f(clamp(b.y - h - 10, 8, innerHeight - h - 8)) + 'px';
|
|
2405
|
+
}
|
|
2406
|
+
/** The pointer is on the slider of `kind`, or on the one shown. */
|
|
2407
|
+
function overSlider(p, kind = shownSlider()) {
|
|
2408
|
+
const el = kind && SLIDERS[kind].el;
|
|
2409
|
+
return !!el && !el.hidden && !leaving(el) && inRect(p, el.getBoundingClientRect(), 6);
|
|
2410
|
+
}
|
|
2411
|
+
function stepSlider() {
|
|
2412
|
+
const p = cursor.at;
|
|
2413
|
+
const over = (p && Object.keys(SLIDERS).find((k) => overAction(p, k))) ?? null;
|
|
2414
|
+
// a bubble over the pet (the typing box, a reply, a question) takes the slider's place until it closes; with every
|
|
2415
|
+
// click passing through the window it could not be used
|
|
2416
|
+
if ((!bubble.hidden && !bubble.classList.contains('status')) || clicksPass()) { pinSlider(null); closeSlider(); return; }
|
|
2417
|
+
// over another kind's button, its slider takes the place, unless the one there is held or pinned: a pinned slider
|
|
2418
|
+
// stays while the pointer crosses the other buttons, and gives way only to a click on another
|
|
2419
|
+
if (over && over !== shownSlider() && !sliding() && !pinned) openSlider(over);
|
|
2420
|
+
// decided after opening: the slider just opened waits on as the pointer rests on its button
|
|
2421
|
+
const shown = shownSlider();
|
|
2422
|
+
if (sliding() || pinned || amongControls(p, shown && SLIDERS[shown].el)) sliderState.until = T + SLIDER_LINGER;
|
|
2423
|
+
if (T > sliderState.until) closeSlider();
|
|
2424
|
+
}
|
|
2425
|
+
// the mouse wheel steps the slider over it or over a button of its kind, while it shows: up is larger
|
|
2426
|
+
document.addEventListener('wheel', (e) => {
|
|
2427
|
+
const on = e.target.closest?.(`.head-slider, ${SLIDER_BUTTONS}`);
|
|
2428
|
+
const kind = on && (on.dataset.kind ?? on.dataset.action);
|
|
2429
|
+
if (!kind || kind !== shownSlider()) return;
|
|
2430
|
+
e.preventDefault();
|
|
2431
|
+
sliderState.acc += Math.abs(e.deltaY) >= Math.abs(e.deltaX) ? e.deltaY : e.deltaX;
|
|
2432
|
+
if (Math.abs(sliderState.acc) < WHEEL_NOTCH) return;
|
|
2433
|
+
SLIDERS[kind].bar.nudge(-Math.sign(sliderState.acc));
|
|
2434
|
+
sliderState.acc = 0;
|
|
2435
|
+
sliderState.until = T + SLIDER_LINGER;
|
|
2436
|
+
sfx.tick();
|
|
2437
|
+
}, { passive: false });
|
|
2438
|
+
|
|
2439
|
+
/* ---------- transparency: the body and its bubbles, never the controls ---------- */
|
|
2440
|
+
/** The transparency setting on screen now. */
|
|
2441
|
+
const fadeKey = () => (fullscreenFaded ? 'fullscreenFade' : 'fade');
|
|
2442
|
+
let opacityShown = 1;
|
|
2443
|
+
/**
|
|
2444
|
+
* The body at the transparency on screen (pet.css --pet-opacity), whatever it does: talking, asking, held or with the
|
|
2445
|
+
* typing box open. The bubbles and the controls never take it. A tab draws the body opaque.
|
|
2446
|
+
*/
|
|
2447
|
+
function stepFade() {
|
|
2448
|
+
const o = !host ? 1 : 1 - prefs[fadeKey()] / 100;
|
|
2449
|
+
if (o === opacityShown) return;
|
|
2450
|
+
opacityShown = o;
|
|
2451
|
+
document.documentElement.style.setProperty('--pet-opacity', String(o));
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
/* ---------- pointer ---------- */
|
|
2455
|
+
let pointerSeen = false;
|
|
2456
|
+
const lastPointer = { x: 0, y: 0 };
|
|
2457
|
+
/** Whether the page is on screen and drawing; the mouse is not taken while it is not. */
|
|
2458
|
+
const FRAME_STALL_MS = 1000;
|
|
2459
|
+
let lastFrameAt = performance.now();
|
|
2460
|
+
const rendering = () => windowShown && document.visibilityState === 'visible' && performance.now() - lastFrameAt < FRAME_STALL_MS;
|
|
2461
|
+
/** How often the wish for the mouse is renewed; the window process's lease is longer. */
|
|
2462
|
+
const MOUSE_RENEW_MS = 500;
|
|
2463
|
+
let interactive = null, renewedAt = -Infinity;
|
|
2464
|
+
/**
|
|
2465
|
+
* `by`: which check decided, 'move' (the page's pointermove) or 'poll' (the window's cursor report).
|
|
2466
|
+
* `on` is a wish renewed as a lease; see host/mouse-lease.cjs.
|
|
2467
|
+
*/
|
|
2468
|
+
function setInteractive(on, by) {
|
|
2469
|
+
if (!host) return;
|
|
2470
|
+
const now = performance.now();
|
|
2471
|
+
const changed = interactive !== on;
|
|
2472
|
+
if (!changed && !(on && now - renewedAt >= MOUSE_RENEW_MS)) return;
|
|
2473
|
+
interactive = on;
|
|
2474
|
+
renewedAt = now;
|
|
2475
|
+
host.setInteractive(on);
|
|
2476
|
+
if (changed) logPointer('flip', by);
|
|
2477
|
+
}
|
|
2478
|
+
|
|
2479
|
+
/**
|
|
2480
|
+
* Pointer diagnostics, one console line `[pointer] {json}` that reaches the run log: each time the
|
|
2481
|
+
* window switches between taking the mouse and passing it through, with what both checks last saw
|
|
2482
|
+
* (position, hit on the body or the UI, how long ago, and the pointerType of the move), and each
|
|
2483
|
+
* time the pointerType of the moves changes.
|
|
2484
|
+
*/
|
|
2485
|
+
const diag = { move: null, poll: null, type: '', types: new Set(), skipped: 0, lastAt: -Infinity, timer: 0, held: null };
|
|
2486
|
+
/**
|
|
2487
|
+
* Fewest milliseconds between two lines; the lines in between are counted into the next one, and
|
|
2488
|
+
* the last of them is written once the gap has passed. A flickering pointer flips the window at
|
|
2489
|
+
* the cursor report rate (up to 66 a second) or faster; one line a second still names the check that
|
|
2490
|
+
* flipped it, and an hour of flicker stays under 3600 lines.
|
|
2491
|
+
*/
|
|
2492
|
+
const POINTER_LOG_EVERY_MS = 1000;
|
|
2493
|
+
function logPointer(event, by) {
|
|
2494
|
+
const now = performance.now(), wait = POINTER_LOG_EVERY_MS - (now - diag.lastAt);
|
|
2495
|
+
diag.held = { event, by };
|
|
2496
|
+
if (wait <= 0) { writePointer(now); return; }
|
|
2497
|
+
diag.skipped++;
|
|
2498
|
+
diag.timer ||= setTimeout(() => { diag.skipped--; writePointer(performance.now()); }, wait);
|
|
2499
|
+
}
|
|
2500
|
+
/** What a check last saw, with how many milliseconds ago in place of when. */
|
|
2501
|
+
function seen(s, now) {
|
|
2502
|
+
if (!s) return null;
|
|
2503
|
+
const { at, ...rest } = s;
|
|
2504
|
+
return { ...rest, ageMs: Math.round(now - at) };
|
|
2505
|
+
}
|
|
2506
|
+
function writePointer(now) {
|
|
2507
|
+
clearTimeout(diag.timer);
|
|
2508
|
+
diag.timer = 0;
|
|
2509
|
+
const c = at()?.side ?? { x: 0, y: 0 };
|
|
2510
|
+
console.log('[pointer] ' + JSON.stringify({
|
|
2511
|
+
...diag.held, interactive, pressing: !!at()?.pressing,
|
|
2512
|
+
move: seen(diag.move, now), poll: seen(diag.poll, now),
|
|
2513
|
+
pet: { x: Math.round(c.x), y: Math.round(c.y) },
|
|
2514
|
+
types: [...diag.types], skipped: diag.skipped,
|
|
2515
|
+
}));
|
|
2516
|
+
diag.lastAt = now;
|
|
2517
|
+
diag.skipped = 0;
|
|
2518
|
+
diag.types.clear();
|
|
2519
|
+
}
|
|
2520
|
+
|
|
2521
|
+
// the menu itself covers the whole page without taking clicks; its two columns are what can be pointed at
|
|
2522
|
+
const UI_SELECTOR = '.bubble:not(.status):not(.fading):not([hidden]), .menu:not([hidden]):not(.leaving) > *, .tools:not([hidden]):not(.leaving), .wheel:not([hidden]):not(.leaving), .head-slider:not([hidden]):not(.leaving)';
|
|
2523
|
+
const overUi = (e) => e.target.closest && e.target.closest(UI_SELECTOR);
|
|
2524
|
+
|
|
2525
|
+
/**
|
|
2526
|
+
* In a Wayland session the window takes the mouse only over the rects reported here (host/input-shape.cjs),
|
|
2527
|
+
* sent from the frames when they change and at least every MOUSE_RENEW_MS: the body's hit circles inside its
|
|
2528
|
+
* box (body-host.js onBody), one strip per SHAPE_GRID row, and what UI_SELECTOR names, the hover buttons with
|
|
2529
|
+
* TOOLS_MARGIN around them. Every rect is rounded out to SHAPE_GRID, so a body breathing in place leaves the
|
|
2530
|
+
* shape as it is on most frames.
|
|
2531
|
+
*/
|
|
2532
|
+
let inputShape = false, shapeSent = '', shapeAt = -Infinity;
|
|
2533
|
+
host?.onInputShape?.((on) => { inputShape = on; shapeSent = ''; });
|
|
2534
|
+
const SHAPE_GRID = 8;
|
|
2535
|
+
const gridDown = (v) => Math.floor(v / SHAPE_GRID) * SHAPE_GRID, gridUp = (v) => Math.ceil(v / SHAPE_GRID) * SHAPE_GRID;
|
|
2536
|
+
function inputRects() {
|
|
2537
|
+
const out = [];
|
|
2538
|
+
const add = (x0, y0, x1, y1) => {
|
|
2539
|
+
if (x1 > x0 && y1 > y0) out.push({ x: gridDown(x0), y: gridDown(y0), width: gridUp(x1) - gridDown(x0), height: gridUp(y1) - gridDown(y0) });
|
|
2540
|
+
};
|
|
2541
|
+
const l = at();
|
|
2542
|
+
for (const c of l?.hit ?? []) {
|
|
2543
|
+
const b = l.box, top = Math.max(b.y, c.y - c.r), bottom = Math.min(b.y + b.h, c.y + c.r);
|
|
2544
|
+
for (let y0 = gridDown(top); y0 < bottom; y0 += SHAPE_GRID) {
|
|
2545
|
+
// as wide as the circle's widest chord in the row: on the centre line when the row holds it, else at its edge nearer to it
|
|
2546
|
+
const y1 = y0 + SHAPE_GRID, dy = Math.max(0, y0 - c.y, c.y - y1), half = Math.sqrt(c.r * c.r - dy * dy);
|
|
2547
|
+
add(Math.max(b.x, c.x - half), Math.max(top, y0), Math.min(b.x + b.w, c.x + half), Math.min(bottom, y1));
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
for (const el of document.querySelectorAll(UI_SELECTOR)) {
|
|
2551
|
+
// a bubble's close button hangs outside it (sideColumn)
|
|
2552
|
+
const r = el === bubble ? bubbleRect() : el.getBoundingClientRect(), m = el === tools ? TOOLS_MARGIN : 0;
|
|
2553
|
+
add(r.left - m, r.top - m, r.right + m, r.bottom + m);
|
|
2554
|
+
}
|
|
2555
|
+
return out;
|
|
2556
|
+
}
|
|
2557
|
+
function stepInputShape() {
|
|
2558
|
+
if (!inputShape) return;
|
|
2559
|
+
const rects = inputRects(), key = JSON.stringify(rects), now = performance.now();
|
|
2560
|
+
if (key === shapeSent && now - shapeAt < MOUSE_RENEW_MS) return;
|
|
2561
|
+
shapeSent = key;
|
|
2562
|
+
shapeAt = now;
|
|
2563
|
+
host.setInputRects(rects);
|
|
2564
|
+
}
|
|
2565
|
+
document.addEventListener('pointermove', (e) => {
|
|
2566
|
+
pointerSeen = true;
|
|
2567
|
+
lastPointer.x = e.clientX; lastPointer.y = e.clientY;
|
|
2568
|
+
const p = { x: e.clientX, y: e.clientY };
|
|
2569
|
+
cursor.at = p;
|
|
2570
|
+
// a move carries the buttons that are really down: a press whose release was missed ends here
|
|
2571
|
+
if (pressing && e.buttons === 0) pressing = false;
|
|
2572
|
+
// while the window moves to another display, moves may come in either display's coordinates; the drag shifts over once it has moved
|
|
2573
|
+
if (!shifting) body?.pointer('move', { ...p, t: e.timeStamp });
|
|
2574
|
+
const hit = !!body?.hit(p), ui = !!overUi(e);
|
|
2575
|
+
diag.move = { at: performance.now(), type: e.pointerType, x: Math.round(p.x), y: Math.round(p.y), hit, ui };
|
|
2576
|
+
diag.types.add(e.pointerType);
|
|
2577
|
+
if (e.pointerType !== diag.type) {
|
|
2578
|
+
const first = !diag.type;
|
|
2579
|
+
diag.type = e.pointerType;
|
|
2580
|
+
if (!first) logPointer('type', 'move');
|
|
2581
|
+
}
|
|
2582
|
+
setInteractive(rendering() && (pressing || barHeld || sliding() || hit || ui), 'move');
|
|
2583
|
+
followDrag(p);
|
|
2584
|
+
});
|
|
2585
|
+
/**
|
|
2586
|
+
* The pet window also reports where the cursor is on its own, several times a second: a click-through
|
|
2587
|
+
* window may miss the move that takes the cursor off the pet (onto the taskbar, another screen),
|
|
2588
|
+
* and the hover buttons would then stay. While the window passes the mouse through, the reports
|
|
2589
|
+
* are also the body's pointer moves: on Windows such a window gets no moves at all.
|
|
2590
|
+
*/
|
|
2591
|
+
let polled = null;
|
|
2592
|
+
host?.onCursor?.((p) => {
|
|
2593
|
+
// in a Wayland session the reports keep the spot where the cursor left the last X11 window; there the page's own pointer events place it
|
|
2594
|
+
if (!inputShape || !p) cursor.at = p;
|
|
2595
|
+
if (!p) {
|
|
2596
|
+
diag.poll = { at: performance.now(), off: true };
|
|
2597
|
+
if (!pressing && !sliding()) setInteractive(false, 'poll');
|
|
2598
|
+
if (polled && !pressing) body?.pointer('leave', {});
|
|
2599
|
+
polled = null;
|
|
2600
|
+
return;
|
|
2601
|
+
}
|
|
2602
|
+
if (!interactive && !pressing && (p.x !== polled?.x || p.y !== polled?.y)) {
|
|
2603
|
+
pointerSeen = true;
|
|
2604
|
+
lastPointer.x = p.x; lastPointer.y = p.y;
|
|
2605
|
+
body?.pointer('move', { ...p, t: performance.now() });
|
|
2606
|
+
}
|
|
2607
|
+
polled = p;
|
|
2608
|
+
const el = document.elementFromPoint(p.x, p.y);
|
|
2609
|
+
const hit = !!body?.hit(p), ui = !!el?.closest?.(UI_SELECTOR);
|
|
2610
|
+
diag.poll = { at: performance.now(), x: p.x, y: p.y, hit, ui };
|
|
2611
|
+
setInteractive(rendering() && (pressing || barHeld || sliding() || hit || ui), 'poll');
|
|
2612
|
+
});
|
|
2613
|
+
/** A press that began on the body and has not been let go of: the window keeps the mouse meanwhile. */
|
|
2614
|
+
let pressing = false;
|
|
2615
|
+
/** The typing box's scrollbar thumb is held (openInput): the window keeps the mouse meanwhile. */
|
|
2616
|
+
let barHeld = false;
|
|
2617
|
+
stage.addEventListener('pointerdown', (e) => {
|
|
2618
|
+
if (e.button !== 0) return;
|
|
2619
|
+
closeMenu();
|
|
2620
|
+
const p = { x: e.clientX, y: e.clientY, t: e.timeStamp };
|
|
2621
|
+
body?.pointer('down', p);
|
|
2622
|
+
if (body?.hit(p)) { pressing = true; stage.setPointerCapture(e.pointerId); e.preventDefault(); }
|
|
2623
|
+
});
|
|
2624
|
+
const up = (e) => { pressing = false; body?.pointer('up', { x: e?.clientX ?? lastPointer.x, y: e?.clientY ?? lastPointer.y, t: e?.timeStamp ?? performance.now() }); stage.style.cursor = ''; };
|
|
2625
|
+
/**
|
|
2626
|
+
* Most milliseconds a move onto another display waits for the page to take the window's new size
|
|
2627
|
+
* (within a pixel: fractional scales round it). The size normally arrives a frame or two after
|
|
2628
|
+
* the move; the cap ends the wait when the window settled at some other size, and the pet then
|
|
2629
|
+
* stays inside whatever size the page has.
|
|
2630
|
+
*/
|
|
2631
|
+
const RESIZE_WAIT_MS = 1000;
|
|
2632
|
+
/** Waits until the page has the window size `to` gives, or RESIZE_WAIT_MS has passed, then lays the stage out again. */
|
|
2633
|
+
async function settleSize(to) {
|
|
2634
|
+
const t0 = performance.now();
|
|
2635
|
+
while ((Math.abs(innerWidth - to.w) > 1 || Math.abs(innerHeight - to.h) > 1) && performance.now() - t0 < RESIZE_WAIT_MS) {
|
|
2636
|
+
await new Promise((r) => requestAnimationFrame(r));
|
|
2637
|
+
}
|
|
2638
|
+
body?.set({ bounds: bounds() });
|
|
2639
|
+
}
|
|
2640
|
+
const outside = (p) => p.x < 0 || p.y < 0 || p.x >= innerWidth || p.y >= innerHeight;
|
|
2641
|
+
/**
|
|
2642
|
+
* Moves the window onto the display under the cursor and returns what `followCursor` gives, or null when the
|
|
2643
|
+
* cursor is over the window's own display. The page draws blank from before the move until it has the new size:
|
|
2644
|
+
* a frame drawn in the old display's coordinates after the move shows at the new place. `moved(to)` runs as
|
|
2645
|
+
* soon as the window has moved, `settled(to)` once the page has the new size; the page shows again after it.
|
|
2646
|
+
*/
|
|
2647
|
+
async function moveToCursorDisplay(moved, settled) {
|
|
2648
|
+
if (!(await host.cursorElsewhere().catch(() => false))) return null;
|
|
2649
|
+
// opacity keeps the held stage under the pointer: with visibility hidden it misses the moves and the release
|
|
2650
|
+
document.body.style.opacity = '0';
|
|
2651
|
+
try {
|
|
2652
|
+
// the blank frame is on screen before the window moves
|
|
2653
|
+
for (let i = 0; i < 2; i++) await new Promise((r) => requestAnimationFrame(r));
|
|
2654
|
+
const to = await host.followCursor().catch(() => null);
|
|
2655
|
+
if (!to) return null;
|
|
2656
|
+
moved?.(to);
|
|
2657
|
+
await settleSize(to);
|
|
2658
|
+
settled?.(to);
|
|
2659
|
+
return to;
|
|
2660
|
+
} finally {
|
|
2661
|
+
document.body.style.opacity = '';
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
/** A move of the window onto the display under the cursor, while one is under way. */
|
|
2665
|
+
let following = null;
|
|
2666
|
+
/** True from asking for that move until the drag has shifted into the new coordinates. */
|
|
2667
|
+
let shifting = false;
|
|
2668
|
+
/**
|
|
2669
|
+
* A drag carried past the window's edge: over another display the window moves there at once, so
|
|
2670
|
+
* the held pet stays in sight instead of being cut off at the edge until it is let go of.
|
|
2671
|
+
*/
|
|
2672
|
+
function followDrag(p) {
|
|
2673
|
+
if (following || at()?.mode !== 'drag' || !host?.followCursor || !outside(p)) return;
|
|
2674
|
+
shifting = true;
|
|
2675
|
+
following = moveToCursorDisplay((to) => { shifting = false; body?.shift(to.dx, to.dy); })
|
|
2676
|
+
.finally(() => { following = null; shifting = false; });
|
|
2677
|
+
}
|
|
2678
|
+
stage.addEventListener('pointerup', async (e) => {
|
|
2679
|
+
// the window was moving under the cursor: the release point is in the coordinates it left behind
|
|
2680
|
+
if (following) { await following; up(); return; }
|
|
2681
|
+
if (!outside({ x: e.clientX, y: e.clientY }) || at()?.mode !== 'drag' || !host?.followCursor) { up(e); return; }
|
|
2682
|
+
// let go of past the window's edge in one move: over another display the window follows and the pet drops there
|
|
2683
|
+
const to = await moveToCursorDisplay(() => { pressing = false; stage.style.cursor = ''; }, (to) => body?.drop({ x: to.x, y: to.y }));
|
|
2684
|
+
if (!to) up(e);
|
|
2685
|
+
});
|
|
2686
|
+
stage.addEventListener('pointercancel', up);
|
|
2687
|
+
document.addEventListener('pointerleave', () => { cursor.at = null; body?.pointer('leave', {}); });
|
|
2688
|
+
stage.addEventListener('dblclick', (e) => { if (prefs.doubleClickChat && body?.hit({ x: e.clientX, y: e.clientY })) openInput(); });
|
|
2689
|
+
document.addEventListener('contextmenu', (e) => {
|
|
2690
|
+
e.preventDefault();
|
|
2691
|
+
if (body?.hit({ x: e.clientX, y: e.clientY })) openMenu();
|
|
2692
|
+
});
|
|
2693
|
+
document.addEventListener('pointerdown', (e) => {
|
|
2694
|
+
if (!e.target.closest('.menu, .wheel')) closeMenu();
|
|
2695
|
+
if (!e.target.closest(`.head-slider, ${SLIDER_BUTTONS}`)) pinSlider(null);
|
|
2696
|
+
}, { capture: true });
|
|
2697
|
+
// clicks off the figure pass through the window to what is underneath; the window losing focus is how they show here
|
|
2698
|
+
window.addEventListener('blur', () => { closeMenu(); pinSlider(null); });
|
|
2699
|
+
document.addEventListener('focusin', (e) => {
|
|
2700
|
+
if (e.target.matches?.('input, textarea')) host?.focus?.();
|
|
2701
|
+
});
|
|
2702
|
+
document.addEventListener('keydown', (e) => {
|
|
2703
|
+
// Escape and number keys belong to the input method while choosing a candidate.
|
|
2704
|
+
if (e.isComposing || e.keyCode === 229) return;
|
|
2705
|
+
if (e.key === 'Escape') {
|
|
2706
|
+
closeMenu();
|
|
2707
|
+
pinSlider(null);
|
|
2708
|
+
if (item && item.kind === 'ask') dismissAsk();
|
|
2709
|
+
else if (item && item.kind === 'input') closeBubble();
|
|
2710
|
+
return;
|
|
2711
|
+
}
|
|
2712
|
+
const typing = e.target.closest && e.target.closest('input, textarea');
|
|
2713
|
+
// the digit row or the number pad, whether or not Num Lock is on
|
|
2714
|
+
const digit = /^(?:Digit|Numpad)([1-9])$/.exec(e.code) || /^([1-9])$/.exec(e.key);
|
|
2715
|
+
if (item && item.kind === 'ask' && item.optsShown && !item.answered && !typing && digit && !e.ctrlKey && !e.altKey && !e.metaKey) {
|
|
2716
|
+
e.preventDefault();
|
|
2717
|
+
const b = bubble.querySelectorAll('.b-opt')[+digit[1] - 1];
|
|
2718
|
+
if (b) b.click();
|
|
2719
|
+
}
|
|
2720
|
+
});
|
|
2721
|
+
|
|
2722
|
+
/* ---------- layout ---------- */
|
|
2723
|
+
/** Coo's bubble above its head, moved over to the side it faces. */
|
|
2724
|
+
function place(el, a, extraUp) {
|
|
2725
|
+
const bw = el.offsetWidth, bh = el.offsetHeight;
|
|
2726
|
+
// a close button hangs off the bubble's right side (sideColumn): it stays on the screen too
|
|
2727
|
+
const left = clamp(a.x - bw / 2 + (at()?.facing ?? 1) * 26, 10, Math.max(10, innerWidth - bw - 10 - sideRoom(el)));
|
|
2728
|
+
const top = Math.max(8, a.y - bh - extraUp);
|
|
2729
|
+
el.style.left = f(left) + 'px';
|
|
2730
|
+
el.style.top = f(top) + 'px';
|
|
2731
|
+
el.style.setProperty('--tail', f(tailAt(bw, a.x - left, prefs.bubbleSize)) + 'px');
|
|
2732
|
+
return { left, top, bw, bh };
|
|
2733
|
+
}
|
|
2734
|
+
function placeTalk(it, a) {
|
|
2735
|
+
const bw = bubble.offsetWidth, bh = bubble.offsetHeight;
|
|
2736
|
+
// picked up, or still falling when the bubble opened, Coo takes the bubble along until it has landed, and it
|
|
2737
|
+
// stays where Coo came down; the hops and strolls of stepTalkMotion's demo (talk.motion) are Coo's own and leave it be
|
|
2738
|
+
const mode = at()?.mode;
|
|
2739
|
+
if (mode === 'drag' || (FLYING.has(mode) && !talk.motion)) it.carried = true;
|
|
2740
|
+
if (it.carried) { it.pinX = a.x; it.pinY = a.y; if (!FLYING.has(mode)) it.carried = false; }
|
|
2741
|
+
const left = clamp(it.pinX - bw / 2, 10, Math.max(10, innerWidth - bw - 10 - sideRoom(bubble)));
|
|
2742
|
+
const top = Math.max(8, it.pinY - bh - 18 * prefs.bubbleSize);
|
|
2743
|
+
bubble.style.left = f(left) + 'px';
|
|
2744
|
+
bubble.style.top = f(top) + 'px';
|
|
2745
|
+
bubble.style.setProperty('--tail', f(tailAt(bw, a.x - left, prefs.bubbleSize)) + 'px');
|
|
2746
|
+
return { left, top, bw, bh };
|
|
2747
|
+
}
|
|
2748
|
+
|
|
2749
|
+
/** Milliseconds a group of controls let go of glides back to its place (`.returning` in pet.css), and a margin. */
|
|
2750
|
+
const RETURN_MS = () => cssMs(document.documentElement, '--return-time', 260);
|
|
2751
|
+
/** Whether each group of controls was held last frame, and the timers that end its glide back. */
|
|
2752
|
+
const heldGroups = new WeakMap(), returning = new WeakMap();
|
|
2753
|
+
/**
|
|
2754
|
+
* One rule for every group of controls placed by the body (the hover buttons, the menu's two sides, the look wheel, the
|
|
2755
|
+
* size slider): while the pointer is on the group, or its slider is held, it holds still, so a look or a size put on from
|
|
2756
|
+
* it moves the body and not the control pointed at; let go, it glides back to its place, and follows the body again.
|
|
2757
|
+
*/
|
|
2758
|
+
function follow(els, pointed, place) {
|
|
2759
|
+
if (!els.length) { place(); return; }
|
|
2760
|
+
const was = heldGroups.get(els[0]) ?? false;
|
|
2761
|
+
heldGroups.set(els[0], pointed);
|
|
2762
|
+
if (pointed) return;
|
|
2763
|
+
if (was && !lowMotion()) {
|
|
2764
|
+
for (const el of els) {
|
|
2765
|
+
el.classList.add('returning');
|
|
2766
|
+
clearTimeout(returning.get(el));
|
|
2767
|
+
returning.set(el, setTimeout(() => el.classList.remove('returning'), RETURN_MS() + 60));
|
|
2768
|
+
}
|
|
2769
|
+
}
|
|
2770
|
+
place();
|
|
2771
|
+
}
|
|
2772
|
+
const menuParts = () => [menu.querySelector('.m-grid'), menu.querySelector('.m-rail')].filter(Boolean);
|
|
2773
|
+
/** The pointer is on one of the menu's two sides (the menu itself covers the page without taking the pointer). */
|
|
2774
|
+
function overMenu(p) { return !menu.hidden && !leaving(menu) && menuParts().some((el) => inRect(p, el.getBoundingClientRect(), 6)); }
|
|
2775
|
+
|
|
2776
|
+
/** Beside the body as the menu's buttons are, so opening the menu leaves each button where it was. */
|
|
2777
|
+
function placeTools(l) {
|
|
2778
|
+
// across from where the body stands, not from its middle: a figure's middle swings sideways as it turns round
|
|
2779
|
+
layBeside(tools, l.x, l.side.reach + 10, innerWidth);
|
|
2780
|
+
tools.style.top = f(clamp(l.side.y - tools.offsetHeight / 2, 8, innerHeight - tools.offsetHeight - 8)) + 'px';
|
|
2781
|
+
}
|
|
2782
|
+
function layout(dt = 0) {
|
|
2783
|
+
const l = at();
|
|
2784
|
+
if (!l) return;
|
|
2785
|
+
stage.style.cursor = l.cursor;
|
|
2786
|
+
// the sounds come from where Coo is on its display: screenX and availLeft (the left of the work area the pet window
|
|
2787
|
+
// covers) count from the same origin across all displays
|
|
2788
|
+
sfx.setPan(((screenX - screen.availLeft + l.x) / (screen.availWidth || innerWidth)) * 2 - 1);
|
|
2789
|
+
const p = cursor.at;
|
|
2790
|
+
if (!tools.hidden) follow([tools], !!p && overTools(p), () => placeTools(l));
|
|
2791
|
+
if (!menu.hidden) follow(menuParts(), !!p && overMenu(p), () => placeMenu(l));
|
|
2792
|
+
if (!wheel.hidden) follow([wheel], !!p && overWheel(p), () => placeWheel(l));
|
|
2793
|
+
for (const [kind, s] of Object.entries(SLIDERS)) {
|
|
2794
|
+
if (!s.el.hidden) follow([s.el], s.bar.active || (!!p && overSlider(p, kind)), () => placeSlider(kind, l));
|
|
2795
|
+
}
|
|
2796
|
+
const a = l.bubble;
|
|
2797
|
+
let sayBox = null;
|
|
2798
|
+
// choice cards and a World's confirmation keep their bubble where it was; its tail follows Coo along the bottom edge
|
|
2799
|
+
if (!bubble.hidden && item?.pinX !== undefined) sayBox = placeTalk(item, a);
|
|
2800
|
+
else if (!bubble.hidden) sayBox = place(bubble, a, 18 * prefs.bubbleSize);
|
|
2801
|
+
placeLines(a, sayBox, dt);
|
|
2802
|
+
}
|
|
2803
|
+
|
|
2804
|
+
/** From Coo's head to the newest line's bottom edge, and between lines, in pixels at bubble size 1. */
|
|
2805
|
+
const LINES_UP = 46, LINES_GAP = 8;
|
|
2806
|
+
/**
|
|
2807
|
+
* The person's lines above Coo: newest at the bottom, older ones above it, centred over Coo's own bubble (`box`)
|
|
2808
|
+
* while it is up and over Coo's head otherwise. Each line eases to its place over `dt`, so a new line pushes the
|
|
2809
|
+
* others up and a closed one is closed over; a fading line stays where it was.
|
|
2810
|
+
*/
|
|
2811
|
+
function placeLines(a, box, dt) {
|
|
2812
|
+
if (!lines.length) return;
|
|
2813
|
+
const W = innerWidth, size = prefs.bubbleSize, gap = LINES_GAP * size;
|
|
2814
|
+
const cx = box ? box.left + box.bw / 2 : a.x;
|
|
2815
|
+
let bottom = box ? box.top - gap : a.y - LINES_UP * size;
|
|
2816
|
+
// at low motion the stack takes its places at once
|
|
2817
|
+
const k = dt > 0 && !lowMotion() ? Math.min(1, dt * 12) : 1;
|
|
2818
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
2819
|
+
const line = lines[i], el = line.el;
|
|
2820
|
+
el.classList.toggle('older', i !== lines.length - 1);
|
|
2821
|
+
if (line.fadeAt === null || line.ox === null) {
|
|
2822
|
+
const bw = el.offsetWidth, bh = el.offsetHeight;
|
|
2823
|
+
const left = clamp(cx - bw / 2, 10, Math.max(10, W - bw - 10));
|
|
2824
|
+
const top = Math.max(8, bottom - bh);
|
|
2825
|
+
if (line.ox === null) { line.ox = left - a.x; line.oy = top - a.y; }
|
|
2826
|
+
else { line.ox += (left - a.x - line.ox) * k; line.oy += (top - a.y - line.oy) * k; }
|
|
2827
|
+
bottom = top - gap;
|
|
2828
|
+
}
|
|
2829
|
+
el.style.left = f(a.x + line.ox) + 'px';
|
|
2830
|
+
el.style.top = f(a.y + line.oy) + 'px';
|
|
2831
|
+
}
|
|
2832
|
+
}
|
|
2833
|
+
|
|
2834
|
+
/* ---------- backdrop: a light gray halo when the body melts into what is behind it ---------- */
|
|
2835
|
+
/** Seconds between looks at the screen around the body. */
|
|
2836
|
+
const BACKDROP_EVERY = .8;
|
|
2837
|
+
/** OKLab distance under which a backdrop pixel counts as the body's color. */
|
|
2838
|
+
const SAME_COLOR = .15;
|
|
2839
|
+
/** Share of such pixels around the body that turns the halo on (most of them), and the share it turns off below. */
|
|
2840
|
+
const HALO_ON = .6, HALO_OFF = .45;
|
|
2841
|
+
/** The halo's opacity when fully on. */
|
|
2842
|
+
const HALO_STRENGTH = .5;
|
|
2843
|
+
// a window host too old to sample the screen keeps the halo on; a browser tab draws its own wall
|
|
2844
|
+
const backdrop = { on: !!host && !host.sampleBackdrop, fixed: !!host && !host.sampleBackdrop, k: 0, busy: false, next: 0 };
|
|
2845
|
+
|
|
2846
|
+
const lin = (c) => (c <= .04045 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4);
|
|
2847
|
+
function oklab(r, g, b) {
|
|
2848
|
+
r = lin(r / 255); g = lin(g / 255); b = lin(b / 255);
|
|
2849
|
+
const l = Math.cbrt(.4122214708 * r + .5363325363 * g + .0514459929 * b);
|
|
2850
|
+
const m = Math.cbrt(.2119034982 * r + .6806995451 * g + .1073969566 * b);
|
|
2851
|
+
const s = Math.cbrt(.0883024619 * r + .2817188376 * g + .6299787005 * b);
|
|
2852
|
+
return [.2104542553 * l + .793617785 * m - .0040720468 * s, 1.9779984951 * l - 2.428592205 * m + .4505937099 * s, .0259040371 * l + .7827717662 * m - .808675766 * s];
|
|
2853
|
+
}
|
|
2854
|
+
/** The body's color as [r, g, b]: its palette's fixed body, else `--skin-ink` (#rgb or #rrggbb). */
|
|
2855
|
+
function inkRgb() {
|
|
2856
|
+
const fixed = skin.figure === 'coo' ? PALETTES.find((p) => p.id === skin.palette)?.fixed?.body : null;
|
|
2857
|
+
let h = (fixed ?? getComputedStyle(document.documentElement).getPropertyValue('--skin-ink')).trim().replace('#', '');
|
|
2858
|
+
if (h.length === 3) h = [...h].map((c) => c + c).join('');
|
|
2859
|
+
const n = parseInt(h, 16);
|
|
2860
|
+
return /^[0-9a-f]{6}$/i.test(h) ? [n >> 16, (n >> 8) & 255, n & 255] : null;
|
|
2861
|
+
}
|
|
2862
|
+
const inflate = (r, d) => ({ x: r.x - d, y: r.y - d, width: r.width + 2 * d, height: r.height + 2 * d });
|
|
2863
|
+
const rectOf = (el) => { const r = el.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height }; };
|
|
2864
|
+
/** An element's rect, Coo's bubble's with its close button outside it (bubbleRect). */
|
|
2865
|
+
const partRect = (el) => (el === bubble ? bubbleRect() : rectOf(el));
|
|
2866
|
+
/** A bubble's rect with its shadow (0 8px 22px) and its tail below it, none of which is the screen behind. */
|
|
2867
|
+
const shadowed = (r) => ({ x: r.x - 14, y: r.y - 14, width: r.width + 28, height: r.height + 14 + 36 });
|
|
2868
|
+
/** Modes in which the body flies or is carried: a screen copy taken now would be of where it was a moment ago. */
|
|
2869
|
+
const FLYING = new Set(['air', 'drag', 'land']);
|
|
2870
|
+
|
|
2871
|
+
/** Samples a ring around the body (past the halo's reach, minus the page's own bubbles) and flips the halo. */
|
|
2872
|
+
async function probeBackdrop() {
|
|
2873
|
+
const l = at(), ink = inkRgb(), b = l?.box;
|
|
2874
|
+
if (!ink || !b || FLYING.has(l.mode)) return;
|
|
2875
|
+
const S = bounds().S;
|
|
2876
|
+
// the ring starts past the halo, so a wide one (prefs.glow) is not taken for the screen behind
|
|
2877
|
+
const near = inflate({ x: b.x, y: b.y, width: b.w, height: b.h }, Math.max(4 + 34 * S, 4 + 2 * prefs.glow)), far = inflate(near, 8 + 40 * S);
|
|
2878
|
+
const x = Math.max(0, far.x), y = Math.max(0, far.y);
|
|
2879
|
+
const rect = { x, y, width: Math.min(innerWidth, far.x + far.width) - x, height: Math.min(innerHeight, far.y + far.height) - y };
|
|
2880
|
+
const covers = [bubble, ...(menu.hidden ? [] : menu.children), tools, wheel, ...lines.map((l) => l.el)].filter((el) => !el.hidden).map((el) => shadowed(partRect(el)));
|
|
2881
|
+
const px = await host.sampleBackdrop(rect, [near, ...covers]);
|
|
2882
|
+
// this platform cannot read the screen cheaply: the halo just stays
|
|
2883
|
+
if (px === null) { backdrop.on = true; backdrop.fixed = true; return; }
|
|
2884
|
+
const n = px.length / 3;
|
|
2885
|
+
if (n < 24) return;
|
|
2886
|
+
const [L, A, B] = oklab(...ink);
|
|
2887
|
+
let same = 0;
|
|
2888
|
+
for (let i = 0; i < px.length; i += 3) {
|
|
2889
|
+
const [l, a, b] = oklab(px[i], px[i + 1], px[i + 2]);
|
|
2890
|
+
if (Math.hypot(l - L, a - A, b - B) < SAME_COLOR) same++;
|
|
2891
|
+
}
|
|
2892
|
+
const share = same / n;
|
|
2893
|
+
// while the page's own bubbles cover part of the ring the halo may come on, but does not go off
|
|
2894
|
+
if (backdrop.on && covers.length) return;
|
|
2895
|
+
backdrop.on = backdrop.on ? share >= HALO_OFF : share > HALO_ON;
|
|
2896
|
+
}
|
|
2897
|
+
function stepBackdrop(dt) {
|
|
2898
|
+
const now = performance.now() / 1000;
|
|
2899
|
+
if (host?.sampleBackdrop && prefs.glow > 0 && !backdrop.fixed && !backdrop.busy && now >= backdrop.next && document.visibilityState === 'visible') {
|
|
2900
|
+
backdrop.busy = true;
|
|
2901
|
+
probeBackdrop().catch(() => {}).finally(() => { backdrop.busy = false; backdrop.next = performance.now() / 1000 + BACKDROP_EVERY; });
|
|
2902
|
+
}
|
|
2903
|
+
const k = backdrop.k + ((backdrop.on ? 1 : 0) - backdrop.k) * Math.min(1, dt * 6);
|
|
2904
|
+
backdrop.k = k < .005 ? 0 : k;
|
|
2905
|
+
// the body is in its own frame: it takes the halo as a CSS filter
|
|
2906
|
+
// none during a figure switch: the halo cuts the body's frame window down to its surroundings, and a window that moves
|
|
2907
|
+
// with the new body's size would move the point the switch scales it from
|
|
2908
|
+
body?.setHalo(performance.now() < haloAfter ? 0 : backdrop.k * HALO_STRENGTH, prefs.glow);
|
|
2909
|
+
}
|
|
2910
|
+
|
|
2911
|
+
/* ---------- loop ---------- */
|
|
2912
|
+
/**
|
|
2913
|
+
* Frames per second: `prefs.frameRate` while the body moves (its layout's `moving`), changes figure, look or size, and
|
|
2914
|
+
* always while `lockFrameRate` is on, RESTING_FPS otherwise; a frame rate of 0, or one above the display's, draws on every display refresh. Each frame
|
|
2915
|
+
* redraws what changed in the figure, so the window's CPU and GPU time grows with this rate.
|
|
2916
|
+
*
|
|
2917
|
+
* While the pet window is hidden, frames come at HIDDEN_FPS: the clock, the orders, the bubbles' text and the body's
|
|
2918
|
+
* motion go on, so a walk still arrives and a line still runs out, but the body is not drawn, nothing on the stage is
|
|
2919
|
+
* placed, the screen behind is not sampled and the streaming layer gets no frames.
|
|
2920
|
+
*
|
|
2921
|
+
* Each frame advances the clock by the time since the frame before, in steps (frame-loop.js); the page's orders and
|
|
2922
|
+
* the body take every step, and only the last one is drawn.
|
|
2923
|
+
*/
|
|
2924
|
+
const RESTING_FPS = 30;
|
|
2925
|
+
/** Frames a second while the window is hidden: the World hears of an arrival within a tenth of a second. */
|
|
2926
|
+
const HIDDEN_FPS = 10;
|
|
2927
|
+
/** The last error the frame loop logged, so one that keeps recurring is reported once, not per frame. */
|
|
2928
|
+
let frameErr = null;
|
|
2929
|
+
/**
|
|
2930
|
+
* Frames whose timestamp was not past the one before (no time to step), and when that was last logged (ms):
|
|
2931
|
+
* where these timestamps come from is not known yet. Logged at most once a minute, with the count so far. The first frame is
|
|
2932
|
+
* left out: the loop starts its count at the page's clock, which may be ahead of the first frame's timestamp.
|
|
2933
|
+
*/
|
|
2934
|
+
let stalls = 0, stallLoggedAt = -Infinity, framed = false;
|
|
2935
|
+
function frame(steps, now, last) {
|
|
2936
|
+
const drawn = windowShown;
|
|
2937
|
+
if (framed && now <= last) {
|
|
2938
|
+
stalls++;
|
|
2939
|
+
if (performance.now() - stallLoggedAt > 60_000) {
|
|
2940
|
+
stallLoggedAt = performance.now();
|
|
2941
|
+
console.warn(`[pet] 帧时间戳没有前进(累计 ${stalls} 次):now=${now} 上一帧=${last} 页面=${document.visibilityState} 焦点=${document.hasFocus()} 模式=${at()?.mode ?? '-'}`);
|
|
2942
|
+
}
|
|
2943
|
+
}
|
|
2944
|
+
framed = true;
|
|
2945
|
+
let activityMoving = false;
|
|
2946
|
+
try {
|
|
2947
|
+
steps.forEach((dt, i) => {
|
|
2948
|
+
T += dt;
|
|
2949
|
+
stepActs();
|
|
2950
|
+
stepDialog(dt);
|
|
2951
|
+
stepTalkRead(dt);
|
|
2952
|
+
stepTalkMotion();
|
|
2953
|
+
stepLines();
|
|
2954
|
+
stepStatus();
|
|
2955
|
+
setBody({ dialogOpen: !!item || !!listen.phase, still: !menu.hidden });
|
|
2956
|
+
let pose = null;
|
|
2957
|
+
if (host) {
|
|
2958
|
+
const figure = at();
|
|
2959
|
+
const eligible = drawn && !!body && !lowMotion() && !pressing && !figure?.pressing &&
|
|
2960
|
+
!bodyState.dialogOpen && !bodyState.still && !bodyState.thinking && !bodyState.listening && !sliding() &&
|
|
2961
|
+
!acts.length && T >= actUntil;
|
|
2962
|
+
const canCue = eligible && figure?.mode === 'idle' && !figure.busy && !figure.moving;
|
|
2963
|
+
const activity = agentSpeedMotion.step(Date.now(), dt, eligible, canCue, words, body?.words ?? null);
|
|
2964
|
+
if (activity.cue) body.do(activity.cue);
|
|
2965
|
+
if (activity.energy || activity.focus) {
|
|
2966
|
+
pose = activity;
|
|
2967
|
+
activityMoving = true;
|
|
2968
|
+
}
|
|
2969
|
+
}
|
|
2970
|
+
if (drawnScale.step(dt)) body?.set({ bounds: bounds() });
|
|
2971
|
+
body?.tick(dt, drawn && i === steps.length - 1, pose);
|
|
2972
|
+
});
|
|
2973
|
+
if (drawn) {
|
|
2974
|
+
const dt = steps.reduce((a, b) => a + b, 0);
|
|
2975
|
+
stepBackdrop(dt);
|
|
2976
|
+
stepTools();
|
|
2977
|
+
stepWheel();
|
|
2978
|
+
stepSlider();
|
|
2979
|
+
stepFade();
|
|
2980
|
+
stepLend();
|
|
2981
|
+
layout(dt);
|
|
2982
|
+
stepInputShape();
|
|
2983
|
+
// the frame's own time, so the layer shows frames as far apart as they were drawn
|
|
2984
|
+
if (overlayOn) host.overlayFrame(overlayRect(), performance.timeOrigin + now);
|
|
2985
|
+
}
|
|
2986
|
+
} catch (err) {
|
|
2987
|
+
// a throwing step must not take the loop with it: the next frame is only asked for after this returns, and
|
|
2988
|
+
// without it the pet freezes for good (a broken figure throws again on every frame it draws)
|
|
2989
|
+
const msg = err?.message ?? String(err);
|
|
2990
|
+
if (msg !== frameErr) { frameErr = msg; console.error(err); }
|
|
2991
|
+
}
|
|
2992
|
+
for (const done of afterFrame.splice(0)) done();
|
|
2993
|
+
// a switch of figure or look, or a size on its way, is motion too: at the resting rate it would show as stutter
|
|
2994
|
+
const full = drawn && (prefs.lockFrameRate || activityMoving || !!at()?.moving || (!!host && drawnScale.moving) || performance.now() < smoothUntil);
|
|
2995
|
+
// a moving rate of 0 draws on every display refresh
|
|
2996
|
+
return { fps: full ? prefs.frameRate : drawn ? RESTING_FPS : HIDDEN_FPS, refresh: full };
|
|
2997
|
+
}
|
|
2998
|
+
addEventListener('pagehide', reportPosition);
|
|
2999
|
+
// drawn frames stop while the window is hidden or occluded, which `rendering()` reads
|
|
3000
|
+
runFrames(frame, { refreshed: () => { if (windowShown) lastFrameAt = performance.now(); } });
|