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
25 changes: 25 additions & 0 deletions src/components/canvas/canvas-gestures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export interface Point {
x: number;
y: number;
}

/** Where the edit sits in the canvas and how large it is drawn. */
export interface View {
x: number;
y: number;
zoom: number;
}

export interface ZoomLimits {
min: number;
max: number;
}

const clamp = (value: number, { min, max }: ZoomLimits): number => Math.min(Math.max(value, min), max);

/** Zooms to `zoom`, within the limits, so the point under `anchor` stays under it. */
export function zoomAbout(view: View, anchor: Point, zoom: number, limits: ZoomLimits): View {
const next = clamp(zoom, limits);
const ratio = next / view.zoom;
return { zoom: next, x: anchor.x - (anchor.x - view.x) * ratio, y: anchor.y - (anchor.y - view.y) * ratio };
}
57 changes: 35 additions & 22 deletions src/components/canvas/shotstack-canvas.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { BufferingNotice, visibleBounds } from "@canvas/buffering-notice";
import { zoomAbout, type View } from "@canvas/canvas-gestures";
import type { Player } from "@canvas/players/player";
import { AlignmentGuides } from "@canvas/system/alignment-guides";
import { createWebGLErrorOverlay } from "@canvas/webgl-error-overlay";
Expand Down Expand Up @@ -156,6 +157,28 @@ export class Canvas {
root.addEventListener("pointerdown", this.onPanPointerDown);
}

private getView(): View {
const { x, y } = this.viewportContainer?.position ?? { x: 0, y: 0 };
return { x, y, zoom: this.currentZoom };
}

private setView({ x, y, zoom }: View): void {
if (!this.viewportContainer) return;

this.currentZoom = zoom;
this.viewportContainer.position.set(x, y);
this.viewportContainer.scale.set(zoom);
this.syncContentTransforms();
}

private get viewportCentre(): { x: number; y: number } {
return { x: this.viewportSize.width / 2, y: this.viewportSize.height / 2 };
}

private get zoomLimits(): { min: number; max: number } {
return { min: this.minZoom, max: this.maxZoom };
}

