summaryrefslogtreecommitdiffstats
path: root/dom/html/HTMLElement.cpp
blob: b033ceee71ecbba383f5e673c759b03c68ba31bd (plain)
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/dom/HTMLElement.h"

#include "mozilla/dom/CustomElementRegistry.h"
#include "mozilla/dom/HTMLElementBinding.h"
#include "mozilla/EventDispatcher.h"
#include "nsContentUtils.h"

namespace mozilla::dom {

HTMLElement::HTMLElement(already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo)
    : nsGenericHTMLFormElement(std::move(aNodeInfo)) {
  if (NodeInfo()->Equals(nsGkAtoms::bdi)) {
    AddStatesSilently(ElementState::HAS_DIR_ATTR_LIKE_AUTO);
  }
}

NS_IMPL_CYCLE_COLLECTION_INHERITED(HTMLElement, nsGenericHTMLFormElement)

// QueryInterface implementation for HTMLElement

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(HTMLElement)
  NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIFormControl, GetElementInternals())
  NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIConstraintValidation, GetElementInternals())
NS_INTERFACE_MAP_END_INHERITING(nsGenericHTMLFormElement)

NS_IMPL_ADDREF_INHERITED(HTMLElement, nsGenericHTMLFormElement)
NS_IMPL_RELEASE_INHERITED(HTMLElement, nsGenericHTMLFormElement)

NS_IMPL_ELEMENT_CLONE(HTMLElement)

JSObject* HTMLElement::WrapNode(JSContext* aCx,
                                JS::Handle<JSObject*> aGivenProto) {
  return dom::HTMLElement_Binding::Wrap(aCx, this, aGivenProto);
}

void HTMLElement::GetEventTargetParent(EventChainPreVisitor& aVisitor) {
  if (IsDisabledForEvents(aVisitor.mEvent)) {
    // Do not process any DOM events if the element is disabled
    aVisitor.mCanHandle = false;
    return;
  }

  nsGenericHTMLFormElement::GetEventTargetParent(aVisitor);
}

nsINode* HTMLElement::GetScopeChainParent() const {
  if (IsFormAssociatedCustomElements()) {
    auto* form = GetFormInternal();
    if (form) {
      return form;
    }
  }
  return nsGenericHTMLFormElement::GetScopeChainParent();
}

nsresult HTMLElement::BindToTree(BindContext& aContext, nsINode& aParent) {
  nsresult rv = nsGenericHTMLFormElement::BindToTree(aContext, aParent);
  NS_ENSURE_SUCCESS(rv, rv);

  UpdateBarredFromConstraintValidation();
  return rv;
}

void HTMLElement::UnbindFromTree(bool aNullParent) {
  nsGenericHTMLFormElement::UnbindFromTree(aNullParent);

  UpdateBarredFromConstraintValidation();
}

void HTMLElement::SetCustomElementDefinition(
    CustomElementDefinition* aDefinition) {
  nsGenericHTMLFormElement::SetCustomElementDefinition(aDefinition);
  // Always create an ElementInternal for form-associated custom element as the
  // Form related implementation lives in ElementInternal which implements
  // nsIFormControl. It is okay for the attachElementInternal API as there is a
  // separated flag for whether attachElementInternal is called.
  if (aDefinition && !aDefinition->IsCustomBuiltIn() &&
      aDefinition->mFormAssociated) {
    CustomElementData* data = GetCustomElementData();
    MOZ_ASSERT(data);
    data->GetOrCreateElementInternals(this);

    // This is for the case that script constructs a custom element directly,
    // e.g. via new MyCustomElement(), where the upgrade steps won't be ran to
    // update the disabled state in UpdateFormOwner().
    if (data->mState == CustomElementData::State::eCustom) {
      UpdateDisabledState(true);
    }
  }
}

