-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
LayoutManager.ts
347 lines (315 loc) · 9.36 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
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
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,
RegistrationContext,
StrictLayoutContext,
} from './types';
import { classRegistry } from '../ClassRegistry';
import type { TModificationEvents } from '../EventTypeDefs';
const LAYOUT_MANAGER = 'layoutManager';
export type SerializedLayoutManager = {
type: string;
strategy: string;
};
export class LayoutManager {
private declare _prevLayoutStrategy?: LayoutStrategy;
protected 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);
if (layoutResult) {
this.commitLayout(strictContext, layoutResult);
}
this.onAfterLayout(strictContext, layoutResult);
this._prevLayoutStrategy = strictContext.strategy;
}
/**
* Attach handlers for events that we know will invalidate the layout when
* performed on child objects ( general transforms ).
* Returns the disposers for later unsubscribing and cleanup
* @param {FabricObject} object
* @param {RegistrationContext & Partial<StrictLayoutContext>} context
* @returns {VoidFunction[]} disposers remove the handlers
*/
protected attachHandlers(
object: FabricObject,
context: RegistrationContext & Partial<StrictLayoutContext>
): VoidFunction[] {
const { target } = context;
return (
[
'modified',
'moving',
'resizing',
'rotating',
'scaling',
'skewing',
'changed',
'modifyPoly',
] as (TModificationEvents & 'modified')[]
).map((key) =>
object.on(key, (e) =>
this.performLayout(
key === 'modified'
? {
type: LAYOUT_TYPE_OBJECT_MODIFIED,
trigger: key,
e,
target,
}
: {
type: LAYOUT_TYPE_OBJECT_MODIFYING,
trigger: key,
e,
target,
}
)
)
);
}
/**
* Subscribe an object to transform events that will trigger a layout change on the parent
* This is important only for interactive groups.
* @param object
* @param context
*/
protected subscribe(
object: FabricObject,
context: RegistrationContext & Partial<StrictLayoutContext>
) {
this.unsubscribe(object, context);
const disposers = this.attachHandlers(object, context);
this._subscriptions.set(object, disposers);
}
/**
* unsubscribe object layout triggers
*/
protected unsubscribe(
object: FabricObject,
context?: RegistrationContext & Partial<StrictLayoutContext>
) {
(this._subscriptions.get(object) || []).forEach((d) => d());
this._subscriptions.delete(object);
}
unsubscribeTargets(
context: RegistrationContext & Partial<StrictLayoutContext>
) {
context.targets.forEach((object) => this.unsubscribe(object, context));
}
subscribeTargets(
context: RegistrationContext & Partial<StrictLayoutContext>
) {
context.targets.forEach((object) => this.subscribe(object, context));
}
protected onBeforeLayout(context: StrictLayoutContext) {
const { target, type } = context;
const { canvas } = target;
// handle layout triggers subscription
// @TODO: gate the registration when the group is interactive
if (type === LAYOUT_TYPE_INITIALIZATION || type === LAYOUT_TYPE_ADDED) {
this.subscribeTargets(context);
} else if (type === LAYOUT_TYPE_REMOVED) {
this.unsubscribeTargets(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 (type === LAYOUT_TYPE_IMPERATIVE && context.deep) {
const { strategy: _, ...tricklingContext } = context;
// traverse the tree
target.forEachObject(
(object) =>
(object as Group).layoutManager &&
(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
) {
// TODO: this is here for cache invalidation.
// verify if this is necessary since we have explicit
// cache invalidation at the end of commitLayout
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.parent;
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,
});
}
target.set('dirty', true);
}
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);