tldraw/state/commands/create-page.ts

71 lines
1.6 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'
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
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-06-03 13:10:54 +00:00
data.currentPageId = page.id
storage.savePage(data, data.document.id, page.id)
storage.saveDocumentToLocalStorage(data)
2021-06-17 12:03:08 +00:00
if (goToPage) {
data.currentPageId = page.id
} else {
data.currentPageId = currentPageId
}
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]
data.currentPageId = currentPageId
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: new Set([]),
2021-06-03 13:10:54 +00:00
camera: {
point: [0, 0],
zoom: 1,
},
}
return {
currentPageId,
page,
pageState,
}
}