tldraw/state/commands/create-page.ts

87 lines
2.1 KiB
TypeScript
Raw Normal View History

2021-06-03 13:10:54 +00:00
import Command from './command'
import history from '../history'
import { Data, Page, PageState } from 'types'
import { uniqueId } from 'utils/utils'
2021-07-09 18:42:43 +00:00
import tld from 'utils/tld'
import storage from 'state/storage'
2021-06-03 13:10:54 +00:00
2021-06-21 21:35:28 +00:00
export default function createPage(data: Data, goToPage = true): void {
2021-06-03 13:10:54 +00:00
const snapshot = getSnapshot(data)
history.execute(
data,
new Command({
2021-06-19 17:22:46 +00:00
name: 'create_page',
2021-06-03 13:10:54 +00:00
category: 'canvas',
do(data) {
2021-06-17 12:03:08 +00:00
const { page, pageState, currentPageId } = snapshot
storage.savePage(data, data.document.id, currentPageId)
2021-06-03 13:10:54 +00:00
data.document.pages[page.id] = page
data.pageStates[page.id] = pageState
2021-06-17 12:03:08 +00:00
2021-07-14 11:39:34 +00:00
storage.savePage(data, data.document.id, page.id)
2021-06-17 12:03:08 +00:00
if (goToPage) {
storage.loadPage(data, data.document.id, page.id)
2021-06-17 12:03:08 +00:00
data.currentPageId = page.id
data.currentParentId = page.id
tld.setZoomCSS(tld.getPageState(data).camera.zoom)
}
2021-07-14 11:39:34 +00:00
storage.saveAppStateToLocalStorage(data)
storage.saveDocumentToLocalStorage(data)
2021-06-03 13:10:54 +00:00
},
undo(data) {
const { page, currentPageId } = snapshot
delete data.document.pages[page.id]
delete data.pageStates[page.id]
if (goToPage) {
storage.loadPage(data, data.document.id, currentPageId)
data.currentPageId = currentPageId
data.currentParentId = currentPageId
tld.setZoomCSS(tld.getPageState(data).camera.zoom)
}
2021-07-14 11:39:34 +00:00
storage.saveAppStateToLocalStorage(data)
storage.saveDocumentToLocalStorage(data)
2021-06-03 13:10:54 +00:00
},
})
)
}
function getSnapshot(data: Data) {
2021-06-24 12:34:43 +00:00
const { currentPageId } = data
2021-06-03 13:10:54 +00:00
const pages = Object.values(data.document.pages)
const unchanged = pages.filter((page) => page.name.startsWith('Page '))
const id = uniqueId()
2021-06-03 13:10:54 +00:00
const page: Page = {
type: 'page',
id,
name: `Page ${unchanged.length + 1}`,
childIndex: pages.length,
shapes: {},
}
2021-06-17 12:03:08 +00:00
const pageState: PageState = {
id,
selectedIds: [],
2021-06-03 13:10:54 +00:00
camera: {
point: [0, 0],
zoom: 1,
},
}
return {
currentPageId,
page,
pageState,
}
}