@energy8platform/game-engine 0.20.0 → 0.22.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 (93) hide show
  1. package/README.md +121 -0
  2. package/dist/animation.cjs.js +18 -3
  3. package/dist/animation.cjs.js.map +1 -1
  4. package/dist/animation.esm.js +18 -3
  5. package/dist/animation.esm.js.map +1 -1
  6. package/dist/core.cjs.js +18 -3
  7. package/dist/core.cjs.js.map +1 -1
  8. package/dist/core.esm.js +18 -3
  9. package/dist/core.esm.js.map +1 -1
  10. package/dist/host.cjs.js +18 -3
  11. package/dist/host.cjs.js.map +1 -1
  12. package/dist/host.d.ts +3 -5
  13. package/dist/host.esm.js +18 -3
  14. package/dist/host.esm.js.map +1 -1
  15. package/dist/index.cjs.js +18 -2535
  16. package/dist/index.cjs.js.map +1 -1
  17. package/dist/index.d.ts +3 -1020
  18. package/dist/index.esm.js +20 -2525
  19. package/dist/index.esm.js.map +1 -1
  20. package/dist/slot.cjs.js +1872 -61
  21. package/dist/slot.cjs.js.map +1 -1
  22. package/dist/slot.d.ts +555 -28
  23. package/dist/slot.esm.js +1857 -62
  24. package/dist/slot.esm.js.map +1 -1
  25. package/dist/vite.cjs.js +0 -5
  26. package/dist/vite.cjs.js.map +1 -1
  27. package/dist/vite.esm.js +0 -5
  28. package/dist/vite.esm.js.map +1 -1
  29. package/package.json +2 -35
  30. package/src/animation/Tween.ts +14 -3
  31. package/src/host/index.ts +0 -1
  32. package/src/host/types.ts +0 -3
  33. package/src/index.ts +0 -28
  34. package/src/slot/anim/easing-map.ts +16 -2
  35. package/src/slot/cascade/TumbleController.ts +230 -0
  36. package/src/slot/config/ReelSystemConfig.ts +559 -0
  37. package/src/slot/config/presets.ts +222 -0
  38. package/src/slot/features/extra.ts +189 -0
  39. package/src/slot/features/index.ts +44 -0
  40. package/src/slot/features/symbols.ts +183 -0
  41. package/src/slot/features/types.ts +136 -0
  42. package/src/slot/features/wilds.ts +151 -0
  43. package/src/slot/grid/ReelGrid.ts +93 -24
  44. package/src/slot/grid/SymbolCell.ts +45 -11
  45. package/src/slot/index.ts +61 -2
  46. package/src/slot/motion/AnticipationController.ts +96 -0
  47. package/src/slot/motion/SpinEngine.ts +384 -0
  48. package/src/slot/system/ReelSystem.ts +295 -0
  49. package/src/vite/index.ts +0 -5
  50. package/dist/react-jsx.cjs.js +0 -3
  51. package/dist/react-jsx.cjs.js.map +0 -1
  52. package/dist/react-jsx.d.ts +0 -602
  53. package/dist/react-jsx.esm.js +0 -2
  54. package/dist/react-jsx.esm.js.map +0 -1
  55. package/dist/react.cjs.js +0 -3787
  56. package/dist/react.cjs.js.map +0 -1
  57. package/dist/react.d.ts +0 -1467
  58. package/dist/react.esm.js +0 -3771
  59. package/dist/react.esm.js.map +0 -1
  60. package/dist/ui.cjs.js +0 -2999
  61. package/dist/ui.cjs.js.map +0 -1
  62. package/dist/ui.d.ts +0 -1116
  63. package/dist/ui.esm.js +0 -2983
  64. package/dist/ui.esm.js.map +0 -1
  65. package/src/react/EngineContext.ts +0 -26
  66. package/src/react/ReactScene.ts +0 -88
  67. package/src/react/applyProps.ts +0 -271
  68. package/src/react/catalogue.ts +0 -17
  69. package/src/react/createPixiRoot.ts +0 -31
  70. package/src/react/extendAll.ts +0 -74
  71. package/src/react/hooks.ts +0 -46
  72. package/src/react/index.ts +0 -29
  73. package/src/react/jsx-runtime.ts +0 -346
  74. package/src/react/reconciler.ts +0 -338
  75. package/src/slot/freeSpins/FreeSpinsSession.ts +0 -40
  76. package/src/state/StateMachine.ts +0 -231
  77. package/src/state/index.ts +0 -1
  78. package/src/ui/BalanceDisplay.ts +0 -159
  79. package/src/ui/Button.ts +0 -304
  80. package/src/ui/FlexContainer.ts +0 -775
  81. package/src/ui/Label.ts +0 -124
  82. package/src/ui/LabelValue.ts +0 -122
  83. package/src/ui/Layout.ts +0 -291
  84. package/src/ui/Modal.ts +0 -170
  85. package/src/ui/Panel.ts +0 -204
  86. package/src/ui/ProgressBar.ts +0 -170
  87. package/src/ui/ScrollContainer.ts +0 -478
  88. package/src/ui/Slider.ts +0 -241
  89. package/src/ui/Toast.ts +0 -150
  90. package/src/ui/Toggle.ts +0 -201
  91. package/src/ui/WinDisplay.ts +0 -145
  92. package/src/ui/index.ts +0 -33
  93. package/src/ui/view.ts +0 -28
