@tldraw/editor 4.5.0-canary.034ea85352da → 4.5.0-canary.0d748e7df5db

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist-cjs/index.d.ts +24 -1
  2. package/dist-cjs/index.js +1 -1
  3. package/dist-cjs/lib/components/default-components/DefaultCanvas.js +13 -16
  4. package/dist-cjs/lib/components/default-components/DefaultCanvas.js.map +2 -2
  5. package/dist-cjs/lib/editor/Editor.js +206 -254
  6. package/dist-cjs/lib/editor/Editor.js.map +2 -2
  7. package/dist-cjs/lib/editor/managers/HistoryManager/HistoryManager.js +15 -16
  8. package/dist-cjs/lib/editor/managers/HistoryManager/HistoryManager.js.map +3 -3
  9. package/dist-cjs/lib/editor/shapes/ShapeUtil.js.map +1 -1
  10. package/dist-cjs/lib/hooks/useCanvasEvents.js +1 -1
  11. package/dist-cjs/lib/hooks/useCanvasEvents.js.map +2 -2
  12. package/dist-cjs/lib/primitives/geometry/Geometry2d.js +10 -0
  13. package/dist-cjs/lib/primitives/geometry/Geometry2d.js.map +2 -2
  14. package/dist-cjs/version.js +3 -3
  15. package/dist-cjs/version.js.map +1 -1
  16. package/dist-esm/index.d.mts +24 -1
  17. package/dist-esm/index.mjs +1 -1
  18. package/dist-esm/lib/components/default-components/DefaultCanvas.mjs +13 -16
  19. package/dist-esm/lib/components/default-components/DefaultCanvas.mjs.map +2 -2
  20. package/dist-esm/lib/editor/Editor.mjs +207 -255
  21. package/dist-esm/lib/editor/Editor.mjs.map +2 -2
  22. package/dist-esm/lib/editor/managers/HistoryManager/HistoryManager.mjs +15 -16
  23. package/dist-esm/lib/editor/managers/HistoryManager/HistoryManager.mjs.map +3 -3
  24. package/dist-esm/lib/editor/shapes/ShapeUtil.mjs.map +1 -1
  25. package/dist-esm/lib/hooks/useCanvasEvents.mjs +1 -1
  26. package/dist-esm/lib/hooks/useCanvasEvents.mjs.map +2 -2
  27. package/dist-esm/lib/primitives/geometry/Geometry2d.mjs +10 -0
  28. package/dist-esm/lib/primitives/geometry/Geometry2d.mjs.map +2 -2
  29. package/dist-esm/version.mjs +3 -3
  30. package/dist-esm/version.mjs.map +1 -1
  31. package/package.json +7 -7
  32. package/src/lib/components/default-components/DefaultCanvas.tsx +19 -26
  33. package/src/lib/editor/Editor.ts +283 -393
  34. package/src/lib/editor/managers/HistoryManager/HistoryManager.ts +6 -5
  35. package/src/lib/editor/shapes/ShapeUtil.ts +1 -1
  36. package/src/lib/hooks/useCanvasEvents.ts +1 -1
  37. package/src/lib/primitives/geometry/Geometry2d.ts +12 -0
  38. package/src/version.ts +3 -3
