# Prebuilt Interaction Widgets — bundled `ui-component-package`

Reusable mlua interaction widgets from the official MSWPackages `ui-component-package` (MIT), **bundled in this skill under `assets/widgets/`** — no network access needed. Some scripts carry fixes for upstream defects (text nodes read via `TextGUIRendererComponent` so labels render in a `.ui`, number pad multi-digit entry); copy the bundled sources rather than re-fetching the package. Use these instead of hand-building interaction patterns that native components don't cover: checkbox / radio / switch / toggle groups, dropdowns, pagination, progress bars, scroll pickers, time picker, number pad.

**When NOT to use**: a plain click button (`ButtonComponent`), a plain value slider (`SliderComponent`), plain text input (`TextInputComponent`) — native components already cover those; see `msw-ui-system` `references/component-api.md`. Likewise, for a trivial one-off behavior (one on/off toggle on one screen), a ~30-line custom component you write in place beats integrating a whole widget family — integrate when the widget's state logic (groups, inertia, pagination math) or reuse across screens earns it.

---

## Integration (once per project)

1. Copy from this skill's `assets/widgets/`:
   - `UIComponent/<Family>/**/*.mlua` → `RootDesk/MyDesk/UIComponent/<Family>/` (keep folder structure and **script names unchanged**); `UITimePicker` also needs the `UICompoundButton` and `UIScrollPicker` families
   - `Util/Util.mlua` → `RootDesk/MyDesk/Util/` — the `Util` Logic whose `IsNilorEmptyString` the `UICompoundButton` family and `UISlider` call; when the workspace already has its own `Util` Logic, add that method to it in place of copying
   - `.mlua` only; `.codeblock` files are generated by Maker Refresh.
2. Build the widget's entity tree with the `msw-ui-system` UIBuilder, following the structure digest in `assets/widgets/trees/<Family>/<Model>.txt` (entity names, nesting, component layout) — but skin it with **your chosen theme's parts** from `references/themes/<theme>.md`, not the digest's original RUIDs. Attach the widget script component to the root node the digest shows it on.
3. Maker Refresh, then drive the widget from your own ClientOnly script (all widget scripts are `@ExecSpace("ClientOnly")`).

> First refresh after copying a whole family can report a burst of unresolved-type errors on the scripts' own types (`UICompoundButton`, `*StyleStruct`, …). This is a first-registration ordering artifact, not a source defect. Re-running Refresh alone does nothing (no change → skipped); **touch one of the referencing `.mlua` files, then Refresh again**. Never "fix" it by weakening the type annotations to `any`/`Entity` or by deleting `Style/` — that trades permanent type safety for a transient.

## Property binding — two widget groups

**A. Auto-bind by child entity name** — `Init()` falls back to `GetChildByName(...)`; matching the names below in your tree is enough:

| Widget | Required child names |
|---|---|
| `UIProgressBar` (+Filled/Resizable) | `Img_Value`, `Img_BackValue`, `Text` |
| `UIDropdown` | `Btn`, `GridView`, `Item`, `Img_Outline`, `Img_Icon` |
| `UIMultiSelectDropdown` | + `Img_Dim`; item: `Img_Check` |
| `UIHorizontalSelector` | `Text`, `ScrollLayout`, `Item`, `Btn_Prev`, `Btn_Next` |
| `UIPagination` (+Fixed/Centered) | `ScrollLayout`, `Item`, `First`, `Last`, `Prev`, `Next`; item: `Default`, `Selected` |
| `UIScrollPicker` family | `Viewport` (**must carry a `MaskComponent`**), `Item`; item: `Text` |
| `UISlider` | `Slider`, `Text` |
| `UITimePicker` | `HourPicker`, `MinutePicker`, `SecondPicker`, `MeridiemButtonGroup` (**`Btn_Am`/`Btn_Pm` are group-B — see below**) |
| `UILoadingSpinner` | `Img_Rotation` |

Every `Text`-ish child above must be a text node created by the UIBuilder's `text()` (i.e. carrying `TextGUIRendererComponent`). A `TextComponent` node — what `.model`-authored trees use — is a *sibling* type, not a base class, so the widget reads `nil` and the label silently never renders.

