tldraw/state/commands/duplicate.ts

58 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-05-28 20:30:27 +00:00
import Command from './command'
import history from '../history'
import { Data } from 'types'
import {
getCurrentCamera,
getPage,
getSelectedIds,
getSelectedShapes,
setSelectedIds,
} from 'utils/utils'
import { uniqueId } from 'utils/utils'
2021-05-28 20:30:27 +00:00
import { current } from 'immer'
import vec from 'utils/vec'
2021-05-28 20:30:27 +00:00
export default function duplicateCommand(data: Data) {
const { currentPageId } = data
const selectedShapes = getSelectedShapes(current(data))
const duplicates = selectedShapes.map((shape) => ({
...shape,
id: uniqueId(),
2021-06-03 12:06:39 +00:00
point: vec.add(shape.point, vec.div([16, 16], getCurrentCamera(data).zoom)),
2021-06-19 17:22:46 +00:00
isGenerated: false,
2021-05-28 20:30:27 +00:00
}))
history.execute(
data,
new Command({
name: 'duplicate_shapes',
category: 'canvas',
manualSelection: true,
do(data) {
const { shapes } = getPage(data, currentPageId)
for (const duplicate of duplicates) {
shapes[duplicate.id] = duplicate
}
setSelectedIds(
data,
duplicates.map((d) => d.id)
)
2021-05-28 20:30:27 +00:00
},
undo(data) {
const { shapes } = getPage(data, currentPageId)
for (const duplicate of duplicates) {
delete shapes[duplicate.id]
}
setSelectedIds(
data,
selectedShapes.map((d) => d.id)
)
2021-05-28 20:30:27 +00:00
},
})
)
}