Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Add a React component for embedding avatars
shinshin86555611abeb30
diff --git a/.changeset/add-react-component.md b/.changeset/add-react-component.mdnew file mode 100644index 0000000..5fffe85--- /dev/null+++ b/.changeset/add-react-component.md@@ -0,0 +1,5 @@+---+"mesh-avatar-react": minor+---++Add a React component with typed props, element refs, source loading and event callbacks.diff --git a/.changeset/coalesce-element-loads.md b/.changeset/coalesce-element-loads.mdnew file mode 100644index 0000000..eaaca85--- /dev/null+++ b/.changeset/coalesce-element-loads.md@@ -0,0 +1,5 @@+---+"mesh-avatar-element": patch+---++Coalesce connected element source and fit changes into one load per task.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f4d9961..30c9d16 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -43,6 +43,9 @@ jobs:- name: Build embed elementrun: npm run build:element+ - name: Build React wrapper+ run: npm run build:react+- name: Build landing pagerun: npm run build:site@@ -52,6 +55,9 @@ jobs:- name: Check embed element package contentsrun: npm pack --dry-run -w mesh-avatar-element+ - name: Check React wrapper package contents+ run: npm pack --dry-run -w mesh-avatar-react+- name: Check the setup command packagerun: npm pack --dry-run -w create-mesh-avatar-studiodiff --git a/AGENTS.md b/AGENTS.mdindex aaafddf..e1d3511 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -19,6 +19,7 @@ npm testnpm run buildnpm run build:runtimenpm run build:element+npm run build:reactnpm run e2euv run --with numpy --with pillow --with opencv-python-headless tools/test_build_layers.pyuv run tools/test_agent_tools.pydiff --git a/e2e/embed-element.spec.ts b/e2e/embed-element.spec.tsindex bd4b0bf..6600983 100644--- a/e2e/embed-element.spec.ts+++ b/e2e/embed-element.spec.ts@@ -212,3 +212,30 @@ test('load rejects broken archive data, emits error and recovers from a subsequeexpect(errors).toEqual([]);await drawn(page);});++test('coalesces connection, src and fit changes and exposes a pending ready immediately', async ({ page }) => {+ await open(page);+ let defaults = 0;+ let explicit = 0;+ page.on('request', request => {+ if (request.url() === defaultSrc) defaults++;+ if (request.url() === sample + '?coalesced') explicit++;+ });+ expect(await page.evaluate(async url => {+ const el = document.createElement('mesh-avatar');+ let loads = 0;+ el.addEventListener('load', () => loads++);+ document.querySelector('#second')!.append(el);+ el.src = url;+ el.fit = 'cover';+ await el.ready;+ const old = el.avatar;+ el.src = url + '&again';+ el.fit = 'contain';+ const pending = el.ready;+ const avatar = await pending;+ return loads === 2 && avatar !== old && avatar === el.avatar;+ }, sample + '?coalesced')).toBe(true);+ expect(defaults).toBe(0);+ expect(explicit).toBe(1);+});diff --git a/e2e/fixtures/react-harness.ts b/e2e/fixtures/react-harness.tsnew file mode 100644index 0000000..4b3274a--- /dev/null+++ b/e2e/fixtures/react-harness.ts@@ -0,0 +1,25 @@+import type * as React from 'react';+import type { createRoot } from 'react-dom/client';+import type { MeshAvatar, MeshAvatarProps, MeshAvatarElement } from '../../packages/react/src/index';++export function mount(react: typeof React, create: typeof createRoot, Component: typeof MeshAvatar) {+ const root = create(document.getElementById('root')!);+ const ref = react.createRef<MeshAvatarElement>();+ const log: { version: number; event: string; value: unknown }[] = [];+ let props: MeshAvatarProps = { src: new URLSearchParams(location.search).get('src') ?? undefined, paused: true };+ let version = 0;+ const render = () => {+ const current = version;+ const child = react.createElement(Component, { ...props, ref, style: { width: 300 }, id: 'avatar', 'aria-label': 'Character',+ onLoad: avatar => log.push({ version: current, event: 'load', value: !!avatar }),+ onError: error => log.push({ version: current, event: 'error', value: String(error) }),+ onMotion: id => log.push({ version: current, event: 'motion', value: id }),+ });+ root.render(new URLSearchParams(location.search).has('strict') ? react.createElement(react.StrictMode, null, child) : child);+ };+ Reflect.set(window, 'harness', { ref, log, reactVersion: react.version,+ update(next: MeshAvatarProps) { props = next; version++; render(); },+ unmount() { root.unmount(); },+ });+ render();+}diff --git a/e2e/fixtures/react.html b/e2e/fixtures/react.htmlnew file mode 100644index 0000000..4c3a96d--- /dev/null+++ b/e2e/fixtures/react.html@@ -0,0 +1,3 @@+<!doctype html>+<html lang="en"><head><meta charset="utf-8"><title>React avatar test</title></head>+<body><div id="root"></div><script type="module" src="./react.tsx"></script></body></html>diff --git a/e2e/fixtures/react.tsx b/e2e/fixtures/react.tsxnew file mode 100644index 0000000..0638770--- /dev/null+++ b/e2e/fixtures/react.tsx@@ -0,0 +1,5 @@+import * as React from 'react';+import { createRoot } from 'react-dom/client';+import { MeshAvatar } from '../../packages/react/src/index';+import { mount } from './react-harness';+mount(React, createRoot, MeshAvatar);diff --git a/e2e/react-wrapper.spec.ts b/e2e/react-wrapper.spec.tsnew file mode 100644index 0000000..a883c06--- /dev/null+++ b/e2e/react-wrapper.spec.ts@@ -0,0 +1,97 @@+import { expect, test, type Page } from '@playwright/test';+import { samplePresent, sampleSkipReason } from './sample';+import type { MeshAvatarElement, MeshAvatarProps } from '../packages/react/src/index';++const sample = `http://127.0.0.1:${process.env.PLAYWRIGHT_SITE_PORT ?? 5174}/mesh-avatar-studio/miko.mavatar`;+const defaultSrc = 'https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar';+type Harness = { ref: { current: MeshAvatarElement | null }; log: { version: number; event: string; value: unknown }[];+ reactVersion: string; update: (props: MeshAvatarProps) => void; unmount: () => void };+declare global { interface Window { harness: Harness } }+const requests = new WeakMap<Page, string[]>();++test.beforeEach(async ({ page, context }) => {+ test.skip(!samplePresent, sampleSkipReason);+ const urls: string[] = [];+ requests.set(page, urls);+ await context.route('**/*', route => {+ const url = route.request().url();+ urls.push(url);+ if (url === defaultSrc) return route.fetch({ url: sample }).then(response => route.fulfill({ response }));+ if (new URL(url).hostname !== '127.0.0.1') return route.abort();+ return route.continue();+ });+});+test.afterEach(({ page }) => {+ expect(requests.get(page)!.filter(url => new URL(url).hostname !== '127.0.0.1')).toEqual([]);+});+async function open(page: Page, fixture = 'react', strict = false) {+ await page.goto(`/e2e/fixtures/${fixture}.html?src=${encodeURIComponent(sample)}${strict ? '&strict' : ''}`);+ await expect.poll(() => page.evaluate(() => !!window.harness?.ref.current?.avatar)).toBe(true);+ expect(await page.evaluate(() => window.harness.log.filter(x => x.event === 'load').length)).toBe(1);+ expect(requests.get(page)!.filter(url => url === sample)).toHaveLength(1);+ expect(requests.get(page)).not.toContain(defaultSrc);+}++test('loads only the supplied src and forwards HTML props and ref', async ({ page }) => {+ await open(page);+ await expect(page.locator('mesh-avatar')).toHaveAttribute('aria-label', 'Character');+ await expect(page.locator('mesh-avatar')).toHaveCSS('width', '300px');+ await page.locator('mesh-avatar').screenshot({ path: 'test-results/react-avatar.png', omitBackground: true });+});++test('updates and removes controlled attributes', async ({ page }) => {+ await open(page);+ await page.evaluate(src => window.harness.update({ src, expression: 'smile', emotion: 'happy', noIdle: true, paused: true, label: 'Miko' }), sample);+ const el = page.locator('mesh-avatar');+ for (const [name, value] of Object.entries({ expression: 'smile', emotion: 'happy', 'no-idle': '', paused: '', label: 'Miko' })) {+ await expect(el).toHaveAttribute(name, value);+ }+ expect(await page.evaluate(() => window.harness.ref.current!.avatar!.getExpression().name)).toBe('smile');+ await page.evaluate(src => window.harness.update({ src }), sample);+ for (const name of ['expression', 'emotion', 'no-idle', 'paused', 'label']) await expect(el).not.toHaveAttribute(name);+ expect(await page.evaluate(() => window.harness.ref.current!.avatar!.getExpression().name)).toBe('neutral');+});++async function fileAndRestore(page: Page) {+ await page.evaluate(async src => {+ const data = await (await fetch(src)).arrayBuffer();+ window.harness.update({ src, source: new File([data], 'chosen.mavatar'), paused: true });+ }, sample);+ await expect.poll(() => page.evaluate(() => window.harness.log.filter(x => x.event === 'load').length)).toBe(2);+ await page.evaluate(src => window.harness.update({ src, paused: true }), sample);+ await expect.poll(() => page.evaluate(() => window.harness.log.filter(x => x.event === 'load').length)).toBe(3);+ await expect.poll(() => page.evaluate(() => !!window.harness.ref.current!.avatar)).toBe(true);+}+test('loads a File and restores the unchanged src when source is removed', async ({ page }) => {+ await open(page);+ await fileAndRestore(page);+});++test('delivers load, error and motion once to the latest callbacks', async ({ page }) => {+ await open(page);+ await page.evaluate(async src => {+ window.harness.update({ src, paused: true });+ await new Promise(requestAnimationFrame);+ window.harness.ref.current!.dispatchEvent(new CustomEvent('motion', { detail: { id: 'wave' } }));+ }, sample);+ expect(await page.evaluate(() => window.harness.log.filter(x => x.event === 'motion'))).toEqual([{ version: 1, event: 'motion', value: 'wave' }]);+ await page.evaluate(src => window.harness.update({ src, source: new Blob(['broken']) }), sample);+ await expect.poll(() => page.evaluate(() => window.harness.log.filter(x => x.event === 'error'))).toEqual([{ version: 2, event: 'error', value: expect.any(String) }]);+ await page.evaluate(src => window.harness.update({ src }), sample);+ await expect.poll(() => page.evaluate(() => window.harness.log.filter(x => x.event === 'load').map(x => x.version))).toEqual([0, 3]);+});++test('StrictMode loads once and destroys the avatar on unmount', async ({ page }) => {+ const errors: string[] = [];+ page.on('pageerror', error => errors.push(error.message));+ await open(page, 'react', true);+ await page.evaluate(() => {+ const el = window.harness.ref.current!;+ Reflect.set(window, 'removedElement', el);+ window.harness.unmount();+ });+ await expect.poll(() => page.evaluate(() => (Reflect.get(window, 'removedElement') as MeshAvatarElement).avatar)).toBe(null);+ expect(await page.evaluate(() => window.harness.ref.current)).toBe(null);+ expect(errors).toEqual([]);+});+diff --git a/package-lock.json b/package-lock.jsonindex 0358ace..2481c60 100644--- a/package-lock.json+++ b/package-lock.json@@ -3746,6 +3746,10 @@"resolved": "packages/element","link": true},+ "node_modules/mesh-avatar-react": {+ "resolved": "packages/react",+ "link": true+ },"node_modules/micromatch": {"version": "4.0.8","resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",@@ -4993,12 +4997,23 @@},"packages/element": {"name": "mesh-avatar-element",- "version": "0.0.0",+ "version": "0.1.0","license": "MIT","dependencies": {"mesh-avatar": "^0.2.1"}},+ "packages/react": {+ "name": "mesh-avatar-react",+ "version": "0.0.0",+ "license": "MIT",+ "dependencies": {+ "mesh-avatar-element": "^0.1.0"+ },+ "peerDependencies": {+ "react": ">=18"+ }+ },"packages/runtime": {"name": "mesh-avatar","version": "0.2.1",diff --git a/package.json b/package.jsonindex f144e9f..53bec25 100644--- a/package.json+++ b/package.json@@ -11,10 +11,11 @@"preview:site": "vite preview --config site/vite.config.ts","screenshots": "node tools/capture-readme-screenshots.mjs","test": "vitest run",- "lint": "eslint src tests e2e tools/*.mjs packages/create-mesh-avatar-studio/*.mjs packages/runtime/src packages/runtime/tests packages/runtime/vite.config.ts packages/runtime/*.mjs packages/element/src packages/element/tests packages/element/vite.config.ts site/src site/vite.config.ts",+ "lint": "eslint src tests e2e tools/*.mjs packages/create-mesh-avatar-studio/*.mjs packages/runtime/src packages/runtime/tests packages/runtime/vite.config.ts packages/runtime/*.mjs packages/element/src packages/element/tests packages/element/vite.config.ts site/src site/vite.config.ts packages/react/src packages/react/tests packages/react/vite.config.ts","build": "tsc --noEmit && vite build","build:runtime": "npm run build -w mesh-avatar","build:element": "npm run build -w mesh-avatar-element",+ "build:react": "npm run build -w mesh-avatar-react","changeset": "changeset","changeset:version": "changeset version","changeset:publish": "changeset publish",diff --git a/packages/element/README.md b/packages/element/README.mdindex a78213d..864d889 100644--- a/packages/element/README.md+++ b/packages/element/README.md@@ -2,6 +2,8 @@Embed an animated 2D avatar with a `<mesh-avatar>` HTML element. Uses the [mesh-avatar](https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/runtime) WebGL runtime, with no framework required.+For React and Next.js, use [mesh-avatar-react](https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/react).+<p align="center"><img src="https://raw.githubusercontent.com/shinshin86/mesh-avatar-studio/main/docs/images/face-tracking.gif" width="400" alt="A Mesh Avatar Studio avatar following a face through a webcam"></p>@@ -67,7 +69,7 @@ The element defaults to `display: block; aspect-ratio: 1 / 1`. Set its width in| `no-idle` | Boolean attribute; presence disables automatic idle motion | Absent || `label` | Accessible canvas label | `Avatar` |-Attributes can be changed after loading. Changing `src` or `fit` destroys the current avatar and loads a new one. After `load(source)`, changing `fit` reloads that source; changing `src` switches back to the attribute URL. A failed load leaves the element empty; listen for `error` to show a fallback. Unknown expression, emotion or fit values warn once per attribute/value pair rather than throwing.+Attributes can be changed after loading. Connection and `src` / `fit` changes in the same task are combined into one load in a microtask; `load(source)` starts immediately. Changing `src` or `fit` destroys the current avatar and loads a new one. After `load(source)`, changing `fit` reloads that source; changing `src` switches back to the attribute URL. A failed load leaves the element empty; listen for `error` to show a fallback. Unknown expression, emotion or fit values warn once per attribute/value pair rather than throwing.## Properties, methods and eventsdiff --git a/packages/element/src/index.ts b/packages/element/src/index.tsindex cdce57c..f119be8 100644--- a/packages/element/src/index.ts+++ b/packages/element/src/index.ts@@ -26,6 +26,7 @@ export class MeshAvatarElement extends Base {#ready = new ReadySignal<MeshAvatar>();#loadId = 0;#loading = false;+ #scheduled: object | null = null;#source: AvatarSource | undefined;#raf = 0;#previous = 0;@@ -55,6 +56,7 @@ export class MeshAvatarElement extends Base {/** Loads a file, archive or URL without changing `src`. A changed `src` replaces this source. */load(source: AvatarSource): Promise<MeshAvatar> {+ this.#scheduled = null;this.#source = source;void this.#load();return this.ready;@@ -94,7 +96,7 @@ export class MeshAvatarElement extends Base {});this.#observer.observe(this);document.addEventListener('visibilitychange', this.#updateLoop);- if (!this.#avatar && !this.#loading) this.#load();+ if (!this.#avatar && !this.#loading) this.#scheduleLoad();else this.#updateLoop();}@@ -111,7 +113,7 @@ export class MeshAvatarElement extends Base {if (name === 'src' || name === 'fit') {if (name === 'src') this.#source = undefined;if (name === 'fit' && parseFit(value) === undefined) this.#warn(name, value);- if (this.isConnected) this.#load();+ if (this.isConnected) this.#scheduleLoad();} else if (name === 'label') {this.#canvas.setAttribute('aria-label', value || 'Avatar');} else if (name === 'paused') {@@ -133,6 +135,17 @@ export class MeshAvatarElement extends Base {}}+ #scheduleLoad() {+ this.#ready.start();+ if (this.#scheduled) return;+ const reservation = this.#scheduled = {};+ queueMicrotask(() => {+ if (this.#scheduled !== reservation) return;+ this.#scheduled = null;+ if (this.isConnected) void this.#load();+ });+ }+async #load(source: AvatarSource = this.#source ?? (this.getAttribute('src') || DEFAULT_SRC)) {const id = ++this.#loadId;this.#unload(false);diff --git a/packages/react/LICENSE b/packages/react/LICENSEnew file mode 100644index 0000000..8b20d89--- /dev/null+++ b/packages/react/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Yuki Shindo++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/react/README.md b/packages/react/README.mdnew file mode 100644index 0000000..7262d38--- /dev/null+++ b/packages/react/README.md@@ -0,0 +1,196 @@+# mesh-avatar-react++Embed an animated 2D avatar in React with `<MeshAvatar />`. Uses the [mesh-avatar-element](https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/element) custom element and the [mesh-avatar](https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/runtime) WebGL runtime. Tested with React 19. The peer dependency accepts React 18 and later.++<p align="center">+ <img src="https://raw.githubusercontent.com/shinshin86/mesh-avatar-studio/main/docs/images/face-tracking.gif" width="400" alt="A Mesh Avatar Studio avatar following a face through a webcam">+</p>++## Getting started++```sh+npm install mesh-avatar-react+```++```tsx+import { MeshAvatar } from 'mesh-avatar-react';++export function Character() {+ return <MeshAvatar expression="smile" label="Character" style={{ width: 320 }} />;+}+```++Without `src`, the component loads Miko from+`https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar`.+The background is transparent. Set the size with CSS: the element defaults to `display: block; aspect-ratio: 1 / 1`.++### Your own avatar++Open your project in [Mesh Avatar Studio](https://github.com/shinshin86/mesh-avatar-studio) and choose **Export .mavatar**. Put the exported file on your site:++```tsx+<MeshAvatar src="/avatars/character.mavatar" style={{ width: 'min(100%, 320px)' }} />+```++An unpacked avatar folder URL also works. Cross-origin assets need CORS headers.++### A file chosen by the user++```tsx+import { useState } from 'react';+import { MeshAvatar } from 'mesh-avatar-react';++export function FilePreview() {+ const [file, setFile] = useState<File>();+ return <>+ <input type="file" accept=".mavatar" onChange={event => setFile(event.target.files?.[0])} />+ <MeshAvatar source={file} onError={error => console.error(error)} style={{ width: 320 }} />+ <button onClick={() => setFile(undefined)}>Restore Miko</button>+ </>;+}+```++`source` takes precedence over `src`. Removing `source` restores `src`, or Miko if `src` is omitted. Keep the same File, Blob or buffer object between renders to avoid loading it again.++## Props++| Prop | Type | Default or behavior |+| --- | --- | --- |+| `src` | `string` | Miko archive URL when omitted |+| `source` | `AvatarSource` | File, Blob, ArrayBuffer, Uint8Array, URL or URL string; takes precedence over `src` |+| `expression` | `LiveExpression` | `neutral`; also `smile`, `shy`, `surprise`, `halfLidded`, `angry`, `sad`, `wink` |+| `emotion` | `Emotion` | Unset; `happy`, `sad`, `angry`, `surprised`, `relaxed`, `neutral` |+| `fit` | `Fit` | `contain` or `cover`; defaults to `contain` |+| `paused` | `boolean` | Pause animation; defaults to `false` |+| `noIdle` | `boolean` | Disable automatic idle motion; defaults to `false` |+| `label` | `string` | Accessible canvas label; defaults to `Avatar` |+| `onLoad` | `(avatar: MeshAvatarInstance) => void` | Avatar loaded and ready |+| `onError` | `(error: unknown) => void` | Loading failed; the element is empty until a successful load |+| `onMotion` | `(id: string \| null) => void` | Motion changed |+| `ref` | `Ref<MeshAvatarElement>` | Access the element and runtime methods |+| HTML attributes | `id`, `className`, `style`, `title`, `hidden`, `aria-*`, `data-*`, etc. | Forwarded to the element |++Removing a prop removes its attribute. Changes to `src` or `fit` reload the avatar; changes in the same React commit are combined into one load. `onLoad` and `onError` receive avatar data and errors, rather than React DOM events.++Exported types: `MeshAvatarProps`, `MeshAvatarElement`, `MeshAvatarInstance`, `AvatarSource`, `LiveExpression`, `Emotion`, `Fit`. The package also exports `DEFAULT_SRC` and `EMOTIONS`.++## Ref methods++The ref points to the custom element. `ref.current.avatar` exposes all [runtime methods](https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/runtime#drive-the-avatar). `ready` resolves with the current avatar; handle rejections if loading can fail.++```tsx+import { useRef } from 'react';+import { MeshAvatar, type MeshAvatarElement } from 'mesh-avatar-react';++export function SpeakingCharacter() {+ const ref = useRef<MeshAvatarElement>(null);+ return <>+ <MeshAvatar ref={ref} style={{ width: 320 }} />+ <button onClick={() => ref.current?.avatar?.setExpression('smile')}>Smile</button>+ <button onClick={() => void ref.current?.speak('こんにちは').catch(console.error)}>Animate speech</button>+ </>;+}+```++`speak(text, { speed, loop })` animates Japanese mouth shapes without generating audio. `play(id)` plays a motion and waits for loading. `load(source)` loads an imperative source, returning the loading promise.++### Audio file or TTS audio++Use `setVoiceLevel` through the ref for per-frame mouth movement. Replace `/voice.mp3` with an audio file or a TTS audio URL. Cross-origin audio needs CORS headers. This example starts playback from a button and cleans up on unmount.++```tsx+import { useEffect, useRef } from 'react';+import { MeshAvatar, type MeshAvatarElement } from 'mesh-avatar-react';++export function VoiceCharacter() {+ const ref = useRef<MeshAvatarElement>(null);+ const stop = useRef<() => void>(() => {});+ useEffect(() => () => stop.current(), []);++ async function playVoice() {+ stop.current();+ const el = ref.current;+ if (!el) return;+ const audio = new Audio();+ audio.crossOrigin = 'anonymous';+ audio.src = '/voice.mp3';+ const ctx = new AudioContext();+ const analyser = ctx.createAnalyser();+ ctx.createMediaElementSource(audio).connect(analyser);+ analyser.connect(ctx.destination);+ const data = new Float32Array(analyser.fftSize);+ let frameId = 0;+ let stopped = false;+ const cleanup = () => {+ if (stopped) return;+ stopped = true;+ cancelAnimationFrame(frameId);+ audio.pause();+ el.avatar?.setSpeaking(false);+ el.setVoiceLevel(0);+ void ctx.close();+ };+ stop.current = cleanup;+ audio.onended = cleanup;+ audio.onerror = cleanup;+ try {+ await ctx.resume();+ await el.ready;+ if (stopped) return;+ await audio.play();+ if (stopped) { audio.pause(); return; }+ el.avatar?.setSpeaking(true);+ const frame = () => {+ if (stopped) return;+ analyser.getFloatTimeDomainData(data);+ const rms = Math.sqrt(data.reduce((sum, value) => sum + value * value, 0) / data.length);+ el.setVoiceLevel(Math.min(1, rms * 5));+ frameId = requestAnimationFrame(frame);+ };+ frame();+ } catch (error) {+ cleanup();+ console.error(error);+ }+ }++ return <>+ <MeshAvatar ref={ref} style={{ width: 320 }} />+ <button onClick={() => void playVoice()}>Play voice</button>+ </>;+}+```++## Next.js++The package includes a `'use client'` directive and can be imported directly in an App Router page:++```tsx+import { MeshAvatar } from 'mesh-avatar-react';++export default function Page() {+ return <MeshAvatar src="/avatars/character.mavatar" style={{ width: 320 }} />;+}+```++Use your own client component when passing callbacks or accessing a ref. Server rendering outputs the element and HTML attributes; avatar attributes and loading are applied in the browser. Size is controlled by CSS.++## Using the Miko sample++Without `src`, Miko loads from Mesh Avatar Studio's GitHub Pages site. To host it yourself instead, save+[the Miko archive](https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar) as part of your site and point `src` at your copy.++Miko © Yuki Shindo (AITuber OnAir). Follow the [Miko character guidelines](https://miko.aituberonair.com/#terms).+Redistribution as part of an application or website is allowed; standalone distribution, asset collections and distribution primarily intended to provide the assets are not.+Do not imply official affiliation or endorsement by Miko or AITuber OnAir, or claim ownership of the character or exclusive usage rights. See also the [sample asset terms](https://github.com/shinshin86/mesh-avatar-studio/blob/main/samples/miko-qipao/MIKO_ASSET_TERMS.md).++## Notes++- Requires WebGL2 in a browser.+- Avoid placing many avatars on one page: browsers limit simultaneous WebGL contexts.+- Animation pauses offscreen, while the tab is hidden, or when `paused` is true.+- With `prefers-reduced-motion: reduce`, hair sway is reduced.++## License++MIT. Miko's artwork is subject to the character guidelines above.diff --git a/packages/react/package.json b/packages/react/package.jsonnew file mode 100644index 0000000..6d84fb9--- /dev/null+++ b/packages/react/package.json@@ -0,0 +1,51 @@+{+ "name": "mesh-avatar-react",+ "version": "0.0.0",+ "type": "module",+ "license": "MIT",+ "description": "A React component for animated Mesh Avatar Studio avatars.",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/shinshin86/mesh-avatar-studio.git",+ "directory": "packages/react"+ },+ "homepage": "https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/react",+ "keywords": [+ "avatar",+ "react",+ "nextjs",+ "webgl",+ "vtuber",+ "mesh-avatar"+ ],+ "sideEffects": [+ "./src/index.tsx",+ "./dist/index.js"+ ],+ "types": "./dist/index.d.ts",+ "files": [+ "dist",+ "README.md",+ "LICENSE"+ ],+ "publishConfig": {+ "access": "public",+ "provenance": true+ },+ "scripts": {+ "build": "vite build && tsc -p tsconfig.build.json",+ "prepack": "npm run build"+ },+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "import": "./dist/index.js"+ }+ },+ "dependencies": {+ "mesh-avatar-element": "^0.1.0"+ },+ "peerDependencies": {+ "react": ">=18"+ }+}diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsxnew file mode 100644index 0000000..9537da9--- /dev/null+++ b/packages/react/src/index.tsx@@ -0,0 +1,77 @@+'use client';++import { createElement, forwardRef, useImperativeHandle, useLayoutEffect, useRef, version, type HTMLAttributes } from 'react';+import { type MeshAvatarElement, type AvatarSource, type Emotion, type Fit, type LiveExpression, type MeshAvatar as MeshAvatarInstance } from 'mesh-avatar-element';+import 'mesh-avatar-element';++export { DEFAULT_SRC, EMOTIONS } from 'mesh-avatar-element';+export type { MeshAvatarElement, AvatarSource, Emotion, Fit, LiveExpression, MeshAvatar as MeshAvatarInstance } from 'mesh-avatar-element';++export interface MeshAvatarProps extends Omit<HTMLAttributes<MeshAvatarElement>, 'onLoad' | 'onError' | 'children' | 'dangerouslySetInnerHTML'> {+ src?: string;+ source?: AvatarSource;+ expression?: LiveExpression;+ emotion?: Emotion;+ fit?: Fit;+ paused?: boolean;+ noIdle?: boolean;+ label?: string;+ onLoad?: (avatar: MeshAvatarInstance) => void;+ onError?: (error: unknown) => void;+ onMotion?: (id: string | null) => void;+}++// React 18 passes className to custom elements as a "classname" attribute; React 19 maps it to class.+const CLASS_PROP = Number(version.split('.')[0]) >= 19 ? 'className' : 'class';++/** A React interface to the <mesh-avatar> element. Set its size with CSS. */+export const MeshAvatar = forwardRef<MeshAvatarElement, MeshAvatarProps>(function MeshAvatar({+ src, source, expression, emotion, fit, paused, noIdle, label, onLoad, onError, onMotion, className, ...html+}, forwardedRef) {+ const element = useRef<MeshAvatarElement>(null);+ const callbacks = useRef({ onLoad, onError, onMotion });+ const applied = useRef<{ source?: AvatarSource; src?: string; fit?: Fit } | null>(null);++ useImperativeHandle(forwardedRef, () => element.current!, []);++ useLayoutEffect(() => { callbacks.current = { onLoad, onError, onMotion }; });+ useLayoutEffect(() => {+ const el = element.current!;+ const load = (event: Event) => callbacks.current.onLoad?.((event as CustomEvent<{ avatar: MeshAvatarInstance }>).detail.avatar);+ const error = (event: Event) => callbacks.current.onError?.((event as CustomEvent<{ error: unknown }>).detail.error);+ const motion = (event: Event) => callbacks.current.onMotion?.((event as CustomEvent<{ id: string | null }>).detail.id);+ el.addEventListener('load', load);+ el.addEventListener('error', error);+ el.addEventListener('motion', motion);+ return () => {+ el.removeEventListener('load', load);+ el.removeEventListener('error', error);+ el.removeEventListener('motion', motion);+ };+ }, []);++ useLayoutEffect(() => {+ const el = element.current!;+ const previous = applied.current;+ for (const [name, value] of Object.entries({ src, fit, expression, emotion, label })) {+ if (value === undefined) el.removeAttribute(name);+ else el.setAttribute(name, value);+ }+ el.toggleAttribute('paused', !!paused);+ el.toggleAttribute('no-idle', !!noIdle);+ if (source !== undefined) {+ if (!previous || source !== previous.source || src !== previous.src || fit !== previous.fit) {+ // Errors are delivered through onError as well as the element's ready promise.+ void el.load(source).catch(() => {});+ }+ } else if (previous?.source !== undefined) {+ // Changing src clears the element's imperative source, even if the URL is unchanged.+ el.removeAttribute('src');+ el.setAttribute('src', src ?? '');+ if (src === undefined) el.removeAttribute('src');+ }+ applied.current = { source, src, fit };+ }, [src, source, expression, emotion, fit, paused, noIdle, label]);++ return createElement('mesh-avatar', { ...html, [CLASS_PROP]: className, ref: element });+});diff --git a/packages/react/tests/ssr.test.ts b/packages/react/tests/ssr.test.tsnew file mode 100644index 0000000..49b292d--- /dev/null+++ b/packages/react/tests/ssr.test.ts@@ -0,0 +1,18 @@+import { createElement } from 'react';+import { renderToString } from 'react-dom/server';+import { expect, test } from 'vitest';+import { MeshAvatar } from '../src/index';++test('server rendering emits HTML attributes without loading an avatar', () => {+ expect(typeof window).toBe('undefined');+ const html = renderToString(createElement(MeshAvatar, {+ src: '/character.mavatar', source: new Uint8Array(), expression: 'smile', noIdle: true,+ className: 'character', style: { width: 320 }, title: 'Character', 'aria-label': 'Avatar',+ }));+ expect(html).toContain('<mesh-avatar');+ expect(html).toContain('class="character"');+ expect(html).toContain('width:320px');+ expect(html).toContain('aria-label="Avatar"');+ expect(html).not.toMatch(/\b(src|source|expression|no-idle)=/);+ expect(html).not.toContain('<canvas');+});diff --git a/packages/react/tests/types.test-d.tsx b/packages/react/tests/types.test-d.tsxnew file mode 100644index 0000000..ddc4f87--- /dev/null+++ b/packages/react/tests/types.test-d.tsx@@ -0,0 +1,14 @@+import { createRef } from 'react';+import { MeshAvatar, type MeshAvatarElement, type MeshAvatarInstance, type MeshAvatarProps } from '../src/index';++const ref = createRef<MeshAvatarElement>();+const props: MeshAvatarProps = { source: new Uint8Array(), expression: 'smile', emotion: 'happy', fit: 'cover' };+export const example = <MeshAvatar {...props} ref={ref} id="avatar" aria-label="Character" data-character="miko"+ onLoad={avatar => { const runtime: MeshAvatarInstance = avatar; runtime.setVoiceLevel(0.5); }}+ onError={error => { const value: unknown = error; void value; }}+ onMotion={id => { const motion: string | null = id; void motion; }} />;+ref.current?.setVoiceLevel(0.5);+// @ts-expect-error Unsupported expressions are rejected.+export const invalidExpression = <MeshAvatar expression="invalid" />;+// @ts-expect-error The ref exposes the element, not a canvas.+export const invalidRef = <MeshAvatar ref={createRef<HTMLCanvasElement>()} />;diff --git a/packages/react/tsconfig.build.json b/packages/react/tsconfig.build.jsonnew file mode 100644index 0000000..adbeca6--- /dev/null+++ b/packages/react/tsconfig.build.json@@ -0,0 +1,23 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "lib": [+ "ES2022",+ "DOM",+ "DOM.Iterable"+ ],+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "strict": true,+ "declaration": true,+ "emitDeclarationOnly": true,+ "noEmitOnError": true,+ "rootDir": "src",+ "outDir": "dist",+ "types": [],+ "jsx": "react-jsx"+ },+ "include": [+ "src"+ ]+}diff --git a/packages/react/vite.config.ts b/packages/react/vite.config.tsnew file mode 100644index 0000000..75a7a4f--- /dev/null+++ b/packages/react/vite.config.ts@@ -0,0 +1,25 @@+import { fileURLToPath } from 'node:url';+import { defineConfig } from 'vite';++export default defineConfig({+ publicDir: false,+ plugins: [{+ name: 'client-directive',+ enforce: 'pre',+ transform(code, id) {+ // Rollup discards module directives with a noisy warning; output.banner restores it in the bundle.+ // Spaces keep the original column positions.+ if (id === fileURLToPath(new URL('./src/index.tsx', import.meta.url))) {+ return { code: code.replace(/^'use client';/, ' '), map: null };+ }+ },+ }],+ build: {+ target: 'es2022',+ lib: { entry: fileURLToPath(new URL('./src/index.tsx', import.meta.url)), formats: ['es'], fileName: () => 'index.js' },+ rollupOptions: {+ external: ['react', 'react/jsx-runtime', 'mesh-avatar-element', 'mesh-avatar'],+ output: { banner: "'use client';" },+ },+ },+});diff --git a/packages/runtime/README.md b/packages/runtime/README.mdindex bc7b8d7..54a1bad 100644--- a/packages/runtime/README.md+++ b/packages/runtime/README.md@@ -2,6 +2,8 @@A WebGL runtime for 2D mesh avatars created with [Mesh Avatar Studio](https://github.com/shinshin86/mesh-avatar-studio). Load a `.mavatar` archive or an avatar folder into a canvas, then control its motion, voice level and expressions.+For React and Next.js, use [mesh-avatar-react](https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/react).+<p align="center"><img src="https://raw.githubusercontent.com/shinshin86/mesh-avatar-studio/main/docs/images/face-tracking.gif" width="400" alt="A Mesh Avatar Studio avatar following a face through a webcam"></p>diff --git a/tsconfig.json b/tsconfig.jsonindex d5b7741..5f0c859 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -9,7 +9,8 @@"module": "ESNext","moduleResolution": "Bundler","paths": {- "mesh-avatar": ["./packages/runtime/src/index.ts"]+ "mesh-avatar": ["./packages/runtime/src/index.ts"],+ "mesh-avatar-element": ["./packages/element/src/index.ts"]},"jsx": "react-jsx","strict": true,@@ -30,6 +31,8 @@"tests","e2e","vite.config.ts",- "playwright.config.ts"+ "playwright.config.ts",+ "packages/react/src",+ "packages/react/tests"]}diff --git a/vite.config.ts b/vite.config.tsindex 8a37396..810182a 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -22,5 +22,5 @@ export default defineConfig({}],publicDir: 'samples',build: { rollupOptions: { input: { editor: 'index.html', stream: 'stream.html', live: 'live.html' } } },- test: { include: ['tests/**/*.test.ts', 'packages/runtime/tests/**/*.test.ts', 'packages/element/tests/**/*.test.ts'] },+ test: { include: ['tests/**/*.test.ts', 'packages/runtime/tests/**/*.test.ts', 'packages/element/tests/**/*.test.ts', 'packages/react/tests/**/*.test.ts'] },});