// https://html.spec.whatwg.org/commit-snapshots/53bc3803433e1c817918b83e8a84f3db900031dd/#dom-attachinternals
already_AddRefed<ElementInternals> HTMLElement::AttachInternals(
    ErrorResult& aRv) {
  CustomElementData* ceData = GetCustomElementData();

  // 1. If element's is value is not null, then throw a "NotSupportedError"
  //    DOMException.
  if (nsAtom* isAtom = ceData ? ceData->GetIs(this) : nullptr) {
    aRv.ThrowNotSupportedError(nsPrintfCString(
        "Cannot attach ElementInternals to a customized built-in element "
        "'%s'",
        NS_ConvertUTF16toUTF8(isAtom->GetUTF16String()).get()));
    return nullptr;
  }

  // 2. Let definition be the result of looking up a custom element definition
  //    given element's node document, its namespace, its local name, and null
  //    as is value.
  nsAtom* nameAtom = NodeInfo()->NameAtom();
  CustomElementDefinition* definition = nullptr;
  if (ceData) {
    definition = ceData->GetCustomElementDefinition();

    // If the definition is null, the element possible hasn't yet upgraded.
    // Fallback to use LookupCustomElementDefinition to find its definition.
    if (!definition) {
      definition = nsContentUtils::LookupCustomElementDefinition(
          NodeInfo()->GetDocument(), nameAtom, NodeInfo()->NamespaceID(),
          ceData->GetCustomElementType());
    }
  }

  // 3. If definition is null, then throw an "NotSupportedError" DOMException.
  if (!definition) {
    aRv.ThrowNotSupportedError(nsPrintfCString(
        "Cannot attach ElementInternals to a non-custom element '%s'",
        NS_ConvertUTF16toUTF8(nameAtom->GetUTF16String()).get()));
    return nullptr;
  }

  // 4. If definition's disable internals is true, then throw a
  //    "NotSupportedError" DOMException.
  if (definition->mDisableInternals) {
    aRv.ThrowNotSupportedError(nsPrintfCString(
        "AttachInternal() to '%s' is disabled by disabledFeatures",
        NS_ConvertUTF16toUTF8(nameAtom->GetUTF16String()).get()));
    return nullptr;
  }

  // If this is not a custom element, i.e. ceData is nullptr, we are unable to
  // find a definition and should return earlier above.
  MOZ_ASSERT(ceData);

  // 5. If element's attached internals is true, then throw an
  //    "NotSupportedError" DOMException.
  if (ceData->HasAttachedInternals()) {
    aRv.ThrowNotSupportedError(nsPrintfCString(
        "AttachInternals() has already been called from '%s'",
        NS_ConvertUTF16toUTF8(nameAtom->GetUTF16String()).get()));
    return nullptr;
  }

  // 6. If element's custom element state is not "precustomized" or "custom",
  //    then throw a "NotSupportedError" DOMException.
  if (ceData->mState != CustomElementData::State::ePrecustomized &&
      ceData->mState != CustomElementData::State::eCustom) {
    aRv.ThrowNotSupportedError(
        R"(Custom element state is not "precustomized" or "custom".)");
    return nullptr;
  }

  // 7. Set element's attached internals to true.
  ceData->AttachedInternals();

  // 8. Create a new ElementInternals instance targeting element, and return it.
  return do_AddRef(ceData->GetOrCreateElementInternals(this));
}

void HTMLElement::AfterClearForm(bool aUnbindOrDelete) {
  // No need to enqueue formAssociated callback if we aren't releasing or
  // unbinding from tree, UpdateFormOwner() will handle it.
  if (aUnbindOrDelete) {
    MOZ_ASSERT(IsFormAssociatedElement());
    nsContentUtils::EnqueueLifecycleCallback(
        ElementCallbackType::eFormAssociated, this, {});
  }
}

void HTMLElement::UpdateFormOwner() {
  MOZ_ASSERT(IsFormAssociatedElement());

  // If @form is set, the element *has* to be in a composed document,
  // otherwise it wouldn't be possible to find an element with the
  // corresponding id. If @form isn't set, the element *has* to have a parent,
  // otherwise it wouldn't be possible to find a form ancestor. We should not
  // call UpdateFormOwner if none of these conditions are fulfilled.
  if (HasAttr(kNameSpaceID_None, nsGkAtoms::form) ? IsInComposedDoc()
                                                  : !!GetParent()) {
    UpdateFormOwner(true, nullptr);
  }
  UpdateFieldSet(true);
  UpdateDisabledState(true);
  UpdateBarredFromConstraintValidation();
}

bool HTMLElement::IsDisabledForEvents(WidgetEvent* aEvent) {
  if (IsFormAssociatedElement()) {
    return IsElementDisabledForEvents(aEvent, GetPrimaryFrame());
  }

  return false;
}

void HTMLElement::AfterSetAttr(int32_t aNameSpaceID, nsAtom* aName,
                               const nsAttrValue* aValue,
                               const nsAttrValue* aOldValue,
                               nsIPrincipal* aMaybeScriptedPrincipal,
                               bool aNotify) {
  if (aNameSpaceID == kNameSpaceID_None &&
      (aName == nsGkAtoms::disabled || aName == nsGkAtoms::readonly)) {
    if (aName == nsGkAtoms::disabled) {
      // This *has* to be called *before* validity state check because
      // UpdateBarredFromConstraintValidation depend on our disabled state.
      UpdateDisabledState(aNotify);
    }
    UpdateBarredFromConstraintValidation();
  }

  return nsGenericHTMLFormElement::AfterSetAttr(
      aNameSpaceID, aName, aValue, aOldValue, aMaybeScriptedPrincipal, aNotify);
}

