-
Notifications
You must be signed in to change notification settings - Fork 0
/
interactive.js
942 lines (824 loc) · 30 KB
/
interactive.js
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
import { Morph, config, ProportionalLayout } from 'lively.morphic';
import { pt, Color } from 'lively.graphics';
import { connect, disconnect, signal, disconnectAll } from 'lively.bindings';
import { newUUID } from 'lively.lang/string.js';
import { arr } from 'lively.lang';
import { DeserializationAwareMorph } from './utilities/deserialization-morph.js';
import { zoomKeyPressed } from './keys.js';
import { error } from './utilities/messages.js';
export const DEFAULT_SCROLLOVERLAY_OPACITY = 0.001;
export class Interactive extends DeserializationAwareMorph {
static async base (props = {}) {
const interactive = new Interactive(props);
const { exampleForegroundLayer, exampleBackgroundLayer } = await System.import('qinoq/examples.js');
const foregroundLayer = exampleForegroundLayer();
const backgroundLayer = exampleBackgroundLayer();
interactive.addLayer(backgroundLayer);
interactive.addLayer(foregroundLayer);
const baseSequence = Sequence.baseSequence({ layer: foregroundLayer });
interactive.addSequence(baseSequence);
return interactive;
}
static isMorphInInteractive (morph) {
return morph.isInteractive || morph.isSequence || Sequence.getSequenceOfMorph(morph);
}
static get properties () {
return {
// if this is true, changes to the scrollPosition of the interactive will not be propagated to the scroll overlay
blockScrollEvents: {
defaultValue: false
},
_length: {
type: 'Number',
isFloat: false,
min: 0,
set (_length) {
this.setProperty('_length', _length);
signal(this, 'onLengthChange', _length);
}
},
showHalosForContent: {
defaultValue: true
},
scrollPosition: {
type: 'Number',
isFloat: false,
defaultValue: 0,
set (scrollPosition) {
if (Math.abs(scrollPosition - this.scrollPosition) < 0.5) return; // redraw may be costly! If you want to redraw use redraw explicitly
this.setProperty('scrollPosition', scrollPosition);
this.redraw();
}
},
fixedAspectRatio: {
defaultValue: 16 / 9,
set (aspectRatio) {
this.setProperty('fixedAspectRatio', aspectRatio);
// eslint-disable-next-line no-self-assign
this.extent = this.applyAspectRatio(this.extent);
}
},
extent: {
defaultValue: pt(533, 300),
set (extent) {
// the extent becoming zero in either dimension breaks proportional layouts
if (extent.x < 1 || extent.y < 1) extent = pt(1, 1);
if (this.fixedAspectRatio) {
extent = this.applyAspectRatio(extent);
}
this.setProperty('extent', extent);
if (!this._deserializing) {
this.updateSequenceExtents();
this.scaleText();
}
}
},
sequences: {
defaultValue: []
},
layers: {
defaultValue: []
},
clipMode: {
defaultValue: 'hidden'
},
nextKeyframeNumber: {
// used for default keyframe names
type: 'Number',
defaultValue: 1
},
linkMap: {
initialize () {
this.linkMap = new Map();
}
},
_scrollOverlay: {
after: ['extent'],
initialize () {
this.initScrollOverlay();
// VDOM seems to hold older nodes and mistakes them for the new ScrollHolder
// this leads to unexpected jumps of the scrollPosition
// therefore we reset it again here with respect to the rendering routine
this.whenRendered().then(() => { this.scrollOverlay.scroll = pt(0, 0); });
}
}
};
}
updateSequenceExtents () {
this.sequences.forEach(sequence => sequence.extent = this.extent);
}
applyAspectRatio (extent, calculateAspectRatio = false) {
let aspectRatio;
aspectRatio = calculateAspectRatio ? this.width / this.height : this.fixedAspectRatio;
return pt(aspectRatio ? extent.y * aspectRatio : extent.x, extent.y);
}
fitBounds (extent) {
this.scale = extent.y / this.extent.y;
}
interactiveZoomed () {
// a hook to listen for zooming in the interactive
}
// this is to be called if the scrollPosition is changed via any means that are not natural scrolling
onExternalScrollChange (scrollPosition) {
this.blockScrollEvents = true;
// this is necessary since the actual change of this.scrollPosition will only be done after onScroll on the InteractiveScrollHolder was executed
// the scrollEvent for that is not handled synchronously
this.scrollPosition = scrollPosition;
this.scrollOverlay.setProperty('scroll', pt(0, scrollPosition));
}
// this can be listened to to get changes to the scrollPosition due to natural scrolling
onInternalScrollChange (scrollPosition) {}
get scrollOverlay () {
return this._scrollOverlay;
}
set scrollOverlay (scrollOverlay) {
this._scrollOverlay = scrollOverlay;
}
initScrollOverlay () {
this.scrollOverlay = new InteractiveScrollHolder({ interactive: this });
const scrollLengthContainer = new Morph({
name: 'scrollable content',
halosEnabled: false,
acceptsDrops: false
});
this.scrollOverlay.addMorph(scrollLengthContainer);
connect(this, 'position', this.scrollOverlay, 'position');
connect(this, 'onLengthChange', scrollLengthContainer, 'extent', { converter: '(length) => pt(1, length + source.extent.y)', varMapping: { pt } });
connect(this, 'extent', this, 'updateScrollContainerExtents');
connect(this, 'scale', this.scrollOverlay, 'scale');
}
scaleText () {
const morphsWithText = this.sequences.flatMap(sequence => sequence.submorphs).filter(morph => 'fontSize' in morph);
morphsWithText.forEach(morph => {
morph.fontSize = Math.ceil(morph._fontRatio * this.extent.y);
});
}
updateScrollContainerExtents () {
this.scrollOverlay.extent = this.extent;
const scrollableContent = this.scrollOverlay.submorphs[0];
scrollableContent.extent = pt(1, this.extent.y + this._length);
}
updateInteractiveLength () {
this._length = Math.max(0, Math.max(...this.sequences.map(sequence => sequence.end)));
}
openInWorld () {
this.updateInteractiveLength();
super.openInWorld();
this.scrollOverlay.openInWorld();
this.scrollOverlay.position = this.position;
}
remove () {
this.scrollOverlay.remove();
super.remove();
}
onOwnerChanged (newOwner) {
if (newOwner && this.scrollOverlay) {
newOwner.addMorph(this.scrollOverlay);
}
}
get isInteractive () {
return true;
}
redraw () {
this.sequences.forEach(sequence => {
sequence.updateProgress(this.scrollPosition);
if (sequence.isDisplayed()) {
if (sequence.owner !== this) {
sequence.onSequenceEnter();
}
this.addMorph(sequence);
} else if (sequence.owner == this) {
sequence.remove();
sequence.onSequenceLeave();
}
});
}
// Is called every time any layer changes zIndex
sortSequences () {
this.sequences.sort((a, b) => a.layer.zIndex - b.layer.zIndex);
this.redraw();
}
getSequencesInLayer (layer) {
return this.sequences.filter(sequence => sequence.layer === layer);
}
getSequencesInLayerBetween (layer, start, end) {
return this.getSequencesInLayer(layer).filter(sequence => (sequence.end >= start && sequence.end <= end) || (sequence.start >= start && sequence.start <= end));
}
getSequenceInLayerBefore (sequence) {
const sequencesInLayer = this.getSequencesInLayer(sequence.layer);
sequencesInLayer.sort((a, b) => a.start - b.start); // Sort in ascending order
const sequenceIndex = sequencesInLayer.indexOf(sequence);
return sequencesInLayer[sequenceIndex - 1];
}
getSequenceInLayerAfter (sequence) {
const sequencesInLayer = this.getSequencesInLayer(sequence.layer);
sequencesInLayer.sort((a, b) => a.start - b.start); // Sort in ascending order
const sequenceIndex = sequencesInLayer.indexOf(sequence);
return sequencesInLayer[sequenceIndex + 1];
}
getLastSequenceInLayer (layer) {
return this.getSequencesInLayer(layer).sort((a, b) => b.end - a.end)[0];
}
getSequenceStarts () {
return this.sequences.map(sequence => sequence.start).sort((a, b) => a - b);
}
getSequenceEnds () {
return this.sequences.map(sequence => sequence.end).sort((a, b) => a - b);
}
getSequenceStartAndEnds () {
return this.getSequenceStarts().concat(this.getSequenceEnds()).sort((a, b) => a - b);
}
getNextSequenceStartOrEnd (scrollPosition = this.scrollPosition) {
return this.getSequenceStartAndEnds().find(position => position > scrollPosition);
}
getPrevSequenceStartOrEnd (scrollPosition = this.scrollPosition) {
return this.getSequenceStartAndEnds().reverse().find(position => position < scrollPosition);
}
addLayer (layer) {
this.layers.push(layer);
layer.interactive = this;
}
removeLayer (layer) {
arr.remove(this.layers, layer);
this.getSequencesInLayer(layer).forEach(sequence => this.removeSequence(sequence));
}
get highestZIndex () {
return Math.max(...this.layers.map(layer => layer.zIndex));
}
addSequence (sequence) {
// morphs with text in the added sequence do not yet have a stored fontRatio
sequence.submorphs.forEach(morph => {
if (morph.fontSize) morph._fontRatio = morph.fontSize * this.extent.y;
});
connect(sequence, 'layer', this, 'sortSequences');
this.sequences.push(sequence);
if (!sequence.layer || !this.layers.includes(sequence.layer)) {
sequence.layer = this.layers[0];
}
sequence.interactive = this;
this.updateInteractiveLength();
signal(this, 'onSequenceAddition', sequence);
this.sortSequences();
}
removeSequence (sequence) {
disconnectAll(sequence);
arr.remove(this.sequences, sequence);
sequence.remove();
signal(this, 'onSequenceRemoval', sequence);
this.updateInteractiveLength();
}
sequenceWouldBeValidInLayer (sequence, start, duration, layer) {
return this.getSequencesInLayerBetween(layer, start, start + duration).filter(s => s != sequence).length === 0;
}
validSequenceStart (sequence, start) {
if (start == undefined || start == null || isNaN(start)) return false;
if (start < 0) return false;
return this.getSequencesInLayerBetween(sequence.layer, start, start + sequence.duration).filter(s => s != sequence).length === 0;
}
validSequenceDuration (sequence, duration) {
if (duration == undefined || duration == null || isNaN(duration)) return false;
if (duration < 1) return false;
const nextSequence = this.getSequenceInLayerAfter(sequence);
if (nextSequence) {
return nextSequence.start >= sequence.start + duration;
}
return true;
}
showOnly (sequence) {
if (sequence) {
this.sequences.forEach(seq => {
seq.focused = (sequence == seq);
});
}
this.redraw();
}
showAllSequences () {
this.sequences.forEach(seq => {
seq.focused = true;
});
this.redraw();
}
get length () {
return this._length;
}
findKeyframe (keyframe) {
for (const sequence of this.sequences) {
let foundAnimation;
for (const animation of sequence.animations) {
if (animation.keyframes.find(anotherKeyframe => anotherKeyframe.equals(keyframe))) {
foundAnimation = animation;
break;
}
}
if (foundAnimation) {
return { sequence, animation: foundAnimation };
}
}
}
get thisAndAllSubmorphs () {
const result = [this];
this.sequences.forEach(sequence => sequence.withAllSubmorphsDo(morph => result.push(morph)));
return result;
}
get isScrollBarVisible () {
return this.scrollOverlay.opacity != DEFAULT_SCROLLOVERLAY_OPACITY;
}
setScrollBarVisibility (visible) {
this.scrollOverlay.opacity = visible ? 1 : DEFAULT_SCROLLOVERLAY_OPACITY;
}
triggerClickAction (target) {
if (this.linkMap.has(target)) {
window.open(this.linkMap.get(target), '_blank', 'noreferrer=yes,noopener=yes').focus();
}
}
}
export class Scrollytelling extends Interactive {}
class InteractiveScrollHolder extends Morph {
static get properties () {
return {
interactive: {
set (interactive) {
this.setProperty('interactive', interactive);
if (this.interactive) {
this.extent = pt(this.interactive.width, this.interactive.height);
}
}
},
name: {
defaultValue: 'scrollable container'
},
clipMode: {
defaultValue: 'auto'
},
// opacity of zero leads to removal of object from DOM in firefox
opacity: {
defaultValue: DEFAULT_SCROLLOVERLAY_OPACITY
},
fill: {
defaultValue: Color.transparent
},
halosEnabled: {
defaultValue: false
},
draggable: {
defaultValue: true
},
passThroughMorph: {
defaultValue: false
},
// holds morphs that are created with the topbar for the editor to subscribe to
newMorph: {},
scrollToResize: {
defaultValue: false
}
};
}
get topbar () {
return $world.getSubmorphNamed('lively top bar');
}
onMouseWheel (event) {
if (this.scrollToResize && zoomKeyPressed(event)) {
event.domEvt.preventDefault();
// 1000 is an empirical value derived from the feeling on my device.
// Might need to be adapted later one, especially since the feeling might diverge for touchpads.
this.interactive.scale += event.domEvt.deltaY / 1000;
this.interactive.position = pt(0, 0);
this.interactive.interactiveZoomed();
}
}
onScroll (event) {
if (!this.interactive.blockScrollEvents) {
this.interactive.scrollPosition = this.scroll.y;
this.interactive.onInternalScrollChange(this.interactive.scrollPosition);
}
this.interactive.blockScrollEvents = false;
}
onDrag (event) {
if (!this.passThroughMorph && this.delegatedTarget) {
event.state.dragStartMorphPosition = this.dragStartPosition;
this.delegatedTarget.onDrag(event);
}
}
onDragStart (event) {
this.opacity = 1;
this.clipMode = 'hidden';
if (!this.passThroughMorph) {
const targetMorph = this.getUnderlyingMorph(event.hand.globalPosition);
this.delegatedTarget = undefined;
if (targetMorph.draggable) {
this.delegatedTarget = targetMorph;
const { dragStartMorphPosition } = event.state;
this.dragStartPosition = targetMorph.position;
event.state.dragStartMorphPosition = this.dragStartPosition;
targetMorph.onDragStart(event);
}
}
}
onDragEnd (event) {
this.setNewMorph();
if (!this.passThroughMorph && this.delegatedTarget) {
event.state.dragStartMorphPosition = this.dragStartPosition;
// this should not be necessary but if we do not call this here
// grabbing will only work once
// in theory the onDragEnd of the delegatedTarget should stop the undo
// and we do not start a separate one
this.env.undoManager.undoStop();
this.delegatedTarget.onDragEnd(event);
}
this.opacity = DEFAULT_SCROLLOVERLAY_OPACITY;
this.clipMode = 'auto';
}
onHoverIn (event) {
if (!this.passThroughMorph && this.topbar) {
if (this.topbar.editMode != 'Halo' && this.topbar.editMode != 'Hand') {
this.topbar.setEditMode('Halo');
error('Draw in sequence view!');
}
}
if (this.passThroughMorph && this.topbar) {
// upon attaching a new target to the topbar it switches to halo mode
// since we attach on HoverIn, we need to restore the previous mode
// otherwise no mode except for halo mode would be possible
const topbarMode = this.topbar.editMode;
this.topbar.attachToTarget(this);
this.topbar.setEditMode(topbarMode);
// used for creation of morph that get created via single click (e.g. label)
connect(this.topbar, 'handleShapeCreation', this, 'setNewMorph');
}
}
onHoverOut (event) {
if (this.passThroughMorph && this.topbar) {
this.topbar.attachToTarget($world);
disconnect(this.topbar, 'handleShapeCreation', this, 'setNewMorph');
}
}
onDrop (event) {
if (event.type != 'morphicdragend') return;
if (!this.passThroughMorph) {
signal(this, 'rejectDrop', event);
return;
}
event.hand.grabbedMorphs.forEach(grabbedMorph => {
const { pointerAndShadow } = event.hand._grabbedMorphProperties.get(grabbedMorph) || {};
Object.assign(grabbedMorph, pointerAndShadow);
this.newMorph = grabbedMorph;
});
}
onMouseDown (event) {
// select morphs in halo mode without triggering their implementation of onMouseDown
if (this.topbar && this.topbar.editMode == 'Halo') return;
super.onMouseDown(event);
this.currentMouseTarget = this.getUnderlyingMorph(event.hand.globalPosition);
// allows to select text in text morphs by dragging in sequence view
if (!this.passThroughMorph || this.topbar.editMode == 'Halo' || this.topbar.editMode == 'Hand') this.updateEventDispatcherState();
this.currentMouseTarget.onMouseDown(event);
}
onDoubleMouseDown (event) {
if (this.getUnderlyingMorph(event.hand.position) == this.currentMouseTarget) this.currentMouseTarget.onDoubleMouseDown(event);
}
createMockEvent (target) {
return {
hand: $world.firstHand,
isClickTarget: () => false,
targetMorph: target,
position: $world.firstHand.position,
positionIn: (morph) => morph.localize($world.firstHand.globalPosition),
state: {}
};
}
onMouseMove (event) {
// for not absolutely clear reasons it is important that this comes before the hover handling
this.currentMouseTarget = this.getUnderlyingMorph(event.hand.globalPosition);
this.updateEventDispatcherState();
if (!this.currentMouseTarget) return;
// handle halo mode on our own when the scrollOverlay is target of the topbar (i.e., with editor in sequence view)
// the handling of the topbar never finds the actual morphs in the interactive, but oly the scrollholder
if (this.topbar && this.topbar.editMode == 'Halo' && this.editor && this.editor.isInSequenceView) {
if (Sequence.getSequenceOfMorph(this.currentMouseTarget) == this.editor.currentSequence) {
this.topbar.showHaloPreviewFor(this.currentMouseTarget);
}
}
if (this.currentMouseTarget == this.previousMorphUnderMouse) return;
if (this.currentMouseTarget) {
this.currentMouseTarget.onMouseMove(event);
this.currentMouseTarget.onHoverIn(this.createMockEvent(this.currentMouseTarget));
this.handleTooltips(this.currentMouseTarget);
(this.topbar && (this.topbar.editMode == 'Text' || this.topbar.editMode == 'Shape'))
? this.nativeCursor = 'crosshair'
: this.nativeCursor = this.currentMouseTarget.nativeCursor;
}
if (this.previousMorphUnderMouse) {
this.previousMorphUnderMouse.onHoverOut(this.createMockEvent(this.currentMouseTarget));
this.tooltipViewer.hoverOutOfMorph(this.tooltipViewer.currentMorph);
}
this.previousMorphUnderMouse = this.currentMouseTarget;
}
onMouseUp (event) {
// select morphs in halo mode without triggering their implementation of onMouseUp
if (!(this.topbar && this.topbar.editMode == 'Halo')) {
let target = this.getUnderlyingMorph(event.hand.globalPosition);
this.interactive.triggerClickAction(target);
target.onMouseUp(event);
}
}
get tooltipViewer () {
return $world._tooltipViewer;
}
handleTooltips (target) {
const handTooltipOffset = pt(10, 7);
if (target.tooltip) {
this.tooltipViewer.currentMorph = target;
this.tooltipViewer.timer = setTimeout(
() => {
const hand = $world.firstHand;
this.tooltipViewer.showTooltipFor(target, hand);
if (this.tooltipViewer.currentTooltip) this.tooltipViewer.currentTooltip.position = hand.position.addPt(handTooltipOffset);
},
config.showTooltipsAfter * 1000);
}
}
onContextMenu (event) {
const underlyingMorph = this.getUnderlyingMorph(event.hand.globalPosition);
event.targetMorphs.unshift(underlyingMorph);
underlyingMorph.onContextMenu(event);
}
// some morphs (like textMorphs) check some state that is saved here to determine if they are focused or not
// just changing the values in the events that are passed around does not suffice
// therefore we change this state here with the values that we need for the event delegation
updateEventDispatcherState () {
this.env.eventDispatcher.eventState.focusedMorph = this.currentMouseTarget;
this.env.eventDispatcher.eventState.clickedOnMorph = this.currentMouseTarget;
}
setNewMorph () {
if (this.passThroughMorph) {
const newMorph = this.submorphs.filter(submorph => submorph.name !== 'scrollable content')[0];
if (newMorph) {
this.newMorph = newMorph;
// resetting this on mouse up will break the creation of morphs with a single click
this.topbar.setEditMode('Halo');
}
}
}
getUnderlyingMorph (position) {
let targetedMorph = this.morphBeneath(position);
while (targetedMorph && targetedMorph.isSequence) {
targetedMorph = targetedMorph.morphBeneath(position);
}
return targetedMorph;
}
onOwnerChanged (newOwner) {
if (!newOwner) return;
// for unkown reasons, the scrollOverlay escaped the editor on some interactions
// this catches it back
if (this.owner != this.interactive.owner) {
this.interactive.owner.addMorph(this);
}
}
get editor () {
return this.owner.owner;
}
}
export class Layer {
set zIndex (zIndex) {
this._zIndex = zIndex;
if (this.interactive) {
this.interactive.sortSequences();
}
}
get zIndex () {
return this._zIndex;
}
constructor (props = {}) {
const {
name = 'Unnamed Layer',
hidden = false,
zIndex = 0
} = props;
this.name = name;
this.hidden = hidden;
this._zIndex = zIndex;
this.uuid = newUUID();
}
equals (layer) {
return this.uuid === layer.uuid;
}
}
export class Sequence extends DeserializationAwareMorph {
static get properties () {
return {
start: {
set (start) {
this.setProperty('start', Math.round(start));
},
defaultValue: 0
},
duration: {
defaultValue: 0,
set (duration) {
this.setProperty('duration', Math.round(duration));
},
isFloat: false
},
_progress: {
defaultValue: 0,
isFloat: true
},
layer: {},
name: {
defaultValue: 'unnamed sequence'
},
fill: {
defaultValue: Color.transparent
},
reactsToPointer: {
defaultValue: false
},
halosEnabled: {
defaultValue: false
},
extent: {
defaultValue: pt(0, 0)
},
focused: {
defaultValue: true,
set (focused) {
this.setProperty('focused', focused);
this.applyUnfocusedEffect();
}
},
_originalOpacity: { defaultValue: 1 },
_originalGrayscale: { defaultValue: 0 },
opacity: {
defaultValue: 1,
set (opacity) {
this.setProperty('opacity', opacity);
if (!this._lockEffect && !this._deserializing) this._originalOpacity = opacity;
}
},
grayScale: {
defaultValue: 0,
set (grayscale) {
this.setProperty('grayscale', grayscale);
if (!this._lockEffect && !this._deserializing) this._originalGrayscale = grayscale;
}
},
animations: {
defaultValue: []
},
interactive: {
set (interactive) {
this.setProperty('interactive', interactive);
this.extent = interactive.extent;
this.layout = new ProportionalLayout({ lastExtent: this.extent });
}
},
isHidden: {
defaultValue: false,
set (isHidden) {
this.setProperty('isHidden', isHidden);
if (this.interactive) this.interactive.redraw();
}
}
};
}
static getSequenceOfMorph (morph) {
return morph ? morph.ownerChain().find(m => m.isSequence) : undefined;
}
static baseSequence (props = {}) {
return new Sequence({ name: 'first sequence', start: 0, duration: 250, ...props });
}
get isSequence () {
return true;
}
get isEmpty () {
return this.submorphs.length === 0;
}
get end () {
return this.start + this.duration;
}
get progress () {
return this._progress;
}
isDisplayed () {
return this.progress >= 0 && this.progress < 1 && !this.layer.hidden && !this.isHidden;
}
toggleHide () {
this.isHidden = !this.isHidden;
}
addMorph (morph, insertBeforeMorph) {
super.addMorph(morph, insertBeforeMorph);
if (morph.fontSize && this.interactive) morph._fontRatio = morph.fontSize / this.interactive.extent.y;
}
addMorphAt (morph, index) {
super.addMorphAt(morph, index);
if (morph.fontSize && this.interactive) morph._fontRatio = morph.fontSize / this.interactive.extent.y;
}
addMorphBack (morph) {
super.addMorphBack(morph);
if (morph.fontSize && this.interactive) morph._fontRatio = morph.fontSize / this.interactive.extent.y;
}
/**
* Remove a morph from a sequence and clear references to it,
* e.g. removing animations with that morph
* Name "removeMorph" is already taken, a call with doNotAbandonMorph = false,
* results in clearing all connections from sequence to morph
* while not calling abandon on the morph
**/
abandonMorph (morph, doNotAbandonMorph = false) {
// remove all custom connection from the interactive to the morph to be removed
this.interactive.attributeConnections.forEach(connection => {
if (connection.targetObj == morph) {
disconnect(this.interactive, connection.sourceAttrName, morph, connection.targetMethodName);
}
});
if (doNotAbandonMorph) {
if (morph._fontRatio) delete morph._fontRatio;
morph.remove();
} else morph.abandon(true);
this.animations.filter(animation => animation.target == morph).forEach(animation => this.removeAnimation(animation));
signal(this, 'onMorphRemoval', morph);
}
applyUnfocusedEffect () {
this.submorphs.forEach(submorph => submorph.halosEnabled = this.focused);
// stop opacity and grayscale setters from overwriting saved effects
this._lockEffect = true;
this.opacity = this.focused ? this._originalOpacity : 0.2;
this.grayscale = this.focused ? this._originalGrayscale : 1;
this._lockEffect = false;
}
updateProgress (scrollPosition) {
this._progress = (scrollPosition - this.start) / this.duration;
this.animations.forEach(animation => animation.progress = this.progress);
this.submorphs.forEach(submorph => typeof submorph.onInteractiveScrollChange === 'function' && submorph.onInteractiveScrollChange(scrollPosition));
}
onSequenceEnter () {
this.submorphs.forEach(submorph => typeof submorph.onSequenceEnter === 'function' && submorph.onSequenceEnter());
}
onSequenceLeave () {
this.submorphs.forEach(submorph => typeof submorph.onSequenceLeave === 'function' && submorph.onSequenceLeave());
}
getAbsolutePosition (progress) {
return Math.round((this.duration * progress) + this.start);
}
addAnimation (animation) {
this.animations.push(animation);
signal(this, 'onAnimationAddition', animation);
}
removeAnimation (animation) {
arr.remove(this.animations, animation);
signal(this, 'onAnimationRemoval', animation);
}
getAnimationForMorphProperty (morph, property) {
// Assumes only one animation per property/morph combination
const possibleAnimations = this.animations.filter(animation => animation.target === morph && animation.property === property);
return possibleAnimations[0];
}
// Generic interface to add a keyframe to a sequence
async addKeyframeForMorph (keyframe, morph, property, propertyType = 'point', transformKeyframe = false) {
const existingAnimation = this.getAnimationForMorphProperty(morph, property);
const transformKeyframeValue = (animation) => {
if (transformKeyframe && animation.useRelativeValues && propertyType == 'point') {
keyframe.value = pt(keyframe.value.x / this.width, keyframe.value.y / this.height);
}
};
if (existingAnimation) {
transformKeyframeValue(existingAnimation);
existingAnimation.addKeyframe(keyframe);
return existingAnimation;
}
const { createAnimationForPropertyType } = await System.import('qinoq/animations.js');
const newAnimation = createAnimationForPropertyType(propertyType, morph, property);
transformKeyframeValue(newAnimation);
newAnimation.addKeyframe(keyframe);
this.addAnimation(newAnimation);
return newAnimation;
}
onKeyframeAddedInAnimation (change = { keyframe: null, animation: null }) {
// used for connections
}
onKeyframeRemovedInAnimation (change = { keyframe: null, animation: null }) {
// used for connections
}
getAnimationsForMorph (morph) {
return this.animations.filter(animation => animation.target === morph);
}
get allKeyframes () {
return this.animations.map(animation => animation.keyframes).flat().sort((a, b) => a.position - b.position);
}
getNextKeyframePositionForAbsolutePosition (absolutePosition) {
return this.allKeyframes.map(keyframe => keyframe.position).find(keyframePosition => this.getAbsolutePosition(keyframePosition) > absolutePosition);
}
getPrevKeyframePositionForAbsolutePosition (absolutePosition) {
return this.allKeyframes.reverse().map(keyframe => keyframe.position).find(keyframePosition => this.getAbsolutePosition(keyframePosition) < absolutePosition);
}
getAbsolutePositionFor (keyframe) {
return Math.round(this.start + (this.duration * keyframe.position));
}
getRelativePositionFor (scrollPosition) {
return (scrollPosition - this.start) / this.duration;
}
onLoad () {
// while saving the easings itself get lost and we need to recreate them
this.animations.forEach(animation => animation.keyframes.forEach(keyframe => keyframe.setEasing(keyframe.easingName)));
}
}