-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Group.ts
1053 lines (991 loc) · 31.3 KB
/
Group.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-nocheck
import type { CollectionEvents, ObjectEvents } from '../EventTypeDefs';
import { createCollectionMixin } from '../Collection';
import { resolveOrigin } from '../util/misc/resolveOrigin';
import { Point } from '../Point';
import type { TClassProperties } from '../typedefs';
import { cos } from '../util/misc/cos';
import {
invertTransform,
multiplyTransformMatrices,
transformPoint,
} from '../util/misc/matrix';
import {
enlivenObjectEnlivables,
enlivenObjects,
} from '../util/misc/objectEnlive';
import { applyTransformToObject } from '../util/misc/objectTransforms';
import { degreesToRadians } from '../util/misc/radiansDegreesConversion';
import { sin } from '../util/misc/sin';
import { FabricObject, stateProperties } from './Object/FabricObject';
import { Rect } from './Rect';
import { classRegistry } from '../util/class_registry';
export type LayoutContextType =
| 'initialization'
| 'object_modified'
| 'added'
| 'removed'
| 'layout_change'
| 'imperative';
export type LayoutContext = {
type: LayoutContextType;
/**
* array of objects starting from the object that triggered the call to the current one
*/
path?: Group[];
[key: string]: any;
};
export type GroupEvents = ObjectEvents &
CollectionEvents & {
layout: {
context: LayoutContext;
result: LayoutResult;
diff: Point;
};
};
export type LayoutStrategy =
| 'fit-content'
| 'fit-content-lazy'
| 'fixed'
| 'clip-path';
/**
* positioning and layout data **relative** to instance's parent
*/
export type LayoutResult = {
/**
* new centerX as measured by the containing plane (same as `left` with `originX` set to `center`)
*/
centerX: number;
/**
* new centerY as measured by the containing plane (same as `top` with `originY` set to `center`)
*/
centerY: number;
/**
* correctionX to translate objects by, measured as `centerX`
*/
correctionX?: number;
/**
* correctionY to translate objects by, measured as `centerY`
*/
correctionY?: number;
width: number;
height: number;
};
/**
* @fires object:added
* @fires object:removed
* @fires layout once layout completes
*/
export class Group extends createCollectionMixin(FabricObject<GroupEvents>) {
/**
* Specifies the **layout strategy** for instance
* Used by `getLayoutStrategyResult` to calculate layout
* `fit-content`, `fit-content-lazy`, `fixed`, `clip-path` are supported out of the box
* @type LayoutStrategy
* @default
*/
declare layout: LayoutStrategy;
/**
* Used to optimize performance
* set to `false` if you don't need contained objects to be targets of events
* @default
* @type boolean
*/
declare subTargetCheck: boolean;
/**
* Used to allow targeting of object inside groups.
* set to true if you want to select an object inside a group.\
* **REQUIRES** `subTargetCheck` set to true
* @default
* @type boolean
*/
declare interactive: boolean;
/**
* Used internally to optimize performance
* Once an object is selected, instance is rendered without the selected object.
* This way instance is cached only once for the entire interaction with the selected object.
* @private
*/
protected _activeObjects: FabricObject[] = [];
/**
* Constructor
*
* @param {FabricObject[]} [objects] instance objects
* @param {Object} [options] Options object
* @param {boolean} [objectsRelativeToGroup] true if objects exist in group coordinate plane
*/
constructor(
objects: FabricObject[] = [],
options: any = {},
objectsRelativeToGroup?: boolean
) {
super();
this._objects = objects;
this.__objectMonitor = this.__objectMonitor.bind(this);
this.__objectSelectionTracker = this.__objectSelectionMonitor.bind(
this,
true
);
this.__objectSelectionDisposer = this.__objectSelectionMonitor.bind(
this,
false
);
this._firstLayoutDone = false;
// setting angle, skewX, skewY must occur after initial layout
this.set({ ...options, angle: 0, skewX: 0, skewY: 0 });
this.forEachObject((object) => {
this.enterGroup(object, false);
});
this._applyLayoutStrategy({
type: 'initialization',
options,
objectsRelativeToGroup,
});
}
/**
* Checks if object can enter group and logs relevant warnings
* @private
* @param {FabricObject} object
* @returns
*/
canEnterGroup(object: FabricObject) {
if (object === this || this.isDescendantOf(object)) {
// prevent circular object tree
/* _DEV_MODE_START_ */
console.error(
'fabric.Group: circular object trees are not supported, this call has no effect'
);
/* _DEV_MODE_END_ */
return false;
} else if (this._objects.indexOf(object) !== -1) {
// is already in the objects array
/* _DEV_MODE_START_ */
console.error(
'fabric.Group: duplicate objects are not supported inside group, this call has no effect'
);
/* _DEV_MODE_END_ */
return false;
}
return true;
}
/**
* Override this method to enhance performance (for groups with a lot of objects).
* If Overriding, be sure not pass illegal objects to group - it will break your app.
* @private
*/
protected _filterObjectsBeforeEnteringGroup(objects: FabricObject[]) {
return objects.filter((object, index, array) => {
// can enter AND is the first occurrence of the object in the passed args (to prevent adding duplicates)
return this.canEnterGroup(object) && array.indexOf(object) === index;
});
}
/**
* Add objects
* @param {...FabricObject[]} objects
*/
add(...objects: FabricObject[]) {
const allowedObjects = this._filterObjectsBeforeEnteringGroup(objects);
const size = super.add(...allowedObjects);
this._onAfterObjectsChange('added', allowedObjects);
return size;
}
/**
* Inserts an object into collection at specified index
* @param {FabricObject[]} objects Object to insert
* @param {Number} index Index to insert object at
*/
insertAt(index: number, ...objects: FabricObject[]) {
const allowedObjects = this._filterObjectsBeforeEnteringGroup(objects);
const size = super.insertAt(index, ...allowedObjects);
this._onAfterObjectsChange('added', allowedObjects);
return size;
}
/**
* Remove objects
* @param {...FabricObject[]} objects
* @returns {FabricObject[]} removed objects
*/
remove(...objects: FabricObject[]) {
const removed = super.remove(...objects);
this._onAfterObjectsChange('removed', removed);
return removed;
}
_onObjectAdded(object: FabricObject) {
this.enterGroup(object, true);
this.fire('object:added', { target: object });
object.fire('added', { target: this });
}
_onRelativeObjectAdded(object: FabricObject) {
this.enterGroup(object, false);
this.fire('object:added', { target: object });
object.fire('added', { target: this });
}
/**
* @private
* @param {FabricObject} object
* @param {boolean} [removeParentTransform] true if object should exit group without applying group's transform to it
*/
_onObjectRemoved(object: FabricObject, removeParentTransform?: boolean) {
this.exitGroup(object, removeParentTransform);
this.fire('object:removed', { target: object });
object.fire('removed', { target: this });
}
/**
* @private
* @param {'added'|'removed'} type
* @param {FabricObject[]} targets
*/
_onAfterObjectsChange(type: 'added' | 'removed', targets: FabricObject[]) {
this._applyLayoutStrategy({
type: type,
targets: targets,
});
this._set('dirty', true);
}
_onStackOrderChanged() {
this._set('dirty', true);
}
/**
* @private
* @param {string} key
* @param {*} value
*/
_set(key: string, value: any) {
const prev = this[key];
super._set(key, value);
if (key === 'canvas' && prev !== value) {
this.forEachObject((object) => {
object._set(key, value);
});
}
if (key === 'layout' && prev !== value) {
this._applyLayoutStrategy({
type: 'layout_change',
layout: value,
prevLayout: prev,
});
}
if (key === 'interactive') {
this.forEachObject((object) => this._watchObject(value, object));
}
return this;
}
/**
* @private
*/
_shouldSetNestedCoords() {
return this.subTargetCheck;
}
/**
* Remove all objects
* @returns {FabricObject[]} removed objects
*/
removeAll() {
this._activeObjects = [];
return this.remove(...this._objects);
}
/**
* invalidates layout on object modified
* @private
*/
__objectMonitor(opt) {
this._applyLayoutStrategy({ ...opt, type: 'object_modified' });
this._set('dirty', true);
}
/**
* keeps track of the selected objects
* @private
*/
__objectSelectionMonitor(selected: boolean, opt) {
const object = opt.target;
if (selected) {
this._activeObjects.push(object);
this._set('dirty', true);
} else if (this._activeObjects.length > 0) {
const index = this._activeObjects.indexOf(object);
if (index > -1) {
this._activeObjects.splice(index, 1);
this._set('dirty', true);
}
}
}
/**
* @private
* @param {boolean} watch
* @param {FabricObject} object
*/
_watchObject(watch: boolean, object: FabricObject) {
const directive = watch ? 'on' : 'off';
// make sure we listen only once
watch && this._watchObject(false, object);
object[directive]('changed', this.__objectMonitor);
object[directive]('modified', this.__objectMonitor);
object[directive]('selected', this.__objectSelectionTracker);
object[directive]('deselected', this.__objectSelectionDisposer);
}
/**
* @private
* @param {FabricObject} object
* @param {boolean} [removeParentTransform] true if object is in canvas coordinate plane
* @returns {boolean} true if object entered group
*/
enterGroup(object: FabricObject, removeParentTransform?: boolean) {
if (object.group) {
object.group.remove(object);
}
this._enterGroup(object, removeParentTransform);
return true;
}
/**
* @private
* @param {FabricObject} object
* @param {boolean} [removeParentTransform] true if object is in canvas coordinate plane
*/
_enterGroup(object: FabricObject, removeParentTransform?: boolean) {
if (removeParentTransform) {
// can this be converted to utils (sendObjectToPlane)?
applyTransformToObject(
object,
multiplyTransformMatrices(
invertTransform(this.calcTransformMatrix()),
object.calcTransformMatrix()
)
);
}
this._shouldSetNestedCoords() && object.setCoords();
object._set('group', this);
object._set('canvas', this.canvas);
this.interactive && this._watchObject(true, object);
const activeObject =
this.canvas &&
this.canvas.getActiveObject &&
this.canvas.getActiveObject();
// if we are adding the activeObject in a group
if (
activeObject &&
(activeObject === object || object.isDescendantOf(activeObject))
) {
this._activeObjects.push(object);
}
}
/**
* @private
* @param {FabricObject} object
* @param {boolean} [removeParentTransform] true if object should exit group without applying group's transform to it
*/
exitGroup(object: FabricObject, removeParentTransform?: boolean) {
this._exitGroup(object, removeParentTransform);
object._set('canvas', undefined);
}
/**
* @private
* @param {FabricObject} object
* @param {boolean} [removeParentTransform] true if object should exit group without applying group's transform to it
*/
_exitGroup(object: FabricObject, removeParentTransform?: boolean) {
object._set('group', undefined);
if (!removeParentTransform) {
applyTransformToObject(
object,
multiplyTransformMatrices(
this.calcTransformMatrix(),
object.calcTransformMatrix()
)
);
object.setCoords();
}
this._watchObject(false, object);
const index =
this._activeObjects.length > 0 ? this._activeObjects.indexOf(object) : -1;
if (index > -1) {
this._activeObjects.splice(index, 1);
}
}
/**
* Decide if the object should cache or not. Create its own cache level
* needsItsOwnCache should be used when the object drawing method requires
* a cache step. None of the fabric classes requires it.
* Generally you do not cache objects in groups because the group is already cached.
* @return {Boolean}
*/
shouldCache() {
const ownCache = FabricObject.prototype.shouldCache.call(this);
if (ownCache) {
for (let i = 0; i < this._objects.length; i++) {
if (this._objects[i].willDrawShadow()) {
this.ownCaching = false;
return false;
}
}
}
return ownCache;
}
/**
* Check if this object or a child object will cast a shadow
* @return {Boolean}
*/
willDrawShadow() {
if (FabricObject.prototype.willDrawShadow.call(this)) {
return true;
}
for (let i = 0; i < this._objects.length; i++) {
if (this._objects[i].willDrawShadow()) {
return true;
}
}
return false;
}
/**
* Check if instance or its group are caching, recursively up
* @return {Boolean}
*/
isOnACache(): boolean {
return this.ownCaching || (!!this.group && this.group.isOnACache());
}
/**
* Execute the drawing operation for an object on a specified context
* @param {CanvasRenderingContext2D} ctx Context to render on
*/
drawObject(ctx: CanvasRenderingContext2D) {
this._renderBackground(ctx);
for (let i = 0; i < this._objects.length; i++) {
this._objects[i].render(ctx);
}
this._drawClipPath(ctx, this.clipPath);
}
/**
* @override
* @return {Boolean}
*/
setCoords() {
super.setCoords();
this._shouldSetNestedCoords() &&
this.forEachObject((object) => object.setCoords());
}
/**
* Renders instance on a given context
* @param {CanvasRenderingContext2D} ctx context to render instance on
*/
render(ctx: CanvasRenderingContext2D) {
this._transformDone = true;
super.render(ctx);
this._transformDone = false;
}
/**
* @public
* @param {Partial<LayoutResult> & { layout?: string }} [context] pass values to use for layout calculations
*/
triggerLayout(context) {
if (context && context.layout) {
context.prevLayout = this.layout;
this.layout = context.layout;
}
this._applyLayoutStrategy({ type: 'imperative', context });
}
/**
* @private
* @param {FabricObject} object
* @param {Point} diff
*/
_adjustObjectPosition(object: FabricObject, diff: Point) {
object.set({
left: object.left + diff.x,
top: object.top + diff.y,
});
}
/**
* initial layout logic:
* calculate bbox of objects (if necessary) and translate it according to options received from the constructor (left, top, width, height)
* so it is placed in the center of the bbox received from the constructor
*
* @private
* @param {LayoutContext} context
*/
_applyLayoutStrategy(context) {
const isFirstLayout = context.type === 'initialization';
if (!isFirstLayout && !this._firstLayoutDone) {
// reject layout requests before initialization layout
return;
}
const options = isFirstLayout && context.options;
const initialTransform = options && {
angle: options.angle || 0,
skewX: options.skewX || 0,
skewY: options.skewY || 0,
};
const center = this.getRelativeCenterPoint();
let result = this.getLayoutStrategyResult(
this.layout,
this._objects.concat(),
context
);
let diff: Point;
if (result) {
// handle positioning
const newCenter = new Point(result.centerX, result.centerY);
const vector = center
.subtract(newCenter)
.add(new Point(result.correctionX || 0, result.correctionY || 0));
diff = vector.transform(invertTransform(this.calcOwnMatrix()), true);
// set dimensions
this.set({ width: result.width, height: result.height });
// adjust objects to account for new center
!context.objectsRelativeToGroup &&
this.forEachObject((object) => {
this._adjustObjectPosition(object, diff);
});
// clip path as well
!isFirstLayout &&
this.layout !== 'clip-path' &&
this.clipPath &&
!this.clipPath.absolutePositioned &&
this._adjustObjectPosition(this.clipPath, diff);
if (!newCenter.eq(center) || initialTransform) {
// set position
this.setPositionByOrigin(newCenter, 'center', 'center');
initialTransform && this.set(initialTransform);
this.setCoords();
}
} else if (isFirstLayout) {
// fill `result` with initial values for the layout hook
result = {
centerX: center.x,
centerY: center.y,
width: this.width,
height: this.height,
};
initialTransform && this.set(initialTransform);
} else {
// no `result` so we return
return;
}
// flag for next layouts
this._firstLayoutDone = true;
// fire layout hook and event (event will fire only for layouts after initialization layout)
this.onLayout(context, result);
this.fire('layout', {
context,
result,
diff,
});
// recursive up
if (this.group && this.group._applyLayoutStrategy) {
// append the path recursion to context
if (!context.path) {
context.path = [];
}
context.path.push(this);
// all parents should invalidate their layout
this.group._applyLayoutStrategy(context);
}
}
/**
* Override this method to customize layout.
* If you need to run logic once layout completes use `onLayout`
* @public
* @param {string} layoutDirective
* @param {FabricObject[]} objects
* @param {LayoutContext} context
* @returns {LayoutResult | undefined}
*/
getLayoutStrategyResult(
layoutDirective: LayoutStrategy,
objects: FabricObject[],
context: LayoutContext
) {
if (
layoutDirective === 'fit-content-lazy' &&
context.type === 'added' &&
objects.length > context.targets.length
) {
// calculate added objects' bbox with existing bbox
const addedObjects = context.targets.concat(this);
return this.prepareBoundingBox(layoutDirective, addedObjects, context);
} else if (
layoutDirective === 'fit-content' ||
layoutDirective === 'fit-content-lazy' ||
(layoutDirective === 'fixed' &&
(context.type === 'initialization' || context.type === 'imperative'))
) {
return this.prepareBoundingBox(layoutDirective, objects, context);
} else if (layoutDirective === 'clip-path' && this.clipPath) {
const clipPath = this.clipPath;
const clipPathSizeAfter = clipPath._getTransformedDimensions();
if (
clipPath.absolutePositioned &&
(context.type === 'initialization' || context.type === 'layout_change')
) {
// we want the center point to exist in group's containing plane
let clipPathCenter = clipPath.getCenterPoint();
if (this.group) {
// send point from canvas plane to group's containing plane
const inv = invertTransform(this.group.calcTransformMatrix());
clipPathCenter = transformPoint(clipPathCenter, inv);
}
return {
centerX: clipPathCenter.x,
centerY: clipPathCenter.y,
width: clipPathSizeAfter.x,
height: clipPathSizeAfter.y,
};
} else if (!clipPath.absolutePositioned) {
let center;
const clipPathRelativeCenter = clipPath.getRelativeCenterPoint(),
// we want the center point to exist in group's containing plane, so we send it upwards
clipPathCenter = transformPoint(
clipPathRelativeCenter,
this.calcOwnMatrix(),
true
);
if (
context.type === 'initialization' ||
context.type === 'layout_change'
) {
const bbox =
this.prepareBoundingBox(layoutDirective, objects, context) || {};
center = new Point(bbox.centerX || 0, bbox.centerY || 0);
return {
centerX: center.x + clipPathCenter.x,
centerY: center.y + clipPathCenter.y,
correctionX: bbox.correctionX - clipPathCenter.x,
correctionY: bbox.correctionY - clipPathCenter.y,
width: clipPath.width,
height: clipPath.height,
};
} else {
center = this.getRelativeCenterPoint();
return {
centerX: center.x + clipPathCenter.x,
centerY: center.y + clipPathCenter.y,
width: clipPathSizeAfter.x,
height: clipPathSizeAfter.y,
};
}
}
} else if (layoutDirective === 'svg' && context.type === 'initialization') {
const bbox = this.getObjectsBoundingBox(objects, true) || {};
return Object.assign(bbox, {
correctionX: -bbox.offsetX || 0,
correctionY: -bbox.offsetY || 0,
});
}
}
/**
* Override this method to customize layout.
* A wrapper around {@link Group#getObjectsBoundingBox}
* @public
* @param {string} layoutDirective
* @param {FabricObject[]} objects
* @param {LayoutContext} context
* @returns {LayoutResult | undefined}
*/
prepareBoundingBox(
layoutDirective: LayoutStrategy,
objects: FabricObject[],
context: LayoutContext
) {
if (context.type === 'initialization') {
return this.prepareInitialBoundingBox(layoutDirective, objects, context);
} else if (context.type === 'imperative' && context.context) {
return Object.assign(
this.getObjectsBoundingBox(objects) || {},
context.context
);
} else {
return this.getObjectsBoundingBox(objects);
}
}
/**
* Calculates center taking into account originX, originY while not being sure that width/height are initialized
* @public
* @param {string} layoutDirective
* @param {FabricObject[]} objects
* @param {LayoutContext} context
* @returns {LayoutResult | undefined}
*/
prepareInitialBoundingBox(
layoutDirective: LayoutStrategy,
objects: FabricObject[],
context: LayoutContext
) {
const options = context.options || {},
hasX = typeof options.left === 'number',
hasY = typeof options.top === 'number',
hasWidth = typeof options.width === 'number',
hasHeight = typeof options.height === 'number';
// performance enhancement
// skip layout calculation if bbox is defined
if (
(hasX &&
hasY &&
hasWidth &&
hasHeight &&
context.objectsRelativeToGroup) ||
objects.length === 0
) {
// return nothing to skip layout
return;
}
const bbox = this.getObjectsBoundingBox(objects) || {};
const width = hasWidth ? this.width : bbox.width || 0,
height = hasHeight ? this.height : bbox.height || 0,
calculatedCenter = new Point(bbox.centerX || 0, bbox.centerY || 0),
origin = new Point(
resolveOrigin(this.originX),
resolveOrigin(this.originY)
),
size = new Point(width, height),
strokeWidthVector = this._getTransformedDimensions({
width: 0,
height: 0,
}),
sizeAfter = this._getTransformedDimensions({
width: width,
height: height,
strokeWidth: 0,
}),
bboxSizeAfter = this._getTransformedDimensions({
width: bbox.width,
height: bbox.height,
strokeWidth: 0,
}),
rotationCorrection = new Point(0, 0);
// calculate center and correction
const originT = origin.scalarAdd(0.5);
const originCorrection = sizeAfter.multiply(originT);
const centerCorrection = new Point(
hasWidth ? bboxSizeAfter.x / 2 : originCorrection.x,
hasHeight ? bboxSizeAfter.y / 2 : originCorrection.y
);
const center = new Point(
hasX
? this.left - (sizeAfter.x + strokeWidthVector.x) * origin.x
: calculatedCenter.x - centerCorrection.x,
hasY
? this.top - (sizeAfter.y + strokeWidthVector.y) * origin.y
: calculatedCenter.y - centerCorrection.y
);
const offsetCorrection = new Point(
hasX
? center.x - calculatedCenter.x + bboxSizeAfter.x * (hasWidth ? 0.5 : 0)
: -(hasWidth
? (sizeAfter.x - strokeWidthVector.x) * 0.5
: sizeAfter.x * originT.x),
hasY
? center.y -
calculatedCenter.y +
bboxSizeAfter.y * (hasHeight ? 0.5 : 0)
: -(hasHeight
? (sizeAfter.y - strokeWidthVector.y) * 0.5
: sizeAfter.y * originT.y)
).add(rotationCorrection);
const correction = new Point(
hasWidth ? -sizeAfter.x / 2 : 0,
hasHeight ? -sizeAfter.y / 2 : 0
).add(offsetCorrection);
return {
centerX: center.x,
centerY: center.y,
correctionX: correction.x,
correctionY: correction.y,
width: size.x,
height: size.y,
};
}
/**
* Calculate the bbox of objects relative to instance's containing plane
* @public
* @param {FabricObject[]} objects
* @returns {LayoutResult | null} bounding box
*/
getObjectsBoundingBox(
objects: FabricObject[],
ignoreOffset?: boolean
): LayoutResult | null {
if (objects.length === 0) {
return null;
}
let min: Point, max: Point;
objects.forEach((object, i) => {
const objCenter = object.getRelativeCenterPoint();
let sizeVector = object._getTransformedDimensions().scalarDivide(2);
if (object.angle) {
const rad = degreesToRadians(object.angle),
sine = Math.abs(sin(rad)),
cosine = Math.abs(cos(rad)),
rx = sizeVector.x * cosine + sizeVector.y * sine,
ry = sizeVector.x * sine + sizeVector.y * cosine;
sizeVector = new Point(rx, ry);
}
const a = objCenter.subtract(sizeVector);
const b = objCenter.add(sizeVector);
if (i === 0) {
min = new Point(Math.min(a.x, b.x), Math.min(a.y, b.y));
max = new Point(Math.max(a.x, b.x), Math.max(a.y, b.y));
} else {
min.setXY(Math.min(min.x, a.x, b.x), Math.min(min.y, a.y, b.y));
max.setXY(Math.max(max.x, a.x, b.x), Math.max(max.y, a.y, b.y));
}
});
const size = max.subtract(min),
relativeCenter = ignoreOffset
? size.scalarDivide(2)
: min.midPointFrom(max),
// we send `relativeCenter` up to group's containing plane
offset = min.transform(this.calcOwnMatrix()),
center = relativeCenter.transform(this.calcOwnMatrix());
return {
offsetX: offset.x,
offsetY: offset.y,
centerX: center.x,
centerY: center.y,
width: size.x,
height: size.y,
};
}
/**
* Hook that is called once layout has completed.
* Provided for layout customization, override if necessary.
* Complements `getLayoutStrategyResult`, which is called at the beginning of layout.
* @public
* @param {LayoutContext} context layout context
* @param {LayoutResult} result layout result
*/
// eslint-disable-next-line @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars
onLayout(context: LayoutContext, result: LayoutResult) {}
/**
*
* @private
* @param {'toObject'|'toDatalessObject'} [method]
* @param {string[]} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @returns {FabricObject[]} serialized objects
*/
__serializeObjects(
method: 'toObject' | 'toDatalessObject',
propertiesToInclude?: string[]
) {
const _includeDefaultValues = this.includeDefaultValues;
return this._objects
.filter(function (obj) {
return !obj.excludeFromExport;
})
.map(function (obj) {
const originalDefaults = obj.includeDefaultValues;
obj.includeDefaultValues = _includeDefaultValues;
const data = obj[method || 'toObject'](propertiesToInclude);
obj.includeDefaultValues = originalDefaults;
//delete data.version;
return data;
});
}
/**
* Returns object representation of an instance
* @param {string[]} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @return {Object} object representation of an instance
*/
toObject(propertiesToInclude: (keyof this)[] = []) {
const obj = super.toObject([
'layout',
'subTargetCheck',
'interactive',
...propertiesToInclude,
]);
obj.objects = this.__serializeObjects('toObject', propertiesToInclude);
return obj;
}
toString() {
return `#<Group: (${this.complexity()})>`;
}
dispose() {
this._activeObjects = [];
this.forEachObject((object) => {
this._watchObject(false, object);
object.dispose();
});
super.dispose();
}
/**
* @private
*/
_createSVGBgRect(reviver?: (markup: string) => any) {
if (!this.backgroundColor) {
return '';
}
const fillStroke = Rect.prototype._toSVG.call(this, reviver);
const commons = fillStroke.indexOf('COMMON_PARTS');
fillStroke[commons] = 'for="group" ';
return fillStroke.join('');
}
/**
* Returns svg representation of an instance
* @param {Function} [reviver] Method for further parsing of svg representation.
* @return {String} svg representation of an instance
*/
_toSVG(reviver?: (markup: string) => any) {
const svgString = ['<g ', 'COMMON_PARTS', ' >\n'];
const bg = this._createSVGBgRect(reviver);
bg && svgString.push('\t\t', bg);
for (let i = 0; i < this._objects.length; i++) {
svgString.push('\t\t', this._objects[i].toSVG(reviver));
}
svgString.push('</g>\n');
return svgString;
}
/**
* Returns styles-string for svg-export, specific version for group
* @return {String}
*/
getSvgStyles() {
const opacity =
typeof this.opacity !== 'undefined' && this.opacity !== 1
? `opacity: ${this.opacity};`
: '',
visibility = this.visible ? '' : ' visibility: hidden;';