Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/core/interaction/selection-overlay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ export const SELECTION_CONSTANTS = {
EDGE_HIT_ZONE: 8,
/** Hit zone for rotation detection outside corners in pixels */
ROTATION_HIT_ZONE: 15,
/** Touch reach from a corner in pixels, a 44 px target */
TOUCH_HANDLE_RADIUS: 22,
/** Touch reach either side of an edge in pixels */
TOUCH_EDGE_HIT_ZONE: 22,
/** Touch rotation band beyond a corner's touch reach in pixels */
TOUCH_ROTATION_HIT_ZONE: 24,
/** Share of the shorter side touch zones may cover from each side, so a small clip's middle still moves it */
TOUCH_ZONE_MAX_SHARE: 0.35,
/** Default selection outline color (blue) */
DEFAULT_COLOR: 0x0d99ff,
/** Active/hover selection color (soft cyan) */
Expand Down
60 changes: 59 additions & 1 deletion src/core/ui/selection-handles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
} from "@core/interaction/clip-interaction";
import {
SELECTION_CONSTANTS,
CORNER_NAMES,
CURSOR_BASE_ANGLES,
type CornerName,
buildResizeCursor,
Expand Down Expand Up @@ -91,6 +92,7 @@ export class SelectionHandles implements CanvasOverlayRegistration {
private originalDimensions: { width: number; height: number; offsetX: number; offsetY: number } | null = null;

private isRotating = false;
private activePointerId: number | null = null;
private rotationStart: number | null = null;
private initialRotation = 0;

Expand All @@ -111,8 +113,10 @@ export class SelectionHandles implements CanvasOverlayRegistration {
private onClipBlurredBound: () => void;
private onGestureStartedBound: () => void;
private onPointerDownBound: (event: pixi.FederatedPointerEvent) => void;
private onTouchDownBound: (event: pixi.FederatedPointerEvent) => void;
private onPointerMoveBound: (event: pixi.FederatedPointerEvent) => void;
private onPointerUpBound: () => void;
private onPointerCancelBound: (event: PointerEvent) => void;

constructor(private edit: Edit) {
this.container = new pixi.Container();
Expand Down Expand Up @@ -153,8 +157,10 @@ export class SelectionHandles implements CanvasOverlayRegistration {
this.onClipBlurredBound = this.onClipBlurred.bind(this);
this.onGestureStartedBound = this.cancelInteraction.bind(this);
this.onPointerDownBound = this.onPointerDown.bind(this);
this.onTouchDownBound = this.onTouchDown.bind(this);
this.onPointerMoveBound = this.onPointerMove.bind(this);
this.onPointerUpBound = this.onPointerUp.bind(this);
this.onPointerCancelBound = this.onPointerCancel.bind(this);

// Listen to selection events
this.edit.events.on(EditEvent.ClipSelected, this.onClipSelectedBound);
Expand Down Expand Up @@ -200,9 +206,13 @@ export class SelectionHandles implements CanvasOverlayRegistration {

// Setup pointer events on the stage
app.stage.on("pointerdown", this.onPointerDownBound);
// Capture, so a touch zone reaching past the outline is claimed before the background or a clip under it.
app.stage.on("pointerdowncapture", this.onTouchDownBound);
app.stage.on("globalpointermove", this.onPointerMoveBound);
app.stage.on("pointerup", this.onPointerUpBound);
app.stage.on("pointerupoutside", this.onPointerUpBound);
// Pixi maps no pointercancel, so a cancelled pointer would never reach pointerup.
app.canvas.addEventListener("pointercancel", this.onPointerCancelBound);
}

update(_deltaTime: number, _elapsed: number): void {
Expand Down Expand Up @@ -239,9 +249,11 @@ export class SelectionHandles implements CanvasOverlayRegistration {

if (this.app) {
this.app.stage.off("pointerdown", this.onPointerDownBound);
this.app.stage.off("pointerdowncapture", this.onTouchDownBound);
this.app.stage.off("globalpointermove", this.onPointerMoveBound);
this.app.stage.off("pointerup", this.onPointerUpBound);
this.app.stage.off("pointerupoutside", this.onPointerUpBound);
this.app.canvas.removeEventListener("pointercancel", this.onPointerCancelBound);
}

this.outline.destroy();
Expand Down Expand Up @@ -438,6 +450,8 @@ export class SelectionHandles implements CanvasOverlayRegistration {
// ─── Pointer Event Handlers ──────────────────────────────────────────────────

private onPointerDown(event: pixi.FederatedPointerEvent): void {
// Pixi still calls the stage's own listeners after a capture claim when the stage is the target.
if (event.propagationStopped) return;
if (event.button !== Pointer.ButtonLeftClick) return;
if (!this.selectedPlayer) return;

Expand Down Expand Up @@ -486,6 +500,42 @@ export class SelectionHandles implements CanvasOverlayRegistration {
}
}

private onTouchDown(event: pixi.FederatedPointerEvent): void {
// Only what draw() shows: a clip outside the playhead's time stays selected with no handles.
if (event.pointerType !== "touch" || !this.selectedPlayer?.isActive() || this.edit.isInExportMode()) return;

const localPoint = event.getLocalPosition(this.selectedPlayer.getContainer());
const size = this.selectedPlayer.getSize();
const uiScale = this.getUIScale();
const cap = SELECTION_CONSTANTS.TOUCH_ZONE_MAX_SHARE * Math.min(size.width, size.height);
const handleRadius = Math.min(SELECTION_CONSTANTS.TOUCH_HANDLE_RADIUS / uiScale, cap);
const corners = [
{ x: 0, y: 0 },
{ x: size.width, y: 0 },
{ x: size.width, y: size.height },
{ x: 0, y: size.height }
];
const inside = localPoint.x >= 0 && localPoint.x <= size.width && localPoint.y >= 0 && localPoint.y <= size.height;

const corner = CORNER_NAMES.find((_, i) => Math.hypot(localPoint.x - corners[i].x, localPoint.y - corners[i].y) <= handleRadius);
const edgeZone = Math.min(SELECTION_CONSTANTS.TOUCH_EDGE_HIT_ZONE / uiScale, cap);
const edge = this.selectedPlayer.supportsEdgeResize() ? detectEdgeZone(localPoint, size, edgeZone) : null;
// On a small clip the rotation band reaches the edge pills, and a finger aimed at a pill means resize.
const rotationCorner =
inside || corner || edge ? null : detectCornerZone(localPoint, corners, handleRadius, SELECTION_CONSTANTS.TOUCH_ROTATION_HIT_ZONE / uiScale);
if (!rotationCorner && !corner && !edge && !inside) return;

event.stopPropagation();
this.initialClipConfiguration = structuredClone(this.selectedPlayer.clipConfiguration);
if (corner) this.startCornerResize(event, corner);
else if (edge) this.startEdgeResize(event, edge);
else if (rotationCorner) this.startRotation(event, rotationCorner);
else {
this.edit.getInternalEvents().emit(InternalEvent.CanvasClipClicked, { player: this.selectedPlayer });
this.startDrag(event);
}
}

private onPointerMove(event: pixi.FederatedPointerEvent): void {
if (!this.selectedPlayer) return;

Expand Down Expand Up @@ -582,7 +632,11 @@ export class SelectionHandles implements CanvasOverlayRegistration {
this.edit.clearAlignmentGuides();
}

/** A second pointer means a pinch: put back what the drag has moved so far, and drop it without committing. */
private onPointerCancel(event: PointerEvent): void {
if (event.pointerId === this.activePointerId) this.cancelInteraction();
}

/** A second pointer means a pinch, and a cancelled one means the platform took the touch: put back what the drag has moved so far, and drop it without committing. */
private cancelInteraction(): void {
if (!(this.isDragging || this.scaleDirection || this.edgeDragDirection || this.isRotating)) return;

Expand Down Expand Up @@ -610,6 +664,7 @@ export class SelectionHandles implements CanvasOverlayRegistration {
if (!this.selectedPlayer || this.hasKeyframedOffset()) return;

this.isDragging = true;
this.activePointerId = event.pointerId;
const viewportContainer = this.edit.getViewportContainer();
const timelinePoint = event.getLocalPosition(viewportContainer);
const playerPos = this.selectedPlayer.getContainer().position;
Expand Down Expand Up @@ -693,6 +748,7 @@ export class SelectionHandles implements CanvasOverlayRegistration {
if (!this.selectedPlayer || this.hasKeyframedOffset()) return;

this.scaleDirection = corner;
this.activePointerId = event.pointerId;
const timelinePoint = event.getLocalPosition(this.edit.getViewportContainer());
this.edgeDragStart = timelinePoint;

Expand Down Expand Up @@ -734,6 +790,7 @@ export class SelectionHandles implements CanvasOverlayRegistration {
if (!this.selectedPlayer || this.hasKeyframedOffset()) return;

this.edgeDragDirection = edge;
this.activePointerId = event.pointerId;
const timelinePoint = event.getLocalPosition(this.edit.getViewportContainer());
this.edgeDragStart = timelinePoint;

Expand Down Expand Up @@ -775,6 +832,7 @@ export class SelectionHandles implements CanvasOverlayRegistration {
if (!this.selectedPlayer || this.hasKeyframedRotation()) return;

this.isRotating = true;
this.activePointerId = event.pointerId;

const center = this.getContentCenter();
this.rotationStart = Math.atan2(event.globalY - center.y, event.globalX - center.x);
Expand Down
110 changes: 110 additions & 0 deletions tests/helpers/selection-handles-edit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import type { Player } from "@canvas/players/player";
import { Edit } from "@core/edit-session";
import { SelectionHandles } from "@core/ui/selection-handles";
import * as pixi from "pixi.js";

// earcut is ESM-only, which jest cannot require. Nothing drawn here needs triangulating.
jest.mock("earcut", () => ({ __esModule: true, default: () => [] }));

// Every image loads as a blank texture, so the edit needs no network.
jest.mock("@loaders/asset-loader", () => ({
AssetLoader: jest.fn().mockImplementation(() => ({
load: jest.fn().mockImplementation(async () => {
const { Texture, ImageSource } = jest.requireActual("pixi.js");
return new Texture({ source: new ImageSource({ resource: { width: 100, height: 100 }, width: 100, height: 100 }) });
}),
unload: jest.fn(),
getProgress: jest.fn().mockReturnValue(100),
incrementRef: jest.fn(),
decrementRef: jest.fn().mockReturnValue(true),
rejectAsset: jest.fn(),
loadTracker: { on: jest.fn(), off: jest.fn() }
}))
}));

type Pointer = { pointerType?: string; pointerId?: number; target?: unknown };

const image = (src: string): { type: "image"; src: string } => ({ type: "image", src });

/** A real edit whose first clip, 400 × 300 at the origin of its own pixels, is selected under mounted SelectionHandles. */
export default async function selectOnEdit(clip: Record<string, unknown> = {}, later: Record<string, unknown>[] = []) {
const edit = new Edit({
timeline: {
tracks: [
{
clips: [
{ asset: image("https://example.com/a.jpg"), start: 0, length: 1, width: 400, height: 300, offset: { x: 0.1, y: -0.1 }, ...clip },
...later.map(next => ({ asset: image("https://example.com/b.jpg"), start: 1, length: 1, ...next }))
]
}
]
},
output: { size: { width: 1920, height: 1080 }, format: "mp4" }
});
await edit.load();
jest.spyOn(edit, "getViewportContainer").mockReturnValue(new pixi.Container());
// Measuring the dimension label needs a DOM canvas; its size doesn't matter here.
jest.spyOn(pixi.CanvasTextMetrics, "measureText").mockReturnValue({ width: 60, height: 14 } as pixi.CanvasTextMetrics);

const handles = new SelectionHandles(edit);
const stage = new pixi.Container();
const canvas = new EventTarget();
handles.mount(new pixi.Container(), { stage, canvas } as unknown as pixi.Application);
edit.selectClip(0, 0);

/** A pointer at a point in the clip's own pixels; the stand-in clip sits at the origin, so it's the global point too. */
const pointerEvent = (
x: number,
y: number,
{ pointerType = "touch", pointerId = 1, target = stage as unknown }: Pointer = {}
): pixi.FederatedPointerEvent => {
const event = {
pointerType,
pointerId,
button: 0,
globalX: x,
globalY: y,
target,
propagationStopped: false,
stopPropagation: () => {
event.propagationStopped = true;
},
getLocalPosition: () => ({ x, y })
};
return event as unknown as pixi.FederatedPointerEvent;
};

/** A press, as Pixi delivers it when the stage is the target. */
const press = (x: number, y: number, pointer?: Pointer): void => {
const event = pointerEvent(x, y, pointer);
stage.emit("pointerdowncapture", event);
stage.emit("pointerdown", event);
};

return {
edit,
handles,
stage,
canvas,
player: edit.getPlayerClip(0, 0) as Player,
touchEvent: (x: number, y: number, target?: unknown) => pointerEvent(x, y, { target }),
press,
/** A first finger landing. */
touch: (x: number, y: number, target?: unknown): void => press(x, y, { target }),
drag: (x: number, y: number, pointer?: Pointer): void => {
stage.emit("globalpointermove", pointerEvent(x, y, pointer));
},
lift: (x: number, y: number, pointer?: Pointer): void => {
stage.emit("pointerup", pointerEvent(x, y, pointer));
},
/** The browser giving up on a pointer: Pixi maps none, so it reaches the canvas element as a DOM event. */
cancel: ({ pointerType = "touch", pointerId = 1 }: Pointer = {}): void => {
canvas.dispatchEvent(Object.assign(new Event("pointercancel"), { pointerType, pointerId }));
},
history: (): number => (edit as unknown as { commandHistory: unknown[] }).commandHistory.length,
dispose: (): void => {
handles.dispose();
edit.dispose();
}
};
}
66 changes: 66 additions & 0 deletions tests/selection-handles-cancel.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/**
* @jest-environment node
*/

import selectOnEdit from "./helpers/selection-handles-edit";

describe("SelectionHandles when the browser cancels a pointer", () => {
let harness: Awaited<ReturnType<typeof selectOnEdit>>;

afterEach(() => harness.dispose());

// Where the finger lands in the clip's own pixels, the interaction that starts, and where the finger then moves.
it.each([
["a corner resize", [2, 2], "scaleDirection", [40, 40]],
["an edge resize", [2, 150], "edgeDragDirection", [40, 150]],
["a rotation", [-24, -24], "isRotating", [60, -60]],
["a move", [200, 150], "isDragging", [300, 250]]
])("puts back %s and records nothing", async (_name, [x, y], flag, [toX, toY]) => {
harness = await selectOnEdit();
const initial = structuredClone(harness.player.clipConfiguration);
const entries = harness.history();

harness.touch(x, y);
harness.drag(toX, toY);
expect((harness.handles as unknown as Record<string, unknown>)[flag]).toBeTruthy();
expect(harness.player.clipConfiguration).not.toEqual(initial);

harness.cancel({ pointerType: "touch", pointerId: 1 });
harness.lift(toX, toY);

expect(harness.player.clipConfiguration).toEqual(initial);
expect(harness.history()).toBe(entries);
});

it.each(["mouse", "pen"])("leaves a %s drag running when a palm touch is cancelled, and commits it on its own lift", async pointerType => {
harness = await selectOnEdit();
const initial = structuredClone(harness.player.clipConfiguration);
const entries = harness.history();
const drawing = { pointerType, pointerId: 1 };

harness.press(200, 150, drawing);
harness.drag(300, 250, drawing);
const moved = structuredClone(harness.player.clipConfiguration);
harness.cancel({ pointerType: "touch", pointerId: 2 });

expect(harness.player.clipConfiguration).toEqual(moved);
harness.drag(320, 260, drawing);
harness.lift(320, 260, drawing);
expect(harness.player.clipConfiguration.offset).not.toEqual(initial.offset);
expect(harness.history()).toBe(entries + 1);
});

it("hears no cancel once disposed", async () => {
harness = await selectOnEdit();
const { edit, handles } = harness;
harness.touch(200, 150);
harness.drag(300, 250);
const moved = structuredClone(harness.player.clipConfiguration);

handles.dispose();
harness.dispose = (): void => edit.dispose();
harness.cancel();

expect(harness.player.clipConfiguration).toEqual(moved);
});
});
Loading
Loading