Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(mobile): finish a released tab swipe on a spring
Elian Doran5f56a2cb0023
diff --git a/apps/client/src/widgets/mobile_widgets/TabSwitcher.tsx b/apps/client/src/widgets/mobile_widgets/TabSwitcher.tsxindex eb1bab7ded..a0159af70c 100644--- a/apps/client/src/widgets/mobile_widgets/TabSwitcher.tsx+++ b/apps/client/src/widgets/mobile_widgets/TabSwitcher.tsx@@ -190,7 +190,7 @@ function useTabSwipe() {if (!gesture?.swipe) return;const isFlick = e.type === "pointerup" && e.timeStamp - gesture.lastTime <= FLICK_WINDOW;- gesture.swipe.release(isFlick ? gesture.velocity : 0);+ gesture.swipe.release(isFlick ? gesture.velocity : 0, gesture.room);},takeSwipe() {const swiped = swipedRef.current;diff --git a/apps/client/src/widgets/mobile_widgets/tab_swipe.spec.ts b/apps/client/src/widgets/mobile_widgets/tab_swipe.spec.tsindex 47db068117..6f0a861e30 100644--- a/apps/client/src/widgets/mobile_widgets/tab_swipe.spec.ts+++ b/apps/client/src/widgets/mobile_widgets/tab_swipe.spec.ts@@ -12,8 +12,11 @@ describe("TabSwipe", () => {vi.spyOn(appContext, "triggerCommand").mockImplementation(async (name) => {log.push(name);});+ let now = 0;vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {- callback(0);+ now += 16;+ const time = now;+ setTimeout(() => callback(time));return 0;});});@@ -28,20 +31,30 @@ describe("TabSwipe", () => {/** A view transition whose slide animates the content's two sides and is held open by `TabSwipe`. */function fakeTransition({ skipped = false } = {}) {const root = document.documentElement;- const animation = (target: Element, pseudoElement: string) => ({- currentTime: 0,- playbackRate: 1,- paused: false,- effect: { target, pseudoElement, getComputedTiming: () => ({ duration: 250 }) },- pause() {- this.paused = true;- },- play() {- this.paused = false;- this.currentTime = this.playbackRate > 0 ? 250 : 0;- },- finished: Promise.resolve()- });+ const animation = (target: Element, pseudoElement: string) => {+ let currentTime = 0;+ return {+ /** Every position the slide was moved to. */+ positions: [] as number[],+ get currentTime() {+ return currentTime;+ },+ set currentTime(time: number) {+ currentTime = time;+ this.positions.push(time);+ },+ playbackRate: 1,+ paused: false,+ effect: { target, pseudoElement, getComputedTiming: () => ({ duration: 250 }) },+ pause() {+ this.paused = true;+ },+ finish() {+ this.paused = false;+ currentTime = this.playbackRate > 0 ? 250 : 0;+ }+ };+ };const outgoing = animation(root, "::view-transition-old(tab-content)");const incoming = animation(root, "::view-transition-new(tab-content)");const unrelated = animation(document.body, "");@@ -81,9 +94,17 @@ describe("TabSwipe", () => {expect(outgoing.currentTime).toBe(250);swipe.move(0.4);+ outgoing.positions.length = 0;swipe.release(0);- expect(outgoing.playbackRate).toBeGreaterThan(0);await finished;+ // The spring carries the slide on from where the finger left it, without passing the end.+ expect(outgoing.positions.length).toBeGreaterThan(5);+ expect(outgoing.positions).toEqual([ ...outgoing.positions ].sort((a, b) => a - b));+ expect(outgoing.positions[0]).toBe(100);+ expect(outgoing.positions.at(-1)).toBe(250);+ expect(outgoing.currentTime).toBe(250);+ // A paused animation would keep the transition from ending.+ expect(outgoing.paused).toBe(false);await vi.waitFor(() => expect(isTabSwipeActive()).toBe(false));expect(log).toEqual([ "activateNextTab", "end" ]);expect(document.documentElement.dataset.tabSlide).toBeUndefined();@@ -96,11 +117,30 @@ describe("TabSwipe", () => {await vi.waitFor(() => expect(outgoing.paused).toBe(true));swipe.move(0.1);swipe.release(0);- expect(outgoing.playbackRate).toBeLessThan(0);await finished;+ expect(outgoing.positions.at(-1)).toBe(0);+ expect(outgoing.currentTime).toBe(0);expect(log).toEqual([ "activateNextTab", "activatePreviousTab", "end" ]);});+ it("starts the spring at the speed of the finger", async () => {+ const firstStep = async (velocity: number) => {+ const { outgoing, finished } = fakeTransition();+ const swipe = new TabSwipe("next");+ await vi.waitFor(() => expect(outgoing.paused).toBe(true));+ swipe.move(0.5);+ outgoing.positions.length = 0;+ swipe.release(velocity, 400);+ await finished;+ return outgoing.positions[1] - outgoing.positions[0];+ };++ const resting = await firstStep(0);+ const flicked = await firstStep(2);+ expect(resting).toBeGreaterThan(0);+ expect(flicked).toBeGreaterThan(2 * resting);+ });+it("settles a flick released before the slide takes over", async () => {const { outgoing, finished } = fakeTransition();@@ -109,6 +149,8 @@ describe("TabSwipe", () => {swipe.release(1);await finished;expect(outgoing.currentTime).toBe(250);+ // A paused animation would keep the transition from ending.+ expect(outgoing.paused).toBe(false);expect(log).toEqual([ "activatePreviousTab", "end" ]);});diff --git a/apps/client/src/widgets/mobile_widgets/tab_swipe.ts b/apps/client/src/widgets/mobile_widgets/tab_swipe.tsindex b59a6ffb22..f82375bf95 100644--- a/apps/client/src/widgets/mobile_widgets/tab_swipe.ts+++ b/apps/client/src/widgets/mobile_widgets/tab_swipe.ts@@ -6,8 +6,12 @@ export type SwipeDirection = "next" | "previous";const COMMIT_PROGRESS = 0.3;/** How fast, in px/ms, a released flick must move toward the other tab to switch whatever its distance. */const COMMIT_VELOCITY = 0.3;-/** How much faster than the full slide the rest of it plays once released. */-const SETTLE_RATE = 1.5;+/** The stiffness of the spring that finishes a released slide, per ms: it settles in about 300 ms. */+const SPRING_OMEGA = 0.022;+/** How close to its end, in progress, the spring counts as settled. */+const SPRING_REST = 0.002;+/** The longest the spring runs, in ms, whatever it started from. */+const SPRING_MAX_DURATION = 1000;/** Longer than any swipe is held; the animation holding the transition open is canceled long before. */const HOLD_DURATION = 1e9;@@ -16,7 +20,8 @@ let activeTransition: ViewTransition | undefined;/*** A tab switch whose slide follows the finger. The tab switches as the swipe starts, inside a view* transition whose animations stay paused while `move()` sets how far they have run. `release()`- * plays them on to the other tab, or back to the first one and switches back to it. Without view+ * carries them on to the other tab, or back to the first one and switches back to it, on a spring+ * that starts at the finger's speed. Without view* transitions, or with animations off, the tab switches on release instead.*/export class TabSwipe {@@ -25,6 +30,8 @@ export class TabSwipe {private readonly direction: SwipeDirection;private progress = 0;private commit?: boolean;+ /** How fast the slide was moving toward the other tab as the finger lifted, in progress per ms. */+ private releaseVelocity = 0;private transition?: ViewTransition;private animations?: Animation[];private hold?: Animation;@@ -45,9 +52,13 @@ export class TabSwipe {this.#seek();}- /** Ends the swipe; `velocity` is how fast, in px/ms, the finger was moving toward the other tab. */- release(velocity: number) {+ /**+ * Ends the swipe; `velocity` is how fast, in px/ms, the finger was moving toward the other tab,+ * and `room` how far, in px, it travels for the whole slide.+ */+ release(velocity: number, room = window.innerWidth) {this.commit = this.progress >= COMMIT_PROGRESS || velocity >= COMMIT_VELOCITY;+ this.releaseVelocity = velocity / room;if (!this.transition) {if (this.commit) void appContext.triggerCommand(getCommand(this.direction));} else if (this.animations) {@@ -103,13 +114,14 @@ export class TabSwipe {}async #settle() {- const animations = this.animations ?? [];- for (const animation of animations) {- animation.playbackRate = this.commit ? SETTLE_RATE : -SETTLE_RATE;- animation.play();- }- await Promise.all(animations.map((animation) => animation.finished));+ const target = this.commit ? 1 : 0;+ await this.#spring(target);+ // Finished, not paused, so that the transition can end once the hold is canceled.+ for (const animation of this.animations ?? []) {+ animation.playbackRate = target ? 1 : -1;+ animation.finish();+ }if (!this.commit) {await appContext.triggerCommand(getCommand(getOpposite(this.direction)));// The transition reveals the page as it ends, so the first tab is drawn before that.@@ -118,6 +130,27 @@ export class TabSwipe {this.hold?.cancel();}+ /** Moves the slide to `target` on a critically damped spring, which settles without bouncing. */+ #spring(target: number) {+ const offset = this.progress - target;+ const velocity = this.releaseVelocity;+ return new Promise<void>((resolve) => {+ let start: number | undefined;+ const step = (time: number) => {+ start ??= time;+ const elapsed = time - start;+ const position = (offset + (velocity + SPRING_OMEGA * offset) * elapsed)+ * Math.exp(-SPRING_OMEGA * elapsed);+ const isSettled = (elapsed > 0 && Math.abs(position) < SPRING_REST)+ || elapsed >= SPRING_MAX_DURATION;+ this.move(isSettled ? target : target + position);+ if (isSettled) resolve();+ else requestAnimationFrame(step);+ };+ requestAnimationFrame(step);+ });+ }+#switchBackIfCanceled() {if (!this.commit) void appContext.triggerCommand(getCommand(getOpposite(this.direction)));}