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.6 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    ui/core/compose.ts
 * @brief   Composition sugar over the Layer-1 primitives: build full component
 *          literals from sparse inits, and spawn a UI entity in one call.
 *
 * Lives in core (not widgets) because everything that assembles UI needs it —
 * widget factories, the text-input plugin, and behavior systems that build
 * transient subtrees (a dropdown popup). Pure over L1 components only.
 */
import {
    Transform,
    mergeIntoDefaults,
    type TransformData,
} from '../../ecs/component';
import type { Entity, Vec2 } from '../../types';
import type { World } from '../../ecs/world';

import { UINode, UIPositionType, UIDisplay, UIPointerEvents, type UINodeData } from './ui-node';
import { px, auto, type Dimension } from './dimension';
import { UIVisual, UIVisualType, UIVisualFit, FillMethod, FillOrigin, type UIVisualData } from './ui-visual';
import { Text, TextAlign, TextVerticalAlign, type TextData } from './text';

/** Identity Transform. Fresh object per call — safe to insert into ECS. */
export function identityTransform(): TransformData {
    return {
        position: { x: 0, y: 0, z: 0 },
        rotation: { w: 1, x: 0, y: 0, z: 0 },
        scale: { x: 1, y: 1, z: 1 },
        worldPosition: { x: 0, y: 0, z: 0 },
        worldRotation: { w: 1, x: 0, y: 0, z: 0 },
        worldScale: { x: 1, y: 1, z: 1 },
    };
}

export interface UINodeInit {
    /** Stretch to fill the parent (absolute + inset 0 on all edges). */
    fill?: boolean;
    /** UIPositionType: Relative (flex flow) or Absolute (placed by inset). */
    position?: number;
    /** Subtree opacity (CSS `opacity`), multiplied down the tree. */
    opacity?: number;
    /** UIPointerEvents: None makes this node and its subtree click-through. */
    pointerEvents?: number;
    width?: Dimension;
    height?: Dimension;
    insetLeft?: Dimension;
    insetTop?: Dimension;
    insetRight?: Dimension;
    insetBottom?: Dimension;
    flexGrow?: number;
    flexShrink?: number;
    marginLeft?: Dimension;
    marginTop?: Dimension;
    marginRight?: Dimension;
    marginBottom?: Dimension;
}

/**
 * Build a UINode (CSS box). `fill: true` is the common widget case
 * (stretch to the parent); otherwise set width/height and/or inset. Anchoring
 * (e.g. top-right) = position Absolute + the relevant insets.
 */
export function buildUINode(init: UINodeInit = {}): UINodeData {
    const fill = init.fill ?? false;
    return {
        position: init.position ?? (fill ? UIPositionType.Absolute : UIPositionType.Relative),
        display: UIDisplay.Flex,
        opacity: init.opacity ?? 1,
        pointerEvents: init.pointerEvents ?? UIPointerEvents.Auto,
        width: init.width ?? auto(),
        height: init.height ?? auto(),
        minWidth: auto(),
        minHeight: auto(),
        maxWidth: auto(),
        maxHeight: auto(),
        flexGrow: init.flexGrow ?? 0,
        flexShrink: init.flexShrink ?? 1,
        flexBasis: auto(),
        alignSelf: 0,
        marginLeft: init.marginLeft ?? px(0),
        marginTop: init.marginTop ?? px(0),
        marginRight: init.marginRight ?? px(0),
        marginBottom: init.marginBottom ?? px(0),
        insetLeft: init.insetLeft ?? (fill ? px(0) : auto()),
        insetTop: init.insetTop ?? (fill ? px(0) : auto()),
        insetRight: init.insetRight ?? (fill ? px(0) : auto()),
        insetBottom: init.insetBottom ?? (fill ? px(0) : auto()),
    };
}

export interface UIVisualInit {
    visualType?: UIVisualType;
    texture?: number;
    color?: { r: number; g: number; b: number; a: number };
    /** CSS `object-fit` (UIVisualFit). Default Fill. */
    fit?: UIVisualFit;
    uvOffset?: Vec2;
    uvScale?: Vec2;
    sliceBorder?: { x: number; y: number; z: number; w: number };
    tileSize?: Vec2;
    fillMethod?: FillMethod;
    fillOrigin?: FillOrigin;
    fillAmount?: number;
    material?: number;
    enabled?: boolean;
}

