Skip to content

AI-native design editor. Open-source Figma alternative.

feat: fit pages as Figma does and reopen files where they were left (#1675)

Danila Poyarkov2e571a40fa08
diff --git a/changes/1675/added.md b/changes/1675/added.md
new file mode 100644
index 000000000..8f272b215
--- /dev/null
+++ b/changes/1675/added.md
@@ -0,0 +1 @@
+- In the desktop app and for files in storage, a file reopens on the page and at the view it was left at, as in Figma (#1675).
diff --git a/changes/1675/changed.md b/changes/1675/changed.md
new file mode 100644
index 000000000..643af3abf
--- /dev/null
+++ b/changes/1675/changed.md
@@ -0,0 +1 @@
+- Zoom to fit and zoom to selection fill the canvas with the layers inside the margins Figma keeps, zooming in past 100% for small layers, and zoom to fit on an empty page shows its origin at the centre at 100%; a page opens fitted to its layers on its first visit and returns to the view it was left at after (#1675).
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index 3decbd9c2..35a5e6c78 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -277,6 +277,9 @@ export const SECTION_DEFAULT_STROKE: Stroke = {
export const SECTION_CORNER_RADIUS = 2
export const ZOOM_DIVISOR = 50
+/** Figma's zoom range, 2% to 25,600%. */
+export const ZOOM_MIN = 0.02
+export const ZOOM_MAX = 256
export const ZOOM_SCALE_MIN = 0.75
export const ZOOM_SCALE_MAX = 1.25
diff --git a/packages/core/src/editor/page-viewports.ts b/packages/core/src/editor/page-viewports.ts
deleted file mode 100644
index 9589a143e..000000000
--- a/packages/core/src/editor/page-viewports.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { getPageColor } from '#core/figma-api/page-backgrounds'
-import type { ViewportTransform } from '#core/geometry/types'
-
-import type { EditorContext } from './types'
-
-export function createPageViewportStore(ctx: EditorContext) {
- const pageViewports = new Map<string, ViewportTransform>()
-
- function saveCurrentPageViewport() {
- pageViewports.set(ctx.state.currentPageId, {
- panX: ctx.state.panX,
- panY: ctx.state.panY,
- zoom: ctx.state.zoom
- })
- }
-
- function restorePageViewport(pageId: string) {
- ctx.state.pageColor = getPageColor(ctx.graph.getNode(pageId))
- const viewport = pageViewports.get(pageId)
- if (viewport) {
- ctx.state.panX = viewport.panX
- ctx.state.panY = viewport.panY
- ctx.state.zoom = viewport.zoom
- return
- }
-
- ctx.state.panX = 0
- ctx.state.panY = 0
- ctx.state.zoom = 1
- }
-
- function deletePageViewport(pageId: string) {
- pageViewports.delete(pageId)
- }
-
- function clearPageViewports() {
- pageViewports.clear()
- }
-
- return { saveCurrentPageViewport, restorePageViewport, deletePageViewport, clearPageViewports }
-}
diff --git a/packages/core/src/editor/pages.ts b/packages/core/src/editor/pages.ts
index 5bcbc8ba2..4c4c69ee7 100644
--- a/packages/core/src/editor/pages.ts
+++ b/packages/core/src/editor/pages.ts
@@ -19,8 +19,8 @@ import { fontManager } from '#core/text/font/manager'
import { collectGraphFontRequirements } from '#core/text/requirements/collect'
import { missingGraphFontScripts } from '#core/text/requirements/resolved'
-import { createPageViewportStore } from './page-viewports'
import { createPageLayouts } from './pages/layouts'
+import { createPageViewportStore } from './pages/viewports'
import type { EditorContext } from './types'
export interface PageSwitchProgress {
diff --git a/packages/core/src/editor/pages/viewports.ts b/packages/core/src/editor/pages/viewports.ts
new file mode 100644
index 000000000..5878ab520
--- /dev/null
+++ b/packages/core/src/editor/pages/viewports.ts
@@ -0,0 +1,66 @@
+import type { EditorContext } from '#core/editor/types'
+import { FIT_INSETS, fitViewport, pageContentBounds } from '#core/editor/viewport'
+import { getPageColor } from '#core/figma-api/page-backgrounds'
+import type { ViewportTransform } from '#core/geometry/types'
+
+export function createPageViewportStore(ctx: EditorContext) {
+ const pageViewports = new Map<string, ViewportTransform>()
+ // Pages opened while the canvas had no size, so never fitted: they are not remembered at that
+ // placeholder view, and their next visit fits them.
+ const unfitted = new Set<string>()
+
+ function isMeasured() {
+ const { width, height } = ctx.getViewportSize()
+ return width > 0 && height > 0
+ }
+
+ function saveCurrentPageViewport() {
+ const pageId = ctx.state.currentPageId
+ if (unfitted.has(pageId)) {
+ if (!isMeasured()) return
+ unfitted.delete(pageId)
+ }
+ pageViewports.set(ctx.state.currentPageId, {
+ panX: ctx.state.panX,
+ panY: ctx.state.panY,
+ zoom: ctx.state.zoom
+ })
+ }
+
+ /**
+ * The view a page opens with, as in Figma: the one it was left at, or on its first visit every
+ * layer fitted into the canvas, and the origin at the centre at 100% when it has none.
+ */
+ function firstVisitViewport(pageId: string): ViewportTransform {
+ const size = ctx.getViewportSize()
+ // Nothing to fit into a canvas not yet measured: the page opens at the origin at 100%, and a
+ // host that reports its size later calls zoomToFit.
+ if (!isMeasured()) {
+ unfitted.add(pageId)
+ return { panX: 0, panY: 0, zoom: 1 }
+ }
+ const bounds = pageContentBounds(ctx.graph, pageId)
+ if (!bounds) return { panX: size.width / 2, panY: size.height / 2, zoom: 1 }
+ return fitViewport(bounds, size, FIT_INSETS)
+ }
+
+ function restorePageViewport(pageId: string) {
+ ctx.state.pageColor = getPageColor(ctx.graph.getNode(pageId))
+ const viewport = pageViewports.get(pageId) ?? firstVisitViewport(pageId)
+ ctx.state.panX = viewport.panX
+ ctx.state.panY = viewport.panY
+ ctx.state.zoom = viewport.zoom
+ }
+
+ function deletePageViewport(pageId: string) {
+ pageViewports.delete(pageId)
+ unfitted.delete(pageId)
+ }
+
+ function clearPageViewports() {
+ pageViewports.clear()
+ unfitted.clear()
+ }
+
+ return { saveCurrentPageViewport, restorePageViewport, deletePageViewport, clearPageViewports }
+}
diff --git a/packages/core/src/editor/viewport.ts b/packages/core/src/editor/viewport.ts
index 2e25dd6f6..0de033759 100644
--- a/packages/core/src/editor/viewport.ts
+++ b/packages/core/src/editor/viewport.ts
@@ -1,7 +1,10 @@
+import type { SceneGraph } from '@open-pencil/scene-graph'
import { getAxisAlignedWorldBounds } from '@open-pencil/scene-graph/coordinate'
-import { computeBounds, computeAbsoluteBounds } from '@open-pencil/scene-graph/geometry'
+import { computeBounds } from '@open-pencil/scene-graph/geometry'
+import type { Rect } from '@open-pencil/scene-graph/primitives'
-import { ZOOM_DIVISOR, ZOOM_SCALE_MAX, ZOOM_SCALE_MIN } from '#core/constants'
+import { ZOOM_DIVISOR, ZOOM_MAX, ZOOM_MIN, ZOOM_SCALE_MAX, ZOOM_SCALE_MIN } from '#core/constants'
+import type { ViewportTransform } from '#core/geometry/types'
import { emitNavigationTrace } from '#core/profiler'
import type { EditorContext } from './types'
@@ -9,6 +12,64 @@ import type { EditorContext } from './types'
/** Space kept between revealed layers and the viewport edge. */
const REVEAL_MARGIN = 48
+/** Screen pixels between the canvas edge and layers fitted into it. */
+export interface ViewportInsets {
+ left: number
+ right: number
+ top: number
+ bottom: number
+}
+
+/**
+ * Figma's insets for zoom to fit and the first visit of a page, measured on its canvas: 35 px a
+ * side, plus the 10 px left and top and 50 px at the bottom its floating toolbar and chrome take.
+ */
+export const FIT_INSETS: ViewportInsets = { left: 45, right: 25, top: 45, bottom: 85 }
+
+/** Figma's insets for zoom to selection: 50 px a side plus the same chrome allowance. */
+export const SELECTION_INSETS: ViewportInsets = { left: 60, right: 40, top: 60, bottom: 100 }
+
+/**
+ * The world box the page's visible top-level layers take, rotation included; null when it shows
+ * none. As in Figma, hidden layers count for nothing and each layer counts by its own box, so
+ * children drawn outside an unclipped frame are left out.
+ */
+export function pageContentBounds(
+ graph: Pick<SceneGraph, 'getChildren' | 'getNode'>,
+ pageId: string
+): Rect | null {
+ const nodes = graph.getChildren(pageId).filter((node) => node.visible)
+ if (nodes.length === 0) return null
+ return computeBounds(nodes.map((node) => getAxisAlignedWorldBounds(node, graph)))
+}
+
+function clampZoom(zoom: number): number {
+ return Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, zoom))
+}
+
+/**
+ * The viewport that fills the `size` canvas less `insets` with `bounds`, centred there, as Figma
+ * fits layers: zoomed past 100% for small layers, to the maximum zoom for a point.
+ */
+export function fitViewport(
+ bounds: Rect,
+ size: { width: number; height: number },
+ insets: ViewportInsets
+): ViewportTransform {
+ // A canvas too small for the insets fits into all of itself rather than a negative area.
+ const fitted = size.width > insets.left + insets.right && size.height > insets.top + insets.bottom
+ const { left, top } = fitted ? insets : { left: 0, top: 0 }
+ const areaWidth = fitted ? size.width - insets.left - insets.right : size.width
+ const areaHeight = fitted ? size.height - insets.top - insets.bottom : size.height
+ const fit = Math.min(areaWidth / bounds.width, areaHeight / bounds.height)
+ const zoom = clampZoom(Number.isNaN(fit) ? 1 : fit)
+ return {
+ zoom,
+ panX: left + areaWidth / 2 - (bounds.x + bounds.width / 2) * zoom,
+ panY: top + areaHeight / 2 - (bounds.y + bounds.height / 2) * zoom
+ }
+}
+
export function createViewportActions(ctx: EditorContext) {
function currentViewport() {
return { panX: ctx.state.panX, panY: ctx.state.panY, zoom: ctx.state.zoom }
@@ -38,7 +99,7 @@ export function createViewportActions(ctx: EditorContext) {
function setZoomAroundPoint(level: number, centerX: number, centerY: number) {
const previous = currentViewport()
- const newZoom = Math.max(0.02, Math.min(256, level))
+ const newZoom = clampZoom(level)
ctx.state.panX = centerX - (centerX - ctx.state.panX) * (newZoom / ctx.state.zoom)
ctx.state.panY = centerY - (centerY - ctx.state.panY) * (newZoom / ctx.state.zoom)
ctx.state.zoom = newZoom
@@ -62,18 +123,20 @@ export function createViewportActions(ctx: EditorContext) {
emitViewportChanged(previous)
}
- function zoomToBounds(minX: number, minY: number, maxX: number, maxY: number) {
+ /** Fills the canvas less `insets` with the world rectangle, centred, zooming in or out as needed. */
+ function zoomToBounds(
+ minX: number,
+ minY: number,
+ maxX: number,
+ maxY: number,
+ insets: ViewportInsets = SELECTION_INSETS
+ ) {
const previous = currentViewport()
- const padding = 80
- const w = maxX - minX + padding * 2
- const h = maxY - minY + padding * 2
-
- const { width: viewW, height: viewH } = ctx.getViewportSize()
- const zoom = Math.min(viewW / w, viewH / h, 1)
-
- ctx.state.zoom = zoom
- ctx.state.panX = (viewW - w * zoom) / 2 - minX * zoom + padding * zoom
- ctx.state.panY = (viewH - h * zoom) / 2 - minY * zoom + padding * zoom
+ const bounds = { x: minX, y: minY, width: maxX - minX, height: maxY - minY }
+ const next = fitViewport(bounds, ctx.getViewportSize(), insets)
+ ctx.state.zoom = next.zoom
+ ctx.state.panX = next.panX
+ ctx.state.panY = next.panY
ctx.requestRepaint()
emitViewportChanged(previous)
}
@@ -82,7 +145,7 @@ export function createViewportActions(ctx: EditorContext) {
function centerOn(x: number, y: number, zoom = ctx.state.zoom) {
const previous = currentViewport()
const { width, height } = ctx.getViewportSize()
- const nextZoom = Math.max(0.02, Math.min(256, zoom))
+ const nextZoom = clampZoom(zoom)
const panX = width / 2 - x * nextZoom
const panY = height / 2 - y * nextZoom
// Remote cursors are finite but unbounded; a point that overflows leaves the view alone.
@@ -94,12 +157,14 @@ export function createViewportActions(ctx: EditorContext) {
emitViewportChanged(previous)
}
+ /** Figma's Shift+1: every layer of the page fitted; an empty page shows its origin at 100%. */
function zoomToFit() {
- const nodes = ctx.graph.getChildren(ctx.state.currentPageId)
- if (nodes.length === 0) return
-
- const b = computeBounds(nodes)
- zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)
+ const b = pageContentBounds(ctx.graph, ctx.state.currentPageId)
+ if (!b) {
+ centerOn(0, 0, 1)
+ return
+ }
+ zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height, FIT_INSETS)
}
function zoomToLevel(level: number) {
@@ -108,7 +173,7 @@ export function createViewportActions(ctx: EditorContext) {
const centerY = (-ctx.state.panY + viewH / 2) / ctx.state.zoom
const previous = currentViewport()
- ctx.state.zoom = Math.max(0.02, Math.min(256, level))
+ ctx.state.zoom = clampZoom(level)
// Keep the world point at the center of the viewport where it was.
ctx.state.panX = viewW / 2 - centerX * ctx.state.zoom
ctx.state.panY = viewH / 2 - centerY * ctx.state.zoom
@@ -128,7 +193,7 @@ export function createViewportActions(ctx: EditorContext) {
.filter((n): n is NonNullable<typeof n> => n != null)
if (nodes.length === 0) return
- const b = computeAbsoluteBounds(nodes, (id) => ctx.graph.getAbsolutePosition(id))
+ const b = computeBounds(nodes.map((node) => getAxisAlignedWorldBounds(node, ctx.graph)))
zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)
}
diff --git a/packages/core/tests/editor/bridges/frames.test.ts b/packages/core/tests/editor/bridges/frames.test.ts
index 699b1a7f5..9775eb02c 100644
--- a/packages/core/tests/editor/bridges/frames.test.ts
+++ b/packages/core/tests/editor/bridges/frames.test.ts
@@ -57,8 +57,9 @@ describe('frame navigation', () => {
const { editor, right } = frames()
editor.zoomToPreviousFrame()
const { panX, panY, zoom } = editor.state
- const centerX = (VIEWPORT.width / 2 - panX) / zoom
- const centerY = (VIEWPORT.height / 2 - panY) / zoom
+ // The frame is centred in the canvas less the zoom-to-selection insets (60/40 and 60/100).
+ const centerX = (60 + (VIEWPORT.width - 100) / 2 - panX) / zoom
+ const centerY = (60 + (VIEWPORT.height - 160) / 2 - panY) / zoom
expect(centerX).toBeCloseTo(right.x + right.width / 2)
expect(centerY).toBeCloseTo(right.y + right.height / 2)
})
diff --git a/packages/core/tests/editor/pages/viewports.test.ts b/packages/core/tests/editor/pages/viewports.test.ts
new file mode 100644
index 000000000..492afc145
--- /dev/null
+++ b/packages/core/tests/editor/pages/viewports.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core'
+
+const VIEWPORT = { width: 800, height: 600 }
+
+function setup() {
+ const editor = createEditor({ getViewportSize: () => VIEWPORT })
+ const first = editor.state.currentPageId
+ const second = editor.graph.addPage('Second').id
+ return { editor, first, second }
+}
+
+// Figma opens a page the first time with every layer fitted, an empty one with the origin at the
+// centre at 100%, and later at the view it was left at.
+describe('page viewports', () => {
+ test('a first visit fits the page\'s layers with the fit insets', async () => {
+ const { editor, second } = setup()
+ editor.graph.createNode('RECTANGLE', second, { x: 100, y: 200, width: 300, height: 180 })
+
+ await editor.switchPage(second)
+
+ expect(editor.state.zoom).toBeCloseTo(730 / 300, 6)
+ expect(250 * editor.state.zoom + editor.state.panX).toBeCloseTo(45 + 730 / 2, 6)
+ expect(290 * editor.state.zoom + editor.state.panY).toBeCloseTo(45 + 470 / 2, 6)
+ })
+
+ test('a first visit of an empty page shows the origin at the centre at 100%', async () => {
+ const { editor, second } = setup()
+ await editor.switchPage(second)
+ expect(editor.state).toMatchObject({ panX: 400, panY: 300, zoom: 1 })
+ })
+
+ test('a revisit restores the view the page was left at', async () => {
+ const { editor, first, second } = setup()
+ editor.graph.createNode('RECTANGLE', second, { x: 0, y: 0, width: 100, height: 100 })
+ await editor.switchPage(second)
+ editor.state.panX = -120
+ editor.state.panY = 80
+ editor.state.zoom = 0.5
+
+ await editor.switchPage(first)
+ await editor.switchPage(second)
+
+ expect(editor.state).toMatchObject({ panX: -120, panY: 80, zoom: 0.5 })
+ })
+
+ test('an unmeasured canvas leaves the first visit at the origin, and fits it once measured', async () => {
+ let size = { width: 0, height: 0 }
+ const editor = createEditor({ getViewportSize: () => size })
+ const first = editor.state.currentPageId
+ const second = editor.graph.addPage('Second').id
+ editor.graph.createNode('RECTANGLE', second, { x: 100, y: 200, width: 300, height: 180 })
+ await editor.switchPage(second)
+ expect(editor.state).toMatchObject({ panX: 0, panY: 0, zoom: 1 })
+
+ await editor.switchPage(first)
+ size = VIEWPORT
+ await editor.switchPage(second)
+ expect(editor.state.zoom).toBeCloseTo(730 / 300, 6)
+ })
+
+ test("keeps a measured page's view when the canvas has no size as it is left", async () => {
+ let size = VIEWPORT
+ const editor = createEditor({ getViewportSize: () => size })
+ const first = editor.state.currentPageId
+ const second = editor.graph.addPage('Second').id
+ await editor.switchPage(second)
+ editor.state.panX = -120
+ editor.state.zoom = 0.5
+
+ size = { width: 0, height: 0 }
+ await editor.switchPage(first)
+ size = VIEWPORT
+ await editor.switchPage(second)
+
+ expect(editor.state).toMatchObject({ panX: -120, zoom: 0.5 })
+ })
+
+})
diff --git a/packages/core/tests/editor/viewport.test.ts b/packages/core/tests/editor/viewport.test.ts
index b0a72499e..7c6fd4693 100644
--- a/packages/core/tests/editor/viewport.test.ts
+++ b/packages/core/tests/editor/viewport.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core'
+import type { Rect } from '@open-pencil/scene-graph/primitives'
const VIEWPORT = { width: 800, height: 600 }
@@ -40,3 +41,120 @@ describe('centerOn', () => {
expect({ ...center(editor), zoom: editor.state.zoom }).toEqual(before)
})
})
+
+/** Where the world point lands on the canvas. */
+function screenOf(editor: ReturnType<typeof createEditor>, x: number, y: number) {
+ const { panX, panY, zoom } = editor.state
+ return { x: x * zoom + panX, y: y * zoom + panY }
+}
+
+function withRect(rect: Rect) {
+ const editor = createEditor({ getViewportSize: () => VIEWPORT })
+ const node = editor.graph.createNode('RECTANGLE', editor.state.currentPageId, rect)
+ return { editor, node }
+}
+
+// Insets measured in Figma 126: zoom to fit keeps 45/25 px at the sides and 45/85 px above and
+// below the layers, zoom to selection 60/40 and 60/100, both zooming past 100% when the layers
+// are small.
+describe('zoomToFit', () => {
+ test('fills the canvas less the fit insets with every layer, past 100% when they are small', () => {
+ const { editor } = withRect({ x: 100, y: 200, width: 300, height: 180 })
+ editor.graph.createNode('RECTANGLE', editor.state.currentPageId, {
+ x: 300,
+ y: 250,
+ width: 100,
+ height: 100
+ })
+
+ editor.zoomToFit()
+
+ // The 300 × 180 union fits the 730 × 470 area by its width.
+ expect(editor.state.zoom).toBeCloseTo(730 / 300, 6)
+ expect(screenOf(editor, 250, 290)).toEqual({ x: 45 + 730 / 2, y: 45 + 470 / 2 })
+ })
+
+ test('zooms out for layers larger than the canvas', () => {
+ const { editor } = withRect({ x: -1000, y: 500, width: 4000, height: 1000 })
+ editor.zoomToFit()
+ expect(editor.state.zoom).toBeCloseTo(730 / 4000, 6)
+ })
+
+ test('stops at the maximum zoom for a point-sized layer and still centres it', () => {
+ const { editor } = withRect({ x: 50, y: 50, width: 0, height: 0 })
+ editor.zoomToFit()
+ expect(editor.state.zoom).toBe(256)
+ expect(screenOf(editor, 50, 50)).toEqual({ x: 45 + 730 / 2, y: 45 + 470 / 2 })
+ })
+
+ test('fits a rotated layer by the box it draws in', () => {
+ const { editor } = withRect({ x: 0, y: 0, width: 400, height: 40 })
+ const node = editor.graph.getChildren(editor.state.currentPageId)[0]
+ editor.graph.updateNode(node.id, { rotation: 90 })
+
+ editor.zoomToFit()
+
+ // Standing upright, the 400 × 40 bar fits the 470 px tall area by its length.
+ expect(editor.state.zoom).toBeCloseTo(470 / 400, 6)
+ })
+
+ test('leaves hidden layers and children outside an unclipped frame out of the fit', () => {
+ const { editor } = withRect({ x: 100, y: 200, width: 300, height: 180 })
+ const page = editor.state.currentPageId
+ editor.graph.createNode('RECTANGLE', page, { x: 3000, y: 3000, width: 100, height: 100, visible: false })
+ const frame = editor.graph.createNode('FRAME', page, { x: 100, y: 200, width: 300, height: 180, clipsContent: false })
+ editor.graph.createNode('RECTANGLE', frame.id, { x: 400, y: 0, width: 100, height: 100 })
+
+ editor.zoomToFit()
+ expect(editor.state.zoom).toBeCloseTo(730 / 300, 6)
+ })
+
+ test('shows the origin at the centre at 100% on an empty page', () => {
+ const editor = createEditor({ getViewportSize: () => VIEWPORT })
+ editor.state.zoom = 3
+ editor.state.panX = 900
+ editor.zoomToFit()
+ expect(editor.state.zoom).toBe(1)
+ expect(center(editor)).toEqual({ x: 0, y: 0 })
+ })
+})
+
+describe('zoomToSelection', () => {
+ test('fits into the whole canvas when it is smaller than the insets', () => {
+ const editor = createEditor({ getViewportSize: () => ({ width: 90, height: 150 }) })
+ const node = editor.graph.createNode('RECTANGLE', editor.state.currentPageId, {
+ x: 0,
+ y: 0,
+ width: 30,
+ height: 30
+ })
+ editor.select([node.id])
+
+ editor.zoomToSelection()
+
+ expect(editor.state.zoom).toBeCloseTo(3, 6)
+ expect(editor.state).toMatchObject({ panX: 0, panY: 30 })
+ })
+
+ test('fits a rotated layer by the box it draws in', () => {
+ const { editor, node } = withRect({ x: 0, y: 0, width: 400, height: 40 })
+ editor.graph.updateNode(node.id, { rotation: 90 })
+ editor.select([node.id])
+
+ editor.zoomToSelection()
+
+ // Standing upright, the 400 × 40 bar fits the 440 px tall area by its length.
+ expect(editor.state.zoom).toBeCloseTo(440 / 400, 6)
+ })
+
+ test('fills the canvas less the selection insets with the selected layers', () => {
+ const { editor, node } = withRect({ x: 700, y: 500, width: 120, height: 90 })
+ editor.select([node.id])
+
+ editor.zoomToSelection()
+
+ // The 120 × 90 layer fits the 700 × 440 area by its height.
+ expect(editor.state.zoom).toBeCloseTo(440 / 90, 6)
+ expect(screenOf(editor, 760, 545)).toEqual({ x: 60 + 700 / 2, y: 60 + 440 / 2 })
+ })
+})
diff --git a/packages/docs/user-guide/canvas-navigation.md b/packages/docs/user-guide/canvas-navigation.md
index cd601da2f..72775d22d 100644
--- a/packages/docs/user-guide/canvas-navigation.md
+++ b/packages/docs/user-guide/canvas-navigation.md
@@ -55,6 +55,8 @@ Pinch-to-zoom on UI panels (layers, properties) is prevented so it doesn't accid
<kbd>Page Down</kbd> and <kbd>Page Up</kbd> open the next and previous page in the Pages panel's order.
+A page opens fitted to its layers the first time you visit it, and an empty page with its origin at the centre at 100%; later visits return to the view you left. In the desktop app, and for files in storage, a file reopens on the page and at the view you left it at; in the browser, a file picked through the file picker opens fitted each time. Zoom to fit and zoom to selection fill the canvas with the layers, zooming in past 100% for small ones, with the margins Figma keeps.
+
## Pixel Grid
Zoomed in far enough that each document pixel covers eight screen pixels (800% on a standard display, 400% on a Retina one), the canvas shows a line at every pixel, as in Figma. Turn it off or on with **View → Pixel Grid**.
diff --git a/src/app/presence/schema.ts b/src/app/presence/schema.ts
index 9ed3f7ef3..2796dbb37 100644
--- a/src/app/presence/schema.ts
+++ b/src/app/presence/schema.ts
@@ -1,6 +1,7 @@
import * as v from 'valibot'
import { MAX_PRESENCE_NAME_LENGTH } from '@open-pencil/cloud/contract'
+import { ZOOM_MAX, ZOOM_MIN } from '@open-pencil/core/constants'
import type { RemotePeer } from '@/app/collab/types'
import { PEER_COLORS } from '@/constants'
@@ -31,7 +32,7 @@ const colorSchema = v.object({
const pointSchema = v.object({ x: finiteSchema, y: finiteSchema, pageId: idSchema })
const personPointSchema = v.object({
...pointSchema.entries,
- zoom: lenient(v.pipe(finiteSchema, v.minValue(0.02), v.maxValue(256)))
+ zoom: lenient(v.pipe(finiteSchema, v.minValue(ZOOM_MIN), v.maxValue(ZOOM_MAX)))
})
const selectionSchema = v.pipe(v.array(idSchema), v.maxLength(MAX_SELECTION))
const extentSchema = v.pipe(finiteSchema, v.minValue(0))
diff --git a/src/app/recent-files/index.ts b/src/app/recent-files/index.ts
index ee94cd31f..20924bb94 100644
--- a/src/app/recent-files/index.ts
+++ b/src/app/recent-files/index.ts
@@ -7,13 +7,18 @@ export {
recentFiles,
recentLocalFileAt,
recentLocalFilePaths,
+ recentDocumentIdOf,
recentDocumentKind,
+ recentDocumentView,
+ rememberRecentDocumentView,
rememberRecentFile,
rememberRecentStorageDocument,
type RecentDocument,
+ type RecentDocumentView,
type RecentLocalDocument,
type RecentStorageDocument
} from './store'
+export { rememberDocumentView, rememberedDocumentView } from './view'
export {
cacheRecentFileCover,
cacheRecentFileThumbnail,
diff --git a/src/app/recent-files/schema.ts b/src/app/recent-files/schema.ts
index 791fd9450..99af915e0 100644
--- a/src/app/recent-files/schema.ts
+++ b/src/app/recent-files/schema.ts
@@ -1,5 +1,7 @@
import * as v from 'valibot'
+import { ZOOM_MAX, ZOOM_MIN } from '@open-pencil/core/constants'
+
export const RECENT_FILES_LIMIT_MIN = 1
export const RECENT_FILES_LIMIT_MAX = 1000
@@ -9,3 +11,13 @@ export const recentFilesLimitSchema = v.pipe(
v.minValue(RECENT_FILES_LIMIT_MIN),
v.maxValue(RECENT_FILES_LIMIT_MAX)
)
+
+const finiteSchema = v.pipe(v.number(), v.finite())
+
+/** The page and view a document was left at, which it opens on again, as in Figma. */
+export const recentDocumentViewSchema = v.object({
+ pageId: v.pipe(v.string(), v.nonEmpty()),
+ /** The world point at the centre of the canvas. */
+ center: v.object({ x: finiteSchema, y: finiteSchema }),
+ zoom: v.pipe(finiteSchema, v.minValue(ZOOM_MIN), v.maxValue(ZOOM_MAX))
+})
diff --git a/src/app/recent-files/store.ts b/src/app/recent-files/store.ts
index a9e7197c8..f4b407ad1 100644
--- a/src/app/recent-files/store.ts
+++ b/src/app/recent-files/store.ts
@@ -1,5 +1,6 @@
import { useLocalStorage } from '@vueuse/core'
import { basename } from 'pathe'
+import * as v from 'valibot'
import { computed } from 'vue'
import { DOCUMENT_EXTENSIONS } from '@open-pencil/core/io'
@@ -14,10 +15,13 @@ import {
} from '@/app/integrations/storage'
import { recentFilesLimit } from './preferences'
+import { recentDocumentViewSchema } from './schema'
import { clearRecentFileThumbnails } from './thumbnails'
const RECENT_DOCUMENTS_STORAGE_KEY = 'open-pencil:recent-documents'
+export type RecentDocumentView = v.InferOutput<typeof recentDocumentViewSchema>
+
export interface RecentLocalDocument {
id: string
kind: 'local'
@@ -26,6 +30,7 @@ export interface RecentLocalDocument {
updatedAt: string
/** A design or a board; entries recorded before this was kept have none. */
documentKind?: DocumentKind
+ view?: RecentDocumentView
}
export interface RecentStorageDocument {
@@ -39,6 +44,7 @@ export interface RecentStorageDocument {
updatedAt: string
/** A design or a board; entries recorded before this was kept have none. */
documentKind?: DocumentKind
+ view?: RecentDocumentView
}
export type RecentDocument = RecentLocalDocument | RecentStorageDocument
@@ -74,10 +80,41 @@ export const recentLocalFilePaths = computed<string[]>(() =>
)
function remember(document: RecentDocument): void {
- recentDocuments.value = [
- document,
- ...normalizedRecentDocuments().filter((recent) => recent.id !== document.id)
- ].slice(0, recentFilesLimit.value)
+ const others = normalizedRecentDocuments().filter((recent) => recent.id !== document.id)
+ const previous = recentDocuments.value.find((recent) => recent.id === document.id)
+ // Opening or saving a document again keeps the view it was left at.
+ const view = document.view ?? previous?.view
+ recentDocuments.value = [view ? { ...document, view } : document, ...others].slice(
+ 0,
+ recentFilesLimit.value
+ )
+}
+
+/**
+ * The recent-files id of an open document: a stored one by its binding, a file by its path; none
+ * for a document that is neither, which recent files do not list.
+ */
+export function recentDocumentIdOf(
+ path: string | null,
+ binding: StorageDocumentBinding | null
+): string | null {
+ if (binding) return storageDocumentId(binding)
+ return path ? localDocumentId(path) : null
+}
+
+/** Keeps the view a listed document was left at, without moving it up the list. */
+export function rememberRecentDocumentView(id: string, view: RecentDocumentView): void {
+ if (!recentDocuments.value.some((document) => document.id === id)) return
+ recentDocuments.value = recentDocuments.value.map((document) =>
+ document.id === id ? { ...document, view } : document
+ )
+}
+
+/** The view a listed document was left at, if one was kept and stored intact. */
+export function recentDocumentView(id: string): RecentDocumentView | null {
+ const view: unknown = recentDocuments.value.find((document) => document.id === id)?.view
+ const parsed = v.safeParse(recentDocumentViewSchema, view)
+ return parsed.success ? parsed.output : null
}
/** What a file on this device is by its name: a FigJam `.jam` is a board, anything else a design. */
diff --git a/src/app/recent-files/view.ts b/src/app/recent-files/view.ts
new file mode 100644
index 000000000..f52e4e638
--- /dev/null
+++ b/src/app/recent-files/view.ts
@@ -0,0 +1,41 @@
+import type { EditorStore } from '@/app/editor/session'
+
+import {
+ recentDocumentIdOf,
+ recentDocumentView,
+ rememberRecentDocumentView,
+ type RecentDocumentView
+} from './store'
+
+type ViewedDocument = Pick<
+ EditorStore,
+ 'graph' | 'state' | 'getDocumentFilePath' | 'getStorageBinding' | 'getViewportSize'
+>
+
+function recentIdOf(store: ViewedDocument): string | null {
+ return recentDocumentIdOf(store.getDocumentFilePath(), store.getStorageBinding())
+}
+
+/** Keeps the page and view a tab shows its document at, for the document's next open. */
+export function rememberDocumentView(store: ViewedDocument): void {
+ const id = recentIdOf(store)
+ if (!id) return
+ const { width, height } = store.getViewportSize()
+ const { panX, panY, zoom, currentPageId } = store.state
+ if (width <= 0 || height <= 0 || zoom <= 0) return
+ const center = { x: (width / 2 - panX) / zoom, y: (height / 2 - panY) / zoom }
+ // A view too far out to store as a number opens fitted instead.
+ if (!Number.isFinite(center.x) || !Number.isFinite(center.y)) return
+ rememberRecentDocumentView(id, { pageId: currentPageId, center, zoom })
+}
+
+/**
+ * The view the document was left at, when one was kept and its page is still one of the document's
+ * visible pages; an internal page an automation left current opens the first page instead.
+ */
+export function rememberedDocumentView(store: ViewedDocument): RecentDocumentView | null {
+ const id = recentIdOf(store)
+ const view = id ? recentDocumentView(id) : null
+ if (!view || !store.graph.getPages().some((page) => page.id === view.pageId)) return null
+ return view
+}
diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.ts
index bb2e51a95..579b30953 100644
--- a/src/app/tabs/index.ts
+++ b/src/app/tabs/index.ts
@@ -37,6 +37,8 @@ import {
import {
cacheRecentFileCover,
loadCachedRecentFileThumbnail,
+ rememberDocumentView,
+ rememberedDocumentView,
rememberRecentStorageDocument
} from '@/app/recent-files'
import { createDeferred } from '@/app/runtime/deferred'
@@ -241,6 +243,7 @@ export async function closeTab(tabId: string, unsaved?: 'save' | 'discard'): Pro
else await closingTab.store.persistRecoveryNow()
if (!tabsRef.value.includes(closingTab)) return
if (choice !== 'discard' && closingTab.store.hasUnsavedChanges()) return
+ rememberDocumentView(closingTab.store)
removeTab(closingTab)
}
@@ -347,12 +350,20 @@ async function showImportedGraph(
load?.signal.throwIfAborted()
await prepare?.()
load?.signal.throwIfAborted()
- const pageId = store.graph.getPages()[0]?.id ?? store.graph.rootId
+ // A document opens where it was left; a new one on its first page, fitted.
+ const remembered = rememberedDocumentView(store)
+ const firstPageId = store.graph.getPages()[0]?.id ?? store.graph.rootId
+ const pageId = remembered?.pageId ?? firstPageId
load?.update({ phase: 'populating-page', detail: store.graph.getNode(pageId)?.name ?? null })
await store.switchPage(pageId, { preparation: load })
load?.signal.throwIfAborted()
load?.update({ phase: 'preparing-render', detail: store.state.documentName })
- await store.fitCurrentPageToViewport()
+ if (remembered) {
+ await yieldToUI()
+ store.centerOn(remembered.center.x, remembered.center.y, remembered.zoom)
+ } else {
+ await store.fitCurrentPageToViewport()
+ }
}
async function cacheOpenedFigCover(path: string, store: EditorStore): Promise<void> {
@@ -682,13 +693,18 @@ export async function restoreRecoverySnapshot(id: string): Promise<void> {
}
}
-export function prepareForClose(): Promise<boolean> {
- return confirmAllDocuments(() =>
- tabsRef.value.filter((tab) => tab.kind === 'document').map((tab) => tab.store)
- )
+function documentStores(): EditorStore[] {
+ return tabsRef.value.filter((tab) => tab.kind === 'document').map((tab) => tab.store)
+}
+
+export async function prepareForClose(): Promise<boolean> {
+ const closing = await confirmAllDocuments(documentStores)
+ if (closing) documentStores().forEach(rememberDocumentView)
+ return closing
}
export async function prepareForReload(): Promise<void> {
+ documentStores().forEach(rememberDocumentView)
await Promise.all(tabsRef.value.map((tab) => tab.store.persistRecoveryNow()))
}
diff --git a/tests/app/recent-files/view.test.ts b/tests/app/recent-files/view.test.ts
new file mode 100644
index 000000000..11027a1ee
--- /dev/null
+++ b/tests/app/recent-files/view.test.ts
@@ -0,0 +1,108 @@
+import 'fake-indexeddb/auto'
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
+
+import { createEditorStore } from '@/app/editor/session/create'
+import {
+ recentDocuments,
+ rememberDocumentView,
+ rememberedDocumentView,
+ rememberRecentFile
+} from '@/app/recent-files'
+
+const PATH = '/designs/poster.fig'
+
+let recentBefore: typeof recentDocuments.value
+
+beforeEach(() => {
+ // Recent files live in shared storage; each test starts from none and leaves them as it found them.
+ recentBefore = recentDocuments.value
+ recentDocuments.value = []
+})
+
+afterEach(() => {
+ recentDocuments.value = recentBefore
+})
+
+/** A store showing a file on this device, as a tab opened from a path has. */
+function openedFromPath(path = PATH) {
+ const store = createEditorStore()
+ store.setViewportSize(1920, 1080)
+ store.setDocumentSource('poster.fig', 'fig', undefined, path)
+ return store
+}
+
+// Figma reopens a file on the page and at the view it was left at.
+describe("a document's remembered view", () => {
+ test('keeps the page and the world point at the canvas centre with the recent file', async () => {
+ const store = openedFromPath()
+ rememberRecentFile(PATH, 'design')
+ const second = store.graph.addPage('Second').id
+ store.preparationController.acknowledgePresentation(Number.MAX_SAFE_INTEGER)
+ await store.switchPage(second)
+ store.centerOn(300, 200, 2)
+
+ rememberDocumentView(store)
+
+ const again = openedFromPath()
+ again.graph.addPage('Second')
+ expect(rememberedDocumentView(again)).toBeNull()
+ expect(rememberedDocumentView(store)).toEqual({
+ pageId: second,
+ center: { x: 300, y: 200 },
+ zoom: 2
+ })
+ })
+
+ test('is kept when the file is opened again and forgotten with the file', () => {
+ const store = openedFromPath()
+ rememberRecentFile(PATH, 'design')
+ rememberDocumentView(store)
+ const view = rememberedDocumentView(store)
+ expect(view).not.toBeNull()
+
+ rememberRecentFile(PATH, 'design')
+ expect(rememberedDocumentView(store)).toEqual(view)
+
+ recentDocuments.value = []
+ expect(rememberedDocumentView(store)).toBeNull()
+ })
+
+ test('is ignored when stored malformed, or on a page the document hides', async () => {
+ const store = openedFromPath()
+ rememberRecentFile(PATH, 'design')
+ const first = store.state.currentPageId
+ const hidden = store.graph.addPage('Internal')
+ store.graph.updateNode(hidden.id, { internalOnly: true })
+
+ rememberDocumentView(store)
+ recentDocuments.value = recentDocuments.value.map((document) => ({
+ ...document,
+ view: { pageId: first, zoom: 1 } as never
+ }))
+ expect(rememberedDocumentView(store)).toBeNull()
+
+ store.preparationController.acknowledgePresentation(Number.MAX_SAFE_INTEGER)
+ await store.switchPage(hidden.id)
+ rememberDocumentView(store)
+ expect(recentDocuments.value[0]?.view?.pageId).toBe(hidden.id)
+ expect(rememberedDocumentView(store)).toBeNull()
+ })
+
+ test('is not kept for a document recent files do not list', () => {
+ const store = openedFromPath()
+ rememberDocumentView(store)
+ expect(recentDocuments.value).toEqual([])
+ expect(rememberedDocumentView(store)).toBeNull()
+ })
+
+ test('is not kept for an unsaved document, or before the canvas has a size', () => {
+ const store = createEditorStore()
+ rememberRecentFile(PATH, 'design')
+ rememberDocumentView(store)
+ expect(recentDocuments.value[0]?.view).toBeUndefined()
+
+ store.setViewportSize(1920, 1080)
+ rememberDocumentView(store)
+ expect(recentDocuments.value[0]?.view).toBeUndefined()
+ })
+})
diff --git a/tests/e2e/canvas/instance-sizing.spec.ts-snapshots/instance-fill-sizing-openpencil-darwin.png b/tests/e2e/canvas/instance-sizing.spec.ts-snapshots/instance-fill-sizing-openpencil-darwin.png
index 624d64518..d01fe1ae4 100644
Binary files a/tests/e2e/canvas/instance-sizing.spec.ts-snapshots/instance-fill-sizing-openpencil-darwin.png and b/tests/e2e/canvas/instance-sizing.spec.ts-snapshots/instance-fill-sizing-openpencil-darwin.png differ