Coverage Report

Created: 2025-03-04 07:22

/src/serenity/Userland/Libraries/LibWeb/HTML/Focus.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
3
 * Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
4
 * Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
5
 *
6
 * SPDX-License-Identifier: BSD-2-Clause
7
 */
8
9
#include <AK/TypeCasts.h>
10
#include <AK/Vector.h>
11
#include <LibJS/Heap/Handle.h>
12
#include <LibWeb/DOM/Document.h>
13
#include <LibWeb/DOM/Element.h>
14
#include <LibWeb/DOM/ShadowRoot.h>
15
#include <LibWeb/HTML/Focus.h>
16
#include <LibWeb/HTML/HTMLInputElement.h>
17
#include <LibWeb/HTML/TraversableNavigable.h>
18
#include <LibWeb/UIEvents/FocusEvent.h>
19
20
namespace Web::HTML {
21
22
// https://html.spec.whatwg.org/multipage/interaction.html#fire-a-focus-event
23
static void fire_a_focus_event(JS::GCPtr<DOM::EventTarget> focus_event_target, JS::GCPtr<DOM::EventTarget> related_focus_target, FlyString const& event_name, bool bubbles)
24
0
{
25
    // To fire a focus event named e at an element t with a given related target r, fire an event named e at t, using FocusEvent,
26
    // with the relatedTarget attribute initialized to r, the view attribute initialized to t's node document's relevant global
27
    // object, and the composed flag set.
28
0
    UIEvents::FocusEventInit focus_event_init {};
29
0
    focus_event_init.related_target = related_focus_target;
30
0
    focus_event_init.view = verify_cast<HTML::Window>(focus_event_target->realm().global_object());
31
32
0
    auto focus_event = UIEvents::FocusEvent::create(focus_event_target->realm(), event_name, focus_event_init);
33
    // AD-HOC: support bubbling focus events, used for focusin & focusout.
34
    //         See: https://github.com/whatwg/html/issues/3514
35
0
    focus_event->set_bubbles(bubbles);
36
0
    focus_event->set_composed(true);
37
0
    focus_event_target->dispatch_event(focus_event);
38
0
}
39
40
// https://html.spec.whatwg.org/multipage/interaction.html#focus-update-steps
41
static void run_focus_update_steps(Vector<JS::Handle<DOM::Node>> old_chain, Vector<JS::Handle<DOM::Node>> new_chain, DOM::Node* new_focus_target)
42
0
{
43
    // 1. If the last entry in old chain and the last entry in new chain are the same,
44
    //    pop the last entry from old chain and the last entry from new chain and redo this step.
45
0
    while (!old_chain.is_empty()
46
0
        && !new_chain.is_empty()
47
0
        && &old_chain.last() == &new_chain.last()) {
48
0
        (void)old_chain.take_last();
49
0
        (void)new_chain.take_last();
50
0
    }
51
52
    // 2. For each entry entry in old chain, in order, run these substeps:
53
0
    for (auto& entry : old_chain) {
54
        // 1. If entry is an input element, and the change event applies to the element, and the element does not have
55
        //    a defined activation behavior, and the user has changed the element's value or its list of selected files
56
        //    while the control was focused without committing that change (such that it is different to what it was
57
        //    when the control was first focused), then fire an event named change at the element, with the bubbles
58
        //    attribute initialized to true.
59
0
        if (is<HTMLInputElement>(*entry)) {
60
0
            auto& input_element = static_cast<HTMLInputElement&>(*entry);
61
62
            // FIXME: Spec issue: It doesn't make sense to check if the element has a defined activation behavior, as
63
            //        that is always true. Instead, we check if it has an *input* activation behavior.
64
            //        https://github.com/whatwg/html/issues/9973
65
0
            if (input_element.change_event_applies() && !input_element.has_input_activation_behavior()) {
66
0
                input_element.commit_pending_changes();
67
0
            }
68
0
        }
69
70
0
        JS::GCPtr<DOM::EventTarget> blur_event_target;
71
0
        if (is<DOM::Element>(*entry)) {
72
            // 2. If entry is an element, let blur event target be entry.
73
0
            blur_event_target = entry.ptr();
74
0
        } else if (is<DOM::Document>(*entry)) {
75
            // If entry is a Document object, let blur event target be that Document object's relevant global object.
76
0
            blur_event_target = static_cast<DOM::Document&>(*entry).window();
77
0
        }
78
79
        // 3. If entry is the last entry in old chain, and entry is an Element,
80
        //    and the last entry in new chain is also an Element,
81
        //    then let related blur target be the last entry in new chain.
82
        //    Otherwise, let related blur target be null.
83
0
        JS::GCPtr<DOM::EventTarget> related_blur_target;
84
0
        if (!old_chain.is_empty()
85
0
            && &entry == &old_chain.last()
86
0
            && is<DOM::Element>(*entry)
87
0
            && !new_chain.is_empty()
88
0
            && is<DOM::Element>(*new_chain.last())) {
89
0
            related_blur_target = new_chain.last().ptr();
90
0
        }
91
92
        // 4. If blur event target is not null, fire a focus event named blur at blur event target,
93
        //    with related blur target as the related target.
94
0
        if (blur_event_target) {
95
0
            fire_a_focus_event(blur_event_target, related_blur_target, HTML::EventNames::blur, false);
96
97
            // AD-HOC: dispatch focusout
98
0
            fire_a_focus_event(blur_event_target, related_blur_target, HTML::EventNames::focusout, true);
99
0
        }
100
0
    }
101
102
    // FIXME: 3. Apply any relevant platform-specific conventions for focusing new focus target.
103
    //           (For example, some platforms select the contents of a text control when that control is focused.)
104
0
    (void)new_focus_target;
105
106
    // 4. For each entry entry in new chain, in reverse order, run these substeps:
107
0
    for (auto& entry : new_chain.in_reverse()) {
108
        // 1. If entry is a focusable area: designate entry as the focused area of the document.
109
        // FIXME: This isn't entirely right.
110
0
        if (is<DOM::Element>(*entry))
111
0
            entry->document().set_focused_element(&static_cast<DOM::Element&>(*entry));
112
0
        else if (is<DOM::Document>(*entry))
113
0
            entry->document().set_focused_element(static_cast<DOM::Document&>(*entry).document_element());
114
115
0
        JS::GCPtr<DOM::EventTarget> focus_event_target;
116
0
        if (is<DOM::Element>(*entry)) {
117
            // 2. If entry is an element, let focus event target be entry.
118
0
            focus_event_target = entry.ptr();
119
0
        } else if (is<DOM::Document>(*entry)) {
120
            // If entry is a Document object, let focus event target be that Document object's relevant global object.
121
0
            focus_event_target = static_cast<DOM::Document&>(*entry).window();
122
0
        }
123
124
        // 3. If entry is the last entry in new chain, and entry is an Element,
125
        //    and the last entry in old chain is also an Element,
126
        //    then let related focus target be the last entry in old chain.
127
        //    Otherwise, let related focus target be null.
128
0
        JS::GCPtr<DOM::EventTarget> related_focus_target;
129
0
        if (!new_chain.is_empty()
130
0
            && &entry == &new_chain.last()
131
0
            && is<DOM::Element>(*entry)
132
0
            && !old_chain.is_empty()
133
0
            && is<DOM::Element>(*old_chain.last())) {
134
0
            related_focus_target = old_chain.last().ptr();
135
0
        }
136
137
        // 4. If focus event target is not null, fire a focus event named focus at focus event target,
138
        //    with related focus target as the related target.
139
0
        if (focus_event_target) {
140
0
            fire_a_focus_event(focus_event_target, related_focus_target, HTML::EventNames::focus, false);
141
142
            // AD-HOC: dispatch focusin
143
0
            fire_a_focus_event(focus_event_target, related_focus_target, HTML::EventNames::focusin, true);
144
0
        }
145
0
    }
146
0
}
147
148
// https://html.spec.whatwg.org/multipage/interaction.html#focus-chain
149
static Vector<JS::Handle<DOM::Node>> focus_chain(DOM::Node* subject)
150
0
{
151
    // FIXME: Move this somewhere more spec-friendly.
152
0
    if (!subject)
153
0
        return {};
154
155
    // 1. Let output be an empty list.
156
0
    Vector<JS::Handle<DOM::Node>> output;
157
158
    // 2. Let currentObject be subject.
159
0
    auto* current_object = subject;
160
161
    // 3. While true:
162
0
    while (true) {
163
        // 1. Append currentObject to output.
164
0
        output.append(JS::make_handle(*current_object));
165
166
        // FIXME: 2. If currentObject is an area element's shape, then append that area element to output.
167
168
        // FIXME:    Otherwise, if currentObject's DOM anchor is an element that is not currentObject itself, then append currentObject's DOM anchor to output.
169
170
        // FIXME: Everything below needs work. The conditions are not entirely right.
171
0
        if (!is<DOM::Document>(*current_object)) {
172
            // 3. If currentObject is a focusable area, then set currentObject to currentObject's DOM anchor's node document.
173
0
            current_object = &current_object->document();
174
0
        } else if (is<DOM::Document>(*current_object)
175
0
            && current_object->navigable()
176
0
            && current_object->navigable()->parent()) {
177
            // Otherwise, if currentObject is a Document whose node navigable's parent is non-null, then set currentObject to currentObject's node navigable's parent.
178
0
            current_object = current_object->navigable()->container();
179
0
        } else {
180
            // Otherwise, break.
181
0
            break;
182
0
        }
183
0
    }
184
185
    // 4. Return output.
186
0
    return output;
187
0
}
188
189
// https://html.spec.whatwg.org/multipage/interaction.html#focusing-steps
190
// FIXME: This should accept more types.
191
void run_focusing_steps(DOM::Node* new_focus_target, DOM::Node* fallback_target, [[maybe_unused]] Optional<ByteString> focus_trigger)
192
0
{
193
    // FIXME: 1. If new focus target is not a focusable area, then set new focus target
194
    //           to the result of getting the focusable area for new focus target,
195
    //           given focus trigger if it was passed.
196
197
    // 2. If new focus target is null, then:
198
0
    if (!new_focus_target) {
199
        // 1. If no fallback target was specified, then return.
200
0
        if (!fallback_target)
201
0
            return;
202
203
        // 2. Otherwise, set new focus target to the fallback target.
204
0
        new_focus_target = fallback_target;
205
0
    }
206
207
    // 3. If new focus target is a navigable container with non-null nested browsing context,
208
    //    then set new focus target to the nested browsing context's active document.
209
0
    if (is<HTML::NavigableContainer>(*new_focus_target)) {
210
0
        auto& navigable_container = static_cast<HTML::NavigableContainer&>(*new_focus_target);
211
0
        if (auto* nested_browsing_context = navigable_container.nested_browsing_context())
212
0
            new_focus_target = nested_browsing_context->active_document();
213
0
    }
214
215
    // FIXME: 4. If new focus target is a focusable area and its DOM anchor is inert, then return.
216
217
    // 5. If new focus target is the currently focused area of a top-level browsing context, then return.
218
0
    if (!new_focus_target->document().browsing_context())
219
0
        return;
220
0
    auto top_level_traversable = new_focus_target->document().browsing_context()->top_level_traversable();
221
0
    if (new_focus_target == top_level_traversable->currently_focused_area().ptr())
222
0
        return;
223
224
    // 6. Let old chain be the current focus chain of the top-level browsing context in which
225
    //    new focus target finds itself.
226
0
    auto old_chain = focus_chain(top_level_traversable->currently_focused_area());
227
228
    // 7. Let new chain be the focus chain of new focus target.
229
0
    auto new_chain = focus_chain(new_focus_target);
230
231
    // 8. Run the focus update steps with old chain, new chain, and new focus target respectively.
232
0
    run_focus_update_steps(old_chain, new_chain, new_focus_target);
233
0
}
234
235
// https://html.spec.whatwg.org/multipage/interaction.html#unfocusing-steps
236
void run_unfocusing_steps(DOM::Node* old_focus_target)
237
0
{
238
    // NOTE: The unfocusing steps do not always result in the focus changing, even when applied to the currently focused
239
    // area of a top-level browsing context. For example, if the currently focused area of a top-level browsing context
240
    // is a viewport, then it will usually keep its focus regardless until another focusable area is explicitly focused
241
    // with the focusing steps.
242
243
0
    auto is_shadow_host = [](DOM::Node* node) {
244
0
        return is<DOM::Element>(node) && static_cast<DOM::Element*>(node)->is_shadow_host();
245
0
    };
246
247
    // 1. If old focus target is a shadow host whose shadow root's delegates focus is true, and old focus target's
248
    //    shadow root is a shadow-including inclusive ancestor of the currently focused area of a top-level browsing
249
    //    context's DOM anchor, then set old focus target to that currently focused area of a top-level browsing
250
    //    context.
251
0
    if (is_shadow_host(old_focus_target)) {
252
0
        auto shadow_root = static_cast<DOM::Element*>(old_focus_target)->shadow_root();
253
0
        if (shadow_root->delegates_focus()) {
254
0
            auto top_level_traversable = old_focus_target->document().browsing_context()->top_level_traversable();
255
0
            if (auto currently_focused_area = top_level_traversable->currently_focused_area()) {
256
0
                if (shadow_root->is_shadow_including_ancestor_of(*currently_focused_area)) {
257
0
                    old_focus_target = currently_focused_area;
258
0
                }
259
0
            }
260
0
        }
261
0
    }
262
263
    // FIXME: 2. If old focus target is inert, then return.
264
265
    // FIXME: 3. If old focus target is an area element and one of its shapes is the currently focused area of a
266
    //    top-level browsing context, or, if old focus target is an element with one or more scrollable regions, and one
267
    //    of them is the currently focused area of a top-level browsing context, then let old focus target be that
268
    //    currently focused area of a top-level browsing context.
269
270
    // NOTE: HTMLAreaElement is currently missing the shapes property
271
272
0
    auto top_level_traversable = old_focus_target->document().browsing_context()->top_level_traversable();
273
274
    // 4. Let old chain be the current focus chain of the top-level browsing context in which old focus target finds itself.
275
0
    auto old_chain = focus_chain(top_level_traversable->currently_focused_area());
276
277
    // 5. If old focus target is not one of the entries in old chain, then return.
278
0
    auto it = old_chain.find_if([&](auto const& node) { return old_focus_target == node; });
279
0
    if (it == old_chain.end())
280
0
        return;
281
282
    // 6. If old focus target is not a focusable area, then return.
283
0
    if (!old_focus_target->is_focusable())
284
0
        return;
285
286
    // 7. Let topDocument be old chain's last entry.
287
0
    auto* top_document = verify_cast<DOM::Document>(old_chain.last().ptr());
288
289
    // 8. If topDocument's node navigable has system focus, then run the focusing steps for topDocument's viewport.
290
0
    if (top_document->navigable()->traversable_navigable()->system_visibility_state() == HTML::VisibilityState::Visible) {
291
0
        run_focusing_steps(top_document);
292
0
    } else {
293
        // FIXME: Otherwise, apply any relevant platform-specific conventions for removing system focus from
294
        // topDocument's browsing context, and run the focus update steps with old chain, an empty list, and null
295
        // respectively.
296
297
        // What? It already doesn't have system focus, what possible platform-specific conventions are there?
298
299
0
        run_focus_update_steps(old_chain, {}, nullptr);
300
0
    }
301
302
    // FIXME: When the currently focused area of a top-level browsing context is somehow unfocused without another
303
    // element being explicitly focused in its stead, the user agent must immediately run the unfocusing steps for that
304
    // object.
305
306
    // What? How are we supposed to detect when something is "somehow unfocused without another element being explicitly focused"?
307
0
}
308
309
}