File: AnimatorsDemo.h

package info (click to toggle)
juce 8.0.6%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 78,204 kB
  • sloc: cpp: 521,891; ansic: 159,819; java: 2,996; javascript: 847; xml: 273; python: 224; sh: 162; makefile: 84
file content (900 lines) | stat: -rw-r--r-- 32,882 bytes parent folder | download | duplicates (2)
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
/*
  ==============================================================================

   This file is part of the JUCE framework examples.
   Copyright (c) Raw Material Software Limited

   The code included in this file is provided under the terms of the ISC license
   http://www.isc.org/downloads/software-support-policy/isc-license. Permission
   to use, copy, modify, and/or distribute this software for any purpose with or
   without fee is hereby granted provided that the above copyright notice and
   this permission notice appear in all copies.

   THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
   REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
   AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
   INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
   LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
   OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
   PERFORMANCE OF THIS SOFTWARE.

  ==============================================================================
*/

/*******************************************************************************
 The block below describes the properties of this PIP. A PIP is a short snippet
 of code that can be read by the Projucer and used to generate a JUCE project.

 BEGIN_JUCE_PIP_METADATA

 name:             AnimatorsDemo
 version:          1.0.0
 vendor:           JUCE
 website:          http://juce.com
 description:      Application demonstrating how the JUCE provided Animator
                   classes can be used to create dynamic, composable, smooth
                   animations.

 dependencies:     juce_core, juce_data_structures, juce_events, juce_graphics,
                   juce_gui_basics, juce_animation
 exporters:        xcode_mac, vs2022, androidstudio, xcode_iphone

 moduleFlags:      JUCE_STRICT_REFCOUNTEDPOINTER=1

 type:             Component
 mainClass:        AnimatorsDemo

 useLocalCopy:     1

 END_JUCE_PIP_METADATA

*******************************************************************************/

#pragma once

struct Paintable
{
    virtual ~Paintable() = default;
    virtual void paint (Graphics& g) const = 0;
};

namespace Shapes
{

class Arc final : public Paintable
{
    static constexpr auto pi = MathConstants<float>::pi;
    static constexpr auto arcStart = pi / 2.0f;

public:
    Arc() = default;

    Arc (Point<float> centreIn, float radiusIn, float thicknessIn, Colour colourIn)
        : centre (centreIn),
          initialRadius (radiusIn - thicknessIn / 2),
          initialThickness (thicknessIn),
          colour (colourIn)
    {
    }

    void paint (Graphics& g) const override
    {
        if (! active)
            return;

        const Graphics::ScopedSaveState s { g };

        Path p;
        p.addCentredArc (centre.getX(),
                         centre.getY(),
                         radius,
                         radius,
                         0.0f,
                         arcStart,
                         arcStart + sweepAngle,
                         true);

        g.setColour (colour);
        g.strokePath (p, { thickness, PathStrokeType::mitered });
    }

    void setActive (bool activeIn)
    {
        active = activeIn;
    }

    auto getFanoutAnimator() const { return fanoutAnimator; }

    auto getFillAnimator() const   { return fillAnimator; }

    Point<float> centre;
    float initialRadius = 0.0f, initialThickness = 0.0f;
    Colour colour = Colours::white;

private:
    bool active = false;
    float radius = 0.0f, thickness = 0.0f, sweepAngle = 0.0f;

    void reset()
    {
        sweepAngle = 0.0f;
        radius = initialRadius;
        thickness = initialThickness;
    }

    Animator fanoutAnimator = ValueAnimatorBuilder{}
                                  .withOnStartCallback ([this]
                                                        {
                                                            reset();
                                                            active = true;
                                                        })
                                  .withValueChangedCallback ([this] (auto value)
                                                              {
                                                                  sweepAngle = makeAnimationLimits (2.1f * MathConstants<float>::pi).lerp (value);
                                                              })
                                  .withEasing (Easings::createLinear())
                                  .build();

