-
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathavatar-creator.js
More file actions
242 lines (220 loc) · 7.52 KB
/
Copy pathavatar-creator.js
File metadata and controls
242 lines (220 loc) · 7.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// three.ws Avatar Creator — the in-app modal that opens either the
// • three.ws Studio iframe (in-browser builder), or
// • three.ws Selfie SDK (photo-to-avatar editor),
// and resolves the user's chosen avatar as a GLB Blob.
//
// Provider names ("characterstudio", "avaturn") only appear in internal
// postMessage payloads and import paths — every user-visible surface reads
// "three.ws". Ready Player Me was retired upstream after the 2026
// acquisition; this module no longer references it.
import { AvaturnSDK } from '@avaturn/sdk';
import { log } from './shared/log.js';
function getStudioUrl() {
// Explicit override wins in any environment (e.g. a standalone studio dev
// server on :5173 during character-studio development).
try {
if (typeof import.meta !== 'undefined' && import.meta.env?.VITE_CHARACTER_STUDIO_URL) {
return String(import.meta.env.VITE_CHARACTER_STUDIO_URL)
.trim()
.replace(/\/$/, '');
}
} catch (_) {}
// Default: the Avatar Studio is served SAME-ORIGIN under /avatar-studio — the
// Vite dev middleware serves character-studio/build there in dev, and the
// copy-avatar-studio step ships the same build to /avatar-studio in prod
// (see vite.config.js). Resolving to the live origin keeps this correct on
// every deployment and avoids a dead localhost fallback in production. The
// value must stay absolute: it's used as an iframe src and parsed with
// `new URL(studioUrl).origin` for postMessage validation.
if (typeof location !== 'undefined' && location.origin) {
return `${location.origin}/avatar-studio`;
}
return 'https://three.ws/avatar-studio';
}
export class AvatarCreator {
/**
* @param {Element} containerEl - Parent element to mount the modal into
* @param {function(Blob, {provider:string, sourceUrl?:string|null}): void} onExport - Called with the exported GLB Blob and provenance
* @param {object} [opts]
* @param {string} [opts.studioUrl] - Override the three.ws Studio URL
*/
constructor(containerEl, onExport, opts = {}) {
this.container = containerEl;
this.onExport = onExport;
this.studioUrl = opts.studioUrl || getStudioUrl();
this.modal = null;
this.iframe = null;
this.sdk = null;
this._onMessage = null;
this._onKeyDown = null;
this._provider = null;
}
/**
* Opens the three.ws Avatar Creator modal.
* @param {string} [sessionUrl] - When provided, opens the three.ws Selfie editor in edit mode.
* When omitted, opens three.ws Studio.
*/
async open(sessionUrl) {
if (this.modal) return;
if (sessionUrl) {
this._provider = 'three-ws-selfie';
await this._openSelfie(sessionUrl);
} else {
this._provider = 'three-ws-studio';
this._buildModal(true);
this._onMessage = (e) => this._handleStudioMessage(e);
window.addEventListener('message', this._onMessage);
this.iframe.src = this.studioUrl;
}
}
/**
* Opens the default three.ws Selfie editor (no session URL required).
*/
async openDefaultEditor() {
if (this.modal) return;
this._provider = 'three-ws-selfie';
await this._openSelfie();
}
async _openSelfie(url) {
this._buildModal(false);
try {
this.sdk = new AvaturnSDK();
await this.sdk.init(this.modal.querySelector('.avatar-creator-container'), {
iframeClassName: 'avatar-creator-iframe',
url,
});
const loading = this.modal?.querySelector('.avatar-creator-loading');
if (loading) loading.style.display = 'none';
this.sdk.on('export', async (data) => {
const glbUrl = data?.url;
if (!glbUrl) return;
try {
let blob;
if (data.urlType === 'dataURL') {
const res = await fetch(glbUrl);
blob = await res.blob();
} else {
const res = await fetch(glbUrl);
if (!res.ok) throw new Error(`GLB fetch failed: ${res.status}`);
blob = await res.blob();
}
const glbBlob = blob.type
? blob
: new Blob([await blob.arrayBuffer()], { type: 'model/gltf-binary' });
this._fireExport(glbBlob, { sourceUrl: data.urlType === 'dataURL' ? null : glbUrl });
} catch (err) {
log.error('[three.ws Avatar Creator] failed to fetch selfie GLB:', err);
}
});
} catch (err) {
log.error('[three.ws Avatar Creator] Failed to initialize selfie SDK:', err);
this._showError('Failed to load the avatar creator. Please try again.');
}
}
_handleStudioMessage(event) {
try {
const csOrigin = new URL(this.studioUrl).origin;
if (event.origin !== csOrigin) return;
} catch (_) {
return;
}
const msg = event.data;
// Studio iframe uses the `characterstudio` postMessage source for backwards
// compatibility with the upstream open-source builder we forked.
if (!msg || msg.source !== 'characterstudio' || msg.type !== 'export') return;
if (!(msg.glb instanceof ArrayBuffer)) return;
const blob = new Blob([msg.glb], { type: 'model/gltf-binary' });
this._fireExport(blob);
}
_fireExport(blob, meta = {}) {
if (this.onExport) {
try {
this.onExport(blob, { provider: this._provider, ...meta });
} catch (err) {
log.error('[three.ws Avatar Creator] onExport handler threw:', err);
}
}
this.close();
}
_showError(message) {
const loading = this.modal?.querySelector('.avatar-creator-loading');
if (loading) {
loading.innerHTML = `<span class="avatar-creator-error">${message}</span>`;
}
}
/**
* @param {boolean} withIframe - true for three.ws Studio (pre-rendered iframe),
* false for three.ws Selfie SDK (SDK injects its own iframe).
*/
_buildModal(withIframe) {
const title = withIframe ? 'three.ws · Create your avatar' : 'three.ws · Edit your avatar';
this.modal = document.createElement('div');
this.modal.className = 'avatar-creator-overlay';
this.modal.innerHTML = `
<div class="avatar-creator-modal">
<div class="avatar-creator-header">
<span class="avatar-creator-title">${title}</span>
<button class="avatar-creator-close" aria-label="Close">×</button>
</div>
<div class="avatar-creator-body">
<div class="avatar-creator-container">${
withIframe
? `<iframe
class="avatar-creator-iframe"
title="three.ws · Avatar Creator"
allow="camera *; microphone *; clipboard-write"
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
></iframe>`
: ''
}</div>
<div class="avatar-creator-loading">
<div class="spinner"></div>
<span>Loading three.ws Avatar Creator…</span>
</div>
</div>
</div>
`;
this.container.appendChild(this.modal);
if (withIframe) {
this.iframe = this.modal.querySelector('.avatar-creator-iframe');
this.iframe.addEventListener('load', () => {
const loading = this.modal?.querySelector('.avatar-creator-loading');
if (loading) loading.style.display = 'none';
});
}
this.modal
.querySelector('.avatar-creator-close')
.addEventListener('click', () => this.close());
this.modal.addEventListener('click', (e) => {
if (e.target === this.modal) this.close();
});
this._onKeyDown = (e) => {
if (e.key === 'Escape') this.close();
};
document.addEventListener('keydown', this._onKeyDown);
}
close() {
if (this.sdk) {
try {
this.sdk.destroy();
} catch (_) {}
this.sdk = null;
}
if (this._onMessage) {
window.removeEventListener('message', this._onMessage);
this._onMessage = null;
}
if (this._onKeyDown) {
document.removeEventListener('keydown', this._onKeyDown);
this._onKeyDown = null;
}
if (this.modal) {
this.modal.remove();
this.modal = null;
this.iframe = null;
}
}
dispose() {
this.close();
}
}