ElementState HTMLElement::IntrinsicState() const {
  ElementState state = nsGenericHTMLFormElement::IntrinsicState();
  if (ElementInternals* internals = GetElementInternals()) {
    if (internals->IsCandidateForConstraintValidation()) {
      if (internals->IsValid()) {
        state |= ElementState::VALID | ElementState::USER_VALID;
      } else {
        state |= ElementState::INVALID | ElementState::USER_INVALID;
      }
    }
  }
  return state;
}

void HTMLElement::SetFormInternal(HTMLFormElement* aForm, bool aBindToTree) {
  ElementInternals* internals = GetElementInternals();
  MOZ_ASSERT(internals);
  internals->SetForm(aForm);
}

HTMLFormElement* HTMLElement::GetFormInternal() const {
  ElementInternals* internals = GetElementInternals();
  MOZ_ASSERT(internals);
  return internals->GetForm();
}

void HTMLElement::SetFieldSetInternal(HTMLFieldSetElement* aFieldset) {
  ElementInternals* internals = GetElementInternals();
  MOZ_ASSERT(internals);
  internals->SetFieldSet(aFieldset);
}

HTMLFieldSetElement* HTMLElement::GetFieldSetInternal() const {
  ElementInternals* internals = GetElementInternals();
  MOZ_ASSERT(internals);
  return internals->GetFieldSet();
}

bool HTMLElement::CanBeDisabled() const { return IsFormAssociatedElement(); }

bool HTMLElement::DoesReadOnlyApply() const {
  return IsFormAssociatedElement();
}

void HTMLElement::UpdateDisabledState(bool aNotify) {
  bool oldState = IsDisabled();
  nsGenericHTMLFormElement::UpdateDisabledState(aNotify);
  if (oldState != IsDisabled()) {
    MOZ_ASSERT(IsFormAssociatedElement());
    LifecycleCallbackArgs args;
    args.mDisabled = !oldState;
    nsContentUtils::EnqueueLifecycleCallback(ElementCallbackType::eFormDisabled,
                                             this, args);
  }
}

void HTMLElement::UpdateFormOwner(bool aBindToTree, Element* aFormIdElement) {
  HTMLFormElement* oldForm = GetFormInternal();
  nsGenericHTMLFormElement::UpdateFormOwner(aBindToTree, aFormIdElement);
  HTMLFormElement* newForm = GetFormInternal();
  if (newForm != oldForm) {
    LifecycleCallbackArgs args;
    args.mForm = newForm;
    nsContentUtils::EnqueueLifecycleCallback(
        ElementCallbackType::eFormAssociated, this, args);
  }
}

bool HTMLElement::IsFormAssociatedElement() const {
  CustomElementData* data = GetCustomElementData();
  return data && data->IsFormAssociated();
}

void HTMLElement::FieldSetDisabledChanged(bool aNotify) {
  // This *has* to be called *before* UpdateBarredFromConstraintValidation
  // because this function depend on our disabled state.
  nsGenericHTMLFormElement::FieldSetDisabledChanged(aNotify);

  UpdateBarredFromConstraintValidation();
}

ElementInternals* HTMLElement::GetElementInternals() const {
  CustomElementData* data = GetCustomElementData();
  if (!data || !data->IsFormAssociated()) {
    // If the element is not a form associated custom element, it should not be
    // able to be QueryInterfaced to nsIFormControl and could not perform
    // the form operation, either, so we return nullptr here.
    return nullptr;
  }

  return data->GetElementInternals();
}

void HTMLElement::UpdateBarredFromConstraintValidation() {
  CustomElementData* data = GetCustomElementData();
  if (data && data->IsFormAssociated()) {
    ElementInternals* internals = data->GetElementInternals();
    MOZ_ASSERT(internals);
    internals->UpdateBarredFromConstraintValidation();
  }
}

}  // namespace mozilla::dom

// Here, we expand 'NS_IMPL_NS_NEW_HTML_ELEMENT()' by hand.
// (Calling the macro directly (with no args) produces compiler warnings.)
nsGenericHTMLElement* NS_NewHTMLElement(
    already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo,
    mozilla::dom::FromParser aFromParser) {
  RefPtr<mozilla::dom::NodeInfo> nodeInfo(aNodeInfo);
  auto* nim = nodeInfo->NodeInfoManager();
  return new (nim) mozilla::dom::HTMLElement(nodeInfo.forget());
}

// Distinct from the above in order to have function pointer that compared
// unequal to a function pointer to the above.
nsGenericHTMLElement* NS_NewCustomElement(
    already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo,
    mozilla::dom::FromParser aFromParser) {
  RefPtr<mozilla::dom::NodeInfo> nodeInfo(aNodeInfo);
  auto* nim = nodeInfo->NodeInfoManager();
  return new (nim) mozilla::dom::HTMLElement(nodeInfo.forget());
}