ExtendableEvent.cpp [plain text]
#include "config.h"
#include "ExtendableEvent.h"
#if ENABLE(SERVICE_WORKER)
#include "JSDOMPromise.h"
#include <JavaScriptCore/Microtask.h>
namespace WebCore {
ExtendableEvent::ExtendableEvent(const AtomicString& type, const ExtendableEventInit& initializer, IsTrusted isTrusted)
: Event(type, initializer, isTrusted)
{
}
ExtendableEvent::ExtendableEvent(const AtomicString& type, bool bubbles, bool cancelable)
: Event(type, bubbles, cancelable)
{
}
ExtendableEvent::~ExtendableEvent()
{
}
ExceptionOr<void> ExtendableEvent::waitUntil(Ref<DOMPromise>&& promise)
{
if (!isTrusted())
return Exception { InvalidStateError, "Event is not trusted"_s };
if (!m_pendingPromiseCount && !isBeingDispatched())
return Exception { InvalidStateError, "Event is no longer being dispatched and has no pending promises"_s };
addExtendLifetimePromise(WTFMove(promise));
return { };
}
class FunctionMicrotask final : public JSC::Microtask {
public:
static Ref<FunctionMicrotask> create(Function<void()>&& function)
{
return adoptRef(*new FunctionMicrotask(WTFMove(function)));
}
private:
explicit FunctionMicrotask(Function<void()>&& function)
: m_function(WTFMove(function))
{
}
void run(JSC::ExecState*) final
{
m_function();
}
Function<void()> m_function;
};
void ExtendableEvent::addExtendLifetimePromise(Ref<DOMPromise>&& promise)
{
promise->whenSettled([this, protectedThis = makeRefPtr(this), settledPromise = promise.ptr()] () mutable {
settledPromise->globalObject()->queueMicrotask(FunctionMicrotask::create([this, protectedThis = WTFMove(protectedThis)] {
--m_pendingPromiseCount;
if (m_pendingPromiseCount)
return;
auto settledPromises = WTFMove(m_extendLifetimePromises);
if (auto handler = WTFMove(m_whenAllExtendLifetimePromisesAreSettledHandler))
handler(WTFMove(settledPromises));
}));
});
m_extendLifetimePromises.add(WTFMove(promise));
++m_pendingPromiseCount;
}
void ExtendableEvent::whenAllExtendLifetimePromisesAreSettled(WTF::Function<void(HashSet<Ref<DOMPromise>>&&)>&& handler)
{
ASSERT_WITH_MESSAGE(target(), "Event has not been dispatched yet");
ASSERT(!m_whenAllExtendLifetimePromisesAreSettledHandler);
if (!m_pendingPromiseCount) {
handler(WTFMove(m_extendLifetimePromises));
return;
}
m_whenAllExtendLifetimePromisesAreSettledHandler = WTFMove(handler);
}
}
#endif // ENABLE(SERVICE_WORKER)