private onWheel(e: WheelEvent): void {
// Allow native scrolling inside toolbar popups (font picker, TTS voice list, etc.).
const target = e.target as HTMLElement;
Expand All @@ -169,29 +192,11 @@ export class Canvas {
if (!this.viewportContainer) return;

if (e.ctrlKey) {
const scaleFactor = Math.exp(-e.deltaY / 100);
const newZoom = this.currentZoom * scaleFactor;
const oldZoom = this.currentZoom;
this.currentZoom = Math.min(Math.max(newZoom, this.minZoom), this.maxZoom);

const stageCenter = {
x: this.viewportSize.width / 2,
y: this.viewportSize.height / 2
};

const distanceFromCenter = {
x: this.viewportContainer.position.x - stageCenter.x,
y: this.viewportContainer.position.y - stageCenter.y
};

const zoomRatio = this.currentZoom / oldZoom;

this.viewportContainer.position.x = stageCenter.x + distanceFromCenter.x * zoomRatio;
this.viewportContainer.position.y = stageCenter.y + distanceFromCenter.y * zoomRatio;
this.zoomBy(Math.exp(-e.deltaY / 100));
return;
}

this.viewportContainer.scale.x = this.currentZoom;
this.viewportContainer.scale.y = this.currentZoom;
} else if (e.shiftKey) {
if (e.shiftKey) {
this.viewportContainer.position.x -= e.deltaY || e.deltaX;
} else {
this.viewportContainer.position.y -= e.deltaY;
Expand Down Expand Up @@ -315,6 +320,14 @@ export class Canvas {
return this.currentZoom;
}

/**
* Multiply the zoom by `factor`, within the limits, about the centre of the viewport.
* @internal
*/
public zoomBy(factor: number): void {
this.setView(zoomAbout(this.getView(), this.viewportCentre, this.currentZoom * factor, this.zoomLimits));
}

/**
* The user supplied Studio root element.
* @internal
Expand Down
48 changes: 48 additions & 0 deletions src/core/ui/canvas-zoom-controls.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import type { Canvas } from "@canvas/shotstack-canvas";

import type { UIRegistration } from "./ui-controller";

const ZOOM_STEP = 1.2;

const icon = (paths: string): string =>
`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths}</svg>`;

const ICON_OUT = icon('<circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35M8 11h6"/>');
const ICON_FIT = icon('<path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/>');
const ICON_IN = icon('<circle cx="11" cy="11" r="7"/><path d="M21 21l-4.35-4.35M8 11h6M11 8v6"/>');

/** Zoom buttons for the canvas. Pinching is a multipoint gesture, so touch needs a single-tap way to do the same. */
export class CanvasZoomControls implements UIRegistration {
private element: HTMLDivElement | null = null;

constructor(private readonly canvas: Canvas) {}

mount(container: HTMLElement): void {
const element = document.createElement("div");
element.className = "ss-canvas-zoom";
element.setAttribute("role", "group");
element.setAttribute("aria-label", "Canvas zoom");
element.append(
this.button("out", "Zoom out", ICON_OUT, () => this.canvas.zoomBy(1 / ZOOM_STEP)),
this.button("fit", "Fit to screen", ICON_FIT, () => this.canvas.zoomToFit()),
this.button("in", "Zoom in", ICON_IN, () => this.canvas.zoomBy(ZOOM_STEP))
);
container.append(element);
this.element = element;
}

dispose(): void {
this.element?.remove();
this.element = null;
}

private button(name: string, label: string, svg: string, onClick: () => void): HTMLButtonElement {
const button = document.createElement("button");
button.type = "button";
button.className = `ss-canvas-zoom-btn ss-canvas-zoom-${name}`;
button.setAttribute("aria-label", label);
button.innerHTML = svg;
button.addEventListener("click", onClick);
return button;
}
}
6 changes: 4 additions & 2 deletions src/core/ui/ui-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type * as pixi from "pixi.js";

import { AssetToolbar } from "./asset-toolbar";
import { CanvasToolbar } from "./canvas-toolbar";
import { CanvasZoomControls } from "./canvas-zoom-controls";
import { ClipToolbar } from "./clip-toolbar";
import { GenerateToolbar } from "./generate-toolbar";
import { MediaToolbar } from "./media-toolbar";
Expand Down Expand Up @@ -177,7 +178,7 @@ export class UIController {
const ui = new UIController(edit, canvas, options);
ui.subscribeToEvents();
canvas.setUIController(ui);
ui.registerStandardToolbars();
ui.registerStandardToolbars(canvas);

// Auto-mount if canvas is already loaded (element exists in DOM)
// This handles the case where UIController is created after canvas.load()
Expand Down Expand Up @@ -238,7 +239,7 @@ export class UIController {
/**
* Register all standard toolbars. Called by create() factory.
*/
private registerStandardToolbars(): void {
private registerStandardToolbars(canvas: Canvas): void {
// Selection handles
if (this.selectionHandlesEnabled) {
this.registerCanvasOverlay(new SelectionHandles(this.edit));
Expand All @@ -263,6 +264,7 @@ export class UIController {
maxPixels: this.maxPixels
});
this.registerUtility(this.canvasToolbar);
this.registerUtility(new CanvasZoomControls(canvas));

// Wire up toolbar callbacks to Edit methods
this.canvasToolbar.onResolutionChange((w, h) => this.edit.setOutputSize(w, h));
Expand Down
1 change: 1 addition & 0 deletions src/styles/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
@import "./ui/text-to-speech-toolbar.css";
@import "./ui/clip-toolbar.css";
@import "./ui/canvas-toolbar.css";
@import "./ui/canvas-zoom.css";
@import "./ui/asset-toolbar.css";
@import "./ui/font-color-picker.css";
@import "./ui/background-color-picker.css";
Expand Down
47 changes: 47 additions & 0 deletions src/styles/ui/canvas-zoom.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
.ss-canvas-zoom {
display: none;
}

/* Pinching is no use to anyone who can't use two fingers, so touch gets buttons too. A mouse has the wheel. */
@media (pointer: coarse) {
.ss-canvas-zoom {
position: absolute;
right: 24px;
bottom: 24px;
z-index: 9;
display: flex;
gap: 2px;
padding: 6px;
background: rgba(255, 255, 255, 0.98);
border: 1px solid rgba(0, 0, 0, 0.06);
border-radius: 14px;
box-shadow:
0 2px 8px rgba(0, 0, 0, 0.06),
0 8px 24px rgba(0, 0, 0, 0.08);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
}

.ss-canvas-zoom-btn {
display: flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
padding: 0;
background: transparent;
border: none;
border-radius: 8px;
color: rgba(0, 0, 0, 0.65);
cursor: pointer;
}

.ss-canvas-zoom-btn:active {
background: rgba(0, 0, 0, 0.1);
}

.ss-canvas-zoom-btn svg {
width: 20px;
height: 20px;
}
}
3 changes: 2 additions & 1 deletion test-package.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ const CONTRACT = {
"getViewportContainer(",
"updateViewportForSize(",
"pauseTicker(",
"resumeTicker("
"resumeTicker(",
"zoomBy("
],
Timeline: [
"draw(): void;",
Expand Down
33 changes: 33 additions & 0 deletions tests/canvas-gestures.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* @jest-environment jsdom
*/

import { zoomAbout, type Point, type View } from "@canvas/canvas-gestures";

const LIMITS = { min: 0.1, max: 4 };

/** The point of the edit that sits under a screen point. */
const worldAt = (view: View, screen: Point): Point => ({ x: (screen.x - view.x) / view.zoom, y: (screen.y - view.y) / view.zoom });

describe("zoomAbout", () => {
it("keeps the point under the anchor still", () => {
const view = { x: 40, y: -20, zoom: 1.5 };
const anchor = { x: 300, y: 200 };

const zoomed = zoomAbout(view, anchor, 3, LIMITS);

expect(zoomed.zoom).toBe(3);
expect(worldAt(zoomed, anchor)).toEqual(worldAt(view, anchor));
});

it("clamps to the limits and anchors on the zoom it reached", () => {
const view = { x: 10, y: 10, zoom: 3 };
const anchor = { x: 120, y: 80 };

const zoomed = zoomAbout(view, anchor, 12, LIMITS);

expect(zoomed.zoom).toBe(4);
expect(worldAt(zoomed, anchor).x).toBeCloseTo(worldAt(view, anchor).x);
expect(zoomAbout(view, anchor, 0.001, LIMITS).zoom).toBe(0.1);
});
});
84 changes: 84 additions & 0 deletions tests/canvas-zoom-controls.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* @jest-environment jsdom
*/

import type { Canvas } from "@canvas/shotstack-canvas";
import { CanvasZoomControls } from "@core/ui/canvas-zoom-controls";

// @ts-expect-error - Jest transforms this via moduleNameMapper to css-inline.js mock
import styles from "../src/styles/index.css?inline";

describe("CanvasZoomControls", () => {
let host: HTMLElement;
let canvas: { zoomBy: jest.Mock; zoomToFit: jest.Mock };
let controls: CanvasZoomControls;

beforeEach(() => {
document.body.innerHTML = "";
host = document.createElement("div");
document.body.append(host);
canvas = { zoomBy: jest.fn(), zoomToFit: jest.fn() };
controls = new CanvasZoomControls(canvas as unknown as Canvas);
controls.mount(host);
});

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

const button = (name: string): HTMLButtonElement => host.querySelector<HTMLButtonElement>(`.ss-canvas-zoom-${name}`) as HTMLButtonElement;

it("mounts three real buttons with labels and stable class names", () => {
const labelled = ["out", "fit", "in"].map(name => [button(name).tagName, button(name).type, button(name).getAttribute("aria-label")]);

expect(labelled).toEqual([
["BUTTON", "button", "Zoom out"],
["BUTTON", "button", "Fit to screen"],
["BUTTON", "button", "Zoom in"]
]);
});

it("zooms out by a fifth", () => {
button("out").click();

expect(canvas.zoomBy).toHaveBeenCalledWith(1 / 1.2);
expect(canvas.zoomToFit).not.toHaveBeenCalled();
});

it("zooms in by a fifth", () => {
button("in").click();

expect(canvas.zoomBy).toHaveBeenCalledWith(1.2);
expect(canvas.zoomToFit).not.toHaveBeenCalled();
});

it("fits the edit to the canvas", () => {
button("fit").click();

expect(canvas.zoomToFit).toHaveBeenCalledTimes(1);
expect(canvas.zoomBy).not.toHaveBeenCalled();
});

it("removes itself when disposed", () => {
controls.dispose();

expect(host.querySelector(".ss-canvas-zoom")).toBeNull();
});
});

describe("canvas zoom buttons CSS", () => {
const coarse: string[] = styles.match(/@media \(pointer: coarse\) \{[\s\S]*?\n\}/g) ?? [];
const outside = coarse.reduce((css, block) => css.replace(block, ""), styles as string);

it("hides the buttons everywhere but under a coarse primary pointer", () => {
const bodies = [...outside.matchAll(/[^{}]*ss-canvas-zoom[^{}]*\{([^}]*)\}/g)].map(([, body]) => body.trim());

expect(bodies).toEqual(["display: none;"]);
expect(coarse.join("\n")).toMatch(/\.ss-canvas-zoom \{[^}]*display: flex;/);
});

it("gives each button a target of at least 44px", () => {
const [, width, height] = coarse.join("\n").match(/\.ss-canvas-zoom-btn \{[^}]*width: (\d+)px;[^}]*height: (\d+)px;/) ?? [];

expect(Number(width)).toBeGreaterThanOrEqual(44);
expect(Number(height)).toBeGreaterThanOrEqual(44);
});
});
Loading
Loading