A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(ui): UIToggleGroup — the toggles beneath it are exclusive
yhhe4f9e3ae5831
diff --git a/desktop b/desktopindex bb54f433e..3926af21d 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit bb54f433e7c507025bb1ef6a99981dc0ab15ca9d+Subproject commit 3926af21d581099fa5cf64e67e71ecbdd9d7f073diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex dd39b1698..ebfea6dff 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -98,6 +98,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {UIDropdown: { category: 'ui', summary: 'A dropdown selector: its options and the selected index.', doc: 'ui/widgets', anchor: 'dropdown', anchorZh: 'dropdown-下拉框' },UISlider: { category: 'ui', summary: 'A draggable value along a range, with an optional step.', doc: 'ui/widgets', anchor: 'slider', anchorZh: 'slider-滑块' },UIToggle: { category: 'ui', summary: 'A two-state widget — checkbox or switch — and its group membership.', doc: 'ui/widgets', anchor: 'toggle', anchorZh: 'toggle-开关' },+ UIToggleGroup: { category: 'ui', summary: 'Makes the toggles beneath it exclusive — a radio group or tab bar. Put it on their common ancestor.', doc: 'ui/widgets', anchor: 'toggle', anchorZh: 'toggle-开关' },// ── Physics ────────────────────────────────────────────────────────────────RigidBody2D: { category: 'physics', summary: 'Puts the entity under the flat solver: static, kinematic or dynamic, with damping, gravity scale and sleep.', doc: 'gameplay/physics', anchor: 'rigidbody2d', anchorZh: 'rigidbody2d' },diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex ab9422376..8c6d9ac45 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -4762,6 +4762,18 @@"check"]},+ {+ "name": "UIToggleGroup",+ "source": "ts",+ "fields": [+ {+ "key": "allowSwitchOff",+ "type": "boolean",+ "default": "false",+ "doc": "Let a click turn the selected toggle off, leaving none selected."+ }+ ]+ },{"name": "UIVisual","source": "cpp",diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.tsindex c9ff6ed23..8e2219a3a 100644--- a/sdk/src/core-ui.ts+++ b/sdk/src/core-ui.ts@@ -202,7 +202,9 @@ export {type SliderOptions,type SliderHandle,UIToggle,+ UIToggleGroup,type UIToggleData,+ type UIToggleGroupData,UIDropdown,isDropdownOpen,openDropdown,diff --git a/sdk/src/ui/behavior/plugin.ts b/sdk/src/ui/behavior/plugin.tsindex b5a8fa2ad..900a97272 100644--- a/sdk/src/ui/behavior/plugin.ts+++ b/sdk/src/ui/behavior/plugin.ts@@ -21,7 +21,7 @@ import { UIInteraction, type UIInteractionData } from '../input/interactable';import { getEntityDepth, walkParentChain } from '../util/helpers';import { UIDialog, createDialogSystem } from './dialog';import { UISlider, createSliderSystem } from './slider';-import { UIToggle, createToggleSystem } from './toggle';+import { UIToggle, UIToggleGroup, createToggleSystem } from './toggle';import { UIDropdown, createDropdownSystem } from './dropdown';import { createScrollbarSystem } from './scrollbar';import { registerComponent } from '../../ecs/component';@@ -115,6 +115,7 @@ export class UIBehaviorPlugin implements Plugin {);registerComponent('UIToggle', UIToggle);+ registerComponent('UIToggleGroup', UIToggleGroup);app.addSystemToSchedule(Schedule.Update,createToggleSystem(world, events),diff --git a/sdk/src/ui/behavior/toggle.ts b/sdk/src/ui/behavior/toggle.tsindex 3753da59d..9787fec67 100644--- a/sdk/src/ui/behavior/toggle.ts+++ b/sdk/src/ui/behavior/toggle.ts@@ -4,6 +4,8 @@* @file ui/behavior/toggle.ts* @brief UIToggle — data-driven on/off state.*+ * A group makes them exclusive: UIToggleGroup on a common ancestor.+ ** The component IS the state (`isOn` + the check-indicator entity ref); the* system flips it on click and is the single writer of the check visual. Any* writer — the pointer, `setValue`, a binding, the editor inspector — shows@@ -17,7 +19,7 @@ import type { Entity } from '../../types';import { setUIVisible } from '../core/compose';import { Interactable, type InteractableData } from '../input/interactable';import { UIEventType, type UIEventQueue } from '../core/events';-import { EntityStateMap } from '../util/helpers';+import { EntityStateMap, walkParentChain } from '../util/helpers';export interface UIToggleData {isOn: boolean;@@ -30,6 +32,46 @@ export const UIToggle = defineComponent<UIToggleData>('UIToggle', {check: 0 as Entity,}, { entityFields: ['check'] });+export interface UIToggleGroupData {+ /** Whether the group may end up with nothing selected. */+ allowSwitchOff: boolean;+}++/**+ * Makes the UIToggles beneath it exclusive — a radio group, a tab bar, a+ * difficulty picker. Sits on the COMMON ANCESTOR, like FlexContainer, so the+ * toggles need no reference to each other or to it.+ */+export const UIToggleGroup = defineComponent<UIToggleGroupData>('UIToggleGroup', {+ allowSwitchOff: false,+}, {+ fields: {+ allowSwitchOff: { tooltip: 'Let a click turn the selected toggle off, leaving none selected.' },+ },+});++/** The nearest ancestor that groups this toggle, or 0 when it is on its own. */+function groupOf(world: World, entity: Entity): Entity {+ let group = 0 as Entity;+ walkParentChain(world, entity, (ancestor) => {+ if (!world.has(ancestor, UIToggleGroup)) return false;+ group = ancestor;+ return true;+ });+ return group;+}++/** Turn off every other toggle the same group owns. */+function clearSiblings(world: World, group: Entity, keep: Entity): void {+ for (const other of world.getEntitiesWithComponents([UIToggle])) {+ if (other === keep) continue;+ const d = world.get(other, UIToggle) as UIToggleData;+ if (!d.isOn || groupOf(world, other) !== group) continue;+ d.isOn = false;+ world.insert(other, UIToggle, d);+ }+}+/** Flips on click; syncs `isOn` → check visibility; emits `change`. */export function createToggleSystem(world: World, events: UIEventQueue): SystemDef {const shown = new EntityStateMap<boolean>(); // last isOn whose visual was applied@@ -42,8 +84,14 @@ export function createToggleSystem(world: World, events: UIEventQueue): SystemDeif (world.has(e, Interactable)&& !(world.get(e, Interactable) as InteractableData).enabled) return;const d = world.get(e, UIToggle) as UIToggleData;+ const group = groupOf(world, e);+ // A group that must keep a selection ignores a click on the selected+ // one; otherwise the tab bar can be clicked into showing nothing.+ if (group && d.isOn+ && !(world.get(group, UIToggleGroup) as UIToggleGroupData).allowSwitchOff) return;d.isOn = !d.isOn;world.insert(e, UIToggle, d);+ if (group && d.isOn) clearSiblings(world, group, e);});return defineSystem([], () => {diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.tsindex 465d49cf4..c40a3329e 100644--- a/sdk/src/ui/index.ts+++ b/sdk/src/ui/index.ts@@ -136,8 +136,10 @@ export {export {UIToggle,+ UIToggleGroup,createToggleSystem,type UIToggleData,+ type UIToggleGroupData,} from './behavior/toggle';export {diff --git a/sdk/tests/ui-toggle-group.test.ts b/sdk/tests/ui-toggle-group.test.tsnew file mode 100644index 000000000..d4e644fdc--- /dev/null+++ b/sdk/tests/ui-toggle-group.test.ts@@ -0,0 +1,116 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file UIToggleGroup — the toggles beneath one ancestor are exclusive.+ *+ * The group sits on a common ancestor rather than on the toggles, so these+ * drive a world that really carries `Parent`: the rule is "nearest ancestor+ * that groups me", and a mock without a hierarchy cannot tell it apart from+ * "every toggle in the world".+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { Parent } from '../src/ecs/component';+import { UIToggle, UIToggleGroup, createToggleSystem } from '../src/ui/behavior/toggle';+import { UIEventQueue, UIEventType } from '../src/ui/core/events';+import type { Entity } from '../src/types';+import type { World } from '../src/ecs/world';++function createWorld() {+ const comps = new Map<number, Map<object, unknown>>();+ let next = 1;+ const w = {+ spawn(): Entity { const e = next++; comps.set(e, new Map()); return e as Entity; },+ valid(e: Entity) { return comps.has(e as number); },+ has(e: Entity, c: object) { return comps.get(e as number)?.has(c) ?? false; },+ get(e: Entity, c: object) { return comps.get(e as number)?.get(c); },+ insert(e: Entity, c: object, d: unknown) { comps.get(e as number)?.set(c, d); },+ getEntitiesWithComponents(cs: object[]): Entity[] {+ return [...comps.entries()]+ .filter(([, m]) => cs.every(c => m.has(c)))+ .map(([e]) => e as Entity);+ },+ onDespawn() { return () => {}; },+ };+ return w as unknown as World & typeof w;+}++/** A toggle under `parent`, with a check entity so the system has one to show. */+function addToggle(w: ReturnType<typeof createWorld>, parent: Entity, isOn: boolean): Entity {+ const e = w.spawn();+ w.insert(e, Parent, { entity: parent });+ w.insert(e, UIToggle, { isOn, check: w.spawn() });+ return e;+}++describe('UIToggleGroup', () => {+ let world: ReturnType<typeof createWorld>;+ let events: UIEventQueue;+ let tick: () => void;++ beforeEach(() => {+ world = createWorld();+ events = new UIEventQueue();+ const sys = createToggleSystem(world as unknown as World, events);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ tick = () => (sys as any)._fn();+ });++ const isOn = (e: Entity) => (world.get(e, UIToggle) as { isOn: boolean }).isOn;++ it('turns the others off when one is clicked', () => {+ const group = world.spawn();+ world.insert(group, UIToggleGroup, { allowSwitchOff: false });+ const a = addToggle(world, group, true);+ const b = addToggle(world, group, false);+ const c = addToggle(world, group, false);+ tick();++ events.emit(b, UIEventType.Click);+ expect([isOn(a), isOn(b), isOn(c)]).toEqual([false, true, false]);+ });++ // Without this a tab bar can be clicked into showing no tab at all.+ it('keeps the selected one on when the group requires a selection', () => {+ const group = world.spawn();+ world.insert(group, UIToggleGroup, { allowSwitchOff: false });+ const a = addToggle(world, group, true);+ tick();++ events.emit(a, UIEventType.Click);+ expect(isOn(a)).toBe(true);+ });++ it('lets the selected one switch off when the group allows it', () => {+ const group = world.spawn();+ world.insert(group, UIToggleGroup, { allowSwitchOff: true });+ const a = addToggle(world, group, true);+ tick();++ events.emit(a, UIEventType.Click);+ expect(isOn(a)).toBe(false);+ });++ // The rule is the NEAREST grouping ancestor, not "every toggle there is".+ it('does not reach across into another group', () => {+ const left = world.spawn();+ const right = world.spawn();+ world.insert(left, UIToggleGroup, { allowSwitchOff: false });+ world.insert(right, UIToggleGroup, { allowSwitchOff: false });+ const a = addToggle(world, left, true);+ const b = addToggle(world, right, true);+ tick();++ events.emit(b, UIEventType.Click);+ expect(isOn(a)).toBe(true); // b was already on; a is another group's business+ });++ it('leaves an ungrouped toggle free to flip on its own', () => {+ const plain = world.spawn();+ const a = addToggle(world, plain, true);+ const b = addToggle(world, plain, true);+ tick();++ events.emit(a, UIEventType.Click);+ expect([isOn(a), isOn(b)]).toEqual([false, true]);+ });+});