export function buildUIVisual(init: UIVisualInit = {}): UIVisualData {
    return {
        visualType: init.visualType ?? UIVisualType.SolidColor,
        texture: init.texture ?? 0,
        color: init.color ?? { r: 1, g: 1, b: 1, a: 1 },
        fit: init.fit ?? UIVisualFit.Fill,
        uvOffset: init.uvOffset ?? { x: 0, y: 0 },
        uvScale: init.uvScale ?? { x: 1, y: 1 },
        sliceBorder: init.sliceBorder ?? { x: 0, y: 0, z: 0, w: 0 },
        tileSize: init.tileSize ?? { x: 32, y: 32 },
        fillMethod: init.fillMethod ?? FillMethod.Horizontal,
        fillOrigin: init.fillOrigin ?? FillOrigin.Left,
        fillAmount: init.fillAmount ?? 1,
        material: init.material ?? 0,
        enabled: init.enabled ?? true,
    };
}

/** The edge a partial fill grows toward, for widgets built on `Filled`. */
export type LinearFillDirection = 'right' | 'left' | 'up' | 'down';

/**
 * direction → the `Filled` visual's crop axis + anchor edge (grows along
 * `direction`, cropped from the opposite edge). The one canonical table for
 * progress, slider, and future Filled widgets.
 */
export const FILL_AXIS: Record<LinearFillDirection, readonly [FillMethod, FillOrigin]> = {
    right: [FillMethod.Horizontal, FillOrigin.Left],
    left: [FillMethod.Horizontal, FillOrigin.Right],
    up: [FillMethod.Vertical, FillOrigin.Bottom],
    down: [FillMethod.Vertical, FillOrigin.Top],
};

export interface TextInit extends Partial<TextData> {}

/**
 * Where a composed label differs from a bare `Text`: a widget's caption sits
 * centred in its box on one line at 14px, while an authored `Text` starts as a
 * top-left paragraph. Everything else is the component's own default.
 */
const COMPOSED_TEXT_DEFAULTS: Partial<TextData> = {
    fontSize: 14,
    align: TextAlign.Center,
    verticalAlign: TextVerticalAlign.Middle,
    wordWrap: false,
};

/**
 * Build a full `Text` from a sparse init. It goes through the component's own
 * `create`, so every field of `TextData` - one added later included - is taken
 * from the init when given and from the component's defaults when not; nested
 * records (colours, the box pivot) are fresh copies, never the caller's object.
 */
export function buildText(init: TextInit = {}): TextData {
    return Text.create(mergeIntoDefaults(COMPOSED_TEXT_DEFAULTS, init));
}

export interface UIEntityInit {
    world: World;
    parent?: Entity;
    /** CSS-box layout (defaults to fill the parent). */
    node?: UINodeInit;
    visual?: UIVisualInit;
    text?: TextInit;
}

/**
 * Spawn a UI entity — Transform and UINode always, UIVisual and Text when the
 * init asks for them, parented when it names a parent. Every built-in widget is
 * composed from this, so a hand-built node and a widget are the same thing.
 *
 * @beta
 */
export function spawnUIEntity(init: UIEntityInit): Entity {
    const { world } = init;
    const entity = world.spawn();

    world.insert(entity, Transform, identityTransform());
    world.insert(entity, UINode, buildUINode(init.node));

    if (init.visual) {
        world.insert(entity, UIVisual, buildUIVisual(init.visual));
    }
    if (init.text) {
        world.insert(entity, Text, buildText(init.text));
    }
    if (init.parent !== undefined) {
        world.setParent(entity, init.parent);
    }

    return entity;
}

/**
 * Toggle visibility of a UI entity via UIVisual.enabled. Safe if the
 * entity has no UIVisual — no-op in that case.
 */
export function setUIVisible(world: World, entity: Entity, visible: boolean): void {
    if (!world.valid(entity) || !world.has(entity, UIVisual)) return;
    const r = world.get(entity, UIVisual) as UIVisualData;
    if (r.enabled !== visible) {
        r.enabled = visible;
        world.insert(entity, UIVisual, r);
    }
}