-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
LayoutManager.ts
307 lines (277 loc) · 8.3 KB
/
LayoutManager.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
import type { TModificationEvents } from '../EventTypeDefs';
import { Point } from '../Point';
import { CENTER, iMatrix } from '../constants';
import type { Group } from '../shapes/Group';
import type { FabricObject } from '../shapes/Object/FabricObject';
import { invertTransform } from '../util/misc/matrix';
import { resolveOrigin } from '../util/misc/resolveOrigin';
import { FitContentLayout } from './LayoutStrategies/FitContentLayout';
import type { LayoutStrategy } from './LayoutStrategies/LayoutStrategy';
import {
LAYOUT_TYPE_INITIALIZATION,
LAYOUT_TYPE_ADDED,
LAYOUT_TYPE_REMOVED,
LAYOUT_TYPE_IMPERATIVE,
LAYOUT_TYPE_OBJECT_MODIFIED,
LAYOUT_TYPE_OBJECT_MODIFYING,
} from './constants';
import type { LayoutContext, LayoutResult, StrictLayoutContext } from './types';
import { classRegistry } from '../ClassRegistry';
const LAYOUT_MANAGER = 'layoutManager';
export type SerializedLayoutManager = {
type: string;
strategy: string;
};
export class LayoutManager {
private declare _prevLayoutStrategy?: LayoutStrategy;
private declare _subscriptions: Map<FabricObject, VoidFunction[]>;
strategy: LayoutStrategy;
constructor(strategy: LayoutStrategy = new FitContentLayout()) {
this.strategy = strategy;
this._subscriptions = new Map();
}
public performLayout(context: LayoutContext) {
const strictContext: StrictLayoutContext = {
bubbles: true,
strategy: this.strategy,
...context,
prevStrategy: this._prevLayoutStrategy,
stopPropagation() {
this.bubbles = false;
},
};
this.onBeforeLayout(strictContext);
const layoutResult = this.getLayoutResult(strictContext);
layoutResult && this.commitLayout(strictContext, layoutResult);
this.onAfterLayout(strictContext, layoutResult);
this._prevLayoutStrategy = strictContext.strategy;
}
/**
* subscribe to object layout triggers
*/
protected subscribe(object: FabricObject, context: StrictLayoutContext) {
const { target } = context;
this.unsubscribe(object, context);
const disposers = [
object.on('modified', (e) =>
this.performLayout({
trigger: 'modified',
e: { ...e, target: object },
type: LAYOUT_TYPE_OBJECT_MODIFIED,
target,
})
),
...(
[
'moving',
'resizing',
'rotating',
'scaling',
'skewing',
'changed',
'modifyPoly',
] as TModificationEvents[]
).map((key) =>
object.on(key, (e) =>
this.performLayout({
trigger: key,
e: { ...e, target: object },
type: LAYOUT_TYPE_OBJECT_MODIFYING,
target,
})
)
),
];
this._subscriptions.set(object, disposers);
}
/**
* unsubscribe object layout triggers
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected unsubscribe(object: FabricObject, context?: StrictLayoutContext) {
(this._subscriptions.get(object) || []).forEach((d) => d());
this._subscriptions.delete(object);
}
unsubscribeTarget(target: Group) {
target.forEachObject((object) => this.unsubscribe(object));
}
protected onBeforeLayout(context: StrictLayoutContext) {
const { target } = context;
const { canvas } = target;
// handle layout triggers subscription
if (
// subscribe only if instance is the target's `layoutManager`
target.layoutManager === this &&
(context.type === LAYOUT_TYPE_INITIALIZATION ||
context.type === LAYOUT_TYPE_ADDED)
) {
context.targets.forEach((object) => this.subscribe(object, context));
} else if (context.type === LAYOUT_TYPE_REMOVED) {
context.targets.forEach((object) => this.unsubscribe(object, context));
}
// fire layout event (event will fire only for layouts after initialization layout)
target.fire('layout:before', {
context,
});
canvas &&
canvas.fire('object:layout:before', {
target,
context,
});
if (context.type === LAYOUT_TYPE_IMPERATIVE && context.deep) {
const { strategy: _, ...tricklingContext } = context;
// traverse the tree
target.forEachObject((object) => {
(object as Group).layoutManager?.performLayout({
...tricklingContext,
bubbles: false,
target: object as Group,
});
});
}
}
protected getLayoutResult(
context: StrictLayoutContext
): Required<LayoutResult> | undefined {
const { target } = context;
const result = context.strategy.calcLayoutResult(
context,
target.getObjects()
);
if (!result) {
return;
}
const prevCenter =
context.type === LAYOUT_TYPE_INITIALIZATION
? new Point()
: target.getRelativeCenterPoint();
const {
center: nextCenter,
correction = new Point(),
relativeCorrection = new Point(),
} = result;
const offset = prevCenter
.subtract(nextCenter)
.add(correction)
.transform(
// in `initialization` we do not account for target's transformation matrix
context.type === LAYOUT_TYPE_INITIALIZATION
? iMatrix
: invertTransform(target.calcOwnMatrix()),
true
)
.add(relativeCorrection);
return {
result,
prevCenter,
nextCenter,
offset,
};
}
protected commitLayout(
context: StrictLayoutContext,
layoutResult: Required<LayoutResult>
) {
const { target } = context;
const {
result: { size },
nextCenter,
} = layoutResult;
// set dimensions
target.set({ width: size.x, height: size.y });
// layout descendants
this.layoutObjects(context, layoutResult);
// set position
// in `initialization` we do not account for target's transformation matrix
if (context.type === LAYOUT_TYPE_INITIALIZATION) {
// TODO: what about strokeWidth?
target.set({
left:
context.x ?? nextCenter.x + size.x * resolveOrigin(target.originX),
top: context.y ?? nextCenter.y + size.y * resolveOrigin(target.originY),
});
} else {
target.setPositionByOrigin(nextCenter, CENTER, CENTER);
// invalidate
target.setCoords();
target.set({ dirty: true });
}
}
protected layoutObjects(
context: StrictLayoutContext,
layoutResult: Required<LayoutResult>
) {
const { target } = context;
// adjust objects to account for new center
target.forEachObject((object) => {
object.group === target &&
this.layoutObject(context, layoutResult, object);
});
// adjust clip path to account for new center
context.strategy.shouldLayoutClipPath(context) &&
this.layoutObject(context, layoutResult, target.clipPath as FabricObject);
}
/**
* @param {FabricObject} object
* @param {Point} offset
*/
protected layoutObject(
context: StrictLayoutContext,
{ offset }: Required<LayoutResult>,
object: FabricObject
) {
object.set({
left: object.left + offset.x,
top: object.top + offset.y,
});
}
protected onAfterLayout(
context: StrictLayoutContext,
layoutResult?: LayoutResult
) {
const {
target,
strategy,
bubbles,
prevStrategy: _,
...bubblingContext
} = context;
const { canvas } = target;
// fire layout event (event will fire only for layouts after initialization layout)
target.fire('layout:after', {
context,
result: layoutResult,
});
canvas &&
canvas.fire('object:layout:after', {
context,
result: layoutResult,
target,
});
// bubble
const parent = target.group;
if (bubbles && parent?.layoutManager) {
// add target to context#path
(bubblingContext.path || (bubblingContext.path = [])).push(target);
// all parents should invalidate their layout
parent.layoutManager.performLayout({
...bubblingContext,
target: parent,
});
}
}
dispose() {
this._subscriptions.forEach((disposers) => disposers.forEach((d) => d()));
this._subscriptions.clear();
}
toObject() {
return {
type: LAYOUT_MANAGER,
strategy: (this.strategy.constructor as typeof LayoutStrategy).type,
};
}
toJSON() {
return this.toObject();
}
}
classRegistry.setClass(LayoutManager, LAYOUT_MANAGER);