Skip to content

Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor

Focus the embed demo on three features with matching code

shinshin8686bb8bc537f1
diff --git a/e2e/embed-demo.spec.ts b/e2e/embed-demo.spec.ts
index bd830f8..c3d525f 100644
--- a/e2e/embed-demo.spec.ts
+++ b/e2e/embed-demo.spec.ts
@@ -4,13 +4,18 @@ import { readFile } from 'node:fs/promises';
import { samplePresent, sampleSkipReason } from './sample';
const site = `http://127.0.0.1:${process.env.PLAYWRIGHT_SITE_PORT ?? 5174}/mesh-avatar-studio/`;
+const defaultSource = 'https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar';
const outside = new WeakMap<Page, string[]>();
test.beforeEach(async ({ context, page }) => {
test.skip(!samplePresent, sampleSkipReason);
const requests: string[] = [];
outside.set(page, requests);
+ const archive = await (await page.request.get(`${site}miko.mavatar`)).body();
await context.route('**/*', route => {
+ if (route.request().url() === defaultSource) {
+ return route.fulfill({ contentType: 'application/octet-stream', headers: { 'access-control-allow-origin': '*' }, body: archive });
+ }
if (new URL(route.request().url()).hostname !== '127.0.0.1') {
requests.push(route.request().url());
return route.abort();
@@ -31,16 +36,20 @@ for (const language of ['en', 'ja']) {
expect(image.data.some((value, index) => index % 4 === 3 && value > 0)).toBe(true);
await page.locator('[data-expression="smile"]').click();
expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.avatar!.getExpression().name)).toBe('smile');
- await page.locator('#emotion').selectOption('happy');
- await page.locator('#emotion').selectOption('');
- await page.locator('#paused').check();
- expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.paused)).toBe(true);
- await page.locator('#paused').uncheck();
- await page.locator('#no-idle').check();
- await expect(page.locator('mesh-avatar')).toHaveAttribute('no-idle', '');
+ await expect(page.locator('#expression-code')).toHaveText('<mesh-avatar expression="smile"></mesh-avatar>');
+ await page.locator('[data-expression="neutral"]').click();
+ await expect(page.locator('#expression-code')).toHaveText('<mesh-avatar></mesh-avatar>');
+ expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.avatar!.getExpression().name)).toBe('neutral');
+ await expect(page.locator('mesh-avatar')).not.toHaveAttribute('src');
+ const box = await page.locator('mesh-avatar').boundingBox();
+ expect(box!.width).toBeCloseTo(box!.height);
+ await expect(page.locator('#emotion, #paused, #no-idle, #audio-file, #microphone')).toHaveCount(0);
await page.locator('#speech-text').fill('こんにちは、よろしくお願いします。');
await page.locator('#speech-form button').click();
expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.avatar!.getLipSyncState().active)).toBe(true);
+ await expect(page.locator('#speech-code')).toHaveText("const el = document.querySelector('mesh-avatar');\nel.speak('こんにちは、よろしくお願いします。');");
+ await page.locator('#speech-text').fill("a'\\b</script>");
+ await expect(page.locator('#speech-code')).toHaveText("const el = document.querySelector('mesh-avatar');\nel.speak('a\\'\\\\b\\x3c/script>');");
await page.evaluate(() => Reflect.set(window, 'previousAvatar', document.querySelector('mesh-avatar')!.avatar));
const archive = await (await page.request.get(`${site}miko.mavatar`)).body();
@@ -49,9 +58,12 @@ for (const language of ['en', 'ja']) {
});
await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
await expect(page.locator('#source-name')).toHaveText('chosen.mavatar');
+ await expect(page.locator('#selected-file')).toContainText('chosen.mavatar');
+ await expect(page.locator('#file-code')).toHaveText('<mesh-avatar src="/path/to/your-avatar.mavatar"></mesh-avatar>');
expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.avatar !== Reflect.get(window, 'previousAvatar'))).toBe(true);
await page.locator('#restore-miko').click();
await expect(page.locator('#source-name')).toHaveText('Miko');
+ await expect(page.locator('#file-code')).toHaveText('<mesh-avatar></mesh-avatar>');
await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
await page.locator('#avatar-file').setInputFiles({
@@ -65,95 +77,6 @@ for (const language of ['en', 'ja']) {
});
}
-test('microphone input drives the mouth and stopping releases the stream', async ({ page }) => {
- await page.addInitScript(() => {
- Object.defineProperty(navigator.mediaDevices, 'getUserMedia', { value: async () => {
- const ctx = new AudioContext();
- await ctx.resume();
- const oscillator = ctx.createOscillator();
- const destination = ctx.createMediaStreamDestination();
- oscillator.connect(destination);
- oscillator.start();
- const stream = destination.stream;
- const track = stream.getAudioTracks()[0], stop = track.stop.bind(track);
- track.stop = () => {
- Reflect.set(window, 'microphoneStopped', true);
- oscillator.stop();
- void ctx.close();
- stop();
- };
- return stream;
- } });
- });
- await page.goto(`${site}embed/`);
- await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
- await page.evaluate(() => {
- const el = document.querySelector('mesh-avatar')!;
- const set = el.setVoiceLevel.bind(el);
- el.setVoiceLevel = value => {
- Reflect.set(window, 'voiceLevel', value);
- set(value);
- };
- });
- await page.locator('#microphone').click();
- await expect(page.locator('#microphone')).toHaveAttribute('aria-pressed', 'true');
- await expect.poll(() => page.evaluate(() => Number(Reflect.get(window, 'voiceLevel')))).toBeGreaterThan(0.1);
- await page.locator('#microphone').click();
- await expect(page.locator('#microphone')).toHaveAttribute('aria-pressed', 'false');
- expect(await page.evaluate(() => Reflect.get(window, 'microphoneStopped'))).toBe(true);
- expect(await page.evaluate(() => Reflect.get(window, 'voiceLevel'))).toBe(0);
-});
-
-test('microphone denial leaves controls usable and shows a localized message', async ({ page }) => {
- await page.addInitScript(() => {
- Object.defineProperty(navigator.mediaDevices, 'getUserMedia', {
- value: async () => { throw new DOMException('Denied', 'NotAllowedError'); },
- });
- });
- await page.goto(`${site}ja/embed/`);
- await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
- await page.locator('#microphone').click();
- await expect(page.locator('#notice')).toContainText('マイクを開始できませんでした');
- await expect(page.locator('#microphone')).toBeEnabled();
- await expect(page.locator('#microphone')).toHaveAttribute('aria-pressed', 'false');
-});
-
-test('local audio drives mouth volume and resets it when playback stops', async ({ page }) => {
- const sampleRate = 16000, samples = sampleRate * 2;
- const wav = Buffer.alloc(44 + samples * 2);
- wav.write('RIFF', 0);
- wav.writeUInt32LE(wav.length - 8, 4);
- wav.write('WAVEfmt ', 8);
- wav.writeUInt32LE(16, 16);
- wav.writeUInt16LE(1, 20);
- wav.writeUInt16LE(1, 22);
- wav.writeUInt32LE(sampleRate, 24);
- wav.writeUInt32LE(sampleRate * 2, 28);
- wav.writeUInt16LE(2, 32);
- wav.writeUInt16LE(16, 34);
- wav.write('data', 36);
- wav.writeUInt32LE(samples * 2, 40);
- for (let i = 0; i < samples; i++) wav.writeInt16LE(Math.round(Math.sin(i * 440 * 2 * Math.PI / sampleRate) * 10000), 44 + i * 2);
- await page.goto(`${site}embed/`);
- await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
- await page.evaluate(() => {
- const el = document.querySelector('mesh-avatar')!;
- const set = el.setVoiceLevel.bind(el);
- el.setVoiceLevel = value => {
- Reflect.set(window, 'voiceLevel', value);
- set(value);
- };
- });
- await page.locator('#audio-file').setInputFiles({ name: 'voice.wav', mimeType: 'audio/wav', buffer: wav });
- // Give the Web Audio context a user gesture before programmatic playback.
- await page.locator('#speech-form button').click();
- await page.locator('audio').evaluate(async audio => { await (audio as HTMLAudioElement).play(); });
- await expect.poll(() => page.evaluate(() => Number(Reflect.get(window, 'voiceLevel')))).toBeGreaterThan(0.1);
- await page.locator('audio').evaluate(audio => (audio as HTMLAudioElement).pause());
- await expect.poll(() => page.evaluate(() => Reflect.get(window, 'voiceLevel'))).toBe(0);
- await expect(page.locator('#notice')).toHaveText('');
-});
-
for (const example of ['basic', 'playground']) {
test(`standalone ${example} example opens directly from disk`, async ({ page }) => {
// Use the unpublished build at the real CDN URL, without sending any requests outside.
diff --git a/packages/element/README.md b/packages/element/README.md
index 4111d5c..a78213d 100644
--- a/packages/element/README.md
+++ b/packages/element/README.md
@@ -17,6 +17,9 @@ Add these two lines to your page to show the Miko sample:
<mesh-avatar></mesh-avatar>
```
+Without `src`, the element loads Miko from
+`https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar`.
+
### npm
```sh
@@ -43,7 +46,7 @@ An unpacked avatar folder URL also works. Cross-origin assets need CORS headers.
### Size
-The element defaults to `display: block; aspect-ratio: 3 / 4`. Set its width in your page's CSS; you can also override its height or aspect ratio. The background is transparent.
+The element defaults to `display: block; aspect-ratio: 1 / 1`. Set its width in your page's CSS; you can also override its height or aspect ratio. The background is transparent.
```html
<style>
diff --git a/packages/element/src/index.ts b/packages/element/src/index.ts
index 09812a8..cdce57c 100644
--- a/packages/element/src/index.ts
+++ b/packages/element/src/index.ts
@@ -6,7 +6,7 @@ export type { Emotion, Fit } from './attributes.js';
export type { AvatarSource, MeshAvatar, LiveExpression } from 'mesh-avatar';
const STYLE = `
-:host { display: block; position: relative; aspect-ratio: 3 / 4; }
+:host { display: block; position: relative; aspect-ratio: 1 / 1; }
:host([hidden]) { display: none; }
canvas { display: block; width: 100%; height: 100%; }
`;
diff --git a/site/embed/index.html b/site/embed/index.html
index 493abcf..2da8d11 100644
--- a/site/embed/index.html
+++ b/site/embed/index.html
@@ -3,8 +3,8 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
- <meta http-equiv="Content-Security-Policy" content="connect-src 'self' blob: data: ws://127.0.0.1:* ws://localhost:*; img-src 'self' blob: data:; media-src 'self' blob:; object-src 'none'; base-uri 'self'">
- <meta name="description" content="Try expressions, text lip sync and your own avatar files. Without a src attribute, the element loads the same Miko from GitHub Pages.">
+ <meta http-equiv="Content-Security-Policy" content="connect-src 'self' https://shinshin86.github.io blob: data: ws://127.0.0.1:* ws://localhost:*; img-src 'self' blob: data:; media-src 'self' blob:; object-src 'none'; base-uri 'self'">
+ <meta name="description" content="Try expressions, text lip sync and your own avatar files. Without src, the element loads Miko from https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar.">
<title>Mesh Avatar — Try the HTML embed</title>
<link rel="canonical" href="https://shinshin86.github.io/mesh-avatar-studio/embed/">
<link rel="alternate" hreflang="en" href="https://shinshin86.github.io/mesh-avatar-studio/embed/">
@@ -22,11 +22,11 @@
<a class="header-link language-switch" href="../ja/embed/" lang="ja">日本語</a>
</nav>
</header>
- <main id="embed-playground" class="shell" data-loading="Loading avatar…" data-ready="Avatar ready" data-error="Could not load this avatar. Choose another file or return to Miko." data-audio-error="Could not play this audio file." data-mic-error="Could not start the microphone. Check browser permissions and use HTTPS or localhost." data-copy-error="Select and copy the code above.">
+ <main id="embed-playground" class="shell" data-loading="Loading avatar…" data-ready="Avatar ready" data-error="Could not load this avatar. Choose another file or return to Miko." data-copy-error="Select and copy the code above.">
<section class="intro" aria-labelledby="embed-title">
<p class="eyebrow">mesh-avatar-element</p>
<h1 id="embed-title">Try the HTML embed</h1>
- <p>Try expressions, text lip sync and your own avatar files. Without a src attribute, the element loads the same Miko from GitHub Pages.</p>
+ <p>Try expressions, text lip sync and your own avatar files. Without src, the element loads Miko from https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar.</p>
<div class="code-card">
<div class="code-heading">
<h2>Embed on your page <span>HTML</span></h2>
@@ -39,21 +39,16 @@
</section>
<div class="embed-layout">
<section class="embed-stage" aria-label="Avatar preview">
- <mesh-avatar src="%BASE_URL%miko.mavatar" label="Miko"></mesh-avatar>
+ <mesh-avatar></mesh-avatar>
<p id="source-name">Miko</p>
<p id="status" role="status" data-state="loading">Loading avatar…</p>
</section>
<div class="embed-panels">
- <section class="control-panel">
- <h2>Avatar file</h2>
- <label for="avatar-file">Choose a .mavatar file</label>
- <input id="avatar-file" type="file" accept=".mavatar">
- <button id="restore-miko" type="button">Return to Miko</button>
- </section>
<fieldset id="avatar-controls" disabled>
<legend class="sr-only">Avatar controls</legend>
<section class="control-panel">
- <h2>Expressions</h2>
+ <div class="embed-demo-controls">
+ <h2>Expressions</h2>
<div class="expression-chips" role="group" aria-label="Expressions">
<button type="button" data-expression="neutral" aria-pressed="true">Neutral</button>
<button type="button" data-expression="smile" aria-pressed="false">Smile</button>
@@ -64,30 +59,49 @@
<button type="button" data-expression="sad" aria-pressed="false">Sad</button>
<button type="button" data-expression="wink" aria-pressed="false">Wink</button>
</div>
- <label for="emotion">Emotion</label>
- <select id="emotion"><option value="">None</option><option value="happy">Happy</option><option value="sad">Sad</option><option value="angry">Angry</option><option value="surprised">Surprised</option><option value="relaxed">Relaxed</option><option value="neutral">Neutral</option></select>
- <label class="check"><input id="paused" type="checkbox">Pause animation</label>
- <label class="check"><input id="no-idle" type="checkbox">Disable idle motion</label>
- </section>
- <section class="control-panel">
- <h2>Text lip sync</h2>
- <form id="speech-form">
- <label for="speech-text">Japanese text</label>
- <input id="speech-text" type="text" value="こんにちは" maxlength="300">
- <button type="submit">Animate speech</button>
- </form>
- <p class="hint">Mouth animation only. No voice is generated.</p>
+ </div>
+ <div class="code-card">
+ <div class="code-heading"><h3>HTML</h3><button type="button" class="copy-button" data-copy="expression-code" data-copied="Copied">Copy</button></div>
+ <pre tabindex="0"><code id="expression-code">&lt;mesh-avatar&gt;&lt;/mesh-avatar&gt;</code></pre>
+ </div>
</section>
<section class="control-panel">
- <h2>Audio lip sync</h2>
- <label for="audio-file">Choose an audio file</label>
- <input id="audio-file" type="file" accept="audio/*">
- <audio controls aria-label="Audio lip sync"></audio>
- <button id="microphone" type="button" aria-pressed="false" data-start="Start microphone" data-stop="Stop microphone">Start microphone</button>
+ <div class="embed-demo-controls">
+ <h2>Text lip sync</h2>
+ <form id="speech-form">
+ <label for="speech-text">Japanese text</label>
+ <input id="speech-text" type="text" value="こんにちは" maxlength="300">
+ <button type="submit">Animate speech</button>
+ </form>
+ <p class="hint">Mouth animation only. No voice is generated.</p>
+ </div>
+ <div class="code-card">
+ <div class="code-heading"><h3>JavaScript</h3><button type="button" class="copy-button" data-copy="speech-code" data-copied="Copied">Copy</button></div>
+ <pre tabindex="0"><code id="speech-code">const el = document.querySelector('mesh-avatar');
+el.speak('こんにちは');</code></pre>
+ </div>
</section>
</fieldset>
+ <section class="control-panel">
+ <div class="embed-demo-controls">
+ <h2>Use your own .mavatar</h2>
+ <div class="file-actions">
+ <input id="avatar-file" class="file-input" type="file" accept=".mavatar" aria-labelledby="avatar-file-label">
+ <label id="avatar-file-label" class="file-button" for="avatar-file">Choose a .mavatar file</label>
+ <button id="restore-miko" type="button">Return to Miko</button>
+ </div>
+ <p id="selected-file" class="hint" aria-live="polite">Selected: Miko</p>
+ <p class="hint">Files are read in your browser and are not uploaded.</p>
+ </div>
+ <div>
+ <div class="code-card">
+ <div class="code-heading"><h3>HTML</h3><button type="button" class="copy-button" data-copy="file-code" data-copied="Copied">Copy</button></div>
+ <pre tabindex="0"><code id="file-code">&lt;mesh-avatar src="/path/to/your-avatar.mavatar"&gt;&lt;/mesh-avatar&gt;</code></pre>
+ </div>
+ <p class="hint">Set src to the path or URL of the file hosted on your site.</p>
+ </div>
+ </section>
<p id="notice" role="status"></p>
- <p class="embed-privacy">Avatar files, audio files and microphone audio are processed in your browser and are not uploaded.</p>
</div>
</div>
</main>
diff --git a/site/ja/embed/index.html b/site/ja/embed/index.html
index 565305c..1d6ad07 100644
--- a/site/ja/embed/index.html
+++ b/site/ja/embed/index.html
@@ -3,8 +3,8 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
- <meta http-equiv="Content-Security-Policy" content="connect-src 'self' blob: data: ws://127.0.0.1:* ws://localhost:*; img-src 'self' blob: data:; media-src 'self' blob:; object-src 'none'; base-uri 'self'">
- <meta name="description" content="表情や口パクを試したり、自分のアバターを表示したりできます。src 属性を省くと、同じ Miko が GitHub Pages から読み込まれます。">
+ <meta http-equiv="Content-Security-Policy" content="connect-src 'self' https://shinshin86.github.io blob: data: ws://127.0.0.1:* ws://localhost:*; img-src 'self' blob: data:; media-src 'self' blob:; object-src 'none'; base-uri 'self'">
+ <meta name="description" content="表情や口パクを試したり、自分のアバターを表示したりできます。src を省くと、https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar から Miko を読み込みます。">
<title>Mesh Avatar — HTML の埋め込みを試す</title>
<link rel="canonical" href="https://shinshin86.github.io/mesh-avatar-studio/ja/embed/">
<link rel="alternate" hreflang="en" href="https://shinshin86.github.io/mesh-avatar-studio/embed/">
@@ -22,11 +22,11 @@
<a class="header-link language-switch" href="../../embed/" lang="en">English</a>
</nav>
</header>
- <main id="embed-playground" class="shell" data-loading="読み込み中…" data-ready="アバターを読み込みました" data-error="読み込めませんでした。別のファイルを選ぶか、Miko に戻してください。" data-audio-error="この音声ファイルを再生できませんでした。" data-mic-error="マイクを開始できませんでした。ブラウザのアクセス許可を確認し、HTTPS または localhost で開いてください。" data-copy-error="上のコードを選択してコピーしてください。">
+ <main id="embed-playground" class="shell" data-loading="読み込み中…" data-ready="アバターを読み込みました" data-error="読み込めませんでした。別のファイルを選ぶか、Miko に戻してください。" data-copy-error="上のコードを選択してコピーしてください。">
<section class="intro" aria-labelledby="embed-title">
<p class="eyebrow">mesh-avatar-element</p>
<h1 id="embed-title">HTML の埋め込みを試す</h1>
- <p>表情や口パクを試したり、自分のアバターを表示したりできます。src 属性を省くと、同じ Miko が GitHub Pages から読み込まれます。</p>
+ <p>表情や口パクを試したり、自分のアバターを表示したりできます。src を省くと、https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar から Miko を読み込みます。</p>
<div class="code-card">
<div class="code-heading">
<h2>自分のページに埋め込む <span>HTML</span></h2>
@@ -39,21 +39,16 @@
</section>
<div class="embed-layout">
<section class="embed-stage" aria-label="アバターのプレビュー">
- <mesh-avatar src="%BASE_URL%miko.mavatar" label="Miko"></mesh-avatar>
+ <mesh-avatar></mesh-avatar>
<p id="source-name">Miko</p>
<p id="status" role="status" data-state="loading">読み込み中…</p>
</section>
<div class="embed-panels">
- <section class="control-panel">
- <h2>アバター</h2>
- <label for="avatar-file">.mavatar ファイルを選ぶ</label>
- <input id="avatar-file" type="file" accept=".mavatar">
- <button id="restore-miko" type="button">Miko に戻す</button>
- </section>
<fieldset id="avatar-controls" disabled>
<legend class="sr-only">アバターの操作</legend>
<section class="control-panel">
- <h2>表情</h2>
+ <div class="embed-demo-controls">
+ <h2>表情</h2>
<div class="expression-chips" role="group" aria-label="表情">
<button type="button" data-expression="neutral" aria-pressed="true">ふつう</button>
<button type="button" data-expression="smile" aria-pressed="false">笑顔</button>
@@ -64,30 +59,49 @@
<button type="button" data-expression="sad" aria-pressed="false">悲しみ</button>
<button type="button" data-expression="wink" aria-pressed="false">ウインク</button>
</div>
- <label for="emotion">感情</label>
- <select id="emotion"><option value="">指定なし</option><option value="happy">喜び</option><option value="sad">悲しみ</option><option value="angry">怒り</option><option value="surprised">驚き</option><option value="relaxed">リラックス</option><option value="neutral">ふつう</option></select>
- <label class="check"><input id="paused" type="checkbox">動きを止める</label>
- <label class="check"><input id="no-idle" type="checkbox">待機動作を使わない</label>
- </section>
- <section class="control-panel">
- <h2>文章で口を動かす</h2>
- <form id="speech-form">
- <label for="speech-text">日本語の文章</label>
- <input id="speech-text" type="text" value="こんにちは" maxlength="300">
- <button type="submit">口を動かす</button>
- </form>
- <p class="hint">口の動きだけを試せます。音声は流れません。</p>
+ </div>
+ <div class="code-card">
+ <div class="code-heading"><h3>HTML</h3><button type="button" class="copy-button" data-copy="expression-code" data-copied="コピー済み">コピー</button></div>
+ <pre tabindex="0"><code id="expression-code">&lt;mesh-avatar&gt;&lt;/mesh-avatar&gt;</code></pre>
+ </div>
</section>
<section class="control-panel">
- <h2>音声に合わせて口を動かす</h2>
- <label for="audio-file">音声ファイルを選ぶ</label>
- <input id="audio-file" type="file" accept="audio/*">
- <audio controls aria-label="音声に合わせて口を動かす"></audio>
- <button id="microphone" type="button" aria-pressed="false" data-start="マイクを開始" data-stop="マイクを停止">マイクを開始</button>
+ <div class="embed-demo-controls">
+ <h2>文章で口を動かす</h2>
+ <form id="speech-form">
+ <label for="speech-text">日本語の文章</label>
+ <input id="speech-text" type="text" value="こんにちは" maxlength="300">
+ <button type="submit">口を動かす</button>
+ </form>
+ <p class="hint">口の動きだけを試せます。音声は流れません。</p>
+ </div>
+ <div class="code-card">
+ <div class="code-heading"><h3>JavaScript</h3><button type="button" class="copy-button" data-copy="speech-code" data-copied="コピー済み">コピー</button></div>
+ <pre tabindex="0"><code id="speech-code">const el = document.querySelector('mesh-avatar');
+el.speak('こんにちは');</code></pre>
+ </div>
</section>
</fieldset>
+ <section class="control-panel">
+ <div class="embed-demo-controls">
+ <h2>自分の .mavatar を表示</h2>
+ <div class="file-actions">
+ <input id="avatar-file" class="file-input" type="file" accept=".mavatar" aria-labelledby="avatar-file-label">
+ <label id="avatar-file-label" class="file-button" for="avatar-file">.mavatar ファイルを選ぶ</label>
+ <button id="restore-miko" type="button">Miko に戻す</button>
+ </div>
+ <p id="selected-file" class="hint" aria-live="polite">選択中: Miko</p>
+ <p class="hint">ファイルはブラウザ内で読み込み、外部には送信しません。</p>
+ </div>
+ <div>
+ <div class="code-card">
+ <div class="code-heading"><h3>HTML</h3><button type="button" class="copy-button" data-copy="file-code" data-copied="コピー済み">コピー</button></div>
+ <pre tabindex="0"><code id="file-code">&lt;mesh-avatar src="/path/to/your-avatar.mavatar"&gt;&lt;/mesh-avatar&gt;</code></pre>
+ </div>
+ <p class="hint">自分のサイトに置いたファイルのパスか URL を src に指定してください。</p>
+ </div>
+ </section>
<p id="notice" role="status"></p>
- <p class="embed-privacy">選んだアバターや音声ファイル、マイクの音声はブラウザ内で処理し、外部には送信しません。</p>
</div>
</div>
</main>
diff --git a/site/src/embed/main.ts b/site/src/embed/main.ts
index a06e0f9..35a4994 100644
--- a/site/src/embed/main.ts
+++ b/site/src/embed/main.ts
@@ -1,8 +1,7 @@
import '../../../packages/element/src/index';
+import { DEFAULT_SRC } from '../../../packages/element/src/attributes';
import '../style.css';
import './style.css';
import { setupPlayground } from './playground.js';
-setupPlayground(document.querySelector('#embed-playground')!, {
- sampleURL: `${import.meta.env.BASE_URL}miko.mavatar`,
-});
+setupPlayground(document.querySelector('#embed-playground')!, { sampleURL: DEFAULT_SRC });
diff --git a/site/src/embed/playground.js b/site/src/embed/playground.js
index e69f014..de51980 100644
--- a/site/src/embed/playground.js
+++ b/site/src/embed/playground.js
@@ -1,62 +1,23 @@
-// Kept inline in the standalone example so it can also open directly from disk.
export function setupPlayground(root, { sampleURL }) {
const el = root.querySelector('mesh-avatar');
const status = root.querySelector('#status');
const sourceName = root.querySelector('#source-name');
+ const selectedFile = root.querySelector('#selected-file');
+ const selectedPrefix = selectedFile.textContent.replace(/Miko$/, '');
const controls = root.querySelector('#avatar-controls');
- const audio = root.querySelector('audio');
- const micButton = root.querySelector('#microphone');
const notice = root.querySelector('#notice');
- let context;
- let audioAnalyser;
- let audioURL;
- let microphone;
- let microphoneSource;
- let microphoneRequest = 0;
- let voiceFrame = 0;
+ const speechText = root.querySelector('#speech-text');
+ const fileInput = root.querySelector('#avatar-file');
- function stopVoice() {
- cancelAnimationFrame(voiceFrame);
- voiceFrame = 0;
- el.avatar?.setSpeaking(false);
- el.setVoiceLevel(0);
- }
-
- function stopMicrophone() {
- microphoneRequest++;
- microphone?.getTracks().forEach(track => track.stop());
- microphone = undefined;
- microphoneSource?.disconnect();
- microphoneSource = undefined;
- micButton.disabled = false;
- micButton.textContent = micButton.dataset.start;
- micButton.setAttribute('aria-pressed', 'false');
- stopVoice();
- }
-
- function followVolume(analyser) {
- stopVoice();
- el.avatar?.stopLipSync();
- el.avatar?.setSpeaking(true);
- const data = new Float32Array(analyser.fftSize);
- const frame = () => {
- analyser.getFloatTimeDomainData(data);
- const rms = Math.sqrt(data.reduce((sum, value) => sum + value * value, 0) / data.length);
- el.setVoiceLevel(Math.min(1, rms * 5));
- voiceFrame = requestAnimationFrame(frame);
- };
- frame();
- }
-
- function audioContext() {
- context ??= new AudioContext();
- return context;
+ function updateCode(id, text) {
+ root.querySelector(`#${id}`).textContent = text;
+ const copy = root.querySelector(`[data-copy="${id}"]`);
+ copy.textContent = copy.dataset.label;
}
function loading(name) {
- audio.pause();
- stopMicrophone();
sourceName.textContent = name;
+ selectedFile.textContent = selectedPrefix + name;
status.textContent = root.dataset.loading;
status.dataset.state = 'loading';
controls.disabled = true;
@@ -75,133 +36,64 @@ export function setupPlayground(root, { sampleURL }) {
status.dataset.state = 'error';
controls.disabled = true;
});
- // Also cover callers that initialize controls after the avatar has loaded.
if (el.avatar) ready();
for (const button of root.querySelectorAll('[data-expression]')) {
button.addEventListener('click', () => {
- el.expression = button.dataset.expression;
+ const expression = button.dataset.expression;
+ if (expression === 'neutral') el.removeAttribute('expression');
+ else el.expression = expression;
for (const chip of root.querySelectorAll('[data-expression]')) {
chip.setAttribute('aria-pressed', String(chip === button));
}
+ updateCode('expression-code', expression === 'neutral'
+ ? '<mesh-avatar></mesh-avatar>'
+ : `<mesh-avatar expression="${expression}"></mesh-avatar>`);
});
}
- root.querySelector('#emotion').addEventListener('change', event => {
- el.emotion = event.target.value || null;
- });
- root.querySelector('#paused').addEventListener('change', event => {
- el.paused = event.target.checked;
- });
- root.querySelector('#no-idle').addEventListener('change', event => {
- el.toggleAttribute('no-idle', event.target.checked);
- });
+ function speechCode() {
+ // Escape a single-quoted JavaScript string; textContent keeps HTML inert.
+ const text = speechText.value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
+ .replace(/\r/g, '\\r').replace(/\n/g, '\\n')
+ .replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')
+ .replace(/</g, '\\x3c');
+ updateCode('speech-code', `const el = document.querySelector('mesh-avatar');\nel.speak('${text}');`);
+ }
+ speechText.addEventListener('input', speechCode);
root.querySelector('#speech-form').addEventListener('submit', event => {
event.preventDefault();
- audio.pause();
- stopMicrophone();
- void el.speak(root.querySelector('#speech-text').value).catch(() => {
+ speechCode();
+ void el.speak(speechText.value).catch(() => {
notice.textContent = root.dataset.error;
});
});
- root.querySelector('#avatar-file').addEventListener('change', event => {
- const file = event.target.files?.[0];
+ fileInput.addEventListener('change', () => {
+ const file = fileInput.files?.[0];
if (!file) return;
loading(file.name);
+ updateCode('file-code', '<mesh-avatar src="/path/to/your-avatar.mavatar"></mesh-avatar>');
void el.load(file).catch(() => {});
- event.target.value = '';
+ fileInput.value = '';
});
root.querySelector('#restore-miko').addEventListener('click', () => {
loading('Miko');
- // Setting an unchanged src or removing an absent attribute would not reload.
+ updateCode('file-code', '<mesh-avatar></mesh-avatar>');
+ // load() reloads even when the src attribute is already absent.
void el.load(sampleURL).catch(() => {});
- root.querySelector('#avatar-file').value = '';
- });
-
- root.querySelector('#audio-file').addEventListener('change', event => {
- const file = event.target.files?.[0];
- if (!file) return;
- audio.pause();
- stopMicrophone();
- if (audioURL) URL.revokeObjectURL(audioURL);
- audioURL = URL.createObjectURL(file);
- audio.src = audioURL;
- notice.textContent = '';
- });
- audio.addEventListener('play', async () => {
- stopMicrophone();
- try {
- const ctx = audioContext();
- audioAnalyser ??= ctx.createAnalyser();
- if (!audio.dataset.connected) {
- ctx.createMediaElementSource(audio).connect(audioAnalyser);
- audioAnalyser.connect(ctx.destination);
- audio.dataset.connected = 'true';
- }
- await ctx.resume();
- if (!audio.paused && !audio.ended) followVolume(audioAnalyser);
- } catch {
- audio.pause();
- notice.textContent = root.dataset.audioError;
- }
- });
- for (const event of ['pause', 'ended']) audio.addEventListener(event, () => {
- if (!microphone) stopVoice();
- });
- audio.addEventListener('error', () => {
- if (audio.getAttribute('src')) notice.textContent = root.dataset.audioError;
- if (!microphone) stopVoice();
+ fileInput.value = '';
});
- micButton.addEventListener('click', async () => {
- if (microphone) {
- stopMicrophone();
- return;
- }
- audio.pause();
- stopVoice();
- notice.textContent = '';
- const request = ++microphoneRequest;
- micButton.disabled = true;
- try {
- const ctx = audioContext();
- await ctx.resume();
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
- if (request !== microphoneRequest) {
- stream.getTracks().forEach(track => track.stop());
- return;
- }
- microphone = stream;
- const analyser = ctx.createAnalyser();
- microphoneSource = ctx.createMediaStreamSource(stream);
- microphoneSource.connect(analyser);
- followVolume(analyser);
- micButton.textContent = micButton.dataset.stop;
- micButton.setAttribute('aria-pressed', 'true');
- } catch {
- if (request === microphoneRequest) {
- stopMicrophone();
- notice.textContent = root.dataset.micError;
+ for (const button of root.querySelectorAll('[data-copy], #copy-snippet')) {
+ button.dataset.label = button.textContent;
+ button.addEventListener('click', async () => {
+ try {
+ await navigator.clipboard.writeText(root.querySelector(`#${button.dataset.copy ?? 'embed-code'}`).textContent);
+ button.textContent = button.dataset.copied;
+ } catch {
+ notice.textContent = root.dataset.copyError;
}
- } finally {
- if (request === microphoneRequest) micButton.disabled = false;
- }
- });
-
- root.querySelector('#copy-snippet')?.addEventListener('click', async event => {
- try {
- await navigator.clipboard.writeText(root.querySelector('#embed-code').textContent);
- event.target.textContent = event.target.dataset.copied;
- } catch {
- notice.textContent = root.dataset.copyError;
- }
- });
-
- window.addEventListener('pagehide', () => {
- audio.pause();
- stopMicrophone();
- if (audioURL) URL.revokeObjectURL(audioURL);
- if (context) void context.close();
- }, { once: true });
+ });
+ }
}
diff --git a/site/src/embed/style.css b/site/src/embed/style.css
index e062b50..eff861d 100644
--- a/site/src/embed/style.css
+++ b/site/src/embed/style.css
@@ -2,38 +2,47 @@
.embed-page .site-header { min-height: 76px; }
.embed-page .intro { padding-block: 36px 24px; }
.embed-page h1 { font-size: clamp(30px, 4vw, 44px); letter-spacing: -1px; line-height: 1.25; }
-.embed-page .intro > p { max-width: 780px; color: var(--muted); line-height: 1.7; }
-.embed-page .code-card { margin-block: 16px; }
+.embed-page .intro > p { max-width: 900px; color: var(--muted); line-height: 1.7; overflow-wrap: anywhere; }
+.embed-page .code-card { margin-block: 16px; min-width: 0; }
.embed-page .code-card pre { padding-block: 12px; }
-.embed-layout { display: grid; grid-template-columns: minmax(240px, .8fr) minmax(0, 1.2fr); gap: 24px; align-items: start; margin-top: 28px; }
-.embed-stage, .control-panel { min-width: 0; padding: 20px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); }
-.embed-stage { position: sticky; top: 20px; text-align: center; }
-.embed-stage mesh-avatar { width: min(100%, 340px); margin: auto; background: #f7f9fc; border-radius: 8px; }
+.embed-layout { display: grid; grid-template-columns: minmax(240px, .7fr) minmax(0, 1.6fr); gap: 24px; align-items: start; margin-top: 28px; }
+.embed-stage { min-width: 0; position: sticky; top: 20px; text-align: center; }
+.embed-stage mesh-avatar { width: min(100%, 340px); margin: auto; }
.embed-stage #status { margin-bottom: 0; font-size: 14px; color: var(--muted); }
.embed-stage #status[data-state='error'], #notice { color: #a52b2b; }
.embed-stage #source-name { margin: 12px 0 0; font-size: 13px; overflow-wrap: anywhere; }
.embed-panels { display: grid; gap: 16px; min-width: 0; }
-.control-panel h2, .control-panel legend { margin: 0 0 16px; font-size: 18px; font-weight: 650; letter-spacing: 0; }
+.control-panel { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 20px; min-width: 0; padding: 20px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); }
+.control-panel > *, .embed-demo-controls { min-width: 0; }
+.control-panel h2 { margin: 0 0 16px; font-size: 18px; font-weight: 650; letter-spacing: 0; }
+.control-panel .code-card { margin: 0; align-self: start; }
+.control-panel .code-heading { padding: 10px 12px; gap: 8px; }
+.control-panel h3 { margin: 0; font-size: 12px; font-weight: 500; }
+.control-panel pre { white-space: pre-wrap; overflow-wrap: anywhere; padding-inline: 12px; }
.control-panel label { display: block; margin-block: 12px 8px; font-size: 14px; }
-.control-panel .check { display: flex; align-items: center; gap: 8px; }
-.control-panel input[type='file'] { display: block; width: 100%; font-size: 13px; margin-bottom: 12px; }
-.control-panel input[type='text'], .control-panel select { width: 100%; min-height: 40px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 6px; font: inherit; background: white; color: var(--ink); }
-.control-panel button { min-height: 40px; padding: 8px 12px; border: 1px solid var(--line); border-radius: 8px; background: white; color: var(--ink); cursor: pointer; }
-.control-panel button:hover:not(:disabled), .control-panel button[aria-pressed='true'] { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
+.control-panel input[type='text'] { width: 100%; min-height: 40px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 6px; font: inherit; background: white; color: var(--ink); }
+.control-panel button:not(.copy-button), .control-panel .file-button { min-height: 40px; padding: 8px 12px; border: 1px solid var(--line); border-radius: 8px; background: white; color: var(--ink); cursor: pointer; font: inherit; font-size: 14px; }
+.control-panel button:hover:not(:disabled), .control-panel button[aria-pressed='true'], .file-button:hover { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
.control-panel button:disabled { opacity: .5; cursor: default; }
-.control-panel audio { display: block; width: 100%; margin-block: 12px; }
.control-panel form button { margin-top: 12px; }
-.control-panel .expression-chips { margin-bottom: 16px; }
+.control-panel .expression-chips { margin: 0; }
.control-panel .expression-chips button { flex: 0 0 auto; white-space: nowrap; }
-.control-panel .hint, .embed-privacy { color: var(--muted); font-size: 13px; line-height: 1.7; }
+.control-panel .hint { color: var(--muted); font-size: 13px; line-height: 1.7; overflow-wrap: anywhere; }
#avatar-controls { display: grid; gap: 16px; }
#notice { margin: 0; font-size: 14px; line-height: 1.6; }
-.embed-page input:focus-visible, .embed-page select:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; }
+.file-actions { display: flex; flex-wrap: wrap; gap: 8px; position: relative; }
+.control-panel .file-button { display: inline-flex; align-items: center; margin: 0; }
+.file-input { position: absolute; width: 1px; height: 1px; padding: 0; border: 0; clip-path: inset(50%); overflow: hidden; white-space: nowrap; }
+.file-input:focus-visible + .file-button, .embed-page input[type='text']:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; }
+@media (max-width: 1000px) {
+ .embed-layout { grid-template-columns: minmax(240px, .7fr) minmax(0, 1fr); }
+ .control-panel { grid-template-columns: 1fr; }
+}
@media (max-width: 760px) {
.embed-page .shell { width: calc(100% - 32px); }
.embed-page .site-header { flex-wrap: wrap; padding-block: 16px; }
.embed-page .primary-nav { gap: 16px; }
.embed-layout { grid-template-columns: 1fr; }
.embed-stage { position: static; }
- .embed-stage mesh-avatar { width: min(100%, 270px); }
+ .embed-stage mesh-avatar { width: min(100%, 300px); }
}