tldraw/state/commands/delete-page.ts

53 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-06-03 13:10:54 +00:00
import Command from './command'
import history from '../history'
import { Data } from 'types'
import storage from 'state/storage'
2021-06-29 12:00:59 +00:00
import { deepClone } from 'utils'
import tld from 'utils/tld'
2021-06-03 13:10:54 +00:00
2021-06-21 21:35:28 +00:00
export default function deletePage(data: Data, pageId: string): void {
2021-06-03 13:10:54 +00:00
const snapshot = getSnapshot(data, pageId)
history.execute(
data,
new Command({
2021-06-19 17:22:46 +00:00
name: 'delete_page',
2021-06-03 13:10:54 +00:00
category: 'canvas',
do(data) {
data.currentPageId = snapshot.nextPageId
delete data.document.pages[pageId]
delete data.pageStates[pageId]
storage.loadPage(data, snapshot.nextPageId)
2021-06-03 13:10:54 +00:00
},
undo(data) {
data.currentPageId = snapshot.currentPageId
data.document.pages[pageId] = snapshot.page
data.pageStates[pageId] = snapshot.pageState
storage.loadPage(data, snapshot.currentPageId)
2021-06-03 13:10:54 +00:00
},
})
)
}
function getSnapshot(data: Data, pageId: string) {
2021-06-24 12:34:43 +00:00
const { currentPageId, document } = data
2021-06-03 13:10:54 +00:00
2021-06-29 12:00:59 +00:00
const page = deepClone(tld.getPage(data))
2021-06-03 13:10:54 +00:00
2021-06-29 12:00:59 +00:00
const pageState = deepClone(tld.getPageState(data))
2021-06-03 13:10:54 +00:00
2021-06-24 12:34:43 +00:00
const isCurrent = data.currentPageId === pageId
2021-06-03 13:10:54 +00:00
const nextPageId = isCurrent
? Object.values(document.pages).filter((page) => page.id !== pageId)[0]?.id // TODO: should be at nextIndex
2021-06-24 12:34:43 +00:00
: currentPageId
2021-06-03 13:10:54 +00:00
return {
nextPageId,
isCurrent,
currentPageId,
page,
pageState,
}
}