package/dist/react.cjs.js DELETED
@@ -1,3787 +0,0 @@
1
- 'use strict';
2
-
3
- var constants = require('react-reconciler/constants');
4
- var Reconciler = require('react-reconciler');
5
- var pixi_js = require('pixi.js');
6
- var react = require('react');
7
-
8
- /** Mutable catalogue: PascalCase name -> PixiJS constructor */
9
- const catalogue = {};
10
- /**
11
- * Register PixiJS classes for use as JSX elements.
12
- * Keys must be PascalCase; JSX uses the camelCase equivalent.
13
- *
14
- * @example
15
- * ```ts
16
- * import { Container, Sprite, Text } from 'pixi.js';
17
- * extend({ Container, Sprite, Text });
18
- * // Now <container>, <sprite>, <text> work in JSX
19
- * ```
20
- */
21
- function extend(components) {
22
- Object.assign(catalogue, components);
23
- }
24
-
25
- const RESERVED = new Set(['children', 'key', 'ref']);
26
- /** Props handled by the reconciler as flex item config, not forwarded to components */
27
- const FLEX_ITEM_PROPS$1 = new Set(['flexGrow', 'flexShrink', 'layoutWidth', 'layoutHeight', 'alignSelf', 'flexExclude', 'top', 'right', 'bottom', 'left', 'centerX', 'centerY']);
28
- /** Base Container props applied directly to the instance (not via config) */
29
- const CONTAINER_PROPS = new Set([
30
- 'x', 'y', 'alpha', 'visible', 'rotation', 'angle', 'zIndex',
31
- 'label', 'cursor', 'eventMode',
32
- ]);
33
- // ─── UI Component helpers ────────────────────────────────
34
- /**
35
- * Extract a config object from React props.
36
- * - Strips reserved keys (children, key, ref) and event props
37
- * - Unfolds dash-notation into nested objects: `colors-default` → `{ colors: { default: ... } }`
38
- */
39
- function extractConfig(props) {
40
- const config = {};
41
- for (const key in props) {
42
- if (RESERVED.has(key) || FLEX_ITEM_PROPS$1.has(key) || CONTAINER_PROPS.has(key) || isEventProp(key))
43
- continue;
44
- if (key.includes('-')) {
45
- const parts = key.split('-');
46
- const root = parts[0];
47
- const nested = parts.slice(1).join('-');
48
- if (!config[root] || typeof config[root] !== 'object') {
49
- config[root] = {};
50
- }
51
- config[root][nested] = props[key];
52
- }
53
- else {
54
- config[key] = props[key];
55
- }
56
- }
57
- return config;
58
- }
59
- /**
60
- * Diff two prop sets and return a config object with only changed values.
61
- * Uses extractConfig format (dash-notation unfolded).
62
- */
63
- function diffConfig(newProps, oldProps) {
64
- const changed = {};
65
- // New or changed props
66
- for (const key in newProps) {
67
- if (RESERVED.has(key) || FLEX_ITEM_PROPS$1.has(key) || CONTAINER_PROPS.has(key) || isEventProp(key))
68
- continue;
69
- if (newProps[key] !== oldProps[key]) {
70
- if (key.includes('-')) {
71
- const parts = key.split('-');
72
- const root = parts[0];
73
- const nested = parts.slice(1).join('-');
74
- if (!changed[root] || typeof changed[root] !== 'object') {
75
- changed[root] = {};
76
- }
77
- changed[root][nested] = newProps[key];
78
- }
79
- else {
80
- changed[key] = newProps[key];
81
- }
82
- }
83
- }
84
- return changed;
85
- }
86
- /**
87
- * Apply only event props from React props to a PixiJS instance.
88
- */
89
- function applyEventProps(instance, newProps, oldProps = {}) {
90
- // Remove old event handlers
91
- for (const key in oldProps) {
92
- if (!isEventProp(key) || key in newProps)
93
- continue;
94
- instance[REACT_TO_PIXI_EVENTS[key]] = null;
95
- }
96
- // Apply new/changed event handlers + onPress (component-level callback)
97
- for (const key in newProps) {
98
- if (key === 'onPress') {
99
- instance.onPress = newProps[key];
100
- continue;
101
- }
102
- if (!isEventProp(key))
103
- continue;
104
- if (newProps[key] !== oldProps[key]) {
105
- instance[REACT_TO_PIXI_EVENTS[key]] = newProps[key];
106
- }
107
- }
108
- }
109
- const REACT_TO_PIXI_EVENTS = {
110
- onClick: 'onclick',
111
- onPointerDown: 'onpointerdown',
112
- onPointerUp: 'onpointerup',
113
- onPointerMove: 'onpointermove',
114
- onPointerOver: 'onpointerover',
115
- onPointerOut: 'onpointerout',
116
- onPointerEnter: 'onpointerenter',
117
- onPointerLeave: 'onpointerleave',
118
- onPointerCancel: 'onpointercancel',
119
- onPointerTap: 'onpointertap',
120
- onPointerUpOutside: 'onpointerupoutside',
121
- onMouseDown: 'onmousedown',
122
- onMouseUp: 'onmouseup',
123
- onMouseMove: 'onmousemove',
124
- onMouseOver: 'onmouseover',
125
- onMouseOut: 'onmouseout',
126
- onMouseEnter: 'onmouseenter',
127
- onMouseLeave: 'onmouseleave',
128
- onMouseUpOutside: 'onmouseupoutside',
129
- onTouchStart: 'ontouchstart',
130
- onTouchEnd: 'ontouchend',
131
- onTouchMove: 'ontouchmove',
132
- onTouchCancel: 'ontouchcancel',
133
- onTouchEndOutside: 'ontouchendoutside',
134
- onWheel: 'onwheel',
135
- onRightClick: 'onrightclick',
136
- onRightDown: 'onrightdown',
137
- onRightUp: 'onrightup',
138
- onRightUpOutside: 'onrightupoutside',
139
- onTap: 'ontap',
140
- onGlobalpointermove: 'onglobalpointermove',
141
- onGlobalmousemove: 'onglobalmousemove',
142
- onGlobaltouchmove: 'onglobaltouchmove',
143
- };
144
- function isEventProp(key) {
145
- return key in REACT_TO_PIXI_EVENTS;
146
- }
147
- function hasEventProps(props) {
148
- for (const key in props) {
149
- if (isEventProp(key))
150
- return true;
151
- }
152
- return false;
153
- }
154
- /**
155
- * Graphics does not have an intrinsic size — its bounds come from the `draw` callback.
156
- * PixiJS's `Container.width` setter applies a scale transform to match the requested
157
- * value, which silently makes the rendered size diverge from `getLocalBounds()` and
158
- * breaks downstream flex layout. For Graphics we treat `width`/`height` as layout
159
- * hints instead, storing them on `_flexConfig.layoutWidth`/`layoutHeight` so parent
160
- * FlexContainers measure correctly without touching the child's scale.
161
- */
162
- function isGraphicsLike(instance) {
163
- return typeof instance?.clear === 'function'
164
- && typeof instance?.fill === 'function'
165
- && typeof instance?.rect === 'function';
166
- }
167
- /** Redirect a width/height write on a Graphics into its flex layout hint. Returns true if handled. */
168
- function applyGraphicsDimension(instance, key, value) {
169
- if ((key !== 'width' && key !== 'height') || !isGraphicsLike(instance))
170
- return false;
171
- const target = key === 'width' ? 'layoutWidth' : 'layoutHeight';
172
- if (value === undefined) {
173
- if (instance._flexConfig)
174
- delete instance._flexConfig[target];
175
- return true;
176
- }
177
- if (!instance._flexConfig)
178
- instance._flexConfig = {};
179
- instance._flexConfig[target] = value;
180
- return true;
181
- }
182
- function setNestedValue(target, path, value) {
183
- let obj = target;
184
- for (let i = 0; i < path.length - 1; i++) {
185
- obj = obj[path[i]];
186
- if (obj == null)
187
- return;
188
- }
189
- obj[path[path.length - 1]] = value;
190
- }
191
- /**
192
- * Apply base Container props (x, y, alpha, visible, etc.) directly to the instance.
193
- * Called for ALL elements — both UI components and standard PixiJS elements.
194
- * Also handles scale, pivot, position, anchor via dash-notation.
195
- */
196
- function applyContainerProps(instance, newProps, oldProps = {}) {
197
- for (const key of CONTAINER_PROPS) {
198
- if (key in newProps && newProps[key] !== oldProps[key]) {
199
- try {
200
- instance[key] = newProps[key];
201
- }
202
- catch { /* read-only */ }
203
- }
204
- else if (key in oldProps && !(key in newProps)) {
205
- // Prop removed — reset to undefined (PixiJS defaults)
206
- try {
207
- instance[key] = undefined;
208
- }
209
- catch { /* read-only */ }
210
- }
211
- }
212
- // Handle scale as uniform number or {x,y} object
213
- if ('scale' in newProps && newProps.scale !== oldProps.scale) {
214
- const s = newProps.scale;
215
- if (typeof s === 'number') {
216
- instance.scale?.set?.(s, s);
217
- }
218
- else if (s && typeof s === 'object') {
219
- instance.scale?.set?.(s.x ?? 1, s.y ?? 1);
220
- }
221
- }
222
- // Handle dash-notation container props: scale-x, scale-y, pivot-x, pivot-y, position-x, position-y, anchor-x, anchor-y
223
- for (const key in newProps) {
224
- if (!key.includes('-'))
225
- continue;
226
- const parts = key.split('-');
227
- const root = parts[0];
228
- if (root === 'scale' || root === 'pivot' || root === 'position' || root === 'anchor') {
229
- if (newProps[key] !== oldProps[key]) {
230
- setNestedValue(instance, parts, newProps[key]);
231
- }
232
- }
233
- }
234
- }
235
- function applyProps(instance, newProps, oldProps = {}) {
236
- // Remove old props not in newProps
237
- for (const key in oldProps) {
238
- if (RESERVED.has(key) || FLEX_ITEM_PROPS$1.has(key) || key in newProps)
239
- continue;
240
- const pixiEvent = REACT_TO_PIXI_EVENTS[key];
241
- if (pixiEvent) {
242
- instance[pixiEvent] = null;
243
- }
244
- else if (key === 'draw') ;
245
- else if (key.includes('-')) ;
246
- else if (applyGraphicsDimension(instance, key, undefined)) ;
247
- else {
248
- try {
249
- instance[key] = undefined;
250
- }
251
- catch {
252
- // read-only or non-configurable
253
- }
254
- }
255
- }
256
- // Apply new props
257
- for (const key in newProps) {
258
- if (RESERVED.has(key) || FLEX_ITEM_PROPS$1.has(key))
259
- continue;
260
- const value = newProps[key];
261
- const pixiEvent = REACT_TO_PIXI_EVENTS[key];
262
- if (pixiEvent) {
263
- instance[pixiEvent] = value;
264
- }
265
- else if (key === 'draw' && typeof value === 'function') {
266
- instance.clear?.();
267
- value(instance);
268
- }
269
- else if (key.includes('-')) {
270
- const parts = key.split('-');
271
- setNestedValue(instance, parts, value);
272
- }
273
- else if (applyGraphicsDimension(instance, key, value)) ;
274
- else {
275
- try {
276
- instance[key] = value;
277
- }
278
- catch {
279
- // read-only property
280
- }
281
- }
282
- }
283
- }
284
-
285
- // ─── Helpers ─────────────────────────────────────────────
286
- function normalizePadding(p) {
287
- return typeof p === 'number' ? [p, p, p, p] : p;
288
- }
289
- /** Resolve padding from config: individual props override the base `padding` value */
290
- function resolvePadding(config) {
291
- const base = normalizePadding(config.padding ?? 0);
292
- return [
293
- config.paddingTop ?? base[0],
294
- config.paddingRight ?? base[1],
295
- config.paddingBottom ?? base[2],
296
- config.paddingLeft ?? base[3],
297
- ];
298
- }
299
- /** Resolve a dimension value — number passes through, "50%" resolves against reference */
300
- function resolveDimension(value, reference) {
301
- if (value === undefined)
302
- return undefined;
303
- if (typeof value === 'number')
304
- return value;
305
- if (typeof value === 'string' && value.endsWith('%')) {
306
- const pct = parseFloat(value);
307
- if (!isNaN(pct) && reference > 0 && isFinite(reference))
308
- return (pct / 100) * reference;
309
- }
310
- return undefined;
311
- }
312
- /** Measure a child's size and bounds offset for layout purposes */
313
- function measureChild(child, parentContentW = 0, parentContentH = 0) {
314
- const cfg = child._flexConfig;
315
- const resolvedLW = resolveDimension(cfg?.layoutWidth, parentContentW);
316
- const resolvedLH = resolveDimension(cfg?.layoutHeight, parentContentH);
317
- // FlexContainer children are top-left origin by construction, so `ox/oy = 0`
318
- // is correct and we can skip the `getLocalBounds()` call entirely.
319
- if (child instanceof FlexContainer) {
320
- const fc = child;
321
- const w = fc._explicitWidth > 0 ? fc._explicitWidth : (fc._computedWidth > 0 ? fc._computedWidth : undefined);
322
- const h = fc._explicitHeight > 0 ? fc._explicitHeight : (fc._computedHeight > 0 ? fc._computedHeight : undefined);
323
- if (w !== undefined && h !== undefined) {
324
- return { w: resolvedLW ?? w, h: resolvedLH ?? h, ox: 0, oy: 0 };
325
- }
326
- }
327
- // Use localBounds to get the true visual origin offset.
328
- // We take `ox/oy` from bounds unconditionally — a user-supplied `layoutWidth/Height`
329
- // overrides the SIZE used by flex (protection against pre-paint bounds of 0), but
330
- // it must NOT erase the center-anchor compensation: Button/Label views are drawn at
331
- // `(-w/2..w/2)` and their bounds.x = -w/2 is what lets `layoutLine` place the
332
- // visible rectangle where the layout intends.
333
- const bounds = child.getLocalBounds();
334
- return {
335
- w: resolvedLW ?? bounds.width,
336
- h: resolvedLH ?? bounds.height,
337
- ox: bounds.x,
338
- oy: bounds.y,
339
- };
340
- }
341
- /**
342
- * Set a child's main or cross dimension.
343
- * For FlexContainer children, calls resize() to trigger internal relayout
344
- * instead of the PixiJS scale setter.
345
- */
346
- function setChildMainSize(child, isRow, mainSize, item) {
347
- if (child instanceof FlexContainer) {
348
- const fc = child;
349
- fc.resize(isRow ? mainSize : fc._explicitWidth || fc._computedWidth, isRow ? fc._explicitHeight || fc._computedHeight : mainSize);
350
- }
351
- else {
352
- if (isRow) {
353
- child.width = mainSize;
354
- }
355
- else {
356
- child.height = mainSize;
357
- }
358
- }
359
- if (isRow)
360
- item.w = mainSize;
361
- else
362
- item.h = mainSize;
363
- }
364
- function setChildCrossSize(child, isRow, crossSize) {
365
- if (child instanceof FlexContainer) {
366
- const fc = child;
367
- fc.resize(isRow ? fc._explicitWidth || fc._computedWidth : crossSize, isRow ? crossSize : fc._explicitHeight || fc._computedHeight);
368
- }
369
- else {
370
- if (isRow) {
371
- child.height = crossSize;
372
- }
373
- else {
374
- child.width = crossSize;
375
- }
376
- }
377
- }
378
- function layoutLine(items, isRow, mainSize, justify, align, gap, crossOffset, crossSize) {
379
- if (items.length === 0)
380
- return;
381
- // Compute total fixed main size and flex grow total
382
- let totalFixed = 0;
383
- let totalGrow = 0;
384
- for (const item of items) {
385
- const grow = item.child._flexConfig?.flexGrow ?? 0;
386
- if (grow > 0) {
387
- totalGrow += grow;
388
- }
389
- else {
390
- totalFixed += isRow ? item.w : item.h;
391
- }
392
- }
393
- const totalGap = gap * (items.length - 1);
394
- const availableForFlex = Math.max(0, mainSize - totalFixed - totalGap);
395
- // Resolve flex sizes
396
- if (totalGrow > 0) {
397
- for (const item of items) {
398
- const grow = item.child._flexConfig?.flexGrow ?? 0;
399
- if (grow > 0) {
400
- const flexSize = (grow / totalGrow) * availableForFlex;
401
- setChildMainSize(item.child, isRow, flexSize, item);
402
- }
403
- }
404
- }
405
- // Shrink: if content overflows and mainSize is finite, shrink eligible items
406
- if (totalGrow === 0 && mainSize > 0) {
407
- const overflow = totalFixed + totalGap - mainSize;
408
- if (overflow > 0) {
409
- let totalShrinkable = 0;
410
- for (const item of items) {
411
- const shrink = item.child._flexConfig?.flexShrink ?? 1;
412
- if (shrink > 0) {
413
- totalShrinkable += isRow ? item.w : item.h;
414
- }
415
- }
416
- if (totalShrinkable > 0) {
417
- for (const item of items) {
418
- const shrink = item.child._flexConfig?.flexShrink ?? 1;
419
- if (shrink > 0) {
420
- const itemMain = isRow ? item.w : item.h;
421
- const reduction = overflow * (itemMain / totalShrinkable);
422
- const newSize = Math.max(0, itemMain - reduction);
423
- setChildMainSize(item.child, isRow, newSize, item);
424
- }
425
- }
426
- }
427
- }
428
- }
429
- // Calculate total main size after flex
430
- let totalMain = totalGap;
431
- for (const item of items) {
432
- totalMain += isRow ? item.w : item.h;
433
- }
434
- // Justify: compute starting offset and extra spacing
435
- let mainOffset = 0;
436
- let extraGap = 0;
437
- switch (justify) {
438
- case 'start':
439
- break;
440
- case 'center':
441
- mainOffset = Math.max(0, (mainSize - totalMain) / 2);
442
- break;
443
- case 'end':
444
- mainOffset = Math.max(0, mainSize - totalMain);
445
- break;
446
- case 'space-between':
447
- if (items.length > 1) {
448
- extraGap = Math.max(0, (mainSize - totalMain + totalGap) / (items.length - 1)) - gap;
449
- }
450
- break;
451
- case 'space-around':
452
- if (items.length > 0) {
453
- const totalSpace = Math.max(0, mainSize - totalMain + totalGap);
454
- const segment = totalSpace / items.length;
455
- mainOffset = segment / 2;
456
- extraGap = segment - gap;
457
- }
458
- break;
459
- }
460
- // Position each item
461
- let pos = mainOffset;
462
- for (const item of items) {
463
- const mainDim = isRow ? item.w : item.h;
464
- const crossDim = isRow ? item.h : item.w;
465
- // Cross-axis alignment (alignSelf overrides align)
466
- const effectiveAlign = (item.child._flexConfig?.alignSelf && item.child._flexConfig.alignSelf !== 'auto')
467
- ? item.child._flexConfig.alignSelf
468
- : align;
469
- let crossPos = crossOffset;
470
- switch (effectiveAlign) {
471
- case 'start':
472
- break;
473
- case 'center':
474
- crossPos += (crossSize - crossDim) / 2;
475
- break;
476
- case 'end':
477
- crossPos += crossSize - crossDim;
478
- break;
479
- case 'stretch':
480
- setChildCrossSize(item.child, isRow, crossSize);
481
- break;
482
- }
483
- // Compensate for local bounds offset (e.g. centered anchors)
484
- if (isRow) {
485
- item.child.x = pos - item.ox;
486
- item.child.y = crossPos - item.oy;
487
- }
488
- else {
489
- item.child.x = crossPos - item.ox;
490
- item.child.y = pos - item.oy;
491
- }
492
- pos += mainDim + gap + extraGap;
493
- }
494
- }
495
- // ─── FlexContainer ───────────────────────────────────────
496
- /**
497
- * Lightweight flexbox-like layout container for PixiJS.
498
- *
499
- * Supports row/column direction, justify/align, gap, padding, wrapping,
500
- * and flex-grow distribution. Zero external dependencies.
501
- *
502
- * @example
503
- * ```ts
504
- * const toolbar = new FlexContainer({
505
- * direction: 'row',
506
- * justifyContent: 'space-between',
507
- * alignItems: 'center',
508
- * gap: 16,
509
- * padding: 12,
510
- * });
511
- *
512
- * toolbar.addFlexChild(button1);
513
- * toolbar.addFlexChild(button2);
514
- * toolbar.resize(800, 60);
515
- * ```
516
- */
517
- class FlexContainer extends pixi_js.Container {
518
- __uiComponent = true;
519
- _config;
520
- _padding;
521
- _maxWidth;
522
- _maxHeight;
523
- /** @internal */ _explicitWidth;
524
- /** @internal */ _explicitHeight;
525
- /** @internal */ _computedWidth = 0;
526
- /** @internal */ _computedHeight = 0;
527
- /** @internal */ _availableWidth = 0;
528
- /** @internal */ _availableHeight = 0;
529
- /** @internal */ _rawWidth;
530
- /** @internal */ _rawHeight;
531
- _layoutChildren = [];
532
- _layoutDirty = true;
533
- _layoutSuspended = false;
534
- constructor(config = {}) {
535
- super();
536
- this._config = {
537
- direction: config.direction ?? 'row',
538
- justifyContent: config.justifyContent ?? 'start',
539
- alignItems: config.alignItems ?? 'start',
540
- gap: config.gap ?? 0,
541
- flexWrap: config.flexWrap ?? false,
542
- alignContent: config.alignContent ?? 'start',
543
- };
544
- this._padding = resolvePadding(config);
545
- this._maxWidth = config.maxWidth ?? Infinity;
546
- this._maxHeight = config.maxHeight ?? Infinity;
547
- this._rawWidth = config.width ?? 0;
548
- this._rawHeight = config.height ?? 0;
549
- this._explicitWidth = typeof this._rawWidth === 'number' ? this._rawWidth : 0;
550
- this._explicitHeight = typeof this._rawHeight === 'number' ? this._rawHeight : 0;
551
- }
552
- // ─── Public API ──────────────────────────────────────
553
- /** Add a child with optional flex config. Also registers in flex layout. */
554
- addFlexChild(child, flexConfig) {
555
- if (flexConfig)
556
- child._flexConfig = flexConfig;
557
- if (!this._layoutChildren.includes(child)) {
558
- this._layoutChildren.push(child);
559
- this._layoutDirty = true;
560
- }
561
- super.addChild(child);
562
- return this;
563
- }
564
- /** Remove a child from flex layout and display list */
565
- removeFlexChild(child) {
566
- const idx = this._layoutChildren.indexOf(child);
567
- if (idx !== -1) {
568
- this._layoutChildren.splice(idx, 1);
569
- this._layoutDirty = true;
570
- }
571
- super.removeChild(child);
572
- return this;
573
- }
574
- /** Remove all flex children */
575
- clearFlexChildren() {
576
- for (const child of this._layoutChildren) {
577
- super.removeChild(child);
578
- }
579
- this._layoutChildren.length = 0;
580
- this._layoutDirty = true;
581
- return this;
582
- }
583
- /**
584
- * Override addChild so children automatically participate in flex layout.
585
- * This enables declarative usage from React JSX.
586
- */
587
- addChild(...children) {
588
- for (const child of children) {
589
- if (!this._layoutChildren.includes(child)) {
590
- this._layoutChildren.push(child);
591
- this._layoutDirty = true;
592
- }
593
- }
594
- const result = super.addChild(...children);
595
- if (this._layoutDirty && !this._layoutSuspended)
596
- this.updateLayout();
597
- return result;
598
- }
599
- addChildAt(child, index) {
600
- if (!this._layoutChildren.includes(child)) {
601
- // Insert into layout children at matching position
602
- const layoutIndex = Math.min(index, this._layoutChildren.length);
603
- this._layoutChildren.splice(layoutIndex, 0, child);
604
- this._layoutDirty = true;
605
- }
606
- const result = super.addChildAt(child, index);
607
- if (this._layoutDirty && !this._layoutSuspended)
608
- this.updateLayout();
609
- return result;
610
- }
611
- removeChild(...children) {
612
- for (const child of children) {
613
- const idx = this._layoutChildren.indexOf(child);
614
- if (idx !== -1) {
615
- this._layoutChildren.splice(idx, 1);
616
- this._layoutDirty = true;
617
- }
618
- }
619
- return super.removeChild(...children);
620
- }
621
- /** Get all flex layout children (read-only) */
622
- get flexChildren() {
623
- return this._layoutChildren;
624
- }
625
- /** Suspend automatic layout recalculation. Call resumeLayout() to flush. */
626
- suspendLayout() {
627
- this._layoutSuspended = true;
628
- }
629
- /** Resume automatic layout and flush if dirty. */
630
- resumeLayout() {
631
- this._layoutSuspended = false;
632
- if (this._layoutDirty)
633
- this.updateLayout();
634
- }
635
- /** Update the container size and recalculate layout */
636
- resize(width, height) {
637
- this._explicitWidth = width;
638
- this._explicitHeight = height;
639
- this._layoutDirty = true;
640
- if (!this._layoutSuspended)
641
- this.updateLayout();
642
- }
643
- /** Update layout direction */
644
- setDirection(direction) {
645
- this._config.direction = direction;
646
- this._layoutDirty = true;
647
- }
648
- /** Update justifyContent */
649
- setJustifyContent(justify) {
650
- this._config.justifyContent = justify;
651
- this._layoutDirty = true;
652
- }
653
- /** Update alignItems */
654
- setAlignItems(align) {
655
- this._config.alignItems = align;
656
- this._layoutDirty = true;
657
- }
658
- /** Update gap */
659
- setGap(gap) {
660
- this._config.gap = gap;
661
- this._layoutDirty = true;
662
- }
663
- /** Update padding */
664
- setPadding(padding) {
665
- this._padding = normalizePadding(padding);
666
- this._layoutDirty = true;
667
- }
668
- /**
669
- * Recalculate and apply layout positions for all children.
670
- * Called automatically by `resize()`. Call manually after
671
- * adding/removing children without resize.
672
- */
673
- updateLayout() {
674
- if (this._layoutSuspended) {
675
- this._layoutDirty = true;
676
- return;
677
- }
678
- this._layoutDirty = false;
679
- const { direction, justifyContent, alignItems, gap, flexWrap, alignContent } = this._config;
680
- const [pt, pr, pb, pl] = this._padding;
681
- const isRow = direction === 'row';
682
- // Resolve percentage width/height against parent's available space
683
- if (typeof this._rawWidth === 'string') {
684
- this._explicitWidth = resolveDimension(this._rawWidth, this._availableWidth) ?? 0;
685
- }
686
- if (typeof this._rawHeight === 'string') {
687
- this._explicitHeight = resolveDimension(this._rawHeight, this._availableHeight) ?? 0;
688
- }
689
- const contentW = this._explicitWidth > 0 ? this._explicitWidth - pl - pr : Infinity;
690
- const contentH = this._explicitHeight > 0 ? this._explicitHeight - pt - pb : Infinity;
691
- const mainLimit = isRow ? contentW : contentH;
692
- const crossLimit = isRow ? contentH : contentW;
693
- // Pass content area to measureChild for percentage resolution
694
- const pctRefW = contentW < Infinity ? contentW : 0;
695
- const pctRefH = contentH < Infinity ? contentH : 0;
696
- // Propagate available size to child FlexContainers and resolve their percentages
697
- for (const child of this._layoutChildren) {
698
- if (child instanceof FlexContainer) {
699
- const fc = child;
700
- fc._availableWidth = pctRefW;
701
- fc._availableHeight = pctRefH;
702
- // If child has percentage dimensions, trigger its layout to resolve them
703
- if (typeof fc._rawWidth === 'string' || typeof fc._rawHeight === 'string') {
704
- fc.updateLayout();
705
- }
706
- }
707
- }
708
- // Measure children (skip flexExclude — they position themselves)
709
- const measured = [];
710
- for (const child of this._layoutChildren) {
711
- if (child._flexConfig?.flexExclude)
712
- continue;
713
- const { w, h, ox, oy } = measureChild(child, pctRefW, pctRefH);
714
- measured.push({ child, w, h, ox, oy });
715
- }
716
- // Split into lines (if wrapping)
717
- const lines = [];
718
- if (flexWrap && mainLimit < Infinity) {
719
- let currentLine = [];
720
- let lineMain = 0;
721
- for (const item of measured) {
722
- const itemMain = isRow ? item.w : item.h;
723
- const wouldBe = lineMain + (currentLine.length > 0 ? gap : 0) + itemMain;
724
- if (currentLine.length > 0 && wouldBe > mainLimit) {
725
- lines.push(currentLine);
726
- currentLine = [item];
727
- lineMain = itemMain;
728
- }
729
- else {
730
- currentLine.push(item);
731
- lineMain = wouldBe;
732
- }
733
- }
734
- if (currentLine.length > 0)
735
- lines.push(currentLine);
736
- }
737
- else {
738
- lines.push(measured);
739
- }
740
- // Compute cross size per line
741
- const lineCrossSizes = lines.map((line) => {
742
- let maxCross = 0;
743
- for (const item of line) {
744
- const cross = isRow ? item.h : item.w;
745
- if (cross > maxCross)
746
- maxCross = cross;
747
- }
748
- return maxCross;
749
- });
750
- // Compute natural main size (for auto-sizing when no explicit size given)
751
- let naturalMainSize = 0;
752
- if (mainLimit === Infinity) {
753
- for (const line of lines) {
754
- let lineMain = 0;
755
- for (const item of line) {
756
- lineMain += isRow ? item.w : item.h;
757
- }
758
- lineMain += gap * Math.max(0, line.length - 1);
759
- naturalMainSize = Math.max(naturalMainSize, lineMain);
760
- }
761
- }
762
- // Effective main size: explicit if set, otherwise natural content size
763
- const effectiveMainSize = mainLimit < Infinity ? mainLimit : naturalMainSize;
764
- // Compute alignContent offsets for multi-line layouts
765
- const totalLinesCross = lineCrossSizes.reduce((s, v) => s + v, 0) + gap * Math.max(0, lines.length - 1);
766
- let acOffset = 0;
767
- let acExtraGap = 0;
768
- if (lines.length > 1 && crossLimit < Infinity) {
769
- const freeSpace = Math.max(0, crossLimit - totalLinesCross);
770
- switch (alignContent) {
771
- case 'center':
772
- acOffset = freeSpace / 2;
773
- break;
774
- case 'end':
775
- acOffset = freeSpace;
776
- break;
777
- case 'space-between':
778
- if (lines.length > 1) {
779
- acExtraGap = freeSpace / (lines.length - 1);
780
- }
781
- break;
782
- case 'stretch':
783
- if (lines.length > 0) {
784
- const extra = freeSpace / lines.length;
785
- for (let i = 0; i < lineCrossSizes.length; i++) {
786
- lineCrossSizes[i] += extra;
787
- }
788
- }
789
- break;
790
- // 'start' — no adjustment
791
- }
792
- }
793
- // Layout each line
794
- let crossOffset = (isRow ? pt : pl) + acOffset;
795
- for (let i = 0; i < lines.length; i++) {
796
- const line = lines[i];
797
- const lineCross = lineCrossSizes[i];
798
- const mainStart = isRow ? pl : pt;
799
- // Offset items by padding
800
- const tempItems = line.map((item) => ({ ...item }));
801
- // Cross size for alignment: use container cross size for single-line, line cross for multi-line
802
- const effectiveCross = lines.length === 1 && crossLimit < Infinity ? crossLimit : lineCross;
803
- layoutLine(tempItems, isRow, effectiveMainSize, mainLimit < Infinity ? justifyContent : 'start', alignItems, gap, crossOffset, effectiveCross);
804
- // Apply main-axis padding offset
805
- for (const item of tempItems) {
806
- const origChild = line.find((l) => l.child === item.child);
807
- origChild.child.x = item.child.x + (isRow ? mainStart : 0);
808
- origChild.child.y = item.child.y + (isRow ? 0 : mainStart);
809
- }
810
- crossOffset += lineCross + gap + acExtraGap;
811
- }
812
- // Compute and store actual dimensions for measureChild() and getContentSize()
813
- let totalCrossNatural = 0;
814
- for (let i = 0; i < lineCrossSizes.length; i++) {
815
- totalCrossNatural += lineCrossSizes[i];
816
- if (i < lineCrossSizes.length - 1)
817
- totalCrossNatural += gap;
818
- }
819
- if (isRow) {
820
- this._computedWidth = this._explicitWidth > 0 ? this._explicitWidth : (pl + naturalMainSize + pr);
821
- this._computedHeight = this._explicitHeight > 0 ? this._explicitHeight : (pt + totalCrossNatural + pb);
822
- }
823
- else {
824
- this._computedWidth = this._explicitWidth > 0 ? this._explicitWidth : (pl + totalCrossNatural + pr);
825
- this._computedHeight = this._explicitHeight > 0 ? this._explicitHeight : (pt + naturalMainSize + pb);
826
- }
827
- // Position flexExclude children (absolute positioning).
828
- // All position props describe the visual (bounds) rectangle. We derive the
829
- // visual rectangle directly from `getLocalBounds()` rather than the
830
- // layout-config `w`/`h` returned by measureChild — those may differ from
831
- // actual bounds when the user pins `layoutWidth`/`layoutHeight` to a value
832
- // that doesn't match the child's real visual extent (e.g. a Button whose
833
- // text overflows its configured `width`). Mixing layout size with real
834
- // bounds-origin would shift the visual center off the requested point.
835
- // `centerX/centerY` take precedence over `left/right` / `top/bottom` on each axis.
836
- for (const child of this._layoutChildren) {
837
- if (!child._flexConfig?.flexExclude)
838
- continue;
839
- const cfg = child._flexConfig;
840
- const bounds = child.getLocalBounds();
841
- const cw = this._computedWidth;
842
- const ch = this._computedHeight;
843
- const centerX = resolveDimension(cfg.centerX, pctRefW);
844
- if (centerX !== undefined)
845
- child.x = centerX - bounds.x - bounds.width / 2;
846
- else if (cfg.left !== undefined)
847
- child.x = cfg.left - bounds.x;
848
- else if (cfg.right !== undefined)
849
- child.x = cw - cfg.right - bounds.x - bounds.width;
850
- const centerY = resolveDimension(cfg.centerY, pctRefH);
851
- if (centerY !== undefined)
852
- child.y = centerY - bounds.y - bounds.height / 2;
853
- else if (cfg.top !== undefined)
854
- child.y = cfg.top - bounds.y;
855
- else if (cfg.bottom !== undefined)
856
- child.y = ch - cfg.bottom - bounds.y - bounds.height;
857
- }
858
- }
859
- /** Computed content size (after layout) */
860
- getContentSize() {
861
- if (this._layoutDirty)
862
- this.updateLayout();
863
- return { width: this._computedWidth, height: this._computedHeight };
864
- }
865
- /** React reconciler update hook — applies changed config props */
866
- updateConfig(changed) {
867
- if ('direction' in changed)
868
- this.setDirection(changed.direction);
869
- if ('justifyContent' in changed)
870
- this.setJustifyContent(changed.justifyContent);
871
- if ('alignItems' in changed)
872
- this.setAlignItems(changed.alignItems);
873
- if ('gap' in changed)
874
- this.setGap(changed.gap);
875
- if ('padding' in changed || 'paddingTop' in changed || 'paddingRight' in changed || 'paddingBottom' in changed || 'paddingLeft' in changed) {
876
- this._padding = resolvePadding(changed);
877
- this._layoutDirty = true;
878
- }
879
- if ('flexWrap' in changed) {
880
- this._config.flexWrap = changed.flexWrap;
881
- this._layoutDirty = true;
882
- }
883
- if ('alignContent' in changed) {
884
- this._config.alignContent = changed.alignContent;
885
- this._layoutDirty = true;
886
- }
887
- if ('width' in changed || 'height' in changed) {
888
- const w = changed.width ?? this._rawWidth;
889
- const h = changed.height ?? this._rawHeight;
890
- this._rawWidth = w;
891
- this._rawHeight = h;
892
- if (typeof w === 'number' && typeof h === 'number') {
893
- this.resize(w, h);
894
- }
895
- else {
896
- // Percentage — will resolve in updateLayout
897
- this._explicitWidth = typeof w === 'number' ? w : 0;
898
- this._explicitHeight = typeof h === 'number' ? h : 0;
899
- this._layoutDirty = true;
900
- if (!this._layoutSuspended)
901
- this.updateLayout();
902
- }
903
- return;
904
- }
905
- if (this._layoutDirty && !this._layoutSuspended)
906
- this.updateLayout();
907
- }
908
- destroy(options) {
909
- this._layoutChildren.length = 0;
910
- super.destroy(options);
911
- }
912
- }
913
-
914
- /** Flex item prop names that should be forwarded to _flexConfig on the child */
915
- const FLEX_ITEM_PROPS = ['flexGrow', 'flexShrink', 'layoutWidth', 'layoutHeight', 'alignSelf', 'flexExclude', 'top', 'right', 'bottom', 'left', 'centerX', 'centerY'];
916
- function isSuspendable(obj) {
917
- return typeof obj?.suspendLayout === 'function' && typeof obj?.resumeLayout === 'function';
918
- }
919
- /** Layout containers that need flush after commit phase */
920
- const pendingLayoutFlush = new Set();
921
- /** Suspend a layout container and all its suspendable ancestors, add them to pending flush */
922
- function suspendWithAncestors(instance) {
923
- let current = instance;
924
- while (current) {
925
- if (isSuspendable(current)) {
926
- current.suspendLayout();
927
- pendingLayoutFlush.add(current);
928
- }
929
- current = current.parent;
930
- }
931
- }
932
- /** Extract FlexItemConfig from props if any flex item props are present */
933
- function extractFlexItemConfig(props) {
934
- let config;
935
- for (const key of FLEX_ITEM_PROPS) {
936
- if (key in props) {
937
- if (!config)
938
- config = {};
939
- config[key] = props[key];
940
- }
941
- }
942
- return config;
943
- }
944
- /** Apply flex item config to a child being added to a FlexContainer */
945
- function addChildToFlex(parent, child) {
946
- const flexConfig = child._flexConfig;
947
- if (flexConfig && Object.keys(flexConfig).length > 0) {
948
- parent.addFlexChild(child, flexConfig);
949
- }
950
- else {
951
- parent.addChild(child);
952
- }
953
- }
954
- function toPascalCase(str) {
955
- return str.charAt(0).toUpperCase() + str.slice(1);
956
- }
957
- const hostConfig = {
958
- isPrimaryRenderer: false,
959
- supportsMutation: true,
960
- supportsPersistence: false,
961
- supportsHydration: false,
962
- createInstance(type, props) {
963
- const name = toPascalCase(type);
964
- const Ctor = catalogue[name];
965
- if (!Ctor) {
966
- throw new Error(`[PixiReconciler] Unknown element "<${type}>". ` +
967
- `Call extend({ ${name} }) before rendering.`);
968
- }
969
- let instance;
970
- if (typeof Ctor.prototype.updateConfig === 'function') {
971
- // Config-based UI component: pass props as constructor config
972
- const config = extractConfig(props);
973
- instance = new Ctor(config);
974
- applyContainerProps(instance, props);
975
- applyEventProps(instance, props);
976
- }
977
- else {
978
- // Standard PixiJS element
979
- instance = new Ctor();
980
- applyProps(instance, props);
981
- }
982
- if (hasEventProps(props) && instance.eventMode === 'auto') {
983
- instance.eventMode = 'static';
984
- }
985
- // Store flex item config for when this child is added to a FlexContainer parent
986
- const flexItemConfig = extractFlexItemConfig(props);
987
- if (flexItemConfig) {
988
- instance._flexConfig = { ...instance._flexConfig, ...flexItemConfig };
989
- }
990
- // Auto-set layoutWidth/layoutHeight from explicit width/height props for UI components.
991
- // This ensures parent FlexContainers measure children correctly without relying on
992
- // getLocalBounds() which may return wrong values before the first render pass
993
- // (e.g. Text with unloaded fonts, Graphics with pending geometry).
994
- if (typeof Ctor.prototype.updateConfig === 'function' && !(instance instanceof FlexContainer)) {
995
- const w = typeof props.width === 'number' ? props.width : undefined;
996
- const h = typeof props.height === 'number' ? props.height : undefined;
997
- if (w !== undefined || h !== undefined) {
998
- if (!instance._flexConfig)
999
- instance._flexConfig = {};
1000
- if (w !== undefined && instance._flexConfig.layoutWidth === undefined) {
1001
- instance._flexConfig.layoutWidth = w;
1002
- }
1003
- if (h !== undefined && instance._flexConfig.layoutHeight === undefined) {
1004
- instance._flexConfig.layoutHeight = h;
1005
- }
1006
- }
1007
- }
1008
- return instance;
1009
- },
1010
- createTextInstance() {
1011
- throw new Error('[PixiReconciler] Text strings are not supported. Use a <text> element.');
1012
- },
1013
- appendInitialChild(parent, child) {
1014
- if (child instanceof pixi_js.Container) {
1015
- if (isSuspendable(parent))
1016
- parent.suspendLayout();
1017
- if (parent instanceof FlexContainer) {
1018
- addChildToFlex(parent, child);
1019
- }
1020
- else {
1021
- parent.addChild(child);
1022
- }
1023
- }
1024
- },
1025
- appendChild(parent, child) {
1026
- if (child instanceof pixi_js.Container) {
1027
- if (isSuspendable(parent)) {
1028
- parent.suspendLayout();
1029
- pendingLayoutFlush.add(parent);
1030
- }
1031
- if (parent instanceof FlexContainer) {
1032
- addChildToFlex(parent, child);
1033
- }
1034
- else {
1035
- parent.addChild(child);
1036
- }
1037
- }
1038
- },
1039
- appendChildToContainer(container, child) {
1040
- if (child instanceof pixi_js.Container)
1041
- container.addChild(child);
1042
- },
1043
- removeChild(parent, child) {
1044
- if (child instanceof pixi_js.Container) {
1045
- if (isSuspendable(parent)) {
1046
- parent.suspendLayout();
1047
- pendingLayoutFlush.add(parent);
1048
- }
1049
- parent.removeChild(child);
1050
- child.destroy({ children: true });
1051
- }
1052
- },
1053
- removeChildFromContainer(container, child) {
1054
- if (child instanceof pixi_js.Container) {
1055
- container.removeChild(child);
1056
- child.destroy({ children: true });
1057
- }
1058
- },
1059
- insertBefore(parent, child, beforeChild) {
1060
- if (child instanceof pixi_js.Container && beforeChild instanceof pixi_js.Container) {
1061
- if (child.parent)
1062
- child.parent.removeChild(child);
1063
- if (isSuspendable(parent)) {
1064
- parent.suspendLayout();
1065
- pendingLayoutFlush.add(parent);
1066
- }
1067
- const index = parent.getChildIndex(beforeChild);
1068
- parent.addChildAt(child, index);
1069
- }
1070
- },
1071
- insertInContainerBefore(container, child, beforeChild) {
1072
- if (child instanceof pixi_js.Container && beforeChild instanceof pixi_js.Container) {
1073
- if (child.parent)
1074
- child.parent.removeChild(child);
1075
- const index = container.getChildIndex(beforeChild);
1076
- container.addChildAt(child, index);
1077
- }
1078
- },
1079
- commitUpdate(instance, _updatePayload, _type, oldProps, newProps) {
1080
- // Suspend this instance and ancestors before applying changes —
1081
- // prevents intermediate relayouts with partially-updated tree
1082
- const dimensionsChanged = newProps.width !== oldProps.width || newProps.height !== oldProps.height;
1083
- if (isSuspendable(instance) || dimensionsChanged) {
1084
- suspendWithAncestors(instance);
1085
- }
1086
- if (typeof instance.updateConfig === 'function') {
1087
- const changed = diffConfig(newProps, oldProps);
1088
- if (Object.keys(changed).length > 0) {
1089
- instance.updateConfig(changed);
1090
- }
1091
- applyContainerProps(instance, newProps, oldProps);
1092
- applyEventProps(instance, newProps, oldProps);
1093
- }
1094
- else {
1095
- applyProps(instance, newProps, oldProps);
1096
- }
1097
- // Update flex item config if parent is FlexContainer
1098
- const newFlexConfig = extractFlexItemConfig(newProps);
1099
- const oldFlexConfig = extractFlexItemConfig(oldProps);
1100
- if (newFlexConfig || oldFlexConfig) {
1101
- instance._flexConfig = { ...instance._flexConfig, ...newFlexConfig };
1102
- }
1103
- // Keep auto layoutWidth/layoutHeight in sync with width/height for UI components
1104
- if (typeof instance.updateConfig === 'function' && !(instance instanceof FlexContainer)) {
1105
- if (instance._flexConfig) {
1106
- if (typeof newProps.width === 'number' && instance._flexConfig.layoutWidth !== undefined) {
1107
- instance._flexConfig.layoutWidth = newProps.width;
1108
- }
1109
- if (typeof newProps.height === 'number' && instance._flexConfig.layoutHeight !== undefined) {
1110
- instance._flexConfig.layoutHeight = newProps.height;
1111
- }
1112
- }
1113
- }
1114
- // Mark ancestors dirty if flex config or dimensions changed
1115
- if (newFlexConfig || oldFlexConfig || dimensionsChanged) {
1116
- suspendWithAncestors(instance);
1117
- }
1118
- if (hasEventProps(newProps) && instance.eventMode === 'auto') {
1119
- instance.eventMode = 'static';
1120
- }
1121
- },
1122
- finalizeInitialChildren(instance) {
1123
- // Resume layout after all initial children have been appended
1124
- if (isSuspendable(instance)) {
1125
- instance.resumeLayout();
1126
- }
1127
- return false;
1128
- },
1129
- prepareUpdate() {
1130
- return true;
1131
- },
1132
- shouldSetTextContent() {
1133
- return false;
1134
- },
1135
- getRootHostContext() {
1136
- return null;
1137
- },
1138
- getChildHostContext(parentHostContext) {
1139
- return parentHostContext;
1140
- },
1141
- getPublicInstance(instance) {
1142
- return instance;
1143
- },
1144
- prepareForCommit() {
1145
- return null;
1146
- },
1147
- resetAfterCommit() {
1148
- if (pendingLayoutFlush.size === 0)
1149
- return;
1150
- // Sort by depth (deepest first) so children compute sizes before parents lay out
1151
- const sorted = [...pendingLayoutFlush].sort((a, b) => {
1152
- let da = 0;
1153
- let n = a;
1154
- while (n.parent) {
1155
- da++;
1156
- n = n.parent;
1157
- }
1158
- let db = 0;
1159
- n = b;
1160
- while (n.parent) {
1161
- db++;
1162
- n = n.parent;
1163
- }
1164
- return db - da; // deepest first
1165
- });
1166
- for (const fc of sorted) {
1167
- fc.resumeLayout();
1168
- }
1169
- pendingLayoutFlush.clear();
1170
- },
1171
- preparePortalMount() { },
1172
- scheduleTimeout: setTimeout,
1173
- cancelTimeout: clearTimeout,
1174
- noTimeout: -1,
1175
- getCurrentEventPriority() {
1176
- return constants.DefaultEventPriority;
1177
- },
1178
- hideInstance(instance) {
1179
- instance.visible = false;
1180
- },
1181
- unhideInstance(instance) {
1182
- instance.visible = true;
1183
- },
1184
- hideTextInstance() { },
1185
- unhideTextInstance() { },
1186
- clearContainer() { },
1187
- detachDeletedInstance() { },
1188
- prepareScopeUpdate() { },
1189
- getInstanceFromNode() { return null; },
1190
- getInstanceFromScope() { return null; },
1191
- beforeActiveInstanceBlur() { },
1192
- afterActiveInstanceBlur() { },
1193
- };
1194
- const reconciler = Reconciler(hostConfig);
1195
-
1196
- function createPixiRoot(container) {
1197
- const fiberRoot = reconciler.createContainer(container, // containerInfo
1198
- constants.ConcurrentRoot, // tag
1199
- null, // hydrationCallbacks
1200
- false, // isStrictMode
1201
- null, // concurrentUpdatesByDefaultOverride
1202
- '', // identifierPrefix
1203
- (err) => console.error('[PixiRoot]', err), null);
1204
- return {
1205
- render(element) {
1206
- reconciler.updateContainer(element, fiberRoot, null, () => { });
1207
- },
1208
- unmount() {
1209
- reconciler.updateContainer(null, fiberRoot, null, () => { });
1210
- },
1211
- };
1212
- }
1213
-
1214
- /**
1215
- * Resolve a ViewInput to a Container instance.
1216
- *
1217
- * @example
1218
- * ```ts
1219
- * resolveView('btn-idle') // → Sprite.from('btn-idle')
1220
- * resolveView(someTexture) // → new Sprite(someTexture)
1221
- * resolveView(myCustomContainer) // → myCustomContainer (as-is)
1222
- * resolveView(undefined) // → null
1223
- * ```
1224
- */
1225
- function resolveView(input) {
1226
- if (input == null)
1227
- return null;
1228
- if (typeof input === 'string')
1229
- return pixi_js.Sprite.from(input);
1230
- if (input instanceof pixi_js.Texture)
1231
- return new pixi_js.Sprite(input);
1232
- return input;
1233
- }
1234
-
1235
- /**
1236
- * Collection of easing functions for use with Tween and Timeline.
1237
- *
1238
- * All functions take a progress value t (0..1) and return the eased value.
1239
- */
1240
- const Easing = {
1241
- easeOutQuad: (t) => t * (2 - t),
1242
- easeInCubic: (t) => t * t * t,
1243
- easeOutCubic: (t) => --t * t * t + 1,
1244
- easeOutBack: (t) => {
1245
- const c1 = 1.70158;
1246
- const c3 = c1 + 1;
1247
- return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2);
1248
- }};
1249
-
1250
- /**
1251
- * Lightweight tween system integrated with PixiJS Ticker.
1252
- * Zero external dependencies — no GSAP required.
1253
- *
1254
- * All tweens return a Promise that resolves on completion.
1255
- *
1256
- * @example
1257
- * ```ts
1258
- * // Fade in a sprite
1259
- * await Tween.to(sprite, { alpha: 1, y: 100 }, 500, Easing.easeOutBack);
1260
- *
1261
- * // Move and wait
1262
- * await Tween.to(sprite, { x: 500 }, 300);
1263
- *
1264
- * // From a starting value
1265
- * await Tween.from(sprite, { scale: 0, alpha: 0 }, 400);
1266
- * ```
1267
- */
1268
- class Tween {
1269
- static _tweens = [];
1270
- static _tickerAdded = false;
1271
- /**
1272
- * Animate properties from current values to target values.
1273
- *
1274
- * @param target - Object to animate (Sprite, Container, etc.)
1275
- * @param props - Target property values
1276
- * @param duration - Duration in milliseconds
1277
- * @param easing - Easing function (default: easeOutQuad)
1278
- * @param onUpdate - Progress callback (0..1)
1279
- */
1280
- static to(target, props, duration, easing, onUpdate) {
1281
- return new Promise((resolve) => {
1282
- // Capture starting values
1283
- const from = {};
1284
- for (const key of Object.keys(props)) {
1285
- from[key] = Tween.getProperty(target, key);
1286
- }
1287
- const tween = {
1288
- target,
1289
- from,
1290
- to: { ...props },
1291
- duration: Math.max(1, duration),
1292
- easing: easing ?? Easing.easeOutQuad,
1293
- elapsed: 0,
1294
- delay: 0,
1295
- resolve,
1296
- onUpdate,
1297
- };
1298
- Tween._tweens.push(tween);
1299
- Tween.ensureTicker();
1300
- });
1301
- }
1302
- /**
1303
- * Animate properties from given values to current values.
1304
- */
1305
- static from(target, props, duration, easing, onUpdate) {
1306
- // Capture current values as "to"
1307
- const to = {};
1308
- for (const key of Object.keys(props)) {
1309
- to[key] = Tween.getProperty(target, key);
1310
- Tween.setProperty(target, key, props[key]);
1311
- }
1312
- return Tween.to(target, to, duration, easing, onUpdate);
1313
- }
1314
- /**
1315
- * Animate from one set of values to another.
1316
- */
1317
- static fromTo(target, fromProps, toProps, duration, easing, onUpdate) {
1318
- // Set starting values
1319
- for (const key of Object.keys(fromProps)) {
1320
- Tween.setProperty(target, key, fromProps[key]);
1321
- }
1322
- return Tween.to(target, toProps, duration, easing, onUpdate);
1323
- }
1324
- /**
1325
- * Wait for a given duration (useful in timelines).
1326
- * Uses PixiJS Ticker for consistent timing with other tweens.
1327
- */
1328
- static delay(ms) {
1329
- return new Promise((resolve) => {
1330
- let elapsed = 0;
1331
- const onTick = (ticker) => {
1332
- elapsed += ticker.deltaMS;
1333
- if (elapsed >= ms) {
1334
- pixi_js.Ticker.shared.remove(onTick);
1335
- resolve();
1336
- }
1337
- };
1338
- pixi_js.Ticker.shared.add(onTick);
1339
- });
1340
- }
1341
- /**
1342
- * Kill all tweens on a target.
1343
- */
1344
- static killTweensOf(target) {
1345
- Tween._tweens = Tween._tweens.filter((tw) => {
1346
- if (tw.target === target) {
1347
- tw.resolve();
1348
- return false;
1349
- }
1350
- return true;
1351
- });
1352
- }
1353
- /**
1354
- * Kill all active tweens.
1355
- */
1356
- static killAll() {
1357
- for (const tw of Tween._tweens) {
1358
- tw.resolve();
1359
- }
1360
- Tween._tweens.length = 0;
1361
- }
1362
- /** Number of active tweens */
1363
- static get activeTweens() {
1364
- return Tween._tweens.length;
1365
- }
1366
- /**
1367
- * Reset the tween system — kill all tweens and remove the ticker.
1368
- * Useful for cleanup between game instances, tests, or hot-reload.
1369
- */
1370
- static reset() {
1371
- for (const tw of Tween._tweens) {
1372
- tw.resolve();
1373
- }
1374
- Tween._tweens.length = 0;
1375
- if (Tween._tickerAdded) {
1376
- pixi_js.Ticker.shared.remove(Tween.tick);
1377
- Tween._tickerAdded = false;
1378
- }
1379
- }
1380
- // ─── Internal ──────────────────────────────────────────
1381
- static ensureTicker() {
1382
- if (Tween._tickerAdded)
1383
- return;
1384
- Tween._tickerAdded = true;
1385
- pixi_js.Ticker.shared.add(Tween.tick);
1386
- }
1387
- static tick = (ticker) => {
1388
- const dt = ticker.deltaMS;
1389
- const completed = [];
1390
- for (const tw of Tween._tweens) {
1391
- tw.elapsed += dt;
1392
- if (tw.elapsed < tw.delay)
1393
- continue;
1394
- const raw = Math.min((tw.elapsed - tw.delay) / tw.duration, 1);
1395
- const t = tw.easing(raw);
1396
- // Interpolate each property
1397
- for (const key of Object.keys(tw.to)) {
1398
- const start = tw.from[key];
1399
- const end = tw.to[key];
1400
- const value = start + (end - start) * t;
1401
- Tween.setProperty(tw.target, key, value);
1402
- }
1403
- tw.onUpdate?.(raw);
1404
- if (raw >= 1) {
1405
- completed.push(tw);
1406
- }
1407
- }
1408
- // Remove completed tweens
1409
- for (const tw of completed) {
1410
- const idx = Tween._tweens.indexOf(tw);
1411
- if (idx !== -1)
1412
- Tween._tweens.splice(idx, 1);
1413
- tw.resolve();
1414
- }
1415
- // Remove ticker when no active tweens
1416
- if (Tween._tweens.length === 0 && Tween._tickerAdded) {
1417
- pixi_js.Ticker.shared.remove(Tween.tick);
1418
- Tween._tickerAdded = false;
1419
- }
1420
- };
1421
- /**
1422
- * Get a potentially nested property (supports 'scale.x', 'position.y', etc.)
1423
- */
1424
- static getProperty(target, key) {
1425
- const parts = key.split('.');
1426
- let obj = target;
1427
- for (let i = 0; i < parts.length - 1; i++) {
1428
- obj = obj[parts[i]];
1429
- }
1430
- return obj[parts[parts.length - 1]] ?? 0;
1431
- }
1432
- /**
1433
- * Set a potentially nested property.
1434
- */
1435
- static setProperty(target, key, value) {
1436
- const parts = key.split('.');
1437
- let obj = target;
1438
- for (let i = 0; i < parts.length - 1; i++) {
1439
- obj = obj[parts[i]];
1440
- }
1441
- obj[parts[parts.length - 1]] = value;
1442
- }
1443
- }
1444
-
1445
- const DEFAULT_COLORS = {
1446
- default: 0xffd700,
1447
- hover: 0xffe44d,
1448
- pressed: 0xccac00,
1449
- disabled: 0x666666,
1450
- };
1451
- function makeGraphicsView(w, h, radius, color) {
1452
- const g = new pixi_js.Graphics();
1453
- g.roundRect(-w / 2, -h / 2, w, h, radius).fill(color);
1454
- return g;
1455
- }
1456
- /**
1457
- * Interactive button with per-state custom views and animations.
1458
- *
1459
- * Each visual state accepts a `ViewInput`: texture name, Texture, or any Container
1460
- * (Sprite, NineSliceSprite, AnimatedSprite, custom artwork, etc).
1461
- * Falls back to colored Graphics when no custom view is provided.
1462
- *
1463
- * @example
1464
- * ```ts
1465
- * // Graphics-based (quick prototyping)
1466
- * const btn = new Button({
1467
- * width: 200, height: 60, borderRadius: 12,
1468
- * colors: { default: 0x22aa22, hover: 0x33cc33 },
1469
- * text: 'SPIN',
1470
- * onPress: () => spin(),
1471
- * });
1472
- *
1473
- * // Asset-based (production art)
1474
- * const btn = new Button({
1475
- * defaultView: 'btn-idle',
1476
- * hoverView: 'btn-hover',
1477
- * pressedView: 'btn-pressed',
1478
- * disabledView: 'btn-disabled',
1479
- * text: 'SPIN',
1480
- * onPress: () => spin(),
1481
- * });
1482
- *
1483
- * // Custom Container view
1484
- * const btn = new Button({
1485
- * defaultView: myAnimatedSprite,
1486
- * text: 'SPIN',
1487
- * });
1488
- * ```
1489
- */
1490
- class Button extends pixi_js.Container {
1491
- __uiComponent = true;
1492
- _views = new Map();
1493
- _state = 'default';
1494
- _enabled = true;
1495
- _config;
1496
- _textObj = null;
1497
- /** Press callback */
1498
- onPress;
1499
- constructor(config = {}) {
1500
- super();
1501
- this._config = {
1502
- width: config.width ?? 200,
1503
- height: config.height ?? 60,
1504
- borderRadius: config.borderRadius ?? 8,
1505
- pressScale: config.pressScale ?? 0.95,
1506
- animationDuration: config.animationDuration ?? 100,
1507
- ...config,
1508
- };
1509
- this.onPress = config.onPress;
1510
- this._buildViews(config);
1511
- // Text
1512
- if (config.text) {
1513
- this._textObj = new pixi_js.Text({
1514
- text: config.text,
1515
- style: {
1516
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
1517
- fontSize: 20,
1518
- fill: 0xffffff,
1519
- fontWeight: 'bold',
1520
- ...config.textStyle,
1521
- },
1522
- });
1523
- this._textObj.anchor.set(0.5);
1524
- this.addChild(this._textObj);
1525
- }
1526
- // Interaction
1527
- this.eventMode = 'static';
1528
- this.cursor = 'pointer';
1529
- this.on('pointerover', this._onPointerOver, this);
1530
- this.on('pointerout', this._onPointerOut, this);
1531
- this.on('pointerdown', this._onPointerDown, this);
1532
- this.on('pointerup', this._onPointerUp, this);
1533
- this.on('pointerupoutside', this._onPointerUpOutside, this);
1534
- if (config.disabled) {
1535
- this.enabled = false;
1536
- }
1537
- }
1538
- /** Current button state */
1539
- get state() {
1540
- return this._state;
1541
- }
1542
- /** Enable the button */
1543
- enable() {
1544
- this.enabled = true;
1545
- }
1546
- /** Disable the button */
1547
- disable() {
1548
- this.enabled = false;
1549
- }
1550
- /** Whether the button is enabled */
1551
- get enabled() {
1552
- return this._enabled;
1553
- }
1554
- set enabled(value) {
1555
- this._enabled = value;
1556
- this.cursor = value ? 'pointer' : 'default';
1557
- this.eventMode = value ? 'static' : 'none';
1558
- this._setState(value ? 'default' : 'disabled');
1559
- }
1560
- /** Whether the button is disabled */
1561
- get disabled() {
1562
- return !this._enabled;
1563
- }
1564
- /** Update button text */
1565
- set text(value) {
1566
- if (this._textObj) {
1567
- this._textObj.text = value;
1568
- }
1569
- }
1570
- // ─── View building ──────────────────────────────────
1571
- _buildViews(config) {
1572
- const colorMap = { ...DEFAULT_COLORS, ...config.colors };
1573
- const { width, height, borderRadius } = this._config;
1574
- const stateViews = {
1575
- default: config.defaultView,
1576
- hover: config.hoverView,
1577
- pressed: config.pressedView,
1578
- disabled: config.disabledView,
1579
- };
1580
- const states = ['default', 'hover', 'pressed', 'disabled'];
1581
- for (const state of states) {
1582
- const customView = resolveView(stateViews[state]);
1583
- const view = customView ?? makeGraphicsView(width, height, borderRadius, colorMap[state]);
1584
- view.visible = state === 'default';
1585
- this._views.set(state, view);
1586
- this.addChild(view);
1587
- }
1588
- }
1589
- _rebuildViews() {
1590
- for (const [, view] of this._views) {
1591
- this.removeChild(view);
1592
- view.destroy();
1593
- }
1594
- this._views.clear();
1595
- this._buildViews(this._config);
1596
- // Re-insert views before text
1597
- if (this._textObj && this._textObj.parent === this) {
1598
- this.setChildIndex(this._textObj, this.children.length - 1);
1599
- }
1600
- }
1601
- // ─── State management ───────────────────────────────
1602
- _setState(state) {
1603
- if (this._state === state)
1604
- return;
1605
- this._state = state;
1606
- for (const [s, view] of this._views) {
1607
- view.visible = s === state;
1608
- }
1609
- }
1610
- _onPointerOver() {
1611
- if (!this._enabled)
1612
- return;
1613
- this._setState('hover');
1614
- Tween.killTweensOf(this);
1615
- Tween.to(this, { 'scale.x': 1.03, 'scale.y': 1.03 }, this._config.animationDuration, Easing.easeOutQuad);
1616
- }
1617
- _onPointerOut() {
1618
- if (!this._enabled)
1619
- return;
1620
- this._setState('default');
1621
- Tween.killTweensOf(this);
1622
- Tween.to(this, { 'scale.x': 1, 'scale.y': 1 }, this._config.animationDuration, Easing.easeOutQuad);
1623
- }
1624
- _onPointerDown() {
1625
- if (!this._enabled)
1626
- return;
1627
- this._setState('pressed');
1628
- Tween.killTweensOf(this);
1629
- const s = this._config.pressScale;
1630
- Tween.to(this, { 'scale.x': s, 'scale.y': s }, this._config.animationDuration, Easing.easeOutQuad);
1631
- }
1632
- _onPointerUp() {
1633
- if (!this._enabled)
1634
- return;
1635
- this._setState('hover');
1636
- Tween.killTweensOf(this);
1637
- Tween.to(this, { 'scale.x': 1.03, 'scale.y': 1.03 }, this._config.animationDuration, Easing.easeOutQuad);
1638
- this.onPress?.();
1639
- }
1640
- _onPointerUpOutside() {
1641
- if (!this._enabled)
1642
- return;
1643
- this._setState('default');
1644
- Tween.killTweensOf(this);
1645
- Tween.to(this, { 'scale.x': 1, 'scale.y': 1 }, this._config.animationDuration, Easing.easeOutQuad);
1646
- }
1647
- /** React reconciler update hook */
1648
- updateConfig(changed) {
1649
- if ('text' in changed && this._textObj)
1650
- this._textObj.text = changed.text;
1651
- if ('disabled' in changed)
1652
- this.enabled = !changed.disabled;
1653
- if ('onPress' in changed)
1654
- this.onPress = changed.onPress;
1655
- const structural = [
1656
- 'colors', 'width', 'height', 'borderRadius', 'textStyle',
1657
- 'defaultView', 'hoverView', 'pressedView', 'disabledView',
1658
- ];
1659
- const needsRebuild = structural.some((k) => k in changed);
1660
- if (needsRebuild) {
1661
- Object.assign(this._config, changed);
1662
- this._rebuildViews();
1663
- }
1664
- }
1665
- destroy(options) {
1666
- Tween.killTweensOf(this);
1667
- this.off('pointerover', this._onPointerOver, this);
1668
- this.off('pointerout', this._onPointerOut, this);
1669
- this.off('pointerdown', this._onPointerDown, this);
1670
- this.off('pointerup', this._onPointerUp, this);
1671
- this.off('pointerupoutside', this._onPointerUpOutside, this);
1672
- this._views.clear();
1673
- this._textObj = null;
1674
- super.destroy(options);
1675
- }
1676
- }
1677
-
1678
- /**
1679
- * Horizontal progress bar with optional custom track/fill views.
1680
- *
1681
- * Supports asset-based skinning: provide `trackView` and/or `fillView`
1682
- * as texture names, Textures, or any Container (NineSliceSprite, custom artwork, etc).
1683
- * Falls back to colored Graphics when no custom views are provided.
1684
- *
1685
- * @example
1686
- * ```ts
1687
- * // Graphics-based (quick prototyping)
1688
- * const bar = new ProgressBar({ width: 300, height: 20, fillColor: 0x22cc22 });
1689
- * bar.progress = 0.5;
1690
- *
1691
- * // Asset-based (production art)
1692
- * const bar = new ProgressBar({
1693
- * width: 300, height: 20,
1694
- * trackView: 'bar-track',
1695
- * fillView: new NineSliceSprite({ texture: 'bar-fill', ... }),
1696
- * });
1697
- * bar.progress = 0.75;
1698
- * ```
1699
- */
1700
- class ProgressBar extends pixi_js.Container {
1701
- __uiComponent = true;
1702
- _track;
1703
- _fill;
1704
- _fillMask;
1705
- _borderGfx;
1706
- _config;
1707
- _progress = 0;
1708
- _displayedProgress = 0;
1709
- constructor(config = {}) {
1710
- super();
1711
- this._config = {
1712
- width: config.width ?? 300,
1713
- height: config.height ?? 16,
1714
- borderRadius: config.borderRadius ?? 8,
1715
- fillColor: config.fillColor ?? 0xffd700,
1716
- trackColor: config.trackColor ?? 0x333333,
1717
- borderColor: config.borderColor ?? 0x555555,
1718
- borderWidth: config.borderWidth ?? 1,
1719
- animated: config.animated ?? true,
1720
- animationSpeed: config.animationSpeed ?? 0.1,
1721
- };
1722
- const { width, height, borderRadius, fillColor, trackColor, borderColor, borderWidth } = this._config;
1723
- // Track background — custom view or Graphics
1724
- const customTrack = resolveView(config.trackView);
1725
- if (customTrack) {
1726
- customTrack.width = width;
1727
- customTrack.height = height;
1728
- this._track = customTrack;
1729
- }
1730
- else {
1731
- const g = new pixi_js.Graphics();
1732
- g.roundRect(0, 0, width, height, borderRadius).fill(trackColor);
1733
- this._track = g;
1734
- }
1735
- this.addChild(this._track);
1736
- // Fill bar — custom view or Graphics
1737
- const customFill = resolveView(config.fillView);
1738
- if (customFill) {
1739
- customFill.x = borderWidth;
1740
- customFill.y = borderWidth;
1741
- customFill.width = width - borderWidth * 2;
1742
- customFill.height = height - borderWidth * 2;
1743
- this._fill = customFill;
1744
- }
1745
- else {
1746
- const g = new pixi_js.Graphics();
1747
- g.roundRect(borderWidth, borderWidth, width - borderWidth * 2, height - borderWidth * 2, Math.max(0, borderRadius - 1)).fill(fillColor);
1748
- this._fill = g;
1749
- }
1750
- this.addChild(this._fill);
1751
- // Mask for the fill (controls visible width)
1752
- this._fillMask = new pixi_js.Graphics();
1753
- this._fillMask.rect(0, 0, 0, height).fill(0xffffff);
1754
- this.addChild(this._fillMask);
1755
- this._fill.mask = this._fillMask;
1756
- // Border overlay
1757
- this._borderGfx = new pixi_js.Graphics();
1758
- if (borderColor !== undefined && borderWidth > 0) {
1759
- this._borderGfx
1760
- .roundRect(0, 0, width, height, borderRadius)
1761
- .stroke({ color: borderColor, width: borderWidth });
1762
- }
1763
- this.addChild(this._borderGfx);
1764
- }
1765
- /** Get/set progress (0..1) */
1766
- get progress() {
1767
- return this._progress;
1768
- }
1769
- set progress(value) {
1770
- this._progress = Math.max(0, Math.min(1, value));
1771
- if (!this._config.animated) {
1772
- this._displayedProgress = this._progress;
1773
- this.updateMask();
1774
- }
1775
- }
1776
- /**
1777
- * Call each frame if animated is true.
1778
- */
1779
- update(_dt) {
1780
- if (!this._config.animated)
1781
- return;
1782
- if (Math.abs(this._displayedProgress - this._progress) < 0.001) {
1783
- this._displayedProgress = this._progress;
1784
- this.updateMask();
1785
- return;
1786
- }
1787
- this._displayedProgress +=
1788
- (this._progress - this._displayedProgress) * this._config.animationSpeed;
1789
- this.updateMask();
1790
- }
1791
- /** React reconciler update hook */
1792
- updateConfig(changed) {
1793
- if ('progress' in changed)
1794
- this.progress = changed.progress;
1795
- if ('animated' in changed)
1796
- this._config.animated = changed.animated;
1797
- if ('animationSpeed' in changed)
1798
- this._config.animationSpeed = changed.animationSpeed;
1799
- }
1800
- updateMask() {
1801
- const w = this._config.width * this._displayedProgress;
1802
- this._fillMask.clear();
1803
- this._fillMask.rect(0, 0, w, this._config.height).fill(0xffffff);
1804
- }
1805
- }
1806
-
1807
- /**
1808
- * Enhanced text label with auto-fit scaling and currency formatting.
1809
- *
1810
- * @example
1811
- * ```ts
1812
- * const label = new Label({
1813
- * text: 'BALANCE',
1814
- * style: { fontSize: 24, fill: 0xffd700 },
1815
- * maxWidth: 200,
1816
- * autoFit: true,
1817
- * });
1818
- * ```
1819
- */
1820
- class Label extends pixi_js.Container {
1821
- __uiComponent = true;
1822
- _text;
1823
- _maxWidth;
1824
- _autoFit;
1825
- constructor(config = {}) {
1826
- super();
1827
- this._maxWidth = config.maxWidth ?? Infinity;
1828
- this._autoFit = config.autoFit ?? false;
1829
- this._text = new pixi_js.Text({
1830
- text: config.text ?? '',
1831
- style: {
1832
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
1833
- fontSize: 24,
1834
- fill: 0xffffff,
1835
- ...config.style,
1836
- },
1837
- });
1838
- this._text.anchor.set(0.5);
1839
- this.addChild(this._text);
1840
- this.fitText();
1841
- }
1842
- /** Get/set the displayed text */
1843
- get text() {
1844
- return this._text.text;
1845
- }
1846
- set text(value) {
1847
- this._text.text = value;
1848
- this.fitText();
1849
- }
1850
- /** Get/set the text style */
1851
- get style() {
1852
- return this._text.style;
1853
- }
1854
- /** Set max width constraint */
1855
- set maxWidth(value) {
1856
- this._maxWidth = value;
1857
- this.fitText();
1858
- }
1859
- /**
1860
- * Format and display a number as currency.
1861
- *
1862
- * @param amount - The numeric amount
1863
- * @param currency - Currency code (e.g., 'USD', 'EUR')
1864
- * @param locale - Locale string (default: 'en-US')
1865
- */
1866
- setCurrency(amount, currency, locale = 'en-US') {
1867
- try {
1868
- this.text = new Intl.NumberFormat(locale, {
1869
- style: 'currency',
1870
- currency,
1871
- minimumFractionDigits: 2,
1872
- maximumFractionDigits: 2,
1873
- }).format(amount);
1874
- }
1875
- catch {
1876
- this.text = `${amount.toFixed(2)} ${currency}`;
1877
- }
1878
- }
1879
- /**
1880
- * Format a number with thousands separators.
1881
- */
1882
- setNumber(value, decimals = 0, locale = 'en-US') {
1883
- this.text = new Intl.NumberFormat(locale, {
1884
- minimumFractionDigits: decimals,
1885
- maximumFractionDigits: decimals,
1886
- }).format(value);
1887
- }
1888
- /** React reconciler update hook */
1889
- updateConfig(changed) {
1890
- if ('text' in changed)
1891
- this.text = changed.text;
1892
- if ('maxWidth' in changed)
1893
- this.maxWidth = changed.maxWidth;
1894
- if ('autoFit' in changed) {
1895
- this._autoFit = changed.autoFit;
1896
- this.fitText();
1897
- }
1898
- if ('style' in changed && typeof changed.style === 'object') {
1899
- Object.assign(this._text.style, changed.style);
1900
- this.fitText();
1901
- }
1902
- }
1903
- fitText() {
1904
- if (!this._autoFit || this._maxWidth === Infinity)
1905
- return;
1906
- this._text.scale.set(1);
1907
- if (this._text.width > this._maxWidth) {
1908
- const scale = this._maxWidth / this._text.width;
1909
- this._text.scale.set(scale);
1910
- }
1911
- }
1912
- }
1913
-
1914
- /**
1915
- * Two-row text cell with a muted caption above and a prominent value below —
1916
- * the archetypal casino UI pattern (BALANCE/€500, BET/€1, WIN/€0.00).
1917
- *
1918
- * Extends FlexContainer, so it participates in parent flex layouts directly
1919
- * (you can pass `flexGrow`, `alignSelf`, etc. when it's a child of another
1920
- * FlexContainer) and auto-sizes to its contents when no explicit size is set.
1921
- *
1922
- * @example
1923
- * ```tsx
1924
- * <labelValue
1925
- * label="BALANCE"
1926
- * value={`€${balance.toFixed(2)}`}
1927
- * labelStyle={{ fontSize: 12, fill: 0x888888 }}
1928
- * valueStyle={{ fontSize: 22, fill: 0xffffff, fontWeight: 'bold' }}
1929
- * gap={6}
1930
- * align="center"
1931
- * />
1932
- * ```
1933
- */
1934
- class LabelValue extends FlexContainer {
1935
- _labelEl;
1936
- _valueEl;
1937
- _valueMaxWidth;
1938
- constructor(config = {}) {
1939
- super({
1940
- direction: 'column',
1941
- alignItems: toAlignItems(config.align ?? 'center'),
1942
- gap: config.gap ?? 4,
1943
- padding: config.padding,
1944
- });
1945
- this._valueMaxWidth = config.maxWidth ?? Infinity;
1946
- this._labelEl = new Label({
1947
- text: config.label ?? '',
1948
- style: config.labelStyle,
1949
- });
1950
- this._valueEl = new Label({
1951
- text: config.value ?? '',
1952
- style: config.valueStyle,
1953
- maxWidth: config.maxWidth,
1954
- autoFit: config.maxWidth !== undefined,
1955
- });
1956
- this.addFlexChild(this._labelEl);
1957
- this.addFlexChild(this._valueEl);
1958
- }
1959
- /** Get the caption Label (for advanced styling / animation) */
1960
- get labelElement() {
1961
- return this._labelEl;
1962
- }
1963
- /** Get the value Label */
1964
- get valueElement() {
1965
- return this._valueEl;
1966
- }
1967
- /** Update caption text */
1968
- setLabel(text) {
1969
- this._labelEl.text = text;
1970
- this.updateLayout();
1971
- }
1972
- /** Update value text */
1973
- setValue(text) {
1974
- this._valueEl.text = text;
1975
- this.updateLayout();
1976
- }
1977
- /** React reconciler update hook */
1978
- updateConfig(changed) {
1979
- if ('label' in changed)
1980
- this._labelEl.text = changed.label ?? '';
1981
- if ('value' in changed)
1982
- this._valueEl.text = changed.value ?? '';
1983
- if ('labelStyle' in changed && typeof changed.labelStyle === 'object') {
1984
- Object.assign(this._labelEl.style, changed.labelStyle);
1985
- }
1986
- if ('valueStyle' in changed && typeof changed.valueStyle === 'object') {
1987
- Object.assign(this._valueEl.style, changed.valueStyle);
1988
- }
1989
- if ('maxWidth' in changed) {
1990
- this._valueMaxWidth = changed.maxWidth ?? Infinity;
1991
- this._valueEl.maxWidth = this._valueMaxWidth;
1992
- }
1993
- if ('gap' in changed)
1994
- this.setGap(changed.gap);
1995
- if ('align' in changed)
1996
- this.setAlignItems(toAlignItems(changed.align));
1997
- // Forward remaining FlexContainer props (e.g. padding, width, height)
1998
- super.updateConfig(changed);
1999
- }
2000
- }
2001
- function toAlignItems(align) {
2002
- return align;
2003
- }
2004
-
2005
- /**
2006
- * Background panel with optional flexbox content layout.
2007
- *
2008
- * Supports both Graphics-based (color + border) and 9-slice sprite backgrounds.
2009
- * Children added via `addContent()` participate in flex layout automatically.
2010
- *
2011
- * @example
2012
- * ```ts
2013
- * // Simple colored panel
2014
- * const panel = new Panel({ width: 400, height: 300, backgroundColor: 0x222222, borderRadius: 12 });
2015
- *
2016
- * // 9-slice panel (texture-based)
2017
- * const panel = new Panel({
2018
- * nineSliceTexture: 'panel-bg',
2019
- * nineSliceBorders: [20, 20, 20, 20],
2020
- * width: 400, height: 300,
2021
- * });
2022
- * ```
2023
- */
2024
- class Panel extends pixi_js.Container {
2025
- __uiComponent = true;
2026
- _bg;
2027
- _content;
2028
- _internalSetup = true;
2029
- _panelConfig;
2030
- constructor(config = {}) {
2031
- super();
2032
- const resolvedConfig = {
2033
- width: config.width ?? 400,
2034
- height: config.height ?? 300,
2035
- padding: config.padding ?? 16,
2036
- backgroundAlpha: config.backgroundAlpha ?? 1,
2037
- ...config,
2038
- };
2039
- this._panelConfig = resolvedConfig;
2040
- // Create background
2041
- if (config.nineSliceTexture) {
2042
- const texture = typeof config.nineSliceTexture === 'string'
2043
- ? pixi_js.Texture.from(config.nineSliceTexture)
2044
- : config.nineSliceTexture;
2045
- const [left, top, right, bottom] = config.nineSliceBorders ?? [10, 10, 10, 10];
2046
- const nineSlice = new pixi_js.NineSliceSprite({
2047
- texture,
2048
- leftWidth: left,
2049
- topHeight: top,
2050
- rightWidth: right,
2051
- bottomHeight: bottom,
2052
- });
2053
- nineSlice.width = resolvedConfig.width;
2054
- nineSlice.height = resolvedConfig.height;
2055
- nineSlice.alpha = resolvedConfig.backgroundAlpha;
2056
- this._bg = nineSlice;
2057
- }
2058
- else {
2059
- const g = new pixi_js.Graphics();
2060
- const bgColor = config.backgroundColor ?? 0x1a1a2e;
2061
- const radius = config.borderRadius ?? 0;
2062
- g.roundRect(0, 0, resolvedConfig.width, resolvedConfig.height, radius).fill(bgColor);
2063
- if (config.borderColor !== undefined && config.borderWidth) {
2064
- g.roundRect(0, 0, resolvedConfig.width, resolvedConfig.height, radius)
2065
- .stroke({ color: config.borderColor, width: config.borderWidth });
2066
- }
2067
- g.alpha = resolvedConfig.backgroundAlpha;
2068
- this._bg = g;
2069
- }
2070
- this.addChild(this._bg);
2071
- // Create content flex container
2072
- this._content = new FlexContainer({
2073
- ...config.layout,
2074
- direction: config.layout?.direction ?? 'column',
2075
- justifyContent: config.layout?.justifyContent ?? 'start',
2076
- alignItems: config.layout?.alignItems ?? 'start',
2077
- gap: config.layout?.gap ?? 0,
2078
- padding: resolvedConfig.padding,
2079
- width: resolvedConfig.width,
2080
- height: resolvedConfig.height,
2081
- });
2082
- this.addChild(this._content);
2083
- this._internalSetup = false;
2084
- }
2085
- /** Access the content flex container — add children here for layout */
2086
- get content() {
2087
- return this._content;
2088
- }
2089
- /** Suspend content layout recalculation. Call resumeLayout() to flush. */
2090
- suspendLayout() {
2091
- this._content.suspendLayout();
2092
- }
2093
- /** Resume content layout and flush if dirty. */
2094
- resumeLayout() {
2095
- this._content.resumeLayout();
2096
- }
2097
- /** Convenience: add a child to the content layout */
2098
- addContent(child) {
2099
- this._content.addFlexChild(child);
2100
- this._content.updateLayout();
2101
- return this;
2102
- }
2103
- /** Resize the panel */
2104
- setSize(width, height) {
2105
- this._panelConfig.width = width;
2106
- this._panelConfig.height = height;
2107
- // Resize background
2108
- if (this._bg instanceof pixi_js.NineSliceSprite) {
2109
- this._bg.width = width;
2110
- this._bg.height = height;
2111
- }
2112
- else if (this._bg instanceof pixi_js.Graphics) {
2113
- const radius = this._panelConfig.borderRadius ?? 0;
2114
- const bgColor = this._panelConfig.backgroundColor ?? 0x1a1a2e;
2115
- this._bg.clear();
2116
- this._bg.roundRect(0, 0, width, height, radius).fill(bgColor);
2117
- if (this._panelConfig.borderColor !== undefined && this._panelConfig.borderWidth) {
2118
- this._bg.roundRect(0, 0, width, height, radius)
2119
- .stroke({ color: this._panelConfig.borderColor, width: this._panelConfig.borderWidth });
2120
- }
2121
- this._bg.alpha = this._panelConfig.backgroundAlpha;
2122
- }
2123
- this._content.resize(width, height);
2124
- }
2125
- /**
2126
- * Override addChild so external children are routed to content FlexContainer.
2127
- * Enables `<panel><label /><button /></panel>` in React JSX.
2128
- */
2129
- addChild(...children) {
2130
- if (this._internalSetup) {
2131
- return super.addChild(...children);
2132
- }
2133
- for (const child of children) {
2134
- this._content.addFlexChild(child);
2135
- }
2136
- this._content.updateLayout();
2137
- return children[0];
2138
- }
2139
- removeChild(...children) {
2140
- if (this._internalSetup) {
2141
- return super.removeChild(...children);
2142
- }
2143
- for (const child of children) {
2144
- this._content.removeFlexChild(child);
2145
- }
2146
- return children[0];
2147
- }
2148
- /** React reconciler update hook */
2149
- updateConfig(changed) {
2150
- if ('width' in changed || 'height' in changed) {
2151
- this.setSize(changed.width ?? this._panelConfig.width, changed.height ?? this._panelConfig.height);
2152
- }
2153
- if ('backgroundAlpha' in changed) {
2154
- this._panelConfig.backgroundAlpha = changed.backgroundAlpha;
2155
- this._bg.alpha = changed.backgroundAlpha;
2156
- }
2157
- }
2158
- destroy(options) {
2159
- super.destroy(options);
2160
- }
2161
- }
2162
-
2163
- /**
2164
- * Reactive balance display component.
2165
- *
2166
- * Automatically formats currency and can animate value changes
2167
- * with a smooth countup/countdown effect using engine Tween.
2168
- *
2169
- * @example
2170
- * ```ts
2171
- * const balance = new BalanceDisplay({ currency: 'USD', animated: true });
2172
- * balance.setValue(1000);
2173
- *
2174
- * // Wire to SDK
2175
- * sdk.on('balanceUpdate', ({ balance: val }) => balance.setValue(val));
2176
- * ```
2177
- */
2178
- class BalanceDisplay extends pixi_js.Container {
2179
- __uiComponent = true;
2180
- _prefixLabel = null;
2181
- _valueLabel;
2182
- _config;
2183
- _currentValue = 0;
2184
- _displayedValue = 0;
2185
- /** Internal target for Tween animation */
2186
- _tweenTarget = { value: 0 };
2187
- constructor(config = {}) {
2188
- super();
2189
- this._config = {
2190
- currency: config.currency ?? 'USD',
2191
- locale: config.locale ?? 'en-US',
2192
- animated: config.animated ?? true,
2193
- animationDuration: config.animationDuration ?? 500,
2194
- };
2195
- // Prefix label
2196
- if (config.prefix) {
2197
- this._prefixLabel = new Label({
2198
- text: config.prefix,
2199
- style: {
2200
- fontSize: 16,
2201
- fill: 0xaaaaaa,
2202
- ...config.style,
2203
- },
2204
- });
2205
- this.addChild(this._prefixLabel);
2206
- }
2207
- // Value label
2208
- this._valueLabel = new Label({
2209
- text: '0.00',
2210
- style: {
2211
- fontSize: 28,
2212
- fontWeight: 'bold',
2213
- fill: 0xffffff,
2214
- ...config.style,
2215
- },
2216
- maxWidth: config.maxWidth,
2217
- autoFit: !!config.maxWidth,
2218
- });
2219
- this.addChild(this._valueLabel);
2220
- this.layoutLabels();
2221
- }
2222
- /** Current displayed value */
2223
- get value() {
2224
- return this._currentValue;
2225
- }
2226
- /**
2227
- * Set the balance value. If animated, smoothly counts to the new value.
2228
- */
2229
- setValue(value) {
2230
- const oldValue = this._currentValue;
2231
- this._currentValue = value;
2232
- if (this._config.animated && oldValue !== value) {
2233
- this.animateValue(oldValue, value);
2234
- }
2235
- else {
2236
- this._displayedValue = value;
2237
- this.updateDisplay();
2238
- }
2239
- }
2240
- /**
2241
- * Set the currency code.
2242
- */
2243
- setCurrency(currency) {
2244
- this._config.currency = currency;
2245
- this.updateDisplay();
2246
- }
2247
- animateValue(from, to) {
2248
- // Cancel any running animation
2249
- Tween.killTweensOf(this._tweenTarget);
2250
- this._tweenTarget.value = from;
2251
- Tween.to(this._tweenTarget, { value: to }, this._config.animationDuration, Easing.easeOutCubic, () => {
2252
- this._displayedValue = this._tweenTarget.value;
2253
- this.updateDisplay();
2254
- });
2255
- }
2256
- updateDisplay() {
2257
- this._valueLabel.setCurrency(this._displayedValue, this._config.currency, this._config.locale);
2258
- }
2259
- layoutLabels() {
2260
- if (this._prefixLabel) {
2261
- this._prefixLabel.y = -14;
2262
- this._valueLabel.y = 14;
2263
- }
2264
- }
2265
- /** React reconciler update hook */
2266
- updateConfig(changed) {
2267
- if ('value' in changed)
2268
- this.setValue(changed.value);
2269
- if ('currency' in changed)
2270
- this.setCurrency(changed.currency);
2271
- }
2272
- destroy(options) {
2273
- Tween.killTweensOf(this._tweenTarget);
2274
- super.destroy(options);
2275
- }
2276
- }
2277
-
2278
- /**
2279
- * Win amount display with countup animation.
2280
- *
2281
- * Shows a dramatic countup from 0 to the win amount, with optional
2282
- * scale pop effect — typical of slot games. Uses engine Tween system.
2283
- *
2284
- * @example
2285
- * ```ts
2286
- * const winDisplay = new WinDisplay({ currency: 'USD' });
2287
- * scene.container.addChild(winDisplay);
2288
- * await winDisplay.showWin(150.50); // countup animation
2289
- * winDisplay.hide();
2290
- * ```
2291
- */
2292
- class WinDisplay extends pixi_js.Container {
2293
- __uiComponent = true;
2294
- _label;
2295
- _config;
2296
- /** Internal target for Tween countup */
2297
- _tweenTarget = { value: 0 };
2298
- constructor(config = {}) {
2299
- super();
2300
- this._config = {
2301
- currency: config.currency ?? 'USD',
2302
- locale: config.locale ?? 'en-US',
2303
- countupDuration: config.countupDuration ?? 1500,
2304
- popScale: config.popScale ?? 1.2,
2305
- };
2306
- this._label = new Label({
2307
- text: '',
2308
- style: {
2309
- fontSize: 48,
2310
- fontWeight: 'bold',
2311
- fill: 0xffd700,
2312
- stroke: { color: 0x000000, width: 3 },
2313
- ...config.style,
2314
- },
2315
- });
2316
- this.addChild(this._label);
2317
- this.visible = false;
2318
- }
2319
- /**
2320
- * Show a win with countup animation.
2321
- *
2322
- * @param amount - Win amount
2323
- * @returns Promise that resolves when the animation completes
2324
- */
2325
- async showWin(amount) {
2326
- this.visible = true;
2327
- this.alpha = 1;
2328
- // Cancel any running animation
2329
- Tween.killTweensOf(this._tweenTarget);
2330
- Tween.killTweensOf(this);
2331
- // Setup countup
2332
- this._tweenTarget.value = 0;
2333
- this.scale.set(0.5);
2334
- // Scale pop animation
2335
- const scalePromise = Tween.to(this, { 'scale.x': 1, 'scale.y': 1 }, 300, Easing.easeOutBack);
2336
- // Countup animation
2337
- const countupPromise = Tween.to(this._tweenTarget, { value: amount }, this._config.countupDuration, Easing.easeOutCubic, () => {
2338
- this.displayAmount(this._tweenTarget.value);
2339
- });
2340
- await Promise.all([scalePromise, countupPromise]);
2341
- // Ensure final value is exact
2342
- this.displayAmount(amount);
2343
- this.scale.set(1);
2344
- }
2345
- /**
2346
- * Skip the countup animation and show the final amount immediately.
2347
- */
2348
- skipCountup(amount) {
2349
- Tween.killTweensOf(this._tweenTarget);
2350
- Tween.killTweensOf(this);
2351
- this.displayAmount(amount);
2352
- this.scale.set(1);
2353
- }
2354
- /**
2355
- * Hide the win display.
2356
- */
2357
- hide() {
2358
- Tween.killTweensOf(this._tweenTarget);
2359
- Tween.killTweensOf(this);
2360
- this.visible = false;
2361
- this._label.text = '';
2362
- }
2363
- displayAmount(amount) {
2364
- this._label.setCurrency(amount, this._config.currency, this._config.locale);
2365
- }
2366
- /** React reconciler update hook */
2367
- updateConfig(changed) {
2368
- if ('currency' in changed)
2369
- this._config.currency = changed.currency;
2370
- if ('locale' in changed)
2371
- this._config.locale = changed.locale;
2372
- }
2373
- destroy(options) {
2374
- Tween.killTweensOf(this._tweenTarget);
2375
- Tween.killTweensOf(this);
2376
- super.destroy(options);
2377
- }
2378
- }
2379
-
2380
- /**
2381
- * Modal overlay component.
2382
- * Shows content on top of a dark overlay with enter/exit animations.
2383
- *
2384
- * Content is automatically centered via position calculations.
2385
- *
2386
- * @example
2387
- * ```ts
2388
- * const modal = new Modal({ closeOnOverlay: true });
2389
- * modal.content.addChild(settingsPanel);
2390
- * modal.onClose = () => console.log('Closed');
2391
- * await modal.show(1920, 1080);
2392
- * ```
2393
- */
2394
- class Modal extends pixi_js.Container {
2395
- __uiComponent = true;
2396
- _overlay;
2397
- _contentContainer;
2398
- _config;
2399
- _showing = false;
2400
- _internalSetup = true;
2401
- /** Called when the modal is closed */
2402
- onClose;
2403
- constructor(config = {}) {
2404
- super();
2405
- this._config = {
2406
- overlayColor: config.overlayColor ?? 0x000000,
2407
- overlayAlpha: config.overlayAlpha ?? 0.7,
2408
- closeOnOverlay: config.closeOnOverlay ?? true,
2409
- animationDuration: config.animationDuration ?? 300,
2410
- };
2411
- // Overlay
2412
- this._overlay = new pixi_js.Graphics();
2413
- this._overlay.eventMode = 'static';
2414
- this._overlay.on('pointertap', () => {
2415
- if (this._config.closeOnOverlay)
2416
- this.hide();
2417
- });
2418
- this.addChild(this._overlay);
2419
- // Content container
2420
- this._contentContainer = new pixi_js.Container();
2421
- this.addChild(this._contentContainer);
2422
- this.visible = false;
2423
- this._internalSetup = false;
2424
- }
2425
- /** Content container — add your UI here */
2426
- get content() {
2427
- return this._contentContainer;
2428
- }
2429
- /**
2430
- * Override addChild so external children are routed to _contentContainer.
2431
- * Enables `<modal><flexContainer>...</flexContainer></modal>` in React JSX.
2432
- */
2433
- addChild(...children) {
2434
- if (this._internalSetup) {
2435
- return super.addChild(...children);
2436
- }
2437
- for (const child of children) {
2438
- this._contentContainer.addChild(child);
2439
- }
2440
- return children[0];
2441
- }
2442
- removeChild(...children) {
2443
- if (this._internalSetup) {
2444
- return super.removeChild(...children);
2445
- }
2446
- for (const child of children) {
2447
- this._contentContainer.removeChild(child);
2448
- }
2449
- return children[0];
2450
- }
2451
- /** Whether the modal is currently showing */
2452
- get isShowing() {
2453
- return this._showing;
2454
- }
2455
- /**
2456
- * Show the modal with animation.
2457
- */
2458
- async show(viewWidth, viewHeight) {
2459
- this._showing = true;
2460
- this.visible = true;
2461
- // Draw overlay to cover full screen
2462
- this._overlay.clear();
2463
- this._overlay.rect(0, 0, viewWidth, viewHeight).fill(this._config.overlayColor);
2464
- this._overlay.alpha = 0;
2465
- // Center content
2466
- this._contentContainer.x = viewWidth / 2;
2467
- this._contentContainer.y = viewHeight / 2;
2468
- this._contentContainer.alpha = 0;
2469
- this._contentContainer.scale.set(0.8);
2470
- // Animate in
2471
- await Promise.all([
2472
- Tween.to(this._overlay, { alpha: this._config.overlayAlpha }, this._config.animationDuration, Easing.easeOutCubic),
2473
- Tween.to(this._contentContainer, { alpha: 1, 'scale.x': 1, 'scale.y': 1 }, this._config.animationDuration, Easing.easeOutBack),
2474
- ]);
2475
- }
2476
- /**
2477
- * Hide the modal with animation.
2478
- */
2479
- async hide() {
2480
- if (!this._showing)
2481
- return;
2482
- await Promise.all([
2483
- Tween.to(this._overlay, { alpha: 0 }, this._config.animationDuration * 0.7, Easing.easeInCubic),
2484
- Tween.to(this._contentContainer, { alpha: 0, 'scale.x': 0.8, 'scale.y': 0.8 }, this._config.animationDuration * 0.7, Easing.easeInCubic),
2485
- ]);
2486
- this.visible = false;
2487
- this._showing = false;
2488
- this.onClose?.();
2489
- }
2490
- /** React reconciler update hook */
2491
- updateConfig(changed) {
2492
- if ('overlayAlpha' in changed)
2493
- this._config.overlayAlpha = changed.overlayAlpha;
2494
- if ('closeOnOverlay' in changed)
2495
- this._config.closeOnOverlay = changed.closeOnOverlay;
2496
- if ('animationDuration' in changed)
2497
- this._config.animationDuration = changed.animationDuration;
2498
- if ('onClose' in changed)
2499
- this.onClose = changed.onClose;
2500
- }
2501
- }
2502
-
2503
- const TOAST_COLORS = {
2504
- info: 0x3498db,
2505
- success: 0x27ae60,
2506
- warning: 0xf39c12,
2507
- error: 0xe74c3c,
2508
- };
2509
- /**
2510
- * Toast notification component for displaying transient messages.
2511
- *
2512
- * @example
2513
- * ```ts
2514
- * const toast = new Toast();
2515
- * scene.container.addChild(toast);
2516
- * await toast.show('Connection lost', 'error', 1920, 1080);
2517
- * ```
2518
- */
2519
- class Toast extends pixi_js.Container {
2520
- __uiComponent = true;
2521
- _bg;
2522
- _customBg;
2523
- _text;
2524
- _config;
2525
- _dismissPending = false;
2526
- constructor(config = {}) {
2527
- super();
2528
- this._config = {
2529
- duration: config.duration ?? 3000,
2530
- bottomOffset: config.bottomOffset ?? 60,
2531
- };
2532
- const customBg = resolveView(config.backgroundView);
2533
- this._customBg = !!customBg;
2534
- this._bg = customBg ?? new pixi_js.Graphics();
2535
- this.addChild(this._bg);
2536
- this._text = new pixi_js.Text({
2537
- text: '',
2538
- style: {
2539
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
2540
- fontSize: 16,
2541
- fill: 0xffffff,
2542
- },
2543
- });
2544
- this._text.anchor.set(0.5);
2545
- this.addChild(this._text);
2546
- this.visible = false;
2547
- }
2548
- /**
2549
- * Show a toast message.
2550
- */
2551
- async show(message, type = 'info', viewWidth, viewHeight) {
2552
- // Cancel any pending dismiss
2553
- Tween.killTweensOf(this);
2554
- this._dismissPending = false;
2555
- this._text.text = message;
2556
- const padding = 20;
2557
- const width = Math.max(200, this._text.width + padding * 2);
2558
- const height = 44;
2559
- const radius = 8;
2560
- // Draw the background
2561
- if (this._customBg) {
2562
- this._bg.width = width;
2563
- this._bg.height = height;
2564
- this._bg.x = -width / 2;
2565
- this._bg.y = -height / 2;
2566
- }
2567
- else {
2568
- const g = this._bg;
2569
- g.clear();
2570
- g.roundRect(-width / 2, -height / 2, width, height, radius);
2571
- g.fill(TOAST_COLORS[type]);
2572
- }
2573
- // Position
2574
- if (viewWidth && viewHeight) {
2575
- this.x = viewWidth / 2;
2576
- this.y = viewHeight - this._config.bottomOffset;
2577
- }
2578
- this.visible = true;
2579
- this.alpha = 0;
2580
- this.y += 20;
2581
- await Tween.to(this, { alpha: 1, y: this.y - 20 }, 300, Easing.easeOutCubic);
2582
- if (this._config.duration > 0) {
2583
- this._dismissPending = true;
2584
- await Tween.delay(this._config.duration);
2585
- if (this._dismissPending) {
2586
- this._dismissPending = false;
2587
- await this.dismiss();
2588
- }
2589
- }
2590
- }
2591
- /**
2592
- * Dismiss the toast.
2593
- */
2594
- async dismiss() {
2595
- if (!this.visible)
2596
- return;
2597
- this._dismissPending = false;
2598
- Tween.killTweensOf(this);
2599
- await Tween.to(this, { alpha: 0, y: this.y + 20 }, 200, Easing.easeInCubic);
2600
- this.visible = false;
2601
- }
2602
- /** React reconciler update hook */
2603
- updateConfig(changed) {
2604
- if ('duration' in changed)
2605
- this._config.duration = changed.duration;
2606
- if ('bottomOffset' in changed)
2607
- this._config.bottomOffset = changed.bottomOffset;
2608
- }
2609
- destroy(options) {
2610
- this._dismissPending = false;
2611
- Tween.killTweensOf(this);
2612
- super.destroy(options);
2613
- }
2614
- }
2615
-
2616
- // ─── Helpers ─────────────────────────────────────────────
2617
- function directionToFlex(direction) {
2618
- switch (direction) {
2619
- case 'horizontal': return { direction: 'row', wrap: false };
2620
- case 'vertical': return { direction: 'column', wrap: false };
2621
- case 'grid': return { direction: 'row', wrap: true };
2622
- case 'wrap': return { direction: 'row', wrap: true };
2623
- }
2624
- }
2625
- /**
2626
- * Responsive layout container powered by a lightweight built-in flex layout solver.
2627
- *
2628
- * Supports horizontal, vertical, grid, and wrap layout modes with
2629
- * alignment, padding, gap, and viewport-anchor positioning.
2630
- * Breakpoints allow different layouts for different screen sizes.
2631
- *
2632
- * @example
2633
- * ```ts
2634
- * const toolbar = new Layout({
2635
- * direction: 'horizontal',
2636
- * gap: 20,
2637
- * alignment: 'center',
2638
- * anchor: 'bottom-center',
2639
- * padding: 16,
2640
- * breakpoints: {
2641
- * 768: { direction: 'vertical', gap: 10 },
2642
- * },
2643
- * });
2644
- *
2645
- * toolbar.addItem(spinButton);
2646
- * toolbar.addItem(betLabel);
2647
- * scene.container.addChild(toolbar);
2648
- *
2649
- * toolbar.updateViewport(width, height);
2650
- * ```
2651
- */
2652
- class Layout extends pixi_js.Container {
2653
- __uiComponent = true;
2654
- _layoutConfig;
2655
- _padding;
2656
- _anchor;
2657
- _maxWidth;
2658
- _breakpoints;
2659
- _items = [];
2660
- _viewportWidth = 0;
2661
- _viewportHeight = 0;
2662
- _flex;
2663
- constructor(config = {}) {
2664
- super();
2665
- this._layoutConfig = {
2666
- direction: config.direction ?? 'vertical',
2667
- gap: config.gap ?? 0,
2668
- alignment: config.alignment ?? 'start',
2669
- autoLayout: config.autoLayout ?? true,
2670
- columns: config.columns ?? 2,
2671
- };
2672
- this._padding = config.padding ?? 0;
2673
- this._anchor = config.anchor ?? 'top-left';
2674
- this._maxWidth = config.maxWidth ?? Infinity;
2675
- this._breakpoints = config.breakpoints
2676
- ? Object.entries(config.breakpoints)
2677
- .map(([w, cfg]) => [Number(w), cfg])
2678
- .sort((a, b) => a[0] - b[0])
2679
- : [];
2680
- // Create internal FlexContainer
2681
- this._flex = new FlexContainer();
2682
- super.addChild(this._flex);
2683
- this.applyLayoutStyles();
2684
- }
2685
- /** Add an item to the layout */
2686
- addItem(child) {
2687
- this._items.push(child);
2688
- const flexConfig = this.buildFlexItemConfig(child);
2689
- this._flex.addFlexChild(child, flexConfig);
2690
- if (this._layoutConfig.autoLayout) {
2691
- this.applyLayoutStyles();
2692
- }
2693
- return this;
2694
- }
2695
- /** Remove an item from the layout */
2696
- removeItem(child) {
2697
- const idx = this._items.indexOf(child);
2698
- if (idx !== -1) {
2699
- this._items.splice(idx, 1);
2700
- this._flex.removeFlexChild(child);
2701
- }
2702
- return this;
2703
- }
2704
- /** Remove all items */
2705
- clearItems() {
2706
- this._flex.clearFlexChildren();
2707
- this._items.length = 0;
2708
- return this;
2709
- }
2710
- /** Get all layout items */
2711
- get items() {
2712
- return this._items;
2713
- }
2714
- /**
2715
- * Update the viewport size and recalculate layout.
2716
- * Should be called from `Scene.onResize()`.
2717
- */
2718
- updateViewport(width, height) {
2719
- this._viewportWidth = width;
2720
- this._viewportHeight = height;
2721
- this.applyLayoutStyles();
2722
- this.applyAnchor();
2723
- }
2724
- applyLayoutStyles() {
2725
- const effective = this.resolveConfig();
2726
- const direction = effective.direction ?? this._layoutConfig.direction;
2727
- const gap = effective.gap ?? this._layoutConfig.gap;
2728
- const alignment = effective.alignment ?? this._layoutConfig.alignment;
2729
- const padding = effective.padding ?? this._padding;
2730
- const maxWidth = effective.maxWidth ?? this._maxWidth;
2731
- const { direction: flexDir, wrap } = directionToFlex(direction);
2732
- this._flex.setDirection(flexDir);
2733
- this._flex.setJustifyContent('start');
2734
- this._flex.setAlignItems(alignment);
2735
- this._flex.setGap(gap);
2736
- this._flex.setPadding(padding);
2737
- // Wrap and maxWidth
2738
- if (wrap) {
2739
- this._flex._config.flexWrap = true;
2740
- if (direction === 'grid' && maxWidth < Infinity) {
2741
- this._flex._maxWidth = maxWidth;
2742
- }
2743
- if (maxWidth < Infinity) {
2744
- this._flex._maxWidth = maxWidth;
2745
- }
2746
- }
2747
- else {
2748
- this._flex._config.flexWrap = false;
2749
- }
2750
- // Update grid child widths
2751
- if (direction === 'grid') {
2752
- for (const item of this._items) {
2753
- const flexConfig = this.buildFlexItemConfig(item);
2754
- item._flexConfig = flexConfig;
2755
- }
2756
- }
2757
- // Set explicit size if we have viewport dimensions
2758
- if (this._viewportWidth > 0 && this._viewportHeight > 0) {
2759
- this._flex.resize(this._viewportWidth, this._viewportHeight);
2760
- }
2761
- else {
2762
- this._flex.updateLayout();
2763
- }
2764
- }
2765
- buildFlexItemConfig(_child) {
2766
- const effective = this.resolveConfig();
2767
- const direction = effective.direction ?? this._layoutConfig.direction;
2768
- const columns = effective.columns ?? this._layoutConfig.columns;
2769
- if (direction === 'grid' && columns > 0) {
2770
- // For grid, give each item a proportional width
2771
- // The actual pixel width will be computed during layout
2772
- return { flexGrow: 1 };
2773
- }
2774
- return undefined;
2775
- }
2776
- applyAnchor() {
2777
- const anchor = this.resolveConfig().anchor ?? this._anchor;
2778
- if (this._viewportWidth === 0 || this._viewportHeight === 0)
2779
- return;
2780
- const { width: contentW, height: contentH } = this._flex.getContentSize();
2781
- const vw = this._viewportWidth;
2782
- const vh = this._viewportHeight;
2783
- let anchorX = 0;
2784
- let anchorY = 0;
2785
- if (anchor.includes('left')) {
2786
- anchorX = 0;
2787
- }
2788
- else if (anchor.includes('right')) {
2789
- anchorX = vw - contentW;
2790
- }
2791
- else {
2792
- anchorX = (vw - contentW) / 2;
2793
- }
2794
- if (anchor.startsWith('top')) {
2795
- anchorY = 0;
2796
- }
2797
- else if (anchor.startsWith('bottom')) {
2798
- anchorY = vh - contentH;
2799
- }
2800
- else {
2801
- anchorY = (vh - contentH) / 2;
2802
- }
2803
- this.x = anchorX;
2804
- this.y = anchorY;
2805
- }
2806
- resolveConfig() {
2807
- if (this._breakpoints.length === 0 || this._viewportWidth === 0) {
2808
- return {};
2809
- }
2810
- for (const [maxWidth, overrides] of this._breakpoints) {
2811
- if (this._viewportWidth <= maxWidth) {
2812
- return overrides;
2813
- }
2814
- }
2815
- return {};
2816
- }
2817
- /** React reconciler update hook */
2818
- updateConfig(changed) {
2819
- if ('direction' in changed)
2820
- this._layoutConfig.direction = changed.direction;
2821
- if ('gap' in changed)
2822
- this._layoutConfig.gap = changed.gap;
2823
- if ('alignment' in changed)
2824
- this._layoutConfig.alignment = changed.alignment;
2825
- if ('anchor' in changed)
2826
- this._anchor = changed.anchor;
2827
- if ('padding' in changed)
2828
- this._padding = changed.padding;
2829
- if ('columns' in changed)
2830
- this._layoutConfig.columns = changed.columns;
2831
- this.applyLayoutStyles();
2832
- if (this._viewportWidth > 0)
2833
- this.applyAnchor();
2834
- }
2835
- destroy(options) {
2836
- this._items.length = 0;
2837
- super.destroy(options);
2838
- }
2839
- }
2840
-
2841
- const DECELERATION = 0.95;
2842
- const MIN_VELOCITY = 0.5;
2843
- /**
2844
- * Scrollable container with touch/drag, mouse wheel, and inertia.
2845
- *
2846
- * @example
2847
- * ```ts
2848
- * const scroll = new ScrollContainer({
2849
- * width: 600,
2850
- * height: 400,
2851
- * direction: 'vertical',
2852
- * elementsMargin: 8,
2853
- * });
2854
- *
2855
- * for (let i = 0; i < 50; i++) {
2856
- * scroll.addItem(createRow(i));
2857
- * }
2858
- *
2859
- * scene.container.addChild(scroll);
2860
- * ```
2861
- */
2862
- class ScrollContainer extends pixi_js.Container {
2863
- __uiComponent = true;
2864
- _viewport;
2865
- _internalSetup = true;
2866
- _content;
2867
- _maskGfx;
2868
- _bg = null;
2869
- _scrollConfig;
2870
- _items = [];
2871
- // Scrollbar
2872
- _scrollbar = null;
2873
- _scrollbarConfig;
2874
- // Drag state
2875
- _dragging = false;
2876
- _dragStart = { x: 0, y: 0 };
2877
- _contentStart = { x: 0, y: 0 };
2878
- _velocity = { x: 0, y: 0 };
2879
- _lastDragPos = { x: 0, y: 0 };
2880
- _lastDragTime = 0;
2881
- _inertiaActive = false;
2882
- // Bound handlers for cleanup
2883
- _onTickBound = null;
2884
- _onWheelBound = null;
2885
- constructor(config) {
2886
- super();
2887
- this._viewport = { width: config.width, height: config.height };
2888
- this._scrollConfig = {
2889
- direction: config.direction ?? 'vertical',
2890
- elementsMargin: config.elementsMargin ?? 0,
2891
- padding: config.padding ?? 0,
2892
- borderRadius: config.borderRadius ?? 0,
2893
- disableEasing: config.disableEasing ?? false,
2894
- };
2895
- // Background
2896
- if (config.backgroundColor !== undefined) {
2897
- this._bg = new pixi_js.Graphics();
2898
- this._bg.roundRect(0, 0, config.width, config.height, this._scrollConfig.borderRadius)
2899
- .fill(config.backgroundColor);
2900
- this.addChild(this._bg);
2901
- }
2902
- // Mask
2903
- this._maskGfx = new pixi_js.Graphics();
2904
- this._maskGfx.roundRect(0, 0, config.width, config.height, this._scrollConfig.borderRadius)
2905
- .fill(0xffffff);
2906
- this.addChild(this._maskGfx);
2907
- // Content container
2908
- this._content = new pixi_js.Container();
2909
- this._content.mask = this._maskGfx;
2910
- this.addChild(this._content);
2911
- // Interaction
2912
- this.eventMode = 'static';
2913
- this.hitArea = { contains: (x, y) => x >= 0 && x <= config.width && y >= 0 && y <= config.height };
2914
- this.on('pointerdown', this._onPointerDown, this);
2915
- this.on('pointermove', this._onPointerMove, this);
2916
- this.on('pointerup', this._onPointerUp, this);
2917
- this.on('pointerupoutside', this._onPointerUp, this);
2918
- // Mouse wheel
2919
- this._onWheelBound = this._onWheel.bind(this);
2920
- // Scrollbar
2921
- const sbWidth = config.scrollbarWidth ?? 6;
2922
- const sbPadding = config.scrollbarPadding ?? 4;
2923
- this._scrollbarConfig = { width: sbWidth, padding: sbPadding };
2924
- if (config.scrollbar) {
2925
- const customThumb = resolveView(config.thumbView);
2926
- if (customThumb) {
2927
- this._scrollbar = customThumb;
2928
- }
2929
- else {
2930
- const g = new pixi_js.Graphics();
2931
- g.roundRect(0, 0, sbWidth, 40, sbWidth / 2).fill(config.scrollbarColor ?? 0xaaaaaa);
2932
- g.alpha = config.scrollbarAlpha ?? 0.5;
2933
- this._scrollbar = g;
2934
- }
2935
- this._scrollbar.visible = false;
2936
- super.addChild(this._scrollbar);
2937
- }
2938
- this._internalSetup = false;
2939
- }
2940
- /**
2941
- * Override addChild so external children are routed to scroll content.
2942
- * Enables `<scrollContainer><label /><panel /></scrollContainer>` in React JSX.
2943
- */
2944
- addChild(...children) {
2945
- if (this._internalSetup) {
2946
- return super.addChild(...children);
2947
- }
2948
- for (const child of children) {
2949
- this.addItem(child);
2950
- }
2951
- return children[0];
2952
- }
2953
- removeChild(...children) {
2954
- if (this._internalSetup) {
2955
- return super.removeChild(...children);
2956
- }
2957
- for (const child of children) {
2958
- const idx = this._items.indexOf(child);
2959
- if (idx !== -1) {
2960
- this._items.splice(idx, 1);
2961
- this._content.removeChild(child);
2962
- }
2963
- }
2964
- this.layoutItems();
2965
- return children[0];
2966
- }
2967
- /** React reconciler update hook */
2968
- updateConfig(changed) {
2969
- if ('width' in changed || 'height' in changed) {
2970
- this.setViewportSize(changed.width ?? this._viewport.width, changed.height ?? this._viewport.height);
2971
- }
2972
- }
2973
- /** Enable mouse wheel scrolling (call after adding to stage) */
2974
- enableWheel(canvas) {
2975
- if (this._onWheelBound) {
2976
- canvas.addEventListener('wheel', this._onWheelBound, { passive: false });
2977
- }
2978
- }
2979
- /** Set scrollable content. Replaces any existing items. */
2980
- setContent(content) {
2981
- this.clearItems();
2982
- const children = [...content.children];
2983
- for (const child of children) {
2984
- this.addItem(child);
2985
- }
2986
- }
2987
- /** Add a single item */
2988
- addItem(child) {
2989
- this._items.push(child);
2990
- this._content.addChild(child);
2991
- this.layoutItems();
2992
- return this;
2993
- }
2994
- /** Remove all items */
2995
- clearItems() {
2996
- for (const item of this._items) {
2997
- this._content.removeChild(item);
2998
- }
2999
- this._items.length = 0;
3000
- }
3001
- /** Get items */
3002
- get items() {
3003
- return this._items;
3004
- }
3005
- /** Scroll to make a specific item index visible */
3006
- scrollToItem(index) {
3007
- if (index < 0 || index >= this._items.length)
3008
- return;
3009
- const item = this._items[index];
3010
- const isVert = this._scrollConfig.direction !== 'horizontal';
3011
- if (isVert) {
3012
- this._content.y = -item.y + this._scrollConfig.padding;
3013
- }
3014
- else {
3015
- this._content.x = -item.x + this._scrollConfig.padding;
3016
- }
3017
- this.clampScroll();
3018
- }
3019
- /** Current scroll position */
3020
- get scrollPosition() {
3021
- return { x: this._content.x, y: this._content.y };
3022
- }
3023
- /** Resize the scroll viewport */
3024
- setViewportSize(width, height) {
3025
- this._viewport.width = width;
3026
- this._viewport.height = height;
3027
- this._maskGfx.clear();
3028
- this._maskGfx.roundRect(0, 0, width, height, this._scrollConfig.borderRadius).fill(0xffffff);
3029
- if (this._bg) {
3030
- this._bg.clear();
3031
- this._bg.roundRect(0, 0, width, height, this._scrollConfig.borderRadius)
3032
- .fill(0xffffff); // color will be overridden if needed
3033
- }
3034
- this.clampScroll();
3035
- }
3036
- // ─── Layout ──────────────────────────────────────────
3037
- layoutItems() {
3038
- const { direction, elementsMargin, padding } = this._scrollConfig;
3039
- const isVert = direction !== 'horizontal';
3040
- let pos = padding;
3041
- for (const item of this._items) {
3042
- if (isVert) {
3043
- item.x = padding;
3044
- item.y = pos;
3045
- pos += item.height + elementsMargin;
3046
- }
3047
- else {
3048
- item.x = pos;
3049
- item.y = padding;
3050
- pos += item.width + elementsMargin;
3051
- }
3052
- }
3053
- }
3054
- // ─── Drag handling ───────────────────────────────────
3055
- _onPointerDown(e) {
3056
- this._dragging = true;
3057
- this._inertiaActive = false;
3058
- this._dragStart.x = e.globalX;
3059
- this._dragStart.y = e.globalY;
3060
- this._contentStart.x = this._content.x;
3061
- this._contentStart.y = this._content.y;
3062
- this._lastDragPos.x = e.globalX;
3063
- this._lastDragPos.y = e.globalY;
3064
- this._lastDragTime = Date.now();
3065
- this._velocity.x = 0;
3066
- this._velocity.y = 0;
3067
- this.stopInertia();
3068
- }
3069
- _onPointerMove(e) {
3070
- if (!this._dragging)
3071
- return;
3072
- const dx = e.globalX - this._dragStart.x;
3073
- const dy = e.globalY - this._dragStart.y;
3074
- const { direction } = this._scrollConfig;
3075
- if (direction !== 'horizontal') {
3076
- this._content.y = this._contentStart.y + dy;
3077
- }
3078
- if (direction !== 'vertical') {
3079
- this._content.x = this._contentStart.x + dx;
3080
- }
3081
- // Track velocity
3082
- const now = Date.now();
3083
- const dt = now - this._lastDragTime;
3084
- if (dt > 0) {
3085
- this._velocity.x = (e.globalX - this._lastDragPos.x) / dt * 16;
3086
- this._velocity.y = (e.globalY - this._lastDragPos.y) / dt * 16;
3087
- }
3088
- this._lastDragPos.x = e.globalX;
3089
- this._lastDragPos.y = e.globalY;
3090
- this._lastDragTime = now;
3091
- this.clampScroll();
3092
- }
3093
- _onPointerUp() {
3094
- if (!this._dragging)
3095
- return;
3096
- this._dragging = false;
3097
- if (!this._scrollConfig.disableEasing &&
3098
- (Math.abs(this._velocity.x) > MIN_VELOCITY || Math.abs(this._velocity.y) > MIN_VELOCITY)) {
3099
- this.startInertia();
3100
- }
3101
- }
3102
- // ─── Inertia ─────────────────────────────────────────
3103
- startInertia() {
3104
- this._inertiaActive = true;
3105
- this._onTickBound = this._inertiaTick.bind(this);
3106
- pixi_js.Ticker.shared.add(this._onTickBound);
3107
- }
3108
- stopInertia() {
3109
- if (this._onTickBound && this._inertiaActive) {
3110
- pixi_js.Ticker.shared.remove(this._onTickBound);
3111
- this._inertiaActive = false;
3112
- }
3113
- }
3114
- _inertiaTick() {
3115
- const { direction } = this._scrollConfig;
3116
- if (direction !== 'horizontal') {
3117
- this._content.y += this._velocity.y;
3118
- this._velocity.y *= DECELERATION;
3119
- }
3120
- if (direction !== 'vertical') {
3121
- this._content.x += this._velocity.x;
3122
- this._velocity.x *= DECELERATION;
3123
- }
3124
- this.clampScroll();
3125
- if (Math.abs(this._velocity.x) < MIN_VELOCITY && Math.abs(this._velocity.y) < MIN_VELOCITY) {
3126
- this.stopInertia();
3127
- }
3128
- }
3129
- // ─── Mouse wheel ─────────────────────────────────────
3130
- _onWheel(e) {
3131
- const { direction } = this._scrollConfig;
3132
- e.preventDefault();
3133
- if (direction !== 'horizontal') {
3134
- this._content.y -= e.deltaY;
3135
- }
3136
- if (direction !== 'vertical') {
3137
- this._content.x -= e.deltaX;
3138
- }
3139
- this.clampScroll();
3140
- }
3141
- // ─── Scroll bounds ───────────────────────────────────
3142
- clampScroll() {
3143
- const { direction } = this._scrollConfig;
3144
- const bounds = this._content.getLocalBounds();
3145
- if (direction !== 'horizontal') {
3146
- const contentHeight = bounds.height + bounds.y;
3147
- const maxScroll = Math.min(0, this._viewport.height - contentHeight);
3148
- this._content.y = Math.max(maxScroll, Math.min(0, this._content.y));
3149
- }
3150
- if (direction !== 'vertical') {
3151
- const contentWidth = bounds.width + bounds.x;
3152
- const maxScroll = Math.min(0, this._viewport.width - contentWidth);
3153
- this._content.x = Math.max(maxScroll, Math.min(0, this._content.x));
3154
- }
3155
- this.updateScrollbar();
3156
- }
3157
- updateScrollbar() {
3158
- if (!this._scrollbar)
3159
- return;
3160
- const { direction } = this._scrollConfig;
3161
- const { width: sbW, padding: sbPad } = this._scrollbarConfig;
3162
- const bounds = this._content.getLocalBounds();
3163
- const isVert = direction !== 'horizontal';
3164
- if (isVert) {
3165
- const contentH = bounds.height + bounds.y;
3166
- if (contentH <= this._viewport.height) {
3167
- this._scrollbar.visible = false;
3168
- return;
3169
- }
3170
- this._scrollbar.visible = true;
3171
- const ratio = this._viewport.height / contentH;
3172
- const thumbH = Math.max(20, this._viewport.height * ratio);
3173
- const scrollRange = this._viewport.height - thumbH;
3174
- const scrollProgress = -this._content.y / (contentH - this._viewport.height);
3175
- this._scrollbar.x = this._viewport.width - sbW - sbPad;
3176
- this._scrollbar.y = scrollProgress * scrollRange;
3177
- this._scrollbar.height = thumbH;
3178
- this._scrollbar.width = sbW;
3179
- }
3180
- else {
3181
- const contentW = bounds.width + bounds.x;
3182
- if (contentW <= this._viewport.width) {
3183
- this._scrollbar.visible = false;
3184
- return;
3185
- }
3186
- this._scrollbar.visible = true;
3187
- const ratio = this._viewport.width / contentW;
3188
- const thumbW = Math.max(20, this._viewport.width * ratio);
3189
- const scrollRange = this._viewport.width - thumbW;
3190
- const scrollProgress = -this._content.x / (contentW - this._viewport.width);
3191
- this._scrollbar.y = this._viewport.height - sbW - sbPad;
3192
- this._scrollbar.x = scrollProgress * scrollRange;
3193
- this._scrollbar.width = thumbW;
3194
- this._scrollbar.height = sbW;
3195
- }
3196
- }
3197
- destroy(options) {
3198
- this.stopInertia();
3199
- this.off('pointerdown', this._onPointerDown, this);
3200
- this.off('pointermove', this._onPointerMove, this);
3201
- this.off('pointerup', this._onPointerUp, this);
3202
- this.off('pointerupoutside', this._onPointerUp, this);
3203
- this._items.length = 0;
3204
- super.destroy(options);
3205
- }
3206
- }
3207
-
3208
- /**
3209
- * Draggable slider with customizable track, fill, and handle views.
3210
- *
3211
- * @example
3212
- * ```ts
3213
- * const volume = new Slider({
3214
- * min: 0, max: 1, value: 0.5,
3215
- * width: 200, height: 8,
3216
- * fillColor: 0xffd700,
3217
- * onUpdate: (v) => console.log('Volume:', v),
3218
- * });
3219
- * ```
3220
- */
3221
- class Slider extends pixi_js.Container {
3222
- __uiComponent = true;
3223
- _track;
3224
- _fill;
3225
- _fillMask;
3226
- _handle;
3227
- _config;
3228
- _value;
3229
- _dragging = false;
3230
- onUpdate = null;
3231
- onChange = null;
3232
- constructor(config = {}) {
3233
- super();
3234
- this._config = {
3235
- min: config.min ?? 0,
3236
- max: config.max ?? 1,
3237
- step: config.step ?? 0,
3238
- width: config.width ?? 200,
3239
- height: config.height ?? 8,
3240
- borderRadius: config.borderRadius ?? 4,
3241
- trackColor: config.trackColor ?? 0x333333,
3242
- fillColor: config.fillColor ?? 0xffd700,
3243
- handleRadius: config.handleRadius ?? 12,
3244
- handleColor: config.handleColor ?? 0xffffff,
3245
- };
3246
- this._value = config.value ?? this._config.min;
3247
- this.onUpdate = config.onUpdate ?? null;
3248
- this.onChange = config.onChange ?? null;
3249
- const { width, height, borderRadius, trackColor, fillColor, handleRadius, handleColor } = this._config;
3250
- // Track
3251
- const customTrack = resolveView(config.trackView);
3252
- if (customTrack) {
3253
- customTrack.width = width;
3254
- customTrack.height = height;
3255
- this._track = customTrack;
3256
- }
3257
- else {
3258
- const g = new pixi_js.Graphics();
3259
- g.roundRect(0, 0, width, height, borderRadius).fill(trackColor);
3260
- this._track = g;
3261
- }
3262
- this.addChild(this._track);
3263
- // Fill
3264
- const customFill = resolveView(config.fillView);
3265
- if (customFill) {
3266
- customFill.width = width;
3267
- customFill.height = height;
3268
- this._fill = customFill;
3269
- }
3270
- else {
3271
- const g = new pixi_js.Graphics();
3272
- g.roundRect(0, 0, width, height, borderRadius).fill(fillColor);
3273
- this._fill = g;
3274
- }
3275
- this.addChild(this._fill);
3276
- // Fill mask
3277
- this._fillMask = new pixi_js.Graphics();
3278
- this.addChild(this._fillMask);
3279
- this._fill.mask = this._fillMask;
3280
- // Handle
3281
- const customHandle = resolveView(config.handleView);
3282
- if (customHandle) {
3283
- this._handle = customHandle;
3284
- }
3285
- else {
3286
- const g = new pixi_js.Graphics();
3287
- g.circle(0, 0, handleRadius).fill(handleColor);
3288
- this._handle = g;
3289
- }
3290
- this._handle.y = height / 2;
3291
- this.addChild(this._handle);
3292
- // Interaction
3293
- this.eventMode = 'static';
3294
- this.cursor = 'pointer';
3295
- // Hit area covers track + handle overflow
3296
- const hitPad = Math.max(handleRadius - height / 2, 0);
3297
- this.hitArea = { contains: (x, y) => x >= -hitPad && x <= width + hitPad && y >= -hitPad && y <= height + hitPad };
3298
- this.on('pointerdown', this._onPointerDown, this);
3299
- this.on('globalpointermove', this._onPointerMove, this);
3300
- this.on('pointerup', this._onPointerUp, this);
3301
- this.on('pointerupoutside', this._onPointerUp, this);
3302
- this._updateVisuals();
3303
- }
3304
- /** Current value */
3305
- get value() {
3306
- return this._value;
3307
- }
3308
- set value(v) {
3309
- const clamped = this._applyStep(Math.max(this._config.min, Math.min(this._config.max, v)));
3310
- if (clamped === this._value)
3311
- return;
3312
- this._value = clamped;
3313
- this._updateVisuals();
3314
- }
3315
- get min() { return this._config.min; }
3316
- get max() { return this._config.max; }
3317
- /** React reconciler update hook */
3318
- updateConfig(changed) {
3319
- if ('value' in changed)
3320
- this.value = changed.value;
3321
- if ('min' in changed) {
3322
- this._config.min = changed.min;
3323
- this._updateVisuals();
3324
- }
3325
- if ('max' in changed) {
3326
- this._config.max = changed.max;
3327
- this._updateVisuals();
3328
- }
3329
- if ('step' in changed)
3330
- this._config.step = changed.step;
3331
- if ('onUpdate' in changed)
3332
- this.onUpdate = changed.onUpdate;
3333
- if ('onChange' in changed)
3334
- this.onChange = changed.onChange;
3335
- }
3336
- _fraction() {
3337
- const { min, max } = this._config;
3338
- return max === min ? 0 : (this._value - min) / (max - min);
3339
- }
3340
- _applyStep(v) {
3341
- const { step, min } = this._config;
3342
- if (step <= 0)
3343
- return v;
3344
- return min + Math.round((v - min) / step) * step;
3345
- }
3346
- _updateVisuals() {
3347
- const frac = this._fraction();
3348
- const w = this._config.width;
3349
- const h = this._config.height;
3350
- // Update fill mask
3351
- this._fillMask.clear();
3352
- this._fillMask.rect(0, 0, w * frac, h).fill(0xffffff);
3353
- // Update handle position
3354
- this._handle.x = w * frac;
3355
- }
3356
- _valueFromPointer(e) {
3357
- const local = this.toLocal(e.global);
3358
- const frac = Math.max(0, Math.min(1, local.x / this._config.width));
3359
- const { min, max } = this._config;
3360
- return this._applyStep(min + frac * (max - min));
3361
- }
3362
- _onPointerDown(e) {
3363
- this._dragging = true;
3364
- const newValue = this._valueFromPointer(e);
3365
- if (newValue !== this._value) {
3366
- this._value = newValue;
3367
- this._updateVisuals();
3368
- this.onUpdate?.(this._value);
3369
- }
3370
- }
3371
- _onPointerMove(e) {
3372
- if (!this._dragging)
3373
- return;
3374
- const newValue = this._valueFromPointer(e);
3375
- if (newValue !== this._value) {
3376
- this._value = newValue;
3377
- this._updateVisuals();
3378
- this.onUpdate?.(this._value);
3379
- }
3380
- }
3381
- _onPointerUp(_e) {
3382
- if (!this._dragging)
3383
- return;
3384
- this._dragging = false;
3385
- this.onChange?.(this._value);
3386
- }
3387
- destroy(options) {
3388
- this.off('pointerdown', this._onPointerDown, this);
3389
- this.off('globalpointermove', this._onPointerMove, this);
3390
- this.off('pointerup', this._onPointerUp, this);
3391
- this.off('pointerupoutside', this._onPointerUp, this);
3392
- this.onUpdate = null;
3393
- this.onChange = null;
3394
- super.destroy(options);
3395
- }
3396
- }
3397
-
3398
- /**
3399
- * Toggle switch with two states.
3400
- *
3401
- * Supports custom ON/OFF views or auto-generated Graphics-based toggle.
3402
- * Click to toggle, or use `forceSwitch(value)` programmatically.
3403
- *
3404
- * @example
3405
- * ```ts
3406
- * const mute = new Toggle({
3407
- * value: false,
3408
- * onColor: 0x22cc22,
3409
- * onChange: (on) => audioManager.mute(!on),
3410
- * });
3411
- * ```
3412
- */
3413
- class Toggle extends pixi_js.Container {
3414
- __uiComponent = true;
3415
- _value;
3416
- _onView = null;
3417
- _offView = null;
3418
- _handle = null;
3419
- _trackGfx = null;
3420
- _config;
3421
- _useCustomViews;
3422
- onChange = null;
3423
- constructor(config = {}) {
3424
- super();
3425
- this._config = {
3426
- width: config.width ?? 52,
3427
- height: config.height ?? 28,
3428
- onColor: config.onColor ?? 0x22cc22,
3429
- offColor: config.offColor ?? 0x666666,
3430
- handleColor: config.handleColor ?? 0xffffff,
3431
- handleRadius: config.handleRadius ?? 0, // 0 = auto
3432
- animationDuration: config.animationDuration ?? 200,
3433
- };
3434
- this._value = config.value ?? false;
3435
- this.onChange = config.onChange ?? null;
3436
- const customOn = resolveView(config.onView);
3437
- const customOff = resolveView(config.offView);
3438
- this._useCustomViews = !!(customOn || customOff);
3439
- if (this._useCustomViews) {
3440
- // Custom view mode: show/hide ON and OFF views
3441
- if (customOn) {
3442
- this._onView = customOn;
3443
- this._onView.visible = this._value;
3444
- this.addChild(this._onView);
3445
- }
3446
- if (customOff) {
3447
- this._offView = customOff;
3448
- this._offView.visible = !this._value;
3449
- this.addChild(this._offView);
3450
- }
3451
- }
3452
- else {
3453
- // Graphics mode: track + sliding handle
3454
- const { width, height, handleColor } = this._config;
3455
- const handleRadius = this._config.handleRadius || (height / 2 - 3);
3456
- this._config.handleRadius = handleRadius;
3457
- this._trackGfx = new pixi_js.Graphics();
3458
- this.addChild(this._trackGfx);
3459
- this._drawTrack();
3460
- const handle = new pixi_js.Graphics();
3461
- handle.circle(0, 0, handleRadius).fill(handleColor);
3462
- handle.y = height / 2;
3463
- handle.x = this._value ? width - handleRadius - 3 : handleRadius + 3;
3464
- this._handle = handle;
3465
- this.addChild(handle);
3466
- }
3467
- // Interaction
3468
- this.eventMode = 'static';
3469
- this.cursor = 'pointer';
3470
- this.on('pointertap', this._onTap, this);
3471
- }
3472
- /** Current toggle state */
3473
- get value() {
3474
- return this._value;
3475
- }
3476
- set value(v) {
3477
- if (v === this._value)
3478
- return;
3479
- this.forceSwitch(v);
3480
- }
3481
- /** Programmatically switch to a specific state with animation */
3482
- forceSwitch(value) {
3483
- this._value = value;
3484
- this._animateToState();
3485
- }
3486
- /** React reconciler update hook */
3487
- updateConfig(changed) {
3488
- if ('value' in changed)
3489
- this.value = changed.value;
3490
- if ('onChange' in changed)
3491
- this.onChange = changed.onChange;
3492
- if ('animationDuration' in changed)
3493
- this._config.animationDuration = changed.animationDuration;
3494
- }
3495
- _onTap() {
3496
- this._value = !this._value;
3497
- this._animateToState();
3498
- this.onChange?.(this._value);
3499
- }
3500
- _animateToState() {
3501
- const duration = this._config.animationDuration;
3502
- if (this._useCustomViews) {
3503
- // Custom views: crossfade
3504
- if (this._onView) {
3505
- Tween.killTweensOf(this._onView);
3506
- if (this._value) {
3507
- this._onView.visible = true;
3508
- Tween.to(this._onView, { alpha: 1 }, duration);
3509
- }
3510
- else {
3511
- Tween.to(this._onView, { alpha: 0 }, duration).then(() => {
3512
- if (this._onView)
3513
- this._onView.visible = false;
3514
- });
3515
- }
3516
- }
3517
- if (this._offView) {
3518
- Tween.killTweensOf(this._offView);
3519
- if (!this._value) {
3520
- this._offView.visible = true;
3521
- Tween.to(this._offView, { alpha: 1 }, duration);
3522
- }
3523
- else {
3524
- Tween.to(this._offView, { alpha: 0 }, duration).then(() => {
3525
- if (this._offView)
3526
- this._offView.visible = false;
3527
- });
3528
- }
3529
- }
3530
- }
3531
- else {
3532
- // Graphics mode: slide handle + recolor track
3533
- this._drawTrack();
3534
- if (this._handle) {
3535
- const { width } = this._config;
3536
- const handleRadius = this._config.handleRadius;
3537
- const targetX = this._value ? width - handleRadius - 3 : handleRadius + 3;
3538
- Tween.killTweensOf(this._handle);
3539
- Tween.to(this._handle, { x: targetX }, duration);
3540
- }
3541
- }
3542
- }
3543
- _drawTrack() {
3544
- if (!this._trackGfx)
3545
- return;
3546
- const { width, height, onColor, offColor } = this._config;
3547
- const radius = height / 2;
3548
- this._trackGfx.clear();
3549
- this._trackGfx.roundRect(0, 0, width, height, radius).fill(this._value ? onColor : offColor);
3550
- }
3551
- destroy(options) {
3552
- this.off('pointertap', this._onTap, this);
3553
- if (this._handle)
3554
- Tween.killTweensOf(this._handle);
3555
- if (this._onView)
3556
- Tween.killTweensOf(this._onView);
3557
- if (this._offView)
3558
- Tween.killTweensOf(this._offView);
3559
- this.onChange = null;
3560
- super.destroy(options);
3561
- }
3562
- }
3563
-
3564
- /**
3565
- * Register all standard PixiJS display objects for JSX use.
3566
- * Call once at app startup before rendering any React scenes.
3567
- */
3568
- function extendPixiElements() {
3569
- extend({
3570
- Container: pixi_js.Container,
3571
- Sprite: pixi_js.Sprite,
3572
- Graphics: pixi_js.Graphics,
3573
- Text: pixi_js.Text,
3574
- AnimatedSprite: pixi_js.AnimatedSprite,
3575
- NineSliceSprite: pixi_js.NineSliceSprite,
3576
- TilingSprite: pixi_js.TilingSprite,
3577
- Mesh: pixi_js.Mesh,
3578
- MeshPlane: pixi_js.MeshPlane,
3579
- MeshRope: pixi_js.MeshRope,
3580
- MeshSimple: pixi_js.MeshSimple,
3581
- BitmapText: pixi_js.BitmapText,
3582
- HTMLText: pixi_js.HTMLText,
3583
- });
3584
- }
3585
- /**
3586
- * Register all engine UI components for JSX use.
3587
- * Call once at app startup before rendering React scenes that use UI components.
3588
- *
3589
- * @example
3590
- * ```ts
3591
- * extendPixiElements();
3592
- * extendUIElements();
3593
- *
3594
- * // Now you can use:
3595
- * // <button text="SPIN" onPress={handler} />
3596
- * // <flexContainer direction="row" gap={16}>...</flexContainer>
3597
- * // <label text="Hello" style-fontSize={24} />
3598
- * ```
3599
- */
3600
- function extendUIElements() {
3601
- extend({
3602
- Button, Label, LabelValue, Panel, FlexContainer, ProgressBar,
3603
- ScrollContainer, Modal, Toast, BalanceDisplay, WinDisplay, Layout,
3604
- Slider, Toggle,
3605
- });
3606
- }
3607
- /**
3608
- * Register additional custom components for JSX use.
3609
- * Pass an object mapping component names to their constructors.
3610
- */
3611
- function extendCustomElements(components) {
3612
- extend(components);
3613
- }
3614
-
3615
- /**
3616
- * Base class for all scenes.
3617
- * Provides a root PixiJS Container and lifecycle hooks.
3618
- *
3619
- * @example
3620
- * ```ts
3621
- * class MenuScene extends Scene {
3622
- * async onEnter() {
3623
- * const bg = Sprite.from('menu-bg');
3624
- * this.container.addChild(bg);
3625
- * }
3626
- *
3627
- * onUpdate(dt: number) {
3628
- * // per-frame logic
3629
- * }
3630
- *
3631
- * onResize(width: number, height: number) {
3632
- * // reposition UI
3633
- * }
3634
- * }
3635
- * ```
3636
- */
3637
- class Scene {
3638
- container;
3639
- constructor() {
3640
- this.container = new pixi_js.Container();
3641
- this.container.label = this.constructor.name;
3642
- }
3643
- }
3644
-
3645
- const EngineContext = react.createContext(null);
3646
- function useEngine() {
3647
- const ctx = react.useContext(EngineContext);
3648
- if (!ctx)
3649
- throw new Error('useEngine() must be used inside a ReactScene');
3650
- return ctx;
3651
- }
3652
-
3653
- // ─── Scale Modes ───────────────────────────────────────────
3654
- var ScaleMode;
3655
- (function (ScaleMode) {
3656
- /** Fit inside container, maintain aspect ratio (letterbox/pillarbox) */
3657
- ScaleMode["FIT"] = "FIT";
3658
- /** Fill container, maintain aspect ratio (crop edges) */
3659
- ScaleMode["FILL"] = "FILL";
3660
- /** Stretch to fill (distorts) */
3661
- ScaleMode["STRETCH"] = "STRETCH";
3662
- })(ScaleMode || (ScaleMode = {}));
3663
- // ─── Orientation ───────────────────────────────────────────
3664
- var Orientation;
3665
- (function (Orientation) {
3666
- Orientation["LANDSCAPE"] = "landscape";
3667
- Orientation["PORTRAIT"] = "portrait";
3668
- Orientation["ANY"] = "any";
3669
- })(Orientation || (Orientation = {}));
3670
- // ─── Transition Types ──────────────────────────────────────
3671
- var TransitionType;
3672
- (function (TransitionType) {
3673
- TransitionType["NONE"] = "none";
3674
- TransitionType["FADE"] = "fade";
3675
- TransitionType["SLIDE_LEFT"] = "slide-left";
3676
- TransitionType["SLIDE_RIGHT"] = "slide-right";
3677
- })(TransitionType || (TransitionType = {}));
3678
-
3679
- class ReactScene extends Scene {
3680
- _pixiRoot = null;
3681
- _contextValue = null;
3682
- /** Access the GameApplication instance. */
3683
- getApp() {
3684
- const app = this.__engineApp;
3685
- if (!app) {
3686
- throw new Error('[ReactScene] No GameApplication reference. ' +
3687
- 'Ensure this scene is managed by SceneManager (not instantiated manually).');
3688
- }
3689
- return app;
3690
- }
3691
- async onEnter(data) {
3692
- const app = this.getApp();
3693
- this._contextValue = {
3694
- app,
3695
- sdk: app.sdk,
3696
- audio: app.audio,
3697
- input: app.input,
3698
- viewport: app.viewport,
3699
- gameConfig: app.gameConfig,
3700
- screen: {
3701
- width: app.viewport.width,
3702
- height: app.viewport.height,
3703
- scale: app.viewport.scale,
3704
- },
3705
- isPortrait: app.viewport.orientation === Orientation.PORTRAIT,
3706
- };
3707
- this._pixiRoot = createPixiRoot(this.container);
3708
- this._mountReactTree();
3709
- }
3710
- async onExit() {
3711
- this._pixiRoot?.unmount();
3712
- this._pixiRoot = null;
3713
- this._contextValue = null;
3714
- }
3715
- onResize(width, height) {
3716
- if (!this._contextValue)
3717
- return;
3718
- const app = this.getApp();
3719
- this._contextValue = {
3720
- ...this._contextValue,
3721
- screen: { width, height, scale: app.viewport.scale },
3722
- isPortrait: height > width,
3723
- };
3724
- this._mountReactTree();
3725
- }
3726
- onDestroy() {
3727
- this._pixiRoot?.unmount();
3728
- this._pixiRoot = null;
3729
- this._contextValue = null;
3730
- }
3731
- _mountReactTree() {
3732
- if (!this._pixiRoot || !this._contextValue)
3733
- return;
3734
- this._pixiRoot.render(react.createElement(EngineContext.Provider, { value: this._contextValue }, this.render()));
3735
- }
3736
- }
3737
-
3738
- function useSDK() {
3739
- return useEngine().sdk;
3740
- }
3741
- function useAudio() {
3742
- return useEngine().audio;
3743
- }
3744
- function useInput() {
3745
- return useEngine().input;
3746
- }
3747
- function useViewport() {
3748
- const { screen, isPortrait } = useEngine();
3749
- return { ...screen, isPortrait };
3750
- }
3751
- function useBalance() {
3752
- const { sdk } = useEngine();
3753
- const [balance, setBalance] = react.useState(sdk?.balance ?? 0);
3754
- react.useEffect(() => {
3755
- if (!sdk)
3756
- return;
3757
- const handler = (data) => setBalance(data.balance);
3758
- sdk.on('balanceUpdate', handler);
3759
- return () => {
3760
- sdk.off('balanceUpdate', handler);
3761
- };
3762
- }, [sdk]);
3763
- return balance;
3764
- }
3765
- function useSession() {
3766
- return useEngine().app.session;
3767
- }
3768
- function useGameConfig() {
3769
- return useEngine().gameConfig;
3770
- }
3771
-
3772
- exports.EngineContext = EngineContext;
3773
- exports.ReactScene = ReactScene;
3774
- exports.createPixiRoot = createPixiRoot;
3775
- exports.extend = extend;
3776
- exports.extendCustomElements = extendCustomElements;
3777
- exports.extendPixiElements = extendPixiElements;
3778
- exports.extendUIElements = extendUIElements;
3779
- exports.useAudio = useAudio;
3780
- exports.useBalance = useBalance;
3781
- exports.useEngine = useEngine;
3782
- exports.useGameConfig = useGameConfig;
3783
- exports.useInput = useInput;
3784
- exports.useSDK = useSDK;
3785
- exports.useSession = useSession;
3786
- exports.useViewport = useViewport;
3787
- //# sourceMappingURL=react.cjs.js.map