AnimationFrameCallbackDriver.h 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * Copyright (c) 2022, the SerenityOS developers.
  3. * Copyright (c) 2024, Andreas Kling <andreas@ladybird.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/Function.h>
  9. #include <AK/HashMap.h>
  10. #include <LibCore/Timer.h>
  11. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  12. #include <LibWeb/WebIDL/Types.h>
  13. namespace Web::HTML {
  14. struct AnimationFrameCallbackDriver {
  15. using Callback = Function<void(double)>;
  16. [[nodiscard]] WebIDL::UnsignedLong add(Callback handler)
  17. {
  18. auto id = ++m_animation_frame_callback_identifier;
  19. m_callbacks.set(id, move(handler));
  20. return id;
  21. }
  22. bool remove(WebIDL::UnsignedLong id)
  23. {
  24. auto it = m_callbacks.find(id);
  25. if (it == m_callbacks.end())
  26. return false;
  27. m_callbacks.remove(it);
  28. return true;
  29. }
  30. void run(double now)
  31. {
  32. auto taken_callbacks = move(m_callbacks);
  33. for (auto& [id, callback] : taken_callbacks)
  34. callback(now);
  35. }
  36. bool has_callbacks() const
  37. {
  38. return !m_callbacks.is_empty();
  39. }
  40. private:
  41. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#animation-frame-callback-identifier
  42. WebIDL::UnsignedLong m_animation_frame_callback_identifier { 0 };
  43. OrderedHashMap<WebIDL::UnsignedLong, Callback> m_callbacks;
  44. };
  45. }