An unmasked `UIScrollPicker` `Viewport` fails the same silent way in the other direction: `Init` spawns `floor(viewportH/itemH)+4` items spread across ±(n//2)×itemH, and without clipping they scatter across the screen over neighbouring widgets — no error, no log, invisible to lint because the nodes are runtime-spawned.

**B. Explicit property binding required** — no name fallback; set the component's entity/component properties yourself (via `b.write(path, { bind: {...} })` binding injection or the Maker inspector). **The names in parentheses are property names, not required child names** — group-B child entities can be named anything:

- `UICompoundButton` family: `UICheckBox` (`Mark`, `Frame`, `Outline1`, `Outline2`), `UIRadioButton` (`Dot`, `Frame`, `Outline`), `UISwitch` (`Track`, `Handle`), `UIToggle` (`Frame`, `Outline`), `UIEntityToggle` (`OnStateEntity`/`OffStateEntity` + their `ButtonComponent`s), plus `Label` / `ButtonGroup` on all of them
- `UINumberPadInput`: every `Btn_*` / `Text_*` / `Slider` property
- `UITimePicker`'s `Btn_Am` / `Btn_Pm` — the one group-A widget with a group-B hole. Its other children fall back by name, but AM/PM does not; leave them unset and 12-hour mode dies with no warning. Inject both entity and component properties, then call `RegisterButton` on the meridiem group yourself.

The `trees/` digests show which node each property should point at (e.g. `UISwtich1`: root `[UISwitch] BTN` → `Img_Track` → nested `Img_Handle`).

---

## Widget catalog

### Compound buttons — `UICompoundButton` family
Base `UICompoundButton` (on/off state machine: `IsOn`, `SetIsOn(v, sendCallback)`, `SetIsOnWithoutNotify`, `Toggle()`, `SetInteractable`, optional `SoundRUID`) with variants:
- **`UICheckBox`** — check mark + frame + outline sprites, per-state colors.
- **`UIRadioButton`** — dot + frame + outline, per-state colors.
- **`UISwitch`** — sliding handle on a track (`Img_Track`/`Img_Handle`), `HandleOffsetX`.
- **`UIToggle`** — frame/outline color-swap toggle.
- **`UIEntityToggle`** — swaps two whole entities (`OnStateEntity`/`OffStateEntity`), each with its own `ButtonComponent`.

**`UICompoundButtonGroup`** — put on a parent entity, assign each button's `ButtonGroup` property: radio-group behavior (`AllowAllOff`, `AllowMultipleSelection`, `MaxSelectionCount`), query via `GetActiveButton()` / `GetActiveButtons()`, bulk `SelectAllButtons` / `DeselectAllButtons`.

Structure digests: `assets/widgets/trees/UICompoundButton/{UICheckBox,UIRadioButton,UISwitch,UIToggle,UIEntityToggle}/…` (3+ visual variants each — pick one as the tree blueprint, skin with theme parts).

### Dropdown — `UIDropdown`, `UIMultiSelectDropdown`
Single/multi-select dropdown backed by a GridView list. API: `SetDataList(table)`, `SetSelectedIndex(i, sendCallback)`, `GetSelectedData()` (multi: `GetSelectedDataList()`), `OpenDropdown()` / `CloseDropdown()`, `PlaceHolder`, `DropdownDirection` (0=BOTTOM 1=TOP 2=CENTER via `UIDropdownDirectionEnum`), `IsShowAll`, custom text callbacks `OnRefreshText` / `OnRefreshButtonText`. Multi-select adds a dim overlay + per-item check marks.

### Horizontal selector — `UIHorizontalSelector`
Prev/next arrows cycling a string list (`SetStringList`, `Prev()` / `Next()`, `SetSelectedIndex(i, useAnim)`, `GetString()`, `IsLoop`, optional page-dot indicator with select/deselect colors). Good for option rows in settings screens.

### Pagination — `UIPagination` / `UIFixedPagination` / `UICenteredPagination`
Page-number button strip with First/Last/Prev/Next. `SetPage(n)`, `SetTotalPages(n)`, `SetPageAndTotalPages(n, total)`. Variants: **Fixed** = block paging (`BlockSize`, e.g. 1–5 / 6–10), **Centered** = current page centered with ellipsis (`TotalPagesToShow`, `OuterPagesToShow`, `UseEllipsis`). Emits `UIPaginationItemClickedEvent`.

### Progress bar — `UIProgressBar` → `UIFilledProgressBar` / `UIResizableProgressBar`
`Value` / `MaxValue`, text render modes (`RenderTextType` 0=percent 1=cur/max 2=cur), optional tween animation. **Filled** drives `FillAmount` (needs `ImageType.Filled` sprite); **Resizable** resizes the fill sprite's width. Children by name: `Img_Value`, `Img_BackValue`, `Text`.

### Scroll picker — `UIScrollPicker` → `UIScrollValuePicker` / `UIScrollRangeNumberPicker`
Drag/inertia wheel picker (slot-machine style). Value picker: `SetDataValueList(list)`, `SetValue(v)`. Range-number picker: `SetValueRange(min, max, gap)`, `RenderPrecision`. Tuning: `IsLoop`, `DragSensitivity`, `UseInertia`, selected/deselected text colors. Emits `UIScrollPickerValueChangedEvent`.

### Time picker — `UITimePicker`
Composite of 3 `UIScrollRangeNumberPicker`s (hour/minute/second) + AM/PM `UICompoundButtonGroup`. `SetTime(h, m, s, sendCallback)` / `SetTime12h(…, isPm, …)`, `Is24Hour`. Emits `UITimePickerValueChangedEvent`.

### Number pad input — `UINumberPadInput`
Full numeric entry popup: digit buttons 0–9, +/−, min/max/clear, slider sync. `Open(value, minValue, maxValue, enterCallback, closeCallback)`, `SetValue(v)`. Callbacks are functions, not events. Digits accumulate in a typing buffer and a keystroke that would exceed `MaxValue` is ignored, so the displayed number always equals what was typed. Note two name collisions in this widget: the `Clear` **button** restores `DefaultValue` (it does not zero the field), and the `Clear()` **method** closes the pad and releases callbacks.

### Slider text helper — `UISlider`
Thin wrapper over native `SliderComponent` that renders the value into a `Text` child (`Multiplier`, `RenderPrecision`, `RenderPostfixStr`, `SetMinMaxValue`). Use only when you need the value label; otherwise use native `SliderComponent` directly.

### Loading spinner — `UILoadingSpinner`
Rotates the `Img_Rotation` child every `Interval` seconds by `RotationAngle`. Use any circular glyph from your theme (e.g. a `Tint_*` ring) as the rotating sprite.

---

## Events

Widgets dispatch custom event types **on their own entity** via `entity:SendEvent(event)`:

| Event | Fields | Sent by |
|---|---|---|
| `UICompoundButtonValueChangedEvent` | `Entity`, `Value` (bool) | every compound button |
| `UICompoundButtonGroupValueChangedEvent` | `Entity` | button group |
| `UIDropdownValueChangedEvent` | `Entity` | dropdown (both) |
| `UIHorizontalSelectorIndexChangedEvent` | `Entity` | horizontal selector |
| `UIPaginationItemClickedEvent` | page info | pagination |
| `UIScrollPickerValueChangedEvent` | value info | scroll pickers |
| `UITimePickerValueChangedEvent` | time info | time picker |

Listen with an entity-scoped handler in your own component on (or attached to) the widget entity, e.g. `@EventSender("Self")` handler for the event type, or connect from a parent script.

---

## Styles (compound buttons only)

`SetStyle(styleName)` looks up named style structs registered in the `UICompoundButtonStyleLogic` Logic by `UIStyle*` components. The style-struct scripts are bundled (`UICompoundButton/Style/*.mlua`) but no pre-registered style entities are — you would have to author registration entities yourself. Default posture: skip the style system and set colors/sprites directly on the widget properties (theme-driven anyway).

---

## Pitfalls

- **ClientOnly everywhere** — never touch widget components from server space; values are client-local. Sync selections to server explicitly via your own RPC if gameplay depends on them.
- **`Init()` runs on `OnBeginPlay`** — if you call widget APIs immediately after spawn in the same frame, call `Init()` yourself first (it is idempotent via `IsInitialized`).
- **Binding group confusion** — group A widgets bind by exact child names (table above; renaming silently breaks them), group B widgets bind nothing automatically (a visually perfect tree still does nothing until properties are injected). Check the group before wiring.
- **Required names cut both ways** — if you skin the UI by walking entity names (a `Bg_*` / `Btn_*` prefix convention, say), widget internals are locked to names like `ScrollLayout` / `Item` / `First` / `Default` that carry no such prefix, so your painter walks straight past them: no error, the widget just never takes the theme. You cannot rename them out of the problem — that breaks the binding. Keep an explicit name-to-role map for each widget family instead of relying on the naming convention.
- **A widget owns its parts' colors** — every compound button rewrites `Color` on its mark/dot/track/handle/frame from its own `*ActiveColor` / `*InactiveColor` properties on each state change, and scroll-picker items rewrite `FontColor` from the picker's selected/deselected colors. Their defaults are opaque white, so a theme color painted onto the node itself survives exactly until the first interaction. Put theme colors in the **widget properties**, not on the child nodes, and force one reapply after injecting them (`UpdateVisualState(false)` / `SetSelected(state, true)`).
- **Keep script names** — the widget scripts reference each other by type name (e.g. `UITimePicker` holds `UIScrollRangeNumberPicker` properties); renaming any bundled `.mlua` breaks the family.
