AbortSignal.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/DOM/AbortSignal.h>
  7. #include <LibWeb/DOM/Document.h>
  8. #include <LibWeb/DOM/EventDispatcher.h>
  9. #include <LibWeb/HTML/EventHandler.h>
  10. namespace Web::DOM {
  11. JS::NonnullGCPtr<AbortSignal> AbortSignal::create_with_global_object(HTML::Window& window)
  12. {
  13. return *window.heap().allocate<AbortSignal>(window.realm(), window);
  14. }
  15. AbortSignal::AbortSignal(HTML::Window& window)
  16. : EventTarget(window.realm())
  17. {
  18. set_prototype(&window.cached_web_prototype("AbortSignal"));
  19. }
  20. // https://dom.spec.whatwg.org/#abortsignal-add
  21. void AbortSignal::add_abort_algorithm(Function<void()> abort_algorithm)
  22. {
  23. // 1. If signal is aborted, then return.
  24. if (aborted())
  25. return;
  26. // 2. Append algorithm to signal’s abort algorithms.
  27. m_abort_algorithms.append(move(abort_algorithm));
  28. }
  29. // https://dom.spec.whatwg.org/#abortsignal-signal-abort
  30. void AbortSignal::signal_abort(JS::Value reason)
  31. {
  32. // 1. If signal is aborted, then return.
  33. if (aborted())
  34. return;
  35. // 2. Set signal’s abort reason to reason if it is given; otherwise to a new "AbortError" DOMException.
  36. if (!reason.is_undefined())
  37. m_abort_reason = reason;
  38. else
  39. m_abort_reason = AbortError::create(global_object(), "Aborted without reason").ptr();
  40. // 3. For each algorithm in signal’s abort algorithms: run algorithm.
  41. for (auto& algorithm : m_abort_algorithms)
  42. algorithm();
  43. // 4. Empty signal’s abort algorithms.
  44. m_abort_algorithms.clear();
  45. // 5. Fire an event named abort at signal.
  46. dispatch_event(*Event::create(global_object(), HTML::EventNames::abort));
  47. }
  48. void AbortSignal::set_onabort(Bindings::CallbackType* event_handler)
  49. {
  50. set_event_handler_attribute(HTML::EventNames::abort, event_handler);
  51. }
  52. Bindings::CallbackType* AbortSignal::onabort()
  53. {
  54. return event_handler_attribute(HTML::EventNames::abort);
  55. }
  56. // https://dom.spec.whatwg.org/#dom-abortsignal-throwifaborted
  57. JS::ThrowCompletionOr<void> AbortSignal::throw_if_aborted() const
  58. {
  59. // The throwIfAborted() method steps are to throw this’s abort reason, if this is aborted.
  60. if (!aborted())
  61. return {};
  62. return JS::throw_completion(m_abort_reason);
  63. }
  64. void AbortSignal::visit_edges(JS::Cell::Visitor& visitor)
  65. {
  66. Base::visit_edges(visitor);
  67. visitor.visit(m_abort_reason);
  68. }
  69. }