Perf: Use a computed cache for masked shape page bounds (#3460)

This PR adds a computed cache for masked shape page bounds, which speeds
up visibility checks (a lot!).

### Change Type

- [x] `sdk` — Changes the tldraw SDK
- [x] `improvement` — Improving existing features
This commit is contained in:
Steve Ruiz 2024-04-13 21:07:10 +01:00 committed by GitHub
parent 143755fda0
commit 87f70b7de5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -4057,22 +4057,25 @@ export class Editor extends EventEmitter<TLEventMap> {
*/ */
getShapeMaskedPageBounds(shape: TLShapeId | TLShape): Box | undefined { getShapeMaskedPageBounds(shape: TLShapeId | TLShape): Box | undefined {
if (typeof shape !== 'string') shape = shape.id if (typeof shape !== 'string') shape = shape.id
const pageBounds = this._getShapePageBoundsCache().get(shape) return this._getShapeMaskedPageBoundsCache().get(shape)
if (!pageBounds) return }
const pageMask = this._getShapeMaskCache().get(shape)
if (pageMask) {
if (pageMask.length === 0) return undefined
const { corners } = pageBounds /** @internal */
if (corners.every((p, i) => p && Vec.Equals(p, pageMask[i]))) return pageBounds.clone() @computed private _getShapeMaskedPageBoundsCache(): ComputedCache<Box, TLShape> {
return this.store.createComputedCache('shapeMaskedPageBoundsCache', (shape) => {
// todo: find out why intersect polygon polygon for identical polygons produces zero w/h intersections const pageBounds = this._getShapePageBoundsCache().get(shape.id)
const intersection = intersectPolygonPolygon(pageMask, corners) if (!pageBounds) return
if (!intersection) return const pageMask = this._getShapeMaskCache().get(shape.id)
return Box.FromPoints(intersection) if (pageMask) {
} if (pageMask.length === 0) return undefined
const { corners } = pageBounds
return pageBounds if (corners.every((p, i) => p && Vec.Equals(p, pageMask[i]))) return pageBounds.clone()
const intersection = intersectPolygonPolygon(pageMask, corners)
if (!intersection) return
return Box.FromPoints(intersection)
}
return pageBounds
})
} }
/** /**