@openbone/player 0.0.0-stage → 0.3.0

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.
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Build the self-contained WebView player bundle: one classic (non-module) script with the player, renderers,
3
+ * runtime and the QuickJS script sandbox (its .wasm inlined), so it runs from file:// in any WebView.
4
+ *
5
+ * pnpm build:player-bundle -> packages/player/dist/openbone-player.js
6
+ *
7
+ * The editor builds the same bundle through a Vite plugin (apps/editor/vite.config.ts), so exports never need
8
+ * a prebuilt file and work offline.
9
+ */
10
+ import fs from "node:fs";
11
+ import { createRequire } from "node:module";
12
+ import path from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ import { build } from "esbuild";
15
+ const here = path.dirname(fileURLToPath(import.meta.url));
16
+ // ".ts" when run from the sources (monorepo), ".js" when run from the compiled npm package (dist/bundle).
17
+ const ext = path.extname(fileURLToPath(import.meta.url)) || ".js";
18
+ const entry = (name) => path.join(here, `${name}${ext}`);
19
+ export const BUNDLE_ENTRY = entry("webview");
20
+ /** Folder whose changes invalidate the bundle (player, runtime, renderers, core, scripting sources). */
21
+ export const BUNDLE_SOURCES = path.resolve(here, "../../..");
22
+ export function quickJsWasmPath() {
23
+ const req = createRequire(import.meta.url);
24
+ const qjs = req.resolve("quickjs-emscripten");
25
+ const variant = createRequire(qjs).resolve("@jitl/quickjs-wasmfile-release-sync");
26
+ return path.join(path.dirname(variant), "emscripten-module.wasm");
27
+ }
28
+ /** Build the bundle and return its source. */
29
+ export async function buildPlayerBundle(opts = {}) {
30
+ const wasm = quickJsWasmPath();
31
+ const result = await build({
32
+ entryPoints: [BUNDLE_ENTRY],
33
+ bundle: true,
34
+ write: false,
35
+ format: "iife",
36
+ platform: "browser",
37
+ target: "es2020",
38
+ minify: opts.minify ?? true,
39
+ legalComments: "none",
40
+ // Emscripten builds a .wasm URL from import.meta.url even when given the bytes. Classic scripts have no
41
+ // import.meta, and the page URL can be blob:/about: (not a valid base), so use a fixed, never-fetched URL.
42
+ define: { "import.meta.url": JSON.stringify("file:///openbone-player.js") },
43
+ logLevel: "silent",
44
+ banner: { js: "/*! OpenBone player bundle (MIT). Includes quickjs-emscripten (MIT). https://github.com/UXCentury/open-bone */" },
45
+ plugins: [
46
+ {
47
+ name: "openbone-quickjs-wasm",
48
+ setup(b) {
49
+ b.onResolve({ filter: /^@openbone\/core$/ }, () => ({ path: entry("core-lite") }));
50
+ b.onResolve({ filter: /^openbone:quickjs-wasm$/ }, () => ({ path: wasm, namespace: "openbone-wasm" }));
51
+ b.onLoad({ filter: /.*/, namespace: "openbone-wasm" }, () => ({ contents: fs.readFileSync(wasm), loader: "binary" }));
52
+ },
53
+ },
54
+ ],
55
+ });
56
+ return result.outputFiles[0].text;
57
+ }
58
+ function packageVersion() {
59
+ try {
60
+ return JSON.parse(fs.readFileSync(path.resolve(here, "../../package.json"), "utf8")).version ?? "0.0.0";
61
+ }
62
+ catch {
63
+ return "0.0.0";
64
+ }
65
+ }
66
+ /**
67
+ * Build the web player library (`<openbone-player>` + `OpenBone.Player`) for websites: classic script or ES module,
68
+ * minified or readable, with or without the script sandbox. Returns the source.
69
+ */
70
+ export async function buildWebBundle(opts = {}) {
71
+ const format = opts.format ?? "iife";
72
+ const scripts = opts.scripts ?? true;
73
+ const minify = opts.minify ?? true;
74
+ const sandbox = scripts === "lazy" ? "sandbox-lazy" : scripts ? "sandbox-quickjs" : "sandbox-none";
75
+ const result = await build({
76
+ entryPoints: [entry("web")],
77
+ bundle: true,
78
+ write: false,
79
+ format,
80
+ ...(format === "iife" ? { globalName: "OpenBone" } : {}),
81
+ platform: "browser",
82
+ target: "es2020",
83
+ minify,
84
+ legalComments: "none",
85
+ define: {
86
+ // Emscripten (inlined sandbox) needs some URL; the lazy loader reads the real one in ES modules.
87
+ ...(scripts === "lazy" && format === "esm" ? {} : { "import.meta.url": JSON.stringify("file:///openbone-player.js") }),
88
+ __OPENBONE_VERSION__: JSON.stringify(packageVersion()),
89
+ },
90
+ logLevel: "silent",
91
+ banner: {
92
+ js: `/*! OpenBone web player ${packageVersion()} (MIT)${scripts === true ? ". Includes quickjs-emscripten (MIT)" : ""}. https://github.com/UXCentury/open-bone */`,
93
+ },
94
+ plugins: [
95
+ {
96
+ name: "openbone-web",
97
+ setup(b) {
98
+ b.onResolve({ filter: /^@openbone\/core$/ }, () => ({ path: entry("core-lite") }));
99
+ b.onResolve({ filter: /^openbone:script-sandbox$/ }, () => ({ path: entry(sandbox) }));
100
+ if (scripts !== true)
101
+ b.onResolve({ filter: /^@openbone\/scripting$/ }, () => ({ path: entry("scripting-stub") }));
102
+ b.onResolve({ filter: /^openbone:quickjs-wasm$/ }, () => ({ path: quickJsWasmPath(), namespace: "openbone-wasm" }));
103
+ b.onLoad({ filter: /.*/, namespace: "openbone-wasm" }, () => ({ contents: fs.readFileSync(quickJsWasmPath()), loader: "binary" }));
104
+ },
105
+ },
106
+ ],
107
+ });
108
+ return result.outputFiles[0].text;
109
+ }
110
+ /**
111
+ * `openbone-scripts.js`: the QuickJS sandbox add-on loaded by "lazy" web players (classic script, any page).
112
+ * Ship it with `quickjs.wasm` (quickJsWasmBytes) next to the player.
113
+ */
114
+ export async function buildScriptsAddon(opts = {}) {
115
+ const result = await build({
116
+ entryPoints: [entry("scripts-addon")],
117
+ bundle: true,
118
+ write: false,
119
+ format: "iife",
120
+ platform: "browser",
121
+ target: "es2020",
122
+ minify: opts.minify ?? true,
123
+ legalComments: "none",
124
+ define: { "import.meta.url": JSON.stringify("file:///openbone-scripts.js") },
125
+ logLevel: "silent",
126
+ banner: { js: `/*! OpenBone script sandbox ${packageVersion()} (MIT). Includes quickjs-emscripten (MIT). https://github.com/UXCentury/open-bone */` },
127
+ plugins: [
128
+ {
129
+ name: "openbone-scripts",
130
+ setup(b) {
131
+ b.onResolve({ filter: /^@openbone\/core$/ }, () => ({ path: entry("core-lite") }));
132
+ },
133
+ },
134
+ ],
135
+ });
136
+ return result.outputFiles[0].text;
137
+ }
138
+ /** The QuickJS .wasm the sandbox add-on fetches. */
139
+ export function quickJsWasmBytes() {
140
+ return new Uint8Array(fs.readFileSync(quickJsWasmPath()));
141
+ }
142
+ const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
143
+ if (isMain) {
144
+ const out = path.resolve(here, "../../dist/openbone-player.js");
145
+ const code = await buildPlayerBundle();
146
+ fs.mkdirSync(path.dirname(out), { recursive: true });
147
+ fs.writeFileSync(out, code);
148
+ console.log(`Wrote ${path.relative(process.cwd(), out)} (${(code.length / 1024).toFixed(0)} KB)`);
149
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * `@openbone/core` without the op registry and DocumentStore (they pull in zod, ~450 KB, and are only needed for
3
+ * editing). The bundle build aliases `@openbone/core` to this file; esbuild fails the build if a player module
4
+ * imports something not re-exported here.
5
+ */
6
+ export * from "@openbone/core/lite";
@@ -0,0 +1,6 @@
1
+ /**
2
+ * `@openbone/core` without the op registry and DocumentStore (they pull in zod, ~450 KB, and are only needed for
3
+ * editing). The bundle build aliases `@openbone/core` to this file; esbuild fails the build if a player module
4
+ * imports something not re-exported here.
5
+ */
6
+ export * from "@openbone/core/lite";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Script sandbox for web bundles that ship QuickJS as separate files: `openbone-scripts.js` (the sandbox glue) and
3
+ * `quickjs.wasm`, next to the player. They are loaded only when an animation actually has scripts, so pages
4
+ * without scripts never download them. Set `window.OPENBONE_SCRIPTS_BASE` to load them from another folder.
5
+ */
6
+ import type { ScriptHost } from "@openbone/runtime";
7
+ export declare function sandboxFactory(): Promise<ScriptHost | null>;
@@ -0,0 +1,54 @@
1
+ // Where the player was loaded from: classic scripts know their own <script> element; modules know import.meta.url.
2
+ const playerUrl = (() => {
3
+ try {
4
+ const s = typeof document !== "undefined" ? document.currentScript : null;
5
+ if (s?.src)
6
+ return s.src;
7
+ }
8
+ catch {
9
+ /* ignore */
10
+ }
11
+ try {
12
+ const u = import.meta.url;
13
+ if (u && !u.startsWith("file:///openbone-player"))
14
+ return u;
15
+ }
16
+ catch {
17
+ /* ignore */
18
+ }
19
+ return typeof location !== "undefined" ? location.href : "";
20
+ })();
21
+ /** Folder holding openbone-scripts.js and quickjs.wasm (default: the player's folder). */
22
+ function folder() {
23
+ const g = globalThis;
24
+ const b = g.OPENBONE_SCRIPTS_BASE ?? new URL(".", playerUrl).href;
25
+ return b.endsWith("/") ? b : `${b}/`;
26
+ }
27
+ let loading = null;
28
+ function loadAddon() {
29
+ const g = globalThis;
30
+ if (g.OpenBoneScripts)
31
+ return Promise.resolve(g.OpenBoneScripts);
32
+ loading ??= new Promise((resolve, reject) => {
33
+ const s = document.createElement("script");
34
+ s.src = `${folder()}openbone-scripts.js`;
35
+ s.async = true;
36
+ s.onload = () => (g.OpenBoneScripts ? resolve(g.OpenBoneScripts) : reject(new Error("openbone-scripts.js did not register")));
37
+ s.onerror = () => reject(new Error(`could not load ${s.src}`));
38
+ document.head.append(s);
39
+ }).catch((e) => {
40
+ loading = null;
41
+ throw e;
42
+ });
43
+ return loading;
44
+ }
45
+ export async function sandboxFactory() {
46
+ try {
47
+ const addon = await loadAddon();
48
+ return await addon.createHost(`${folder()}quickjs.wasm`);
49
+ }
50
+ catch (e) {
51
+ console.warn("OpenBone: could not load the script sandbox (openbone-scripts.js + quickjs.wasm next to the player); scripts will not run.", e);
52
+ return null;
53
+ }
54
+ }
@@ -0,0 +1,3 @@
1
+ /** Script sandbox stub for web bundles built without QuickJS (smaller): scripts are skipped. */
2
+ import type { ScriptHost } from "@openbone/runtime";
3
+ export declare function sandboxFactory(): Promise<ScriptHost | null>;
@@ -0,0 +1,3 @@
1
+ export async function sandboxFactory() {
2
+ return null;
3
+ }
@@ -0,0 +1,3 @@
1
+ /** Script sandbox for web bundles that include QuickJS: the .wasm is inlined, so nothing is fetched. */
2
+ import type { ScriptHost } from "@openbone/runtime";
3
+ export declare function sandboxFactory(): Promise<ScriptHost | null>;
@@ -0,0 +1,7 @@
1
+ import { createQuickJsHost } from "@openbone/scripting";
2
+ import { RELEASE_SYNC, newQuickJSWASMModuleFromVariant, newVariant } from "quickjs-emscripten";
3
+ import wasmBinary from "openbone:quickjs-wasm";
4
+ export async function sandboxFactory() {
5
+ const module = await newQuickJSWASMModuleFromVariant(newVariant(RELEASE_SYNC, { wasmBinary: wasmBinary.slice().buffer }));
6
+ return createQuickJsHost({ module });
7
+ }
@@ -0,0 +1,2 @@
1
+ /** Stands in for @openbone/scripting in web bundles built without the sandbox (never called: see sandbox-none.ts). */
2
+ export declare function createQuickJsHost(): Promise<never>;
@@ -0,0 +1,4 @@
1
+ /** Stands in for @openbone/scripting in web bundles built without the sandbox (never called: see sandbox-none.ts). */
2
+ export async function createQuickJsHost() {
3
+ throw new Error("OpenBone: this player build has no script sandbox");
4
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `openbone-scripts.js`: the QuickJS script sandbox as an add-on for the web player. The player loads it (and
3
+ * `quickjs.wasm`) only when an animation has scripts; see sandbox-lazy.ts. Registers `globalThis.OpenBoneScripts`.
4
+ */
5
+ import { createQuickJsHost } from "@openbone/scripting";
6
+ import { RELEASE_SYNC, newQuickJSWASMModuleFromVariant, newVariant } from "quickjs-emscripten";
7
+ async function createHost(wasmUrl) {
8
+ const res = await fetch(wasmUrl);
9
+ if (!res.ok)
10
+ throw new Error(`${wasmUrl}: HTTP ${res.status}`);
11
+ const wasmBinary = await res.arrayBuffer();
12
+ const module = await newQuickJSWASMModuleFromVariant(newVariant(RELEASE_SYNC, { wasmBinary }));
13
+ return createQuickJsHost({ module });
14
+ }
15
+ globalThis.OpenBoneScripts = { createHost };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Entry of the web player library (`openbone-player.js` / `.mjs`) shipped by the editor's Web export.
3
+ *
4
+ * Including it defines `<openbone-player>` (unless something already did) and exposes the API:
5
+ * - classic script: `window.OpenBone` = { Player, OpenBonePlayerElement, definePlayerElement, parseDocument, version }
6
+ * - ES module: the same names as exports.
7
+ *
8
+ * Built in two flavours: with the QuickJS script sandbox inlined (scripts run), or without it (smaller; documents
9
+ * with scripts still play, their scripts are skipped with a console warning). See build.ts.
10
+ */
11
+ import { parseDocument } from "@openbone/core";
12
+ import { OpenBonePlayerElement, definePlayerElement } from "../element.js";
13
+ import { Player } from "../player.js";
14
+ export declare const version: string;
15
+ export { OpenBonePlayerElement, Player, definePlayerElement, parseDocument };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Entry of the web player library (`openbone-player.js` / `.mjs`) shipped by the editor's Web export.
3
+ *
4
+ * Including it defines `<openbone-player>` (unless something already did) and exposes the API:
5
+ * - classic script: `window.OpenBone` = { Player, OpenBonePlayerElement, definePlayerElement, parseDocument, version }
6
+ * - ES module: the same names as exports.
7
+ *
8
+ * Built in two flavours: with the QuickJS script sandbox inlined (scripts run), or without it (smaller; documents
9
+ * with scripts still play, their scripts are skipped with a console warning). See build.ts.
10
+ */
11
+ import { parseDocument } from "@openbone/core";
12
+ import { OpenBonePlayerElement, definePlayerElement } from "../element.js";
13
+ import { Player, setScriptHostFactory } from "../player.js";
14
+ import { sandboxFactory } from "openbone:script-sandbox";
15
+ export const version = __OPENBONE_VERSION__;
16
+ setScriptHostFactory(sandboxFactory);
17
+ if (typeof customElements !== "undefined" && !customElements.get("openbone-player"))
18
+ definePlayerElement();
19
+ export { OpenBonePlayerElement, Player, definePlayerElement, parseDocument };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Entry of the self-contained player bundle (`openbone-player.js`) used by the WebView packages.
3
+ *
4
+ * The page provides the document in one of these ways (first found wins):
5
+ * - `<script type="application/octet-stream" id="openbone-data">BASE64</script>` (.obone or .obonb bytes)
6
+ * - `?src=url` in the page URL (fetched; needs http(s), not file://)
7
+ * - `window.OPENBONE_SRC` (a URL or a parsed document)
8
+ * Options come from `data-*` attributes on `<body>`: data-state-machine, data-animation, data-skin, data-fit,
9
+ * data-background ("none" = transparent), data-renderer.
10
+ *
11
+ * It exposes `window.OpenBone` (see bridge.ts for the message format).
12
+ */
13
+ import { type OpenBoneDocument } from "@openbone/core";
14
+ declare global {
15
+ interface Window {
16
+ OPENBONE_SRC?: string | OpenBoneDocument;
17
+ OpenBone?: unknown;
18
+ }
19
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Entry of the self-contained player bundle (`openbone-player.js`) used by the WebView packages.
3
+ *
4
+ * The page provides the document in one of these ways (first found wins):
5
+ * - `<script type="application/octet-stream" id="openbone-data">BASE64</script>` (.obone or .obonb bytes)
6
+ * - `?src=url` in the page URL (fetched; needs http(s), not file://)
7
+ * - `window.OPENBONE_SRC` (a URL or a parsed document)
8
+ * Options come from `data-*` attributes on `<body>`: data-state-machine, data-animation, data-skin, data-fit,
9
+ * data-background ("none" = transparent), data-renderer.
10
+ *
11
+ * It exposes `window.OpenBone` (see bridge.ts for the message format).
12
+ */
13
+ import { parseDocument } from "@openbone/core";
14
+ import { createQuickJsHost } from "@openbone/scripting";
15
+ import { RELEASE_SYNC, newQuickJSWASMModuleFromVariant, newVariant } from "quickjs-emscripten";
16
+ // Resolved by the bundle build to the QuickJS .wasm bytes (esbuild `binary` loader).
17
+ import wasmBinary from "openbone:quickjs-wasm";
18
+ import { Player } from "../player.js";
19
+ import { applyCommand, parseCommand, postToHost } from "../bridge.js";
20
+ function base64ToBytes(b64) {
21
+ const bin = atob(b64.replace(/\s+/g, ""));
22
+ const out = new Uint8Array(bin.length);
23
+ for (let i = 0; i < bin.length; i++)
24
+ out[i] = bin.charCodeAt(i);
25
+ return out;
26
+ }
27
+ function findSource() {
28
+ const el = document.getElementById("openbone-data");
29
+ if (el?.textContent?.trim())
30
+ return parseDocument(base64ToBytes(el.textContent));
31
+ const q = new URLSearchParams(location.search).get("src");
32
+ if (q)
33
+ return q;
34
+ return window.OPENBONE_SRC ?? null;
35
+ }
36
+ async function scriptHostFor() {
37
+ const module = await newQuickJSWASMModuleFromVariant(newVariant(RELEASE_SYNC, { wasmBinary: wasmBinary.slice().buffer }));
38
+ return createQuickJsHost({ module });
39
+ }
40
+ function start() {
41
+ const body = document.body;
42
+ const opt = (k) => body.dataset[k] || undefined;
43
+ let canvas = document.querySelector("canvas#openbone");
44
+ if (!canvas) {
45
+ canvas = document.createElement("canvas");
46
+ canvas.id = "openbone";
47
+ body.append(canvas);
48
+ }
49
+ let player = null;
50
+ const queue = [];
51
+ const inputs = () => {
52
+ const sm = player?.stateMachine;
53
+ if (!sm)
54
+ return [];
55
+ return sm.data.inputs.map((i) => ({ name: i.name, type: i.type, value: i.type === "trigger" ? null : (sm.getInput(i.name) ?? null) }));
56
+ };
57
+ const adapter = {
58
+ setInput: (n, v) => player?.setInput(n, v),
59
+ fire: (n) => player?.fire(n),
60
+ play: () => player?.play(),
61
+ pause: () => player?.pause(),
62
+ playAnimation: (n, loop) => player?.playAnimation(n, loop),
63
+ setSkin: (n) => player?.setSkin(n),
64
+ useStateMachine: (n) => {
65
+ if (!player)
66
+ return;
67
+ player.instance.useStateMachine(n);
68
+ watchInputs();
69
+ },
70
+ inputs,
71
+ };
72
+ const watchInputs = () => player?.stateMachine?.on("inputChange", () => postToHost({ type: "inputs", inputs: inputs() }));
73
+ /** Run a command now, or once the document has loaded. Errors go to the host as `error` messages. */
74
+ const run = (cmd) => {
75
+ try {
76
+ const c = parseCommand(cmd);
77
+ if (!player?.instance) {
78
+ queue.push(c);
79
+ return;
80
+ }
81
+ const reply = applyCommand(adapter, c);
82
+ if (reply)
83
+ postToHost(reply);
84
+ }
85
+ catch (e) {
86
+ postToHost({ type: "error", message: e.message });
87
+ }
88
+ };
89
+ window.OpenBone = {
90
+ /** Host entry point: a JSON string or object command. */
91
+ receive: run,
92
+ setInput: (name, value) => run({ type: "setInput", name, value }),
93
+ fire: (name) => run({ type: "fire", name }),
94
+ play: (animation, loop) => run({ type: "play", animation, loop }),
95
+ pause: () => run({ type: "pause" }),
96
+ setSkin: (name) => run({ type: "setSkin", name }),
97
+ useStateMachine: (name) => run({ type: "useStateMachine", name }),
98
+ getInputs: () => inputs(),
99
+ get player() {
100
+ return player;
101
+ },
102
+ };
103
+ // iframe hosts can send commands with postMessage({ openbone: command }).
104
+ window.addEventListener("message", (e) => {
105
+ const d = e.data;
106
+ if (d && typeof d === "object" && "openbone" in d)
107
+ run(d.openbone);
108
+ });
109
+ let src;
110
+ try {
111
+ src = findSource();
112
+ }
113
+ catch (e) {
114
+ postToHost({ type: "error", message: `Could not read the embedded document: ${e.message}` });
115
+ return;
116
+ }
117
+ if (!src) {
118
+ postToHost({ type: "error", message: "No document: embed one in #openbone-data, or pass ?src=" });
119
+ return;
120
+ }
121
+ const bg = opt("background");
122
+ const hasScripts = typeof src === "object" ? src.scripts.length > 0 : true;
123
+ (hasScripts ? scriptHostFor() : Promise.resolve(undefined)).then((host) => {
124
+ player = new Player({
125
+ canvas: canvas,
126
+ src: src,
127
+ stateMachine: opt("stateMachine"),
128
+ animation: opt("animation"),
129
+ skin: opt("skin"),
130
+ fit: opt("fit") ?? "contain",
131
+ renderer: opt("renderer") ?? "webgl",
132
+ ...(bg !== undefined ? { background: bg === "none" ? null : bg } : {}),
133
+ scripts: host ?? "none",
134
+ onEvent: (e) => postToHost({ type: "event", name: e.name, int: e.int, float: e.float, string: e.string, time: e.time }),
135
+ onStateChange: (e) => postToHost({ type: "stateChange", layer: e.layer, from: e.from, to: e.to }),
136
+ });
137
+ player.ready.then(() => {
138
+ const p = player;
139
+ watchInputs();
140
+ postToHost({
141
+ type: "ready",
142
+ animations: p.doc.animations.map((a) => a.name),
143
+ stateMachines: p.doc.stateMachines.map((s) => s.name),
144
+ inputs: inputs(),
145
+ skins: p.skins,
146
+ width: p.doc.width,
147
+ height: p.doc.height,
148
+ });
149
+ for (const c of queue.splice(0))
150
+ run(c);
151
+ }, (e) => postToHost({ type: "error", message: e.message }));
152
+ }, (e) => postToHost({ type: "error", message: `Script engine failed to start: ${e.message}` }));
153
+ }
154
+ if (document.readyState === "loading")
155
+ document.addEventListener("DOMContentLoaded", start);
156
+ else
157
+ start();
@@ -0,0 +1,31 @@
1
+ import { Player } from "./player.js";
2
+ /**
3
+ * <openbone-player src="hero.obone" state-machine="ui" animation="idle" skin="red" fit="contain" renderer="webgl">
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).
6
+ * Audio plays after the first click/key press; `muted` attribute starts muted, `audio="off"` disables it.
7
+ * Changing the `skin` attribute switches the outfit without reloading.
8
+ */
9
+ export declare class OpenBonePlayerElement extends HTMLElement {
10
+ /** `skin` switches skins in place; any other of these reloads the player with the new settings. */
11
+ static observedAttributes: string[];
12
+ player: Player | null;
13
+ private canvas;
14
+ constructor();
15
+ connectedCallback(): void;
16
+ disconnectedCallback(): void;
17
+ attributeChangedCallback(n: string, old: string | null, val: string | null): void;
18
+ /** The attributes the current player was built with (everything observed except `skin`). */
19
+ private loadedWith;
20
+ private settings;
21
+ private init;
22
+ /** `background` attribute: a colour, "transparent"/"none" for no background, absent for the file's own. */
23
+ private background;
24
+ setInput(name: string, value: boolean | number | string): void;
25
+ setText(slot: string, text: string | null): void;
26
+ fire(name: string): void;
27
+ setSkin(name: string | null): void;
28
+ play(): void;
29
+ pause(): void;
30
+ }
31
+ export declare function definePlayerElement(tag?: string): void;
@@ -0,0 +1,102 @@
1
+ import { Player } from "./player.js";
2
+ /**
3
+ * <openbone-player src="hero.obone" state-machine="ui" animation="idle" skin="red" fit="contain" renderer="webgl">
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).
6
+ * Audio plays after the first click/key press; `muted` attribute starts muted, `audio="off"` disables it.
7
+ * Changing the `skin` attribute switches the outfit without reloading.
8
+ */
9
+ export class OpenBonePlayerElement extends HTMLElement {
10
+ /** `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"];
12
+ player = null;
13
+ canvas;
14
+ constructor() {
15
+ super();
16
+ const root = this.attachShadow({ mode: "open" });
17
+ root.innerHTML = `<style>:host{display:inline-block;width:400px;height:300px;position:relative}canvas{width:100%;height:100%;display:block;touch-action:none}</style>`;
18
+ this.canvas = document.createElement("canvas");
19
+ root.appendChild(this.canvas);
20
+ }
21
+ connectedCallback() {
22
+ // An upgraded element may already have loaded from attributeChangedCallback.
23
+ if (!this.player)
24
+ this.init();
25
+ }
26
+ disconnectedCallback() {
27
+ this.player?.dispose();
28
+ this.player = null;
29
+ }
30
+ attributeChangedCallback(n, old, val) {
31
+ if (old === val || !this.isConnected)
32
+ return;
33
+ if (n === "skin")
34
+ this.player?.setSkin(val);
35
+ // Includes `src` set for the first time after the element was added to the page. Upgrading an element reports each
36
+ // attribute it already has; those match what the player was built with, so they don't reload it.
37
+ else if (this.settings() !== this.loadedWith)
38
+ this.init();
39
+ }
40
+ /** The attributes the current player was built with (everything observed except `skin`). */
41
+ loadedWith;
42
+ settings() {
43
+ return JSON.stringify(OpenBonePlayerElement.observedAttributes.filter((a) => a !== "skin").map((a) => this.getAttribute(a)));
44
+ }
45
+ init() {
46
+ const src = this.getAttribute("src");
47
+ this.player?.dispose();
48
+ this.player = null;
49
+ this.loadedWith = this.settings();
50
+ if (!src)
51
+ return;
52
+ this.player = new Player({
53
+ canvas: this.canvas,
54
+ src,
55
+ stateMachine: this.getAttribute("state-machine") ?? undefined,
56
+ animation: this.getAttribute("animation") ?? undefined,
57
+ skin: this.getAttribute("skin") ?? undefined,
58
+ fit: this.getAttribute("fit") ?? "contain",
59
+ renderer: this.getAttribute("renderer") ?? "webgl",
60
+ autoplay: this.getAttribute("autoplay") !== "false",
61
+ background: this.background(),
62
+ scripts: this.getAttribute("scripts") === "none" ? "none" : "quickjs",
63
+ audio: this.getAttribute("audio") === "off" ? false : this.hasAttribute("muted") ? "muted" : true,
64
+ onEvent: (e) => this.dispatchEvent(new CustomEvent("openbone-event", { detail: e, bubbles: true, composed: true })),
65
+ onStateChange: (e) => this.dispatchEvent(new CustomEvent("openbone-state", { detail: e, bubbles: true, composed: true })),
66
+ onLoad: () => this.dispatchEvent(new CustomEvent("openbone-load", { bubbles: true, composed: true })),
67
+ });
68
+ this.player.ready.catch((e) => console.error(e));
69
+ }
70
+ /** `background` attribute: a colour, "transparent"/"none" for no background, absent for the file's own. */
71
+ background() {
72
+ if (!this.hasAttribute("background"))
73
+ return undefined;
74
+ const v = this.getAttribute("background")?.trim() ?? "";
75
+ return v === "" || v === "transparent" || v === "none" ? null : v;
76
+ }
77
+ setInput(name, value) {
78
+ this.player?.setInput(name, value);
79
+ }
80
+ setText(slot, text) {
81
+ this.player?.setText(slot, text);
82
+ }
83
+ fire(name) {
84
+ this.player?.fire(name);
85
+ }
86
+ setSkin(name) {
87
+ if (name)
88
+ this.setAttribute("skin", name);
89
+ else
90
+ this.removeAttribute("skin");
91
+ }
92
+ play() {
93
+ this.player?.play();
94
+ }
95
+ pause() {
96
+ this.player?.pause();
97
+ }
98
+ }
99
+ export function definePlayerElement(tag = "openbone-player") {
100
+ if (!customElements.get(tag))
101
+ customElements.define(tag, OpenBonePlayerElement);
102
+ }
@@ -0,0 +1,3 @@
1
+ export { Player, type PlayerOptions, setScriptHostFactory } from "./player.js";
2
+ export { OpenBonePlayerElement, definePlayerElement } from "./element.js";
3
+ export { WebAudioBackend, type WebAudioOptions } from "./audio.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { Player, setScriptHostFactory } from "./player.js";
2
+ export { OpenBonePlayerElement, definePlayerElement } from "./element.js";
3
+ export { WebAudioBackend } from "./audio.js";