diff --git a/src/components/timeline/components/clip/clip-component.ts b/src/components/timeline/components/clip/clip-component.ts index 96e71b96..ec11fb11 100644 --- a/src/components/timeline/components/clip/clip-component.ts +++ b/src/components/timeline/components/clip/clip-component.ts @@ -196,7 +196,8 @@ export class ClipComponent { // Once the browser takes a touch as a pan it sends pointercancel, so pointerup means a tap this.element.addEventListener("pointerup", e => { - if (!isTouchPointer(e) || !this.currentState) return; + // A pinch cancels its fingers' lifts + if (!isTouchPointer(e) || e.defaultPrevented || !this.currentState) return; this.options.onSelect(this.currentState.trackIndex, this.currentState.clipIndex, false); }); } diff --git a/src/components/timeline/interaction/interaction-controller.ts b/src/components/timeline/interaction/interaction-controller.ts index 610278a6..30a2ec61 100644 --- a/src/components/timeline/interaction/interaction-controller.ts +++ b/src/components/timeline/interaction/interaction-controller.ts @@ -613,7 +613,8 @@ export class InteractionController implements TimelineInteractionRegistration { /** Once the browser takes a touch as a pan it sends pointercancel, so a pointerup here is a tap */ private onTouchTap(e: PointerEvent): void { // A drag or resize of the selected clip also ends here, on the container that captured it - if (!isTouchPointer(e) || this.state.type !== "idle" || (e.target as HTMLElement).closest(".ss-clip")) return; + // A pinch cancels its fingers' lifts + if (!isTouchPointer(e) || e.defaultPrevented || this.state.type !== "idle" || (e.target as HTMLElement).closest(".ss-clip")) return; this.stateManager.clearSelection(); } @@ -623,7 +624,7 @@ export class InteractionController implements TimelineInteractionRegistration { } /** Abandon the current interaction without executing any command */ - private cancelInteraction(): void { + public cancelInteraction(): void { if (this.state.type === "dragging") this.cancelDrag(this.state); else if (this.state.type === "resizing") this.cancelResize(this.state); this.setIdle(); diff --git a/src/components/timeline/interaction/timeline-pinch.ts b/src/components/timeline/interaction/timeline-pinch.ts new file mode 100644 index 00000000..b59b3984 --- /dev/null +++ b/src/components/timeline/interaction/timeline-pinch.ts @@ -0,0 +1,111 @@ +import type { Seconds } from "@core/timing/types"; + +import { distance, timeToViewX, viewXToTime } from "./interaction-calculations"; + +interface TimelinePinchOptions { + /** The scroller whose scrollLeft keeps the pinched time under the fingers */ + scroller: HTMLElement; + getPixelsPerSecond: () => number; + setZoom: (pixelsPerSecond: number) => void; + /** Ends any lift or drag the first finger started */ + onPinchStart: () => void; +} + +type Pair = [Touch, Touch]; +const span = ([a, b]: Pair) => distance(b.clientX - a.clientX, b.clientY - a.clientY); +const midX = ([a, b]: Pair) => (a.clientX + b.clientX) / 2; + +/** Two fingers on the timeline zoom it around their midpoint; a single finger keeps the browser's own touch handling. */ +export class TimelinePinch { + private pinch: { span: number; pixelsPerSecond: number; time: Seconds } | null = null; + /** + * From a pinch's start until its last finger lifts: touch presses and moves don't reach the timeline, and lifts are + * cancelled so they don't count as taps. The second finger's press lands before the pinch is known, so on the ruler it seeks. + */ + private gestureActive = false; + + constructor( + private readonly root: HTMLElement, + private readonly options: TimelinePinchOptions + ) {} + + public mount(): void { + this.root.addEventListener("touchstart", this.onTouchStart, { passive: false }); + this.root.addEventListener("touchmove", this.onTouchMove, { passive: false }); + this.root.addEventListener("touchend", this.onTouchEnd); + this.root.addEventListener("touchcancel", this.onTouchEnd); + // iOS Safari zooms the page from its own gesture events unless they are cancelled too + this.root.addEventListener("gesturestart", this.onGesture); + this.root.addEventListener("gesturechange", this.onGesture); + ["pointerdown", "pointermove"].forEach(type => this.root.addEventListener(type, this.swallowPointer, true)); + // Lifts still reach every handler, as drags such as the playhead's only end on them + this.root.addEventListener("pointerup", this.markLift, true); + } + + public dispose(): void { + this.root.removeEventListener("touchstart", this.onTouchStart); + this.root.removeEventListener("touchmove", this.onTouchMove); + this.root.removeEventListener("touchend", this.onTouchEnd); + this.root.removeEventListener("touchcancel", this.onTouchEnd); + this.root.removeEventListener("gesturestart", this.onGesture); + this.root.removeEventListener("gesturechange", this.onGesture); + ["pointerdown", "pointermove"].forEach(type => this.root.removeEventListener(type, this.swallowPointer, true)); + this.root.removeEventListener("pointerup", this.markLift, true); + } + + private readonly onTouchStart = (e: TouchEvent): void => { + const pair = this.pairOnTimeline(e); + if (!pair) return; + e.preventDefault(); + this.gestureActive = true; + this.options.onPinchStart(); + + const pixelsPerSecond = this.options.getPixelsPerSecond(); + this.pinch = { span: Math.max(1, span(pair)), pixelsPerSecond, time: viewXToTime(this.contentX(midX(pair)), pixelsPerSecond) }; + }; + + private readonly onTouchMove = (e: TouchEvent): void => { + const pair = this.pairOnTimeline(e); + if (!pair || !this.pinch) return; + e.preventDefault(); + + this.options.setZoom(this.pinch.pixelsPerSecond * (span(pair) / this.pinch.span)); + // Read back after the timeline clamps the zoom + const pixelsPerSecond = this.options.getPixelsPerSecond(); + const { scroller } = this.options; + scroller.scrollLeft = timeToViewX(this.pinch.time, pixelsPerSecond) - (midX(pair) - scroller.getBoundingClientRect().left); + }; + + private readonly onTouchEnd = (e: TouchEvent): void => { + const left = this.onTimeline(e).length; + if (left < 2) this.pinch = null; + if (left === 0) this.gestureActive = false; + }; + + private readonly onGesture = (e: Event): void => { + if (this.gestureActive) e.preventDefault(); + }; + + private readonly swallowPointer = (e: Event): void => { + if (this.gestureActive && (e as PointerEvent).pointerType === "touch") e.stopPropagation(); + }; + + private readonly markLift = (e: Event): void => { + if (this.gestureActive && (e as PointerEvent).pointerType === "touch") e.preventDefault(); + }; + + /** `touches` spans the whole document, and a finger elsewhere on the page is no part of a timeline pinch */ + private onTimeline(e: TouchEvent): Touch[] { + return Array.from(e.touches).filter(touch => this.root.contains(touch.target as Node)); + } + + private pairOnTimeline(e: TouchEvent): Pair | null { + const touches = this.onTimeline(e); + return touches.length === 2 ? [touches[0], touches[1]] : null; + } + + private contentX(clientX: number): number { + const { scroller } = this.options; + return clientX - scroller.getBoundingClientRect().left + scroller.scrollLeft; + } +} diff --git a/src/components/timeline/timeline.ts b/src/components/timeline/timeline.ts index e4c60fad..faa9be85 100644 --- a/src/components/timeline/timeline.ts +++ b/src/components/timeline/timeline.ts @@ -13,6 +13,7 @@ import { RulerComponent } from "./components/ruler/ruler-component"; import { ToolbarComponent } from "./components/toolbar/toolbar-component"; import { TrackListComponent } from "./components/track/track-list"; import { InteractionController } from "./interaction/interaction-controller"; +import { TimelinePinch } from "./interaction/timeline-pinch"; import { MediaThumbnailRenderer } from "./media-thumbnail-renderer"; import { ThumbnailGenerator } from "./thumbnail-generator"; import { createTimelineResizeHandle, type TimelineResizeHandle } from "./timeline-resize-handle"; @@ -47,6 +48,7 @@ export class Timeline { private playheadGhost: HTMLElement | null = null; private feedbackLayer: HTMLElement | null = null; private interactionController: InteractionController | null = null; + private pinch: TimelinePinch | null = null; private clipContextMenu: ClipContextMenu | null = null; private resizeHandle: TimelineResizeHandle | null = null; @@ -493,6 +495,18 @@ export class Timeline { }); this.interactionController.mount(); + this.pinch = new TimelinePinch(this.element, { + scroller: this.trackList.element, + getPixelsPerSecond: () => this.stateManager.getViewport().pixelsPerSecond, + setZoom: pps => { + this.setZoom(pps); + // Playback defers rendering a frame, which would hold the pinch's scroll to the pre-zoom width + this.draw(); + }, + onPinchStart: () => this.interactionController?.cancelInteraction() + }); + this.pinch.mount(); + this.clipContextMenu = new ClipContextMenu(this.edit, this.trackList.element); this.clipContextMenu.mount(); @@ -509,6 +523,9 @@ export class Timeline { this.interactionController?.dispose(); this.interactionController = null; + this.pinch?.dispose(); + this.pinch = null; + this.clipContextMenu?.dispose(); this.clipContextMenu = null; diff --git a/src/styles/timeline/timeline.css b/src/styles/timeline/timeline.css index d04d7fcd..6ab5e7b8 100644 --- a/src/styles/timeline/timeline.css +++ b/src/styles/timeline/timeline.css @@ -14,11 +14,15 @@ } /* Double-tap zoom and the tap delay get in the way of editing by touch */ -.ss-html-timeline, .ss-clip-context-menu { touch-action: manipulation; } +/* A pinch zooms the timeline, never the page; this also rules out double-tap zoom */ +.ss-html-timeline { + touch-action: pan-x pan-y; +} + /* Toolbar */ .ss-timeline-toolbar { display: flex; @@ -185,6 +189,8 @@ } .ss-ruler-content { + /* A zoom rebuilds the ticks, and a finger whose target is rebuilt away never delivers its touchend */ + pointer-events: none; position: relative; height: 100%; margin-left: var(--ss-timeline-padding); diff --git a/tests/timeline-pinch.test.ts b/tests/timeline-pinch.test.ts new file mode 100644 index 00000000..eb69b128 --- /dev/null +++ b/tests/timeline-pinch.test.ts @@ -0,0 +1,235 @@ +/** @jest-environment jsdom */ +import { AssetLoadTracker } from "@core/events/asset-load-tracker"; +import { EventEmitter } from "@core/events/event-emitter"; +import { sec } from "@core/timing/types"; +import { Timeline } from "@timeline/timeline"; + +// @ts-expect-error - Jest transforms this via moduleNameMapper to css-inline.js mock +import styles from "../src/styles/index.css?inline"; + +async function mountTimeline() { + const events = new EventEmitter(); + const config = { timeline: { tracks: [{ clips: [{ id: "clip-1", asset: { type: "html5", html: "

Title

" }, start: 0, length: 5 }] }] } }; + const edit = { + events, + assetLoader: { loadTracker: new AssetLoadTracker() }, + getInternalEvents: () => events, + getResolvedEdit: () => config, + getEdit: () => config, + isClipSelected: () => false, + selectClip: jest.fn(), + clearSelection: jest.fn(), + getClipGenerationState: () => undefined, + getClipError: () => null, + getPendingCaptures: () => ({ pending: 0, total: 0, progress: 1 }), + getClipCaptureProgress: () => null, + playbackTime: sec(0), + totalDuration: sec(5), + isPlaying: false + }; + const container = document.createElement("div"); + document.body.appendChild(container); + const timeline = new Timeline(edit as never, container); + timeline.registerClipRenderer("html5", { render: () => {} }); + await timeline.load(); + + const root = container.querySelector(".ss-html-timeline")!; + const tracks = container.querySelector(".ss-timeline-tracks")!; + // jsdom keeps no scroll position; the rects it reports all sit at 0, so client x is the scroller's own x + let scrollLeft = 100; + Object.defineProperty(tracks, "scrollLeft", { + get: () => scrollLeft, + set: (value: number) => { + scrollLeft = Math.max(0, value); + } + }); + const pps = () => Number(root.style.getPropertyValue("--ss-timeline-pixels-per-second")); + return { edit, timeline, root, tracks, pps, ruler: container.querySelector(".ss-timeline-ruler")! }; +} + +/** A touch event with fingers at these client x positions, each on the element at the same index (or the first), as jsdom has no Touch */ +function touchEvent(type: string, xs: number[], targets: Element[]): Event { + const event = new Event(type, { bubbles: true, cancelable: true }); + Object.defineProperty(event, "touches", { value: xs.map((clientX, i) => ({ clientX, clientY: 60, target: targets[i] ?? targets[0] })) }); + return event; +} + +function pointerEvent(type: string, pointerId: number): Event { + const event = new Event(type, { bubbles: true, cancelable: true }); + Object.defineProperties(event, { + pointerType: { value: "touch" }, + pointerId: { value: pointerId }, + button: { value: 0 }, + buttons: { value: type === "pointerup" ? 0 : 1 }, + clientX: { value: 40 }, + clientY: { value: 60 } + }); + return event; +} + +/** Puts two fingers 100px apart around x 150, then moves them to `to` */ +function pinch(target: HTMLElement, to: number[]): void { + target.dispatchEvent(touchEvent("touchstart", [100, 200], [target])); + target.dispatchEvent(touchEvent("touchmove", to, [target])); +} + +const gesture = (root: HTMLElement, type: string) => { + const event = new Event(type, { bubbles: true, cancelable: true }); + root.dispatchEvent(event); + return event.defaultPrevented; +}; + +afterEach(() => { + jest.useRealTimers(); + document.body.replaceChildren(); +}); + +describe("timeline pinch", () => { + it("doubles pixels per second when the fingers spread from 100px to 200px apart", async () => { + const { tracks, pps } = await mountTimeline(); + expect(pps()).toBe(50); + + pinch(tracks, [50, 250]); + + expect(pps()).toBe(100); + }); + + it("holds the zoom to the timeline's limit", async () => { + const { timeline, ruler, pps } = await mountTimeline(); + timeline.setZoom(150); + + pinch(ruler, [50, 250]); + + expect(pps()).toBe(200); + }); + + it("keeps the time under the fingers' midpoint", async () => { + const { tracks } = await mountTimeline(); + // Midpoint x 150 at scrollLeft 100 is (150 + 100 - 16) / 50 = 4.68 s + pinch(tracks, [50, 250]); + + expect(tracks.scrollLeft).toBeCloseTo(16 + 4.68 * 100 - 150); + }); + + it("keeps the time under the midpoint when the scroller sits away from the page's edge", async () => { + const { tracks } = await mountTimeline(); + tracks.getBoundingClientRect = () => ({ left: 40, top: 0, width: 400, height: 200, right: 440, bottom: 200, x: 40, y: 0, toJSON: () => ({}) }); + // Midpoint x 150 is 110 px into the scroller: (110 + 100 - 16) / 50 = 3.88 s + pinch(tracks, [50, 250]); + + expect(tracks.scrollLeft).toBeCloseTo(16 + 3.88 * 100 - 110); + }); + + it("widens the tracks at once while playback defers rendering, so the scroll isn't held to the old width", async () => { + const { timeline, tracks } = await mountTimeline(); + const content = tracks.querySelector(".ss-tracks-content")!; + timeline.beginInteraction(); + + pinch(tracks, [50, 250]); + timeline.endInteraction(); + + // 60 s of extended timeline at 100 px/s + expect(content.style.width).toBe("6000px"); + }); + + it("cancels the browser's own zoom and scroll for two fingers only", async () => { + const { tracks } = await mountTimeline(); + const one = [touchEvent("touchstart", [100], [tracks]), touchEvent("touchmove", [140], [tracks])]; + one.forEach(event => tracks.dispatchEvent(event)); + expect(one.map(event => event.defaultPrevented)).toEqual([false, false]); + + const two = [touchEvent("touchstart", [100, 200], [tracks]), touchEvent("touchmove", [50, 250], [tracks])]; + two.forEach(event => tracks.dispatchEvent(event)); + expect(two.map(event => event.defaultPrevented)).toEqual([true, true]); + + // The finger left after the pinch is a one-finger touch again + tracks.dispatchEvent(touchEvent("touchend", [250], [tracks])); + const left = touchEvent("touchmove", [260], [tracks]); + tracks.dispatchEvent(left); + expect(left.defaultPrevented).toBe(false); + }); + + it("counts only fingers on the timeline", async () => { + const { root, tracks, pps } = await mountTimeline(); + const canvas = document.body.appendChild(document.createElement("div")); + + const start = touchEvent("touchstart", [100, 200], [canvas, tracks]); + tracks.dispatchEvent(start); + tracks.dispatchEvent(touchEvent("touchmove", [50, 250], [canvas, tracks])); + expect(start.defaultPrevented).toBe(false); + expect(pps()).toBe(50); + + // A real pinch, with a third finger resting outside that lifts last + tracks.dispatchEvent(touchEvent("touchstart", [100, 200, 300], [tracks, tracks, canvas])); + tracks.dispatchEvent(touchEvent("touchend", [300], [canvas])); + expect(gesture(root, "gesturestart")).toBe(false); + }); + + it("cancels Safari's gesture events during a pinch, and leaves a trackpad's alone", async () => { + const { root, tracks } = await mountTimeline(); + expect(gesture(root, "gesturestart")).toBe(false); + + tracks.dispatchEvent(touchEvent("touchstart", [100, 200], [tracks])); + expect(gesture(root, "gesturestart")).toBe(true); + expect(gesture(root, "gesturechange")).toBe(true); + }); + + it("ends the gesture when its last finger lifts", async () => { + const { root, tracks } = await mountTimeline(); + pinch(tracks, [50, 250]); + + tracks.dispatchEvent(touchEvent("touchend", [250], [tracks])); + expect(gesture(root, "gesturechange")).toBe(true); + + tracks.dispatchEvent(touchEvent("touchend", [], [tracks])); + expect(gesture(root, "gesturechange")).toBe(false); + }); + + it("cancels a pending lift when a second finger lands, wherever it lands", async () => { + const { edit, tracks, ruler } = await mountTimeline(); + jest.useFakeTimers(); + tracks.querySelector(".ss-clip")!.dispatchEvent(pointerEvent("pointerdown", 1)); + + ruler.dispatchEvent(touchEvent("touchstart", [100, 200], [ruler])); + jest.advanceTimersByTime(500); + + expect(edit.selectClip).not.toHaveBeenCalled(); + }); + + it("treats no finger of a pinch as a tap", async () => { + const { edit, tracks } = await mountTimeline(); + const clip = tracks.querySelector(".ss-clip")!; + pinch(tracks, [50, 250]); + + tracks.dispatchEvent(touchEvent("touchend", [250], [tracks])); + clip.dispatchEvent(pointerEvent("pointerup", 2)); + tracks.dispatchEvent(pointerEvent("pointerup", 1)); + + expect(edit.selectClip).not.toHaveBeenCalled(); + expect(edit.clearSelection).not.toHaveBeenCalled(); + }); + + it("lets a playhead drag end when a pinch interrupts it", async () => { + const { edit, timeline, root, ruler } = await mountTimeline(); + const handle = root.querySelector(".ss-playhead-handle")!; + Object.assign(handle, { setPointerCapture: jest.fn(), releasePointerCapture: jest.fn() }); + + handle.dispatchEvent(pointerEvent("pointerdown", 1)); + ruler.dispatchEvent(touchEvent("touchstart", [100, 200], [ruler])); + handle.dispatchEvent(pointerEvent("pointerup", 1)); + ruler.dispatchEvent(touchEvent("touchend", [], [ruler])); + + // A playhead still dragging ignores playback + edit.playbackTime = sec(3); + timeline.draw(); + expect(root.querySelector(".ss-playhead")!.style.getPropertyValue("--playhead-time")).toBe("3"); + }); + + it("keeps the browser from zooming the page over the timeline", () => { + expect(styles).toMatch(/\.ss-html-timeline \{\s*touch-action: pan-x pan-y;/); + }); + + it("leaves ruler ticks out of hit testing, since a zoom rebuilds them under the finger", () => { + expect(styles).toMatch(/\.ss-ruler-content \{[^}]*pointer-events: none;/); + }); +});