@energy8platform/game-engine 0.21.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 (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 +2 -35
  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/ui.cjs.js DELETED
@@ -1,3014 +0,0 @@
1
- 'use strict';
2
-
3
- var pixi_js = require('pixi.js');
4
-
5
- /**
6
- * Resolve a ViewInput to a Container instance.
7
- *
8
- * @example
9
- * ```ts
10
- * resolveView('btn-idle') // → Sprite.from('btn-idle')
11
- * resolveView(someTexture) // → new Sprite(someTexture)
12
- * resolveView(myCustomContainer) // → myCustomContainer (as-is)
13
- * resolveView(undefined) // → null
14
- * ```
15
- */
16
- function resolveView(input) {
17
- if (input == null)
18
- return null;
19
- if (typeof input === 'string')
20
- return pixi_js.Sprite.from(input);
21
- if (input instanceof pixi_js.Texture)
22
- return new pixi_js.Sprite(input);
23
- return input;
24
- }
25
-
26
- // ─── Helpers ─────────────────────────────────────────────
27
- function normalizePadding(p) {
28
- return typeof p === 'number' ? [p, p, p, p] : p;
29
- }
30
- /** Resolve padding from config: individual props override the base `padding` value */
31
- function resolvePadding(config) {
32
- const base = normalizePadding(config.padding ?? 0);
33
- return [
34
- config.paddingTop ?? base[0],
35
- config.paddingRight ?? base[1],
36
- config.paddingBottom ?? base[2],
37
- config.paddingLeft ?? base[3],
38
- ];
39
- }
40
- /** Resolve a dimension value — number passes through, "50%" resolves against reference */
41
- function resolveDimension(value, reference) {
42
- if (value === undefined)
43
- return undefined;
44
- if (typeof value === 'number')
45
- return value;
46
- if (typeof value === 'string' && value.endsWith('%')) {
47
- const pct = parseFloat(value);
48
- if (!isNaN(pct) && reference > 0 && isFinite(reference))
49
- return (pct / 100) * reference;
50
- }
51
- return undefined;
52
- }
53
- /** Measure a child's size and bounds offset for layout purposes */
54
- function measureChild(child, parentContentW = 0, parentContentH = 0) {
55
- const cfg = child._flexConfig;
56
- const resolvedLW = resolveDimension(cfg?.layoutWidth, parentContentW);
57
- const resolvedLH = resolveDimension(cfg?.layoutHeight, parentContentH);
58
- // FlexContainer children are top-left origin by construction, so `ox/oy = 0`
59
- // is correct and we can skip the `getLocalBounds()` call entirely.
60
- if (child instanceof FlexContainer) {
61
- const fc = child;
62
- const w = fc._explicitWidth > 0 ? fc._explicitWidth : (fc._computedWidth > 0 ? fc._computedWidth : undefined);
63
- const h = fc._explicitHeight > 0 ? fc._explicitHeight : (fc._computedHeight > 0 ? fc._computedHeight : undefined);
64
- if (w !== undefined && h !== undefined) {
65
- return { w: resolvedLW ?? w, h: resolvedLH ?? h, ox: 0, oy: 0 };
66
- }
67
- }
68
- // Use localBounds to get the true visual origin offset.
69
- // We take `ox/oy` from bounds unconditionally — a user-supplied `layoutWidth/Height`
70
- // overrides the SIZE used by flex (protection against pre-paint bounds of 0), but
71
- // it must NOT erase the center-anchor compensation: Button/Label views are drawn at
72
- // `(-w/2..w/2)` and their bounds.x = -w/2 is what lets `layoutLine` place the
73
- // visible rectangle where the layout intends.
74
- const bounds = child.getLocalBounds();
75
- return {
76
- w: resolvedLW ?? bounds.width,
77
- h: resolvedLH ?? bounds.height,
78
- ox: bounds.x,
79
- oy: bounds.y,
80
- };
81
- }
82
- /**
83
- * Set a child's main or cross dimension.
84
- * For FlexContainer children, calls resize() to trigger internal relayout
85
- * instead of the PixiJS scale setter.
86
- */
87
- function setChildMainSize(child, isRow, mainSize, item) {
88
- if (child instanceof FlexContainer) {
89
- const fc = child;
90
- fc.resize(isRow ? mainSize : fc._explicitWidth || fc._computedWidth, isRow ? fc._explicitHeight || fc._computedHeight : mainSize);
91
- }
92
- else {
93
- if (isRow) {
94
- child.width = mainSize;
95
- }
96
- else {
97
- child.height = mainSize;
98
- }
99
- }
100
- if (isRow)
101
- item.w = mainSize;
102
- else
103
- item.h = mainSize;
104
- }
105
- function setChildCrossSize(child, isRow, crossSize) {
106
- if (child instanceof FlexContainer) {
107
- const fc = child;
108
- fc.resize(isRow ? fc._explicitWidth || fc._computedWidth : crossSize, isRow ? crossSize : fc._explicitHeight || fc._computedHeight);
109
- }
110
- else {
111
- if (isRow) {
112
- child.height = crossSize;
113
- }
114
- else {
115
- child.width = crossSize;
116
- }
117
- }
118
- }
119
- function layoutLine(items, isRow, mainSize, justify, align, gap, crossOffset, crossSize) {
120
- if (items.length === 0)
121
- return;
122
- // Compute total fixed main size and flex grow total
123
- let totalFixed = 0;
124
- let totalGrow = 0;
125
- for (const item of items) {
126
- const grow = item.child._flexConfig?.flexGrow ?? 0;
127
- if (grow > 0) {
128
- totalGrow += grow;
129
- }
130
- else {
131
- totalFixed += isRow ? item.w : item.h;
132
- }
133
- }
134
- const totalGap = gap * (items.length - 1);
135
- const availableForFlex = Math.max(0, mainSize - totalFixed - totalGap);
136
- // Resolve flex sizes
137
- if (totalGrow > 0) {
138
- for (const item of items) {
139
- const grow = item.child._flexConfig?.flexGrow ?? 0;
140
- if (grow > 0) {
141
- const flexSize = (grow / totalGrow) * availableForFlex;
142
- setChildMainSize(item.child, isRow, flexSize, item);
143
- }
144
- }
145
- }
146
- // Shrink: if content overflows and mainSize is finite, shrink eligible items
147
- if (totalGrow === 0 && mainSize > 0) {
148
- const overflow = totalFixed + totalGap - mainSize;
149
- if (overflow > 0) {
150
- let totalShrinkable = 0;
151
- for (const item of items) {
152
- const shrink = item.child._flexConfig?.flexShrink ?? 1;
153
- if (shrink > 0) {
154
- totalShrinkable += isRow ? item.w : item.h;
155
- }
156
- }
157
- if (totalShrinkable > 0) {
158
- for (const item of items) {
159
- const shrink = item.child._flexConfig?.flexShrink ?? 1;
160
- if (shrink > 0) {
161
- const itemMain = isRow ? item.w : item.h;
162
- const reduction = overflow * (itemMain / totalShrinkable);
163
- const newSize = Math.max(0, itemMain - reduction);
164
- setChildMainSize(item.child, isRow, newSize, item);
165
- }
166
- }
167
- }
168
- }
169
- }
170
- // Calculate total main size after flex
171
- let totalMain = totalGap;
172
- for (const item of items) {
173
- totalMain += isRow ? item.w : item.h;
174
- }
175
- // Justify: compute starting offset and extra spacing
176
- let mainOffset = 0;
177
- let extraGap = 0;
178
- switch (justify) {
179
- case 'start':
180
- break;
181
- case 'center':
182
- mainOffset = Math.max(0, (mainSize - totalMain) / 2);
183
- break;
184
- case 'end':
185
- mainOffset = Math.max(0, mainSize - totalMain);
186
- break;
187
- case 'space-between':
188
- if (items.length > 1) {
189
- extraGap = Math.max(0, (mainSize - totalMain + totalGap) / (items.length - 1)) - gap;
190
- }
191
- break;
192
- case 'space-around':
193
- if (items.length > 0) {
194
- const totalSpace = Math.max(0, mainSize - totalMain + totalGap);
195
- const segment = totalSpace / items.length;
196
- mainOffset = segment / 2;
197
- extraGap = segment - gap;
198
- }
199
- break;
200
- }
201
- // Position each item
202
- let pos = mainOffset;
203
- for (const item of items) {
204
- const mainDim = isRow ? item.w : item.h;
205
- const crossDim = isRow ? item.h : item.w;
206
- // Cross-axis alignment (alignSelf overrides align)
207
- const effectiveAlign = (item.child._flexConfig?.alignSelf && item.child._flexConfig.alignSelf !== 'auto')
208
- ? item.child._flexConfig.alignSelf
209
- : align;
210
- let crossPos = crossOffset;
211
- switch (effectiveAlign) {
212
- case 'start':
213
- break;
214
- case 'center':
215
- crossPos += (crossSize - crossDim) / 2;
216
- break;
217
- case 'end':
218
- crossPos += crossSize - crossDim;
219
- break;
220
- case 'stretch':
221
- setChildCrossSize(item.child, isRow, crossSize);
222
- break;
223
- }
224
- // Compensate for local bounds offset (e.g. centered anchors)
225
- if (isRow) {
226
- item.child.x = pos - item.ox;
227
- item.child.y = crossPos - item.oy;
228
- }
229
- else {
230
- item.child.x = crossPos - item.ox;
231
- item.child.y = pos - item.oy;
232
- }
233
- pos += mainDim + gap + extraGap;
234
- }
235
- }
236
- // ─── FlexContainer ───────────────────────────────────────
237
- /**
238
- * Lightweight flexbox-like layout container for PixiJS.
239
- *
240
- * Supports row/column direction, justify/align, gap, padding, wrapping,
241
- * and flex-grow distribution. Zero external dependencies.
242
- *
243
- * @example
244
- * ```ts
245
- * const toolbar = new FlexContainer({
246
- * direction: 'row',
247
- * justifyContent: 'space-between',
248
- * alignItems: 'center',
249
- * gap: 16,
250
- * padding: 12,
251
- * });
252
- *
253
- * toolbar.addFlexChild(button1);
254
- * toolbar.addFlexChild(button2);
255
- * toolbar.resize(800, 60);
256
- * ```
257
- */
258
- class FlexContainer extends pixi_js.Container {
259
- __uiComponent = true;
260
- _config;
261
- _padding;
262
- _maxWidth;
263
- _maxHeight;
264
- /** @internal */ _explicitWidth;
265
- /** @internal */ _explicitHeight;
266
- /** @internal */ _computedWidth = 0;
267
- /** @internal */ _computedHeight = 0;
268
- /** @internal */ _availableWidth = 0;
269
- /** @internal */ _availableHeight = 0;
270
- /** @internal */ _rawWidth;
271
- /** @internal */ _rawHeight;
272
- _layoutChildren = [];
273
- _layoutDirty = true;
274
- _layoutSuspended = false;
275
- constructor(config = {}) {
276
- super();
277
- this._config = {
278
- direction: config.direction ?? 'row',
279
- justifyContent: config.justifyContent ?? 'start',
280
- alignItems: config.alignItems ?? 'start',
281
- gap: config.gap ?? 0,
282
- flexWrap: config.flexWrap ?? false,
283
- alignContent: config.alignContent ?? 'start',
284
- };
285
- this._padding = resolvePadding(config);
286
- this._maxWidth = config.maxWidth ?? Infinity;
287
- this._maxHeight = config.maxHeight ?? Infinity;
288
- this._rawWidth = config.width ?? 0;
289
- this._rawHeight = config.height ?? 0;
290
- this._explicitWidth = typeof this._rawWidth === 'number' ? this._rawWidth : 0;
291
- this._explicitHeight = typeof this._rawHeight === 'number' ? this._rawHeight : 0;
292
- }
293
- // ─── Public API ──────────────────────────────────────
294
- /** Add a child with optional flex config. Also registers in flex layout. */
295
- addFlexChild(child, flexConfig) {
296
- if (flexConfig)
297
- child._flexConfig = flexConfig;
298
- if (!this._layoutChildren.includes(child)) {
299
- this._layoutChildren.push(child);
300
- this._layoutDirty = true;
301
- }
302
- super.addChild(child);
303
- return this;
304
- }
305
- /** Remove a child from flex layout and display list */
306
- removeFlexChild(child) {
307
- const idx = this._layoutChildren.indexOf(child);
308
- if (idx !== -1) {
309
- this._layoutChildren.splice(idx, 1);
310
- this._layoutDirty = true;
311
- }
312
- super.removeChild(child);
313
- return this;
314
- }
315
- /** Remove all flex children */
316
- clearFlexChildren() {
317
- for (const child of this._layoutChildren) {
318
- super.removeChild(child);
319
- }
320
- this._layoutChildren.length = 0;
321
- this._layoutDirty = true;
322
- return this;
323
- }
324
- /**
325
- * Override addChild so children automatically participate in flex layout.
326
- * This enables declarative usage from React JSX.
327
- */
328
- addChild(...children) {
329
- for (const child of children) {
330
- if (!this._layoutChildren.includes(child)) {
331
- this._layoutChildren.push(child);
332
- this._layoutDirty = true;
333
- }
334
- }
335
- const result = super.addChild(...children);
336
- if (this._layoutDirty && !this._layoutSuspended)
337
- this.updateLayout();
338
- return result;
339
- }
340
- addChildAt(child, index) {
341
- if (!this._layoutChildren.includes(child)) {
342
- // Insert into layout children at matching position
343
- const layoutIndex = Math.min(index, this._layoutChildren.length);
344
- this._layoutChildren.splice(layoutIndex, 0, child);
345
- this._layoutDirty = true;
346
- }
347
- const result = super.addChildAt(child, index);
348
- if (this._layoutDirty && !this._layoutSuspended)
349
- this.updateLayout();
350
- return result;
351
- }
352
- removeChild(...children) {
353
- for (const child of children) {
354
- const idx = this._layoutChildren.indexOf(child);
355
- if (idx !== -1) {
356
- this._layoutChildren.splice(idx, 1);
357
- this._layoutDirty = true;
358
- }
359
- }
360
- return super.removeChild(...children);
361
- }
362
- /** Get all flex layout children (read-only) */
363
- get flexChildren() {
364
- return this._layoutChildren;
365
- }
366
- /** Suspend automatic layout recalculation. Call resumeLayout() to flush. */
367
- suspendLayout() {
368
- this._layoutSuspended = true;
369
- }
370
- /** Resume automatic layout and flush if dirty. */
371
- resumeLayout() {
372
- this._layoutSuspended = false;
373
- if (this._layoutDirty)
374
- this.updateLayout();
375
- }
376
- /** Update the container size and recalculate layout */
377
- resize(width, height) {
378
- this._explicitWidth = width;
379
- this._explicitHeight = height;
380
- this._layoutDirty = true;
381
- if (!this._layoutSuspended)
382
- this.updateLayout();
383
- }
384
- /** Update layout direction */
385
- setDirection(direction) {
386
- this._config.direction = direction;
387
- this._layoutDirty = true;
388
- }
389
- /** Update justifyContent */
390
- setJustifyContent(justify) {
391
- this._config.justifyContent = justify;
392
- this._layoutDirty = true;
393
- }
394
- /** Update alignItems */
395
- setAlignItems(align) {
396
- this._config.alignItems = align;
397
- this._layoutDirty = true;
398
- }
399
- /** Update gap */
400
- setGap(gap) {
401
- this._config.gap = gap;
402
- this._layoutDirty = true;
403
- }
404
- /** Update padding */
405
- setPadding(padding) {
406
- this._padding = normalizePadding(padding);
407
- this._layoutDirty = true;
408
- }
409
- /**
410
- * Recalculate and apply layout positions for all children.
411
- * Called automatically by `resize()`. Call manually after
412
- * adding/removing children without resize.
413
- */
414
- updateLayout() {
415
- if (this._layoutSuspended) {
416
- this._layoutDirty = true;
417
- return;
418
- }
419
- this._layoutDirty = false;
420
- const { direction, justifyContent, alignItems, gap, flexWrap, alignContent } = this._config;
421
- const [pt, pr, pb, pl] = this._padding;
422
- const isRow = direction === 'row';
423
- // Resolve percentage width/height against parent's available space
424
- if (typeof this._rawWidth === 'string') {
425
- this._explicitWidth = resolveDimension(this._rawWidth, this._availableWidth) ?? 0;
426
- }
427
- if (typeof this._rawHeight === 'string') {
428
- this._explicitHeight = resolveDimension(this._rawHeight, this._availableHeight) ?? 0;
429
- }
430
- const contentW = this._explicitWidth > 0 ? this._explicitWidth - pl - pr : Infinity;
431
- const contentH = this._explicitHeight > 0 ? this._explicitHeight - pt - pb : Infinity;
432
- const mainLimit = isRow ? contentW : contentH;
433
- const crossLimit = isRow ? contentH : contentW;
434
- // Pass content area to measureChild for percentage resolution
435
- const pctRefW = contentW < Infinity ? contentW : 0;
436
- const pctRefH = contentH < Infinity ? contentH : 0;
437
- // Propagate available size to child FlexContainers and resolve their percentages
438
- for (const child of this._layoutChildren) {
439
- if (child instanceof FlexContainer) {
440
- const fc = child;
441
- fc._availableWidth = pctRefW;
442
- fc._availableHeight = pctRefH;
443
- // If child has percentage dimensions, trigger its layout to resolve them
444
- if (typeof fc._rawWidth === 'string' || typeof fc._rawHeight === 'string') {
445
- fc.updateLayout();
446
- }
447
- }
448
- }
449
- // Measure children (skip flexExclude — they position themselves)
450
- const measured = [];
451
- for (const child of this._layoutChildren) {
452
- if (child._flexConfig?.flexExclude)
453
- continue;
454
- const { w, h, ox, oy } = measureChild(child, pctRefW, pctRefH);
455
- measured.push({ child, w, h, ox, oy });
456
- }
457
- // Split into lines (if wrapping)
458
- const lines = [];
459
- if (flexWrap && mainLimit < Infinity) {
460
- let currentLine = [];
461
- let lineMain = 0;
462
- for (const item of measured) {
463
- const itemMain = isRow ? item.w : item.h;
464
- const wouldBe = lineMain + (currentLine.length > 0 ? gap : 0) + itemMain;
465
- if (currentLine.length > 0 && wouldBe > mainLimit) {
466
- lines.push(currentLine);
467
- currentLine = [item];
468
- lineMain = itemMain;
469
- }
470
- else {
471
- currentLine.push(item);
472
- lineMain = wouldBe;
473
- }
474
- }
475
- if (currentLine.length > 0)
476
- lines.push(currentLine);
477
- }
478
- else {
479
- lines.push(measured);
480
- }
481
- // Compute cross size per line
482
- const lineCrossSizes = lines.map((line) => {
483
- let maxCross = 0;
484
- for (const item of line) {
485
- const cross = isRow ? item.h : item.w;
486
- if (cross > maxCross)
487
- maxCross = cross;
488
- }
489
- return maxCross;
490
- });
491
- // Compute natural main size (for auto-sizing when no explicit size given)
492
- let naturalMainSize = 0;
493
- if (mainLimit === Infinity) {
494
- for (const line of lines) {
495
- let lineMain = 0;
496
- for (const item of line) {
497
- lineMain += isRow ? item.w : item.h;
498
- }
499
- lineMain += gap * Math.max(0, line.length - 1);
500
- naturalMainSize = Math.max(naturalMainSize, lineMain);
501
- }
502
- }
503
- // Effective main size: explicit if set, otherwise natural content size
504
- const effectiveMainSize = mainLimit < Infinity ? mainLimit : naturalMainSize;
505
- // Compute alignContent offsets for multi-line layouts
506
- const totalLinesCross = lineCrossSizes.reduce((s, v) => s + v, 0) + gap * Math.max(0, lines.length - 1);
507
- let acOffset = 0;
508
- let acExtraGap = 0;
509
- if (lines.length > 1 && crossLimit < Infinity) {
510
- const freeSpace = Math.max(0, crossLimit - totalLinesCross);
511
- switch (alignContent) {
512
- case 'center':
513
- acOffset = freeSpace / 2;
514
- break;
515
- case 'end':
516
- acOffset = freeSpace;
517
- break;
518
- case 'space-between':
519
- if (lines.length > 1) {
520
- acExtraGap = freeSpace / (lines.length - 1);
521
- }
522
- break;
523
- case 'stretch':
524
- if (lines.length > 0) {
525
- const extra = freeSpace / lines.length;
526
- for (let i = 0; i < lineCrossSizes.length; i++) {
527
- lineCrossSizes[i] += extra;
528
- }
529
- }
530
- break;
531
- // 'start' — no adjustment
532
- }
533
- }
534
- // Layout each line
535
- let crossOffset = (isRow ? pt : pl) + acOffset;
536
- for (let i = 0; i < lines.length; i++) {
537
- const line = lines[i];
538
- const lineCross = lineCrossSizes[i];
539
- const mainStart = isRow ? pl : pt;
540
- // Offset items by padding
541
- const tempItems = line.map((item) => ({ ...item }));
542
- // Cross size for alignment: use container cross size for single-line, line cross for multi-line
543
- const effectiveCross = lines.length === 1 && crossLimit < Infinity ? crossLimit : lineCross;
544
- layoutLine(tempItems, isRow, effectiveMainSize, mainLimit < Infinity ? justifyContent : 'start', alignItems, gap, crossOffset, effectiveCross);
545
- // Apply main-axis padding offset
546
- for (const item of tempItems) {
547
- const origChild = line.find((l) => l.child === item.child);
548
- origChild.child.x = item.child.x + (isRow ? mainStart : 0);
549
- origChild.child.y = item.child.y + (isRow ? 0 : mainStart);
550
- }
551
- crossOffset += lineCross + gap + acExtraGap;
552
- }
553
- // Compute and store actual dimensions for measureChild() and getContentSize()
554
- let totalCrossNatural = 0;
555
- for (let i = 0; i < lineCrossSizes.length; i++) {
556
- totalCrossNatural += lineCrossSizes[i];
557
- if (i < lineCrossSizes.length - 1)
558
- totalCrossNatural += gap;
559
- }
560
- if (isRow) {
561
- this._computedWidth = this._explicitWidth > 0 ? this._explicitWidth : (pl + naturalMainSize + pr);
562
- this._computedHeight = this._explicitHeight > 0 ? this._explicitHeight : (pt + totalCrossNatural + pb);
563
- }
564
- else {
565
- this._computedWidth = this._explicitWidth > 0 ? this._explicitWidth : (pl + totalCrossNatural + pr);
566
- this._computedHeight = this._explicitHeight > 0 ? this._explicitHeight : (pt + naturalMainSize + pb);
567
- }
568
- // Position flexExclude children (absolute positioning).
569
- // All position props describe the visual (bounds) rectangle. We derive the
570
- // visual rectangle directly from `getLocalBounds()` rather than the
571
- // layout-config `w`/`h` returned by measureChild — those may differ from
572
- // actual bounds when the user pins `layoutWidth`/`layoutHeight` to a value
573
- // that doesn't match the child's real visual extent (e.g. a Button whose
574
- // text overflows its configured `width`). Mixing layout size with real
575
- // bounds-origin would shift the visual center off the requested point.
576
- // `centerX/centerY` take precedence over `left/right` / `top/bottom` on each axis.
577
- for (const child of this._layoutChildren) {
578
- if (!child._flexConfig?.flexExclude)
579
- continue;
580
- const cfg = child._flexConfig;
581
- const bounds = child.getLocalBounds();
582
- const cw = this._computedWidth;
583
- const ch = this._computedHeight;
584
- const centerX = resolveDimension(cfg.centerX, pctRefW);
585
- if (centerX !== undefined)
586
- child.x = centerX - bounds.x - bounds.width / 2;
587
- else if (cfg.left !== undefined)
588
- child.x = cfg.left - bounds.x;
589
- else if (cfg.right !== undefined)
590
- child.x = cw - cfg.right - bounds.x - bounds.width;
591
- const centerY = resolveDimension(cfg.centerY, pctRefH);
592
- if (centerY !== undefined)
593
- child.y = centerY - bounds.y - bounds.height / 2;
594
- else if (cfg.top !== undefined)
595
- child.y = cfg.top - bounds.y;
596
- else if (cfg.bottom !== undefined)
597
- child.y = ch - cfg.bottom - bounds.y - bounds.height;
598
- }
599
- }
600
- /** Computed content size (after layout) */
601
- getContentSize() {
602
- if (this._layoutDirty)
603
- this.updateLayout();
604
- return { width: this._computedWidth, height: this._computedHeight };
605
- }
606
- /** React reconciler update hook — applies changed config props */
607
- updateConfig(changed) {
608
- if ('direction' in changed)
609
- this.setDirection(changed.direction);
610
- if ('justifyContent' in changed)
611
- this.setJustifyContent(changed.justifyContent);
612
- if ('alignItems' in changed)
613
- this.setAlignItems(changed.alignItems);
614
- if ('gap' in changed)
615
- this.setGap(changed.gap);
616
- if ('padding' in changed || 'paddingTop' in changed || 'paddingRight' in changed || 'paddingBottom' in changed || 'paddingLeft' in changed) {
617
- this._padding = resolvePadding(changed);
618
- this._layoutDirty = true;
619
- }
620
- if ('flexWrap' in changed) {
621
- this._config.flexWrap = changed.flexWrap;
622
- this._layoutDirty = true;
623
- }
624
- if ('alignContent' in changed) {
625
- this._config.alignContent = changed.alignContent;
626
- this._layoutDirty = true;
627
- }
628
- if ('width' in changed || 'height' in changed) {
629
- const w = changed.width ?? this._rawWidth;
630
- const h = changed.height ?? this._rawHeight;
631
- this._rawWidth = w;
632
- this._rawHeight = h;
633
- if (typeof w === 'number' && typeof h === 'number') {
634
- this.resize(w, h);
635
- }
636
- else {
637
- // Percentage — will resolve in updateLayout
638
- this._explicitWidth = typeof w === 'number' ? w : 0;
639
- this._explicitHeight = typeof h === 'number' ? h : 0;
640
- this._layoutDirty = true;
641
- if (!this._layoutSuspended)
642
- this.updateLayout();
643
- }
644
- return;
645
- }
646
- if (this._layoutDirty && !this._layoutSuspended)
647
- this.updateLayout();
648
- }
649
- destroy(options) {
650
- this._layoutChildren.length = 0;
651
- super.destroy(options);
652
- }
653
- }
654
-
655
- /**
656
- * Collection of easing functions for use with Tween and Timeline.
657
- *
658
- * All functions take a progress value t (0..1) and return the eased value.
659
- */
660
- const Easing = {
661
- easeOutQuad: (t) => t * (2 - t),
662
- easeInCubic: (t) => t * t * t,
663
- easeOutCubic: (t) => --t * t * t + 1,
664
- easeOutBack: (t) => {
665
- const c1 = 1.70158;
666
- const c3 = c1 + 1;
667
- return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2);
668
- }};
669
-
670
- /**
671
- * Lightweight tween system integrated with PixiJS Ticker.
672
- * Zero external dependencies — no GSAP required.
673
- *
674
- * All tweens return a Promise that resolves on completion.
675
- *
676
- * @example
677
- * ```ts
678
- * // Fade in a sprite
679
- * await Tween.to(sprite, { alpha: 1, y: 100 }, 500, Easing.easeOutBack);
680
- *
681
- * // Move and wait
682
- * await Tween.to(sprite, { x: 500 }, 300);
683
- *
684
- * // From a starting value
685
- * await Tween.from(sprite, { scale: 0, alpha: 0 }, 400);
686
- * ```
687
- */
688
- class Tween {
689
- static _tweens = [];
690
- static _tickerAdded = false;
691
- /**
692
- * Animate properties from current values to target values.
693
- *
694
- * @param target - Object to animate (Sprite, Container, etc.)
695
- * @param props - Target property values
696
- * @param duration - Duration in milliseconds
697
- * @param easing - Easing function (default: easeOutQuad)
698
- * @param onUpdate - Progress callback (0..1)
699
- */
700
- static to(target, props, duration, easing, onUpdate) {
701
- // A destroyed (Pixi) target has null transform fields — skip rather than throw. This guards
702
- // animations whose target is torn down mid-flight (e.g. a reel grid rebuilt during a spin).
703
- if (target == null || target.destroyed)
704
- return Promise.resolve();
705
- return new Promise((resolve) => {
706
- // Capture starting values
707
- const from = {};
708
- for (const key of Object.keys(props)) {
709
- from[key] = Tween.getProperty(target, key);
710
- }
711
- const tween = {
712
- target,
713
- from,
714
- to: { ...props },
715
- duration: Math.max(1, duration),
716
- easing: easing ?? Easing.easeOutQuad,
717
- elapsed: 0,
718
- delay: 0,
719
- resolve,
720
- onUpdate,
721
- };
722
- Tween._tweens.push(tween);
723
- Tween.ensureTicker();
724
- });
725
- }
726
- /**
727
- * Animate properties from given values to current values.
728
- */
729
- static from(target, props, duration, easing, onUpdate) {
730
- if (target == null || target.destroyed)
731
- return Promise.resolve();
732
- // Capture current values as "to"
733
- const to = {};
734
- for (const key of Object.keys(props)) {
735
- to[key] = Tween.getProperty(target, key);
736
- Tween.setProperty(target, key, props[key]);
737
- }
738
- return Tween.to(target, to, duration, easing, onUpdate);
739
- }
740
- /**
741
- * Animate from one set of values to another.
742
- */
743
- static fromTo(target, fromProps, toProps, duration, easing, onUpdate) {
744
- if (target == null || target.destroyed)
745
- return Promise.resolve();
746
- // Set starting values
747
- for (const key of Object.keys(fromProps)) {
748
- Tween.setProperty(target, key, fromProps[key]);
749
- }
750
- return Tween.to(target, toProps, duration, easing, onUpdate);
751
- }
752
- /**
753
- * Wait for a given duration (useful in timelines).
754
- * Uses PixiJS Ticker for consistent timing with other tweens.
755
- */
756
- static delay(ms) {
757
- return new Promise((resolve) => {
758
- let elapsed = 0;
759
- const onTick = (ticker) => {
760
- elapsed += ticker.deltaMS;
761
- if (elapsed >= ms) {
762
- pixi_js.Ticker.shared.remove(onTick);
763
- resolve();
764
- }
765
- };
766
- pixi_js.Ticker.shared.add(onTick);
767
- });
768
- }
769
- /**
770
- * Kill all tweens on a target.
771
- */
772
- static killTweensOf(target) {
773
- Tween._tweens = Tween._tweens.filter((tw) => {
774
- if (tw.target === target) {
775
- tw.resolve();
776
- return false;
777
- }
778
- return true;
779
- });
780
- }
781
- /**
782
- * Kill all active tweens.
783
- */
784
- static killAll() {
785
- for (const tw of Tween._tweens) {
786
- tw.resolve();
787
- }
788
- Tween._tweens.length = 0;
789
- }
790
- /** Number of active tweens */
791
- static get activeTweens() {
792
- return Tween._tweens.length;
793
- }
794
- /**
795
- * Reset the tween system — kill all tweens and remove the ticker.
796
- * Useful for cleanup between game instances, tests, or hot-reload.
797
- */
798
- static reset() {
799
- for (const tw of Tween._tweens) {
800
- tw.resolve();
801
- }
802
- Tween._tweens.length = 0;
803
- if (Tween._tickerAdded) {
804
- pixi_js.Ticker.shared.remove(Tween.tick);
805
- Tween._tickerAdded = false;
806
- }
807
- }
808
- // ─── Internal ──────────────────────────────────────────
809
- static ensureTicker() {
810
- if (Tween._tickerAdded)
811
- return;
812
- Tween._tickerAdded = true;
813
- pixi_js.Ticker.shared.add(Tween.tick);
814
- }
815
- static tick = (ticker) => {
816
- const dt = ticker.deltaMS;
817
- const completed = [];
818
- for (const tw of Tween._tweens) {
819
- // target torn down mid-tween → finish it quietly
820
- if (tw.target?.destroyed) {
821
- completed.push(tw);
822
- continue;
823
- }
824
- tw.elapsed += dt;
825
- if (tw.elapsed < tw.delay)
826
- continue;
827
- const raw = Math.min((tw.elapsed - tw.delay) / tw.duration, 1);
828
- const t = tw.easing(raw);
829
- // Interpolate each property
830
- for (const key of Object.keys(tw.to)) {
831
- const start = tw.from[key];
832
- const end = tw.to[key];
833
- const value = start + (end - start) * t;
834
- Tween.setProperty(tw.target, key, value);
835
- }
836
- tw.onUpdate?.(raw);
837
- if (raw >= 1) {
838
- completed.push(tw);
839
- }
840
- }
841
- // Remove completed tweens
842
- for (const tw of completed) {
843
- const idx = Tween._tweens.indexOf(tw);
844
- if (idx !== -1)
845
- Tween._tweens.splice(idx, 1);
846
- tw.resolve();
847
- }
848
- // Remove ticker when no active tweens
849
- if (Tween._tweens.length === 0 && Tween._tickerAdded) {
850
- pixi_js.Ticker.shared.remove(Tween.tick);
851
- Tween._tickerAdded = false;
852
- }
853
- };
854
- /**
855
- * Get a potentially nested property (supports 'scale.x', 'position.y', etc.)
856
- */
857
- static getProperty(target, key) {
858
- const parts = key.split('.');
859
- let obj = target;
860
- for (let i = 0; i < parts.length - 1; i++) {
861
- obj = obj?.[parts[i]];
862
- }
863
- return obj?.[parts[parts.length - 1]] ?? 0;
864
- }
865
- /**
866
- * Set a potentially nested property.
867
- */
868
- static setProperty(target, key, value) {
869
- const parts = key.split('.');
870
- let obj = target;
871
- for (let i = 0; i < parts.length - 1; i++) {
872
- obj = obj?.[parts[i]];
873
- }
874
- if (obj == null)
875
- return;
876
- obj[parts[parts.length - 1]] = value;
877
- }
878
- }
879
-
880
- const DEFAULT_COLORS = {
881
- default: 0xffd700,
882
- hover: 0xffe44d,
883
- pressed: 0xccac00,
884
- disabled: 0x666666,
885
- };
886
- function makeGraphicsView(w, h, radius, color) {
887
- const g = new pixi_js.Graphics();
888
- g.roundRect(-w / 2, -h / 2, w, h, radius).fill(color);
889
- return g;
890
- }
891
- /**
892
- * Interactive button with per-state custom views and animations.
893
- *
894
- * Each visual state accepts a `ViewInput`: texture name, Texture, or any Container
895
- * (Sprite, NineSliceSprite, AnimatedSprite, custom artwork, etc).
896
- * Falls back to colored Graphics when no custom view is provided.
897
- *
898
- * @example
899
- * ```ts
900
- * // Graphics-based (quick prototyping)
901
- * const btn = new Button({
902
- * width: 200, height: 60, borderRadius: 12,
903
- * colors: { default: 0x22aa22, hover: 0x33cc33 },
904
- * text: 'SPIN',
905
- * onPress: () => spin(),
906
- * });
907
- *
908
- * // Asset-based (production art)
909
- * const btn = new Button({
910
- * defaultView: 'btn-idle',
911
- * hoverView: 'btn-hover',
912
- * pressedView: 'btn-pressed',
913
- * disabledView: 'btn-disabled',
914
- * text: 'SPIN',
915
- * onPress: () => spin(),
916
- * });
917
- *
918
- * // Custom Container view
919
- * const btn = new Button({
920
- * defaultView: myAnimatedSprite,
921
- * text: 'SPIN',
922
- * });
923
- * ```
924
- */
925
- class Button extends pixi_js.Container {
926
- __uiComponent = true;
927
- _views = new Map();
928
- _state = 'default';
929
- _enabled = true;
930
- _config;
931
- _textObj = null;
932
- /** Press callback */
933
- onPress;
934
- constructor(config = {}) {
935
- super();
936
- this._config = {
937
- width: config.width ?? 200,
938
- height: config.height ?? 60,
939
- borderRadius: config.borderRadius ?? 8,
940
- pressScale: config.pressScale ?? 0.95,
941
- animationDuration: config.animationDuration ?? 100,
942
- ...config,
943
- };
944
- this.onPress = config.onPress;
945
- this._buildViews(config);
946
- // Text
947
- if (config.text) {
948
- this._textObj = new pixi_js.Text({
949
- text: config.text,
950
- style: {
951
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
952
- fontSize: 20,
953
- fill: 0xffffff,
954
- fontWeight: 'bold',
955
- ...config.textStyle,
956
- },
957
- });
958
- this._textObj.anchor.set(0.5);
959
- this.addChild(this._textObj);
960
- }
961
- // Interaction
962
- this.eventMode = 'static';
963
- this.cursor = 'pointer';
964
- this.on('pointerover', this._onPointerOver, this);
965
- this.on('pointerout', this._onPointerOut, this);
966
- this.on('pointerdown', this._onPointerDown, this);
967
- this.on('pointerup', this._onPointerUp, this);
968
- this.on('pointerupoutside', this._onPointerUpOutside, this);
969
- if (config.disabled) {
970
- this.enabled = false;
971
- }
972
- }
973
- /** Current button state */
974
- get state() {
975
- return this._state;
976
- }
977
- /** Enable the button */
978
- enable() {
979
- this.enabled = true;
980
- }
981
- /** Disable the button */
982
- disable() {
983
- this.enabled = false;
984
- }
985
- /** Whether the button is enabled */
986
- get enabled() {
987
- return this._enabled;
988
- }
989
- set enabled(value) {
990
- this._enabled = value;
991
- this.cursor = value ? 'pointer' : 'default';
992
- this.eventMode = value ? 'static' : 'none';
993
- this._setState(value ? 'default' : 'disabled');
994
- }
995
- /** Whether the button is disabled */
996
- get disabled() {
997
- return !this._enabled;
998
- }
999
- /** Update button text */
1000
- set text(value) {
1001
- if (this._textObj) {
1002
- this._textObj.text = value;
1003
- }
1004
- }
1005
- // ─── View building ──────────────────────────────────
1006
- _buildViews(config) {
1007
- const colorMap = { ...DEFAULT_COLORS, ...config.colors };
1008
- const { width, height, borderRadius } = this._config;
1009
- const stateViews = {
1010
- default: config.defaultView,
1011
- hover: config.hoverView,
1012
- pressed: config.pressedView,
1013
- disabled: config.disabledView,
1014
- };
1015
- const states = ['default', 'hover', 'pressed', 'disabled'];
1016
- for (const state of states) {
1017
- const customView = resolveView(stateViews[state]);
1018
- const view = customView ?? makeGraphicsView(width, height, borderRadius, colorMap[state]);
1019
- view.visible = state === 'default';
1020
- this._views.set(state, view);
1021
- this.addChild(view);
1022
- }
1023
- }
1024
- _rebuildViews() {
1025
- for (const [, view] of this._views) {
1026
- this.removeChild(view);
1027
- view.destroy();
1028
- }
1029
- this._views.clear();
1030
- this._buildViews(this._config);
1031
- // Re-insert views before text
1032
- if (this._textObj && this._textObj.parent === this) {
1033
- this.setChildIndex(this._textObj, this.children.length - 1);
1034
- }
1035
- }
1036
- // ─── State management ───────────────────────────────
1037
- _setState(state) {
1038
- if (this._state === state)
1039
- return;
1040
- this._state = state;
1041
- for (const [s, view] of this._views) {
1042
- view.visible = s === state;
1043
- }
1044
- }
1045
- _onPointerOver() {
1046
- if (!this._enabled)
1047
- return;
1048
- this._setState('hover');
1049
- Tween.killTweensOf(this);
1050
- Tween.to(this, { 'scale.x': 1.03, 'scale.y': 1.03 }, this._config.animationDuration, Easing.easeOutQuad);
1051
- }
1052
- _onPointerOut() {
1053
- if (!this._enabled)
1054
- return;
1055
- this._setState('default');
1056
- Tween.killTweensOf(this);
1057
- Tween.to(this, { 'scale.x': 1, 'scale.y': 1 }, this._config.animationDuration, Easing.easeOutQuad);
1058
- }
1059
- _onPointerDown() {
1060
- if (!this._enabled)
1061
- return;
1062
- this._setState('pressed');
1063
- Tween.killTweensOf(this);
1064
- const s = this._config.pressScale;
1065
- Tween.to(this, { 'scale.x': s, 'scale.y': s }, this._config.animationDuration, Easing.easeOutQuad);
1066
- }
1067
- _onPointerUp() {
1068
- if (!this._enabled)
1069
- return;
1070
- this._setState('hover');
1071
- Tween.killTweensOf(this);
1072
- Tween.to(this, { 'scale.x': 1.03, 'scale.y': 1.03 }, this._config.animationDuration, Easing.easeOutQuad);
1073
- this.onPress?.();
1074
- }
1075
- _onPointerUpOutside() {
1076
- if (!this._enabled)
1077
- return;
1078
- this._setState('default');
1079
- Tween.killTweensOf(this);
1080
- Tween.to(this, { 'scale.x': 1, 'scale.y': 1 }, this._config.animationDuration, Easing.easeOutQuad);
1081
- }
1082
- /** React reconciler update hook */
1083
- updateConfig(changed) {
1084
- if ('text' in changed && this._textObj)
1085
- this._textObj.text = changed.text;
1086
- if ('disabled' in changed)
1087
- this.enabled = !changed.disabled;
1088
- if ('onPress' in changed)
1089
- this.onPress = changed.onPress;
1090
- const structural = [
1091
- 'colors', 'width', 'height', 'borderRadius', 'textStyle',
1092
- 'defaultView', 'hoverView', 'pressedView', 'disabledView',
1093
- ];
1094
- const needsRebuild = structural.some((k) => k in changed);
1095
- if (needsRebuild) {
1096
- Object.assign(this._config, changed);
1097
- this._rebuildViews();
1098
- }
1099
- }
1100
- destroy(options) {
1101
- Tween.killTweensOf(this);
1102
- this.off('pointerover', this._onPointerOver, this);
1103
- this.off('pointerout', this._onPointerOut, this);
1104
- this.off('pointerdown', this._onPointerDown, this);
1105
- this.off('pointerup', this._onPointerUp, this);
1106
- this.off('pointerupoutside', this._onPointerUpOutside, this);
1107
- this._views.clear();
1108
- this._textObj = null;
1109
- super.destroy(options);
1110
- }
1111
- }
1112
-
1113
- /**
1114
- * Horizontal progress bar with optional custom track/fill views.
1115
- *
1116
- * Supports asset-based skinning: provide `trackView` and/or `fillView`
1117
- * as texture names, Textures, or any Container (NineSliceSprite, custom artwork, etc).
1118
- * Falls back to colored Graphics when no custom views are provided.
1119
- *
1120
- * @example
1121
- * ```ts
1122
- * // Graphics-based (quick prototyping)
1123
- * const bar = new ProgressBar({ width: 300, height: 20, fillColor: 0x22cc22 });
1124
- * bar.progress = 0.5;
1125
- *
1126
- * // Asset-based (production art)
1127
- * const bar = new ProgressBar({
1128
- * width: 300, height: 20,
1129
- * trackView: 'bar-track',
1130
- * fillView: new NineSliceSprite({ texture: 'bar-fill', ... }),
1131
- * });
1132
- * bar.progress = 0.75;
1133
- * ```
1134
- */
1135
- class ProgressBar extends pixi_js.Container {
1136
- __uiComponent = true;
1137
- _track;
1138
- _fill;
1139
- _fillMask;
1140
- _borderGfx;
1141
- _config;
1142
- _progress = 0;
1143
- _displayedProgress = 0;
1144
- constructor(config = {}) {
1145
- super();
1146
- this._config = {
1147
- width: config.width ?? 300,
1148
- height: config.height ?? 16,
1149
- borderRadius: config.borderRadius ?? 8,
1150
- fillColor: config.fillColor ?? 0xffd700,
1151
- trackColor: config.trackColor ?? 0x333333,
1152
- borderColor: config.borderColor ?? 0x555555,
1153
- borderWidth: config.borderWidth ?? 1,
1154
- animated: config.animated ?? true,
1155
- animationSpeed: config.animationSpeed ?? 0.1,
1156
- };
1157
- const { width, height, borderRadius, fillColor, trackColor, borderColor, borderWidth } = this._config;
1158
- // Track background — custom view or Graphics
1159
- const customTrack = resolveView(config.trackView);
1160
- if (customTrack) {
1161
- customTrack.width = width;
1162
- customTrack.height = height;
1163
- this._track = customTrack;
1164
- }
1165
- else {
1166
- const g = new pixi_js.Graphics();
1167
- g.roundRect(0, 0, width, height, borderRadius).fill(trackColor);
1168
- this._track = g;
1169
- }
1170
- this.addChild(this._track);
1171
- // Fill bar — custom view or Graphics
1172
- const customFill = resolveView(config.fillView);
1173
- if (customFill) {
1174
- customFill.x = borderWidth;
1175
- customFill.y = borderWidth;
1176
- customFill.width = width - borderWidth * 2;
1177
- customFill.height = height - borderWidth * 2;
1178
- this._fill = customFill;
1179
- }
1180
- else {
1181
- const g = new pixi_js.Graphics();
1182
- g.roundRect(borderWidth, borderWidth, width - borderWidth * 2, height - borderWidth * 2, Math.max(0, borderRadius - 1)).fill(fillColor);
1183
- this._fill = g;
1184
- }
1185
- this.addChild(this._fill);
1186
- // Mask for the fill (controls visible width)
1187
- this._fillMask = new pixi_js.Graphics();
1188
- this._fillMask.rect(0, 0, 0, height).fill(0xffffff);
1189
- this.addChild(this._fillMask);
1190
- this._fill.mask = this._fillMask;
1191
- // Border overlay
1192
- this._borderGfx = new pixi_js.Graphics();
1193
- if (borderColor !== undefined && borderWidth > 0) {
1194
- this._borderGfx
1195
- .roundRect(0, 0, width, height, borderRadius)
1196
- .stroke({ color: borderColor, width: borderWidth });
1197
- }
1198
- this.addChild(this._borderGfx);
1199
- }
1200
- /** Get/set progress (0..1) */
1201
- get progress() {
1202
- return this._progress;
1203
- }
1204
- set progress(value) {
1205
- this._progress = Math.max(0, Math.min(1, value));
1206
- if (!this._config.animated) {
1207
- this._displayedProgress = this._progress;
1208
- this.updateMask();
1209
- }
1210
- }
1211
- /**
1212
- * Call each frame if animated is true.
1213
- */
1214
- update(_dt) {
1215
- if (!this._config.animated)
1216
- return;
1217
- if (Math.abs(this._displayedProgress - this._progress) < 0.001) {
1218
- this._displayedProgress = this._progress;
1219
- this.updateMask();
1220
- return;
1221
- }
1222
- this._displayedProgress +=
1223
- (this._progress - this._displayedProgress) * this._config.animationSpeed;
1224
- this.updateMask();
1225
- }
1226
- /** React reconciler update hook */
1227
- updateConfig(changed) {
1228
- if ('progress' in changed)
1229
- this.progress = changed.progress;
1230
- if ('animated' in changed)
1231
- this._config.animated = changed.animated;
1232
- if ('animationSpeed' in changed)
1233
- this._config.animationSpeed = changed.animationSpeed;
1234
- }
1235
- updateMask() {
1236
- const w = this._config.width * this._displayedProgress;
1237
- this._fillMask.clear();
1238
- this._fillMask.rect(0, 0, w, this._config.height).fill(0xffffff);
1239
- }
1240
- }
1241
-
1242
- /**
1243
- * Enhanced text label with auto-fit scaling and currency formatting.
1244
- *
1245
- * @example
1246
- * ```ts
1247
- * const label = new Label({
1248
- * text: 'BALANCE',
1249
- * style: { fontSize: 24, fill: 0xffd700 },
1250
- * maxWidth: 200,
1251
- * autoFit: true,
1252
- * });
1253
- * ```
1254
- */
1255
- class Label extends pixi_js.Container {
1256
- __uiComponent = true;
1257
- _text;
1258
- _maxWidth;
1259
- _autoFit;
1260
- constructor(config = {}) {
1261
- super();
1262
- this._maxWidth = config.maxWidth ?? Infinity;
1263
- this._autoFit = config.autoFit ?? false;
1264
- this._text = new pixi_js.Text({
1265
- text: config.text ?? '',
1266
- style: {
1267
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
1268
- fontSize: 24,
1269
- fill: 0xffffff,
1270
- ...config.style,
1271
- },
1272
- });
1273
- this._text.anchor.set(0.5);
1274
- this.addChild(this._text);
1275
- this.fitText();
1276
- }
1277
- /** Get/set the displayed text */
1278
- get text() {
1279
- return this._text.text;
1280
- }
1281
- set text(value) {
1282
- this._text.text = value;
1283
- this.fitText();
1284
- }
1285
- /** Get/set the text style */
1286
- get style() {
1287
- return this._text.style;
1288
- }
1289
- /** Set max width constraint */
1290
- set maxWidth(value) {
1291
- this._maxWidth = value;
1292
- this.fitText();
1293
- }
1294
- /**
1295
- * Format and display a number as currency.
1296
- *
1297
- * @param amount - The numeric amount
1298
- * @param currency - Currency code (e.g., 'USD', 'EUR')
1299
- * @param locale - Locale string (default: 'en-US')
1300
- */
1301
- setCurrency(amount, currency, locale = 'en-US') {
1302
- try {
1303
- this.text = new Intl.NumberFormat(locale, {
1304
- style: 'currency',
1305
- currency,
1306
- minimumFractionDigits: 2,
1307
- maximumFractionDigits: 2,
1308
- }).format(amount);
1309
- }
1310
- catch {
1311
- this.text = `${amount.toFixed(2)} ${currency}`;
1312
- }
1313
- }
1314
- /**
1315
- * Format a number with thousands separators.
1316
- */
1317
- setNumber(value, decimals = 0, locale = 'en-US') {
1318
- this.text = new Intl.NumberFormat(locale, {
1319
- minimumFractionDigits: decimals,
1320
- maximumFractionDigits: decimals,
1321
- }).format(value);
1322
- }
1323
- /** React reconciler update hook */
1324
- updateConfig(changed) {
1325
- if ('text' in changed)
1326
- this.text = changed.text;
1327
- if ('maxWidth' in changed)
1328
- this.maxWidth = changed.maxWidth;
1329
- if ('autoFit' in changed) {
1330
- this._autoFit = changed.autoFit;
1331
- this.fitText();
1332
- }
1333
- if ('style' in changed && typeof changed.style === 'object') {
1334
- Object.assign(this._text.style, changed.style);
1335
- this.fitText();
1336
- }
1337
- }
1338
- fitText() {
1339
- if (!this._autoFit || this._maxWidth === Infinity)
1340
- return;
1341
- this._text.scale.set(1);
1342
- if (this._text.width > this._maxWidth) {
1343
- const scale = this._maxWidth / this._text.width;
1344
- this._text.scale.set(scale);
1345
- }
1346
- }
1347
- }
1348
-
1349
- /**
1350
- * Two-row text cell with a muted caption above and a prominent value below —
1351
- * the archetypal casino UI pattern (BALANCE/€500, BET/€1, WIN/€0.00).
1352
- *
1353
- * Extends FlexContainer, so it participates in parent flex layouts directly
1354
- * (you can pass `flexGrow`, `alignSelf`, etc. when it's a child of another
1355
- * FlexContainer) and auto-sizes to its contents when no explicit size is set.
1356
- *
1357
- * @example
1358
- * ```tsx
1359
- * <labelValue
1360
- * label="BALANCE"
1361
- * value={`€${balance.toFixed(2)}`}
1362
- * labelStyle={{ fontSize: 12, fill: 0x888888 }}
1363
- * valueStyle={{ fontSize: 22, fill: 0xffffff, fontWeight: 'bold' }}
1364
- * gap={6}
1365
- * align="center"
1366
- * />
1367
- * ```
1368
- */
1369
- class LabelValue extends FlexContainer {
1370
- _labelEl;
1371
- _valueEl;
1372
- _valueMaxWidth;
1373
- constructor(config = {}) {
1374
- super({
1375
- direction: 'column',
1376
- alignItems: toAlignItems(config.align ?? 'center'),
1377
- gap: config.gap ?? 4,
1378
- padding: config.padding,
1379
- });
1380
- this._valueMaxWidth = config.maxWidth ?? Infinity;
1381
- this._labelEl = new Label({
1382
- text: config.label ?? '',
1383
- style: config.labelStyle,
1384
- });
1385
- this._valueEl = new Label({
1386
- text: config.value ?? '',
1387
- style: config.valueStyle,
1388
- maxWidth: config.maxWidth,
1389
- autoFit: config.maxWidth !== undefined,
1390
- });
1391
- this.addFlexChild(this._labelEl);
1392
- this.addFlexChild(this._valueEl);
1393
- }
1394
- /** Get the caption Label (for advanced styling / animation) */
1395
- get labelElement() {
1396
- return this._labelEl;
1397
- }
1398
- /** Get the value Label */
1399
- get valueElement() {
1400
- return this._valueEl;
1401
- }
1402
- /** Update caption text */
1403
- setLabel(text) {
1404
- this._labelEl.text = text;
1405
- this.updateLayout();
1406
- }
1407
- /** Update value text */
1408
- setValue(text) {
1409
- this._valueEl.text = text;
1410
- this.updateLayout();
1411
- }
1412
- /** React reconciler update hook */
1413
- updateConfig(changed) {
1414
- if ('label' in changed)
1415
- this._labelEl.text = changed.label ?? '';
1416
- if ('value' in changed)
1417
- this._valueEl.text = changed.value ?? '';
1418
- if ('labelStyle' in changed && typeof changed.labelStyle === 'object') {
1419
- Object.assign(this._labelEl.style, changed.labelStyle);
1420
- }
1421
- if ('valueStyle' in changed && typeof changed.valueStyle === 'object') {
1422
- Object.assign(this._valueEl.style, changed.valueStyle);
1423
- }
1424
- if ('maxWidth' in changed) {
1425
- this._valueMaxWidth = changed.maxWidth ?? Infinity;
1426
- this._valueEl.maxWidth = this._valueMaxWidth;
1427
- }
1428
- if ('gap' in changed)
1429
- this.setGap(changed.gap);
1430
- if ('align' in changed)
1431
- this.setAlignItems(toAlignItems(changed.align));
1432
- // Forward remaining FlexContainer props (e.g. padding, width, height)
1433
- super.updateConfig(changed);
1434
- }
1435
- }
1436
- function toAlignItems(align) {
1437
- return align;
1438
- }
1439
-
1440
- /**
1441
- * Background panel with optional flexbox content layout.
1442
- *
1443
- * Supports both Graphics-based (color + border) and 9-slice sprite backgrounds.
1444
- * Children added via `addContent()` participate in flex layout automatically.
1445
- *
1446
- * @example
1447
- * ```ts
1448
- * // Simple colored panel
1449
- * const panel = new Panel({ width: 400, height: 300, backgroundColor: 0x222222, borderRadius: 12 });
1450
- *
1451
- * // 9-slice panel (texture-based)
1452
- * const panel = new Panel({
1453
- * nineSliceTexture: 'panel-bg',
1454
- * nineSliceBorders: [20, 20, 20, 20],
1455
- * width: 400, height: 300,
1456
- * });
1457
- * ```
1458
- */
1459
- class Panel extends pixi_js.Container {
1460
- __uiComponent = true;
1461
- _bg;
1462
- _content;
1463
- _internalSetup = true;
1464
- _panelConfig;
1465
- constructor(config = {}) {
1466
- super();
1467
- const resolvedConfig = {
1468
- width: config.width ?? 400,
1469
- height: config.height ?? 300,
1470
- padding: config.padding ?? 16,
1471
- backgroundAlpha: config.backgroundAlpha ?? 1,
1472
- ...config,
1473
- };
1474
- this._panelConfig = resolvedConfig;
1475
- // Create background
1476
- if (config.nineSliceTexture) {
1477
- const texture = typeof config.nineSliceTexture === 'string'
1478
- ? pixi_js.Texture.from(config.nineSliceTexture)
1479
- : config.nineSliceTexture;
1480
- const [left, top, right, bottom] = config.nineSliceBorders ?? [10, 10, 10, 10];
1481
- const nineSlice = new pixi_js.NineSliceSprite({
1482
- texture,
1483
- leftWidth: left,
1484
- topHeight: top,
1485
- rightWidth: right,
1486
- bottomHeight: bottom,
1487
- });
1488
- nineSlice.width = resolvedConfig.width;
1489
- nineSlice.height = resolvedConfig.height;
1490
- nineSlice.alpha = resolvedConfig.backgroundAlpha;
1491
- this._bg = nineSlice;
1492
- }
1493
- else {
1494
- const g = new pixi_js.Graphics();
1495
- const bgColor = config.backgroundColor ?? 0x1a1a2e;
1496
- const radius = config.borderRadius ?? 0;
1497
- g.roundRect(0, 0, resolvedConfig.width, resolvedConfig.height, radius).fill(bgColor);
1498
- if (config.borderColor !== undefined && config.borderWidth) {
1499
- g.roundRect(0, 0, resolvedConfig.width, resolvedConfig.height, radius)
1500
- .stroke({ color: config.borderColor, width: config.borderWidth });
1501
- }
1502
- g.alpha = resolvedConfig.backgroundAlpha;
1503
- this._bg = g;
1504
- }
1505
- this.addChild(this._bg);
1506
- // Create content flex container
1507
- this._content = new FlexContainer({
1508
- ...config.layout,
1509
- direction: config.layout?.direction ?? 'column',
1510
- justifyContent: config.layout?.justifyContent ?? 'start',
1511
- alignItems: config.layout?.alignItems ?? 'start',
1512
- gap: config.layout?.gap ?? 0,
1513
- padding: resolvedConfig.padding,
1514
- width: resolvedConfig.width,
1515
- height: resolvedConfig.height,
1516
- });
1517
- this.addChild(this._content);
1518
- this._internalSetup = false;
1519
- }
1520
- /** Access the content flex container — add children here for layout */
1521
- get content() {
1522
- return this._content;
1523
- }
1524
- /** Suspend content layout recalculation. Call resumeLayout() to flush. */
1525
- suspendLayout() {
1526
- this._content.suspendLayout();
1527
- }
1528
- /** Resume content layout and flush if dirty. */
1529
- resumeLayout() {
1530
- this._content.resumeLayout();
1531
- }
1532
- /** Convenience: add a child to the content layout */
1533
- addContent(child) {
1534
- this._content.addFlexChild(child);
1535
- this._content.updateLayout();
1536
- return this;
1537
- }
1538
- /** Resize the panel */
1539
- setSize(width, height) {
1540
- this._panelConfig.width = width;
1541
- this._panelConfig.height = height;
1542
- // Resize background
1543
- if (this._bg instanceof pixi_js.NineSliceSprite) {
1544
- this._bg.width = width;
1545
- this._bg.height = height;
1546
- }
1547
- else if (this._bg instanceof pixi_js.Graphics) {
1548
- const radius = this._panelConfig.borderRadius ?? 0;
1549
- const bgColor = this._panelConfig.backgroundColor ?? 0x1a1a2e;
1550
- this._bg.clear();
1551
- this._bg.roundRect(0, 0, width, height, radius).fill(bgColor);
1552
- if (this._panelConfig.borderColor !== undefined && this._panelConfig.borderWidth) {
1553
- this._bg.roundRect(0, 0, width, height, radius)
1554
- .stroke({ color: this._panelConfig.borderColor, width: this._panelConfig.borderWidth });
1555
- }
1556
- this._bg.alpha = this._panelConfig.backgroundAlpha;
1557
- }
1558
- this._content.resize(width, height);
1559
- }
1560
- /**
1561
- * Override addChild so external children are routed to content FlexContainer.
1562
- * Enables `<panel><label /><button /></panel>` in React JSX.
1563
- */
1564
- addChild(...children) {
1565
- if (this._internalSetup) {
1566
- return super.addChild(...children);
1567
- }
1568
- for (const child of children) {
1569
- this._content.addFlexChild(child);
1570
- }
1571
- this._content.updateLayout();
1572
- return children[0];
1573
- }
1574
- removeChild(...children) {
1575
- if (this._internalSetup) {
1576
- return super.removeChild(...children);
1577
- }
1578
- for (const child of children) {
1579
- this._content.removeFlexChild(child);
1580
- }
1581
- return children[0];
1582
- }
1583
- /** React reconciler update hook */
1584
- updateConfig(changed) {
1585
- if ('width' in changed || 'height' in changed) {
1586
- this.setSize(changed.width ?? this._panelConfig.width, changed.height ?? this._panelConfig.height);
1587
- }
1588
- if ('backgroundAlpha' in changed) {
1589
- this._panelConfig.backgroundAlpha = changed.backgroundAlpha;
1590
- this._bg.alpha = changed.backgroundAlpha;
1591
- }
1592
- }
1593
- destroy(options) {
1594
- super.destroy(options);
1595
- }
1596
- }
1597
-
1598
- /**
1599
- * Reactive balance display component.
1600
- *
1601
- * Automatically formats currency and can animate value changes
1602
- * with a smooth countup/countdown effect using engine Tween.
1603
- *
1604
- * @example
1605
- * ```ts
1606
- * const balance = new BalanceDisplay({ currency: 'USD', animated: true });
1607
- * balance.setValue(1000);
1608
- *
1609
- * // Wire to SDK
1610
- * sdk.on('balanceUpdate', ({ balance: val }) => balance.setValue(val));
1611
- * ```
1612
- */
1613
- class BalanceDisplay extends pixi_js.Container {
1614
- __uiComponent = true;
1615
- _prefixLabel = null;
1616
- _valueLabel;
1617
- _config;
1618
- _currentValue = 0;
1619
- _displayedValue = 0;
1620
- /** Internal target for Tween animation */
1621
- _tweenTarget = { value: 0 };
1622
- constructor(config = {}) {
1623
- super();
1624
- this._config = {
1625
- currency: config.currency ?? 'USD',
1626
- locale: config.locale ?? 'en-US',
1627
- animated: config.animated ?? true,
1628
- animationDuration: config.animationDuration ?? 500,
1629
- };
1630
- // Prefix label
1631
- if (config.prefix) {
1632
- this._prefixLabel = new Label({
1633
- text: config.prefix,
1634
- style: {
1635
- fontSize: 16,
1636
- fill: 0xaaaaaa,
1637
- ...config.style,
1638
- },
1639
- });
1640
- this.addChild(this._prefixLabel);
1641
- }
1642
- // Value label
1643
- this._valueLabel = new Label({
1644
- text: '0.00',
1645
- style: {
1646
- fontSize: 28,
1647
- fontWeight: 'bold',
1648
- fill: 0xffffff,
1649
- ...config.style,
1650
- },
1651
- maxWidth: config.maxWidth,
1652
- autoFit: !!config.maxWidth,
1653
- });
1654
- this.addChild(this._valueLabel);
1655
- this.layoutLabels();
1656
- }
1657
- /** Current displayed value */
1658
- get value() {
1659
- return this._currentValue;
1660
- }
1661
- /**
1662
- * Set the balance value. If animated, smoothly counts to the new value.
1663
- */
1664
- setValue(value) {
1665
- const oldValue = this._currentValue;
1666
- this._currentValue = value;
1667
- if (this._config.animated && oldValue !== value) {
1668
- this.animateValue(oldValue, value);
1669
- }
1670
- else {
1671
- this._displayedValue = value;
1672
- this.updateDisplay();
1673
- }
1674
- }
1675
- /**
1676
- * Set the currency code.
1677
- */
1678
- setCurrency(currency) {
1679
- this._config.currency = currency;
1680
- this.updateDisplay();
1681
- }
1682
- animateValue(from, to) {
1683
- // Cancel any running animation
1684
- Tween.killTweensOf(this._tweenTarget);
1685
- this._tweenTarget.value = from;
1686
- Tween.to(this._tweenTarget, { value: to }, this._config.animationDuration, Easing.easeOutCubic, () => {
1687
- this._displayedValue = this._tweenTarget.value;
1688
- this.updateDisplay();
1689
- });
1690
- }
1691
- updateDisplay() {
1692
- this._valueLabel.setCurrency(this._displayedValue, this._config.currency, this._config.locale);
1693
- }
1694
- layoutLabels() {
1695
- if (this._prefixLabel) {
1696
- this._prefixLabel.y = -14;
1697
- this._valueLabel.y = 14;
1698
- }
1699
- }
1700
- /** React reconciler update hook */
1701
- updateConfig(changed) {
1702
- if ('value' in changed)
1703
- this.setValue(changed.value);
1704
- if ('currency' in changed)
1705
- this.setCurrency(changed.currency);
1706
- }
1707
- destroy(options) {
1708
- Tween.killTweensOf(this._tweenTarget);
1709
- super.destroy(options);
1710
- }
1711
- }
1712
-
1713
- /**
1714
- * Win amount display with countup animation.
1715
- *
1716
- * Shows a dramatic countup from 0 to the win amount, with optional
1717
- * scale pop effect — typical of slot games. Uses engine Tween system.
1718
- *
1719
- * @example
1720
- * ```ts
1721
- * const winDisplay = new WinDisplay({ currency: 'USD' });
1722
- * scene.container.addChild(winDisplay);
1723
- * await winDisplay.showWin(150.50); // countup animation
1724
- * winDisplay.hide();
1725
- * ```
1726
- */
1727
- class WinDisplay extends pixi_js.Container {
1728
- __uiComponent = true;
1729
- _label;
1730
- _config;
1731
- /** Internal target for Tween countup */
1732
- _tweenTarget = { value: 0 };
1733
- constructor(config = {}) {
1734
- super();
1735
- this._config = {
1736
- currency: config.currency ?? 'USD',
1737
- locale: config.locale ?? 'en-US',
1738
- countupDuration: config.countupDuration ?? 1500,
1739
- popScale: config.popScale ?? 1.2,
1740
- };
1741
- this._label = new Label({
1742
- text: '',
1743
- style: {
1744
- fontSize: 48,
1745
- fontWeight: 'bold',
1746
- fill: 0xffd700,
1747
- stroke: { color: 0x000000, width: 3 },
1748
- ...config.style,
1749
- },
1750
- });
1751
- this.addChild(this._label);
1752
- this.visible = false;
1753
- }
1754
- /**
1755
- * Show a win with countup animation.
1756
- *
1757
- * @param amount - Win amount
1758
- * @returns Promise that resolves when the animation completes
1759
- */
1760
- async showWin(amount) {
1761
- this.visible = true;
1762
- this.alpha = 1;
1763
- // Cancel any running animation
1764
- Tween.killTweensOf(this._tweenTarget);
1765
- Tween.killTweensOf(this);
1766
- // Setup countup
1767
- this._tweenTarget.value = 0;
1768
- this.scale.set(0.5);
1769
- // Scale pop animation
1770
- const scalePromise = Tween.to(this, { 'scale.x': 1, 'scale.y': 1 }, 300, Easing.easeOutBack);
1771
- // Countup animation
1772
- const countupPromise = Tween.to(this._tweenTarget, { value: amount }, this._config.countupDuration, Easing.easeOutCubic, () => {
1773
- this.displayAmount(this._tweenTarget.value);
1774
- });
1775
- await Promise.all([scalePromise, countupPromise]);
1776
- // Ensure final value is exact
1777
- this.displayAmount(amount);
1778
- this.scale.set(1);
1779
- }
1780
- /**
1781
- * Skip the countup animation and show the final amount immediately.
1782
- */
1783
- skipCountup(amount) {
1784
- Tween.killTweensOf(this._tweenTarget);
1785
- Tween.killTweensOf(this);
1786
- this.displayAmount(amount);
1787
- this.scale.set(1);
1788
- }
1789
- /**
1790
- * Hide the win display.
1791
- */
1792
- hide() {
1793
- Tween.killTweensOf(this._tweenTarget);
1794
- Tween.killTweensOf(this);
1795
- this.visible = false;
1796
- this._label.text = '';
1797
- }
1798
- displayAmount(amount) {
1799
- this._label.setCurrency(amount, this._config.currency, this._config.locale);
1800
- }
1801
- /** React reconciler update hook */
1802
- updateConfig(changed) {
1803
- if ('currency' in changed)
1804
- this._config.currency = changed.currency;
1805
- if ('locale' in changed)
1806
- this._config.locale = changed.locale;
1807
- }
1808
- destroy(options) {
1809
- Tween.killTweensOf(this._tweenTarget);
1810
- Tween.killTweensOf(this);
1811
- super.destroy(options);
1812
- }
1813
- }
1814
-
1815
- /**
1816
- * Modal overlay component.
1817
- * Shows content on top of a dark overlay with enter/exit animations.
1818
- *
1819
- * Content is automatically centered via position calculations.
1820
- *
1821
- * @example
1822
- * ```ts
1823
- * const modal = new Modal({ closeOnOverlay: true });
1824
- * modal.content.addChild(settingsPanel);
1825
- * modal.onClose = () => console.log('Closed');
1826
- * await modal.show(1920, 1080);
1827
- * ```
1828
- */
1829
- class Modal extends pixi_js.Container {
1830
- __uiComponent = true;
1831
- _overlay;
1832
- _contentContainer;
1833
- _config;
1834
- _showing = false;
1835
- _internalSetup = true;
1836
- /** Called when the modal is closed */
1837
- onClose;
1838
- constructor(config = {}) {
1839
- super();
1840
- this._config = {
1841
- overlayColor: config.overlayColor ?? 0x000000,
1842
- overlayAlpha: config.overlayAlpha ?? 0.7,
1843
- closeOnOverlay: config.closeOnOverlay ?? true,
1844
- animationDuration: config.animationDuration ?? 300,
1845
- };
1846
- // Overlay
1847
- this._overlay = new pixi_js.Graphics();
1848
- this._overlay.eventMode = 'static';
1849
- this._overlay.on('pointertap', () => {
1850
- if (this._config.closeOnOverlay)
1851
- this.hide();
1852
- });
1853
- this.addChild(this._overlay);
1854
- // Content container
1855
- this._contentContainer = new pixi_js.Container();
1856
- this.addChild(this._contentContainer);
1857
- this.visible = false;
1858
- this._internalSetup = false;
1859
- }
1860
- /** Content container — add your UI here */
1861
- get content() {
1862
- return this._contentContainer;
1863
- }
1864
- /**
1865
- * Override addChild so external children are routed to _contentContainer.
1866
- * Enables `<modal><flexContainer>...</flexContainer></modal>` in React JSX.
1867
- */
1868
- addChild(...children) {
1869
- if (this._internalSetup) {
1870
- return super.addChild(...children);
1871
- }
1872
- for (const child of children) {
1873
- this._contentContainer.addChild(child);
1874
- }
1875
- return children[0];
1876
- }
1877
- removeChild(...children) {
1878
- if (this._internalSetup) {
1879
- return super.removeChild(...children);
1880
- }
1881
- for (const child of children) {
1882
- this._contentContainer.removeChild(child);
1883
- }
1884
- return children[0];
1885
- }
1886
- /** Whether the modal is currently showing */
1887
- get isShowing() {
1888
- return this._showing;
1889
- }
1890
- /**
1891
- * Show the modal with animation.
1892
- */
1893
- async show(viewWidth, viewHeight) {
1894
- this._showing = true;
1895
- this.visible = true;
1896
- // Draw overlay to cover full screen
1897
- this._overlay.clear();
1898
- this._overlay.rect(0, 0, viewWidth, viewHeight).fill(this._config.overlayColor);
1899
- this._overlay.alpha = 0;
1900
- // Center content
1901
- this._contentContainer.x = viewWidth / 2;
1902
- this._contentContainer.y = viewHeight / 2;
1903
- this._contentContainer.alpha = 0;
1904
- this._contentContainer.scale.set(0.8);
1905
- // Animate in
1906
- await Promise.all([
1907
- Tween.to(this._overlay, { alpha: this._config.overlayAlpha }, this._config.animationDuration, Easing.easeOutCubic),
1908
- Tween.to(this._contentContainer, { alpha: 1, 'scale.x': 1, 'scale.y': 1 }, this._config.animationDuration, Easing.easeOutBack),
1909
- ]);
1910
- }
1911
- /**
1912
- * Hide the modal with animation.
1913
- */
1914
- async hide() {
1915
- if (!this._showing)
1916
- return;
1917
- await Promise.all([
1918
- Tween.to(this._overlay, { alpha: 0 }, this._config.animationDuration * 0.7, Easing.easeInCubic),
1919
- Tween.to(this._contentContainer, { alpha: 0, 'scale.x': 0.8, 'scale.y': 0.8 }, this._config.animationDuration * 0.7, Easing.easeInCubic),
1920
- ]);
1921
- this.visible = false;
1922
- this._showing = false;
1923
- this.onClose?.();
1924
- }
1925
- /** React reconciler update hook */
1926
- updateConfig(changed) {
1927
- if ('overlayAlpha' in changed)
1928
- this._config.overlayAlpha = changed.overlayAlpha;
1929
- if ('closeOnOverlay' in changed)
1930
- this._config.closeOnOverlay = changed.closeOnOverlay;
1931
- if ('animationDuration' in changed)
1932
- this._config.animationDuration = changed.animationDuration;
1933
- if ('onClose' in changed)
1934
- this.onClose = changed.onClose;
1935
- }
1936
- }
1937
-
1938
- const TOAST_COLORS = {
1939
- info: 0x3498db,
1940
- success: 0x27ae60,
1941
- warning: 0xf39c12,
1942
- error: 0xe74c3c,
1943
- };
1944
- /**
1945
- * Toast notification component for displaying transient messages.
1946
- *
1947
- * @example
1948
- * ```ts
1949
- * const toast = new Toast();
1950
- * scene.container.addChild(toast);
1951
- * await toast.show('Connection lost', 'error', 1920, 1080);
1952
- * ```
1953
- */
1954
- class Toast extends pixi_js.Container {
1955
- __uiComponent = true;
1956
- _bg;
1957
- _customBg;
1958
- _text;
1959
- _config;
1960
- _dismissPending = false;
1961
- constructor(config = {}) {
1962
- super();
1963
- this._config = {
1964
- duration: config.duration ?? 3000,
1965
- bottomOffset: config.bottomOffset ?? 60,
1966
- };
1967
- const customBg = resolveView(config.backgroundView);
1968
- this._customBg = !!customBg;
1969
- this._bg = customBg ?? new pixi_js.Graphics();
1970
- this.addChild(this._bg);
1971
- this._text = new pixi_js.Text({
1972
- text: '',
1973
- style: {
1974
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
1975
- fontSize: 16,
1976
- fill: 0xffffff,
1977
- },
1978
- });
1979
- this._text.anchor.set(0.5);
1980
- this.addChild(this._text);
1981
- this.visible = false;
1982
- }
1983
- /**
1984
- * Show a toast message.
1985
- */
1986
- async show(message, type = 'info', viewWidth, viewHeight) {
1987
- // Cancel any pending dismiss
1988
- Tween.killTweensOf(this);
1989
- this._dismissPending = false;
1990
- this._text.text = message;
1991
- const padding = 20;
1992
- const width = Math.max(200, this._text.width + padding * 2);
1993
- const height = 44;
1994
- const radius = 8;
1995
- // Draw the background
1996
- if (this._customBg) {
1997
- this._bg.width = width;
1998
- this._bg.height = height;
1999
- this._bg.x = -width / 2;
2000
- this._bg.y = -height / 2;
2001
- }
2002
- else {
2003
- const g = this._bg;
2004
- g.clear();
2005
- g.roundRect(-width / 2, -height / 2, width, height, radius);
2006
- g.fill(TOAST_COLORS[type]);
2007
- }
2008
- // Position
2009
- if (viewWidth && viewHeight) {
2010
- this.x = viewWidth / 2;
2011
- this.y = viewHeight - this._config.bottomOffset;
2012
- }
2013
- this.visible = true;
2014
- this.alpha = 0;
2015
- this.y += 20;
2016
- await Tween.to(this, { alpha: 1, y: this.y - 20 }, 300, Easing.easeOutCubic);
2017
- if (this._config.duration > 0) {
2018
- this._dismissPending = true;
2019
- await Tween.delay(this._config.duration);
2020
- if (this._dismissPending) {
2021
- this._dismissPending = false;
2022
- await this.dismiss();
2023
- }
2024
- }
2025
- }
2026
- /**
2027
- * Dismiss the toast.
2028
- */
2029
- async dismiss() {
2030
- if (!this.visible)
2031
- return;
2032
- this._dismissPending = false;
2033
- Tween.killTweensOf(this);
2034
- await Tween.to(this, { alpha: 0, y: this.y + 20 }, 200, Easing.easeInCubic);
2035
- this.visible = false;
2036
- }
2037
- /** React reconciler update hook */
2038
- updateConfig(changed) {
2039
- if ('duration' in changed)
2040
- this._config.duration = changed.duration;
2041
- if ('bottomOffset' in changed)
2042
- this._config.bottomOffset = changed.bottomOffset;
2043
- }
2044
- destroy(options) {
2045
- this._dismissPending = false;
2046
- Tween.killTweensOf(this);
2047
- super.destroy(options);
2048
- }
2049
- }
2050
-
2051
- // ─── Helpers ─────────────────────────────────────────────
2052
- function directionToFlex(direction) {
2053
- switch (direction) {
2054
- case 'horizontal': return { direction: 'row', wrap: false };
2055
- case 'vertical': return { direction: 'column', wrap: false };
2056
- case 'grid': return { direction: 'row', wrap: true };
2057
- case 'wrap': return { direction: 'row', wrap: true };
2058
- }
2059
- }
2060
- /**
2061
- * Responsive layout container powered by a lightweight built-in flex layout solver.
2062
- *
2063
- * Supports horizontal, vertical, grid, and wrap layout modes with
2064
- * alignment, padding, gap, and viewport-anchor positioning.
2065
- * Breakpoints allow different layouts for different screen sizes.
2066
- *
2067
- * @example
2068
- * ```ts
2069
- * const toolbar = new Layout({
2070
- * direction: 'horizontal',
2071
- * gap: 20,
2072
- * alignment: 'center',
2073
- * anchor: 'bottom-center',
2074
- * padding: 16,
2075
- * breakpoints: {
2076
- * 768: { direction: 'vertical', gap: 10 },
2077
- * },
2078
- * });
2079
- *
2080
- * toolbar.addItem(spinButton);
2081
- * toolbar.addItem(betLabel);
2082
- * scene.container.addChild(toolbar);
2083
- *
2084
- * toolbar.updateViewport(width, height);
2085
- * ```
2086
- */
2087
- class Layout extends pixi_js.Container {
2088
- __uiComponent = true;
2089
- _layoutConfig;
2090
- _padding;
2091
- _anchor;
2092
- _maxWidth;
2093
- _breakpoints;
2094
- _items = [];
2095
- _viewportWidth = 0;
2096
- _viewportHeight = 0;
2097
- _flex;
2098
- constructor(config = {}) {
2099
- super();
2100
- this._layoutConfig = {
2101
- direction: config.direction ?? 'vertical',
2102
- gap: config.gap ?? 0,
2103
- alignment: config.alignment ?? 'start',
2104
- autoLayout: config.autoLayout ?? true,
2105
- columns: config.columns ?? 2,
2106
- };
2107
- this._padding = config.padding ?? 0;
2108
- this._anchor = config.anchor ?? 'top-left';
2109
- this._maxWidth = config.maxWidth ?? Infinity;
2110
- this._breakpoints = config.breakpoints
2111
- ? Object.entries(config.breakpoints)
2112
- .map(([w, cfg]) => [Number(w), cfg])
2113
- .sort((a, b) => a[0] - b[0])
2114
- : [];
2115
- // Create internal FlexContainer
2116
- this._flex = new FlexContainer();
2117
- super.addChild(this._flex);
2118
- this.applyLayoutStyles();
2119
- }
2120
- /** Add an item to the layout */
2121
- addItem(child) {
2122
- this._items.push(child);
2123
- const flexConfig = this.buildFlexItemConfig(child);
2124
- this._flex.addFlexChild(child, flexConfig);
2125
- if (this._layoutConfig.autoLayout) {
2126
- this.applyLayoutStyles();
2127
- }
2128
- return this;
2129
- }
2130
- /** Remove an item from the layout */
2131
- removeItem(child) {
2132
- const idx = this._items.indexOf(child);
2133
- if (idx !== -1) {
2134
- this._items.splice(idx, 1);
2135
- this._flex.removeFlexChild(child);
2136
- }
2137
- return this;
2138
- }
2139
- /** Remove all items */
2140
- clearItems() {
2141
- this._flex.clearFlexChildren();
2142
- this._items.length = 0;
2143
- return this;
2144
- }
2145
- /** Get all layout items */
2146
- get items() {
2147
- return this._items;
2148
- }
2149
- /**
2150
- * Update the viewport size and recalculate layout.
2151
- * Should be called from `Scene.onResize()`.
2152
- */
2153
- updateViewport(width, height) {
2154
- this._viewportWidth = width;
2155
- this._viewportHeight = height;
2156
- this.applyLayoutStyles();
2157
- this.applyAnchor();
2158
- }
2159
- applyLayoutStyles() {
2160
- const effective = this.resolveConfig();
2161
- const direction = effective.direction ?? this._layoutConfig.direction;
2162
- const gap = effective.gap ?? this._layoutConfig.gap;
2163
- const alignment = effective.alignment ?? this._layoutConfig.alignment;
2164
- const padding = effective.padding ?? this._padding;
2165
- const maxWidth = effective.maxWidth ?? this._maxWidth;
2166
- const { direction: flexDir, wrap } = directionToFlex(direction);
2167
- this._flex.setDirection(flexDir);
2168
- this._flex.setJustifyContent('start');
2169
- this._flex.setAlignItems(alignment);
2170
- this._flex.setGap(gap);
2171
- this._flex.setPadding(padding);
2172
- // Wrap and maxWidth
2173
- if (wrap) {
2174
- this._flex._config.flexWrap = true;
2175
- if (direction === 'grid' && maxWidth < Infinity) {
2176
- this._flex._maxWidth = maxWidth;
2177
- }
2178
- if (maxWidth < Infinity) {
2179
- this._flex._maxWidth = maxWidth;
2180
- }
2181
- }
2182
- else {
2183
- this._flex._config.flexWrap = false;
2184
- }
2185
- // Update grid child widths
2186
- if (direction === 'grid') {
2187
- for (const item of this._items) {
2188
- const flexConfig = this.buildFlexItemConfig(item);
2189
- item._flexConfig = flexConfig;
2190
- }
2191
- }
2192
- // Set explicit size if we have viewport dimensions
2193
- if (this._viewportWidth > 0 && this._viewportHeight > 0) {
2194
- this._flex.resize(this._viewportWidth, this._viewportHeight);
2195
- }
2196
- else {
2197
- this._flex.updateLayout();
2198
- }
2199
- }
2200
- buildFlexItemConfig(_child) {
2201
- const effective = this.resolveConfig();
2202
- const direction = effective.direction ?? this._layoutConfig.direction;
2203
- const columns = effective.columns ?? this._layoutConfig.columns;
2204
- if (direction === 'grid' && columns > 0) {
2205
- // For grid, give each item a proportional width
2206
- // The actual pixel width will be computed during layout
2207
- return { flexGrow: 1 };
2208
- }
2209
- return undefined;
2210
- }
2211
- applyAnchor() {
2212
- const anchor = this.resolveConfig().anchor ?? this._anchor;
2213
- if (this._viewportWidth === 0 || this._viewportHeight === 0)
2214
- return;
2215
- const { width: contentW, height: contentH } = this._flex.getContentSize();
2216
- const vw = this._viewportWidth;
2217
- const vh = this._viewportHeight;
2218
- let anchorX = 0;
2219
- let anchorY = 0;
2220
- if (anchor.includes('left')) {
2221
- anchorX = 0;
2222
- }
2223
- else if (anchor.includes('right')) {
2224
- anchorX = vw - contentW;
2225
- }
2226
- else {
2227
- anchorX = (vw - contentW) / 2;
2228
- }
2229
- if (anchor.startsWith('top')) {
2230
- anchorY = 0;
2231
- }
2232
- else if (anchor.startsWith('bottom')) {
2233
- anchorY = vh - contentH;
2234
- }
2235
- else {
2236
- anchorY = (vh - contentH) / 2;
2237
- }
2238
- this.x = anchorX;
2239
- this.y = anchorY;
2240
- }
2241
- resolveConfig() {
2242
- if (this._breakpoints.length === 0 || this._viewportWidth === 0) {
2243
- return {};
2244
- }
2245
- for (const [maxWidth, overrides] of this._breakpoints) {
2246
- if (this._viewportWidth <= maxWidth) {
2247
- return overrides;
2248
- }
2249
- }
2250
- return {};
2251
- }
2252
- /** React reconciler update hook */
2253
- updateConfig(changed) {
2254
- if ('direction' in changed)
2255
- this._layoutConfig.direction = changed.direction;
2256
- if ('gap' in changed)
2257
- this._layoutConfig.gap = changed.gap;
2258
- if ('alignment' in changed)
2259
- this._layoutConfig.alignment = changed.alignment;
2260
- if ('anchor' in changed)
2261
- this._anchor = changed.anchor;
2262
- if ('padding' in changed)
2263
- this._padding = changed.padding;
2264
- if ('columns' in changed)
2265
- this._layoutConfig.columns = changed.columns;
2266
- this.applyLayoutStyles();
2267
- if (this._viewportWidth > 0)
2268
- this.applyAnchor();
2269
- }
2270
- destroy(options) {
2271
- this._items.length = 0;
2272
- super.destroy(options);
2273
- }
2274
- }
2275
-
2276
- const DECELERATION = 0.95;
2277
- const MIN_VELOCITY = 0.5;
2278
- /**
2279
- * Scrollable container with touch/drag, mouse wheel, and inertia.
2280
- *
2281
- * @example
2282
- * ```ts
2283
- * const scroll = new ScrollContainer({
2284
- * width: 600,
2285
- * height: 400,
2286
- * direction: 'vertical',
2287
- * elementsMargin: 8,
2288
- * });
2289
- *
2290
- * for (let i = 0; i < 50; i++) {
2291
- * scroll.addItem(createRow(i));
2292
- * }
2293
- *
2294
- * scene.container.addChild(scroll);
2295
- * ```
2296
- */
2297
- class ScrollContainer extends pixi_js.Container {
2298
- __uiComponent = true;
2299
- _viewport;
2300
- _internalSetup = true;
2301
- _content;
2302
- _maskGfx;
2303
- _bg = null;
2304
- _scrollConfig;
2305
- _items = [];
2306
- // Scrollbar
2307
- _scrollbar = null;
2308
- _scrollbarConfig;
2309
- // Drag state
2310
- _dragging = false;
2311
- _dragStart = { x: 0, y: 0 };
2312
- _contentStart = { x: 0, y: 0 };
2313
- _velocity = { x: 0, y: 0 };
2314
- _lastDragPos = { x: 0, y: 0 };
2315
- _lastDragTime = 0;
2316
- _inertiaActive = false;
2317
- // Bound handlers for cleanup
2318
- _onTickBound = null;
2319
- _onWheelBound = null;
2320
- constructor(config) {
2321
- super();
2322
- this._viewport = { width: config.width, height: config.height };
2323
- this._scrollConfig = {
2324
- direction: config.direction ?? 'vertical',
2325
- elementsMargin: config.elementsMargin ?? 0,
2326
- padding: config.padding ?? 0,
2327
- borderRadius: config.borderRadius ?? 0,
2328
- disableEasing: config.disableEasing ?? false,
2329
- };
2330
- // Background
2331
- if (config.backgroundColor !== undefined) {
2332
- this._bg = new pixi_js.Graphics();
2333
- this._bg.roundRect(0, 0, config.width, config.height, this._scrollConfig.borderRadius)
2334
- .fill(config.backgroundColor);
2335
- this.addChild(this._bg);
2336
- }
2337
- // Mask
2338
- this._maskGfx = new pixi_js.Graphics();
2339
- this._maskGfx.roundRect(0, 0, config.width, config.height, this._scrollConfig.borderRadius)
2340
- .fill(0xffffff);
2341
- this.addChild(this._maskGfx);
2342
- // Content container
2343
- this._content = new pixi_js.Container();
2344
- this._content.mask = this._maskGfx;
2345
- this.addChild(this._content);
2346
- // Interaction
2347
- this.eventMode = 'static';
2348
- this.hitArea = { contains: (x, y) => x >= 0 && x <= config.width && y >= 0 && y <= config.height };
2349
- this.on('pointerdown', this._onPointerDown, this);
2350
- this.on('pointermove', this._onPointerMove, this);
2351
- this.on('pointerup', this._onPointerUp, this);
2352
- this.on('pointerupoutside', this._onPointerUp, this);
2353
- // Mouse wheel
2354
- this._onWheelBound = this._onWheel.bind(this);
2355
- // Scrollbar
2356
- const sbWidth = config.scrollbarWidth ?? 6;
2357
- const sbPadding = config.scrollbarPadding ?? 4;
2358
- this._scrollbarConfig = { width: sbWidth, padding: sbPadding };
2359
- if (config.scrollbar) {
2360
- const customThumb = resolveView(config.thumbView);
2361
- if (customThumb) {
2362
- this._scrollbar = customThumb;
2363
- }
2364
- else {
2365
- const g = new pixi_js.Graphics();
2366
- g.roundRect(0, 0, sbWidth, 40, sbWidth / 2).fill(config.scrollbarColor ?? 0xaaaaaa);
2367
- g.alpha = config.scrollbarAlpha ?? 0.5;
2368
- this._scrollbar = g;
2369
- }
2370
- this._scrollbar.visible = false;
2371
- super.addChild(this._scrollbar);
2372
- }
2373
- this._internalSetup = false;
2374
- }
2375
- /**
2376
- * Override addChild so external children are routed to scroll content.
2377
- * Enables `<scrollContainer><label /><panel /></scrollContainer>` in React JSX.
2378
- */
2379
- addChild(...children) {
2380
- if (this._internalSetup) {
2381
- return super.addChild(...children);
2382
- }
2383
- for (const child of children) {
2384
- this.addItem(child);
2385
- }
2386
- return children[0];
2387
- }
2388
- removeChild(...children) {
2389
- if (this._internalSetup) {
2390
- return super.removeChild(...children);
2391
- }
2392
- for (const child of children) {
2393
- const idx = this._items.indexOf(child);
2394
- if (idx !== -1) {
2395
- this._items.splice(idx, 1);
2396
- this._content.removeChild(child);
2397
- }
2398
- }
2399
- this.layoutItems();
2400
- return children[0];
2401
- }
2402
- /** React reconciler update hook */
2403
- updateConfig(changed) {
2404
- if ('width' in changed || 'height' in changed) {
2405
- this.setViewportSize(changed.width ?? this._viewport.width, changed.height ?? this._viewport.height);
2406
- }
2407
- }
2408
- /** Enable mouse wheel scrolling (call after adding to stage) */
2409
- enableWheel(canvas) {
2410
- if (this._onWheelBound) {
2411
- canvas.addEventListener('wheel', this._onWheelBound, { passive: false });
2412
- }
2413
- }
2414
- /** Set scrollable content. Replaces any existing items. */
2415
- setContent(content) {
2416
- this.clearItems();
2417
- const children = [...content.children];
2418
- for (const child of children) {
2419
- this.addItem(child);
2420
- }
2421
- }
2422
- /** Add a single item */
2423
- addItem(child) {
2424
- this._items.push(child);
2425
- this._content.addChild(child);
2426
- this.layoutItems();
2427
- return this;
2428
- }
2429
- /** Remove all items */
2430
- clearItems() {
2431
- for (const item of this._items) {
2432
- this._content.removeChild(item);
2433
- }
2434
- this._items.length = 0;
2435
- }
2436
- /** Get items */
2437
- get items() {
2438
- return this._items;
2439
- }
2440
- /** Scroll to make a specific item index visible */
2441
- scrollToItem(index) {
2442
- if (index < 0 || index >= this._items.length)
2443
- return;
2444
- const item = this._items[index];
2445
- const isVert = this._scrollConfig.direction !== 'horizontal';
2446
- if (isVert) {
2447
- this._content.y = -item.y + this._scrollConfig.padding;
2448
- }
2449
- else {
2450
- this._content.x = -item.x + this._scrollConfig.padding;
2451
- }
2452
- this.clampScroll();
2453
- }
2454
- /** Current scroll position */
2455
- get scrollPosition() {
2456
- return { x: this._content.x, y: this._content.y };
2457
- }
2458
- /** Resize the scroll viewport */
2459
- setViewportSize(width, height) {
2460
- this._viewport.width = width;
2461
- this._viewport.height = height;
2462
- this._maskGfx.clear();
2463
- this._maskGfx.roundRect(0, 0, width, height, this._scrollConfig.borderRadius).fill(0xffffff);
2464
- if (this._bg) {
2465
- this._bg.clear();
2466
- this._bg.roundRect(0, 0, width, height, this._scrollConfig.borderRadius)
2467
- .fill(0xffffff); // color will be overridden if needed
2468
- }
2469
- this.clampScroll();
2470
- }
2471
- // ─── Layout ──────────────────────────────────────────
2472
- layoutItems() {
2473
- const { direction, elementsMargin, padding } = this._scrollConfig;
2474
- const isVert = direction !== 'horizontal';
2475
- let pos = padding;
2476
- for (const item of this._items) {
2477
- if (isVert) {
2478
- item.x = padding;
2479
- item.y = pos;
2480
- pos += item.height + elementsMargin;
2481
- }
2482
- else {
2483
- item.x = pos;
2484
- item.y = padding;
2485
- pos += item.width + elementsMargin;
2486
- }
2487
- }
2488
- }
2489
- // ─── Drag handling ───────────────────────────────────
2490
- _onPointerDown(e) {
2491
- this._dragging = true;
2492
- this._inertiaActive = false;
2493
- this._dragStart.x = e.globalX;
2494
- this._dragStart.y = e.globalY;
2495
- this._contentStart.x = this._content.x;
2496
- this._contentStart.y = this._content.y;
2497
- this._lastDragPos.x = e.globalX;
2498
- this._lastDragPos.y = e.globalY;
2499
- this._lastDragTime = Date.now();
2500
- this._velocity.x = 0;
2501
- this._velocity.y = 0;
2502
- this.stopInertia();
2503
- }
2504
- _onPointerMove(e) {
2505
- if (!this._dragging)
2506
- return;
2507
- const dx = e.globalX - this._dragStart.x;
2508
- const dy = e.globalY - this._dragStart.y;
2509
- const { direction } = this._scrollConfig;
2510
- if (direction !== 'horizontal') {
2511
- this._content.y = this._contentStart.y + dy;
2512
- }
2513
- if (direction !== 'vertical') {
2514
- this._content.x = this._contentStart.x + dx;
2515
- }
2516
- // Track velocity
2517
- const now = Date.now();
2518
- const dt = now - this._lastDragTime;
2519
- if (dt > 0) {
2520
- this._velocity.x = (e.globalX - this._lastDragPos.x) / dt * 16;
2521
- this._velocity.y = (e.globalY - this._lastDragPos.y) / dt * 16;
2522
- }
2523
- this._lastDragPos.x = e.globalX;
2524
- this._lastDragPos.y = e.globalY;
2525
- this._lastDragTime = now;
2526
- this.clampScroll();
2527
- }
2528
- _onPointerUp() {
2529
- if (!this._dragging)
2530
- return;
2531
- this._dragging = false;
2532
- if (!this._scrollConfig.disableEasing &&
2533
- (Math.abs(this._velocity.x) > MIN_VELOCITY || Math.abs(this._velocity.y) > MIN_VELOCITY)) {
2534
- this.startInertia();
2535
- }
2536
- }
2537
- // ─── Inertia ─────────────────────────────────────────
2538
- startInertia() {
2539
- this._inertiaActive = true;
2540
- this._onTickBound = this._inertiaTick.bind(this);
2541
- pixi_js.Ticker.shared.add(this._onTickBound);
2542
- }
2543
- stopInertia() {
2544
- if (this._onTickBound && this._inertiaActive) {
2545
- pixi_js.Ticker.shared.remove(this._onTickBound);
2546
- this._inertiaActive = false;
2547
- }
2548
- }
2549
- _inertiaTick() {
2550
- const { direction } = this._scrollConfig;
2551
- if (direction !== 'horizontal') {
2552
- this._content.y += this._velocity.y;
2553
- this._velocity.y *= DECELERATION;
2554
- }
2555
- if (direction !== 'vertical') {
2556
- this._content.x += this._velocity.x;
2557
- this._velocity.x *= DECELERATION;
2558
- }
2559
- this.clampScroll();
2560
- if (Math.abs(this._velocity.x) < MIN_VELOCITY && Math.abs(this._velocity.y) < MIN_VELOCITY) {
2561
- this.stopInertia();
2562
- }
2563
- }
2564
- // ─── Mouse wheel ─────────────────────────────────────
2565
- _onWheel(e) {
2566
- const { direction } = this._scrollConfig;
2567
- e.preventDefault();
2568
- if (direction !== 'horizontal') {
2569
- this._content.y -= e.deltaY;
2570
- }
2571
- if (direction !== 'vertical') {
2572
- this._content.x -= e.deltaX;
2573
- }
2574
- this.clampScroll();
2575
- }
2576
- // ─── Scroll bounds ───────────────────────────────────
2577
- clampScroll() {
2578
- const { direction } = this._scrollConfig;
2579
- const bounds = this._content.getLocalBounds();
2580
- if (direction !== 'horizontal') {
2581
- const contentHeight = bounds.height + bounds.y;
2582
- const maxScroll = Math.min(0, this._viewport.height - contentHeight);
2583
- this._content.y = Math.max(maxScroll, Math.min(0, this._content.y));
2584
- }
2585
- if (direction !== 'vertical') {
2586
- const contentWidth = bounds.width + bounds.x;
2587
- const maxScroll = Math.min(0, this._viewport.width - contentWidth);
2588
- this._content.x = Math.max(maxScroll, Math.min(0, this._content.x));
2589
- }
2590
- this.updateScrollbar();
2591
- }
2592
- updateScrollbar() {
2593
- if (!this._scrollbar)
2594
- return;
2595
- const { direction } = this._scrollConfig;
2596
- const { width: sbW, padding: sbPad } = this._scrollbarConfig;
2597
- const bounds = this._content.getLocalBounds();
2598
- const isVert = direction !== 'horizontal';
2599
- if (isVert) {
2600
- const contentH = bounds.height + bounds.y;
2601
- if (contentH <= this._viewport.height) {
2602
- this._scrollbar.visible = false;
2603
- return;
2604
- }
2605
- this._scrollbar.visible = true;
2606
- const ratio = this._viewport.height / contentH;
2607
- const thumbH = Math.max(20, this._viewport.height * ratio);
2608
- const scrollRange = this._viewport.height - thumbH;
2609
- const scrollProgress = -this._content.y / (contentH - this._viewport.height);
2610
- this._scrollbar.x = this._viewport.width - sbW - sbPad;
2611
- this._scrollbar.y = scrollProgress * scrollRange;
2612
- this._scrollbar.height = thumbH;
2613
- this._scrollbar.width = sbW;
2614
- }
2615
- else {
2616
- const contentW = bounds.width + bounds.x;
2617
- if (contentW <= this._viewport.width) {
2618
- this._scrollbar.visible = false;
2619
- return;
2620
- }
2621
- this._scrollbar.visible = true;
2622
- const ratio = this._viewport.width / contentW;
2623
- const thumbW = Math.max(20, this._viewport.width * ratio);
2624
- const scrollRange = this._viewport.width - thumbW;
2625
- const scrollProgress = -this._content.x / (contentW - this._viewport.width);
2626
- this._scrollbar.y = this._viewport.height - sbW - sbPad;
2627
- this._scrollbar.x = scrollProgress * scrollRange;
2628
- this._scrollbar.width = thumbW;
2629
- this._scrollbar.height = sbW;
2630
- }
2631
- }
2632
- destroy(options) {
2633
- this.stopInertia();
2634
- this.off('pointerdown', this._onPointerDown, this);
2635
- this.off('pointermove', this._onPointerMove, this);
2636
- this.off('pointerup', this._onPointerUp, this);
2637
- this.off('pointerupoutside', this._onPointerUp, this);
2638
- this._items.length = 0;
2639
- super.destroy(options);
2640
- }
2641
- }
2642
-
2643
- /**
2644
- * Draggable slider with customizable track, fill, and handle views.
2645
- *
2646
- * @example
2647
- * ```ts
2648
- * const volume = new Slider({
2649
- * min: 0, max: 1, value: 0.5,
2650
- * width: 200, height: 8,
2651
- * fillColor: 0xffd700,
2652
- * onUpdate: (v) => console.log('Volume:', v),
2653
- * });
2654
- * ```
2655
- */
2656
- class Slider extends pixi_js.Container {
2657
- __uiComponent = true;
2658
- _track;
2659
- _fill;
2660
- _fillMask;
2661
- _handle;
2662
- _config;
2663
- _value;
2664
- _dragging = false;
2665
- onUpdate = null;
2666
- onChange = null;
2667
- constructor(config = {}) {
2668
- super();
2669
- this._config = {
2670
- min: config.min ?? 0,
2671
- max: config.max ?? 1,
2672
- step: config.step ?? 0,
2673
- width: config.width ?? 200,
2674
- height: config.height ?? 8,
2675
- borderRadius: config.borderRadius ?? 4,
2676
- trackColor: config.trackColor ?? 0x333333,
2677
- fillColor: config.fillColor ?? 0xffd700,
2678
- handleRadius: config.handleRadius ?? 12,
2679
- handleColor: config.handleColor ?? 0xffffff,
2680
- };
2681
- this._value = config.value ?? this._config.min;
2682
- this.onUpdate = config.onUpdate ?? null;
2683
- this.onChange = config.onChange ?? null;
2684
- const { width, height, borderRadius, trackColor, fillColor, handleRadius, handleColor } = this._config;
2685
- // Track
2686
- const customTrack = resolveView(config.trackView);
2687
- if (customTrack) {
2688
- customTrack.width = width;
2689
- customTrack.height = height;
2690
- this._track = customTrack;
2691
- }
2692
- else {
2693
- const g = new pixi_js.Graphics();
2694
- g.roundRect(0, 0, width, height, borderRadius).fill(trackColor);
2695
- this._track = g;
2696
- }
2697
- this.addChild(this._track);
2698
- // Fill
2699
- const customFill = resolveView(config.fillView);
2700
- if (customFill) {
2701
- customFill.width = width;
2702
- customFill.height = height;
2703
- this._fill = customFill;
2704
- }
2705
- else {
2706
- const g = new pixi_js.Graphics();
2707
- g.roundRect(0, 0, width, height, borderRadius).fill(fillColor);
2708
- this._fill = g;
2709
- }
2710
- this.addChild(this._fill);
2711
- // Fill mask
2712
- this._fillMask = new pixi_js.Graphics();
2713
- this.addChild(this._fillMask);
2714
- this._fill.mask = this._fillMask;
2715
- // Handle
2716
- const customHandle = resolveView(config.handleView);
2717
- if (customHandle) {
2718
- this._handle = customHandle;
2719
- }
2720
- else {
2721
- const g = new pixi_js.Graphics();
2722
- g.circle(0, 0, handleRadius).fill(handleColor);
2723
- this._handle = g;
2724
- }
2725
- this._handle.y = height / 2;
2726
- this.addChild(this._handle);
2727
- // Interaction
2728
- this.eventMode = 'static';
2729
- this.cursor = 'pointer';
2730
- // Hit area covers track + handle overflow
2731
- const hitPad = Math.max(handleRadius - height / 2, 0);
2732
- this.hitArea = { contains: (x, y) => x >= -hitPad && x <= width + hitPad && y >= -hitPad && y <= height + hitPad };
2733
- this.on('pointerdown', this._onPointerDown, this);
2734
- this.on('globalpointermove', this._onPointerMove, this);
2735
- this.on('pointerup', this._onPointerUp, this);
2736
- this.on('pointerupoutside', this._onPointerUp, this);
2737
- this._updateVisuals();
2738
- }
2739
- /** Current value */
2740
- get value() {
2741
- return this._value;
2742
- }
2743
- set value(v) {
2744
- const clamped = this._applyStep(Math.max(this._config.min, Math.min(this._config.max, v)));
2745
- if (clamped === this._value)
2746
- return;
2747
- this._value = clamped;
2748
- this._updateVisuals();
2749
- }
2750
- get min() { return this._config.min; }
2751
- get max() { return this._config.max; }
2752
- /** React reconciler update hook */
2753
- updateConfig(changed) {
2754
- if ('value' in changed)
2755
- this.value = changed.value;
2756
- if ('min' in changed) {
2757
- this._config.min = changed.min;
2758
- this._updateVisuals();
2759
- }
2760
- if ('max' in changed) {
2761
- this._config.max = changed.max;
2762
- this._updateVisuals();
2763
- }
2764
- if ('step' in changed)
2765
- this._config.step = changed.step;
2766
- if ('onUpdate' in changed)
2767
- this.onUpdate = changed.onUpdate;
2768
- if ('onChange' in changed)
2769
- this.onChange = changed.onChange;
2770
- }
2771
- _fraction() {
2772
- const { min, max } = this._config;
2773
- return max === min ? 0 : (this._value - min) / (max - min);
2774
- }
2775
- _applyStep(v) {
2776
- const { step, min } = this._config;
2777
- if (step <= 0)
2778
- return v;
2779
- return min + Math.round((v - min) / step) * step;
2780
- }
2781
- _updateVisuals() {
2782
- const frac = this._fraction();
2783
- const w = this._config.width;
2784
- const h = this._config.height;
2785
- // Update fill mask
2786
- this._fillMask.clear();
2787
- this._fillMask.rect(0, 0, w * frac, h).fill(0xffffff);
2788
- // Update handle position
2789
- this._handle.x = w * frac;
2790
- }
2791
- _valueFromPointer(e) {
2792
- const local = this.toLocal(e.global);
2793
- const frac = Math.max(0, Math.min(1, local.x / this._config.width));
2794
- const { min, max } = this._config;
2795
- return this._applyStep(min + frac * (max - min));
2796
- }
2797
- _onPointerDown(e) {
2798
- this._dragging = true;
2799
- const newValue = this._valueFromPointer(e);
2800
- if (newValue !== this._value) {
2801
- this._value = newValue;
2802
- this._updateVisuals();
2803
- this.onUpdate?.(this._value);
2804
- }
2805
- }
2806
- _onPointerMove(e) {
2807
- if (!this._dragging)
2808
- return;
2809
- const newValue = this._valueFromPointer(e);
2810
- if (newValue !== this._value) {
2811
- this._value = newValue;
2812
- this._updateVisuals();
2813
- this.onUpdate?.(this._value);
2814
- }
2815
- }
2816
- _onPointerUp(_e) {
2817
- if (!this._dragging)
2818
- return;
2819
- this._dragging = false;
2820
- this.onChange?.(this._value);
2821
- }
2822
- destroy(options) {
2823
- this.off('pointerdown', this._onPointerDown, this);
2824
- this.off('globalpointermove', this._onPointerMove, this);
2825
- this.off('pointerup', this._onPointerUp, this);
2826
- this.off('pointerupoutside', this._onPointerUp, this);
2827
- this.onUpdate = null;
2828
- this.onChange = null;
2829
- super.destroy(options);
2830
- }
2831
- }
2832
-
2833
- /**
2834
- * Toggle switch with two states.
2835
- *
2836
- * Supports custom ON/OFF views or auto-generated Graphics-based toggle.
2837
- * Click to toggle, or use `forceSwitch(value)` programmatically.
2838
- *
2839
- * @example
2840
- * ```ts
2841
- * const mute = new Toggle({
2842
- * value: false,
2843
- * onColor: 0x22cc22,
2844
- * onChange: (on) => audioManager.mute(!on),
2845
- * });
2846
- * ```
2847
- */
2848
- class Toggle extends pixi_js.Container {
2849
- __uiComponent = true;
2850
- _value;
2851
- _onView = null;
2852
- _offView = null;
2853
- _handle = null;
2854
- _trackGfx = null;
2855
- _config;
2856
- _useCustomViews;
2857
- onChange = null;
2858
- constructor(config = {}) {
2859
- super();
2860
- this._config = {
2861
- width: config.width ?? 52,
2862
- height: config.height ?? 28,
2863
- onColor: config.onColor ?? 0x22cc22,
2864
- offColor: config.offColor ?? 0x666666,
2865
- handleColor: config.handleColor ?? 0xffffff,
2866
- handleRadius: config.handleRadius ?? 0, // 0 = auto
2867
- animationDuration: config.animationDuration ?? 200,
2868
- };
2869
- this._value = config.value ?? false;
2870
- this.onChange = config.onChange ?? null;
2871
- const customOn = resolveView(config.onView);
2872
- const customOff = resolveView(config.offView);
2873
- this._useCustomViews = !!(customOn || customOff);
2874
- if (this._useCustomViews) {
2875
- // Custom view mode: show/hide ON and OFF views
2876
- if (customOn) {
2877
- this._onView = customOn;
2878
- this._onView.visible = this._value;
2879
- this.addChild(this._onView);
2880
- }
2881
- if (customOff) {
2882
- this._offView = customOff;
2883
- this._offView.visible = !this._value;
2884
- this.addChild(this._offView);
2885
- }
2886
- }
2887
- else {
2888
- // Graphics mode: track + sliding handle
2889
- const { width, height, handleColor } = this._config;
2890
- const handleRadius = this._config.handleRadius || (height / 2 - 3);
2891
- this._config.handleRadius = handleRadius;
2892
- this._trackGfx = new pixi_js.Graphics();
2893
- this.addChild(this._trackGfx);
2894
- this._drawTrack();
2895
- const handle = new pixi_js.Graphics();
2896
- handle.circle(0, 0, handleRadius).fill(handleColor);
2897
- handle.y = height / 2;
2898
- handle.x = this._value ? width - handleRadius - 3 : handleRadius + 3;
2899
- this._handle = handle;
2900
- this.addChild(handle);
2901
- }
2902
- // Interaction
2903
- this.eventMode = 'static';
2904
- this.cursor = 'pointer';
2905
- this.on('pointertap', this._onTap, this);
2906
- }
2907
- /** Current toggle state */
2908
- get value() {
2909
- return this._value;
2910
- }
2911
- set value(v) {
2912
- if (v === this._value)
2913
- return;
2914
- this.forceSwitch(v);
2915
- }
2916
- /** Programmatically switch to a specific state with animation */
2917
- forceSwitch(value) {
2918
- this._value = value;
2919
- this._animateToState();
2920
- }
2921
- /** React reconciler update hook */
2922
- updateConfig(changed) {
2923
- if ('value' in changed)
2924
- this.value = changed.value;
2925
- if ('onChange' in changed)
2926
- this.onChange = changed.onChange;
2927
- if ('animationDuration' in changed)
2928
- this._config.animationDuration = changed.animationDuration;
2929
- }
2930
- _onTap() {
2931
- this._value = !this._value;
2932
- this._animateToState();
2933
- this.onChange?.(this._value);
2934
- }
2935
- _animateToState() {
2936
- const duration = this._config.animationDuration;
2937
- if (this._useCustomViews) {
2938
- // Custom views: crossfade
2939
- if (this._onView) {
2940
- Tween.killTweensOf(this._onView);
2941
- if (this._value) {
2942
- this._onView.visible = true;
2943
- Tween.to(this._onView, { alpha: 1 }, duration);
2944
- }
2945
- else {
2946
- Tween.to(this._onView, { alpha: 0 }, duration).then(() => {
2947
- if (this._onView)
2948
- this._onView.visible = false;
2949
- });
2950
- }
2951
- }
2952
- if (this._offView) {
2953
- Tween.killTweensOf(this._offView);
2954
- if (!this._value) {
2955
- this._offView.visible = true;
2956
- Tween.to(this._offView, { alpha: 1 }, duration);
2957
- }
2958
- else {
2959
- Tween.to(this._offView, { alpha: 0 }, duration).then(() => {
2960
- if (this._offView)
2961
- this._offView.visible = false;
2962
- });
2963
- }
2964
- }
2965
- }
2966
- else {
2967
- // Graphics mode: slide handle + recolor track
2968
- this._drawTrack();
2969
- if (this._handle) {
2970
- const { width } = this._config;
2971
- const handleRadius = this._config.handleRadius;
2972
- const targetX = this._value ? width - handleRadius - 3 : handleRadius + 3;
2973
- Tween.killTweensOf(this._handle);
2974
- Tween.to(this._handle, { x: targetX }, duration);
2975
- }
2976
- }
2977
- }
2978
- _drawTrack() {
2979
- if (!this._trackGfx)
2980
- return;
2981
- const { width, height, onColor, offColor } = this._config;
2982
- const radius = height / 2;
2983
- this._trackGfx.clear();
2984
- this._trackGfx.roundRect(0, 0, width, height, radius).fill(this._value ? onColor : offColor);
2985
- }
2986
- destroy(options) {
2987
- this.off('pointertap', this._onTap, this);
2988
- if (this._handle)
2989
- Tween.killTweensOf(this._handle);
2990
- if (this._onView)
2991
- Tween.killTweensOf(this._onView);
2992
- if (this._offView)
2993
- Tween.killTweensOf(this._offView);
2994
- this.onChange = null;
2995
- super.destroy(options);
2996
- }
2997
- }
2998
-
2999
- exports.BalanceDisplay = BalanceDisplay;
3000
- exports.Button = Button;
3001
- exports.FlexContainer = FlexContainer;
3002
- exports.Label = Label;
3003
- exports.LabelValue = LabelValue;
3004
- exports.Layout = Layout;
3005
- exports.Modal = Modal;
3006
- exports.Panel = Panel;
3007
- exports.ProgressBar = ProgressBar;
3008
- exports.ScrollContainer = ScrollContainer;
3009
- exports.Slider = Slider;
3010
- exports.Toast = Toast;
3011
- exports.Toggle = Toggle;
3012
- exports.WinDisplay = WinDisplay;
3013
- exports.resolveView = resolveView;
3014
- //# sourceMappingURL=ui.cjs.js.map