Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Integrate live preview for screenshot editor

Richie McIlroy77cac643615e
diff --git a/apps/desktop/src/routes/screenshot-editor/Preview.tsx b/apps/desktop/src/routes/screenshot-editor/Preview.tsx
index 85d0b8521..d161d5284 100644
--- a/apps/desktop/src/routes/screenshot-editor/Preview.tsx
+++ b/apps/desktop/src/routes/screenshot-editor/Preview.tsx
@@ -1,6 +1,6 @@
import { convertFileSrc } from "@tauri-apps/api/core";
import { cx } from "cva";
-import { createMemo, createSignal, Show } from "solid-js";
+import { createEffect, createMemo, createSignal, Show } from "solid-js";
import Tooltip from "~/components/Tooltip";
import IconCapCrop from "~icons/cap/crop";
import IconCapZoomIn from "~icons/cap/zoom-in";
@@ -10,88 +10,38 @@ import AspectRatioSelect from "./AspectRatioSelect";
import { useScreenshotEditorContext } from "./context";
export function Preview() {
- const { path, project, setDialog } = useScreenshotEditorContext();
+ const { path, project, setDialog, latestFrame } =
+ useScreenshotEditorContext();
const [zoom, setZoom] = createSignal(1);
-
- // Background Style Helper
- const backgroundStyle = createMemo(() => {
- const source = project.background.source;
- const blur = project.background.blur;
-
- const style: any = {};
-
- if (source.type === "color") {
- const [r, g, b] = source.value;
- const a = source.alpha ?? 255;
- style.backgroundColor = `rgba(${r}, ${g}, ${b}, ${a / 255})`;
- } else if (source.type === "gradient") {
- const { from, to, angle = 90 } = source;
- style.background = `linear-gradient(${angle}deg, rgb(${from.join(",")}), rgb(${to.join(",")}))`;
+ let canvasRef: HTMLCanvasElement | undefined;
+
+ createEffect(() => {
+ const frame = latestFrame();
+ if (frame && canvasRef) {
+ const ctx = canvasRef.getContext("2d");
+ if (ctx) {
+ ctx.putImageData(frame.data, 0, 0);
+ }
}
-
- if (blur > 0) {
- style.filter = `blur(${blur}px)`;
- }
-
- return style;
- });
-
- // Image Style Helper
- const imageStyle = createMemo(() => {
- const { rounding, roundingType, shadow, advancedShadow, border } =
- project.background;
-
- const style: any = {};
-
- // Rounding
- if (rounding > 0) {
- style.borderRadius = `${rounding}px`;
- }
-
- // Shadow
- if (advancedShadow) {
- const { size, opacity, blur } = advancedShadow;
- style.boxShadow = `0 ${size / 2}px ${blur}px rgba(0,0,0, ${opacity / 100})`;
- } else if (shadow > 0) {
- style.boxShadow = `0 ${shadow / 2}px ${shadow}px rgba(0,0,0, ${shadow / 100})`;
- }
-
- // Border
- if (border?.enabled) {
- const { width, color, opacity } = border;
- const [r, g, b] = color;
- style.border = `${width}px solid rgba(${r}, ${g}, ${b}, ${opacity / 100})`;
- }
-
- return style;
- });
-
- const paddingStyle = createMemo(() => {
- const padding = project.background.padding;
- return {
- padding: `${padding * 2}px`, // Scale padding for visibility
- };
});
const cropDialogHandler = () => {
- const img = document.querySelector(
- "img[data-screenshot-preview]",
- ) as HTMLImageElement;
- if (img) {
- setDialog({
- open: true,
- type: "crop",
- position: {
- ...(project.background.crop?.position ?? { x: 0, y: 0 }),
- },
- size: {
- ...(project.background.crop?.size ?? {
- x: img.naturalWidth,
- y: img.naturalHeight,
- }),
- },
- });
- }
+ // We use the original image for cropping
+ // We can get dimensions from the latest frame or load the image
+ // For now, let's just open the dialog and let it handle loading
+ setDialog({
+ open: true,
+ type: "crop",
+ position: {
+ ...(project.background.crop?.position ?? { x: 0, y: 0 }),
+ },
+ size: {
+ ...(project.background.crop?.size ?? {
+ x: latestFrame()?.width ?? 0,
+ y: latestFrame()?.height ?? 0,
+ }),
+ },
+ });
};
return (
@@ -111,40 +61,24 @@ export function Preview() {
{/* Preview Area */}
<div class="flex-1 relative flex items-center justify-center bg-[--bg-subtle] overflow-hidden">
<div
- class="relative shadow-2xl bg-white transition-transform duration-200 ease-out"
+ class="relative shadow-2xl transition-transform duration-200 ease-out"
style={{
- ...paddingStyle(),
transform: `scale(${zoom()})`,
}}
>
- {/* Background Layer */}
- <div class="absolute inset-0 z-0 overflow-hidden transition-all duration-200">
- <Show
- when={
- project.background.source.type === "wallpaper" ||
- project.background.source.type === "image"
- }
- >
- <Show when={(project.background.source as any).path}>
- <img
- src={convertFileSrc((project.background.source as any).path)}
- class="w-full h-full object-cover"
- style={{ filter: `blur(${project.background.blur}px)` }}
- />
- </Show>
- </Show>
- <div class="w-full h-full" style={backgroundStyle()} />
- </div>
-
- {/* Content Layer */}
- <div class="relative z-10">
- <img
- data-screenshot-preview
- src={convertFileSrc(path)}
- class="max-w-full max-h-[80vh] block transition-all duration-200"
- style={imageStyle()}
- />
- </div>
+ <Show
+ when={latestFrame()}
+ fallback={<div class="text-gray-11">Loading preview...</div>}
+ >
+ {(frame) => (
+ <canvas
+ ref={canvasRef}
+ width={frame().width}
+ height={frame().height}
+ class="max-w-full max-h-[80vh] block"
+ />
+ )}
+ </Show>
</div>
</div>
diff --git a/apps/desktop/src/routes/screenshot-editor/context.tsx b/apps/desktop/src/routes/screenshot-editor/context.tsx
index 2981ceaa4..b7d2eaf7a 100644
--- a/apps/desktop/src/routes/screenshot-editor/context.tsx
+++ b/apps/desktop/src/routes/screenshot-editor/context.tsx
@@ -1,7 +1,18 @@
import { createContextProvider } from "@solid-primitives/context";
-import { createSignal } from "solid-js";
+import { trackStore } from "@solid-primitives/deep";
+import { createEffect, createResource, createSignal, on } from "solid-js";
import { createStore } from "solid-js/store";
-import type { AspectRatio, BackgroundConfiguration, XY } from "~/utils/tauri";
+import { createImageDataWS, createLazySignal } from "~/utils/socket";
+import {
+ type AspectRatio,
+ type BackgroundConfiguration,
+ commands,
+ type XY,
+} from "~/utils/tauri";
+import {
+ normalizeProject,
+ serializeProjectConfiguration,
+} from "../editor/context";
import {
DEFAULT_GRADIENT_FROM,
DEFAULT_GRADIENT_TO,
@@ -48,6 +59,53 @@ export const [ScreenshotEditorProvider, useScreenshotEditorContext] =
open: false,
});
+ const [latestFrame, setLatestFrame] = createLazySignal<{
+ width: number;
+ data: ImageData;
+ }>();
+
+ const [editorInstance] = createResource(async () => {
+ const instance = await commands.createScreenshotEditorInstance(
+ props.path,
+ );
+
+ const [_ws, isConnected] = createImageDataWS(
+ instance.framesSocketUrl,
+ setLatestFrame,
+ );
+
+ return instance;
+ });
+
+ createEffect(
+ on(
+ () => trackStore(project),
+ async () => {
+ const instance = editorInstance();
+ if (!instance) return;
+
+ // Convert ScreenshotProject to ProjectConfiguration
+ // We need to construct a full ProjectConfiguration from the partial ScreenshotProject
+ // For now, we can use a default one and override background
+ const config = serializeProjectConfiguration({
+ ...normalizeProject({
+ // @ts-expect-error - partial config
+ background: project.background,
+ // @ts-expect-error - partial config
+ camera: {
+ source: { type: "none" },
+ },
+ }),
+ // @ts-expect-error
+ aspectRatio: project.aspectRatio,
+ });
+
+ await commands.updateScreenshotConfig(instance, config);
+ },
+ { defer: true },
+ ),
+ );
+
// Mock history for now or implement if needed
const projectHistory = {
pause: () => () => {},
@@ -66,5 +124,7 @@ export const [ScreenshotEditorProvider, useScreenshotEditorContext] =
projectHistory,
dialog,
setDialog,
+ latestFrame,
+ editorInstance,
};
}, null!);
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 5b8fd1dbc..5d8bf386c 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -134,6 +134,12 @@ async uploadExportedVideo(path: string, mode: UploadMode, channel: TAURI_CHANNEL
async uploadScreenshot(screenshotPath: string) : Promise<UploadResult> {
return await TAURI_INVOKE("upload_screenshot", { screenshotPath });
},
+async createScreenshotEditorInstance(path: string) : Promise<SerializedScreenshotEditorInstance> {
+ return await TAURI_INVOKE("create_screenshot_editor_instance", { path });
+},
+async updateScreenshotConfig(config: ProjectConfiguration) : Promise<null> {
+ return await TAURI_INVOKE("update_screenshot_config", { config });
+},
async getRecordingMeta(path: string, fileType: FileType) : Promise<RecordingMetaWithMetadata> {
return await TAURI_INVOKE("get_recording_meta", { path, fileType });
},
@@ -475,6 +481,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 SerializedScreenshotEditorInstance = { framesSocketUrl: string; path: string }
export type SetCaptureAreaPending = boolean
export type ShadowConfiguration = { size: number; opacity: number; blur: number }
export type SharingMeta = { id: string; link: string }