Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

perf(image): add comprehensive performance optimizations

Augustus Otu32d5f953d68e
diff --git a/apps/image/index.html b/apps/image/index.html
index 566929a3..e81cdf22 100644
--- a/apps/image/index.html
+++ b/apps/image/index.html
@@ -3,9 +3,13 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="manifest" href="/manifest.json" />
+ <link rel="apple-touch-icon" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#22c55e" />
<meta name="description" content="Professional browser-based graphic design editor - Create stunning visuals offline" />
+ <meta name="apple-mobile-web-app-capable" content="yes" />
+ <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=DM+Sans:wght@400;500;700&family=Poppins:wght@300;400;500;600;700;800;900&family=Montserrat:wght@300;400;500;600;700;800;900&family=Playfair+Display:wght@400;500;600;700;800;900&family=Roboto:wght@300;400;500;700;900&family=Open+Sans:wght@300;400;600;700;800&family=Lato:wght@300;400;700;900&family=Oswald:wght@300;400;500;600;700&family=Bebas+Neue&family=Pacifico&family=Lobster&family=Dancing+Script:wght@400;700&family=Great+Vibes&display=swap" rel="stylesheet" />
@@ -14,5 +18,12 @@
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
+ <script>
+ if ('serviceWorker' in navigator) {
+ window.addEventListener('load', () => {
+ navigator.serviceWorker.register('/sw.js').catch(() => {});
+ });
+ }
+ </script>
</body>
</html>
diff --git a/apps/image/public/manifest.json b/apps/image/public/manifest.json
new file mode 100644
index 00000000..80a6703c
--- /dev/null
+++ b/apps/image/public/manifest.json
@@ -0,0 +1,19 @@
+{
+ "name": "OpenReel Image",
+ "short_name": "OpenReel",
+ "description": "Professional browser-based graphic design editor",
+ "start_url": "/",
+ "display": "standalone",
+ "background_color": "#0a0a0a",
+ "theme_color": "#22c55e",
+ "orientation": "landscape",
+ "icons": [
+ {
+ "src": "/favicon.svg",
+ "sizes": "any",
+ "type": "image/svg+xml",
+ "purpose": "any maskable"
+ }
+ ],
+ "categories": ["graphics", "design", "productivity"]
+}
diff --git a/apps/image/public/sw.js b/apps/image/public/sw.js
new file mode 100644
index 00000000..2a878f7e
--- /dev/null
+++ b/apps/image/public/sw.js
@@ -0,0 +1,47 @@
+const CACHE_NAME = 'openreel-image-v1';
+const STATIC_ASSETS = [
+ '/',
+ '/index.html',
+ '/manifest.json',
+];
+
+self.addEventListener('install', (event) => {
+ event.waitUntil(
+ caches.open(CACHE_NAME).then((cache) => cache.addAll(STATIC_ASSETS))
+ );
+ self.skipWaiting();
+});
+
+self.addEventListener('activate', (event) => {
+ event.waitUntil(
+ caches.keys().then((keys) =>
+ Promise.all(
+ keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key))
+ )
+ )
+ );
+ self.clients.claim();
+});
+
+self.addEventListener('fetch', (event) => {
+ if (event.request.method !== 'GET') return;
+
+ const url = new URL(event.request.url);
+ if (url.origin !== location.origin) return;
+
+ event.respondWith(
+ caches.match(event.request).then((cached) => {
+ const fetchPromise = fetch(event.request)
+ .then((response) => {
+ if (response.ok && response.status === 200) {
+ const clone = response.clone();
+ caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
+ }
+ return response;
+ })
+ .catch(() => cached);
+
+ return cached || fetchPromise;
+ })
+ );
+});
diff --git a/apps/image/src/components/editor/EditorInterface.tsx b/apps/image/src/components/editor/EditorInterface.tsx
index 4fcf1949..2640307c 100644
--- a/apps/image/src/components/editor/EditorInterface.tsx
+++ b/apps/image/src/components/editor/EditorInterface.tsx
@@ -1,4 +1,4 @@
-import { useState } from 'react';
+import { useState, lazy, Suspense } from 'react';
import { Toolbar } from './toolbar/Toolbar';
import { LeftPanel } from './panels/LeftPanel';
import { Canvas } from './canvas/Canvas';
@@ -7,11 +7,12 @@ import { LayerPanel } from './layers/LayerPanel';
import { HistoryPanel } from './panels/HistoryPanel';
import { GuidePanel } from './panels/GuidePanel';
import { PagesBar } from './pages/PagesBar';
-import { ExportDialog } from './ExportDialog';
import { useUIStore } from '../../stores/ui-store';
import { useProjectStore } from '../../stores/project-store';
import { Layers, History, Ruler } from 'lucide-react';
+const ExportDialog = lazy(() => import('./ExportDialog').then(m => ({ default: m.ExportDialog })));
+
type BottomTab = 'layers' | 'history' | 'guides';
export function EditorInterface() {
@@ -96,7 +97,11 @@ export function EditorInterface() {
)}
</div>
- <ExportDialog open={isExportDialogOpen} onClose={closeExportDialog} />
+ {isExportDialogOpen && (
+ <Suspense fallback={null}>
+ <ExportDialog open={isExportDialogOpen} onClose={closeExportDialog} />
+ </Suspense>
+ )}
</div>
);
}
diff --git a/apps/image/src/components/editor/canvas/Canvas.tsx b/apps/image/src/components/editor/canvas/Canvas.tsx
index 4b365ca4..b2c70b1e 100644
--- a/apps/image/src/components/editor/canvas/Canvas.tsx
+++ b/apps/image/src/components/editor/canvas/Canvas.tsx
@@ -11,7 +11,9 @@ const RULER_SIZE = 20;
const HANDLE_SIZE = 8;
const ROTATION_HANDLE_DISTANCE = 24;
+const MAX_IMAGE_CACHE_SIZE = 50;
const imageCache = new Map<string, HTMLImageElement>();
+const imageCacheOrder: string[] = [];
let renderCallback: (() => void) | null = null;
function getCachedImage(src: string): HTMLImageElement | null {
@@ -19,13 +21,30 @@ function getCachedImage(src: string): HTMLImageElement | null {
const cached = imageCache.get(src);
if (cached && cached.complete && cached.naturalWidth > 0) {
+ const idx = imageCacheOrder.indexOf(src);
+ if (idx > -1) {
+ imageCacheOrder.splice(idx, 1);
+ imageCacheOrder.push(src);
+ }
return cached;
}
if (!cached) {
+ if (imageCache.size >= MAX_IMAGE_CACHE_SIZE) {
+ const oldest = imageCacheOrder.shift();
+ if (oldest) {
+ const oldImg = imageCache.get(oldest);
+ if (oldImg?.src?.startsWith('blob:')) {
+ URL.revokeObjectURL(oldImg.src);
+ }
+ imageCache.delete(oldest);
+ }
+ }
+
const img = new window.Image();
img.src = src;
imageCache.set(src, img);
+ imageCacheOrder.push(src);
if (!img.complete) {
img.onload = () => {
@@ -44,10 +63,52 @@ function getCachedImage(src: string): HTMLImageElement | null {
return null;
}
+interface ViewportBounds {
+ left: number;
+ top: number;
+ right: number;
+ bottom: number;
+}
+
+function getViewportBounds(
+ canvasWidth: number,
+ canvasHeight: number,
+ artboardWidth: number,
+ artboardHeight: number,
+ zoom: number,
+ panX: number,
+ panY: number
+): ViewportBounds {
+ const centerX = canvasWidth / 2 + panX;
+ const centerY = canvasHeight / 2 + panY;
+ const artboardX = centerX - (artboardWidth * zoom) / 2;
+ const artboardY = centerY - (artboardHeight * zoom) / 2;
+
+ return {
+ left: -artboardX / zoom,
+ top: -artboardY / zoom,
+ right: (canvasWidth - artboardX) / zoom,
+ bottom: (canvasHeight - artboardY) / zoom,
+ };
+}
+
+function isLayerInViewport(layer: Layer, viewport: ViewportBounds): boolean {
+ const { x, y, width, height } = layer.transform;
+ return !(
+ x + width < viewport.left ||
+ x > viewport.right ||
+ y + height < viewport.top ||
+ y > viewport.bottom
+ );
+}
+
export function Canvas() {
const containerRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });
+ const renderScheduledRef = useRef(false);
+ const lastRenderHashRef = useRef<string>('');
+ const forceRenderRef = useRef(false);
const {
project,
@@ -109,6 +170,13 @@ export function Canvas() {
canvas.height = container.clientHeight;
}
+ const renderHash = `${zoom}-${panX}-${panY}-${selectedLayerIds.join(',')}-${project.updatedAt}-${showGrid}-${drawing.isDrawing}-${isMarqueeSelecting}`;
+ if (renderHash === lastRenderHashRef.current && !forceRenderRef.current) {
+ return;
+ }
+ lastRenderHashRef.current = renderHash;
+ forceRenderRef.current = false;
+
ctx.save();
ctx.fillStyle = '#18181b';
ctx.fillRect(0, 0, canvas.width, canvas.height);
@@ -156,10 +224,21 @@ export function Canvas() {
}
}
+ const viewport = getViewportBounds(
+ canvas.width,
+ canvas.height,
+ artboard.size.width,
+ artboard.size.height,
+ zoom,
+ panX,
+ panY
+ );
+
const sortedLayerIds = [...artboard.layerIds].reverse();
sortedLayerIds.forEach((layerId) => {
const layer = project.layers[layerId];
if (!layer || !layer.visible) return;
+ if (!isLayerInViewport(layer, viewport)) return;
renderLayerWithChildren(ctx, layer, project);
});
@@ -365,20 +444,35 @@ export function Canvas() {
ctx.restore();
}, [artboard, project, zoom, panX, panY, selectedLayerIds, showGrid, gridSize, crop, smartGuides, drawing, penSettings, isMarqueeSelecting, marqueeRect]);
- useEffect(() => {
- render();
+ const scheduleRender = useCallback(() => {
+ if (renderScheduledRef.current) return;
+ renderScheduledRef.current = true;
+
+ requestAnimationFrame(() => {
+ render();
+ renderScheduledRef.current = false;
+ });
}, [render]);
+ const forceRender = useCallback(() => {
+ forceRenderRef.current = true;
+ scheduleRender();
+ }, [scheduleRender]);
+
useEffect(() => {
- renderCallback = render;
+ scheduleRender();
+ }, [scheduleRender]);
+
+ useEffect(() => {
+ renderCallback = forceRender;
return () => {
renderCallback = null;
};
- }, [render]);
+ }, [forceRender]);
useEffect(() => {
const handleResize = () => {
- render();
+ forceRender();
if (containerRef.current) {
setContainerSize({
width: containerRef.current.clientWidth,
@@ -389,7 +483,7 @@ export function Canvas() {
window.addEventListener('resize', handleResize);
handleResize();
return () => window.removeEventListener('resize', handleResize);
- }, [render]);
+ }, [forceRender]);
const screenToCanvas = useCallback(
(screenX: number, screenY: number) => {
@@ -579,7 +673,7 @@ export function Canvas() {
if (drawing.isDrawing) {
const { x, y } = screenToCanvas(e.clientX, e.clientY);
addDrawingPoint({ x, y });
- render();
+ scheduleRender();
return;
}
@@ -599,7 +693,7 @@ export function Canvas() {
if (dragMode === 'marquee') {
const { x, y } = screenToCanvas(e.clientX, e.clientY);
updateMarqueeSelect(x, y);
- render();
+ scheduleRender();
return;
}
@@ -794,7 +888,7 @@ export function Canvas() {
}
}
},
- [isDragging, dragMode, dragCurrentX, dragCurrentY, dragStartX, dragStartY, panX, panY, setPan, zoom, selectedLayerIds, project, updateLayerTransform, updateDrag, artboard, guides, snapToObjects, snapToGuides, snapToGrid, gridSize, setSmartGuides, drawing.isDrawing, screenToCanvas, addDrawingPoint, render, updateMarqueeSelect, activeResizeHandle, activeTool, getHandleAtPoint]
+ [isDragging, dragMode, dragCurrentX, dragCurrentY, dragStartX, dragStartY, panX, panY, setPan, zoom, selectedLayerIds, project, updateLayerTransform, updateDrag, artboard, guides, snapToObjects, snapToGuides, snapToGrid, gridSize, setSmartGuides, drawing.isDrawing, screenToCanvas, addDrawingPoint, scheduleRender, updateMarqueeSelect, activeResizeHandle, activeTool, getHandleAtPoint]
);
const findLayersInRect = useCallback(
@@ -834,7 +928,7 @@ export function Canvas() {
if (path && path.length > 1) {
addPathLayer(path, penSettings.color, penSettings.width);
}
- render();
+ scheduleRender();
return;
}
@@ -847,7 +941,7 @@ export function Canvas() {
}
}
endDrag();
- render();
+ scheduleRender();
return;
}
@@ -855,7 +949,7 @@ export function Canvas() {
setActiveResizeHandle(null);
endDrag();
clearSmartGuides();
- }, [endDrag, clearSmartGuides, drawing.isDrawing, finishDrawing, addPathLayer, penSettings, render, dragMode, endMarqueeSelect, findLayersInRect, selectLayers, setActiveResizeHandle]);
+ }, [endDrag, clearSmartGuides, drawing.isDrawing, finishDrawing, addPathLayer, penSettings, scheduleRender, dragMode, endMarqueeSelect, findLayersInRect, selectLayers, setActiveResizeHandle]);
const handleContextMenu = useCallback(
(e: React.MouseEvent) => {
diff --git a/apps/image/src/components/editor/inspector/Inspector.tsx b/apps/image/src/components/editor/inspector/Inspector.tsx
index 8c324256..e6c668b6 100644
--- a/apps/image/src/components/editor/inspector/Inspector.tsx
+++ b/apps/image/src/components/editor/inspector/Inspector.tsx
@@ -1,22 +1,28 @@
+import { memo, lazy, Suspense } from 'react';
import { useProjectStore } from '../../../stores/project-store';
import { useUIStore } from '../../../stores/ui-store';
import { TransformSection } from './TransformSection';
import { AlignmentSection } from './AlignmentSection';
import { AppearanceSection } from './AppearanceSection';
import { EffectsSection } from './EffectsSection';
-import { ImageAdjustmentsSection } from './ImageAdjustmentsSection';
-import { FilterPresetsSection } from './FilterPresetsSection';
-import { CropSection } from './CropSection';
-import { ImageControlsSection } from './ImageControlsSection';
-import { BackgroundRemovalSection } from './BackgroundRemovalSection';
-import { TextSection } from './TextSection';
-import { ShapeSection } from './ShapeSection';
import { ArtboardSection } from './ArtboardSection';
import { PenSettingsSection } from './PenSettingsSection';
import { ColorHarmonySection } from './ColorHarmonySection';
import type { Layer, ImageLayer, TextLayer, ShapeLayer } from '../../../types/project';
-export function Inspector() {
+const ImageAdjustmentsSection = lazy(() => import('./ImageAdjustmentsSection').then(m => ({ default: m.ImageAdjustmentsSection })));
+const FilterPresetsSection = lazy(() => import('./FilterPresetsSection').then(m => ({ default: m.FilterPresetsSection })));
+const CropSection = lazy(() => import('./CropSection').then(m => ({ default: m.CropSection })));
+const ImageControlsSection = lazy(() => import('./ImageControlsSection').then(m => ({ default: m.ImageControlsSection })));
+const BackgroundRemovalSection = lazy(() => import('./BackgroundRemovalSection').then(m => ({ default: m.BackgroundRemovalSection })));
+const TextSection = lazy(() => import('./TextSection').then(m => ({ default: m.TextSection })));
+const ShapeSection = lazy(() => import('./ShapeSection').then(m => ({ default: m.ShapeSection })));
+
+function SectionLoader() {
+ return <div className="h-8 animate-pulse bg-muted/30 rounded" />;
+}
+
+function InspectorContent() {
const { project, selectedLayerIds, selectedArtboardId } = useProjectStore();
const { activeTool } = useUIStore();
@@ -87,17 +93,17 @@ export function Inspector() {
<EffectsSection layer={singleLayer} />
{singleLayer.type === 'image' && (
- <>
+ <Suspense fallback={<SectionLoader />}>
<ImageControlsSection layer={singleLayer as ImageLayer} />
<CropSection layer={singleLayer as ImageLayer} />
<BackgroundRemovalSection layer={singleLayer as ImageLayer} />
<FilterPresetsSection layer={singleLayer as ImageLayer} />
<ImageAdjustmentsSection layer={singleLayer as ImageLayer} />
- </>
+ </Suspense>
)}
{singleLayer.type === 'text' && (
- <>
+ <Suspense fallback={<SectionLoader />}>
<TextSection layer={singleLayer as TextLayer} />
<ColorHarmonySection
baseColor={(singleLayer as TextLayer).style.color}
@@ -107,11 +113,11 @@ export function Inspector() {
});
}}
/>
- </>
+ </Suspense>
)}
{singleLayer.type === 'shape' && (
- <>
+ <Suspense fallback={<SectionLoader />}>
<ShapeSection layer={singleLayer as ShapeLayer} />
{(singleLayer as ShapeLayer).shapeStyle.fill && (
<ColorHarmonySection
@@ -123,8 +129,10 @@ export function Inspector() {
}}
/>
)}
- </>
+ </Suspense>
)}
</div>
);
}
+
+export const Inspector = memo(InspectorContent);
diff --git a/apps/image/src/components/editor/panels/LeftPanel.tsx b/apps/image/src/components/editor/panels/LeftPanel.tsx
index 7cfbe4b8..aa6c8abc 100644
--- a/apps/image/src/components/editor/panels/LeftPanel.tsx
+++ b/apps/image/src/components/editor/panels/LeftPanel.tsx
@@ -1,4 +1,4 @@
-import { useState, useRef, useEffect } from 'react';
+import { useState, useRef, useEffect, memo, useMemo } from 'react';
import {
Layers,
Image,
@@ -83,7 +83,7 @@ interface LayerItemProps {
getLayerIcon: (type: string) => React.ReactNode;
}
-function LayerItem({
+const LayerItem = memo(function LayerItem({
layer,
depth,
project,
@@ -252,7 +252,8 @@ function LayerItem({
)}
</>
);
-}
+});
+
import {
TEMPLATE_CATEGORIES,
getTemplatesByCategory,
@@ -271,7 +272,7 @@ const panels: { id: Panel; icon: React.ElementType; label: string }[] = [
{ id: 'uploads', icon: Upload, label: 'Uploads' },
];
-export function LeftPanel() {
+export const LeftPanel = memo(function LeftPanel() {
const { activePanel, setActivePanel } = useUIStore();
return (
@@ -308,7 +309,7 @@ export function LeftPanel() {
</div>
</div>
);
-}
+});
function LayersPanel() {
const {
@@ -335,13 +336,17 @@ function LayersPanel() {
const dragSelectIds = useRef<Set<string>>(new Set());
const artboard = project?.artboards.find((a) => a.id === selectedArtboardId);
- const layers = artboard?.layerIds.map((id) => project?.layers[id]).filter(Boolean) ?? [];
- const filteredLayers = searchQuery
- ? layers.filter((layer) =>
- layer && layer.name.toLowerCase().includes(searchQuery.toLowerCase())
- )
- : layers;
+ const layers = useMemo(() => {
+ if (!artboard || !project) return [];
+ return artboard.layerIds.map((id) => project.layers[id]).filter(Boolean);
+ }, [artboard, project]);
+
+ const filteredLayers = useMemo(() => {
+ if (!searchQuery) return layers;
+ const query = searchQuery.toLowerCase();
+ return layers.filter((layer) => layer && layer.name.toLowerCase().includes(query));
+ }, [layers, searchQuery]);
const handleStartRename = (layer: { id: string; name: string }) => {
setEditingLayerId(layer.id);
diff --git a/apps/image/vite.config.ts b/apps/image/vite.config.ts
index 1037c9ce..d21d3b27 100644
--- a/apps/image/vite.config.ts
+++ b/apps/image/vite.config.ts
@@ -12,17 +12,30 @@ export default defineConfig({
},
build: {
target: "esnext",
+ chunkSizeWarningLimit: 1000,
rollupOptions: {
output: {
manualChunks: (id) => {
- if (id.includes("node_modules/react") || id.includes("node_modules/react-dom")) {
- return "react";
+ if (id.includes("node_modules/react") || id.includes("node_modules/react-dom") || id.includes("node_modules/scheduler")) {
+ return "vendor-react";
}
if (id.includes("node_modules/zustand")) {
- return "zustand";
+ return "vendor-zustand";
}
if (id.includes("node_modules/@radix-ui")) {
- return "radix";
+ return "vendor-radix";
+ }
+ if (id.includes("node_modules/lucide-react")) {
+ return "vendor-icons";
+ }
+ if (id.includes("components/editor/canvas/Canvas")) {
+ return "editor-canvas";
+ }
+ if (id.includes("components/editor/ExportDialog")) {
+ return "editor-export";
+ }
+ if (id.includes("components/editor/inspector")) {
+ return "editor-inspector";
}
},
},