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): drag & touch scrolling with kinetic fling for scroll containers
yhhda15ff1c7bdc
diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex 9a3f4f3f1..1b0bf0831 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -193,8 +193,44 @@ async function runScreenshot(w: BrowserWindow, out: string): Promise<void> {if (err) console.log('[play] error:', err);await settleFrames(30); // let the game loop run so animation/assets settle}+ // Pointer-drag gesture inside the PLAY REALM ("x0,y0,x1,y1" in play-canvas+ // px). The play iframe is estella:// — cross-origin to the editor, so+ // neither SHOT_EVAL (renderer, same-origin only) nor sendInputEvent+ // (doesn't route into OOPIFs) can reach it. The main process CAN: target+ // the frame via mainFrame.frames and dispatch DOM pointer events from+ // within its origin, spread over rAF ticks so the engine's per-frame input+ // sampling sees a real gesture. Verifies drag-scroll / drag&drop e2e.+ if (process.env.ESTELLA_SHOT_DRAG) {+ const [x0, y0, x1, y1] = process.env.ESTELLA_SHOT_DRAG.split(',').map(Number);+ const playFrame = w.webContents.mainFrame.frames.find((f) => f.url.startsWith('estella://'));+ if (!playFrame) {+ console.log('[drag] no estella:// play frame found');+ } else {+ const result = await playFrame.executeJavaScript(`(async () => {+ const c = document.querySelector('canvas');+ if (!c) return 'no canvas';+ const raf = () => new Promise((r) => requestAnimationFrame(r));+ const fire = (t, x, y, tgt) => (tgt ?? c).dispatchEvent(+ new MouseEvent(t, { clientX: x, clientY: y, bubbles: true, cancelable: true, button: 0 }));+ fire('mousemove', ${x0}, ${y0});+ await raf(); await raf();+ fire('mousedown', ${x0}, ${y0});+ await raf(); await raf();+ for (let i = 1; i <= 12; i++) {+ fire('mousemove', ${x0} + (${x1} - ${x0}) * i / 12, ${y0} + (${y1} - ${y0}) * i / 12);+ await raf(); await raf();+ }+ fire('mouseup', ${x1}, ${y1}, document);+ await raf();+ return 'ok';+ })()`);+ console.log('[drag]', `${x0},${y0} → ${x1},${y1}`, result);+ }+ await settleFrames(8); // let a kinetic fling play out before the capture+ }if (process.env.ESTELLA_SHOT_EVAL) {- await exec(process.env.ESTELLA_SHOT_EVAL);+ const result = await exec(process.env.ESTELLA_SHOT_EVAL);+ console.log('[eval]', typeof result === 'string' ? result : JSON.stringify(result));await settleFrames(8);}await settleFrames(12); // was sleep(2500) — let the engine loop spin up + fully paint the WebGL viewportdiff --git a/docs/astro/src/content/docs/guides/ui-components.mdx b/docs/astro/src/content/docs/guides/ui-components.mdxindex 799d32014..109ca445a 100644--- a/docs/astro/src/content/docs/guides/ui-components.mdx+++ b/docs/astro/src/content/docs/guides/ui-components.mdx@@ -274,10 +274,12 @@ list.data.setItems(freshList); // replace all`scroll` and `view` as escape hatches to the underlying `ScrollContainer` / `ListView`.<Aside type="note">- Mouse-wheel scrolling works out of the box (the viewport is a hover target). Drag /- touch scrolling isn't wired yet — drive it from your own pointer handler via- `list.scroll.scrollBy(...)`. For heterogeneous rows, pass a map of item type →- template instead of one `item`, and give the data source a `getItemType(i)`.+ Scrolling works out of the box: mouse wheel over the viewport, and pointer **drag with+ a kinetic fling** — the platform layer funnels the primary touch into the pointer+ stream, so touch scrolling rides the same path. Tune it with `dragScroll: false` or+ `decelerationRate` (fling velocity left after 1s; default `0.135`, the ScrollRect+ standard). For heterogeneous rows, pass a map of item type → template instead of one+ `item`, and give the data source a `getItemType(i)`.</Aside>## Editor prefabsdiff --git a/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx b/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdxindex 96e1cbe5b..929e03a6d 100644--- a/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx@@ -263,9 +263,10 @@ list.data.setItems(freshList); // 全替换`ScrollContainer` / `ListView` 的逃生舱。<Aside type="note">- 鼠标滚轮滚动开箱即用(视口是悬停目标)。拖拽/触摸滚动尚未接线——需要的话用- `list.scroll.scrollBy(...)` 从你自己的指针处理器驱动。异构行:用「item 类型 → 模板」的映射- 代替单个 `item`,并给数据源一个 `getItemType(i)`。+ 滚动开箱即用:视口上的鼠标滚轮,以及指针**拖拽 + 惯性甩动**——平台层把主触点并入指针流,+ 触摸滚动走同一条路径。可用 `dragScroll: false` 关闭,或用 `decelerationRate` 调惯性+ (甩动 1 秒后剩余的速度比例;默认 `0.135`,ScrollRect 标准值)。异构行:用「item 类型 → 模板」+ 的映射代替单个 `item`,并给数据源一个 `getItemType(i)`。</Aside>## 编辑器预制体diff --git a/examples/ui-list/README.md b/examples/ui-list/README.mdindex bd01aadf8..51a61b917 100644--- a/examples/ui-list/README.md+++ b/examples/ui-list/README.md@@ -22,6 +22,7 @@ source holds.| Input | Action || --------------- | ------------------------------------------------------- || Mouse wheel | Scroll whichever list is under the cursor |+| Drag (mouse/touch) | Grab the content and fling it — kinetic scrolling with inertia || **+ Append row** | `data.append(…)` — the list grows live, then jumps to it || **− Remove first** | `data.remove(0)` — rows above re-bind in place || **Top / End** | `scrollToIndex()` — programmatic jumps |diff --git a/examples/ui-list/src/systems/stats.ts b/examples/ui-list/src/systems/stats.tsindex 871e21c6f..b8219cff8 100644--- a/examples/ui-list/src/systems/stats.ts+++ b/examples/ui-list/src/systems/stats.ts@@ -13,7 +13,7 @@ export const statsSystem = defineSystem(const text =`list: ${list.mountedCount()} entities mounted for ${list.data.getCount()} rows · ` +- `grid: ${grid.mountedCount()} for ${grid.data.getCount()} tiles · scroll with the mouse wheel`;+ `grid: ${grid.mountedCount()} for ${grid.data.getCount()} tiles · wheel-scroll or drag to fling`;if (text === state.lastStats) return;state.lastStats = text;diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.tsindex e97653425..62cb1c7fa 100644--- a/sdk/src/core-ui.ts+++ b/sdk/src/core-ui.ts@@ -153,6 +153,7 @@ export {ListView,type ListViewOptions,ScrollContainer,+ KineticScroll,ArrayDataSource,arrayDataSource,type DataSource,diff --git a/sdk/src/ui/behavior/plugin.ts b/sdk/src/ui/behavior/plugin.tsindex ddeb70cd6..c9889e514 100644--- a/sdk/src/ui/behavior/plugin.ts+++ b/sdk/src/ui/behavior/plugin.ts@@ -1,13 +1,16 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { App, Plugin } from '../../app';-import { Res } from '../../resource';+import { Res, Time, type TimeData } from '../../resource';import { defineSystem, Schedule } from '../../system';import { Input, type InputState } from '../../input';-import type { Entity } from '../../types';+import { Transform, type TransformData } from '../../component';+import { playModeOnly } from '../../env';+import type { Entity, Vec2 } from '../../types';import { UIEvents, UIEventQueue } from '../core/events';-import { PluginName } from '../../systemLabels';+import { UICameraInfo, type UICameraData } from '../core/ui-camera-info';+import { PluginName, SystemLabel } from '../../systemLabels';import {createInteractableDriverSystem,createStateMachineDiffSystem,@@ -15,7 +18,12 @@ import {} from './systems';import { ListView, ListViewRegistry } from '../collection/list-view';import { ScrollContainer, ScrollContainerRegistry } from '../collection/scroll-container';+import { KineticScroll } from '../collection/kinetic-scroll';import { UIInteraction, type UIInteractionData } from '../input/interactable';+import { getEntityDepth } from '../util/helpers';++/** Screen-px slop before a press becomes a scroll drag (matches Draggable). */+const SCROLL_DRAG_THRESHOLD_PX = 5;/*** Wires the Layer 2 behavior systems — interactable-driven state machine@@ -104,6 +112,21 @@ export class UIBehaviorPlugin implements Plugin {Schedule.Update,defineSystem([], () => listViews.tick(), { name: 'ListViewSystem' }),);+ // Kinetic (fling) state per scroll entity — shared between the wheel+ // and drag systems so either input source interrupts a coast. Kept in+ // a closure Map (the StateVisualsApplySystem precedent): runtime-only,+ // invisible to serialization, dropped with detach.+ const dynamics = new Map<Entity, KineticScroll>();+ const dynamicsFor = (entity: Entity, container: ScrollContainer): KineticScroll => {+ let d = dynamics.get(entity);+ if (!d) {+ d = new KineticScroll({ decelerationRate: container.getDecelerationRate() });+ dynamics.set(entity, d);+ }+ return d;+ };+ app.world.onDespawn((entity) => dynamics.delete(entity));+app.addSystemToSchedule(Schedule.Update,defineSystem([Res(Input)], (input: InputState) => {@@ -114,11 +137,136 @@ export class UIBehaviorPlugin implements Plugin {if (!world.has(entity as Entity, UIInteraction)) continue;const ui = world.get(entity as Entity, UIInteraction) as UIInteractionData;if (!ui.hovered) continue;+ dynamics.get(entity as Entity)?.stop(); // wheel takes over from a flingconst speed = container.getWheelSpeed();container.scrollBy({ x: dx * speed, y: dy * speed });}}, { name: 'ScrollWheelSystem' }),);++ // Drag/touch scrolling. The web platform layer already funnels the+ // primary touch into the pointer stream (touchstart → onPointerDown+ // etc.), so one pointer-based system covers mouse and touch alike.+ // Same pending → slop → active capture shape as DragSystem, but the+ // delta drives the ScrollContainer offset instead of the entity box,+ // and release hands the sampled velocity to KineticScroll to coast.+ let pendingEntity: Entity | null = null;+ let activeEntity: Entity | null = null;+ let grabStartWorld: Vec2 = { x: 0, y: 0 };+ let grabStartOffset: Vec2 = { x: 0, y: 0 };+ let lastOffset: Vec2 = { x: 0, y: 0 };++ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(+ [Res(Input), Res(UICameraInfo), Res(Time)],+ (input: InputState, camera: UICameraData, time: TimeData) => {+ if (!camera.valid) return;+ const worldMouse = { x: camera.worldMouseX, y: camera.worldMouseY };++ // New press over a hovered container: catch it (stop any+ // coast) and arm the drag. Deepest hovered wins so a nested+ // list scrolls itself, not its ancestor.+ if (input.isMouseButtonPressed(0)) {+ let best: Entity | null = null;+ let bestDepth = -1;+ for (const [entity, container] of scrollContainers.entries()) {+ if (!container.getDragScroll()) continue;+ if (!world.has(entity as Entity, UIInteraction)) continue;+ const ui = world.get(entity as Entity, UIInteraction) as UIInteractionData;+ if (!ui.hovered) continue;+ const depth = getEntityDepth(world, entity as Entity);+ if (depth > bestDepth) {+ bestDepth = depth;+ best = entity as Entity;+ }+ }+ if (best !== null) {+ const container = scrollContainers.get(best)!;+ dynamicsFor(best, container).stop();+ pendingEntity = best;+ grabStartWorld = { x: worldMouse.x, y: worldMouse.y };+ }+ }++ // Released before crossing the slop: it was a tap/click, not a drag.+ if (pendingEntity !== null && !input.isMouseButtonDown(0)) {+ pendingEntity = null;+ }++ // Cross the slop threshold (screen px, like Draggable) → grab.+ if (pendingEntity !== null && activeEntity === null) {+ const container = scrollContainers.get(pendingEntity);+ if (!container) {+ pendingEntity = null;+ } else {+ const dx = worldMouse.x - grabStartWorld.x;+ const dy = worldMouse.y - grabStartWorld.y;+ const worldSpan = camera.worldRight - camera.worldLeft;+ const screenDist = Math.hypot(dx, dy) * (worldSpan !== 0 ? camera.vpW / worldSpan : 1);+ if (screenDist >= SCROLL_DRAG_THRESHOLD_PX) {+ activeEntity = pendingEntity;+ pendingEntity = null;+ grabStartOffset = container.getOffset();+ lastOffset = { x: grabStartOffset.x, y: grabStartOffset.y };+ dynamicsFor(activeEntity, container).beginDrag();+ }+ }+ }++ // Active drag: the content follows the pointer 1:1 (absolute+ // mapping from the grab point, so clamped overshoot re-tracks+ // the finger on the way back). World-unit deltas divide by the+ // viewport's world scale to land in UI px; world y is up while+ // offset y is down, hence the sign split.+ if (activeEntity !== null) {+ const container = scrollContainers.get(activeEntity);+ if (!container || !world.valid(activeEntity)) {+ activeEntity = null;+ return;+ }+ let sx = 1;+ let sy = 1;+ if (world.has(activeEntity, Transform)) {+ const wt = world.get(activeEntity, Transform) as TransformData;+ if (wt.worldScale.x !== 0) sx = wt.worldScale.x;+ if (wt.worldScale.y !== 0) sy = wt.worldScale.y;+ }+ const totalDx = worldMouse.x - grabStartWorld.x;+ const totalDy = worldMouse.y - grabStartWorld.y;+ container.setOffset({+ x: grabStartOffset.x - totalDx / sx,+ y: grabStartOffset.y + totalDy / sy,+ });++ const now = container.getOffset();+ const dyn = dynamicsFor(activeEntity, container);+ dyn.sample({ x: now.x - lastOffset.x, y: now.y - lastOffset.y }, time.delta);+ lastOffset = now;++ if (!input.isMouseButtonDown(0)) {+ dyn.endDrag(); // sampled velocity carries into the coast+ activeEntity = null;+ }+ }++ // Coast phase: tick each flung container, killing an axis the+ // moment the clamp stops it so the fling dies at the edge.+ for (const [entity, dyn] of dynamics) {+ if (!dyn.isCoasting()) continue;+ const container = scrollContainers.get(entity);+ if (!container) {+ dynamics.delete(entity);+ continue;+ }+ const delta = dyn.tick(time.delta);+ const before = container.getOffset();+ container.scrollBy(delta);+ const after = container.getOffset();+ if (delta.x !== 0 && after.x === before.x) dyn.killAxis('x');+ if (delta.y !== 0 && after.y === before.y) dyn.killAxis('y');+ }+ },+ { name: 'ScrollDragSystem', runAfter: [SystemLabel.UIInteraction] },+ ), { runIf: playModeOnly });}}diff --git a/sdk/src/ui/collection/kinetic-scroll.ts b/sdk/src/ui/collection/kinetic-scroll.tsnew file mode 100644index 000000000..a86651786--- /dev/null+++ b/sdk/src/ui/collection/kinetic-scroll.ts@@ -0,0 +1,103 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file ui/collection/kinetic-scroll.ts+ * @brief KineticScroll — the pure velocity model behind drag/touch scrolling.+ *+ * Tracks the pointer's velocity while a drag is held (EMA-smoothed so one+ * jittery frame doesn't dictate the fling) and, after release, decays it+ * exponentially so the content coasts to rest — the standard kinetic-scroll+ * feel (Unity ScrollRect / iOS). Like {@link ScrollContainer}, it has no+ * input or ECS knowledge: a behavior system pushes samples in and applies+ * the ticked deltas back to the container, keeping the model unit-testable.+ */+import type { Vec2 } from '../../types';++export interface KineticScrollOptions {+ /**+ * Fraction of the release velocity remaining after one second of+ * coasting (`v *= rate^dt`). Default 0.135 — Unity's ScrollRect default.+ */+ decelerationRate?: number;+ /** Speed floor (px/s) below which coasting stops. Default 4. */+ restVelocity?: number;+ /**+ * Per-second EMA rate blending new velocity samples over the held drag+ * (`blend = 1 - e^(-rate·dt)`). Default 12 — ≈70% weight in 100ms.+ */+ sampleRate?: number;+}++export class KineticScroll {+ private readonly decelerationRate_: number;+ private readonly restVelocity_: number;+ private readonly sampleRate_: number;+ private velocity_: Vec2 = { x: 0, y: 0 };+ private dragging_ = false;++ constructor(opts: KineticScrollOptions = {}) {+ this.decelerationRate_ = opts.decelerationRate ?? 0.135;+ this.restVelocity_ = opts.restVelocity ?? 4;+ this.sampleRate_ = opts.sampleRate ?? 12;+ }++ /** A finger/pointer grabbed the content: cancel any coast, start sampling. */+ beginDrag(): void {+ this.dragging_ = true;+ this.velocity_ = { x: 0, y: 0 };+ }++ /** Feed one frame's offset delta (px) while the drag is held. */+ sample(delta: Vec2, dt: number): void {+ if (!this.dragging_ || dt <= 0) return;+ const instant = { x: delta.x / dt, y: delta.y / dt };+ const blend = 1 - Math.exp(-this.sampleRate_ * dt);+ this.velocity_.x += (instant.x - this.velocity_.x) * blend;+ this.velocity_.y += (instant.y - this.velocity_.y) * blend;+ }++ /** Release: the sampled velocity carries over into coasting. */+ endDrag(): void {+ this.dragging_ = false;+ }++ /** Hard stop (new grab, wheel input, or hitting a clamp edge). */+ stop(): void {+ this.dragging_ = false;+ this.velocity_ = { x: 0, y: 0 };+ }++ /** Kill one axis of the coast (that axis hit its clamp edge). */+ killAxis(axis: 'x' | 'y'): void {+ this.velocity_[axis] = 0;+ }++ isDragging(): boolean {+ return this.dragging_;+ }++ /** Coasting = released with speed above the rest floor. */+ isCoasting(): boolean {+ if (this.dragging_) return false;+ const { x, y } = this.velocity_;+ return Math.hypot(x, y) > this.restVelocity_;+ }++ getVelocity(): Vec2 {+ return { x: this.velocity_.x, y: this.velocity_.y };+ }++ /**+ * Advance one coast frame: returns the offset delta to apply and decays+ * the velocity. Zero vector when not coasting.+ */+ tick(dt: number): Vec2 {+ if (!this.isCoasting() || dt <= 0) return { x: 0, y: 0 };+ const delta = { x: this.velocity_.x * dt, y: this.velocity_.y * dt };+ const decay = Math.pow(this.decelerationRate_, dt);+ this.velocity_.x *= decay;+ this.velocity_.y *= decay;+ if (!this.isCoasting()) this.velocity_ = { x: 0, y: 0 };+ return delta;+ }+}diff --git a/sdk/src/ui/collection/scroll-container.ts b/sdk/src/ui/collection/scroll-container.tsindex c35131e5a..a56115e88 100644--- a/sdk/src/ui/collection/scroll-container.ts+++ b/sdk/src/ui/collection/scroll-container.ts@@ -11,6 +11,13 @@ export interface ScrollContainerOptions {direction?: 'both' | 'vertical' | 'horizontal';/** Multiplier applied to wheel deltas. Default 1. */wheelSpeed?: number;+ /** Drag/touch scrolling (pointer grab + kinetic fling). Default true. */+ dragScroll?: boolean;+ /**+ * Fraction of the fling velocity remaining after one second of coasting.+ * Default 0.135 (Unity ScrollRect). Only meaningful with `dragScroll`.+ */+ decelerationRate?: number;}export type ScrollListener = (offset: Vec2) => void;@@ -29,6 +36,8 @@ export class ScrollContainer {private offset_: Vec2 = { x: 0, y: 0 };private readonly direction_: 'both' | 'vertical' | 'horizontal';private readonly wheelSpeed_: number;+ private readonly dragScroll_: boolean;+ private readonly decelerationRate_: number;private readonly listeners_ = new Set<ScrollListener>();constructor(opts: ScrollContainerOptions) {@@ -36,6 +45,8 @@ export class ScrollContainer {this.contentSize_ = { x: opts.contentSize.x, y: opts.contentSize.y };this.direction_ = opts.direction ?? 'vertical';this.wheelSpeed_ = opts.wheelSpeed ?? 1;+ this.dragScroll_ = opts.dragScroll ?? true;+ this.decelerationRate_ = opts.decelerationRate ?? 0.135;this.setOffset(opts.initialOffset ?? { x: 0, y: 0 });}@@ -62,6 +73,14 @@ export class ScrollContainer {return this.wheelSpeed_;}+ getDragScroll(): boolean {+ return this.dragScroll_;+ }++ getDecelerationRate(): number {+ return this.decelerationRate_;+ }+setOffset(offset: Vec2): void {const max = this.getMaxOffset();const lockX = this.direction_ === 'vertical';diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.tsindex bfa08abd4..db8b957ac 100644--- a/sdk/src/ui/index.ts+++ b/sdk/src/ui/index.ts@@ -177,6 +177,11 @@ export {type ScrollListener,} from './collection/scroll-container';+export {+ KineticScroll,+ type KineticScrollOptions,+} from './collection/kinetic-scroll';+// ─── Widgets (Layer 3 factories) ────────────────────────────────────────────export {diff --git a/sdk/src/ui/widgets/list-view.ts b/sdk/src/ui/widgets/list-view.tsindex c7a0b413e..b5fdf4914 100644--- a/sdk/src/ui/widgets/list-view.ts+++ b/sdk/src/ui/widgets/list-view.ts@@ -10,9 +10,12 @@** Layout integration (REARCH_UI_LIST §3): items are positioned by UINode* Absolute inset (not Transform, which the UI layout owns); the content frame is- * translated by the scroll offset; a Scissor UIMask on the viewport clips. Mouse- * wheel is handled by the behavior plugin's ScrollWheelSystem once the viewport is- * a hovered raycast target — drag/touch scrolling is not wired here (v1).+ * translated by the scroll offset; a Scissor UIMask on the viewport clips. Input+ * is handled by the behavior plugin once the viewport is a hovered raycast+ * target: ScrollWheelSystem applies wheel deltas, and ScrollDragSystem grabs+ * pointer drags (the primary touch is funneled into the pointer stream by the+ * platform layer, so touch scrolling rides the same path) with a kinetic fling+ * on release.*/import { Transform } from '../../component';import type { Entity, Vec2 } from '../../types';@@ -74,6 +77,10 @@ export interface CreateListViewOptions<T> {recycleBuffer?: number;/** Wheel delta multiplier. Default 1. */wheelSpeed?: number;+ /** Drag/touch scrolling with a kinetic fling. Default true. */+ dragScroll?: boolean;+ /** Fling velocity fraction left after 1s of coasting. Default 0.135. */+ decelerationRate?: number;/** Called after each item bind. */onItemBound?: (entity: Entity, data: T, index: number) => void;}@@ -205,13 +212,15 @@ export function createListView<T>(opts: CreateListViewOptions<T>): ListViewHandl});uiPlugin.registerListView(view as ListView<unknown>);- // 6) Scroll model: wheel-driven by the plugin; onScroll translates the content- // frame and pushes the offset into the driver.+ // 6) Scroll model: wheel- and drag-driven by the plugin; onScroll translates+ // the content frame and pushes the offset into the driver.const scroll = new ScrollContainer({viewportSize,contentSize: layout.getContentSize(data.getCount()),direction: opts.direction ?? axis,wheelSpeed: opts.wheelSpeed,+ dragScroll: opts.dragScroll,+ decelerationRate: opts.decelerationRate,});const offScroll = scroll.onScroll((offset) => {const n = world.get(content, UINode) as UINodeData;diff --git a/sdk/tests/ui-kinetic-scroll.test.ts b/sdk/tests/ui-kinetic-scroll.test.tsnew file mode 100644index 000000000..af6afc0a5--- /dev/null+++ b/sdk/tests/ui-kinetic-scroll.test.ts@@ -0,0 +1,137 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { KineticScroll, ScrollContainer } from '../src/ui';++describe('ScrollContainer drag options', () => {+ it('defaults dragScroll on and decelerationRate to the ScrollRect standard', () => {+ const c = new ScrollContainer({+ viewportSize: { x: 100, y: 100 },+ contentSize: { x: 100, y: 500 },+ });+ expect(c.getDragScroll()).toBe(true);+ expect(c.getDecelerationRate()).toBe(0.135);+ });++ it('plumbs explicit dragScroll / decelerationRate through', () => {+ const c = new ScrollContainer({+ viewportSize: { x: 100, y: 100 },+ contentSize: { x: 100, y: 500 },+ dragScroll: false,+ decelerationRate: 0.5,+ });+ expect(c.getDragScroll()).toBe(false);+ expect(c.getDecelerationRate()).toBe(0.5);+ });+});++describe('KineticScroll', () => {+ const dt = 1 / 60;++ it('starts at rest: no drag, no coast, zero velocity', () => {+ const k = new KineticScroll();+ expect(k.isDragging()).toBe(false);+ expect(k.isCoasting()).toBe(false);+ expect(k.getVelocity()).toEqual({ x: 0, y: 0 });+ });++ it('beginDrag marks dragging and zeroes any prior velocity', () => {+ const k = new KineticScroll();+ k.beginDrag();+ k.sample({ x: 0, y: 10 }, dt);+ k.endDrag();+ expect(k.isCoasting()).toBe(true);++ k.beginDrag(); // catch: a new grab kills the coast+ expect(k.isDragging()).toBe(true);+ expect(k.getVelocity()).toEqual({ x: 0, y: 0 });+ expect(k.isCoasting()).toBe(false);+ });++ it('sampling steers velocity toward delta/dt (EMA, not raw last frame)', () => {+ const k = new KineticScroll();+ k.beginDrag();+ // Steady 10px per frame at 60fps = 600 px/s.+ for (let i = 0; i < 60; i++) k.sample({ x: 0, y: 10 }, dt);+ const v = k.getVelocity();+ expect(v.y).toBeGreaterThan(550);+ expect(v.y).toBeLessThanOrEqual(600 + 1e-9);++ // One jittery zero-delta frame must not wipe the built-up velocity.+ k.sample({ x: 0, y: 0 }, dt);+ expect(k.getVelocity().y).toBeGreaterThan(400);+ });++ it('ignores samples when not dragging and ticks zero while dragging', () => {+ const k = new KineticScroll();+ k.sample({ x: 5, y: 5 }, dt); // no beginDrag → no-op+ expect(k.getVelocity()).toEqual({ x: 0, y: 0 });++ k.beginDrag();+ k.sample({ x: 0, y: 10 }, dt);+ expect(k.tick(dt)).toEqual({ x: 0, y: 0 }); // held drag never coasts+ });++ it('release coasts: tick returns v·dt and decays to rest', () => {+ const k = new KineticScroll();+ k.beginDrag();+ for (let i = 0; i < 30; i++) k.sample({ x: 0, y: 10 }, dt);+ k.endDrag();+ expect(k.isCoasting()).toBe(true);++ const first = k.tick(dt);+ expect(first.y).toBeGreaterThan(0);++ let travelled = first.y;+ let frames = 0;+ while (k.isCoasting() && frames < 10_000) {+ travelled += k.tick(dt).y;+ frames++;+ }+ expect(frames).toBeLessThan(10_000); // it does come to rest+ expect(k.isCoasting()).toBe(false);+ expect(k.getVelocity()).toEqual({ x: 0, y: 0 });+ // ~600 px/s decaying at 0.135/s integrates to ≈ v0·(-1/ln r) ≈ 300 px.+ expect(travelled).toBeGreaterThan(100);+ expect(travelled).toBeLessThan(600);+ });++ it('decelerationRate is framerate-independent (30fps ≈ 120fps distance)', () => {+ const run = (step: number): number => {+ const k = new KineticScroll();+ k.beginDrag();+ for (let i = 0; i < 50; i++) k.sample({ x: 0, y: 600 * step }, step);+ k.endDrag();+ let d = 0;+ let guard = 0;+ while (k.isCoasting() && guard++ < 100_000) d += k.tick(step).y;+ return d;+ };+ const d30 = run(1 / 30);+ const d120 = run(1 / 120);+ expect(Math.abs(d30 - d120) / d30).toBeLessThan(0.1);+ });++ it('killAxis stops one axis and lets the other coast on', () => {+ const k = new KineticScroll();+ k.beginDrag();+ for (let i = 0; i < 30; i++) k.sample({ x: 10, y: 10 }, dt);+ k.endDrag();++ k.killAxis('x');+ expect(k.getVelocity().x).toBe(0);+ expect(k.isCoasting()).toBe(true); // y still alive+ expect(k.tick(dt).x).toBe(0);+ expect(k.getVelocity().y).toBeGreaterThan(0);+ });++ it('stop() halts everything immediately', () => {+ const k = new KineticScroll();+ k.beginDrag();+ for (let i = 0; i < 30; i++) k.sample({ x: 10, y: 10 }, dt);+ k.endDrag();+ k.stop();+ expect(k.isCoasting()).toBe(false);+ expect(k.tick(dt)).toEqual({ x: 0, y: 0 });+ });+});