HTMLLabelElement.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/Bindings/HTMLLabelElementPrototype.h>
  7. #include <LibWeb/DOM/Document.h>
  8. #include <LibWeb/HTML/HTMLLabelElement.h>
  9. #include <LibWeb/Layout/Label.h>
  10. namespace Web::HTML {
  11. JS_DEFINE_ALLOCATOR(HTMLLabelElement);
  12. HTMLLabelElement::HTMLLabelElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  13. : HTMLElement(document, move(qualified_name))
  14. {
  15. }
  16. HTMLLabelElement::~HTMLLabelElement() = default;
  17. void HTMLLabelElement::initialize(JS::Realm& realm)
  18. {
  19. Base::initialize(realm);
  20. WEB_SET_PROTOTYPE_FOR_INTERFACE(HTMLLabelElement);
  21. }
  22. JS::GCPtr<Layout::Node> HTMLLabelElement::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
  23. {
  24. return heap().allocate_without_realm<Layout::Label>(document(), this, move(style));
  25. }
  26. // https://html.spec.whatwg.org/multipage/forms.html#labeled-control
  27. JS::GCPtr<HTMLElement> HTMLLabelElement::control() const
  28. {
  29. JS::GCPtr<HTMLElement> control;
  30. // The for attribute may be specified to indicate a form control with which the caption is
  31. // to be associated. If the attribute is specified, the attribute's value must be the ID of
  32. // a labelable element in the same tree as the label element. If the attribute is specified
  33. // and there is an element in the tree whose ID is equal to the value of the for attribute,
  34. // and the first such element in tree order is a labelable element, then that element is the
  35. // label element's labeled control.
  36. if (for_().has_value()) {
  37. root().for_each_in_inclusive_subtree_of_type<HTMLElement>([&](auto& element) {
  38. if (element.id() == *for_() && element.is_labelable()) {
  39. control = &const_cast<HTMLElement&>(element);
  40. return TraversalDecision::Break;
  41. }
  42. return TraversalDecision::Continue;
  43. });
  44. return control;
  45. }
  46. // If the for attribute is not specified, but the label element has a labelable element descendant,
  47. // then the first such descendant in tree order is the label element's labeled control.
  48. for_each_in_subtree_of_type<HTMLElement>([&](auto& element) {
  49. if (element.is_labelable()) {
  50. control = &const_cast<HTMLElement&>(element);
  51. return TraversalDecision::Break;
  52. }
  53. return TraversalDecision::Continue;
  54. });
  55. return control;
  56. }
  57. }