tldraw/state/commands/toggle.ts

53 lines
1.4 KiB
TypeScript
Raw Normal View History

import Command from './command'
import history from '../history'
import { Data, Shape } from 'types'
2021-06-29 12:00:59 +00:00
import tld from 'utils/tld'
2021-06-21 21:35:28 +00:00
import { getShapeUtils } from 'state/shape-utils'
import { PropsOfType } from 'types'
/**
* The toggle command toggles a boolean property on all selected shapes.
* If the value is true for all selected shapes, then the property is
* set to false; the value is false for one or more of the selected
* shapes, then the value for all shapes is set to true.
*/
export default function toggleCommand(
data: Data,
2021-06-21 21:35:28 +00:00
prop: PropsOfType<Shape>
): void {
2021-06-29 12:00:59 +00:00
const selectedShapes = tld.getSelectedShapes(data)
const isAllToggled = selectedShapes.every((shape) => shape[prop])
const initialShapes = selectedShapes.map((shape) => ({
id: shape.id,
value: shape[prop],
}))
history.execute(
data,
new Command({
2021-06-19 17:22:46 +00:00
name: 'toggle_prop',
category: 'canvas',
do(data) {
2021-06-29 12:00:59 +00:00
const { shapes } = tld.getPage(data)
initialShapes.forEach(({ id }) => {
const shape = shapes[id]
getShapeUtils(shape).setProperty(
shape,
prop,
isAllToggled ? false : true
)
})
},
undo(data) {
2021-06-29 12:00:59 +00:00
const { shapes } = tld.getPage(data)
initialShapes.forEach(({ id, value }) => {
const shape = shapes[id]
getShapeUtils(shape).setProperty(shape, prop, value)
})
},
})
)
}