summaryrefslogtreecommitdiffstats
path: root/devtools/client/inspector/animation/animation.js
blob: c0f5d389d044e9d0c23b15beb52f1612537a585f (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const {
  createElement,
  createFactory,
} = require("resource://devtools/client/shared/vendor/react.js");
const {
  Provider,
} = require("resource://devtools/client/shared/vendor/react-redux.js");

const EventEmitter = require("resource://devtools/shared/event-emitter.js");

const App = createFactory(
  require("resource://devtools/client/inspector/animation/components/App.js")
);
const CurrentTimeTimer = require("resource://devtools/client/inspector/animation/current-time-timer.js");

const animationsReducer = require("resource://devtools/client/inspector/animation/reducers/animations.js");
const {
  updateAnimations,
  updateDetailVisibility,
  updateElementPickerEnabled,
  updateHighlightedNode,
  updatePlaybackRates,
  updateSelectedAnimation,
  updateSidebarSize,
} = require("resource://devtools/client/inspector/animation/actions/animations.js");
const {
  hasAnimationIterationCountInfinite,
  hasRunningAnimation,
} = require("resource://devtools/client/inspector/animation/utils/utils.js");

class AnimationInspector {
  constructor(inspector, win) {
    this.inspector = inspector;
    this.win = win;

    this.inspector.store.injectReducer("animations", animationsReducer);

    this.addAnimationsCurrentTimeListener =
      this.addAnimationsCurrentTimeListener.bind(this);
    this.getAnimatedPropertyMap = this.getAnimatedPropertyMap.bind(this);
    this.getAnimationsCurrentTime = this.getAnimationsCurrentTime.bind(this);
    this.getComputedStyle = this.getComputedStyle.bind(this);
    this.getNodeFromActor = this.getNodeFromActor.bind(this);
    this.removeAnimationsCurrentTimeListener =
      this.removeAnimationsCurrentTimeListener.bind(this);
    this.rewindAnimationsCurrentTime =
      this.rewindAnimationsCurrentTime.bind(this);
    this.selectAnimation = this.selectAnimation.bind(this);
    this.setAnimationsCurrentTime = this.setAnimationsCurrentTime.bind(this);
    this.setAnimationsPlaybackRate = this.setAnimationsPlaybackRate.bind(this);
    this.setAnimationsPlayState = this.setAnimationsPlayState.bind(this);
    this.setDetailVisibility = this.setDetailVisibility.bind(this);
    this.setHighlightedNode = this.setHighlightedNode.bind(this);
    this.setSelectedNode = this.setSelectedNode.bind(this);
    this.simulateAnimation = this.simulateAnimation.bind(this);
    this.simulateAnimationForKeyframesProgressBar =
      this.simulateAnimationForKeyframesProgressBar.bind(this);
    this.toggleElementPicker = this.toggleElementPicker.bind(this);
    this.update = this.update.bind(this);
    this.onAnimationStateChanged = this.onAnimationStateChanged.bind(this);
    this.onAnimationsCurrentTimeUpdated =
      this.onAnimationsCurrentTimeUpdated.bind(this);
    this.onAnimationsMutation = this.onAnimationsMutation.bind(this);
    this.onCurrentTimeTimerUpdated = this.onCurrentTimeTimerUpdated.bind(this);
    this.onElementPickerStarted = this.onElementPickerStarted.bind(this);
    this.onElementPickerStopped = this.onElementPickerStopped.bind(this);
    this.onNavigate = this.onNavigate.bind(this);
    this.onSidebarResized = this.onSidebarResized.bind(this);
    this.onSidebarSelectionChanged = this.onSidebarSelectionChanged.bind(this);
    this.onTargetAvailable = this.onTargetAvailable.bind(this);

    EventEmitter.decorate(this);
    this.emitForTests = this.emitForTests.bind(this);

    this.initComponents();
    this.initListeners();
  }

  initComponents() {
    const {
      addAnimationsCurrentTimeListener,
      emitForTests: emitEventForTest,
      getAnimatedPropertyMap,
      getAnimationsCurrentTime,
      getComputedStyle,
      getNodeFromActor,
      isAnimationsRunning,
      removeAnimationsCurrentTimeListener,
      rewindAnimationsCurrentTime,
      selectAnimation,
      setAnimationsCurrentTime,
      setAnimationsPlaybackRate,
      setAnimationsPlayState,
      setDetailVisibility,
      setHighlightedNode,
      setSelectedNode,
      simulateAnimation,
      simulateAnimationForKeyframesProgressBar,
      toggleElementPicker,
    } = this;

    const direction = this.win.document.dir;

    this.animationsCurrentTimeListeners = [];
    this.isCurrentTimeSet = false;

    const provider = createElement(
      Provider,
      {
        id: "animationinspector",
        key: "animationinspector",
        store: this.inspector.store,
      },
      App({
        addAnimationsCurrentTimeListener,
        direction,
        emitEventForTest,
        getAnimatedPropertyMap,
        getAnimationsCurrentTime,
        getComputedStyle,
        getNodeFromActor,
        isAnimationsRunning,
        removeAnimationsCurrentTimeListener,
        rewindAnimationsCurrentTime,
        selectAnimation,
        setAnimationsCurrentTime,
        setAnimationsPlaybackRate,
        setAnimationsPlayState,
        setDetailVisibility,
        setHighlightedNode,
        setSelectedNode,
        simulateAnimation,
        simulateAnimationForKeyframesProgressBar,
        toggleElementPicker,
      })
    );
    this.provider = provider;
  }

  async initListeners() {
    await this.inspector.commands.targetCommand.watchTargets({
      types: [this.inspector.commands.targetCommand.TYPES.FRAME],
      onAvailable: this.onTargetAvailable,
    });

    this.inspector.on("new-root", this.onNavigate);
    this.inspector.selection.on("new-node-front", this.update);
    this.inspector.sidebar.on("select", this.onSidebarSelectionChanged);
    this.inspector.toolbox.on("select", this.onSidebarSelectionChanged);
    this.inspector.toolbox.on(
      "inspector-sidebar-resized",
      this.onSidebarResized
    );
    this.inspector.toolbox.nodePicker.on(
      "picker-started",
      this.onElementPickerStarted
    );
    this.inspector.toolbox.nodePicker.on(
      "picker-stopped",
      this.onElementPickerStopped
    );
  }

  destroy() {
    this.setAnimationStateChangedListenerEnabled(false);
    this.inspector.off("new-root", this.onNavigate);
    this.inspector.selection.off("new-node-front", this.update);
    this.inspector.sidebar.off("select", this.onSidebarSelectionChanged);
    this.inspector.toolbox.off(
      "inspector-sidebar-resized",
      this.onSidebarResized
    );
    this.inspector.toolbox.nodePicker.off(
      "picker-started",
      this.onElementPickerStarted
    );
    this.inspector.toolbox.nodePicker.off(
      "picker-stopped",
      this.onElementPickerStopped
    );
    this.inspector.toolbox.off("select", this.onSidebarSelectionChanged);

    if (this.animationsFront) {
      this.animationsFront.off("mutations", this.onAnimationsMutation);
    }

    if (this.simulatedAnimation) {
      this.simulatedAnimation.cancel();
      this.simulatedAnimation = null;
    }

    if (this.simulatedElement) {
      this.simulatedElement.remove();
      this.simulatedElement = null;
    }

    if (this.simulatedAnimationForKeyframesProgressBar) {
      this.simulatedAnimationForKeyframesProgressBar.cancel();
      this.simulatedAnimationForKeyframesProgressBar = null;
    }

    this.stopAnimationsCurrentTimeTimer();

    this.inspector = null;
    this.win = null;
  }

  get state() {
    return this.inspector.store.getState().animations;
  }

  addAnimationsCurrentTimeListener(listener) {
    this.animationsCurrentTimeListeners.push(listener);
  }

  /**
   * This function calls AnimationsFront.setCurrentTimes with considering the createdTime.
   *
   * @param {Number} currentTime
   */
  async doSetCurrentTimes(currentTime) {
    const { animations, timeScale } = this.state;
    currentTime = currentTime + timeScale.minStartTime;
    await this.animationsFront.setCurrentTimes(animations, currentTime, true, {
      relativeToCreatedTime: true,
    });
  }

  /**
   * Return a map of animated property from given animation actor.
   *
   * @param {Object} animation
   * @return {Map} A map of animated property
   *         key: {String} Animated property name
   *         value: {Array} Array of keyframe object
   *         Also, the keyframe object is consisted as following.
   *         {
   *           value: {String} style,
   *           offset: {Number} offset of keyframe,
   *           easing: {String} easing from this keyframe to next keyframe,
   *           distance: {Number} use as y coordinate in graph,
   *         }
   */
  getAnimatedPropertyMap(animation) {
    const properties = animation.state.properties;
    const animatedPropertyMap = new Map();

    for (const { name, values } of properties) {
      const keyframes = values.map(
        ({ value, offset, easing, distance = 0 }) => {
          offset = parseFloat(offset.toFixed(3));
          return { value, offset, easing, distance };
        }
      );

      animatedPropertyMap.set(name, keyframes);
    }

    return animatedPropertyMap;
  }

  getAnimationsCurrentTime() {
    return this.currentTime;
  }

  /**
   * Return the computed style of the specified property after setting the given styles
   * to the simulated element.
   *
   * @param {String} property
   *        CSS property name (e.g. text-align).
   * @param {Object} styles
   *        Map of CSS property name and value.
   * @return {String}
   *         Computed style of property.
   */
  getComputedStyle(property, styles) {
    this.simulatedElement.style.cssText = "";

    for (const propertyName in styles) {
      this.simulatedElement.style.setProperty(
        propertyName,
        styles[propertyName]
      );
    }

    return this.win
      .getComputedStyle(this.simulatedElement)
      .getPropertyValue(property);
  }

  getNodeFromActor(actorID) {
    if (!this.inspector) {
      return Promise.reject("Animation inspector already destroyed");
    }

    return this.inspector.walker.getNodeFromActor(actorID, ["node"]);
  }

  isPanelVisible() {
    return (
      this.inspector &&
      this.inspector.toolbox &&
      this.inspector.sidebar &&
      this.inspector.toolbox.currentToolId === "inspector" &&
      this.inspector.sidebar.getCurrentTabID() === "animationinspector"
    );
  }

  onAnimationStateChanged() {
    // Simply update the animations since the state has already been updated.
    this.fireUpdateAction([...this.state.animations]);
  }

  /**
   * This method should call when the current time is changed.
   * Then, dispatches the current time to listeners that are registered
   * by addAnimationsCurrentTimeListener.
   *
   * @param {Number} currentTime
   */
  onAnimationsCurrentTimeUpdated(currentTime) {
    this.currentTime = currentTime;

    for (const listener of this.animationsCurrentTimeListeners) {
      listener(currentTime);
    }
  }

  /**
   * This method is called when the current time proceed by CurrentTimeTimer.
   *
   * @param {Number} currentTime
   * @param {Bool} shouldStop
   */
  onCurrentTimeTimerUpdated(currentTime, shouldStop) {
    if (shouldStop) {
      this.setAnimationsCurrentTime(currentTime, true);
    } else {
      this.onAnimationsCurrentTimeUpdated(currentTime);
    }
  }

  async onAnimationsMutation(changes) {
    let animations = [...this.state.animations];
    const addedAnimations = [];

    for (const { type, player: animation } of changes) {
      if (type === "added") {
        if (!animation.state.type) {
          // This animation was added but removed immediately.
          continue;
        }

        addedAnimations.push(animation);
        animation.on("changed", this.onAnimationStateChanged);
      } else if (type === "removed") {
        const index = animations.indexOf(animation);

        if (index < 0) {
          // This animation was added but removed immediately.
          continue;
        }

        animations.splice(index, 1);
        animation.off("changed", this.onAnimationStateChanged);
      }
    }

    // Update existing other animations as well since the currentTime would be proceeded
    // sice the scrubber position is related the currentTime.
    // Also, don't update the state of removed animations since React components
    // may refer to the same instance still.
    try {
      animations = await this.refreshAnimationsState(animations);
    } catch (_) {
      console.error(`Updating Animations failed`);
      return;
    }

    this.fireUpdateAction(animations.concat(addedAnimations));
  }

  onElementPickerStarted() {
    this.inspector.store.dispatch(updateElementPickerEnabled(true));
  }

  onElementPickerStopped() {
    this.inspector.store.dispatch(updateElementPickerEnabled(false));
  }

  onNavigate() {
    if (!this.isPanelVisible()) {
      return;
    }

    this.inspector.store.dispatch(updatePlaybackRates());
  }

  async onSidebarSelectionChanged() {
    const isPanelVisibled = this.isPanelVisible();

    if (this.wasPanelVisibled === isPanelVisibled) {
      // onSidebarSelectionChanged is called some times even same state
      // from sidebar and toolbar.
      return;
    }

    this.wasPanelVisibled = isPanelVisibled;

    if (this.isPanelVisible()) {
      await this.update();
      this.onSidebarResized(null, this.inspector.getSidebarSize());
    } else {
      this.stopAnimationsCurrentTimeTimer();
      this.setAnimationStateChangedListenerEnabled(false);
    }
  }

  onSidebarResized(size) {
    if (!this.isPanelVisible()) {
      return;
    }

    this.inspector.store.dispatch(updateSidebarSize(size));
  }

  async onTargetAvailable({ targetFront }) {
    if (targetFront.isTopLevel) {
      this.animationsFront = await targetFront.getFront("animations");
      this.animationsFront.setWalkerActor(this.inspector.walker);
      this.animationsFront.on("mutations", this.onAnimationsMutation);

      await this.update();
    }
  }

  removeAnimationsCurrentTimeListener(listener) {
    this.animationsCurrentTimeListeners =
      this.animationsCurrentTimeListeners.filter(l => l !== listener);
  }

  async rewindAnimationsCurrentTime() {
    const { timeScale } = this.state;
    await this.setAnimationsCurrentTime(timeScale.zeroPositionTime, true);
  }

  selectAnimation(animation) {
    this.inspector.store.dispatch(updateSelectedAnimation(animation));
  }

  async setSelectedNode(nodeFront) {
    if (this.inspector.selection.nodeFront === nodeFront) {
      return;
    }

    await this.inspector
      .getCommonComponentProps()
      .setSelectedNode(nodeFront, { reason: "animation-panel" });
  }

  async setAnimationsCurrentTime(currentTime, shouldRefresh) {
    this.stopAnimationsCurrentTimeTimer();
    this.onAnimationsCurrentTimeUpdated(currentTime);

    if (!shouldRefresh && this.isCurrentTimeSet) {
      return;
    }

    let animations = this.state.animations;
    this.isCurrentTimeSet = true;

    try {
      await this.doSetCurrentTimes(currentTime);
      animations = await this.refreshAnimationsState(animations);
    } catch (e) {
      // Expected if we've already been destroyed or other node have been selected
      // in the meantime.
      console.error(e);
      return;
    }

    this.isCurrentTimeSet = false;

    if (shouldRefresh) {
      this.fireUpdateAction(animations);
    }
  }

  async setAnimationsPlaybackRate(playbackRate) {
    if (!this.inspector) {
      return; // Already destroyed or another node selected.
    }

    let animations = this.state.animations;
    // "changed" event on each animation will fire respectively when the playback
    // rate changed. Since for each occurrence of event, change of UI is urged.
    // To avoid this, disable the listeners once in order to not capture the event.
    this.setAnimationStateChangedListenerEnabled(false);
    try {
      await this.animationsFront.setPlaybackRates(animations, playbackRate);
      animations = await this.refreshAnimationsState(animations);
    } catch (e) {
      // Expected if we've already been destroyed or another node has been
      // selected in the meantime.
      console.error(e);
      return;
    } finally {
      this.setAnimationStateChangedListenerEnabled(true);
    }

    if (animations) {
      await this.fireUpdateAction(animations);
    }
  }

  async setAnimationsPlayState(doPlay) {
    if (!this.inspector) {
      return; // Already destroyed or another node selected.
    }

    let { animations, timeScale } = this.state;

    try {
      if (
        doPlay &&
        animations.every(
          animation =>
            timeScale.getEndTime(animation) <= animation.state.currentTime
        )
      ) {
        await this.doSetCurrentTimes(timeScale.zeroPositionTime);
      }

      if (doPlay) {
        await this.animationsFront.playSome(animations);
      } else {
        await this.animationsFront.pauseSome(animations);
      }

      animations = await this.refreshAnimationsState(animations);
    } catch (e) {
      // Expected if we've already been destroyed or other node have been selected
      // in the meantime.
      console.error(e);
      return;
    }

    await this.fireUpdateAction(animations);
  }

  /**
   * Enable/disable the animation state change listener.
   * If set true, observe "changed" event on current animations.
   * Otherwise, quit observing the "changed" event.
   *
   * @param {Bool} isEnabled
   */
  setAnimationStateChangedListenerEnabled(isEnabled) {
    if (!this.inspector) {
      return; // Already destroyed.
    }
    if (isEnabled) {
      for (const animation of this.state.animations) {
        animation.on("changed", this.onAnimationStateChanged);
      }
    } else {
      for (const animation of this.state.animations) {
        animation.off("changed", this.onAnimationStateChanged);
      }
    }
  }

  setDetailVisibility(isVisible) {
    this.inspector.store.dispatch(updateDetailVisibility(isVisible));
  }

  /**
   * Persistently highlight the given node identified with a unique selector.
   * If no node is provided, hide any persistent highlighter.
   *
   * @param {NodeFront} nodeFront
   */
  async setHighlightedNode(nodeFront) {
    await this.inspector.highlighters.hideHighlighterType(
      this.inspector.highlighters.TYPES.SELECTOR
    );

    if (nodeFront) {
      const selector = await nodeFront.getUniqueSelector();
      if (!selector) {
        console.warn(
          `Couldn't get unique selector for NodeFront: ${nodeFront.actorID}`
        );
        return;
      }

      /**
       * NOTE: Using a Selector Highlighter here because only one Box Model Highlighter
       * can be visible at a time. The Box Model Highlighter is shown when hovering nodes
       * which would cause this persistent highlighter to be hidden unexpectedly.
       * This limitation of one highlighter type a time should be solved by switching
       * to a highlighter by role approach (Bug 1663443).
       */
      await this.inspector.highlighters.showHighlighterTypeForNode(
        this.inspector.highlighters.TYPES.SELECTOR,
        nodeFront,
        {
          hideInfoBar: true,
          hideGuides: true,
          selector,
        }
      );
    }

    this.inspector.store.dispatch(updateHighlightedNode(nodeFront));
  }

  /**
   * Returns simulatable animation by given parameters.
   * The returned animation is implementing Animation interface of Web Animation API.
   * https://drafts.csswg.org/web-animations/#the-animation-interface
   *
   * @param {Array} keyframes
   *        e.g. [{ opacity: 0 }, { opacity: 1 }]
   * @param {Object} effectTiming
   *        e.g. { duration: 1000, fill: "both" }
   * @param {Boolean} isElementNeeded
   *        true:  create animation with an element.
   *               If want to know computed value of the element, turn on.
   *        false: create animation without an element,
   *               If need to know only timing progress.
   * @return {Animation}
   *         https://drafts.csswg.org/web-animations/#the-animation-interface
   */
  simulateAnimation(keyframes, effectTiming, isElementNeeded) {
    // Don't simulate animation if the animation inspector is already destroyed.
    if (!this.win) {
      return null;
    }

    let targetEl = null;

    if (isElementNeeded) {
      if (!this.simulatedElement) {
        this.simulatedElement = this.win.document.createElement("div");
        this.win.document.documentElement.appendChild(this.simulatedElement);
      } else {
        // Reset styles.
        this.simulatedElement.style.cssText = "";
      }

      targetEl = this.simulatedElement;
    }

    if (!this.simulatedAnimation) {
      this.simulatedAnimation = new this.win.Animation();
    }

    this.simulatedAnimation.effect = new this.win.KeyframeEffect(
      targetEl,
      keyframes,
      effectTiming
    );

    return this.simulatedAnimation;
  }

  /**
   * Returns a simulatable efect timing animation for the keyframes progress bar.
   * The returned animation is implementing Animation interface of Web Animation API.
   * https://drafts.csswg.org/web-animations/#the-animation-interface
   *
   * @param {Object} effectTiming
   *        e.g. { duration: 1000, fill: "both" }
   * @return {Animation}
   *         https://drafts.csswg.org/web-animations/#the-animation-interface
   */
  simulateAnimationForKeyframesProgressBar(effectTiming) {
    if (!this.simulatedAnimationForKeyframesProgressBar) {
      this.simulatedAnimationForKeyframesProgressBar = new this.win.Animation();
    }

    this.simulatedAnimationForKeyframesProgressBar.effect =
      new this.win.KeyframeEffect(null, null, effectTiming);

    return this.simulatedAnimationForKeyframesProgressBar;
  }

  stopAnimationsCurrentTimeTimer() {
    if (this.currentTimeTimer) {
      this.currentTimeTimer.destroy();
      this.currentTimeTimer = null;
    }
  }

  startAnimationsCurrentTimeTimer() {
    const timeScale = this.state.timeScale;
    const shouldStopAfterEndTime = !hasAnimationIterationCountInfinite(
      this.state.animations
    );

    const currentTimeTimer = new CurrentTimeTimer(
      timeScale,
      shouldStopAfterEndTime,
      this.win,
      this.onCurrentTimeTimerUpdated
    );
    currentTimeTimer.start();
    this.currentTimeTimer = currentTimeTimer;
  }

  toggleElementPicker() {
    this.inspector.toolbox.nodePicker.togglePicker();
  }

  async update() {
    if (!this.isPanelVisible()) {
      return;
    }

    const done = this.inspector.updating("animationinspector");

    const selection = this.inspector.selection;
    const animations =
      selection.isConnected() && selection.isElementNode()
        ? await this.animationsFront.getAnimationPlayersForNode(
            selection.nodeFront
          )
        : [];
    this.fireUpdateAction(animations);
    this.setAnimationStateChangedListenerEnabled(true);

    done();
  }

  async refreshAnimationsState(animations) {
    let error = null;

    const promises = animations.map(animation => {
      return new Promise(resolve => {
        animation
          .refreshState()
          .catch(e => {
            error = e;
          })
          .finally(() => {
            resolve();
          });
      });
    });
    await Promise.all(promises);

    if (error) {
      throw new Error(error);
    }

    // Even when removal animation on inspected document, refreshAnimationsState
    // might be called before onAnimationsMutation due to the async timing.
    // Return the animations as result of refreshAnimationsState after getting rid of
    // the animations since they should not display.
    return animations.filter(anim => !!anim.state.type);
  }

  fireUpdateAction(animations) {
    // Animation inspector already destroyed
    if (!this.inspector) {
      return;
    }

    this.stopAnimationsCurrentTimeTimer();

    // Although it is not possible to set a delay or end delay of infinity using
    // the animation API, if the value passed exceeds the limit of our internal
    // representation of times, it will be treated as infinity. Rather than
    // adding special case code to represent this very rare case, we simply omit
    // such animations from the graph.
    animations = animations.filter(
      anim =>
        Math.abs(anim.state.delay) !== Infinity &&
        Math.abs(anim.state.endDelay) !== Infinity
    );

    this.inspector.store.dispatch(updateAnimations(animations));

    if (hasRunningAnimation(animations)) {
      this.startAnimationsCurrentTimeTimer();
    } else {
      // Even no running animations, update the current time once
      // so as to show the state.
      this.onCurrentTimeTimerUpdated(this.state.timeScale.getCurrentTime());
    }
  }
}

module.exports = AnimationInspector;