ImageConstructor.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  7. #include <LibWeb/Bindings/HTMLImageElementPrototype.h>
  8. #include <LibWeb/Bindings/ImageConstructor.h>
  9. #include <LibWeb/DOM/ElementFactory.h>
  10. #include <LibWeb/HTML/Scripting/Environments.h>
  11. #include <LibWeb/HTML/Window.h>
  12. #include <LibWeb/Namespace.h>
  13. namespace Web::Bindings {
  14. ImageConstructor::ImageConstructor(JS::Realm& realm)
  15. : NativeFunction(realm.intrinsics().function_prototype())
  16. {
  17. }
  18. void ImageConstructor::initialize(JS::Realm& realm)
  19. {
  20. auto& vm = this->vm();
  21. Base::initialize(realm);
  22. define_direct_property(vm.names.prototype, &ensure_web_prototype<Bindings::HTMLImageElementPrototype>(realm, "HTMLImageElement"_fly_string), 0);
  23. define_direct_property(vm.names.length, JS::Value(0), JS::Attribute::Configurable);
  24. }
  25. JS::ThrowCompletionOr<JS::Value> ImageConstructor::call()
  26. {
  27. return vm().throw_completion<JS::TypeError>(JS::ErrorType::ConstructorWithoutNew, "Image");
  28. }
  29. // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-image
  30. JS::ThrowCompletionOr<JS::NonnullGCPtr<JS::Object>> ImageConstructor::construct(FunctionObject&)
  31. {
  32. auto& vm = this->vm();
  33. // 1. Let document be the current global object's associated Document.
  34. auto& window = verify_cast<HTML::Window>(HTML::current_global_object());
  35. auto& document = window.associated_document();
  36. // 2. Let img be the result of creating an element given document, img, and the HTML namespace.
  37. auto image_element = TRY(Bindings::throw_dom_exception_if_needed(vm, [&]() { return DOM::create_element(document, HTML::TagNames::img, Namespace::HTML); }));
  38. // 3. If width is given, then set an attribute value for img using "width" and width.
  39. if (vm.argument_count() > 0) {
  40. u32 width = TRY(vm.argument(0).to_u32(vm));
  41. MUST(image_element->set_attribute(HTML::AttributeNames::width, MUST(String::formatted("{}", width))));
  42. }
  43. // 4. If height is given, then set an attribute value for img using "height" and height.
  44. if (vm.argument_count() > 1) {
  45. u32 height = TRY(vm.argument(1).to_u32(vm));
  46. MUST(image_element->set_attribute(HTML::AttributeNames::height, MUST(String::formatted("{}", height))));
  47. }
  48. // 5. Return img.
  49. return image_element;
  50. }
  51. }