@peerbots/face 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +30 -2
  2. package/dist/VizijFaceView-3fvAa51G.d.ts +57 -0
  3. package/dist/chunk-AT25NYX2.js +211 -0
  4. package/dist/chunk-AT25NYX2.js.map +1 -0
  5. package/dist/chunk-T7QJ6B66.js +1475 -0
  6. package/dist/chunk-T7QJ6B66.js.map +1 -0
  7. package/dist/chunk-XHICGN32.js +62 -0
  8. package/dist/chunk-XHICGN32.js.map +1 -0
  9. package/dist/index.cjs +4353 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.ts +525 -0
  12. package/dist/index.js +1408 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/pixi.cjs +2403 -0
  15. package/dist/pixi.cjs.map +1 -0
  16. package/dist/pixi.d.ts +9 -0
  17. package/dist/pixi.js +882 -0
  18. package/dist/pixi.js.map +1 -0
  19. package/dist/vizij.cjs +1546 -0
  20. package/dist/vizij.cjs.map +1 -0
  21. package/dist/vizij.d.ts +2 -0
  22. package/dist/vizij.js +193 -0
  23. package/dist/vizij.js.map +1 -0
  24. package/package.json +114 -4
  25. package/public/FaceAssets/Hugo/cheek.png +0 -0
  26. package/public/FaceAssets/Hugo/concerned_l.png +0 -0
  27. package/public/FaceAssets/Hugo/concerned_r.png +0 -0
  28. package/public/FaceAssets/Hugo/happy_l.png +0 -0
  29. package/public/FaceAssets/Hugo/happy_r.png +0 -0
  30. package/public/FaceAssets/Hugo/hugo_spritesheet.json +97 -0
  31. package/public/FaceAssets/Hugo/hugo_spritesheet.png +0 -0
  32. package/public/FaceAssets/Hugo/neutral_l.png +0 -0
  33. package/public/FaceAssets/Hugo/neutral_r.png +0 -0
  34. package/public/FaceAssets/Hugo/sad_l.png +0 -0
  35. package/public/FaceAssets/Hugo/sad_r.png +0 -0
  36. package/public/FaceAssets/Hugo/sleepy_l.png +0 -0
  37. package/public/FaceAssets/Hugo/sleepy_r.png +0 -0
  38. package/public/FaceAssets/Hugo/surprised_l.png +0 -0
  39. package/public/FaceAssets/Hugo/surprised_r.png +0 -0
  40. package/public/FaceAssets/Icons/Concerned.png +0 -0
  41. package/public/FaceAssets/Icons/Neutral.png +0 -0
  42. package/public/FaceAssets/Icons/Sad.png +0 -0
  43. package/public/FaceAssets/Icons/Sleep.png +0 -0
  44. package/public/FaceAssets/Icons/Surprised.png +0 -0
  45. package/public/FaceAssets/Misty/misty_spritesheet.json +97 -0
  46. package/public/FaceAssets/Misty/misty_spritesheet.png +0 -0
  47. package/public/FaceAssets/Robotic/robotic_spritesheet.json +97 -0
  48. package/public/FaceAssets/Robotic/robotic_spritesheet.png +0 -0
  49. package/public/FaceAssets/Vizij/Hugo.glb +0 -0
  50. package/public/FaceAssets/Vizij/brand.svg +15 -0