    Animator fillAnimator = ValueAnimatorBuilder{}
                                .withOnStartReturningValueChangedCallback (
                                    [this]
                                    {
                                        const auto thicknessChange = radius - 5.0f;
                                        const std::tuple begin { initialRadius, initialThickness };
                                        const std::tuple end { initialRadius - thicknessChange / 2.0f, initialThickness + thicknessChange };
                                        const auto limits = makeAnimationLimits (begin, end);

                                        return [this, limits] (auto value)
                                        {
                                            std::tie (radius, thickness) = limits.lerp (value);
                                        };
                                    })
                                .withEasing (Easings::createLinear())
                                .build();
};

class Circle : public Paintable
{
public:
    Circle (Point<float> centreIn, float radiusIn, Colour colourIn)
        : centre (centreIn), radius (radiusIn), colour (colourIn)
    {
    }

    void paint (Graphics& g) const override
    {
        if (! active)
            return;

        const Graphics::ScopedSaveState s { g };

        g.setColour (colour);
        g.fillEllipse (centre.getX() - radius, centre.getY() - radius, 2.0f * radius, 2.0f * radius);
    }

    void setActive (bool activeIn) { active = activeIn; }

private:
    Point<float> centre;
    float radius = 0.0f;
    Colour colour;
    bool active = false;
};

/* Can return a subpath based on a proportion between [0, 1.0]. Useful for creating an animation
   where a path is drawn over time.
*/
class PartialPath
{
public:
    explicit PartialPath (std::initializer_list<Point<float>> points)
    {
        bool pathIsEmpty = false;

        for (auto p : points)
        {
            if (std::exchange (pathIsEmpty, true) == false)
            {
                path.startNewSubPath (p);
                pts.push_back (std::make_pair (p, 0.0f));
            }
            else
            {
                path.lineTo (p);
                pts.push_back (std::make_pair (p, path.getLength()));
            }
        }
    }

    Path getPartialPath (float proportion) const
    {
        proportion = jmin (1.0f, proportion);

        Path partialPath;
        bool pathIsEmpty = false;

        if (pts.size() < 2)
            return partialPath;

        const auto proportionalLength = path.getLength() * proportion;

        const auto lineTo = [&partialPath, &pathIsEmpty] (Point<float> p)
        {
            if (std::exchange (pathIsEmpty, true) == false)
                partialPath.startNewSubPath (p);
            else
                partialPath.lineTo (p);
        };

        for (const auto& point : pts)
        {
            if (point.second > proportionalLength)
            {
                lineTo (path.getPointAlongPath (proportionalLength));
                break;
            }

            lineTo (point.first);
        }

        return partialPath;
    }

private:
    Path path;
    std::vector<std::pair<Point<float>, float>> pts;
};

class Checkmark : public Paintable
{
public:
    Checkmark (Rectangle<float> placementIn, float thicknessIn)
        : placement (placementIn),
          partialPath { { placement.getX(), placement.getY() + 0.7f * placement.getHeight() },
                        { placement.getX() + 0.4f * placement.getWidth(), placement.getBottom() },
                        { placement.getRight(), placement.getY() + 0.2f * placement.getHeight() } },
          thickness (thicknessIn)
    {
    }

    void paint (Graphics& g) const override
    {
        if (exactlyEqual (progress, 0.0f))
            return;

        const Graphics::ScopedSaveState s { g };

        g.setColour (colour);

        const auto p = partialPath.getPartialPath (progress);
        g.strokePath (p, PathStrokeType { thickness, PathStrokeType::JointStyle::curved, PathStrokeType::EndCapStyle::rounded });
    }

    void setProgress (float p) { progress = p; }

private:
    Rectangle<float> placement;
    PartialPath partialPath;
    float progress = 0.0f;
    float thickness = 10.0f;
    Colour colour { Colours::white };
};

} // namespace Shapes

inline auto createComponentMover (Component& component, Rectangle<int> targetBounds)
{
    const auto boundsToTuple = [] (auto b)
    {
        return std::make_tuple (b.getX(), b.getY(), b.getWidth(), b.getHeight());
    };

    const auto begin = boundsToTuple (component.getBoundsInParent());
    const auto end   = boundsToTuple (targetBounds);
    const auto limits = makeAnimationLimits (begin, end);

    return [&component, limits] (auto v)
    {
        const auto [x, y, w, h] = limits.lerp (v);
        component.setBounds (x, y, w, h);
    };
}

class AnimatedCheckmark : public Paintable
{
public:
    AnimatedCheckmark (Point<float> centre, float radius, float thickness, Colour colour)
        : arc (centre, radius, thickness, colour),
          circle (centre, radius, colour),
          checkmark (Rectangle<float> { centre.getX() - radius,
                                        centre.getY() - radius,
                                        2.0f * radius,
                                        2.0f * radius }.reduced (radius * 0.4f),
                     thickness)
    {
    }

