feat(viewport): add fit artboard command

This commit is contained in:
syntaxbullet
2026-07-03 11:31:55 +02:00
parent 84a610f019
commit 8965532c3a
5 changed files with 78 additions and 1 deletions

View File

@@ -1,3 +1,4 @@
import type { ArtboardId } from "@core/id";
import type { Vec2D } from "@core/geometry";
import type { Command } from "./command";
import { commandIds } from "./ids";
@@ -20,6 +21,11 @@ export type ViewportSetSizePayload = {
h: number;
};
export type ViewportFitArtboardPayload = {
artboardId?: ArtboardId;
padding?: number;
};
export const viewportPanCommand: Command<ViewportPanPayload> = {
id: commandIds.viewportPan,
name: "Pan viewport",
@@ -111,6 +117,40 @@ export const viewportSetSizeCommand: Command<ViewportSetSizePayload> = {
},
};
export const viewportFitArtboardCommand: Command<ViewportFitArtboardPayload | undefined> = {
id: commandIds.viewportFitArtboard,
name: "Fit artboard in viewport",
execute({ state }, payload) {
const artboardId = payload?.artboardId ?? state.editor.selection.artboardId;
const artboard = artboardId
? state.document.artboards.find((candidate) => candidate.id === artboardId)
: state.document.artboards[0];
if (!artboard) return state;
const padding = Math.max(0, payload?.padding ?? 48);
const availableWidth = Math.max(0, state.editor.viewport.size.w - padding * 2);
const availableHeight = Math.max(0, state.editor.viewport.size.h - padding * 2);
const canFitZoom = availableWidth > 0 && availableHeight > 0 && artboard.bounds.w > 0 && artboard.bounds.h > 0;
const zoom = canFitZoom ? Math.max(0.01, Math.min(availableWidth / artboard.bounds.w, availableHeight / artboard.bounds.h)) : state.editor.viewport.zoom;
return {
...state,
editor: {
...state.editor,
viewport: {
...state.editor.viewport,
center: {
x: artboard.bounds.x + artboard.bounds.w / 2,
y: artboard.bounds.y + artboard.bounds.h / 2,
},
zoom,
},
},
};
},
};
export const viewportResetCommand: Command = {
id: commandIds.viewportReset,
name: "Reset viewport",
@@ -135,5 +175,6 @@ export const viewportCommands = [
viewportSetZoomCommand,
viewportZoomAroundPointCommand,
viewportSetSizeCommand,
viewportFitArtboardCommand,
viewportResetCommand,
] satisfies Command<unknown>[];