package/dist/pixi.cjs ADDED
@@ -0,0 +1,2403 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/components/PixiFaceView.tsx
21
+ var PixiFaceView_exports = {};
22
+ __export(PixiFaceView_exports, {
23
+ PixiFaceView: () => PixiFaceView,
24
+ default: () => PixiFaceView_default
25
+ });
26
+ module.exports = __toCommonJS(PixiFaceView_exports);
27
+ var import_react17 = require("react");
28
+ var import_react18 = require("@pixi/react");
29
+ var import_pixi8 = require("pixi.js");
30
+
31
+ // src/store/FaceStoreContext.tsx
32
+ var import_react = require("react");
33
+ var import_zustand2 = require("zustand");
34
+
35
+ // src/store/createPeerbotsFaceStore.ts
36
+ var import_zustand = require("zustand");
37
+ var import_middleware = require("zustand/middleware");
38
+
39
+ // src/types/face.ts
40
+ var DEFAULT_FACE_MESSAGE = {
41
+ title: "Ready",
42
+ speech: "",
43
+ color: "Light Blue",
44
+ emotion: "Neutral"
45
+ };
46
+ var defaultFaceSettings = {
47
+ zoom: 1,
48
+ offset: { x: 0, y: 0 },
49
+ rotation: 0,
50
+ autoRotate: true,
51
+ showFullScreenButton: true,
52
+ showScrollButton: true,
53
+ amplitudeGain: 1,
54
+ vizijSettings: {
55
+ faceExpressivity: 1
56
+ },
57
+ pixiSettings: {
58
+ eyeDisplay: "default",
59
+ mouthDisplay: "default",
60
+ cheekDisplay: "default",
61
+ emotionDisplay: "emoticon"
62
+ },
63
+ selectedLanguage: "English",
64
+ speechQueueMode: "interrupt",
65
+ captions: {
66
+ enabled: false,
67
+ fontSize: 32,
68
+ offset: { x: 0, y: 0 }
69
+ }
70
+ };
71
+ function normalizeAssetBaseUrl(assetBaseUrl = "/FaceAssets") {
72
+ const trimmed = assetBaseUrl.trim();
73
+ if (!trimmed) {
74
+ return "/FaceAssets";
75
+ }
76
+ return trimmed.endsWith("/") ? trimmed.slice(0, -1) : trimmed;
77
+ }
78
+ function createBuiltInPixiFaces(assetBaseUrl) {
79
+ const base = normalizeAssetBaseUrl(assetBaseUrl);
80
+ return [
81
+ {
82
+ kind: "PixiFace",
83
+ type: "avatar",
84
+ name: "Hugo",
85
+ mouth: "Hugo",
86
+ eyes: {
87
+ kind: "spritesheet",
88
+ path: `${base}/Hugo/hugo_spritesheet.json`
89
+ },
90
+ cheeks: {
91
+ kind: "texture",
92
+ path: `${base}/Hugo/cheek.png`
93
+ },
94
+ eyebrows: "Hugo"
95
+ },
96
+ {
97
+ kind: "PixiFace",
98
+ type: "avatar",
99
+ name: "Simple",
100
+ mouth: "Ellipse",
101
+ eyes: {
102
+ kind: "spritesheet",
103
+ path: `${base}/Hugo/hugo_spritesheet.json`
104
+ },
105
+ cheeks: null,
106
+ eyebrows: null
107
+ },
108
+ {
109
+ kind: "PixiFace",
110
+ type: "avatar",
111
+ name: "Robotic",
112
+ mouth: "ZigZag",
113
+ eyes: {
114
+ kind: "spritesheet",
115
+ path: `${base}/Robotic/robotic_spritesheet.json`
116
+ },
117
+ cheeks: null,
118
+ eyebrows: null
119
+ },
120
+ {
121
+ kind: "PixiFace",
122
+ type: "text",
123
+ name: "Display",
124
+ showEmotion: "emoticon",
125
+ showText: true
126
+ }
127
+ ];
128
+ }
129
+ function createCustomVizijFace(glbUrl = "") {
130
+ return {
131
+ kind: "Vizij",
132
+ name: "Custom Face",
133
+ assetBundle: {
134
+ namespace: "custom",
135
+ glb: {
136
+ kind: "url",
137
+ src: glbUrl,
138
+ aggressiveImport: true
139
+ }
140
+ }
141
+ };
142
+ }
143
+ function createIncludedVizijFaces(assetBaseUrl) {
144
+ const base = normalizeAssetBaseUrl(assetBaseUrl);
145
+ return [
146
+ {
147
+ kind: "Vizij",
148
+ name: "Hugo - Expressive",
149
+ assetBundle: {
150
+ namespace: "hugo",
151
+ glb: {
152
+ kind: "url",
153
+ src: `${base}/Vizij/Hugo.glb`,
154
+ aggressiveImport: true
155
+ }
156
+ }
157
+ },
158
+ createCustomVizijFace("")
159
+ ];
160
+ }
161
+ function createBuiltInFaces(assetBaseUrl) {
162
+ return [
163
+ ...createBuiltInPixiFaces(assetBaseUrl),
164
+ ...createIncludedVizijFaces(assetBaseUrl)
165
+ ];
166
+ }
167
+ var builtInFaces = createBuiltInPixiFaces();
168
+ var customFace = createCustomVizijFace();
169
+ var includedVizijFaces = createIncludedVizijFaces();
170
+ var availableFaces = [...builtInFaces, ...includedVizijFaces];
171
+ var defaultFace = builtInFaces[0];
172
+
173
+ // src/store/faceRenderingSlice.ts
174
+ function clampUnit(value) {
175
+ if (Number.isNaN(value)) {
176
+ return 0;
177
+ }
178
+ return Math.max(-1, Math.min(1, value));
179
+ }
180
+ function mergeFaceSettings(base, patch) {
181
+ if (!patch) {
182
+ return {
183
+ ...base,
184
+ offset: { ...base.offset },
185
+ captions: {
186
+ ...base.captions,
187
+ offset: { ...base.captions.offset }
188
+ },
189
+ pixiSettings: base.pixiSettings ? { ...base.pixiSettings } : void 0,
190
+ vizijSettings: base.vizijSettings ? { ...base.vizijSettings } : void 0
191
+ };
192
+ }
193
+ return {
194
+ ...defaultFaceSettings,
195
+ ...base,
196
+ ...patch,
197
+ offset: {
198
+ ...defaultFaceSettings.offset,
199
+ ...base.offset || {},
200
+ ...patch.offset || {}
201
+ },
202
+ captions: {
203
+ ...defaultFaceSettings.captions,
204
+ ...base.captions || {},
205
+ ...patch.captions || {},
206
+ offset: {
207
+ ...defaultFaceSettings.captions.offset,
208
+ ...base.captions?.offset || {},
209
+ ...patch.captions?.offset || {}
210
+ }
211
+ },
212
+ pixiSettings: {
213
+ ...defaultFaceSettings.pixiSettings,
214
+ ...base.pixiSettings || {},
215
+ ...patch.pixiSettings || {}
216
+ },
217
+ vizijSettings: {
218
+ ...defaultFaceSettings.vizijSettings,
219
+ ...base.vizijSettings || {},
220
+ ...patch.vizijSettings || {}
221
+ }
222
+ };
223
+ }
224
+ function createFaceRenderingSlice(options = {}) {
225
+ const initialBaseUrl = normalizeAssetBaseUrl(options.assetBaseUrl);
226
+ const initialFaces = createBuiltInFaces(initialBaseUrl);
227
+ const initialSelectedFace = options.initialFace ?? initialFaces[0];
228
+ const initialMergedSettings = mergeFaceSettings(
229
+ defaultFaceSettings,
230
+ options.initialSettings
231
+ );
232
+ return (set, get) => ({
233
+ assetBaseUrl: initialBaseUrl,
234
+ availableFaces: initialFaces,
235
+ selectedFace: initialSelectedFace,
236
+ faceSettings: initialMergedSettings,
237
+ gaze: { x: 0, y: 0 },
238
+ setFace: (face) => {
239
+ set({ selectedFace: face });
240
+ },
241
+ setFaceByName: (name) => {
242
+ const found = get().availableFaces.find((f) => f.name === name);
243
+ if (found) {
244
+ set({ selectedFace: found });
245
+ }
246
+ },
247
+ setFaceSettings: (settings) => {
248
+ set((state) => ({
249
+ faceSettings: mergeFaceSettings(state.faceSettings, settings)
250
+ }));
251
+ },
252
+ resetPositioning: () => {
253
+ set((state) => ({
254
+ faceSettings: mergeFaceSettings(state.faceSettings, {
255
+ zoom: 1,
256
+ offset: { x: 0, y: 0 },
257
+ rotation: 0
258
+ })
259
+ }));
260
+ },
261
+ setGaze: (gaze) => {
262
+ set({
263
+ gaze: {
264
+ x: clampUnit(gaze.x),
265
+ y: clampUnit(gaze.y)
266
+ }
267
+ });
268
+ },
269
+ setLanguage: (lang) => {
270
+ set((state) => ({
271
+ faceSettings: mergeFaceSettings(state.faceSettings, {
272
+ selectedLanguage: lang
273
+ })
274
+ }));
275
+ },
276
+ setAssetBaseUrl: (assetBaseUrl) => {
277
+ const normalized = normalizeAssetBaseUrl(assetBaseUrl);
278
+ const updatedFaces = createBuiltInFaces(normalized);
279
+ const currentName = get().selectedFace?.name;
280
+ const matchingUpdated = updatedFaces.find((f) => f.name === currentName);
281
+ set({
282
+ assetBaseUrl: normalized,
283
+ availableFaces: updatedFaces,
284
+ selectedFace: matchingUpdated ?? get().selectedFace
285
+ });
286
+ }
287
+ });
288
+ }
289
+
290
+ // src/helpers/voice_helpers.ts
291
+ var languageDisplayNames = typeof Intl !== "undefined" && typeof Intl.DisplayNames === "function" ? new Intl.DisplayNames(["en"], { type: "language" }) : null;
292
+ function getLanguageName(code) {
293
+ if (!code) {
294
+ return "";
295
+ }
296
+ try {
297
+ const baseCode = code.split("-")[0];
298
+ if (!baseCode || !languageDisplayNames) {
299
+ return code;
300
+ }
301
+ return languageDisplayNames.of(baseCode) || code;
302
+ } catch (err) {
303
+ void err;
304
+ return code;
305
+ }
306
+ }
307
+ function formatVoiceDisplayName(rawName) {
308
+ if (!rawName) return "";
309
+ let name = rawName.replace(/^AWS - /, "").trim();
310
+ if (name.startsWith("aws:")) {
311
+ const parts = name.split(":");
312
+ name = parts[1] || name.slice(4);
313
+ }
314
+ if (!name.includes("com.apple.") && !name.includes("com.google.")) {
315
+ return name;
316
+ }
317
+ if (name.includes("com.google.")) {
318
+ const afterColon = name.split(":").pop() || name;
319
+ return afterColon.replace(/[-_]/g, " ").trim();
320
+ }
321
+ const siriMatch = name.match(
322
+ /siri_([a-zA-Z]+)_[a-zA-Z0-9-_]+?(?:_(compact|premium|enhanced))?$/i
323
+ );
324
+ if (siriMatch) {
325
+ const gender = siriMatch[1].charAt(0).toUpperCase() + siriMatch[1].slice(1).toLowerCase();
326
+ const quality = siriMatch[2] && siriMatch[2].toLowerCase() !== "compact" ? ` (${siriMatch[2].charAt(0).toUpperCase() + siriMatch[2].slice(1).toLowerCase()})` : "";
327
+ return `Siri ${gender}${quality}`;
328
+ }
329
+ const ttsMatch = name.match(
330
+ /com\.apple\.ttsbundle\.([a-zA-Z0-9]+)(?:-(compact|premium|enhanced))?/i
331
+ );
332
+ if (ttsMatch) {
333
+ const base = ttsMatch[1].replace(/([a-z])([A-Z])/g, "$1 $2");
334
+ const quality = ttsMatch[2] && ttsMatch[2].toLowerCase() !== "compact" ? ` (${ttsMatch[2].charAt(0).toUpperCase() + ttsMatch[2].slice(1).toLowerCase()})` : "";
335
+ return `${base}${quality}`;
336
+ }
337
+ const speechMatch = name.match(
338
+ /com\.apple\.speech\.synthesis\.voice\.([a-zA-Z0-9_-]+)/i
339
+ );
340
+ if (speechMatch) {
341
+ return speechMatch[1].replace(/([a-z])([A-Z])/g, "$1 $2");
342
+ }
343
+ const tierMatch = name.match(
344
+ /com\.apple\.voice\.(compact|enhanced|premium)\.[^.]+\.([a-zA-Z0-9_-]+)/i
345
+ );
346
+ if (tierMatch) {
347
+ const base = tierMatch[2].replace(/([a-z])([A-Z])/g, "$1 $2");
348
+ const quality = tierMatch[1].toLowerCase() !== "compact" ? ` (${tierMatch[1].charAt(0).toUpperCase() + tierMatch[1].slice(1).toLowerCase()})` : "";
349
+ return `${base}${quality}`;
350
+ }
351
+ const eloquenceMatch = name.match(
352
+ /com\.apple\.eloquence\.[^.]+\.([a-zA-Z0-9_-]+)/i
353
+ );
354
+ if (eloquenceMatch) {
355
+ return eloquenceMatch[1].replace(/([a-z])([A-Z])/g, "$1 $2");
356
+ }
357
+ const segments = name.split(".");
358
+ let last = segments[segments.length - 1] || name;
359
+ last = last.replace(/[-_](compact|premium|enhanced)$/i, "");
360
+ last = last.replace(/([a-z])([A-Z])/g, "$1 $2");
361
+ last = last.replace(/[-_]/g, " ").trim();
362
+ return last || name;
363
+ }
364
+ function findMatchingVoice(voices, target) {
365
+ if (!target) return void 0;
366
+ const directUri = voices.find((v) => v.voiceURI === target);
367
+ if (directUri) return directUri;
368
+ const directName = voices.find((v) => v.name === target);
369
+ if (directName) return directName;
370
+ const targetClean = formatVoiceDisplayName(target).toLowerCase();
371
+ const cleanMatch = voices.find(
372
+ (v) => formatVoiceDisplayName(v.name).toLowerCase() === targetClean || formatVoiceDisplayName(v.voiceURI).toLowerCase() === targetClean
373
+ );
374
+ if (cleanMatch) return cleanMatch;
375
+ const lowerTarget = target.toLowerCase();
376
+ return voices.find(
377
+ (v) => v.voiceURI.toLowerCase() === lowerTarget || v.name.toLowerCase() === lowerTarget
378
+ );
379
+ }
380
+
381
+ // src/helpers/viseme_mapper.ts
382
+ var pollyVisemeToVizijPath = {
383
+ "@": "pose_pzzzfnvy",
384
+ a: "a",
385
+ e: "e_2",
386
+ E: "e",
387
+ f: "f",
388
+ i: "i",
389
+ k: "k",
390
+ l: "r",
391
+ o: "o",
392
+ O: "o_2",
393
+ p: "p",
394
+ r: "r",
395
+ s: "s",
396
+ S: "s",
397
+ t: "t",
398
+ T: "t_2",
399
+ u: "u",
400
+ sil: ""
401
+ };
402
+ var possiblePollyVisemes = Array.from(
403
+ new Set(Object.values(pollyVisemeToVizijPath).filter((v) => v.length > 0))
404
+ );
405
+ var CHAR_TO_POLLY_VISEME = {
406
+ a: "a",
407
+ b: "p",
408
+ c: "k",
409
+ d: "t",
410
+ e: "e",
411
+ f: "f",
412
+ g: "k",
413
+ h: "@",
414
+ i: "i",
415
+ j: "S",
416
+ k: "k",
417
+ l: "l",
418
+ m: "p",
419
+ n: "t",
420
+ o: "o",
421
+ p: "p",
422
+ q: "k",
423
+ r: "r",
424
+ s: "s",
425
+ t: "t",
426
+ u: "u",
427
+ v: "f",
428
+ w: "u",
429
+ x: "s",
430
+ y: "i",
431
+ z: "s"
432
+ };
433
+ function estimateVisemesFromText(text, msPerChar = 65) {
434
+ const cleaned = text.trim();
435
+ if (!cleaned) {
436
+ return [];
437
+ }
438
+ const visemes = [];
439
+ const durationSec = Math.max(0.03, msPerChar / 1e3);
440
+ for (const ch of cleaned.toLowerCase()) {
441
+ const mapped = CHAR_TO_POLLY_VISEME[ch] ?? "sil";
442
+ const prev = visemes[visemes.length - 1];
443
+ if (prev && prev.value === mapped) {
444
+ prev.time = Number((prev.time + durationSec).toFixed(4));
445
+ } else {
446
+ visemes.push({
447
+ time: Number(durationSec.toFixed(4)),
448
+ type: "viseme",
449
+ value: mapped
450
+ });
451
+ }
452
+ }
453
+ if (visemes[visemes.length - 1]?.value !== "sil") {
454
+ visemes.push({
455
+ time: 0.1,
456
+ type: "viseme",
457
+ value: "sil"
458
+ });
459
+ }
460
+ return visemes;
461
+ }
462
+
463
+ // src/services/AudioAnalyzer.ts
464
+ var AudioAnalyzer = class {
465
+ ctx = null;
466
+ analyzer = null;
467
+ data = null;
468
+ connectedElements = /* @__PURE__ */ new WeakSet();
469
+ connect(audio) {
470
+ if (typeof window === "undefined") {
471
+ return;
472
+ }
473
+ const AudioContextCtor = window.AudioContext || window.webkitAudioContext;
474
+ if (!AudioContextCtor) {
475
+ return;
476
+ }
477
+ try {
478
+ if (!this.ctx) {
479
+ this.ctx = new AudioContextCtor();
480
+ this.analyzer = this.ctx.createAnalyser();
481
+ this.analyzer.fftSize = 256;
482
+ this.data = new Uint8Array(new ArrayBuffer(this.analyzer.frequencyBinCount));
483
+ }
484
+ if (!this.connectedElements.has(audio) && this.analyzer) {
485
+ const source = this.ctx.createMediaElementSource(audio);
486
+ source.connect(this.analyzer);
487
+ this.analyzer.connect(this.ctx.destination);
488
+ this.connectedElements.add(audio);
489
+ }
490
+ } catch (error) {
491
+ console.warn("AudioAnalyzer connect error:", error);
492
+ }
493
+ }
494
+ getAmplitude() {
495
+ if (!this.analyzer || !this.data) {
496
+ return 0;
497
+ }
498
+ this.analyzer.getByteTimeDomainData(this.data);
499
+ let sum = 0;
500
+ for (const v of this.data) {
501
+ const normalized = (v - 128) / 128;
502
+ sum += normalized * normalized;
503
+ }
504
+ return Math.sqrt(sum / this.data.length);
505
+ }
506
+ };
507
+ var audioAnalyzer = new AudioAnalyzer();
508
+
509
+ // src/services/ttsAudioCache.ts
510
+ function buildTtsCacheKey(params) {
511
+ const voice = params.voiceId.trim();
512
+ const engine = (params.engine ?? "default").trim() || "default";
513
+ const normalizedText = params.text.trim();
514
+ if (params.rate === void 0 && params.pitch === void 0) {
515
+ return `${voice}:${engine}:${normalizedText}`;
516
+ }
517
+ const rate = params.rate ?? 1;
518
+ const pitch = params.pitch ?? 1;
519
+ return `${voice}:${engine}:${rate}:${pitch}:${normalizedText}`;
520
+ }
521
+ async function blobToArrayBuffer(blob) {
522
+ if (typeof blob.arrayBuffer === "function") {
523
+ return blob.arrayBuffer();
524
+ }
525
+ return new Promise((resolve, reject) => {
526
+ const reader = new FileReader();
527
+ reader.onload = () => {
528
+ if (reader.result instanceof ArrayBuffer) {
529
+ resolve(reader.result);
530
+ } else {
531
+ reject(new Error("Failed to read Blob as ArrayBuffer"));
532
+ }
533
+ };
534
+ reader.onerror = () => {
535
+ reject(reader.error ?? new Error("FileReader error"));
536
+ };
537
+ reader.readAsArrayBuffer(blob);
538
+ });
539
+ }
540
+ var TtsAudioCache = class {
541
+ maxEntries;
542
+ enableIndexedDb;
543
+ dbName;
544
+ storeName;
545
+ memory = /* @__PURE__ */ new Map();
546
+ dbPromise = null;
547
+ constructor(options = {}) {
548
+ this.maxEntries = Math.max(1, options.maxEntries ?? 100);
549
+ this.enableIndexedDb = options.enableIndexedDb ?? true;
550
+ this.dbName = options.dbName ?? "peerbots-tts-cache";
551
+ this.storeName = options.storeName ?? "entries";
552
+ }
553
+ get size() {
554
+ return this.memory.size;
555
+ }
556
+ hasInMemory(key) {
557
+ return this.memory.has(key);
558
+ }
559
+ async get(key) {
560
+ const existing = this.memory.get(key);
561
+ if (existing) {
562
+ this.memory.delete(key);
563
+ this.memory.set(key, existing);
564
+ return existing;
565
+ }
566
+ const fromIdb = await this.readFromIndexedDb(key);
567
+ if (fromIdb) {
568
+ this.putInMemory(key, fromIdb);
569
+ return fromIdb;
570
+ }
571
+ return void 0;
572
+ }
573
+ async set(key, entry) {
574
+ const fullEntry = {
575
+ ...entry,
576
+ createdAt: entry.createdAt ?? Date.now()
577
+ };
578
+ this.putInMemory(key, fullEntry);
579
+ await this.writeToIndexedDb(key, fullEntry);
580
+ }
581
+ async delete(key) {
582
+ const removedMem = this.memory.delete(key);
583
+ const removedIdb = await this.deleteFromIndexedDb(key);
584
+ return removedMem || removedIdb;
585
+ }
586
+ async clear() {
587
+ this.memory.clear();
588
+ await this.clearIndexedDb();
589
+ }
590
+ createObjectUrl(entry) {
591
+ return URL.createObjectURL(entry.audioBlob);
592
+ }
593
+ putInMemory(key, entry) {
594
+ if (this.memory.has(key)) {
595
+ this.memory.delete(key);
596
+ }
597
+ this.memory.set(key, entry);
598
+ while (this.memory.size > this.maxEntries) {
599
+ const oldestKey = this.memory.keys().next().value;
600
+ if (oldestKey !== void 0) {
601
+ this.memory.delete(oldestKey);
602
+ } else {
603
+ break;
604
+ }
605
+ }
606
+ }
607
+ openDatabase() {
608
+ if (!this.enableIndexedDb || typeof indexedDB === "undefined") {
609
+ return Promise.resolve(null);
610
+ }
611
+ if (this.dbPromise) {
612
+ return this.dbPromise;
613
+ }
614
+ this.dbPromise = new Promise((resolve) => {
615
+ try {
616
+ const request = indexedDB.open(this.dbName, 1);
617
+ request.onupgradeneeded = () => {
618
+ const db = request.result;
619
+ if (!db.objectStoreNames.contains(this.storeName)) {
620
+ db.createObjectStore(this.storeName, { keyPath: "key" });
621
+ }
622
+ };
623
+ request.onsuccess = () => resolve(request.result);
624
+ request.onerror = () => resolve(null);
625
+ } catch (err) {
626
+ void err;
627
+ resolve(null);
628
+ }
629
+ });
630
+ return this.dbPromise;
631
+ }
632
+ async readFromIndexedDb(key) {
633
+ const db = await this.openDatabase();
634
+ if (!db) {
635
+ return void 0;
636
+ }
637
+ return new Promise((resolve) => {
638
+ try {
639
+ const tx = db.transaction(this.storeName, "readonly");
640
+ const store = tx.objectStore(this.storeName);
641
+ const req = store.get(key);
642
+ req.onsuccess = () => {
643
+ const record = req.result;
644
+ if (!record || !record.audioBuffer) {
645
+ resolve(void 0);
646
+ return;
647
+ }
648
+ resolve({
649
+ audioBlob: new Blob([record.audioBuffer], {
650
+ type: record.mimeType || "audio/mpeg"
651
+ }),
652
+ mimeType: record.mimeType || "audio/mpeg",
653
+ visemes: record.visemes,
654
+ amplitudeData: record.amplitudeData,
655
+ extrema: record.extrema,
656
+ createdAt: record.createdAt
657
+ });
658
+ };
659
+ req.onerror = () => resolve(void 0);
660
+ } catch (err) {
661
+ void err;
662
+ resolve(void 0);
663
+ }
664
+ });
665
+ }
666
+ async writeToIndexedDb(key, entry) {
667
+ const db = await this.openDatabase();
668
+ if (!db) {
669
+ return;
670
+ }
671
+ try {
672
+ const audioBuffer = await blobToArrayBuffer(entry.audioBlob);
673
+ await new Promise((resolve) => {
674
+ const tx = db.transaction(this.storeName, "readwrite");
675
+ const store = tx.objectStore(this.storeName);
676
+ const record = {
677
+ key,
678
+ audioBuffer,
679
+ mimeType: entry.mimeType,
680
+ visemes: entry.visemes,
681
+ amplitudeData: entry.amplitudeData,
682
+ extrema: entry.extrema,
683
+ createdAt: entry.createdAt
684
+ };
685
+ const req = store.put(record);
686
+ req.onsuccess = () => resolve();
687
+ req.onerror = () => resolve();
688
+ });
689
+ } catch (err) {
690
+ void err;
691
+ }
692
+ }
693
+ async deleteFromIndexedDb(key) {
694
+ const db = await this.openDatabase();
695
+ if (!db) {
696
+ return false;
697
+ }
698
+ return new Promise((resolve) => {
699
+ try {
700
+ const tx = db.transaction(this.storeName, "readwrite");
701
+ const store = tx.objectStore(this.storeName);
702
+ const req = store.delete(key);
703
+ req.onsuccess = () => resolve(true);
704
+ req.onerror = () => resolve(false);
705
+ } catch (err) {
706
+ void err;
707
+ resolve(false);
708
+ }
709
+ });
710
+ }
711
+ async clearIndexedDb() {
712
+ const db = await this.openDatabase();
713
+ if (!db) {
714
+ return;
715
+ }
716
+ await new Promise((resolve) => {
717
+ try {
718
+ const tx = db.transaction(this.storeName, "readwrite");
719
+ const store = tx.objectStore(this.storeName);
720
+ const req = store.clear();
721
+ req.onsuccess = () => resolve();
722
+ req.onerror = () => resolve();
723
+ } catch (err) {
724
+ void err;
725
+ resolve();
726
+ }
727
+ });
728
+ }
729
+ };
730
+ var defaultTtsAudioCache = new TtsAudioCache();
731
+
732
+ // src/store/faceSpeechSlice.ts
733
+ var FALLBACK_DEFAULT_VOICE = {
734
+ default: false,
735
+ lang: "en-US",
736
+ localService: false,
737
+ name: "en-US-Standard-B",
738
+ voiceURI: "en-US-Standard-B"
739
+ };
740
+ function isNativeSpeechSynthesisVoice(voice) {
741
+ if (!voice || typeof voice !== "object") {
742
+ return false;
743
+ }
744
+ if (typeof SpeechSynthesisVoice !== "undefined" && voice instanceof SpeechSynthesisVoice) {
745
+ return true;
746
+ }
747
+ return Object.prototype.toString.call(voice) === "[object SpeechSynthesisVoice]";
748
+ }
749
+ function matchesLanguage(voiceLang, selectedLang) {
750
+ if (!voiceLang || !selectedLang) {
751
+ return false;
752
+ }
753
+ return getLanguageName(voiceLang) === selectedLang || voiceLang === selectedLang || voiceLang.toLowerCase() === selectedLang.toLowerCase() || voiceLang.toLowerCase().startsWith(selectedLang.toLowerCase()) || selectedLang.toLowerCase().startsWith(voiceLang.toLowerCase());
754
+ }
755
+ function stopNativeSpeechSynthesis() {
756
+ if (typeof window !== "undefined" && "speechSynthesis" in window) {
757
+ try {
758
+ if (window.speechSynthesis.speaking || window.speechSynthesis.pending) {
759
+ window.speechSynthesis.cancel();
760
+ }
761
+ } catch (err) {
762
+ void err;
763
+ }
764
+ }
765
+ }
766
+ function createFaceSpeechSlice(sliceOptions = {}) {
767
+ let adapter = sliceOptions.speechAdapter ?? null;
768
+ const cache = sliceOptions.ttsCache === false ? null : sliceOptions.ttsCache ?? defaultTtsAudioCache;
769
+ const analyzer = sliceOptions.audioAnalyzer ?? audioAnalyzer;
770
+ const utteranceDeferMs = sliceOptions.utteranceDeferMs ?? 10;
771
+ let activeAudio = null;
772
+ let activeObjectUrl = null;
773
+ let activeUtterance = null;
774
+ let activeTimer = null;
775
+ let activeBoundaryTimer = null;
776
+ let activeGeneration = 0;
777
+ const revokeActiveObjectUrl = () => {
778
+ if (activeObjectUrl) {
779
+ try {
780
+ URL.revokeObjectURL(activeObjectUrl);
781
+ } catch (err) {
782
+ void err;
783
+ }
784
+ activeObjectUrl = null;
785
+ }
786
+ };
787
+ const cleanupActivePlayback = () => {
788
+ activeGeneration += 1;
789
+ if (activeTimer !== null) {
790
+ clearTimeout(activeTimer);
791
+ activeTimer = null;
792
+ }
793
+ if (activeBoundaryTimer !== null) {
794
+ clearTimeout(activeBoundaryTimer);
795
+ activeBoundaryTimer = null;
796
+ }
797
+ if (activeAudio) {
798
+ activeAudio.onplay = null;
799
+ activeAudio.onended = null;
800
+ activeAudio.onerror = null;
801
+ try {
802
+ activeAudio.pause();
803
+ activeAudio.currentTime = 0;
804
+ } catch (err) {
805
+ void err;
806
+ }
807
+ activeAudio = null;
808
+ }
809
+ revokeActiveObjectUrl();
810
+ if (activeUtterance) {
811
+ activeUtterance.onstart = null;
812
+ activeUtterance.onend = null;
813
+ activeUtterance.onerror = null;
814
+ activeUtterance.onboundary = null;
815
+ activeUtterance = null;
816
+ }
817
+ stopNativeSpeechSynthesis();
818
+ };
819
+ return (set, get) => {
820
+ const playNextFromQueue = () => {
821
+ const queue = get().speechQueue;
822
+ if (queue.length > 0) {
823
+ const [next, ...rest] = queue;
824
+ set({ speechQueue: rest });
825
+ void get().express(next.message, next.options);
826
+ }
827
+ };
828
+ const finishGeneration = (gen) => {
829
+ if (gen !== activeGeneration) {
830
+ return;
831
+ }
832
+ if (activeBoundaryTimer !== null) {
833
+ clearTimeout(activeBoundaryTimer);
834
+ activeBoundaryTimer = null;
835
+ }
836
+ activeAudio = null;
837
+ activeUtterance = null;
838
+ revokeActiveObjectUrl();
839
+ set({
840
+ isSpeaking: false,
841
+ speechStartTime: null,
842
+ currentAmplitude: 0
843
+ });
844
+ playNextFromQueue();
845
+ };
846
+ const expressImpl = async (message, options) => {
847
+ const speechText = (message.speech ?? "").trim();
848
+ const hasWords = speechText.length > 0;
849
+ if (sliceOptions.isSilent || options?.silent || !hasWords) {
850
+ set({
851
+ lastMessage: message,
852
+ isSpeaking: false
853
+ });
854
+ return;
855
+ }
856
+ const effectiveQueueMode = options?.queueMode ?? get().faceSettings?.speechQueueMode ?? "interrupt";
857
+ const currentlyPlaying = get().isSpeaking || activeAudio !== null || activeUtterance !== null || activeTimer !== null;
858
+ if (effectiveQueueMode === "queue" && currentlyPlaying) {
859
+ set((state) => ({
860
+ speechQueue: [...state.speechQueue, { message, options }]
861
+ }));
862
+ return;
863
+ }
864
+ cleanupActivePlayback();
865
+ const myGeneration = activeGeneration;
866
+ set({
867
+ lastMessage: message,
868
+ isSpeaking: true
869
+ });
870
+ const selectedVoice = get().getSelectedVoice();
871
+ const shouldUseAdapter = adapter !== null && typeof adapter.synthesizeSpeech === "function" && (adapter.canHandleVoice ? adapter.canHandleVoice(selectedVoice.voiceURI, selectedVoice) : true);
872
+ if (shouldUseAdapter && adapter?.synthesizeSpeech) {
873
+ try {
874
+ const cacheKey = buildTtsCacheKey({
875
+ voiceId: selectedVoice.voiceURI,
876
+ engine: selectedVoice.engine,
877
+ text: speechText
878
+ });
879
+ const cached = cache ? await cache.get(cacheKey) : void 0;
880
+ if (myGeneration !== activeGeneration) {
881
+ return;
882
+ }
883
+ let playbackUrl;
884
+ let shouldRevokeUrl = false;
885
+ let visemes = null;
886
+ let ampData = null;
887
+ let extrema = null;
888
+ if (cached && cache) {
889
+ playbackUrl = cache.createObjectUrl(cached);
890
+ shouldRevokeUrl = true;
891
+ visemes = cached.visemes ?? null;
892
+ ampData = cached.amplitudeData ?? null;
893
+ extrema = cached.extrema ?? null;
894
+ } else {
895
+ const synthesized = await adapter.synthesizeSpeech(
896
+ speechText,
897
+ selectedVoice.voiceURI,
898
+ {
899
+ engine: selectedVoice.engine,
900
+ language: get().faceSettings?.selectedLanguage
901
+ }
902
+ );
903
+ if (myGeneration !== activeGeneration) {
904
+ return;
905
+ }
906
+ visemes = synthesized.visemes ?? null;
907
+ ampData = synthesized.amplitudeData ?? null;
908
+ extrema = synthesized.extrema ?? null;
909
+ const mimeType = synthesized.mimeType || "audio/mpeg";
910
+ let blobToCache = null;
911
+ if (synthesized.audioBlob) {
912
+ blobToCache = synthesized.audioBlob;
913
+ } else if (synthesized.audioBuffer) {
914
+ blobToCache = new Blob([synthesized.audioBuffer], { type: mimeType });
915
+ }
916
+ if (blobToCache) {
917
+ if (cache) {
918
+ await cache.set(cacheKey, {
919
+ audioBlob: blobToCache,
920
+ mimeType,
921
+ visemes: synthesized.visemes,
922
+ amplitudeData: synthesized.amplitudeData,
923
+ extrema: synthesized.extrema
924
+ });
925
+ }
926
+ playbackUrl = URL.createObjectURL(blobToCache);
927
+ shouldRevokeUrl = true;
928
+ } else if (synthesized.audioUrl) {
929
+ playbackUrl = synthesized.audioUrl;
930
+ }
931
+ }
932
+ if (playbackUrl && typeof Audio !== "undefined") {
933
+ get().setSpokenVisemes(visemes);
934
+ get().setAmplitudeData(ampData, extrema);
935
+ const audio = new Audio(playbackUrl);
936
+ audio.crossOrigin = "anonymous";
937
+ activeAudio = audio;
938
+ if (shouldRevokeUrl) {
939
+ activeObjectUrl = playbackUrl;
940
+ }
941
+ analyzer.connect(audio);
942
+ audio.onplay = () => {
943
+ if (myGeneration !== activeGeneration) {
944
+ return;
945
+ }
946
+ set({
947
+ isSpeaking: true,
948
+ speechStartTime: performance.now()
949
+ });
950
+ const pollAmplitude = () => {
951
+ if (myGeneration === activeGeneration && activeAudio === audio && !audio.paused && !audio.ended) {
952
+ get().setCurrentAmplitude(analyzer.getAmplitude());
953
+ if (typeof requestAnimationFrame === "function") {
954
+ requestAnimationFrame(pollAmplitude);
955
+ }
956
+ } else if (myGeneration === activeGeneration) {
957
+ get().setCurrentAmplitude(0);
958
+ }
959
+ };
960
+ pollAmplitude();
961
+ };
962
+ audio.onended = () => {
963
+ finishGeneration(myGeneration);
964
+ };
965
+ audio.onerror = () => {
966
+ finishGeneration(myGeneration);
967
+ };
968
+ await audio.play();
969
+ return;
970
+ }
971
+ } catch (adapterError) {
972
+ console.warn(
973
+ "SpeechSynthesizerAdapter failed; falling back to Web Speech API:",
974
+ adapterError
975
+ );
976
+ if (myGeneration !== activeGeneration) {
977
+ return;
978
+ }
979
+ }
980
+ }
981
+ if (typeof window === "undefined" || typeof SpeechSynthesisUtterance === "undefined" || typeof window.speechSynthesis === "undefined") {
982
+ finishGeneration(myGeneration);
983
+ return;
984
+ }
985
+ const utterance = new SpeechSynthesisUtterance(speechText);
986
+ activeUtterance = utterance;
987
+ if (isNativeSpeechSynthesisVoice(selectedVoice)) {
988
+ utterance.voice = selectedVoice;
989
+ } else {
990
+ const nativeVoices = window.speechSynthesis.getVoices();
991
+ const matched = findMatchingVoice(nativeVoices, selectedVoice.voiceURI) || findMatchingVoice(nativeVoices, selectedVoice.name);
992
+ if (matched) {
993
+ utterance.voice = matched;
994
+ }
995
+ }
996
+ utterance.lang = selectedVoice.lang || get().faceSettings?.selectedLanguage || "en-US";
997
+ const estimatedVisemes = estimateVisemesFromText(speechText);
998
+ set({
999
+ spokenVisemes: estimatedVisemes,
1000
+ amplitudeData: null,
1001
+ amplitudeExtrema: null,
1002
+ currentAmplitude: 0
1003
+ });
1004
+ utterance.onstart = () => {
1005
+ if (myGeneration !== activeGeneration) {
1006
+ return;
1007
+ }
1008
+ set({
1009
+ isSpeaking: true,
1010
+ speechStartTime: performance.now()
1011
+ });
1012
+ };
1013
+ utterance.onboundary = (event) => {
1014
+ if (myGeneration !== activeGeneration) {
1015
+ return;
1016
+ }
1017
+ if (event.name === "word") {
1018
+ get().setCurrentAmplitude(1);
1019
+ if (activeBoundaryTimer !== null) {
1020
+ clearTimeout(activeBoundaryTimer);
1021
+ }
1022
+ activeBoundaryTimer = setTimeout(() => {
1023
+ if (myGeneration === activeGeneration) {
1024
+ get().setCurrentAmplitude(0);
1025
+ }
1026
+ }, 100);
1027
+ }
1028
+ };
1029
+ utterance.onend = () => {
1030
+ finishGeneration(myGeneration);
1031
+ };
1032
+ utterance.onerror = (event) => {
1033
+ if (event.error === "not-allowed") {
1034
+ get().setSpeechAllowed(false);
1035
+ }
1036
+ finishGeneration(myGeneration);
1037
+ };
1038
+ const invokeSpeak = () => {
1039
+ activeTimer = null;
1040
+ if (myGeneration !== activeGeneration) {
1041
+ return;
1042
+ }
1043
+ try {
1044
+ if (window.speechSynthesis.paused) {
1045
+ window.speechSynthesis.resume();
1046
+ }
1047
+ window.speechSynthesis.speak(utterance);
1048
+ } catch (speakErr) {
1049
+ console.warn("SpeechSynthesis speak invocation error:", speakErr);
1050
+ finishGeneration(myGeneration);
1051
+ }
1052
+ };
1053
+ if (utteranceDeferMs <= 0) {
1054
+ invokeSpeak();
1055
+ } else {
1056
+ activeTimer = setTimeout(invokeSpeak, utteranceDeferMs);
1057
+ }
1058
+ };
1059
+ return {
1060
+ lastMessage: sliceOptions.initialMessage ?? DEFAULT_FACE_MESSAGE,
1061
+ isSpeaking: false,
1062
+ speechAllowed: false,
1063
+ selectedVoiceUri: null,
1064
+ availableVoices: [],
1065
+ spokenVisemes: null,
1066
+ amplitudeData: null,
1067
+ amplitudeExtrema: null,
1068
+ currentAmplitude: 0,
1069
+ speechStartTime: null,
1070
+ speechQueue: [],
1071
+ setSpeechAllowed: (allowed) => {
1072
+ set({ speechAllowed: allowed });
1073
+ },
1074
+ setAvailableVoices: (voices) => {
1075
+ set({ availableVoices: voices });
1076
+ },
1077
+ refreshVoices: async () => {
1078
+ const collected = [];
1079
+ const seen = /* @__PURE__ */ new Set();
1080
+ if (typeof window !== "undefined" && "speechSynthesis" in window) {
1081
+ const browserVoices = window.speechSynthesis.getVoices();
1082
+ for (const v of browserVoices) {
1083
+ if (!seen.has(v.voiceURI)) {
1084
+ seen.add(v.voiceURI);
1085
+ collected.push(v);
1086
+ }
1087
+ }
1088
+ }
1089
+ if (adapter?.fetchVoices) {
1090
+ try {
1091
+ const remoteVoices = await adapter.fetchVoices();
1092
+ for (const v of remoteVoices) {
1093
+ if (!seen.has(v.voiceURI)) {
1094
+ seen.add(v.voiceURI);
1095
+ collected.push(v);
1096
+ }
1097
+ }
1098
+ } catch (err) {
1099
+ console.warn("Failed to fetch adapter voices:", err);
1100
+ }
1101
+ }
1102
+ set({ availableVoices: collected });
1103
+ return collected;
1104
+ },
1105
+ getDefaultVoice: () => {
1106
+ const voices = get().availableVoices;
1107
+ const selectedLang = get().faceSettings?.selectedLanguage;
1108
+ if (selectedLang) {
1109
+ const langVoice = voices.find(
1110
+ (v) => matchesLanguage(v.lang, selectedLang)
1111
+ );
1112
+ if (langVoice) {
1113
+ return langVoice;
1114
+ }
1115
+ }
1116
+ const defaultFlagged = voices.find((v) => v.default === true);
1117
+ if (defaultFlagged) {
1118
+ return defaultFlagged;
1119
+ }
1120
+ if (voices.length > 0) {
1121
+ return voices[0];
1122
+ }
1123
+ return {
1124
+ ...FALLBACK_DEFAULT_VOICE,
1125
+ lang: selectedLang || "en-US"
1126
+ };
1127
+ },
1128
+ getSelectedVoice: () => {
1129
+ const uri = get().selectedVoiceUri;
1130
+ const voices = get().availableVoices;
1131
+ if (uri !== null) {
1132
+ const matched = findMatchingVoice(voices, uri);
1133
+ if (matched) {
1134
+ return matched;
1135
+ }
1136
+ }
1137
+ return get().getDefaultVoice();
1138
+ },
1139
+ setVoice: (voiceUri, voiceOptions) => {
1140
+ const prevVoice = get().selectedVoiceUri || get().getSelectedVoice()?.voiceURI;
1141
+ set({ selectedVoiceUri: voiceUri });
1142
+ if (!sliceOptions.isSilent && !voiceOptions?.silent && prevVoice && prevVoice !== voiceUri) {
1143
+ void get().express({
1144
+ title: "Switching voice",
1145
+ speech: "Switching voice",
1146
+ color: "Light Blue",
1147
+ emotion: "Neutral"
1148
+ });
1149
+ }
1150
+ },
1151
+ setSpokenVisemes: (visemes) => {
1152
+ set({ spokenVisemes: visemes });
1153
+ },
1154
+ setAmplitudeData: (data, extrema) => {
1155
+ set({
1156
+ amplitudeData: data,
1157
+ amplitudeExtrema: extrema
1158
+ });
1159
+ },
1160
+ setIsSpeaking: (isSpeaking) => {
1161
+ set({ isSpeaking });
1162
+ },
1163
+ setCurrentAmplitude: (amplitude) => {
1164
+ const gain = get().faceSettings?.amplitudeGain ?? 1;
1165
+ const scaled = amplitude * gain;
1166
+ const clamped = Number.isNaN(scaled) ? 0 : Math.min(1, Math.max(0, scaled));
1167
+ set({ currentAmplitude: clamped });
1168
+ },
1169
+ setSpeechAdapter: (nextAdapter) => {
1170
+ adapter = nextAdapter;
1171
+ },
1172
+ express: expressImpl,
1173
+ _express: expressImpl,
1174
+ stopSpeech: () => {
1175
+ cleanupActivePlayback();
1176
+ set({
1177
+ isSpeaking: false,
1178
+ speechStartTime: null,
1179
+ currentAmplitude: 0,
1180
+ spokenVisemes: null,
1181
+ amplitudeData: null,
1182
+ amplitudeExtrema: null,
1183
+ speechQueue: []
1184
+ });
1185
+ }
1186
+ };
1187
+ };
1188
+ }
1189
+
1190
+ // src/store/createPeerbotsFaceStore.ts
1191
+ function restorePersistedFace(persistedSelection, builtIns, fallback) {
1192
+ if (typeof persistedSelection === "string") {
1193
+ return builtIns.find((f) => f.name === persistedSelection) ?? fallback;
1194
+ }
1195
+ if (persistedSelection && typeof persistedSelection === "object") {
1196
+ const selectionObj = persistedSelection;
1197
+ if (typeof selectionObj.name === "string") {
1198
+ const found = builtIns.find((f) => f.name === selectionObj.name);
1199
+ if (found) {
1200
+ if (found.kind === "Vizij" && selectionObj.assetBundle && typeof selectionObj.assetBundle === "object") {
1201
+ const persistedBundle = selectionObj.assetBundle;
1202
+ const persistedGlb = persistedBundle.glb && typeof persistedBundle.glb === "object" ? persistedBundle.glb : {};
1203
+ return {
1204
+ ...found,
1205
+ assetBundle: {
1206
+ ...found.assetBundle,
1207
+ ...persistedBundle,
1208
+ glb: {
1209
+ ...found.assetBundle.glb,
1210
+ ...persistedGlb
1211
+ }
1212
+ }
1213
+ };
1214
+ }
1215
+ return found;
1216
+ }
1217
+ if (typeof selectionObj.kind === "string") {
1218
+ return persistedSelection;
1219
+ }
1220
+ }
1221
+ }
1222
+ return fallback;
1223
+ }
1224
+ function createPeerbotsFaceStore(options = {}) {
1225
+ const stateInitializer = (...args) => ({
1226
+ ...createFaceRenderingSlice(options)(...args),
1227
+ ...createFaceSpeechSlice(options)(...args)
1228
+ });
1229
+ if (!options.persistName) {
1230
+ return (0, import_zustand.createStore)()(stateInitializer);
1231
+ }
1232
+ const builtIns = createBuiltInFaces(options.assetBaseUrl);
1233
+ const fallbackFace = options.initialFace ?? builtIns[0];
1234
+ return (0, import_zustand.createStore)()(
1235
+ (0, import_middleware.persist)(stateInitializer, {
1236
+ name: options.persistName,
1237
+ version: 1,
1238
+ partialize: (state) => ({
1239
+ selectedFace: state.selectedFace,
1240
+ faceSettings: state.faceSettings,
1241
+ selectedVoiceUri: state.selectedVoiceUri,
1242
+ lastMessage: state.lastMessage
1243
+ }),
1244
+ merge: (persistedState, currentState) => {
1245
+ const persisted = persistedState ?? {};
1246
+ const restoredFace = restorePersistedFace(
1247
+ persisted.selectedFace,
1248
+ currentState.availableFaces,
1249
+ fallbackFace
1250
+ );
1251
+ const restoredSettings = persisted.faceSettings ? mergeFaceSettings(
1252
+ defaultFaceSettings,
1253
+ persisted.faceSettings
1254
+ ) : currentState.faceSettings;
1255
+ return {
1256
+ ...currentState,
1257
+ selectedFace: restoredFace,
1258
+ selectedVoiceUri: persisted.selectedVoiceUri ?? null,
1259
+ faceSettings: restoredSettings,
1260
+ lastMessage: persisted.lastMessage ?? options.initialMessage ?? DEFAULT_FACE_MESSAGE,
1261
+ isSpeaking: false
1262
+ };
1263
+ }
1264
+ })
1265
+ );
1266
+ }
1267
+ var globalFaceStore = createPeerbotsFaceStore({
1268
+ persistName: "faceSettings"
1269
+ });
1270
+
1271
+ // src/store/FaceStoreContext.tsx
1272
+ var import_jsx_runtime = require("react/jsx-runtime");
1273
+ var FaceStoreContext = (0, import_react.createContext)(null);
1274
+ function useFaceStoreInstance() {
1275
+ const context = (0, import_react.useContext)(FaceStoreContext);
1276
+ return context ?? globalFaceStore;
1277
+ }
1278
+ function useFaceStoreBase(selector) {
1279
+ const store = useFaceStoreInstance();
1280
+ return (0, import_zustand2.useStore)(store, selector);
1281
+ }
1282
+ var useFaceStore = Object.assign(useFaceStoreBase, {
1283
+ getState: () => globalFaceStore.getState(),
1284
+ setState: ((...args) => globalFaceStore.setState(...args)),
1285
+ subscribe: ((...args) => globalFaceStore.subscribe(...args))
1286
+ });
1287
+
1288
+ // src/components/FaceContainer.tsx
1289
+ var import_react11 = require("react");
1290
+ var import_pixi5 = require("pixi.js");
1291
+ var import_react12 = require("@pixi/react");
1292
+
1293
+ // src/helpers/color_mappers.ts
1294
+ var color_mapping = {
1295
+ "Light Blue": "#ABE3FA",
1296
+ Blue: "#5F94D6",
1297
+ Green: "#65C77D",
1298
+ Red: "#E6817E",
1299
+ Purple: "#9B86F3",
1300
+ Pink: "#EBA4E4",
1301
+ Yellow: "#F8EDB1",
1302
+ Orange: "#E6A575",
1303
+ Grey: "#CECECE",
1304
+ Black: "#4D4D4D",
1305
+ White: "#FDFEFE"
1306
+ };
1307
+ function hexToRgb(hex) {
1308
+ const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
1309
+ const expanded = hex.replace(shorthandRegex, (_m, r, g, b) => {
1310
+ return r + r + g + g + b + b;
1311
+ });
1312
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(expanded);
1313
+ return result ? {
1314
+ r: parseInt(result[1], 16),
1315
+ g: parseInt(result[2], 16),
1316
+ b: parseInt(result[3], 16)
1317
+ } : null;
1318
+ }
1319
+ var hexToRgba = (color, alpha = 1) => {
1320
+ const rgb = hexToRgb(color);
1321
+ if (rgb !== null) {
1322
+ return `rgba(${rgb.r},${rgb.g},${rgb.b},${alpha})`;
1323
+ }
1324
+ return null;
1325
+ };
1326
+ function rgbaToHex(orig) {
1327
+ const rgb = orig.replace(/\s/g, "").match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i);
1328
+ if (!rgb) {
1329
+ return orig;
1330
+ }
1331
+ const alphaStr = (rgb[4] || "").trim();
1332
+ const hexRgb = (Number(rgb[1]) | 1 << 8).toString(16).slice(1) + (Number(rgb[2]) | 1 << 8).toString(16).slice(1) + (Number(rgb[3]) | 1 << 8).toString(16).slice(1);
1333
+ const numericAlpha = alphaStr !== "" ? Number(alphaStr) : 1;
1334
+ const clampedAlpha = Math.max(0, Math.min(1, Number.isNaN(numericAlpha) ? 1 : numericAlpha));
1335
+ const hexAlpha = (Math.round(clampedAlpha * 255) | 1 << 8).toString(16).slice(1);
1336
+ return hexRgb + hexAlpha;
1337
+ }
1338
+ var deconstructRgba = (rgba) => {
1339
+ return rgba.replace(/[^\d.,]/g, "").split(",").map((x) => Number(x));
1340
+ };
1341
+ var formatRgba = (color) => {
1342
+ return `rgba(${color.r},${color.g},${color.b},${color.a})`;
1343
+ };
1344
+ var interpolateColor = (colorA, colorB, progress) => {
1345
+ const rgbaColorA = hexToRgba(colorA);
1346
+ const rgbaColorB = hexToRgba(colorB);
1347
+ if (rgbaColorA && rgbaColorB) {
1348
+ const [r1, g1, b1, a1] = deconstructRgba(rgbaColorA);
1349
+ const [r2, g2, b2, a2] = deconstructRgba(rgbaColorB);
1350
+ const clampedProgress = Math.max(0, Math.min(1, progress));
1351
+ return formatRgba({
1352
+ r: Math.round(r1 + (r2 - r1) * clampedProgress),
1353
+ g: Math.round(g1 + (g2 - g1) * clampedProgress),
1354
+ b: Math.round(b1 + (b2 - b1) * clampedProgress),
1355
+ a: Number((a1 + (a2 - a1) * clampedProgress).toFixed(3))
1356
+ });
1357
+ }
1358
+ return null;
1359
+ };
1360
+
1361
+ // src/components/FaceEyes.tsx
1362
+ var import_pixi = require("pixi.js");
1363
+ var import_react2 = require("@pixi/react");
1364
+ var import_react3 = require("react");
1365
+ var import_jsx_runtime2 = require("react/jsx-runtime");
1366
+ var EYEBROW_POINTS = [
1367
+ { x: -5, y: 2.5 },
1368
+ { x: -4, y: 1.6 },
1369
+ { x: -3, y: 0.9 },
1370
+ { x: -2, y: 0.4 },
1371
+ { x: -1, y: 0.1 },
1372
+ { x: 0, y: 0 },
1373
+ { x: 1, y: 0.1 },
1374
+ { x: 2, y: 0.4 },
1375
+ { x: 3, y: 0.9 },
1376
+ { x: 4, y: 1.6 },
1377
+ { x: 5, y: 2.5 }
1378
+ ];
1379
+ function FaceEyes({
1380
+ scale,
1381
+ frozen = false
1382
+ }) {
1383
+ const message = useFaceStore((state) => state.lastMessage);
1384
+ const face = useFaceStore((state) => state.selectedFace);
1385
+ const gaze = useFaceStore((state) => state.gaze);
1386
+ const pixiSettings = useFaceStore((state) => state.faceSettings.pixiSettings);
1387
+ (0, import_react2.useExtend)({ Container: import_pixi.Container, Sprite: import_pixi.Sprite, Graphics: import_pixi.Graphics });
1388
+ const [faceSheet, setFaceSheet] = (0, import_react3.useState)(null);
1389
+ const [cheekTexture, setCheekTexture] = (0, import_react3.useState)(null);
1390
+ const [eyeBrows, setEyeBrows] = (0, import_react3.useState)("Hugo");
1391
+ const leftEyeTexture = (0, import_react3.useMemo)(() => {
1392
+ if (!faceSheet) return import_pixi.Texture.EMPTY;
1393
+ const emotion = message?.emotion || "Neutral";
1394
+ return faceSheet.textures?.[`${emotion.toLowerCase()}_l.png`] || faceSheet.textures?.["neutral_l.png"] || import_pixi.Texture.EMPTY;
1395
+ }, [message, faceSheet]);
1396
+ const rightEyeTexture = (0, import_react3.useMemo)(() => {
1397
+ if (!faceSheet) return import_pixi.Texture.EMPTY;
1398
+ const emotion = message?.emotion || "Neutral";
1399
+ return faceSheet.textures?.[`${emotion.toLowerCase()}_r.png`] || faceSheet.textures?.["neutral_r.png"] || import_pixi.Texture.EMPTY;
1400
+ }, [message, faceSheet]);
1401
+ const breathingScaleRef = (0, import_react3.useRef)(1);
1402
+ const breathingTimeRef = (0, import_react3.useRef)(0);
1403
+ const blinkScaleRef = (0, import_react3.useRef)(1);
1404
+ const isBlinkingRef = (0, import_react3.useRef)(false);
1405
+ const blinkEveryRef = (0, import_react3.useRef)(500);
1406
+ const blinkTimerRef = (0, import_react3.useRef)(0);
1407
+ const blinkTargetScaleRef = (0, import_react3.useRef)(1);
1408
+ const currentGazeRef = (0, import_react3.useRef)({ x: 0, y: 0 });
1409
+ const leftEyeContainerRef = (0, import_react3.useRef)(null);
1410
+ const rightEyeContainerRef = (0, import_react3.useRef)(null);
1411
+ const leftEyebrowRef = (0, import_react3.useRef)(null);
1412
+ const rightEyebrowRef = (0, import_react3.useRef)(null);
1413
+ const leftEyeSpriteRef = (0, import_react3.useRef)(null);
1414
+ const rightEyeSpriteRef = (0, import_react3.useRef)(null);
1415
+ const leftCheekRef = (0, import_react3.useRef)(null);
1416
+ const rightCheekRef = (0, import_react3.useRef)(null);
1417
+ const positions = (0, import_react3.useMemo)(() => {
1418
+ return {
1419
+ leftEyeX: -300 * scale,
1420
+ rightEyeX: 300 * scale,
1421
+ leftEyeY: 0,
1422
+ rightEyeY: 0,
1423
+ leftEyeToRightEyeScaleRatio: 1.1,
1424
+ cheekYOffset: 150 * scale,
1425
+ eyebrowMultiplier: 7.5 * scale,
1426
+ eyebrowOffset: -180 * scale
1427
+ };
1428
+ }, [scale]);
1429
+ (0, import_react2.useTick)((ticker) => {
1430
+ const deltaTime = frozen ? 0 : ticker.deltaTime;
1431
+ const frequency = 785e-5;
1432
+ breathingTimeRef.current += deltaTime;
1433
+ breathingScaleRef.current = 1 + 0.1 * Math.sin(breathingTimeRef.current * frequency);
1434
+ const blinkDuration = 20;
1435
+ const blinkSpeed = 0.5;
1436
+ blinkTimerRef.current += deltaTime;
1437
+ if (isBlinkingRef.current) {
1438
+ if (blinkTimerRef.current > blinkDuration) {
1439
+ blinkEveryRef.current = 200 + Math.random() * 400;
1440
+ blinkTargetScaleRef.current = 1;
1441
+ isBlinkingRef.current = false;
1442
+ blinkTimerRef.current = 0;
1443
+ }
1444
+ } else if (blinkTimerRef.current > blinkEveryRef.current) {
1445
+ blinkTargetScaleRef.current = 0.05;
1446
+ isBlinkingRef.current = true;
1447
+ blinkTimerRef.current = 0;
1448
+ }
1449
+ blinkScaleRef.current += (blinkTargetScaleRef.current - blinkScaleRef.current) * blinkSpeed * deltaTime;
1450
+ currentGazeRef.current.x += (gaze.x - currentGazeRef.current.x) * 0.15;
1451
+ currentGazeRef.current.y += (gaze.y - currentGazeRef.current.y) * 0.15;
1452
+ const gazeOffsetX = currentGazeRef.current.x * 40 * scale;
1453
+ const gazeOffsetY = currentGazeRef.current.y * 30 * scale;
1454
+ if (leftEyeContainerRef.current) {
1455
+ leftEyeContainerRef.current.x = positions.leftEyeX + gazeOffsetX;
1456
+ leftEyeContainerRef.current.y = positions.leftEyeY + gazeOffsetY;
1457
+ }
1458
+ if (rightEyeContainerRef.current) {
1459
+ rightEyeContainerRef.current.x = positions.rightEyeX + gazeOffsetX;
1460
+ rightEyeContainerRef.current.y = positions.rightEyeY + gazeOffsetY;
1461
+ }
1462
+ const breathe = breathingScaleRef.current;
1463
+ const blink = blinkScaleRef.current;
1464
+ if (leftEyeSpriteRef.current) {
1465
+ leftEyeSpriteRef.current.scale.x = positions.leftEyeToRightEyeScaleRatio * breathe * scale;
1466
+ leftEyeSpriteRef.current.scale.y = positions.leftEyeToRightEyeScaleRatio * breathe * blink * scale;
1467
+ }
1468
+ if (rightEyeSpriteRef.current) {
1469
+ rightEyeSpriteRef.current.scale.x = 1 * breathe * scale;
1470
+ rightEyeSpriteRef.current.scale.y = 1 * breathe * blink * scale;
1471
+ }
1472
+ if (leftCheekRef.current) {
1473
+ leftCheekRef.current.scale.x = 0.08 * breathe * scale;
1474
+ leftCheekRef.current.scale.y = 0.04 * breathe * scale;
1475
+ }
1476
+ if (rightCheekRef.current) {
1477
+ rightCheekRef.current.scale.x = 0.08 * breathe * scale;
1478
+ rightCheekRef.current.scale.y = 0.04 * breathe * scale;
1479
+ }
1480
+ const strokeWidth = Math.max(1.5, 3 * scale);
1481
+ if (leftEyebrowRef.current) {
1482
+ const g = leftEyebrowRef.current;
1483
+ g.clear();
1484
+ const mult = positions.eyebrowMultiplier * breathe;
1485
+ g.moveTo(EYEBROW_POINTS[0].x * mult, EYEBROW_POINTS[0].y * mult);
1486
+ for (let i = 1; i < EYEBROW_POINTS.length; i++) {
1487
+ g.lineTo(EYEBROW_POINTS[i].x * mult, EYEBROW_POINTS[i].y * mult);
1488
+ }
1489
+ g.stroke({
1490
+ width: strokeWidth,
1491
+ color: "black",
1492
+ cap: "round",
1493
+ join: "round"
1494
+ });
1495
+ }
1496
+ if (rightEyebrowRef.current) {
1497
+ const g = rightEyebrowRef.current;
1498
+ g.clear();
1499
+ const mult = positions.eyebrowMultiplier * breathe;
1500
+ g.moveTo(EYEBROW_POINTS[0].x * mult, EYEBROW_POINTS[0].y * mult);
1501
+ for (let i = 1; i < EYEBROW_POINTS.length; i++) {
1502
+ g.lineTo(EYEBROW_POINTS[i].x * mult, EYEBROW_POINTS[i].y * mult);
1503
+ }
1504
+ g.stroke({
1505
+ width: strokeWidth,
1506
+ color: "black",
1507
+ cap: "round",
1508
+ join: "round"
1509
+ });
1510
+ }
1511
+ });
1512
+ const drawEyebrow = (0, import_react3.useCallback)(
1513
+ (g) => {
1514
+ g.clear();
1515
+ const mult = positions.eyebrowMultiplier * breathingScaleRef.current;
1516
+ const strokeWidth = Math.max(1.5, 3 * scale);
1517
+ g.moveTo(EYEBROW_POINTS[0].x * mult, EYEBROW_POINTS[0].y * mult);
1518
+ for (let i = 1; i < EYEBROW_POINTS.length; i++) {
1519
+ g.lineTo(EYEBROW_POINTS[i].x * mult, EYEBROW_POINTS[i].y * mult);
1520
+ }
1521
+ g.stroke({
1522
+ width: strokeWidth,
1523
+ color: "black",
1524
+ cap: "round",
1525
+ join: "round"
1526
+ });
1527
+ },
1528
+ [positions.eyebrowMultiplier, scale]
1529
+ );
1530
+ (0, import_react3.useEffect)(() => {
1531
+ let cancelled = false;
1532
+ async function loadAvatarTextures(currentFace) {
1533
+ if (currentFace?.kind !== "PixiFace" || currentFace.type !== "avatar") {
1534
+ return;
1535
+ }
1536
+ try {
1537
+ if (currentFace.eyes?.kind === "spritesheet") {
1538
+ const sheet = await import_pixi.Assets.load(currentFace.eyes.path);
1539
+ if (!cancelled) {
1540
+ setFaceSheet(sheet);
1541
+ }
1542
+ }
1543
+ if (currentFace.cheeks?.kind === "texture") {
1544
+ const cheek = await import_pixi.Assets.load(currentFace.cheeks.path);
1545
+ if (!cancelled) {
1546
+ setCheekTexture(cheek);
1547
+ }
1548
+ } else if (!cancelled) {
1549
+ setCheekTexture(null);
1550
+ }
1551
+ if (!cancelled) {
1552
+ setEyeBrows(currentFace.eyebrows);
1553
+ }
1554
+ } catch (err) {
1555
+ console.warn("Failed to load PixiFace textures:", err);
1556
+ }
1557
+ }
1558
+ void loadAvatarTextures(face);
1559
+ return () => {
1560
+ cancelled = true;
1561
+ };
1562
+ }, [face]);
1563
+ if (pixiSettings?.eyeDisplay === "none") {
1564
+ return null;
1565
+ }
1566
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
1567
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1568
+ "pixiContainer",
1569
+ {
1570
+ ref: leftEyeContainerRef,
1571
+ position: { x: positions.leftEyeX, y: positions.leftEyeY },
1572
+ label: "LeftEyeContainer",
1573
+ children: [
1574
+ eyeBrows === "Hugo" && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1575
+ "pixiGraphics",
1576
+ {
1577
+ ref: leftEyebrowRef,
1578
+ label: "LeftEyebrow",
1579
+ position: { x: 0, y: positions.eyebrowOffset },
1580
+ draw: drawEyebrow
1581
+ }
1582
+ ),
1583
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1584
+ "pixiSprite",
1585
+ {
1586
+ ref: leftEyeSpriteRef,
1587
+ label: "LeftEye",
1588
+ anchor: { x: 0.5, y: 0.5 },
1589
+ position: { x: 0, y: 0 },
1590
+ texture: leftEyeTexture,
1591
+ pivot: { x: 0.5, y: 0.5 }
1592
+ }
1593
+ ),
1594
+ cheekTexture && pixiSettings?.cheekDisplay !== "none" && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1595
+ "pixiSprite",
1596
+ {
1597
+ ref: leftCheekRef,
1598
+ label: "LeftCheek",
1599
+ texture: cheekTexture,
1600
+ pivot: { x: 0.5, y: 0.5 },
1601
+ anchor: { x: 0.5, y: 0.5 },
1602
+ position: { x: 0, y: positions.cheekYOffset }
1603
+ }
1604
+ )
1605
+ ]
1606
+ }
1607
+ ),
1608
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1609
+ "pixiContainer",
1610
+ {
1611
+ ref: rightEyeContainerRef,
1612
+ position: { x: positions.rightEyeX, y: positions.rightEyeY },
1613
+ label: "RightEyeContainer",
1614
+ children: [
1615
+ eyeBrows === "Hugo" && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1616
+ "pixiGraphics",
1617
+ {
1618
+ ref: rightEyebrowRef,
1619
+ label: "RightEyebrow",
1620
+ position: { x: 0, y: positions.eyebrowOffset },
1621
+ draw: drawEyebrow
1622
+ }
1623
+ ),
1624
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1625
+ "pixiSprite",
1626
+ {
1627
+ ref: rightEyeSpriteRef,
1628
+ label: "RightEye",
1629
+ position: { x: 0, y: 0 },
1630
+ pivot: { x: 0.5, y: 0.5 },
1631
+ anchor: { x: 0.5, y: 0.5 },
1632
+ texture: rightEyeTexture
1633
+ }
1634
+ ),
1635
+ cheekTexture && pixiSettings?.cheekDisplay !== "none" && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1636
+ "pixiSprite",
1637
+ {
1638
+ ref: rightCheekRef,
1639
+ label: "RightCheek",
1640
+ texture: cheekTexture,
1641
+ pivot: { x: 0.5, y: 0.5 },
1642
+ anchor: { x: 0.5, y: 0.5 },
1643
+ position: { x: 0, y: positions.cheekYOffset }
1644
+ }
1645
+ )
1646
+ ]
1647
+ }
1648
+ )
1649
+ ] });
1650
+ }
1651
+
1652
+ // src/components/FaceMouth.tsx
1653
+ var import_react4 = require("react");
1654
+ var import_pixi2 = require("pixi.js");
1655
+ var import_react5 = require("@pixi/react");
1656
+ var import_jsx_runtime3 = require("react/jsx-runtime");
1657
+ var ZIG_ZAG_POINTS = [
1658
+ { x: 0, y: -10 },
1659
+ { x: 10, y: 10 },
1660
+ { x: 20, y: -10 },
1661
+ { x: 30, y: 10 },
1662
+ { x: 40, y: -10 },
1663
+ { x: 50, y: 10 },
1664
+ { x: 60, y: -10 },
1665
+ { x: 70, y: 10 },
1666
+ { x: 80, y: -10 },
1667
+ { x: 90, y: 10 },
1668
+ { x: 100, y: -10 },
1669
+ { x: 110, y: 10 }
1670
+ ];
1671
+ var SMILEY_POINTS = [
1672
+ { x: -40, y: 40 },
1673
+ { x: -30, y: 30 },
1674
+ { x: -20, y: 20 },
1675
+ { x: -10, y: 10 },
1676
+ { x: 0, y: 0 },
1677
+ { x: 10, y: 10 },
1678
+ { x: 20, y: 20 },
1679
+ { x: 30, y: 30 },
1680
+ { x: 40, y: 40 }
1681
+ ];
1682
+ function FaceMouth({
1683
+ scale,
1684
+ frozen = false
1685
+ }) {
1686
+ (0, import_react5.useExtend)({ Graphics: import_pixi2.Graphics });
1687
+ const talking = useFaceStore((state) => state.isSpeaking);
1688
+ const face = useFaceStore((state) => state.selectedFace);
1689
+ const pixiSettings = useFaceStore((state) => state.faceSettings.pixiSettings);
1690
+ const currentAmplitude = useFaceStore((state) => state.currentAmplitude);
1691
+ const amplitudeData = useFaceStore((state) => state.amplitudeData);
1692
+ const speechStartTime = useFaceStore((state) => state.speechStartTime);
1693
+ const talkingScaleRef = (0, import_react4.useRef)(1);
1694
+ const talkingTimeRef = (0, import_react4.useRef)(0);
1695
+ const talkingShape = (0, import_react4.useMemo)(
1696
+ () => face?.kind === "PixiFace" && face.type === "avatar" ? face.mouth : "Ellipse",
1697
+ [face]
1698
+ );
1699
+ const graphicsRef = (0, import_react4.useRef)(null);
1700
+ const getAmplitudeAtTime = (0, import_react4.useCallback)(
1701
+ (timeMs) => {
1702
+ if (!amplitudeData || amplitudeData.length === 0) return 0;
1703
+ const point = amplitudeData.find((p, i) => {
1704
+ const nextPoint = amplitudeData[i + 1];
1705
+ return p.time <= timeMs && (!nextPoint || nextPoint.time > timeMs);
1706
+ });
1707
+ return point ? point.value : 0;
1708
+ },
1709
+ [amplitudeData]
1710
+ );
1711
+ const drawMouth = (0, import_react4.useCallback)(
1712
+ (graphics) => {
1713
+ graphics.clear();
1714
+ const talkingScale = talkingScaleRef.current;
1715
+ const talkingTime = talkingTimeRef.current;
1716
+ switch (talkingShape) {
1717
+ case "Hugo": {
1718
+ const width = 40 * scale;
1719
+ const smileDepth = 20 * scale;
1720
+ const openHeight = talking ? talkingScale * 30 * scale : 0;
1721
+ const topLipLift = talking ? talkingScale * 10 * scale : 0;
1722
+ const centerY = scale * 240;
1723
+ graphics.moveTo(-width, centerY);
1724
+ graphics.quadraticCurveTo(
1725
+ 0,
1726
+ centerY + smileDepth * 0.5 - topLipLift,
1727
+ width,
1728
+ centerY
1729
+ );
1730
+ graphics.quadraticCurveTo(
1731
+ 0,
1732
+ centerY + smileDepth + openHeight * 1.5,
1733
+ -width,
1734
+ centerY
1735
+ );
1736
+ graphics.fill({ color: "black" });
1737
+ break;
1738
+ }
1739
+ case "Beak": {
1740
+ SMILEY_POINTS.forEach((eachPoint, index) => {
1741
+ const y = talkingScale * (Math.pow(40, 1.1) - Math.pow(Math.abs(eachPoint.x), 1.1)) + scale * 240;
1742
+ if (index === 0) {
1743
+ graphics.moveTo(eachPoint.x, y);
1744
+ }
1745
+ graphics.lineTo(eachPoint.x, y);
1746
+ });
1747
+ graphics.moveTo(SMILEY_POINTS[0].x, -1 * SMILEY_POINTS[0].y);
1748
+ SMILEY_POINTS.forEach((eachPoint, index) => {
1749
+ const y = -1 * talkingScale * (Math.pow(40, 1.1) - Math.pow(Math.abs(eachPoint.x), 1.1)) + scale * 240;
1750
+ if (index === 0) {
1751
+ graphics.moveTo(eachPoint.x, y);
1752
+ }
1753
+ graphics.lineTo(eachPoint.x, y);
1754
+ });
1755
+ break;
1756
+ }
1757
+ case "ZigZag": {
1758
+ ZIG_ZAG_POINTS.forEach((eachPoint, index) => {
1759
+ const x = eachPoint.x - ZIG_ZAG_POINTS[ZIG_ZAG_POINTS.length - 1].x / 2;
1760
+ const y = talking ? Math.sin(talkingTime * 0.3 + index * 5) * (10 * talkingScale) + scale * 240 : eachPoint.y + scale * 240;
1761
+ if (index === 0) {
1762
+ graphics.moveTo(x, y);
1763
+ }
1764
+ graphics.lineTo(x, y);
1765
+ });
1766
+ break;
1767
+ }
1768
+ case "Ellipse":
1769
+ default: {
1770
+ graphics.ellipse(
1771
+ 0,
1772
+ scale * 240,
1773
+ scale * 60,
1774
+ talking ? 2 + talkingScale * scale * 15 : 4
1775
+ );
1776
+ graphics.fill({ color: "black" });
1777
+ break;
1778
+ }
1779
+ }
1780
+ graphics.stroke({ color: "black", width: 2 });
1781
+ },
1782
+ [scale, talking, talkingShape]
1783
+ );
1784
+ (0, import_react5.useTick)((time) => {
1785
+ if (frozen) return;
1786
+ let targetScale;
1787
+ if (talking) {
1788
+ if (currentAmplitude > 0) {
1789
+ targetScale = Math.min(currentAmplitude * 1.5, 1);
1790
+ } else if (amplitudeData && speechStartTime) {
1791
+ const elapsed = performance.now() - speechStartTime;
1792
+ targetScale = Math.min(getAmplitudeAtTime(elapsed) * 1.5, 1);
1793
+ } else {
1794
+ targetScale = Math.abs(Math.sin(time.lastTime * 0.1));
1795
+ }
1796
+ talkingTimeRef.current = time.lastTime;
1797
+ } else {
1798
+ targetScale = 0;
1799
+ }
1800
+ const lerpAlpha = 0.2;
1801
+ talkingScaleRef.current += (targetScale - talkingScaleRef.current) * lerpAlpha;
1802
+ if (graphicsRef.current) {
1803
+ drawMouth(graphicsRef.current);
1804
+ }
1805
+ });
1806
+ if (pixiSettings?.mouthDisplay === "none") return null;
1807
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("pixiGraphics", { ref: graphicsRef, label: "Mouth", draw: drawMouth });
1808
+ }
1809
+
1810
+ // src/components/FaceText.tsx
1811
+ var import_react7 = require("react");
1812
+ var import_pixi3 = require("pixi.js");
1813
+ var import_react8 = require("@pixi/react");
1814
+
1815
+ // src/helpers/emotion_mapper.ts
1816
+ var EMOTION_EMOTICONS = {
1817
+ Happy: ":D",
1818
+ Sad: ":(",
1819
+ Surprised: ":o",
1820
+ Neutral: ":)",
1821
+ Sleepy: ":z",
1822
+ Concerned: ":/"
1823
+ };
1824
+ var EMOTION_EMOJIS = {
1825
+ Happy: "\u{1F600}",
1826
+ Sad: "\u{1F622}",
1827
+ Surprised: "\u{1F62E}",
1828
+ Neutral: "\u{1F610}",
1829
+ Sleepy: "\u{1F634}",
1830
+ Concerned: "\u{1F61F}"
1831
+ };
1832
+ var EMOTION_ICON_FILES = {
1833
+ Neutral: "Neutral.png",
1834
+ Surprised: "Surprised.png",
1835
+ Happy: "Neutral.png",
1836
+ Sad: "Sad.png",
1837
+ Concerned: "Concerned.png",
1838
+ Sleepy: "Sleep.png"
1839
+ };
1840
+ function getEmotionIconPath(emotion, assetBaseUrl) {
1841
+ const base = normalizeAssetBaseUrl(assetBaseUrl);
1842
+ const file = EMOTION_ICON_FILES[emotion] ?? EMOTION_ICON_FILES.Neutral;
1843
+ return `${base}/Icons/${file}`;
1844
+ }
1845
+ var emotion_mapping = {
1846
+ Neutral: getEmotionIconPath("Neutral"),
1847
+ Surprised: getEmotionIconPath("Surprised"),
1848
+ Happy: getEmotionIconPath("Happy"),
1849
+ Sad: getEmotionIconPath("Sad"),
1850
+ Concerned: getEmotionIconPath("Concerned"),
1851
+ Sleepy: getEmotionIconPath("Sleepy")
1852
+ };
1853
+
1854
+ // src/hooks/useMessageVisualState.ts
1855
+ var import_react6 = require("react");
1856
+ function useMessageVisualState(isSpeaking, config = {}) {
1857
+ const {
1858
+ msPerChar = 50,
1859
+ persistenceDuration = 3e3,
1860
+ pauseBeforeNextMsg = 500
1861
+ } = config;
1862
+ const [displayText, setDisplayText] = (0, import_react6.useState)("");
1863
+ const [visualState, setVisualState] = (0, import_react6.useState)("IDLE");
1864
+ const stateRef = (0, import_react6.useRef)("IDLE");
1865
+ const displayTextRef = (0, import_react6.useRef)("");
1866
+ const currentMsgRef = (0, import_react6.useRef)(null);
1867
+ const nextMsgRef = (0, import_react6.useRef)(null);
1868
+ const timerRef = (0, import_react6.useRef)(0);
1869
+ const charTimerRef = (0, import_react6.useRef)(0);
1870
+ const typingIndexRef = (0, import_react6.useRef)(0);
1871
+ const startShowing = (0, import_react6.useCallback)(
1872
+ (speech) => {
1873
+ currentMsgRef.current = speech;
1874
+ nextMsgRef.current = null;
1875
+ stateRef.current = "SHOWING";
1876
+ setVisualState("SHOWING");
1877
+ typingIndexRef.current = 0;
1878
+ charTimerRef.current = 0;
1879
+ if (msPerChar <= 0) {
1880
+ setDisplayText(speech);
1881
+ displayTextRef.current = speech;
1882
+ typingIndexRef.current = speech.length;
1883
+ } else {
1884
+ setDisplayText("");
1885
+ displayTextRef.current = "";
1886
+ }
1887
+ },
1888
+ [msPerChar]
1889
+ );
1890
+ const queueMessage = (0, import_react6.useCallback)(
1891
+ (speech) => {
1892
+ if (stateRef.current === "IDLE" || stateRef.current === "PERSISTING") {
1893
+ startShowing(speech);
1894
+ return;
1895
+ }
1896
+ nextMsgRef.current = speech;
1897
+ },
1898
+ [startShowing]
1899
+ );
1900
+ const update = (0, import_react6.useCallback)(
1901
+ (ms) => {
1902
+ const prevState = stateRef.current;
1903
+ switch (stateRef.current) {
1904
+ case "IDLE":
1905
+ if (displayTextRef.current !== "") {
1906
+ setDisplayText("");
1907
+ displayTextRef.current = "";
1908
+ }
1909
+ if (nextMsgRef.current) {
1910
+ startShowing(nextMsgRef.current);
1911
+ }
1912
+ break;
1913
+ case "SHOWING":
1914
+ if (!currentMsgRef.current) {
1915
+ stateRef.current = "IDLE";
1916
+ break;
1917
+ }
1918
+ if (msPerChar <= 0) {
1919
+ if (nextMsgRef.current) {
1920
+ stateRef.current = "PAUSED";
1921
+ timerRef.current = 0;
1922
+ } else {
1923
+ stateRef.current = "WAITING_FOR_AUDIO";
1924
+ }
1925
+ break;
1926
+ }
1927
+ charTimerRef.current += ms;
1928
+ if (charTimerRef.current > msPerChar) {
1929
+ const fullText = currentMsgRef.current;
1930
+ const charCountToAdd = Math.floor(charTimerRef.current / msPerChar);
1931
+ charTimerRef.current %= msPerChar;
1932
+ const nextIndex = typingIndexRef.current + charCountToAdd;
1933
+ if (nextIndex >= fullText.length) {
1934
+ setDisplayText(fullText);
1935
+ displayTextRef.current = fullText;
1936
+ typingIndexRef.current = fullText.length;
1937
+ if (nextMsgRef.current) {
1938
+ stateRef.current = "PAUSED";
1939
+ timerRef.current = 0;
1940
+ } else {
1941
+ stateRef.current = "WAITING_FOR_AUDIO";
1942
+ }
1943
+ } else {
1944
+ typingIndexRef.current = nextIndex;
1945
+ const partial = fullText.substring(0, nextIndex);
1946
+ setDisplayText(partial);
1947
+ displayTextRef.current = partial;
1948
+ }
1949
+ }
1950
+ break;
1951
+ case "WAITING_FOR_AUDIO":
1952
+ if (nextMsgRef.current) {
1953
+ stateRef.current = "PAUSED";
1954
+ timerRef.current = 0;
1955
+ break;
1956
+ }
1957
+ if (!isSpeaking) {
1958
+ stateRef.current = "PERSISTING";
1959
+ timerRef.current = 0;
1960
+ }
1961
+ break;
1962
+ case "PERSISTING":
1963
+ if (nextMsgRef.current) {
1964
+ stateRef.current = "PAUSED";
1965
+ timerRef.current = 0;
1966
+ break;
1967
+ }
1968
+ timerRef.current += ms;
1969
+ if (timerRef.current > persistenceDuration) {
1970
+ stateRef.current = "IDLE";
1971
+ }
1972
+ break;
1973
+ case "PAUSED":
1974
+ timerRef.current += ms;
1975
+ if (timerRef.current > pauseBeforeNextMsg) {
1976
+ if (nextMsgRef.current) {
1977
+ startShowing(nextMsgRef.current);
1978
+ } else {
1979
+ stateRef.current = "WAITING_FOR_AUDIO";
1980
+ }
1981
+ }
1982
+ break;
1983
+ }
1984
+ if (stateRef.current !== prevState) {
1985
+ setVisualState(stateRef.current);
1986
+ }
1987
+ },
1988
+ [
1989
+ isSpeaking,
1990
+ msPerChar,
1991
+ persistenceDuration,
1992
+ pauseBeforeNextMsg,
1993
+ startShowing
1994
+ ]
1995
+ );
1996
+ return {
1997
+ displayText,
1998
+ visualState,
1999
+ queueMessage,
2000
+ update
2001
+ };
2002
+ }
2003
+
2004
+ // src/components/FaceText.tsx
2005
+ var import_jsx_runtime4 = require("react/jsx-runtime");
2006
+ var FONT_FAMILY = "Courier New, Courier, monospace";
2007
+ var TEXT_PERSISTENCE_DURATION = 3e3;
2008
+ var MS_PER_CHAR = 50;
2009
+ var PAUSE_BEFORE_NEXT_MSG = 500;
2010
+ function FaceText({ scale }) {
2011
+ (0, import_react8.useExtend)({ Text: import_pixi3.Text });
2012
+ const lastMessage = useFaceStore((state) => state.lastMessage);
2013
+ const isSpeaking = useFaceStore((state) => state.isSpeaking);
2014
+ const selectedFace = useFaceStore((state) => state.selectedFace);
2015
+ const pixiSettings = useFaceStore((state) => state.faceSettings.pixiSettings);
2016
+ const emotionType = (0, import_react7.useMemo)(() => {
2017
+ if (pixiSettings?.emotionDisplay) {
2018
+ return pixiSettings.emotionDisplay;
2019
+ }
2020
+ if (selectedFace?.kind === "PixiFace" && selectedFace.type === "text") {
2021
+ return selectedFace.showEmotion;
2022
+ }
2023
+ return "emoticon";
2024
+ }, [pixiSettings?.emotionDisplay, selectedFace]);
2025
+ const { displayText, queueMessage, update } = useMessageVisualState(
2026
+ isSpeaking,
2027
+ {
2028
+ msPerChar: MS_PER_CHAR,
2029
+ persistenceDuration: TEXT_PERSISTENCE_DURATION,
2030
+ pauseBeforeNextMsg: PAUSE_BEFORE_NEXT_MSG
2031
+ }
2032
+ );
2033
+ (0, import_react7.useEffect)(() => {
2034
+ queueMessage(lastMessage.speech);
2035
+ }, [lastMessage.speech, queueMessage]);
2036
+ (0, import_react8.useTick)((delta) => {
2037
+ update(delta.deltaMS);
2038
+ });
2039
+ const emotionStyle = (0, import_react7.useMemo)(
2040
+ () => new import_pixi3.TextStyle({
2041
+ fontFamily: FONT_FAMILY,
2042
+ fontSize: Math.max(12, 48 * scale),
2043
+ fill: "black",
2044
+ align: "center"
2045
+ }),
2046
+ [scale]
2047
+ );
2048
+ const bodyStyle = (0, import_react7.useMemo)(
2049
+ () => new import_pixi3.TextStyle({
2050
+ fontFamily: FONT_FAMILY,
2051
+ fontSize: Math.max(12, 48 * scale),
2052
+ fill: "black",
2053
+ align: "center",
2054
+ wordWrap: true,
2055
+ wordWrapWidth: Math.max(200, 800 * scale)
2056
+ }),
2057
+ [scale]
2058
+ );
2059
+ const emotionSymbol = emotionType === "emoji" ? EMOTION_EMOJIS[lastMessage.emotion] : EMOTION_EMOTICONS[lastMessage.emotion];
2060
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
2061
+ emotionType !== "none" && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
2062
+ "pixiText",
2063
+ {
2064
+ anchor: 0.5,
2065
+ x: 0,
2066
+ y: -50 * scale,
2067
+ text: emotionSymbol,
2068
+ style: emotionStyle
2069
+ }
2070
+ ),
2071
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
2072
+ "pixiText",
2073
+ {
2074
+ text: displayText,
2075
+ anchor: 0.5,
2076
+ x: 0,
2077
+ y: 0,
2078
+ style: bodyStyle
2079
+ }
2080
+ )
2081
+ ] });
2082
+ }
2083
+
2084
+ // src/components/FaceBackground.tsx
2085
+ var import_react9 = require("react");
2086
+ var import_pixi4 = require("pixi.js");
2087
+ var import_react10 = require("@pixi/react");
2088
+ var import_jsx_runtime5 = require("react/jsx-runtime");
2089
+ function createRadialGradientTexture(size) {
2090
+ if (typeof document === "undefined") {
2091
+ return import_pixi4.Texture.EMPTY;
2092
+ }
2093
+ const canvas = document.createElement("canvas");
2094
+ canvas.width = size;
2095
+ canvas.height = size;
2096
+ const ctx = canvas.getContext("2d");
2097
+ if (!ctx) return import_pixi4.Texture.EMPTY;
2098
+ const gradient = ctx.createRadialGradient(
2099
+ size / 2,
2100
+ size / 2,
2101
+ 0,
2102
+ size / 2,
2103
+ size / 2,
2104
+ size / 2
2105
+ );
2106
+ gradient.addColorStop(0, "rgba(255, 255, 255, 0.7)");
2107
+ gradient.addColorStop(0.4, "rgba(255, 255, 255, 0.2)");
2108
+ gradient.addColorStop(1, "rgba(255, 255, 255, 0)");
2109
+ ctx.fillStyle = gradient;
2110
+ ctx.fillRect(0, 0, size, size);
2111
+ return import_pixi4.Texture.from(canvas);
2112
+ }
2113
+ function FaceBackground() {
2114
+ (0, import_react10.useExtend)({ Sprite: import_pixi4.Sprite });
2115
+ const { app, isInitialised } = (0, import_react10.useApplication)();
2116
+ const texture = (0, import_react9.useMemo)(() => createRadialGradientTexture(1024), []);
2117
+ if (!app || !isInitialised || !app.renderer) return null;
2118
+ const screenWidth = app.renderer.screen && app.renderer.screen.width || app.renderer.width || 2e3;
2119
+ const screenHeight = app.renderer.screen && app.renderer.screen.height || app.renderer.height || 2e3;
2120
+ const size = Math.max(screenWidth, screenHeight) * 2;
2121
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2122
+ "pixiSprite",
2123
+ {
2124
+ texture,
2125
+ anchor: 0.5,
2126
+ width: size,
2127
+ height: size,
2128
+ x: 0,
2129
+ y: 0,
2130
+ blendMode: "screen",
2131
+ alpha: 0.5
2132
+ }
2133
+ );
2134
+ }
2135
+
2136
+ // src/components/FaceContainer.tsx
2137
+ var import_jsx_runtime6 = require("react/jsx-runtime");
2138
+ function stepRendererBackgroundColor(renderer, targetHex) {
2139
+ try {
2140
+ const currentHex = renderer.background.color.toHex();
2141
+ if (currentHex.toLowerCase() === targetHex.toLowerCase()) {
2142
+ return;
2143
+ }
2144
+ const interpolated = interpolateColor(currentHex, targetHex, 0.1);
2145
+ if (interpolated !== null) {
2146
+ renderer.background.color = rgbaToHex(interpolated);
2147
+ }
2148
+ } catch (err) {
2149
+ void err;
2150
+ }
2151
+ }
2152
+ function FaceContainer({ frozen = false }) {
2153
+ (0, import_react12.useExtend)({ Container: import_pixi5.Container });
2154
+ const settings = useFaceStore((state) => state.faceSettings);
2155
+ const selectedFace = useFaceStore((state) => state.selectedFace);
2156
+ const lastMessage = useFaceStore((state) => state.lastMessage);
2157
+ const { app, isInitialised } = (0, import_react12.useApplication)();
2158
+ const [layout, setLayout] = (0, import_react11.useState)({
2159
+ landscape: true,
2160
+ scale: 1,
2161
+ x: 400,
2162
+ y: 300
2163
+ });
2164
+ const isAvatar = selectedFace?.kind === "PixiFace" && selectedFace.type === "avatar";
2165
+ (0, import_react11.useEffect)(() => {
2166
+ if (!app || !isInitialised || !app.renderer) return;
2167
+ const updateLayout = () => {
2168
+ if (!app?.renderer) return;
2169
+ const width = app.renderer.screen && app.renderer.screen.width || app.renderer.width || 800;
2170
+ const height = app.renderer.screen && app.renderer.screen.height || app.renderer.height || 600;
2171
+ const isLandscape = width > height;
2172
+ const baseScale = isLandscape ? width / 1200 : height / 1200;
2173
+ const effectiveLandscape = settings.autoRotate ? isLandscape : true;
2174
+ setLayout({
2175
+ landscape: effectiveLandscape,
2176
+ scale: baseScale,
2177
+ x: width / 2,
2178
+ y: height / 2
2179
+ });
2180
+ };
2181
+ updateLayout();
2182
+ const onResize = () => {
2183
+ if (app?.renderer) {
2184
+ updateLayout();
2185
+ }
2186
+ };
2187
+ window.addEventListener("resize", onResize);
2188
+ window.addEventListener("orientationchange", onResize);
2189
+ app.renderer.on("resize", onResize);
2190
+ return () => {
2191
+ window.removeEventListener("resize", onResize);
2192
+ window.removeEventListener("orientationchange", onResize);
2193
+ if (app?.renderer) {
2194
+ app.renderer.off("resize", onResize);
2195
+ }
2196
+ };
2197
+ }, [app, isInitialised, settings.autoRotate]);
2198
+ (0, import_react12.useTick)(() => {
2199
+ if (app?.renderer && lastMessage) {
2200
+ const targetColor = color_mapping[lastMessage.color] ?? color_mapping["Light Blue"];
2201
+ stepRendererBackgroundColor(app.renderer, targetColor);
2202
+ }
2203
+ });
2204
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
2205
+ "pixiContainer",
2206
+ {
2207
+ label: "FaceContainer",
2208
+ position: {
2209
+ x: layout.x + (settings.offset?.x ?? 0),
2210
+ y: layout.y + (settings.offset?.y ?? 0)
2211
+ },
2212
+ pivot: { x: 0.5, y: 0.5 },
2213
+ angle: layout.landscape ? settings.rotation : 90 + settings.rotation,
2214
+ children: [
2215
+ isAvatar && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(FaceBackground, {}),
2216
+ selectedFace?.kind === "PixiFace" && selectedFace.type === "text" ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(FaceText, { scale: layout.scale * settings.zoom }) : /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_jsx_runtime6.Fragment, { children: [
2217
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(FaceEyes, { scale: layout.scale * settings.zoom, frozen }),
2218
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(FaceMouth, { scale: layout.scale * settings.zoom, frozen })
2219
+ ] })
2220
+ ]
2221
+ }
2222
+ );
2223
+ }
2224
+
2225
+ // src/components/FaceFullScreenButton.tsx
2226
+ var import_react13 = require("react");
2227
+ var import_react14 = require("@pixi/react");
2228
+ var import_pixi6 = require("pixi.js");
2229
+ var import_core = require("@peerbots/core");
2230
+ var import_jsx_runtime7 = require("react/jsx-runtime");
2231
+ function FaceFullScreenButton() {
2232
+ (0, import_react14.useExtend)({ Graphics: import_pixi6.Graphics, Container: import_pixi6.Container });
2233
+ const { app } = (0, import_react14.useApplication)();
2234
+ const [fullScreen, setFullScreen] = (0, import_react13.useState)(false);
2235
+ (0, import_react13.useEffect)(() => {
2236
+ if (typeof document === "undefined") {
2237
+ return;
2238
+ }
2239
+ const handleFullscreenChange = () => {
2240
+ setFullScreen(Boolean(document.fullscreenElement));
2241
+ };
2242
+ document.addEventListener("fullscreenchange", handleFullscreenChange);
2243
+ return () => {
2244
+ document.removeEventListener("fullscreenchange", handleFullscreenChange);
2245
+ };
2246
+ }, []);
2247
+ const toggleFullScreen = (0, import_react13.useCallback)(() => {
2248
+ if (typeof document === "undefined") {
2249
+ return;
2250
+ }
2251
+ if (fullScreen) {
2252
+ void document.exitFullscreen().catch((err) => {
2253
+ console.warn("Exit fullscreen error:", err);
2254
+ });
2255
+ } else {
2256
+ const container = document.getElementById("face-view-container");
2257
+ if (container) {
2258
+ container.requestFullscreen().catch((err) => {
2259
+ console.warn("Container fullscreen error:", err);
2260
+ if (app?.canvas) {
2261
+ void app.canvas.requestFullscreen().catch((canvasErr) => {
2262
+ console.warn("Canvas fullscreen error:", canvasErr);
2263
+ });
2264
+ }
2265
+ });
2266
+ } else if (app?.canvas) {
2267
+ void app.canvas.requestFullscreen().catch((err) => {
2268
+ console.warn("Canvas fullscreen error:", err);
2269
+ });
2270
+ }
2271
+ }
2272
+ }, [app, fullScreen]);
2273
+ const drawIcon = (0, import_react13.useCallback)(
2274
+ (graphics) => {
2275
+ graphics.clear();
2276
+ const pathD = fullScreen ? import_core.iconPaths.arrowsPointingIn : import_core.iconPaths.arrowsPointingOut;
2277
+ graphics.svg(`
2278
+ <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="black">
2279
+ <path strokeLinecap="round" strokeLinejoin="round" d="${pathD}" />
2280
+ </svg>
2281
+ `);
2282
+ },
2283
+ [fullScreen]
2284
+ );
2285
+ return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
2286
+ "pixiContainer",
2287
+ {
2288
+ label: "FullScreenToggle",
2289
+ x: 20,
2290
+ y: 20,
2291
+ eventMode: "static",
2292
+ onPointerDown: toggleFullScreen,
2293
+ hitArea: new import_pixi6.Rectangle(0, 0, 50, 50),
2294
+ children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
2295
+ "pixiGraphics",
2296
+ {
2297
+ onPointerDown: toggleFullScreen,
2298
+ eventMode: "static",
2299
+ draw: drawIcon
2300
+ }
2301
+ )
2302
+ }
2303
+ );
2304
+ }
2305
+
2306
+ // src/components/FaceScrollToTopButton.tsx
2307
+ var import_react15 = require("react");
2308
+ var import_react16 = require("@pixi/react");
2309
+ var import_pixi7 = require("pixi.js");
2310
+ var import_core2 = require("@peerbots/core");
2311
+ var import_jsx_runtime8 = require("react/jsx-runtime");
2312
+ function FaceScrollToTopButton() {
2313
+ (0, import_react16.useExtend)({ Graphics: import_pixi7.Graphics, Container: import_pixi7.Container });
2314
+ const [xPos, setXPos] = (0, import_react15.useState)(
2315
+ () => typeof window !== "undefined" ? window.innerWidth - 50 : 750
2316
+ );
2317
+ const scrollToTop = (0, import_react15.useCallback)(() => {
2318
+ if (typeof window !== "undefined") {
2319
+ window.scrollTo(0, 0);
2320
+ }
2321
+ }, []);
2322
+ (0, import_react15.useLayoutEffect)(() => {
2323
+ if (typeof window === "undefined") {
2324
+ return;
2325
+ }
2326
+ const calculatePositionBasedOnWindow = () => {
2327
+ setXPos(window.innerWidth - 50);
2328
+ };
2329
+ const orientation = typeof screen !== "undefined" ? screen.orientation : void 0;
2330
+ orientation?.addEventListener("change", calculatePositionBasedOnWindow);
2331
+ window.addEventListener("resize", calculatePositionBasedOnWindow);
2332
+ return () => {
2333
+ orientation?.removeEventListener("change", calculatePositionBasedOnWindow);
2334
+ window.removeEventListener("resize", calculatePositionBasedOnWindow);
2335
+ };
2336
+ }, []);
2337
+ const drawChevron = (0, import_react15.useCallback)((graphics) => {
2338
+ graphics.clear();
2339
+ graphics.svg(`
2340
+ <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="black">
2341
+ <path strokeLinecap="round" strokeLinejoin="round" d="${import_core2.iconPaths.chevronUpSmall}" />
2342
+ </svg>
2343
+ `);
2344
+ }, []);
2345
+ return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
2346
+ "pixiContainer",
2347
+ {
2348
+ label: "ScrollToTopButton",
2349
+ x: xPos,
2350
+ y: 20,
2351
+ eventMode: "static",
2352
+ onPointerDown: scrollToTop,
2353
+ hitArea: new import_pixi7.Rectangle(0, 0, 50, 50),
2354
+ children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
2355
+ "pixiGraphics",
2356
+ {
2357
+ onPointerDown: scrollToTop,
2358
+ eventMode: "static",
2359
+ draw: drawChevron
2360
+ }
2361
+ )
2362
+ }
2363
+ );
2364
+ }
2365
+
2366
+ // src/components/PixiFaceView.tsx
2367
+ var import_jsx_runtime9 = require("react/jsx-runtime");
2368
+ function PixiFaceView({
2369
+ isPreview = false,
2370
+ frozen = false
2371
+ } = {}) {
2372
+ (0, import_react18.useExtend)({ Container: import_pixi8.Container, Graphics: import_pixi8.Graphics, Sprite: import_pixi8.Sprite, Text: import_pixi8.Text });
2373
+ const settings = useFaceStore((state) => state.faceSettings);
2374
+ const currentStore = useFaceStoreInstance();
2375
+ const [containerEl, setContainerEl] = (0, import_react17.useState)(null);
2376
+ return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
2377
+ "div",
2378
+ {
2379
+ ref: setContainerEl,
2380
+ className: "w-full h-full relative overflow-hidden",
2381
+ "data-testid": "pixi-face-view",
2382
+ children: containerEl ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
2383
+ import_react18.Application,
2384
+ {
2385
+ resizeTo: containerEl,
2386
+ backgroundColor: "#ABE3FA",
2387
+ className: "w-full h-full block",
2388
+ children: /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(FaceStoreContext.Provider, { value: currentStore, children: [
2389
+ !isPreview && settings.showFullScreenButton && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(FaceFullScreenButton, {}),
2390
+ !isPreview && settings.showScrollButton && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(FaceScrollToTopButton, {}),
2391
+ /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(FaceContainer, { frozen })
2392
+ ] })
2393
+ }
2394
+ ) : null
2395
+ }
2396
+ );
2397
+ }
2398
+ var PixiFaceView_default = PixiFaceView;
2399
+ // Annotate the CommonJS export names for ESM import in node:
2400
+ 0 && (module.exports = {
2401
+ PixiFaceView
2402
+ });
2403
+ //# sourceMappingURL=pixi.cjs.map