    void paint (Graphics& g) const override
    {
        arc.paint (g);
        circle.paint (g);
        checkmark.paint (g);
    }

    auto getAnimator() const { return animator; }

private:
    Shapes::Arc arc;
    Shapes::Circle circle;
    Shapes::Checkmark checkmark;

    Animator animator = [&]
    {
        circle.setActive (false);

        const auto checkmarkAnimator = ValueAnimatorBuilder{}
                                           .withEasing (Easings::createEaseOutBack())
                                           .withDurationMs (450)
                                           .withValueChangedCallback ([this] (auto value)
                                                                      {
                                                                          checkmark.setProgress (value);
                                                                      })
                                           .build();

        return AnimatorSetBuilder (arc.getFanoutAnimator())
            .followedBy (arc.getFillAnimator())
            .followedBy ([this]
                         {
                             arc.setActive (false);
                             circle.setActive (true);
                         })
            .followedBy (checkmarkAnimator)
            .build();
    }();
};

class FallingBall : public Component
{
private:
    template <typename T>
    auto getDimensions (Rectangle<T> r)
    {
        return std::make_tuple (r.getX(), r.getY(), r.getWidth(), r.getHeight());
    }

public:
    void paint (Graphics& g) override
    {
        g.setColour (Colour { 0xff179af0 });
        const auto [x, y, width, height] = getDimensions (getLocalBounds().toFloat());
        g.fillEllipse (x, y, width, height);
    }

    Animator updateAndGetAnimator()
    {
        newBounds = getBoundsInParent().withY (getParentHeight() - getHeight());
        return fallAnimator;
    }

private:
    Rectangle<int> newBounds;

    Animator fallAnimator = ValueAnimatorBuilder{}
                                .withOnStartReturningValueChangedCallback ([this] { return createComponentMover (*this, newBounds); })
                                .withEasing (Easings::createBounce())
                                .withDurationMs (600)
                                .build();
};

class PulsingCheckmark : public Component
{
public:
    PulsingCheckmark (Point<float> centre, float radius)
        : checkmark ({ radius, radius }, radius, radius / 6.25f, Colour { 0xff1bc211 })
    {
        const auto widthAndHeight = 2 * (int) radius;
        const auto x = (int) (centre.getX() - radius);
        const auto y = (int) (centre.getY() - radius);

        setBounds (x, y, widthAndHeight, widthAndHeight);
    }

    //==============================================================================
    void paint (Graphics& g) override
    {
        checkmark.paint (g);
    }

    void mouseDown (const MouseEvent&) override
    {
        animator.complete();
    }

    Animator getAnimator() const { return animator; }

private:
    //==============================================================================
    AnimatedCheckmark checkmark;

    Animator animator = [&]
    {
        const auto checkmarkAnimator = checkmark.getAnimator();
        const auto checkmarkDuration = checkmarkAnimator.getDurationMs();

        const auto pulseAnimator = ValueAnimatorBuilder{}
                                       .withEasing (Easings::createOnOffRamp())
                                       .withOnStartReturningValueChangedCallback (
                                           [this]
                                           {
                                               const auto radius = (float) getWidth() / 2.0f;
                                               const auto centreInParent = getBoundsInParent().toFloat().getPosition()
                                                                           + Point<float> { radius, radius };

                                               return [this, centreInParent] (auto value)
                                               {
                                                   setTransform (AffineTransform::translation (-centreInParent)
                                                                     .followedBy (AffineTransform::scale (1.0f + 0.2f * value))
                                                                     .followedBy (AffineTransform::translation (centreInParent)));
                                               };
                                           })
                                       .build();

        const auto timeBeforePulseAnimation = checkmarkDuration - pulseAnimator.getDurationMs();

        const auto repaintAnimator = ValueAnimatorBuilder{}
                                         .withValueChangedCallback ([this] (auto) { repaint(); })
                                         .runningInfinitely()
                                         .build();

        return AnimatorSetBuilder (checkmarkAnimator)
            .togetherWith (repaintAnimator)
            .togetherWith (timeBeforePulseAnimation)
            .followedBy (pulseAnimator)
            .followedBy ([repaintAnimator] { repaintAnimator.complete(); })
            .build();
    }();
};