@@ -34,7 +34,6 @@ import {
34
34
  TLCursorType,
35
35
  TLDOCUMENT_ID,
36
36
  TLDocument,
37
- TLFrameShape,
38
37
  TLGroupShape,
39
38
  TLHandle,
40
39
  TLINSTANCE_ID,
@@ -134,7 +133,7 @@ import {
134
133
  } from '../utils/deepLinks'
135
134
  import { getIncrementedName } from '../utils/getIncrementedName'
136
135
  import { getReorderingShapesChanges } from '../utils/reorderShapes'
137
- import { getDroppedShapesToNewParents } from '../utils/reparenting'
136
+ import { getDroppedShapesToNewParents, kickoutOccludedShapes } from '../utils/reparenting'
138
137
  import { TLTextOptions, TiptapEditor } from '../utils/richText'
139
138
  import { applyRotationToSnapshotShapes, getRotationSnapshot } from '../utils/rotation'
140
139
  import { BindingOnDeleteOptions, BindingUtil } from './bindings/BindingUtil'
@@ -159,6 +158,7 @@ import {
159
158
  TLEditStartInfo,
160
159
  TLGeometryOpts,
161
160
  TLResizeMode,
161
+ TLShapeUtilCanBeLaidOutOpts,
162
162
  TLShapeUtilCanBindOpts,
163
163
  } from './shapes/ShapeUtil'
164
164
  import { RootState } from './tools/RootState'
@@ -5404,6 +5404,11 @@ export class Editor extends EventEmitter<TLEventMap> {
5404
5404
  // Are we close to the shape's edge?
5405
5405
  if (distance <= outerMargin || (hitInside && distance <= 0 && distance > -innerMargin)) {
5406
5406
  if (geometry.isFilled || (isGroup && geometry.children[0].isFilled)) {
5407
+ // If the geometry rejects this hit (e.g. transparent image pixel),
5408
+ // skip this shape and check shapes behind it.
5409
+ if (geometry.ignoreHit(pointInShapeSpace)) {
5410
+ continue
5411
+ }
5407
5412
  // If the shape is filled, then it's a hit. Remember, we're
5408
5413
  // starting from the TOP-MOST shape in z-index order, so any
5409
5414
  // other hits would be occluded by the shape.
@@ -6767,6 +6772,77 @@ export class Editor extends EventEmitter<TLEventMap> {
6767
6772
  return this
6768
6773
  }
6769
6774
 
6775
+ /**
6776
+ * Shared clustering logic for layout methods. Resolves shapes, optionally filters to
6777
+ * axis-aligned shapes, checks canBeLaidOut, and groups shapes into clusters via arrow bindings.
6778
+ *
6779
+ * @internal
6780
+ */
6781
+ private getShapeClusters(
6782
+ shapes: TLShapeId[] | TLShape[],
6783
+ type: TLShapeUtilCanBeLaidOutOpts['type'],
6784
+ opts?: { filterAxisAligned?: boolean }
6785
+ ): { clusters: { shapes: TLShape[]; pageBounds: Box }[]; allBounds: Box[] } {
6786
+ const ids =
6787
+ typeof shapes[0] === 'string'
6788
+ ? (shapes as TLShapeId[])
6789
+ : (shapes as TLShape[]).map((s) => s.id)
6790
+
6791
+ // always fresh shapes
6792
+ let freshShapes = compact(ids.map((id) => this.getShape(id)))
6793
+
6794
+ // optionally filter to axis-aligned shapes (rotation is a multiple of 90 degrees)
6795
+ if (opts?.filterAxisAligned) {
6796
+ freshShapes = freshShapes.filter(
6797
+ (s) => this.getShapePageTransform(s)?.rotation() % (PI / 2) === 0
6798
+ )
6799
+ }
6800
+
6801
+ const clusters: { shapes: TLShape[]; pageBounds: Box }[] = []
6802
+ const allBounds: Box[] = []
6803
+ const visited = new Set<TLShapeId>()
6804
+
6805
+ for (const shape of freshShapes) {
6806
+ if (visited.has(shape.id)) continue
6807
+ visited.add(shape.id)
6808
+
6809
+ const shapePageBounds = this.getShapePageBounds(shape)
6810
+ if (!shapePageBounds) continue
6811
+
6812
+ if (
6813
+ !this.getShapeUtil(shape).canBeLaidOut?.(shape, {
6814
+ type,
6815
+ shapes: freshShapes,
6816
+ })
6817
+ ) {
6818
+ continue
6819
+ }
6820
+
6821
+ const shapesMovingTogether = [shape]
6822
+ const boundsOfShapesMovingTogether: Box[] = [shapePageBounds]
6823
+
6824
+ this.collectShapesViaArrowBindings({
6825
+ bindings: this.getBindingsToShape(shape.id, 'arrow'),
6826
+ initialShapes: freshShapes,
6827
+ resultShapes: shapesMovingTogether,
6828
+ resultBounds: boundsOfShapesMovingTogether,
6829
+ visited,
6830
+ })
6831
+
6832
+ const commonPageBounds = Box.Common(boundsOfShapesMovingTogether)
6833
+ if (!commonPageBounds) continue
6834
+
6835
+ clusters.push({
6836
+ shapes: shapesMovingTogether,
6837
+ pageBounds: commonPageBounds,
6838
+ })
6839
+
6840
+ allBounds.push(commonPageBounds)
6841
+ }
6842
+
6843
+ return { clusters, allBounds }
6844
+ }
6845
+
6770
6846
  /**
6771
6847
  * @internal
6772
6848
  */
@@ -6912,61 +6988,11 @@ export class Editor extends EventEmitter<TLEventMap> {
6912
6988
  gap?: number
6913
6989
  ): this {
6914
6990
  const _gap = gap ?? this.options.adjacentShapeMargin
6915
- const ids =
6916
- typeof shapes[0] === 'string'
6917
- ? (shapes as TLShapeId[])
6918
- : (shapes as TLShape[]).map((s) => s.id)
6919
6991
  if (this.getIsReadonly()) return this
6920
6992
 
6921
6993
  // todo: this has a lot of extra code to handle stacking with custom gaps or auto gaps or other things like that. I don't think anyone has ever used this stuff.
6922
6994
 
6923
- // always fresh shapes
6924
- const shapesToStackFirstPass = compact(ids.map((id) => this.getShape(id)))
6925
-
6926
- const shapeClustersToStack: {
6927
- shapes: TLShape[]
6928
- pageBounds: Box
6929
- }[] = []
6930
- const allBounds: Box[] = []
6931
- const visited = new Set<TLShapeId>()
6932
-
6933
- for (const shape of shapesToStackFirstPass) {
6934
- if (visited.has(shape.id)) continue
6935
- visited.add(shape.id)
6936
-
6937
- const shapePageBounds = this.getShapePageBounds(shape)
6938
- if (!shapePageBounds) continue
6939
-
6940
- if (
6941
- !this.getShapeUtil(shape).canBeLaidOut?.(shape, {
6942
- type: 'stack',
6943
- shapes: shapesToStackFirstPass,
6944
- })
6945
- ) {
6946
- continue
6947
- }
6948
-
6949
- const shapesMovingTogether = [shape]
6950
- const boundsOfShapesMovingTogether: Box[] = [shapePageBounds]
6951
-
6952
- this.collectShapesViaArrowBindings({
6953
- bindings: this.getBindingsToShape(shape.id, 'arrow'),
6954
- initialShapes: shapesToStackFirstPass,
6955
- resultShapes: shapesMovingTogether,
6956
- resultBounds: boundsOfShapesMovingTogether,
6957
- visited,
6958
- })
6959
-
6960
- const commonPageBounds = Box.Common(boundsOfShapesMovingTogether)
6961
- if (!commonPageBounds) continue
6962
-
6963
- shapeClustersToStack.push({
6964
- shapes: shapesMovingTogether,
6965
- pageBounds: commonPageBounds,
6966
- })
6967
-
6968
- allBounds.push(commonPageBounds)
6969
- }
6995
+ const { clusters: shapeClustersToStack } = this.getShapeClusters(shapes, 'stack')
6970
6996
 
6971
6997
  const len = shapeClustersToStack.length
6972
6998
  if ((_gap === 0 && len < 3) || len < 2) return this
@@ -7082,61 +7108,12 @@ export class Editor extends EventEmitter<TLEventMap> {
7082
7108
 
7083
7109
  const gap = _gap ?? this.options.adjacentShapeMargin
7084
7110
 
7085
- const ids =
7086
- typeof shapes[0] === 'string'
7087
- ? (shapes as TLShapeId[])
7088
- : (shapes as TLShape[]).map((s) => s.id)
7089
-
7090
- // Always fresh shapes
7091
- const shapesToPackFirstPass = compact(ids.map((id) => this.getShape(id)))
7092
-
7093
- const shapeClustersToPack: {
7094
- shapes: TLShape[]
7095
- pageBounds: Box
7096
- nextPageBounds: Box
7097
- }[] = []
7098
-
7099
- const allBounds: Box[] = []
7100
- const visited = new Set<TLShapeId>()
7101
-
7102
- for (const shape of shapesToPackFirstPass) {
7103
- if (visited.has(shape.id)) continue
7104
- visited.add(shape.id)
7105
-
7106
- const shapePageBounds = this.getShapePageBounds(shape)
7107
- if (!shapePageBounds) continue
7111
+ const { clusters, allBounds } = this.getShapeClusters(shapes, 'pack')
7108
7112
 
7109
- if (
7110
- !this.getShapeUtil(shape).canBeLaidOut?.(shape, {
7111
- type: 'pack',
7112
- shapes: shapesToPackFirstPass,
7113
- })
7114
- ) {
7115
- continue
7116
- }
7117
-
7118
- const shapesMovingTogether = [shape]
7119
- const boundsOfShapesMovingTogether: Box[] = [shapePageBounds]
7120
-
7121
- this.collectShapesViaArrowBindings({
7122
- bindings: this.getBindingsToShape(shape.id, 'arrow'),
7123
- initialShapes: shapesToPackFirstPass,
7124
- resultShapes: shapesMovingTogether,
7125
- resultBounds: boundsOfShapesMovingTogether,
7126
- visited,
7127
- })
7128
-
7129
- const commonPageBounds = Box.Common(boundsOfShapesMovingTogether)
7130
- if (!commonPageBounds) continue
7131
-
7132
- shapeClustersToPack.push({
7133
- shapes: shapesMovingTogether,
7134
- pageBounds: commonPageBounds,
7135
- nextPageBounds: commonPageBounds.clone(),
7136
- })
7137
-
7138
- allBounds.push(commonPageBounds)
7139
- }
7113
+ const shapeClustersToPack = clusters.map((cluster) => ({
7114
+ ...cluster,
7115
+ nextPageBounds: cluster.pageBounds.clone(),
7116
+ }))
7140
7117
 
7141
7118
  if (shapeClustersToPack.length < 2) return this
7142
7119
 
@@ -7258,63 +7235,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7258
7235
  ): this {
7259
7236
  if (this.getIsReadonly()) return this
7260
7237
 
7261
- const ids =
7262
- typeof shapes[0] === 'string'
7263
- ? (shapes as TLShapeId[])
7264
- : (shapes as TLShape[]).map((s) => s.id)
7265
-
7266
- // Always get fresh shapes
7267
- const shapesToAlignFirstPass = compact(ids.map((id) => this.getShape(id)))
7268
-
7269
- const shapeClustersToAlign: {
7270
- shapes: TLShape[]
7271
- pageBounds: Box
7272
- }[] = []
7273
- const allBounds: Box[] = []
7274
- const visited = new Set<TLShapeId>()
7275
-
7276
- for (const shape of shapesToAlignFirstPass) {
7277
- if (visited.has(shape.id)) continue
7278
- visited.add(shape.id)
7279
-
7280
- const shapePageBounds = this.getShapePageBounds(shape)
7281
- if (!shapePageBounds) continue
7282
-
7283
- if (
7284
- !this.getShapeUtil(shape).canBeLaidOut?.(shape, {
7285
- type: 'align',
7286
- shapes: shapesToAlignFirstPass,
7287
- })
7288
- ) {
7289
- continue
7290
- }
7291
-
7292
- // In this implementation, we want to create psuedo-groups out of shapes that
7293
- // are moving together. At the moment shapes only move together if they're connected
7294
- // by arrows. So let's say A -> B -> C -> D and A, B, and C are selected. If we're
7295
- // aligning A, B, and C, then we want these to move together as one unit.
7296
-
7297
- const shapesMovingTogether = [shape]
7298
- const boundsOfShapesMovingTogether: Box[] = [shapePageBounds]
7299
-
7300
- this.collectShapesViaArrowBindings({
7301
- bindings: this.getBindingsToShape(shape.id, 'arrow'),
7302
- initialShapes: shapesToAlignFirstPass,
7303
- resultShapes: shapesMovingTogether,
7304
- resultBounds: boundsOfShapesMovingTogether,
7305
- visited,
7306
- })
7307
-
7308
- const commonPageBounds = Box.Common(boundsOfShapesMovingTogether)
7309
- if (!commonPageBounds) continue
7310
-
7311
- shapeClustersToAlign.push({
7312
- shapes: shapesMovingTogether,
7313
- pageBounds: commonPageBounds,
7314
- })
7315
-
7316
- allBounds.push(commonPageBounds)
7317
- }
7238
+ const { clusters: shapeClustersToAlign, allBounds } = this.getShapeClusters(shapes, 'align')
7318
7239
 
7319
7240
  if (shapeClustersToAlign.length < 2) return this
7320
7241
 
@@ -7389,59 +7310,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7389
7310
  distributeShapes(shapes: TLShapeId[] | TLShape[], operation: 'horizontal' | 'vertical'): this {
7390
7311
  if (this.getIsReadonly()) return this
7391
7312
 
7392
- const ids =
7393
- typeof shapes[0] === 'string'
7394
- ? (shapes as TLShapeId[])
7395
- : (shapes as TLShape[]).map((s) => s.id)
7396
-
7397
- // always fresh shapes
7398
- const shapesToDistributeFirstPass = compact(ids.map((id) => this.getShape(id)))
7399
-
7400
- const shapeClustersToDistribute: {
7401
- shapes: TLShape[]
7402
- pageBounds: Box
7403
- }[] = []
7404
-
7405
- const allBounds: Box[] = []
7406
- const visited = new Set<TLShapeId>()
7407
-
7408
- for (const shape of shapesToDistributeFirstPass) {
7409
- if (visited.has(shape.id)) continue
7410
- visited.add(shape.id)
7411
-
7412
- const shapePageBounds = this.getShapePageBounds(shape)
7413
- if (!shapePageBounds) continue
7414
-
7415
- if (
7416
- !this.getShapeUtil(shape).canBeLaidOut?.(shape, {
7417
- type: 'distribute',
7418
- shapes: shapesToDistributeFirstPass,
7419
- })
7420
- ) {
7421
- continue
7422
- }
7423
-
7424
- const shapesMovingTogether = [shape]
7425
- const boundsOfShapesMovingTogether: Box[] = [shapePageBounds]
7426
-
7427
- this.collectShapesViaArrowBindings({
7428
- bindings: this.getBindingsToShape(shape.id, 'arrow'),
7429
- initialShapes: shapesToDistributeFirstPass,
7430
- resultShapes: shapesMovingTogether,
7431
- resultBounds: boundsOfShapesMovingTogether,
7432
- visited,
7433
- })
7434
-
7435
- const commonPageBounds = Box.Common(boundsOfShapesMovingTogether)
7436
- if (!commonPageBounds) continue
7437
-
7438
- shapeClustersToDistribute.push({
7439
- shapes: shapesMovingTogether,
7440
- pageBounds: commonPageBounds,
7441
- })
7442
-
7443
- allBounds.push(commonPageBounds)
7444
- }
7313
+ const { clusters: shapeClustersToDistribute } = this.getShapeClusters(shapes, 'distribute')
7445
7314
 
7446
7315
  if (shapeClustersToDistribute.length < 3) return this
7447
7316
 
@@ -7469,6 +7338,10 @@ export class Editor extends EventEmitter<TLEventMap> {
7469
7338
  // If the first shape group is also the last shape group, distribute without it
7470
7339
  if (first === last) {
7471
7340
  const excludedShapeIds = new Set(first.shapes.map((s) => s.id))
7341
+ const ids =
7342
+ typeof shapes[0] === 'string'
7343
+ ? (shapes as TLShapeId[])
7344
+ : (shapes as TLShape[]).map((s) => s.id)
7472
7345
  return this.distributeShapes(
7473
7346
  ids.filter((id) => !excludedShapeIds.has(id)),
7474
7347
  operation
@@ -7538,63 +7411,14 @@ export class Editor extends EventEmitter<TLEventMap> {
7538
7411
  * @public
7539
7412
  */
7540
7413
  stretchShapes(shapes: TLShapeId[] | TLShape[], operation: 'horizontal' | 'vertical'): this {
7541
- const ids =
7542
- typeof shapes[0] === 'string'
7543
- ? (shapes as TLShapeId[])
7544
- : (shapes as TLShape[]).map((s) => s.id)
7545
-
7546
7414
  if (this.getIsReadonly()) return this
7547
7415
 
7548
- // always fresh shapes, skip anything that isn't rotated 90 deg
7549
- const shapesToStretchFirstPass = compact(ids.map((id) => this.getShape(id))).filter(
7550
- (s) => this.getShapePageTransform(s)?.rotation() % (PI / 2) === 0
7416
+ const { clusters: shapeClustersToStretch, allBounds } = this.getShapeClusters(
7417
+ shapes,
7418
+ 'stretch',
7419
+ { filterAxisAligned: true }
7551
7420
  )
7552
7421
 
7553
- const shapeClustersToStretch: {
7554
- shapes: TLShape[]
7555
- pageBounds: Box
7556
- }[] = []
7557
-
7558
- const allBounds: Box[] = []
7559
- const visited = new Set<TLShapeId>()
7560
-
7561
- for (const shape of shapesToStretchFirstPass) {
7562
- if (visited.has(shape.id)) continue
7563
- visited.add(shape.id)
7564
-
7565
- const shapePageBounds = this.getShapePageBounds(shape)
7566
- if (!shapePageBounds) continue
7567
-
7568
- const shapesMovingTogether = [shape]
7569
- const boundsOfShapesMovingTogether: Box[] = [shapePageBounds]
7570
-
7571
- if (
7572
- !this.getShapeUtil(shape).canBeLaidOut?.(shape, {
7573
- type: 'stretch',
7574
- })
7575
- ) {
7576
- continue
7577
- }
7578
-
7579
- this.collectShapesViaArrowBindings({
7580
- bindings: this.getBindingsToShape(shape.id, 'arrow'),
7581
- initialShapes: shapesToStretchFirstPass,
7582
- resultShapes: shapesMovingTogether,
7583
- resultBounds: boundsOfShapesMovingTogether,
7584
- visited,
7585
- })
7586
-
7587
- const commonPageBounds = Box.Common(boundsOfShapesMovingTogether)
7588
- if (!commonPageBounds) continue
7589
-
7590
- shapeClustersToStretch.push({
7591
- shapes: shapesMovingTogether,
7592
- pageBounds: commonPageBounds,
7593
- })
7594
-
7595
- allBounds.push(commonPageBounds)
7596
- }
7597
-
7598
7422
  if (shapeClustersToStretch.length < 2) return this
7599
7423
 
7600
7424
  const commonBounds = Box.Common(allBounds)
@@ -7627,7 +7451,7 @@ export class Editor extends EventEmitter<TLEventMap> {
7627
7451
  // First translate
7628
7452
  const shapeLocalOffset = localOffset.clone()
7629
7453
  const parentTransform = this.getShapeParentTransform(shape)
7630
- if (parentTransform) localOffset.rot(-parentTransform.rotation())
7454
+ if (parentTransform) shapeLocalOffset.rot(-parentTransform.rotation())
7631
7455
  shapeLocalOffset.add(shape)
7632
7456
  const changes = this.getChangesToTranslateShape(shape, shapeLocalOffset)
7633
7457
  this.updateShape(changes)
@@ -7646,6 +7470,77 @@ export class Editor extends EventEmitter<TLEventMap> {
7646
7470
  return this
7647
7471
  }
7648
7472
 
7473
+ /**
7474
+ * Resize and reposition a set of shapes so that their combined page bounds matches the given
7475
+ * target bounds.
7476
+ *
7477
+ * @example
7478
+ * ```ts
7479
+ * editor.resizeToBounds([box1, box2], { x: 0, y: 0, w: 500, h: 500 })
7480
+ * editor.resizeToBounds(editor.getSelectedShapeIds(), new Box(0, 0, 500, 500))
7481
+ * ```
7482
+ *
7483
+ * @param shapes - The shapes (or shape ids) to resize.
7484
+ * @param bounds - The target bounding box.
7485
+ *
7486
+ * @public
7487
+ */
7488
+ resizeToBounds(shapes: TLShapeId[] | TLShape[], bounds: BoxLike): this {
7489
+ if (this.getIsReadonly()) return this
7490
+
7491
+ const targetBounds = Box.From(bounds)
7492
+
7493
+ const { clusters: shapeClusters, allBounds } = this.getShapeClusters(
7494
+ shapes,
7495
+ 'resize_to_bounds',
7496
+ { filterAxisAligned: true }
7497
+ )
7498
+
7499
+ if (shapeClusters.length === 0) return this
7500
+
7501
+ const commonBounds = Box.Common(allBounds)
7502
+ if (!commonBounds) return this
7503
+ if (commonBounds.width === 0 || commonBounds.height === 0) return this
7504
+
7505
+ const scaleX = targetBounds.width / commonBounds.width
7506
+ const scaleY = targetBounds.height / commonBounds.height
7507
+ const scale = new Vec(scaleX, scaleY)
7508
+
7509
+ shapeClusters.forEach(({ shapes, pageBounds }) => {
7510
+ const localOffset = new Vec(
7511
+ targetBounds.minX -
7512
+ commonBounds.minX +
7513
+ (pageBounds.minX - commonBounds.minX) * (scaleX - 1),
7514
+ targetBounds.minY - commonBounds.minY + (pageBounds.minY - commonBounds.minY) * (scaleY - 1)
7515
+ )
7516
+
7517
+ const scaleOrigin = new Vec(
7518
+ targetBounds.minX + (pageBounds.minX - commonBounds.minX) * scaleX,
7519
+ targetBounds.minY + (pageBounds.minY - commonBounds.minY) * scaleY
7520
+ )
7521
+
7522
+ for (const shape of shapes) {
7523
+ // First translate
7524
+ const shapeLocalOffset = localOffset.clone()
7525
+ const parentTransform = this.getShapeParentTransform(shape)
7526
+ if (parentTransform) shapeLocalOffset.rot(-parentTransform.rotation())
7527
+ shapeLocalOffset.add(shape)
7528
+ const changes = this.getChangesToTranslateShape(shape, shapeLocalOffset)
7529
+ this.updateShape(changes)
7530
+
7531
+ // Then resize
7532
+ this.resizeShape(shape.id, scale, {
7533
+ initialBounds: this.getShapeGeometry(shape).bounds,
7534
+ scaleOrigin,
7535
+ isAspectRatioLocked: this.getShapeUtil(shape).isAspectRatioLocked(shape),
7536
+ scaleAxisRotation: 0,
7537
+ })
7538
+ }
7539
+ })
7540
+
7541
+ return this
7542
+ }
7543
+
7649
7544
  /**
7650
7545
  * Resize a shape.
7651
7546
  *
@@ -9356,46 +9251,13 @@ export class Editor extends EventEmitter<TLEventMap> {
9356
9251
  : bindings.map((binding) => [binding.id, createBindingId()])
9357
9252
  )
9358
9253
 
9359
- // By default, the paste parent will be the current page.
9360
- let pasteParentId = this.getCurrentPageId() as TLPageId | TLShapeId
9361
- let lowestDepth = Infinity
9362
- let lowestAncestors: TLShape[] = []
9363
-
9364
- // Among the selected shapes, find the shape with the fewest ancestors and use its first ancestor.
9365
- for (const shape of this.getSelectedShapes()) {
9366
- if (lowestDepth === 0) break
9254
+ let pasteParentId: TLPageId | TLShapeId = currentPageId
9367
9255
 
9368
- const isFrame = this.isShapeOfType(shape, 'frame')
9369
- const ancestors = this.getShapeAncestors(shape)
9370
- if (isFrame) ancestors.push(shape)
9371
-
9372
- const depth = isFrame ? ancestors.length + 1 : ancestors.length
9373
-
9374
- if (depth < lowestDepth) {
9375
- lowestDepth = depth
9376
- lowestAncestors = ancestors
9377
- pasteParentId = isFrame ? shape.id : shape.parentId
9378
- } else if (depth === lowestDepth) {
9379
- if (lowestAncestors.length !== ancestors.length) {
9380
- throw Error(`Ancestors: ${lowestAncestors.length} !== ${ancestors.length}`)
9381
- }
9382
-
9383
- if (lowestAncestors.length === 0) {
9384
- pasteParentId = currentPageId
9385
- break
9386
- } else {
9387
- pasteParentId = currentPageId
9388
- for (let i = 0; i < lowestAncestors.length; i++) {
9389
- if (ancestors[i] !== lowestAncestors[i]) break
9390
- pasteParentId = ancestors[i].id
9391
- }
9392
- }
9393
- }
9394
- }
9256
+ const shapesById = new Map(shapes.map((s) => [s.id, s]))
9257
+ const rootShapesFromContent = compact(rootShapeIds.map((id) => shapesById.get(id)))
9395
9258
 
9396
9259
  if (point) {
9397
- const shapesById = new Map<TLShapeId, TLShape>(shapes.map((shape) => [shape.id, shape]))
9398
- const rootShapesFromContent = compact(rootShapeIds.map((id) => shapesById.get(id)))
9260
+ // PASTE AT CURSOR: find the deepest accepts-children shape under the cursor
9399
9261
  if (rootShapesFromContent.length > 0) {
9400
9262
  const targetParent = this.getShapeAtPoint(point, {
9401
9263
  hitInside: true,
@@ -9403,51 +9265,72 @@ export class Editor extends EventEmitter<TLEventMap> {
9403
9265
  hitLocked: true,
9404
9266
  filter: (shape) => {
9405
9267
  const util = this.getShapeUtil(shape)
9406
- if (!util.canReceiveNewChildrenOfType) return false
9407
9268
  return rootShapesFromContent.every((rootShape) =>
9408
- util.canReceiveNewChildrenOfType!(shape, rootShape.type)
9269
+ util.canReceiveNewChildrenOfType?.(shape, rootShape.type)
9409
9270
  )
9410
9271
  },
9411
9272
  })
9412
-
9413
- // When pasting at a specific point (e.g. paste-at-cursor) prefer the
9414
- // parent under the pointer so that we don't keep using the original
9415
- // selection's parent (which can keep shapes clipped inside frames).
9416
- pasteParentId = targetParent ? targetParent.id : currentPageId
9273
+ pasteParentId = targetParent?.id ?? currentPageId
9417
9274
  }
9418
- }
9275
+ } else if (!preservePosition) {
9276
+ // STANDARD PASTE: check if a selected shape (or its ancestor) accepts children
9277
+ const selectedShapes = this.getSelectedShapes()
9278
+ let selectedParent: TLShape | null = null
9419
9279
 
9420
- let isDuplicating = false
9280
+ const canAcceptAll = (candidate: TLShape) => {
9281
+ const util = this.getShapeUtil(candidate)
9282
+ return rootShapesFromContent.every((rs) =>
9283
+ util.canReceiveNewChildrenOfType?.(candidate, rs.type)
9284
+ )
9285
+ }
9421
9286
 
9422
- if (!isPageId(pasteParentId)) {
9423
- const parent = this.getShape(pasteParentId)
9424
- if (parent) {
9425
- if (!this.getViewportPageBounds().includes(this.getShapePageBounds(parent)!)) {
9426
- pasteParentId = currentPageId
9427
- } else {
9428
- if (rootShapeIds.length === 1) {
9429
- const rootShape = shapes.find((s) => s.id === rootShapeIds[0])!
9430
- if (
9431
- this.isShapeOfType(parent, 'frame') &&
9432
- this.isShapeOfType(rootShape, 'frame') &&
9433
- rootShape.props.w === parent?.props.w &&
9434
- rootShape.props.h === parent?.props.h
9435
- ) {
9436
- isDuplicating = true
9287
+ for (const shape of selectedShapes) {
9288
+ // Find the nearest container: the shape itself if it can accept,
9289
+ // an accepting ancestor, or fall back to the shape's parent
9290
+ // (handles groups and other non-frame containers)
9291
+ const candidate = canAcceptAll(shape)
9292
+ ? shape
9293
+ : (this.findShapeAncestor(shape, canAcceptAll) ??
9294
+ (isShapeId(shape.parentId) ? this.getShape(shape.parentId)! : null))
9295
+
9296
+ if (!candidate) {
9297
+ selectedParent = null
9298
+ break
9299
+ }
9300
+ if (!selectedParent) {
9301
+ selectedParent = candidate
9302
+ } else if (selectedParent.id !== candidate.id) {
9303
+ // Different candidates — find the deepest common accepting ancestor
9304
+ const spAncestors = this.getShapeAncestors(selectedParent)
9305
+ if (canAcceptAll(selectedParent)) spAncestors.push(selectedParent)
9306
+ const acceptingAncestors = spAncestors.filter(canAcceptAll)
9307
+
9308
+ const candidateAncestorIds = new Set([
9309
+ candidate.id,
9310
+ ...this.getShapeAncestors(candidate).map((a) => a.id),
9311
+ ])
9312
+
9313
+ let common: TLShape | null = null
9314
+ for (let i = acceptingAncestors.length - 1; i >= 0; i--) {
9315
+ if (candidateAncestorIds.has(acceptingAncestors[i].id)) {
9316
+ common = acceptingAncestors[i]
9317
+ break
9437
9318
  }
9438
9319
  }
9320
+
9321
+ selectedParent = common
9322
+ if (!selectedParent) break
9439
9323
  }
9440
- } else {
9441
- pasteParentId = currentPageId
9442
9324
  }
9443
- }
9444
9325
 
9445
- if (!isDuplicating) {
9446
- isDuplicating = shapeIdMap.has(pasteParentId)
9447
- }
9326
+ // Don't paste a shape into itself (the duplicating-a-frame case)
9327
+ if (selectedParent && shapeIdMap.has(selectedParent.id)) {
9328
+ selectedParent = null
9329
+ }
9448
9330
 
9449
- if (isDuplicating) {
9450
- pasteParentId = this.getShape(pasteParentId)!.parentId
9331
+ if (selectedParent) {
9332
+ pasteParentId = selectedParent.id
9333
+ }
9451
9334
  }
9452
9335
 
9453
9336
  let index = this.getHighestIndexForParent(pasteParentId) // todo: requires that the putting page is the current page
@@ -9555,20 +9438,12 @@ export class Editor extends EventEmitter<TLEventMap> {
9555
9438
  )
9556
9439
 
9557
9440
  this.run(() => {
9558
- // Create any assets that need to be created
9559
- if (assetsToCreate.length > 0) {
9560
- this.createAssets(assetsToCreate)
9561
- }
9562
-
9563
- // Create the shapes with root shapes as children of the page
9441
+ if (assetsToCreate.length > 0) this.createAssets(assetsToCreate)
9564
9442
  this.createShapes(newShapes)
9565
9443
  this.createBindings(newBindings)
9444
+ if (select) this.select(...rootShapes.map((s) => s.id))
9566
9445
 
9567
- if (select) {
9568
- this.select(...rootShapes.map((s) => s.id))
9569
- }
9570
-
9571
- // And then, if needed, reparent the root shapes to the paste parent
9446
+ // Reparent root shapes to paste parent if not page
9572
9447
  if (pasteParentId !== currentPageId) {
9573
9448
  this.reparentShapes(
9574
9449
  rootShapes.map((s) => s.id),
@@ -9576,69 +9451,65 @@ export class Editor extends EventEmitter<TLEventMap> {
9576
9451
  )
9577
9452
  }
9578
9453
 
9579
- const newCreatedShapes = newShapes.map((s) => this.getShape(s.id)!)
9580
- const bounds = Box.Common(newCreatedShapes.map((s) => this.getShapePageBounds(s)!))
9454
+ // --- POSITIONING ---
9455
+ const rootBounds = Box.Common(compact(rootShapes.map((s) => this.getShapePageBounds(s.id))))
9581
9456
 
9582
9457
  if (point === undefined) {
9583
9458
  if (!isPageId(pasteParentId)) {
9584
- // Put the shapes in the middle of the (on screen) parent
9459
+ // Paste into selected parent → center in that shape
9585
9460
  const shape = this.getShape(pasteParentId)!
9586
9461
  point = Mat.applyToPoint(
9587
9462
  this.getShapePageTransform(shape),
9588
9463
  this.getShapeGeometry(shape).bounds.center
9589
9464
  )
9465
+ } else if (preservePosition) {
9466
+ // preservePosition (page duplication) → keep original coords
9467
+ point = rootBounds.center
9590
9468
  } else {
9469
+ // Standard paste to page: check viewport overlap
9591
9470
  const viewportPageBounds = this.getViewportPageBounds()
9592
- if (preservePosition || viewportPageBounds.includes(Box.From(bounds))) {
9593
- // Otherwise, put shapes where they used to be
9594
- point = bounds.center
9595
- } else {
9596
- // If the old bounds are outside of the viewport...
9597
- // put the shapes in the middle of the viewport
9598
- point = viewportPageBounds.center
9599
- }
9600
- }
9601
- }
9602
-
9603
- if (rootShapes.length === 1) {
9604
- const onlyRoot = rootShapes[0] as TLFrameShape
9605
- // If the old bounds are in the viewport...
9606
- // todo: replace frame references with shapes that can accept children
9607
- if (this.isShapeOfType(onlyRoot, 'frame')) {
9608
- while (
9609
- this.getShapesAtPoint(point).some(
9610
- (shape) =>
9611
- this.isShapeOfType(shape, 'frame') &&
9612
- shape.props.w === onlyRoot.props.w &&
9613
- shape.props.h === onlyRoot.props.h
9614
- )
9615
- ) {
9616
- point.x += bounds.w + 16
9617
- }
9471
+ const anyOverlap = rootShapes.some((s) => {
9472
+ const b = this.getShapePageBounds(s.id)
9473
+ return b && viewportPageBounds.collides(b)
9474
+ })
9475
+ point = anyOverlap ? rootBounds.center : viewportPageBounds.center
9618
9476
  }
9619
9477
  }
9620
9478
 
9479
+ // Apply offset to move shapes to target point
9621
9480
  const pageCenter = Box.Common(
9622
9481
  compact(rootShapes.map(({ id }) => this.getShapePageBounds(id)))
9623
9482
  ).center
9624
-
9625
9483
  const offset = Vec.Sub(point, pageCenter)
9626
9484
 
9627
- this.updateShapes(
9628
- rootShapes.map(({ id }) => {
9629
- const s = this.getShape(id)!
9630
- const localRotation = this.getShapeParentTransform(id).decompose().rotation
9631
- const localDelta = Vec.Rot(offset, -localRotation)
9632
-
9633
- return { id: s.id, type: s.type, x: s.x + localDelta.x, y: s.y + localDelta.y }
9634
- })
9635
- )
9485
+ if (offset.x !== 0 || offset.y !== 0) {
9486
+ this.updateShapes(
9487
+ rootShapes.map(({ id }) => {
9488
+ const s = this.getShape(id)!
9489
+ const localRotation = this.getShapeParentTransform(id).decompose().rotation
9490
+ const localDelta = Vec.Rot(offset, -localRotation)
9491
+ return { id: s.id, type: s.type, x: s.x + localDelta.x, y: s.y + localDelta.y }
9492
+ })
9493
+ )
9494
+ }
9636
9495
 
9637
- // If shapes were pasted onto the page (not into a specific parent),
9638
- // check whether they landed inside a frame and reparent if so.
9496
+ // Auto-reparent into frames when pasted to page level
9639
9497
  if (isPageId(pasteParentId)) {
9640
9498
  const currentRootShapes = compact(rootShapes.map((s) => this.getShape(s.id)))
9641
- const { reparenting } = getDroppedShapesToNewParents(this, currentRootShapes)
9499
+ // Don't reparent into source shapes (prevents a duplicate frame
9500
+ // from being swallowed by its original), and require the shape's
9501
+ // center to be inside the parent (filters out edge-only overlaps)
9502
+ const { reparenting } = getDroppedShapesToNewParents(
9503
+ this,
9504
+ currentRootShapes,
9505
+ (shape, parent) => {
9506
+ if (shapeIdMap.has(parent.id)) return false
9507
+ const shapeBounds = this.getShapePageBounds(shape)
9508
+ const parentBounds = this.getShapePageBounds(parent)
9509
+ if (!shapeBounds || !parentBounds) return false
9510
+ return parentBounds.containsPoint(shapeBounds.center)
9511
+ }
9512
+ )
9642
9513
  reparenting.forEach((childrenToReparent, newParentId) => {
9643
9514
  if (childrenToReparent.length === 0) return
9644
9515
  this.reparentShapes(
@@ -9647,6 +9518,25 @@ export class Editor extends EventEmitter<TLEventMap> {
9647
9518
  )
9648
9519
  })
9649
9520
  }
9521
+
9522
+ // Kick out any pasted root shapes that ended up outside their parent container
9523
+ const newShapeIdSet = new Set(newShapes.map((s) => s.id))
9524
+ const shapesToKickout = rootShapes
9525
+ .map((s) => s.id)
9526
+ .filter((id) => {
9527
+ const shape = this.getShape(id)
9528
+ if (!shape) return false
9529
+ // Only check shapes that are children of a shape (not page)
9530
+ if (isPageId(shape.parentId)) return false
9531
+ // Don't check containers with pasted children (preserves intentional
9532
+ // parent-child relationships from the copied content)
9533
+ const children = this.getSortedChildIdsForParent(id)
9534
+ return !children.some((childId) => newShapeIdSet.has(childId))
9535
+ })
9536
+
9537
+ if (shapesToKickout.length > 0) {
9538
+ kickoutOccludedShapes(this, shapesToKickout)
9539
+ }
9650
9540
  })
9651
9541
 
9652
9542
  return this