Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
New Cropper across the app (#1079)
Ilya0f2ff40e0852
diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.jsonindex 5991565da..f832fff88 100644--- a/apps/desktop/src-tauri/capabilities/default.json+++ b/apps/desktop/src-tauri/capabilities/default.json@@ -24,6 +24,7 @@"core:path:default","core:event:default","core:menu:default",+ "core:resources:allow-close","core:window:default","core:window:allow-close","core:window:allow-destroy",diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rsindex 7bc7d3e71..fbd618985 100644--- a/apps/desktop/src-tauri/src/general_settings.rs+++ b/apps/desktop/src-tauri/src/general_settings.rs@@ -70,8 +70,6 @@ pub struct GeneralSettingsStore {pub upload_individual_files: bool,#[serde(default)]pub hide_dock_icon: bool,- #[serde(default = "true_b")]- pub haptics_enabled: bool,#[serde(default)]pub auto_create_shareable_link: bool,#[serde(default = "true_b")]@@ -166,7 +164,6 @@ impl Default for GeneralSettingsStore {instance_id: uuid::Uuid::new_v4(),upload_individual_files: false,hide_dock_icon: false,- haptics_enabled: true,auto_create_shareable_link: false,enable_notifications: true,disable_auto_open_links: false,diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 115008412..04fe4131c 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -285,6 +285,9 @@ pub struct RecordingDeleted {path: PathBuf,}+#[derive(specta::Type, tauri_specta::Event, Serialize)]+pub struct SetCaptureAreaPending(bool);+#[derive(Deserialize, specta::Type, Serialize, tauri_specta::Event, Debug, Clone)]pub struct NewScreenshotAdded {path: PathBuf,@@ -1920,6 +1923,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {target_select_overlay::TargetUnderCursor,hotkeys::OnEscapePress,upload::UploadProgressEvent,+ SetCaptureAreaPending,]).error_handling(tauri_specta::ErrorHandlingMode::Throw).typ::<ProjectConfiguration>()diff --git a/apps/desktop/src-tauri/src/platform/mod.rs b/apps/desktop/src-tauri/src/platform/mod.rsindex b409f600d..e51d3e709 100644--- a/apps/desktop/src-tauri/src/platform/mod.rs+++ b/apps/desktop/src-tauri/src/platform/mod.rs@@ -11,6 +11,7 @@ pub use macos::*;use tracing::instrument;#[derive(Debug, Serialize, Deserialize, Type, Default)]+#[serde(rename_all = "camelCase")]#[repr(isize)]pub enum HapticPattern {Alignment = 0,@@ -20,6 +21,7 @@ pub enum HapticPattern {}#[derive(Debug, Serialize, Deserialize, Type, Default)]+#[serde(rename_all = "camelCase")]#[repr(usize)]pub enum HapticPerformanceTime {Default = 0,diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex 47828293a..ba6d5a71f 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -578,6 +578,7 @@ impl ShowCapWindow {.maximized(false).fullscreen(false).shadow(false)+ .resizable(false).always_on_top(true).content_protected(should_protect).skip_taskbar(true)@@ -608,7 +609,7 @@ impl ShowCapWindow {#[cfg(target_os = "macos")]crate::platform::set_window_level(window.as_ref().window(),- objc2_app_kit::NSScreenSaverWindowLevel,+ objc2_app_kit::NSPopUpMenuWindowLevel,);// Hide the main window if the target monitor is the samediff --git a/apps/desktop/src/components/CapErrorBoundary.tsx b/apps/desktop/src/components/CapErrorBoundary.tsxindex 5fc9e35cf..5bf7fc132 100644--- a/apps/desktop/src/components/CapErrorBoundary.tsx+++ b/apps/desktop/src/components/CapErrorBoundary.tsx@@ -1,4 +1,5 @@import { Button } from "@cap/ui-solid";+import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";import { writeText } from "@tauri-apps/plugin-clipboard-manager";import { ErrorBoundary, type ParentProps } from "solid-js";@@ -32,6 +33,12 @@ export function CapErrorBoundary(props: ParentProps) {>Reload</Button>+ <Button+ onClick={() => getCurrentWebviewWindow().close()}+ variant="destructive"+ >+ Close+ </Button></div>{import.meta.env.DEV && (diff --git a/apps/desktop/src/components/CropAreaRenderer.tsx b/apps/desktop/src/components/CropAreaRenderer.tsxdeleted file mode 100644index b40e0d7ad..000000000--- a/apps/desktop/src/components/CropAreaRenderer.tsx+++ /dev/null@@ -1,290 +0,0 @@-import {- createEffect,- createSignal,- onCleanup,- onMount,- type ParentProps,-} from "solid-js";-import { createHiDPICanvasContext } from "~/utils/canvas";-import type { LogicalBounds } from "~/utils/tauri";--type DrawContext = {- ctx: CanvasRenderingContext2D;- bounds: LogicalBounds;- radius: number;- prefersDark: boolean;- highlighted: boolean;- selected: boolean;-};--function drawHandles({- ctx,- bounds,- radius,- highlighted,- selected,-}: DrawContext) {- const {- position: { x, y },- size: { width, height },- } = bounds;- const minSizeForSideHandles = 100;-- ctx.strokeStyle = selected- ? "rgba(255, 255, 255, 1)"- : highlighted- ? "rgba(60, 150, 280, 1)"- : "rgba(255, 255, 255, 0.8)";-- ctx.lineWidth = 1;- ctx.beginPath();- ctx.roundRect(x, y, width, height, radius);- ctx.stroke();-- ctx.lineWidth = 5;- ctx.lineCap = "round";- ctx.setLineDash([]);-- const cornerHandleLength = radius === 0 ? 20 : 10;-- // Corner handles- const adjustedRadius = Math.min(radius, width / 2, height / 2);-- const x2 = x + width;- const y2 = y + height;-- // top left- ctx.beginPath();-- ctx.moveTo(x, y + adjustedRadius + cornerHandleLength);- ctx.arcTo(x, y, x2, y, adjustedRadius);- ctx.lineTo(x + adjustedRadius + cornerHandleLength, y);-- // top right- ctx.moveTo(x2 - adjustedRadius - cornerHandleLength, y);- ctx.arcTo(x2, y, x2, y2, adjustedRadius);- ctx.lineTo(x2, y + adjustedRadius + cornerHandleLength);-- // bottom left- ctx.moveTo(x + adjustedRadius + cornerHandleLength, y2);- ctx.arcTo(x, y2, x, y, adjustedRadius);- ctx.lineTo(x, y2 - adjustedRadius - cornerHandleLength);-- // bottom right- ctx.moveTo(x2, y2 - adjustedRadius - cornerHandleLength);- ctx.arcTo(x2, y2, x, y2, adjustedRadius);- ctx.lineTo(x2 - adjustedRadius - cornerHandleLength, y2);-- ctx.stroke();-- // Only draw side handles if there's enough space.- if (!(width > minSizeForSideHandles && height > minSizeForSideHandles)) {- return;- }-- // Center handles- const handleLength = 35;- const sideHandleDistance = 0;- const centerX = x + width / 2;- const centerY = y + height / 2;-- ctx.beginPath();-- // top center- ctx.moveTo(centerX - handleLength / 2, y - sideHandleDistance);- ctx.lineTo(centerX + handleLength / 2, y - sideHandleDistance);-- // bottom center- ctx.moveTo(centerX - handleLength / 2, y + height + sideHandleDistance);- ctx.lineTo(centerX + handleLength / 2, y + height + sideHandleDistance);-- // left center- ctx.moveTo(x - sideHandleDistance, centerY - handleLength / 2);- ctx.lineTo(x - sideHandleDistance, centerY + handleLength / 2);-- // right center- ctx.moveTo(x + width + sideHandleDistance, centerY - handleLength / 2);- ctx.lineTo(x + width + sideHandleDistance, centerY + handleLength / 2);-- ctx.stroke();-}--// Rule of thirds guide lines and center crosshair-function drawGuideLines({- ctx,- bounds: { position, size },- prefersDark,-}: DrawContext) {- ctx.strokeStyle = prefersDark- ? "rgba(255, 255, 255, 0.5)"- : "rgba(0, 0, 0, 0.5)";- ctx.lineWidth = 1;- ctx.setLineDash([5, 2]);-- // Rule of thirds- ctx.beginPath();- for (let i = 1; i < 3; i++) {- const x = position.x + (size.width * i) / 3;- ctx.moveTo(x, position.y);- ctx.lineTo(x, position.y + size.height);- }- ctx.stroke();-- ctx.beginPath();- for (let i = 1; i < 3; i++) {- const y = position.y + (size.height * i) / 3;- ctx.moveTo(position.x, y);- ctx.lineTo(position.x + size.width, y);- }- ctx.stroke();-- // Center crosshair- const centerX = Math.round(position.x + size.width / 2);- const centerY = Math.round(position.y + size.height / 2);-- ctx.setLineDash([]);- ctx.lineWidth = 2;- const crosshairLength = 7;-- ctx.beginPath();- ctx.moveTo(centerX - crosshairLength, centerY);- ctx.lineTo(centerX + crosshairLength, centerY);- ctx.stroke();-- ctx.beginPath();- ctx.moveTo(centerX, centerY - crosshairLength);- ctx.lineTo(centerX, centerY + crosshairLength);- ctx.stroke();-}--// Main draw function-function draw(- ctx: CanvasRenderingContext2D,- { position, size }: LogicalBounds,- radius: number,- guideLines: boolean,- showHandles: boolean,- highlighted: boolean,- selected: boolean,- prefersDark: boolean,-) {- if (size.width <= 0 || size.height <= 0) return;- const drawContext: DrawContext = {- ctx,- bounds: { position, size },- radius,- prefersDark,- highlighted,- selected,- };-- ctx.save();- ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);-- ctx.fillStyle = "rgba(0, 0, 0, 0.65)";- ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);-- // Shadow- ctx.save();- ctx.shadowColor = "rgba(0, 0, 0, 0.8)";- ctx.shadowBlur = 200;- ctx.shadowOffsetY = 25;- ctx.beginPath();- ctx.roundRect(position.x, position.y, size.width, size.height, radius);- ctx.fill();- ctx.restore();-- if (showHandles) drawHandles(drawContext);-- ctx.beginPath();- ctx.roundRect(position.x, position.y, size.width, size.height, radius);- ctx.clip();- ctx.clearRect(position.x, position.y, size.width, size.height);-- if (guideLines) drawGuideLines(drawContext);-- ctx.restore();-}--export default function CropAreaRenderer(- props: ParentProps<{- bounds: LogicalBounds;- guideLines?: boolean;- handles?: boolean;- borderRadius?: number;- highlighted?: boolean;- selected?: boolean;- }>,-) {- let canvasRef: HTMLCanvasElement | undefined;- const [prefersDarkScheme, setPrefersDarkScheme] = createSignal(false);-- onMount(() => {- if (!canvasRef) {- console.error("Canvas ref was not setup");- return;- }-- const colorSchemeQuery = window.matchMedia("(prefers-color-scheme: dark)");- setPrefersDarkScheme(colorSchemeQuery.matches);- const handleChange = (e: MediaQueryListEvent) =>- setPrefersDarkScheme(e.matches);- colorSchemeQuery.addEventListener("change", handleChange);-- const hidpiCanvas = createHiDPICanvasContext(canvasRef, (ctx) =>- draw(- ctx,- props.bounds,- props.borderRadius || 0,- props.guideLines || false,- props.handles || false,- props.highlighted || false,- props.selected || false,- prefersDarkScheme(),- ),- );- const ctx = hidpiCanvas?.ctx;- if (!ctx) return;-- let lastAnimationFrameId: number | undefined;- createEffect(() => {- if (lastAnimationFrameId) cancelAnimationFrame(lastAnimationFrameId);-- const {- guideLines,- handles,- borderRadius,- highlighted,- selected,- bounds: { ...bounds },- } = props;-- const prefersDark = prefersDarkScheme();- lastAnimationFrameId = requestAnimationFrame(() =>- draw(- ctx,- bounds,- borderRadius || 0,- guideLines || false,- handles || false,- highlighted || false,- selected || false,- prefersDark,- ),- );- });-- onCleanup(() => {- if (lastAnimationFrameId) cancelAnimationFrame(lastAnimationFrameId);- hidpiCanvas.cleanup();- colorSchemeQuery.removeEventListener("change", handleChange);- });- });-- return (- <div class="*:h-full *:w-full animate-in fade-in">- <canvas ref={canvasRef} class="pointer-events-none absolute" />- <div>{props.children}</div>- </div>- );-}diff --git a/apps/desktop/src/components/Cropper.tsx b/apps/desktop/src/components/Cropper.tsxindex 88379b221..6509ce71c 100644--- a/apps/desktop/src/components/Cropper.tsx+++ b/apps/desktop/src/components/Cropper.tsx@@ -1,771 +1,1520 @@import { createEventListenerMap } from "@solid-primitives/event-listener";-import { makePersisted } from "@solid-primitives/storage";-import { type CheckMenuItemOptions, Menu } from "@tauri-apps/api/menu";+import { createResizeObserver } from "@solid-primitives/resize-observer";+import type {+ CheckMenuItemOptions,+ PredefinedMenuItemOptions,+} from "@tauri-apps/api/menu";import { type as ostype } from "@tauri-apps/plugin-os";import {- batch,+ type Accessor,+ children,createEffect,createMemo,- createResource,createRoot,createSignal,For,on,- onCleanup,onMount,type ParentProps,Show,} from "solid-js";import { createStore } from "solid-js/store";import { Transition } from "solid-transition-group";-import { generalSettingsStore } from "~/store";-import Box from "~/utils/box";-import { type Crop, commands, type XY } from "~/utils/tauri";-import CropAreaRenderer from "./CropAreaRenderer";+import { createKeyDownSignal } from "~/utils/events";++import { commands } from "~/utils/tauri";+export interface CropBounds {+ x: number;+ y: number;+ width: number;+ height: number;+}+export const CROP_ZERO: CropBounds = { x: 0, y: 0, width: 0, height: 0 };type Direction = "n" | "e" | "s" | "w" | "nw" | "ne" | "se" | "sw";+type BoundsConstraints = {+ top: boolean;+ right: boolean;+ bottom: boolean;+ left: boolean;+};+type Vec2 = { x: number; y: number };+type HandleSide = {x: "l" | "r" | "c";y: "t" | "b" | "c";direction: Direction;- cursor: "ew" | "ns" | "nesw" | "nwse";+ cursor: string;+ movable: BoundsConstraints;+ origin: Vec2;+ isCorner: boolean;};-const HANDLES: HandleSide[] = [- { x: "l", y: "t", direction: "nw", cursor: "nwse" },- { x: "r", y: "t", direction: "ne", cursor: "nesw" },- { x: "l", y: "b", direction: "sw", cursor: "nesw" },- { x: "r", y: "b", direction: "se", cursor: "nwse" },- { x: "c", y: "t", direction: "n", cursor: "ns" },- { x: "c", y: "b", direction: "s", cursor: "ns" },- { x: "l", y: "c", direction: "w", cursor: "ew" },- { x: "r", y: "c", direction: "e", cursor: "ew" },-];--type Ratio = [number, number];-const COMMON_RATIOS: Ratio[] = [+const HANDLES: readonly HandleSide[] = [+ { x: "l", y: "t", direction: "nw", cursor: "nwse-resize" },+ { x: "r", y: "t", direction: "ne", cursor: "nesw-resize" },+ { x: "l", y: "b", direction: "sw", cursor: "nesw-resize" },+ { x: "r", y: "b", direction: "se", cursor: "nwse-resize" },+ { x: "c", y: "t", direction: "n", cursor: "ns-resize" },+ { x: "c", y: "b", direction: "s", cursor: "ns-resize" },+ { x: "l", y: "c", direction: "w", cursor: "ew-resize" },+ { x: "r", y: "c", direction: "e", cursor: "ew-resize" },+].map(+ (handle) =>+ ({+ ...handle,+ movable: {+ top: handle.y === "t",+ bottom: handle.y === "b",+ left: handle.x === "l",+ right: handle.x === "r",+ },+ origin: {+ x: handle.x === "l" ? 1 : handle.x === "r" ? 0 : 0.5,+ y: handle.y === "t" ? 1 : handle.y === "b" ? 0 : 0.5,+ },+ isCorner: handle.x !== "c" && handle.y !== "c",+ }) as HandleSide,+);+export type Ratio = [number, number];+export const COMMON_RATIOS: readonly Ratio[] = [[1, 1],- [4, 3],+ [2, 1],[3, 2],+ [4, 3],+ [9, 16],[16, 9],- [2, 1],+ [16, 10],[21, 9],];+const ORIGIN_CENTER: Vec2 = { x: 0.5, y: 0.5 };-const KEY_MAPPINGS = new Map([- ["ArrowRight", "e"],- ["ArrowDown", "s"],- ["ArrowLeft", "w"],- ["ArrowUp", "n"],-]);+const ratioToValue = (r: Ratio) => r[0] / r[1];+const clamp = (n: number, min = 0, max = 1) => Math.max(min, Math.min(max, n));+const easeInOutCubic = (t: number) =>+ t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2;-const ORIGIN_CENTER: XY<number> = { x: 0.5, y: 0.5 };+const shouldTriggerHaptic = ostype() === "macos";+function triggerHaptic() {+ if (shouldTriggerHaptic) commands.performHapticFeedback("alignment", null);+}-function clamp(n: number, min = 0, max = 1) {- return Math.max(min, Math.min(max, n));+function findClosestRatio(+ width: number,+ height: number,+ threshold = 0.01,+): Ratio | null {+ const currentRatio = width / height;+ for (const ratio of COMMON_RATIOS) {+ if (Math.abs(currentRatio - ratio[0] / ratio[1]) < threshold)+ return [ratio[0], ratio[1]];+ if (Math.abs(currentRatio - ratio[1] / ratio[0]) < threshold)+ return [ratio[1], ratio[0]];+ }+ return null;}-function distanceOf(firstPoint: Touch, secondPoint: Touch): number {- const dx = firstPoint.clientX - secondPoint.clientX;- const dy = firstPoint.clientY - secondPoint.clientY;- return Math.sqrt(dx * dx + dy * dy);+// -----------------------------+// Bounds helpers+// -----------------------------+function moveBounds(+ bounds: CropBounds,+ x: number | null,+ y: number | null,+): CropBounds {+ return {+ ...bounds,+ x: x !== null ? Math.round(x) : bounds.x,+ y: y !== null ? Math.round(y) : bounds.y,+ };}-export function cropToFloor(value: Crop): Crop {+function resizeBounds(+ bounds: CropBounds,+ newWidth: number,+ newHeight: number,+ origin: Vec2,+): CropBounds {+ const fromX = bounds.x + bounds.width * origin.x;+ const fromY = bounds.y + bounds.height * origin.y;return {- size: {- x: Math.floor(value.size.x),- y: Math.floor(value.size.y),- },- position: {- x: Math.floor(value.position.x),- y: Math.floor(value.position.y),- },+ x: Math.round(fromX - newWidth * origin.x),+ y: Math.round(fromY - newHeight * origin.y),+ width: Math.round(newWidth),+ height: Math.round(newHeight),};}-export default function Cropper(+function scaleBounds(bounds: CropBounds, factor: number, origin: Vec2) {+ return resizeBounds(+ bounds,+ bounds.width * factor,+ bounds.height * factor,+ origin,+ );+}++function constrainBoundsToRatio(+ bounds: CropBounds,+ ratio: number,+ origin: Vec2,+) {+ const currentRatio = bounds.width / bounds.height;+ if (Math.abs(currentRatio - ratio) < 0.001) return bounds;+ return resizeBounds(bounds, bounds.width, bounds.width / ratio, origin);+}++function constrainBoundsToSize(+ bounds: CropBounds,+ max: Vec2 | null,+ min: Vec2 | null,+ origin: Vec2,+ ratio: number | null = null,+) {+ let next = { ...bounds };+ let maxW = max?.x ?? null;+ let maxH = max?.y ?? null;+ let minW = min?.x ?? null;+ let minH = min?.y ?? null;++ if (ratio) {+ // Correctly calculate effective min/max sizes when a ratio is present+ if (minW && minH) {+ const effectiveMinW = Math.max(minW, minH * ratio);+ minW = effectiveMinW;+ minH = effectiveMinW / ratio;+ }+ if (maxW && maxH) {+ const effectiveMaxW = Math.min(maxW, maxH * ratio);+ maxW = effectiveMaxW;+ maxH = effectiveMaxW / ratio;+ }+ }++ if (maxW && next.width > maxW)+ next = resizeBounds(next, maxW, ratio ? maxW / ratio : next.height, origin);+ if (maxH && next.height > maxH)+ next = resizeBounds(next, ratio ? maxH * ratio : next.width, maxH, origin);+ if (minW && next.width < minW)+ next = resizeBounds(next, minW, ratio ? minW / ratio : next.height, origin);+ if (minH && next.height < minH)+ next = resizeBounds(next, ratio ? minH * ratio : next.width, minH, origin);++ return next;+}++function slideBoundsIntoContainer(+ bounds: CropBounds,+ containerWidth: number,+ containerHeight: number,+): CropBounds {+ let { x, y, width, height } = bounds;++ if (x < 0) x = 0;+ if (y < 0) y = 0;+ if (x + width > containerWidth) x = containerWidth - width;+ if (y + height > containerHeight) y = containerHeight - height;++ return { ...bounds, x, y };+}++export type CropperRef = {+ fill: () => void;+ reset: () => void;+ setCropProperty: (field: keyof CropBounds, value: number) => void;+ setCrop: (+ value: CropBounds | ((b: CropBounds) => CropBounds),+ origin?: Vec2,+ ) => void;+ bounds: Accessor<CropBounds>;+ animateTo: (real: CropBounds, durationMs?: number) => void;+};++export function Cropper(props: ParentProps<{+ onCropChange?: (bounds: CropBounds) => void;+ onInteraction?: (interacting: boolean) => void;+ onContextMenu?: (event: PointerEvent) => void;+ ref?: CropperRef | ((ref: CropperRef) => void);class?: string;- onCropChange: (value: Crop) => void;- value: Crop;- mappedSize?: XY<number>;- minSize?: XY<number>;- initialSize?: XY<number>;- aspectRatio?: number;- showGuideLines?: boolean;+ minSize?: Vec2;+ maxSize?: Vec2;+ targetSize?: Vec2;+ initialCrop?: CropBounds | (() => CropBounds | undefined);+ aspectRatio?: Ratio;+ showBounds?: boolean;+ snapToRatioEnabled?: boolean;+ useBackdropFilter?: boolean;+ allowLightMode?: boolean;}>,) {- const position = () => props.value.position;- const size = () => props.value.size;+ let containerRef: HTMLDivElement | undefined;+ let regionRef: HTMLDivElement | undefined;+ let occTopRef: HTMLDivElement | undefined;+ let occBottomRef: HTMLDivElement | undefined;+ let occLeftRef: HTMLDivElement | undefined;+ let occRightRef: HTMLDivElement | undefined;++ const resolvedChildren = children(() => props.children);++ // raw bounds are in "logical" coordinates (not scaled to targetSize)+ const [rawBounds, setRawBounds] = createSignal<CropBounds>(CROP_ZERO);+ const [displayRawBounds, setDisplayRawBounds] =+ createSignal<CropBounds>(CROP_ZERO);++ const [isAnimating, setIsAnimating] = createSignal(false);+ let animationFrameId: number | null = null;+ const [isReady, setIsReady] = createSignal(false);++ function stopAnimation() {+ if (animationFrameId !== null) cancelAnimationFrame(animationFrameId);+ animationFrameId = null;+ setIsAnimating(false);+ setDisplayRawBounds(rawBounds());+ }- const [containerSize, setContainerSize] = createSignal({ x: 0, y: 0 });- const mappedSize = createMemo(() => props.mappedSize || containerSize());- const minSize = createMemo(() => {- const mapped = mappedSize();- return {- x: Math.min(100, mapped.x * 0.1),- y: Math.min(100, mapped.y * 0.1),+ const boundsTooSmall = createMemo(+ () => displayRawBounds().width <= 30 || displayRawBounds().height <= 30,+ );++ const [mouseState, setMouseState] = createStore<+ (+ | { drag: null | "region" | "overlay" }+ | { drag: "handle"; cursor: string }+ ) & { hoveringHandle: HandleSide | null }+ >({ drag: null, hoveringHandle: null });++ const resizing = () =>+ mouseState.drag === "handle" || mouseState.drag === "overlay";+ const cursorStyle = () => {+ if (mouseState.drag === "region" || mouseState.drag === "overlay")+ return "grabbing";+ if (mouseState.drag === "handle") return mouseState.cursor;+ };++ createEffect(() => props.onInteraction?.(mouseState.drag !== null));++ const [aspectState, setAspectState] = createStore({+ snapped: null as Ratio | null,+ value: null as number | null,+ });++ createEffect(() => {+ const min = props.minSize;+ const max = props.maxSize;++ if (min && max) {+ if (min.x > max.x)+ throw new Error(+ `Cropper constraint error: minSize.x (${min.x}px) exceeds maxSize.x (${max.x}px). Please adjust the size constraints.`,+ );+ if (min.y > max.y)+ throw new Error(+ `Cropper constraint error: minSize.y (${min.y}px) exceeds maxSize.y (${max.y}px). Please adjust the size constraints.`,+ );+ }+ });++ createEffect(+ on(+ () => props.aspectRatio,+ (v) => {+ const nextRatio = v ? ratioToValue(v) : null;+ setAspectState("value", nextRatio);++ if (!isReady() || !nextRatio) return;+ let targetBounds = rawBounds();++ targetBounds = constrainBoundsToRatio(+ targetBounds,+ nextRatio,+ ORIGIN_CENTER,+ );+ setRawBoundsAndAnimate(targetBounds);+ },+ ),+ );++ const [containerSize, setContainerSize] = createSignal<Vec2>({ x: 1, y: 1 });+ const targetSize = createMemo(() => props.targetSize || containerSize());++ const logicalScale = createMemo<Vec2>(() => {+ if (props.targetSize) {+ const target = props.targetSize;+ const container = containerSize();+ return { x: target.x / container.x, y: target.y / container.y };+ }+ return { x: 1, y: 1 };+ });++ const realBounds = createMemo<CropBounds>(() => {+ const { x, y, width, height } = rawBounds();+ const scale = logicalScale();+ const target = targetSize();+ const bounds = {+ x: Math.round(x * scale.x),+ y: Math.round(y * scale.y),+ width: Math.round(width * scale.x),+ height: Math.round(height * scale.y),};++ if (bounds.width > target.x) bounds.width = target.x;+ if (bounds.height > target.y) bounds.height = target.y;+ if (bounds.x < 0) bounds.x = 0;+ if (bounds.y < 0) bounds.y = 0;+ if (bounds.x + bounds.width > target.x) bounds.x = target.x - bounds.width;+ if (bounds.y + bounds.height > target.y)+ bounds.y = target.y - bounds.height;++ props.onCropChange?.(bounds);+ return bounds;});- const containerToMappedSizeScale = createMemo(() => {- const container = containerSize();- const mapped = mappedSize();+ function calculateLabelTransform(handle: HandleSide) {+ const bounds = rawBounds();+ if (!containerRef) return { x: 0, y: 0 };+ const containerRect = containerRef.getBoundingClientRect();+ const labelWidth = 80;+ const labelHeight = 25;+ const margin = 25;++ const handleScreenX =+ containerRect.left ++ bounds.x ++ bounds.width * (handle.x === "l" ? 0 : handle.x === "r" ? 1 : 0.5);+ const handleScreenY =+ containerRect.top ++ bounds.y ++ bounds.height * (handle.y === "t" ? 0 : handle.y === "b" ? 1 : 0.5);++ let idealX = handleScreenX;+ let idealY = handleScreenY;++ if (handle.x === "l") idealX -= labelWidth + margin;+ else if (handle.x === "r") idealX += margin;+ else idealX -= labelWidth / 2;++ if (handle.y === "t") idealY -= labelHeight + margin;+ else if (handle.y === "b") idealY += margin;+ else idealY -= labelHeight / 2;++ const finalX = clamp(+ idealX,+ margin,+ window.innerWidth - labelWidth - margin,+ );+ const finalY = clamp(+ idealY,+ margin,+ window.innerHeight - labelHeight - margin,+ );++ return { x: finalX, y: finalY };+ }++ const labelTransform = createMemo(() =>+ resizing() && mouseState.hoveringHandle+ ? calculateLabelTransform(mouseState.hoveringHandle)+ : null,+ );++ function boundsToRaw(real: CropBounds) {+ const scale = logicalScale();return {- x: container.x / mapped.x,- y: container.y / mapped.y,+ x: Math.max(0, real.x / scale.x),+ y: Math.max(0, real.y / scale.y),+ width: Math.max(0, real.width / scale.x),+ height: Math.max(0, real.height / scale.y),};- });+ }++ function animateToRawBounds(target: CropBounds, durationMs = 240) {+ const start = displayRawBounds();+ if (+ target.x === start.x &&+ target.y === start.y &&+ target.width === start.width &&+ target.height === start.height+ ) {+ return;+ }++ setIsAnimating(true);+ if (animationFrameId !== null) cancelAnimationFrame(animationFrameId);+ const startTime = performance.now();++ const step = () => {+ const now = performance.now();+ const t = Math.min(1, (now - startTime) / durationMs);+ const e = easeInOutCubic(t);+ setDisplayRawBounds({+ x: start.x + (target.x - start.x) * e,+ y: start.y + (target.y - start.y) * e,+ width: start.width + (target.width - start.width) * e,+ height: start.height + (target.height - start.height) * e,+ });+ if (t < 1) animationFrameId = requestAnimationFrame(step);+ else {+ animationFrameId = null;+ setIsAnimating(false);+ triggerHaptic();+ }+ };++ animationFrameId = requestAnimationFrame(step);+ }++ function setRawBoundsAndAnimate(+ bounds: CropBounds,+ origin?: Vec2,+ durationMs = 240,+ ) {+ if (animationFrameId !== null) cancelAnimationFrame(animationFrameId);+ setIsAnimating(true);+ setRawBoundsConstraining(bounds, origin);+ animateToRawBounds(rawBounds(), durationMs);+ }- const displayScaledCrop = createMemo(() => {- const mapped = mappedSize();+ function computeInitialBounds(): CropBounds {+ const target = targetSize();+ const initialCrop =+ typeof props.initialCrop === "function"+ ? props.initialCrop()+ : props.initialCrop;++ const startBoundsReal = initialCrop ?? {+ x: 0,+ y: 0,+ width: Math.round(target.x / 2),+ height: Math.round(target.y / 2),+ };++ let bounds = boundsToRaw(startBoundsReal);+ const ratioValue = aspectState.value;+ if (ratioValue)+ bounds = constrainBoundsToRatio(bounds, ratioValue, ORIGIN_CENTER);const container = containerSize();++ if (bounds.width > container.x)+ bounds = scaleBounds(bounds, container.x / bounds.width, ORIGIN_CENTER);+ if (bounds.height > container.y)+ bounds = scaleBounds(bounds, container.y / bounds.height, ORIGIN_CENTER);++ bounds = slideBoundsIntoContainer(bounds, container.x, container.y);++ if (!initialCrop)+ bounds = moveBounds(+ bounds,+ container.x / 2 - bounds.width / 2,+ container.y / 2 - bounds.height / 2,+ );+ return bounds;+ }++ function rawSizeConstraint() {+ const scale = logicalScale();return {- x: (position().x / mapped.x) * container.x,- y: (position().y / mapped.y) * container.y,- width: (size().x / mapped.x) * container.x,- height: (size().y / mapped.y) * container.y,+ min: props.minSize+ ? { x: props.minSize.x / scale.x, y: props.minSize.y / scale.y }+ : null,+ max: props.maxSize+ ? { x: props.maxSize.x / scale.x, y: props.maxSize.y / scale.y }+ : null,};- });+ }++ function setRawBoundsConstraining(+ bounds: CropBounds,+ origin = ORIGIN_CENTER,+ ) {+ const ratioValue = aspectState.value;+ const container = containerSize();+ const { min, max } = rawSizeConstraint();+ let newBounds = { ...bounds };++ newBounds = constrainBoundsToSize(newBounds, max, min, origin, ratioValue);++ if (ratioValue)+ newBounds = constrainBoundsToRatio(newBounds, ratioValue, origin);++ if (newBounds.width > container.x)+ newBounds = scaleBounds(newBounds, container.x / newBounds.width, origin);+ if (newBounds.height > container.y)+ newBounds = scaleBounds(+ newBounds,+ container.y / newBounds.height,+ origin,+ );++ newBounds = slideBoundsIntoContainer(newBounds, container.x, container.y);+ setRawBounds(newBounds);+ if (!isAnimating()) setDisplayRawBounds(newBounds);+ }++ function fill() {+ const container = containerSize();+ const targetRaw = {+ x: 0,+ y: 0,+ width: container.x,+ height: container.y,+ };+ setRawBoundsAndAnimate(targetRaw);+ setAspectState("snapped", null);+ }- let containerRef: HTMLDivElement | undefined;onMount(() => {if (!containerRef) return;+ let initialized = false;- const updateContainerSize = () => {- setContainerSize({- x: containerRef!.clientWidth,- y: containerRef!.clientHeight,- });- };+ const updateContainerSize = (width: number, height: number) => {+ const prevScale = logicalScale();+ const currentRaw = rawBounds();+ const preservedReal = {+ x: Math.round(currentRaw.x * prevScale.x),+ y: Math.round(currentRaw.y * prevScale.y),+ width: Math.round(currentRaw.width * prevScale.x),+ height: Math.round(currentRaw.height * prevScale.y),+ };- updateContainerSize();- const resizeObserver = new ResizeObserver(updateContainerSize);- resizeObserver.observe(containerRef);- onCleanup(() => resizeObserver.disconnect());+ setContainerSize({ x: width, y: height });- const mapped = mappedSize();- const initial = props.initialSize || {- x: mapped.x / 2,- y: mapped.y / 2,- };+ setRawBoundsConstraining(boundsToRaw(preservedReal));- const width = clamp(initial.x, minSize().x, mapped.x);- const height = clamp(initial.y, minSize().y, mapped.y);+ if (!initialized && width > 1 && height > 1) {+ initialized = true;+ init();+ }+ };- const box = Box.from(- { x: (mapped.x - width) / 2, y: (mapped.y - height) / 2 },- { x: width, y: height },+ createResizeObserver(containerRef, (e) =>+ updateContainerSize(e.width, e.height),);- box.constrainAll(box, containerSize(), ORIGIN_CENTER, props.aspectRatio);+ updateContainerSize(containerRef.clientWidth, containerRef.clientHeight);- setCrop({- size: { x: width, y: height },- position: {- x: (mapped.x - width) / 2,- y: (mapped.y - height) / 2,- },- });- });+ setDisplayRawBounds(rawBounds());- createEffect(- on(- () => props.aspectRatio,- () => {- if (!props.aspectRatio) return;- const box = Box.from(position(), size());- box.constrainToRatio(props.aspectRatio, ORIGIN_CENTER);- box.constrainToBoundary(mappedSize().x, mappedSize().y, ORIGIN_CENTER);- setCrop(box.toBounds());- },- ),- );+ function init() {+ const bounds = computeInitialBounds();+ setRawBoundsConstraining(bounds);+ setDisplayRawBounds(bounds);+ setIsReady(true);+ }- const [snapToRatioEnabled, setSnapToRatioEnabled] = makePersisted(- createSignal(true),- { name: "cropSnapsToRatio" },- );- const [snappedRatio, setSnappedRatio] = createSignal<Ratio | null>(null);- const [dragging, setDragging] = createSignal(false);- const [gestureState, setGestureState] = createStore<{- isTrackpadGesture: boolean;- lastTouchCenter: XY<number> | null;- initialPinchDistance: number;- initialSize: { width: number; height: number };- }>({- isTrackpadGesture: false,- lastTouchCenter: null,- initialPinchDistance: 0,- initialSize: { width: 0, height: 0 },+ if (props.ref) {+ const cropperRef: CropperRef = {+ reset: () => {+ const bounds = computeInitialBounds();+ setRawBoundsAndAnimate(bounds);+ setAspectState("snapped", null);+ },+ fill,+ setCropProperty: (field, value) => {+ setAspectState("snapped", null);+ setRawBoundsConstraining(+ boundsToRaw({ ...realBounds(), [field]: value }),+ { x: 0, y: 0 },+ );+ },+ setCrop: (value, origin) =>+ setRawBoundsConstraining(+ boundsToRaw(+ typeof value === "function" ? value(rawBounds()) : value,+ ),+ origin,+ ),+ get bounds() {+ return realBounds;+ },+ animateTo: (real, durationMs) =>+ setRawBoundsAndAnimate(boundsToRaw(real), undefined, durationMs),+ };++ if (typeof props.ref === "function") props.ref(cropperRef);+ else props.ref = cropperRef;+ }});- function handleDragStart(event: MouseEvent) {- if (gestureState.isTrackpadGesture) return; // Don't start drag if we're in a trackpad gesture- event.stopPropagation();- setDragging(true);- let lastValidPos = { x: event.clientX, y: event.clientY };- const box = Box.from(position(), size());- const scaleFactors = containerToMappedSizeScale();+ function onRegionPointerDown(e: PointerEvent) {+ if (!containerRef || e.button !== 0) return;++ stopAnimation();+ e.stopPropagation();+ setMouseState({ drag: "region" });+ let currentBounds = rawBounds();+ const containerRect = containerRef.getBoundingClientRect();+ const startOffset = {+ x: e.clientX - containerRect.left - currentBounds.x,+ y: e.clientY - containerRect.top - currentBounds.y,+ };- createRoot((dispose) => {- const mapped = mappedSize();+ createRoot((dispose) =>createEventListenerMap(window, {- mouseup: () => {- setDragging(false);+ pointerup: () => {+ setMouseState({ drag: null });dispose();},- mousemove: (e) => {- requestAnimationFrame(() => {- const dx = (e.clientX - lastValidPos.x) / scaleFactors.x;- const dy = (e.clientY - lastValidPos.y) / scaleFactors.y;-- box.move(- clamp(box.x + dx, 0, mapped.x - box.width),- clamp(box.y + dy, 0, mapped.y - box.height),- );-- const newBox = box;- if (newBox.x !== position().x || newBox.y !== position().y) {- lastValidPos = { x: e.clientX, y: e.clientY };- setCrop(newBox.toBounds());- }- });+ pointermove: (e) => {+ let newX = e.clientX - containerRect.left - startOffset.x;+ let newY = e.clientY - containerRect.top - startOffset.y;++ newX = clamp(newX, 0, containerRect.width - currentBounds.width);+ newY = clamp(newY, 0, containerRect.height - currentBounds.height);++ currentBounds = moveBounds(currentBounds, newX, newY);+ setRawBounds(currentBounds);++ if (!isAnimating()) setDisplayRawBounds(currentBounds);},- });- });+ }),+ );}- function handleWheel(event: WheelEvent) {- event.preventDefault();- const box = Box.from(position(), size());- const mapped = mappedSize();+ // Helper: update handle movable sides when switching between anchor <-> center-origin mode+ function updateHandleForModeSwitch(+ handle: HandleSide,+ currentBounds: CropBounds,+ pointX: number,+ pointY: number,+ ) {+ const center = {+ x: currentBounds.x + currentBounds.width / 2,+ y: currentBounds.y + currentBounds.height / 2,+ };+ const newMovable = { ...handle.movable };+ if (handle.movable.left || handle.movable.right) {+ newMovable.left = pointX < center.x;+ newMovable.right = pointX >= center.x;+ }+ if (handle.movable.top || handle.movable.bottom) {+ newMovable.top = pointY < center.y;+ newMovable.bottom = pointY >= center.y;+ }+ return { ...handle, movable: newMovable };+ }- if (event.ctrlKey) {- setGestureState("isTrackpadGesture", true);+ type ResizeSessionState = {+ startBounds: CropBounds;+ isAltMode: boolean;+ activeHandle: HandleSide;+ originalHandle: HandleSide;+ containerRect: DOMRect;+ };- const velocity = Math.max(0.001, Math.abs(event.deltaY) * 0.001);- const scale = 1 - event.deltaY * velocity;+ function handleResizePointerMove(+ e: PointerEvent,+ context: ResizeSessionState,+ ) {+ const pointX = e.clientX - context.containerRect.left;+ const pointY = e.clientY - context.containerRect.top;++ if (e.altKey !== context.isAltMode) {+ context.isAltMode = e.altKey;+ context.startBounds = rawBounds();+ if (context.isAltMode) {+ context.activeHandle = context.originalHandle;+ } else {+ context.activeHandle = updateHandleForModeSwitch(+ context.originalHandle,+ context.startBounds,+ pointX,+ pointY,+ );+ }+ }- box.resize(- clamp(box.width * scale, minSize().x, mapped.x),- clamp(box.height * scale, minSize().y, mapped.y),- ORIGIN_CENTER,- );- box.constrainAll(box, mapped, ORIGIN_CENTER, props.aspectRatio);- setTimeout(() => setGestureState("isTrackpadGesture", false), 100);- setSnappedRatio(null);+ const { min, max } = rawSizeConstraint();+ const shiftKey = e.shiftKey;+ const ratioValue = aspectState.value;++ const options: ResizeOptions = {+ container: containerSize(),+ min,+ max,+ isAltMode: context.isAltMode,+ shiftKey,+ ratioValue,+ snapToRatioEnabled: !!props.snapToRatioEnabled && !boundsTooSmall(),+ };++ let nextBounds: CropBounds;++ if (ratioValue !== null) {+ nextBounds =+ computeAspectRatioResize(+ pointX,+ pointY,+ context.startBounds,+ context.activeHandle,+ options,+ ) ?? rawBounds();} else {- const velocity = Math.max(1, Math.abs(event.deltaY) * 0.01);- const scaleFactors = containerToMappedSizeScale();- const dx = (-event.deltaX * velocity) / scaleFactors.x;- const dy = (-event.deltaY * velocity) / scaleFactors.y;-- box.move(- clamp(box.x + dx, 0, mapped.x - box.width),- clamp(box.y + dy, 0, mapped.y - box.height),+ const { bounds, snappedRatio } = computeFreeResize(+ pointX,+ pointY,+ context.startBounds,+ context.activeHandle,+ options,);+ nextBounds = bounds;+ if (snappedRatio && !aspectState.snapped) {+ triggerHaptic();+ }+ setAspectState("snapped", snappedRatio);}- setCrop(box.toBounds());- }+ const finalBounds = slideBoundsIntoContainer(+ nextBounds,+ containerSize().x,+ containerSize().y,+ );- function handleTouchStart(event: TouchEvent) {- if (event.touches.length === 2) {- // Initialize pinch zoom- const distance = distanceOf(event.touches[0], event.touches[1]);-- // Initialize touch center- const centerX = (event.touches[0].clientX + event.touches[1].clientX) / 2;- const centerY = (event.touches[0].clientY + event.touches[1].clientY) / 2;-- batch(() => {- setGestureState("initialPinchDistance", distance);- setGestureState("initialSize", {- width: size().x,- height: size().y,- });- setGestureState("lastTouchCenter", { x: centerX, y: centerY });- });- } else if (event.touches.length === 1) {- // Handle single touch as drag- batch(() => {- setDragging(true);- setGestureState("lastTouchCenter", {- x: event.touches[0].clientX,- y: event.touches[0].clientY,- });- });- }+ setRawBounds(finalBounds);+ if (!isAnimating()) setDisplayRawBounds(finalBounds);}- function handleTouchMove(event: TouchEvent) {- if (event.touches.length === 2) {- // Handle pinch zoom- const currentDistance = distanceOf(event.touches[0], event.touches[1]);- const scale = currentDistance / gestureState.initialPinchDistance;-- const box = Box.from(position(), size());- const mapped = mappedSize();-- // Calculate new dimensions while maintaining aspect ratio- const currentRatio = size().x / size().y;- let newWidth = clamp(- gestureState.initialSize.width * scale,- minSize().x,- mapped.x,- );- let newHeight = newWidth / currentRatio;-- // Adjust if height exceeds bounds- if (newHeight < minSize().y || newHeight > mapped.y) {- newHeight = clamp(newHeight, minSize().y, mapped.y);- newWidth = newHeight * currentRatio;- }+ function onHandlePointerDown(handle: HandleSide, e: PointerEvent) {+ if (!containerRef || e.button !== 0) return;+ e.stopPropagation();- // Resize from center- box.resize(newWidth, newHeight, ORIGIN_CENTER);+ stopAnimation();+ setMouseState({ drag: "handle", cursor: handle.cursor });- // Handle two-finger pan- const centerX = (event.touches[0].clientX + event.touches[1].clientX) / 2;- const centerY = (event.touches[0].clientY + event.touches[1].clientY) / 2;+ const context: ResizeSessionState = {+ containerRect: containerRef.getBoundingClientRect(),+ startBounds: rawBounds(),+ isAltMode: e.altKey,+ activeHandle: { ...handle },+ originalHandle: handle,+ };- if (gestureState.lastTouchCenter) {- const scaleFactors = containerToMappedSizeScale();- const dx = (centerX - gestureState.lastTouchCenter.x) / scaleFactors.x;- const dy = (centerY - gestureState.lastTouchCenter.y) / scaleFactors.y;+ createRoot((dispose) =>+ createEventListenerMap(window, {+ pointerup: () => {+ setMouseState({ drag: null });+ // Note: may need to be added back+ // setAspectState("snapped", null);+ dispose();+ },+ pointermove: (e) => handleResizePointerMove(e, context),+ }),+ );+ }- box.move(- clamp(box.x + dx, 0, mapped.x - box.width),- clamp(box.y + dy, 0, mapped.y - box.height),- );- }+ function onHandleDoubleClick(handle: HandleSide, e: MouseEvent) {+ e.stopPropagation();+ const currentBounds = rawBounds();+ const container = containerSize();- setGestureState("lastTouchCenter", { x: centerX, y: centerY });- setCrop(box.toBounds());- } else if (event.touches.length === 1 && dragging()) {- // Handle single touch drag- const box = Box.from(position(), size());- const scaleFactors = containerToMappedSizeScale();- const mapped = mappedSize();-- if (gestureState.lastTouchCenter) {- const dx =- (event.touches[0].clientX - gestureState.lastTouchCenter.x) /- scaleFactors.x;- const dy =- (event.touches[0].clientY - gestureState.lastTouchCenter.y) /- scaleFactors.y;-- box.move(- clamp(box.x + dx, 0, mapped.x - box.width),- clamp(box.y + dy, 0, mapped.y - box.height),- );- }+ const newBounds = { ...currentBounds };- setGestureState("lastTouchCenter", {- x: event.touches[0].clientX,- y: event.touches[0].clientY,- });- setCrop(box.toBounds());+ if (handle.movable.top) {+ newBounds.height = currentBounds.y + currentBounds.height;+ newBounds.y = 0;}- }-- function handleTouchEnd(event: TouchEvent) {- if (event.touches.length === 0) {- setDragging(false);- setGestureState("lastTouchCenter", null);- } else if (event.touches.length === 1) {- setGestureState("lastTouchCenter", {- x: event.touches[0].clientX,- y: event.touches[0].clientY,- });+ if (handle.movable.bottom) {+ newBounds.height = container.y - currentBounds.y;+ }+ if (handle.movable.left) {+ newBounds.width = currentBounds.x + currentBounds.width;+ newBounds.x = 0;+ }+ if (handle.movable.right) {+ newBounds.width = container.x - currentBounds.x;}- }- function handleResizeStartTouch(event: TouchEvent, dir: Direction) {- if (event.touches.length !== 1) return;- event.stopPropagation();- const touch = event.touches[0];- handleResizeStart(touch.clientX, touch.clientY, dir);+ setRawBoundsAndAnimate(newBounds, handle.origin);}- function findClosestRatio(- width: number,- height: number,- threshold = 0.01,- ): Ratio | null {- if (props.aspectRatio) return null;- const currentRatio = width / height;- for (const ratio of COMMON_RATIOS) {- if (Math.abs(currentRatio - ratio[0] / ratio[1]) < threshold) {- return [ratio[0], ratio[1]];- }- if (Math.abs(currentRatio - ratio[1] / ratio[0]) < threshold) {- return [ratio[1], ratio[0]];- }- }- return null;- }+ function onOverlayPointerDown(e: PointerEvent) {+ if (!containerRef || e.button !== 0) return;+ e.preventDefault();+ e.stopPropagation();++ const initialBounds = { ...rawBounds() };+ const SE_HANDLE_INDEX = 3; // use bottom-right as the temporary handle+ const handle = HANDLES[SE_HANDLE_INDEX];++ setMouseState({ drag: "overlay" });- function handleResizeStart(clientX: number, clientY: number, dir: Direction) {- const origin: XY<number> = {- x: dir.includes("w") ? 1 : 0,- y: dir.includes("n") ? 1 : 0,+ const containerRect = containerRef.getBoundingClientRect();+ const startPoint = {+ x: e.clientX - containerRect.left,+ y: e.clientY - containerRect.top,};- let lastValidPos = { x: clientX, y: clientY };- const box = Box.from(position(), size());- const scaleFactors = containerToMappedSizeScale();- const mapped = mappedSize();+ const startBounds: CropBounds = {+ x: startPoint.x,+ y: startPoint.y,+ width: 1,+ height: 1,+ };++ const context: ResizeSessionState = {+ containerRect,+ startBounds,+ isAltMode: e.altKey,+ activeHandle: { ...handle },+ originalHandle: handle,+ };createRoot((dispose) => {createEventListenerMap(window, {- mouseup: dispose,- touchend: dispose,- touchmove: (e) =>- requestAnimationFrame(() => {- if (e.touches.length !== 1) return;- handleResizeMove(e.touches[0].clientX, e.touches[0].clientY);- }),- mousemove: (e) =>- requestAnimationFrame(() =>- handleResizeMove(e.clientX, e.clientY, e.altKey),- ),+ pointerup: () => {+ setMouseState({ drag: null });+ const bounds = rawBounds();+ if (bounds.width < 5 || bounds.height < 5) {+ setRawBounds(initialBounds);+ if (!isAnimating()) setDisplayRawBounds(initialBounds);+ }+ dispose();+ },+ pointermove: (e) => handleResizePointerMove(e, context),});});+ }- const [hapticsEnabled, hapticsEnabledOptions] = createResource(- async () =>- (await generalSettingsStore.get())?.hapticsEnabled &&- ostype() === "macos",- );- generalSettingsStore.listen(() => hapticsEnabledOptions.refetch());+ const KEY_MAPPINGS = new Map([+ ["ArrowRight", "e"],+ ["ArrowDown", "s"],+ ["ArrowLeft", "w"],+ ["ArrowUp", "n"],+ ]);++ const [keyboardState, setKeyboardState] = createStore({+ pressedKeys: new Set<string>(),+ shift: false,+ alt: false,+ meta: false, // Cmd or Ctrl+ });- function handleResizeMove(- moveX: number,- moveY: number,- centerOrigin = false,- ) {- const dx = (moveX - lastValidPos.x) / scaleFactors.x;- const dy = (moveY - lastValidPos.y) / scaleFactors.y;-- const scaleMultiplier = centerOrigin ? 2 : 1;- const currentBox = box.toBounds();-- let newWidth =- dir.includes("e") || dir.includes("w")- ? clamp(- dir.includes("w")- ? currentBox.size.x - dx * scaleMultiplier- : currentBox.size.x + dx * scaleMultiplier,- minSize().x,- mapped.x,- )- : currentBox.size.x;-- let newHeight =- dir.includes("n") || dir.includes("s")- ? clamp(- dir.includes("n")- ? currentBox.size.y - dy * scaleMultiplier- : currentBox.size.y + dy * scaleMultiplier,- minSize().y,- mapped.y,- )- : currentBox.size.y;-- const closest = findClosestRatio(newWidth, newHeight);- if (dir.length === 2 && snapToRatioEnabled() && closest) {- const ratio = closest[0] / closest[1];- if (dir.includes("n") || dir.includes("s")) {- newWidth = newHeight * ratio;- } else {- newHeight = newWidth / ratio;- }- if (!snappedRatio() && hapticsEnabled()) {- commands.performHapticFeedback("Alignment", "Now");- }- setSnappedRatio(closest);- } else {- setSnappedRatio(null);- }+ let keyboardFrameId: number | null = null;- const newOrigin = centerOrigin ? ORIGIN_CENTER : origin;- box.resize(newWidth, newHeight, newOrigin);+ function keyboardActionLoop() {+ const currentBounds = rawBounds();+ const { pressedKeys, shift, alt, meta } = keyboardState;- if (props.aspectRatio) {- box.constrainToRatio(- props.aspectRatio,- newOrigin,- dir.includes("n") || dir.includes("s") ? "width" : "height",- );- }- box.constrainToBoundary(mapped.x, mapped.y, newOrigin);-- const newBox = box.toBounds();- if (- newBox.size.x !== size().x ||- newBox.size.y !== size().y ||- newBox.position.x !== position().x ||- newBox.position.y !== position().y- ) {- lastValidPos = { x: moveX, y: moveY };- props.onCropChange(newBox);- }+ const delta = shift ? 10 : 2;++ if (meta) {+ // Resize+ const origin = alt ? ORIGIN_CENTER : { x: 0, y: 0 };+ let newWidth = currentBounds.width;+ let newHeight = currentBounds.height;++ if (pressedKeys.has("ArrowLeft")) newWidth -= delta;+ if (pressedKeys.has("ArrowRight")) newWidth += delta;+ if (pressedKeys.has("ArrowUp")) newHeight -= delta;+ if (pressedKeys.has("ArrowDown")) newHeight += delta;++ newWidth = Math.max(1, newWidth);+ newHeight = Math.max(1, newHeight);++ const resized = resizeBounds(currentBounds, newWidth, newHeight, origin);++ setRawBoundsConstraining(resized, origin);+ } else {+ // Move+ let dx = 0;+ let dy = 0;++ if (pressedKeys.has("ArrowLeft")) dx -= delta;+ if (pressedKeys.has("ArrowRight")) dx += delta;+ if (pressedKeys.has("ArrowUp")) dy -= delta;+ if (pressedKeys.has("ArrowDown")) dy += delta;++ const moved = moveBounds(+ currentBounds,+ currentBounds.x + dx,+ currentBounds.y + dy,+ );++ setRawBoundsConstraining(moved);}- }- function setCrop(value: Crop) {- props.onCropChange(value);+ keyboardFrameId = requestAnimationFrame(keyboardActionLoop);}- const pressedKeys = new Set<string>([]);- let lastKeyHandleFrame: number | null = null;- function handleKeyDown(event: KeyboardEvent) {- if (dragging()) return;- const dir = KEY_MAPPINGS.get(event.key);- if (!dir) return;- event.preventDefault();- pressedKeys.add(event.key);-- if (lastKeyHandleFrame) return;- lastKeyHandleFrame = requestAnimationFrame(() => {- const box = Box.from(position(), size());- const mapped = mappedSize();- const scaleFactors = containerToMappedSizeScale();-- const moveDelta = event.shiftKey ? 20 : 5;- const origin = event.altKey ? ORIGIN_CENTER : { x: 0, y: 0 };-- for (const key of pressedKeys) {- const dir = KEY_MAPPINGS.get(key);- if (!dir) continue;-- const isUpKey = dir === "n";- const isLeftKey = dir === "w";- const isDownKey = dir === "s";- const isRightKey = dir === "e";-- if (event.metaKey || event.ctrlKey) {- const scaleMultiplier = event.altKey ? 2 : 1;- const currentBox = box.toBounds();-- let newWidth = currentBox.size.x;- let newHeight = currentBox.size.y;-- if (isLeftKey || isRightKey) {- newWidth = clamp(- isLeftKey- ? currentBox.size.x - moveDelta * scaleMultiplier- : currentBox.size.x + moveDelta * scaleMultiplier,- minSize().x,- mapped.x,- );- }+ function handleKeyDown(e: KeyboardEvent) {+ if (!KEY_MAPPINGS.has(e.key) || mouseState.drag !== null) return;- if (isUpKey || isDownKey) {- newHeight = clamp(- isUpKey- ? currentBox.size.y - moveDelta * scaleMultiplier- : currentBox.size.y + moveDelta * scaleMultiplier,- minSize().y,- mapped.y,- );- }+ e.preventDefault();+ e.stopPropagation();- box.resize(newWidth, newHeight, origin);- } else {- const dx =- (isRightKey ? moveDelta : isLeftKey ? -moveDelta : 0) /- scaleFactors.x;- const dy =- (isDownKey ? moveDelta : isUpKey ? -moveDelta : 0) / scaleFactors.y;-- box.move(- clamp(box.x + dx, 0, mapped.x - box.width),- clamp(box.y + dy, 0, mapped.y - box.height),- );- }- }+ setKeyboardState("pressedKeys", (p) => p.add(e.key));+ setKeyboardState({+ shift: e.shiftKey,+ alt: e.altKey,+ meta: e.metaKey || e.ctrlKey,+ });++ if (!keyboardFrameId) {+ stopAnimation();+ keyboardActionLoop();+ }+ }- if (props.aspectRatio) box.constrainToRatio(props.aspectRatio, origin);- box.constrainToBoundary(mapped.x, mapped.y, origin);- setCrop(box.toBounds());+ function handleKeyUp(e: KeyboardEvent) {+ if (+ !KEY_MAPPINGS.has(e.key) &&+ !["Shift", "Alt", "Meta", "Control"].includes(e.key)+ )+ return;- pressedKeys.clear();- lastKeyHandleFrame = null;+ e.preventDefault();++ setKeyboardState("pressedKeys", (p) => {+ p.delete(e.key);+ return p;+ });++ setKeyboardState({+ shift: e.shiftKey,+ alt: e.altKey,+ meta: e.metaKey || e.ctrlKey,});++ if (keyboardState.pressedKeys.size === 0) {+ if (keyboardFrameId) {+ cancelAnimationFrame(keyboardFrameId);+ keyboardFrameId = null;+ }+ }}+ // Only update during a frame animation.+ // Note: Doing this any other way can very likely cause a huge memory usage or even leak until the resizing stops.+ createEffect(+ on<CropBounds, number>(displayRawBounds, (b, _prevIn, prevFrameId) => {+ if (prevFrameId) cancelAnimationFrame(prevFrameId);+ return requestAnimationFrame(() => {+ if (regionRef) {+ regionRef.style.width = `${Math.round(b.width)}px`;+ regionRef.style.height = `${Math.round(b.height)}px`;+ regionRef.style.transform = `translate(${Math.round(b.x)}px,${Math.round(b.y)}px)`;+ }+ if (occLeftRef) {+ occLeftRef.style.width = `${Math.max(0, Math.round(b.x))}px`;+ }+ if (occRightRef) {+ occRightRef.style.left = `${Math.round(b.x + b.width)}px`;+ }+ if (occTopRef) {+ occTopRef.style.left = `${Math.round(b.x)}px`;+ occTopRef.style.width = `${Math.round(b.width)}px`;+ occTopRef.style.height = `${Math.max(0, Math.round(b.y))}px`;+ }+ if (occBottomRef) {+ occBottomRef.style.top = `${Math.round(b.y + b.height)}px`;+ occBottomRef.style.left = `${Math.round(b.x)}px`;+ occBottomRef.style.width = `${Math.round(b.width)}px`;+ }+ });+ }),+ );++ const altDown = createKeyDownSignal(window, "Alt");+return (<divref={containerRef}- class={`relative h-full w-full overflow-hidden overscroll-contain *:overscroll-none ${props.class}`}- onWheel={handleWheel}- onTouchStart={handleTouchStart}- onTouchMove={handleTouchMove}- onTouchEnd={handleTouchEnd}+ class="relative w-full h-full select-none overscroll-contain focus:outline-none touch-none"+ style={{+ cursor: cursorStyle() ?? (props.aspectRatio ? "default" : "crosshair"),+ }}onKeyDown={handleKeyDown}+ onKeyUp={handleKeyUp}tabIndex={0}- // onContextMenu={async (e) => {- // e.preventDefault();- // const menu = await Menu.new({- // id: "crop-options",- // items: [- // {- // id: "enableRatioSnap",- // text: "Snap to aspect ratios",- // checked: snapToRatioEnabled(),- // action: () => {- // setSnapToRatioEnabled((v) => !v);- // },- // } satisfies CheckMenuItemOptions,- // ],- // });- // menu.popup();- // }}+ onContextMenu={props.onContextMenu}+ onDblClick={() => fill()}>- <CropAreaRenderer- bounds={{- position: {- x: displayScaledCrop().x,- y: displayScaledCrop().y,- },- size: {- width: displayScaledCrop().width,- height: displayScaledCrop().height,- },- }}- borderRadius={9}- guideLines={props.showGuideLines}- handles={true}- highlighted={snappedRatio() !== null}+ <Transition+ appear+ enterActiveClass="transition-opacity duration-300 ease-in-out"+ enterClass="opacity-0 blur-sm"+ enterToClass="opacity-100 blur-none"+ exitActiveClass="transition-opacity duration-300 ease-in-out"+ exitClass="opacity-100 blur-none"+ exitToClass="opacity-0 blur-sm">- {props.children}- </CropAreaRenderer>+ <Show when={props.showBounds && labelTransform()}>+ {(transform) => (+ <div+ class="fixed z-50 pointer-events-none bg-gray-2 text-xs px-2 py-0.5 rounded-full shadow-lg border border-gray-5 font-mono scale-50"+ style={{+ transform: `translate(${transform().x}px, ${transform().y}px)`,+ }}+ >+ {realBounds().width} x {realBounds().height}+ </div>+ )}+ </Show>+ </Transition>++ {resolvedChildren()}++ {/* Occluder */}<div- class="absolute"- style={{- top: `${displayScaledCrop().y}px`,- left: `${displayScaledCrop().x}px`,- width: `${displayScaledCrop().width}px`,- height: `${displayScaledCrop().height}px`,- cursor: dragging() ? "grabbing" : "grab",- }}- onMouseDown={handleDragStart}+ class="absolute inset-0 *:absolute *:bg-black/45 *:pointer-events-none"+ aria-hidden="true">- <div class="relative w-full">+ <div ref={occLeftRef} class="top-0 left-0 h-full" />+ <div ref={occRightRef} class="top-0 right-0 h-full" />+ <div ref={occTopRef} class="top-0" />+ <div ref={occBottomRef} class="bottom-0" />+ </div>++ {/* Crop region container */}+ <div class="size-full">+ <div+ ref={regionRef}+ class="absolute top-0 left-0 z-30 size-36 border border-white/50"+ style={{+ cursor: cursorStyle() ?? "grab",+ }}+ onDblClick={(e) => e.stopPropagation()}+ >+ <button+ class="absolute inset-0 z-10 bg-transparent"+ type="button"+ tabIndex={-1}+ style={{ cursor: cursorStyle() ?? "grab" }}+ onPointerDown={onRegionPointerDown}+ />++ <Show when={altDown()}>+ <div class="absolute opacity-70 pointer-events-none flex items-center justify-center size-full">+ <IconLucidePlus class="pointer-events-none size-6" />+ </div>+ </Show>+<Transition- name="slide"- onEnter={(el, done) => {- const animation = el.animate(- [- { opacity: 0, transform: "translateY(-8px)" },- { opacity: 0.65, transform: "translateY(0)" },- ],- {- duration: 100,- easing: "ease-out",- },- );- animation.finished.then(done);- }}- onExit={(el, done) => {- const animation = el.animate(- [- { opacity: 0.65, transform: "translateY(0)" },- { opacity: 0, transform: "translateY(-8px)" },- ],- {- duration: 100,- easing: "ease-in",- },- );- animation.finished.then(done);- }}+ appear+ enterActiveClass="transition-opacity duration-300"+ enterClass="opacity-0"+ enterToClass="opacity-100"+ exitActiveClass="transition-opacity duration-300"+ exitClass="opacity-100"+ exitToClass="opacity-0">- <Show when={snappedRatio() !== null}>- <div class="absolute left-0 right-0 mx-auto top-2 bg-gray-3 opacity-80 h-6 w-10 rounded-[7px] text-center text-blue-9 text-sm border border-blue-9 outline outline-1 outline-[#dedede] dark:outline-[#000]">- {snappedRatio()![0]}:{snappedRatio()![1]}+ <Show when={mouseState.drag !== null}>+ <div class="pointer-events-none *:absolute *:border-white/40">+ <div class="left-0 w-full border-t border-b pointer-events-none h-[calc(100%/3)] top-[calc(100%/3)]" />+ <div class="top-0 h-full border-l border-r pointer-events-none w-[calc(100%/3)] left-[calc(100%/3)]" /></div></Show></Transition>- </div>- <For each={HANDLES}>- {(handle) => {- const isCorner = handle.x !== "c" && handle.y !== "c";- return isCorner ? (- <div- role="slider"- class="absolute z-10 flex h-[30px] w-[30px] items-center justify-center"- style={{- ...(handle.x === "l"- ? { left: "-12px" }- : handle.x === "r"- ? { right: "-12px" }- : { left: "50%", transform: "translateX(-50%)" }),- ...(handle.y === "t"- ? { top: "-12px" }- : handle.y === "b"- ? { bottom: "-12px" }- : { top: "50%", transform: "translateY(-50%)" }),- cursor: dragging() ? "grabbing" : `${handle.cursor}-resize`,- }}- onMouseDown={(e) => {- e.stopPropagation();- handleResizeStart(e.clientX, e.clientY, handle.direction);- }}- onTouchStart={(e) =>- handleResizeStartTouch(e, handle.direction)- }- />- ) : (- <div- role="slider"- class="absolute"- style={{- ...(handle.x === "l"- ? {- left: "0",- width: "16px",- transform: "translateX(-50%)",+ <For each={HANDLES}>+ {(handle) =>+ handle.isCorner ? (+ <button+ type="button"+ class="fixed z-50 flex h-[30px] w-[30px] focus:ring-0 outline-none"+ tabIndex={-1}+ classList={{ "opacity-0": mouseState.drag === "overlay" }}+ style={{+ cursor:+ mouseState.drag === "handle" &&+ mouseState.hoveringHandle?.isCorner+ ? mouseState.hoveringHandle.cursor+ : (cursorStyle() ?? handle.cursor),+ ...(handle.x === "l"+ ? { left: "-12px" }+ : { right: "-12px" }),+ ...(handle.y === "t"+ ? { top: "-12px" }+ : { bottom: "-12px" }),+ }}+ onMouseEnter={() =>+ setMouseState("hoveringHandle", { ...handle })+ }+ onDblClick={[onHandleDoubleClick, handle]}+ onPointerDown={[onHandlePointerDown, handle]}+ aria-label={`Resize ${handle.direction}`}+ aria-describedby="cropper-aspect"+ >+ <svg+ aria-hidden="true"+ class="absolute pointer-events-none drop-shadow-sm shadow-black"+ classList={{+ "size-1": boundsTooSmall(),+ "size-6": !boundsTooSmall(),+ }}+ viewBox="0 0 16 16"+ fill="none"+ stroke="white"+ stroke-width="4"+ stroke-linecap="square"+ style={{+ ...(handle.x === "l"+ ? { left: "9px" }+ : { right: "9px" }),+ ...(handle.y === "t"+ ? { top: "9px" }+ : { bottom: "9px" }),+ filter: `drop-shadow(${handle.x === "l" ? "-3px" : "3px"} ${handle.y === "t" ? "-3px" : "3px"} 5px rgba(0, 0, 0, 0.3))`,+ }}+ >+ <path+ d={+ handle.x === "l" && handle.y === "t"+ ? "M0 0 H12 M0 0 V12"+ : handle.x === "r" && handle.y === "t"+ ? "M16 0 H4 M16 0 V12"+ : handle.x === "r" && handle.y === "b"+ ? "M16 16 H4 M16 16 V4"+ : "M0 16 H12 M0 16 V4"}- : handle.x === "r"+ />+ </svg>+ </button>+ ) : (+ <button+ type="button"+ class="absolute focus:outline-none focus:ring-0 outline-none"+ tabIndex={-1}+ style={{+ visibility:+ resizing() && mouseState.hoveringHandle?.isCorner+ ? "hidden"+ : "visible",+ cursor: cursorStyle() ?? handle.cursor,+ ...(handle.x === "l"? {- right: "0",- width: "16px",- transform: "translateX(50%)",+ left: "-1px",+ width: "10px",+ top: "10px",+ bottom: "10px",+ transform: "translateX(-50%)",}- : {- left: "0",- right: "0",- transform: "translateY(50%)",- }),- ...(handle.y === "t"- ? {- top: "0",- height: "16px",- transform: "translateY(-50%)",- }- : handle.y === "b"- ? { bottom: "0", height: "16px" }- : { top: "0", bottom: "0" }),- cursor: `${handle.cursor}-resize`,- }}- onMouseDown={(e) => {- e.stopPropagation();- handleResizeStart(e.clientX, e.clientY, handle.direction);- }}- onTouchStart={(e) =>- handleResizeStartTouch(e, handle.direction)- }- />- );- }}- </For>+ : handle.x === "r"+ ? {+ right: "-1px",+ width: "10px",+ top: "10px",+ bottom: "10px",+ transform: "translateX(50%)",+ }+ : handle.y === "t"+ ? {+ top: "-1px",+ height: "10px",+ left: "10px",+ right: "10px",+ transform: "translateY(-50%)",+ }+ : {+ bottom: "-1px",+ height: "10px",+ left: "10px",+ right: "10px",+ transform: "translateY(50%)",+ }),+ }}+ onMouseEnter={() =>+ setMouseState("hoveringHandle", { ...handle })+ }+ onDblClick={[onHandleDoubleClick, handle]}+ onPointerDown={[onHandlePointerDown, handle]}+ aria-label={`Resize ${handle.direction}`}+ aria-describedby="cropper-aspect"+ />+ )+ }+ </For>++ <Show+ when={+ !props.aspectRatio && !boundsTooSmall()+ ? aspectState.snapped+ : null+ }+ keyed+ >+ {(bounds) => (+ <div+ class="w-full h-8 flex items-center justify-center"+ id="cropper-aspect"+ aria-live="polite"+ >+ <div+ class="h-[18px] w-11 rounded-full text-center text-xs text-gray-12 border border-white/70 dark:border-white/20 drop-shadow-md outline-1 outline outline-black/80"+ classList={{+ "backdrop-blur-sm bg-white/50 dark:bg-black/50 dark:backdrop-brightness-90 backdrop-brightness-200":+ props.useBackdropFilter,+ "bg-gray-3 opacity-80": !props.useBackdropFilter,+ }}+ >+ {bounds[0]}:{bounds[1]}+ </div>+ </div>+ )}+ </Show>+ </div>++ <button+ type="button"+ class="absolute inset-0 z-20 bg-transparent p-0 m-0 border-0"+ aria-label="Start selection"+ onPointerDown={onOverlayPointerDown}+ style={{ cursor: cursorStyle() ?? "crosshair" }}+ /></div></div>);}++type ResizeOptions = {+ container: Vec2;+ min: Vec2 | null;+ max: Vec2 | null;+ isAltMode: boolean;+ shiftKey: boolean;+ ratioValue: number | null;+ snapToRatioEnabled: boolean;+};++function computeAspectRatioResize(+ pointX: number,+ pointY: number,+ startBounds: CropBounds,+ handle: HandleSide,+ options: ResizeOptions,+): CropBounds | null {+ const { container, min, max, ratioValue } = options;+ if (ratioValue === null) return startBounds;++ // Determine the stationary anchor point.+ const anchorX = startBounds.x + (handle.movable.left ? startBounds.width : 0);+ const anchorY = startBounds.y + (handle.movable.top ? startBounds.height : 0);++ // Calculate raw dimensions from anchor to the clamped mouse position+ const mX = clamp(pointX, 0, container.x);+ const mY = clamp(pointY, 0, container.y);+ const rawWidth = Math.abs(mX - anchorX);+ const rawHeight = Math.abs(mY - anchorY);++ // Determine the "ideal" size by respecting the aspect ratio based on the dominant mouse movement+ let targetW: number;+ let targetH: number;++ if (handle.isCorner) {+ // For corners, let the dominant mouse direction drive the aspect ratio+ if (rawWidth / ratioValue > rawHeight) {+ targetW = rawWidth;+ targetH = targetW / ratioValue;+ } else {+ targetH = rawHeight;+ targetW = targetH * ratioValue;+ }+ } else if (handle.x !== "c") {+ targetW = rawWidth;+ targetH = targetW / ratioValue;+ } else {+ targetH = rawHeight;+ targetW = targetH * ratioValue;+ }++ const newX = mX < anchorX ? anchorX - targetW : anchorX;+ const newY = mY < anchorY ? anchorY - targetH : anchorY;+ let finalBounds = { x: newX, y: newY, width: targetW, height: targetH };++ if (+ finalBounds.x < 0 ||+ finalBounds.y < 0 ||+ finalBounds.x + finalBounds.width > container.x ||+ finalBounds.y + finalBounds.height > container.y+ ) {+ return null;+ }++ const resizeOrigin = { x: mX < anchorX ? 1 : 0, y: mY < anchorY ? 1 : 0 };+ finalBounds = constrainBoundsToSize(+ finalBounds,+ max,+ min,+ resizeOrigin,+ ratioValue,+ );++ if (finalBounds.width > container.x) {+ const scale = container.x / finalBounds.width;+ finalBounds.width = container.x;+ finalBounds.height *= scale;+ }+ if (finalBounds.height > container.y) {+ const scale = container.y / finalBounds.height;+ finalBounds.height = container.y;+ finalBounds.width *= scale;+ }++ finalBounds = slideBoundsIntoContainer(finalBounds, container.x, container.y);++ return {+ x: Math.round(finalBounds.x),+ y: Math.round(finalBounds.y),+ width: Math.round(Math.max(1, finalBounds.width)),+ height: Math.round(Math.max(1, finalBounds.height)),+ };+}++function computeFreeResize(+ pointX: number,+ pointY: number,+ startBounds: CropBounds,+ handle: HandleSide,+ options: ResizeOptions,+): { bounds: CropBounds; snappedRatio: Ratio | null } {+ const { container, min, max, isAltMode, shiftKey, snapToRatioEnabled } =+ options;+ let snappedRatio: Ratio | null = null;++ let bounds: CropBounds;++ if (isAltMode) {+ const center = {+ x: startBounds.x + startBounds.width / 2,+ y: startBounds.y + startBounds.height / 2,+ };++ const distW = Math.abs(pointX - center.x);+ const distH = Math.abs(pointY - center.y);++ const expLeft = Math.min(distW, center.x);+ const expRight = Math.min(distW, container.x - center.x);+ const expTop = Math.min(distH, center.y);+ const expBottom = Math.min(distH, container.y - center.y);++ let newW = expLeft + expRight;+ let newH = expTop + expBottom;++ if (min) {+ newW = Math.max(newW, min.x);+ newH = Math.max(newH, min.y);+ }+ if (max) {+ newW = Math.min(newW, max.x);+ newH = Math.min(newH, max.y);+ }++ if (!shiftKey && handle.isCorner && snapToRatioEnabled) {+ const closest = findClosestRatio(newW, newH);+ if (closest) {+ const r = ratioToValue(closest);+ if (handle.movable.top || handle.movable.bottom) newW = newH * r;+ else newH = newW / r;+ snappedRatio = closest;+ }+ }++ bounds = {+ x: Math.round(center.x - newW / 2),+ y: Math.round(center.y - newH / 2),+ width: Math.round(newW),+ height: Math.round(newH),+ };+ } else {+ const anchor = {+ x: startBounds.x + (handle.movable.left ? startBounds.width : 0),+ y: startBounds.y + (handle.movable.top ? startBounds.height : 0),+ };+ const clampedX = clamp(pointX, 0, container.x);+ const clampedY = clamp(pointY, 0, container.y);++ let x1 =+ handle.movable.left || handle.movable.right ? clampedX : startBounds.x;+ let y1 =+ handle.movable.top || handle.movable.bottom ? clampedY : startBounds.y;+ let x2 = anchor.x;+ let y2 = anchor.y;++ if (!handle.movable.left && !handle.movable.right) {+ x1 = startBounds.x;+ x2 = startBounds.x + startBounds.width;+ }+ if (!handle.movable.top && !handle.movable.bottom) {+ y1 = startBounds.y;+ y2 = startBounds.y + startBounds.height;+ }++ let newX = Math.min(x1, x2);+ let newY = Math.min(y1, y2);+ let newW = Math.abs(x1 - x2);+ let newH = Math.abs(y1 - y2);++ if (min) {+ if (newW < min.x) {+ const diff = min.x - newW;+ newW = min.x;+ if (clampedX < anchor.x) newX -= diff;+ }+ if (newH < min.y) {+ const diff = min.y - newH;+ newH = min.y;+ if (clampedY < anchor.y) newY -= diff;+ }+ }+ if (max) {+ if (newW > max.x) {+ const diff = newW - max.x;+ newW = max.x;+ if (clampedX < anchor.x) newX += diff;+ }+ if (newH > max.y) {+ const diff = newH - max.y;+ newH = max.y;+ if (clampedY < anchor.y) newY += diff;+ }+ }++ if (!shiftKey && handle.isCorner && snapToRatioEnabled) {+ const closest = findClosestRatio(newW, newH);+ if (closest) {+ const r = ratioToValue(closest);+ if (handle.movable.top || handle.movable.bottom) newW = newH * r;+ else newH = newW / r;+ if (clampedX < anchor.x) newX = anchor.x - newW;+ if (clampedY < anchor.y) newY = anchor.y - newH;+ snappedRatio = closest;+ }+ }++ bounds = {+ x: Math.round(newX),+ y: Math.round(newY),+ width: Math.round(newW),+ height: Math.round(newH),+ };+ }+ return { bounds, snappedRatio };+}++export function createCropOptionsMenuItems(options: {+ aspect: Ratio | null;+ snapToRatioEnabled: boolean;+ onAspectSet: (aspect: Ratio | null) => void;+ onSnapToRatioSet: (enabled: boolean) => void;+}) {+ return [+ {+ text: "Free",+ checked: !options.aspect,+ action: () => options.onAspectSet(null),+ } satisfies CheckMenuItemOptions,+ ...COMMON_RATIOS.map(+ (ratio) =>+ ({+ text: `${ratio[0]}:${ratio[1]}`,+ checked: options.aspect === ratio,+ action: () => options.onAspectSet(ratio),+ }) satisfies CheckMenuItemOptions,+ ),+ { item: "Separator" } satisfies PredefinedMenuItemOptions,+ {+ text: "Snap to ratios",+ checked: options.snapToRatioEnabled,+ action: () => options.onSnapToRatioSet(!options.snapToRatioEnabled),+ } satisfies CheckMenuItemOptions,+ ];+}diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsxindex dcfbe8a86..23e41f6f2 100644--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx@@ -33,6 +33,7 @@ import {type CaptureDisplay,type CaptureWindow,commands,+ events,type RecordingMode,type ScreenCaptureTarget,} from "~/utils/tauri";@@ -565,6 +566,7 @@ import * as updater from "@tauri-apps/plugin-updater";import { Transition } from "solid-transition-group";import { SignInButton } from "~/components/SignInButton";import { authStore, generalSettingsStore } from "~/store";+import { createTauriEventListener } from "~/utils/createEventListener";import { handleRecordingResult } from "~/utils/recording";import { apiClient } from "~/utils/web-api";import { WindowChromeHeader } from "./Context";@@ -638,14 +640,10 @@ function AreaSelectButton(props: {});}- onMount(async () => {- const unlistenCaptureAreaWindow =- await getCurrentWebviewWindow().listen<boolean>(- "cap-window://capture-area/state/pending",- (event) => setAreaSelection("pending", event.payload),- );- onCleanup(unlistenCaptureAreaWindow);- });+ createTauriEventListener(+ events.setCaptureAreaPending(getCurrentWebviewWindow()),+ (pending) => setAreaSelection("pending", pending),+ );return (<Tooltipdiff --git a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx b/apps/desktop/src/routes/(window-chrome)/settings/general.tsxindex 868fb762f..52cd6384b 100644--- a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx+++ b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx@@ -420,12 +420,6 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {handleChange("enableNotifications", value);}}/>- <ToggleSettingItem- label="Enable haptics"- description="Use haptics on Force Touch™ trackpads"- value={!!settings.hapticsEnabled}- onChange={(v) => handleChange("hapticsEnabled", v)}- /></SettingGroup>)}diff --git a/apps/desktop/src/routes/capture-area.tsx b/apps/desktop/src/routes/capture-area.tsxindex 5a00adda9..d6f724aae 100644--- a/apps/desktop/src/routes/capture-area.tsx+++ b/apps/desktop/src/routes/capture-area.tsx@@ -1,78 +1,112 @@-import { Tooltip } from "@kobalte/core";-import { createEventListenerMap } from "@solid-primitives/event-listener";+import { createEventListener } from "@solid-primitives/event-listener";+import { createScheduled, debounce } from "@solid-primitives/scheduled";import { makePersisted } from "@solid-primitives/storage";+import { LogicalPosition } from "@tauri-apps/api/dpi";+import { Menu } from "@tauri-apps/api/menu";import {getCurrentWebviewWindow,WebviewWindow,} from "@tauri-apps/api/webviewWindow";-import { createSignal, onCleanup, onMount, Show } from "solid-js";+import { type as ostype } from "@tauri-apps/plugin-os";+import { createMemo, createSignal, onCleanup, onMount, Show } from "solid-js";import { createStore, reconcile } from "solid-js/store";import { Transition } from "solid-transition-group";-import Cropper from "~/components/Cropper";+import {+ CROP_ZERO,+ type CropBounds,+ Cropper,+ type CropperRef,+ createCropOptionsMenuItems,+ type Ratio,+} from "~/components/Cropper";import { createOptionsQuery } from "~/utils/queries";-import type { Crop } from "~/utils/tauri";+import type { DisplayId } from "~/utils/tauri";+import { emitTo } from "~/utils/tauriSpectaHack";++const MIN_SIZE = { width: 150, height: 150 };export default function CaptureArea() {- const { rawOptions, setOptions } = createOptionsQuery();const webview = getCurrentWebviewWindow();- const [state, setState] = makePersisted(- createStore({- showGrid: true,- }),- { name: "captureArea" },- );-const setPendingState = (pending: boolean) =>- webview.emitTo("main", "cap-window://capture-area/state/pending", pending);+ // events.setCaptureAreaPending(webview).emitTo("main", pending);+ emitTo(webview, "setCaptureAreaPending", "main", pending);- let unlisten: () => void | undefined;onMount(async () => {setPendingState(true);- unlisten = await webview.onCloseRequested(() => setPendingState(false));+ const unlisten = await webview.onCloseRequested(() =>+ setPendingState(false),+ );+ onCleanup(() => unlisten());});- onCleanup(() => unlisten?.());- const [windowSize, setWindowSize] = createSignal({- x: window.innerWidth,- y: window.innerHeight,- });+ const [state, setState] = makePersisted(+ createStore<{+ snapToRatio: boolean;+ lastSelectedBounds: { screenId: DisplayId; bounds: CropBounds }[];+ }>({ snapToRatio: true, lastSelectedBounds: [] }),+ {+ name: "capture-area",+ },+ );- onMount(() => {- createEventListenerMap(window, {- resize: () =>- setWindowSize({ x: window.innerWidth, y: window.innerHeight }),- keydown: (e) => {- if (e.key === "Escape") close();- else if (e.key === "Enter") handleConfirm();- },- });+ createEventListener(window, "keydown", (e) => {+ if (e.key === "Escape") close();+ else if (e.key === "Enter") handleConfirm();});- const [crop, setCrop] = createStore<Crop>({- size: { x: 0, y: 0 },- position: { x: 0, y: 0 },+ let cropperRef: CropperRef | undefined;++ const [crop, setCrop] = createSignal(CROP_ZERO);++ const scheduled = createScheduled((fn) => debounce(fn, 50));++ const isValid = createMemo((p: boolean = true) => {+ const b = crop();+ return scheduled()+ ? b.width >= MIN_SIZE.width && b.height >= MIN_SIZE.height+ : p;});+ const { rawOptions, setOptions } = createOptionsQuery();+async function handleConfirm() {+ const currentBounds = cropperRef?.bounds();+ if (!currentBounds) throw new Error("Cropper not initialized");+ if (+ currentBounds.width < MIN_SIZE.width ||+ currentBounds.height < MIN_SIZE.height+ )+ return;+const target = rawOptions.captureTarget;if (target.variant !== "display") return;- setPendingState(false);+ const existingIndex = state.lastSelectedBounds?.findIndex(+ (item) => item.screenId === target.id,+ );++ if (existingIndex >= 0) {+ setState("lastSelectedBounds", existingIndex, {+ screenId: target.id,+ bounds: currentBounds,+ });+ } else {+ setState("lastSelectedBounds", [+ ...state.lastSelectedBounds,+ { screenId: target.id, bounds: currentBounds },+ ]);+ }++ const b = crop();setOptions("captureTarget",reconcile({variant: "area",screen: target.id,bounds: {- position: {- x: crop.position.x,- y: crop.position.y,- },- size: {- width: crop.size.x,- height: crop.size.y,- },+ position: { x: b.x, y: b.y },+ size: { width: b.width, height: b.height },},}),);@@ -90,55 +124,131 @@ export default function CaptureArea() {}, 250);}+ const [aspect, setAspect] = createSignal<Ratio | null>(null);++ function reset() {+ cropperRef?.reset();+ setAspect(null);++ const target = rawOptions.captureTarget;+ if (target.variant !== "display") return;+ setState("lastSelectedBounds", (values) =>+ values?.filter((v) => v.screenId !== target.id),+ );+ }++ async function showCropOptionsMenu(e: UIEvent, positionAtCursor = false) {+ e.preventDefault();+ const items = createCropOptionsMenuItems({+ aspect: aspect(),+ snapToRatioEnabled: state.snapToRatio,+ onAspectSet: setAspect,+ onSnapToRatioSet: (enabled) => setState("snapToRatio", enabled),+ });+ const menu = await Menu.new({ items });+ let pos: LogicalPosition | undefined;+ if (!positionAtCursor) {+ const rect = (e.target as HTMLDivElement).getBoundingClientRect();+ pos = new LogicalPosition(rect.x, rect.y + 50);+ }+ await menu.popup(pos);+ await menu.close();+ }+return (- <div class="overflow-hidden w-screen h-screen">+ <div class="overflow-hidden w-screen h-screen fixed"><div class="flex fixed z-50 justify-center items-center w-full"><Transitionappear- enterActiveClass="fade-in animate-in slide-in-from-top-6"- exitActiveClass="fade-out animate-out slide-out-to-top-6"+ enterClass="-translate-y-5 scale-75 opacity-0 blur-lg"+ enterActiveClass="duration-500 [transition-timing-function:cubic-bezier(0.175,0.885,0.12,1.175)]"+ enterToClass="translate-y-0 scale-100 opacity-100"+ exitClass="translate-y-0 scale-100 opacity-100"+ exitActiveClass="duration-500 [transition-timing-function:cubic-bezier(0.275,0.05,0.22,1.3)]"+ exitToClass="-translate-y-5 scale-75 opacity-0 blur-lg"><Show when={visible()}>- <div class="transition-all ease-out duration-200 absolute w-auto h-10 bg-gray-1 rounded-[12px] drop-shadow-2xl overflow-visible border border-gray-3 outline outline-1 outline-gray-6 flex justify-around p-1 top-11">+ <div+ class="scale-100 flex items-center p-1 gap-2 absolute w-auto h-14 rounded-full top-12"+ classList={{ "flex-row-reverse": ostype() === "windows" }}+ ><button- class="py-[0.25rem] px-2 text-gray-11 gap-[0.25rem] flex flex-row items-center rounded-[8px] ml-0 right-auto"+ title="Close"+ class="group flex items-center justify-center size-12 text-gray-11 shadow-xl shadow-black/30 bg-gray-1 border border-gray-5 hover:bg-gray-4 active:bg-gray-6 rounded-full transition-colors duration-200 cursor-default"type="button"onClick={close}>- <IconCapCircleX class="size-5" />+ <IconLucideX class="group-active:scale-90 transition-transform size-5 *:pointer-events-none" /></button>- <Tooltip.Root openDelay={500}>- <Tooltip.Trigger tabIndex={-1}>+ <div class="flex items-center h-full gap-2">+ <div class="flex items-center justify-between gap-1 px-[3px] size-full shadow-xl shadow-black/30 bg-gray-1 border border-gray-5 rounded-full">+ <button+ title="Reset"+ type="button"+ class="group flex items-center justify-center size-10 text-gray-11 hover:bg-gray-5 active:bg-gray-6 rounded-full transition-colors duration-200 cursor-default"+ onClick={reset}+ >+ <IconLucideRotateCcw class="group-active:scale-90 transition-transform size-5 *:pointer-events-none" />+ </button>+ <div class="inline-block my-3 w-[1px] self-stretch bg-gray-3" />+ <button+ title="Fill"+ class="group flex items-center justify-center size-10 text-gray-11 hover:bg-gray-5 active:bg-gray-6 rounded-full transition-colors duration-200 cursor-default"+ type="button"+ onClick={() => cropperRef?.fill()}+ >+ <IconLucideExpand class="group-active:scale-90 transition-transform size-5 *:pointer-events-none" />+ </button>+ <div class="inline-block my-3 w-[1px] self-stretch bg-gray-3" />+ <button+ title="Aspect Ratio"+ class="group flex items-center justify-center size-10 text-gray-11 hover:bg-gray-5 active:bg-gray-6 rounded-full transition-colors duration-200 cursor-default"+ type="button"+ onMouseDown={showCropOptionsMenu}+ onClick={showCropOptionsMenu}+ >+ <div class="relative size-5 pointer-events-none">+ <Show when={!aspect()}>+ <IconLucideRatio class="group-active:scale-90 transition-transform size-5 pointer-events-none *:pointer-events-none" />+ </Show>+ <Transition+ enterClass="scale-50 opacity-0 blur-md"+ enterActiveClass="duration-200 [transition-timing-function:cubic-bezier(0.215,0.61,0.355,1)]"+ enterToClass="scale-100 opacity-100 blur-0"+ exitClass="opacity-0"+ exitActiveClass="duration-0"+ exitToClass="opacity-0"+ >+ <Show when={aspect()} keyed>+ {(ratio) => (+ <span class="absolute inset-0 flex items-center justify-center text-[13px] text font-medium leading-none tracking-tight text-blue-10 pointer-events-none">+ {ratio[0]}:{ratio[1]}+ </span>+ )}+ </Show>+ </Transition>+ </div>+ </button>+ </div>++ <div class="h-full transition-all duration-300 ease-out"><button- class={`py-[0.25rem] px-2 gap-[0.25rem] mr-2 hover:bg-gray-3 flex flex-row items-center rounded-[8px] transition-colors duration-200 ${- state.showGrid- ? "bg-gray-3 text-blue-9"- : "text-gray-12 opacity-50"- }`}+ class="group flex items-center justify-center px-3 h-full min-w-28 border border-gray-5 rounded-full gap-2 text-blue-10 disabled:text-gray-10 bg-gray-1 shadow-xl shadow-black/30 duration-200 enabled:hover:bg-blue-2 enabled:hover:border-blue-5 enabled:active:bg-blue-3 disabled:opacity-90 disabled:cursor-not-allowed disabled:bg-gray-3 disabled:border-gray-4 cursor-default"type="button"- onClick={() => setState("showGrid", (v) => !v)}+ disabled={!isValid()}+ onClick={handleConfirm}>- <IconCapPadding class="size-5" />+ <div+ class="flex gap-2"+ classList={{+ "group-active:scale-95 transition-transform": isValid(),+ }}+ >+ <IconLucideCheck class="size-5 *:pointer-events-none" />+ <span class="font-medium text-sm">Confirm</span>+ </div></button>- </Tooltip.Trigger>- <Tooltip.Portal>- <Tooltip.Content class="z-50 px-2 py-1 text-xs rounded shadow-lg duration-500 delay-1000 text-gray-1 bg-gray-12 animate-in fade-in">- Rule of Thirds- <Tooltip.Arrow class="fill-gray-12" />- </Tooltip.Content>- </Tooltip.Portal>- </Tooltip.Root>- <div class="flex flex-row flex-grow gap-2 justify-center">- <button- class="text-blue-9 px-2 gap-[0.25rem] hover:bg-blue-3 flex flex-row items-center rounded-[8px] grow justify-center transition-colors duration-200"- type="button"- onClick={handleConfirm}- >- <IconCapCircleCheck class="size-5" />- <span class="font-[500] text-[0.875rem]">- Confirm selection- </span>- </button>+ </div></div></div></Show>@@ -147,16 +257,25 @@ export default function CaptureArea() {<Transitionappear- enterActiveClass="fade-in animate-in"+ enterActiveClass="fade-in animate-in duration-500"exitActiveClass="fade-out animate-out"><Show when={visible()}><Cropper- class="transition-all duration-200"- value={crop}+ ref={cropperRef}+ aspectRatio={aspect() ?? undefined}+ showBounds={true}onCropChange={setCrop}- showGuideLines={state.showGrid}- mappedSize={{ x: windowSize().x, y: windowSize().y }}+ snapToRatioEnabled={state.snapToRatio}+ initialCrop={() => {+ const target = rawOptions.captureTarget;+ if (target.variant === "display")+ return state.lastSelectedBounds?.find(+ (m) => m.screenId === target.id,+ )?.bounds;+ else return undefined;+ }}+ onContextMenu={(e) => showCropOptionsMenu(e, true)}/></Show></Transition>diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsxindex f07cd4761..2e72ed3bc 100644--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx@@ -1037,9 +1037,7 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) {},};- const generalSettings = generalSettingsStore.createQuery();- const hapticsEnabled = () =>- generalSettings.data?.hapticsEnabled && ostype() === "macos";+ const hapticsEnabled = ostype() === "macos";return (<KTabs.Content value={TAB_IDS.background} class="flex flex-col gap-6">@@ -1576,14 +1574,14 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) {if (!moveEvent.shiftKey &&- hapticsEnabled() &&+ hapticsEnabled &&project.background.source.type ==="gradient" &&project.background.source.angle !== newAngle) {commands.performHapticFeedback(- "Alignment",- "Now",+ "alignment",+ "now",);}diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsxindex 6bdf7466d..38020839e 100644--- a/apps/desktop/src/routes/editor/Editor.tsx+++ b/apps/desktop/src/routes/editor/Editor.tsx@@ -1,10 +1,12 @@import { Button } from "@cap/ui-solid";+import { NumberField } from "@kobalte/core/number-field";import { trackDeep } from "@solid-primitives/deep";import { throttle } from "@solid-primitives/scheduled";import { makePersisted } from "@solid-primitives/storage";import { createMutation } from "@tanstack/solid-query";import { convertFileSrc } from "@tauri-apps/api/core";-import { cx } from "cva";+import { LogicalPosition } from "@tauri-apps/api/dpi";+import { Menu } from "@tauri-apps/api/menu";import {createEffect,createMemo,@@ -15,12 +17,19 @@ import {Switch,} from "solid-js";import { createStore } from "solid-js/store";--import Cropper, { cropToFloor } from "~/components/Cropper";+import { Transition } from "solid-transition-group";+import {+ CROP_ZERO,+ type CropBounds,+ Cropper,+ type CropperRef,+ createCropOptionsMenuItems,+ type Ratio,+} from "~/components/Cropper";import { Toggle } from "~/components/Toggle";-import Tooltip from "~/components/Tooltip";+import { composeEventHandlers } from "~/utils/composeEventHandlers";import { createTauriEventListener } from "~/utils/createEventListener";-import { type Crop, events } from "~/utils/tauri";+import { events } from "~/utils/tauri";import { ConfigSidebar } from "./ConfigSidebar";import {EditorContextProvider,@@ -114,7 +123,7 @@ function Inner() {<><Header /><div- class="flex overflow-y-hidden flex-col flex-1 min-h-0 gap-2 pb-4 w-full leading-5 animate-in fade-in"+ class="flex overflow-y-hidden flex-col flex-1 gap-2 pb-4 w-full min-h-0 leading-5 animate-in fade-in"data-tauri-drag-region><div class="flex overflow-hidden flex-col flex-1 min-h-0">@@ -293,20 +302,72 @@ function Dialogs() {{(dialog) => {const { setProject: setState, editorInstance } =useEditorContext();- const [crop, setCrop] = createStore<Crop>({- position: dialog().position,- size: dialog().size,- });- const [cropOptions, setCropOptions] = makePersisted(- createStore({- showGrid: false,- }),- { name: "cropOptionsState" },+ const display = editorInstance.recordings.segments[0].display;++ let cropperRef: CropperRef | undefined;+ const [crop, setCrop] = createSignal(CROP_ZERO);+ const [aspect, setAspect] = createSignal<Ratio | null>(null);++ const initialBounds = {+ x: dialog().position.x,+ y: dialog().position.y,+ width: dialog().size.x,+ height: dialog().size.y,+ };++ const [snapToRatio, setSnapToRatioEnabled] = makePersisted(+ createSignal(true),+ { name: "editorCropSnapToRatio" },);- const display = editorInstance.recordings.segments[0].display;+ async function showCropOptionsMenu(+ e: UIEvent,+ positionAtCursor = false,+ ) {+ e.preventDefault();+ const items = createCropOptionsMenuItems({+ aspect: aspect(),+ snapToRatioEnabled: snapToRatio(),+ onAspectSet: setAspect,+ onSnapToRatioSet: setSnapToRatioEnabled,+ });+ const menu = await Menu.new({ items });+ let pos: LogicalPosition | undefined;+ if (!positionAtCursor) {+ const rect = (+ e.target as HTMLDivElement+ ).getBoundingClientRect();+ pos = new LogicalPosition(rect.x, rect.y + 40);+ }+ await menu.popup(pos);+ await menu.close();+ }- const adjustedCrop = createMemo(() => cropToFloor(crop));+ function BoundInput(props: {+ field: keyof CropBounds;+ min?: number;+ max?: number;+ }) {+ return (+ <NumberField+ value={crop()[props.field]}+ minValue={props.min}+ maxValue={props.max}+ onRawValueChange={(v) => {+ cropperRef?.setCropProperty(props.field, v);+ }}+ changeOnWheel={true}+ format={false}+ >+ <NumberField.Input+ class="rounded-[0.5rem] bg-gray-2 hover:ring-1 py-[18px] hover:ring-gray-5 h-[2rem] font-normal placeholder:text-black-transparent-40 text-xs caret-gray-500 transition-shadow duration-200 focus:ring-offset-1 focus:bg-gray-3 focus:ring-offset-gray-100 focus:ring-1 focus:ring-gray-10 px-[0.5rem] w-full text-[0.875rem] outline-none text-gray-12"+ onKeyDown={composeEventHandlers<HTMLInputElement>([+ (e) => e.stopPropagation(),+ ])}+ />+ </NumberField>+ );+ }return (<>@@ -315,109 +376,78 @@ function Dialogs() {<div class="flex flex-row items-center space-x-[0.75rem] text-gray-11"><span>Size</span><div class="w-[3.25rem]">- <Input- class="bg-transparent dark:!text-[#ababab]"- value={adjustedCrop().size.x}- onChange={(e) =>- setCrop((c) => ({- ...c,- size: {- ...c.size,- x: Number(e.currentTarget.value),- },- }))- }- />+ <BoundInput field="width" max={display.width} /></div>- <span>x</span>+ <span>×</span><div class="w-[3.25rem]">- <Input- class="bg-transparent dark:!text-[#ababab]"- value={adjustedCrop().size.y}- onChange={(e) =>- setCrop((c) => ({- ...c,- size: {- ...c.size,- y: Number(e.currentTarget.value),- },- }))- }- />+ <BoundInput field="height" max={display.height} /></div></div><div class="flex flex-row items-center space-x-[0.75rem] text-gray-11"><span>Position</span><div class="w-[3.25rem]">- <Input- class="bg-transparent dark:!text-[#ababab]"- value={adjustedCrop().position.x}- onChange={(e) =>- setCrop((c) => ({- ...c,- position: {- ...c.position,- x: Number(e.currentTarget.value),- },- }))- }- />+ <BoundInput field="x" /></div>- <span>x</span>+ <span>×</span><div class="w-[3.25rem]">- <Input- class="w-[3.25rem] bg-transparent dark:!text-[#ababab]"- value={adjustedCrop().position.y}- onChange={(e) =>- setCrop((c) => ({- ...c,- position: {- ...c.position,- y: Number(e.currentTarget.value),- },- }))- }- />+ <BoundInput field="y" /></div></div></div><div class="flex flex-row gap-3 justify-end items-center w-full">- <div class="flex flex-row items-center space-x-[0.5rem] text-gray-11">- <Tooltip content="Rule of Thirds">- <Button- variant="gray"- size="xs"- class={cx(- "flex items-center justify-center text-center rounded-full h-[2rem] w-[2rem] border text-[0.875rem] focus:border-blue-9",- cropOptions.showGrid- ? "border-blue-9"- : "border-transparent",- )}- onClick={() =>- setCropOptions("showGrid", (s) => !s)- }+ <div class="flex flex-row items-center space-x-[0.5rem] text-gray-11"></div>++ <Button+ variant="white"+ size="xs"+ class="flex items-center justify-center text-center rounded-full h-[2rem] w-[2rem] border focus:border-blue-9"+ onMouseDown={showCropOptionsMenu}+ onClick={showCropOptionsMenu}+ >+ <div class="relative pointer-events-none size-4">+ <Show when={!aspect()}>+ <IconLucideRatio class="group-active:scale-90 transition-transform size-4 pointer-events-none *:pointer-events-none" />+ </Show>+ <Transition+ enterClass="scale-50 opacity-0 blur-md"+ enterActiveClass="duration-200 [transition-timing-function:cubic-bezier(0.215,0.61,0.355,1)]"+ enterToClass="scale-100 opacity-100 blur-0"+ exitClass="opacity-0"+ exitActiveClass="duration-0"+ exitToClass="opacity-0">- <IconCapPadding- class={cx(- "w-4",- cropOptions.showGrid- ? "text-blue-9"- : "text-gray-12",+ <Show when={aspect()} keyed>+ {(ratio) => (+ <span class="flex absolute inset-0 justify-center items-center text-xs font-medium tracking-tight leading-none pointer-events-none text text-blue-10">+ {ratio[0]}:{ratio[1]}+ </span>)}- />- </Button>- </Tooltip>- </div>+ </Show>+ </Transition>+ </div>+ </Button>++ <EditorButton+ leftIcon={<IconLucideMaximize />}+ onClick={() => cropperRef?.fill()}+ disabled={+ crop().width === display.width &&+ crop().height === display.height+ }+ >+ Full+ </EditorButton><EditorButtonleftIcon={<IconCapCircleX />}- onClick={() =>- setCrop({- position: { x: 0, y: 0 },- size: {- x: display.width,- y: display.height,- },- })+ onClick={() => {+ cropperRef?.reset();+ setAspect(null);+ }}+ disabled={+ crop().x === dialog().position.x &&+ crop().y === dialog().position.y &&+ crop().width === dialog().size.x &&+ crop().height === dialog().size.y}>Reset@@ -426,15 +456,17 @@ function Dialogs() {</Dialog.Header><Dialog.Content><div class="flex flex-row justify-center">- <div class="overflow-hidden rounded divide-black-transparent-10">+ <div class="rounded divide-black-transparent-10"><Cropper- value={crop}+ ref={cropperRef}onCropChange={setCrop}- mappedSize={{- x: display.width,- y: display.height,- }}- showGuideLines={cropOptions.showGrid}+ aspectRatio={aspect() ?? undefined}+ targetSize={{ x: display.width, y: display.height }}+ initialCrop={initialBounds}+ snapToRatioEnabled={snapToRatio()}+ useBackdropFilter={true}+ allowLightMode={true}+ onContextMenu={(e) => showCropOptionsMenu(e, true)}><imgclass="shadow pointer-events-none max-h-[70vh]"@@ -450,7 +482,17 @@ function Dialogs() {<Dialog.Footer><ButtononClick={() => {- setState("background", "crop", adjustedCrop());+ const bounds = crop();+ setState("background", "crop", {+ position: {+ x: bounds.x,+ y: bounds.y,+ },+ size: {+ x: bounds.width,+ y: bounds.height,+ },+ });setDialog((d) => ({ ...d, open: false }));}}>diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsxindex 79f8820ae..36a593c72 100644--- a/apps/desktop/src/routes/editor/Player.tsx+++ b/apps/desktop/src/routes/editor/Player.tsx@@ -97,7 +97,7 @@ export function Player() {return total > 0 && total - editorState.playbackTime <= 0.1;};- const cropDialogHandler = () => {+ const cropDialogHandler = async () => {const display = editorInstance.recordings.segments[0].display;setDialog({open: true,@@ -112,6 +112,8 @@ export function Player() {}),},});+ await commands.stopPlayback();+ setEditorState("playing", false);};createEffect(() => {@@ -204,7 +206,7 @@ export function Player() {<AspectRatioSelect /><EditorButtontooltipText="Crop Video"- onClick={() => cropDialogHandler()}+ onClick={cropDialogHandler}leftIcon={<IconCapCrop class="w-5 text-gray-12" />}>Cropdiff --git a/apps/desktop/src/routes/target-select-overlay.tsx b/apps/desktop/src/routes/target-select-overlay.tsxindex ee540a3da..55b9cec22 100644--- a/apps/desktop/src/routes/target-select-overlay.tsx+++ b/apps/desktop/src/routes/target-select-overlay.tsx@@ -1,41 +1,44 @@import { Button } from "@cap/ui-solid";-import { makeBroadcastChannel } from "@solid-primitives/broadcast-channel";-import {- createEventListener,- createEventListenerMap,-} from "@solid-primitives/event-listener";-import { createWritableMemo } from "@solid-primitives/memo";+import { createEventListener } from "@solid-primitives/event-listener";+import { createElementSize } from "@solid-primitives/resize-observer";+import { createScheduled, debounce } from "@solid-primitives/scheduled";import { useSearchParams } from "@solidjs/router";-import { createQuery, useMutation } from "@tanstack/solid-query";+import { useQuery } from "@tanstack/solid-query";+import { LogicalPosition } from "@tauri-apps/api/dpi";import { emit } from "@tauri-apps/api/event";-import { CheckMenuItem, Menu, Submenu } from "@tauri-apps/api/menu";-import { cx } from "cva";import {- type ComponentProps,- createEffect,+ CheckMenuItem,+ Menu,+ MenuItem,+ PredefinedMenuItem,+} from "@tauri-apps/api/menu";+import { type as ostype } from "@tauri-apps/plugin-os";+import {createMemo,- createRoot,createSignal,- For,- type JSX,Match,mergeProps,onCleanup,- onMount,Show,Suspense,Switch,} from "solid-js";import { createStore, reconcile } from "solid-js/store";+import {+ CROP_ZERO,+ type CropBounds,+ Cropper,+ type CropperRef,+ createCropOptionsMenuItems,+ type Ratio,+} from "~/components/Cropper";import ModeSelect from "~/components/ModeSelect";import { authStore, generalSettingsStore } from "~/store";import { createOptionsQuery, createOrganizationsQuery } from "~/utils/queries";-import { handleRecordingResult } from "~/utils/recording";import {commands,type DisplayId,events,- Organization,type ScreenCaptureTarget,type TargetUnderCursor,} from "~/utils/tauri";@@ -44,18 +47,7 @@ import {useRecordingOptions,} from "./(window-chrome)/OptionsContext";-const MIN_WIDTH = 200;-const MIN_HEIGHT = 100;--const EMPTY_BOUNDS = () => ({- position: { x: 0, y: 0 },- size: { width: 0, height: 0 },-});--const DEFAULT_BOUNDS = {- position: { x: 100, y: 100 },- size: { width: 400, height: 300 },-};+const MIN_SIZE = { width: 150, height: 150 };const capitalize = (str: string) => {return str.charAt(0).toUpperCase() + str.slice(1);@@ -95,8 +87,8 @@ function Inner() {displayId: DisplayId;isHoveredDisplay: string;}>();- const isHoveredDisplay = params.isHoveredDisplay === "true";const [options, setOptions] = useOptions();+const [toggleModeSelect, setToggleModeSelect] = createSignal(false);const [targetUnderCursor, setTargetUnderCursor] =@@ -110,7 +102,7 @@ function Inner() {});onCleanup(() => unsubTargetUnderCursor.then((unsub) => unsub()));- const windowIcon = createQuery(() => ({+ const windowIcon = useQuery(() => ({queryKey: ["windowIcon", targetUnderCursor.window?.id],queryFn: async () => {if (!targetUnderCursor.window?.id) return null;@@ -122,7 +114,7 @@ function Inner() {staleTime: 5 * 60 * 1000, // Cache for 5 minutes}));- const displayInformation = createQuery(() => ({+ const displayInformation = useQuery(() => ({queryKey: ["displayId", params.displayId],queryFn: async () => {if (!params.displayId) return null;@@ -137,19 +129,12 @@ function Inner() {enabled: params.displayId !== undefined && options.targetMode === "display",}));- const [bounds, setBounds] = createStore(- structuredClone(isHoveredDisplay ? DEFAULT_BOUNDS : EMPTY_BOUNDS()),- );+ const [crop, setCrop] = createSignal<CropBounds>(CROP_ZERO);- const { postMessage, onMessage } = makeBroadcastChannel<{ type: "reset" }>(- "target_select_overlay",- );- createEventListener(window, "mousedown", () =>- postMessage({ type: "reset" }),- );- onMessage(() => setBounds(EMPTY_BOUNDS()));+ const [initialAreaBounds, setInitialAreaBounds] = createSignal<+ CropBounds | undefined+ >(undefined);- // We do this so any Cap window, (or external in the case of a bug) that are focused can trigger the close shortcutconst unsubOnEscapePress = events.onEscapePress.listen(() => {setOptions("targetMode", null);commands.closeTargetSelectOverlays();@@ -162,10 +147,10 @@ function Inner() {return (<Switch>- <Match when={options.targetMode === "display"}>- {(_) => (+ <Match when={options.targetMode === "display" && params.displayId}>+ {(displayId) => (<div- data-over={targetUnderCursor.display_id === params.displayId}+ data-over={targetUnderCursor.display_id === displayId()}class="relative w-screen h-screen flex flex-col items-center justify-center data-[over='true']:bg-blue-600/40 transition-colors"><div class="absolute inset-0 bg-black/50 -z-10" />@@ -201,7 +186,7 @@ function Inner() {<RecordingControlssetToggleModeSelect={setToggleModeSelect}- target={{ variant: "display", id: params.displayId! }}+ target={{ variant: "display", id: displayId() }}/><ShowCapFreeWarning isInstantMode={options.mode === "instant"} /></div>@@ -250,7 +235,6 @@ function Inner() {</span></div><RecordingControls- setToggleModeSelect={setToggleModeSelect}target={{variant: "window",id: windowUnderCursor.id,@@ -261,7 +245,12 @@ function Inner() {variant="dark"size="sm"onClick={() => {- setBounds(windowUnderCursor.bounds);+ setInitialAreaBounds({+ x: windowUnderCursor.bounds.position.x,+ y: windowUnderCursor.bounds.position.y,+ width: windowUnderCursor.bounds.size.width,+ height: windowUnderCursor.bounds.size.height,+ });setOptions({targetMode: "area",});@@ -278,571 +267,166 @@ function Inner() {)}</Show></Match>- <Match when={options.targetMode === "area"}>- {(_) => {- const [state, setState] = createSignal<- "creating" | "dragging" | undefined- >();-- // Initialize hasArea based on whether bounds have meaningful dimensions- const [hasArea, setHasArea] = createWritableMemo(- () => bounds.size.width > 0 && bounds.size.height > 0,- );- // Track whether the controls should be placed above the selection to avoid window bottom overflow+ <Match when={options.targetMode === "area" && params.displayId}>+ {(displayId) => {let controlsEl: HTMLDivElement | undefined;+ let cropperRef: CropperRef | undefined;- const [controlsHeight, setControlsHeight] = createSignal<- number | undefined- >(undefined);- const [controlsWidth, setControlsWidth] = createSignal<- number | undefined- >(undefined);-- // Determine the best placement for controls- const controlsPlacement = createMemo(() => {- const top = bounds.position.y;- const left = bounds.position.x;- const width = bounds.size.width;- const height = bounds.size.height;- // Measure controls dimensions (fallback if not yet mounted)- const ctrlH = controlsHeight() ?? 64;- const ctrlW = controlsWidth() ?? 300;- const margin = 16;-- // Check if selection spans full height (or nearly full height)- const isFullHeight = height >= window.innerHeight * 0.9;+ const [aspect, setAspect] = createSignal<Ratio | null>(null);+ const [snapToRatioEnabled, setSnapToRatioEnabled] =+ createSignal(true);- if (isFullHeight) {- // Try to place on the right side- const rightSpace = window.innerWidth - (left + width);- if (rightSpace >= ctrlW + margin)- return { position: "right" as const };+ const scheduled = createScheduled((fn) => debounce(fn, 30));- // Try to place on the left side- if (left >= ctrlW + margin) return { position: "left" as const };-- // Fall back to inside at the bottom- return { position: "inside-bottom" as const };- }-- // For non-full-height selections, use original logic- const wouldOverflow =- top + height + margin + ctrlH > window.innerHeight;- return { position: wouldOverflow ? "above" : "below" } as const;+ const isValid = createMemo((p: boolean = true) => {+ const b = crop();+ return scheduled()+ ? b.width >= MIN_SIZE.width && b.height >= MIN_SIZE.height+ : p;});- onMount(() => {- setControlsHeight(controlsEl?.offsetHeight);- setControlsWidth(controlsEl?.offsetWidth);- });- createEventListener(window, "resize", () => {- setControlsHeight(controlsEl?.offsetHeight);- setControlsWidth(controlsEl?.offsetWidth);- });-- function createOnMouseDown(- onDrag: (- startBounds: typeof bounds,- delta: { x: number; y: number },- ) => void,- ) {- return (downEvent: MouseEvent) => {- const startBounds = {- position: { ...bounds.position },- size: { ...bounds.size },- };-- let animationFrame: number | null = null;-- createRoot((dispose) => {- createEventListenerMap(window, {- mouseup: () => {- if (animationFrame) cancelAnimationFrame(animationFrame);- dispose();- },- mousemove: (moveEvent) => {- if (animationFrame) cancelAnimationFrame(animationFrame);-- animationFrame = requestAnimationFrame(() => {- onDrag(startBounds, {- x: moveEvent.clientX - downEvent.clientX, // Remove Math.max constraint- y: moveEvent.clientY - downEvent.clientY, // Remove Math.max constraint- });- });- },- });- });- };+ async function showCropOptionsMenu(e: UIEvent) {+ e.preventDefault();+ const items = [+ {+ text: "Reset selection",+ action: () => {+ cropperRef?.reset();+ setAspect(null);+ },+ },+ await PredefinedMenuItem.new({+ item: "Separator",+ }),+ ...createCropOptionsMenuItems({+ aspect: aspect(),+ snapToRatioEnabled: snapToRatioEnabled(),+ onAspectSet: setAspect,+ onSnapToRatioSet: setSnapToRatioEnabled,+ }),+ ];+ const menu = await Menu.new({ items });+ await menu.popup();+ await menu.close();}- function ResizeHandles() {- return (- <>- {/* Top Left Button */}- <ResizeHandle- class="cursor-nw-resize"- style={{- left: `${bounds.position.x + 1}px`,- top: `${bounds.position.y + 1}px`,- }}- onMouseDown={(e) => {- e.stopPropagation();- createOnMouseDown((startBounds, delta) => {- const width = startBounds.size.width - delta.x;- const limitedWidth = Math.max(width, MIN_WIDTH);-- const height = startBounds.size.height - delta.y;- const limitedHeight = Math.max(height, MIN_HEIGHT);-- setBounds({- position: {- x:- startBounds.position.x +- delta.x -- (limitedWidth - width),- y:- startBounds.position.y +- delta.y -- (limitedHeight - height),- },- size: {- width: limitedWidth,- height: limitedHeight,- },- });- })(e);- }}- />-- {/* Top Right Button */}- <ResizeHandle- class="cursor-ne-resize"- style={{- left: `${bounds.position.x + bounds.size.width - 1}px`,- top: `${bounds.position.y + 1}px`,- }}- onMouseDown={(e) => {- e.stopPropagation();- createOnMouseDown((startBounds, delta) => {- const width = startBounds.size.width + delta.x;- const limitedWidth = Math.max(width, MIN_WIDTH);-- const height = startBounds.size.height - delta.y;- const limitedHeight = Math.max(height, MIN_HEIGHT);-- setBounds({- position: {- x: startBounds.position.x,- y:- startBounds.position.y +- delta.y -- (limitedHeight - height),- },- size: {- width: limitedWidth,- height: limitedHeight,- },- });- })(e);- }}- />-- {/* Bottom Left Button */}- <ResizeHandle- class="cursor-sw-resize"- style={{- left: `${bounds.position.x + 1}px`,- top: `${bounds.position.y + bounds.size.height - 1}px`,- }}- onMouseDown={(e) => {- e.stopPropagation();- createOnMouseDown((startBounds, delta) => {- const width = startBounds.size.width - delta.x;- const limitedWidth = Math.max(width, MIN_WIDTH);-- const height = startBounds.size.height + delta.y;- const limitedHeight = Math.max(height, MIN_HEIGHT);-- setBounds({- position: {- x:- startBounds.position.x +- delta.x -- (limitedWidth - width),- y: startBounds.position.y,- },- size: {- width: limitedWidth,- height: limitedHeight,- },- });- })(e);- }}- />-- {/* Bottom Right Button */}- <ResizeHandle- class="cursor-se-resize"- style={{- left: `${bounds.position.x + bounds.size.width - 1}px`,- top: `${bounds.position.y + bounds.size.height - 1}px`,- }}- onMouseDown={(e) => {- e.stopPropagation();- createOnMouseDown((startBounds, delta) => {- const width = startBounds.size.width + delta.x;- const limitedWidth = Math.max(width, MIN_WIDTH);-- const height = startBounds.size.height + delta.y;- const limitedHeight = Math.max(height, MIN_HEIGHT);-- setBounds({- position: {- x: startBounds.position.x,- y: startBounds.position.y,- },- size: {- width: limitedWidth,- height: limitedHeight,- },- });- })(e);- }}- />-- {/* Top Edge Button */}- <ResizeHandle- class="cursor-n-resize"- style={{- left: `${bounds.position.x + bounds.size.width / 2}px`,- top: `${bounds.position.y + 1}px`,- }}- onMouseDown={(e) => {- e.stopPropagation();- createOnMouseDown((startBounds, delta) => {- const height = startBounds.size.height - delta.y;- const limitedHeight = Math.max(height, MIN_HEIGHT);-- setBounds({- position: {- x: startBounds.position.x,- y:- startBounds.position.y +- delta.y -- (limitedHeight - height),- },- size: {- width: startBounds.size.width,- height: limitedHeight,- },- });- })(e);- }}- />+ // Spacing rules:+ // Prefer below the crop (smaller margin)+ // If no space below, place above the crop (larger top margin)+ // Otherwise, place inside at the top of the crop (small inner margin)+ const macos = ostype() === "macos";+ const SIDE_MARGIN = 16;+ const MARGIN_BELOW = 16;+ const MARGIN_TOP_OUTSIDE = 16;+ const MARGIN_TOP_INSIDE = macos ? 40 : 28;+ const TOP_SAFE_MARGIN = macos ? 40 : 10; // keep clear of notch on MacBooks++ const controlsSize = createElementSize(() => controlsEl);+ const [controllerInside, _setControllerInside] = createSignal(false);++ // This is required due to the use of a ResizeObserver within the createElementSize function+ // Otherwise there will be an infinite loop: ResizeObserver loop completed with undelivered notifications.+ let raf: number | null = null;+ function setControllerInside(value: boolean) {+ if (raf) cancelAnimationFrame(raf);+ raf = requestAnimationFrame(() => _setControllerInside(value));+ }+ onCleanup(() => {+ if (raf) cancelAnimationFrame(raf);+ });- {/* Right Edge Button */}- <ResizeHandle- class="cursor-e-resize"- style={{- left: `${bounds.position.x + bounds.size.width - 1}px`,- top: `${bounds.position.y + bounds.size.height / 2}px`,- }}- onMouseDown={(e) => {- e.stopPropagation();- createOnMouseDown((startBounds, delta) => {- setBounds({- position: {- x: startBounds.position.x,- y: startBounds.position.y,- },- size: {- width: Math.max(- MIN_WIDTH,- startBounds.size.width + delta.x,- ),- height: startBounds.size.height,- },- });- })(e);- }}- />+ const controlsStyle = createMemo(() => {+ const bounds = crop();+ const size = controlsSize;+ if (!size?.width || !size?.height) return undefined;- {/* Bottom Edge Button */}- <ResizeHandle- class="cursor-s-resize"- style={{- left: `${bounds.position.x + bounds.size.width / 2}px`,- top: `${bounds.position.y + bounds.size.height - 1}px`,- }}- onMouseDown={(e) => {- e.stopPropagation();- createOnMouseDown((startBounds, delta) => {- setBounds({- position: {- x: startBounds.position.x,- y: startBounds.position.y,- },- size: {- width: startBounds.size.width,- height: Math.max(- MIN_HEIGHT,- startBounds.size.height + delta.y,- ),- },- });- })(e);- }}- />+ if (size.width === 0 || bounds.width === 0) {+ return { transform: "translate(-1000px, -1000px)" }; // Hide off-screen initially+ }- {/* Left Edge Button */}- <ResizeHandle- class="cursor-w-resize"- style={{- left: `${bounds.position.x + 1}px`,- top: `${bounds.position.y + bounds.size.height / 2}px`,- }}- onMouseDown={(e) => {- e.stopPropagation();- createOnMouseDown((startBounds, delta) => {- const width = startBounds.size.width - delta.x;- const limitedWidth = Math.max(MIN_WIDTH, width);+ const centerX = bounds.x + bounds.width / 2;+ let finalY: number;++ // Try below the crop+ const belowY = bounds.y + bounds.height + MARGIN_BELOW;+ if (belowY + size.height <= window.innerHeight) {+ finalY = belowY;+ setControllerInside(false);+ } else {+ // Try above the crop with a larger top margin+ const aboveY = bounds.y - size.height - MARGIN_TOP_OUTSIDE;+ if (aboveY >= TOP_SAFE_MARGIN) {+ finalY = aboveY;+ setControllerInside(false);+ } else {+ // Default to inside+ finalY = bounds.y + MARGIN_TOP_INSIDE;+ setControllerInside(true);+ }+ }- setBounds({- position: {- x:- startBounds.position.x +- delta.x -- (limitedWidth - width),- y: startBounds.position.y,- },- size: {- width: limitedWidth,- height: startBounds.size.height,- },- });- })(e);- }}- />- </>+ const finalX = Math.max(+ SIDE_MARGIN,+ Math.min(+ centerX - size.width / 2,+ window.innerWidth - size.width - SIDE_MARGIN,+ ),);- }- function Occluders() {- return (- <>- {/* Left */}- <div- class="absolute top-0 bottom-0 left-0 bg-black/50"- style={{ width: `${bounds.position.x}px` }}- />- {/* Right */}- <div- class="absolute top-0 right-0 bottom-0 bg-black/50"- style={{- width: `${- window.innerWidth -- (bounds.size.width + bounds.position.x)- }px`,- }}- />- {/* Top center */}- <div- class="absolute top-0 bg-black/50"- style={{- left: `${bounds.position.x}px`,- width: `${bounds.size.width}px`,- height: `${bounds.position.y}px`,- }}- />- {/* Bottom center */}- <div- class="absolute bottom-0 bg-black/50"- style={{- left: `${bounds.position.x}px`,- width: `${bounds.size.width}px`,- height: `${- window.innerHeight -- (bounds.size.height + bounds.position.y)- }px`,- }}- />- </>- );- }+ return {+ transform: `translate(${finalX}px, ${finalY}px)`,+ };+ });return (- <div- class="w-screen h-screen flex flex-col items-center justify-center data-[over='true']:bg-blue-600/40 transition-colors relative cursor-crosshair"- onMouseDown={(downEvent) => {- // Start creating a new area- downEvent.preventDefault();- postMessage({ type: "reset" });- setState("creating");- setHasArea(false);-- const startX = downEvent.clientX;- const startY = downEvent.clientY;-- setBounds({- position: { x: startX, y: startY },- size: { width: 0, height: 0 },- });-- createRoot((dispose) => {- createEventListenerMap(window, {- mousemove: (moveEvent) => {- const width = Math.abs(moveEvent.clientX - startX);- const height = Math.abs(moveEvent.clientY - startY);- const x = Math.min(startX, moveEvent.clientX);- const y = Math.min(startY, moveEvent.clientY);-- setBounds({- position: { x, y },- size: { width, height },- });- },- mouseup: () => {- setState(undefined);- // Only set hasArea if we created a meaningful area- if (bounds.size.width > 10 && bounds.size.height > 10) {- setHasArea(true);- } else {- // Reset to no area if too small- setBounds(EMPTY_BOUNDS());- }- dispose();- },- });- });- }}- >- <Occluders />-- <Show when={hasArea()}>- <div- class={cx(- "flex absolute flex-col items-center",- state() === "dragging" ? "cursor-grabbing" : "cursor-grab",- )}- style={{- width: `${bounds.size.width}px`,- height: `${bounds.size.height}px`,- left: `${bounds.position.x}px`,- top: `${bounds.position.y}px`,- }}- onMouseDown={(downEvent) => {- downEvent.stopPropagation();- setState("dragging");- const startPosition = { ...bounds.position };-- createRoot((dispose) => {- createEventListenerMap(window, {- mousemove: (moveEvent) => {- const newPosition = {- x:- startPosition.x +- moveEvent.clientX -- downEvent.clientX,- y:- startPosition.y +- moveEvent.clientY -- downEvent.clientY,- };-- if (newPosition.x < 0) newPosition.x = 0;- if (newPosition.y < 0) newPosition.y = 0;- if (- newPosition.x + bounds.size.width >- window.innerWidth- )- newPosition.x =- window.innerWidth - bounds.size.width;- if (- newPosition.y + bounds.size.height >- window.innerHeight- )- newPosition.y =- window.innerHeight - bounds.size.height;-- setBounds("position", newPosition);- },- mouseup: () => {- setState(undefined);- dispose();- },- });- });- }}+ <div class="fixed w-screen h-screen">+ <div+ ref={controlsEl}+ class="fixed z-50 transition-opacity"+ style={controlsStyle()}+ >+ <Show+ when={isValid()}+ fallback={+ <div>+ <div class="flex flex-col gap-1 items-center p-2.5 my-2 rounded-xl border min-w-fit w-fit bg-red-2 shadow-sm border-red-4 text-sm">+ <p>Minimum size is 150 x 150</p>+ <small>+ <code>+ {crop().width} x {crop().height}+ </code>{" "}+ is too small+ </small>+ </div>+ </div>+ }>- <div- ref={controlsEl}- class={cx(- "flex absolute flex-col items-center m-2",- controlsPlacement().position === "above" && "bottom-full",- controlsPlacement().position === "below" && "top-full",- controlsPlacement().position === "right" &&- "left-full top-1/2 -translate-y-1/2",- controlsPlacement().position === "left" &&- "right-full top-1/2 -translate-y-1/2",- controlsPlacement().position === "inside-bottom" &&- "bottom-2 left-1/2 -translate-x-1/2",- )}- style={{- width:- controlsPlacement().position === "right" ||- controlsPlacement().position === "left"- ? "auto"- : controlsPlacement().position === "inside-bottom"- ? "auto"- : `${bounds.size.width}px`,+ <RecordingControls+ target={{+ variant: "area",+ screen: displayId(),+ bounds: {+ position: { x: crop().x, y: crop().y },+ size: { width: crop().width, height: crop().height },+ },}}- >- <RecordingControls- target={{- variant: "area",- screen: params.displayId!,- bounds,- }}- setToggleModeSelect={setToggleModeSelect}- showBackground={- controlsPlacement().position === "inside-bottom"- }- />- <ShowCapFreeWarning- isInstantMode={options.mode === "instant"}- />- </div>- </div>-- <ResizeHandles />- </Show>-- <Show when={state() === "creating"}>- <div- class="absolute border-2 border-blue-500 bg-blue-500/20 pointer-events-none"- style={{- left: `${bounds.position.x}px`,- top: `${bounds.position.y}px`,- width: `${bounds.size.width}px`,- height: `${bounds.size.height}px`,- }}- />- </Show>-- <Show when={!state()}>- <Show when={!hasArea()}>- <p class="z-10 text-xl pointer-events-none text-white">- Click and drag to select area- </p>+ showBackground={controllerInside()}+ />+ <ShowCapFreeWarning+ isInstantMode={options.mode === "instant"}+ /></Show>- <Show when={hasArea()}>- <Show when={controlsPlacement().position !== "inside-bottom"}>- <p class="z-10 text-xl pointer-events-none text-white absolute bottom-4">- Click and drag to create new area- </p>- </Show>- </Show>- </Show>+ </div>++ <Cropper+ ref={cropperRef}+ onCropChange={setCrop}+ initialCrop={initialAreaBounds()}+ showBounds={isValid()}+ aspectRatio={aspect() ?? undefined}+ snapToRatioEnabled={snapToRatioEnabled()}+ onContextMenu={(e) => showCropOptionsMenu(e)}+ /></div>);}}@@ -857,16 +441,10 @@ function RecordingControls(props: {showBackground?: boolean;}) {const auth = authStore.createQuery();- const [options, setOptions] = useOptions();+ const { setOptions, rawOptions } = useRecordingOptions();const generalSetings = generalSettingsStore.createQuery();- const isAreaTooSmall = () => {- if (props.target.variant !== "area") return false;- const { width, height } = props.target.bounds.size;- return width < MIN_WIDTH || height < MIN_HEIGHT;- };-const menuModes = async () =>await Menu.new({items: [@@ -875,82 +453,64 @@ function RecordingControls(props: {action: () => {setOptions("mode", "studio");},- checked: options.mode === "studio",+ checked: rawOptions.mode === "studio",}),await CheckMenuItem.new({text: "Instant Mode",action: () => {setOptions("mode", "instant");},- checked: options.mode === "instant",+ checked: rawOptions.mode === "instant",}),],});- const countdownMenu = async () =>- await Submenu.new({- text: "Recording Countdown",+ const countdownItems = async () => [+ await CheckMenuItem.new({+ text: "Off",+ action: () => generalSettingsStore.set({ recordingCountdown: 0 }),+ checked:+ !generalSetings.data?.recordingCountdown ||+ generalSetings.data?.recordingCountdown === 0,+ }),+ await CheckMenuItem.new({+ text: "3 seconds",+ action: () => generalSettingsStore.set({ recordingCountdown: 3 }),+ checked: generalSetings.data?.recordingCountdown === 3,+ }),+ await CheckMenuItem.new({+ text: "5 seconds",+ action: () => generalSettingsStore.set({ recordingCountdown: 5 }),+ checked: generalSetings.data?.recordingCountdown === 5,+ }),+ await CheckMenuItem.new({+ text: "10 seconds",+ action: () => generalSettingsStore.set({ recordingCountdown: 10 }),+ checked: generalSetings.data?.recordingCountdown === 10,+ }),+ ];++ const preRecordingMenu = async () => {+ return await Menu.new({items: [- await CheckMenuItem.new({- text: "Off",- action: () => generalSettingsStore.set({ recordingCountdown: 0 }),- checked:- !generalSetings.data?.recordingCountdown ||- generalSetings.data?.recordingCountdown === 0,- }),- await CheckMenuItem.new({- text: "3 seconds",- action: () => generalSettingsStore.set({ recordingCountdown: 3 }),- checked: generalSetings.data?.recordingCountdown === 3,- }),- await CheckMenuItem.new({- text: "5 seconds",- action: () => generalSettingsStore.set({ recordingCountdown: 5 }),- checked: generalSetings.data?.recordingCountdown === 5,- }),- await CheckMenuItem.new({- text: "10 seconds",- action: () => generalSettingsStore.set({ recordingCountdown: 10 }),- checked: generalSetings.data?.recordingCountdown === 10,+ await MenuItem.new({+ text: "Recording Countdown",+ enabled: false,}),+ ...(await countdownItems()),],});-- const preRecordingMenu = async () => {- return await Menu.new({ items: [await countdownMenu()] });};- const startRecording = useMutation(() => ({- mutationFn: () =>- handleRecordingResult(- commands.startRecording({- capture_target: props.target,- mode: options.mode,- capture_system_audio: options.captureSystemAudio,- organization_id: options.organizationId ?? null,- }),- setOptions,- ),- }));+ function showMenu(menu: Promise<Menu>, e: UIEvent) {+ e.stopPropagation();+ const rect = (e.target as HTMLDivElement).getBoundingClientRect();+ menu.then((menu) => menu.popup(new LogicalPosition(rect.x, rect.y + 40)));+ }return (- <Show- when={!isAreaTooSmall()}- fallback={- <div class="flex flex-col gap-2 items-center p-2 my-2.5 rounded-xl border w-52 bg-red-500/80 border-red-500/60 text-white">- <div class="flex gap-2 items-center">- <IconCapInfo class="will-change-transform size-4" />- <p class="text-sm font-medium">Area Too Small</p>- </div>- <p class="text-xs text-center tabular-nums">- Selection must be at least {MIN_WIDTH}x{MIN_HEIGHT} pixels- {props.target.variant === "area" &&- ` (currently ${props.target.bounds.size.width}x${props.target.bounds.size.height})`}- </p>- </div>- }- >- <div class="flex gap-2.5 items-center p-2.5 my-2.5 rounded-xl border min-w-fit w-fit bg-gray-2 border-gray-4">+ <>+ <div class="flex gap-2.5 items-center p-2.5 my-2.5 rounded-xl border min-w-fit w-fit bg-gray-2 shadow-sm border-gray-4"><divonClick={() => {setOptions("targetMode", null);@@ -961,131 +521,72 @@ function RecordingControls(props: {<IconCapX class="invert will-change-transform size-3 dark:invert-0" /></div><div- data-inactive={- (options.mode === "instant" && !auth.data) ||- startRecording.isPending- }- class="flex overflow-hidden flex-row h-11 rounded-full bg-blue-9 text-white group data-[inactive='true']:bg-blue-8 data-[inactive='true']:text-white/80"+ data-inactive={rawOptions.mode === "instant" && !auth.data}+ class="flex overflow-hidden flex-row h-11 rounded-full bg-blue-9 group"onClick={() => {- if (options.mode === "instant" && !auth.data) {+ if (rawOptions.mode === "instant" && !auth.data) {emit("start-sign-in");return;}- if (startRecording.isPending) return;- startRecording.mutate();+ commands.startRecording({+ capture_target: props.target,+ mode: rawOptions.mode,+ capture_system_audio: rawOptions.captureSystemAudio,+ });}}>- <div- class={cx(- "flex items-center py-1 pl-4 transition-colors",- !startRecording.isPending && "hover:bg-blue-10",- )}- >- {options.mode === "studio" ? (+ <div class="flex items-center py-1 pl-4 transition-colors hover:bg-blue-10">+ {rawOptions.mode === "studio" ? (<IconCapFilmCut class="size-4" />) : (<IconCapInstant class="size-4" />)}<div class="flex flex-col mr-2 ml-3">- <span class="text-sm font-medium text-nowrap">- {options.mode === "instant" && !auth.data+ <span class="text-sm font-medium text-white text-nowrap">+ {rawOptions.mode === "instant" && !auth.data? "Sign In To Use": "Start Recording"}</span>- <span class="text-xs flex items-center text-nowrap gap-1 transition-opacity duration-200 font-light -mt-0.5 opacity-90">- {`${capitalize(options.mode)} Mode`}+ <span class="text-xs flex items-center text-nowrap gap-1 transition-opacity duration-200 text-white font-light -mt-0.5 opacity-90">+ {`${capitalize(rawOptions.mode)} Mode`}</span></div></div><div- class={cx(- "pl-2.5 transition-colors pr-3 py-1.5 flex items-center",- !startRecording.isPending && "group-hover:bg-blue-10",- )}- onClick={(e) => {- e.stopPropagation();- menuModes().then((menu) => menu.popup());- }}+ class="pl-2.5 group-hover:bg-blue-10 transition-colors pr-3 py-1.5 flex items-center"+ onMouseDown={(e) => showMenu(menuModes(), e)}+ onClick={(e) => showMenu(menuModes(), e)}>- <IconCapCaretDown class="focus:rotate-90" />+ <IconCapCaretDown class="pointer-events-none focus:rotate-90" /></div></div><div- onClick={(e) => {- e.stopPropagation();- preRecordingMenu().then((menu) => menu.popup());- }}class="flex justify-center items-center rounded-full border transition-opacity bg-gray-6 text-gray-12 size-9 hover:opacity-80"+ onMouseDown={(e) => showMenu(preRecordingMenu(), e)}+ onClick={(e) => showMenu(preRecordingMenu(), e)}>- <IconCapGear class="will-change-transform size-5" />+ <IconCapGear class="pointer-events-none will-change-transform size-5" /></div></div>- <div class="flex flex-col items-center gap-2">- <button+ <div class="flex justify-center items-center w-full">+ <divonClick={() => props.setToggleModeSelect?.(true)}- class="cursor-pointer flex gap-1 items-center transition-all duration-200 relative z-20"+ class="flex gap-1 justify-center items-center self-center mb-5 transition-opacity duration-200 w-fit hover:opacity-60"classList={{- "bg-black/40 p-2 rounded-lg backdrop-blur-sm border border-white/10 hover:bg-black/50 hover:opacity-80":+ "bg-black/50 p-2 rounded-lg border border-white/10 hover:bg-black/50 hover:opacity-80":props.showBackground,"hover:opacity-60": !props.showBackground,}}><IconCapInfo class="opacity-70 will-change-transform size-3" />- <p class="text-sm text-white">+ <p class="text-sm text-white drop-shadow-md"><span class="opacity-70">What is </span>- <span class="font-medium">{capitalize(options.mode)} Mode</span>?+ <span class="font-medium">{capitalize(rawOptions.mode)} Mode</span>?</p>- </button>- <OrganizationSelect />- </div>- </Show>- );-}--function OrganizationSelect(props: { showBackground?: boolean }) {- const organisations = createOrganizationsQuery();- const [options, setOptions] = useOptions();-- return (- <Show when={organisations().length > 1}>- <button- class="flex gap-1 items-center mb-5 group hover:opacity-60 transition-opacity duration-200"- classList={{- "bg-black/40 p-2 rounded-lg backdrop-blur-sm border border-white/10":- props.showBackground,- }}- onClick={async () => {- const menu = await Menu.new({- items: await Promise.all(- organisations().map((org) =>- CheckMenuItem.new({- text: org.name,- action: () => {- setOptions("organizationId", org.id);- },- checked: options.organizationId === org.id,- }),- ),- ),- });- menu.popup();- }}- >- <div class="text-sm text-white flex flex-row">- <span class="opacity-70">Organization:</span>- <span class="ml-1 flex flex-row ">- {- (- organisations().find((o) => o.id === options.organizationId) ??- organisations()[0]- )?.name- }- <IconCapChevronDown />- </span></div>- </button>- </Show>+ </div>+ </>);}@@ -1095,7 +596,7 @@ function ShowCapFreeWarning(props: { isInstantMode: boolean }) {return (<Suspense><Show when={props.isInstantMode && auth.data?.plan?.upgraded === false}>- <p class="text-sm text-center text-white max-w-64">+ <p class="text-sm text-center max-w-64">Instant Mode recordings are limited to 5 mins,{" "}<buttonclass="underline"@@ -1108,20 +609,3 @@ function ShowCapFreeWarning(props: { isInstantMode: boolean }) {</Suspense>);}--function ResizeHandle(- props: Omit<ComponentProps<"button">, "style"> & {- style?: JSX.CSSProperties;- },-) {- return (- <button- {...props}- class={cx(- "size-3 bg-black rounded-full absolute border-[1.2px] border-white",- props.class,- )}- style={{ ...props.style, transform: "translate(-50%, -50%)" }}- />- );-}diff --git a/apps/desktop/src/routes/window-capture-occluder.tsx b/apps/desktop/src/routes/window-capture-occluder.tsxindex d1ecc3575..962be1f9e 100644--- a/apps/desktop/src/routes/window-capture-occluder.tsx+++ b/apps/desktop/src/routes/window-capture-occluder.tsx@@ -1,6 +1,5 @@import { getAllWindows } from "@tauri-apps/api/window";import { Show, Suspense } from "solid-js";-import CropAreaRenderer from "~/components/CropAreaRenderer";import { createCurrentRecordingQuery } from "~/utils/queries";export default function () {@@ -35,10 +34,43 @@ export default function () {);return (- <CropAreaRenderer- bounds={bounds()}- // no border radius as that should be added in editor- />+ <div class="size-full absolute inset-0 *:absolute *:bg-black/50 *:pointer-events-none">+ {(() => {+ const { size, position } = bounds();+ return (+ <>+ {/* Top blind */}+ <div+ class="top-0 left-0 w-full"+ style={{ height: `${position.y}px` }}+ />+ {/* Bottom blind */}+ <div+ class="left-0 bottom-0 w-full"+ style={{ top: `${position.y + size.height}px` }}+ />+ {/* Left blind */}+ <div+ class="left-0"+ style={{+ top: `${position.y}px`,+ width: `${position.x}px`,+ height: `${size.height}px`,+ }}+ />+ {/* Right blind */}+ <div+ class="right-0"+ style={{+ top: `${position.y}px`,+ left: `${position.x + size.width}px`,+ height: `${size.height}px`,+ }}+ />+ </>+ );+ })()}+ </div>);}}</Show>diff --git a/apps/desktop/src/utils/box.ts b/apps/desktop/src/utils/box.tsdeleted file mode 100644index 2eba426b0..000000000--- a/apps/desktop/src/utils/box.ts+++ /dev/null@@ -1,187 +0,0 @@-// Attribution to area-selection (MIT License) by 7anshuai-// https://github.com/7anshuai/area-selection--type XY = { x: number; y: number };--export type Bounds = { size: XY; position: XY };--export default class Box {- x: number;- y: number;- width: number;- height: number;-- private constructor(x: number, y: number, width: number, height: number) {- this.x = x;- this.y = y;- this.width = width;- this.height = height;- }-- static from(position: XY, size: XY): Box {- return new Box(position.x, position.y, size.x, size.y);- }-- toBounds(): Bounds {- return {- position: { x: this.x, y: this.y },- size: { x: this.width, y: this.height },- };- }-- resize(newWidth: number, newHeight: number, origin: XY): Box {- const fromX = this.x + this.width * origin.x;- const fromY = this.y + this.height * origin.y;-- this.x = fromX - newWidth * origin.x;- this.y = fromY - newHeight * origin.y;- this.width = newWidth;- this.height = newHeight;-- return this;- }-- scale(factor: number, origin: XY): Box {- const newWidth = this.width * factor;- const newHeight = this.height * factor;- return this.resize(newWidth, newHeight, origin);- }-- move(x: number | null, y: number | null): Box {- if (x !== null) {- this.x = x;- }- if (y !== null) {- this.y = y;- }- return this;- }-- getAbsolutePoint(point: XY): XY {- return {- x: this.x + this.width * point.x,- y: this.y + this.height * point.y,- };- }-- constrainAll(box: Box, mapped: XY, origin: XY, aspectRatio?: number) {- if (aspectRatio) this.constrainToRatio(aspectRatio, origin);- this.constrainToBoundary(mapped.x, mapped.y, origin);- return box;- }-- constrainToRatio(- ratio: number,- origin: XY,- grow: "width" | "height" = "height",- ): Box {- if (!ratio) return this;-- switch (grow) {- case "height":- return this.resize(this.width, this.width / ratio, origin);- case "width":- return this.resize(this.height * ratio, this.height, origin);- default:- return this.resize(this.width, this.width / ratio, origin);- }- }-- constrainToBoundary(- boundaryWidth: number,- boundaryHeight: number,- origin: XY,- ): Box {- const originPoint = this.getAbsolutePoint(origin);-- const directionX = -2 * origin.x + 1;- const directionY = -2 * origin.y + 1;-- let maxWidth: number;- let maxHeight: number;-- switch (directionX) {- case -1:- maxWidth = originPoint.x;- break;- case 0:- maxWidth = Math.min(originPoint.x, boundaryWidth - originPoint.x) * 2;- break;- case 1:- maxWidth = boundaryWidth - originPoint.x;- break;- default:- maxWidth = boundaryWidth;- }-- switch (directionY) {- case -1:- maxHeight = originPoint.y;- break;- case 0:- maxHeight = Math.min(originPoint.y, boundaryHeight - originPoint.y) * 2;- break;- case 1:- maxHeight = boundaryHeight - originPoint.y;- break;- default:- maxHeight = boundaryHeight;- }-- if (this.width > maxWidth) {- const factor = maxWidth / this.width;- this.scale(factor, origin);- }- if (this.height > maxHeight) {- const factor = maxHeight / this.height;- this.scale(factor, origin);- }-- return this;- }-- constrainToSize(- maxWidth: number | null,- maxHeight: number | null,- minWidth: number | null,- minHeight: number | null,- origin: XY,- ratio: number | null = null,- ): Box {- if (ratio) {- if (ratio > 1) {- maxWidth = maxHeight ? maxHeight / ratio : maxWidth;- minHeight = minWidth ? minWidth * ratio : minHeight;- } else if (ratio < 1) {- maxHeight = maxWidth ? maxWidth * ratio : maxHeight;- minWidth = minHeight ? minHeight / ratio : minWidth;- }- }-- if (maxWidth && this.width > maxWidth) {- const newWidth = maxWidth;- const newHeight = ratio === null ? this.height : maxHeight!;- this.resize(newWidth, newHeight, origin);- }-- if (maxHeight && this.height > maxHeight) {- const newWidth = ratio === null ? this.width : maxWidth!;- const newHeight = maxHeight;- this.resize(newWidth, newHeight, origin);- }-- if (minWidth && this.width < minWidth) {- const newWidth = minWidth;- const newHeight = ratio === null ? this.height : minHeight!;- this.resize(newWidth, newHeight, origin);- }-- if (minHeight && this.height < minHeight) {- const newWidth = ratio === null ? this.width : minWidth!;- const newHeight = minHeight;- this.resize(newWidth, newHeight, origin);- }-- return this;- }-}diff --git a/apps/desktop/src/utils/canvas.ts b/apps/desktop/src/utils/canvas.tsdeleted file mode 100644index 8e069499a..000000000--- a/apps/desktop/src/utils/canvas.ts+++ /dev/null@@ -1,71 +0,0 @@-/**- * Creates a high DPI canvas context and sets up a resize observer to handle- * redrawing the canvas when its size changes.- *- * @param canvas - The HTML canvas element to create the context for.- * @param drawOnResizeCallback - A callback function that is called whenever the canvas is resized.- * It receives the 2D rendering context as an argument.- * @returns An object containing the 2D rendering context and a cleanup function to disconnect the resize observer,- * or null if the context could not be obtained.- */-export function createHiDPICanvasContext(- canvas: HTMLCanvasElement,- drawOnResizeCallback: (ctx: CanvasRenderingContext2D) => void,-): {- ctx: CanvasRenderingContext2D;- cleanup: () => void;-} | null {- const ctx = canvas.getContext("2d");- if (!ctx) return null;- polyfillCanvasContextRoundRect();-- const scale = (rect: DOMRect) => {- const dpr = window.devicePixelRatio || 1;- canvas.width = rect.width * dpr;- canvas.height = rect.height * dpr;- ctx.scale(dpr, dpr);- drawOnResizeCallback(ctx);- };-- const observer = new ResizeObserver(([entry]) => scale(entry.contentRect));- observer.observe(canvas);-- return {- ctx,- cleanup: () => observer.disconnect(),- };-}--// TODO: May not be needed depending on the minimum macOS version.-// https://stackoverflow.com/questions/51232811/canvas-clearrect-with-rounded-corners-function polyfillCanvasContextRoundRect() {- if ("roundRect" in CanvasRenderingContext2D) return;- CanvasRenderingContext2D.prototype.roundRect = function (- x: number,- y: number,- w: number,- h: number,- radii?: number | DOMPointInit | Iterable<number | DOMPointInit>,- ) {- this.beginPath();- let radius = typeof radii === "number" ? radii : 0;-- if (typeof radii === "object") {- if (Symbol.iterator in radii) {- const radiiArray = Array.from(radii) as number[];- radius = radiiArray[0] || 0;- } else if ("x" in radii && "y" in radii) {- radius = radii.x!;- }- }-- const adjustedRadius = Math.min(radius, w / 2, h / 2);-- this.moveTo(x + adjustedRadius, y);- this.arcTo(x + w, y, x + w, y + h, adjustedRadius);- this.arcTo(x + w, y + h, x, y + h, adjustedRadius);- this.arcTo(x, y + h, x, y, adjustedRadius);- this.arcTo(x, y, x + w, y, adjustedRadius);- this.closePath();- };-}diff --git a/apps/desktop/src/utils/events.ts b/apps/desktop/src/utils/events.tsindex 7683d0a96..27bad5c6e 100644--- a/apps/desktop/src/utils/events.ts+++ b/apps/desktop/src/utils/events.ts@@ -1,8 +1,9 @@-import type { CreateQueryResult } from "@tanstack/solid-query";-import { onCleanup, onMount, type ResourceReturn } from "solid-js";+import { createEventListenerMap } from "@solid-primitives/event-listener";+import type { UseQueryResult } from "@tanstack/solid-query";+import { createSignal, onCleanup, onMount } from "solid-js";import { events } from "./tauri";-export function createQueryInvalidate<T extends CreateQueryResult>(+export function createQueryInvalidate<T extends UseQueryResult>(query: T,event: keyof typeof events,) {@@ -11,3 +12,24 @@ export function createQueryInvalidate<T extends CreateQueryResult>(onCleanup(() => cleanup.then((c) => c()));});}++export function createKeyDownSignal(+ element: HTMLElement | Window,+ key: string,+) {+ const [isDown, setDown] = createSignal(false);++ createEventListenerMap(element, {+ keydown: (e) => {+ if (e.key === key) setDown(true);+ },+ keyup: (e) => {+ if (e.key === key) setDown(false);+ },+ blur: () => {+ setDown(false);+ },+ });++ return isDown;+}diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex bcf2824ad..0a0199912 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -313,6 +313,7 @@ requestOpenRecordingPicker: RequestOpenRecordingPicker,requestOpenSettings: RequestOpenSettings,requestScreenCapturePrewarm: RequestScreenCapturePrewarm,requestStartRecording: RequestStartRecording,+setCaptureAreaPending: SetCaptureAreaPending,targetUnderCursor: TargetUnderCursor,uploadProgressEvent: UploadProgressEvent}>({@@ -334,6 +335,7 @@ requestOpenRecordingPicker: "request-open-recording-picker",requestOpenSettings: "request-open-settings",requestScreenCapturePrewarm: "request-screen-capture-prewarm",requestStartRecording: "request-start-recording",+setCaptureAreaPending: "set-capture-area-pending",targetUnderCursor: "target-under-cursor",uploadProgressEvent: "upload-progress-event"})@@ -399,7 +401,7 @@ export type ExportSettings = ({ format: "Mp4" } & Mp4ExportSettings) | ({ formatexport type FileType = "recording" | "screenshot"export type Flags = { captions: boolean }export type FramesRendered = { renderedCount: number; totalFrames: number; type: "FramesRendered" }-export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; hapticsEnabled?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; custom_cursor_capture2?: boolean; serverUrl?: string; recordingCountdown?: number | null; enableNativeCameraPreview: boolean; autoZoomOnClicks?: boolean; enableNewRecordingFlow: boolean; postDeletionBehaviour?: PostDeletionBehaviour; excludedWindows?: WindowExclusion[]; deleteInstantRecordingsAfterUpload?: boolean; instantModeMaxResolution?: number }+export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; custom_cursor_capture2?: boolean; serverUrl?: string; recordingCountdown?: number | null; enableNativeCameraPreview: boolean; autoZoomOnClicks?: boolean; enableNewRecordingFlow: boolean; postDeletionBehaviour?: PostDeletionBehaviour; excludedWindows?: WindowExclusion[]; deleteInstantRecordingsAfterUpload?: boolean; instantModeMaxResolution?: number }export type GifExportSettings = { fps: number; resolution_base: XY<number>; quality: GifQuality | null }export type GifQuality = {/**@@ -410,8 +412,8 @@ quality: number | null;* Whether to prioritize speed over quality (default: false)*/fast: boolean | null }-export type HapticPattern = "Alignment" | "LevelChange" | "Generic"-export type HapticPerformanceTime = "Default" | "Now" | "DrawCompleted"+export type HapticPattern = "alignment" | "levelChange" | "generic"+export type HapticPerformanceTime = "default" | "now" | "drawCompleted"export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean; shift: boolean }export type HotkeyAction = "startStudioRecording" | "startInstantRecording" | "stopRecording" | "restartRecording" | "openRecordingPicker" | "openRecordingPickerDisplay" | "openRecordingPickerWindow" | "openRecordingPickerArea" | "other"export type HotkeysConfiguration = { show: boolean }@@ -465,6 +467,7 @@ export type SceneSegment = { start: number; end: number; mode?: SceneMode }export type ScreenCaptureTarget = { variant: "window"; id: WindowId } | { variant: "display"; id: DisplayId } | { variant: "area"; screen: DisplayId; bounds: LogicalBounds }export type SegmentRecordings = { display: Video; camera: Video | null; mic: Audio | null; system_audio: Audio | null }export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordingsMeta; path: string }+export type SetCaptureAreaPending = booleanexport type ShadowConfiguration = { size: number; opacity: number; blur: number }export type SharingMeta = { id: string; link: string }export type ShowCapWindow = "Setup" | { Main: { init_target_mode: RecordingTargetMode | null } } | { Settings: { page: string | null } } | { Editor: { project_path: string } } | "RecordingsOverlay" | { WindowCaptureOccluder: { screen_id: DisplayId } } | { TargetSelectOverlay: { display_id: DisplayId } } | { CaptureArea: { screen_id: DisplayId } } | "Camera" | { InProgressRecording: { countdown: number | null } } | "Upgrade" | "ModeSelect"diff --git a/apps/desktop/src/utils/tauriSpectaHack.ts b/apps/desktop/src/utils/tauriSpectaHack.tsnew file mode 100644index 000000000..51cb29ed6--- /dev/null+++ b/apps/desktop/src/utils/tauriSpectaHack.ts@@ -0,0 +1,28 @@+// Workaround for: https://github.com/specta-rs/tauri-specta/issues/187++import type * as TAURI_API_EVENT from "@tauri-apps/api/event";+import type { WebviewWindow } from "@tauri-apps/api/webviewWindow";+import type { events } from "./tauri";++type __EventObj__<T> = {+ listen: (+ cb: TAURI_API_EVENT.EventCallback<T>,+ ) => ReturnType<typeof TAURI_API_EVENT.listen<T>>;+ once: (+ cb: TAURI_API_EVENT.EventCallback<T>,+ ) => ReturnType<typeof TAURI_API_EVENT.once<T>>;+ emit: null extends T+ ? (payload?: T) => ReturnType<typeof TAURI_API_EVENT.emit>+ : (payload: T) => ReturnType<typeof TAURI_API_EVENT.emit>;+};++const mappings = {+ setCaptureAreaPending: "set-capture-area-pending",+};++export const emitTo = <K extends keyof typeof mappings>(+ webview: WebviewWindow,+ event: K,+ target: string,+ value: (typeof events)[K] extends __EventObj__<infer U> ? U : never,+) => webview.emitTo(target, mappings[event], value);diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.tsindex 66d8db55d..773c20138 100644--- a/packages/ui-solid/src/auto-imports.d.ts+++ b/packages/ui-solid/src/auto-imports.d.ts@@ -70,6 +70,7 @@ declare global {const IconLucideClock: typeof import('~icons/lucide/clock.jsx')['default']const IconLucideDatabase: typeof import('~icons/lucide/database.jsx')['default']const IconLucideEdit: typeof import('~icons/lucide/edit.jsx')['default']+ const IconLucideExpand: typeof import('~icons/lucide/expand.jsx')['default']const IconLucideEye: typeof import("~icons/lucide/eye.jsx")["default"]const IconLucideEyeOff: typeof import('~icons/lucide/eye-off.jsx')['default']const IconLucideFolder: typeof import('~icons/lucide/folder.jsx')['default']@@ -81,6 +82,7 @@ declare global {const IconLucideMessageSquarePlus: typeof import('~icons/lucide/message-square-plus.jsx')['default']const IconLucideMicOff: typeof import('~icons/lucide/mic-off.jsx')['default']const IconLucideMonitor: typeof import('~icons/lucide/monitor.jsx')['default']+ const IconLucidePlus: typeof import('~icons/lucide/plus.jsx')['default']const IconLucideRatio: typeof import('~icons/lucide/ratio.jsx')['default']const IconLucideRectangleHorizontal: typeof import('~icons/lucide/rectangle-horizontal.jsx')['default']const IconLucideRotateCcw: typeof import('~icons/lucide/rotate-ccw.jsx')['default']@@ -90,6 +92,7 @@ declare global {const IconLucideVideo: typeof import('~icons/lucide/video.jsx')['default']const IconLucideVolume2: typeof import('~icons/lucide/volume2.jsx')['default']const IconLucideVolumeX: typeof import('~icons/lucide/volume-x.jsx')['default']+ const IconLucideX: typeof import('~icons/lucide/x.jsx')['default']const IconMaterialSymbolsScreenshotFrame2Rounded: typeof import('~icons/material-symbols/screenshot-frame2-rounded.jsx')['default']const IconMdiLoading: typeof import("~icons/mdi/loading.jsx")["default"]const IconMdiMonitor: typeof import('~icons/mdi/monitor.jsx')['default']