// Displays the PulsingCheckmark as it looks when its animation is complete
class CompletedCheckmark : public Component
{
public:
    explicit CompletedCheckmark (std::function<void()> onClickIn)
        : onClick (std::move (onClickIn)) {}

    void resized() override
    {
        const auto getCentre  = [this]
        {
            return Point<float> { (float) getWidth() / 2, (float) getHeight() / 2 };
        };

        const auto radius = (float) std::min (getWidth(), getHeight()) / 2.0f;
        checkmark = std::make_unique<PulsingCheckmark> (getCentre(), radius);
        checkmark->setInterceptsMouseClicks (false, false);
        addAndMakeVisible (*checkmark);
        checkmark->getAnimator().start();
        checkmark->getAnimator().complete();
        checkmark->getAnimator().update (0);
    }

    void mouseDown (const MouseEvent&) override
    {
        NullCheckedInvocation::invoke (onClick);
    }

private:
    std::unique_ptr<PulsingCheckmark> checkmark;
    std::function<void()> onClick;
};

class BallToolComponent : public Component
{
public:
    explicit BallToolComponent (std::function<void()> onClickIn)
        : onClick (std::move (onClickIn)) {}

    void paint (Graphics& g) override
    {
        g.setColour (Colour { 0xff179af0 });
        g.fillEllipse (getLocalBounds().toFloat());
    }

    void mouseDown (const MouseEvent&) override
    {
        NullCheckedInvocation::invoke (onClick);
    }

private:
    std::function<void()> onClick;
};

class AnimatorsDemo : public Component
{
public:
    //==============================================================================
    AnimatorsDemo()
    {
        welcomeComponent.setOnAnimatedClickEnd ([this]
                                                {
                                                    toolsPanel.open();
                                                });
        addAndMakeVisible (welcomeComponent);

        toolsPanel.onClose = [this] { welcomeComponent.reset(); };
        toolsPanel.addToolComponent (std::make_unique<CompletedCheckmark> ([this] { selectedTool = SelectedTool::checkmark; }));
        toolsPanel.addToolComponent (std::make_unique<BallToolComponent> ([this]
                                                                          {
                                                                              selectedTool = SelectedTool::ball;
                                                                          }));
        addAndMakeVisible (toolsPanel);

        setSize (600, 400);
    }

    //==============================================================================
    void paint (Graphics& g) override
    {
        g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId));

        for (const auto& paintable : objects)
            paintable.second->paint (g);
    }

    void resized() override
    {
        welcomeComponent.setBounds (getLocalBounds());
    }

    void mouseDown (const MouseEvent& event) override
    {
        switch (selectedTool)
        {
            case SelectedTool::checkmark:
                makeCheckmark (event.getPosition().toFloat());
                break;

            case SelectedTool::ball:
                makeBall (event.getPosition().toFloat());
                break;

            case SelectedTool::none:
                toolsPanel.wobbleLabel();
                break;
        }
    }

