Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

chore(pixi): remove pixi.js — the last consumers were already dead code

Etienne Lescot5bd02bd27016
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 382618b35..9a719360f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -47,7 +47,7 @@ jobs:
- name: Typecheck tests against a baseline
shell: bash
env:
- BASELINE: 74
+ BASELINE: 71
run: |
set -uo pipefail
COUNT=$(npx tsc -p tsconfig.test.json --noEmit 2>&1 | grep -c 'error TS' || true)
diff --git a/package-lock.json b/package-lock.json
index 8b2875dbd..e7c3c517b 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -40,8 +40,6 @@
"mediabunny": "^1.40.1",
"motion": "^12.38.0",
"mp4box": "^2.3.0",
- "pixi-filters": "^6.1.5",
- "pixi.js": "^8.18.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-icons": "^5.6.0",
@@ -2354,12 +2352,6 @@
"@octokit/openapi-types": "^27.0.0"
}
},
- "node_modules/@pixi/colord": {
- "version": "2.9.6",
- "resolved": "https://registry.npmjs.org/@pixi/colord/-/colord-2.9.6.tgz",
- "integrity": "sha512-nezytU2pw587fQstUu1AsJZDVEynjskwOL+kibwcdxsMBFqPsFFNA7xl0ii/gXuDi6M0xj3mfRJj8pBSc2jCfA==",
- "license": "MIT"
- },
"node_modules/@playwright/test": {
"version": "1.59.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.59.1.tgz",
@@ -4498,12 +4490,6 @@
"@types/node": "*"
}
},
- "node_modules/@types/gradient-parser": {
- "version": "0.1.5",
- "resolved": "https://registry.npmjs.org/@types/gradient-parser/-/gradient-parser-0.1.5.tgz",
- "integrity": "sha512-r7K3NkJz3A95WkVVmjs0NcchhHstC2C/VIYNX4JC6tieviUNo774FFeOHjThr3Vw/WCeMP9kAT77MKbIRlO/4w==",
- "license": "MIT"
- },
"node_modules/@types/http-cache-semantics": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",
@@ -4999,16 +4985,11 @@
"url": "https://opencollective.com/vitest"
}
},
- "node_modules/@webgpu/types": {
- "version": "0.1.69",
- "resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.69.tgz",
- "integrity": "sha512-RPmm6kgRbI8e98zSD3RVACvnuktIja5+yLgDAkTmxLr90BEwdTXRQWNLF3ETTTyH/8mKhznZuN5AveXYFEsMGQ==",
- "license": "BSD-3-Clause"
- },
"node_modules/@xmldom/xmldom": {
"version": "0.8.13",
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz",
"integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=10.0.0"
@@ -7409,15 +7390,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
- "node_modules/gifuct-js": {
- "version": "2.1.2",
- "resolved": "https://registry.npmjs.org/gifuct-js/-/gifuct-js-2.1.2.tgz",
- "integrity": "sha512-rI2asw77u0mGgwhV3qA+OEgYqaDn5UNqgs+Bx0FGwSpuqfYn+Ir6RQY5ENNQ8SbIiG/m5gVa7CD5RriO4f4Lsg==",
- "license": "MIT",
- "dependencies": {
- "js-binary-schema-parser": "^2.0.3"
- }
- },
"node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
@@ -7970,12 +7942,6 @@
"node": ">=18"
}
},
- "node_modules/ismobilejs": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/ismobilejs/-/ismobilejs-1.1.1.tgz",
- "integrity": "sha512-VaFW53yt8QO61k2WJui0dHf4SlL8lxBofUuUmwBo0ljPk0Drz2TiuDW4jo3wDcv41qy/SxrJ+VAzJ/qYqsmzRw==",
- "license": "MIT"
- },
"node_modules/jake": {
"version": "10.9.4",
"resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz",
@@ -8004,12 +7970,6 @@
"jiti": "lib/jiti-cli.mjs"
}
},
- "node_modules/js-binary-schema-parser": {
- "version": "2.0.3",
- "resolved": "https://registry.npmjs.org/js-binary-schema-parser/-/js-binary-schema-parser-2.0.3.tgz",
- "integrity": "sha512-xezGJmOb4lk/M1ZZLTR/jaBHQ4gG/lqQnJqdIv4721DMggsa1bDVlHXNeHYogaIEHD9vCRv0fcL4hMA+Coarkg==",
- "license": "MIT"
- },
"node_modules/js-tiktoken": {
"version": "1.0.21",
"resolved": "https://registry.npmjs.org/js-tiktoken/-/js-tiktoken-1.0.21.tgz",
@@ -9210,12 +9170,6 @@
"node": ">=8"
}
},
- "node_modules/parse-svg-path": {
- "version": "0.1.2",
- "resolved": "https://registry.npmjs.org/parse-svg-path/-/parse-svg-path-0.1.2.tgz",
- "integrity": "sha512-JyPSBnkTJ0AI8GGJLfMXvKq42cj5c006fnLz6fXy6zfoVjJizi8BNTpu8on8ziI1cKy9d9DGNuY17Ce7wuejpQ==",
- "license": "MIT"
- },
"node_modules/parse5": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",
@@ -9320,62 +9274,6 @@
"node": ">= 6"
}
},
- "node_modules/pixi-filters": {
- "version": "6.1.5",
- "resolved": "https://registry.npmjs.org/pixi-filters/-/pixi-filters-6.1.5.tgz",
- "integrity": "sha512-Ewb/J+kxAbaNN+0/ATJbglAJG+skGJfh7BIDP3ILIDdD6wWk1p0pGa25pVf1T8hGBOQSUNVAmwwJBwkj+cyLLA==",
- "license": "MIT",
- "dependencies": {
- "@types/gradient-parser": "^0.1.2"
- },
- "peerDependencies": {
- "pixi.js": ">=8.0.0-0"
- }
- },
- "node_modules/pixi.js": {
- "version": "8.18.1",
- "resolved": "https://registry.npmjs.org/pixi.js/-/pixi.js-8.18.1.tgz",
- "integrity": "sha512-6LUPWYgulZhp/w4kam2XHXB0QedISZIqrJbRdHLLQ3csn5a38uzKxAp6B5j6s89QFYaIJbg95kvgTRcbgpO1ow==",
- "license": "MIT",
- "workspaces": [
- "examples",
- "playground"
- ],
- "dependencies": {
- "@pixi/colord": "^2.9.6",
- "@types/earcut": "^3.0.0",
- "@webgpu/types": "^0.1.69",
- "@xmldom/xmldom": "^0.8.12",
- "earcut": "^3.0.2",
- "eventemitter3": "^5.0.1",
- "gifuct-js": "^2.1.2",
- "ismobilejs": "^1.1.1",
- "parse-svg-path": "^0.1.2",
- "tiny-lru": "^11.4.7"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/pixijs"
- }
- },
- "node_modules/pixi.js/node_modules/@types/earcut": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/@types/earcut/-/earcut-3.0.0.tgz",
- "integrity": "sha512-k/9fOUGO39yd2sCjrbAJvGDEQvRwRnQIZlBz43roGwUZo5SHAmyVvSFyaVVZkicRVCaDXPKlbxrUcBuJoSWunQ==",
- "license": "MIT"
- },
- "node_modules/pixi.js/node_modules/earcut": {
- "version": "3.0.2",
- "resolved": "https://registry.npmjs.org/earcut/-/earcut-3.0.2.tgz",
- "integrity": "sha512-X7hshQbLyMJ/3RPhyObLARM2sNxxmRALLKx1+NVFFnQ9gKzmCrxm9+uLIAdBcvc8FNLpctqlQ2V6AE92Ol9UDQ==",
- "license": "ISC"
- },
- "node_modules/pixi.js/node_modules/eventemitter3": {
- "version": "5.0.4",
- "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
- "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
- "license": "MIT"
- },
"node_modules/playwright": {
"version": "1.59.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.1.tgz",
@@ -11057,15 +10955,6 @@
"semver": "bin/semver"
}
},
- "node_modules/tiny-lru": {
- "version": "11.4.7",
- "resolved": "https://registry.npmjs.org/tiny-lru/-/tiny-lru-11.4.7.tgz",
- "integrity": "sha512-w/Te7uMUVeH0CR8vZIjr+XiN41V+30lkDdK+NRIDCUYKKuL9VcmaUEmaPISuwGhLlrTGh5yu18lENtR9axSxYw==",
- "license": "BSD-3-Clause",
- "engines": {
- "node": ">=12"
- }
- },
"node_modules/tinybench": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
diff --git a/package.json b/package.json
index 8602a807f..0c8c0194a 100644
--- a/package.json
+++ b/package.json
@@ -88,8 +88,6 @@
"mediabunny": "^1.40.1",
"motion": "^12.38.0",
"mp4box": "^2.3.0",
- "pixi-filters": "^6.1.5",
- "pixi.js": "^8.18.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-icons": "^5.6.0",
diff --git a/src/components/ai-edition/CursorPreviewLayer.module.css b/src/components/ai-edition/CursorPreviewLayer.module.css
deleted file mode 100644
index 8237d3aef..000000000
--- a/src/components/ai-edition/CursorPreviewLayer.module.css
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Cursor preview layer. Transparent overlay that hosts a Pixi canvas +
- a native-cursor <img>. The Pixi canvas is appended by the component on
- mount; the <img> is positioned via translate3d in the same coordinate
- space as the <video>, so cursor + video always align. */
-
-.layer {
- position: absolute;
- inset: 0;
- z-index: 2;
- pointer-events: none;
- overflow: hidden;
-}
-
-.layer[data-clip="off"] {
- overflow: visible;
-}
-
-.nativeCursorClip {
- position: absolute;
- inset: 0;
- pointer-events: none;
-}
-
-.nativeCursor {
- position: absolute;
- top: 0;
- left: 0;
- image-rendering: -webkit-optimize-contrast;
- image-rendering: crisp-edges;
- will-change: transform, filter;
- user-select: none;
- -webkit-user-drag: none;
- display: none;
-}
diff --git a/src/components/ai-edition/CursorPreviewLayer.test.tsx b/src/components/ai-edition/CursorPreviewLayer.test.tsx
deleted file mode 100644
index d906d1508..000000000
--- a/src/components/ai-edition/CursorPreviewLayer.test.tsx
+++ /dev/null
@@ -1,212 +0,0 @@
-import "@testing-library/jest-dom";
-import { act, cleanup, render } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
-import { CursorPreviewLayer } from "./CursorPreviewLayer";
-
-const bridgeMocks = vi.hoisted(() => ({
- getRecordingData: vi.fn(),
- getTelemetry: vi.fn(),
-}));
-
-class StubResizeObserver {
- private callback: ResizeObserverCallback;
- private target: Element | null = null;
- constructor(callback: ResizeObserverCallback) {
- this.callback = callback;
- }
- observe(target: Element) {
- this.target = target;
- return undefined;
- }
- unobserve() {
- return undefined;
- }
- disconnect() {
- return undefined;
- }
-}
-
-vi.mock("@/native/client", () => ({
- nativeBridgeClient: {
- cursor: {
- getRecordingData: bridgeMocks.getRecordingData,
- getTelemetry: bridgeMocks.getTelemetry,
- },
- },
-}));
-
-vi.mock("@/lib/cursor/pixiCursorRenderer", () => ({
- DEFAULT_CURSOR_CONFIG: { dotRadius: 28, smoothingFactor: 0, motionBlur: 0, clickBounce: 1 },
- preloadCursorAssets: vi.fn(async () => undefined),
- PixiCursorOverlay: class {
- public container = { label: "" };
- // ponytail: no-op stubs — the test asserts on the React boundary,
- // not on Pixi internals.
- update() {
- /* no-op */
- }
- setDotRadius() {
- /* no-op */
- }
- setSmoothingFactor() {
- /* no-op */
- }
- setMotionBlur() {
- /* no-op */
- }
- setClickBounce() {
- /* no-op */
- }
- reset() {
- /* no-op */
- }
- destroy() {
- /* no-op */
- }
- },
-}));
-
-vi.mock("pixi.js", () => ({
- Application: class {
- public canvas = document.createElement("canvas");
- public stage = { addChild: vi.fn() };
- public ticker = { maxFPS: 60 };
- public renderer = {};
- // ponytail: no-op stubs — the test asserts on the React boundary,
- // not on Pixi internals.
- async init() {
- /* no-op */
- }
- destroy() {
- /* no-op */
- }
- },
- Container: class {},
-}));
-
-const SAMPLE_DOC = {
- schemaVersion: 3,
- project: {
- id: "proj_test",
- title: "Test",
- createdAt: "2026-06-25T10:00:00.000Z",
- updatedAt: "2026-06-25T10:00:00.000Z",
- },
- assets: [],
- transcript: null,
- transcripts: [],
- timeline: {
- clips: [],
- gaps: [],
- trimRanges: [],
- muteRanges: [],
- speedRegions: [],
- captionRanges: [],
- },
- annotations: [],
- zoomRanges: [],
- legacyEditor: null,
-};
-
-function renderWithVideo(): { host: HTMLDivElement; video: HTMLVideoElement } {
- const stage = document.createElement("div");
- const video = document.createElement("video");
- stage.appendChild(video);
- document.body.appendChild(stage);
- vi.spyOn(video, "getBoundingClientRect").mockReturnValue({
- x: 0,
- y: 0,
- width: 1920,
- height: 1080,
- top: 0,
- right: 1920,
- bottom: 1080,
- left: 0,
- toJSON: () => "",
- });
-
- const host = document.createElement("div");
- stage.appendChild(host);
- act(() => {
- render(
- <CursorPreviewLayer videoPath="/tmp/recording.mp4" currentTimeSec={0.5} isPlaying={false} />,
- { container: host },
- );
- });
- return { host: stage, video };
-}
-
-describe("CursorPreviewLayer (shared)", () => {
- beforeEach(() => {
- Object.defineProperty(window, "ResizeObserver", {
- writable: true,
- value: StubResizeObserver,
- });
- useProjectStore.getState().clear();
- useProjectStore.setState({
- projectId: "proj_test",
- document: SAMPLE_DOC,
- revision: 1,
- status: "ready",
- error: null,
- sourceDurationSec: 0,
- currentTimeSec: 0,
- dirty: false,
- lastSavedAt: new Date(),
- });
- for (const mock of Object.values(bridgeMocks)) {
- mock.mockReset();
- }
- });
-
- afterEach(() => {
- cleanup();
- document.body.innerHTML = "";
- });
-
- it("renders nothing when videoPath is null", () => {
- bridgeMocks.getRecordingData.mockResolvedValue(null);
- bridgeMocks.getTelemetry.mockResolvedValue([]);
- const host = document.createElement("div");
- document.body.appendChild(host);
- act(() => {
- render(<CursorPreviewLayer videoPath={null} currentTimeSec={0} isPlaying={false} />, {
- container: host,
- });
- });
- expect(host.querySelector("img")).toBeNull();
- });
-
- it("queries the native bridge for cursor data when videoPath is set", async () => {
- bridgeMocks.getRecordingData.mockImplementation(async () => null);
- bridgeMocks.getTelemetry.mockImplementation(async () => []);
- renderWithVideo();
-
- await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 0));
- });
-
- expect(bridgeMocks.getRecordingData).toHaveBeenCalledWith("/tmp/recording.mp4");
- expect(bridgeMocks.getTelemetry).toHaveBeenCalledWith("/tmp/recording.mp4");
- });
-
- it("hides the native cursor <img> when settings.cursorShow is false", async () => {
- bridgeMocks.getRecordingData.mockImplementation(async () => null);
- bridgeMocks.getTelemetry.mockImplementation(async () => []);
- const document = useProjectStore.getState().document;
- useProjectStore.setState({
- document: { ...document!, legacyEditor: { cursorShow: false } },
- });
- const { host } = renderWithVideo();
-
- // ponytail: let the rAF tick fire + flush.
- await act(async () => {
- await new Promise((resolve) => setTimeout(resolve, 16));
- });
-
- const img = host.querySelector("img");
- expect(img).toBeTruthy();
- expect((img as HTMLImageElement).style.display).toBe("none");
- });
-});
diff --git a/src/components/ai-edition/CursorPreviewLayer.tsx b/src/components/ai-edition/CursorPreviewLayer.tsx
deleted file mode 100644
index 7a4d70a5f..000000000
--- a/src/components/ai-edition/CursorPreviewLayer.tsx
+++ /dev/null
@@ -1,440 +0,0 @@
-// Shared cursor preview layer for the editor.
-//
-// Renders the cursor on top of a <video> element. Uses the same cursor
-// assets, smoothing, click bounce, motion blur, and themed native cursor
-// bitmaps as the legacy editor's Pixi-based path. Reads cursor visual
-// config from `useEditorSettings`.
-//
-// The cursor data lives in `src/lib/cursor/` so both editors share the
-// same `PixiCursorOverlay` class: the new editor mounts this component as
-// a sibling of the <video>, and the legacy editor drives the same
-// `PixiCursorOverlay` directly from inside its existing Pixi stage
-// (which carries the additional zoom / crop / 3D transform math).
-
-import { Application, Container } from "pixi.js";
-import { useEffect, useMemo, useRef, useState } from "react";
-import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
-import { getSmoothedCursorPath } from "@/lib/cursor/cursorPathSmoothing";
-import {
- createNativeCursorMotionBlurState,
- getNativeCursorClickBounceProgress,
- getNativeCursorClickBounceScale,
- getNativeCursorMotionBlurPx,
- hasNativeCursorRecordingData,
- resolveInterpolatedNativeCursorFrame,
- resolveNativeCursorRenderAsset,
-} from "@/lib/cursor/nativeCursor";
-import {
- DEFAULT_CURSOR_CONFIG,
- PixiCursorOverlay,
- preloadCursorAssets,
-} from "@/lib/cursor/pixiCursorRenderer";
-import { useCursorRecordingData } from "@/native/hooks/useCursorRecordingData";
-import { useCursorTelemetry } from "@/native/hooks/useCursorTelemetry";
-import styles from "./CursorPreviewLayer.module.css";
-
-interface CursorPreviewLayerProps {
- videoPath: string | null;
- currentTimeSec: number;
- isPlaying: boolean;
-}
-
-export function CursorPreviewLayer({
- videoPath,
- currentTimeSec,
- isPlaying,
-}: CursorPreviewLayerProps) {
- const { settings } = useEditorSettings();
- const { data: cursorRecordingData } = useCursorRecordingData(videoPath);
- const { samples: cursorTelemetry } = useCursorTelemetry(videoPath);
-
- const hasNativeCursor = useMemo(
- () => hasNativeCursorRecordingData(cursorRecordingData),
- [cursorRecordingData],
- );
-
- // Layer ref — the DOM <div> that hosts the Pixi canvas + native-cursor
- // <img>. Sized to the <video> via ResizeObserver; both editors mount the
- // layer as a sibling of the <video> so the measurements line up.
- const layerRef = useRef<HTMLDivElement | null>(null);
- const [size, setSize] = useState({ width: 0, height: 0 });
-
- // biome-ignore lint/correctness/useExhaustiveDependencies: re-run when videoPath changes so the observer re-attaches to the new <video>.
- useEffect(() => {
- const layer = layerRef.current;
- if (!layer) return;
- const video = layer.parentElement?.querySelector("video");
- if (!video) return;
- const update = () => {
- const rect = video.getBoundingClientRect();
- setSize({ width: rect.width, height: rect.height });
- };
- update();
- const ro = new ResizeObserver(update);
- ro.observe(video);
- window.addEventListener("resize", update);
- return () => {
- ro.disconnect();
- window.removeEventListener("resize", update);
- };
- }, [videoPath]);
-
- // Pixi application + cursor overlay lifecycle. The app is created once
- // per videoPath and torn down on swap. The overlay is created after
- // cursor assets finish loading (otherwise it'd throw on missing assets).
- const appRef = useRef<Application | null>(null);
- const overlayRef = useRef<PixiCursorOverlay | null>(null);
- const [pixiReady, setPixiReady] = useState(false);
- const appMountedRef = useRef<HTMLDivElement | null>(null);
-
- // biome-ignore lint/correctness/useExhaustiveDependencies: re-create on videoPath so the Pixi stage tracks the current asset.
- useEffect(() => {
- if (!videoPath) {
- setPixiReady(false);
- return;
- }
- const host = layerRef.current;
- if (!host) return;
- let mounted = true;
- let app: Application | null = null;
-
- (async () => {
- let enabled = true;
- try {
- await preloadCursorAssets();
- } catch {
- enabled = false;
- }
- if (!mounted) return;
- if (!enabled) {
- setPixiReady(false);
- return;
- }
- app = new Application();
- await app.init({
- width: size.width || 1,
- height: size.height || 1,
- backgroundAlpha: 0,
- antialias: true,
- resolution: window.devicePixelRatio || 1,
- autoDensity: true,
- });
- if (!mounted) {
- app.destroy(true, { children: true, texture: true, textureSource: true });
- return;
- }
- app.ticker.maxFPS = 60;
- host.appendChild(app.canvas);
- appRef.current = app;
- appMountedRef.current = host;
-
- const overlay = new PixiCursorOverlay({
- dotRadius: DEFAULT_CURSOR_CONFIG.dotRadius * settings.cursor.size,
- smoothingFactor: settings.cursor.smoothing,
- motionBlur: settings.cursor.motionBlur,
- clickBounce: settings.cursor.clickBounce,
- });
- overlay.container.label = "cursor-overlay";
- app.stage.addChild(overlay.container as Container);
- overlayRef.current = overlay;
- setPixiReady(true);
- })();
-
- return () => {
- mounted = false;
- setPixiReady(false);
- if (overlayRef.current) {
- overlayRef.current.destroy();
- overlayRef.current = null;
- }
- if (app && app.renderer) {
- const canvas = app.canvas;
- if (canvas.parentElement === host) host.removeChild(canvas);
- app.destroy(true, { children: true, texture: true, textureSource: true });
- }
- appRef.current = null;
- appMountedRef.current = null;
- };
- // ponytail: settings.* are read inside the async init only on
- // mount; live updates go through the rAF tick + the live-update
- // effect below.
- }, [videoPath]);
-
- // Live-update the overlay's config when the panel sliders move. The
- // effect is debounced via the rAF tick — the smoothing slider in
- // particular benefits from resetting the spring state.
- useEffect(() => {
- const overlay = overlayRef.current;
- if (!overlay) return;
- overlay.setDotRadius(DEFAULT_CURSOR_CONFIG.dotRadius * settings.cursor.size);
- overlay.setSmoothingFactor(settings.cursor.smoothing);
- overlay.setMotionBlur(settings.cursor.motionBlur);
- overlay.setClickBounce(settings.cursor.clickBounce);
- overlay.reset();
- }, [
- settings.cursor.size,
- settings.cursor.smoothing,
- settings.cursor.motionBlur,
- settings.cursor.clickBounce,
- ]);
-
- // Native cursor (DOM <img>) refs.
- const imageRef = useRef<HTMLImageElement | null>(null);
- const clipRef = useRef<HTMLDivElement | null>(null);
- const motionBlurStateRef = useRef(createNativeCursorMotionBlurState());
- const lastImageIdRef = useRef<string | null>(null);
-
- // rAF tick — drives both the Pixi overlay (telemetry cursor) and the
- // native cursor DOM <img> (recorded cursor). Reads the latest refs
- // inside the tick so React state churn doesn't restart the loop.
- const timeRef = useRef(currentTimeSec);
- const playingRef = useRef(isPlaying);
- const showCursorRef = useRef(settings.cursorShow);
- const cursorThemeRef = useRef(settings.cursorTheme);
- const sizeRef = useRef(size);
- const hasNativeRef = useRef(hasNativeCursor);
- const recordingDataRef = useRef(cursorRecordingData);
- const telemetryRef = useRef(cursorTelemetry);
- const smoothingRef = useRef(settings.cursor.smoothing);
- const clickBounceRef = useRef(settings.cursor.clickBounce);
- const cursorSizeRef = useRef(settings.cursor.size);
- const cursorMotionBlurRef = useRef(settings.cursor.motionBlur);
- const cursorClipToBoundsRef = useRef(settings.cursor.clipToBounds);
-
- useEffect(() => {
- timeRef.current = currentTimeSec;
- }, [currentTimeSec]);
- useEffect(() => {
- playingRef.current = isPlaying;
- }, [isPlaying]);
- useEffect(() => {
- showCursorRef.current = settings.cursorShow;
- }, [settings.cursorShow]);
- useEffect(() => {
- cursorThemeRef.current = settings.cursorTheme;
- }, [settings.cursorTheme]);
- useEffect(() => {
- sizeRef.current = size;
- }, [size]);
- useEffect(() => {
- hasNativeRef.current = hasNativeCursor;
- }, [hasNativeCursor]);
- useEffect(() => {
- recordingDataRef.current = cursorRecordingData;
- }, [cursorRecordingData]);
- useEffect(() => {
- telemetryRef.current = cursorTelemetry;
- }, [cursorTelemetry]);
- useEffect(() => {
- smoothingRef.current = settings.cursor.smoothing;
- }, [settings.cursor.smoothing]);
- useEffect(() => {
- clickBounceRef.current = settings.cursor.clickBounce;
- }, [settings.cursor.clickBounce]);
- useEffect(() => {
- cursorSizeRef.current = settings.cursor.size;
- }, [settings.cursor.size]);
- useEffect(() => {
- cursorMotionBlurRef.current = settings.cursor.motionBlur;
- }, [settings.cursor.motionBlur]);
- useEffect(() => {
- cursorClipToBoundsRef.current = settings.cursor.clipToBounds;
- }, [settings.cursor.clipToBounds]);
-
- // rAF loop is restarted only when the Pixi app mounts (or unmounts).
- useEffect(() => {
- if (!pixiReady) return;
- let raf = 0;
- const tick = () => {
- raf = window.requestAnimationFrame(tick);
- const overlay = overlayRef.current;
- if (!overlay) return;
- const timeMs = timeRef.current * 1000;
- const viewport = { x: 0, y: 0, ...sizeRef.current };
- const samples = hasNativeRef.current ? [] : telemetryRef.current;
- overlay.update(samples, timeMs, viewport, showCursorRef.current, !playingRef.current);
- };
- raf = window.requestAnimationFrame(tick);
- return () => window.cancelAnimationFrame(raf);
- }, [pixiReady]);
-
- // Native cursor DOM <img> tick — separate from the Pixi tick because
- // this layer doesn't depend on the Pixi app mount.
- useEffect(() => {
- if (!videoPath) return;
- let raf = 0;
- const tick = () => {
- raf = window.requestAnimationFrame(tick);
- renderNativeCursorFrame({
- hasNativeCursor: hasNativeRef.current,
- recordingData: recordingDataRef.current,
- telemetry: telemetryRef.current,
- timeMs: timeRef.current * 1000,
- isPlaying: playingRef.current,
- size: sizeRef.current,
- cursorSize: cursorSizeRef.current,
- cursorSmoothing: smoothingRef.current,
- cursorClickBounce: clickBounceRef.current,
- cursorMotionBlur: cursorMotionBlurRef.current,
- cursorTheme: cursorThemeRef.current,
- cursorClipToBounds: cursorClipToBoundsRef.current,
- showCursor: showCursorRef.current,
- imageRef,
- clipRef,
- lastImageIdRef,
- motionBlurStateRef,
- });
- };
- raf = window.requestAnimationFrame(tick);
- return () => window.cancelAnimationFrame(raf);
- }, [videoPath]);
-
- if (!videoPath) return null;
-
- return (
- <div
- ref={layerRef}
- className={styles.layer}
- data-clip={settings.cursor.clipToBounds ? "on" : "off"}
- >
- <div ref={clipRef} className={styles.nativeCursorClip}>
- <img ref={imageRef} alt="" className={styles.nativeCursor} draggable={false} />
- </div>
- </div>
- );
-}
-
-interface NativeCursorFrameInputs {
- hasNativeCursor: boolean;
- recordingData: ReturnType<typeof useCursorRecordingData>["data"];
- telemetry: ReturnType<typeof useCursorTelemetry>["samples"];
- timeMs: number;
- isPlaying: boolean;
- size: { width: number; height: number };
- cursorSize: number;
- cursorSmoothing: number;
- cursorClickBounce: number;
- cursorMotionBlur: number;
- cursorTheme: string;
- cursorClipToBounds: boolean;
- showCursor: boolean;
- imageRef: React.MutableRefObject<HTMLImageElement | null>;
- clipRef: React.MutableRefObject<HTMLDivElement | null>;
- lastImageIdRef: React.MutableRefObject<string | null>;
- motionBlurStateRef: React.MutableRefObject<ReturnType<typeof createNativeCursorMotionBlurState>>;
-}
-
-function renderNativeCursorFrame(inputs: NativeCursorFrameInputs) {
- const {
- hasNativeCursor,
- recordingData,
- telemetry,
- timeMs,
- isPlaying,
- size,
- cursorSize,
- cursorSmoothing,
- cursorClickBounce,
- cursorMotionBlur,
- cursorTheme,
- cursorClipToBounds,
- showCursor,
- imageRef,
- clipRef,
- lastImageIdRef,
- motionBlurStateRef,
- } = inputs;
-
- const imageEl = imageRef.current;
- const clipEl = clipRef.current;
- const hide = () => {
- if (imageEl) imageEl.style.display = "none";
- if (clipEl) clipEl.style.clipPath = "none";
- };
-
- if (!showCursor || size.width <= 0 || size.height <= 0) {
- hide();
- return;
- }
-
- if (!hasNativeCursor || !recordingData) {
- // ponytail: telemetry-only fallback. Draw a synthetic dot at the
- // smoothed path. The Pixi overlay already does this with the
- // bundled SVG art; the DOM <img> is the no-native path used in
- // legacy recordings (no cursor bitmaps captured).
- const samples = telemetry;
- if (samples.length === 0) {
- hide();
- return;
- }
- const path = getSmoothedCursorPath(
- { version: 1, provider: "none", samples: samples as never, assets: [] },
- cursorSmoothing,
- );
- const pos = path?.sampleAt(timeMs);
- if (!pos || !imageEl) {
- hide();
- return;
- }
- const radius = Math.max(4, 28 * Math.max(0, cursorSize));
- const x = pos.cx * size.width;
- const y = pos.cy * size.height;
- if (lastImageIdRef.current !== "fallback-dot") {
- imageEl.src =
- "data:image/svg+xml;utf8," +
- encodeURIComponent(
- `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><circle cx="16" cy="16" r="14" fill="#ff4040" stroke="#fff" stroke-width="2"/></svg>`,
- );
- lastImageIdRef.current = "fallback-dot";
- }
- imageEl.style.display = "block";
- imageEl.style.width = `${radius * 2}px`;
- imageEl.style.height = `${radius * 2}px`;
- imageEl.style.transform = `translate3d(${x - radius}px, ${y - radius}px, 0)`;
- imageEl.style.filter = "none";
- return;
- }
-
- const frame = resolveInterpolatedNativeCursorFrame(recordingData, timeMs);
- if (!frame) {
- hide();
- return;
- }
- const pos = getSmoothedCursorPath(recordingData, cursorSmoothing)?.sampleAt(timeMs);
- const displaySample = pos ? { ...frame.sample, cx: pos.cx, cy: pos.cy } : frame.sample;
- const renderAsset = resolveNativeCursorRenderAsset(frame.asset, 1, displaySample, cursorTheme);
- const bounceProgress = getNativeCursorClickBounceProgress(recordingData, timeMs);
- const scale =
- Math.max(0, cursorSize) * getNativeCursorClickBounceScale(cursorClickBounce, bounceProgress);
- const x = displaySample.cx * size.width;
- const y = displaySample.cy * size.height;
- const motionBlurPx = isPlaying
- ? getNativeCursorMotionBlurPx({
- motionBlur: cursorMotionBlur,
- point: { x, y },
- state: motionBlurStateRef.current,
- timeMs,
- })
- : 0;
-
- if (imageEl) {
- if (lastImageIdRef.current !== renderAsset.id) {
- imageEl.src = renderAsset.imageDataUrl;
- lastImageIdRef.current = renderAsset.id;
- }
- imageEl.style.display = "block";
- imageEl.style.width = `${renderAsset.width * scale}px`;
- imageEl.style.height = `${renderAsset.height * scale}px`;
- imageEl.style.transform = `translate3d(${x - renderAsset.hotspotX * scale}px, ${
- y - renderAsset.hotspotY * scale
- }px, 0)`;
- imageEl.style.filter = motionBlurPx > 0 ? `blur(${motionBlurPx.toFixed(2)}px)` : "none";
- }
- if (clipEl) {
- if (!cursorClipToBounds) {
- clipEl.style.clipPath = "none";
- } else {
- clipEl.style.clipPath = `inset(0 0 0 0)`;
- }
- }
-}
diff --git a/src/lib/cursor/nativeCursor.test.ts b/src/lib/cursor/nativeCursor.test.ts
deleted file mode 100644
index 3bc49a0a2..000000000
--- a/src/lib/cursor/nativeCursor.test.ts
+++ /dev/null
@@ -1,285 +0,0 @@
-import { describe, expect, it } from "vitest";
-import type { NativeCursorAsset } from "@/native/contracts";
-import {
- getNativeCursorClickBounceProgress,
- getNativeCursorClickBounceScale,
- hasNativeCursorRecordingData,
- projectNativeCursorToLocal,
- resolveInterpolatedNativeCursorFrame,
- resolveNativeCursorRenderAsset,
-} from "./nativeCursor";
-
-describe("native cursor click bounce", () => {
- it("keeps click progress visible across several frames", () => {
- const recordingData = {
- version: 2,
- provider: "native" as const,
- assets: [],
- samples: [
- { timeMs: 0, cx: 0.5, cy: 0.5, interactionType: "move" as const },
- { timeMs: 100, cx: 0.5, cy: 0.5, interactionType: "click" as const },
- { timeMs: 133, cx: 0.5, cy: 0.5, interactionType: "move" as const },
- { timeMs: 166, cx: 0.5, cy: 0.5, interactionType: "move" as const },
- { timeMs: 200, cx: 0.5, cy: 0.5, interactionType: "move" as const },
- { timeMs: 300, cx: 0.5, cy: 0.5, interactionType: "move" as const },
- ],
- };
-
- expect(getNativeCursorClickBounceProgress(recordingData, 133)).toBeGreaterThan(0);
- expect(getNativeCursorClickBounceProgress(recordingData, 200)).toBeGreaterThan(0);
- expect(getNativeCursorClickBounceProgress(recordingData, 400)).toBe(0);
- });
-
- it("applies a visible press and rebound scale at high intensity", () => {
- expect(getNativeCursorClickBounceScale(5, 1)).toBe(1);
- expect(getNativeCursorClickBounceScale(5, 0.82)).toBeLessThan(0.9);
- expect(getNativeCursorClickBounceScale(5, 0.28)).toBeGreaterThan(1.05);
- expect(getNativeCursorClickBounceScale(5, 0)).toBe(1);
- });
-
- it("uses the default cursor asset for telemetry-only macOS recordings", () => {
- const recordingData = {
- version: 2,
- provider: "none" as const,
- assets: [],
- samples: [
- { timeMs: 0, cx: 0.25, cy: 0.4, visible: true },
- { timeMs: 100, cx: 0.75, cy: 0.6, visible: true },
- ],
- };
-
- expect(hasNativeCursorRecordingData(recordingData)).toBe(true);
- const frame = resolveInterpolatedNativeCursorFrame(recordingData, 50);
- expect(frame?.asset.cursorType).toBe("arrow");
- expect(frame?.sample.cx).toBeCloseTo(0.5);
- expect(frame?.sample.cy).toBeCloseTo(0.5);
- });
-
- it("renders the natively captured cursor bitmap for untyped macOS samples", () => {
- const capturedAsset: NativeCursorAsset = {
- id: "sha-custom",
- platform: "darwin",
- imageDataUrl: "data:image/png;base64,CUSTOMCURSOR",
- width: 48,
- height: 48,
- hotspotX: 8,
- hotspotY: 8,
- scaleFactor: 2,
- };
- const recordingData = {
- version: 2,
- provider: "native" as const,
- assets: [capturedAsset],
- samples: [
- { timeMs: 0, cx: 0.4, cy: 0.4, visible: true, assetId: "sha-custom" },
- { timeMs: 100, cx: 0.6, cy: 0.6, visible: true, assetId: "sha-custom" },
- ],
- };
-
- const frame = resolveInterpolatedNativeCursorFrame(recordingData, 50);
- expect(frame?.asset.id).toBe("sha-custom");
-
- // No cursorType => no bundled pretty SVG substitution => real captured bitmap,
- // downscaled from pixels to points via the asset scale factor.
- const rendered = resolveNativeCursorRenderAsset(capturedAsset, 1, frame?.sample);
- expect(rendered.imageDataUrl).toBe("data:image/png;base64,CUSTOMCURSOR");
- expect(rendered.width).toBe(24);
- expect(rendered.hotspotX).toBe(4);
- });
-
- it("applies click bounce to telemetry-only macOS recordings", () => {
- const recordingData = {
- version: 2,
- provider: "none" as const,
- assets: [],
- samples: [
- { timeMs: 0, cx: 0.5, cy: 0.5, visible: true, interactionType: "move" as const },
- { timeMs: 100, cx: 0.5, cy: 0.5, visible: true, interactionType: "click" as const },
- { timeMs: 133, cx: 0.5, cy: 0.5, visible: true, interactionType: "move" as const },
- ],
- };
-
- expect(getNativeCursorClickBounceProgress(recordingData, 133)).toBeGreaterThan(0);
- });
-});
-
-describe("custom cursor themes", () => {
- const arrowAsset: NativeCursorAsset = {
- id: "telemetry-arrow",
- platform: "darwin",
- imageDataUrl: "default-arrow",
- width: 32,
- height: 32,
- hotspotX: 16,
- hotspotY: 15,
- cursorType: "arrow",
- };
-
- it("substitutes the themed art for an overridden cursor type", () => {
- const rendered = resolveNativeCursorRenderAsset(
- arrowAsset,
- 1,
- { timeMs: 0, cx: 0.5, cy: 0.5, cursorType: "arrow" },
- "hello-kitty-watermelon",
- );
-
- expect(rendered.id).toBe("theme:hello-kitty-watermelon:arrow");
- expect(rendered.imageDataUrl).toContain("cursors/hello-kitty-watermelon/arrow.png");
- expect(rendered.width).toBe(32);
- expect(rendered.hotspotX).toBeCloseTo(1.5);
- });
-
- it("classifies an untyped macOS arrow bitmap (top-left hotspot) as the themed arrow", () => {
- const macArrow: NativeCursorAsset = {
- id: "sha-arrow",
- platform: "darwin",
- imageDataUrl: "captured-bitmap",
- width: 34,
- height: 46,
- hotspotX: 8,
- hotspotY: 8,
- scaleFactor: 2,
- };
- const rendered = resolveNativeCursorRenderAsset(
- macArrow,
- 1,
- { timeMs: 0, cx: 0.5, cy: 0.5 },
- "hello-kitty-watermelon",
- );
-
- expect(rendered.id).toBe("theme:hello-kitty-watermelon:arrow");
- expect(rendered.imageDataUrl).toContain("cursors/hello-kitty-watermelon/arrow.png");
- });
-
- it("classifies an untyped macOS hand bitmap (upper-center hotspot) as the themed pointer", () => {
- const macHand: NativeCursorAsset = {
- id: "sha-hand",
- platform: "darwin",
- imageDataUrl: "captured-bitmap",
- width: 64,
- height: 64,
- hotspotX: 26,
- hotspotY: 16,
- scaleFactor: 2,
- };
- const rendered = resolveNativeCursorRenderAsset(
- macHand,
- 1,
- { timeMs: 0, cx: 0.5, cy: 0.5 },
- "hello-kitty-watermelon",
- );
-
- expect(rendered.id).toBe("theme:hello-kitty-watermelon:pointer");
- expect(rendered.imageDataUrl).toContain("cursors/hello-kitty-watermelon/pointer.png");
- });
-
- it("leaves an untyped text/crosshair bitmap (centered hotspot) as the real captured cursor", () => {
- const macText: NativeCursorAsset = {
- id: "sha-text",
- platform: "darwin",
- imageDataUrl: "captured-ibeam",
- width: 18,
- height: 36,
- hotspotX: 8,
- hotspotY: 18,
- scaleFactor: 2,
- };
- const rendered = resolveNativeCursorRenderAsset(
- macText,
- 1,
- { timeMs: 0, cx: 0.5, cy: 0.5 },
- "hello-kitty-watermelon",
- );
-
- expect(rendered.id).toBe("sha-text");
- expect(rendered.imageDataUrl).toBe("captured-ibeam");
- });
-
- it("keeps the default art for the default theme id", () => {
- const rendered = resolveNativeCursorRenderAsset(
- arrowAsset,
- 1,
- { timeMs: 0, cx: 0.5, cy: 0.5, cursorType: "arrow" },
- "default",
- );
-
- expect(rendered.id).toBe("pretty:arrow");
- expect(rendered.imageDataUrl).not.toContain("hello-kitty-watermelon");
- });
-
- it("falls back to default art for a cursor type the theme does not override", () => {
- const rendered = resolveNativeCursorRenderAsset(
- { ...arrowAsset, cursorType: "text" },
- 1,
- { timeMs: 0, cx: 0.5, cy: 0.5, cursorType: "text" },
- "hello-kitty-watermelon",
- );
-
- expect(rendered.id).toBe("pretty:text");
- });
-});
-
-describe("projectNativeCursorToLocal", () => {
- const identityCrop = { x: 0, y: 0, width: 1, height: 1 };
-
- it("maps a sample onto the supplied painted rectangle 1:1 with no crop", () => {
- const point = projectNativeCursorToLocal({
- cropRegion: identityCrop,
- maskRect: { x: 100, y: 200, width: 1280, height: 720 },
- sample: { timeMs: 0, cx: 0.25, cy: 0.5, visible: true },
- });
-
- expect(point?.x).toBeCloseTo(100 + 0.25 * 1280);
- expect(point?.y).toBeCloseTo(200 + 0.5 * 720);
- });
-
- it("maps a sample into the cropped region of the painted rectangle", () => {
- const point = projectNativeCursorToLocal({
- cropRegion: { x: 0.25, y: 0.0, width: 0.5, height: 1.0 },
- maskRect: { x: 0, y: 0, width: 1920, height: 1080 },
- sample: { timeMs: 0, cx: 0.5, cy: 0.5, visible: true },
- });
-
- expect(point?.x).toBeCloseTo(0 + ((0.5 - 0.25) / 0.5) * 1920);
- expect(point?.y).toBeCloseTo(0 + (0.5 / 1.0) * 1080);
- });
-
- it("projects onto the cropped (cover-overflowing) painted rect, not the mask rect", () => {
- const screenRect = { x: 0, y: 0, width: 1920, height: 1080 };
- const croppedRect = { x: 0, y: -540, width: 1920, height: 2160 };
-
- const point = projectNativeCursorToLocal({
- cropRegion: { x: 0.0, y: 0.0, width: 0.5, height: 1.0 },
- maskRect: croppedRect,
- sample: { timeMs: 0, cx: 0.25, cy: 0.25, visible: true },
- });
-
- const wrong = screenRect.y + 0.25 * screenRect.height;
- expect(wrong).toBe(270);
-
- expect(point?.x).toBeCloseTo(croppedRect.x + ((0.25 - 0) / 0.5) * croppedRect.width);
- expect(point?.y).toBeCloseTo(croppedRect.y + (0.25 / 1.0) * croppedRect.height);
- expect(point?.y).toBe(0);
- expect(point?.y).not.toBe(wrong);
- });
-
- it("returns null for a sample outside the cropped region", () => {
- const point = projectNativeCursorToLocal({
- cropRegion: { x: 0.25, y: 0.25, width: 0.5, height: 0.5 },
- maskRect: { x: 0, y: 0, width: 1920, height: 1080 },
- sample: { timeMs: 0, cx: 0.1, cy: 0.5, visible: true },
- });
-
- expect(point).toBeNull();
- });
-
- it("returns null for a degenerate (zero-size) crop region", () => {
- const point = projectNativeCursorToLocal({
- cropRegion: { x: 0, y: 0, width: 0, height: 1 },
- maskRect: { x: 0, y: 0, width: 1920, height: 1080 },
- sample: { timeMs: 0, cx: 0.5, cy: 0.5, visible: true },
- });
-
- expect(point).toBeNull();
- });
-});
diff --git a/src/lib/cursor/nativeCursor.ts b/src/lib/cursor/nativeCursor.ts
deleted file mode 100644
index 353f6be5a..000000000
--- a/src/lib/cursor/nativeCursor.ts
+++ /dev/null
@@ -1,626 +0,0 @@
-import { type Container, Point } from "pixi.js";
-import appStartingUrl from "@/assets/cursors/Cursor=App-Starting.svg";
-import crosshairUrl from "@/assets/cursors/Cursor=Cross.svg";
-import arrowUrl from "@/assets/cursors/Cursor=Default.svg";
-import closedHandUrl from "@/assets/cursors/Cursor=Hand-(Grabbing).svg";
-import openHandUrl from "@/assets/cursors/Cursor=Hand-(Open).svg";
-import pointerUrl from "@/assets/cursors/Cursor=Hand-(Pointing).svg";
-import helpUrl from "@/assets/cursors/Cursor=Help.svg";
-import moveUrl from "@/assets/cursors/Cursor=Move.svg";
-import notAllowedUrl from "@/assets/cursors/Cursor=Not-Allowed.svg";
-import resizeNeswUrl from "@/assets/cursors/Cursor=Resize-North-East-South-West.svg";
-import resizeNsUrl from "@/assets/cursors/Cursor=Resize-North-South.svg";
-import resizeNwseUrl from "@/assets/cursors/Cursor=Resize-North-West-South-East.svg";
-import resizeEwUrl from "@/assets/cursors/Cursor=Resize-West-East.svg";
-import textUrl from "@/assets/cursors/Cursor=Text-Cursor.svg";
-import upArrowUrl from "@/assets/cursors/Cursor=Up-Arrow.svg";
-import waitUrl from "@/assets/cursors/Cursor=Wait.svg";
-import type { CropRegion } from "@/components/video-editor/types";
-import { getAssetPath } from "@/lib/assetPath";
-import { DEFAULT_CURSOR_THEME_ID, getCursorTheme } from "@/lib/cursor/cursorThemes";
-import type {
- CursorRecordingData,
- CursorRecordingSample,
- NativeCursorAsset,
- NativeCursorType,
-} from "@/native/contracts";
-import { clamp } from "@/utils/math";
-
-export interface ActiveNativeCursorFrame {
- asset: NativeCursorAsset;
- sample: CursorRecordingSample;
-}
-
-export interface NativeCursorMotionBlurState {
- x: number;
- y: number;
- lastTimeMs: number | null;
- initialized: boolean;
-}
-
-interface ProjectNativeCursorOptions {
- cropRegion: CropRegion;
- maskRect: { x: number; y: number; width: number; height: number };
- sample: CursorRecordingSample;
-}
-
-interface ProjectNativeCursorToStageOptions extends ProjectNativeCursorOptions {
- cameraContainer: Container;
- videoContainerPosition: { x: number; y: number };
-}
-
-const NATIVE_CURSOR_CLICK_ANIMATION_MS = 260;
-const NATIVE_CURSOR_MOTION_BLUR_MAX_PX = 6;
-const nativeCursorAssetMapCache = new WeakMap<
- CursorRecordingData,
- Map<string, NativeCursorAsset>
->();
-
-function findNativeCursorSampleIndexAtOrBefore(samples: CursorRecordingSample[], timeMs: number) {
- let low = 0;
- let high = samples.length - 1;
- let result = -1;
-
- while (low <= high) {
- const middle = low + Math.floor((high - low) / 2);
- if (samples[middle].timeMs <= timeMs) {
- result = middle;
- low = middle + 1;
- } else {
- high = middle - 1;
- }
- }
-
- return result;
-}
-
-function getNativeCursorAssetMap(recordingData: CursorRecordingData) {
- const cached = nativeCursorAssetMapCache.get(recordingData);
- if (cached) {
- return cached;
- }
-
- const assetMap = new Map(recordingData.assets.map((asset) => [asset.id, asset]));
- nativeCursorAssetMapCache.set(recordingData, assetMap);
- return assetMap;
-}
-
-function getNativeCursorAsset(recordingData: CursorRecordingData, assetId: string) {
- return getNativeCursorAssetMap(recordingData).get(assetId) ?? null;
-}
-
-interface PrettyNativeCursorAsset {
- imageDataUrl: string;
- width: number;
- height: number;
- hotspotX: number;
- hotspotY: number;
-}
-
-const PRETTY_NATIVE_CURSOR_ASSETS: Partial<Record<NativeCursorType, PrettyNativeCursorAsset>> = {
- arrow: {
- imageDataUrl: arrowUrl,
- width: 32,
- height: 32,
- hotspotX: 16.25,
- hotspotY: 15.03,
- },
- text: {
- imageDataUrl: textUrl,
- width: 32,
- height: 32,
- hotspotX: 16,
- hotspotY: 16,
- },
- pointer: {
- imageDataUrl: pointerUrl,
- width: 32,
- height: 33,
- hotspotX: 16.65,
- hotspotY: 14.24,
- },
- crosshair: {
- imageDataUrl: crosshairUrl,
- width: 32,
- height: 32,
- hotspotX: 16,
- hotspotY: 16,
- },
- "open-hand": {
- imageDataUrl: openHandUrl,
- width: 32,
- height: 32,
- hotspotX: 16,
- hotspotY: 9,
- },
- "closed-hand": {
- imageDataUrl: closedHandUrl,
- width: 32,
- height: 32,
- hotspotX: 16,
- // Not 9 — that was open-hand's value, and the grabbing fist is drawn lower and
- // shorter, so it put the hotspot above the artwork entirely. Centred on the fist.
- hotspotY: 17,
- },
- "resize-ew": {
- imageDataUrl: resizeEwUrl,
- width: 32,
- height: 32,
- hotspotX: 16,
- hotspotY: 16,
- },
- "resize-ns": {
- imageDataUrl: resizeNsUrl,
- width: 32,
- height: 32,
- hotspotX: 16,
- hotspotY: 16,
- },
- "resize-nesw": {
- imageDataUrl: resizeNeswUrl,
- width: 32,
- height: 32,
- hotspotX: 16,
- hotspotY: 16,
- },
- "resize-nwse": {
- imageDataUrl: resizeNwseUrl,
- width: 32,
- height: 32,
- hotspotX: 16,
- hotspotY: 16,
- },
- move: {
- imageDataUrl: moveUrl,
- width: 32,
- height: 32,
- hotspotX: 16,
- hotspotY: 16,
- },
- "not-allowed": {
- imageDataUrl: notAllowedUrl,
- width: 32,
- height: 32,
- hotspotX: 16,
- hotspotY: 16,
- },
- wait: {
- imageDataUrl: waitUrl,
- width: 32,
- height: 32,
- hotspotX: 16,
- hotspotY: 16,
- },
- "app-starting": {
- imageDataUrl: appStartingUrl,
- width: 32,
- height: 32,
- hotspotX: 7.25,
- hotspotY: 4.03,
- },
- help: {
- imageDataUrl: helpUrl,
- width: 32,
- height: 32,
- hotspotX: 7.25,
- hotspotY: 4.03,
- },
- "up-arrow": {
- imageDataUrl: upArrowUrl,
- width: 32,
- height: 32,
- hotspotX: 16,
- hotspotY: 3,
- },
-};
-
-const TELEMETRY_CURSOR_ASSET: NativeCursorAsset = {
- id: "telemetry-arrow",
- platform: "darwin",
- imageDataUrl: arrowUrl,
- width: PRETTY_NATIVE_CURSOR_ASSETS.arrow?.width ?? 32,
- height: PRETTY_NATIVE_CURSOR_ASSETS.arrow?.height ?? 32,
- hotspotX: PRETTY_NATIVE_CURSOR_ASSETS.arrow?.hotspotX ?? 16,
- hotspotY: PRETTY_NATIVE_CURSOR_ASSETS.arrow?.hotspotY ?? 16,
- cursorType: "arrow",
-};
-
-function getTelemetryCursorAsset(sample?: CursorRecordingSample): NativeCursorAsset {
- const cursorType = sample?.cursorType ?? "arrow";
- const prettyAsset = PRETTY_NATIVE_CURSOR_ASSETS[cursorType] ?? PRETTY_NATIVE_CURSOR_ASSETS.arrow;
-
- return {
- ...TELEMETRY_CURSOR_ASSET,
- id: `telemetry-${cursorType}`,
- imageDataUrl: prettyAsset?.imageDataUrl ?? TELEMETRY_CURSOR_ASSET.imageDataUrl,
- width: prettyAsset?.width ?? TELEMETRY_CURSOR_ASSET.width,
- height: prettyAsset?.height ?? TELEMETRY_CURSOR_ASSET.height,
- hotspotX: prettyAsset?.hotspotX ?? TELEMETRY_CURSOR_ASSET.hotspotX,
- hotspotY: prettyAsset?.hotspotY ?? TELEMETRY_CURSOR_ASSET.hotspotY,
- cursorType,
- };
-}
-
-function resolveUntypedPrettyNativeCursorAsset(asset: NativeCursorAsset) {
- if (
- asset.cursorType ||
- asset.width < 24 ||
- asset.width > 64 ||
- asset.height < 24 ||
- asset.height > 64
- ) {
- return null;
- }
-
- const hotspotXNorm = asset.hotspotX / asset.width;
- const hotspotYNorm = asset.hotspotY / asset.height;
- const looksLikeChromiumGrabCursor =
- hotspotXNorm >= 0.22 && hotspotXNorm <= 0.55 && hotspotYNorm >= 0.2 && hotspotYNorm <= 0.45;
-
- return looksLikeChromiumGrabCursor ? (PRETTY_NATIVE_CURSOR_ASSETS["open-hand"] ?? null) : null;
-}
-
-export function hasNativeCursorRecordingData(
- recordingData: CursorRecordingData | null | undefined,
-): recordingData is CursorRecordingData {
- return Boolean(
- recordingData &&
- recordingData.samples.length > 0 &&
- (recordingData.assets.length > 0 || recordingData.provider === "none"),
- );
-}
-
-export function createNativeCursorMotionBlurState(): NativeCursorMotionBlurState {
- return {
- x: 0,
- y: 0,
- lastTimeMs: null,
- initialized: false,
- };
-}
-
-export function resetNativeCursorMotionBlurState(state: NativeCursorMotionBlurState) {
- state.x = 0;
- state.y = 0;
- state.lastTimeMs = null;
- state.initialized = false;
-}
-
-export function getNativeCursorClickBounceProgress(
- recordingData: CursorRecordingData | null | undefined,
- timeMs: number,
-) {
- if (!recordingData || recordingData.samples.length === 0) {
- return 0;
- }
-
- for (
- let index = findNativeCursorSampleIndexAtOrBefore(recordingData.samples, timeMs);
- index >= 0;
- index -= 1
- ) {
- const sample = recordingData.samples[index];
- const ageMs = timeMs - sample.timeMs;
- if (ageMs > NATIVE_CURSOR_CLICK_ANIMATION_MS) {
- return 0;
- }
-
- if (sample.interactionType === "click") {
- return 1 - ageMs / NATIVE_CURSOR_CLICK_ANIMATION_MS;
- }
- }
-
- return 0;
-}
-
-export function getNativeCursorClickBounceScale(clickBounce: number, progress: number) {
- if (progress <= 0 || clickBounce <= 0) {
- return 1;
- }
-
- const intensity = clamp(clickBounce, 0, 5) / 5;
- const elapsed = 1 - clamp(progress, 0, 1);
- if (elapsed < 0.38) {
- const pressProgress = Math.sin((elapsed / 0.38) * Math.PI);
- return 1 - pressProgress * intensity * 0.24;
- }
-
- const reboundProgress = Math.sin(((elapsed - 0.38) / 0.62) * Math.PI);
- return 1 + reboundProgress * intensity * 0.16;
-}
-
-export function getNativeCursorMotionBlurPx({
- motionBlur,
- point,
- state,
- timeMs,
-}: {
- motionBlur: number;
- point: { x: number; y: number };
- state: NativeCursorMotionBlurState;
- timeMs: number;
-}) {
- const clampedMotionBlur = clamp(Number.isFinite(motionBlur) ? motionBlur : 0, 0, 1);
- const previousTimeMs = state.lastTimeMs;
- const shouldSnap =
- clampedMotionBlur <= 0 ||
- !state.initialized ||
- previousTimeMs === null ||
- timeMs <= previousTimeMs;
-
- if (shouldSnap) {
- state.x = point.x;
- state.y = point.y;
- state.lastTimeMs = timeMs;
- state.initialized = true;
- return 0;
- }
-
- const deltaMs = Math.max(1, timeMs - previousTimeMs);
- const distance = Math.hypot(point.x - state.x, point.y - state.y);
- const speedPxPerSecond = (distance / deltaMs) * 1000;
- state.x = point.x;
- state.y = point.y;
- state.lastTimeMs = timeMs;
-
- return clamp(speedPxPerSecond * clampedMotionBlur * 0.004, 0, NATIVE_CURSOR_MOTION_BLUR_MAX_PX);
-}
-
-function getCroppedCursorPosition(sample: CursorRecordingSample, cropRegion: CropRegion) {
- if (cropRegion.width <= 0 || cropRegion.height <= 0) {
- return null;
- }
-
- const croppedCx = (sample.cx - cropRegion.x) / cropRegion.width;
- const croppedCy = (sample.cy - cropRegion.y) / cropRegion.height;
-
- if (croppedCx < 0 || croppedCx > 1 || croppedCy < 0 || croppedCy > 1) {
- return null;
- }
-
- return {
- cx: clamp(croppedCx, 0, 1),
- cy: clamp(croppedCy, 0, 1),
- };
-}
-
-function getNativeCursorMaskPoint(sample: CursorRecordingSample, cropRegion: CropRegion) {
- const croppedPosition = getCroppedCursorPosition(sample, cropRegion);
- if (!croppedPosition) {
- return null;
- }
-
- return new Point(croppedPosition.cx, croppedPosition.cy);
-}
-
-export function resolveActiveNativeCursorFrame(
- recordingData: CursorRecordingData | null | undefined,
- timeMs: number,
-): ActiveNativeCursorFrame | null {
- if (!hasNativeCursorRecordingData(recordingData)) {
- return null;
- }
-
- const index = findNativeCursorSampleIndexAtOrBefore(recordingData.samples, timeMs);
- if (index >= 0) {
- const sample = recordingData.samples[index];
-
- if (sample.visible === false) {
- return null;
- }
-
- const asset = sample.assetId
- ? getNativeCursorAsset(recordingData, sample.assetId)
- : getTelemetryCursorAsset(sample);
- if (!asset) {
- return null;
- }
-
- return { sample, asset };
- }
-
- return null;
-}
-
-export function resolveInterpolatedNativeCursorFrame(
- recordingData: CursorRecordingData | null | undefined,
- timeMs: number,
-): ActiveNativeCursorFrame | null {
- if (!hasNativeCursorRecordingData(recordingData)) {
- return null;
- }
-
- const samples = recordingData.samples;
- const activeIndex = findNativeCursorSampleIndexAtOrBefore(samples, timeMs);
-
- if (activeIndex < 0) {
- return null;
- }
-
- const activeSample = samples[activeIndex];
- if (activeSample.visible === false) {
- return null;
- }
-
- const asset = activeSample.assetId
- ? getNativeCursorAsset(recordingData, activeSample.assetId)
- : getTelemetryCursorAsset(activeSample);
- if (!asset) {
- return null;
- }
-
- const nextSample = samples[activeIndex + 1];
- if (
- !nextSample ||
- nextSample.timeMs <= activeSample.timeMs ||
- nextSample.visible === false ||
- (nextSample.assetId ?? null) !== (activeSample.assetId ?? null) ||
- timeMs <= activeSample.timeMs
- ) {
- return { asset, sample: activeSample };
- }
-
- const interpolation = clamp(
- (timeMs - activeSample.timeMs) / (nextSample.timeMs - activeSample.timeMs),
- 0,
- 1,
- );
-
- return {
- asset,
- sample: {
- ...activeSample,
- cx: activeSample.cx + (nextSample.cx - activeSample.cx) * interpolation,
- cy: activeSample.cy + (nextSample.cy - activeSample.cy) * interpolation,
- },
- };
-}
-
-export function projectNativeCursorToLocal({
- cropRegion,
- maskRect,
- sample,
-}: ProjectNativeCursorOptions) {
- const maskPoint = getNativeCursorMaskPoint(sample, cropRegion);
- if (!maskPoint) {
- return null;
- }
-
- return new Point(
- maskRect.x + maskPoint.x * maskRect.width,
- maskRect.y + maskPoint.y * maskRect.height,
- );
-}
-
-export function projectNativeCursorToStage({
- cameraContainer,
- videoContainerPosition,
- ...options
-}: ProjectNativeCursorToStageOptions) {
- const localPoint = projectNativeCursorToLocal(options);
- if (!localPoint) {
- return null;
- }
-
- return cameraContainer.toGlobal(
- new Point(localPoint.x + videoContainerPosition.x, localPoint.y + videoContainerPosition.y),
- );
-}
-
-export function getNativeCursorDisplayMetrics(asset: NativeCursorAsset, deviceScaleFactor: number) {
- const scaleFactor = asset.scaleFactor ?? deviceScaleFactor ?? 1;
- return {
- width: asset.width / scaleFactor,
- height: asset.height / scaleFactor,
- hotspotX: asset.hotspotX / scaleFactor,
- hotspotY: asset.hotspotY / scaleFactor,
- };
-}
-
-export function resolvePrettyNativeCursorAsset(
- asset: NativeCursorAsset,
- sample?: CursorRecordingSample,
-) {
- const cursorType = sample?.cursorType ?? asset.cursorType ?? null;
- return cursorType
- ? (PRETTY_NATIVE_CURSOR_ASSETS[cursorType] ?? null)
- : resolveUntypedPrettyNativeCursorAsset(asset);
-}
-
-/**
- * Infers "arrow" vs "pointer" from a captured bitmap's hotspot, for platforms (macOS)
- * that don't tag samples with a `cursorType`. Arrow's hotspot is in the top-left tip;
- * the pointing hand's fingertip is in the upper-center band. Anything else stays
- * unclassified so it keeps its real captured cursor instead of a themed arrow/pointer.
- */
-function classifyCapturedCursorType(asset: NativeCursorAsset): NativeCursorType | null {
- if (asset.width <= 0 || asset.height <= 0) {
- return null;
- }
- const hotspotXNorm = asset.hotspotX / asset.width;
- const hotspotYNorm = asset.hotspotY / asset.height;
- if (hotspotXNorm < 0.33 && hotspotYNorm < 0.33) {
- return "arrow";
- }
- if (hotspotYNorm < 0.4 && hotspotXNorm >= 0.33 && hotspotXNorm <= 0.6) {
- return "pointer";
- }
- return null;
-}
-
-/**
- * Resolves the theme override for a cursor type, or null when the default theme is active
- * or has no art for that type. The asset URL resolves lazily (only when a theme is active)
- * so this is safe from tests and non-renderer contexts; a failure degrades to default art.
- */
-function resolveThemedCursorAsset(
- themeId: string | null | undefined,
- cursorType: NativeCursorType,
-): PrettyNativeCursorAsset | null {
- if (!themeId || themeId === DEFAULT_CURSOR_THEME_ID) {
- return null;
- }
- const themeAsset = getCursorTheme(themeId)?.assets[cursorType];
- if (!themeAsset) {
- return null;
- }
- try {
- return {
- imageDataUrl: getAssetPath(themeAsset.assetPath),
- width: themeAsset.width,
- height: themeAsset.height,
- hotspotX: themeAsset.hotspotX,
- hotspotY: themeAsset.hotspotY,
- };
- } catch {
- return null;
- }
-}
-
-export function resolveNativeCursorRenderAsset(
- asset: NativeCursorAsset,
- deviceScaleFactor: number,
- sample?: CursorRecordingSample,
- themeId?: string | null,
-) {
- const cursorType = sample?.cursorType ?? asset.cursorType ?? null;
- if (themeId && themeId !== DEFAULT_CURSOR_THEME_ID) {
- // A known type uses its override when the theme provides one. Untyped samples
- // (common on macOS, where the type isn't tagged) are classified from the captured
- // bitmap's hotspot so arrow becomes themed-arrow and hand becomes themed-pointer.
- const themedType = cursorType ?? classifyCapturedCursorType(asset);
- const themedAsset = themedType ? resolveThemedCursorAsset(themeId, themedType) : null;
- if (themedAsset && themedType) {
- return {
- id: `theme:${themeId}:${themedType}`,
- imageDataUrl: themedAsset.imageDataUrl,
- width: themedAsset.width,
- height: themedAsset.height,
- hotspotX: themedAsset.hotspotX,
- hotspotY: themedAsset.hotspotY,
- };
- }
- }
-
- const prettyAsset = resolvePrettyNativeCursorAsset(asset, sample);
- if (prettyAsset) {
- return {
- id: `pretty:${sample?.cursorType ?? asset.cursorType}`,
- imageDataUrl: prettyAsset.imageDataUrl,
- width: prettyAsset.width,
- height: prettyAsset.height,
- hotspotX: prettyAsset.hotspotX,
- hotspotY: prettyAsset.hotspotY,
- };
- }
-
- const metrics = getNativeCursorDisplayMetrics(asset, deviceScaleFactor);
- return {
- id: asset.id,
- imageDataUrl: asset.imageDataUrl,
- width: metrics.width,
- height: metrics.height,
- hotspotX: metrics.hotspotX,
- hotspotY: metrics.hotspotY,
- };
-}
diff --git a/src/lib/cursor/pixiCursorRenderer.ts b/src/lib/cursor/pixiCursorRenderer.ts
deleted file mode 100644
index 25bd8ddc3..000000000
--- a/src/lib/cursor/pixiCursorRenderer.ts
+++ /dev/null
@@ -1,762 +0,0 @@
-import { Assets, BlurFilter, Container, Graphics, Sprite, Texture } from "pixi.js";
-import { MotionBlurFilter } from "pixi-filters/motion-blur";
-import type { CursorTelemetryPoint } from "@/components/video-editor/types";
-import {
- createSpringState,
- getCursorSpringConfig,
- resetSpringState,
- stepSpringValue,
-} from "@/lib/zoomMath/motionSmoothing";
-import { clamp } from "@/utils/math";
-import { UPLOADED_CURSOR_SAMPLE_SIZE, uploadedCursorAssets } from "./uploadedCursorAssets";
-
-type CursorAssetKey = NonNullable<CursorTelemetryPoint["cursorType"]>;
-
-/** System cursor asset from native helper (macOS only). */
-type SystemCursorAsset = {
- dataUrl: string;
- width: number;
- height: number;
- hotspotX: number;
- hotspotY: number;
-};
-
-type LoadedCursorAsset = {
- texture: Texture;
- image: HTMLImageElement;
- aspectRatio: number;
- anchorX: number;
- anchorY: number;
-};
-
-export interface CursorViewportRect {
- x: number;
- y: number;
- width: number;
- height: number;
-}
-
-/**
- * Configuration for cursor rendering.
- */
-export interface CursorRenderConfig {
- /** Base cursor height in pixels (at reference width of 1920px) */
- dotRadius: number;
- /** Cursor fill color (hex number for PixiJS) */
- dotColor: number;
- /** Cursor opacity (0-1) */
- dotAlpha: number;
- /** Unused, kept for interface compatibility */
- trailLength: number;
- /** Smoothing factor for cursor interpolation (0-1, lower = smoother/slower) */
- smoothingFactor: number;
- /** Directional cursor motion blur amount. */
- motionBlur: number;
- /** Click bounce multiplier. */
- clickBounce: number;
-}
-
-export const DEFAULT_CURSOR_CONFIG: CursorRenderConfig = {
- dotRadius: 28,
- dotColor: 0xffffff,
- dotAlpha: 0.95,
- trailLength: 0,
- smoothingFactor: 0.18,
- motionBlur: 0,
- clickBounce: 1,
-};
-
-const REFERENCE_WIDTH = 1920;
-const MIN_CURSOR_VIEWPORT_SCALE = 0.55;
-const CLICK_ANIMATION_MS = 140;
-const CLICK_RING_FADE_MS = 240;
-const CURSOR_MOTION_BLUR_BASE_MULTIPLIER = 0.08;
-const CURSOR_TIME_DISCONTINUITY_MS = 100;
-const CURSOR_SVG_DROP_SHADOW_FILTER = "drop-shadow(0px 2px 3px rgba(0, 0, 0, 0.35))";
-const CURSOR_SHADOW_COLOR = 0x000000;
-const CURSOR_SHADOW_ALPHA = 0.35;
-const CURSOR_SHADOW_OFFSET_X = 0;
-const CURSOR_SHADOW_OFFSET_Y = 2;
-const CURSOR_SHADOW_BLUR = 3;
-const CURSOR_SHADOW_PADDING = 12;
-
-let cursorAssetsPromise: Promise<void> | null = null;
-let loadedCursorAssets: Partial<Record<CursorAssetKey, LoadedCursorAsset>> = {};
-const SUPPORTED_CURSOR_KEYS: CursorAssetKey[] = [
- "arrow",
- "text",
- "pointer",
- "crosshair",
- "open-hand",
- "closed-hand",
- "resize-ew",
- "resize-ns",
- "not-allowed",
-];
-
-function loadImage(dataUrl: string) {
- return new Promise<HTMLImageElement>((resolve, reject) => {
- const image = new Image();
- image.onload = () => resolve(image);
- image.onerror = () =>
- reject(new Error(`Failed to load cursor image: ${dataUrl.slice(0, 128)}`));
- image.src = dataUrl;
- });
-}
-
-function getNormalizedAnchor(
- systemAsset: SystemCursorAsset | undefined,
- fallbackAnchor: { x: number; y: number },
-) {
- if (!systemAsset || systemAsset.width <= 0 || systemAsset.height <= 0) {
- return fallbackAnchor;
- }
-
- return {
- x: clamp(systemAsset.hotspotX / systemAsset.width, 0, 1),
- y: clamp(systemAsset.hotspotY / systemAsset.height, 0, 1),
- };
-}
-
-/**
- * Loads an SVG at `sampleSize × sampleSize`, crops the trim region, and returns
- * a PNG data-URL. Needed because an SVG's natural size (e.g. 32×32) doesn't match
- * the 1024-sample coordinate space the trim measurements use.
- */
-async function rasterizeAndCropSvg(
- url: string,
- sampleSize: number,
- trimX: number,
- trimY: number,
- trimWidth: number,
- trimHeight: number,
-): Promise<{ dataUrl: string; width: number; height: number }> {
- const img = await loadImage(url);
-
- const srcCanvas = document.createElement("canvas");
- srcCanvas.width = sampleSize;
- srcCanvas.height = sampleSize;
- const srcCtx = srcCanvas.getContext("2d")!;
- srcCtx.drawImage(img, 0, 0, sampleSize, sampleSize);
-
- const dstCanvas = document.createElement("canvas");
- dstCanvas.width = trimWidth;
- dstCanvas.height = trimHeight;
- const dstCtx = dstCanvas.getContext("2d")!;
- dstCtx.drawImage(srcCanvas, trimX, trimY, trimWidth, trimHeight, 0, 0, trimWidth, trimHeight);
-
- return {
- dataUrl: dstCanvas.toDataURL("image/png"),
- width: dstCanvas.width,
- height: dstCanvas.height,
- };
-}
-
-function getCursorAsset(key: CursorAssetKey): LoadedCursorAsset {
- const asset = loadedCursorAssets[key];
- if (!asset) {
- throw new Error(`Missing cursor asset for ${key}`);
- }
-
- return asset;
-}
-
-function getAvailableCursorKeys(): CursorAssetKey[] {
- const loadedKeys = Object.keys(loadedCursorAssets) as CursorAssetKey[];
- return loadedKeys.length > 0 ? loadedKeys : ["arrow"];
-}
-
-export async function preloadCursorAssets() {
- if (!cursorAssetsPromise) {
- cursorAssetsPromise = (async () => {
- let systemCursors: Record<string, SystemCursorAsset> = {};
-
- try {
- const api = window.electronAPI as Record<string, unknown>;
- if (typeof api.getSystemCursorAssets === "function") {
- const result = await (
- api.getSystemCursorAssets as () => Promise<{
- success: boolean;
- cursors?: Record<string, SystemCursorAsset>;
- }>
- )();
- if (result.success && result.cursors) {
- systemCursors = result.cursors;
- }
- }
- } catch (error) {
- console.warn("[CursorRenderer] Failed to fetch system cursor assets:", error);
- }
-
- const entries = await Promise.all(
- SUPPORTED_CURSOR_KEYS.map(async (key) => {
- const systemAsset = systemCursors[key];
- const uploadedAsset = uploadedCursorAssets[key];
- const assetUrl = uploadedAsset?.url ?? systemAsset?.dataUrl;
-
- if (!assetUrl) {
- console.warn(`[CursorRenderer] No cursor image for: ${key}`);
- return null;
- }
-
- try {
- let finalUrl: string;
- let width: number;
- let height: number;
- let normalizedAnchor: { x: number; y: number };
-
- if (uploadedAsset) {
- const { trim, fallbackAnchor } = uploadedAsset;
- const rasterized = await rasterizeAndCropSvg(
- assetUrl,
- UPLOADED_CURSOR_SAMPLE_SIZE,
- trim.x,
- trim.y,
- trim.width,
- trim.height,
- );
- finalUrl = rasterized.dataUrl;
- width = rasterized.width;
- height = rasterized.height;
- normalizedAnchor = {
- x: clamp((fallbackAnchor.x * trim.width) / width, 0, 1),
- y: clamp((fallbackAnchor.y * trim.height) / height, 0, 1),
- };
- } else {
- finalUrl = assetUrl;
- const img = await loadImage(finalUrl);
- width = img.naturalWidth;
- height = img.naturalHeight;
- normalizedAnchor = getNormalizedAnchor(systemAsset, { x: 0, y: 0 });
- }
-
- await Assets.load(finalUrl);
- const image = await loadImage(finalUrl);
- const texture = Texture.from(finalUrl);
-
- return [
- key,
- {
- texture,
- image,
- aspectRatio: height > 0 ? width / height : 1,
- anchorX: normalizedAnchor.x,
- anchorY: normalizedAnchor.y,
- } satisfies LoadedCursorAsset,
- ] as const;
- } catch (error) {
- console.warn(`[CursorRenderer] Failed to load cursor image for: ${key}`, error);
- return null;
- }
- }),
- );
-
- loadedCursorAssets = Object.fromEntries(
- entries.filter(Boolean).map((entry) => entry!),
- ) as Partial<Record<CursorAssetKey, LoadedCursorAsset>>;
-
- if (!loadedCursorAssets.arrow) {
- throw new Error("Failed to initialize the fallback arrow cursor asset");
- }
- })();
- }
-
- return cursorAssetsPromise;
-}
-
-/**
- * Interpolates cursor position from telemetry samples at a given time.
- * Uses linear interpolation between the two nearest samples.
- */
-export function interpolateCursorPosition(
- samples: CursorTelemetryPoint[],
- timeMs: number,
-): { cx: number; cy: number } | null {
- if (!samples || samples.length === 0) return null;
-
- if (timeMs <= samples[0].timeMs) {
- return { cx: samples[0].cx, cy: samples[0].cy };
- }
-
- if (timeMs >= samples[samples.length - 1].timeMs) {
- return { cx: samples[samples.length - 1].cx, cy: samples[samples.length - 1].cy };
- }
-
- let lo = 0;
- let hi = samples.length - 1;
- while (lo < hi - 1) {
- const mid = (lo + hi) >> 1;
- if (samples[mid].timeMs <= timeMs) {
- lo = mid;
- } else {
- hi = mid;
- }
- }
-
- const a = samples[lo];
- const b = samples[hi];
- const span = b.timeMs - a.timeMs;
- if (span <= 0) return { cx: a.cx, cy: a.cy };
-
- const t = (timeMs - a.timeMs) / span;
- return {
- cx: a.cx + (b.cx - a.cx) * t,
- cy: a.cy + (b.cy - a.cy) * t,
- };
-}
-
-function findLatestSample(samples: CursorTelemetryPoint[], timeMs: number) {
- if (samples.length === 0) return null;
-
- let lo = 0;
- let hi = samples.length - 1;
- while (lo < hi) {
- const mid = Math.ceil((lo + hi) / 2);
- if (samples[mid].timeMs <= timeMs) {
- lo = mid;
- } else {
- hi = mid - 1;
- }
- }
-
- return samples[lo]?.timeMs <= timeMs ? samples[lo] : null;
-}
-
-function findLatestInteractionSample(samples: CursorTelemetryPoint[], timeMs: number) {
- for (let index = samples.length - 1; index >= 0; index -= 1) {
- const sample = samples[index];
- if (sample.timeMs > timeMs) {
- continue;
- }
-
- if (
- sample.interactionType === "click" ||
- sample.interactionType === "double-click" ||
- sample.interactionType === "right-click" ||
- sample.interactionType === "middle-click"
- ) {
- return sample;
- }
- }
-
- return null;
-}
-
-function findLatestStableCursorType(samples: CursorTelemetryPoint[], timeMs: number) {
- // Binary search to position at timeMs, then scan backwards
- let lo = 0;
- let hi = samples.length - 1;
- while (lo < hi) {
- const mid = Math.ceil((lo + hi) / 2);
- if (samples[mid].timeMs <= timeMs) {
- lo = mid;
- } else {
- hi = mid - 1;
- }
- }
-
- // Scan back for a sample with cursorType. Skip click events (not mouseup) to
- // avoid a transient re-type during clicks.
- for (let index = lo; index >= 0; index -= 1) {
- const sample = samples[index];
- if (sample.timeMs > timeMs) {
- continue;
- }
-
- if (!sample.cursorType) {
- continue;
- }
-
- if (
- sample.interactionType === "click" ||
- sample.interactionType === "double-click" ||
- sample.interactionType === "right-click" ||
- sample.interactionType === "middle-click"
- ) {
- continue;
- }
-
- return sample.cursorType;
- }
-
- return findLatestSample(samples, timeMs)?.cursorType ?? "arrow";
-}
-
-function getCursorViewportScale(viewport: CursorViewportRect) {
- return Math.max(MIN_CURSOR_VIEWPORT_SCALE, viewport.width / REFERENCE_WIDTH);
-}
-
-function getCursorVisualState(samples: CursorTelemetryPoint[], timeMs: number) {
- const latestClick = findLatestInteractionSample(samples, timeMs);
- const interactionType = latestClick?.interactionType;
- const ageMs = latestClick ? Math.max(0, timeMs - latestClick.timeMs) : Number.POSITIVE_INFINITY;
- const isClickEvent =
- interactionType === "click" ||
- interactionType === "double-click" ||
- interactionType === "right-click" ||
- interactionType === "middle-click";
- const clickBounceProgress =
- latestClick && isClickEvent && ageMs <= CLICK_ANIMATION_MS ? 1 - ageMs / CLICK_ANIMATION_MS : 0;
-
- return {
- cursorType: findLatestStableCursorType(samples, timeMs),
- clickBounceProgress,
- clickProgress:
- latestClick && isClickEvent && ageMs <= CLICK_RING_FADE_MS
- ? 1 - ageMs / CLICK_RING_FADE_MS
- : 0,
- };
-}
-
-/**
- * Manages a smoothed cursor state that chases the interpolated target.
- */
-export class SmoothedCursorState {
- public x = 0.5;
- public y = 0.5;
- public trail: Array<{ x: number; y: number }> = [];
- private smoothingFactor: number;
- private trailLength: number;
- private initialized = false;
- private lastTimeMs: number | null = null;
- private xSpring = createSpringState(0.5);
- private ySpring = createSpringState(0.5);
-
- constructor(config: Pick<CursorRenderConfig, "smoothingFactor" | "trailLength">) {
- this.smoothingFactor = config.smoothingFactor;
- this.trailLength = config.trailLength;
- }
-
- update(targetX: number, targetY: number, timeMs: number): void {
- if (!this.initialized) {
- this.x = targetX;
- this.y = targetY;
- this.initialized = true;
- this.lastTimeMs = timeMs;
- this.xSpring.value = targetX;
- this.ySpring.value = targetY;
- this.xSpring.velocity = 0;
- this.ySpring.velocity = 0;
- this.xSpring.initialized = true;
- this.ySpring.initialized = true;
- this.trail = [];
- return;
- }
-
- if (this.smoothingFactor <= 0 || (this.lastTimeMs !== null && timeMs < this.lastTimeMs)) {
- this.snapTo(targetX, targetY, timeMs);
- return;
- }
-
- this.trail.unshift({ x: this.x, y: this.y });
- if (this.trail.length > this.trailLength) {
- this.trail.length = this.trailLength;
- }
-
- const deltaMs = this.lastTimeMs === null ? 1000 / 60 : Math.max(1, timeMs - this.lastTimeMs);
- this.lastTimeMs = timeMs;
-
- const springConfig = getCursorSpringConfig(this.smoothingFactor);
- this.x = stepSpringValue(this.xSpring, targetX, deltaMs, springConfig);
- this.y = stepSpringValue(this.ySpring, targetY, deltaMs, springConfig);
- }
-
- setSmoothingFactor(smoothingFactor: number): void {
- this.smoothingFactor = smoothingFactor;
- }
-
- snapTo(targetX: number, targetY: number, timeMs: number): void {
- this.x = targetX;
- this.y = targetY;
- this.initialized = true;
- this.lastTimeMs = timeMs;
- this.xSpring.value = targetX;
- this.ySpring.value = targetY;
- this.xSpring.velocity = 0;
- this.ySpring.velocity = 0;
- this.xSpring.initialized = true;
- this.ySpring.initialized = true;
- this.trail = [];
- }
-
- reset(): void {
- this.initialized = false;
- this.lastTimeMs = null;
- this.trail = [];
- resetSpringState(this.xSpring, this.x);
- resetSpringState(this.ySpring, this.y);
- }
-}
-
-function drawClickRing(graphics: Graphics, px: number, py: number, h: number, progress: number) {
- void graphics;
- void px;
- void py;
- void h;
- void progress;
-}
-
-export class PixiCursorOverlay {
- public readonly container: Container;
- private clickRingGraphics: Graphics;
- private cursorShadowSprites: Partial<Record<CursorAssetKey, Sprite>>;
- private cursorShadowFilters: Partial<Record<CursorAssetKey, BlurFilter>>;
- private cursorSprites: Partial<Record<CursorAssetKey, Sprite>>;
- private cursorMotionBlurFilter: MotionBlurFilter;
- private state: SmoothedCursorState;
- private config: CursorRenderConfig;
- private lastRenderedPoint: { px: number; py: number } | null = null;
- private lastRenderedTimeMs: number | null = null;
-
- constructor(config: Partial<CursorRenderConfig> = {}) {
- this.config = { ...DEFAULT_CURSOR_CONFIG, ...config };
- this.state = new SmoothedCursorState(this.config);
-
- this.container = new Container();
- this.container.label = "cursor-overlay";
-
- this.clickRingGraphics = new Graphics();
- this.cursorShadowSprites = {};
- this.cursorShadowFilters = {};
- this.cursorSprites = {};
- for (const key of getAvailableCursorKeys()) {
- const asset = getCursorAsset(key);
- const shadowSprite = new Sprite(asset.texture);
- shadowSprite.anchor.set(asset.anchorX, asset.anchorY);
- shadowSprite.visible = false;
- shadowSprite.tint = CURSOR_SHADOW_COLOR;
- shadowSprite.alpha = CURSOR_SHADOW_ALPHA;
- const shadowFilter = new BlurFilter();
- shadowFilter.blur = CURSOR_SHADOW_BLUR;
- shadowFilter.quality = 4;
- shadowFilter.padding = CURSOR_SHADOW_PADDING;
- shadowSprite.filters = [shadowFilter];
- this.cursorShadowSprites[key] = shadowSprite;
- this.cursorShadowFilters[key] = shadowFilter;
-
- const sprite = new Sprite(asset.texture);
- sprite.anchor.set(asset.anchorX, asset.anchorY);
- sprite.visible = false;
- this.cursorSprites[key] = sprite;
- }
-
- this.cursorMotionBlurFilter = new MotionBlurFilter([0, 0], 5, 0);
- this.container.filters = null;
-
- this.container.addChild(
- this.clickRingGraphics,
- ...Object.values(this.cursorShadowSprites),
- ...Object.values(this.cursorSprites),
- );
- this.setMotionBlur(this.config.motionBlur);
- }
-
- setDotRadius(dotRadius: number) {
- this.config.dotRadius = dotRadius;
- }
-
- setSmoothingFactor(smoothingFactor: number) {
- this.config.smoothingFactor = smoothingFactor;
- this.state.setSmoothingFactor(smoothingFactor);
- }
-
- setMotionBlur(motionBlur: number) {
- this.config.motionBlur = Math.max(0, motionBlur);
- this.container.filters = this.config.motionBlur > 0 ? [this.cursorMotionBlurFilter] : null;
- if (this.config.motionBlur <= 0) {
- this.cursorMotionBlurFilter.velocity = { x: 0, y: 0 };
- this.cursorMotionBlurFilter.kernelSize = 5;
- this.cursorMotionBlurFilter.offset = 0;
- }
- }
-
- setClickBounce(clickBounce: number) {
- this.config.clickBounce = Math.max(0, clickBounce);
- }
-
- update(
- samples: CursorTelemetryPoint[],
- timeMs: number,
- viewport: CursorViewportRect,
- visible: boolean,
- freeze = false,
- ): void {
- if (!visible || samples.length === 0 || viewport.width <= 0 || viewport.height <= 0) {
- this.container.visible = false;
- this.lastRenderedPoint = null;
- this.lastRenderedTimeMs = null;
- this.cursorMotionBlurFilter.velocity = { x: 0, y: 0 };
- return;
- }
-
- const target = interpolateCursorPosition(samples, timeMs);
- if (!target) {
- this.container.visible = false;
- return;
- }
-
- const sameFrameTime =
- this.lastRenderedTimeMs !== null && Math.abs(this.lastRenderedTimeMs - timeMs) < 0.0001;
- const hasTimeDiscontinuity =
- this.lastRenderedTimeMs !== null &&
- Math.abs(timeMs - this.lastRenderedTimeMs) > CURSOR_TIME_DISCONTINUITY_MS;
-
- if (freeze || hasTimeDiscontinuity) {
- if (!sameFrameTime || !this.lastRenderedPoint) {
- this.state.snapTo(target.cx, target.cy, timeMs);
- }
- } else {
- this.state.update(target.cx, target.cy, timeMs);
- }
- this.container.visible = true;
-
- const px = viewport.x + this.state.x * viewport.width;
- const py = viewport.y + this.state.y * viewport.height;
- const h = this.config.dotRadius * getCursorViewportScale(viewport);
- const { cursorType, clickBounceProgress, clickProgress } = getCursorVisualState(
- samples,
- timeMs,
- );
- const spriteKey = (cursorType in this.cursorSprites ? cursorType : "arrow") as CursorAssetKey;
- const asset = getCursorAsset(spriteKey);
- const shadowSprite = this.cursorShadowSprites[spriteKey] ?? this.cursorShadowSprites.arrow!;
- const sprite = this.cursorSprites[spriteKey] ?? this.cursorSprites.arrow!;
- const bounceScale = Math.max(
- 0.72,
- 1 - Math.sin(clickBounceProgress * Math.PI) * (0.08 * this.config.clickBounce),
- );
- const scaledH = h;
-
- this.clickRingGraphics.clear();
- drawClickRing(this.clickRingGraphics, px, py, h, clickProgress);
-
- for (const [key, currentShadowSprite] of Object.entries(this.cursorShadowSprites) as Array<
- [CursorAssetKey, Sprite]
- >) {
- currentShadowSprite.visible = key === spriteKey;
- }
-
- for (const [key, currentSprite] of Object.entries(this.cursorSprites) as Array<
- [CursorAssetKey, Sprite]
- >) {
- currentSprite.visible = key === spriteKey;
- }
-
- if (shadowSprite) {
- shadowSprite.height = scaledH * bounceScale;
- shadowSprite.width = scaledH * bounceScale * asset.aspectRatio;
- shadowSprite.position.set(px + CURSOR_SHADOW_OFFSET_X, py + CURSOR_SHADOW_OFFSET_Y);
- }
-
- if (sprite) {
- sprite.alpha = this.config.dotAlpha;
- sprite.height = scaledH * bounceScale;
- sprite.width = scaledH * bounceScale * asset.aspectRatio;
- sprite.position.set(px, py);
- }
-
- this.applyCursorMotionBlur(px, py, timeMs, freeze);
- this.lastRenderedPoint = { px, py };
- this.lastRenderedTimeMs = timeMs;
- }
-
- private applyCursorMotionBlur(px: number, py: number, timeMs: number, freeze: boolean) {
- if (
- freeze ||
- this.config.motionBlur <= 0 ||
- !this.lastRenderedPoint ||
- this.lastRenderedTimeMs === null
- ) {
- this.cursorMotionBlurFilter.velocity = { x: 0, y: 0 };
- this.cursorMotionBlurFilter.kernelSize = 5;
- this.cursorMotionBlurFilter.offset = 0;
- return;
- }
-
- const deltaMs = Math.max(1, timeMs - this.lastRenderedTimeMs);
- const dx = px - this.lastRenderedPoint.px;
- const dy = py - this.lastRenderedPoint.py;
- const velocityScale =
- (1000 / deltaMs) * this.config.motionBlur * CURSOR_MOTION_BLUR_BASE_MULTIPLIER;
- const velocity = {
- x: dx * velocityScale,
- y: dy * velocityScale,
- };
- const magnitude = Math.hypot(velocity.x, velocity.y);
-
- this.cursorMotionBlurFilter.velocity = magnitude > 0.05 ? velocity : { x: 0, y: 0 };
- this.cursorMotionBlurFilter.kernelSize = magnitude > 3 ? 9 : magnitude > 1 ? 7 : 5;
- this.cursorMotionBlurFilter.offset = magnitude > 0.5 ? -0.25 : 0;
- }
-
- reset(): void {
- this.state.reset();
- this.clickRingGraphics.clear();
- for (const shadowSprite of Object.values(this.cursorShadowSprites)) {
- shadowSprite.visible = false;
- shadowSprite.scale.set(1);
- }
- for (const sprite of Object.values(this.cursorSprites)) {
- sprite.visible = false;
- sprite.scale.set(1);
- }
- this.container.visible = false;
- this.lastRenderedPoint = null;
- this.lastRenderedTimeMs = null;
- this.cursorMotionBlurFilter.velocity = { x: 0, y: 0 };
- this.cursorMotionBlurFilter.kernelSize = 5;
- this.cursorMotionBlurFilter.offset = 0;
- }
-
- destroy(): void {
- this.clickRingGraphics.destroy();
- for (const shadowFilter of Object.values(this.cursorShadowFilters)) {
- shadowFilter.destroy();
- }
- this.cursorMotionBlurFilter.destroy();
- this.container.destroy({ children: true });
- cursorAssetsPromise = null;
- loadedCursorAssets = {};
- }
-}
-
-export function drawCursorOnCanvas(
- ctx: CanvasRenderingContext2D,
- samples: CursorTelemetryPoint[],
- timeMs: number,
- viewport: CursorViewportRect,
- smoothedState: SmoothedCursorState,
- config: CursorRenderConfig = DEFAULT_CURSOR_CONFIG,
-): void {
- if (samples.length === 0 || viewport.width <= 0 || viewport.height <= 0) return;
-
- const target = interpolateCursorPosition(samples, timeMs);
- if (!target) return;
-
- smoothedState.update(target.cx, target.cy, timeMs);
-
- const px = viewport.x + smoothedState.x * viewport.width;
- const py = viewport.y + smoothedState.y * viewport.height;
- const h = config.dotRadius * getCursorViewportScale(viewport);
- const { cursorType, clickBounceProgress } = getCursorVisualState(samples, timeMs);
- const spriteKey = (
- cursorType && loadedCursorAssets[cursorType] ? cursorType : "arrow"
- ) as CursorAssetKey;
- const asset = getCursorAsset(spriteKey);
- const bounceScale = Math.max(
- 0.72,
- 1 - Math.sin(clickBounceProgress * Math.PI) * (0.08 * config.clickBounce),
- );
-
- ctx.save();
- ctx.filter = CURSOR_SVG_DROP_SHADOW_FILTER;
-
- const drawHeight = h * bounceScale;
- const drawWidth = drawHeight * asset.aspectRatio;
- const hotspotX = asset.anchorX * drawWidth;
- const hotspotY = asset.anchorY * drawHeight;
- ctx.globalAlpha = config.dotAlpha;
- ctx.drawImage(asset.image, px - hotspotX, py - hotspotY, drawWidth, drawHeight);
-
- ctx.restore();
-}
diff --git a/src/lib/zoomMath/zoomTransform.ts b/src/lib/zoomMath/zoomTransform.ts
index ea96077e2..9bb29480e 100644
--- a/src/lib/zoomMath/zoomTransform.ts
+++ b/src/lib/zoomMath/zoomTransform.ts
@@ -1,53 +1,8 @@
-import { BlurFilter, Container } from "pixi.js";
-import { MotionBlurFilter } from "pixi-filters/motion-blur";
-
-const PEAK_VELOCITY_PPS = 1400;
-const MAX_BLUR_PX = 14;
-const VELOCITY_THRESHOLD_PPS = 12;
-const MAX_AMOUNT_BOOST = 2.2;
-
-function getMotionBlurAmountResponse(motionBlurAmount: number) {
- const clampedAmount = Math.min(1, Math.max(0, motionBlurAmount));
- // Keep the low end usable while giving the top of the slider more headroom.
- return clampedAmount * (1 + (MAX_AMOUNT_BOOST - 1) * clampedAmount);
-}
-
-export interface MotionBlurState {
- lastFrameTimeMs: number;
- prevCamX: number;
- prevCamY: number;
- prevCamScale: number;
- initialized: boolean;
-}
-
-export function createMotionBlurState(): MotionBlurState {
- return {
- lastFrameTimeMs: 0,
- prevCamX: 0,
- prevCamY: 0,
- prevCamScale: 1,
- initialized: false,
- };
-}
-
-interface TransformParams {
- cameraContainer: Container;
- blurFilter: BlurFilter | null;
- motionBlurFilter?: MotionBlurFilter | null;
- stageSize: { width: number; height: number };
- baseMask: { x: number; y: number; width: number; height: number };
- zoomScale: number;
- zoomProgress?: number;
- focusX: number;
- focusY: number;
- motionIntensity: number;
- motionVector?: { x: number; y: number };
- isPlaying: boolean;
- motionBlurAmount?: number;
- transformOverride?: AppliedTransform;
- motionBlurState?: MotionBlurState;
- frameTimeMs?: number;
-}
+// Pure zoom geometry for the preview overlay. This module used to also own the
+// Pixi camera application (applyZoomTransform + motion-blur filter state); the
+// native D3D compositor renders zoom and motion blur now, so those exports had
+// no callers and went with the Pixi export path. What is left is the geometry
+// the overlay still needs, and it depends on nothing but arithmetic.
interface AppliedTransform {
scale: number;
@@ -55,14 +10,6 @@ interface AppliedTransform {
y: number;
}
-interface FocusFromTransformGeometry {
- stageSize: { width: number; height: number };
- baseMask: { x: number; y: number; width: number; height: number };
- zoomScale: number;
- x: number;
- y: number;
-}
-
interface ZoomTransformGeometry {
stageSize: { width: number; height: number };
baseMask: { x: number; y: number; width: number; height: number };
@@ -105,145 +52,3 @@ export function computeZoomTransform({
y: finalY * progress,
};
}
-
-export function computeFocusFromTransform({
- stageSize,
- baseMask,
- zoomScale,
- x,
- y,
-}: FocusFromTransformGeometry) {
- if (
- stageSize.width <= 0 ||
- stageSize.height <= 0 ||
- baseMask.width <= 0 ||
- baseMask.height <= 0 ||
- zoomScale <= 0
- ) {
- return { cx: 0.5, cy: 0.5 };
- }
-
- const stageCenterX = stageSize.width / 2;
- const stageCenterY = stageSize.height / 2;
- const focusStagePxX = (stageCenterX - x) / zoomScale;
- const focusStagePxY = (stageCenterY - y) / zoomScale;
-
- return {
- cx: focusStagePxX / stageSize.width,
- cy: focusStagePxY / stageSize.height,
- };
-}
-
-export function applyZoomTransform({
- cameraContainer,
- blurFilter,
- motionBlurFilter,
- stageSize,
- baseMask,
- zoomScale,
- zoomProgress = 1,
- focusX,
- focusY,
- motionIntensity: _motionIntensity,
- motionVector: _motionVector,
- isPlaying,
- motionBlurAmount = 0,
- transformOverride,
- motionBlurState,
- frameTimeMs,
-}: TransformParams): AppliedTransform {
- if (
- stageSize.width <= 0 ||
- stageSize.height <= 0 ||
- baseMask.width <= 0 ||
- baseMask.height <= 0
- ) {
- return { scale: 1, x: 0, y: 0 };
- }
-
- const transform =
- transformOverride ??
- computeZoomTransform({
- stageSize,
- baseMask,
- zoomScale,
- zoomProgress,
- focusX,
- focusY,
- });
-
- cameraContainer.scale.set(transform.scale);
- cameraContainer.position.set(transform.x, transform.y);
-
- if (motionBlurState && motionBlurFilter && motionBlurAmount > 0 && isPlaying) {
- const now = frameTimeMs ?? performance.now();
-
- if (!motionBlurState.initialized) {
- motionBlurState.prevCamX = transform.x;
- motionBlurState.prevCamY = transform.y;
- motionBlurState.prevCamScale = transform.scale;
- motionBlurState.lastFrameTimeMs = now;
- motionBlurState.initialized = true;
- motionBlurFilter.velocity = { x: 0, y: 0 };
- motionBlurFilter.kernelSize = 5;
- motionBlurFilter.offset = 0;
- if (blurFilter) blurFilter.blur = 0;
- } else {
- const dtMs = Math.min(80, Math.max(1, now - motionBlurState.lastFrameTimeMs));
- const dtSeconds = dtMs / 1000;
- motionBlurState.lastFrameTimeMs = now;
- const amountResponse = getMotionBlurAmountResponse(motionBlurAmount);
-
- // Camera displacement this frame (stage-px)
- const dx = transform.x - motionBlurState.prevCamX;
- const dy = transform.y - motionBlurState.prevCamY;
- const dScale = transform.scale - motionBlurState.prevCamScale;
-
- motionBlurState.prevCamX = transform.x;
- motionBlurState.prevCamY = transform.y;
- motionBlurState.prevCamScale = transform.scale;
-
- // Velocity in px/s (translation + scale-change contribution)
- const velocityX = dx / dtSeconds;
- const velocityY = dy / dtSeconds;
- const scaleVelocity =
- Math.abs(dScale / dtSeconds) * Math.max(stageSize.width, stageSize.height) * 0.5;
- const speed = Math.sqrt(velocityX * velocityX + velocityY * velocityY) + scaleVelocity;
-
- const normalised = Math.min(1, speed / PEAK_VELOCITY_PPS);
- const targetBlur =
- speed < VELOCITY_THRESHOLD_PPS ? 0 : normalised * normalised * MAX_BLUR_PX * amountResponse;
-
- const dirMag = Math.sqrt(velocityX * velocityX + velocityY * velocityY) || 1;
- const velocityScale = targetBlur * 2.4;
- motionBlurFilter.velocity =
- targetBlur > 0
- ? { x: (velocityX / dirMag) * velocityScale, y: (velocityY / dirMag) * velocityScale }
- : { x: 0, y: 0 };
- motionBlurFilter.kernelSize = targetBlur > 8 ? 15 : targetBlur > 4 ? 11 : 7;
- motionBlurFilter.offset = targetBlur > 0.5 ? -0.2 : 0;
-
- if (blurFilter) {
- blurFilter.blur = 0;
- }
- }
- } else {
- if (motionBlurFilter) {
- motionBlurFilter.velocity = { x: 0, y: 0 };
- motionBlurFilter.kernelSize = 5;
- motionBlurFilter.offset = 0;
- }
- if (blurFilter) {
- blurFilter.blur = 0;
- }
- if (motionBlurState) {
- motionBlurState.initialized = false;
- }
- }
-
- return {
- scale: transform.scale,
- x: transform.x,
- y: transform.y,
- };
-}
diff --git a/vite.config.ts b/vite.config.ts
index a42dab288..755cd4264 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -78,8 +78,6 @@ export default defineConfig({
rollupOptions: {
output: {
manualChunks(id) {
- if (id.includes("pixi.js") || id.includes("pixi-filters") || id.includes("@pixi/"))
- return "pixi";
if (id.includes("react-dom") || id.includes("/react/")) return "react-vendor";
if (
id.includes("mediabunny") ||