tldraw/state/commands/delete-page.ts

83 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 } 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) {
storage.saveAppStateToLocalStorage(data)
storage.saveDocumentToLocalStorage(data)
2021-06-03 13:10:54 +00:00
data.currentPageId = snapshot.nextPageId
data.currentParentId = snapshot.nextPageId
2021-06-03 13:10:54 +00:00
delete data.document.pages[pageId]
delete data.pageStates[pageId]
if (snapshot.isCurrent) {
2021-07-14 11:39:34 +00:00
storage.loadPage(data, data.document.id, snapshot.nextPageId)
}
2021-07-14 11:39:34 +00:00
storage.saveAppStateToLocalStorage(data)
storage.saveDocumentToLocalStorage(data)
2021-06-03 13:10:54 +00:00
},
undo(data) {
storage.saveAppStateToLocalStorage(data)
storage.saveDocumentToLocalStorage(data)
2021-06-03 13:10:54 +00:00
data.currentPageId = snapshot.currentPageId
data.currentParentId = snapshot.currentParentId
2021-06-03 13:10:54 +00:00
data.document.pages[pageId] = snapshot.page
data.pageStates[pageId] = snapshot.pageState
if (snapshot.isCurrent) {
2021-07-14 11:39:34 +00:00
storage.loadPage(data, data.document.id, snapshot.currentPageId)
}
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, pageId: string) {
const { currentPageId, currentParentId, 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 pageIds = Object.keys(document.pages)
const pageIndex = pageIds.indexOf(pageId)
2021-06-03 13:10:54 +00:00
const nextPageId = isCurrent
? pageIndex === 0
? pageIds[1]
: pageIndex === pageIds.length - 1
? pageIds[pageIndex - 1]
: pageIds[pageIndex + 1]
2021-06-24 12:34:43 +00:00
: currentPageId
2021-06-03 13:10:54 +00:00
return {
nextPageId,
isCurrent,
currentPageId,
currentParentId,
2021-06-03 13:10:54 +00:00
page,
pageState,
}
}