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/speech.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Coo's speech: while a bubble types, each syllable is read from a voice bank the way Animal Crossing's villagers
|
|
3
|
+
* talk. It stands in for the 'talk' kind's babble and is muted with it. The bank (web/speech/, built by
|
|
4
|
+
* scripts/speech-bank/build.py) holds one pitch-flat unit per toneless Mandarin syllable; the pitch is set by
|
|
5
|
+
* playback rate alone, so a unit plays shorter as it plays higher. Which syllables a text is spoken as comes
|
|
6
|
+
* from the World (`POST /api/speech`, src/speech): every language goes through its IPA to the nearest syllable.
|
|
7
|
+
*
|
|
8
|
+
* Two clocks: the bubble reveals characters at its own pace (`reveal`), and the voice starts a unit at most
|
|
9
|
+
* `unitsPerSecond` times a second, so it falls behind the text and ends after it. After each pause mark the voice
|
|
10
|
+
* keeps a silence (VOICE_GAP) however far behind it is; behind by more than MAX_LAG it drops weak characters, by
|
|
11
|
+
* twice that anything but a phrase's last two units. Characters revealed before the World answers wait for it.
|
|
12
|
+
*
|
|
13
|
+
* Within a phrase the pitch stays within about a semitone; a stressed syllable is a semitone higher, a Mandarin
|
|
14
|
+
* one follows its tone a little, a question ends rising, an exclamation starts a semitone higher and louder.
|
|
15
|
+
*/
|
|
16
|
+
const BANK = 'zh';
|
|
17
|
+
/** Seconds the voice keeps silent after each pause mark; consecutive marks add up. */
|
|
18
|
+
export const VOICE_GAP = {
|
|
19
|
+
',': .14, ',': .14, '、': .14, ';': .2, ';': .2, ':': .2, ':': .2,
|
|
20
|
+
'.': .45, '。': .45, '!': .5, '!': .5, '?': .5, '?': .5, '…': .3, '~': .1, '~': .1,
|
|
21
|
+
};
|
|
22
|
+
/** While speech is on, how long the bubble waits after each pause mark, in typing steps (1/20 s). */
|
|
23
|
+
export const TEXT_PAUSE = {
|
|
24
|
+
',': 5, ',': 5, '、': 5, ';': 6, ';': 6, ':': 6, ':': 6,
|
|
25
|
+
'.': 9, '。': 9, '!': 9, '!': 9, '?': 9, '?': 9, '…': 4, '~': 3, '~': 3,
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* While speech is on, the typing steps one character takes. A letter of an alphabet (and a space or apostrophe)
|
|
29
|
+
* takes LETTER_STEP: three or four of them make one syllable, where a Han character, kana or Hangul block is one,
|
|
30
|
+
* so letters type faster for the voice to keep its pace, as Animal Crossing's English text does (45-70 letters
|
|
31
|
+
* against 13-14 syllables a second).
|
|
32
|
+
*/
|
|
33
|
+
const LETTER_STEP = .4;
|
|
34
|
+
const ALPHABET = /[\p{Script=Latin}\p{Script=Cyrillic}\p{Script=Greek}\s'’-]/u;
|
|
35
|
+
export function textSteps(ch) {
|
|
36
|
+
return TEXT_PAUSE[ch] ?? (ALPHABET.test(ch) ? LETTER_STEP : 1);
|
|
37
|
+
}
|
|
38
|
+
/** Seconds behind the text past which the voice drops weak characters (twice this: any but a phrase's last two). */
|
|
39
|
+
export const MAX_LAG = 1;
|
|
40
|
+
/** Each tone as semitones over the unit, scaled by TONE_AMOUNT; 5 is the neutral tone. */
|
|
41
|
+
const TONES = { 1: [.8, .8], 2: [-.6, 1.6], 3: [-1, -1.8, -.6], 4: [1.6, -1.2], 5: [-.8, -.8] };
|
|
42
|
+
const TONE_AMOUNT = .35;
|
|
43
|
+
const STRESS_ST = 1;
|
|
44
|
+
const GAIN = .45;
|
|
45
|
+
|
|
46
|
+
/* ---------- the voice clock ---------- */
|
|
47
|
+
|
|
48
|
+
/** When the voice starts each unit, in seconds on one clock; `now` is when the text revealed it. */
|
|
49
|
+
export class VoiceClock {
|
|
50
|
+
constructor() { this.reset(0); }
|
|
51
|
+
reset(now) { this.last = -Infinity; this.end = now; this.free = now; this.gap = 0; }
|
|
52
|
+
/** A pause mark revealed: the next unit starts no sooner than this mark's silence after the voice ends. */
|
|
53
|
+
mark(ch) { this.gap += VOICE_GAP[ch] ?? 0; this.free = this.end + this.gap; }
|
|
54
|
+
/** The start of a unit `len` seconds long, or null to drop it; `final` = among its phrase's last two. */
|
|
55
|
+
place(now, { weak, final }, unitsPerSecond, len) {
|
|
56
|
+
const t = Math.max(now, this.last + 1 / unitsPerSecond, this.free);
|
|
57
|
+
const lag = t - now;
|
|
58
|
+
if (!final && (lag > 2 * MAX_LAG || (lag > MAX_LAG && weak))) return null;
|
|
59
|
+
this.last = t; this.end = Math.max(this.end, t + len); this.gap = 0;
|
|
60
|
+
return t;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/* ---------- playback ---------- */
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* `sfx` (sound.js) gives the audio output; `onUnit` runs as each unit starts; `base`: where the bank is;
|
|
68
|
+
* `unitsOf(text)`: the units the World gives for `text`.
|
|
69
|
+
*/
|
|
70
|
+
export function createSpeech(sfx, {
|
|
71
|
+
base = new URL('speech/', import.meta.url).href,
|
|
72
|
+
onUnit = () => {},
|
|
73
|
+
unitsOf = (text) => fetch('/api/speech', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text }) })
|
|
74
|
+
.then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))).then((d) => d.units),
|
|
75
|
+
} = {}) {
|
|
76
|
+
let on = false, hz = 400, ups = 13;
|
|
77
|
+
/** The bank once fetched: manifest and encoded audio; `buffer` once decoded. */
|
|
78
|
+
let bank = null, fetching = null, decoding = null;
|
|
79
|
+
/** The text being typed, its units by the index that starts them once the World answered, and reveals waiting for that. */
|
|
80
|
+
let text = '', byAt = null, waiting = [], rnd = 1;
|
|
81
|
+
const clock = new VoiceClock();
|
|
82
|
+
const playing = new Set(), timers = new Set();
|
|
83
|
+
|
|
84
|
+
function fetchBank() {
|
|
85
|
+
const get = (name, how) => fetch(new URL(name, new URL(base, location.href))).then((r) => (r.ok ? r[how]() : Promise.reject(new Error(`HTTP ${r.status}`))));
|
|
86
|
+
fetching ??= Promise.all([get(`${BANK}.json`, 'json'), get(`${BANK}.ogg`, 'arrayBuffer')]).then(([manifest, bytes]) => {
|
|
87
|
+
bank = { hz: manifest.hz, units: new Map(Object.entries(manifest.units)), bytes, buffer: null };
|
|
88
|
+
}, (err) => { console.error('说话声没能载入:', err); });
|
|
89
|
+
return fetching;
|
|
90
|
+
}
|
|
91
|
+
/** The output and the decoded bank, or null while speech would not be heard (then the caller babbles). */
|
|
92
|
+
function ready() {
|
|
93
|
+
if (!on) return null;
|
|
94
|
+
if (!bank) { void fetchBank(); return null; }
|
|
95
|
+
const out = sfx.output('talk');
|
|
96
|
+
if (!out) return null;
|
|
97
|
+
if (!bank.buffer) {
|
|
98
|
+
decoding ??= out.ctx.decodeAudioData(bank.bytes.slice(0)).then((b) => { bank.buffer = b; }, (err) => console.error('说话声没能解码:', err));
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
const random = () => { rnd = (rnd * 16807) % 2147483647; return rnd / 2147483647; };
|
|
104
|
+
|
|
105
|
+
function play(out, u, t) {
|
|
106
|
+
const [off, len] = bank.units.get(u.key);
|
|
107
|
+
const { ctx, master } = out;
|
|
108
|
+
const rate = hz / bank.hz;
|
|
109
|
+
// the phrase's line: a step up at its start, a slow fall, a rise at a question's end
|
|
110
|
+
const q = /[??]/.test(u.end), ex = /[!!]/.test(u.end), last = u.pos === u.of - 1;
|
|
111
|
+
let st = (u.pos === 0 ? .8 : 0) - .06 * u.pos + (random() - .5) * .4 + (ex ? 1 : 0) + (u.stress ? STRESS_ST : 0);
|
|
112
|
+
let bend = 0;
|
|
113
|
+
if (q && u.pos === u.of - 2) st += 1.5;
|
|
114
|
+
if (q && last) { st += 2; bend = 3; }
|
|
115
|
+
if (/…/.test(u.end) && last) st -= .8;
|
|
116
|
+
const tone = u.tone ? TONES[u.tone] : [0, 0];
|
|
117
|
+
const curve = new Float32Array(8);
|
|
118
|
+
for (let k = 0; k < 8; k++) {
|
|
119
|
+
const p = k / 7, x = p * (tone.length - 1), a = Math.floor(x), b = Math.min(tone.length - 1, a + 1);
|
|
120
|
+
const ts = (tone[a] + (tone[b] - tone[a]) * (x - a)) * TONE_AMOUNT;
|
|
121
|
+
curve[k] = rate * 2 ** ((st + ts + bend * p) / 12);
|
|
122
|
+
}
|
|
123
|
+
const src = ctx.createBufferSource(), g = ctx.createGain();
|
|
124
|
+
src.buffer = bank.buffer;
|
|
125
|
+
src.playbackRate.setValueCurveAtTime(curve, t, len / rate);
|
|
126
|
+
g.gain.value = GAIN * (ex ? 1.26 : 1);
|
|
127
|
+
src.connect(g); g.connect(master);
|
|
128
|
+
src.start(t, off, len);
|
|
129
|
+
playing.add(src);
|
|
130
|
+
src.onended = () => playing.delete(src);
|
|
131
|
+
const timer = setTimeout(() => { timers.delete(timer); onUnit(); }, Math.max(0, (t - ctx.currentTime) * 1000));
|
|
132
|
+
timers.add(timer);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
let asked = false;
|
|
136
|
+
/** Asks the World for the units of the text being typed; the reveals waiting meanwhile are spoken once they come. */
|
|
137
|
+
function ask() {
|
|
138
|
+
if (asked || !text) return;
|
|
139
|
+
asked = true;
|
|
140
|
+
const t = text;
|
|
141
|
+
unitsOf(t).then((units) => {
|
|
142
|
+
if (text !== t) return;
|
|
143
|
+
byAt = new Map();
|
|
144
|
+
for (const u of units) { if (!byAt.has(u.at)) byAt.set(u.at, []); byAt.get(u.at).push(u); }
|
|
145
|
+
const out = ready();
|
|
146
|
+
if (out) for (const i of waiting) speak(out, i);
|
|
147
|
+
waiting = [];
|
|
148
|
+
}, (err) => { console.error('说话声没能拆成音节:', err); if (text === t) { byAt = new Map(); waiting = []; } });
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Character `i` reaches the voice: its pause mark, then the units it starts. */
|
|
152
|
+
function speak(out, i) {
|
|
153
|
+
const ch = text[i];
|
|
154
|
+
if (VOICE_GAP[ch] !== undefined) clock.mark(ch);
|
|
155
|
+
const now = out.ctx.currentTime + .02;
|
|
156
|
+
if (clock.end < now - 2) clock.reset(now);
|
|
157
|
+
for (const u of byAt.get(i) ?? []) {
|
|
158
|
+
if (!bank.units.has(u.key)) continue;
|
|
159
|
+
const len = bank.units.get(u.key)[1] / (hz / bank.hz);
|
|
160
|
+
const t = clock.place(now, { weak: u.weak, final: u.pos >= u.of - 2 }, ups, len);
|
|
161
|
+
if (t !== null) play(out, u, t);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return {
|
|
166
|
+
/** `enabled`; `pitchHz`: the voice's pitch; `unitsPerSecond`: most units started a second. */
|
|
167
|
+
configure({ enabled, pitchHz, unitsPerSecond } = {}) {
|
|
168
|
+
if (typeof enabled === 'boolean') { on = enabled; if (on) void fetchBank(); else this.stop(); }
|
|
169
|
+
if (typeof pitchHz === 'number' && pitchHz > 0) hz = pitchHz;
|
|
170
|
+
if (typeof unitsPerSecond === 'number' && unitsPerSecond > 0) ups = unitsPerSecond;
|
|
171
|
+
},
|
|
172
|
+
/** Whether the bubble types with speech's pauses and leaves the sound to it. */
|
|
173
|
+
get active() { return Boolean(ready()); },
|
|
174
|
+
/** The bubble starts typing `t`: while speech is on, its units are asked for now, else at its first reveal. */
|
|
175
|
+
begin(t) {
|
|
176
|
+
if (t === text) return;
|
|
177
|
+
text = t; byAt = null; waiting = []; asked = false;
|
|
178
|
+
if (on) ask();
|
|
179
|
+
},
|
|
180
|
+
/** Character `i` of the text just appeared; false = speech cannot play now, babble instead. */
|
|
181
|
+
reveal(i) {
|
|
182
|
+
const out = ready();
|
|
183
|
+
if (!out) return false;
|
|
184
|
+
if (byAt) speak(out, i); else { waiting.push(i); ask(); }
|
|
185
|
+
return true;
|
|
186
|
+
},
|
|
187
|
+
/** Stops what is playing and what waits to play. */
|
|
188
|
+
stop() {
|
|
189
|
+
for (const s of playing) { try { s.stop(); } catch { /* not started */ } }
|
|
190
|
+
playing.clear();
|
|
191
|
+
for (const t of timers) clearTimeout(t);
|
|
192
|
+
timers.clear();
|
|
193
|
+
clock.reset(0);
|
|
194
|
+
text = ''; byAt = null; waiting = []; asked = false;
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
package/web/stage.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The stage the pet stands on outside the desktop: the pet page in a browser tab (the settings window's
|
|
3
|
+
* preview) and the dressing page's preview. The dotted wall answers the pointer (a soft light follows it,
|
|
4
|
+
* the dots under it grow and take the pet's eye color; pet.css `.wall`), the floor carries a row of
|
|
5
|
+
* taskbar-like icons, and a round button at the top left switches the pet between night and day
|
|
6
|
+
* (`POST /api/prefs`, as the dressing page saves it).
|
|
7
|
+
*/
|
|
8
|
+
import { applyTheme } from './ui.js';
|
|
9
|
+
import { motionLevel } from './motion-level.js';
|
|
10
|
+
import { approachShare } from './motion-frames.js';
|
|
11
|
+
|
|
12
|
+
const line = (d) => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${d}</svg>`;
|
|
13
|
+
/** Decoration only: what a taskbar usually holds. */
|
|
14
|
+
const DOCK = [
|
|
15
|
+
'<rect x="4" y="4" width="7" height="7" rx="1.5"/><rect x="13" y="4" width="7" height="7" rx="1.5"/><rect x="4" y="13" width="7" height="7" rx="1.5"/><rect x="13" y="13" width="7" height="7" rx="1.5"/>',
|
|
16
|
+
'<path d="M3.5 7.5a2 2 0 0 1 2-2h3.8l2 2h7.2a2 2 0 0 1 2 2v7.5a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2z"/>',
|
|
17
|
+
'<circle cx="12" cy="12" r="8.5"/><path d="M3.5 12h17M12 3.5c2.4 2.3 3.5 5.2 3.5 8.5s-1.1 6.2-3.5 8.5c-2.4-2.3-3.5-5.2-3.5-8.5s1.1-6.2 3.5-8.5z"/>',
|
|
18
|
+
'<rect x="3.5" y="5.5" width="17" height="13" rx="2"/><path d="m4 7 8 6 8-6"/>',
|
|
19
|
+
'<path d="M9 17.5V6.5l10-2v11"/><circle cx="6.5" cy="17.5" r="2.5"/><circle cx="16.5" cy="15.5" r="2.5"/>',
|
|
20
|
+
'<rect x="3.5" y="4.5" width="17" height="12" rx="2"/><path d="M8.5 20h7M12 16.5V20"/>',
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
/** Radii of the light and of the lens that shows the grown dots, in pixels (pet.css sizes them the same). */
|
|
24
|
+
const GLOW = 280, LENS = 150;
|
|
25
|
+
/** How fast the light closes on the pointer, per second: .18 of the way each frame at 60 frames a second, on any display. */
|
|
26
|
+
const EASE_RATE = 12;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Lights the wall `wall` under the pointer: a soft light and a round lens of bigger dots in the body's color (setGlow) follow it
|
|
30
|
+
* (pet.css `.wall-glow`, `.wall-lens`). Both are layers of their own moved by `transform` only, eased frame by
|
|
31
|
+
* frame, so the browser composites them instead of repainting the wall (and the pet on it) as the pointer moves.
|
|
32
|
+
* The lens holds a dot grid moved the other way, so its dots stay on the wall's own dots. `area` takes the pointer
|
|
33
|
+
* (the stage, which lies over the wall).
|
|
34
|
+
*/
|
|
35
|
+
export function lightWall(wall, area = wall) {
|
|
36
|
+
wall.classList.add('wall');
|
|
37
|
+
const layer = (cls) => { const e = document.createElement('div'); e.className = cls; e.setAttribute('aria-hidden', 'true'); return e; };
|
|
38
|
+
const glow = layer('wall-glow'), lens = layer('wall-lens'), grid = layer('wall-lens-grid');
|
|
39
|
+
lens.append(grid);
|
|
40
|
+
wall.prepend(glow, lens);
|
|
41
|
+
let x = 0, y = 0, tx = 0, ty = 0, lit = false, frame = 0, last = 0;
|
|
42
|
+
const place = () => {
|
|
43
|
+
glow.style.transform = `translate3d(${x - GLOW}px, ${y - GLOW}px, 0)`;
|
|
44
|
+
lens.style.transform = `translate3d(${x - LENS}px, ${y - LENS}px, 0)`;
|
|
45
|
+
grid.style.transform = `translate3d(${LENS - x}px, ${LENS - y}px, 0)`;
|
|
46
|
+
};
|
|
47
|
+
const step = (now) => {
|
|
48
|
+
const k = approachShare(EASE_RATE, (now - last) / 1000);
|
|
49
|
+
last = now;
|
|
50
|
+
x += (tx - x) * k; y += (ty - y) * k;
|
|
51
|
+
if (Math.abs(tx - x) + Math.abs(ty - y) < .3) { x = tx; y = ty; frame = 0; } else frame = requestAnimationFrame(step);
|
|
52
|
+
place();
|
|
53
|
+
};
|
|
54
|
+
area.addEventListener('pointermove', (e) => {
|
|
55
|
+
// the light that follows the pointer is decoration: full motion only
|
|
56
|
+
if (motionLevel(window) !== 'high') { if (lit) { lit = false; wall.classList.remove('wall-lit'); } return; }
|
|
57
|
+
const r = wall.getBoundingClientRect();
|
|
58
|
+
tx = e.clientX - r.left; ty = e.clientY - r.top;
|
|
59
|
+
// coming in, the light starts where the pointer is instead of sliding over from where it left
|
|
60
|
+
if (!lit) { x = tx; y = ty; place(); lit = true; wall.classList.add('wall-lit'); }
|
|
61
|
+
if (!frame) { last = performance.now(); frame = requestAnimationFrame(step); }
|
|
62
|
+
});
|
|
63
|
+
area.addEventListener('pointerleave', () => { lit = false; wall.classList.remove('wall-lit'); });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The light's color for the body on the stage (`pack` as /api/figures lists it, `skin` the pet's skin): Coo's eye
|
|
68
|
+
* color; another pack's accent for the picked colors (its preset's, else the first picked option's that names one);
|
|
69
|
+
* null when the pack names none, and the light takes the settings window's theme color (pet.css `--glow`).
|
|
70
|
+
*/
|
|
71
|
+
export function glowColor(pack, skin) {
|
|
72
|
+
if (!pack || pack.id === 'coo') return 'var(--skin-eye)';
|
|
73
|
+
const scheme = skin?.scheme || pack.presets?.[0]?.id || '';
|
|
74
|
+
const hex = (c) => (typeof c === 'string' && /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(c) ? c : null);
|
|
75
|
+
const preset = (pack.presets ?? []).find((p) => p.id === scheme);
|
|
76
|
+
if (hex(preset?.accent)) return preset.accent;
|
|
77
|
+
// the scheme names one option per axis, in the axes' order
|
|
78
|
+
const parts = scheme.split('-');
|
|
79
|
+
for (const [i, axis] of (pack.axes ?? []).entries()) {
|
|
80
|
+
const option = (axis.options ?? []).find((o) => o.id === parts[i]);
|
|
81
|
+
if (hex(option?.accent)) return option.accent;
|
|
82
|
+
}
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The page's theme color (`--skin-eye`: the bubble's picked cards, step dots and marks) for another pack's body: its
|
|
88
|
+
* preset's settings-window color, light and dark, else its accent for both; null for Coo, whose palette sets it.
|
|
89
|
+
*/
|
|
90
|
+
export function accentColors(pack, skin) {
|
|
91
|
+
if (!pack || pack.id === 'coo') return null;
|
|
92
|
+
const preset = (pack.presets ?? []).find((p) => p.id === (skin?.scheme || pack.presets?.[0]?.id));
|
|
93
|
+
const light = preset?.console?.light?.a, dark = preset?.console?.dark?.a;
|
|
94
|
+
if (light && dark) return { light, dark };
|
|
95
|
+
const one = glowColor(pack, skin);
|
|
96
|
+
return one ? { light: one, dark: one } : null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The style that colours the bot's bubbles for the body on the stage: its preset's `bubble` colours, else its pack's
|
|
101
|
+
* (src/packs.ts); '' for a pack that names none. The person's own lines (`.heard`) keep the page's colours.
|
|
102
|
+
*/
|
|
103
|
+
export function bubbleCss(pack, skin) {
|
|
104
|
+
if (!pack) return '';
|
|
105
|
+
const preset = (pack.presets ?? []).find((p) => p.id === (skin?.scheme || pack.presets?.[0]?.id));
|
|
106
|
+
const b = preset?.bubble ?? pack.bubble;
|
|
107
|
+
if (!b?.light || !b?.dark) return '';
|
|
108
|
+
const vars = (c) => `--surface:${c.fill};--text:${c.text};--skin-ink:${c.line}`;
|
|
109
|
+
const sel = 'html:root .bubble:not(.heard)';
|
|
110
|
+
return `${sel}{${vars(b.light)}}@media (prefers-color-scheme: dark){html:root:not([data-theme="light"]) .bubble:not(.heard){${vars(b.dark)}}}html:root[data-theme="dark"] .bubble:not(.heard){${vars(b.dark)}}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Colors the light on `wall` (glowColor's answer). */
|
|
114
|
+
export function setGlow(wall, color) {
|
|
115
|
+
if (color) wall.style.setProperty('--glow', color);
|
|
116
|
+
else wall.style.removeProperty('--glow');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Fills `floor` with the row of icons, centred. */
|
|
120
|
+
export function dressFloor(floor) {
|
|
121
|
+
const row = document.createElement('div');
|
|
122
|
+
row.className = 'floor-icons';
|
|
123
|
+
row.setAttribute('aria-hidden', 'true');
|
|
124
|
+
row.innerHTML = DOCK.map(line).join('');
|
|
125
|
+
floor.append(row);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The night/day button, top left of `parent`. `getTheme` gives the pet's theme now; `onSwitch` hears the
|
|
130
|
+
* new one at once. The switch is saved through the pet's server (or by `save`, when given), whose answer
|
|
131
|
+
* comes back as prefs: `show(theme)` redraws the button then. `draw` puts the theme on the button (by
|
|
132
|
+
* default on the whole page too, ui.js applyTheme; the dressing page passes themeButton and themes only its preview).
|
|
133
|
+
*/
|
|
134
|
+
export function modeButton(parent, getTheme, onSwitch, save = (theme) => fetch('/api/prefs', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ theme }) }).catch(() => {}), draw = applyTheme) {
|
|
135
|
+
const b = document.createElement('button');
|
|
136
|
+
b.type = 'button';
|
|
137
|
+
b.className = 'stage-mode';
|
|
138
|
+
b.addEventListener('pointerdown', (e) => e.stopPropagation());
|
|
139
|
+
b.addEventListener('click', (e) => {
|
|
140
|
+
e.stopPropagation();
|
|
141
|
+
const theme = getTheme() === 'dark' ? 'light' : 'dark';
|
|
142
|
+
show(theme);
|
|
143
|
+
onSwitch?.(theme);
|
|
144
|
+
save(theme);
|
|
145
|
+
});
|
|
146
|
+
const show = (theme) => draw(theme, b);
|
|
147
|
+
show(getTheme());
|
|
148
|
+
parent.append(b);
|
|
149
|
+
return { el: b, show };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Tells the settings window embedding this page that it has drawn itself in its own colors (`companion:painted`),
|
|
154
|
+
* two frames after the call: the window keeps the frame hidden until then, so it does not flash the browser's
|
|
155
|
+
* default white or the page's starting theme. The message carries nothing, so any origin may read it.
|
|
156
|
+
*/
|
|
157
|
+
export function announcePainted() {
|
|
158
|
+
if (window.parent === window) return;
|
|
159
|
+
requestAnimationFrame(() => requestAnimationFrame(() => window.parent.postMessage({ type: 'companion:painted' }, '*')));
|
|
160
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a body changes on a stage, shared by the pet window and the dressing page's preview:
|
|
3
|
+
* - another figure: the old body fades out as the new one fades in (`swapOut`, disposed after it, and `swapIn`), both
|
|
4
|
+
* on one course of sizes with a small dip; put on at another size (`ratio`, the new size over the old), that course
|
|
5
|
+
* runs from the old size to the new, so the size and the figure change in one movement;
|
|
6
|
+
* - another look of the same figure: the body dips and rises once (`restyle`);
|
|
7
|
+
* - a new size: the drawn size follows the asked one on a spring (`springSize`) instead of jumping.
|
|
8
|
+
*
|
|
9
|
+
* The body's frame window (body-host.js `el`) is animated with the Web Animations API: its inline style belongs to the
|
|
10
|
+
* halo (body-host.js setHalo), which rewrites it every frame. At low motion (motion-level.js) nothing moves: the change is immediate.
|
|
11
|
+
*
|
|
12
|
+
* A figure switch starts WARM_MS late: the new body, hidden meanwhile, draws its first frames (its textures, its first
|
|
13
|
+
* layout) before it is shown, so that work does not fall on the fade's frames. SWAP_MS is how long a switch takes in all,
|
|
14
|
+
* for a page that draws fewer frames at rest to draw every one meanwhile.
|
|
15
|
+
*/
|
|
16
|
+
import { motionLevel } from './motion-level.js';
|
|
17
|
+
/** How long the new body draws hidden before the switch shows it, and the whole switch, in milliseconds. */
|
|
18
|
+
const WARM_MS = 90, SWAP_RUN_MS = 340;
|
|
19
|
+
/** The whole switch, with a frame's margin for the last frames to land. */
|
|
20
|
+
export const SWAP_MS = WARM_MS + SWAP_RUN_MS + 40;
|
|
21
|
+
|
|
22
|
+
const still = (win) => motionLevel(win) === 'low';
|
|
23
|
+
|
|
24
|
+
/** The point `p` (stage pixels) as a transform origin inside `el`, whose box may be a cut-down window of the stage. */
|
|
25
|
+
function originIn(el, p, stage) {
|
|
26
|
+
const r = el.getBoundingClientRect(), s = stage.getBoundingClientRect();
|
|
27
|
+
return `${p.x - (r.left - s.left)}px ${p.y - (r.top - s.top)}px`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Where a body stands: its feet, the bottom middle of its box. */
|
|
31
|
+
function feet(l) { return { x: l.box.x + l.box.w / 2, y: l.box.y + l.box.h }; }
|
|
32
|
+
|
|
33
|
+
/** A size ratio as the switch draws it: past these bounds the bodies would cover the screen or vanish mid-fade. */
|
|
34
|
+
const drawnRatio = (ratio) => Math.min(4, Math.max(.25, ratio));
|
|
35
|
+
|
|
36
|
+
/** When in the switch each step of its course falls, and the opacities of the body going and the body coming there. */
|
|
37
|
+
const OFFSETS = [0, .55, .85, 1], OUT_OPACITY = [1, .35, 0, 0], IN_OPACITY = [0, .65, 1, 1];
|
|
38
|
+
/** A small dip and rise over the course, so a switch at one size still moves. */
|
|
39
|
+
const DIP = [1, .97, 1.015, 1];
|
|
40
|
+
const SWAP_EASE = 'ease-in-out';
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The switch's course of sizes in the old body's units: from 1 to `r`, most of the way by the middle. The old body is drawn
|
|
44
|
+
* at it and the new one, drawn at its own size, at it over `r`, so both show the same size at every moment.
|
|
45
|
+
*/
|
|
46
|
+
function course(el, l, stage, ratio, of, opacity) {
|
|
47
|
+
const r = drawnRatio(ratio), transformOrigin = originIn(el, feet(l), stage);
|
|
48
|
+
const sizes = [1, r ** .75, r, r];
|
|
49
|
+
return OFFSETS.map((offset, i) => ({ offset, opacity: opacity[i], transformOrigin, transform: `scale(${(sizes[i] * DIP[i] / of(r)).toFixed(4)})` }));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Fades `body` out along the switch's course, then disposes of it. Its halo goes at once: two blurred halos drawn over
|
|
54
|
+
* each other for the length of the fade cost more than the fade.
|
|
55
|
+
*/
|
|
56
|
+
export function swapOut(body, stage, ratio = 1) {
|
|
57
|
+
const el = body?.el, l = body?.layout;
|
|
58
|
+
if (!el || !l || still(stage.ownerDocument.defaultView)) { body?.dispose(); return; }
|
|
59
|
+
body.setHalo(0, 0);
|
|
60
|
+
const frames = course(el, l, stage, ratio, () => 1, OUT_OPACITY);
|
|
61
|
+
// a body still fading in from a switch a moment ago fades out from where it is, not from fully shown
|
|
62
|
+
const running = el.getAnimations?.() ?? [];
|
|
63
|
+
if (running.length) {
|
|
64
|
+
const now = getComputedStyle(el);
|
|
65
|
+
frames[0] = { ...frames[0], opacity: Number(now.opacity), transform: now.transform === 'none' ? frames[0].transform : now.transform };
|
|
66
|
+
for (const a of running) a.cancel();
|
|
67
|
+
}
|
|
68
|
+
const a = el.animate(frames, { duration: SWAP_RUN_MS, delay: WARM_MS, easing: SWAP_EASE, fill: 'forwards' });
|
|
69
|
+
a.finished.then(() => body.dispose(), () => body.dispose());
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Fades `body` in along the switch's course, after WARM_MS hidden; `l` is where it stands when it has not said yet.
|
|
74
|
+
*/
|
|
75
|
+
export function swapIn(body, stage, l = body?.layout, ratio = 1) {
|
|
76
|
+
const el = body?.el;
|
|
77
|
+
if (!el || !l || still(stage.ownerDocument.defaultView)) return;
|
|
78
|
+
el.animate(course(el, l, stage, ratio, (r) => r, IN_OPACITY), { duration: SWAP_RUN_MS, delay: WARM_MS, easing: SWAP_EASE, fill: 'backwards' });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A dip toward the feet and back: the same figure in another look; RESTYLE_MS long. */
|
|
82
|
+
export const RESTYLE_MS = 280;
|
|
83
|
+
export function restyle(body, stage) {
|
|
84
|
+
const el = body?.el, l = body?.layout;
|
|
85
|
+
if (!el || !l || still(stage.ownerDocument.defaultView)) return;
|
|
86
|
+
const transformOrigin = originIn(el, feet(l), stage);
|
|
87
|
+
el.animate([
|
|
88
|
+
{ transform: 'scale(1)', transformOrigin },
|
|
89
|
+
{ transform: 'scale(1.03, .96)', transformOrigin, offset: .35 },
|
|
90
|
+
{ transform: 'scale(1)', transformOrigin },
|
|
91
|
+
], { duration: RESTYLE_MS, easing: 'ease-out' });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* A size that follows the one asked for on a slightly underdamped spring, so a large change overshoots a little and
|
|
96
|
+
* settles in about a third of a second; `step(dt)` advances it and says whether it moved.
|
|
97
|
+
*/
|
|
98
|
+
export function springSize(start) {
|
|
99
|
+
let x = start, v = 0, to = start;
|
|
100
|
+
// a little under critical damping, so it overshoots a touch; below full motion it lands without overshooting
|
|
101
|
+
const K = 260, C = () => 2 * Math.sqrt(K) * (motionLevel(globalThis.window) === 'high' ? .78 : 1);
|
|
102
|
+
return {
|
|
103
|
+
get value() { return x; },
|
|
104
|
+
get target() { return to; },
|
|
105
|
+
/** Whether it is still on its way. */
|
|
106
|
+
get moving() { return x !== to || v !== 0; },
|
|
107
|
+
set(next) { to = next; },
|
|
108
|
+
/** Puts it at `next` at once. */
|
|
109
|
+
jump(next) { x = to = next; v = 0; },
|
|
110
|
+
step(dt) {
|
|
111
|
+
if (x === to && v === 0) return false;
|
|
112
|
+
const h = Math.min(dt, 1 / 30);
|
|
113
|
+
v += (K * (to - x) - C() * v) * h;
|
|
114
|
+
x += v * h;
|
|
115
|
+
if (Math.abs(to - x) < .0015 && Math.abs(v) < .02) { x = to; v = 0; }
|
|
116
|
+
return true;
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
}
|