@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/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Ticker, Assets, Container, Text, Application, AnimatedSprite, Texture, Sprite, Graphics, NineSliceSprite } from 'pixi.js';
1
+ import { Ticker, Assets, Container, Text, Application, AnimatedSprite, Texture } from 'pixi.js';
2
2
  import { createPlatformSession } from '@energy8platform/platform-core';
3
3
  import { waitCSSPreloaderTap, removeCSSPreloader, setCSSPreloaderProgress, createCSSPreloader } from '@energy8platform/platform-core/loading';
4
4
  export { BridgeDestroyedError, BridgeNotReadyError, SDKError, TimeoutError } from '@energy8platform/game-sdk';
@@ -187,6 +187,10 @@ class Tween {
187
187
  * @param onUpdate - Progress callback (0..1)
188
188
  */
189
189
  static to(target, props, duration, easing, onUpdate) {
190
+ // A destroyed (Pixi) target has null transform fields — skip rather than throw. This guards
191
+ // animations whose target is torn down mid-flight (e.g. a reel grid rebuilt during a spin).
192
+ if (target == null || target.destroyed)
193
+ return Promise.resolve();
190
194
  return new Promise((resolve) => {
191
195
  // Capture starting values
192
196
  const from = {};
@@ -212,6 +216,8 @@ class Tween {
212
216
  * Animate properties from given values to current values.
213
217
  */
214
218
  static from(target, props, duration, easing, onUpdate) {
219
+ if (target == null || target.destroyed)
220
+ return Promise.resolve();
215
221
  // Capture current values as "to"
216
222
  const to = {};
217
223
  for (const key of Object.keys(props)) {
@@ -224,6 +230,8 @@ class Tween {
224
230
  * Animate from one set of values to another.
225
231
  */
226
232
  static fromTo(target, fromProps, toProps, duration, easing, onUpdate) {
233
+ if (target == null || target.destroyed)
234
+ return Promise.resolve();
227
235
  // Set starting values
228
236
  for (const key of Object.keys(fromProps)) {
229
237
  Tween.setProperty(target, key, fromProps[key]);
@@ -297,6 +305,11 @@ class Tween {
297
305
  const dt = ticker.deltaMS;
298
306
  const completed = [];
299
307
  for (const tw of Tween._tweens) {
308
+ // target torn down mid-tween → finish it quietly
309
+ if (tw.target?.destroyed) {
310
+ completed.push(tw);
311
+ continue;
312
+ }
300
313
  tw.elapsed += dt;
301
314
  if (tw.elapsed < tw.delay)
302
315
  continue;
@@ -334,9 +347,9 @@ class Tween {
334
347
  const parts = key.split('.');
335
348
  let obj = target;
336
349
  for (let i = 0; i < parts.length - 1; i++) {
337
- obj = obj[parts[i]];
350
+ obj = obj?.[parts[i]];
338
351
  }
339
- return obj[parts[parts.length - 1]] ?? 0;
352
+ return obj?.[parts[parts.length - 1]] ?? 0;
340
353
  }
341
354
  /**
342
355
  * Set a potentially nested property.
@@ -345,8 +358,10 @@ class Tween {
345
358
  const parts = key.split('.');
346
359
  let obj = target;
347
360
  for (let i = 0; i < parts.length - 1; i++) {
348
- obj = obj[parts[i]];
361
+ obj = obj?.[parts[i]];
349
362
  }
363
+ if (obj == null)
364
+ return;
350
365
  obj[parts[parts.length - 1]] = value;
351
366
  }
352
367
  }
@@ -2035,204 +2050,6 @@ class GameApplication extends EventEmitter {
2035
2050
  }
2036
2051
  }
2037
2052
 
2038
- /**
2039
- * Generic finite state machine for game flow management.
2040
- *
2041
- * Supports:
2042
- * - Typed context object shared across all states
2043
- * - Async enter/exit hooks
2044
- * - Per-frame update per state
2045
- * - Transition guards
2046
- * - Event emission on state change
2047
- *
2048
- * @example
2049
- * ```ts
2050
- * interface GameContext {
2051
- * balance: number;
2052
- * bet: number;
2053
- * lastWin: number;
2054
- * }
2055
- *
2056
- * const fsm = new StateMachine<GameContext>({ balance: 1000, bet: 10, lastWin: 0 });
2057
- *
2058
- * fsm.addState('idle', {
2059
- * enter: (ctx) => console.log('Waiting for spin...'),
2060
- * update: (ctx, dt) => { // optional per-frame },
2061
- * });
2062
- *
2063
- * fsm.addState('spinning', {
2064
- * enter: async (ctx) => {
2065
- * const result = await sdk.play({ action: 'spin', bet: ctx.bet });
2066
- * ctx.lastWin = result.totalWin;
2067
- * await fsm.transition('presenting');
2068
- * },
2069
- * });
2070
- *
2071
- * fsm.addState('presenting', {
2072
- * enter: async (ctx) => {
2073
- * await showWinPresentation(ctx.lastWin);
2074
- * await fsm.transition('idle');
2075
- * },
2076
- * });
2077
- *
2078
- * // Optional guard
2079
- * fsm.addGuard('idle', 'spinning', (ctx) => ctx.balance >= ctx.bet);
2080
- *
2081
- * await fsm.start('idle');
2082
- * ```
2083
- */
2084
- class StateMachine extends EventEmitter {
2085
- static MAX_TRANSITION_DEPTH = 10;
2086
- _states = new Map();
2087
- _guards = new Map();
2088
- _current = null;
2089
- _transitionDepth = 0;
2090
- _context;
2091
- constructor(context) {
2092
- super();
2093
- this._context = context;
2094
- }
2095
- /** Current state name */
2096
- get current() {
2097
- return this._current;
2098
- }
2099
- /** Whether a transition is in progress */
2100
- get isTransitioning() {
2101
- return this._transitionDepth > 0;
2102
- }
2103
- /** State machine context (shared data) */
2104
- get context() {
2105
- return this._context;
2106
- }
2107
- /**
2108
- * Register a state with optional enter/exit/update hooks.
2109
- */
2110
- addState(name, config) {
2111
- this._states.set(name, config);
2112
- return this;
2113
- }
2114
- /**
2115
- * Add a transition guard.
2116
- * The guard function must return true to allow the transition.
2117
- *
2118
- * @param from - Source state
2119
- * @param to - Target state
2120
- * @param guard - Guard function
2121
- */
2122
- addGuard(from, to, guard) {
2123
- this._guards.set(`${from}->${to}`, guard);
2124
- return this;
2125
- }
2126
- /**
2127
- * Start the state machine in the given initial state.
2128
- */
2129
- async start(initialState, data) {
2130
- if (this._current !== null) {
2131
- throw new Error('[StateMachine] Already started. Use transition() to change states.');
2132
- }
2133
- const state = this._states.get(initialState);
2134
- if (!state) {
2135
- throw new Error(`[StateMachine] State "${initialState}" not registered.`);
2136
- }
2137
- this._current = initialState;
2138
- await state.enter?.(this._context, data);
2139
- this.emit('transition', { from: null, to: initialState });
2140
- }
2141
- /**
2142
- * Transition to a new state.
2143
- *
2144
- * @param to - Target state name
2145
- * @param data - Optional data passed to the new state's enter hook
2146
- * @returns true if the transition succeeded, false if blocked by a guard
2147
- */
2148
- async transition(to, data) {
2149
- if (this._transitionDepth >= StateMachine.MAX_TRANSITION_DEPTH) {
2150
- throw new Error('[StateMachine] Max transition depth exceeded — possible infinite loop');
2151
- }
2152
- const from = this._current;
2153
- // Check guard
2154
- if (from !== null) {
2155
- const guardKey = `${from}->${to}`;
2156
- const guard = this._guards.get(guardKey);
2157
- if (guard && !guard(this._context)) {
2158
- return false;
2159
- }
2160
- }
2161
- const toState = this._states.get(to);
2162
- if (!toState) {
2163
- throw new Error(`[StateMachine] State "${to}" not registered.`);
2164
- }
2165
- this._transitionDepth++;
2166
- try {
2167
- // Exit current state
2168
- if (from !== null) {
2169
- const fromState = this._states.get(from);
2170
- await fromState?.exit?.(this._context);
2171
- }
2172
- // Enter new state
2173
- this._current = to;
2174
- await toState.enter?.(this._context, data);
2175
- this.emit('transition', { from, to });
2176
- }
2177
- catch (err) {
2178
- this.emit('error', err instanceof Error ? err : new Error(String(err)));
2179
- throw err;
2180
- }
2181
- finally {
2182
- this._transitionDepth--;
2183
- }
2184
- return true;
2185
- }
2186
- /**
2187
- * Call the current state's update function.
2188
- * Should be called from the game loop.
2189
- */
2190
- update(dt) {
2191
- if (this._current === null)
2192
- return;
2193
- const state = this._states.get(this._current);
2194
- state?.update?.(this._context, dt);
2195
- }
2196
- /**
2197
- * Check if a state is registered.
2198
- */
2199
- hasState(name) {
2200
- return this._states.has(name);
2201
- }
2202
- /**
2203
- * Check if a transition is allowed (guard passes).
2204
- */
2205
- canTransition(to) {
2206
- if (this._current === null)
2207
- return false;
2208
- const guardKey = `${this._current}->${to}`;
2209
- const guard = this._guards.get(guardKey);
2210
- if (!guard)
2211
- return true;
2212
- return guard(this._context);
2213
- }
2214
- /**
2215
- * Reset the state machine (exit current state, clear current).
2216
- */
2217
- async reset() {
2218
- if (this._current !== null) {
2219
- const state = this._states.get(this._current);
2220
- await state?.exit?.(this._context);
2221
- }
2222
- this._current = null;
2223
- this._transitionDepth = 0;
2224
- }
2225
- /**
2226
- * Destroy the state machine.
2227
- */
2228
- async destroy() {
2229
- await this.reset();
2230
- this._states.clear();
2231
- this._guards.clear();
2232
- this.removeAllListeners();
2233
- }
2234
- }
2235
-
2236
2053
  /**
2237
2054
  * Sequential/parallel animation timeline built on top of Tween.
2238
2055
  *
@@ -2645,2327 +2462,5 @@ class SpriteAnimation {
2645
2462
  }
2646
2463
  }
2647
2464
 
2648
- // ─── Helpers ─────────────────────────────────────────────
2649
- function normalizePadding(p) {
2650
- return typeof p === 'number' ? [p, p, p, p] : p;
2651
- }
2652
- /** Resolve padding from config: individual props override the base `padding` value */
2653
- function resolvePadding(config) {
2654
- const base = normalizePadding(config.padding ?? 0);
2655
- return [
2656
- config.paddingTop ?? base[0],
2657
- config.paddingRight ?? base[1],
2658
- config.paddingBottom ?? base[2],
2659
- config.paddingLeft ?? base[3],
2660
- ];
2661
- }
2662
- /** Resolve a dimension value — number passes through, "50%" resolves against reference */
2663
- function resolveDimension(value, reference) {
2664
- if (value === undefined)
2665
- return undefined;
2666
- if (typeof value === 'number')
2667
- return value;
2668
- if (typeof value === 'string' && value.endsWith('%')) {
2669
- const pct = parseFloat(value);
2670
- if (!isNaN(pct) && reference > 0 && isFinite(reference))
2671
- return (pct / 100) * reference;
2672
- }
2673
- return undefined;
2674
- }
2675
- /** Measure a child's size and bounds offset for layout purposes */
2676
- function measureChild(child, parentContentW = 0, parentContentH = 0) {
2677
- const cfg = child._flexConfig;
2678
- const resolvedLW = resolveDimension(cfg?.layoutWidth, parentContentW);
2679
- const resolvedLH = resolveDimension(cfg?.layoutHeight, parentContentH);
2680
- // FlexContainer children are top-left origin by construction, so `ox/oy = 0`
2681
- // is correct and we can skip the `getLocalBounds()` call entirely.
2682
- if (child instanceof FlexContainer) {
2683
- const fc = child;
2684
- const w = fc._explicitWidth > 0 ? fc._explicitWidth : (fc._computedWidth > 0 ? fc._computedWidth : undefined);
2685
- const h = fc._explicitHeight > 0 ? fc._explicitHeight : (fc._computedHeight > 0 ? fc._computedHeight : undefined);
2686
- if (w !== undefined && h !== undefined) {
2687
- return { w: resolvedLW ?? w, h: resolvedLH ?? h, ox: 0, oy: 0 };
2688
- }
2689
- }
2690
- // Use localBounds to get the true visual origin offset.
2691
- // We take `ox/oy` from bounds unconditionally — a user-supplied `layoutWidth/Height`
2692
- // overrides the SIZE used by flex (protection against pre-paint bounds of 0), but
2693
- // it must NOT erase the center-anchor compensation: Button/Label views are drawn at
2694
- // `(-w/2..w/2)` and their bounds.x = -w/2 is what lets `layoutLine` place the
2695
- // visible rectangle where the layout intends.
2696
- const bounds = child.getLocalBounds();
2697
- return {
2698
- w: resolvedLW ?? bounds.width,
2699
- h: resolvedLH ?? bounds.height,
2700
- ox: bounds.x,
2701
- oy: bounds.y,
2702
- };
2703
- }
2704
- /**
2705
- * Set a child's main or cross dimension.
2706
- * For FlexContainer children, calls resize() to trigger internal relayout
2707
- * instead of the PixiJS scale setter.
2708
- */
2709
- function setChildMainSize(child, isRow, mainSize, item) {
2710
- if (child instanceof FlexContainer) {
2711
- const fc = child;
2712
- fc.resize(isRow ? mainSize : fc._explicitWidth || fc._computedWidth, isRow ? fc._explicitHeight || fc._computedHeight : mainSize);
2713
- }
2714
- else {
2715
- if (isRow) {
2716
- child.width = mainSize;
2717
- }
2718
- else {
2719
- child.height = mainSize;
2720
- }
2721
- }
2722
- if (isRow)
2723
- item.w = mainSize;
2724
- else
2725
- item.h = mainSize;
2726
- }
2727
- function setChildCrossSize(child, isRow, crossSize) {
2728
- if (child instanceof FlexContainer) {
2729
- const fc = child;
2730
- fc.resize(isRow ? fc._explicitWidth || fc._computedWidth : crossSize, isRow ? crossSize : fc._explicitHeight || fc._computedHeight);
2731
- }
2732
- else {
2733
- if (isRow) {
2734
- child.height = crossSize;
2735
- }
2736
- else {
2737
- child.width = crossSize;
2738
- }
2739
- }
2740
- }
2741
- function layoutLine(items, isRow, mainSize, justify, align, gap, crossOffset, crossSize) {
2742
- if (items.length === 0)
2743
- return;
2744
- // Compute total fixed main size and flex grow total
2745
- let totalFixed = 0;
2746
- let totalGrow = 0;
2747
- for (const item of items) {
2748
- const grow = item.child._flexConfig?.flexGrow ?? 0;
2749
- if (grow > 0) {
2750
- totalGrow += grow;
2751
- }
2752
- else {
2753
- totalFixed += isRow ? item.w : item.h;
2754
- }
2755
- }
2756
- const totalGap = gap * (items.length - 1);
2757
- const availableForFlex = Math.max(0, mainSize - totalFixed - totalGap);
2758
- // Resolve flex sizes
2759
- if (totalGrow > 0) {
2760
- for (const item of items) {
2761
- const grow = item.child._flexConfig?.flexGrow ?? 0;
2762
- if (grow > 0) {
2763
- const flexSize = (grow / totalGrow) * availableForFlex;
2764
- setChildMainSize(item.child, isRow, flexSize, item);
2765
- }
2766
- }
2767
- }
2768
- // Shrink: if content overflows and mainSize is finite, shrink eligible items
2769
- if (totalGrow === 0 && mainSize > 0) {
2770
- const overflow = totalFixed + totalGap - mainSize;
2771
- if (overflow > 0) {
2772
- let totalShrinkable = 0;
2773
- for (const item of items) {
2774
- const shrink = item.child._flexConfig?.flexShrink ?? 1;
2775
- if (shrink > 0) {
2776
- totalShrinkable += isRow ? item.w : item.h;
2777
- }
2778
- }
2779
- if (totalShrinkable > 0) {
2780
- for (const item of items) {
2781
- const shrink = item.child._flexConfig?.flexShrink ?? 1;
2782
- if (shrink > 0) {
2783
- const itemMain = isRow ? item.w : item.h;
2784
- const reduction = overflow * (itemMain / totalShrinkable);
2785
- const newSize = Math.max(0, itemMain - reduction);
2786
- setChildMainSize(item.child, isRow, newSize, item);
2787
- }
2788
- }
2789
- }
2790
- }
2791
- }
2792
- // Calculate total main size after flex
2793
- let totalMain = totalGap;
2794
- for (const item of items) {
2795
- totalMain += isRow ? item.w : item.h;
2796
- }
2797
- // Justify: compute starting offset and extra spacing
2798
- let mainOffset = 0;
2799
- let extraGap = 0;
2800
- switch (justify) {
2801
- case 'start':
2802
- break;
2803
- case 'center':
2804
- mainOffset = Math.max(0, (mainSize - totalMain) / 2);
2805
- break;
2806
- case 'end':
2807
- mainOffset = Math.max(0, mainSize - totalMain);
2808
- break;
2809
- case 'space-between':
2810
- if (items.length > 1) {
2811
- extraGap = Math.max(0, (mainSize - totalMain + totalGap) / (items.length - 1)) - gap;
2812
- }
2813
- break;
2814
- case 'space-around':
2815
- if (items.length > 0) {
2816
- const totalSpace = Math.max(0, mainSize - totalMain + totalGap);
2817
- const segment = totalSpace / items.length;
2818
- mainOffset = segment / 2;
2819
- extraGap = segment - gap;
2820
- }
2821
- break;
2822
- }
2823
- // Position each item
2824
- let pos = mainOffset;
2825
- for (const item of items) {
2826
- const mainDim = isRow ? item.w : item.h;
2827
- const crossDim = isRow ? item.h : item.w;
2828
- // Cross-axis alignment (alignSelf overrides align)
2829
- const effectiveAlign = (item.child._flexConfig?.alignSelf && item.child._flexConfig.alignSelf !== 'auto')
2830
- ? item.child._flexConfig.alignSelf
2831
- : align;
2832
- let crossPos = crossOffset;
2833
- switch (effectiveAlign) {
2834
- case 'start':
2835
- break;
2836
- case 'center':
2837
- crossPos += (crossSize - crossDim) / 2;
2838
- break;
2839
- case 'end':
2840
- crossPos += crossSize - crossDim;
2841
- break;
2842
- case 'stretch':
2843
- setChildCrossSize(item.child, isRow, crossSize);
2844
- break;
2845
- }
2846
- // Compensate for local bounds offset (e.g. centered anchors)
2847
- if (isRow) {
2848
- item.child.x = pos - item.ox;
2849
- item.child.y = crossPos - item.oy;
2850
- }
2851
- else {
2852
- item.child.x = crossPos - item.ox;
2853
- item.child.y = pos - item.oy;
2854
- }
2855
- pos += mainDim + gap + extraGap;
2856
- }
2857
- }
2858
- // ─── FlexContainer ───────────────────────────────────────
2859
- /**
2860
- * Lightweight flexbox-like layout container for PixiJS.
2861
- *
2862
- * Supports row/column direction, justify/align, gap, padding, wrapping,
2863
- * and flex-grow distribution. Zero external dependencies.
2864
- *
2865
- * @example
2866
- * ```ts
2867
- * const toolbar = new FlexContainer({
2868
- * direction: 'row',
2869
- * justifyContent: 'space-between',
2870
- * alignItems: 'center',
2871
- * gap: 16,
2872
- * padding: 12,
2873
- * });
2874
- *
2875
- * toolbar.addFlexChild(button1);
2876
- * toolbar.addFlexChild(button2);
2877
- * toolbar.resize(800, 60);
2878
- * ```
2879
- */
2880
- class FlexContainer extends Container {
2881
- __uiComponent = true;
2882
- _config;
2883
- _padding;
2884
- _maxWidth;
2885
- _maxHeight;
2886
- /** @internal */ _explicitWidth;
2887
- /** @internal */ _explicitHeight;
2888
- /** @internal */ _computedWidth = 0;
2889
- /** @internal */ _computedHeight = 0;
2890
- /** @internal */ _availableWidth = 0;
2891
- /** @internal */ _availableHeight = 0;
2892
- /** @internal */ _rawWidth;
2893
- /** @internal */ _rawHeight;
2894
- _layoutChildren = [];
2895
- _layoutDirty = true;
2896
- _layoutSuspended = false;
2897
- constructor(config = {}) {
2898
- super();
2899
- this._config = {
2900
- direction: config.direction ?? 'row',
2901
- justifyContent: config.justifyContent ?? 'start',
2902
- alignItems: config.alignItems ?? 'start',
2903
- gap: config.gap ?? 0,
2904
- flexWrap: config.flexWrap ?? false,
2905
- alignContent: config.alignContent ?? 'start',
2906
- };
2907
- this._padding = resolvePadding(config);
2908
- this._maxWidth = config.maxWidth ?? Infinity;
2909
- this._maxHeight = config.maxHeight ?? Infinity;
2910
- this._rawWidth = config.width ?? 0;
2911
- this._rawHeight = config.height ?? 0;
2912
- this._explicitWidth = typeof this._rawWidth === 'number' ? this._rawWidth : 0;
2913
- this._explicitHeight = typeof this._rawHeight === 'number' ? this._rawHeight : 0;
2914
- }
2915
- // ─── Public API ──────────────────────────────────────
2916
- /** Add a child with optional flex config. Also registers in flex layout. */
2917
- addFlexChild(child, flexConfig) {
2918
- if (flexConfig)
2919
- child._flexConfig = flexConfig;
2920
- if (!this._layoutChildren.includes(child)) {
2921
- this._layoutChildren.push(child);
2922
- this._layoutDirty = true;
2923
- }
2924
- super.addChild(child);
2925
- return this;
2926
- }
2927
- /** Remove a child from flex layout and display list */
2928
- removeFlexChild(child) {
2929
- const idx = this._layoutChildren.indexOf(child);
2930
- if (idx !== -1) {
2931
- this._layoutChildren.splice(idx, 1);
2932
- this._layoutDirty = true;
2933
- }
2934
- super.removeChild(child);
2935
- return this;
2936
- }
2937
- /** Remove all flex children */
2938
- clearFlexChildren() {
2939
- for (const child of this._layoutChildren) {
2940
- super.removeChild(child);
2941
- }
2942
- this._layoutChildren.length = 0;
2943
- this._layoutDirty = true;
2944
- return this;
2945
- }
2946
- /**
2947
- * Override addChild so children automatically participate in flex layout.
2948
- * This enables declarative usage from React JSX.
2949
- */
2950
- addChild(...children) {
2951
- for (const child of children) {
2952
- if (!this._layoutChildren.includes(child)) {
2953
- this._layoutChildren.push(child);
2954
- this._layoutDirty = true;
2955
- }
2956
- }
2957
- const result = super.addChild(...children);
2958
- if (this._layoutDirty && !this._layoutSuspended)
2959
- this.updateLayout();
2960
- return result;
2961
- }
2962
- addChildAt(child, index) {
2963
- if (!this._layoutChildren.includes(child)) {
2964
- // Insert into layout children at matching position
2965
- const layoutIndex = Math.min(index, this._layoutChildren.length);
2966
- this._layoutChildren.splice(layoutIndex, 0, child);
2967
- this._layoutDirty = true;
2968
- }
2969
- const result = super.addChildAt(child, index);
2970
- if (this._layoutDirty && !this._layoutSuspended)
2971
- this.updateLayout();
2972
- return result;
2973
- }
2974
- removeChild(...children) {
2975
- for (const child of children) {
2976
- const idx = this._layoutChildren.indexOf(child);
2977
- if (idx !== -1) {
2978
- this._layoutChildren.splice(idx, 1);
2979
- this._layoutDirty = true;
2980
- }
2981
- }
2982
- return super.removeChild(...children);
2983
- }
2984
- /** Get all flex layout children (read-only) */
2985
- get flexChildren() {
2986
- return this._layoutChildren;
2987
- }
2988
- /** Suspend automatic layout recalculation. Call resumeLayout() to flush. */
2989
- suspendLayout() {
2990
- this._layoutSuspended = true;
2991
- }
2992
- /** Resume automatic layout and flush if dirty. */
2993
- resumeLayout() {
2994
- this._layoutSuspended = false;
2995
- if (this._layoutDirty)
2996
- this.updateLayout();
2997
- }
2998
- /** Update the container size and recalculate layout */
2999
- resize(width, height) {
3000
- this._explicitWidth = width;
3001
- this._explicitHeight = height;
3002
- this._layoutDirty = true;
3003
- if (!this._layoutSuspended)
3004
- this.updateLayout();
3005
- }
3006
- /** Update layout direction */
3007
- setDirection(direction) {
3008
- this._config.direction = direction;
3009
- this._layoutDirty = true;
3010
- }
3011
- /** Update justifyContent */
3012
- setJustifyContent(justify) {
3013
- this._config.justifyContent = justify;
3014
- this._layoutDirty = true;
3015
- }
3016
- /** Update alignItems */
3017
- setAlignItems(align) {
3018
- this._config.alignItems = align;
3019
- this._layoutDirty = true;
3020
- }
3021
- /** Update gap */
3022
- setGap(gap) {
3023
- this._config.gap = gap;
3024
- this._layoutDirty = true;
3025
- }
3026
- /** Update padding */
3027
- setPadding(padding) {
3028
- this._padding = normalizePadding(padding);
3029
- this._layoutDirty = true;
3030
- }
3031
- /**
3032
- * Recalculate and apply layout positions for all children.
3033
- * Called automatically by `resize()`. Call manually after
3034
- * adding/removing children without resize.
3035
- */
3036
- updateLayout() {
3037
- if (this._layoutSuspended) {
3038
- this._layoutDirty = true;
3039
- return;
3040
- }
3041
- this._layoutDirty = false;
3042
- const { direction, justifyContent, alignItems, gap, flexWrap, alignContent } = this._config;
3043
- const [pt, pr, pb, pl] = this._padding;
3044
- const isRow = direction === 'row';
3045
- // Resolve percentage width/height against parent's available space
3046
- if (typeof this._rawWidth === 'string') {
3047
- this._explicitWidth = resolveDimension(this._rawWidth, this._availableWidth) ?? 0;
3048
- }
3049
- if (typeof this._rawHeight === 'string') {
3050
- this._explicitHeight = resolveDimension(this._rawHeight, this._availableHeight) ?? 0;
3051
- }
3052
- const contentW = this._explicitWidth > 0 ? this._explicitWidth - pl - pr : Infinity;
3053
- const contentH = this._explicitHeight > 0 ? this._explicitHeight - pt - pb : Infinity;
3054
- const mainLimit = isRow ? contentW : contentH;
3055
- const crossLimit = isRow ? contentH : contentW;
3056
- // Pass content area to measureChild for percentage resolution
3057
- const pctRefW = contentW < Infinity ? contentW : 0;
3058
- const pctRefH = contentH < Infinity ? contentH : 0;
3059
- // Propagate available size to child FlexContainers and resolve their percentages
3060
- for (const child of this._layoutChildren) {
3061
- if (child instanceof FlexContainer) {
3062
- const fc = child;
3063
- fc._availableWidth = pctRefW;
3064
- fc._availableHeight = pctRefH;
3065
- // If child has percentage dimensions, trigger its layout to resolve them
3066
- if (typeof fc._rawWidth === 'string' || typeof fc._rawHeight === 'string') {
3067
- fc.updateLayout();
3068
- }
3069
- }
3070
- }
3071
- // Measure children (skip flexExclude — they position themselves)
3072
- const measured = [];
3073
- for (const child of this._layoutChildren) {
3074
- if (child._flexConfig?.flexExclude)
3075
- continue;
3076
- const { w, h, ox, oy } = measureChild(child, pctRefW, pctRefH);
3077
- measured.push({ child, w, h, ox, oy });
3078
- }
3079
- // Split into lines (if wrapping)
3080
- const lines = [];
3081
- if (flexWrap && mainLimit < Infinity) {
3082
- let currentLine = [];
3083
- let lineMain = 0;
3084
- for (const item of measured) {
3085
- const itemMain = isRow ? item.w : item.h;
3086
- const wouldBe = lineMain + (currentLine.length > 0 ? gap : 0) + itemMain;
3087
- if (currentLine.length > 0 && wouldBe > mainLimit) {
3088
- lines.push(currentLine);
3089
- currentLine = [item];
3090
- lineMain = itemMain;
3091
- }
3092
- else {
3093
- currentLine.push(item);
3094
- lineMain = wouldBe;
3095
- }
3096
- }
3097
- if (currentLine.length > 0)
3098
- lines.push(currentLine);
3099
- }
3100
- else {
3101
- lines.push(measured);
3102
- }
3103
- // Compute cross size per line
3104
- const lineCrossSizes = lines.map((line) => {
3105
- let maxCross = 0;
3106
- for (const item of line) {
3107
- const cross = isRow ? item.h : item.w;
3108
- if (cross > maxCross)
3109
- maxCross = cross;
3110
- }
3111
- return maxCross;
3112
- });
3113
- // Compute natural main size (for auto-sizing when no explicit size given)
3114
- let naturalMainSize = 0;
3115
- if (mainLimit === Infinity) {
3116
- for (const line of lines) {
3117
- let lineMain = 0;
3118
- for (const item of line) {
3119
- lineMain += isRow ? item.w : item.h;
3120
- }
3121
- lineMain += gap * Math.max(0, line.length - 1);
3122
- naturalMainSize = Math.max(naturalMainSize, lineMain);
3123
- }
3124
- }
3125
- // Effective main size: explicit if set, otherwise natural content size
3126
- const effectiveMainSize = mainLimit < Infinity ? mainLimit : naturalMainSize;
3127
- // Compute alignContent offsets for multi-line layouts
3128
- const totalLinesCross = lineCrossSizes.reduce((s, v) => s + v, 0) + gap * Math.max(0, lines.length - 1);
3129
- let acOffset = 0;
3130
- let acExtraGap = 0;
3131
- if (lines.length > 1 && crossLimit < Infinity) {
3132
- const freeSpace = Math.max(0, crossLimit - totalLinesCross);
3133
- switch (alignContent) {
3134
- case 'center':
3135
- acOffset = freeSpace / 2;
3136
- break;
3137
- case 'end':
3138
- acOffset = freeSpace;
3139
- break;
3140
- case 'space-between':
3141
- if (lines.length > 1) {
3142
- acExtraGap = freeSpace / (lines.length - 1);
3143
- }
3144
- break;
3145
- case 'stretch':
3146
- if (lines.length > 0) {
3147
- const extra = freeSpace / lines.length;
3148
- for (let i = 0; i < lineCrossSizes.length; i++) {
3149
- lineCrossSizes[i] += extra;
3150
- }
3151
- }
3152
- break;
3153
- // 'start' — no adjustment
3154
- }
3155
- }
3156
- // Layout each line
3157
- let crossOffset = (isRow ? pt : pl) + acOffset;
3158
- for (let i = 0; i < lines.length; i++) {
3159
- const line = lines[i];
3160
- const lineCross = lineCrossSizes[i];
3161
- const mainStart = isRow ? pl : pt;
3162
- // Offset items by padding
3163
- const tempItems = line.map((item) => ({ ...item }));
3164
- // Cross size for alignment: use container cross size for single-line, line cross for multi-line
3165
- const effectiveCross = lines.length === 1 && crossLimit < Infinity ? crossLimit : lineCross;
3166
- layoutLine(tempItems, isRow, effectiveMainSize, mainLimit < Infinity ? justifyContent : 'start', alignItems, gap, crossOffset, effectiveCross);
3167
- // Apply main-axis padding offset
3168
- for (const item of tempItems) {
3169
- const origChild = line.find((l) => l.child === item.child);
3170
- origChild.child.x = item.child.x + (isRow ? mainStart : 0);
3171
- origChild.child.y = item.child.y + (isRow ? 0 : mainStart);
3172
- }
3173
- crossOffset += lineCross + gap + acExtraGap;
3174
- }
3175
- // Compute and store actual dimensions for measureChild() and getContentSize()
3176
- let totalCrossNatural = 0;
3177
- for (let i = 0; i < lineCrossSizes.length; i++) {
3178
- totalCrossNatural += lineCrossSizes[i];
3179
- if (i < lineCrossSizes.length - 1)
3180
- totalCrossNatural += gap;
3181
- }
3182
- if (isRow) {
3183
- this._computedWidth = this._explicitWidth > 0 ? this._explicitWidth : (pl + naturalMainSize + pr);
3184
- this._computedHeight = this._explicitHeight > 0 ? this._explicitHeight : (pt + totalCrossNatural + pb);
3185
- }
3186
- else {
3187
- this._computedWidth = this._explicitWidth > 0 ? this._explicitWidth : (pl + totalCrossNatural + pr);
3188
- this._computedHeight = this._explicitHeight > 0 ? this._explicitHeight : (pt + naturalMainSize + pb);
3189
- }
3190
- // Position flexExclude children (absolute positioning).
3191
- // All position props describe the visual (bounds) rectangle. We derive the
3192
- // visual rectangle directly from `getLocalBounds()` rather than the
3193
- // layout-config `w`/`h` returned by measureChild — those may differ from
3194
- // actual bounds when the user pins `layoutWidth`/`layoutHeight` to a value
3195
- // that doesn't match the child's real visual extent (e.g. a Button whose
3196
- // text overflows its configured `width`). Mixing layout size with real
3197
- // bounds-origin would shift the visual center off the requested point.
3198
- // `centerX/centerY` take precedence over `left/right` / `top/bottom` on each axis.
3199
- for (const child of this._layoutChildren) {
3200
- if (!child._flexConfig?.flexExclude)
3201
- continue;
3202
- const cfg = child._flexConfig;
3203
- const bounds = child.getLocalBounds();
3204
- const cw = this._computedWidth;
3205
- const ch = this._computedHeight;
3206
- const centerX = resolveDimension(cfg.centerX, pctRefW);
3207
- if (centerX !== undefined)
3208
- child.x = centerX - bounds.x - bounds.width / 2;
3209
- else if (cfg.left !== undefined)
3210
- child.x = cfg.left - bounds.x;
3211
- else if (cfg.right !== undefined)
3212
- child.x = cw - cfg.right - bounds.x - bounds.width;
3213
- const centerY = resolveDimension(cfg.centerY, pctRefH);
3214
- if (centerY !== undefined)
3215
- child.y = centerY - bounds.y - bounds.height / 2;
3216
- else if (cfg.top !== undefined)
3217
- child.y = cfg.top - bounds.y;
3218
- else if (cfg.bottom !== undefined)
3219
- child.y = ch - cfg.bottom - bounds.y - bounds.height;
3220
- }
3221
- }
3222
- /** Computed content size (after layout) */
3223
- getContentSize() {
3224
- if (this._layoutDirty)
3225
- this.updateLayout();
3226
- return { width: this._computedWidth, height: this._computedHeight };
3227
- }
3228
- /** React reconciler update hook — applies changed config props */
3229
- updateConfig(changed) {
3230
- if ('direction' in changed)
3231
- this.setDirection(changed.direction);
3232
- if ('justifyContent' in changed)
3233
- this.setJustifyContent(changed.justifyContent);
3234
- if ('alignItems' in changed)
3235
- this.setAlignItems(changed.alignItems);
3236
- if ('gap' in changed)
3237
- this.setGap(changed.gap);
3238
- if ('padding' in changed || 'paddingTop' in changed || 'paddingRight' in changed || 'paddingBottom' in changed || 'paddingLeft' in changed) {
3239
- this._padding = resolvePadding(changed);
3240
- this._layoutDirty = true;
3241
- }
3242
- if ('flexWrap' in changed) {
3243
- this._config.flexWrap = changed.flexWrap;
3244
- this._layoutDirty = true;
3245
- }
3246
- if ('alignContent' in changed) {
3247
- this._config.alignContent = changed.alignContent;
3248
- this._layoutDirty = true;
3249
- }
3250
- if ('width' in changed || 'height' in changed) {
3251
- const w = changed.width ?? this._rawWidth;
3252
- const h = changed.height ?? this._rawHeight;
3253
- this._rawWidth = w;
3254
- this._rawHeight = h;
3255
- if (typeof w === 'number' && typeof h === 'number') {
3256
- this.resize(w, h);
3257
- }
3258
- else {
3259
- // Percentage — will resolve in updateLayout
3260
- this._explicitWidth = typeof w === 'number' ? w : 0;
3261
- this._explicitHeight = typeof h === 'number' ? h : 0;
3262
- this._layoutDirty = true;
3263
- if (!this._layoutSuspended)
3264
- this.updateLayout();
3265
- }
3266
- return;
3267
- }
3268
- if (this._layoutDirty && !this._layoutSuspended)
3269
- this.updateLayout();
3270
- }
3271
- destroy(options) {
3272
- this._layoutChildren.length = 0;
3273
- super.destroy(options);
3274
- }
3275
- }
3276
-
3277
- /**
3278
- * Resolve a ViewInput to a Container instance.
3279
- *
3280
- * @example
3281
- * ```ts
3282
- * resolveView('btn-idle') // → Sprite.from('btn-idle')
3283
- * resolveView(someTexture) // → new Sprite(someTexture)
3284
- * resolveView(myCustomContainer) // → myCustomContainer (as-is)
3285
- * resolveView(undefined) // → null
3286
- * ```
3287
- */
3288
- function resolveView(input) {
3289
- if (input == null)
3290
- return null;
3291
- if (typeof input === 'string')
3292
- return Sprite.from(input);
3293
- if (input instanceof Texture)
3294
- return new Sprite(input);
3295
- return input;
3296
- }
3297
-
3298
- const DEFAULT_COLORS = {
3299
- default: 0xffd700,
3300
- hover: 0xffe44d,
3301
- pressed: 0xccac00,
3302
- disabled: 0x666666,
3303
- };
3304
- function makeGraphicsView(w, h, radius, color) {
3305
- const g = new Graphics();
3306
- g.roundRect(-w / 2, -h / 2, w, h, radius).fill(color);
3307
- return g;
3308
- }
3309
- /**
3310
- * Interactive button with per-state custom views and animations.
3311
- *
3312
- * Each visual state accepts a `ViewInput`: texture name, Texture, or any Container
3313
- * (Sprite, NineSliceSprite, AnimatedSprite, custom artwork, etc).
3314
- * Falls back to colored Graphics when no custom view is provided.
3315
- *
3316
- * @example
3317
- * ```ts
3318
- * // Graphics-based (quick prototyping)
3319
- * const btn = new Button({
3320
- * width: 200, height: 60, borderRadius: 12,
3321
- * colors: { default: 0x22aa22, hover: 0x33cc33 },
3322
- * text: 'SPIN',
3323
- * onPress: () => spin(),
3324
- * });
3325
- *
3326
- * // Asset-based (production art)
3327
- * const btn = new Button({
3328
- * defaultView: 'btn-idle',
3329
- * hoverView: 'btn-hover',
3330
- * pressedView: 'btn-pressed',
3331
- * disabledView: 'btn-disabled',
3332
- * text: 'SPIN',
3333
- * onPress: () => spin(),
3334
- * });
3335
- *
3336
- * // Custom Container view
3337
- * const btn = new Button({
3338
- * defaultView: myAnimatedSprite,
3339
- * text: 'SPIN',
3340
- * });
3341
- * ```
3342
- */
3343
- class Button extends Container {
3344
- __uiComponent = true;
3345
- _views = new Map();
3346
- _state = 'default';
3347
- _enabled = true;
3348
- _config;
3349
- _textObj = null;
3350
- /** Press callback */
3351
- onPress;
3352
- constructor(config = {}) {
3353
- super();
3354
- this._config = {
3355
- width: config.width ?? 200,
3356
- height: config.height ?? 60,
3357
- borderRadius: config.borderRadius ?? 8,
3358
- pressScale: config.pressScale ?? 0.95,
3359
- animationDuration: config.animationDuration ?? 100,
3360
- ...config,
3361
- };
3362
- this.onPress = config.onPress;
3363
- this._buildViews(config);
3364
- // Text
3365
- if (config.text) {
3366
- this._textObj = new Text({
3367
- text: config.text,
3368
- style: {
3369
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
3370
- fontSize: 20,
3371
- fill: 0xffffff,
3372
- fontWeight: 'bold',
3373
- ...config.textStyle,
3374
- },
3375
- });
3376
- this._textObj.anchor.set(0.5);
3377
- this.addChild(this._textObj);
3378
- }
3379
- // Interaction
3380
- this.eventMode = 'static';
3381
- this.cursor = 'pointer';
3382
- this.on('pointerover', this._onPointerOver, this);
3383
- this.on('pointerout', this._onPointerOut, this);
3384
- this.on('pointerdown', this._onPointerDown, this);
3385
- this.on('pointerup', this._onPointerUp, this);
3386
- this.on('pointerupoutside', this._onPointerUpOutside, this);
3387
- if (config.disabled) {
3388
- this.enabled = false;
3389
- }
3390
- }
3391
- /** Current button state */
3392
- get state() {
3393
- return this._state;
3394
- }
3395
- /** Enable the button */
3396
- enable() {
3397
- this.enabled = true;
3398
- }
3399
- /** Disable the button */
3400
- disable() {
3401
- this.enabled = false;
3402
- }
3403
- /** Whether the button is enabled */
3404
- get enabled() {
3405
- return this._enabled;
3406
- }
3407
- set enabled(value) {
3408
- this._enabled = value;
3409
- this.cursor = value ? 'pointer' : 'default';
3410
- this.eventMode = value ? 'static' : 'none';
3411
- this._setState(value ? 'default' : 'disabled');
3412
- }
3413
- /** Whether the button is disabled */
3414
- get disabled() {
3415
- return !this._enabled;
3416
- }
3417
- /** Update button text */
3418
- set text(value) {
3419
- if (this._textObj) {
3420
- this._textObj.text = value;
3421
- }
3422
- }
3423
- // ─── View building ──────────────────────────────────
3424
- _buildViews(config) {
3425
- const colorMap = { ...DEFAULT_COLORS, ...config.colors };
3426
- const { width, height, borderRadius } = this._config;
3427
- const stateViews = {
3428
- default: config.defaultView,
3429
- hover: config.hoverView,
3430
- pressed: config.pressedView,
3431
- disabled: config.disabledView,
3432
- };
3433
- const states = ['default', 'hover', 'pressed', 'disabled'];
3434
- for (const state of states) {
3435
- const customView = resolveView(stateViews[state]);
3436
- const view = customView ?? makeGraphicsView(width, height, borderRadius, colorMap[state]);
3437
- view.visible = state === 'default';
3438
- this._views.set(state, view);
3439
- this.addChild(view);
3440
- }
3441
- }
3442
- _rebuildViews() {
3443
- for (const [, view] of this._views) {
3444
- this.removeChild(view);
3445
- view.destroy();
3446
- }
3447
- this._views.clear();
3448
- this._buildViews(this._config);
3449
- // Re-insert views before text
3450
- if (this._textObj && this._textObj.parent === this) {
3451
- this.setChildIndex(this._textObj, this.children.length - 1);
3452
- }
3453
- }
3454
- // ─── State management ───────────────────────────────
3455
- _setState(state) {
3456
- if (this._state === state)
3457
- return;
3458
- this._state = state;
3459
- for (const [s, view] of this._views) {
3460
- view.visible = s === state;
3461
- }
3462
- }
3463
- _onPointerOver() {
3464
- if (!this._enabled)
3465
- return;
3466
- this._setState('hover');
3467
- Tween.killTweensOf(this);
3468
- Tween.to(this, { 'scale.x': 1.03, 'scale.y': 1.03 }, this._config.animationDuration, Easing.easeOutQuad);
3469
- }
3470
- _onPointerOut() {
3471
- if (!this._enabled)
3472
- return;
3473
- this._setState('default');
3474
- Tween.killTweensOf(this);
3475
- Tween.to(this, { 'scale.x': 1, 'scale.y': 1 }, this._config.animationDuration, Easing.easeOutQuad);
3476
- }
3477
- _onPointerDown() {
3478
- if (!this._enabled)
3479
- return;
3480
- this._setState('pressed');
3481
- Tween.killTweensOf(this);
3482
- const s = this._config.pressScale;
3483
- Tween.to(this, { 'scale.x': s, 'scale.y': s }, this._config.animationDuration, Easing.easeOutQuad);
3484
- }
3485
- _onPointerUp() {
3486
- if (!this._enabled)
3487
- return;
3488
- this._setState('hover');
3489
- Tween.killTweensOf(this);
3490
- Tween.to(this, { 'scale.x': 1.03, 'scale.y': 1.03 }, this._config.animationDuration, Easing.easeOutQuad);
3491
- this.onPress?.();
3492
- }
3493
- _onPointerUpOutside() {
3494
- if (!this._enabled)
3495
- return;
3496
- this._setState('default');
3497
- Tween.killTweensOf(this);
3498
- Tween.to(this, { 'scale.x': 1, 'scale.y': 1 }, this._config.animationDuration, Easing.easeOutQuad);
3499
- }
3500
- /** React reconciler update hook */
3501
- updateConfig(changed) {
3502
- if ('text' in changed && this._textObj)
3503
- this._textObj.text = changed.text;
3504
- if ('disabled' in changed)
3505
- this.enabled = !changed.disabled;
3506
- if ('onPress' in changed)
3507
- this.onPress = changed.onPress;
3508
- const structural = [
3509
- 'colors', 'width', 'height', 'borderRadius', 'textStyle',
3510
- 'defaultView', 'hoverView', 'pressedView', 'disabledView',
3511
- ];
3512
- const needsRebuild = structural.some((k) => k in changed);
3513
- if (needsRebuild) {
3514
- Object.assign(this._config, changed);
3515
- this._rebuildViews();
3516
- }
3517
- }
3518
- destroy(options) {
3519
- Tween.killTweensOf(this);
3520
- this.off('pointerover', this._onPointerOver, this);
3521
- this.off('pointerout', this._onPointerOut, this);
3522
- this.off('pointerdown', this._onPointerDown, this);
3523
- this.off('pointerup', this._onPointerUp, this);
3524
- this.off('pointerupoutside', this._onPointerUpOutside, this);
3525
- this._views.clear();
3526
- this._textObj = null;
3527
- super.destroy(options);
3528
- }
3529
- }
3530
-
3531
- /**
3532
- * Horizontal progress bar with optional custom track/fill views.
3533
- *
3534
- * Supports asset-based skinning: provide `trackView` and/or `fillView`
3535
- * as texture names, Textures, or any Container (NineSliceSprite, custom artwork, etc).
3536
- * Falls back to colored Graphics when no custom views are provided.
3537
- *
3538
- * @example
3539
- * ```ts
3540
- * // Graphics-based (quick prototyping)
3541
- * const bar = new ProgressBar({ width: 300, height: 20, fillColor: 0x22cc22 });
3542
- * bar.progress = 0.5;
3543
- *
3544
- * // Asset-based (production art)
3545
- * const bar = new ProgressBar({
3546
- * width: 300, height: 20,
3547
- * trackView: 'bar-track',
3548
- * fillView: new NineSliceSprite({ texture: 'bar-fill', ... }),
3549
- * });
3550
- * bar.progress = 0.75;
3551
- * ```
3552
- */
3553
- class ProgressBar extends Container {
3554
- __uiComponent = true;
3555
- _track;
3556
- _fill;
3557
- _fillMask;
3558
- _borderGfx;
3559
- _config;
3560
- _progress = 0;
3561
- _displayedProgress = 0;
3562
- constructor(config = {}) {
3563
- super();
3564
- this._config = {
3565
- width: config.width ?? 300,
3566
- height: config.height ?? 16,
3567
- borderRadius: config.borderRadius ?? 8,
3568
- fillColor: config.fillColor ?? 0xffd700,
3569
- trackColor: config.trackColor ?? 0x333333,
3570
- borderColor: config.borderColor ?? 0x555555,
3571
- borderWidth: config.borderWidth ?? 1,
3572
- animated: config.animated ?? true,
3573
- animationSpeed: config.animationSpeed ?? 0.1,
3574
- };
3575
- const { width, height, borderRadius, fillColor, trackColor, borderColor, borderWidth } = this._config;
3576
- // Track background — custom view or Graphics
3577
- const customTrack = resolveView(config.trackView);
3578
- if (customTrack) {
3579
- customTrack.width = width;
3580
- customTrack.height = height;
3581
- this._track = customTrack;
3582
- }
3583
- else {
3584
- const g = new Graphics();
3585
- g.roundRect(0, 0, width, height, borderRadius).fill(trackColor);
3586
- this._track = g;
3587
- }
3588
- this.addChild(this._track);
3589
- // Fill bar — custom view or Graphics
3590
- const customFill = resolveView(config.fillView);
3591
- if (customFill) {
3592
- customFill.x = borderWidth;
3593
- customFill.y = borderWidth;
3594
- customFill.width = width - borderWidth * 2;
3595
- customFill.height = height - borderWidth * 2;
3596
- this._fill = customFill;
3597
- }
3598
- else {
3599
- const g = new Graphics();
3600
- g.roundRect(borderWidth, borderWidth, width - borderWidth * 2, height - borderWidth * 2, Math.max(0, borderRadius - 1)).fill(fillColor);
3601
- this._fill = g;
3602
- }
3603
- this.addChild(this._fill);
3604
- // Mask for the fill (controls visible width)
3605
- this._fillMask = new Graphics();
3606
- this._fillMask.rect(0, 0, 0, height).fill(0xffffff);
3607
- this.addChild(this._fillMask);
3608
- this._fill.mask = this._fillMask;
3609
- // Border overlay
3610
- this._borderGfx = new Graphics();
3611
- if (borderColor !== undefined && borderWidth > 0) {
3612
- this._borderGfx
3613
- .roundRect(0, 0, width, height, borderRadius)
3614
- .stroke({ color: borderColor, width: borderWidth });
3615
- }
3616
- this.addChild(this._borderGfx);
3617
- }
3618
- /** Get/set progress (0..1) */
3619
- get progress() {
3620
- return this._progress;
3621
- }
3622
- set progress(value) {
3623
- this._progress = Math.max(0, Math.min(1, value));
3624
- if (!this._config.animated) {
3625
- this._displayedProgress = this._progress;
3626
- this.updateMask();
3627
- }
3628
- }
3629
- /**
3630
- * Call each frame if animated is true.
3631
- */
3632
- update(_dt) {
3633
- if (!this._config.animated)
3634
- return;
3635
- if (Math.abs(this._displayedProgress - this._progress) < 0.001) {
3636
- this._displayedProgress = this._progress;
3637
- this.updateMask();
3638
- return;
3639
- }
3640
- this._displayedProgress +=
3641
- (this._progress - this._displayedProgress) * this._config.animationSpeed;
3642
- this.updateMask();
3643
- }
3644
- /** React reconciler update hook */
3645
- updateConfig(changed) {
3646
- if ('progress' in changed)
3647
- this.progress = changed.progress;
3648
- if ('animated' in changed)
3649
- this._config.animated = changed.animated;
3650
- if ('animationSpeed' in changed)
3651
- this._config.animationSpeed = changed.animationSpeed;
3652
- }
3653
- updateMask() {
3654
- const w = this._config.width * this._displayedProgress;
3655
- this._fillMask.clear();
3656
- this._fillMask.rect(0, 0, w, this._config.height).fill(0xffffff);
3657
- }
3658
- }
3659
-
3660
- /**
3661
- * Enhanced text label with auto-fit scaling and currency formatting.
3662
- *
3663
- * @example
3664
- * ```ts
3665
- * const label = new Label({
3666
- * text: 'BALANCE',
3667
- * style: { fontSize: 24, fill: 0xffd700 },
3668
- * maxWidth: 200,
3669
- * autoFit: true,
3670
- * });
3671
- * ```
3672
- */
3673
- class Label extends Container {
3674
- __uiComponent = true;
3675
- _text;
3676
- _maxWidth;
3677
- _autoFit;
3678
- constructor(config = {}) {
3679
- super();
3680
- this._maxWidth = config.maxWidth ?? Infinity;
3681
- this._autoFit = config.autoFit ?? false;
3682
- this._text = new Text({
3683
- text: config.text ?? '',
3684
- style: {
3685
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
3686
- fontSize: 24,
3687
- fill: 0xffffff,
3688
- ...config.style,
3689
- },
3690
- });
3691
- this._text.anchor.set(0.5);
3692
- this.addChild(this._text);
3693
- this.fitText();
3694
- }
3695
- /** Get/set the displayed text */
3696
- get text() {
3697
- return this._text.text;
3698
- }
3699
- set text(value) {
3700
- this._text.text = value;
3701
- this.fitText();
3702
- }
3703
- /** Get/set the text style */
3704
- get style() {
3705
- return this._text.style;
3706
- }
3707
- /** Set max width constraint */
3708
- set maxWidth(value) {
3709
- this._maxWidth = value;
3710
- this.fitText();
3711
- }
3712
- /**
3713
- * Format and display a number as currency.
3714
- *
3715
- * @param amount - The numeric amount
3716
- * @param currency - Currency code (e.g., 'USD', 'EUR')
3717
- * @param locale - Locale string (default: 'en-US')
3718
- */
3719
- setCurrency(amount, currency, locale = 'en-US') {
3720
- try {
3721
- this.text = new Intl.NumberFormat(locale, {
3722
- style: 'currency',
3723
- currency,
3724
- minimumFractionDigits: 2,
3725
- maximumFractionDigits: 2,
3726
- }).format(amount);
3727
- }
3728
- catch {
3729
- this.text = `${amount.toFixed(2)} ${currency}`;
3730
- }
3731
- }
3732
- /**
3733
- * Format a number with thousands separators.
3734
- */
3735
- setNumber(value, decimals = 0, locale = 'en-US') {
3736
- this.text = new Intl.NumberFormat(locale, {
3737
- minimumFractionDigits: decimals,
3738
- maximumFractionDigits: decimals,
3739
- }).format(value);
3740
- }
3741
- /** React reconciler update hook */
3742
- updateConfig(changed) {
3743
- if ('text' in changed)
3744
- this.text = changed.text;
3745
- if ('maxWidth' in changed)
3746
- this.maxWidth = changed.maxWidth;
3747
- if ('autoFit' in changed) {
3748
- this._autoFit = changed.autoFit;
3749
- this.fitText();
3750
- }
3751
- if ('style' in changed && typeof changed.style === 'object') {
3752
- Object.assign(this._text.style, changed.style);
3753
- this.fitText();
3754
- }
3755
- }
3756
- fitText() {
3757
- if (!this._autoFit || this._maxWidth === Infinity)
3758
- return;
3759
- this._text.scale.set(1);
3760
- if (this._text.width > this._maxWidth) {
3761
- const scale = this._maxWidth / this._text.width;
3762
- this._text.scale.set(scale);
3763
- }
3764
- }
3765
- }
3766
-
3767
- /**
3768
- * Background panel with optional flexbox content layout.
3769
- *
3770
- * Supports both Graphics-based (color + border) and 9-slice sprite backgrounds.
3771
- * Children added via `addContent()` participate in flex layout automatically.
3772
- *
3773
- * @example
3774
- * ```ts
3775
- * // Simple colored panel
3776
- * const panel = new Panel({ width: 400, height: 300, backgroundColor: 0x222222, borderRadius: 12 });
3777
- *
3778
- * // 9-slice panel (texture-based)
3779
- * const panel = new Panel({
3780
- * nineSliceTexture: 'panel-bg',
3781
- * nineSliceBorders: [20, 20, 20, 20],
3782
- * width: 400, height: 300,
3783
- * });
3784
- * ```
3785
- */
3786
- class Panel extends Container {
3787
- __uiComponent = true;
3788
- _bg;
3789
- _content;
3790
- _internalSetup = true;
3791
- _panelConfig;
3792
- constructor(config = {}) {
3793
- super();
3794
- const resolvedConfig = {
3795
- width: config.width ?? 400,
3796
- height: config.height ?? 300,
3797
- padding: config.padding ?? 16,
3798
- backgroundAlpha: config.backgroundAlpha ?? 1,
3799
- ...config,
3800
- };
3801
- this._panelConfig = resolvedConfig;
3802
- // Create background
3803
- if (config.nineSliceTexture) {
3804
- const texture = typeof config.nineSliceTexture === 'string'
3805
- ? Texture.from(config.nineSliceTexture)
3806
- : config.nineSliceTexture;
3807
- const [left, top, right, bottom] = config.nineSliceBorders ?? [10, 10, 10, 10];
3808
- const nineSlice = new NineSliceSprite({
3809
- texture,
3810
- leftWidth: left,
3811
- topHeight: top,
3812
- rightWidth: right,
3813
- bottomHeight: bottom,
3814
- });
3815
- nineSlice.width = resolvedConfig.width;
3816
- nineSlice.height = resolvedConfig.height;
3817
- nineSlice.alpha = resolvedConfig.backgroundAlpha;
3818
- this._bg = nineSlice;
3819
- }
3820
- else {
3821
- const g = new Graphics();
3822
- const bgColor = config.backgroundColor ?? 0x1a1a2e;
3823
- const radius = config.borderRadius ?? 0;
3824
- g.roundRect(0, 0, resolvedConfig.width, resolvedConfig.height, radius).fill(bgColor);
3825
- if (config.borderColor !== undefined && config.borderWidth) {
3826
- g.roundRect(0, 0, resolvedConfig.width, resolvedConfig.height, radius)
3827
- .stroke({ color: config.borderColor, width: config.borderWidth });
3828
- }
3829
- g.alpha = resolvedConfig.backgroundAlpha;
3830
- this._bg = g;
3831
- }
3832
- this.addChild(this._bg);
3833
- // Create content flex container
3834
- this._content = new FlexContainer({
3835
- ...config.layout,
3836
- direction: config.layout?.direction ?? 'column',
3837
- justifyContent: config.layout?.justifyContent ?? 'start',
3838
- alignItems: config.layout?.alignItems ?? 'start',
3839
- gap: config.layout?.gap ?? 0,
3840
- padding: resolvedConfig.padding,
3841
- width: resolvedConfig.width,
3842
- height: resolvedConfig.height,
3843
- });
3844
- this.addChild(this._content);
3845
- this._internalSetup = false;
3846
- }
3847
- /** Access the content flex container — add children here for layout */
3848
- get content() {
3849
- return this._content;
3850
- }
3851
- /** Suspend content layout recalculation. Call resumeLayout() to flush. */
3852
- suspendLayout() {
3853
- this._content.suspendLayout();
3854
- }
3855
- /** Resume content layout and flush if dirty. */
3856
- resumeLayout() {
3857
- this._content.resumeLayout();
3858
- }
3859
- /** Convenience: add a child to the content layout */
3860
- addContent(child) {
3861
- this._content.addFlexChild(child);
3862
- this._content.updateLayout();
3863
- return this;
3864
- }
3865
- /** Resize the panel */
3866
- setSize(width, height) {
3867
- this._panelConfig.width = width;
3868
- this._panelConfig.height = height;
3869
- // Resize background
3870
- if (this._bg instanceof NineSliceSprite) {
3871
- this._bg.width = width;
3872
- this._bg.height = height;
3873
- }
3874
- else if (this._bg instanceof Graphics) {
3875
- const radius = this._panelConfig.borderRadius ?? 0;
3876
- const bgColor = this._panelConfig.backgroundColor ?? 0x1a1a2e;
3877
- this._bg.clear();
3878
- this._bg.roundRect(0, 0, width, height, radius).fill(bgColor);
3879
- if (this._panelConfig.borderColor !== undefined && this._panelConfig.borderWidth) {
3880
- this._bg.roundRect(0, 0, width, height, radius)
3881
- .stroke({ color: this._panelConfig.borderColor, width: this._panelConfig.borderWidth });
3882
- }
3883
- this._bg.alpha = this._panelConfig.backgroundAlpha;
3884
- }
3885
- this._content.resize(width, height);
3886
- }
3887
- /**
3888
- * Override addChild so external children are routed to content FlexContainer.
3889
- * Enables `<panel><label /><button /></panel>` in React JSX.
3890
- */
3891
- addChild(...children) {
3892
- if (this._internalSetup) {
3893
- return super.addChild(...children);
3894
- }
3895
- for (const child of children) {
3896
- this._content.addFlexChild(child);
3897
- }
3898
- this._content.updateLayout();
3899
- return children[0];
3900
- }
3901
- removeChild(...children) {
3902
- if (this._internalSetup) {
3903
- return super.removeChild(...children);
3904
- }
3905
- for (const child of children) {
3906
- this._content.removeFlexChild(child);
3907
- }
3908
- return children[0];
3909
- }
3910
- /** React reconciler update hook */
3911
- updateConfig(changed) {
3912
- if ('width' in changed || 'height' in changed) {
3913
- this.setSize(changed.width ?? this._panelConfig.width, changed.height ?? this._panelConfig.height);
3914
- }
3915
- if ('backgroundAlpha' in changed) {
3916
- this._panelConfig.backgroundAlpha = changed.backgroundAlpha;
3917
- this._bg.alpha = changed.backgroundAlpha;
3918
- }
3919
- }
3920
- destroy(options) {
3921
- super.destroy(options);
3922
- }
3923
- }
3924
-
3925
- /**
3926
- * Reactive balance display component.
3927
- *
3928
- * Automatically formats currency and can animate value changes
3929
- * with a smooth countup/countdown effect using engine Tween.
3930
- *
3931
- * @example
3932
- * ```ts
3933
- * const balance = new BalanceDisplay({ currency: 'USD', animated: true });
3934
- * balance.setValue(1000);
3935
- *
3936
- * // Wire to SDK
3937
- * sdk.on('balanceUpdate', ({ balance: val }) => balance.setValue(val));
3938
- * ```
3939
- */
3940
- class BalanceDisplay extends Container {
3941
- __uiComponent = true;
3942
- _prefixLabel = null;
3943
- _valueLabel;
3944
- _config;
3945
- _currentValue = 0;
3946
- _displayedValue = 0;
3947
- /** Internal target for Tween animation */
3948
- _tweenTarget = { value: 0 };
3949
- constructor(config = {}) {
3950
- super();
3951
- this._config = {
3952
- currency: config.currency ?? 'USD',
3953
- locale: config.locale ?? 'en-US',
3954
- animated: config.animated ?? true,
3955
- animationDuration: config.animationDuration ?? 500,
3956
- };
3957
- // Prefix label
3958
- if (config.prefix) {
3959
- this._prefixLabel = new Label({
3960
- text: config.prefix,
3961
- style: {
3962
- fontSize: 16,
3963
- fill: 0xaaaaaa,
3964
- ...config.style,
3965
- },
3966
- });
3967
- this.addChild(this._prefixLabel);
3968
- }
3969
- // Value label
3970
- this._valueLabel = new Label({
3971
- text: '0.00',
3972
- style: {
3973
- fontSize: 28,
3974
- fontWeight: 'bold',
3975
- fill: 0xffffff,
3976
- ...config.style,
3977
- },
3978
- maxWidth: config.maxWidth,
3979
- autoFit: !!config.maxWidth,
3980
- });
3981
- this.addChild(this._valueLabel);
3982
- this.layoutLabels();
3983
- }
3984
- /** Current displayed value */
3985
- get value() {
3986
- return this._currentValue;
3987
- }
3988
- /**
3989
- * Set the balance value. If animated, smoothly counts to the new value.
3990
- */
3991
- setValue(value) {
3992
- const oldValue = this._currentValue;
3993
- this._currentValue = value;
3994
- if (this._config.animated && oldValue !== value) {
3995
- this.animateValue(oldValue, value);
3996
- }
3997
- else {
3998
- this._displayedValue = value;
3999
- this.updateDisplay();
4000
- }
4001
- }
4002
- /**
4003
- * Set the currency code.
4004
- */
4005
- setCurrency(currency) {
4006
- this._config.currency = currency;
4007
- this.updateDisplay();
4008
- }
4009
- animateValue(from, to) {
4010
- // Cancel any running animation
4011
- Tween.killTweensOf(this._tweenTarget);
4012
- this._tweenTarget.value = from;
4013
- Tween.to(this._tweenTarget, { value: to }, this._config.animationDuration, Easing.easeOutCubic, () => {
4014
- this._displayedValue = this._tweenTarget.value;
4015
- this.updateDisplay();
4016
- });
4017
- }
4018
- updateDisplay() {
4019
- this._valueLabel.setCurrency(this._displayedValue, this._config.currency, this._config.locale);
4020
- }
4021
- layoutLabels() {
4022
- if (this._prefixLabel) {
4023
- this._prefixLabel.y = -14;
4024
- this._valueLabel.y = 14;
4025
- }
4026
- }
4027
- /** React reconciler update hook */
4028
- updateConfig(changed) {
4029
- if ('value' in changed)
4030
- this.setValue(changed.value);
4031
- if ('currency' in changed)
4032
- this.setCurrency(changed.currency);
4033
- }
4034
- destroy(options) {
4035
- Tween.killTweensOf(this._tweenTarget);
4036
- super.destroy(options);
4037
- }
4038
- }
4039
-
4040
- /**
4041
- * Win amount display with countup animation.
4042
- *
4043
- * Shows a dramatic countup from 0 to the win amount, with optional
4044
- * scale pop effect — typical of slot games. Uses engine Tween system.
4045
- *
4046
- * @example
4047
- * ```ts
4048
- * const winDisplay = new WinDisplay({ currency: 'USD' });
4049
- * scene.container.addChild(winDisplay);
4050
- * await winDisplay.showWin(150.50); // countup animation
4051
- * winDisplay.hide();
4052
- * ```
4053
- */
4054
- class WinDisplay extends Container {
4055
- __uiComponent = true;
4056
- _label;
4057
- _config;
4058
- /** Internal target for Tween countup */
4059
- _tweenTarget = { value: 0 };
4060
- constructor(config = {}) {
4061
- super();
4062
- this._config = {
4063
- currency: config.currency ?? 'USD',
4064
- locale: config.locale ?? 'en-US',
4065
- countupDuration: config.countupDuration ?? 1500,
4066
- popScale: config.popScale ?? 1.2,
4067
- };
4068
- this._label = new Label({
4069
- text: '',
4070
- style: {
4071
- fontSize: 48,
4072
- fontWeight: 'bold',
4073
- fill: 0xffd700,
4074
- stroke: { color: 0x000000, width: 3 },
4075
- ...config.style,
4076
- },
4077
- });
4078
- this.addChild(this._label);
4079
- this.visible = false;
4080
- }
4081
- /**
4082
- * Show a win with countup animation.
4083
- *
4084
- * @param amount - Win amount
4085
- * @returns Promise that resolves when the animation completes
4086
- */
4087
- async showWin(amount) {
4088
- this.visible = true;
4089
- this.alpha = 1;
4090
- // Cancel any running animation
4091
- Tween.killTweensOf(this._tweenTarget);
4092
- Tween.killTweensOf(this);
4093
- // Setup countup
4094
- this._tweenTarget.value = 0;
4095
- this.scale.set(0.5);
4096
- // Scale pop animation
4097
- const scalePromise = Tween.to(this, { 'scale.x': 1, 'scale.y': 1 }, 300, Easing.easeOutBack);
4098
- // Countup animation
4099
- const countupPromise = Tween.to(this._tweenTarget, { value: amount }, this._config.countupDuration, Easing.easeOutCubic, () => {
4100
- this.displayAmount(this._tweenTarget.value);
4101
- });
4102
- await Promise.all([scalePromise, countupPromise]);
4103
- // Ensure final value is exact
4104
- this.displayAmount(amount);
4105
- this.scale.set(1);
4106
- }
4107
- /**
4108
- * Skip the countup animation and show the final amount immediately.
4109
- */
4110
- skipCountup(amount) {
4111
- Tween.killTweensOf(this._tweenTarget);
4112
- Tween.killTweensOf(this);
4113
- this.displayAmount(amount);
4114
- this.scale.set(1);
4115
- }
4116
- /**
4117
- * Hide the win display.
4118
- */
4119
- hide() {
4120
- Tween.killTweensOf(this._tweenTarget);
4121
- Tween.killTweensOf(this);
4122
- this.visible = false;
4123
- this._label.text = '';
4124
- }
4125
- displayAmount(amount) {
4126
- this._label.setCurrency(amount, this._config.currency, this._config.locale);
4127
- }
4128
- /** React reconciler update hook */
4129
- updateConfig(changed) {
4130
- if ('currency' in changed)
4131
- this._config.currency = changed.currency;
4132
- if ('locale' in changed)
4133
- this._config.locale = changed.locale;
4134
- }
4135
- destroy(options) {
4136
- Tween.killTweensOf(this._tweenTarget);
4137
- Tween.killTweensOf(this);
4138
- super.destroy(options);
4139
- }
4140
- }
4141
-
4142
- /**
4143
- * Modal overlay component.
4144
- * Shows content on top of a dark overlay with enter/exit animations.
4145
- *
4146
- * Content is automatically centered via position calculations.
4147
- *
4148
- * @example
4149
- * ```ts
4150
- * const modal = new Modal({ closeOnOverlay: true });
4151
- * modal.content.addChild(settingsPanel);
4152
- * modal.onClose = () => console.log('Closed');
4153
- * await modal.show(1920, 1080);
4154
- * ```
4155
- */
4156
- class Modal extends Container {
4157
- __uiComponent = true;
4158
- _overlay;
4159
- _contentContainer;
4160
- _config;
4161
- _showing = false;
4162
- _internalSetup = true;
4163
- /** Called when the modal is closed */
4164
- onClose;
4165
- constructor(config = {}) {
4166
- super();
4167
- this._config = {
4168
- overlayColor: config.overlayColor ?? 0x000000,
4169
- overlayAlpha: config.overlayAlpha ?? 0.7,
4170
- closeOnOverlay: config.closeOnOverlay ?? true,
4171
- animationDuration: config.animationDuration ?? 300,
4172
- };
4173
- // Overlay
4174
- this._overlay = new Graphics();
4175
- this._overlay.eventMode = 'static';
4176
- this._overlay.on('pointertap', () => {
4177
- if (this._config.closeOnOverlay)
4178
- this.hide();
4179
- });
4180
- this.addChild(this._overlay);
4181
- // Content container
4182
- this._contentContainer = new Container();
4183
- this.addChild(this._contentContainer);
4184
- this.visible = false;
4185
- this._internalSetup = false;
4186
- }
4187
- /** Content container — add your UI here */
4188
- get content() {
4189
- return this._contentContainer;
4190
- }
4191
- /**
4192
- * Override addChild so external children are routed to _contentContainer.
4193
- * Enables `<modal><flexContainer>...</flexContainer></modal>` in React JSX.
4194
- */
4195
- addChild(...children) {
4196
- if (this._internalSetup) {
4197
- return super.addChild(...children);
4198
- }
4199
- for (const child of children) {
4200
- this._contentContainer.addChild(child);
4201
- }
4202
- return children[0];
4203
- }
4204
- removeChild(...children) {
4205
- if (this._internalSetup) {
4206
- return super.removeChild(...children);
4207
- }
4208
- for (const child of children) {
4209
- this._contentContainer.removeChild(child);
4210
- }
4211
- return children[0];
4212
- }
4213
- /** Whether the modal is currently showing */
4214
- get isShowing() {
4215
- return this._showing;
4216
- }
4217
- /**
4218
- * Show the modal with animation.
4219
- */
4220
- async show(viewWidth, viewHeight) {
4221
- this._showing = true;
4222
- this.visible = true;
4223
- // Draw overlay to cover full screen
4224
- this._overlay.clear();
4225
- this._overlay.rect(0, 0, viewWidth, viewHeight).fill(this._config.overlayColor);
4226
- this._overlay.alpha = 0;
4227
- // Center content
4228
- this._contentContainer.x = viewWidth / 2;
4229
- this._contentContainer.y = viewHeight / 2;
4230
- this._contentContainer.alpha = 0;
4231
- this._contentContainer.scale.set(0.8);
4232
- // Animate in
4233
- await Promise.all([
4234
- Tween.to(this._overlay, { alpha: this._config.overlayAlpha }, this._config.animationDuration, Easing.easeOutCubic),
4235
- Tween.to(this._contentContainer, { alpha: 1, 'scale.x': 1, 'scale.y': 1 }, this._config.animationDuration, Easing.easeOutBack),
4236
- ]);
4237
- }
4238
- /**
4239
- * Hide the modal with animation.
4240
- */
4241
- async hide() {
4242
- if (!this._showing)
4243
- return;
4244
- await Promise.all([
4245
- Tween.to(this._overlay, { alpha: 0 }, this._config.animationDuration * 0.7, Easing.easeInCubic),
4246
- Tween.to(this._contentContainer, { alpha: 0, 'scale.x': 0.8, 'scale.y': 0.8 }, this._config.animationDuration * 0.7, Easing.easeInCubic),
4247
- ]);
4248
- this.visible = false;
4249
- this._showing = false;
4250
- this.onClose?.();
4251
- }
4252
- /** React reconciler update hook */
4253
- updateConfig(changed) {
4254
- if ('overlayAlpha' in changed)
4255
- this._config.overlayAlpha = changed.overlayAlpha;
4256
- if ('closeOnOverlay' in changed)
4257
- this._config.closeOnOverlay = changed.closeOnOverlay;
4258
- if ('animationDuration' in changed)
4259
- this._config.animationDuration = changed.animationDuration;
4260
- if ('onClose' in changed)
4261
- this.onClose = changed.onClose;
4262
- }
4263
- }
4264
-
4265
- const TOAST_COLORS = {
4266
- info: 0x3498db,
4267
- success: 0x27ae60,
4268
- warning: 0xf39c12,
4269
- error: 0xe74c3c,
4270
- };
4271
- /**
4272
- * Toast notification component for displaying transient messages.
4273
- *
4274
- * @example
4275
- * ```ts
4276
- * const toast = new Toast();
4277
- * scene.container.addChild(toast);
4278
- * await toast.show('Connection lost', 'error', 1920, 1080);
4279
- * ```
4280
- */
4281
- class Toast extends Container {
4282
- __uiComponent = true;
4283
- _bg;
4284
- _customBg;
4285
- _text;
4286
- _config;
4287
- _dismissPending = false;
4288
- constructor(config = {}) {
4289
- super();
4290
- this._config = {
4291
- duration: config.duration ?? 3000,
4292
- bottomOffset: config.bottomOffset ?? 60,
4293
- };
4294
- const customBg = resolveView(config.backgroundView);
4295
- this._customBg = !!customBg;
4296
- this._bg = customBg ?? new Graphics();
4297
- this.addChild(this._bg);
4298
- this._text = new Text({
4299
- text: '',
4300
- style: {
4301
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
4302
- fontSize: 16,
4303
- fill: 0xffffff,
4304
- },
4305
- });
4306
- this._text.anchor.set(0.5);
4307
- this.addChild(this._text);
4308
- this.visible = false;
4309
- }
4310
- /**
4311
- * Show a toast message.
4312
- */
4313
- async show(message, type = 'info', viewWidth, viewHeight) {
4314
- // Cancel any pending dismiss
4315
- Tween.killTweensOf(this);
4316
- this._dismissPending = false;
4317
- this._text.text = message;
4318
- const padding = 20;
4319
- const width = Math.max(200, this._text.width + padding * 2);
4320
- const height = 44;
4321
- const radius = 8;
4322
- // Draw the background
4323
- if (this._customBg) {
4324
- this._bg.width = width;
4325
- this._bg.height = height;
4326
- this._bg.x = -width / 2;
4327
- this._bg.y = -height / 2;
4328
- }
4329
- else {
4330
- const g = this._bg;
4331
- g.clear();
4332
- g.roundRect(-width / 2, -height / 2, width, height, radius);
4333
- g.fill(TOAST_COLORS[type]);
4334
- }
4335
- // Position
4336
- if (viewWidth && viewHeight) {
4337
- this.x = viewWidth / 2;
4338
- this.y = viewHeight - this._config.bottomOffset;
4339
- }
4340
- this.visible = true;
4341
- this.alpha = 0;
4342
- this.y += 20;
4343
- await Tween.to(this, { alpha: 1, y: this.y - 20 }, 300, Easing.easeOutCubic);
4344
- if (this._config.duration > 0) {
4345
- this._dismissPending = true;
4346
- await Tween.delay(this._config.duration);
4347
- if (this._dismissPending) {
4348
- this._dismissPending = false;
4349
- await this.dismiss();
4350
- }
4351
- }
4352
- }
4353
- /**
4354
- * Dismiss the toast.
4355
- */
4356
- async dismiss() {
4357
- if (!this.visible)
4358
- return;
4359
- this._dismissPending = false;
4360
- Tween.killTweensOf(this);
4361
- await Tween.to(this, { alpha: 0, y: this.y + 20 }, 200, Easing.easeInCubic);
4362
- this.visible = false;
4363
- }
4364
- /** React reconciler update hook */
4365
- updateConfig(changed) {
4366
- if ('duration' in changed)
4367
- this._config.duration = changed.duration;
4368
- if ('bottomOffset' in changed)
4369
- this._config.bottomOffset = changed.bottomOffset;
4370
- }
4371
- destroy(options) {
4372
- this._dismissPending = false;
4373
- Tween.killTweensOf(this);
4374
- super.destroy(options);
4375
- }
4376
- }
4377
-
4378
- // ─── Helpers ─────────────────────────────────────────────
4379
- function directionToFlex(direction) {
4380
- switch (direction) {
4381
- case 'horizontal': return { direction: 'row', wrap: false };
4382
- case 'vertical': return { direction: 'column', wrap: false };
4383
- case 'grid': return { direction: 'row', wrap: true };
4384
- case 'wrap': return { direction: 'row', wrap: true };
4385
- }
4386
- }
4387
- /**
4388
- * Responsive layout container powered by a lightweight built-in flex layout solver.
4389
- *
4390
- * Supports horizontal, vertical, grid, and wrap layout modes with
4391
- * alignment, padding, gap, and viewport-anchor positioning.
4392
- * Breakpoints allow different layouts for different screen sizes.
4393
- *
4394
- * @example
4395
- * ```ts
4396
- * const toolbar = new Layout({
4397
- * direction: 'horizontal',
4398
- * gap: 20,
4399
- * alignment: 'center',
4400
- * anchor: 'bottom-center',
4401
- * padding: 16,
4402
- * breakpoints: {
4403
- * 768: { direction: 'vertical', gap: 10 },
4404
- * },
4405
- * });
4406
- *
4407
- * toolbar.addItem(spinButton);
4408
- * toolbar.addItem(betLabel);
4409
- * scene.container.addChild(toolbar);
4410
- *
4411
- * toolbar.updateViewport(width, height);
4412
- * ```
4413
- */
4414
- class Layout extends Container {
4415
- __uiComponent = true;
4416
- _layoutConfig;
4417
- _padding;
4418
- _anchor;
4419
- _maxWidth;
4420
- _breakpoints;
4421
- _items = [];
4422
- _viewportWidth = 0;
4423
- _viewportHeight = 0;
4424
- _flex;
4425
- constructor(config = {}) {
4426
- super();
4427
- this._layoutConfig = {
4428
- direction: config.direction ?? 'vertical',
4429
- gap: config.gap ?? 0,
4430
- alignment: config.alignment ?? 'start',
4431
- autoLayout: config.autoLayout ?? true,
4432
- columns: config.columns ?? 2,
4433
- };
4434
- this._padding = config.padding ?? 0;
4435
- this._anchor = config.anchor ?? 'top-left';
4436
- this._maxWidth = config.maxWidth ?? Infinity;
4437
- this._breakpoints = config.breakpoints
4438
- ? Object.entries(config.breakpoints)
4439
- .map(([w, cfg]) => [Number(w), cfg])
4440
- .sort((a, b) => a[0] - b[0])
4441
- : [];
4442
- // Create internal FlexContainer
4443
- this._flex = new FlexContainer();
4444
- super.addChild(this._flex);
4445
- this.applyLayoutStyles();
4446
- }
4447
- /** Add an item to the layout */
4448
- addItem(child) {
4449
- this._items.push(child);
4450
- const flexConfig = this.buildFlexItemConfig(child);
4451
- this._flex.addFlexChild(child, flexConfig);
4452
- if (this._layoutConfig.autoLayout) {
4453
- this.applyLayoutStyles();
4454
- }
4455
- return this;
4456
- }
4457
- /** Remove an item from the layout */
4458
- removeItem(child) {
4459
- const idx = this._items.indexOf(child);
4460
- if (idx !== -1) {
4461
- this._items.splice(idx, 1);
4462
- this._flex.removeFlexChild(child);
4463
- }
4464
- return this;
4465
- }
4466
- /** Remove all items */
4467
- clearItems() {
4468
- this._flex.clearFlexChildren();
4469
- this._items.length = 0;
4470
- return this;
4471
- }
4472
- /** Get all layout items */
4473
- get items() {
4474
- return this._items;
4475
- }
4476
- /**
4477
- * Update the viewport size and recalculate layout.
4478
- * Should be called from `Scene.onResize()`.
4479
- */
4480
- updateViewport(width, height) {
4481
- this._viewportWidth = width;
4482
- this._viewportHeight = height;
4483
- this.applyLayoutStyles();
4484
- this.applyAnchor();
4485
- }
4486
- applyLayoutStyles() {
4487
- const effective = this.resolveConfig();
4488
- const direction = effective.direction ?? this._layoutConfig.direction;
4489
- const gap = effective.gap ?? this._layoutConfig.gap;
4490
- const alignment = effective.alignment ?? this._layoutConfig.alignment;
4491
- const padding = effective.padding ?? this._padding;
4492
- const maxWidth = effective.maxWidth ?? this._maxWidth;
4493
- const { direction: flexDir, wrap } = directionToFlex(direction);
4494
- this._flex.setDirection(flexDir);
4495
- this._flex.setJustifyContent('start');
4496
- this._flex.setAlignItems(alignment);
4497
- this._flex.setGap(gap);
4498
- this._flex.setPadding(padding);
4499
- // Wrap and maxWidth
4500
- if (wrap) {
4501
- this._flex._config.flexWrap = true;
4502
- if (direction === 'grid' && maxWidth < Infinity) {
4503
- this._flex._maxWidth = maxWidth;
4504
- }
4505
- if (maxWidth < Infinity) {
4506
- this._flex._maxWidth = maxWidth;
4507
- }
4508
- }
4509
- else {
4510
- this._flex._config.flexWrap = false;
4511
- }
4512
- // Update grid child widths
4513
- if (direction === 'grid') {
4514
- for (const item of this._items) {
4515
- const flexConfig = this.buildFlexItemConfig(item);
4516
- item._flexConfig = flexConfig;
4517
- }
4518
- }
4519
- // Set explicit size if we have viewport dimensions
4520
- if (this._viewportWidth > 0 && this._viewportHeight > 0) {
4521
- this._flex.resize(this._viewportWidth, this._viewportHeight);
4522
- }
4523
- else {
4524
- this._flex.updateLayout();
4525
- }
4526
- }
4527
- buildFlexItemConfig(_child) {
4528
- const effective = this.resolveConfig();
4529
- const direction = effective.direction ?? this._layoutConfig.direction;
4530
- const columns = effective.columns ?? this._layoutConfig.columns;
4531
- if (direction === 'grid' && columns > 0) {
4532
- // For grid, give each item a proportional width
4533
- // The actual pixel width will be computed during layout
4534
- return { flexGrow: 1 };
4535
- }
4536
- return undefined;
4537
- }
4538
- applyAnchor() {
4539
- const anchor = this.resolveConfig().anchor ?? this._anchor;
4540
- if (this._viewportWidth === 0 || this._viewportHeight === 0)
4541
- return;
4542
- const { width: contentW, height: contentH } = this._flex.getContentSize();
4543
- const vw = this._viewportWidth;
4544
- const vh = this._viewportHeight;
4545
- let anchorX = 0;
4546
- let anchorY = 0;
4547
- if (anchor.includes('left')) {
4548
- anchorX = 0;
4549
- }
4550
- else if (anchor.includes('right')) {
4551
- anchorX = vw - contentW;
4552
- }
4553
- else {
4554
- anchorX = (vw - contentW) / 2;
4555
- }
4556
- if (anchor.startsWith('top')) {
4557
- anchorY = 0;
4558
- }
4559
- else if (anchor.startsWith('bottom')) {
4560
- anchorY = vh - contentH;
4561
- }
4562
- else {
4563
- anchorY = (vh - contentH) / 2;
4564
- }
4565
- this.x = anchorX;
4566
- this.y = anchorY;
4567
- }
4568
- resolveConfig() {
4569
- if (this._breakpoints.length === 0 || this._viewportWidth === 0) {
4570
- return {};
4571
- }
4572
- for (const [maxWidth, overrides] of this._breakpoints) {
4573
- if (this._viewportWidth <= maxWidth) {
4574
- return overrides;
4575
- }
4576
- }
4577
- return {};
4578
- }
4579
- /** React reconciler update hook */
4580
- updateConfig(changed) {
4581
- if ('direction' in changed)
4582
- this._layoutConfig.direction = changed.direction;
4583
- if ('gap' in changed)
4584
- this._layoutConfig.gap = changed.gap;
4585
- if ('alignment' in changed)
4586
- this._layoutConfig.alignment = changed.alignment;
4587
- if ('anchor' in changed)
4588
- this._anchor = changed.anchor;
4589
- if ('padding' in changed)
4590
- this._padding = changed.padding;
4591
- if ('columns' in changed)
4592
- this._layoutConfig.columns = changed.columns;
4593
- this.applyLayoutStyles();
4594
- if (this._viewportWidth > 0)
4595
- this.applyAnchor();
4596
- }
4597
- destroy(options) {
4598
- this._items.length = 0;
4599
- super.destroy(options);
4600
- }
4601
- }
4602
-
4603
- const DECELERATION = 0.95;
4604
- const MIN_VELOCITY = 0.5;
4605
- /**
4606
- * Scrollable container with touch/drag, mouse wheel, and inertia.
4607
- *
4608
- * @example
4609
- * ```ts
4610
- * const scroll = new ScrollContainer({
4611
- * width: 600,
4612
- * height: 400,
4613
- * direction: 'vertical',
4614
- * elementsMargin: 8,
4615
- * });
4616
- *
4617
- * for (let i = 0; i < 50; i++) {
4618
- * scroll.addItem(createRow(i));
4619
- * }
4620
- *
4621
- * scene.container.addChild(scroll);
4622
- * ```
4623
- */
4624
- class ScrollContainer extends Container {
4625
- __uiComponent = true;
4626
- _viewport;
4627
- _internalSetup = true;
4628
- _content;
4629
- _maskGfx;
4630
- _bg = null;
4631
- _scrollConfig;
4632
- _items = [];
4633
- // Scrollbar
4634
- _scrollbar = null;
4635
- _scrollbarConfig;
4636
- // Drag state
4637
- _dragging = false;
4638
- _dragStart = { x: 0, y: 0 };
4639
- _contentStart = { x: 0, y: 0 };
4640
- _velocity = { x: 0, y: 0 };
4641
- _lastDragPos = { x: 0, y: 0 };
4642
- _lastDragTime = 0;
4643
- _inertiaActive = false;
4644
- // Bound handlers for cleanup
4645
- _onTickBound = null;
4646
- _onWheelBound = null;
4647
- constructor(config) {
4648
- super();
4649
- this._viewport = { width: config.width, height: config.height };
4650
- this._scrollConfig = {
4651
- direction: config.direction ?? 'vertical',
4652
- elementsMargin: config.elementsMargin ?? 0,
4653
- padding: config.padding ?? 0,
4654
- borderRadius: config.borderRadius ?? 0,
4655
- disableEasing: config.disableEasing ?? false,
4656
- };
4657
- // Background
4658
- if (config.backgroundColor !== undefined) {
4659
- this._bg = new Graphics();
4660
- this._bg.roundRect(0, 0, config.width, config.height, this._scrollConfig.borderRadius)
4661
- .fill(config.backgroundColor);
4662
- this.addChild(this._bg);
4663
- }
4664
- // Mask
4665
- this._maskGfx = new Graphics();
4666
- this._maskGfx.roundRect(0, 0, config.width, config.height, this._scrollConfig.borderRadius)
4667
- .fill(0xffffff);
4668
- this.addChild(this._maskGfx);
4669
- // Content container
4670
- this._content = new Container();
4671
- this._content.mask = this._maskGfx;
4672
- this.addChild(this._content);
4673
- // Interaction
4674
- this.eventMode = 'static';
4675
- this.hitArea = { contains: (x, y) => x >= 0 && x <= config.width && y >= 0 && y <= config.height };
4676
- this.on('pointerdown', this._onPointerDown, this);
4677
- this.on('pointermove', this._onPointerMove, this);
4678
- this.on('pointerup', this._onPointerUp, this);
4679
- this.on('pointerupoutside', this._onPointerUp, this);
4680
- // Mouse wheel
4681
- this._onWheelBound = this._onWheel.bind(this);
4682
- // Scrollbar
4683
- const sbWidth = config.scrollbarWidth ?? 6;
4684
- const sbPadding = config.scrollbarPadding ?? 4;
4685
- this._scrollbarConfig = { width: sbWidth, padding: sbPadding };
4686
- if (config.scrollbar) {
4687
- const customThumb = resolveView(config.thumbView);
4688
- if (customThumb) {
4689
- this._scrollbar = customThumb;
4690
- }
4691
- else {
4692
- const g = new Graphics();
4693
- g.roundRect(0, 0, sbWidth, 40, sbWidth / 2).fill(config.scrollbarColor ?? 0xaaaaaa);
4694
- g.alpha = config.scrollbarAlpha ?? 0.5;
4695
- this._scrollbar = g;
4696
- }
4697
- this._scrollbar.visible = false;
4698
- super.addChild(this._scrollbar);
4699
- }
4700
- this._internalSetup = false;
4701
- }
4702
- /**
4703
- * Override addChild so external children are routed to scroll content.
4704
- * Enables `<scrollContainer><label /><panel /></scrollContainer>` in React JSX.
4705
- */
4706
- addChild(...children) {
4707
- if (this._internalSetup) {
4708
- return super.addChild(...children);
4709
- }
4710
- for (const child of children) {
4711
- this.addItem(child);
4712
- }
4713
- return children[0];
4714
- }
4715
- removeChild(...children) {
4716
- if (this._internalSetup) {
4717
- return super.removeChild(...children);
4718
- }
4719
- for (const child of children) {
4720
- const idx = this._items.indexOf(child);
4721
- if (idx !== -1) {
4722
- this._items.splice(idx, 1);
4723
- this._content.removeChild(child);
4724
- }
4725
- }
4726
- this.layoutItems();
4727
- return children[0];
4728
- }
4729
- /** React reconciler update hook */
4730
- updateConfig(changed) {
4731
- if ('width' in changed || 'height' in changed) {
4732
- this.setViewportSize(changed.width ?? this._viewport.width, changed.height ?? this._viewport.height);
4733
- }
4734
- }
4735
- /** Enable mouse wheel scrolling (call after adding to stage) */
4736
- enableWheel(canvas) {
4737
- if (this._onWheelBound) {
4738
- canvas.addEventListener('wheel', this._onWheelBound, { passive: false });
4739
- }
4740
- }
4741
- /** Set scrollable content. Replaces any existing items. */
4742
- setContent(content) {
4743
- this.clearItems();
4744
- const children = [...content.children];
4745
- for (const child of children) {
4746
- this.addItem(child);
4747
- }
4748
- }
4749
- /** Add a single item */
4750
- addItem(child) {
4751
- this._items.push(child);
4752
- this._content.addChild(child);
4753
- this.layoutItems();
4754
- return this;
4755
- }
4756
- /** Remove all items */
4757
- clearItems() {
4758
- for (const item of this._items) {
4759
- this._content.removeChild(item);
4760
- }
4761
- this._items.length = 0;
4762
- }
4763
- /** Get items */
4764
- get items() {
4765
- return this._items;
4766
- }
4767
- /** Scroll to make a specific item index visible */
4768
- scrollToItem(index) {
4769
- if (index < 0 || index >= this._items.length)
4770
- return;
4771
- const item = this._items[index];
4772
- const isVert = this._scrollConfig.direction !== 'horizontal';
4773
- if (isVert) {
4774
- this._content.y = -item.y + this._scrollConfig.padding;
4775
- }
4776
- else {
4777
- this._content.x = -item.x + this._scrollConfig.padding;
4778
- }
4779
- this.clampScroll();
4780
- }
4781
- /** Current scroll position */
4782
- get scrollPosition() {
4783
- return { x: this._content.x, y: this._content.y };
4784
- }
4785
- /** Resize the scroll viewport */
4786
- setViewportSize(width, height) {
4787
- this._viewport.width = width;
4788
- this._viewport.height = height;
4789
- this._maskGfx.clear();
4790
- this._maskGfx.roundRect(0, 0, width, height, this._scrollConfig.borderRadius).fill(0xffffff);
4791
- if (this._bg) {
4792
- this._bg.clear();
4793
- this._bg.roundRect(0, 0, width, height, this._scrollConfig.borderRadius)
4794
- .fill(0xffffff); // color will be overridden if needed
4795
- }
4796
- this.clampScroll();
4797
- }
4798
- // ─── Layout ──────────────────────────────────────────
4799
- layoutItems() {
4800
- const { direction, elementsMargin, padding } = this._scrollConfig;
4801
- const isVert = direction !== 'horizontal';
4802
- let pos = padding;
4803
- for (const item of this._items) {
4804
- if (isVert) {
4805
- item.x = padding;
4806
- item.y = pos;
4807
- pos += item.height + elementsMargin;
4808
- }
4809
- else {
4810
- item.x = pos;
4811
- item.y = padding;
4812
- pos += item.width + elementsMargin;
4813
- }
4814
- }
4815
- }
4816
- // ─── Drag handling ───────────────────────────────────
4817
- _onPointerDown(e) {
4818
- this._dragging = true;
4819
- this._inertiaActive = false;
4820
- this._dragStart.x = e.globalX;
4821
- this._dragStart.y = e.globalY;
4822
- this._contentStart.x = this._content.x;
4823
- this._contentStart.y = this._content.y;
4824
- this._lastDragPos.x = e.globalX;
4825
- this._lastDragPos.y = e.globalY;
4826
- this._lastDragTime = Date.now();
4827
- this._velocity.x = 0;
4828
- this._velocity.y = 0;
4829
- this.stopInertia();
4830
- }
4831
- _onPointerMove(e) {
4832
- if (!this._dragging)
4833
- return;
4834
- const dx = e.globalX - this._dragStart.x;
4835
- const dy = e.globalY - this._dragStart.y;
4836
- const { direction } = this._scrollConfig;
4837
- if (direction !== 'horizontal') {
4838
- this._content.y = this._contentStart.y + dy;
4839
- }
4840
- if (direction !== 'vertical') {
4841
- this._content.x = this._contentStart.x + dx;
4842
- }
4843
- // Track velocity
4844
- const now = Date.now();
4845
- const dt = now - this._lastDragTime;
4846
- if (dt > 0) {
4847
- this._velocity.x = (e.globalX - this._lastDragPos.x) / dt * 16;
4848
- this._velocity.y = (e.globalY - this._lastDragPos.y) / dt * 16;
4849
- }
4850
- this._lastDragPos.x = e.globalX;
4851
- this._lastDragPos.y = e.globalY;
4852
- this._lastDragTime = now;
4853
- this.clampScroll();
4854
- }
4855
- _onPointerUp() {
4856
- if (!this._dragging)
4857
- return;
4858
- this._dragging = false;
4859
- if (!this._scrollConfig.disableEasing &&
4860
- (Math.abs(this._velocity.x) > MIN_VELOCITY || Math.abs(this._velocity.y) > MIN_VELOCITY)) {
4861
- this.startInertia();
4862
- }
4863
- }
4864
- // ─── Inertia ─────────────────────────────────────────
4865
- startInertia() {
4866
- this._inertiaActive = true;
4867
- this._onTickBound = this._inertiaTick.bind(this);
4868
- Ticker.shared.add(this._onTickBound);
4869
- }
4870
- stopInertia() {
4871
- if (this._onTickBound && this._inertiaActive) {
4872
- Ticker.shared.remove(this._onTickBound);
4873
- this._inertiaActive = false;
4874
- }
4875
- }
4876
- _inertiaTick() {
4877
- const { direction } = this._scrollConfig;
4878
- if (direction !== 'horizontal') {
4879
- this._content.y += this._velocity.y;
4880
- this._velocity.y *= DECELERATION;
4881
- }
4882
- if (direction !== 'vertical') {
4883
- this._content.x += this._velocity.x;
4884
- this._velocity.x *= DECELERATION;
4885
- }
4886
- this.clampScroll();
4887
- if (Math.abs(this._velocity.x) < MIN_VELOCITY && Math.abs(this._velocity.y) < MIN_VELOCITY) {
4888
- this.stopInertia();
4889
- }
4890
- }
4891
- // ─── Mouse wheel ─────────────────────────────────────
4892
- _onWheel(e) {
4893
- const { direction } = this._scrollConfig;
4894
- e.preventDefault();
4895
- if (direction !== 'horizontal') {
4896
- this._content.y -= e.deltaY;
4897
- }
4898
- if (direction !== 'vertical') {
4899
- this._content.x -= e.deltaX;
4900
- }
4901
- this.clampScroll();
4902
- }
4903
- // ─── Scroll bounds ───────────────────────────────────
4904
- clampScroll() {
4905
- const { direction } = this._scrollConfig;
4906
- const bounds = this._content.getLocalBounds();
4907
- if (direction !== 'horizontal') {
4908
- const contentHeight = bounds.height + bounds.y;
4909
- const maxScroll = Math.min(0, this._viewport.height - contentHeight);
4910
- this._content.y = Math.max(maxScroll, Math.min(0, this._content.y));
4911
- }
4912
- if (direction !== 'vertical') {
4913
- const contentWidth = bounds.width + bounds.x;
4914
- const maxScroll = Math.min(0, this._viewport.width - contentWidth);
4915
- this._content.x = Math.max(maxScroll, Math.min(0, this._content.x));
4916
- }
4917
- this.updateScrollbar();
4918
- }
4919
- updateScrollbar() {
4920
- if (!this._scrollbar)
4921
- return;
4922
- const { direction } = this._scrollConfig;
4923
- const { width: sbW, padding: sbPad } = this._scrollbarConfig;
4924
- const bounds = this._content.getLocalBounds();
4925
- const isVert = direction !== 'horizontal';
4926
- if (isVert) {
4927
- const contentH = bounds.height + bounds.y;
4928
- if (contentH <= this._viewport.height) {
4929
- this._scrollbar.visible = false;
4930
- return;
4931
- }
4932
- this._scrollbar.visible = true;
4933
- const ratio = this._viewport.height / contentH;
4934
- const thumbH = Math.max(20, this._viewport.height * ratio);
4935
- const scrollRange = this._viewport.height - thumbH;
4936
- const scrollProgress = -this._content.y / (contentH - this._viewport.height);
4937
- this._scrollbar.x = this._viewport.width - sbW - sbPad;
4938
- this._scrollbar.y = scrollProgress * scrollRange;
4939
- this._scrollbar.height = thumbH;
4940
- this._scrollbar.width = sbW;
4941
- }
4942
- else {
4943
- const contentW = bounds.width + bounds.x;
4944
- if (contentW <= this._viewport.width) {
4945
- this._scrollbar.visible = false;
4946
- return;
4947
- }
4948
- this._scrollbar.visible = true;
4949
- const ratio = this._viewport.width / contentW;
4950
- const thumbW = Math.max(20, this._viewport.width * ratio);
4951
- const scrollRange = this._viewport.width - thumbW;
4952
- const scrollProgress = -this._content.x / (contentW - this._viewport.width);
4953
- this._scrollbar.y = this._viewport.height - sbW - sbPad;
4954
- this._scrollbar.x = scrollProgress * scrollRange;
4955
- this._scrollbar.width = thumbW;
4956
- this._scrollbar.height = sbW;
4957
- }
4958
- }
4959
- destroy(options) {
4960
- this.stopInertia();
4961
- this.off('pointerdown', this._onPointerDown, this);
4962
- this.off('pointermove', this._onPointerMove, this);
4963
- this.off('pointerup', this._onPointerUp, this);
4964
- this.off('pointerupoutside', this._onPointerUp, this);
4965
- this._items.length = 0;
4966
- super.destroy(options);
4967
- }
4968
- }
4969
-
4970
- export { AssetManager, AudioManager, BalanceDisplay, Button, Easing, EventEmitter, FPSOverlay, FlexContainer, GameApplication, InputManager, Label, Layout, LoadingScene, Modal, Orientation, Panel, ProgressBar, ScaleMode, Scene, SceneManager, ScrollContainer, SpineHelper, SpriteAnimation, StateMachine, Timeline, Toast, TransitionType, Tween, ViewportManager, WinDisplay };
2465
+ export { AssetManager, AudioManager, Easing, EventEmitter, FPSOverlay, GameApplication, InputManager, LoadingScene, Orientation, ScaleMode, Scene, SceneManager, SpineHelper, SpriteAnimation, Timeline, TransitionType, Tween, ViewportManager };
4971
2466
  //# sourceMappingURL=index.esm.js.map