diff --git a/src/components/timeline/components/clip/clip-component.ts b/src/components/timeline/components/clip/clip-component.ts index 19f888ff..96e71b96 100644 --- a/src/components/timeline/components/clip/clip-component.ts +++ b/src/components/timeline/components/clip/clip-component.ts @@ -3,6 +3,7 @@ import type { ResolvedClip } from "@schemas"; import { AI_ICON_LINE_PATHS } from "../../../canvas/players/generation/icons"; import { formatClipErrorMessage } from "../../error-messages"; +import { isTouchPointer } from "../../interaction/interaction-calculations"; import type { ClipState, ClipRenderer } from "../../timeline.types"; /** Reference to an attached luma clip */ @@ -185,10 +186,19 @@ export class ClipComponent { if (!this.currentState) return; + // Touch selects on tap, so a pan that scrolls the timeline leaves the selection alone + if (isTouchPointer(e)) return; + // Select clip const addToSelection = e.shiftKey || e.ctrlKey || e.metaKey; this.options.onSelect(this.currentState.trackIndex, this.currentState.clipIndex, addToSelection); }); + + // 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; + this.options.onSelect(this.currentState.trackIndex, this.currentState.clipIndex, false); + }); } public draw(): void { diff --git a/src/components/timeline/components/clip/clip-context-menu.ts b/src/components/timeline/components/clip/clip-context-menu.ts index de7b1ef1..612ac9f0 100644 --- a/src/components/timeline/components/clip/clip-context-menu.ts +++ b/src/components/timeline/components/clip/clip-context-menu.ts @@ -50,6 +50,12 @@ export class ClipContextMenu { } private onContextMenu(e: MouseEvent): void { + // Android fires contextmenu on a touch long-press, mid-gesture. A pen's barrel button is a right-click. + if ((e as Partial).pointerType === "touch") { + e.preventDefault(); + return; + } + const target = e.target as HTMLElement; const clipEl = target.closest(".ss-clip"); if (!clipEl) return; diff --git a/src/components/timeline/components/ruler/ruler-component.ts b/src/components/timeline/components/ruler/ruler-component.ts index c8c00bfe..6f379d1a 100644 --- a/src/components/timeline/components/ruler/ruler-component.ts +++ b/src/components/timeline/components/ruler/ruler-component.ts @@ -1,6 +1,6 @@ import { type Seconds, sec } from "@core/timing/types"; -import { viewXToTime } from "../../interaction/interaction-calculations"; +import { isTouchPointer, viewXToTime } from "../../interaction/interaction-calculations"; interface RulerOptions { onSeek?: (time: Seconds) => void; @@ -27,6 +27,15 @@ export class RulerComponent { private setupClickHandler(): void { this.element.addEventListener("click", this.handleClick.bind(this)); + // A touch drag never ends in a click, so a touch scrubs: seek where it lands and follow it + this.element.addEventListener("pointerdown", e => { + if (!isTouchPointer(e)) return; + this.element.setPointerCapture(e.pointerId); + this.handleClick(e); + }); + this.element.addEventListener("pointermove", e => { + if (isTouchPointer(e) && this.element.hasPointerCapture(e.pointerId)) this.handleClick(e); + }); this.element.addEventListener( "wheel", e => { diff --git a/src/components/timeline/interaction/interaction-calculations.ts b/src/components/timeline/interaction/interaction-calculations.ts index ba43a0dd..29ab07a2 100644 --- a/src/components/timeline/interaction/interaction-calculations.ts +++ b/src/components/timeline/interaction/interaction-calculations.ts @@ -360,6 +360,14 @@ export function exceedsDragThreshold(dx: number, dy: number, threshold: number): return distance(dx, dy) >= threshold; } +// ─── Pointer Type ────────────────────────────────────────────────────────── + +/** Touch and pen are subject to `touch-action`, so the browser can take their gestures as a pan */ +export function isTouchPointer(e: MouseEvent): boolean { + const { pointerType } = e as Partial; + return pointerType === "touch" || pointerType === "pen"; +} + // ─── Drop Action ──────────────────────────────────────────────────────────── export type DropAction = @@ -443,8 +451,7 @@ export interface ClipTimeRange { } export type PasteAction = - | { readonly type: "place"; readonly trackIndex: number } - | { readonly type: "insert-track"; readonly insertionIndex: number }; + { readonly type: "place"; readonly trackIndex: number } | { readonly type: "insert-track"; readonly insertionIndex: number }; export interface ResolvePastePlacementInput { readonly preferredTrackIndex: number; diff --git a/src/components/timeline/interaction/interaction-controller.ts b/src/components/timeline/interaction/interaction-controller.ts index e4e500c6..f4515d75 100644 --- a/src/components/timeline/interaction/interaction-controller.ts +++ b/src/components/timeline/interaction/interaction-controller.ts @@ -27,6 +27,7 @@ import { findNearestSnapPoint, getDragTargetAtY, getTrackYPosition, + isTouchPointer, resolveClipCollision, timeToViewX, viewXToTime @@ -111,6 +112,7 @@ export class InteractionController implements TimelineInteractionRegistration { private readonly handlePointerMove: (e: PointerEvent) => void; private readonly handlePointerUp: (e: PointerEvent) => void; private readonly handlePointerCancel: (e: PointerEvent) => void; + private readonly handleTouchTap: (e: PointerEvent) => void; constructor( private readonly edit: Edit, @@ -128,6 +130,7 @@ export class InteractionController implements TimelineInteractionRegistration { this.handlePointerMove = this.onPointerMove.bind(this); this.handlePointerUp = this.onPointerUp.bind(this); this.handlePointerCancel = this.onPointerCancel.bind(this); + this.handleTouchTap = this.onTouchTap.bind(this); } // ═══════════════════════════════════════════════════════════════════════════ @@ -136,6 +139,7 @@ export class InteractionController implements TimelineInteractionRegistration { public mount(): void { this.tracksContainer.addEventListener("pointerdown", this.handlePointerDown); + this.tracksContainer.addEventListener("pointerup", this.handleTouchTap); document.addEventListener("pointermove", this.handlePointerMove); document.addEventListener("pointerup", this.handlePointerUp); document.addEventListener("pointercancel", this.handlePointerCancel); @@ -159,11 +163,17 @@ export class InteractionController implements TimelineInteractionRegistration { // Find clip element const clipEl = target.closest(".ss-clip") as HTMLElement; if (!clipEl) { + // A touch deselects on tap (onTouchTap), so a pan across empty track keeps the selection + if (isTouchPointer(e)) return; + // Click on empty space - clear selection this.stateManager.clearSelection(); return; } + // Only the selected clip has touch-action: none; a touch anywhere else is the browser's to scroll + if (isTouchPointer(e) && !clipEl.classList.contains("selected")) return; + const trackIndex = parseInt(clipEl.dataset["trackIndex"] || "0", 10); const clipIndex = parseInt(clipEl.dataset["clipIndex"] || "0", 10); @@ -535,6 +545,13 @@ 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; + this.stateManager.clearSelection(); + } + private onPointerCancel(e: PointerEvent): void { if (this.state.type === "idle" || e.pointerId !== this.activePointerId) return; this.cancelInteraction(); @@ -931,6 +948,7 @@ export class InteractionController implements TimelineInteractionRegistration { this.cancelInteraction(); this.tracksContainer.removeEventListener("pointerdown", this.handlePointerDown); + this.tracksContainer.removeEventListener("pointerup", this.handleTouchTap); document.removeEventListener("pointermove", this.handlePointerMove); document.removeEventListener("pointerup", this.handlePointerUp); document.removeEventListener("pointercancel", this.handlePointerCancel); diff --git a/src/styles/canvas/canvas-pan.css b/src/styles/canvas/canvas-pan.css index 5fb0387c..10662021 100644 --- a/src/styles/canvas/canvas-pan.css +++ b/src/styles/canvas/canvas-pan.css @@ -1,3 +1,8 @@ +/* Double-tap zoom and the tap delay get in the way of the toolbars by touch */ +[data-shotstack-studio] { + touch-action: manipulation; +} + .ss-canvas-panning, .ss-canvas-panning * { cursor: grabbing !important; diff --git a/src/styles/timeline/timeline.css b/src/styles/timeline/timeline.css index ebac99f6..d4397d1e 100644 --- a/src/styles/timeline/timeline.css +++ b/src/styles/timeline/timeline.css @@ -13,6 +13,12 @@ -webkit-user-select: none; } +/* 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; +} + /* Toolbar */ .ss-timeline-toolbar { display: flex; @@ -147,8 +153,9 @@ overflow: hidden; } -/* Ruler */ +/* Ruler: a horizontal touch drag scrubs, a vertical one still scrolls the page */ .ss-timeline-ruler { + touch-action: pan-y pinch-zoom; position: relative; height: 32px; background: #ffffff; @@ -203,6 +210,13 @@ background: #ffffff; } +/* On phones and tablets a pan stops at the timeline's edge: no pull-to-refresh, no page scroll */ +@media (pointer: coarse) { + .ss-timeline-tracks { + overscroll-behavior: contain; + } +} + .ss-tracks-content { position: relative; min-height: 100%; @@ -300,7 +314,9 @@ border-radius: 4px; cursor: grab; overflow: hidden; - touch-action: none; + -webkit-touch-callout: none; + user-select: none; + -webkit-user-select: none; transition: box-shadow 0.15s ease, transform 0.1s ease; @@ -310,6 +326,12 @@ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25); } +/* Only the selected clip takes a touch drag. Each child declares it: WebKit doesn't pass it to children rendered before selection. */ +.ss-clip.selected, +.ss-clip.selected * { + touch-action: none; +} + .ss-clip.selected { /* Solid selection ring - professional, non-distracting */ outline: 2px solid var(--clip-border, #3b82f6); @@ -469,6 +491,8 @@ opacity: 0.7; flex-shrink: 0; font-weight: 600; + /* iOS Safari cancels a touch drag that starts on the icon, so touches go to the clip */ + pointer-events: none; } .ss-clip-icon svg { @@ -670,6 +694,8 @@ border-radius: 2px 2px 50% 50%; cursor: grab; pointer-events: auto; + /* A browser pan would cancel the drag partway */ + touch-action: none; } .ss-playhead-handle:hover { diff --git a/tests/clip-context-menu.test.ts b/tests/clip-context-menu.test.ts index 35d840b6..a381662e 100644 --- a/tests/clip-context-menu.test.ts +++ b/tests/clip-context-menu.test.ts @@ -72,8 +72,10 @@ function setup(canDelete = true) { }; } -function rightClick(target: HTMLElement, clientX = 50, clientY = 50): MouseEvent { +function rightClick(target: HTMLElement, clientX = 50, clientY = 50, pointerType?: string): MouseEvent { const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX, clientY, button: 2 }); + // jsdom has no PointerEvent; browsers deliver contextmenu as one + if (pointerType) Object.defineProperty(event, "pointerType", { value: pointerType }); target.dispatchEvent(event); return event; } @@ -132,6 +134,29 @@ describe("ClipContextMenu", () => { }); }); + describe("touch long-press", () => { + it("ignores a touch contextmenu and suppresses the native one", () => { + const { tracksContainer, getMenuEl } = setup(); + const clip = createClipEl(0, 0); + tracksContainer.appendChild(clip); + + const event = rightClick(clip, 50, 50, "touch"); + + expect(event.defaultPrevented).toBe(true); + expect(getMenuEl()).toBeNull(); + }); + + it.each(["mouse", "pen"])("still opens the menu for a %s contextmenu", pointerType => { + const { tracksContainer, getMenuEl } = setup(); + const clip = createClipEl(0, 0); + tracksContainer.appendChild(clip); + + rightClick(clip, 50, 50, pointerType); + + expect(getMenuEl()).toBeTruthy(); + }); + }); + describe("delete item state", () => { it("renders the Delete item enabled when canDeleteClip returns true", () => { const { tracksContainer, getDeleteItem, mockEdit } = setup(true); diff --git a/tests/interaction-controller.test.ts b/tests/interaction-controller.test.ts index 30facc2f..b57d16f1 100644 --- a/tests/interaction-controller.test.ts +++ b/tests/interaction-controller.test.ts @@ -233,6 +233,7 @@ function createPointerEvent( button?: number; buttons?: number; pointerId?: number; + pointerType?: string; } = {} ): Event { // Create a custom event with pointer event properties @@ -253,7 +254,8 @@ function createPointerEvent( metaKey: { value: options.metaKey ?? false, writable: false }, button: { value: options.button ?? 0, writable: false }, buttons: { value: options.buttons ?? defaultButtons, writable: false }, - pointerId: { value: options.pointerId ?? 1, writable: false } + pointerId: { value: options.pointerId ?? 1, writable: false }, + pointerType: { value: options.pointerType, writable: false } }); // Override target if provided @@ -1248,6 +1250,70 @@ describe("InteractionController", () => { }); }); + // ─── Touch Input Tests ─────────────────────────────────────────────────── + + describe("touch input", () => { + beforeEach(() => { + controller = new InteractionController( + mockEdit as never, + mockStateManager as never, + mockTrackList as never, + mockDOM.tracksContainer, + mockDOM.feedbackLayer + ); + controller.mount(); + mockDOM.tracksContainer.setPointerCapture = jest.fn(); + }); + + const firstClip = () => mockDOM.tracksContainer.querySelector(".ss-clip") as HTMLElement; + const press = (target: HTMLElement, pointerType: string) => { + target.dispatchEvent(createPointerEvent("pointerdown", { clientX: 50, clientY: 20, pointerType })); + document.dispatchEvent(createPointerEvent("pointermove", { clientX: 100, clientY: 20, pointerType })); + }; + + it.each(["touch", "pen"])("leaves a %s pan on an unselected clip to the browser", pointerType => { + press(firstClip(), pointerType); + expect(controller.isDragging(0, 0)).toBe(false); + + press(firstClip().querySelector(".ss-clip-resize-handle.right") as HTMLElement, pointerType); + expect(controller.isResizing(0, 0)).toBe(false); + expect(mockDOM.tracksContainer.setPointerCapture).not.toHaveBeenCalled(); + }); + + it("drags the selected clip by touch", () => { + firstClip().classList.add("selected"); + press(firstClip(), "touch"); + expect(controller.isDragging(0, 0)).toBe(true); + }); + + it("deselects on a touch tap on empty track, not on a pan", () => { + mockDOM.tracksContainer.dispatchEvent(createPointerEvent("pointerdown", { pointerType: "touch" })); + document.dispatchEvent(createPointerEvent("pointercancel", { pointerType: "touch" })); + expect(mockStateManager.clearSelection).not.toHaveBeenCalled(); + + mockDOM.tracksContainer.dispatchEvent(createPointerEvent("pointerdown", { pointerType: "touch" })); + mockDOM.tracksContainer.dispatchEvent(createPointerEvent("pointerup", { pointerType: "touch" })); + expect(mockStateManager.clearSelection).toHaveBeenCalledTimes(1); + }); + + it("keeps the selection when a touch drag of the selected clip ends on the captured container", () => { + document.body.appendChild(mockDOM.tracksContainer); + firstClip().classList.add("selected"); + press(firstClip(), "touch"); + mockDOM.tracksContainer.dispatchEvent(createPointerEvent("pointerup", { clientX: 100, clientY: 20, pointerType: "touch" })); + + expect(controller.isDragging(0, 0)).toBe(false); + expect(mockStateManager.clearSelection).not.toHaveBeenCalled(); + mockDOM.tracksContainer.remove(); + }); + + it.each([false, true])("drags with a mouse whether or not the clip is selected (selected: %s)", selected => { + firstClip().classList.toggle("selected", selected); + press(firstClip(), "mouse"); + expect(controller.isDragging(0, 0)).toBe(true); + }); + }); + // ─── Interrupted Interaction Tests ─────────────────────────────────────── describe("interrupted interactions", () => { diff --git a/tests/timeline-touch-input.test.ts b/tests/timeline-touch-input.test.ts new file mode 100644 index 00000000..b84889b3 --- /dev/null +++ b/tests/timeline-touch-input.test.ts @@ -0,0 +1,166 @@ +/** + * @jest-environment jsdom + */ +import { ClipComponent } from "@timeline/components/clip/clip-component"; +import { RulerComponent } from "@timeline/components/ruler/ruler-component"; +import type { ClipState } from "@timeline/timeline.types"; + +// @ts-expect-error - Jest transforms this via moduleNameMapper to css-inline.js mock +import styles from "../src/styles/index.css?inline"; + +// jsdom has no PointerEvent +function pointerEvent(type: string, pointerType: string, clientX = 0): Event { + const event = new Event(type, { bubbles: true, cancelable: true }); + Object.defineProperties(event, { + pointerType: { value: pointerType }, + pointerId: { value: 1 }, + clientX: { value: clientX }, + button: { value: 0 }, + shiftKey: { value: false }, + ctrlKey: { value: false }, + metaKey: { value: false } + }); + return event; +} + +describe("ClipComponent selection by pointer type", () => { + const clip = { + id: "clip-0-2", + trackIndex: 0, + clipIndex: 2, + config: { start: 0, length: 1, asset: { type: "image", src: "image.png" } }, + visualState: "normal", + timingIntent: { start: 0, length: 1 } + } as ClipState; + + const createClip = () => { + const onSelect = jest.fn(); + const { element } = new ClipComponent(clip, { showBadges: false, onSelect, getRenderer: () => undefined, aiAssetNumbers: new Map() }); + return { onSelect, element }; + }; + + it("selects on a touch tap, not when the touch lands", () => { + const { onSelect, element } = createClip(); + + element.dispatchEvent(pointerEvent("pointerdown", "touch")); + expect(onSelect).not.toHaveBeenCalled(); + + element.dispatchEvent(pointerEvent("pointerup", "touch")); + expect(onSelect).toHaveBeenCalledWith(0, 2, false); + }); + + it("leaves the selection alone when the browser takes a touch pan", () => { + const { onSelect, element } = createClip(); + + element.dispatchEvent(pointerEvent("pointerdown", "touch")); + element.dispatchEvent(pointerEvent("pointercancel", "touch")); + + expect(onSelect).not.toHaveBeenCalled(); + }); + + it("selects when a mouse button goes down", () => { + const { onSelect, element } = createClip(); + + element.dispatchEvent(pointerEvent("pointerdown", "mouse")); + expect(onSelect).toHaveBeenCalledWith(0, 2, false); + + element.dispatchEvent(pointerEvent("pointerup", "mouse")); + expect(onSelect).toHaveBeenCalledTimes(1); + }); +}); + +describe("clip touch-action", () => { + const appended: Element[] = []; + + afterEach(() => { + appended.splice(0).forEach(element => element.remove()); + }); + + /** Mounts the SDK stylesheet and a clip in `visualState`, returning the clip's element. */ + const mountClip = (visualState: string): HTMLElement => { + const sheet = document.createElement("style"); + sheet.textContent = styles; + document.head.appendChild(sheet); + const component = new ClipComponent( + { + id: "clip-1-0", + trackIndex: 1, + clipIndex: 0, + config: { start: 5, length: 4, asset: { type: "image", src: "image.png" } }, + visualState, + isFocused: false, + timingIntent: { start: 5, length: 4 } + } as ClipState, + { showBadges: true, onSelect: jest.fn(), onMenuClick: jest.fn(), getRenderer: () => undefined, aiAssetNumbers: new Map() } + ); + component.draw(); + document.body.appendChild(component.element); + appended.push(sheet, component.element); + return component.element; + }; + + /** Style rules that set `property` to `value`. */ + const rulesSetting = (property: string, value: string): CSSStyleRule[] => + [...document.styleSheets] + .flatMap(styleSheet => [...styleSheet.cssRules]) + .filter((rule): rule is CSSStyleRule => rule instanceof CSSStyleRule && rule.style.getPropertyValue(property) === value); + + /** Every element of a clip in `visualState`, with whether a `touch-action: none` rule matches it. */ + const touchActionNone = (visualState: string) => { + const clip = mountClip(visualState); + const noneRules = rulesSetting("touch-action", "none"); + return [clip, ...clip.querySelectorAll("*")].map(element => ({ + name: element.getAttribute("class") ?? element.tagName.toLowerCase(), + none: noneRules.some(rule => element.matches(rule.selectorText)) + })); + }; + + // iOS Safari keeps panning from a child of the selected clip when the clip's own touch-action is all that changed + it("is none on every element of the selected clip a finger can land on", () => { + expect(touchActionNone("selected").filter(({ none }) => !none)).toEqual([]); + }); + + it("leaves every element of an unselected clip free to pan", () => { + expect(touchActionNone("normal").filter(({ none }) => none)).toEqual([]); + }); + + it("passes a touch on the icon through to the clip", () => { + const icon = mountClip("selected").querySelector(".ss-clip-icon") as Element; + + expect(rulesSetting("pointer-events", "none").filter(rule => icon.matches(rule.selectorText))).not.toEqual([]); + }); +}); + +describe("RulerComponent touch scrub", () => { + const createRuler = () => { + const onSeek = jest.fn(); + const ruler = new RulerComponent({ onSeek }); + let captured: number | null = null; + ruler.element.setPointerCapture = (id: number) => { + captured = id; + }; + ruler.element.hasPointerCapture = (id: number) => captured === id; + return { onSeek, element: ruler.element }; + }; + + // 16px timeline padding at the default 50px per second + it("seeks where a touch lands and follows it across the ruler", () => { + const { onSeek, element } = createRuler(); + + element.dispatchEvent(pointerEvent("pointerdown", "touch", 116)); + element.dispatchEvent(pointerEvent("pointermove", "touch", 266)); + + expect(onSeek.mock.calls).toEqual([[2], [5]]); + }); + + it("leaves the mouse to click to seek", () => { + const { onSeek, element } = createRuler(); + + element.dispatchEvent(pointerEvent("pointerdown", "mouse", 116)); + element.dispatchEvent(pointerEvent("pointermove", "mouse", 266)); + expect(onSeek).not.toHaveBeenCalled(); + + element.dispatchEvent(new MouseEvent("click", { bubbles: true, clientX: 266 })); + expect(onSeek).toHaveBeenCalledWith(5); + }); +});