tldraw/state/sessions/brush-session.ts

91 lines
2.4 KiB
TypeScript
Raw Normal View History

import { current } from 'immer'
2021-06-04 16:08:43 +00:00
import { Bounds, Data, ShapeType } from 'types'
import BaseSession from './base-session'
import { getShapeUtils } from 'lib/shape-utils'
2021-06-04 16:08:43 +00:00
import { getBoundsFromPoints, getPage, getShapes } from 'utils/utils'
import * as vec from 'utils/vec'
import state from 'state/state'
2021-05-10 12:16:57 +00:00
export default class BrushSession extends BaseSession {
origin: number[]
snapshot: BrushSnapshot
constructor(data: Data, point: number[]) {
super(data)
this.origin = vec.round(point)
this.snapshot = getBrushSnapshot(data)
2021-05-10 12:16:57 +00:00
}
update = (data: Data, point: number[]) => {
const { origin, snapshot } = this
2021-05-18 08:32:20 +00:00
const brushBounds = getBoundsFromPoints([origin, point])
2021-05-10 12:16:57 +00:00
2021-06-04 17:56:46 +00:00
const hits = new Set<string>([])
for (let id in snapshot.shapeHitTests) {
2021-06-04 16:08:43 +00:00
const { test, selectId } = snapshot.shapeHitTests[id]
2021-06-04 17:56:46 +00:00
if (!hits.has(selectId)) {
if (test(brushBounds)) {
hits.add(selectId)
// When brushing a shape, select its top group parent.
if (!data.selectedIds.has(selectId)) {
data.selectedIds.add(selectId)
}
} else if (data.selectedIds.has(selectId)) {
data.selectedIds.delete(selectId)
}
2021-05-12 11:27:33 +00:00
}
}
2021-05-10 12:16:57 +00:00
data.brush = brushBounds
2021-05-10 12:16:57 +00:00
}
cancel = (data: Data) => {
data.brush = undefined
2021-05-12 11:27:33 +00:00
data.selectedIds = new Set(this.snapshot.selectedIds)
2021-05-10 12:16:57 +00:00
}
complete = (data: Data) => {
data.brush = undefined
}
}
2021-05-10 12:16:57 +00:00
/**
* Get a snapshot of the current selected ids, for each shape that is
* not already selected, the shape's id and a test to see whether the
* brush will intersect that shape. For tests, start broad -> fine.
*/
export function getBrushSnapshot(data: Data) {
return {
selectedIds: new Set(data.selectedIds),
shapeHitTests: Object.fromEntries(
getShapes(state.data)
2021-06-04 16:08:43 +00:00
.filter((shape) => shape.type !== ShapeType.Group)
2021-06-04 21:21:03 +00:00
.map((shape) => {
return [
shape.id,
{
selectId: getTopParentId(data, shape.id),
test: (bounds: Bounds) =>
getShapeUtils(shape).hitTestBounds(shape, bounds),
},
]
})
),
2021-05-10 12:16:57 +00:00
}
}
export type BrushSnapshot = ReturnType<typeof getBrushSnapshot>
2021-06-04 16:08:43 +00:00
function getTopParentId(data: Data, id: string): string {
const shape = getPage(data).shapes[id]
return shape.parentId === data.currentPageId ||
shape.parentId === data.currentParentId
? id
: getTopParentId(data, shape.parentId)
}