Coverage Report

Created: 2026-05-16 07:03

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