FormDataIterator.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright (c) 2023, Kenneth Myhra <kennethmyhra@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/Array.h>
  7. #include <LibJS/Runtime/IteratorOperations.h>
  8. #include <LibWeb/Bindings/FormDataIteratorPrototype.h>
  9. #include <LibWeb/Bindings/Intrinsics.h>
  10. #include <LibWeb/XHR/FormDataIterator.h>
  11. namespace Web::Bindings {
  12. template<>
  13. void Intrinsics::create_web_prototype_and_constructor<FormDataIteratorPrototype>(JS::Realm& realm)
  14. {
  15. auto prototype = heap().allocate<FormDataIteratorPrototype>(realm, realm).release_allocated_value_but_fixme_should_propagate_errors();
  16. m_prototypes.set("FormDataIterator"sv, prototype);
  17. }
  18. }
  19. namespace Web::XHR {
  20. WebIDL::ExceptionOr<JS::NonnullGCPtr<FormDataIterator>> FormDataIterator::create(FormData const& form_data, JS::Object::PropertyKind iterator_kind)
  21. {
  22. return MUST_OR_THROW_OOM(form_data.heap().allocate<FormDataIterator>(form_data.realm(), form_data, iterator_kind));
  23. }
  24. FormDataIterator::FormDataIterator(Web::XHR::FormData const& form_data, JS::Object::PropertyKind iterator_kind)
  25. : PlatformObject(form_data.realm())
  26. , m_form_data(form_data)
  27. , m_iterator_kind(iterator_kind)
  28. {
  29. }
  30. FormDataIterator::~FormDataIterator() = default;
  31. JS::ThrowCompletionOr<void> FormDataIterator::initialize(JS::Realm& realm)
  32. {
  33. MUST_OR_THROW_OOM(Base::initialize(realm));
  34. set_prototype(&Bindings::ensure_web_prototype<Bindings::FormDataIteratorPrototype>(realm, "FormDataIterator"));
  35. return {};
  36. }
  37. void FormDataIterator::visit_edges(Cell::Visitor& visitor)
  38. {
  39. Base::visit_edges(visitor);
  40. visitor.visit(m_form_data);
  41. }
  42. JS::Object* FormDataIterator::next()
  43. {
  44. auto& vm = this->vm();
  45. if (m_index >= m_form_data->m_entry_list.size())
  46. return create_iterator_result_object(vm, JS::js_undefined(), true);
  47. auto entry = m_form_data->m_entry_list[m_index++];
  48. if (m_iterator_kind == JS::Object::PropertyKind::Key)
  49. return create_iterator_result_object(vm, JS::PrimitiveString::create(vm, entry.name), false);
  50. auto entry_value = entry.value.visit(
  51. [&](JS::Handle<FileAPI::File> const& file) -> JS::Value {
  52. return file.cell();
  53. },
  54. [&](String const& string) -> JS::Value {
  55. return JS::PrimitiveString::create(vm, string);
  56. });
  57. if (m_iterator_kind == JS::Object::PropertyKind::Value)
  58. return create_iterator_result_object(vm, entry_value, false);
  59. return create_iterator_result_object(vm, JS::Array::create_from(realm(), { JS::PrimitiveString::create(vm, entry.name), entry_value }), false).ptr();
  60. }
  61. }