-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.spec.ts
More file actions
587 lines (509 loc) · 22 KB
/
index.spec.ts
File metadata and controls
587 lines (509 loc) · 22 KB
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
import { Textbox } from 'fabric'
import SnappingManager from '../../../../src/editor/snapping-manager'
import { MOVE_SNAP_STEP } from '../../../../src/editor/snapping-manager/constants'
import { getObjectBounds } from '../../../../src/editor/utils/geometry'
import { createBoundsObject, createSnappingTestContext } from '../../../test-utils/editor-helpers'
type OriginX = 'left' | 'center' | 'right'
type OriginY = 'top' | 'center' | 'bottom'
type SpacingAxis = 'vertical' | 'horizontal'
/**
* Создаёт мок объекта для тестирования масштабирования со снапом.
*/
const createScalingObject = ({
left,
top,
width,
height,
scaleX = 1,
scaleY = 1,
originX = 'left',
originY = 'top',
angle = 0
}: {
left: number
top: number
width: number
height: number
scaleX?: number
scaleY?: number
originX?: OriginX
originY?: OriginY
angle?: number
}) => {
const obj: any = {
left,
top,
width,
height,
scaleX,
scaleY,
originX,
originY,
angle,
visible: true,
set: (props: Partial<Record<string, number | string>>) => {
Object.assign(obj, props)
},
setCoords: jest.fn(),
getBoundingRect: () => {
const {
left: objLeft = 0,
top: objTop = 0,
width: rawWidth = 0,
height: rawHeight = 0,
scaleX: currentScaleX = 1,
scaleY: currentScaleY = 1
} = obj
const resolvedWidth = rawWidth * currentScaleX
const resolvedHeight = rawHeight * currentScaleY
return {
left: objLeft,
top: objTop,
width: resolvedWidth,
height: resolvedHeight
}
},
getRelativeCenterPoint: () => {
const {
left: objLeft = 0,
top: objTop = 0,
width: rawWidth = 0,
height: rawHeight = 0,
scaleX: currentScaleX = 1,
scaleY: currentScaleY = 1
} = obj
const resolvedWidth = rawWidth * currentScaleX
const resolvedHeight = rawHeight * currentScaleY
return {
x: objLeft + (resolvedWidth / 2),
y: objTop + (resolvedHeight / 2)
}
},
translateToOriginPoint: (point: { x: number; y: number }, nextOriginX: OriginX, nextOriginY: OriginY) => {
const {
width: rawWidth = 0,
height: rawHeight = 0,
scaleX: currentScaleX = 1,
scaleY: currentScaleY = 1
} = obj
const resolvedWidth = rawWidth * currentScaleX
const resolvedHeight = rawHeight * currentScaleY
let nextX = point.x
let nextY = point.y
if (nextOriginX === 'left') {
nextX -= resolvedWidth / 2
}
if (nextOriginX === 'right') {
nextX += resolvedWidth / 2
}
if (nextOriginY === 'top') {
nextY -= resolvedHeight / 2
}
if (nextOriginY === 'bottom') {
nextY += resolvedHeight / 2
}
return {
x: nextX,
y: nextY
}
},
setPositionByOrigin: jest.fn()
}
return obj
}
/**
* Создаёт сценарий равноудалённости с перекрывающим объектом на выбранной оси.
*/
const createSpacingScenario = ({ axis }: { axis: SpacingAxis }) => {
const { editor, objects, canvas } = createSnappingTestContext()
canvas.getZoom.mockReturnValue(2)
const expectedGap = 24
if (axis === 'vertical') {
const first = createBoundsObject({ left: 0, top: 0, width: 20, height: 20, id: 'obj-1' })
const active = createBoundsObject({ left: 0, top: 46, width: 20, height: 20, id: 'active' })
const third = createBoundsObject({ left: 0, top: 88, width: 20, height: 20, id: 'obj-2' })
const blocker = createBoundsObject({ left: 0, top: 60, width: 40, height: 40, id: 'blocker' })
objects.push(first, third, blocker, active)
return {
editor,
active,
expectedGap,
expectedPosition: 44
}
}
const first = createBoundsObject({ left: 0, top: 0, width: 20, height: 20, id: 'obj-1' })
const active = createBoundsObject({ left: 46, top: 0, width: 20, height: 20, id: 'active' })
const third = createBoundsObject({ left: 88, top: 0, width: 20, height: 20, id: 'obj-2' })
const blocker = createBoundsObject({ left: 60, top: 0, width: 40, height: 20, id: 'blocker' })
objects.push(first, third, blocker, active)
return {
editor,
active,
expectedGap,
expectedPosition: 44
}
}
describe('SnappingManager', () => {
beforeEach(() => {
jest.clearAllMocks()
})
it('кеширует интервалы между пересекающимися по ширине объектами независимо от их размеров', () => {
const { editor, objects } = createSnappingTestContext()
const first = createBoundsObject({ left: 0, top: 0, width: 40, height: 30, id: 'obj-1' })
const second = createBoundsObject({ left: 10, top: 100, width: 160, height: 20, id: 'obj-2' })
const active = createBoundsObject({ left: 5, top: 180, width: 60, height: 40, id: 'active' })
objects.push(first, second, active)
const snappingManager = new SnappingManager({ editor });
(snappingManager as any)._handleMouseDown({ target: active })
const { spacingPatterns, cachedTargetBounds } = snappingManager as any
expect(cachedTargetBounds).toHaveLength(2)
expect(spacingPatterns.vertical).toEqual(
expect.arrayContaining([
expect.objectContaining({
distance: 70,
start: 30,
end: 100
})
])
)
})
it('подтягивает активный объект к кешированному расстоянию с учётом перекрытия по ширине', () => {
const { editor, canvas, objects } = createSnappingTestContext()
const first = createBoundsObject({ left: 0, top: 0, width: 40, height: 30, id: 'obj-1' })
const second = createBoundsObject({ left: 10, top: 100, width: 160, height: 20, id: 'obj-2' })
const active = createBoundsObject({ left: 5, top: 188, width: 20, height: 50, id: 'active' })
objects.push(first, second, active)
const snappingManager = new SnappingManager({ editor });
(snappingManager as any)._handleMouseDown({ target: active });
(snappingManager as any)._handleObjectMoving({ target: active })
expect(active.top).toBe(190)
const { activeSpacingGuides } = snappingManager as any
expect(activeSpacingGuides.length).toBeGreaterThan(0)
expect(activeSpacingGuides[0]).toEqual(expect.objectContaining({ distance: 70 }))
expect(canvas.requestRenderAll).toHaveBeenCalled()
})
it('округляет координаты до шага MOVE_SNAP_STEP после перемещения', () => {
const { editor } = createSnappingTestContext()
const active = createBoundsObject({ left: 10.2, top: 15.8, width: 20, height: 20, id: 'active' })
const snappingManager = new SnappingManager({ editor })
const snappingManagerState = snappingManager as any
snappingManagerState._handleObjectMoving({ target: active })
expect(active.left).toBe(Math.round(10.2 / MOVE_SNAP_STEP) * MOVE_SNAP_STEP)
expect(active.top).toBe(Math.round(15.8 / MOVE_SNAP_STEP) * MOVE_SNAP_STEP)
expect(active.setCoords).toHaveBeenCalled()
})
it('округляет координаты до шага MOVE_SNAP_STEP при перемещении с CTRL', () => {
const { editor } = createSnappingTestContext()
const active = createBoundsObject({ left: 21.6, top: 33.3, width: 30, height: 30, id: 'active' })
const snappingManager = new SnappingManager({ editor })
const snappingManagerState = snappingManager as any
snappingManagerState._handleObjectMoving({
target: active,
e: { ctrlKey: true }
})
expect(active.left).toBe(Math.round(21.6 / MOVE_SNAP_STEP) * MOVE_SNAP_STEP)
expect(active.top).toBe(Math.round(33.3 / MOVE_SNAP_STEP) * MOVE_SNAP_STEP)
expect(active.setCoords).toHaveBeenCalled()
})
it('показывает равноудалённость, если половина свободного зазора не кратна шагу', () => {
const { editor, objects } = createSnappingTestContext()
const first = createBoundsObject({ left: 0, top: 0, width: 10, height: 10, id: 'obj-1' })
const second = createBoundsObject({ left: 24, top: 0, width: 10, height: 10, id: 'obj-2' })
const active = createBoundsObject({ left: 14, top: 0, width: 8, height: 10, id: 'active' })
objects.push(first)
objects.push(second)
objects.push(active)
const snappingManager = new SnappingManager({ editor })
const snappingManagerState = snappingManager as any
snappingManagerState._handleMouseDown({ target: active })
snappingManagerState._handleObjectMoving({ target: active })
const { activeSpacingGuides } = snappingManager as any
expect(activeSpacingGuides.length).toBeGreaterThan(0)
expect(activeSpacingGuides[0].distance).toBe(3)
})
it('показывает общий display-distance при неидеально делимом центральном зазоре', () => {
const { editor, objects } = createSnappingTestContext()
const first = createBoundsObject({ left: 0, top: 0, width: 10, height: 10, id: 'obj-1' })
const second = createBoundsObject({ left: 75, top: 0, width: 10, height: 10, id: 'obj-2' })
const active = createBoundsObject({ left: 33, top: 0, width: 20, height: 10, id: 'active' })
objects.push(first)
objects.push(second)
objects.push(active)
const snappingManager = new SnappingManager({ editor })
const snappingManagerState = snappingManager as any
snappingManagerState._handleMouseDown({ target: active })
snappingManagerState._handleObjectMoving({ target: active })
const { activeSpacingGuides } = snappingManager as any
expect(activeSpacingGuides.length).toBeGreaterThan(0)
expect(activeSpacingGuides[0].distance).toBe(23)
})
it('показывает равноудалённость по шагу и расстояние совпадает с фактическим зазором', () => {
const { editor, objects } = createSnappingTestContext()
const first = createBoundsObject({ left: 0, top: 0, width: 10, height: 10, id: 'obj-1' })
const second = createBoundsObject({ left: 26, top: 0, width: 10, height: 10, id: 'obj-2' })
const active = createBoundsObject({ left: 12, top: 0, width: 8, height: 10, id: 'active' })
objects.push(first)
objects.push(second)
objects.push(active)
const snappingManager = new SnappingManager({ editor })
const snappingManagerState = snappingManager as any
snappingManagerState._handleMouseDown({ target: active })
snappingManagerState._handleObjectMoving({ target: active })
const { activeSpacingGuides } = snappingManager as any
expect(activeSpacingGuides.length).toBeGreaterThan(0)
const guide = activeSpacingGuides[0]
const { distance } = guide
const activeBounds = getObjectBounds({ object: active })
const firstBounds = getObjectBounds({ object: first })
const secondBounds = getObjectBounds({ object: second })
if (!activeBounds || !firstBounds || !secondBounds) {
throw new Error('Bounds не рассчитаны для теста равноудалённости')
}
const { left: activeLeft, right: activeRight } = activeBounds
const { right: firstRight } = firstBounds
const { left: secondLeft } = secondBounds
const gapLeft = activeLeft - firstRight
const gapRight = secondLeft - activeRight
expect(gapLeft).toBe(distance)
expect(gapRight).toBe(distance)
expect(distance % MOVE_SNAP_STEP).toBe(0)
})
it('снапит равноудалённость по вертикали при перекрывающем объекте между кругами', () => {
const scenario = createSpacingScenario({ axis: 'vertical' })
const {
editor,
active,
expectedGap,
expectedPosition
} = scenario
const snappingManager = new SnappingManager({ editor })
const snappingManagerState = snappingManager as any
snappingManagerState._handleMouseDown({ target: active })
snappingManagerState._handleObjectMoving({ target: active })
expect(active.top).toBe(expectedPosition)
const { activeSpacingGuides } = snappingManager as any
expect(activeSpacingGuides).toEqual(
expect.arrayContaining([
expect.objectContaining({ distance: expectedGap })
])
)
})
it('снапит равноудалённость по горизонтали при перекрывающем объекте между кругами', () => {
const scenario = createSpacingScenario({ axis: 'horizontal' })
const {
editor,
active,
expectedGap,
expectedPosition
} = scenario
const snappingManager = new SnappingManager({ editor })
const snappingManagerState = snappingManager as any
snappingManagerState._handleMouseDown({ target: active })
snappingManagerState._handleObjectMoving({ target: active })
expect(active.left).toBe(expectedPosition)
const { activeSpacingGuides } = snappingManager as any
expect(activeSpacingGuides).toEqual(
expect.arrayContaining([
expect.objectContaining({ distance: expectedGap })
])
)
})
it('показывает одинаковый display-distance для разных объектов в вертикальной цепочке', () => {
const { editor, objects } = createSnappingTestContext()
const top = createBoundsObject({ left: 0, top: 0, width: 50, height: 50, id: 'top' })
const middle = createBoundsObject({ left: 0, top: 91, width: 50, height: 50, id: 'middle' })
const bottom = createBoundsObject({ left: 0, top: 182, width: 50, height: 50, id: 'bottom' })
objects.push(top)
objects.push(middle)
objects.push(bottom)
const middleSnappingManager = new SnappingManager({ editor });
(middleSnappingManager as any)._handleMouseDown({ target: middle });
(middleSnappingManager as any)._handleObjectMoving({ target: middle })
const middleGuides = (middleSnappingManager as any).activeSpacingGuides
const middleDistance = middleGuides[0]?.distance
const topSnappingManager = new SnappingManager({ editor });
(topSnappingManager as any)._handleMouseDown({ target: top });
(topSnappingManager as any)._handleObjectMoving({ target: top })
const topGuides = (topSnappingManager as any).activeSpacingGuides
const topDistance = topGuides[0]?.distance
expect(middleDistance).toBe(41)
expect(topDistance).toBe(41)
})
it('показывает одинаковый display-distance в вертикальной цепочке при уменьшенном среднем объекте', () => {
const { editor, objects } = createSnappingTestContext()
const top = createBoundsObject({ left: 0, top: 0, width: 80, height: 80, id: 'top' })
const middle = createBoundsObject({ left: 0, top: 109, width: 80, height: 40, id: 'middle' })
const bottom = createBoundsObject({ left: 0, top: 177, width: 80, height: 80, id: 'bottom' })
objects.push(top)
objects.push(middle)
objects.push(bottom)
const middleSnappingManager = new SnappingManager({ editor });
(middleSnappingManager as any)._handleMouseDown({ target: middle });
(middleSnappingManager as any)._handleObjectMoving({ target: middle })
const middleGuides = (middleSnappingManager as any).activeSpacingGuides
const middleDistance = middleGuides[0]?.distance
const bottomSnappingManager = new SnappingManager({ editor });
(bottomSnappingManager as any)._handleMouseDown({ target: bottom });
(bottomSnappingManager as any)._handleObjectMoving({ target: bottom })
const bottomGuides = (bottomSnappingManager as any).activeSpacingGuides
const bottomDistance = bottomGuides[0]?.distance
expect(middleDistance).toBe(29)
expect(bottomDistance).toBe(29)
})
it('не переносит левый референсный зазор на правую сторону без правой цепочки', () => {
const { editor, objects } = createSnappingTestContext()
const first = createBoundsObject({ left: 0, top: 0, width: 20, height: 20, id: 'obj-1' })
const second = createBoundsObject({ left: 82, top: 0, width: 20, height: 20, id: 'obj-2' })
const active = createBoundsObject({ left: 169, top: 0, width: 20, height: 20, id: 'active' })
const right = createBoundsObject({ left: 251, top: 0, width: 20, height: 20, id: 'obj-3' })
objects.push(first, second, right, active)
const snappingManager = new SnappingManager({ editor })
const snappingManagerState = snappingManager as any
snappingManagerState._handleMouseDown({ target: active })
snappingManagerState._handleObjectMoving({ target: active })
expect(active.left).toBe(164)
const activeBounds = getObjectBounds({ object: active })
const rightBounds = getObjectBounds({ object: right })
if (!activeBounds || !rightBounds) {
throw new Error('Bounds не рассчитаны для проверки side ownership')
}
const rightGap = rightBounds.left - activeBounds.right
expect(rightGap).toBe(67)
const {
activeSpacingGuides
}: {
activeSpacingGuides: Array<{
activeEnd: number
activeStart: number
distance: number
}>
} = snappingManager as any
expect(activeSpacingGuides).toHaveLength(1)
expect(activeSpacingGuides[0].distance).toBe(62)
expect(activeSpacingGuides[0].activeStart).toBe(second.left + second.width)
expect(activeSpacingGuides[0].activeEnd).toBe(active.left)
expect(activeSpacingGuides[0].activeEnd).not.toBe(rightBounds.left)
})
it('показывает левый и правый контекст, когда паттерн равноудалённости совместим', () => {
const { editor, objects } = createSnappingTestContext()
const first = createBoundsObject({ left: 0, top: 0, width: 20, height: 20, id: 'obj-1' })
const second = createBoundsObject({ left: 82, top: 0, width: 20, height: 20, id: 'obj-2' })
const active = createBoundsObject({ left: 164, top: 0, width: 20, height: 20, id: 'active' })
const right = createBoundsObject({ left: 246, top: 0, width: 20, height: 20, id: 'obj-3' })
objects.push(first, second, right, active)
const snappingManager = new SnappingManager({ editor })
const snappingManagerState = snappingManager as any
snappingManagerState._handleMouseDown({ target: active })
snappingManagerState._handleObjectMoving({ target: active })
const firstBounds = getObjectBounds({ object: first })
const secondBounds = getObjectBounds({ object: second })
const activeBounds = getObjectBounds({ object: active })
const rightBounds = getObjectBounds({ object: right })
if (!firstBounds || !secondBounds || !activeBounds || !rightBounds) {
throw new Error('Bounds не рассчитаны для проверки совместимого паттерна')
}
const {
activeSpacingGuides
}: {
activeSpacingGuides: Array<{
refStart: number
refEnd: number
activeStart: number
activeEnd: number
distance: number
}>
} = snappingManager as any
expect(activeSpacingGuides.length).toBeGreaterThanOrEqual(2)
let hasLeftReferenceGuide = false
let hasRightActiveGuide = false
for (const guide of activeSpacingGuides) {
const isLeftReferenceGuide = guide.refStart === firstBounds.right
&& guide.refEnd === secondBounds.left
&& guide.distance === 62
if (isLeftReferenceGuide) {
hasLeftReferenceGuide = true
}
const isRightActiveGuide = guide.activeStart === activeBounds.right
&& guide.activeEnd === rightBounds.left
&& guide.distance === 62
if (isRightActiveGuide) {
hasRightActiveGuide = true
}
}
expect(hasLeftReferenceGuide).toBe(true)
expect(hasRightActiveGuide).toBe(true)
})
it('масштабирует объект по X с прилипаниями и фиксирует origin', () => {
const { editor, objects } = createSnappingTestContext()
const active = createScalingObject({
left: 296,
top: 100,
width: 100,
height: 50,
originX: 'left',
originY: 'top'
})
objects.push(active)
const snappingManager = new SnappingManager({ editor })
const snappingManagerState = snappingManager as any
snappingManagerState.anchors = { vertical: [400], horizontal: [] }
snappingManagerState._handleObjectScaling({
target: active,
transform: {
corner: 'mr',
action: 'scaleX',
originX: 'left',
originY: 'top',
scaleX: 1,
scaleY: 1
}
})
expect(active.scaleX).toBeCloseTo(1.04, 4)
expect(active.setPositionByOrigin).toHaveBeenCalledWith(
expect.objectContaining({ x: 296, y: 100 }),
'left',
'top'
)
const { activeGuides } = snappingManager as any
expect(activeGuides).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: 'vertical',
position: 400
})
])
)
})
it('применяет snap для текстового ресайза по горизонтали и фиксирует правый край', () => {
const { editor, canvas } = createSnappingTestContext()
const snappingManager = new SnappingManager({ editor })
const snappingManagerState = snappingManager as any
snappingManagerState.anchors = { vertical: [200], horizontal: [] }
const textbox = new Textbox('Test', {
left: 204,
top: 50,
width: 100
})
textbox.canvas = canvas as any
snappingManager.applyTextResizingSnap({
target: textbox,
transform: {
corner: 'ml',
originX: 'right',
originY: 'top'
} as any,
event: null
})
expect(textbox.width).toBe(104)
expect(textbox.left).toBe(200)
const { activeGuides } = snappingManager as any
expect(activeGuides).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: 'vertical',
position: 200
})
])
)
})
})