@playcanvas/web-components 0.15.0 → 0.17.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.
Files changed (108) hide show
  1. package/dist/app.d.cts +14 -13
  2. package/dist/app.d.ts +14 -13
  3. package/dist/async-element.d.cts +13 -13
  4. package/dist/async-element.d.ts +13 -13
  5. package/dist/components/anim-clip.d.cts +127 -0
  6. package/dist/components/anim-clip.d.ts +127 -0
  7. package/dist/components/anim-component.d.cts +235 -0
  8. package/dist/components/anim-component.d.ts +235 -0
  9. package/dist/components/{listener-component.d.cts → audio-listener-component.d.cts} +7 -5
  10. package/dist/components/{listener-component.d.ts → audio-listener-component.d.ts} +7 -5
  11. package/dist/components/button-component.d.cts +5 -1
  12. package/dist/components/button-component.d.ts +5 -1
  13. package/dist/components/camera-component.d.cts +2 -0
  14. package/dist/components/camera-component.d.ts +2 -0
  15. package/dist/components/collision-component.d.cts +5 -1
  16. package/dist/components/collision-component.d.ts +5 -1
  17. package/dist/components/component.d.cts +3 -2
  18. package/dist/components/component.d.ts +3 -2
  19. package/dist/components/element-component.d.cts +7 -0
  20. package/dist/components/element-component.d.ts +7 -0
  21. package/dist/components/gsplat-component.d.cts +2 -0
  22. package/dist/components/gsplat-component.d.ts +2 -0
  23. package/dist/components/joint-component.d.cts +2 -0
  24. package/dist/components/joint-component.d.ts +2 -0
  25. package/dist/components/{layoutchild-component.d.cts → layout-child-component.d.cts} +3 -1
  26. package/dist/components/{layoutchild-component.d.ts → layout-child-component.d.ts} +3 -1
  27. package/dist/components/{layoutgroup-component.d.cts → layout-group-component.d.cts} +3 -1
  28. package/dist/components/{layoutgroup-component.d.ts → layout-group-component.d.ts} +3 -1
  29. package/dist/components/light-component.d.cts +2 -0
  30. package/dist/components/light-component.d.ts +2 -0
  31. package/dist/components/{particlesystem-component.d.cts → particle-system-component.d.cts} +3 -1
  32. package/dist/components/{particlesystem-component.d.ts → particle-system-component.d.ts} +3 -1
  33. package/dist/components/render-component.d.cts +2 -0
  34. package/dist/components/render-component.d.ts +2 -0
  35. package/dist/components/{rigidbody-component.d.cts → rigid-body-component.d.cts} +3 -1
  36. package/dist/components/{rigidbody-component.d.ts → rigid-body-component.d.ts} +3 -1
  37. package/dist/components/screen-component.d.cts +2 -0
  38. package/dist/components/screen-component.d.ts +2 -0
  39. package/dist/components/script-component.d.cts +23 -12
  40. package/dist/components/script-component.d.ts +23 -12
  41. package/dist/components/{script.d.cts → script-instance.d.cts} +7 -7
  42. package/dist/components/{script.d.ts → script-instance.d.ts} +7 -7
  43. package/dist/components/{scrollview-component.d.cts → scroll-view-component.d.cts} +3 -1
  44. package/dist/components/{scrollview-component.d.ts → scroll-view-component.d.ts} +3 -1
  45. package/dist/components/scrollbar-component.d.cts +2 -0
  46. package/dist/components/scrollbar-component.d.ts +2 -0
  47. package/dist/components/sound-component.d.cts +3 -1
  48. package/dist/components/sound-component.d.ts +3 -1
  49. package/dist/components/sound-slot.d.cts +2 -2
  50. package/dist/components/sound-slot.d.ts +2 -2
  51. package/dist/custom-elements.json +3154 -2005
  52. package/dist/entity-base.d.cts +6 -5
  53. package/dist/entity-base.d.ts +6 -5
  54. package/dist/entity-owner.d.cts +118 -0
  55. package/dist/entity-owner.d.ts +118 -0
  56. package/dist/entity.d.cts +8 -101
  57. package/dist/entity.d.ts +8 -101
  58. package/dist/index.d.cts +26 -21
  59. package/dist/index.d.ts +26 -21
  60. package/dist/model.d.cts +67 -24
  61. package/dist/model.d.ts +67 -24
  62. package/dist/pwc.cjs +1766 -619
  63. package/dist/pwc.cjs.map +1 -1
  64. package/dist/pwc.js +1766 -619
  65. package/dist/pwc.js.map +1 -1
  66. package/dist/pwc.min.js +1 -1
  67. package/dist/pwc.min.js.map +1 -1
  68. package/dist/pwc.min.mjs +1 -1
  69. package/dist/pwc.min.mjs.map +1 -1
  70. package/dist/pwc.mjs +1762 -618
  71. package/dist/pwc.mjs.map +1 -1
  72. package/dist/vscode.html-custom-data.json +203 -89
  73. package/dist/{module.d.cts → wasm.d.cts} +6 -6
  74. package/dist/{module.d.ts → wasm.d.ts} +6 -6
  75. package/dist/web-types.json +556 -273
  76. package/package.json +7 -7
  77. package/src/app.ts +45 -35
  78. package/src/async-element.ts +14 -14
  79. package/src/components/anim-clip.ts +395 -0
  80. package/src/components/anim-component.ts +719 -0
  81. package/src/components/{listener-component.ts → audio-listener-component.ts} +8 -6
  82. package/src/components/button-component.ts +5 -1
  83. package/src/components/camera-component.ts +2 -0
  84. package/src/components/collision-component.ts +5 -1
  85. package/src/components/component.ts +4 -3
  86. package/src/components/element-component.ts +7 -0
  87. package/src/components/gsplat-component.ts +2 -0
  88. package/src/components/joint-component.ts +2 -0
  89. package/src/components/{layoutchild-component.ts → layout-child-component.ts} +4 -2
  90. package/src/components/{layoutgroup-component.ts → layout-group-component.ts} +4 -2
  91. package/src/components/light-component.ts +2 -0
  92. package/src/components/{particlesystem-component.ts → particle-system-component.ts} +4 -2
  93. package/src/components/render-component.ts +2 -0
  94. package/src/components/{rigidbody-component.ts → rigid-body-component.ts} +4 -2
  95. package/src/components/screen-component.ts +2 -0
  96. package/src/components/script-component.ts +63 -42
  97. package/src/components/{script.ts → script-instance.ts} +14 -14
  98. package/src/components/{scrollview-component.ts → scroll-view-component.ts} +4 -2
  99. package/src/components/scrollbar-component.ts +2 -0
  100. package/src/components/sound-component.ts +4 -2
  101. package/src/components/sound-slot.ts +4 -4
  102. package/src/entity-base.ts +6 -5
  103. package/src/entity-owner.ts +298 -0
  104. package/src/entity.ts +15 -270
  105. package/src/index.ts +32 -24
  106. package/src/model.ts +159 -79
  107. package/src/node.ts +9 -5
  108. package/src/{module.ts → wasm.ts} +8 -8
