@openbone/player 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -69,14 +69,16 @@ Images and sounds load relative to the document's URL. The element is 400 × 300
69
69
  | `state-machine` | first | State machine to run, by name or id. |
70
70
  | `animation` | | Play this animation instead of a state machine. |
71
71
  | `skin` | default skin | Skin (outfit) by name or id. Changing it switches the outfit without reloading. |
72
- | `fit` | `contain` | `contain`, `cover` or `none` (actual size, centred). |
72
+ | `fit` | `contain` | `contain`, `cover`, `auto` (cover when it crops at most 15% of a side, contain otherwise) or `none` (actual size, centred). |
73
+ | `clip` | on | Only the artboard is drawn: art past its edges is cut off, the bars around it stay transparent and clicks there are ignored. `clip="false"` draws the whole canvas. |
74
+ | `fullscreen-fit` | `auto` | Fit while the player (or a parent) is full screen. `auto` fills the screen when that crops only a little of the artboard and shows all of it otherwise; `cover`, `contain`, `none`, or `same` to keep `fit`. |
73
75
  | `renderer` | `webgl` | `webgl` or `canvas`. WebGL falls back to Canvas 2D when WebGL2 is not available. |
74
76
  | `background` | the file's | Any CSS colour (`#fff`, `rebeccapurple`, `rgb(0 0 0 / 50%)`, …), or `transparent` / `none`. |
75
77
  | `autoplay` | on | `autoplay="false"` loads and draws the first frame, then waits for `play()`. |
76
78
  | `scripts` | on | `scripts="none"` never runs the document's scripts. |
77
79
  | `audio` / `muted` | on | `audio="off"` disables sound; `muted` loads sounds but starts muted. |
78
80
 
79
- Changing `skin` switches the skin in place. Changing any other attribute, including setting `src` after the element is
81
+ Changing `skin`, `clip` or `fullscreen-fit` applies in place. Changing any other attribute, including setting `src` after the element is
80
82
  on the page, reloads the player with the new settings.
81
83
 
82
84
  ### Element methods and events
@@ -89,6 +91,7 @@ on the page, reloads the player with the new settings.
89
91
  | `setSkin(name)` | Switch skin (updates the `skin` attribute); `null` shows the default skin. |
90
92
  | `play()` / `pause()` | Start or stop playback and sound. |
91
93
  | `player` | The underlying `Player`, or `null` before the element is connected. |
94
+ | `audioContext` | An `AudioContext` to play through, set before `src`. Create and resume it in a click handler (a play button) and the player starts with sound even if it loads after that click. |
92
95
 
93
96
  | Event | `detail` |
94
97
  |---|---|
@@ -127,14 +130,14 @@ player.speed = 0.5;
127
130
  | `src` | A URL, or an already parsed `OpenBoneDocument`. |
128
131
  | `baseUrl` | Folder for relative image and audio paths (default: the folder of `src`). |
129
132
  | `resolveImageUrl(src)`, `resolveAudioUrl(asset)` | Map asset paths to URLs yourself (overrides `baseUrl`). |
130
- | `stateMachine`, `animation`, `skin`, `autoplay`, `fit`, `renderer`, `background` | As the attributes above. `background: null` is transparent. |
133
+ | `stateMachine`, `animation`, `skin`, `autoplay`, `fit`, `clip`, `fullscreenFit`, `renderer`, `background` | As the attributes above. `background: null` is transparent; `fullscreenFit: null` keeps `fit`. |
131
134
  | `scripts` | `"quickjs"` (default when the document has scripts), `"none"`, or your own `ScriptHost`. |
132
135
  | `audio` | `true` (default), `false` or `"muted"`. |
133
136
  | `audioContext` | Share an existing `AudioContext` instead of creating one. |
134
137
  | `onEvent`, `onStateChange`, `onLoad` | Callbacks. |
135
138
 
136
139
  Members: `ready` (promise), `play()`, `pause()`, `playing`, `speed` (sounds follow it), `setInput`, `getInput`,
137
- `fire`, `setText`, `setSkin`, `skins`, `playAnimation(name, loop?)`, `setFit(fit)`, `setMuted(muted)`, `muted`,
140
+ `fire`, `setText`, `setSkin`, `skins`, `playAnimation(name, loop?)`, `setFit(fit)`, `setFullscreenFit(fit)`, `setClip(clip)`, `currentFit`, `setMuted(muted)`, `muted`,
138
141
  `audio`, `instance` (the runtime `OpenBoneInstance`), `stateMachine`, `doc`, `clientToSkeleton(clientX, clientY)`,
139
142
  `boundingBoxes()` and `dispose()`.
140
143
 
