tldraw/state/commands/generate.ts

73 lines
1.6 KiB
TypeScript
Raw Normal View History

import Command from './command'
import history from '../history'
import { CodeControl, Data, Shape } from 'types'
import { current } from 'immer'
import { getPage, getSelectedIds, setSelectedIds } from 'utils/utils'
2021-05-15 13:02:13 +00:00
2021-05-19 09:35:00 +00:00
export default function generateCommand(
2021-05-15 13:02:13 +00:00
data: Data,
currentPageId: string,
generatedShapes: Shape[]
) {
2021-05-17 10:01:11 +00:00
const cData = current(data)
const page = getPage(cData)
2021-05-17 10:01:11 +00:00
const currentShapes = page.shapes
2021-05-15 13:02:13 +00:00
const prevGeneratedShapes = Object.values(currentShapes).filter(
(shape) => shape.isGenerated
)
2021-05-17 10:01:11 +00:00
// Remove previous generated shapes
for (let id in currentShapes) {
if (currentShapes[id].isGenerated) {
delete currentShapes[id]
}
}
// Add new ones
2021-05-15 13:02:13 +00:00
for (let shape of generatedShapes) {
2021-05-17 10:01:11 +00:00
currentShapes[shape.id] = shape
2021-05-15 13:02:13 +00:00
}
history.execute(
data,
new Command({
name: 'translate_shapes',
category: 'canvas',
2021-05-15 13:02:13 +00:00
do(data) {
const { shapes } = getPage(data)
2021-05-15 13:02:13 +00:00
setSelectedIds(data, [])
2021-05-15 13:02:13 +00:00
// Remove previous generated shapes
for (let id in shapes) {
if (shapes[id].isGenerated) {
delete shapes[id]
}
}
// Add new generated shapes
for (let shape of generatedShapes) {
shapes[shape.id] = shape
}
},
undo(data) {
const { shapes } = getPage(data)
2021-05-15 13:02:13 +00:00
// Remove generated shapes
for (let id in shapes) {
if (shapes[id].isGenerated) {
delete shapes[id]
}
}
// Restore previous generated shapes
for (let shape of prevGeneratedShapes) {
shapes[shape.id] = shape
}
},
})
)
}