ImageConstructor.cpp 2.2 KB

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