package/dist/audio.d.ts CHANGED
@@ -26,6 +26,9 @@ export declare class WebAudioBackend {
26
26
  private voices;
27
27
  private hostMuted;
28
28
  private unbind;
29
+ /** Looping sounds requested before audio was unlocked, by voice id; they start when the context runs. */
30
+ private pending;
31
+ private offline;
29
32
  constructor(doc: OpenBoneDocument, opts?: WebAudioOptions);
30
33
  /** True once the browser lets the context play. */
31
34
  get unlocked(): boolean;
@@ -37,6 +40,14 @@ export declare class WebAudioBackend {
37
40
  /** Create (if needed) and resume the context now. Call it from a user gesture (a click) so the browser allows sound. */
38
41
  activate(): AudioContext | null;
39
42
  private context;
43
+ /** Start the loops that were waiting for audio once the context runs (whoever resumed it). */
44
+ private watch;
45
+ private flushPending;
46
+ /**
47
+ * Where sounds are decoded: the live context once it exists, else an OfflineAudioContext, which the browser allows
48
+ * without a user gesture (decoded buffers play in any context).
49
+ */
50
+ private decoder;
40
51
  private masterNode;
41
52
  private busNode;
42
53
  /** Mutes set while playing by "mix" commands (mute buttons): bus id, "" = master. They win over the document. */
package/dist/audio.js CHANGED
@@ -16,10 +16,15 @@ export class WebAudioBackend {
16
16
  voices = new Map();
17
17
  hostMuted = false;
18
18
  unbind = null;
19
+ /** Looping sounds requested before audio was unlocked, by voice id; they start when the context runs. */
20
+ pending = new Map();
21
+ offline = null;
19
22
  constructor(doc, opts = {}) {
20
23
  this.doc = doc;
21
24
  this.opts = opts;
22
25
  this.ctx = opts.context ?? null;
26
+ if (this.ctx)
27
+ this.watch(this.ctx);
23
28
  }
24
29
  /** True once the browser lets the context play. */
25
30
  get unlocked() {
@@ -54,8 +59,36 @@ export class WebAudioBackend {
54
59
  if (!Ctor)
55
60
  return null;
56
61
  this.ctx = new Ctor();
62
+ this.watch(this.ctx);
57
63
  return this.ctx;
58
64
  }
65
+ /** Start the loops that were waiting for audio once the context runs (whoever resumed it). */
66
+ watch(ctx) {
67
+ ctx.addEventListener?.("statechange", () => this.flushPending());
68
+ }
69
+ flushPending() {
70
+ if (this.ctx?.state !== "running" || !this.pending.size)
71
+ return;
72
+ const cmds = [...this.pending.values()];
73
+ this.pending.clear();
74
+ for (const cmd of cmds)
75
+ this.play(cmd);
76
+ }
77
+ /**
78
+ * Where sounds are decoded: the live context once it exists, else an OfflineAudioContext, which the browser allows
79
+ * without a user gesture (decoded buffers play in any context).
80
+ */
81
+ decoder() {
82
+ if (this.ctx)
83
+ return this.ctx;
84
+ if (!this.offline) {
85
+ const Offline = globalThis.OfflineAudioContext ?? globalThis.webkitOfflineAudioContext;
86
+ if (!Offline)
87
+ return this.context();
88
+ this.offline = new Offline(2, 1, 48000);
89
+ }
90
+ return this.offline;
91
+ }
59
92
  masterNode(ctx) {
60
93
  if (!this.master) {
61
94
  this.master = ctx.createGain();
@@ -116,7 +149,7 @@ export class WebAudioBackend {
116
149
  const url = this.url(asset);
117
150
  let p = this.buffers.get(url);
118
151
  if (!p) {
119
- const ctx = this.context();
152
+ const ctx = this.decoder();
120
153
  if (!ctx)
121
154
  return Promise.resolve(null);
122
155
  p = fetch(url)
@@ -196,15 +229,24 @@ export class WebAudioBackend {
196
229
  };
197
230
  play(cmd) {
198
231
  const asset = this.doc.audio?.assets.find((a) => a.id === cmd.asset);
199
- const ctx = this.context();
232
+ // Never create the context here: before a user gesture the browser refuses it ("The AudioContext was not allowed
233
+ // to start"). It is created by unlock() / activate(), from a click or key press.
234
+ const ctx = this.ctx;
200
235
  const name = this.doc.audio?.sounds.find((s) => s.id === cmd.sound)?.name ?? asset?.name ?? cmd.sound;
201
- if (!asset || !ctx) {
202
- this.opts.onLog?.(`play ${name} skipped (${asset ? "no Web Audio" : "asset missing"})`, cmd);
236
+ if (!asset) {
237
+ this.opts.onLog?.(`play ${name} skipped (asset missing)`, cmd);
203
238
  return;
204
239
  }
205
- // One-shots before the first gesture would all burst out at unlock time: drop them. Loops start late.
206
- if (ctx.state !== "running" && !cmd.loop) {
207
- this.opts.onLog?.(`play ${name} skipped (audio locked until a click or key press)`, cmd);
240
+ if (!ctx || ctx.state !== "running") {
241
+ // One-shots before the first gesture would all burst out at unlock time: drop them. Loops (music, ambience)
242
+ // wait and start when audio unlocks.
243
+ if (!cmd.loop) {
244
+ this.opts.onLog?.(`play ${name} skipped (audio locked until a click or key press)`, cmd);
245
+ return;
246
+ }
247
+ this.pending.set(cmd.id, cmd);
248
+ this.opts.onLog?.(`play ${name} [${cmd.id}] loop waits for audio to unlock`, cmd);
249
+ void this.load(asset);
208
250
  return;
209
251
  }
210
252
  const gain = ctx.createGain();
@@ -348,6 +390,8 @@ export class WebAudioBackend {
348
390
  });
349
391
  }
350
392
  stop(id, fade, cmd) {
393
+ if (this.pending.delete(id))
394
+ this.opts.onLog?.(`stop [${id}] (had not started)`, cmd);
351
395
  const v = this.voices.get(id);
352
396
  if (!v)
353
397
  return;
@@ -373,6 +417,7 @@ export class WebAudioBackend {
373
417
  }
374
418
  /** Stop every voice (optionally fading). */
375
419
  stopAll(fade = 0) {
420
+ this.pending.clear();
376
421
  for (const id of [...this.voices.keys()])
377
422
  this.stop(id, fade);
378
423
  }
package/dist/bridge.d.ts CHANGED
@@ -30,6 +30,13 @@ export type BridgeCommand = {
30
30
  name?: string;
31
31
  } | {
32
32
  type: "getInputs";
33
+ } | {
34
+ type: "setMuted";
35
+ muted: boolean;
36
+ } | {
37
+ type: "setBusMuted";
38
+ bus: string | null;
39
+ muted: boolean | "toggle";
33
40
  };
34
41
  export interface BridgeInputInfo {
35
42
  name: string;
@@ -82,6 +89,8 @@ export interface BridgePlayer {
82
89
  playAnimation(name: string, loop?: boolean): void;
83
90
  setSkin(name: string | null): void;
84
91
  useStateMachine?(name?: string): void;
92
+ setMuted?(muted: boolean): void;
93
+ setBusMuted?(bus: string | null, muted: boolean | "toggle"): unknown;
85
94
  inputs(): BridgeInputInfo[];
86
95
  }
87
96
  /** Run a validated command against a player. Returns a reply message for queries. */
package/dist/bridge.js CHANGED
@@ -54,6 +54,18 @@ export function parseCommand(input) {
54
54
  return { type: "setSkin", name: typeof c.name === "string" && c.name ? c.name : null };
55
55
  case "useStateMachine":
56
56
  return { type: "useStateMachine", ...(typeof c.name === "string" ? { name: c.name } : {}) };
57
+ case "setMuted":
58
+ if (typeof c.muted !== "boolean")
59
+ throw new Error('OpenBone bridge: "setMuted" needs a boolean `muted`');
60
+ return { type: "setMuted", muted: c.muted };
61
+ case "setBusMuted": {
62
+ const m = c.muted ?? true;
63
+ if (typeof m !== "boolean" && m !== "toggle")
64
+ throw new Error('OpenBone bridge: "setBusMuted" needs `muted`: true, false or "toggle"');
65
+ if (c.bus !== null && c.bus !== undefined && typeof c.bus !== "string")
66
+ throw new Error('OpenBone bridge: "setBusMuted" needs a string `bus` (or null for the master)');
67
+ return { type: "setBusMuted", bus: c.bus ?? null, muted: m };
68
+ }
57
69
  default:
58
70
  throw new Error(`OpenBone bridge: unknown command "${String(c.type)}"`);
59
71
  }
@@ -83,6 +95,12 @@ export function applyCommand(p, c) {
83
95
  return null;
84
96
  case "getInputs":
85
97
  return { type: "inputs", inputs: p.inputs() };
98
+ case "setMuted":
99
+ p.setMuted?.(c.muted);
100
+ return null;
101
+ case "setBusMuted":
102
+ p.setBusMuted?.(c.bus, c.muted);
103
+ return null;
86
104
  }
87
105
  }
88
106
  /** Send a message to every host channel present on `w` (see the module comment). */
@@ -6,7 +6,7 @@
6
6
  * - `?src=url` in the page URL (fetched; needs http(s), not file://)
7
7
  * - `window.OPENBONE_SRC` (a URL or a parsed document)
8
8
  * Options come from `data-*` attributes on `<body>`: data-state-machine, data-animation, data-skin, data-fit,
9
- * data-background ("none" = transparent), data-renderer.
9
+ * data-background ("none" = transparent), data-renderer, data-clip ("false" draws past the artboard's edges).
10
10
  *
11
11
  * It exposes `window.OpenBone` (see bridge.ts for the message format).
12
12
  */
@@ -6,7 +6,7 @@
6
6
  * - `?src=url` in the page URL (fetched; needs http(s), not file://)
7
7
  * - `window.OPENBONE_SRC` (a URL or a parsed document)
8
8
  * Options come from `data-*` attributes on `<body>`: data-state-machine, data-animation, data-skin, data-fit,
9
- * data-background ("none" = transparent), data-renderer.
9
+ * data-background ("none" = transparent), data-renderer, data-clip ("false" draws past the artboard's edges).
10
10
  *
11
11
  * It exposes `window.OpenBone` (see bridge.ts for the message format).
12
12
  */
@@ -67,6 +67,8 @@ function start() {
67
67
  player.instance.useStateMachine(n);
68
68
  watchInputs();
69
69
  },
70
+ setMuted: (m) => player?.setMuted(m),
71
+ setBusMuted: (b, m) => player?.setBusMuted(b, m),
70
72
  inputs,
71
73
  };
72
74
  const watchInputs = () => player?.stateMachine?.on("inputChange", () => postToHost({ type: "inputs", inputs: inputs() }));
@@ -91,6 +93,8 @@ function start() {
91
93
  receive: run,
92
94
  setInput: (name, value) => run({ type: "setInput", name, value }),
93
95
  fire: (name) => run({ type: "fire", name }),
96
+ setMuted: (muted) => run({ type: "setMuted", muted }),
97
+ setBusMuted: (bus, muted = true) => run({ type: "setBusMuted", bus, muted }),
94
98
  play: (animation, loop) => run({ type: "play", animation, loop }),
95
99
  pause: () => run({ type: "pause" }),
96
100
  setSkin: (name) => run({ type: "setSkin", name }),
@@ -128,6 +132,7 @@ function start() {
128
132
  animation: opt("animation"),
129
133
  skin: opt("skin"),
130
134
  fit: opt("fit") ?? "contain",
135
+ clip: opt("clip") !== "false",
131
136
  renderer: opt("renderer") ?? "webgl",
132
137
  ...(bg !== undefined ? { background: bg === "none" ? null : bg } : {}),
133
138
  scripts: host ?? "none",
package/dist/element.d.ts CHANGED
@@ -2,22 +2,33 @@ import { Player } from "./player.js";
2
2
  /**
3
3
  * <openbone-player src="hero.obone" state-machine="ui" animation="idle" skin="red" fit="contain" renderer="webgl">
4
4
  * Events: "openbone-event" (detail = FiredEvent), "openbone-state" (detail = state change), "openbone-load".
5
- * Methods: setInput(name, value), fire(name), setText(slot, text), setSkin(name), play(), pause(), player (the underlying Player).
5
+ * Methods: setInput(name, value), fire(name), setText(slot, text), setSkin(name), play(), pause(),
6
+ * setMuted(muted), setBusMuted(bus, muted | "toggle"), toggleBus(bus), isBusMuted(bus), buses, player (the underlying Player).
6
7
  * Audio plays after the first click/key press; `muted` attribute starts muted, `audio="off"` disables it.
7
8
  * Changing the `skin` attribute switches the outfit without reloading.
9
+ * Only the artboard is drawn (anything past its edges is cut off); `clip="false"` draws the whole canvas. Full screen
10
+ * fills the screen when that crops only a little (`fullscreen-fit`, default "auto"; "same" keeps `fit`). Both change without reloading.
8
11
  */
9
12
  export declare class OpenBonePlayerElement extends HTMLElement {
10
13
  /** `skin` switches skins in place; any other of these reloads the player with the new settings. */
11
14
  static observedAttributes: string[];
12
15
  player: Player | null;
16
+ /**
17
+ * An AudioContext to play through instead of creating one, set before `src`. Create and resume it in a click
18
+ * handler (a play button) and the player starts with sound even when it loads after that click.
19
+ */
20
+ audioContext: AudioContext | null;
13
21
  private canvas;
14
22
  constructor();
15
23
  connectedCallback(): void;
16
24
  disconnectedCallback(): void;
17
25
  attributeChangedCallback(n: string, old: string | null, val: string | null): void;
18
- /** The attributes the current player was built with (everything observed except `skin`). */
26
+ /** The attributes the current player was built with (everything observed except those that change in place). */
19
27
  private loadedWith;
20
28
  private settings;
29
+ private clip;
30
+ /** `fullscreen-fit`: contain / cover / auto / none; "same" (or "") = the `fit` attribute; absent = auto. */
31
+ private fullscreenFit;
21
32
  private init;
22
33
  /** `background` attribute: a colour, "transparent"/"none" for no background, absent for the file's own. */
23
34
  private background;
@@ -26,6 +37,16 @@ export declare class OpenBonePlayerElement extends HTMLElement {
26
37
  fire(name: string): void;
27
38
  setSkin(name: string | null): void;
28
39
  play(): void;
40
+ /** Mute or unmute everything. */
41
+ setMuted(muted: boolean): void;
42
+ /** Mute, unmute or toggle a sound bus by name ("music", "sfx"…); null or "master" = the master. */
43
+ setBusMuted(bus: string | null, muted?: boolean | "toggle"): boolean | null;
44
+ toggleBus(bus: string | null): boolean | null;
45
+ isBusMuted(bus: string | null): boolean | null;
46
+ get buses(): {
47
+ name: string;
48
+ muted: boolean;
49
+ }[];
29
50
  pause(): void;
30
51
  }
31
52
  export declare function definePlayerElement(tag?: string): void;
package/dist/element.js CHANGED
@@ -2,14 +2,22 @@ import { Player } from "./player.js";
2
2
  /**
3
3
  * <openbone-player src="hero.obone" state-machine="ui" animation="idle" skin="red" fit="contain" renderer="webgl">
4
4
  * Events: "openbone-event" (detail = FiredEvent), "openbone-state" (detail = state change), "openbone-load".
5
- * Methods: setInput(name, value), fire(name), setText(slot, text), setSkin(name), play(), pause(), player (the underlying Player).
5
+ * Methods: setInput(name, value), fire(name), setText(slot, text), setSkin(name), play(), pause(),
6
+ * setMuted(muted), setBusMuted(bus, muted | "toggle"), toggleBus(bus), isBusMuted(bus), buses, player (the underlying Player).
6
7
  * Audio plays after the first click/key press; `muted` attribute starts muted, `audio="off"` disables it.
7
8
  * Changing the `skin` attribute switches the outfit without reloading.
9
+ * Only the artboard is drawn (anything past its edges is cut off); `clip="false"` draws the whole canvas. Full screen
10
+ * fills the screen when that crops only a little (`fullscreen-fit`, default "auto"; "same" keeps `fit`). Both change without reloading.
8
11
  */
9
12
  export class OpenBonePlayerElement extends HTMLElement {
10
13
  /** `skin` switches skins in place; any other of these reloads the player with the new settings. */
11
- static observedAttributes = ["src", "skin", "animation", "state-machine", "fit", "renderer", "autoplay", "background", "scripts", "audio", "muted"];
14
+ static observedAttributes = ["src", "skin", "clip", "fullscreen-fit", "animation", "state-machine", "fit", "renderer", "autoplay", "background", "scripts", "audio", "muted"];
12
15
  player = null;
16
+ /**
17
+ * An AudioContext to play through instead of creating one, set before `src`. Create and resume it in a click
18
+ * handler (a play button) and the player starts with sound even when it loads after that click.
19
+ */
20
+ audioContext = null;
13
21
  canvas;
14
22
  constructor() {
15
23
  super();
@@ -32,15 +40,30 @@ export class OpenBonePlayerElement extends HTMLElement {
32
40
  return;
33
41
  if (n === "skin")
34
42
  this.player?.setSkin(val);
43
+ else if (n === "clip")
44
+ this.player?.setClip(this.clip());
45
+ else if (n === "fullscreen-fit")
46
+ this.player?.setFullscreenFit(this.fullscreenFit() ?? (val === null ? "auto" : null));
35
47
  // Includes `src` set for the first time after the element was added to the page. Upgrading an element reports each
36
48
  // attribute it already has; those match what the player was built with, so they don't reload it.
37
49
  else if (this.settings() !== this.loadedWith)
38
50
  this.init();
39
51
  }
40
- /** The attributes the current player was built with (everything observed except `skin`). */
52
+ /** The attributes the current player was built with (everything observed except those that change in place). */
41
53
  loadedWith;
42
54
  settings() {
43
- return JSON.stringify(OpenBonePlayerElement.observedAttributes.filter((a) => a !== "skin").map((a) => this.getAttribute(a)));
55
+ const live = ["skin", "clip", "fullscreen-fit"];
56
+ return JSON.stringify(OpenBonePlayerElement.observedAttributes.filter((a) => !live.includes(a)).map((a) => this.getAttribute(a)));
57
+ }
58
+ clip() {
59
+ return this.getAttribute("clip") !== "false";
60
+ }
61
+ /** `fullscreen-fit`: contain / cover / auto / none; "same" (or "") = the `fit` attribute; absent = auto. */
62
+ fullscreenFit() {
63
+ const v = this.getAttribute("fullscreen-fit");
64
+ if (v === null)
65
+ return undefined;
66
+ return v === "contain" || v === "cover" || v === "auto" || v === "none" ? v : null;
44
67
  }
45
68
  init() {
46
69
  const src = this.getAttribute("src");
@@ -56,11 +79,14 @@ export class OpenBonePlayerElement extends HTMLElement {
56
79
  animation: this.getAttribute("animation") ?? undefined,
57
80
  skin: this.getAttribute("skin") ?? undefined,
58
81
  fit: this.getAttribute("fit") ?? "contain",
82
+ fullscreenFit: this.fullscreenFit(),
83
+ clip: this.clip(),
59
84
  renderer: this.getAttribute("renderer") ?? "webgl",
60
85
  autoplay: this.getAttribute("autoplay") !== "false",
61
86
  background: this.background(),
62
87
  scripts: this.getAttribute("scripts") === "none" ? "none" : "quickjs",
63
88
  audio: this.getAttribute("audio") === "off" ? false : this.hasAttribute("muted") ? "muted" : true,
89
+ ...(this.audioContext ? { audioContext: this.audioContext } : {}),
64
90
  onEvent: (e) => this.dispatchEvent(new CustomEvent("openbone-event", { detail: e, bubbles: true, composed: true })),
65
91
  onStateChange: (e) => this.dispatchEvent(new CustomEvent("openbone-state", { detail: e, bubbles: true, composed: true })),
66
92
  onLoad: () => this.dispatchEvent(new CustomEvent("openbone-load", { bubbles: true, composed: true })),
@@ -92,6 +118,23 @@ export class OpenBonePlayerElement extends HTMLElement {
92
118
  play() {
93
119
  this.player?.play();
94
120
  }
121
+ /** Mute or unmute everything. */
122
+ setMuted(muted) {
123
+ this.player?.setMuted(muted);
124
+ }
125
+ /** Mute, unmute or toggle a sound bus by name ("music", "sfx"…); null or "master" = the master. */
126
+ setBusMuted(bus, muted = true) {
127
+ return this.player?.setBusMuted(bus, muted) ?? null;
128
+ }
129
+ toggleBus(bus) {
130
+ return this.player?.toggleBus(bus) ?? null;
131
+ }
132
+ isBusMuted(bus) {
133
+ return this.player?.isBusMuted(bus) ?? null;
134
+ }
135
+ get buses() {
136
+ return this.player?.buses ?? [];
137
+ }
95
138
  pause() {
96
139
  this.player?.pause();
97
140
  }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { Player, type PlayerOptions, setScriptHostFactory } from "./player.js";
1
+ export { type Fit, Player, type PlayerOptions, artboardRect, fitView, setScriptHostFactory } from "./player.js";
2
2
  export { OpenBonePlayerElement, definePlayerElement } from "./element.js";
3
3
  export { WebAudioBackend, type WebAudioOptions } from "./audio.js";
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- export { Player, setScriptHostFactory } from "./player.js";
1
+ export { Player, artboardRect, fitView, setScriptHostFactory } from "./player.js";
2
2
  export { OpenBonePlayerElement, definePlayerElement } from "./element.js";
3
3
  export { WebAudioBackend } from "./audio.js";
package/dist/player.d.ts CHANGED
@@ -15,7 +15,18 @@ export interface PlayerOptions {
15
15
  /** "quickjs" (sandboxed, default when the doc has scripts), "none", or a custom host. */
16
16
  scripts?: "quickjs" | "none" | ScriptHost;
17
17
  renderer?: "webgl" | "canvas";
18
- fit?: "contain" | "cover" | "none";
18
+ /** How the artboard fits the canvas (default "contain": all of it, with empty bars on the longer sides). */
19
+ fit?: Fit;
20
+ /**
21
+ * Fit while the canvas is shown full screen (default "auto": fill the screen when that crops only a little of the
22
+ * artboard, otherwise show all of it). null keeps `fit`.
23
+ */
24
+ fullscreenFit?: Fit | null;
25
+ /**
26
+ * Draw only inside the artboard (default true), like a camera: anything placed past its edges is cut off, the bars
27
+ * around it stay clear (the page shows through) and clicks there are ignored. false draws everything on the canvas.
28
+ */
29
+ clip?: boolean;
19
30
  background?: string | null;
20
31
  /** Play the document's sounds (default true). "muted" loads them but starts muted. Audio unlocks on the first click or key press. */
21
32
  audio?: boolean | "muted";
@@ -33,6 +44,33 @@ export interface PlayerOptions {
33
44
  }) => void;
34
45
  onLoad?: (p: Player) => void;
35
46
  }
47
+ /**
48
+ * contain: all of the artboard, with bars on the longer sides. cover: fill the canvas, cropping the artboard's edges.
49
+ * auto: cover when that crops at most AUTO_CROP of the artboard's width or height, contain otherwise (so buttons near
50
+ * the edges of the art never get cut off on a very different screen shape). none: actual size, centred.
51
+ */
52
+ export type Fit = "contain" | "cover" | "auto" | "none";
53
+ /** The most of the artboard's width or height `auto` will crop to fill the canvas. */
54
+ export declare const AUTO_CROP = 0.15;
55
+ /** Where an artboard of aw × ah lands on a canvas of cw × ch (CSS pixels) for a fit: zoom and top-left offset. */
56
+ export declare function fitView(cw: number, ch: number, aw: number, ah: number, fit: Fit): {
57
+ zoom: number;
58
+ x: number;
59
+ y: number;
60
+ };
61
+ /** The canvas rectangle (device pixels, y down) the artboard covers, cut to the canvas; null when none of it shows. */
62
+ export declare function artboardRect(view: {
63
+ x: number;
64
+ y: number;
65
+ zoom: number;
66
+ }, aw: number, ah: number, cw: number, ch: number): {
67
+ x: number;
68
+ y: number;
69
+ w: number;
70
+ h: number;
71
+ } | null;
72
+ /** Whether `node` is the full-screen element or inside it, across shadow roots (a player element's canvas is in one). */
73
+ export declare function isInFullscreen(node: Node): boolean;
36
74
  /**
37
75
  * Replace how players create the sandbox for documents with scripts (default: load `@openbone/scripting`).
38
76
  * Bundles use it to supply an inlined QuickJS build, or `() => Promise.resolve(null)` to run without scripts.
@@ -50,6 +88,7 @@ export declare class Player {
50
88
  private c2d;
51
89
  private view;
52
90
  private ro;
91
+ private onFullscreen;
53
92
  playing: boolean;
54
93
  /** Playback rate (1 = real time). */
55
94
  private _speed;
@@ -64,6 +103,11 @@ export declare class Player {
64
103
  private load;
65
104
  private setupRenderer;
66
105
  private resize;
106
+ /** The fit in use now: `fullscreenFit` while the canvas is full screen, otherwise `fit`. */
107
+ get currentFit(): Fit;
108
+ private get clipping();
109
+ /** Whether page coordinates fall on the artboard (always true with clip off, where the whole canvas is live). */
110
+ private onArtboard;
67
111
  private toSkeleton;
68
112
  /** Page (client) coordinates, e.g. a pointer event's clientX/clientY, to skeleton space (y up), through the current fit. */
69
113
  clientToSkeleton(clientX: number, clientY: number): [number, number];
@@ -74,14 +118,34 @@ export declare class Player {
74
118
  boundingBoxes(): SkeletonBounds;
75
119
  private bindPointer;
76
120
  private draw;
121
+ private clearAll;
77
122
  play(): void;
78
123
  /** Change how the artboard fits the canvas ("none" = actual size, centred). */
79
- setFit(fit: "contain" | "cover" | "none"): void;
124
+ setFit(fit: Fit): void;
125
+ /** Change the fit used while full screen (null = the same as `fit`). */
126
+ setFullscreenFit(fit: Fit | null): void;
127
+ /** Draw only inside the artboard (true, the default) or everything on the canvas (false). */
128
+ setClip(clip: boolean): void;
80
129
  /** Pause the animation and its sounds (play() continues both from where they were). */
81
130
  pause(): void;
82
131
  /** Mute or unmute this player's sounds. */
83
132
  setMuted(muted: boolean): void;
84
133
  get muted(): boolean;
134
+ /**
135
+ * Mute, unmute or toggle one sound bus by name or id ("music", "sfx"…), or the master with null / "master", e.g.
136
+ * from music and sound-effect buttons on your page. Same as a mute-button listener inside the artboard, so both
137
+ * stay in step. Returns the new state, or null when the file has no such bus (or hasn't loaded yet).
138
+ */
139
+ setBusMuted(bus: string | null, muted?: boolean | "toggle"): boolean | null;
140
+ /** Flip a bus's mute (see setBusMuted). Returns the new state. */
141
+ toggleBus(bus: string | null): boolean | null;
142
+ /** Whether a bus (name or id; null / "master" = master) is muted right now; null when there is no such bus. */
143
+ isBusMuted(bus: string | null): boolean | null;
144
+ /** The file's sound buses with their current mute state. */
145
+ get buses(): {
146
+ name: string;
147
+ muted: boolean;
148
+ }[];
85
149
  setInput(name: string, value: boolean | number | string): void;
86
150
  /**
87
151
  * Show fixed text (or a `{input}` template) in a slot's text attachment instead of its own; null restores it.
package/dist/player.js CHANGED
@@ -3,6 +3,34 @@ import { CanvasRenderer } from "@openbone/render-canvas";
3
3
  import { WebGLRenderer } from "@openbone/render-webgl";
4
4
  import { OpenBoneInstance } from "@openbone/runtime";
5
5
  import { WebAudioBackend } from "./audio.js";
6
+ /** The most of the artboard's width or height `auto` will crop to fill the canvas. */
7
+ export const AUTO_CROP = 0.15;
8
+ /** Where an artboard of aw × ah lands on a canvas of cw × ch (CSS pixels) for a fit: zoom and top-left offset. */
9
+ export function fitView(cw, ch, aw, ah, fit) {
10
+ const contain = Math.min(cw / aw, ch / ah);
11
+ const cover = Math.max(cw / aw, ch / ah);
12
+ const zoom = fit === "none" ? 1 : fit === "contain" ? contain : fit === "cover" || 1 - contain / cover <= AUTO_CROP + 1e-9 ? cover : contain;
13
+ return { zoom, x: (cw - aw * zoom) / 2, y: (ch - ah * zoom) / 2 };
14
+ }
15
+ /** The canvas rectangle (device pixels, y down) the artboard covers, cut to the canvas; null when none of it shows. */
16
+ export function artboardRect(view, aw, ah, cw, ch) {
17
+ const x0 = Math.max(0, Math.round(view.x));
18
+ const y0 = Math.max(0, Math.round(view.y));
19
+ const x1 = Math.min(cw, Math.round(view.x + aw * view.zoom));
20
+ const y1 = Math.min(ch, Math.round(view.y + ah * view.zoom));
21
+ return x1 > x0 && y1 > y0 ? { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } : null;
22
+ }
23
+ const fullscreenElement = (d) => d.fullscreenElement ?? d.webkitFullscreenElement ?? null;
24
+ /** Whether `node` is the full-screen element or inside it, across shadow roots (a player element's canvas is in one). */
25
+ export function isInFullscreen(node) {
26
+ const fs = node.ownerDocument ? fullscreenElement(node.ownerDocument) : null;
27
+ if (!fs)
28
+ return false;
29
+ for (let n = node; n; n = n.parentNode ?? n.host ?? null)
30
+ if (n === fs)
31
+ return true;
32
+ return false;
33
+ }
6
34
  let scriptHostFactory = null;
7
35
  /**
8
36
  * Replace how players create the sandbox for documents with scripts (default: load `@openbone/scripting`).
@@ -23,6 +51,7 @@ export class Player {
23
51
  c2d = null;
24
52
  view = { x: 0, y: 0, zoom: 1 };
25
53
  ro = null;
54
+ onFullscreen = () => this.doc && this.resize();
26
55
  playing = false;
27
56
  /** Playback rate (1 = real time). */
28
57
  _speed = 1;
@@ -115,6 +144,9 @@ export class Player {
115
144
  this.bindPointer();
116
145
  this.ro = new ResizeObserver(() => this.resize());
117
146
  this.ro.observe(o.canvas);
147
+ const d = o.canvas.ownerDocument ?? document;
148
+ d.addEventListener("fullscreenchange", this.onFullscreen);
149
+ d.addEventListener("webkitfullscreenchange", this.onFullscreen);
118
150
  this.resize();
119
151
  this.instance.advance(0);
120
152
  this.draw();
@@ -142,12 +174,27 @@ export class Player {
142
174
  const h = c.clientHeight || this.doc.height;
143
175
  c.width = Math.round(w * dpr);
144
176
  c.height = Math.round(h * dpr);
145
- const fit = this.opts.fit ?? "contain";
146
- const z = fit === "none" ? 1 : (fit === "cover" ? Math.max : Math.min)(w / this.doc.width, h / this.doc.height);
147
- this.view = { zoom: z, x: (w - this.doc.width * z) / 2, y: (h - this.doc.height * z) / 2 };
177
+ this.view = fitView(w, h, this.doc.width, this.doc.height, this.currentFit);
148
178
  if (!this.playing)
149
179
  this.draw();
150
180
  }
181
+ /** The fit in use now: `fullscreenFit` while the canvas is full screen, otherwise `fit`. */
182
+ get currentFit() {
183
+ const fs = this.opts.fullscreenFit === undefined ? "auto" : this.opts.fullscreenFit;
184
+ return (fs && isInFullscreen(this.opts.canvas) ? fs : this.opts.fit) ?? "contain";
185
+ }
186
+ get clipping() {
187
+ return this.opts.clip !== false;
188
+ }
189
+ /** Whether page coordinates fall on the artboard (always true with clip off, where the whole canvas is live). */
190
+ onArtboard(clientX, clientY) {
191
+ if (!this.clipping)
192
+ return true;
193
+ const r = this.opts.canvas.getBoundingClientRect();
194
+ const ax = (clientX - r.left - this.view.x) / this.view.zoom;
195
+ const ay = (clientY - r.top - this.view.y) / this.view.zoom;
196
+ return ax >= 0 && ay >= 0 && ax <= this.doc.width && ay <= this.doc.height;
197
+ }
151
198
  toSkeleton(e) {
152
199
  return this.clientToSkeleton(e.clientX, e.clientY);
153
200
  }
@@ -167,7 +214,13 @@ export class Player {
167
214
  }
168
215
  bindPointer() {
169
216
  const c = this.opts.canvas;
170
- const send = (type) => (e) => this.instance.pointer(type, ...this.toSkeleton(e));
217
+ // Past the artboard's edges (with clip on) nothing is drawn, so nothing there can be hit: a move there leaves it.
218
+ const send = (type) => (e) => {
219
+ if (this.onArtboard(e.clientX, e.clientY))
220
+ this.instance.pointer(type, ...this.toSkeleton(e));
221
+ else if (type === "move")
222
+ this.instance.pointer("move", -1e9, -1e9);
223
+ };
171
224
  c.addEventListener("pointerdown", send("down"));
172
225
  c.addEventListener("pointerup", send("up"));
173
226
  c.addEventListener("pointermove", send("move"));
@@ -177,19 +230,58 @@ export class Player {
177
230
  const dpr = window.devicePixelRatio || 1;
178
231
  const v = { x: this.view.x * dpr, y: this.view.y * dpr, zoom: this.view.zoom * dpr };
179
232
  const bg = this.opts.background === undefined ? this.doc.background : this.opts.background;
233
+ const cw = this.opts.canvas.width;
234
+ const ch = this.opts.canvas.height;
235
+ // With clip on, the background and the art fill the artboard only; the bars around it stay transparent.
236
+ const clip = this.clipping ? artboardRect(v, this.doc.width, this.doc.height, cw, ch) : null;
237
+ if (this.clipping && !clip) {
238
+ this.clearAll();
239
+ return;
240
+ }
180
241
  if (this.gl) {
181
242
  const col = bg ? colorToGl(bg) : [0, 0, 0, 0];
182
- this.gl.render(this.instance.skeleton, v, col);
243
+ const gl = this.gl.gl;
244
+ if (clip) {
245
+ this.clearAll();
246
+ gl.enable(gl.SCISSOR_TEST);
247
+ gl.scissor(clip.x, ch - clip.y - clip.h, clip.w, clip.h); // GL counts y from the bottom
248
+ }
249
+ try {
250
+ this.gl.render(this.instance.skeleton, v, col);
251
+ }
252
+ finally {
253
+ if (clip)
254
+ gl.disable(gl.SCISSOR_TEST);
255
+ }
183
256
  }
184
257
  else if (this.c2d) {
185
258
  const ctx = this.c2d.ctx;
186
259
  ctx.setTransform(1, 0, 0, 1, 0, 0);
187
- ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
260
+ ctx.clearRect(0, 0, cw, ch);
261
+ ctx.save();
262
+ if (clip) {
263
+ ctx.beginPath();
264
+ ctx.rect(clip.x, clip.y, clip.w, clip.h);
265
+ ctx.clip();
266
+ }
188
267
  if (bg) {
189
268
  ctx.fillStyle = bg;
190
- ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
269
+ ctx.fillRect(0, 0, cw, ch);
191
270
  }
192
271
  this.c2d.render(this.instance.skeleton, { view: v, clear: false });
272
+ ctx.restore();
273
+ }
274
+ }
275
+ clearAll() {
276
+ if (this.gl) {
277
+ const gl = this.gl.gl;
278
+ gl.disable(gl.SCISSOR_TEST);
279
+ gl.clearColor(0, 0, 0, 0);
280
+ gl.clear(gl.COLOR_BUFFER_BIT);
281
+ }
282
+ else if (this.c2d) {
283
+ this.c2d.ctx.setTransform(1, 0, 0, 1, 0, 0);
284
+ this.c2d.ctx.clearRect(0, 0, this.opts.canvas.width, this.opts.canvas.height);
193
285
  }
194
286
  }
195
287
  play() {
@@ -215,6 +307,18 @@ export class Player {
215
307
  if (this.doc)
216
308
  this.resize();
217
309
  }
310
+ /** Change the fit used while full screen (null = the same as `fit`). */
311
+ setFullscreenFit(fit) {
312
+ this.opts.fullscreenFit = fit;
313
+ if (this.doc)
314
+ this.resize();
315
+ }
316
+ /** Draw only inside the artboard (true, the default) or everything on the canvas (false). */
317
+ setClip(clip) {
318
+ this.opts.clip = clip;
319
+ if (this.doc && !this.playing)
320
+ this.draw();
321
+ }
218
322
  /** Pause the animation and its sounds (play() continues both from where they were). */
219
323
  pause() {
220
324
  this.playing = false;
@@ -228,6 +332,26 @@ export class Player {
228
332
  get muted() {
229
333
  return this.audio?.muted ?? false;
230
334
  }
335
+ /**
336
+ * Mute, unmute or toggle one sound bus by name or id ("music", "sfx"…), or the master with null / "master", e.g.
337
+ * from music and sound-effect buttons on your page. Same as a mute-button listener inside the artboard, so both
338
+ * stay in step. Returns the new state, or null when the file has no such bus (or hasn't loaded yet).
339
+ */
340
+ setBusMuted(bus, muted = true) {
341
+ return this.instance?.setBusMuted(bus, muted) ?? null;
342
+ }
343
+ /** Flip a bus's mute (see setBusMuted). Returns the new state. */
344
+ toggleBus(bus) {
345
+ return this.setBusMuted(bus, "toggle");
346
+ }
347
+ /** Whether a bus (name or id; null / "master" = master) is muted right now; null when there is no such bus. */
348
+ isBusMuted(bus) {
349
+ return this.instance?.isBusMuted(bus) ?? null;
350
+ }
351
+ /** The file's sound buses with their current mute state. */
352
+ get buses() {
353
+ return (this.doc?.audio?.buses ?? []).map((b) => ({ name: b.name, muted: this.isBusMuted(b.id) ?? b.muted }));
354
+ }
231
355
  // ---- convenience API (Rive-like) ----
232
356
  setInput(name, value) {
233
357
  this.stateMachine?.setInput(name, value);
@@ -271,6 +395,9 @@ export class Player {
271
395
  dispose() {
272
396
  this.pause();
273
397
  this.ro?.disconnect();
398
+ const d = this.opts.canvas.ownerDocument ?? document;
399
+ d.removeEventListener("fullscreenchange", this.onFullscreen);
400
+ d.removeEventListener("webkitfullscreenchange", this.onFullscreen);
274
401
  this.instance?.dispose();
275
402
  this.audio?.dispose();
276
403
  this.gl?.dispose();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openbone/player",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Drop-in <openbone-player> web component and JS API for OpenBone animations",
5
5
  "keywords": [
6
6
  "openbone",
@@ -48,11 +48,11 @@
48
48
  },
49
49
  "dependencies": {
50
50
  "quickjs-emscripten": "^0.32.0",
51
- "@openbone/core": "0.3.0",
52
- "@openbone/render-canvas": "0.3.0",
53
- "@openbone/runtime": "0.3.0",
54
- "@openbone/render-webgl": "0.3.0",
55
- "@openbone/scripting": "0.3.0"
51
+ "@openbone/render-canvas": "0.4.1",
52
+ "@openbone/render-webgl": "0.4.1",
53
+ "@openbone/core": "0.4.1",
54
+ "@openbone/runtime": "0.4.1",
55
+ "@openbone/scripting": "0.4.1"
56
56
  },
57
57
  "peerDependencies": {
58
58
  "esbuild": ">=0.25.0"