private:
    void makeCheckmark (Point<float> centre)
    {
        auto checkmark = std::make_unique<PulsingCheckmark> (centre, 50.0f);
        updater.addAnimator (checkmark->getAnimator(), [this] { toolComponent.reset(); });
        checkmark->getAnimator().start();
        addAndMakeVisible (*checkmark, 0);
        toolComponent = std::move (checkmark);
    }

    void makeBall (Point<float> centre)
    {
        auto ball = std::make_unique<FallingBall>();
        addAndMakeVisible (*ball, 0);
        const auto radius = 50.0f;
        const Rectangle<float> bounds { centre.getX() - radius, centre.getY() - radius, 2 * radius, 2 * radius };
        ball->setBounds (bounds.toNearestInt());
        auto animator = ball->updateAndGetAnimator();
        updater.addAnimator (animator, [this] { toolComponent.reset(); });
        animator.start();
        toolComponent = std::move (ball);
    }

    //==============================================================================
    VBlankAnimatorUpdater updater { this };

    struct WelcomeComponent : public Component
    {
        WelcomeComponent()
        {
            startButton.onClick = [this]
            {
                animateForward = true;
                buttonAnimator.start();
                updater.addAnimator (buttonAnimator, [this] { updater.removeAnimator (buttonAnimator); });
            };

            addAndMakeVisible (startButton);
        }

        void setOnAnimatedClickEnd (std::function<void()> onClickIn)
        {
            onClick = std::move (onClickIn);
        }

        void reset()
        {
            animateForward = false;
            buttonAnimator.start();
            updater.addAnimator (buttonAnimator, [this] { updater.removeAnimator (buttonAnimator); });
        }

        void resized() override
        {
            startButton.setBounds (getLocalBounds().withSizeKeepingCentre (140, 40));
        }

    private:
        TextButton startButton { "Start demo" };
        bool animateForward = false;
        Animator buttonAnimator = [&]
        {
            return ValueAnimatorBuilder{}
                .withOnStartCallback ([this] { setVisible (true); })
                .withValueChangedCallback ([this] (auto value)
                                           {
                                               const auto progress = animateForward ? value : (1.0 - value);
                                               setAlpha (1.0f - (float) progress);
                                           })
                .withOnCompleteCallback ([this]
                                         {
                                             setVisible (! animateForward);

                                             if (animateForward)
                                                NullCheckedInvocation::invoke (onClick);
                                         })
                .build();
        }();

        VBlankAnimatorUpdater updater { this };
        std::function<void()> onClick;
    };

    class WobblyLabel : public Component
    {
    public:
        explicit WobblyLabel (const String& text)
            : label ({}, text)
        {
            label.setJustificationType (Justification::right);
            addAndMakeVisible (label);
        }

        void resized() override
        {
            label.setBounds (getLocalBounds().withX ((int) offset));
        }

        void wobble()
        {
            updater.addAnimator (animator, [this] { updater.removeAnimator (animator); });
            animator.start();
        }

    private:
        float offset = 0.0f;
        Label label;
        Animator animator = ValueAnimatorBuilder{}.withValueChangedCallback (
                                                       [this] (float progress)
                                                       {
                                                           offset = 10.0f * std::sin (progress * 20.0f) * (1.0f - progress);
                                                           resized();
                                                       })
                                                  .withDurationMs (600)
                                                  .build();
        VBlankAnimatorUpdater updater { this };
    };

    struct ToolsPanel : public Component
    {
        static constexpr auto margin = 15;

        ToolsPanel()
        {
            shadower.setOwner (this);
            closeButton.onClick = [this] { close(); };
            addAndMakeVisible (closeButton);
            addAndMakeVisible (label);
            addAndMakeVisible (instructions);
            addChildComponent (selectionComponent, 0);

            instructions.setJustificationType (Justification::centred);
        }

        void paint (Graphics& g) override
        {
            g.fillAll (getLookAndFeel().findColour (juce::ResizableWindow::backgroundColourId).brighter (0.1f));
        }

        void resized() override
        {
            closeButton.setBounds (getLocalBounds().removeFromTop (40)
                                                   .removeFromRight (40)
                                                   .reduced (5));

            auto bounds = getLocalBounds();
            instructions.setBounds (bounds.removeFromBottom (30));

            FlexBox flexBox;
            flexBox.flexDirection = FlexBox::Direction::row;
            flexBox.flexWrap = FlexBox::Wrap::noWrap;
            flexBox.justifyContent = FlexBox::JustifyContent::center;
            flexBox.alignItems = FlexBox::AlignItems::center;

            const auto height = (float) (bounds.getHeight() - 2 * margin);

            flexBox.items.add (FlexItem (label).withWidth (200.0f).withHeight (height));

            for (auto& c : toolComponents)
                flexBox.items.add (FlexItem (*c).withWidth (height).withHeight (height).withMargin (margin));

            flexBox.performLayout (bounds);
        }

        //==============================================================================
        void open()
        {
            shouldOpen = true;
            updater.addAnimator (slideInAnimator, [this] { updater.removeAnimator (slideInAnimator); });
            slideInAnimator.start();
        }

        void close()
        {
            shouldOpen = false;
            updater.addAnimator (slideInAnimator, [this]
                                                  {
                                                      NullCheckedInvocation::invoke (onClose);
                                                      updater.removeAnimator (slideInAnimator);
                                                  });
            slideInAnimator.start();
        }

        void addToolComponent (std::unique_ptr<Component> component)
        {
            addAndMakeVisible (*component);
            component->addMouseListener (this, false);
            toolComponents.push_back (std::move (component));
        }

        //==============================================================================
        void mouseUp (const MouseEvent& event) override
        {
            if (event.originalComponent == this)
                return;

            const auto targetBounds = event.originalComponent->getBounds().expanded (std::min (10, margin));

            if (! selectionComponent.isVisible())
            {
                selectionComponent.setBounds (targetBounds);
                selectionComponent.appear (updater);
            }
            else
            {
                selectionComponent.moveTo (updater, targetBounds);
            }
        }

        void wobbleLabel()
        {
            label.wobble();
        }

    private:
        //==============================================================================
        class SelectionComponent : public Component
        {
        public:
            SelectionComponent()
            {
                setVisible (false);
            }

            void paint (Graphics& g) override
            {
                arc.paint (g);
            }

            void appear (VBlankAnimatorUpdater& animatorUpdater)
            {
                appearAnimator.start();
                animatorUpdater.addAnimator (appearAnimator,
                                             [this, &animatorUpdater]
                                             {
                                                 animatorUpdater.removeAnimator (appearAnimator);
                                             });
            }

            void moveTo (VBlankAnimatorUpdater& animatorUpdater, Rectangle<int> newBoundsIn)
            {
                newBounds = newBoundsIn;
                moveToNewBoundsAnimator.start();
                animatorUpdater.addAnimator (moveToNewBoundsAnimator,
                                             [this, &animatorUpdater]
                                             {
                                                 animatorUpdater.removeAnimator (moveToNewBoundsAnimator);
                                             });
            }

        private:
            Shapes::Arc arc;
            Rectangle<int> newBounds;

            Animator appearAnimator = [&]
            {
                const auto repaintAnimator =
                    ValueAnimatorBuilder{}
                        .withValueChangedCallback ([this] (auto) { repaint(); })
                        .runningInfinitely()
                        .build();

                return AnimatorSetBuilder { [this]
                                            {
                                                setVisible (true);
                                                arc.centre        = Point { getWidth(), getHeight() }.toFloat() / 2;
                                                arc.initialRadius = (float) (getWidth()) / 2 - 2.0f;
                                                arc.initialThickness = 4.0f;
                                            } }
                    .followedBy (repaintAnimator)
                    .togetherWith (arc.getFanoutAnimator())
                    .followedBy ([repaintAnimator] { repaintAnimator.complete(); })
                    .withTimeTransform ([] (auto v) { return 1.5 * v; })
                    .build();
            }();

            Animator moveToNewBoundsAnimator = ValueAnimatorBuilder{}
                                                   .withOnStartReturningValueChangedCallback ([this] { return createComponentMover (*this, newBounds); })
                                                   .withEasing (Easings::createSpring())
                                                   .withDurationMs (600)
                                                   .build();
        };

        WobblyLabel label { "Select animation:" };
        Label instructions { "", "Click below to animate" };
        SelectionComponent selectionComponent;
        std::vector<std::unique_ptr<Component>> toolComponents;
        DropShadow shadow { Colour { 0x90000000 }, 12, {} };
        DropShadower shadower { shadow };
        TextButton closeButton { "X" };

        Animator slideInAnimator = ValueAnimatorBuilder{}
                                       .withEasing (Easings::createEaseInOutCubic())
                                       .withOnStartReturningValueChangedCallback (
                                           [this]
                                           {
                                               const auto width = getParentWidth() - 2 * margin;
                                               const auto height = 130;
                                               setBounds (-width, margin, width, height);
                                               setVisible (true);

                                               const auto limits = makeAnimationLimits (-width, margin);

                                               return [this, limits] (auto value)
                                               {
                                                   const auto progress = std::clamp (shouldOpen ? value : 1.0 - value, 0.0, 1.0);
                                                   setTopLeftPosition (roundToInt (limits.lerp ((float) progress)), margin);
                                               };
                                           })
                                       .withDurationMs (500)
                                       .build();

        VBlankAnimatorUpdater updater { this };
        bool shouldOpen = true;

    public:
        std::function<void()> onClose;
    };

    enum class SelectedTool
    {
        none,
        checkmark,
        ball
    };

    WelcomeComponent welcomeComponent;
    ToolsPanel toolsPanel;
    SelectedTool selectedTool = SelectedTool::none;
    std::unique_ptr<Component> toolComponent;
    std::map<Paintable*, std::unique_ptr<Paintable>> objects;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AnimatorsDemo)
};