Skip to content

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.

7.2 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { Color, Entity } from '../../types';
import type { World } from '../../ecs/world';

import { Interactable, type InteractableData } from '../input/interactable';
import {
    UIController,
    INTERACTION_CONTROLLER,
    INTERACTION_PAGES,
    interactionController,
    type UIControllerData,
} from '../controller/ui-controller';
import { UIGear } from '../controller/ui-gear';
import { interactionGears, type ButtonStateVisual } from '../controller/interaction-gears';
import { UIEventType, type UIEventQueue } from '../core/events';
import { themeColors, themeType } from '../theme/tokens';
import { markThemed } from '../theme/theme-style';

import { spawnUIEntity, type UINodeInit, type UIVisualInit, type TextInit } from '../core/compose';
import { makeWidgetInteractable } from '../input/interactable';
import { onGestureClick, takeGestureFired } from '../input/gestureClick';

export type { ButtonStateVisual };

export interface ButtonOptions {
    world: World;
    events: UIEventQueue;
    parent?: Entity;
    /** CSS-box layout. Default: fill the parent. */
    node?: UINodeInit;
    /** Background renderer config. Default: solid white quad. */
    background?: UIVisualInit;
    /** Label text. Omit to skip spawning a child label entity. */
    text?: string | TextInit;
    /**
     * Map of state name (e.g. "normal", "hover", "pressed", "disabled")
     * to its visual override. The `$interaction` driver writes the four
     * canonical state names; callers may add more (e.g. "loading") and
     * flip them manually via `setButtonState`. Omit to default to the
     * active theme's control roles ({@link themeButtonStates}).
     */
    states?: Record<string, ButtonStateVisual>;
    /** Tween time for color/scale state changes. Default 0 (snap). */
    fadeDuration?: number;
    /** Start in the disabled state (Interactable.enabled = false). */
    disabled?: boolean;
    /** Participate in Tab traversal + Enter/Space activation. Default true. */
    focusable?: boolean;
    /** Tab order within the focus ring. Default 0 (document order). */
    tabIndex?: number;
    onClick?: (entity: Entity) => void;
    /** Run `onClick` inside the host's own release event rather than on the next
     *  frame, for a call a host accepts only from a player's gesture (sharing a
     *  recording on WeChat). */
    userGesture?: boolean;
}

export interface ButtonHandle {
    readonly entity: Entity;
    setDisabled(disabled: boolean): void;
    dispose(): void;
}

/** The canonical button state colors from the active theme's control roles —
 *  `createButton`'s default when the caller passes no `states`. `disabled` reuses
 *  the resting control fill at reduced alpha. */
export function themeButtonStates(): Record<string, ButtonStateVisual> {
    const c = themeColors();
    return {
        normal: { color: c.control },
        hover: { color: c.controlHover },
        pressed: { color: c.controlActive },
        disabled: { color: { ...c.control, a: c.control.a * 0.5 } },
        // Keyboard focus reads as hover — there is no ring primitive (yet).
        focused: { color: c.controlFocus },
    };
}

/**
 * Spawn a clickable button entity composed of Interactable + a `$interaction`
 * UIController + UIGear state bindings, optionally with a child Text label.
 *
 * Click comes straight from the interaction layer's `click` event (released
 * while still over the button); the handler is gated on Interactable.enabled.
 */
export function createButton(opts: ButtonOptions): ButtonHandle {
    const { world, events } = opts;

    const entity = spawnUIEntity({
        world,
        parent: opts.parent,
        node: opts.node ?? { fill: true },
        visual: opts.background ?? {},
    });

    makeWidgetInteractable(world, entity, {
        disabled: opts.disabled,
        focusable: opts.focusable,
        tabIndex: opts.tabIndex,
    });

    const states = opts.states ?? themeButtonStates();
    // Canonical pages first (the driver's vocabulary), then any custom states
    // (e.g. "loading") so setButtonState can flip to them.
    const pages = [
        ...INTERACTION_PAGES,
        ...Object.keys(states).filter((s) => !(INTERACTION_PAGES as readonly string[]).includes(s)),
    ];
    const ctrl = interactionController(pages);
    ctrl.current = opts.disabled ? 'disabled' : 'normal';
    world.insert(entity, UIController, { controllers: [ctrl] });
    world.insert(entity, UIGear, { bindings: interactionGears(states, opts.fadeDuration ?? 0) });

    // Only theme-managed default states re-resolve on a theme swap; caller-supplied
    // colors are the caller's own.
    if (opts.states === undefined) {
        markThemed(world, entity, {
            states: {
                normal: 'control', hover: 'controlHover', pressed: 'controlActive',
                disabled: 'control', focused: 'controlFocus',
            },
        });
    }

    if (opts.text !== undefined) {
        const userText = typeof opts.text === 'string' ? { content: opts.text } : opts.text;
        // Theme-default the label's color + size; the caller's fields win.
        const textInit = { color: themeColors().text, fontSize: themeType().label, ...userText };
        const label = spawnUIEntity({
            world,
            parent: entity,
            node: { fill: true },
            text: textInit,
        });
        if (userText.color === undefined) markThemed(world, label, { text: 'text' });
    }

    let offClick: (() => void) | undefined;
    let offGesture: (() => void) | undefined;
    if (opts.onClick) {
        const handler = opts.onClick;
        if (opts.userGesture) offGesture = onGestureClick(world, entity, () => handler(entity));
        offClick = events.on(entity, UIEventType.Click, () => {
            if (opts.userGesture && takeGestureFired(world, entity)) return;
            const interactable = world.get(entity, Interactable) as InteractableData;
            if (interactable.enabled) handler(entity);
        });
    }

    return {
        entity,
        setDisabled: (disabled: boolean) => {
            if (!world.valid(entity)) return;
            const i = world.get(entity, Interactable) as InteractableData;
            if (i.enabled !== !disabled) {
                i.enabled = !disabled;
                world.insert(entity, Interactable, i);
            }
        },
        dispose: () => {
            offClick?.();
            offGesture?.();
            if (world.valid(entity)) world.despawn(entity);
        },
    };
}

/**
 * Imperatively set a button's `$interaction` page. Useful for custom states
 * like "loading" that the pointer driver does not manage — the driver leaves
 * any non-canonical page alone until user code switches back.
 */
export function setButtonState(world: World, entity: Entity, state: string): void {
    if (!world.has(entity, UIController)) return;
    const data = world.get(entity, UIController) as UIControllerData;
    const ctrl = data.controllers.find((c) => c.name === INTERACTION_CONTROLLER);
    if (!ctrl || ctrl.current === state) return;
    if (!ctrl.pages.includes(state)) ctrl.pages.push(state);
    ctrl.current = state;
    world.insert(entity, UIController, data);
}