Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

dynamic canvas zoom, new recent's logic

sora2b672ccf0f67
diff --git a/src/App.tsx b/src/App.tsx
index ea0939d..3054b7c 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -3871,7 +3871,7 @@ export function App() {
options.colorMode,
defaultFreq
);
- resetZoomAndCenter();
+ resetZoomAndCenter(newDims);
resetHistory();
// Add to document tabs (empty perspective ruler by default)
@@ -3891,17 +3891,6 @@ export function App() {
setDocuments((prev) => [...prev, newDoc]);
setActiveDocumentId(newDocId);
- // Track in recent documents
- saveRecentDocument({
- id: newDocId,
- title: name.replace(/\*+$/, ''),
- path: `InkStudio\\${name.replace(/\*+$/, '')}.sora`,
- size: 524288,
- coverUrl: initialLayers[0]?.thumbnailUrl,
- isStarred: false,
- fileType: '.sora',
- }).catch(console.warn);
-
showToast(`Created ${name}`);
},
[primaryColor, resetHistory, resetToNewCanvas, resetZoomAndCenter, showToast, updateBrushSettings]
@@ -3995,7 +3984,7 @@ export function App() {
resizeCanvas(newDims, options);
setDimensions(newDims);
- resetZoomAndCenter();
+ resetZoomAndCenter(newDims);
resetHistory();
showToast(`Canvas resized to ${newDims.width} × ${newDims.height} px`);
},
@@ -4057,7 +4046,7 @@ export function App() {
setSavedFileInfo(null); // Reset handle on new import
loadDocument(doc);
- resetZoomAndCenter();
+ resetZoomAndCenter(doc.dimensions);
resetHistory();
// Create document tab
@@ -4085,6 +4074,7 @@ export function App() {
coverUrl: doc.layers[0]?.thumbnailUrl,
isStarred: false,
fileType: file.name.slice(file.name.lastIndexOf('.')),
+ isSaved: true,
}).catch(console.warn);
showToast(`Opened ${file.name}`);
@@ -4156,7 +4146,7 @@ export function App() {
});
}
setPerspectiveRuler(doc.perspectiveRuler ?? null);
- resetZoomAndCenter();
+ resetZoomAndCenter(doc.dimensions);
},
[documents, loadDocument, resetZoomAndCenter]
);
@@ -4190,6 +4180,7 @@ export function App() {
layers: nextActive.layers,
layerCanvases: nextActive.layerCanvasesMap,
});
+ resetZoomAndCenter(nextActive.dimensions);
} else {
clearDocument();
}
@@ -4250,9 +4241,9 @@ export function App() {
// If haven't saved the file yet, prompt to select a path and file extension
if (!savedFileInfo?.handle) {
try {
- const info = await promptSaveAs(docData, savedFileInfo?.extension || '.png');
+ const info = await promptSaveAs(docData, savedFileInfo?.extension || '.sora');
setSavedFileInfo(info);
- // info.name includes the extension (e.g. art.png or Untitled.png)
+ // info.name includes the extension (e.g. art.sora or Untitled.sora)
setDocumentName(info.name);
setDocuments((prev) =>
prev.map((d) => (d.id === activeDocumentId ? { ...d, name: info.name, savedFileInfo: info } : d))
@@ -4265,6 +4256,7 @@ export function App() {
coverUrl: layers[0]?.thumbnailUrl,
isStarred: false,
fileType: info.extension,
+ isSaved: true,
}).catch(console.warn);
showToast(`Saved to ${info.name}`);
} catch (err: any) {
@@ -4288,12 +4280,13 @@ export function App() {
coverUrl: layers[0]?.thumbnailUrl,
isStarred: false,
fileType: savedFileInfo.extension,
+ isSaved: true,
}).catch(console.warn);
showToast(`Saved to ${savedFileInfo.name}`);
} catch (err: any) {
console.warn('Direct handle save failed, prompting with Save As:', err);
try {
- const info = await promptSaveAs(docData, savedFileInfo.extension || '.png');
+ const info = await promptSaveAs(docData, savedFileInfo.extension || '.sora');
setSavedFileInfo(info);
setDocumentName(info.name);
setDocuments((prev) =>
@@ -4307,6 +4300,7 @@ export function App() {
coverUrl: layers[0]?.thumbnailUrl,
isStarred: false,
fileType: info.extension,
+ isSaved: true,
}).catch(console.warn);
showToast(`Saved to ${info.name}`);
} catch (e: any) {
@@ -4343,7 +4337,7 @@ export function App() {
};
try {
- const defaultExt = savedFileInfo?.extension || '.png';
+ const defaultExt = savedFileInfo?.extension || '.sora';
const info = await promptSaveAs(docData, defaultExt);
setSavedFileInfo(info);
setDocumentName(info.name);
@@ -4358,6 +4352,7 @@ export function App() {
coverUrl: layers[0]?.thumbnailUrl,
isStarred: false,
fileType: info.extension,
+ isSaved: true,
}).catch(console.warn);
showToast(`Saved as ${info.name}`);
} catch (err: any) {
diff --git a/src/hooks/useCanvasNavigation.ts b/src/hooks/useCanvasNavigation.ts
index 482179a..2e4da3b 100644
--- a/src/hooks/useCanvasNavigation.ts
+++ b/src/hooks/useCanvasNavigation.ts
@@ -1,11 +1,17 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { CanvasDimensions } from '../types/editor';
-export const MIN_ZOOM = 0.1; // 10%
+export const MIN_ZOOM = 0.01; // 1% (supports large manga/print canvas vertical adaptation)
export const MAX_ZOOM = 32.0; // 3200%
// Discrete zoom steps used in professional software (Photoshop / Clip Studio Paint)
export const ZOOM_PRESETS = [
+ 0.01, // 1%
+ 0.02, // 2%
+ 0.03, // 3%
+ 0.05, // 5%
+ 0.0625, // 6.25%
+ 0.0833, // 8.33%
0.1, // 10%
0.125, // 12.5%
0.1667, // 16.7%
@@ -41,12 +47,45 @@ export function formatZoomPercent(zoom: number): string {
return `${rounded % 1 === 0 ? rounded.toFixed(0) : rounded.toFixed(1)}%`;
}
+export const VIEWPORT_FIT_PADDING = 48; // 24px margin on each side for clean artboard visibility
+
+/**
+ * Calculates adaptive zoom based on layer/canvas dimensions and viewport size.
+ * 100% (1.0) is the default zoom level when canvas fits.
+ * If canvas exceeds viewport (e.g. manga canvas), adapts vertically to fit cleanly.
+ * 100% is the default zoom level rather than the maximum zoom level (MAX_ZOOM = 32.0).
+ */
+export function calculateAdaptiveZoom(
+ dimensions: CanvasDimensions | undefined,
+ viewport: HTMLDivElement | null
+): number {
+ if (!viewport || !dimensions || dimensions.height <= 0 || dimensions.width <= 0) {
+ return 1.0;
+ }
+
+ const vw = viewport.clientWidth;
+ const vh = viewport.clientHeight;
+ if (vw <= 0 || vh <= 0) {
+ return 1.0;
+ }
+
+ const availH = Math.max(20, vh - VIEWPORT_FIT_PADDING);
+ const availW = Math.max(20, vw - VIEWPORT_FIT_PADDING);
+
+ const scaleY = availH / dimensions.height;
+ const scaleX = availW / dimensions.width;
+ const fitZoom = Math.min(scaleY, scaleX);
+
+ const targetZoom = fitZoom < 1.0 ? fitZoom : 1.0;
+ return Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, targetZoom));
+}
+
interface UseCanvasNavigationProps {
dimensions?: CanvasDimensions;
isWebtoonMode?: boolean;
}
-export function useCanvasNavigation({ dimensions: _dimensions, isWebtoonMode = false }: UseCanvasNavigationProps = {}) {
+export function useCanvasNavigation({ dimensions, isWebtoonMode = false }: UseCanvasNavigationProps = {}) {
const viewportRef = useRef<HTMLDivElement | null>(null);
const [zoom, setZoomState] = useState<number>(1.0);
@@ -54,6 +93,11 @@ export function useCanvasNavigation({ dimensions: _dimensions, isWebtoonMode = f
const [pan, setPanState] = useState<{ x: number; y: number }>({ x: 0, y: 0 });
const [rotation, setRotationState] = useState<number>(0.0);
+ const dimensionsRef = useRef<CanvasDimensions | undefined>(dimensions);
+ useEffect(() => {
+ dimensionsRef.current = dimensions;
+ }, [dimensions]);
+
const [isSpaceDown, setIsSpaceDown] = useState<boolean>(false);
const [isShiftDown, setIsShiftDown] = useState<boolean>(false);
const [isPanning, setIsPanning] = useState<boolean>(false);
@@ -136,19 +180,25 @@ export function useCanvasNavigation({ dimensions: _dimensions, isWebtoonMode = f
y: Math.round(vh / 2),
};
+ const clampedZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, targetZoom));
panRef.current = newCenter;
setPanState(newCenter);
- zoomRef.current = targetZoom;
+ zoomRef.current = clampedZoom;
+ setZoomState(clampedZoom);
}, []);
- // Reset zoom to 100%, rotation to 0°, and re-center the canvas (Ctrl + 0)
- const resetZoomAndCenter = useCallback(() => {
- zoomRef.current = 1.0;
- setZoomState(1.0);
- rotationRef.current = 0.0;
- setRotationState(0.0);
- centerCanvas(1.0);
- }, [centerCanvas]);
+ // Reset zoom based on layer/canvas dimensions (adapts vertically for oversized formats like manga,
+ // defaults to 100% when fitting, centered, rotation to 0°)
+ const resetZoomAndCenter = useCallback(
+ (customDims?: CanvasDimensions) => {
+ const activeDims = customDims || dimensionsRef.current;
+ const targetZoom = calculateAdaptiveZoom(activeDims, viewportRef.current);
+ rotationRef.current = 0.0;
+ setRotationState(0.0);
+ centerCanvas(targetZoom);
+ },
+ [centerCanvas]
+ );
// Reset only rotation to 0° around the viewport center (Ctrl + Alt + 0)
const resetRotation = useCallback(() => {
@@ -284,7 +334,8 @@ export function useCanvasNavigation({ dimensions: _dimensions, isWebtoonMode = f
let prevHeight = viewport.clientHeight;
if (!hasInitializedCenterRef.current && prevWidth > 0 && prevHeight > 0) {
- centerCanvas(1.0);
+ const initialZoom = calculateAdaptiveZoom(dimensionsRef.current, viewport);
+ centerCanvas(initialZoom);
hasInitializedCenterRef.current = true;
}
@@ -294,7 +345,8 @@ export function useCanvasNavigation({ dimensions: _dimensions, isWebtoonMode = f
if (width <= 0 || height <= 0) continue;
if (!hasInitializedCenterRef.current) {
- centerCanvas(1.0);
+ const initialZoom = calculateAdaptiveZoom(dimensionsRef.current, viewport);
+ centerCanvas(initialZoom);
hasInitializedCenterRef.current = true;
} else {
// Adjust canvas center by half the size difference to keep canvas centered
diff --git a/src/utils/__tests__/navigation.test.ts b/src/utils/__tests__/navigation.test.ts
new file mode 100644
index 0000000..d207229
--- /dev/null
+++ b/src/utils/__tests__/navigation.test.ts
@@ -0,0 +1,74 @@
+import { describe, it, expect } from 'vitest';
+import {
+ calculateAdaptiveZoom,
+ MIN_ZOOM,
+ MAX_ZOOM,
+ ZOOM_PRESETS,
+ formatZoomPercent,
+ VIEWPORT_FIT_PADDING,
+} from '../../hooks/useCanvasNavigation';
+
+function createMockViewport(width: number, height: number): HTMLDivElement {
+ return {
+ clientWidth: width,
+ clientHeight: height,
+ } as unknown as HTMLDivElement;
+}
+
+describe('Canvas Navigation & Adaptive Zoom Engine', () => {
+ it('adapts vertically for large manga canvas (e.g. Shueisha 6071 x 8598)', () => {
+ const viewport = createMockViewport(1200, 800);
+ const mangaDims = { width: 6071, height: 8598, dpi: 600 };
+
+ const zoom = calculateAdaptiveZoom(mangaDims, viewport);
+
+ const expectedAvailH = 800 - VIEWPORT_FIT_PADDING;
+ const expectedScaleY = expectedAvailH / 8598;
+
+ expect(zoom).toBeCloseTo(expectedScaleY, 4);
+ expect(zoom).toBeLessThan(1.0);
+ expect(zoom).toBeGreaterThanOrEqual(MIN_ZOOM);
+
+ // Verify canvas rendered height with padding fits inside viewport
+ const renderedHeight = mangaDims.height * zoom;
+ expect(renderedHeight).toBeLessThanOrEqual(800 - VIEWPORT_FIT_PADDING);
+ });
+
+ it('defaults to 100% (1.0) zoom when canvas fits within viewport', () => {
+ const viewport = createMockViewport(1200, 800);
+ const smallDims = { width: 500, height: 500, dpi: 300 };
+
+ const zoom = calculateAdaptiveZoom(smallDims, viewport);
+
+ // 100% should be the default zoom rather than scaling up
+ expect(zoom).toBe(1.0);
+ });
+
+ it('does not treat 100% as the maximum zoom level of the system', () => {
+ expect(MAX_ZOOM).toBe(32.0);
+ expect(MAX_ZOOM).toBeGreaterThan(1.0);
+ expect(MIN_ZOOM).toBeLessThanOrEqual(0.01);
+ });
+
+ it('supports zoom presets down to 1% to accommodate high-resolution manga pages', () => {
+ expect(ZOOM_PRESETS[0]).toBe(0.01);
+ expect(ZOOM_PRESETS).toContain(0.05);
+ expect(ZOOM_PRESETS).toContain(0.1);
+ expect(ZOOM_PRESETS).toContain(1.0);
+ expect(ZOOM_PRESETS[ZOOM_PRESETS.length - 1]).toBe(32.0);
+ });
+
+ it('formats fractional and sub-10% zoom levels cleanly', () => {
+ expect(formatZoomPercent(1.0)).toBe('100%');
+ expect(formatZoomPercent(0.5)).toBe('50%');
+ expect(formatZoomPercent(0.0874)).toBe('8.7%');
+ expect(formatZoomPercent(0.01)).toBe('1%');
+ });
+
+ it('handles empty or zero dimensions gracefully by returning 1.0', () => {
+ const viewport = createMockViewport(1200, 800);
+ expect(calculateAdaptiveZoom(undefined, viewport)).toBe(1.0);
+ expect(calculateAdaptiveZoom({ width: 0, height: 0 }, viewport)).toBe(1.0);
+ expect(calculateAdaptiveZoom({ width: 1000, height: 1000 }, null)).toBe(1.0);
+ });
+});
diff --git a/src/utils/__tests__/recentDocumentsManager.test.ts b/src/utils/__tests__/recentDocumentsManager.test.ts
index d1de432..228df58 100644
--- a/src/utils/__tests__/recentDocumentsManager.test.ts
+++ b/src/utils/__tests__/recentDocumentsManager.test.ts
@@ -103,4 +103,49 @@ describe('recentDocumentsManager', () => {
const docs = await loadRecentDocuments();
expect(docs.find((d) => d.id === testDoc.id)).toBeUndefined();
});
+
+ it('filters out unsaved files and dummy canvas creation entries', async () => {
+ // Unsaved dummy created canvas from handleCreateNewCanvas
+ const unsavedDummy: RecentDocument = {
+ id: 'doc-unsaved-1',
+ title: 'Untitled*',
+ path: 'InkStudio\\Untitled.sora',
+ size: 524288,
+ isStarred: false,
+ lastOpened: Date.now(),
+ isSaved: false,
+ };
+ await saveRecentDocument(unsavedDummy);
+
+ // Document explicitly flagged as not saved
+ const notSavedDoc: RecentDocument = {
+ id: 'doc-unsaved-2',
+ title: 'Manga Draft',
+ path: 'C:\\Draft.sora',
+ size: 1024,
+ isStarred: false,
+ lastOpened: Date.now(),
+ isSaved: false,
+ };
+ await saveRecentDocument(notSavedDoc);
+
+ // Valid actually saved document
+ const savedDoc: RecentDocument = {
+ id: 'doc-saved-1',
+ title: 'Finished_Page.sora',
+ path: 'C:\\Users\\Artist\\Documents\\Finished_Page.sora',
+ size: 1572864,
+ isStarred: false,
+ lastOpened: Date.now(),
+ isSaved: true,
+ fileType: '.sora',
+ };
+ await saveRecentDocument(savedDoc);
+
+ const docs = await loadRecentDocuments();
+ expect(docs.find((d) => d.id === 'doc-unsaved-1')).toBeUndefined();
+ expect(docs.find((d) => d.id === 'doc-unsaved-2')).toBeUndefined();
+ expect(docs.find((d) => d.id === 'doc-saved-1')).toBeDefined();
+ expect(docs.length).toBe(1);
+ });
});
diff --git a/src/utils/recentDocumentsManager.ts b/src/utils/recentDocumentsManager.ts
index 11c9574..b35686f 100644
--- a/src/utils/recentDocumentsManager.ts
+++ b/src/utils/recentDocumentsManager.ts
@@ -9,6 +9,7 @@ export interface RecentDocument {
lastOpened: number; // unix timestamp ms
isStarred: boolean;
fileType?: string;
+ isSaved?: boolean;
}
const DB_NAME = 'InkStudioRecentDocsDB';
@@ -16,6 +17,22 @@ const DB_VERSION = 1;
const STORE_NAME = 'recent_documents';
const LS_BACKUP_KEY = 'inkstudio_recent_docs_backup';
+export function isActualSavedDocument(doc: RecentDocument): boolean {
+ if (!doc) return false;
+ if (doc.isSaved === false) return false;
+ // Purge legacy sample documents
+ if (doc.id.startsWith('sample-doc-')) return false;
+ // Purge unsaved dummy canvases generated on canvas creation
+ if (doc.size === 524288) return false;
+ // Purge unsaved documents with asterisk indicator
+ if (doc.title?.endsWith('*')) return false;
+ // If explicitly flagged as saved to PC
+ if (doc.isSaved === true) return true;
+ // Purge legacy records that used dummy relative paths without being explicitly saved
+ if (doc.path?.startsWith('InkStudio\\') && doc.size <= 524288) return false;
+ return true;
+}
+
function openDB(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
if (typeof window === 'undefined' || !window.indexedDB) {
@@ -37,13 +54,13 @@ function openDB(): Promise<IDBDatabase> {
}
export async function loadRecentDocuments(): Promise<RecentDocument[]> {
- // Purge any legacy sample docs from localStorage
+ // Purge unsaved and legacy sample docs from localStorage
try {
const raw = localStorage.getItem(LS_BACKUP_KEY);
if (raw) {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) {
- const cleaned = parsed.filter((d: RecentDocument) => !d.id.startsWith('sample-doc-'));
+ const cleaned = parsed.filter(isActualSavedDocument);
localStorage.setItem(LS_BACKUP_KEY, JSON.stringify(cleaned));
}
}
@@ -59,13 +76,13 @@ export async function loadRecentDocuments(): Promise<RecentDocument[]> {
const req = store.getAll();
req.onsuccess = () => {
let docs = (req.result as RecentDocument[]) || [];
- // Clean out any legacy sample documents from IDB
- const sampleDocs = docs.filter((d) => d.id.startsWith('sample-doc-'));
- if (sampleDocs.length > 0) {
- for (const s of sampleDocs) {
+ // Clean out any unsaved or legacy dummy documents from IDB
+ const invalidDocs = docs.filter((d) => !isActualSavedDocument(d));
+ if (invalidDocs.length > 0) {
+ for (const s of invalidDocs) {
store.delete(s.id);
}
- docs = docs.filter((d) => !d.id.startsWith('sample-doc-'));
+ docs = docs.filter((d) => isActualSavedDocument(d));
}
docs.sort((a, b) => b.lastOpened - a.lastOpened);
resolve(docs);
@@ -85,7 +102,7 @@ function getFallbackDocs(): RecentDocument[] {
if (raw) {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) {
- return parsed.filter((d: RecentDocument) => !d.id.startsWith('sample-doc-'));
+ return parsed.filter(isActualSavedDocument);
}
}
} catch {
@@ -97,8 +114,14 @@ function getFallbackDocs(): RecentDocument[] {
export async function saveRecentDocument(
doc: Omit<RecentDocument, 'lastOpened'> & { lastOpened?: number }
): Promise<void> {
+ // Only persist documents that were actually saved to the PC
+ if (doc.isSaved === false || doc.size === 524288 || doc.title?.endsWith('*')) {
+ return;
+ }
+
const fullDoc: RecentDocument = {
...doc,
+ isSaved: doc.isSaved ?? true,
lastOpened: doc.lastOpened ?? Date.now(),
};
diff --git a/src/utils/saveManager.ts b/src/utils/saveManager.ts
index ea1190d..b1669df 100644
--- a/src/utils/saveManager.ts
+++ b/src/utils/saveManager.ts
@@ -282,7 +282,7 @@ export function downloadFile(
*/
export async function promptSaveAs(
data: SaveDocumentData,
- defaultExtension: string = '.png',
+ defaultExtension: string = '.sora',
fallbackToDownload: boolean = true
): Promise<SavedFileInfo> {
const safeName = data.name.trim().replace(/[^a-zA-Z0-9_\- ]/g, '_') || 'Untitled';
@@ -290,16 +290,16 @@ export async function promptSaveAs(
const types = [
{
- description: 'PNG Image (*.png)',
- accept: { 'image/png': ['.png'] },
+ description: 'Ink Studio Layered Project (*.sora, *.ink)',
+ accept: { 'application/json': ['.sora', '.ink'] },
},
{
description: 'Photoshop Document with Layers (*.psd)',
accept: { 'image/vnd.adobe.photoshop': ['.psd'] },
},
{
- description: 'Ink Studio Layered Project (*.ink, *.sora)',
- accept: { 'application/json': ['.ink', '.sora'] },
+ description: 'PNG Image (*.png)',
+ accept: { 'image/png': ['.png'] },
},
{
description: 'JPEG Image (*.jpg, *.jpeg)',