Skip to content

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

Show overlay layers from the element and React wrapper

shinshin8643b82d015611
diff --git a/.changeset/element-overlays.md b/.changeset/element-overlays.md
new file mode 100644
index 0000000..62308fb
--- /dev/null
+++ b/.changeset/element-overlays.md
@@ -0,0 +1,5 @@
+---
+"mesh-avatar-element": minor
+---
+
+Add the `overlays` attribute and property to show an avatar's optional overlay layers, such as glasses, by name. The choice is kept when the avatar reloads.
diff --git a/.changeset/react-overlays.md b/.changeset/react-overlays.md
new file mode 100644
index 0000000..904f033
--- /dev/null
+++ b/.changeset/react-overlays.md
@@ -0,0 +1,5 @@
+---
+"mesh-avatar-react": minor
+---
+
+Add the `overlays` prop to show an avatar's optional overlay layers, such as glasses, by name.
diff --git a/e2e/embed-element.spec.ts b/e2e/embed-element.spec.ts
index 1244216..a1f0912 100644
--- a/e2e/embed-element.spec.ts
+++ b/e2e/embed-element.spec.ts
@@ -146,6 +146,23 @@ test('standalone bundle renders with one module script and no dev-server transfo
await drawn(page);
});
+test('overlays attribute and property show overlay layers on the loaded avatar', async ({ page }) => {
+ await open(page);
+ const calls = await page.evaluate(() => {
+ const el = document.querySelector('mesh-avatar')!, avatar = el.avatar!, seen: string[][] = [];
+ const original = avatar.setOverlays.bind(avatar);
+ avatar.setOverlays = names => { seen.push([...names]); original(names); };
+ el.setAttribute('overlays', 'glasses hat');
+ const fromAttribute = el.overlays;
+ el.overlays = ['glasses'];
+ const reflected = el.getAttribute('overlays');
+ el.overlays = [];
+ return { seen, fromAttribute, reflected, removed: el.hasAttribute('overlays') };
+ });
+ expect(calls).toEqual({ seen: [['glasses', 'hat'], ['glasses'], []], fromAttribute: ['glasses', 'hat'], reflected: 'glasses', removed: false });
+ await drawn(page);
+});
+
test('unknown expression warns once without throwing or changing the expression', async ({ page }) => {
const warnings: string[] = [], errors: string[] = [];
page.on('console', message => { if (message.type() === 'warning' && message.text().includes('<mesh-avatar>')) warnings.push(message.text()); });
diff --git a/e2e/react-wrapper.spec.ts b/e2e/react-wrapper.spec.ts
index e06d133..aad40c0 100644
--- a/e2e/react-wrapper.spec.ts
+++ b/e2e/react-wrapper.spec.ts
@@ -41,14 +41,14 @@ test('loads only the supplied src and forwards HTML props and ref', async ({ pag
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);
+ await page.evaluate(src => window.harness.update({ src, expression: 'smile', emotion: 'happy', noIdle: true, paused: true, label: 'Miko', overlays: ['glasses', 'hat'] }), sample);
const el = page.locator('mesh-avatar');
- for (const [name, value] of Object.entries({ expression: 'smile', emotion: 'happy', 'no-idle': '', paused: '', label: 'Miko' })) {
+ for (const [name, value] of Object.entries({ expression: 'smile', emotion: 'happy', 'no-idle': '', paused: '', label: 'Miko', overlays: 'glasses hat' })) {
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);
+ for (const name of ['expression', 'emotion', 'no-idle', 'paused', 'label', 'overlays']) await expect(el).not.toHaveAttribute(name);
expect(await page.evaluate(() => window.harness.ref.current!.avatar!.getExpression().name)).toBe('neutral');
});
diff --git a/packages/element/README.md b/packages/element/README.md
index a6dcd57..b9fa705 100644
--- a/packages/element/README.md
+++ b/packages/element/README.md
@@ -68,6 +68,7 @@ The element defaults to `display: block; aspect-ratio: 1 / 1`. Set its width in
| `paused` | Boolean attribute; presence pauses animation | Absent |
| `no-idle` | Boolean attribute; presence disables automatic idle motion | Absent |
| `label` | Accessible canvas label | `Avatar` |
+| `overlays` | Space-separated overlay layer names to show, such as `glasses`; names come from the avatar's `built/overlays/overlays.json`, and unknown names are ignored | None shown |
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.
@@ -88,6 +89,7 @@ el.avatar.setExpression('smile');
| `load(source)` | Loads a File, Blob, ArrayBuffer, Uint8Array, URL or URL string without changing `src`. Returns the loading promise and emits `load` or `error`. The `AvatarSource` type is re-exported from `mesh-avatar`. |
| `ready` | Promise resolving with the avatar for the current source, rejecting on loading failure. A new load after completion creates a new promise; overlapping pending loads resolve with the latest avatar. |
| `src`, `fit`, `expression`, `emotion`, `paused` | Properties reflecting their corresponding attributes. Use attributes for `no-idle` and `label`. |
+| `overlays` | Array of overlay layer names to show, reflecting the `overlays` attribute; `[]` hides them all. The choice is kept when the avatar reloads. |
| `lipSync` | Get a copy of explicit mouth-movement overrides, or assign a partial `LipSyncSettings` object. Overrides survive avatar reloads. |
| `setLipSync(settings)` | Partially updates mouth movement: `granularity`, `openness`, `closeSpeed` (0–1). Omitted fields keep their values. |
| `setVoiceLevel(value)` | Mouth opening from loudness, 0–1. Retains the value until loading finishes. |
diff --git a/packages/element/src/attributes.ts b/packages/element/src/attributes.ts
index bf5795d..454aba3 100644
--- a/packages/element/src/attributes.ts
+++ b/packages/element/src/attributes.ts
@@ -25,6 +25,11 @@ export function parseFit(value: string | null): Fit | undefined {
return value === 'contain' || value === 'cover' ? value : undefined;
}
+/** Overlay layer names from a space-separated attribute; none when it is missing or empty. */
+export function parseOverlays(value: string | null): string[] {
+ return value ? value.split(/\s+/).filter(Boolean) : [];
+}
+
/** Seconds since the previous frame, limited like the runtime's own loop. */
export function frameSeconds(now: number, previous: number) {
return Math.min(0.05, Math.max(0.001, (now - previous) / 1000));
diff --git a/packages/element/src/index.ts b/packages/element/src/index.ts
index f1b6b51..36ec10a 100644
--- a/packages/element/src/index.ts
+++ b/packages/element/src/index.ts
@@ -1,5 +1,5 @@
import { loadMeshAvatar, parseManifest, type AvatarSource, type MeshAvatar, type LipSyncSettings } from 'mesh-avatar';
-import { DEFAULT_SRC, frameSeconds, parseEmotion, parseExpression, parseFit, ReadySignal, type Fit } from './attributes.js';
+import { DEFAULT_SRC, frameSeconds, parseEmotion, parseExpression, parseFit, parseOverlays, ReadySignal, type Fit } from './attributes.js';
export { DEFAULT_SRC, EMOTIONS } from './attributes.js';
export type { Emotion, Fit } from './attributes.js';
@@ -19,7 +19,7 @@ const Base = (typeof HTMLElement === 'undefined' ? class {} : HTMLElement) as ty
* Animation pauses while the element is off screen, the tab is hidden or `paused` is set.
*/
export class MeshAvatarElement extends Base {
- static observedAttributes = ['src', 'fit', 'expression', 'emotion', 'paused', 'no-idle', 'label'];
+ static observedAttributes = ['src', 'fit', 'expression', 'emotion', 'paused', 'no-idle', 'label', 'overlays'];
#canvas: HTMLCanvasElement;
#avatar: MeshAvatar | null = null;
@@ -73,6 +73,9 @@ export class MeshAvatarElement extends Base {
set emotion(value: string | null) { if (value === null) this.removeAttribute('emotion'); else this.setAttribute('emotion', value); }
get paused() { return this.hasAttribute('paused'); }
set paused(value: boolean) { this.toggleAttribute('paused', value); }
+ /** Overlay layers to show, such as glasses (the avatar's built/overlays). Kept across loads. */
+ get overlays(): string[] { return parseOverlays(this.getAttribute('overlays')); }
+ set overlays(names: string[]) { if (names.length) this.setAttribute('overlays', names.join(' ')); else this.removeAttribute('overlays'); }
/** Mouth opening from the voice loudness, 0 to 1. Kept until the avatar loads. */
setVoiceLevel(value: number) {
@@ -145,6 +148,8 @@ export class MeshAvatarElement extends Base {
if (emotion !== undefined) avatar.setEmotion(emotion); else this.#warn(name, this.getAttribute(name));
} else if (name === 'no-idle') {
avatar.setAutoIdle(!this.hasAttribute('no-idle'));
+ } else if (name === 'overlays') {
+ avatar.setOverlays(this.overlays);
}
}
@@ -169,7 +174,7 @@ export class MeshAvatarElement extends Base {
if (id !== this.#loadId) { avatar.destroy(); return; }
this.#loading = false;
this.#avatar = avatar;
- for (const name of ['expression', 'emotion', 'no-idle']) {
+ for (const name of ['expression', 'emotion', 'no-idle', 'overlays']) {
if (name !== 'emotion' || this.hasAttribute(name)) this.#apply(avatar, name);
}
if (this.#voiceLevel !== null) avatar.setVoiceLevel(this.#voiceLevel);
diff --git a/packages/element/tests/attributes.test.ts b/packages/element/tests/attributes.test.ts
index 7bf7ab8..2b7fd2d 100644
--- a/packages/element/tests/attributes.test.ts
+++ b/packages/element/tests/attributes.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { frameSeconds, parseEmotion, parseExpression, parseFit, ReadySignal } from '../src/attributes';
+import { frameSeconds, parseEmotion, parseExpression, parseFit, parseOverlays, ReadySignal } from '../src/attributes';
describe('attribute parsing', () => {
it('reads expressions, treating a missing attribute as neutral', () => {
@@ -29,6 +29,15 @@ describe('attribute parsing', () => {
});
});
+describe('overlay names', () => {
+ it('come from a space-separated attribute', () => {
+ expect(parseOverlays(null)).toEqual([]);
+ expect(parseOverlays('')).toEqual([]);
+ expect(parseOverlays('glasses')).toEqual(['glasses']);
+ expect(parseOverlays(' glasses hat ')).toEqual(['glasses', 'hat']);
+ });
+});
+
describe('ReadySignal', () => {
it('keeps one pending promise across loads that start before the previous one finishes', async () => {
const ready = new ReadySignal<string>();
diff --git a/packages/react/README.md b/packages/react/README.md
index 05f9489..e6c76e8 100644
--- a/packages/react/README.md
+++ b/packages/react/README.md
@@ -64,6 +64,7 @@ export function FilePreview() {
| `paused` | `boolean` | Pause animation; defaults to `false` |
| `noIdle` | `boolean` | Disable automatic idle motion; defaults to `false` |
| `label` | `string` | Accessible canvas label; defaults to `Avatar` |
+| `overlays` | `string[]` | Overlay layers to show, such as `['glasses']`; none by default. Names come from the avatar's `built/overlays/overlays.json` |
| `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 |
diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx
index 9537da9..82c3534 100644
--- a/packages/react/src/index.tsx
+++ b/packages/react/src/index.tsx
@@ -16,6 +16,8 @@ export interface MeshAvatarProps extends Omit<HTMLAttributes<MeshAvatarElement>,
paused?: boolean;
noIdle?: boolean;
label?: string;
+ /** Overlay layers to show, such as glasses; names come from the avatar's built/overlays. */
+ overlays?: string[];
onLoad?: (avatar: MeshAvatarInstance) => void;
onError?: (error: unknown) => void;
onMotion?: (id: string | null) => void;
@@ -26,8 +28,10 @@ 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
+ src, source, expression, emotion, fit, paused, noIdle, label, overlays, onLoad, onError, onMotion, className, ...html
}, forwardedRef) {
+ // A new array with the same names must not count as a change.
+ const overlayNames = overlays?.length ? overlays.join(' ') : undefined;
const element = useRef<MeshAvatarElement>(null);
const callbacks = useRef({ onLoad, onError, onMotion });
const applied = useRef<{ source?: AvatarSource; src?: string; fit?: Fit } | null>(null);
@@ -53,7 +57,7 @@ export const MeshAvatar = forwardRef<MeshAvatarElement, MeshAvatarProps>(functio
useLayoutEffect(() => {
const el = element.current!;
const previous = applied.current;
- for (const [name, value] of Object.entries({ src, fit, expression, emotion, label })) {
+ for (const [name, value] of Object.entries({ src, fit, expression, emotion, label, overlays: overlayNames })) {
if (value === undefined) el.removeAttribute(name);
else el.setAttribute(name, value);
}
@@ -71,7 +75,7 @@ export const MeshAvatar = forwardRef<MeshAvatarElement, MeshAvatarProps>(functio
if (src === undefined) el.removeAttribute('src');
}
applied.current = { source, src, fit };
- }, [src, source, expression, emotion, fit, paused, noIdle, label]);
+ }, [src, source, expression, emotion, fit, paused, noIdle, label, overlayNames]);
return createElement('mesh-avatar', { ...html, [CLASS_PROP]: className, ref: element });
});
diff --git a/packages/react/tests/types.test-d.tsx b/packages/react/tests/types.test-d.tsx
index ddc4f87..ed0a380 100644
--- a/packages/react/tests/types.test-d.tsx
+++ b/packages/react/tests/types.test-d.tsx
@@ -2,7 +2,7 @@ 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' };
+const props: MeshAvatarProps = { source: new Uint8Array(), expression: 'smile', emotion: 'happy', fit: 'cover', overlays: ['glasses'] };
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; }}
@@ -12,3 +12,5 @@ ref.current?.setVoiceLevel(0.5);
export const invalidExpression = <MeshAvatar expression="invalid" />;
// @ts-expect-error The ref exposes the element, not a canvas.
export const invalidRef = <MeshAvatar ref={createRef<HTMLCanvasElement>()} />;
+// @ts-expect-error Overlay names are a list.
+export const invalidOverlays = <MeshAvatar overlays="glasses" />;