/
select_type.cc
1458 lines (1272 loc) · 51.3 KB
/
select_type.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* Copyright (C) 2004, 2005, 2006, 2007, 2009, 2010, 2011 Apple Inc. All rights
* reserved.
* (C) 2006 Alexey Proskuryakov (ap@nypop.com)
* Copyright (C) 2010 Google Inc. All rights reserved.
* Copyright (C) 2009 Torch Mobile Inc. All rights reserved.
* (http://www.torchmobile.com/)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "third_party/blink/renderer/core/html/forms/select_type.h"
#include "build/build_config.h"
#include "third_party/blink/public/mojom/scroll/scroll_into_view_params.mojom-blink.h"
#include "third_party/blink/public/strings/grit/blink_strings.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_mutation_observer_init.h"
#include "third_party/blink/renderer/core/accessibility/ax_object_cache.h"
#include "third_party/blink/renderer/core/dom/focus_params.h"
#include "third_party/blink/renderer/core/dom/mutation_observer.h"
#include "third_party/blink/renderer/core/dom/mutation_record.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/events/gesture_event.h"
#include "third_party/blink/renderer/core/events/keyboard_event.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/html/forms/html_form_element.h"
#include "third_party/blink/renderer/core/html/forms/html_select_element.h"
#include "third_party/blink/renderer/core/html/forms/menu_list_inner_element.h"
#include "third_party/blink/renderer/core/html/forms/popup_menu.h"
#include "third_party/blink/renderer/core/input/event_handler.h"
#include "third_party/blink/renderer/core/input/input_device_capabilities.h"
#include "third_party/blink/renderer/core/layout/layout_box.h"
#include "third_party/blink/renderer/core/page/autoscroll_controller.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/spatial_navigation.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_scrollable_area.h"
#include "third_party/blink/renderer/core/scroll/scroll_alignment.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "ui/base/ui_base_features.h"
namespace blink {
class PopupUpdater;
namespace {
HTMLOptionElement* EventTargetOption(const Event& event) {
return DynamicTo<HTMLOptionElement>(event.target()->ToNode());
}
} // anonymous namespace
class MenuListSelectType final : public SelectType {
public:
explicit MenuListSelectType(HTMLSelectElement& select) : SelectType(select) {}
void Trace(Visitor* visitor) const override;
bool DefaultEventHandler(const Event& event) override;
void DidSelectOption(HTMLOptionElement* element,
HTMLSelectElement::SelectOptionFlags flags,
bool should_update_popup) override;
void DidBlur() override;
void DidDetachLayoutTree() override;
void DidRecalcStyle(const StyleRecalcChange change) override;
void DidSetSuggestedOption(HTMLOptionElement* option) override;
void SaveLastSelection() override;
void UpdateTextStyle() override { UpdateTextStyleInternal(); }
void UpdateTextStyleAndContent() override;
HTMLOptionElement* OptionToBeShown() const override;
const ComputedStyle* OptionStyle() const override {
return option_style_.get();
}
void MaximumOptionWidthMightBeChanged() const override;
void CreateShadowSubtree(ShadowRoot& root) override;
Element& InnerElement() const override;
void ShowPopup(PopupMenu::ShowEventType type) override;
void HidePopup() override;
void PopupDidHide() override;
bool PopupIsVisible() const override;
PopupMenu* PopupForTesting() const override;
AXObject* PopupRootAXObject() const override;
void DidMutateSubtree();
private:
bool ShouldOpenPopupForKeyDownEvent(const KeyboardEvent& event);
bool ShouldOpenPopupForKeyPressEvent(const KeyboardEvent& event);
// Returns true if this function handled the event.
bool HandlePopupOpenKeyboardEvent();
void SetPopupIsVisible(bool popup_is_visible);
void DispatchEventsIfSelectedOptionChanged();
String UpdateTextStyleInternal();
void DidUpdateActiveOption(HTMLOptionElement* option);
void ObserveTreeMutation();
void UnobserveTreeMutation();
Member<PopupMenu> popup_;
Member<PopupUpdater> popup_updater_;
scoped_refptr<const ComputedStyle> option_style_;
int ax_menulist_last_active_index_ = -1;
bool has_updated_menulist_active_option_ = false;
bool popup_is_visible_ = false;
bool snav_arrow_key_selection_ = false;
};
void MenuListSelectType::Trace(Visitor* visitor) const {
visitor->Trace(popup_);
visitor->Trace(popup_updater_);
SelectType::Trace(visitor);
}
bool MenuListSelectType::DefaultEventHandler(const Event& event) {
// We need to make the layout tree up-to-date to have GetLayoutObject() give
// the correct result below. An author event handler may have set display to
// some element to none which will cause a layout tree detach.
select_->GetDocument().UpdateStyleAndLayoutTree();
const auto* key_event = DynamicTo<KeyboardEvent>(event);
if (event.type() == event_type_names::kKeydown) {
if (!select_->GetLayoutObject() || !key_event)
return false;
if (ShouldOpenPopupForKeyDownEvent(*key_event))
return HandlePopupOpenKeyboardEvent();
// When using spatial navigation, we want to be able to navigate away
// from the select element when the user hits any of the arrow keys,
// instead of changing the selection.
if (IsSpatialNavigationEnabled(select_->GetDocument().GetFrame())) {
if (!snav_arrow_key_selection_)
return false;
}
// The key handling below shouldn't be used for non spatial navigation
// mode Mac
if (LayoutTheme::GetTheme().PopsMenuByArrowKeys() &&
!IsSpatialNavigationEnabled(select_->GetDocument().GetFrame()))
return false;
int ignore_modifiers = WebInputEvent::kShiftKey |
WebInputEvent::kControlKey | WebInputEvent::kAltKey |
WebInputEvent::kMetaKey;
if (key_event->GetModifiers() & ignore_modifiers)
return false;
const String& key = key_event->key();
bool handled = true;
HTMLOptionElement* option = select_->SelectedOption();
int list_index = option ? option->ListIndex() : -1;
if (key == "ArrowDown" || key == "ArrowRight") {
option = NextValidOption(list_index, kSkipForwards, 1);
} else if (key == "ArrowUp" || key == "ArrowLeft") {
option = NextValidOption(list_index, kSkipBackwards, 1);
} else if (key == "PageDown") {
option = NextValidOption(list_index, kSkipForwards, 3);
} else if (key == "PageUp") {
option = NextValidOption(list_index, kSkipBackwards, 3);
} else if (key == "Home") {
option = FirstSelectableOption();
} else if (key == "End") {
option = LastSelectableOption();
} else {
handled = false;
}
if (handled && option) {
select_->SelectOption(
option, HTMLSelectElement::kDeselectOtherOptionsFlag |
HTMLSelectElement::kMakeOptionDirtyFlag |
HTMLSelectElement::kDispatchInputAndChangeEventFlag);
}
return handled;
}
if (event.type() == event_type_names::kKeypress) {
if (!select_->GetLayoutObject() || !key_event)
return false;
int key_code = key_event->keyCode();
if (key_code == ' ' &&
IsSpatialNavigationEnabled(select_->GetDocument().GetFrame())) {
// Use space to toggle arrow key handling for selection change or
// spatial navigation.
snav_arrow_key_selection_ = !snav_arrow_key_selection_;
return true;
}
if (ShouldOpenPopupForKeyPressEvent(*key_event))
return HandlePopupOpenKeyboardEvent();
if (!LayoutTheme::GetTheme().PopsMenuByReturnKey() && key_code == '\r') {
if (HTMLFormElement* form = select_->Form())
form->SubmitImplicitly(event, false);
DispatchEventsIfSelectedOptionChanged();
return true;
}
return false;
}
const auto* mouse_event = DynamicTo<MouseEvent>(event);
if (event.type() == event_type_names::kMousedown && mouse_event &&
mouse_event->button() ==
static_cast<int16_t>(WebPointerProperties::Button::kLeft)) {
InputDeviceCapabilities* source_capabilities =
select_->GetDocument()
.domWindow()
->GetInputDeviceCapabilities()
->FiresTouchEvents(mouse_event->FromTouch());
select_->Focus(FocusParams(SelectionBehaviorOnFocus::kRestore,
mojom::blink::FocusType::kMouse,
source_capabilities));
if (select_->GetLayoutObject() && !will_be_destroyed_ &&
!select_->IsDisabledFormControl()) {
if (PopupIsVisible()) {
HidePopup();
} else {
// Save the selection so it can be compared to the new selection
// when we call onChange during selectOption, which gets called
// from selectOptionByPopup, which gets called after the user
// makes a selection from the menu.
SaveLastSelection();
// TODO(lanwei): Will check if we need to add
// InputDeviceCapabilities here when select menu list gets
// focus, see https://crbug.com/476530.
ShowPopup(mouse_event->FromTouch() ? PopupMenu::kTouch
: PopupMenu::kOther);
}
}
return true;
}
return false;
}
bool MenuListSelectType::ShouldOpenPopupForKeyDownEvent(
const KeyboardEvent& event) {
const String& key = event.key();
LayoutTheme& layout_theme = LayoutTheme::GetTheme();
if (IsSpatialNavigationEnabled(select_->GetDocument().GetFrame()))
return false;
return ((layout_theme.PopsMenuByArrowKeys() &&
(key == "ArrowDown" || key == "ArrowUp")) ||
((key == "ArrowDown" || key == "ArrowUp") && event.altKey()) ||
((!event.altKey() && !event.ctrlKey() && key == "F4")));
}
bool MenuListSelectType::ShouldOpenPopupForKeyPressEvent(
const KeyboardEvent& event) {
LayoutTheme& layout_theme = LayoutTheme::GetTheme();
int key_code = event.keyCode();
return ((key_code == ' ' && !select_->type_ahead_.HasActiveSession(event)) ||
(layout_theme.PopsMenuByReturnKey() && key_code == '\r'));
}
bool MenuListSelectType::HandlePopupOpenKeyboardEvent() {
select_->Focus();
// Calling focus() may cause us to lose our LayoutObject. Return true so
// that our caller doesn't process the event further, but don't set
// the event as handled.
if (!select_->GetLayoutObject() || will_be_destroyed_ ||
select_->IsDisabledFormControl())
return false;
// Save the selection so it can be compared to the new selection when
// dispatching change events during SelectOption, which gets called from
// SelectOptionByPopup, which gets called after the user makes a selection
// from the menu.
SaveLastSelection();
ShowPopup(PopupMenu::kOther);
return true;
}
void MenuListSelectType::CreateShadowSubtree(ShadowRoot& root) {
Document& doc = select_->GetDocument();
Element* inner_element = MakeGarbageCollected<MenuListInnerElement>(doc);
inner_element->setAttribute(html_names::kAriaHiddenAttr, "true");
// Make sure InnerElement() always has a Text node.
inner_element->appendChild(Text::Create(doc, g_empty_string));
root.insertBefore(inner_element, root.firstChild());
}
Element& MenuListSelectType::InnerElement() const {
auto* inner_element =
DynamicTo<Element>(select_->UserAgentShadowRoot()->firstChild());
DCHECK(inner_element);
return *inner_element;
}
void MenuListSelectType::ShowPopup(PopupMenu::ShowEventType type) {
if (PopupIsVisible())
return;
Document& document = select_->GetDocument();
if (document.GetPage()->GetChromeClient().HasOpenedPopup())
return;
if (!select_->GetLayoutObject())
return;
gfx::Rect local_root_rect = select_->VisibleBoundsInLocalRoot();
if (document.GetFrame()->LocalFrameRoot().IsOutermostMainFrame()) {
gfx::Rect visual_viewport_rect =
document.GetPage()->GetVisualViewport().RootFrameToViewport(
local_root_rect);
visual_viewport_rect.Intersect(
gfx::Rect(document.GetPage()->GetVisualViewport().Size()));
if (visual_viewport_rect.IsEmpty())
return;
} else {
// TODO(bokan): If we're in a remote frame, we cannot access the active
// visual viewport. VisibleBoundsInLocalRoot will clip to the outermost
// main frame but if the user is pinch-zoomed this won't be accurate.
// https://crbug.com/840944.
if (local_root_rect.IsEmpty())
return;
}
if (!popup_) {
popup_ = document.GetPage()->GetChromeClient().OpenPopupMenu(
*document.GetFrame(), *select_);
}
if (!popup_)
return;
SetPopupIsVisible(true);
ObserveTreeMutation();
popup_->Show(type);
if (AXObjectCache* cache = document.ExistingAXObjectCache())
cache->DidShowMenuListPopup(select_->GetLayoutObject());
}
void MenuListSelectType::HidePopup() {
if (popup_)
popup_->Hide();
}
void MenuListSelectType::PopupDidHide() {
SetPopupIsVisible(false);
UnobserveTreeMutation();
if (AXObjectCache* cache = select_->GetDocument().ExistingAXObjectCache()) {
if (auto* layout_object = select_->GetLayoutObject())
cache->DidHideMenuListPopup(layout_object);
}
}
bool MenuListSelectType::PopupIsVisible() const {
return popup_is_visible_;
}
void MenuListSelectType::SetPopupIsVisible(bool popup_is_visible) {
popup_is_visible_ = popup_is_visible;
if (auto* layout_object = select_->GetLayoutObject()) {
// Invalidate paint to ensure that the focus ring is updated.
layout_object->SetShouldDoFullPaintInvalidation();
}
}
PopupMenu* MenuListSelectType::PopupForTesting() const {
return popup_.Get();
}
AXObject* MenuListSelectType::PopupRootAXObject() const {
return popup_ ? popup_->PopupRootAXObject() : nullptr;
}
void MenuListSelectType::DidSelectOption(
HTMLOptionElement* element,
HTMLSelectElement::SelectOptionFlags flags,
bool should_update_popup) {
// Need to update last_on_change_option_ before UpdateFromElement().
const bool should_dispatch_events =
(flags & HTMLSelectElement::kDispatchInputAndChangeEventFlag) &&
select_->last_on_change_option_ != element;
select_->last_on_change_option_ = element;
UpdateTextStyleAndContent();
// PopupMenu::UpdateFromElement() posts an O(N) task.
if (PopupIsVisible() && should_update_popup)
popup_->UpdateFromElement(PopupMenu::kBySelectionChange);
select_->SetNeedsValidityCheck();
if (should_dispatch_events) {
select_->DispatchInputEvent();
select_->DispatchChangeEvent();
}
if (select_->GetLayoutObject()) {
// Need to check will_be_destroyed_ because event handlers might
// disassociate |this| and select_.
if (!will_be_destroyed_) {
// DidUpdateActiveOption() is O(N) because of HTMLOptionElement::index().
DidUpdateActiveOption(element);
}
}
}
void MenuListSelectType::DispatchEventsIfSelectedOptionChanged() {
HTMLOptionElement* selected_option = select_->SelectedOption();
if (select_->last_on_change_option_.Get() != selected_option) {
select_->last_on_change_option_ = selected_option;
select_->DispatchInputEvent();
select_->DispatchChangeEvent();
}
}
void MenuListSelectType::DidBlur() {
// We only need to fire change events here for menu lists, because we fire
// change events for list boxes whenever the selection change is actually
// made. This matches other browsers' behavior.
DispatchEventsIfSelectedOptionChanged();
if (PopupIsVisible())
HidePopup();
}
void MenuListSelectType::DidSetSuggestedOption(HTMLOptionElement*) {
UpdateTextStyleAndContent();
if (PopupIsVisible())
popup_->UpdateFromElement(PopupMenu::kBySelectionChange);
}
void MenuListSelectType::SaveLastSelection() {
select_->last_on_change_option_ = select_->SelectedOption();
}
void MenuListSelectType::DidDetachLayoutTree() {
if (popup_)
popup_->DisconnectClient();
SetPopupIsVisible(false);
popup_ = nullptr;
UnobserveTreeMutation();
}
void MenuListSelectType::DidRecalcStyle(const StyleRecalcChange change) {
if (change.ReattachLayoutTree())
return;
UpdateTextStyle();
if (auto* layout_object = select_->GetLayoutObject()) {
// Invalidate paint to ensure that the focus ring is updated.
layout_object->SetShouldDoFullPaintInvalidation();
}
if (PopupIsVisible())
popup_->UpdateFromElement(PopupMenu::kByStyleChange);
}
String MenuListSelectType::UpdateTextStyleInternal() {
HTMLOptionElement* option_to_be_shown = OptionToBeShown();
String text = g_empty_string;
const ComputedStyle* option_style = nullptr;
if (select_->IsMultiple()) {
unsigned selected_count = 0;
HTMLOptionElement* selected_option_element = nullptr;
for (auto* const option : select_->GetOptionList()) {
if (option->Selected()) {
if (++selected_count == 1)
selected_option_element = option;
}
}
if (selected_count == 1) {
text = selected_option_element->TextIndentedToRespectGroupLabel();
option_style = selected_option_element->GetComputedStyle();
} else {
Locale& locale = select_->GetLocale();
String localized_number_string =
locale.ConvertToLocalizedNumber(String::Number(selected_count));
text = locale.QueryString(IDS_FORM_SELECT_MENU_LIST_TEXT,
localized_number_string);
DCHECK(!option_style);
}
} else {
if (option_to_be_shown) {
text = option_to_be_shown->TextIndentedToRespectGroupLabel();
option_style = option_to_be_shown->GetComputedStyle();
}
}
option_style_ = option_style;
auto& inner_element = select_->InnerElement();
const ComputedStyle* inner_style = inner_element.GetComputedStyle();
if (inner_style && option_style &&
((option_style->Direction() != inner_style->Direction() ||
option_style->GetUnicodeBidi() != inner_style->GetUnicodeBidi() ||
option_style->GetTextAlign(true) != inner_style->GetTextAlign(true)))) {
scoped_refptr<ComputedStyle> cloned_style =
ComputedStyle::Clone(*inner_style);
cloned_style->SetDirection(option_style->Direction());
cloned_style->SetUnicodeBidi(option_style->GetUnicodeBidi());
cloned_style->SetTextAlign(option_style->GetTextAlign(true));
if (auto* inner_layout = inner_element.GetLayoutObject()) {
inner_layout->SetModifiedStyleOutsideStyleRecalc(
std::move(cloned_style), LayoutObject::ApplyStyleChanges::kYes);
} else {
inner_element.SetComputedStyle(std::move(cloned_style));
}
}
if (select_->GetLayoutObject())
DidUpdateActiveOption(option_to_be_shown);
return text.StripWhiteSpace();
}
void MenuListSelectType::UpdateTextStyleAndContent() {
select_->InnerElement().firstChild()->setNodeValue(UpdateTextStyleInternal());
if (auto* box = select_->GetLayoutBox()) {
if (auto* cache = select_->GetDocument().ExistingAXObjectCache())
cache->TextChanged(box);
}
}
void MenuListSelectType::DidUpdateActiveOption(HTMLOptionElement* option) {
Document& document = select_->GetDocument();
if (!document.ExistingAXObjectCache())
return;
int option_index = option ? option->index() : -1;
if (ax_menulist_last_active_index_ == option_index)
return;
ax_menulist_last_active_index_ = option_index;
// We skip sending accessiblity notifications for the very first option,
// otherwise we get extra focus and select events that are undesired.
if (!has_updated_menulist_active_option_) {
has_updated_menulist_active_option_ = true;
return;
}
document.ExistingAXObjectCache()->HandleUpdateActiveMenuOption(select_);
}
HTMLOptionElement* MenuListSelectType::OptionToBeShown() const {
if (auto* option =
select_->OptionAtListIndex(select_->index_to_select_on_cancel_))
return option;
if (select_->suggested_option_)
return select_->suggested_option_;
// TODO(tkent): We should not call OptionToBeShown() in IsMultiple() case.
if (select_->IsMultiple())
return select_->SelectedOption();
DCHECK_EQ(select_->SelectedOption(), select_->last_on_change_option_);
return select_->last_on_change_option_;
}
void MenuListSelectType::MaximumOptionWidthMightBeChanged() const {
if (LayoutObject* layout_object = select_->GetLayoutObject()) {
layout_object->SetNeedsLayoutAndIntrinsicWidthsRecalc(
layout_invalidation_reason::kMenuOptionsChanged);
}
}
// PopupUpdater notifies updates of the specified SELECT element subtree to
// a PopupMenu object.
class PopupUpdater : public MutationObserver::Delegate {
public:
explicit PopupUpdater(MenuListSelectType& select_type,
HTMLSelectElement& select)
: select_type_(select_type),
select_(select),
observer_(MutationObserver::Create(this)) {
MutationObserverInit* init = MutationObserverInit::Create();
init->setAttributeOldValue(true);
init->setAttributes(true);
// Observe only attributes which affect popup content.
init->setAttributeFilter({"disabled", "label", "selected", "value"});
init->setCharacterData(true);
init->setCharacterDataOldValue(true);
init->setChildList(true);
init->setSubtree(true);
observer_->observe(select_, init, ASSERT_NO_EXCEPTION);
}
ExecutionContext* GetExecutionContext() const override {
return select_->GetExecutionContext();
}
void Deliver(const MutationRecordVector& records,
MutationObserver&) override {
// We disconnect the MutationObserver when a popup is closed. However
// MutationObserver can call back after disconnection.
if (!select_type_->PopupIsVisible())
return;
for (const auto& record : records) {
if (record->type() == "attributes") {
const auto& element = *To<Element>(record->target());
if (record->oldValue() == element.getAttribute(record->attributeName()))
continue;
} else if (record->type() == "characterData") {
if (record->oldValue() == record->target()->nodeValue())
continue;
}
select_type_->DidMutateSubtree();
return;
}
}
void Dispose() { observer_->disconnect(); }
void Trace(Visitor* visitor) const override {
visitor->Trace(select_type_);
visitor->Trace(select_);
visitor->Trace(observer_);
MutationObserver::Delegate::Trace(visitor);
}
private:
Member<MenuListSelectType> select_type_;
Member<HTMLSelectElement> select_;
Member<MutationObserver> observer_;
};
void MenuListSelectType::ObserveTreeMutation() {
DCHECK(!popup_updater_);
popup_updater_ = MakeGarbageCollected<PopupUpdater>(*this, *select_);
}
void MenuListSelectType::UnobserveTreeMutation() {
if (!popup_updater_)
return;
popup_updater_->Dispose();
popup_updater_ = nullptr;
}
void MenuListSelectType::DidMutateSubtree() {
DCHECK(PopupIsVisible());
DCHECK(popup_);
popup_->UpdateFromElement(PopupMenu::kByDOMChange);
}
// ============================================================================
class ListBoxSelectType final : public SelectType {
public:
explicit ListBoxSelectType(HTMLSelectElement& select) : SelectType(select) {}
void Trace(Visitor* visitor) const override;
bool DefaultEventHandler(const Event& event) override;
void DidSelectOption(HTMLOptionElement* element,
HTMLSelectElement::SelectOptionFlags flags,
bool should_update_popup) override;
void OptionRemoved(HTMLOptionElement& option) override;
void DidBlur() override;
void DidSetSuggestedOption(HTMLOptionElement* option) override;
void SaveLastSelection() override;
HTMLOptionElement* SpatialNavigationFocusedOption() override;
HTMLOptionElement* ActiveSelectionEnd() const override;
void ScrollToSelection() override;
void ScrollToOption(HTMLOptionElement* option) override;
void SelectAll() override;
void SaveListboxActiveSelection() override;
void HandleMouseRelease() override;
void ListBoxOnChange() override;
void ClearLastOnChangeSelection() override;
private:
HTMLOptionElement* NextSelectableOptionPageAway(HTMLOptionElement*,
SkipDirection) const;
// Update :-internal-multi-select-focus state of selected OPTIONs.
void UpdateMultiSelectFocus();
void ToggleSelection(HTMLOptionElement& option);
enum class SelectionMode {
kDeselectOthers,
kRange,
kNotChangeOthers,
};
void UpdateSelectedState(HTMLOptionElement* clicked_option,
SelectionMode mode);
void UpdateListBoxSelection(bool deselect_other_options, bool scroll = true);
void SetActiveSelectionAnchor(HTMLOptionElement*);
void SetActiveSelectionEnd(HTMLOptionElement*);
void ScrollToOptionTask();
Vector<bool> cached_state_for_active_selection_;
Vector<bool> last_on_change_selection_;
Member<HTMLOptionElement> option_to_scroll_to_;
Member<HTMLOptionElement> active_selection_anchor_;
Member<HTMLOptionElement> active_selection_end_;
bool is_in_non_contiguous_selection_ = false;
bool active_selection_state_ = false;
};
void ListBoxSelectType::Trace(Visitor* visitor) const {
visitor->Trace(option_to_scroll_to_);
visitor->Trace(active_selection_anchor_);
visitor->Trace(active_selection_end_);
SelectType::Trace(visitor);
}
bool ListBoxSelectType::DefaultEventHandler(const Event& event) {
const auto* mouse_event = DynamicTo<MouseEvent>(event);
const auto* gesture_event = DynamicTo<GestureEvent>(event);
if (event.type() == event_type_names::kGesturetap && gesture_event) {
select_->Focus();
// Calling focus() may cause us to lose our layoutObject or change the
// layoutObject type, in which case do not want to handle the event.
if (!select_->GetLayoutObject() || will_be_destroyed_)
return false;
// Convert to coords relative to the list box if needed.
if (HTMLOptionElement* option = EventTargetOption(*gesture_event)) {
if (!select_->IsDisabledFormControl()) {
UpdateSelectedState(option, gesture_event->shiftKey()
? SelectionMode::kRange
: SelectionMode::kNotChangeOthers);
ListBoxOnChange();
}
return true;
}
return false;
}
if (event.type() == event_type_names::kMousedown && mouse_event &&
mouse_event->button() ==
static_cast<int16_t>(WebPointerProperties::Button::kLeft)) {
select_->Focus();
// Calling focus() may cause us to lose our layoutObject, in which case
// do not want to handle the event.
if (!select_->GetLayoutObject() || will_be_destroyed_ ||
select_->IsDisabledFormControl())
return false;
// Convert to coords relative to the list box if needed.
if (HTMLOptionElement* option = EventTargetOption(*mouse_event)) {
if (!option->IsDisabledFormControl()) {
#if BUILDFLAG(IS_MAC)
const bool meta_or_ctrl = mouse_event->metaKey();
#else
const bool meta_or_ctrl = mouse_event->ctrlKey();
#endif
UpdateSelectedState(option, mouse_event->shiftKey()
? SelectionMode::kRange
: meta_or_ctrl
? SelectionMode::kNotChangeOthers
: SelectionMode::kDeselectOthers);
}
if (LocalFrame* frame = select_->GetDocument().GetFrame())
frame->GetEventHandler().SetMouseDownMayStartAutoscroll();
return true;
}
return false;
}
if (event.type() == event_type_names::kMousemove && mouse_event) {
if (mouse_event->button() !=
static_cast<int16_t>(WebPointerProperties::Button::kLeft) ||
!mouse_event->ButtonDown())
return false;
if (auto* layout_object = select_->GetLayoutObject()) {
layout_object->GetFrameView()->UpdateAllLifecyclePhasesExceptPaint(
DocumentUpdateReason::kScroll);
}
// Lifecycle update could have detached the layout object.
if (auto* layout_object = select_->GetLayoutObject()) {
if (Page* page = select_->GetDocument().GetPage()) {
page->GetAutoscrollController().StartAutoscrollForSelection(
layout_object);
}
}
// Mousedown didn't happen in this element.
if (last_on_change_selection_.empty())
return false;
if (HTMLOptionElement* option = EventTargetOption(*mouse_event)) {
if (!select_->IsDisabledFormControl()) {
if (select_->is_multiple_) {
// Only extend selection if there is something selected.
if (!active_selection_anchor_)
return false;
SetActiveSelectionEnd(option);
UpdateListBoxSelection(false);
} else {
SetActiveSelectionAnchor(option);
SetActiveSelectionEnd(option);
UpdateListBoxSelection(true);
}
}
}
return false;
}
if (event.type() == event_type_names::kMouseup && mouse_event &&
mouse_event->button() ==
static_cast<int16_t>(WebPointerProperties::Button::kLeft) &&
select_->GetLayoutObject()) {
auto* page = select_->GetDocument().GetPage();
if (page && page->GetAutoscrollController().AutoscrollInProgressFor(
select_->GetLayoutBox()))
page->GetAutoscrollController().StopAutoscroll();
else
HandleMouseRelease();
return false;
}
if (event.type() == event_type_names::kKeydown) {
const auto* keyboard_event = DynamicTo<KeyboardEvent>(event);
if (!keyboard_event)
return false;
const String& key = keyboard_event->key();
bool handled = false;
HTMLOptionElement* end_option = nullptr;
if (!active_selection_end_) {
// Initialize the end index
if (key == "ArrowDown" || key == "PageDown") {
HTMLOptionElement* start_option = select_->LastSelectedOption();
handled = true;
if (key == "ArrowDown") {
end_option = NextSelectableOption(start_option);
} else {
end_option =
NextSelectableOptionPageAway(start_option, kSkipForwards);
}
} else if (key == "ArrowUp" || key == "PageUp") {
HTMLOptionElement* start_option = select_->SelectedOption();
handled = true;
if (key == "ArrowUp") {
end_option = PreviousSelectableOption(start_option);
} else {
end_option =
NextSelectableOptionPageAway(start_option, kSkipBackwards);
}
}
} else {
// Set the end index based on the current end index.
if (key == "ArrowDown") {
end_option = NextSelectableOption(active_selection_end_);
handled = true;
} else if (key == "ArrowUp") {
end_option = PreviousSelectableOption(active_selection_end_);
handled = true;
} else if (key == "PageDown") {
end_option =
NextSelectableOptionPageAway(active_selection_end_, kSkipForwards);
handled = true;
} else if (key == "PageUp") {
end_option =
NextSelectableOptionPageAway(active_selection_end_, kSkipBackwards);
handled = true;
}
}
if (key == "Home") {
end_option = FirstSelectableOption();
handled = true;
} else if (key == "End") {
end_option = LastSelectableOption();
handled = true;
}
if (IsSpatialNavigationEnabled(select_->GetDocument().GetFrame())) {
// Check if the selection moves to the boundary.
if (key == "ArrowLeft" || key == "ArrowRight" ||
((key == "ArrowDown" || key == "ArrowUp") &&
end_option == active_selection_end_))
return false;
}
bool is_control_key = false;
#if BUILDFLAG(IS_MAC)
is_control_key = keyboard_event->metaKey();
#else
is_control_key = keyboard_event->ctrlKey();
#endif
if (select_->is_multiple_ && keyboard_event->keyCode() == ' ' &&
is_control_key && active_selection_end_) {
// Use ctrl+space to toggle selection change.
ToggleSelection(*active_selection_end_);
return true;
}
if (end_option && handled) {
// Save the selection so it can be compared to the new selection
// when dispatching change events immediately after making the new
// selection.
SaveLastSelection();
SetActiveSelectionEnd(end_option);
is_in_non_contiguous_selection_ = select_->is_multiple_ && is_control_key;
bool select_new_item =
!select_->is_multiple_ || keyboard_event->shiftKey() ||
(!IsSpatialNavigationEnabled(select_->GetDocument().GetFrame()) &&
!is_in_non_contiguous_selection_);
if (select_new_item)
active_selection_state_ = true;
// If the anchor is uninitialized, or if we're going to deselect all
// other options, then set the anchor index equal to the end index.
bool deselect_others = !select_->is_multiple_ ||
(!keyboard_event->shiftKey() && select_new_item);
if (!active_selection_anchor_ || deselect_others) {
if (deselect_others)
select_->DeselectItemsWithoutValidation();
SetActiveSelectionAnchor(active_selection_end_.Get());
}
ScrollToOption(end_option);
if (select_new_item || is_in_non_contiguous_selection_) {
if (select_new_item) {
UpdateListBoxSelection(deselect_others);
ListBoxOnChange();
}
UpdateMultiSelectFocus();
} else {
ScrollToSelection();
}
return true;
}
return false;
}
if (event.type() == event_type_names::kKeypress) {
auto* keyboard_event = DynamicTo<KeyboardEvent>(event);
if (!keyboard_event)
return false;
int key_code = keyboard_event->keyCode();
if (key_code == '\r') {
if (HTMLFormElement* form = select_->Form())
form->SubmitImplicitly(event, false);
return true;
} else if (select_->is_multiple_ && key_code == ' ' &&
(IsSpatialNavigationEnabled(select_->GetDocument().GetFrame()) ||
is_in_non_contiguous_selection_)) {
HTMLOptionElement* option = active_selection_end_;
// If there's no active selection,
// act as if "ArrowDown" had been pressed.
if (!option)
option = NextSelectableOption(select_->LastSelectedOption());
if (option) {
// Use space to toggle selection change.
ToggleSelection(*option);
return true;
}
}
return false;
}
return false;
}
void ListBoxSelectType::DidSelectOption(
HTMLOptionElement* element,
HTMLSelectElement::SelectOptionFlags flags,
bool should_update_popup) {
// We should update active selection after finishing OPTION state change
// because SetActiveSelectionAnchor() stores OPTION's selection state.
if (element) {
const bool is_single = !select_->IsMultiple();
const bool deselect_other_options =
flags & HTMLSelectElement::kDeselectOtherOptionsFlag;
// SetActiveSelectionAnchor is O(N).
if (!active_selection_anchor_ || is_single || deselect_other_options)
SetActiveSelectionAnchor(element);
if (!active_selection_end_ || is_single || deselect_other_options)
SetActiveSelectionEnd(element);
}
ScrollToSelection();
select_->SetNeedsValidityCheck();
}
void ListBoxSelectType::OptionRemoved(HTMLOptionElement& option) {
if (option_to_scroll_to_ == &option)
option_to_scroll_to_.Clear();
if (active_selection_anchor_ == &option)
active_selection_anchor_.Clear();
if (active_selection_end_ == &option)
active_selection_end_.Clear();
}