@@ -0,0 +1,719 @@
1
+ import type { AnimComponent, Asset, ContainerResource, Entity } from 'playcanvas';
2
+ import { ANIM_CONTROL_STATES, AnimTrack } from 'playcanvas';
3
+
4
+ import { AssetElement } from '../asset';
5
+ import type { EntityBaseElement } from '../entity-base';
6
+ import { ModelElement } from '../model';
7
+ import { parseBool, parseNumber } from '../parse';
8
+
9
+ import type { AnimClipElement } from './anim-clip';
10
+ import { ComponentElement } from './component';
11
+
12
+ /**
13
+ * A container resource with the `animations` sub-assets the engine documents but does not type:
14
+ * one `Asset` of type `animation` per glTF animation, each holding an `AnimTrack` resource.
15
+ */
16
+ type ContainerWithAnimations = ContainerResource & { animations: Asset[] };
17
+
18
+ /**
19
+ * A playback snapshot captured before a clip-set rebuild and restored afterwards, so a rebuild
20
+ * whose active clip survives it is seamless. Both playing flags are captured: the component's
21
+ * gates the system tick, the layer controller's gates the layer, and they legitimately diverge —
22
+ * {@link AnimComponentElement.pause} clears only the component's.
23
+ */
24
+ type PlaybackState = {
25
+ state: string;
26
+ time: number;
27
+ playing: boolean;
28
+ layerPlaying: boolean;
29
+ };
30
+
31
+ /**
32
+ * The AnimComponentElement interface provides properties and methods for manipulating
33
+ * {@link https://developer.playcanvas.com/user-manual/web-components/tags/pc-anim/ | `<pc-anim>`} elements.
34
+ * The AnimComponentElement interface also inherits the properties and methods of the
35
+ * {@link HTMLElement} interface.
36
+ *
37
+ * The element drives animation clips over the host entity's hierarchy. Clips come from
38
+ * `<pc-anim-clip>` children — or, when the element is a direct child of a `<pc-model>` and
39
+ * declares no clips, every animation of that model's container asset is assigned, named by track
40
+ * name, in container order. The first clip plays automatically (opt out with `activate="false"`);
41
+ * switch clips declaratively through the `clip` attribute, or imperatively through {@link play}
42
+ * and {@link transition}. Tracks bind to scene nodes by name, so any hierarchy whose node names
43
+ * match a clip's curves can be animated — a model's skeleton is simply the common case.
44
+ *
45
+ * The engine reports no clip completion: a non-looping clip holds its last pose silently. Poll
46
+ * the underlying {@link AnimComponent} (via {@link component}) for playback state beyond what
47
+ * this element exposes.
48
+ *
49
+ * Engine component: {@link AnimComponent} (`anim`).
50
+ *
51
+ * @category Components
52
+ */
53
+ class AnimComponentElement extends ComponentElement {
54
+ /**
55
+ * Whether playback starts automatically once a clip is assigned.
56
+ */
57
+ private _activate = true;
58
+
59
+ /**
60
+ * The clip elements whose states are currently assigned, by clip name. The single writer of
61
+ * a state: a later clip child re-using an adopted name is rejected as a duplicate.
62
+ */
63
+ private _assignedClips = new Map<string, AnimClipElement>();
64
+
65
+ /**
66
+ * Whether the current clip set was auto-assigned from the enclosing model rather than
67
+ * declared by clip children.
68
+ */
69
+ private _autoAssigned = false;
70
+
71
+ /**
72
+ * The name of the active clip.
73
+ */
74
+ private _clip = '';
75
+
76
+ /**
77
+ * The binding root this element last assigned through {@link _applyRootBone}, distinguishing
78
+ * its own writes from a `rootBone` assigned through the engine API — which is left alone.
79
+ */
80
+ private _managedRootBone: Entity | null = null;
81
+
82
+ /**
83
+ * The element the model-readiness listener is attached to, held so disconnection can detach
84
+ * it after `closestEntity` no longer resolves.
85
+ */
86
+ private _modelListenerTarget: EntityBaseElement | null = null;
87
+
88
+ /**
89
+ * Incremented whenever the clip source changes, and captured by an auto-assign pass on
90
+ * entry — a pass resuming from an await abandons itself if the value has moved on, so a
91
+ * superseded pass cannot assign clips alongside declared children or a newer pass.
92
+ */
93
+ private _sourceGeneration = 0;
94
+
95
+ /**
96
+ * The playback speed multiplier applied across all clips.
97
+ */
98
+ private _speed = 1;
99
+
100
+ /**
101
+ * The cross-fade duration of declarative clip switches, in seconds.
102
+ */
103
+ private _transitionTime = 0;
104
+
105
+ /**
106
+ * The unknown clip name already warned about, so a repeated selection of the same missing
107
+ * name complains once.
108
+ */
109
+ private _warnedClip: string | null = null;
110
+
111
+ /**
112
+ * Rebinds when a model that is not this component's host announces readiness — a sibling or
113
+ * deeper model whose content changed under the assigned clips. The engine resolves each
114
+ * curve once, at the first tick after assignment, and never retries — and its mesh-instance
115
+ * broadcast fires before an instantiated hierarchy is parented, so a model that loads after
116
+ * the clips were assigned would otherwise stay silently unbound. The host model's own cycles
117
+ * are excluded: those re-enter through {@link initComponent}, which refreshes the whole clip
118
+ * set against the new container.
119
+ */
120
+ private _onModelReady = (event: Event) => {
121
+ if (!(event.target instanceof ModelElement) || !this.component) {
122
+ return;
123
+ }
124
+ // The host model's own readiness cycle already re-initialized this component through
125
+ // ComponentElement's host-ready listener, which is attached first and so has run by now.
126
+ // Acting here too would resolve every track twice and capture the playhead-restore
127
+ // snapshot mid-rebuild.
128
+ if (event.target === this._modelListenerTarget) {
129
+ return;
130
+ }
131
+ // A model cycle can replace the skeleton source's host entity (a rebuild under a
132
+ // retargeting pc-node), so the binding root is re-asserted before the rebind.
133
+ this._applyRootBone();
134
+ this.component.rebind();
135
+ };
136
+
137
+ /**
138
+ * The model whose host entity scopes this component's curve binding: the parent `pc-model`,
139
+ * or the sole `pc-model` among the parent's direct children (the arrangement where clips
140
+ * live in a library asset beside the skeleton). `null` when there is no such model, or more
141
+ * than one — an ambiguous skeleton is left to the engine's name-based resolution.
142
+ */
143
+ private _skeletonSource(): ModelElement | null {
144
+ const parent = this.parentElement;
145
+ if (parent instanceof ModelElement) {
146
+ return parent;
147
+ }
148
+ const models = parent ? parent.querySelectorAll(':scope > pc-model') : null;
149
+ return models?.length === 1 && models[0] instanceof ModelElement ? models[0] : null;
150
+ }
151
+
152
+ /**
153
+ * Keeps the component's binding root pointing at the skeleton source's host entity. The host
154
+ * wraps the instantiated content, so left at its default — the component's own entity — the
155
+ * engine binder mis-resolves curves that target the asset's root node: its fallback treats
156
+ * the graph as the asset root once the root is no longer a direct child.
157
+ *
158
+ * Authoritative in both directions for values this element assigned: a source appearing pins
159
+ * its host, and a source dissolving (the model gone, or a second model making the skeleton
160
+ * ambiguous) clears the pin rather than leaving it on a stale host. A root assigned through
161
+ * the engine API is never overwritten — the user's choice outranks the managed default.
162
+ * Writes are skipped while unchanged, because the engine setter itself triggers a rebind.
163
+ */
164
+ private _applyRootBone() {
165
+ const component = this.component;
166
+
167
+ // A non-null root this element did not assign came through the engine API. A fresh
168
+ // component starts at null, which is always reclaimable.
169
+ if (component.rootBone !== null && component.rootBone !== this._managedRootBone) {
170
+ return;
171
+ }
172
+
173
+ const host = this._skeletonSource()?.entity ?? null;
174
+ if (component.rootBone !== host) {
175
+ // The engine setter accepts null - restoring the component's own entity as the
176
+ // binding graph - but its declared type does not
177
+ component.rootBone = host as Entity;
178
+ }
179
+ this._managedRootBone = host;
180
+ }
181
+
182
+ /** @ignore */
183
+ constructor() {
184
+ super('anim');
185
+ }
186
+
187
+ protected getInitialComponentData() {
188
+ // The engine assigns creation data in key order and `activate` gates playback, so it
189
+ // must precede any future key that builds layers (e.g. a state graph)
190
+ return {
191
+ activate: this._activate,
192
+ speed: this._speed
193
+ };
194
+ }
195
+
196
+ protected initComponent() {
197
+ if (!this.component) {
198
+ return;
199
+ }
200
+
201
+ // A host readiness cycle can re-run this. An identical re-add is deduped by the DOM;
202
+ // the explicit swap handles the listener target changing across connections.
203
+ const host = this.closestEntity;
204
+ if (host && host !== this._modelListenerTarget) {
205
+ this._modelListenerTarget?.removeEventListener('ready', this._onModelReady);
206
+ host.addEventListener('ready', this._onModelReady);
207
+ this._modelListenerTarget = host;
208
+ }
209
+
210
+ this._applyRootBone();
211
+
212
+ if (this.component.baseLayer) {
213
+ // The component survived the host's readiness cycle (a pc-model reloading content on
214
+ // its stable host entity). A loaded graph cannot be reassigned in place, so drop it
215
+ // and reassign from the current source, restoring the active clip and playhead.
216
+ this._refreshClips();
217
+ } else {
218
+ this._applyClips();
219
+ }
220
+ }
221
+
222
+ disconnectedCallback() {
223
+ this._modelListenerTarget?.removeEventListener('ready', this._onModelReady);
224
+ this._modelListenerTarget = null;
225
+
226
+ // Invalidate any auto-assign still awaiting its model, and drop the adoption
227
+ // bookkeeping so a reconnection starts clean
228
+ this._sourceGeneration++;
229
+ this._assignedClips.clear();
230
+ this._autoAssigned = false;
231
+ this._managedRootBone = null;
232
+
233
+ super.disconnectedCallback();
234
+ }
235
+
236
+ /**
237
+ * The clip children in DOM order. Read afresh each pass — the DOM is the single source of
238
+ * truth for the declared clip set.
239
+ */
240
+ private _clipElements(): AnimClipElement[] {
241
+ return Array.from(this.querySelectorAll<AnimClipElement>(':scope > pc-anim-clip'));
242
+ }
243
+
244
+ /**
245
+ * Assigns a clip's state. Until the clip's real track resolves, the engine's own placeholder
246
+ * track stands in — it keeps the layer playable, so `activate` can start playback and the
247
+ * declared `clip` selection can apply before any asset has loaded.
248
+ */
249
+ private _assignClip(clip: AnimClipElement) {
250
+ this.component.assignAnimation(clip.name, clip._track ?? AnimTrack.EMPTY, undefined, clip.speed, clip.loop);
251
+ }
252
+
253
+ /**
254
+ * Validates a clip child and, when valid, assigns its state and starts its track resolution.
255
+ *
256
+ * @param clip - The clip element.
257
+ * @returns Whether the clip was adopted.
258
+ */
259
+ private _adoptClip(clip: AnimClipElement): boolean {
260
+ const name = clip.name;
261
+ if (!name) {
262
+ clip._markInvalid('pc-anim-clip must have a name - clip not assigned');
263
+ return false;
264
+ }
265
+ if (name.indexOf('.') !== -1) {
266
+ clip._markInvalid(`pc-anim-clip '${name}' - '.' in a clip name is reserved for blend tree paths - clip not assigned`);
267
+ return false;
268
+ }
269
+ if (this._assignedClips.has(name)) {
270
+ clip._markInvalid(`pc-anim-clip '${name}' - an earlier clip already uses this name - clip not assigned`);
271
+ return false;
272
+ }
273
+ this._assignedClips.set(name, clip);
274
+ this._assignClip(clip);
275
+ clip._resolveTrack(this);
276
+ return true;
277
+ }
278
+
279
+ /**
280
+ * Assigns the current clip set: the declared clip children when there are any, otherwise the
281
+ * enclosing model's clips. Runs against a fresh component after a host cycle, so the
282
+ * adoption bookkeeping rebuilds from scratch.
283
+ */
284
+ private _applyClips(restore?: PlaybackState) {
285
+ if (!this.component) {
286
+ return;
287
+ }
288
+
289
+ this._sourceGeneration++;
290
+ this._assignedClips.clear();
291
+ this._autoAssigned = false;
292
+
293
+ const clips = this._clipElements();
294
+ if (clips.length === 0) {
295
+ this._kickAutoAssign(restore);
296
+ return;
297
+ }
298
+
299
+ for (const clip of clips) {
300
+ this._adoptClip(clip);
301
+ }
302
+ this._applySelection(restore);
303
+ }
304
+
305
+ /**
306
+ * Assigns every clip of the enclosing model's container, named by track name, in container
307
+ * order. Names the engine cannot host — dotted (reserved for blend tree paths) or already
308
+ * taken — are skipped with a warning naming each.
309
+ */
310
+ private async _kickAutoAssign(restore?: PlaybackState) {
311
+ const generation = this._sourceGeneration;
312
+
313
+ const model = this.parentElement;
314
+ if (!(model instanceof ModelElement)) {
315
+ // Not inside a model: an empty component, driven through the JS API
316
+ return;
317
+ }
318
+
319
+ await model.ready();
320
+
321
+ // The source may have changed while the model loaded - a declared clip child appearing
322
+ // flips the element over to declared mode, and wins
323
+ const component = this.component;
324
+ if (generation !== this._sourceGeneration || !component || this._clipElements().length > 0) {
325
+ return;
326
+ }
327
+
328
+ const container = AssetElement.get(model.asset)?.resource as ContainerWithAnimations | undefined;
329
+ if (!container) {
330
+ // The load failed; the model already reported it
331
+ return;
332
+ }
333
+
334
+ const label = this.id ? ` '${this.id}'` : '';
335
+ if (container.animations.length === 0) {
336
+ console.warn(`pc-anim${label} - model '${model.asset}' has no animations`);
337
+ return;
338
+ }
339
+
340
+ const seen = new Set<string>();
341
+ for (const animationAsset of container.animations) {
342
+ const track = animationAsset.resource;
343
+ if (!(track instanceof AnimTrack)) {
344
+ continue;
345
+ }
346
+ if (track.name.indexOf('.') !== -1) {
347
+ console.warn(`pc-anim${label} - track '${track.name}' - '.' in a clip name is reserved for blend tree paths - track skipped`);
348
+ continue;
349
+ }
350
+ if (seen.has(track.name)) {
351
+ console.warn(`pc-anim${label} - duplicate track name '${track.name}' - track skipped`);
352
+ continue;
353
+ }
354
+ seen.add(track.name);
355
+ component.assignAnimation(track.name, track);
356
+ }
357
+
358
+ this._autoAssigned = seen.size > 0;
359
+ this._applySelection(restore);
360
+ }
361
+
362
+ /**
363
+ * Applies the active-clip selection: the declared `clip` when it names an assigned state,
364
+ * else a captured pre-rebuild state when it survived, else the engine's default (the first
365
+ * assigned clip). A restore also reinstates the playhead and both playing flags exactly as
366
+ * captured — the reassignment that preceded it set both to the `activate` outcome, which is
367
+ * not necessarily the state the rebuild interrupted.
368
+ */
369
+ private _applySelection(restore?: PlaybackState) {
370
+ const component = this.component;
371
+ const layer = component ? component.baseLayer : null;
372
+ if (!component || !layer) {
373
+ return;
374
+ }
375
+
376
+ if (this._clip && !layer.states.includes(this._clip)) {
377
+ this._warnUnknownClip(this._clip);
378
+ }
379
+
380
+ let target: string | null = null;
381
+ if (this._clip && layer.states.includes(this._clip)) {
382
+ target = this._clip;
383
+ } else if (restore && layer.states.includes(restore.state)) {
384
+ target = restore.state;
385
+ }
386
+
387
+ if (target && layer.activeState !== target) {
388
+ layer.play(target);
389
+ }
390
+
391
+ if (restore) {
392
+ if (target === restore.state) {
393
+ layer.activeStateCurrentTime = restore.time;
394
+ }
395
+ layer.playing = restore.layerPlaying;
396
+ component.playing = restore.playing;
397
+ }
398
+ }
399
+
400
+ private _warnUnknownClip(name: string) {
401
+ if (this._warnedClip === name) {
402
+ return;
403
+ }
404
+ this._warnedClip = name;
405
+ const label = this.id ? ` '${this.id}'` : '';
406
+ console.warn(`pc-anim${label} has no clip named '${name}' - selection unchanged`);
407
+ }
408
+
409
+ /**
410
+ * Rebuilds the clip set from the DOM, restoring the active clip and playhead when they
411
+ * survive the rebuild. The engine cannot remove a state from a loaded graph (unassigning
412
+ * only empties the state's tracks), so removals, renames and source changes drop the whole
413
+ * graph and reassign.
414
+ *
415
+ * @internal
416
+ */
417
+ _refreshClips() {
418
+ const component = this.component;
419
+ if (!component) {
420
+ return;
421
+ }
422
+ // A clip-set change is also a chance for the skeleton source to have changed shape (a
423
+ // clip child appearing or leaving can accompany a model coming or going) - re-derive the
424
+ // binding root before the reassignment binds against it.
425
+ this._applyRootBone();
426
+ const layer = component.baseLayer;
427
+ const restore = layer ? {
428
+ state: layer.activeState,
429
+ time: layer.activeStateCurrentTime,
430
+ playing: component.playing,
431
+ layerPlaying: layer.playing
432
+ } : undefined;
433
+ component.removeStateGraph();
434
+ this._applyClips(restore);
435
+ }
436
+
437
+ /**
438
+ * Adopts a clip child announced by its connectedCallback. The initComponent sweep adopts
439
+ * children already present, so this is a no-op for those; it serves clips appended later,
440
+ * and flips an auto-assigned element over to its declared children — declared clips win.
441
+ *
442
+ * @param clip - The clip element.
443
+ * @internal
444
+ */
445
+ _registerClip(clip: AnimClipElement) {
446
+ if (!this.component) {
447
+ return;
448
+ }
449
+ if (this._autoAssigned) {
450
+ this._refreshClips();
451
+ return;
452
+ }
453
+ if (this._assignedClips.get(clip.name) === clip) {
454
+ return;
455
+ }
456
+ // A clip child appearing supersedes an auto-assign still awaiting its model
457
+ this._sourceGeneration++;
458
+ if (this._adoptClip(clip)) {
459
+ this._applySelection();
460
+ }
461
+ }
462
+
463
+ /**
464
+ * Releases a disconnected clip child. Rebuilds the set — a state cannot be removed from a
465
+ * live graph — and the removal of the last child inside a `<pc-model>` flips the element
466
+ * back to auto-assigning the model's clips.
467
+ *
468
+ * @param clip - The clip element.
469
+ * @internal
470
+ */
471
+ _unregisterClip(clip: AnimClipElement) {
472
+ if (!this.component) {
473
+ // The whole subtree is coming down (parents disconnect first) - nothing to rebuild
474
+ return;
475
+ }
476
+ if (this._assignedClips.get(clip.name) !== clip) {
477
+ // The clip never held a state (invalid or duplicate name)
478
+ return;
479
+ }
480
+ this._refreshClips();
481
+ }
482
+
483
+ /**
484
+ * Swaps a clip's resolved track in for the placeholder (or for its previous track after an
485
+ * asset change). A swap of the active clip restarts it: the engine preserves the playhead
486
+ * through a track replacement, which would land mid-way into unrelated animation.
487
+ *
488
+ * @param clip - The clip element.
489
+ * @returns Whether the clip still owns its state — the resolution may have been superseded
490
+ * by a rebuild that dropped it.
491
+ * @internal
492
+ */
493
+ _onClipResolved(clip: AnimClipElement): boolean {
494
+ const component = this.component;
495
+ if (!component || this._assignedClips.get(clip.name) !== clip) {
496
+ return false;
497
+ }
498
+ this._assignClip(clip);
499
+ const layer = component.baseLayer;
500
+ if (layer && layer.activeState === clip.name) {
501
+ layer.play(clip.name);
502
+ }
503
+ return true;
504
+ }
505
+
506
+ /**
507
+ * Applies a clip's changed speed or loop. The engine bakes both into the playback state it
508
+ * creates on state entry, so a live change re-enters the state and restores the playhead.
509
+ *
510
+ * @param clip - The clip element.
511
+ * @internal
512
+ */
513
+ _onClipParamsChanged(clip: AnimClipElement) {
514
+ const component = this.component;
515
+ if (!component || this._assignedClips.get(clip.name) !== clip) {
516
+ return;
517
+ }
518
+ this._assignClip(clip);
519
+ const layer = component.baseLayer;
520
+ if (layer && layer.activeState === clip.name) {
521
+ const time = layer.activeStateCurrentTime;
522
+ layer.play(clip.name);
523
+ layer.activeStateCurrentTime = time;
524
+ }
525
+ }
526
+
527
+ /**
528
+ * Resumes playback, optionally switching to a named clip first (a hard cut). A name that
529
+ * matches no clip leaves the selection unchanged.
530
+ *
531
+ * @param name - The name of the clip to play. Resumes the current clip when omitted.
532
+ */
533
+ play(name?: string) {
534
+ const component = this.component;
535
+ const layer = component ? component.baseLayer : null;
536
+ if (!component || !layer) {
537
+ return;
538
+ }
539
+ // layer.play sets the layer controller's playing flag; the component's is the system
540
+ // gate. Setting both is what makes this a resume regardless of how playback stopped.
541
+ if (name !== undefined) {
542
+ if (!layer.states.includes(name)) {
543
+ return;
544
+ }
545
+ layer.play(name);
546
+ } else {
547
+ layer.play();
548
+ }
549
+ component.playing = true;
550
+ }
551
+
552
+ /**
553
+ * Pauses playback, preserving the playhead — {@link play} resumes from where it stopped.
554
+ */
555
+ pause() {
556
+ if (!this.component) {
557
+ return;
558
+ }
559
+ // Only the component flag - the single gate the system tick reads - is cleared. The
560
+ // layer controller's flag is left as-is so a pause is exactly reversible, whether
561
+ // resumed through play() (which sets both) or through the component API directly.
562
+ this.component.playing = false;
563
+ }
564
+
565
+ /**
566
+ * Cross-fades to a named clip and ensures playback is running. A name that matches no clip
567
+ * leaves the selection unchanged.
568
+ *
569
+ * @param name - The name of the clip to fade to.
570
+ * @param time - The fade duration in seconds. Defaults to the `transition-time` attribute.
571
+ */
572
+ transition(name: string, time?: number) {
573
+ const component = this.component;
574
+ const layer = component ? component.baseLayer : null;
575
+ if (!component || !layer || !layer.states.includes(name)) {
576
+ return;
577
+ }
578
+ layer.transition(name, Math.max(0, time ?? this._transitionTime));
579
+ layer.playing = true;
580
+ component.playing = true;
581
+ }
582
+
583
+ /**
584
+ * Gets the underlying PlayCanvas anim component.
585
+ * @returns The anim component.
586
+ */
587
+ get component(): AnimComponent {
588
+ return super.component as AnimComponent;
589
+ }
590
+
591
+ /**
592
+ * Gets the names of the assigned clips.
593
+ * @returns The clip names, in assignment order.
594
+ */
595
+ get clips(): string[] {
596
+ const layer = this.component ? this.component.baseLayer : null;
597
+ return layer ? layer.states.filter(state => !ANIM_CONTROL_STATES.includes(state)) : [];
598
+ }
599
+
600
+ /**
601
+ * Sets whether playback starts automatically once a clip is assigned. Defaults to `true`.
602
+ * Applies when clips are assigned — it does not stop a clip that is already playing.
603
+ * @param value - Whether playback starts automatically.
604
+ */
605
+ set activate(value: boolean) {
606
+ this._activate = value;
607
+ if (this.component) {
608
+ this.component.activate = value;
609
+ }
610
+ }
611
+
612
+ /**
613
+ * Gets whether playback starts automatically once a clip is assigned.
614
+ * @returns Whether playback starts automatically.
615
+ */
616
+ get activate() {
617
+ return this._activate;
618
+ }
619
+
620
+ /**
621
+ * Sets the name of the active clip. Changing it switches playback, cross-fading over
622
+ * `transition-time` seconds (a hard cut at 0). An empty value leaves the current clip
623
+ * playing; a name that matches no clip warns and leaves the selection unchanged.
624
+ * @param value - The name of the active clip.
625
+ */
626
+ set clip(value: string) {
627
+ this._clip = value;
628
+ const component = this.component;
629
+ const layer = component ? component.baseLayer : null;
630
+ if (!component || !layer || !value) {
631
+ return;
632
+ }
633
+ if (!layer.states.includes(value)) {
634
+ this._warnUnknownClip(value);
635
+ return;
636
+ }
637
+ if (layer.activeState === value) {
638
+ return;
639
+ }
640
+ if (this._transitionTime > 0) {
641
+ this.transition(value);
642
+ } else {
643
+ this.play(value);
644
+ }
645
+ }
646
+
647
+ /**
648
+ * Gets the name of the active clip.
649
+ * @returns The name of the active clip.
650
+ */
651
+ get clip() {
652
+ return this._clip;
653
+ }
654
+
655
+ /**
656
+ * Sets the playback speed multiplier applied across all clips, where 0 freezes playback.
657
+ * Defaults to 1.
658
+ * @param value - The playback speed multiplier.
659
+ */
660
+ set speed(value: number) {
661
+ this._speed = value;
662
+ if (this.component) {
663
+ this.component.speed = value;
664
+ }
665
+ }
666
+
667
+ /**
668
+ * Gets the playback speed multiplier applied across all clips.
669
+ * @returns The playback speed multiplier.
670
+ */
671
+ get speed() {
672
+ return this._speed;
673
+ }
674
+
675
+ /**
676
+ * Sets the cross-fade duration of clip switches made through the `clip` attribute, in
677
+ * seconds. Defaults to 0 (a hard cut).
678
+ * @param value - The cross-fade duration in seconds.
679
+ */
680
+ set transitionTime(value: number) {
681
+ this._transitionTime = value;
682
+ }
683
+
684
+ /**
685
+ * Gets the cross-fade duration of clip switches made through the `clip` attribute.
686
+ * @returns The cross-fade duration in seconds.
687
+ */
688
+ get transitionTime() {
689
+ return this._transitionTime;
690
+ }
691
+
692
+ static get observedAttributes() {
693
+ return [...super.observedAttributes, 'activate', 'clip', 'speed', 'transition-time'];
694
+ }
695
+
696
+ attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null) {
697
+ super.attributeChangedCallback(name, _oldValue, newValue);
698
+
699
+ switch (name) {
700
+ case 'activate':
701
+ this.activate = parseBool(newValue, true);
702
+ break;
703
+ case 'clip':
704
+ this.clip = newValue ?? '';
705
+ break;
706
+ case 'speed':
707
+ this.speed = parseNumber(newValue, 1, name);
708
+ break;
709
+ case 'transition-time':
710
+ this.transitionTime = parseNumber(newValue, 0, name);
711
+ break;
712
+ }
713
+ }
714
+ }
715
+
716
+ customElements.define('pc-anim', AnimComponentElement);
717
+
718
+ export { AnimComponentElement };
719
+ export type { ContainerWithAnimations };