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