feat(viewport): add fit artboard command
This commit is contained in:
@@ -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>[];
|
||||
|
||||
Reference in New Issue
Block a user