Skip to content

Commit acbb163

Browse files
committed
UI: checkbox, slider, skinned button, panel layout and scrolling (#1722)
- UICheckbox: a checkbox with its label, drawn or skinned, a radio button with a `group`; `onChange` only on user input - UISlider: horizontal or vertical, drag, track click, wheel, step, caption and value text, drawn or skinned; `onChange` and `onChangeEnd` - UITextButton: `onClick` setting on a completed click, atlas `skin` with lowered pressed art, `enabled`, `pressedColor`, CSS fonts - UIPanel: nine-slice `skin`, `title`, `draggable`, `layout` (column/row/grid, padding, gap, align, autoSize) and `scroll` (wheel, drag with momentum, scrollbar, scrollTo/scrollToChild) - UIBaseElement: cancelPress/onCancel, so a drag on a button in a scrolling panel scrolls instead of clicking - Input: children cropped by a clipping container, or scrolled out of a panel, no longer get pointer events there - The UI example uses the widgets, with volume sliders wired to audio and a scrolling level list; skill sections and changelog entries Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JnzwA4xBNBw7cEZzG1bUru
1 parent 12218f4 commit acbb163

15 files changed

Lines changed: 4471 additions & 298 deletions

File tree

‎packages/examples/src/examples/ui/ExampleUI.tsx‎

Lines changed: 285 additions & 250 deletions
Large diffs are not rendered by default.

‎packages/melonjs/CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,16 @@
44

55
### Added
66
- Particles: a `depth` setting, the spawn area's size along Z, with `width` and `height`. Under a `Camera3d`, particles are born through a volume instead of on a flat sheet
7+
- UI: `UICheckbox`, a checkbox with its label, drawn or from atlas art, that becomes a radio button with a `group` ([#1722](https://github.com/melonjs/melonJS/issues/1722)). `onChange` only fires on user input, not when `checked` is set from code
8+
- UI: `UISlider`, a horizontal or vertical slider with `min`, `max`, `step`, drag, track clicks and the mouse wheel, an optional caption and value text, drawn or from atlas art. `onChange` fires while it moves, `onChangeEnd` once on release, neither when `value` is set from code
9+
- UI: `UIPanel` lays its children out (`layout`: `"column"`, `"row"` or `"grid"`, with `padding`, `gap`, `align` and `autoSize`), scrolls them (`scroll`, with the wheel, dragging, momentum and a scrollbar; `scrollTo`, `scrollToChild`), and takes a nine-slice `skin`, a `title` and `draggable`
10+
- UI: `UITextButton` takes an `onClick` setting, called on a completed click; a `skin` of atlas regions, with pressed art drawn lowered; `enabled`; and `pressedColor`. A font that is not a loaded bitmap font is drawn as a CSS font, where the button used to throw
11+
- UI: `UIBaseElement#cancelPress()` and `onCancel()`, to call off a press without a release; a scrolling `UIPanel` uses them when a drag on a button turns into a scroll
12+
13+
### Fixed
14+
- Input: a child cropped out of view by a container with `clipping`, or scrolled out of a `UIPanel`, no longer gets pointer events where it is not drawn
15+
- UI: a `UITextButton` moved after it was built draws its background where it is, not where it was first put
16+
- UI: a blocking `UIPanel` stays opaque to hover for as long as the pointer is on it, not only on the frame the pointer enters
717

818
## [20.12.0] (melonJS 2) - _2026-10-30_
919

‎packages/melonjs/skills/melonjs-ui-and-text/SKILL.md‎

Lines changed: 177 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
name: melonjs-ui-and-text
3-
description: "Use this skill for HUDs, buttons, menus, dialogue panels, progress bars and on-screen text in melonJS. Covers UIBaseElement/UISpriteElement/UITextButton, ProgressBar, UIPanel, Draggable and DropTarget, the floating screen-space container pattern, which of two overlapping panels gets the pointer, Text and BitmapText, web font loading, and NineSliceSprite panels. Triggers on: UI, HUD, button, UIBaseElement, UISpriteElement, UITextButton, ProgressBar, progress bar, health bar, gauge, Draggable, DropTarget, menu, dialogue, overlapping panels, moveToTop, onOver, onClick, bindKey, keyboard shortcut, button keyboard, Tween, easing, animate a label, wavy text, per-glyph effect, glyphEffect, shake text, rainbow text, Text, BitmapText, fillStyle, fillGradient, gradient text, tint, font, fontface, wordWrapWidth, NineSliceSprite, score display, floating., fullscreen, full screen, requestFullscreen, exitFullscreen, isFullscreen, fullscreen button, fullscreen option"
3+
description: "Use this skill for HUDs, buttons, menus, options screens, dialogue panels, progress bars and on-screen text in melonJS. Covers UIBaseElement/UISpriteElement/UITextButton, UICheckbox, UISlider, ProgressBar, UIPanel (skins, layout, scrolling), Draggable and DropTarget, the floating screen-space container pattern, which of two overlapping panels gets the pointer, Text and BitmapText, web font loading, and NineSliceSprite panels. Triggers on: UI, HUD, button, checkbox, radio button, UICheckbox, slider, UISlider, volume slider, options menu, settings screen, scrolling list, scroll panel, layout, column, grid, UI skin, UIBaseElement, UISpriteElement, UITextButton, ProgressBar, progress bar, health bar, gauge, Draggable, DropTarget, menu, dialogue, overlapping panels, moveToTop, onOver, onClick, bindKey, keyboard shortcut, button keyboard, Tween, easing, animate a label, wavy text, per-glyph effect, glyphEffect, shake text, rainbow text, Text, BitmapText, fillStyle, fillGradient, gradient text, tint, font, fontface, wordWrapWidth, NineSliceSprite, score display, floating., fullscreen, full screen, requestFullscreen, exitFullscreen, isFullscreen, fullscreen button, fullscreen option"
44
license: MIT
55
---
66

@@ -441,6 +441,79 @@ One consequence worth knowing: `getBounds()` on a bobbing panel answers
441441
differently each frame, so do not cache it or compare two children's bounds
442442
while a bob is running.
443443

444+
### Panel art, title, dragging: `skin`, `title`, `draggable`
445+
446+
```js
447+
const options = new UIPanel(20, 20, {
448+
width: 380, height: 460,
449+
// one atlas region, stretched as a nine-slice to the panel's size
450+
skin: { atlas, region: "grey_panel", insetx: 10, insety: 10 },
451+
title: "OPTIONS", titleFont: "kenpixel", titleFontSize: 20, titleFillStyle: "black",
452+
draggable: true, // comes to the front when grabbed
453+
});
454+
```
455+
456+
The title sits at the top and the content starts below it. `insetx` /
457+
`insety` are the unscaled corners of the art, and also where the frame ends:
458+
layout `padding` is measured from there.
459+
460+
### Laying a panel out: `layout`
461+
462+
Leave `layout` at `"none"` and children stay where you put them. Otherwise
463+
the panel places them, below the title and inside the frame:
464+
465+
```js
466+
const menu = new UIPanel(x, y, {
467+
width: 360, height: 100,
468+
layout: "column", // "row", "grid" (with `columns`), or "none"
469+
padding: 16, // from the frame to the content
470+
gap: 12, // between children
471+
align: "stretch", // "start", "center", "end", or "stretch"
472+
autoSize: true, // grow the panel to fit
473+
});
474+
menu.addChild(new UITextButton(0, 0, { text: "Play", onClick: play }));
475+
menu.addChild(new UITextButton(0, 0, { text: "Options", onClick: openOptions }));
476+
```
477+
478+
Children are laid out in the order they were added. It runs when a child is
479+
added or removed and when the panel is resized, **not every frame**: a child
480+
that changes size afterwards, a label whose text grew, needs
481+
`menu.relayout()`. `"stretch"` resizes children that have a `resize` method,
482+
which `UITextButton` and other containers do; a `Text` keeps its size.
483+
484+
A row inside a column is a second panel that draws nothing and lets clicks
485+
through: `new UIPanel(0, 0, { width, height, layout: "row", blocking: false })`.
486+
487+
### Scrolling lists: `scroll`
488+
489+
```js
490+
const levels = new UIPanel(420, 435, {
491+
width: 340, height: 150,
492+
layout: "grid", columns: 5, gap: 8, padding: 10,
493+
scroll: "vertical", // "horizontal", "both", or "none"
494+
});
495+
```
496+
497+
The content is cropped to the area inside the frame and below the title, and
498+
scrolls with the wheel over the panel and by dragging, with momentum when
499+
flung. A scrollbar shows while it does not fit. `scrollTo(x, y)`,
500+
`scrollToChild(child)`, `scrollX` / `scrollY`, `maxScrollX` / `maxScrollY` and
501+
an `onScroll(x, y, panel)` setting are there to drive it from code.
502+
503+
What to know:
504+
505+
- **Scrolling moves the children.** Their `pos` is where they are drawn, so
506+
it changes as the list scrolls. A child added to a `"none"` layout while
507+
scrolled is placed in content coordinates and moved into view.
508+
- **A drag that starts on a button scrolls the list and cancels the press.**
509+
The button gets `onCancel()` instead of `onRelease()`, and its `onClick`
510+
SETTING is not called. The `onClick()` METHOD already ran on the press, so
511+
a button in a list does its work in the setting: see the next section.
512+
- **A slider in a scrolling panel is dragged, not the panel.** Any widget
513+
that sets `keepsDrag` keeps its drags.
514+
- Children scrolled out of view do not get pointer events. Nested scrolling
515+
panels are not supported yet.
516+
444517
### A pause overlay: `updateWhenPaused` cascades
445518

446519
`state.pause()` stops every world child stepping while rendering carries on, so
@@ -492,6 +565,44 @@ default on a plain `Renderable` — is skipped by the broadphase and receives
492565
nothing. `UISpriteElement` and `UIBaseElement` clear it for you; anything else
493566
you make clickable has to clear it itself.
494567

568+
### A button that does one thing: `UITextButton`
569+
570+
No subclass needed for a single action:
571+
572+
```js
573+
const play = new UITextButton(100, 200, {
574+
text: "Play", // a CSS font by default ("sans-serif")
575+
size: 24, // pixels with a CSS font, a SCALE with a bitmap font
576+
onClick: () => state.change(state.PLAY),
577+
});
578+
```
579+
580+
**`onClick` is called on a COMPLETED click**: pressed and released over the
581+
button, or its `bindKey` pressed and released. A press dragged off the button,
582+
cancelled, or turned into a scroll does not call it, and neither does a
583+
disabled button. The `onClick()` method is different: it runs on the press,
584+
as before, for subclasses.
585+
586+
`font` is a loaded bitmap font's name, drawn with `BitmapText` as before, or
587+
any other name, drawn as a CSS font with `Text`. The label is
588+
`button.label` (`bitmapText` is the old name for it).
589+
590+
**Skinned** from an atlas, drawn as a nine-slice so one image makes a button
591+
of any width:
592+
593+
```js
594+
new UITextButton(0, 0, {
595+
font: "kenpixel", size: 12, text: "Accept", borderWidth: 160,
596+
skin: { atlas, normal: "green_button04", pressed: "green_button05" },
597+
});
598+
```
599+
600+
Pressed art is usually shorter than the normal art. The button draws it
601+
lowered by the difference and moves the label down with it, so it looks
602+
pushed in. `hover` and `disabled` regions are optional. `enabled = false`
603+
draws the `disabled` region, or the button at half opacity, and ignores the
604+
pointer and the key.
605+
495606
### Keyboard shortcuts on a button: `bindKey`
496607

497608
A `UITextButton` can be activated from the keyboard as well as the pointer:
@@ -533,6 +644,60 @@ Three more rules, each with a reason you can feel in a game:
533644
Shortcuts live only while the button is activated, and never start dragging or
534645
tap-and-hold: those stay pointer gestures.
535646

647+
### Checkboxes and radio buttons: `UICheckbox`
648+
649+
```js
650+
const music = new UICheckbox(40, 60, {
651+
labelOn: "Music ON", labelOff: "Music OFF", // or one `label`
652+
checked: settings.music,
653+
onChange: (on) => { settings.music = on; on ? audio.playTrack("theme") : audio.stopTrack(); },
654+
});
655+
```
656+
657+
The label is part of the widget: clicking it toggles the box, and removing
658+
the checkbox takes the label with it. Drawn with primitives by default, or
659+
`skin: { atlas, on, off, disabled? }`.
660+
661+
**Setting `checked` from code does NOT call `onChange`**, nor does
662+
`toggle()`. Only the user does. Restoring saved settings into the widgets
663+
therefore does not re-run the game logic attached to them, so apply what
664+
they stand for yourself after restoring:
665+
666+
```js
667+
music.checked = saved.music; // the look only
668+
applyMusic(saved.music); // the effect, once
669+
```
670+
671+
**Radio buttons** are checkboxes sharing a `group`: exactly one is checked,
672+
clicking the checked one leaves it checked, and they are drawn round. Only
673+
the one the user picked gets `onChange`, as in a web page; read the group with
674+
`UICheckbox.checkedIn("difficulty")`. A checkbox is in its group while it is in
675+
the scene.
676+
677+
### Sliders: `UISlider`
678+
679+
```js
680+
const volume = new UISlider(40, 120, {
681+
label: "Music", showValue: true,
682+
format: (v) => Math.round(v * 100) + "%",
683+
min: 0, max: 1, step: 0.01, value: audio.getVolume(),
684+
length: 300, // orientation: "vertical" too
685+
onChange: (v) => audio.setVolume(v), // every step of the drag
686+
onChangeEnd: () => saveSettings(), // once, on release
687+
});
688+
```
689+
690+
Drag the thumb, or click the track to jump there. The drag follows the
691+
pointer after it leaves the track, until it is released. The mouse wheel over
692+
the slider moves it one `step`. `value` snaps to `step` and clamps to the
693+
range, and setting it does not call `onChange` or `onChangeEnd`: the same rule
694+
as the checkbox. `skin: { atlas, track, fill?, thumb, thumbHover? }` draws it
695+
from art: the track and fill as nine-slices along its length, the thumb at its
696+
own size.
697+
698+
Put work that should not run 60 times a second, such as saving or playing a
699+
test sound, in `onChangeEnd`.
700+
536701
### A fullscreen option
537702

538703
Three methods on the `Application`, not on `device` (they moved there in
@@ -721,6 +886,17 @@ of the level instead, with the scenery drawing over it. Both shipped idioms are
721886
the same rule: afterBurner's HUD sits at `-150`, and the glTF, Billboard, Night
722887
City and Instanced Forest examples park a floating sky at `-10000` or `100000`.
723888

889+
## When the UI misbehaves
890+
891+
| symptom | cause | fix |
892+
|---|---|---|
893+
| loading saved settings plays the music, saves again or fires game logic | the game called its own change handler while restoring | set `checkbox.checked` / `slider.value`, which never call `onChange`, then apply the setting once yourself |
894+
| `onChange` never fires when settings are restored | by design: only user input calls it | apply the restored value yourself |
895+
| a button in a scrolling list fires when the user only meant to scroll | the work is in the `onClick()` METHOD, which runs on the press | use the `onClick` SETTING, called on a completed click; a scroll cancels the press |
896+
| a button scrolled out of a hand-made list still gets clicks | its container does not clip, so the pointer still finds it where it moved to | use `UIPanel`'s `scroll`, or set `clipping` on the container: since 20.13 the pointer skips children outside a clipping container |
897+
| a layout ignores a label that changed size | layout runs on add, remove and resize only | call `panel.relayout()` |
898+
| `new UITextButton` with a font name draws in a plain font | the name is not a loaded bitmap font, so it is drawn as a CSS font | load the bitmap font (image and `.fnt`) under that name, or load the web font |
899+
724900
## Related skills
725901

726902
- `melonjs-scenes-and-state` — `Tween` and the easing families, for animating any of this

‎packages/melonjs/src/index.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,9 @@ import Trail3d from "./renderable/trail3d.js";
5555
import Trigger from "./renderable/trigger.js";
5656
import ProgressBar from "./renderable/ui/progressbar.ts";
5757
import UIBaseElement from "./renderable/ui/uibaseelement.ts";
58+
import UICheckbox from "./renderable/ui/uicheckbox.ts";
5859
import UIPanel from "./renderable/ui/uipanel.ts";
60+
import UISlider from "./renderable/ui/uislider.ts";
5961
import UISpriteElement from "./renderable/ui/uispriteelement.ts";
6062
import UITextButton from "./renderable/ui/uitextbutton.ts";
6163
import Stage from "./state/stage.ts";
@@ -200,7 +202,27 @@ export type {
200202
ProgressBarDirection,
201203
ProgressBarSettings,
202204
} from "./renderable/ui/progressbar.js";
203-
export type { UIPanelSettings } from "./renderable/ui/uipanel.js";
205+
export type {
206+
UICheckboxSettings,
207+
UICheckboxSkin,
208+
} from "./renderable/ui/uicheckbox.js";
209+
export type { UILabel } from "./renderable/ui/uilabel.js";
210+
export type {
211+
UIPanelAlign,
212+
UIPanelLayout,
213+
UIPanelScroll,
214+
UIPanelSettings,
215+
UIPanelSkin,
216+
} from "./renderable/ui/uipanel.js";
217+
export type { UISkin } from "./renderable/ui/uiskin.js";
218+
export type {
219+
UISliderSettings,
220+
UISliderSkin,
221+
} from "./renderable/ui/uislider.js";
222+
export type {
223+
UITextButtonSettings,
224+
UITextButtonSkin,
225+
} from "./renderable/ui/uitextbutton.js";
204226
export * as device from "./system/device.js";
205227
export * as event from "./system/event.ts";
206228
// and the two types it names, so a game can declare a field holding one
@@ -311,7 +333,9 @@ export {
311333
Tween,
312334
timer,
313335
UIBaseElement,
336+
UICheckbox,
314337
UIPanel,
338+
UISlider,
315339
UISpriteElement,
316340
UITextButton,
317341
VignetteEffect,

‎packages/melonjs/src/input/pointerevent.ts‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,28 @@ function triggerEvent(
301301
return false;
302302
}
303303

304+
/**
305+
* Whether a point is outside the visible area of a container above a region.
306+
*
307+
* Asks each ancestor through `clipContains`, which a `Container` answers from
308+
* its own rectangle while `clipping` is on, and a scrolling `UIPanel` from its
309+
* content area. An ancestor without the method never clips.
310+
* @param region - the region being hit-tested
311+
* @param x - the point, in the coordinates of the region's bounds
312+
* @param y - the point, in the coordinates of the region's bounds
313+
* @returns true when some ancestor does not show that point
314+
* @ignore
315+
* @internal
316+
*/
317+
function isClippedOut(region: any, x: number, y: number): boolean {
318+
for (let node = region.ancestor; node != null; node = node.ancestor) {
319+
if (typeof node.clipContains === "function" && !node.clipContains(x, y)) {
320+
return true;
321+
}
322+
}
323+
return false;
324+
}
325+
304326
/**
305327
* propagate events to registered objects
306328
* @ignore
@@ -412,10 +434,15 @@ function dispatchEvent(normalizedEvents: Pointer[]): boolean {
412434
}
413435
}
414436

437+
const hitX =
438+
region.isFloating === true ? pointer.gameX : absoluteWorldX;
439+
const hitY =
440+
region.isFloating === true ? pointer.gameY : absoluteWorldY;
441+
// inside its bounds AND inside every clipping container above
442+
// it: a child scrolled or cropped out of view is not drawn
443+
// there, so it must not answer there either
415444
const eventInBounds =
416-
region.isFloating === true
417-
? bounds.contains(pointer.gameX, pointer.gameY)
418-
: bounds.contains(absoluteWorldX, absoluteWorldY);
445+
bounds.contains(hitX, hitY) && !isClippedOut(region, hitX, hitY);
419446

420447
// Covered by whatever consumed the move above. Being inside its
421448
// own bounds is no longer what decides it, so release the

‎packages/melonjs/src/renderable/container.js‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1527,6 +1527,36 @@ export default class Container extends Renderable {
15271527
return out;
15281528
}
15291529

1530+
/**
1531+
* Whether this container shows its children at a point.
1532+
*
1533+
* Always true unless {@link Container#clipping} is on, in which case only
1534+
* its own rectangle is shown. The pointer asks every container above a
1535+
* region before letting it answer, so a child cropped out of view cannot
1536+
* be clicked where it is not drawn.
1537+
* @param {number} x - the point, in the same coordinates as the bounds of
1538+
* this container (screen pixels for a floating one)
1539+
* @param {number} y - the point
1540+
* @returns {boolean} false where the children are clipped away
1541+
*/
1542+
clipContains(x, y) {
1543+
if (
1544+
this.clipping !== true ||
1545+
this.root === true ||
1546+
!Number.isFinite(this.width) ||
1547+
!Number.isFinite(this.height)
1548+
) {
1549+
return true;
1550+
}
1551+
const origin = this.getAbsolutePosition();
1552+
return (
1553+
x >= origin.x &&
1554+
x < origin.x + this.width &&
1555+
y >= origin.y &&
1556+
y < origin.y + this.height
1557+
);
1558+
}
1559+
15301560
/**
15311561
* draw this renderable (automatically called by melonJS)
15321562
* @param {Renderer} renderer - a renderer instance

0 commit comments

Comments
 (0)