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.

feat(ui): scroll areas can be pulled past an end and spring back (ScrollContainer overscroll, ScrollMotion for the gesture); ScrollMovement.Elastic now does what its comment said. The Cocos ScrollView drives the engine's scroll model instead of carrying its own

yhhd569ff017ee9
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 5f5c689de..111e8aa84 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -9023,21 +9023,29 @@ scaleMode: number
## ScrollContainer — class @experimental
```
+absorb: (axis: "x" | "y", velocity: number) => void
dispose: () => void
+dragTo: (raw: Vec2) => void
getContentSize: () => Vec2
getDecelerationRate: () => number
getDragScroll: () => boolean
getMaxOffset: () => Vec2
getOffset: () => Vec2
+getOverscroll: () => Vec2
getShowScrollbar: () => boolean
getViewportSize: () => Vec2
getWheelSpeed: () => number
+isElastic: () => boolean
+isSpringing: () => boolean
+onOverscroll: (listener: OverscrollListener) => () => void
onScroll: (listener: ScrollListener) => () => void
+releaseSpring: () => void
scrollBy: (delta: Vec2) => void
setContentSize: (size: Vec2) => void
setOffset: (offset: Vec2) => void
setSizes: (viewport: Vec2, content: Vec2) => void
setViewportSize: (size: Vec2) => void
+tickSpring: (dt: number) => boolean
static new (opts: ScrollContainerOptions): ScrollContainer
static prototype: ScrollContainer
```
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 64c6d3a91..d6834dfb4 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -9236,21 +9236,29 @@ scaleMode: number
## ScrollContainer — class @experimental
```
+absorb: (axis: "x" | "y", velocity: number) => void
dispose: () => void
+dragTo: (raw: Vec2) => void
getContentSize: () => Vec2
getDecelerationRate: () => number
getDragScroll: () => boolean
getMaxOffset: () => Vec2
getOffset: () => Vec2
+getOverscroll: () => Vec2
getShowScrollbar: () => boolean
getViewportSize: () => Vec2
getWheelSpeed: () => number
+isElastic: () => boolean
+isSpringing: () => boolean
+onOverscroll: (listener: OverscrollListener) => () => void
onScroll: (listener: ScrollListener) => () => void
+releaseSpring: () => void
scrollBy: (delta: Vec2) => void
setContentSize: (size: Vec2) => void
setOffset: (offset: Vec2) => void
setSizes: (viewport: Vec2, content: Vec2) => void
setViewportSize: (size: Vec2) => void
+tickSpring: (dt: number) => boolean
static new (opts: ScrollContainerOptions): ScrollContainer
static prototype: ScrollContainer
```
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 488325be3..aeea5b619 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -9018,21 +9018,29 @@ scaleMode: number
## ScrollContainer — class @experimental
```
+absorb: (axis: "x" | "y", velocity: number) => void
dispose: () => void
+dragTo: (raw: Vec2) => void
getContentSize: () => Vec2
getDecelerationRate: () => number
getDragScroll: () => boolean
getMaxOffset: () => Vec2
getOffset: () => Vec2
+getOverscroll: () => Vec2
getShowScrollbar: () => boolean
getViewportSize: () => Vec2
getWheelSpeed: () => number
+isElastic: () => boolean
+isSpringing: () => boolean
+onOverscroll: (listener: OverscrollListener) => () => void
onScroll: (listener: ScrollListener) => () => void
+releaseSpring: () => void
scrollBy: (delta: Vec2) => void
setContentSize: (size: Vec2) => void
setOffset: (offset: Vec2) => void
setSizes: (viewport: Vec2, content: Vec2) => void
setViewportSize: (size: Vec2) => void
+tickSpring: (dt: number) => boolean
static new (opts: ScrollContainerOptions): ScrollContainer
static prototype: ScrollContainer
```
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 22696d291..997505e20 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -9313,21 +9313,29 @@ scaleMode: number
## ScrollContainer — class @experimental
```
+absorb: (axis: "x" | "y", velocity: number) => void
dispose: () => void
+dragTo: (raw: Vec2) => void
getContentSize: () => Vec2
getDecelerationRate: () => number
getDragScroll: () => boolean
getMaxOffset: () => Vec2
getOffset: () => Vec2
+getOverscroll: () => Vec2
getShowScrollbar: () => boolean
getViewportSize: () => Vec2
getWheelSpeed: () => number
+isElastic: () => boolean
+isSpringing: () => boolean
+onOverscroll: (listener: OverscrollListener) => () => void
onScroll: (listener: ScrollListener) => () => void
+releaseSpring: () => void
scrollBy: (delta: Vec2) => void
setContentSize: (size: Vec2) => void
setOffset: (offset: Vec2) => void
setSizes: (viewport: Vec2, content: Vec2) => void
setViewportSize: (size: Vec2) => void
+tickSpring: (dt: number) => boolean
static new (opts: ScrollContainerOptions): ScrollContainer
static prototype: ScrollContainer
```
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index f129e63af..12d5f414f 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -9025,21 +9025,29 @@ scaleMode: number
## ScrollContainer — class @experimental
```
+absorb: (axis: "x" | "y", velocity: number) => void
dispose: () => void
+dragTo: (raw: Vec2) => void
getContentSize: () => Vec2
getDecelerationRate: () => number
getDragScroll: () => boolean
getMaxOffset: () => Vec2
getOffset: () => Vec2
+getOverscroll: () => Vec2
getShowScrollbar: () => boolean
getViewportSize: () => Vec2
getWheelSpeed: () => number
+isElastic: () => boolean
+isSpringing: () => boolean
+onOverscroll: (listener: OverscrollListener) => () => void
onScroll: (listener: ScrollListener) => () => void
+releaseSpring: () => void
scrollBy: (delta: Vec2) => void
setContentSize: (size: Vec2) => void
setOffset: (offset: Vec2) => void
setSizes: (viewport: Vec2, content: Vec2) => void
setViewportSize: (size: Vec2) => void
+tickSpring: (dt: number) => boolean
static new (opts: ScrollContainerOptions): ScrollContainer
static prototype: ScrollContainer
```
diff --git a/sdk/src/cocos/ui/scrollView.ts b/sdk/src/cocos/ui/scrollView.ts
index 695594ebd..2a698a25c 100644
--- a/sdk/src/cocos/ui/scrollView.ts
+++ b/sdk/src/cocos/ui/scrollView.ts
@@ -4,21 +4,22 @@
* @file cocos/ui/scrollView.ts
* @brief `ScrollView`: a content node moved inside a view by dragging, with inertia and an elastic edge.
*
- * The motion is the engine's own scroll physics (ui/collection/scroll-physics.ts); what this adds is Cocos's shape around it. The
- * view is the content's parent, the content is a child that is bigger, and the offsets scripts read are Cocos's: `getScrollOffset()`
- * is how far the content has moved toward its end (positive x = scrolled right, positive y = scrolled down).
+ * The motion is the engine's own scroll model (ui/collection: ScrollContainer, KineticScroll, ScrollMotion) — the same one the
+ * engine's UI scroll areas use — and this adds Cocos's shape around it: the view is the content's parent, the content is a child
+ * that is bigger, and the offsets scripts read are Cocos's (`getScrollOffset()` is how far the content has moved toward its end;
+ * positive x is scrolled right, positive y scrolled down). The settings map onto the model: `elastic` and `bounceDuration` are the
+ * container's, `inertia` and `brake` set how long a flick coasts.
*
* Touches are heard in the CAPTURE phase, so a drag that starts on a button inside the content still scrolls; once the finger has
* moved far enough to be a drag, the button is cancelled (`cancelInnerEvents`) and does not click on release.
- *
- * The glide and the spring have Cocos's character and not its digits: a flick goes on for a time that follows its speed and
- * eases out, a pull past the end is damped and returns. Scripts that depend on exact distances should not expect them.
*/
import { Component } from '../component';
import { Node } from '../node';
import { Vec2, Vec3 } from '../math';
import { declareClass } from '../host';
-import { ScrollAxis } from '../../ui/collection/scroll-physics';
+import { ScrollContainer } from '../../ui/collection/scroll-container';
+import { ScrollMotion } from '../../ui/collection/scroll-motion';
+import { KineticScroll } from '../../ui/collection/kinetic-scroll';
import { EventHandler, joinHandlers } from './button';
import { UITransform } from './uiTransform';
import type { EventTouch } from '../input';
@@ -42,6 +43,9 @@ const EventType = Object.freeze({
/** How far a finger must travel before the touch is a drag and the node under it is cancelled. */
const DRAG_THRESHOLD = 7;
+/** Cocos's `brake` (0 = coast long, 1 = stop at once) as the fraction of speed the engine's coast keeps after a second. */
+const decelerationOf = (brake: number): number => 0.5 * 0.04 ** Math.min(1, Math.max(0, brake));
+
export class ScrollView extends Component {
static readonly EventType = EventType;
@@ -57,12 +61,12 @@ export class ScrollView extends Component {
scrollHandlers: { component: string; handler: string; customEventData: string }[] = [];
scrollEvents: EventHandler[] = [];
- private readonly x_ = new ScrollAxis();
- private readonly y_ = new ScrollAxis();
- private clock_ = 0;
+ private motion_: ScrollMotion | null = null;
+ private settings_ = '';
private dragging_ = false;
private began_ = false;
private travelled_ = 0;
+ private anchor_: Vec3 | null = null;
private last_: Vec3 | null = null;
private resting_ = true;
private edge_ = { top: false, bottom: false, left: false, right: false };
@@ -78,7 +82,7 @@ export class ScrollView extends Component {
this.node.on(Node.EventType.TOUCH_CANCEL, this.onCancel_, this, true);
// listening in capture alone leaves the node itself unclaimed when nothing under the finger listens
this.node.on(Node.EventType.TOUCH_START, noop, this);
- this.syncAxes_();
+ this.sync_();
this.place_();
}
@@ -92,50 +96,49 @@ export class ScrollView extends Component {
}
update(dt: number): void {
- this.clock_ += dt;
- if (!this.dragging_) {
- this.syncAxes_();
- const moved = this.x_.update(dt) || this.y_.update(dt);
- if (moved) { this.place_(); this.notify_(EventType.SCROLLING); }
- const idle = !this.x_.moving && !this.y_.moving;
- if (idle && !this.resting_) {
- this.resting_ = true;
- this.notify_(EventType.SCROLL_ENDED);
- } else if (!idle) {
- this.resting_ = false;
- }
+ if (this.dragging_) return;
+ const motion = this.sync_();
+ if (!motion) return;
+ if (motion.tick(dt)) { this.place_(); this.notify_(EventType.SCROLLING); }
+ const idle = !motion.isMoving;
+ if (idle && !this.resting_) {
+ this.resting_ = true;
+ this.notify_(EventType.SCROLL_ENDED);
+ } else if (!idle) {
+ this.resting_ = false;
}
}
// ---- the Cocos API ------------------------------------------------------------------------------------------------
/** How far the content has moved toward its end on each axis (right and down are positive). */
- getScrollOffset(): Vec2 { return new Vec2(this.x_.offset, this.y_.offset); }
- getMaxScrollOffset(): Vec2 { this.syncAxes_(); return new Vec2(this.x_.max, this.y_.max); }
- isScrolling(): boolean { return this.dragging_ || this.x_.moving || this.y_.moving; }
- isAutoScrolling(): boolean { return !this.dragging_ && (this.x_.moving || this.y_.moving); }
- stopAutoScroll(): void { this.x_.stop(); this.y_.stop(); }
+ getScrollOffset(): Vec2 { const o = this.sync_()?.container.getOffset(); return new Vec2(o?.x ?? 0, o?.y ?? 0); }
+ getMaxScrollOffset(): Vec2 { const m = this.sync_()?.container.getMaxOffset(); return new Vec2(m?.x ?? 0, m?.y ?? 0); }
+ isScrolling(): boolean { return this.dragging_ || (this.motion_?.isMoving ?? false); }
+ isAutoScrolling(): boolean { return !this.dragging_ && (this.motion_?.isMoving ?? false); }
+ stopAutoScroll(): void { this.motion_?.stop(); }
- scrollToOffset(offset: Vec2, timeInSecond = 0, attenuated = true): void {
- this.syncAxes_();
- if (this.horizontal) this.x_.scrollTo(offset.x, timeInSecond, attenuated);
- if (this.vertical) this.y_.scrollTo(offset.y, timeInSecond, attenuated);
+ scrollToOffset(offset: Vec2, timeInSecond = 0, _attenuated = true): void {
+ const motion = this.sync_();
+ if (!motion) return;
+ const o = motion.container.getOffset();
+ motion.animateTo({ x: this.horizontal ? offset.x : o.x, y: this.vertical ? offset.y : o.y }, timeInSecond);
if (timeInSecond <= 0) { this.place_(); this.notify_(EventType.SCROLLING); }
}
/** Scroll so the content's position along each axis is @p anchor, 0..1, where (0, 1) is the top-left. */
scrollTo(anchor: Vec2, timeInSecond = 0, attenuated = true): void {
- this.syncAxes_();
- this.scrollToOffset(new Vec2(anchor.x * this.x_.max, (1 - anchor.y) * this.y_.max), timeInSecond, attenuated);
+ const max = this.getMaxScrollOffset();
+ this.scrollToOffset(new Vec2(anchor.x * max.x, (1 - anchor.y) * max.y), timeInSecond, attenuated);
}
- scrollToTop(t = 0, a = true): void { this.scrollToOffset(new Vec2(this.x_.offset, 0), t, a); }
- scrollToBottom(t = 0, a = true): void { this.syncAxes_(); this.scrollToOffset(new Vec2(this.x_.offset, this.y_.max), t, a); }
- scrollToLeft(t = 0, a = true): void { this.scrollToOffset(new Vec2(0, this.y_.offset), t, a); }
- scrollToRight(t = 0, a = true): void { this.syncAxes_(); this.scrollToOffset(new Vec2(this.x_.max, this.y_.offset), t, a); }
+ scrollToTop(t = 0, a = true): void { this.scrollToOffset(new Vec2(this.getScrollOffset().x, 0), t, a); }
+ scrollToBottom(t = 0, a = true): void { this.scrollToOffset(new Vec2(this.getScrollOffset().x, this.getMaxScrollOffset().y), t, a); }
+ scrollToLeft(t = 0, a = true): void { this.scrollToOffset(new Vec2(0, this.getScrollOffset().y), t, a); }
+ scrollToRight(t = 0, a = true): void { this.scrollToOffset(new Vec2(this.getMaxScrollOffset().x, this.getScrollOffset().y), t, a); }
scrollToTopLeft(t = 0, a = true): void { this.scrollToOffset(new Vec2(0, 0), t, a); }
- scrollToTopRight(t = 0, a = true): void { this.syncAxes_(); this.scrollToOffset(new Vec2(this.x_.max, 0), t, a); }
- scrollToBottomLeft(t = 0, a = true): void { this.syncAxes_(); this.scrollToOffset(new Vec2(0, this.y_.max), t, a); }
- scrollToBottomRight(t = 0, a = true): void { this.syncAxes_(); this.scrollToOffset(new Vec2(this.x_.max, this.y_.max), t, a); }
+ scrollToTopRight(t = 0, a = true): void { this.scrollToOffset(new Vec2(this.getMaxScrollOffset().x, 0), t, a); }
+ scrollToBottomLeft(t = 0, a = true): void { this.scrollToOffset(new Vec2(0, this.getMaxScrollOffset().y), t, a); }
+ scrollToBottomRight(t = 0, a = true): void { const m = this.getMaxScrollOffset(); this.scrollToOffset(new Vec2(m.x, m.y), t, a); }
getContentPosition(): Vec3 { return this.content?.getPosition() ?? new Vec3(); }
setContentPosition(p: Vec3): void { this.content?.setPosition(p); this.readBack_(); }
@@ -151,44 +154,62 @@ export class ScrollView extends Component {
return { w: t.width * Math.abs(s.x), h: t.height * Math.abs(s.y), ax: t.anchorX, ay: t.anchorY };
}
- private syncAxes_(): void {
+ /** The engine's scroll model for this view, made when the settings are first known and again when they change; its extents kept current. */
+ private sync_(): ScrollMotion | null {
const view = this.view_();
const c = this.contentSize_();
- if (!view || !c) return;
- for (const axis of [this.x_, this.y_]) {
- axis.settings.inertia = this.inertia;
- axis.settings.elastic = this.elastic;
- axis.settings.brake = this.brake;
- axis.settings.bounceTime = this.bounceDuration;
+ if (!view || !c) return this.motion_;
+ const key = [this.horizontal, this.vertical, this.inertia, this.brake, this.elastic, this.bounceDuration].join(',');
+ if (!this.motion_ || key !== this.settings_) {
+ const previous = this.motion_?.container.getOffset();
+ const container = new ScrollContainer({
+ viewportSize: { x: view.width, y: view.height },
+ contentSize: { x: c.w, y: c.h },
+ direction: this.horizontal && this.vertical ? 'both' : this.horizontal ? 'horizontal' : 'vertical',
+ elastic: this.elastic,
+ bounceTime: this.bounceDuration,
+ initialOffset: previous,
+ showScrollbar: false,
+ });
+ // no inertia is a coast that stops at once
+ this.motion_ = new ScrollMotion(container, new KineticScroll({ decelerationRate: this.inertia ? decelerationOf(this.brake) : 0 }));
+ this.settings_ = key;
+ this.readBack_();
}
- this.x_.setExtents(view.width, c.w);
- this.y_.setExtents(view.height, c.h);
+ this.motion_.container.setSizes({ x: view.width, y: view.height }, { x: c.w, y: c.h });
+ return this.motion_;
}
- /** Put the content where the axes say. */
+ /** Put the content where the model says, pulled past an end by the overscroll. */
private place_(): void {
const view = this.view_();
const c = this.contentSize_();
const content = this.content;
- if (!view || !c || !content) return;
+ const container = this.motion_?.container;
+ if (!view || !c || !content || !container) return;
+ const o = container.getOffset();
+ const over = container.getOverscroll();
const p = content.getPosition();
const viewLeft = -view.anchorX * view.width;
const viewTop = (1 - view.anchorY) * view.height;
// when the content is narrower than the view it sits at the start edge, as Cocos's does
- const x = this.horizontal ? viewLeft - this.x_.offset + c.ax * c.w : p.x;
- const y = this.vertical ? viewTop + this.y_.offset - (1 - c.ay) * c.h : p.y;
+ const x = this.horizontal ? viewLeft - (o.x + over.x) + c.ax * c.w : p.x;
+ const y = this.vertical ? viewTop + (o.y + over.y) - (1 - c.ay) * c.h : p.y;
content.setPosition(new Vec3(x, y, p.z));
}
- /** Take the offsets from where the content is now. */
+ /** Take the offsets from where the content is now (a script may have moved it). */
private readBack_(): void {
const view = this.view_();
const c = this.contentSize_();
const content = this.content;
- if (!view || !c || !content) return;
+ const container = this.motion_?.container;
+ if (!view || !c || !content || !container) return;
const p = content.getPosition();
- this.x_.offset = -view.anchorX * view.width - (p.x - c.ax * c.w);
- this.y_.offset = p.y + (1 - c.ay) * c.h - (1 - view.anchorY) * view.height;
+ container.setOffset({
+ x: -view.anchorX * view.width - (p.x - c.ax * c.w),
+ y: p.y + (1 - c.ay) * c.h - (1 - view.anchorY) * view.height,
+ });
}
// ---- touches -------------------------------------------------------------------------------------------------------
@@ -201,34 +222,36 @@ export class ScrollView extends Component {
}
private onStart_(event: EventTouch): void {
- if (!this.content) return;
- this.syncAxes_();
+ const motion = this.sync_();
+ if (!this.content || !motion) return;
this.readBack_();
- this.x_.press();
- this.y_.press();
+ motion.grab();
this.dragging_ = true;
this.began_ = false;
this.travelled_ = 0;
+ this.anchor_ = null;
this.last_ = this.local_(event);
}
private onMove_(event: EventTouch): void {
- if (!this.dragging_ || !this.last_) return;
+ const motion = this.motion_;
+ if (!this.dragging_ || !this.last_ || !motion) return;
const now = this.local_(event);
if (!now) return;
- const dx = now.x - this.last_.x, dy = now.y - this.last_.y;
+ this.travelled_ += Math.hypot(now.x - this.last_.x, now.y - this.last_.y);
this.last_ = now;
- this.travelled_ += Math.hypot(dx, dy);
if (this.travelled_ < DRAG_THRESHOLD && !this.began_) return;
if (!this.began_) {
this.began_ = true;
this.resting_ = false;
+ // the drag counts from where it became one, so the content does not jump by the threshold
+ this.anchor_ = now;
if (this.cancelInnerEvents) event.cancelInner();
this.notify_(EventType.SCROLL_BEGAN);
+ return;
}
- const view = this.view_()!;
- if (this.horizontal) this.x_.drag(-dx, this.clock_, view.width);
- if (this.vertical) this.y_.drag(dy, this.clock_, view.height);
+ const a = this.anchor_!;
+ motion.dragBy({ x: this.horizontal ? -(now.x - a.x) : 0, y: this.vertical ? now.y - a.y : 0 }, 1 / 60);
this.place_();
this.notify_(EventType.SCROLLING);
// a drag the scroll view owns is not the business of anything above it
@@ -240,8 +263,7 @@ export class ScrollView extends Component {
this.dragging_ = false;
this.notify_(EventType.TOUCH_UP);
if (this.began_) {
- this.x_.release();
- this.y_.release();
+ this.motion_?.release();
event.stopPropagation();
}
this.began_ = false;
@@ -259,13 +281,15 @@ export class ScrollView extends Component {
EventHandler.emitEvents(this.scrollEvents, this, type);
this.node.emit(type, this);
if (type !== EventType.SCROLLING) return;
+ const o = this.motion_?.container.getOffset() ?? { x: 0, y: 0 };
+ const m = this.motion_?.container.getMaxOffset() ?? { x: 0, y: 0 };
const e = this.edge_;
- const atTop = this.y_.offset <= 0, atBottom = this.y_.offset >= this.y_.max && this.y_.max > 0;
- const atLeft = this.x_.offset <= 0, atRight = this.x_.offset >= this.x_.max && this.x_.max > 0;
- if (atTop && !e.top) { this.notifyEdge_(EventType.SCROLL_TO_TOP); }
- if (atBottom && !e.bottom) { this.notifyEdge_(EventType.SCROLL_TO_BOTTOM); }
- if (atLeft && !e.left) { this.notifyEdge_(EventType.SCROLL_TO_LEFT); }
- if (atRight && !e.right) { this.notifyEdge_(EventType.SCROLL_TO_RIGHT); }
+ const atTop = o.y <= 0, atBottom = o.y >= m.y && m.y > 0;
+ const atLeft = o.x <= 0, atRight = o.x >= m.x && m.x > 0;
+ if (atTop && !e.top) this.notifyEdge_(EventType.SCROLL_TO_TOP);
+ if (atBottom && !e.bottom) this.notifyEdge_(EventType.SCROLL_TO_BOTTOM);
+ if (atLeft && !e.left) this.notifyEdge_(EventType.SCROLL_TO_LEFT);
+ if (atRight && !e.right) this.notifyEdge_(EventType.SCROLL_TO_RIGHT);
e.top = atTop; e.bottom = atBottom; e.left = atLeft; e.right = atRight;
}
diff --git a/sdk/src/ui/behavior/plugin.ts b/sdk/src/ui/behavior/plugin.ts
index a230754e2..836389113 100644
--- a/sdk/src/ui/behavior/plugin.ts
+++ b/sdk/src/ui/behavior/plugin.ts
@@ -22,7 +22,7 @@ import { ScrollContainer, ScrollContainerRegistry } from '../collection/scroll-c
import { createScrollAdoptSystem } from './scroll';
import { engineApi } from '../../ecs/bridge/engineApi';
import type { CppRegistry } from '../../wasm';
-import { KineticScroll } from '../collection/kinetic-scroll';
+import { ScrollMotion } from '../collection/scroll-motion';
import { Interactable, UIInteraction, type UIInteractionData } from '../input/interactable';
import { UINode } from '../core/ui-node';
import { getEntityDepth, walkParentChain } from '../util/helpers';
@@ -198,11 +198,11 @@ export class UIBehaviorPlugin implements Plugin {
);
// Fling state per scroll entity, shared between the wheel and drag
// systems so either input source interrupts a coast.
- const dynamics = new Map<Entity, { container: ScrollContainer; motion: KineticScroll }>();
- const dynamicsFor = (entity: Entity, container: ScrollContainer): KineticScroll => {
+ const dynamics = new Map<Entity, { container: ScrollContainer; motion: ScrollMotion }>();
+ const dynamicsFor = (entity: Entity, container: ScrollContainer): ScrollMotion => {
let d = dynamics.get(entity);
if (!d || d.container !== container) {
- d = { container, motion: new KineticScroll({ decelerationRate: container.getDecelerationRate() }) };
+ d = { container, motion: new ScrollMotion(container) };
dynamics.set(entity, d);
}
return d.motion;
@@ -271,8 +271,6 @@ export class UIBehaviorPlugin implements Plugin {
let capturedContainer: ScrollContainer | null = null;
let lastCancellationVersion = primaryPointerCancellationVersion(app.getResource(Input));
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), Res(ScreenLayout), Res(ScreenOverlay)],
@@ -332,9 +330,7 @@ export class UIBehaviorPlugin implements Plugin {
if (screenDist >= SCROLL_DRAG_THRESHOLD_PX) {
activeEntity = pendingEntity;
pendingEntity = null;
- grabStartOffset = container.getOffset();
- lastOffset = { x: grabStartOffset.x, y: grabStartOffset.y };
- dynamicsFor(activeEntity, container).beginDrag();
+ dynamicsFor(activeEntity, container).grab();
}
}
}
@@ -358,37 +354,23 @@ export class UIBehaviorPlugin implements Plugin {
const pointer = pointerFor(activeEntity);
const totalDx = pointer.x - grabStartWorld.x;
const totalDy = pointer.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;
+ dyn.dragBy({ x: -totalDx / sx, y: totalDy / sy }, time.delta);
if (!input.isMouseButtonDown(0)) {
- dyn.endDrag(); // sampled velocity carries into the coast
+ dyn.release(); // sampled velocity carries into the coast; an over-pulled end springs back
activeEntity = null;
}
}
- // Coast: tick flung containers; an axis the clamp stops is dead.
+ // Coast and spring: tick what was let go of. An axis the clamp stops hands its speed to the overscroll.
for (const [entity, state] of dynamics) {
const container = scrollContainers.get(entity);
if (container !== state.container || !scrollAvailable(entity)) {
dynamics.delete(entity);
continue;
}
- const dyn = state.motion;
- if (!dyn.isCoasting()) 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');
+ state.motion.tick(time.delta);
}
},
{ name: 'ScrollDragSystem', runAfter: [SystemLabel.UIInteraction] },
diff --git a/sdk/src/ui/behavior/scroll.ts b/sdk/src/ui/behavior/scroll.ts
index a0cbf8b47..d088ee0c7 100644
--- a/sdk/src/ui/behavior/scroll.ts
+++ b/sdk/src/ui/behavior/scroll.ts
@@ -104,19 +104,24 @@ export function createScrollAdoptSystem(
wheelSpeed: scroll.wheelSpeed,
dragScroll: scroll.dragScroll,
decelerationRate: scroll.movement === ScrollMovement.Elastic ? scroll.decelerationRate : 0,
+ elastic: scroll.movement === ScrollMovement.Elastic,
initialOffset: offset,
});
// The offset moves the content by its insets, exactly as the widget does,
// so both paths leave the same thing in the scene.
+ // …and shows it pulled past an end by the overscroll, when the area is elastic.
const applyOffset = (offset: Vec2): void => {
const node = world.tryGet(content, UINode);
if (!node) return;
+ const over = container.getOverscroll();
node.position = UIPositionType.Absolute;
- node.insetLeft = px(-offset.x);
- node.insetTop = px(-offset.y);
+ node.insetLeft = px(-(offset.x + over.x));
+ node.insetTop = px(-(offset.y + over.y));
world.insert(content, UINode, node);
};
- const unsubscribe = container.onScroll(applyOffset);
+ const unsubscribeScroll = container.onScroll(applyOffset);
+ const unsubscribeOver = container.onOverscroll((_over, offset) => applyOffset(offset));
+ const unsubscribe = (): void => { unsubscribeScroll(); unsubscribeOver(); };
const clamped = container.getOffset();
if (clamped.x !== offset.x || clamped.y !== offset.y) applyOffset(clamped);
host.attachScrollContainer(entity, container);
diff --git a/sdk/src/ui/collection/scroll-container.ts b/sdk/src/ui/collection/scroll-container.ts
index cdbf09570..218c30418 100644
--- a/sdk/src/ui/collection/scroll-container.ts
+++ b/sdk/src/ui/collection/scroll-container.ts
@@ -17,9 +17,32 @@ export interface ScrollContainerOptions {
decelerationRate?: number;
/** Auto-fading overlay scrollbar thumbs. Default true. */
showScrollbar?: boolean;
+ /**
+ * Let a drag pull the content past either end (rubber-banded, so the further out, the stiffer), and spring it back when let go.
+ * The offset itself stays clamped; the extra is {@link ScrollContainer.getOverscroll}. Default false.
+ */
+ elastic?: boolean;
+ /** Seconds the spring back takes to settle. Default 0.5. */
+ bounceTime?: number;
}
export type ScrollListener = (offset: Vec2) => void;
+/** Told when the overscroll changes; @p offset is the (clamped) offset it is measured from. */
+export type OverscrollListener = (overscroll: Vec2, offset: Vec2) => void;
+
+/** How far a pull of @p distance past an end shows, for a viewport of @p view: stiffer the further out, never more than the viewport. */
+export function rubberBand(distance: number, view: number): number {
+ if (distance === 0 || view <= 0) return 0;
+ const d = Math.abs(distance);
+ return Math.sign(distance) * view * (1 - 1 / ((d * 0.55) / view + 1));
+}
+
+/** The pull that {@link rubberBand} turns into @p shown: what the finger has travelled past the end to hold the content there. */
+export function rubberBandInverse(shown: number, view: number): number {
+ if (shown === 0 || view <= 0) return 0;
+ const r = Math.min(0.999, Math.abs(shown) / view);
+ return Math.sign(shown) * (view * r) / (0.55 * (1 - r));
+}
/**
* Scroll state for a virtualized view. Clamps offset to the legal range
@@ -39,6 +62,11 @@ export class ScrollContainer {
private readonly decelerationRate_: number;
private readonly showScrollbar_: boolean;
private readonly listeners_ = new Set<ScrollListener>();
+ private readonly overListeners_ = new Set<OverscrollListener>();
+ private readonly elastic_: boolean;
+ private readonly bounceTime_: number;
+ private over_: Vec2 = { x: 0, y: 0 };
+ private overVel_: Vec2 = { x: 0, y: 0 };
constructor(opts: ScrollContainerOptions) {
this.viewportSize_ = { x: opts.viewportSize.x, y: opts.viewportSize.y };
@@ -48,6 +76,8 @@ export class ScrollContainer {
this.dragScroll_ = opts.dragScroll ?? true;
this.decelerationRate_ = opts.decelerationRate ?? 0.135;
this.showScrollbar_ = opts.showScrollbar ?? true;
+ this.elastic_ = opts.elastic ?? false;
+ this.bounceTime_ = Math.max(0.05, opts.bounceTime ?? 0.5);
this.setOffset(opts.initialOffset ?? { x: 0, y: 0 });
}
@@ -105,6 +135,85 @@ export class ScrollContainer {
}
}
+ isElastic(): boolean {
+ return this.elastic_;
+ }
+
+ /** How far the content is pulled past an end on each axis: negative before the start, positive past the end, 0 inside. */
+ getOverscroll(): Vec2 {
+ return { x: this.over_.x, y: this.over_.y };
+ }
+
+ /** Whether the content is out past an end, or still moving back from it. */
+ isSpringing(): boolean {
+ return this.over_.x !== 0 || this.over_.y !== 0 || this.overVel_.x !== 0 || this.overVel_.y !== 0;
+ }
+
+ /**
+ * Put the content where a finger holding it would: @p raw is the UNCLAMPED offset the drag asks for. Inside the range it is the
+ * offset; past an end the offset stops there and the rest is shown as rubber-banded overscroll. Not elastic, this is `setOffset`.
+ */
+ dragTo(raw: Vec2): void {
+ this.setOffset(raw);
+ if (!this.elastic_) return;
+ const max = this.getMaxOffset();
+ const lockX = this.direction_ === 'vertical';
+ const lockY = this.direction_ === 'horizontal';
+ this.setOverscroll({
+ x: lockX ? 0 : rubberBand(raw.x - clamp(raw.x, 0, max.x), this.viewportSize_.x),
+ y: lockY ? 0 : rubberBand(raw.y - clamp(raw.y, 0, max.y), this.viewportSize_.y),
+ }, { x: 0, y: 0 });
+ }
+
+ /** Take the speed out of the spring, leaving the content where it is. */
+ releaseSpring(): void {
+ this.overVel_ = { x: 0, y: 0 };
+ }
+
+ /** Momentum arriving at an end: some of it goes into the overscroll, which then springs back. */
+ absorb(axis: 'x' | 'y', velocity: number): void {
+ if (!this.elastic_) return;
+ this.overVel_[axis] += velocity * 0.3;
+ }
+
+ /** Advance the spring by @p dt seconds. Returns whether the overscroll changed. */
+ tickSpring(dt: number): boolean {
+ if (!this.elastic_ || dt <= 0 || !this.isSpringing()) return false;
+ // critically damped, in closed form so the step size does not matter; tuned so it has all but settled by `bounceTime`
+ const w = 7 / this.bounceTime_;
+ const decay = Math.exp(-w * dt);
+ const x = { ...this.over_ };
+ const v = { ...this.overVel_ };
+ for (const axis of ['x', 'y'] as const) {
+ const c = v[axis] + w * x[axis];
+ x[axis] = decay * (x[axis] + c * dt);
+ v[axis] = decay * (v[axis] - w * c * dt);
+ }
+ for (const axis of ['x', 'y'] as const) {
+ if (Math.abs(x[axis]) < 0.1 && Math.abs(v[axis]) < 1) { x[axis] = 0; v[axis] = 0; }
+ }
+ return this.setOverscroll(x, v);
+ }
+
+ private setOverscroll(over: Vec2, velocity: Vec2): boolean {
+ const changed = over.x !== this.over_.x || over.y !== this.over_.y;
+ this.over_ = over;
+ this.overVel_ = velocity;
+ if (changed) this.notifyOver_();
+ return changed;
+ }
+
+ private notifyOver_(): void {
+ const offset = this.getOffset();
+ for (const listener of Array.from(this.overListeners_)) {
+ try {
+ listener({ x: this.over_.x, y: this.over_.y }, offset);
+ } catch (err) {
+ log.error('ui', 'ScrollContainer overscroll listener error', err);
+ }
+ }
+ }
+
scrollBy(delta: Vec2): void {
this.setOffset({
x: this.offset_.x + delta.x,
@@ -136,8 +245,16 @@ export class ScrollContainer {
};
}
+ onOverscroll(listener: OverscrollListener): () => void {
+ this.overListeners_.add(listener);
+ return () => {
+ this.overListeners_.delete(listener);
+ };
+ }
+
dispose(): void {
this.listeners_.clear();
+ this.overListeners_.clear();
}
}
diff --git a/sdk/src/ui/collection/scroll-motion.ts b/sdk/src/ui/collection/scroll-motion.ts
new file mode 100644
index 000000000..7ae69f6e3
--- /dev/null
+++ b/sdk/src/ui/collection/scroll-motion.ts
@@ -0,0 +1,112 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/collection/scroll-motion.ts
+ * @brief ScrollMotion — what a hand does to a scroll area, over a ScrollContainer and a KineticScroll.
+ *
+ * The container knows where the content is and how far past an end it is pulled; the kinetic model knows how fast it was going when
+ * let go. This ties them into the gesture: grab, drag, let go, and what follows — a coast that carries on after a flick, a spring
+ * that returns an over-pulled end, and a timed scroll to a place. It has no input or ECS knowledge, so the UI scroll system and any
+ * other host (a world-space node scrolled by touch) drive the same motion.
+ */
+import type { Vec2 } from '../../types';
+import { KineticScroll } from './kinetic-scroll';
+import { rubberBandInverse, type ScrollContainer } from './scroll-container';
+
+const easeOutQuint = (t: number): number => { const k = t - 1; return k * k * k * k * k + 1; };
+
+export class ScrollMotion {
+ readonly kinetic: KineticScroll;
+ private grabOffset_: Vec2 = { x: 0, y: 0 };
+ private last_: Vec2 = { x: 0, y: 0 };
+ private dragging_ = false;
+ private anim_: { from: Vec2; to: Vec2; t: number; duration: number } | null = null;
+
+ constructor(readonly container: ScrollContainer, kinetic?: KineticScroll) {
+ this.kinetic = kinetic ?? new KineticScroll({ decelerationRate: container.getDecelerationRate() });
+ }
+
+ get isDragging(): boolean { return this.dragging_; }
+
+ /** Whether anything is still moving: a coast, a spring, or a timed scroll. */
+ get isMoving(): boolean {
+ return this.anim_ !== null || this.kinetic.isCoasting() || this.container.isSpringing();
+ }
+
+ /**
+ * A finger takes hold. Whatever was moving stops where it is; if the content was over-pulled, the grab continues from
+ * there rather than snapping back.
+ */
+ grab(): void {
+ this.kinetic.stop();
+ this.anim_ = null;
+ this.container.releaseSpring();
+ const offset = this.container.getOffset();
+ const over = this.container.getOverscroll();
+ const view = this.container.getViewportSize();
+ this.grabOffset_ = { x: offset.x + rubberBandInverse(over.x, view.x), y: offset.y + rubberBandInverse(over.y, view.y) };
+ this.last_ = offset;
+ this.dragging_ = true;
+ this.kinetic.beginDrag();
+ }
+
+ /**
+ * The finger is @p total (in offset units, positive = content toward its end) from where it took hold, @p dt after the last call.
+ * The mapping is absolute from the grab point, so a pull past an end re-tracks the finger when it comes back.
+ */
+ dragBy(total: Vec2, dt: number): void {
+ if (!this.dragging_) return;
+ this.container.dragTo({ x: this.grabOffset_.x + total.x, y: this.grabOffset_.y + total.y });
+ const now = this.container.getOffset();
+ this.kinetic.sample({ x: now.x - this.last_.x, y: now.y - this.last_.y }, dt);
+ this.last_ = now;
+ }
+
+ /** The finger lifts: the speed it had carries on as a coast, and an over-pulled end springs back. */
+ release(): void {
+ if (!this.dragging_) return;
+ this.dragging_ = false;
+ this.kinetic.endDrag();
+ }
+
+ /** Stop everything where it is. */
+ stop(): void {
+ this.dragging_ = false;
+ this.anim_ = null;
+ this.kinetic.stop();
+ this.container.releaseSpring();
+ }
+
+ /** Move to @p target (clamped) over @p seconds, easing out; 0 jumps. */
+ animateTo(target: Vec2, seconds: number): void {
+ this.kinetic.stop();
+ if (seconds <= 0) { this.anim_ = null; this.container.setOffset(target); return; }
+ this.anim_ = { from: this.container.getOffset(), to: target, t: 0, duration: seconds };
+ }
+
+ /** Advance @p dt seconds. Returns whether the offset or the overscroll changed. */
+ tick(dt: number): boolean {
+ if (this.dragging_) return false;
+ let changed = false;
+ if (this.anim_) {
+ const a = this.anim_;
+ a.t += dt;
+ const k = a.t >= a.duration - 1e-9 ? 1 : easeOutQuint(a.t / a.duration);
+ const before = this.container.getOffset();
+ this.container.setOffset({ x: a.from.x + (a.to.x - a.from.x) * k, y: a.from.y + (a.to.y - a.from.y) * k });
+ const after = this.container.getOffset();
+ changed = after.x !== before.x || after.y !== before.y;
+ if (k >= 1) this.anim_ = null;
+ } else if (this.kinetic.isCoasting()) {
+ const delta = this.kinetic.tick(dt);
+ const before = this.container.getOffset();
+ this.container.scrollBy(delta);
+ const after = this.container.getOffset();
+ const velocity = this.kinetic.getVelocity();
+ if (delta.x !== 0 && after.x === before.x) { this.container.absorb('x', velocity.x); this.kinetic.killAxis('x'); }
+ if (delta.y !== 0 && after.y === before.y) { this.container.absorb('y', velocity.y); this.kinetic.killAxis('y'); }
+ changed = after.x !== before.x || after.y !== before.y;
+ }
+ return this.container.tickSpring(dt) || changed;
+ }
+}
diff --git a/sdk/src/ui/collection/scroll-physics.ts b/sdk/src/ui/collection/scroll-physics.ts
deleted file mode 100644
index b10391245..000000000
--- a/sdk/src/ui/collection/scroll-physics.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file ui/collection/scroll-physics.ts
- * @brief Drag, inertia and elastic bounce for a scrolled content rectangle — independent of how the UI is laid out.
- *
- * A scroll area is two rectangles on one axis: the view, and the content that moves inside it. This module knows nothing of nodes
- * or layout; it is given the two extents, told about drag deltas and releases, and answers where the content should be. A host
- * (a UINode scroll container, a world-space node in the Cocos compatibility layer) reads the position back each frame and applies it.
- *
- * Positions are the content's offset from "top/left edge aligned with the view's": 0 is aligned, and scrolling toward the end is
- * a growing positive offset up to {@link ScrollAxis.max}. Past either end is overscroll. All values are in the host's own units.
- *
- * The feel: a drag past an end is damped the further it goes; a release with velocity glides to rest on a quintic ease-out whose
- * length and time follow the speed; a rest position past an end springs back over `bounceTime`; `brake` shortens the glide.
- */
-
-export interface ScrollSettings {
- /** Glide after release. */
- inertia: boolean;
- /** Allow overscroll with a spring back; off clamps hard. */
- elastic: boolean;
- /** 0..1: how hard the glide is cut short. 1 stops at once. */
- brake: number;
- /** Seconds for the spring back. */
- bounceTime: number;
-}
-
-export const DEFAULT_SCROLL: Readonly<ScrollSettings> = { inertia: true, elastic: true, brake: 0.5, bounceTime: 1 };
-
-const quintOut = (t: number): number => { const k = t - 1; return k * k * k * k * k + 1; };
-
-/** One axis of a scroll area. */
-export class ScrollAxis {
- /** The content's offset: 0 = start edges aligned, `max` = end edges aligned. */
- offset = 0;
- /** content extent - view extent, never negative. */
- max = 0;
- private from_ = 0;
- private to_ = 0;
- private t_ = 0;
- private duration_ = 0;
- private mode_: 'idle' | 'glide' | 'bounce' = 'idle';
- private samples_: Array<{ t: number; offset: number }> = [];
-
- constructor(public settings: ScrollSettings = { ...DEFAULT_SCROLL }) {}
-
- /** Set the extents; the offset is kept. */
- setExtents(view: number, content: number): void { this.max = Math.max(0, content - view); }
-
- get moving(): boolean { return this.mode_ !== 'idle'; }
-
- /** How far past an end the offset is: negative before the start, positive past the end, 0 inside. */
- get overscroll(): number {
- if (this.offset < 0) return this.offset;
- if (this.offset > this.max) return this.offset - this.max;
- return 0;
- }
-
- /** A finger lands: any glide stops where it is. */
- press(): void {
- this.mode_ = 'idle';
- this.samples_ = [];
- }
-
- /** The finger moved by @p delta (positive = content toward its end), at @p time seconds. */
- drag(delta: number, time: number, viewExtent: number): void {
- const dir = Math.sign(delta);
- let remaining = Math.abs(delta);
- // the part of the move that stays inside the range is free; only what goes past an end is damped
- const over = this.overscroll;
- if (over === 0 || Math.sign(over) !== dir) {
- const room = dir > 0 ? this.max - this.offset : this.offset; // distance to the end this move heads for
- const free = over !== 0 ? remaining : Math.min(remaining, Math.max(0, room));
- this.offset += dir * free;
- remaining -= free;
- }
- if (remaining > 0) {
- if (!this.settings.elastic) {
- this.offset = Math.min(this.max, Math.max(0, this.offset));
- } else {
- const out = Math.abs(this.overscroll);
- this.offset += dir * remaining * Math.max(0, 1 - out / Math.max(viewExtent, 1)) * 0.5;
- }
- }
- this.samples_.push({ t: time, offset: this.offset });
- while (this.samples_.length > 2 && time - this.samples_[0]!.t > 0.1) this.samples_.shift();
- }
-
- /** The finger lifted: glide if it was moving, then settle. */
- release(): void {
- const v = this.velocity_();
- this.samples_ = [];
- if (this.overscroll !== 0) { this.bounceBack_(); return; }
- if (this.settings.inertia && Math.abs(v) > 20) this.glide_(v);
- else this.mode_ = 'idle';
- }
-
- /** Move to @p target (clamped unless elastic) over @p seconds; 0 jumps. */
- scrollTo(target: number, seconds = 0, attenuated = true): void {
- const clamped = Math.min(this.max, Math.max(0, target));
- if (seconds <= 0) { this.offset = clamped; this.mode_ = 'idle'; return; }
- this.from_ = this.offset;
- this.to_ = clamped;
- this.t_ = 0;
- this.duration_ = seconds;
- this.mode_ = attenuated ? 'glide' : 'bounce';
- }
-
- stop(): void { this.mode_ = 'idle'; }
-
- /** Advance @p dt seconds. Returns true if the offset changed. */
- update(dt: number): boolean {
- if (this.mode_ === 'idle') return false;
- this.t_ += dt;
- const k = Math.min(1, this.t_ / this.duration_);
- const before = this.offset;
- this.offset = this.from_ + (this.to_ - this.from_) * quintOut(k);
- if (k >= 1) {
- this.offset = this.to_;
- // a glide that ended past an end (elastic) springs back
- if (this.mode_ === 'glide' && this.overscroll !== 0) this.bounceBack_(); else this.mode_ = 'idle';
- } else if (this.mode_ === 'glide' && this.settings.elastic === false) {
- this.offset = Math.min(this.max, Math.max(0, this.offset));
- }
- return this.offset !== before;
- }
-
- private velocity_(): number {
- const s = this.samples_;
- if (s.length < 2) return 0;
- const a = s[0]!, b = s[s.length - 1]!;
- const dt = b.t - a.t;
- return dt > 0 ? (b.offset - a.offset) / dt : 0;
- }
-
- private bounceBack_(): void {
- this.from_ = this.offset;
- this.to_ = Math.min(this.max, Math.max(0, this.offset));
- this.t_ = 0;
- this.duration_ = Math.max(this.settings.bounceTime, 0.01);
- this.mode_ = 'bounce';
- }
-
- private glide_(velocity: number): void {
- const speed = Math.abs(velocity);
- // longer for a harder flick; the brake cuts both distance and time
- const keep = 1 - Math.min(1, Math.max(0, this.settings.brake)) * 0.6;
- const duration = Math.min(4, Math.sqrt(Math.sqrt(speed / 5))) * keep;
- const distance = velocity * 0.7 * keep;
- this.from_ = this.offset;
- let to = this.offset + distance;
- if (!this.settings.elastic) to = Math.min(this.max, Math.max(0, to));
- this.to_ = to;
- this.t_ = 0;
- this.duration_ = Math.max(duration, 0.05);
- this.mode_ = 'glide';
- }
-}
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 6ee666a32..7ffb262c1 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -248,8 +248,13 @@ export {
ScrollContainerRegistry,
type ScrollContainerOptions,
type ScrollListener,
+ type OverscrollListener,
+ rubberBand,
+ rubberBandInverse,
} from './collection/scroll-container';
+export { ScrollMotion } from './collection/scroll-motion';
+
export {
KineticScroll,
type KineticScrollOptions,
diff --git a/sdk/tests/ui-scroll-elastic.test.ts b/sdk/tests/ui-scroll-elastic.test.ts
new file mode 100644
index 000000000..30fc68dfa
--- /dev/null
+++ b/sdk/tests/ui-scroll-elastic.test.ts
@@ -0,0 +1,184 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Pulling a scroll area past its end and letting it spring back, and the gesture (grab, drag, let go, coast) around it.
+ *
+ * No input, no ECS, no engine: ScrollContainer, KineticScroll and ScrollMotion are models. What is pinned is what a hand feels: a
+ * pull past an end is stiffer the further out it goes and never more than the viewport, the offset itself never leaves its range,
+ * letting go returns the content to its end, a flick that reaches an end bounces instead of stopping dead, and taking hold of
+ * content in mid-bounce continues from where it is.
+ */
+import { describe, expect, it } from 'vitest';
+import { ScrollContainer, rubberBand, rubberBandInverse } from '../src/ui/collection/scroll-container';
+import { ScrollMotion } from '../src/ui/collection/scroll-motion';
+
+const view = { x: 300, y: 400 };
+
+function area(over: Partial<ConstructorParameters<typeof ScrollContainer>[0]> = {}): ScrollContainer {
+ return new ScrollContainer({ viewportSize: view, contentSize: { x: 300, y: 1400 }, elastic: true, bounceTime: 0.4, ...over });
+}
+
+const run = (m: ScrollMotion, seconds: number, dt = 1 / 60): void => { for (let t = 0; t < seconds; t += dt) m.tick(dt); };
+
+describe('rubber banding', () => {
+ it('is zero for no pull, grows with the pull, and never reaches the viewport', () => {
+ expect(rubberBand(0, 400)).toBe(0);
+ const a = rubberBand(50, 400), b = rubberBand(200, 400), c = rubberBand(100000, 400);
+ expect(a).toBeGreaterThan(0);
+ expect(b).toBeGreaterThan(a);
+ expect(c).toBeLessThan(400);
+ expect(rubberBand(-50, 400)).toBe(-a);
+ });
+
+ it('is stiffer the further out: the second 100px of pull shows less than the first', () => {
+ expect(rubberBand(200, 400) - rubberBand(100, 400)).toBeLessThan(rubberBand(100, 400));
+ });
+
+ it('has an inverse: the pull that holds the content where it is shown', () => {
+ for (const pull of [10, 80, 300, 900]) expect(rubberBandInverse(rubberBand(pull, 400), 400)).toBeCloseTo(pull, 5);
+ expect(rubberBandInverse(-rubberBand(70, 400), 400)).toBeCloseTo(-70, 5);
+ });
+});
+
+describe('ScrollContainer overscroll', () => {
+ it('is off by default: a pull past an end is just clamped', () => {
+ const c = area({ elastic: false });
+ c.dragTo({ x: 0, y: -80 });
+ expect(c.getOffset().y).toBe(0);
+ expect(c.getOverscroll()).toEqual({ x: 0, y: 0 });
+ });
+
+ it('keeps the offset in range and shows the pull past an end as overscroll, in the direction of the pull', () => {
+ const c = area();
+ c.dragTo({ x: 0, y: -80 }); // 80 before the start
+ expect(c.getOffset().y).toBe(0);
+ expect(c.getOverscroll().y).toBeLessThan(0);
+ expect(c.getOverscroll().y).toBeGreaterThan(-80);
+ c.dragTo({ x: 0, y: 1000 + 80 }); // 80 past the end (max is 1000)
+ expect(c.getOffset().y).toBe(1000);
+ expect(c.getOverscroll().y).toBeGreaterThan(0);
+ });
+
+ it('does not overscroll an axis it does not scroll', () => {
+ const c = area({ direction: 'vertical' });
+ c.dragTo({ x: -50, y: 20 });
+ expect(c.getOverscroll().x).toBe(0);
+ });
+
+ it('springs back to its end by the bounce time, and says so, without touching the offset', () => {
+ const c = area();
+ c.dragTo({ x: 0, y: -120 });
+ const seen: number[] = [];
+ const scrolled: number[] = [];
+ c.onOverscroll((o) => seen.push(o.y));
+ c.onScroll(() => scrolled.push(1));
+ for (let t = 0; t < 0.4 * 1.5; t += 1 / 60) c.tickSpring(1 / 60);
+ expect(c.getOverscroll().y).toBe(0);
+ expect(c.isSpringing()).toBe(false);
+ expect(seen.length).toBeGreaterThan(1);
+ expect(Math.abs(seen[0]!)).toBeGreaterThan(Math.abs(seen[seen.length - 2]!)); // it only closes
+ expect(scrolled).toEqual([]); // the offset never moved
+ });
+
+ it('does not tick when it is not elastic or has nothing to return', () => {
+ expect(area({ elastic: false }).tickSpring(1 / 60)).toBe(false);
+ expect(area().tickSpring(1 / 60)).toBe(false);
+ });
+});
+
+describe('ScrollMotion', () => {
+ it('follows a drag, with the offset moving until an end and the overscroll after it', () => {
+ const c = area();
+ const m = new ScrollMotion(c);
+ m.grab();
+ m.dragBy({ x: 0, y: 300 }, 1 / 60);
+ expect(c.getOffset().y).toBe(300);
+ expect(c.getOverscroll().y).toBe(0);
+ m.dragBy({ x: 0, y: 1100 }, 1 / 60); // 100 past the end
+ expect(c.getOffset().y).toBe(1000);
+ expect(c.getOverscroll().y).toBeGreaterThan(0);
+ // pulling back re-tracks the finger from the grab point
+ m.dragBy({ x: 0, y: 600 }, 1 / 60);
+ expect(c.getOffset().y).toBe(600);
+ expect(c.getOverscroll().y).toBe(0);
+ });
+
+ it('returns an over-pulled end when let go', () => {
+ const c = area();
+ const m = new ScrollMotion(c);
+ m.grab();
+ m.dragBy({ x: 0, y: -150 }, 1 / 60);
+ m.release();
+ expect(m.isMoving).toBe(true);
+ run(m, 1);
+ expect(c.getOverscroll().y).toBe(0);
+ expect(c.getOffset().y).toBe(0);
+ expect(m.isMoving).toBe(false);
+ });
+
+ it('coasts on after a flick, and a flick that reaches an end bounces off it instead of stopping dead', () => {
+ const c = area({ contentSize: { x: 300, y: 700 } }); // only 300 to scroll
+ const m = new ScrollMotion(c);
+ m.grab();
+ for (let i = 1; i <= 8; i++) m.dragBy({ x: 0, y: i * 40 }, 1 / 60); // fast: 40px a frame
+ m.release();
+ let sawOverscroll = false;
+ let maxOffset = 0;
+ for (let t = 0; t < 2; t += 1 / 60) {
+ m.tick(1 / 60);
+ if (c.getOverscroll().y > 0) sawOverscroll = true;
+ maxOffset = Math.max(maxOffset, c.getOffset().y);
+ }
+ expect(maxOffset).toBe(300);
+ expect(sawOverscroll).toBe(true);
+ expect(c.getOverscroll().y).toBe(0);
+ expect(c.getOffset().y).toBe(300);
+ });
+
+ it('stops a coast dead at an end when the area is not elastic', () => {
+ const c = area({ elastic: false, contentSize: { x: 300, y: 700 } });
+ const m = new ScrollMotion(c);
+ m.grab();
+ for (let i = 1; i <= 8; i++) m.dragBy({ x: 0, y: i * 40 }, 1 / 60);
+ m.release();
+ run(m, 2);
+ expect(c.getOffset().y).toBe(300);
+ expect(c.getOverscroll().y).toBe(0);
+ });
+
+ it('takes hold of content in mid-bounce where it is, not where it will end up', () => {
+ const c = area();
+ const m = new ScrollMotion(c);
+ m.grab();
+ m.dragBy({ x: 0, y: -200 }, 1 / 60);
+ m.release();
+ run(m, 0.1);
+ const shown = c.getOffset().y + c.getOverscroll().y;
+ expect(shown).toBeLessThan(0);
+ m.grab();
+ m.dragBy({ x: 0, y: 0 }, 1 / 60); // a finger that has not moved
+ expect(c.getOffset().y + c.getOverscroll().y).toBeCloseTo(shown, 3);
+ });
+
+ it('scrolls to a place over a time, clamped, and stops a coast to do it', () => {
+ const c = area();
+ const m = new ScrollMotion(c);
+ m.animateTo({ x: 0, y: 500 }, 0.5);
+ expect(m.isMoving).toBe(true);
+ run(m, 0.6);
+ expect(c.getOffset().y).toBe(500);
+ expect(m.isMoving).toBe(false);
+ m.animateTo({ x: 0, y: 99999 }, 0);
+ expect(c.getOffset().y).toBe(1000);
+ });
+
+ it('does not move on its own while a finger holds it', () => {
+ const c = area();
+ const m = new ScrollMotion(c);
+ m.grab();
+ m.dragBy({ x: 0, y: -100 }, 1 / 60);
+ const held = c.getOverscroll().y;
+ run(m, 1);
+ expect(c.getOverscroll().y).toBe(held);
+ });
+});
diff --git a/sdk/tests/ui/scroll-physics.test.ts b/sdk/tests/ui/scroll-physics.test.ts
deleted file mode 100644
index fbfcb1371..000000000
--- a/sdk/tests/ui/scroll-physics.test.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file Drag, inertia and elastic bounce, with no layout or engine in the way.
- */
-import { describe, expect, it } from 'vitest';
-import { ScrollAxis } from '../../src/ui/collection/scroll-physics';
-
-const run = (axis: ScrollAxis, seconds: number): void => { for (let i = 0; i < seconds * 60; i++) axis.update(1 / 60); };
-
-function axis(max = 500, over: Partial<ConstructorParameters<typeof ScrollAxis>[0]> = {}): ScrollAxis {
- const a = new ScrollAxis({ inertia: true, elastic: true, brake: 0.5, bounceTime: 0.5, ...over });
- a.setExtents(400, 400 + max);
- return a;
-}
-
-describe('ScrollAxis', () => {
- it('follows a drag inside its range', () => {
- const a = axis();
- a.press();
- a.drag(30, 0.0, 400);
- a.drag(20, 0.1, 400);
- expect(a.offset).toBe(50);
- expect(a.overscroll).toBe(0);
- });
-
- it('damps a drag past an end, more the further out it goes, and lets it back in freely', () => {
- const a = axis();
- a.press();
- a.drag(-100, 0, 400); // 100 past the start
- const first = a.offset;
- expect(first).toBeLessThan(0);
- expect(first).toBeGreaterThan(-100); // damped
- a.drag(-100, 0.05, 400);
- expect(a.offset - first).toBeGreaterThan(-100 * 0.5); // the second step moves less than the first would have
- const out = a.offset;
- a.drag(20, 0.1, 400);
- expect(a.offset).toBe(out + 20); // back in: undamped
- });
-
- it('springs back inside its range after a release past an end', () => {
- const a = axis(500, { bounceTime: 0.5 });
- a.press();
- a.drag(-80, 0, 400);
- a.release();
- run(a, 0.6);
- expect(a.offset).toBeCloseTo(0, 3);
- expect(a.moving).toBe(false);
- });
-
- it('glides on after a flick, further for a harder one, and rests', () => {
- const slow = axis(5000), fast = axis(5000);
- for (const [a, step] of [[slow, 10], [fast, 40]] as const) {
- a.press();
- for (let i = 0; i < 6; i++) a.drag(step, i * 0.016, 400);
- a.release();
- }
- const atRelease = { slow: slow.offset, fast: fast.offset };
- run(slow, 5); run(fast, 5);
- expect(slow.offset).toBeGreaterThan(atRelease.slow);
- expect(fast.offset - atRelease.fast).toBeGreaterThan(slow.offset - atRelease.slow);
- expect(slow.moving).toBe(false);
- expect(fast.moving).toBe(false);
- });
-
- it('does not glide with inertia off, and a finger landing stops a glide where it is', () => {
- const still = axis(5000, { inertia: false });
- still.press();
- for (let i = 0; i < 6; i++) still.drag(30, i * 0.016, 400);
- still.release();
- const rest = still.offset;
- run(still, 1);
- expect(still.offset).toBe(rest);
-
- const a = axis(5000);
- a.press();
- for (let i = 0; i < 6; i++) a.drag(30, i * 0.016, 400);
- a.release();
- run(a, 0.2);
- const mid = a.offset;
- a.press();
- run(a, 1);
- expect(a.offset).toBe(mid);
- });
-
- it('clamps hard when it is not elastic', () => {
- const a = axis(500, { elastic: false });
- a.press();
- a.drag(-100, 0, 400);
- expect(a.offset).toBe(0);
- a.drag(2000, 0.1, 400);
- expect(a.offset).toBe(500);
- });
-
- it('scrolls to a place over a time, clamped to its range, or at once', () => {
- const a = axis(500);
- a.scrollTo(300, 1);
- run(a, 1.1);
- expect(a.offset).toBe(300);
- a.scrollTo(9999);
- expect(a.offset).toBe(500);
- a.scrollTo(-5);
- expect(a.offset).toBe(0);
- });
-
- it('has nothing to scroll when the content fits', () => {
- const a = new ScrollAxis();
- a.setExtents(400, 300);
- expect(a.max).toBe(0);
- });
-});