summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/html/custom/custom_element_registry.cc
blob: d6fae1df0cb4198fae11b600aba7d48fc50cfcde (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
353
354
355
356
357
358
359
360
361
362
363
364
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/core/html/custom/custom_element_registry.h"

#include <limits>

#include "base/auto_reset.h"
#include "third_party/blink/public/web/web_custom_element.h"
#include "third_party/blink/renderer/bindings/core/v8/script_custom_element_definition_builder.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/dom/element_definition_options.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/html/custom/ce_reactions_scope.h"
#include "third_party/blink/renderer/core/html/custom/custom_element.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_definition.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_definition_builder.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_descriptor.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_reaction_stack.h"
#include "third_party/blink/renderer/core/html/custom/custom_element_upgrade_sorter.h"
#include "third_party/blink/renderer/core/html/custom/v0_custom_element_registration_context.h"
#include "third_party/blink/renderer/core/html_element_type_helpers.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"

namespace blink {

namespace {

void CollectUpgradeCandidateInNode(Node& root,
                                   HeapVector<Member<Element>>& candidates) {
  if (root.IsElementNode()) {
    Element& root_element = ToElement(root);
    if (root_element.GetCustomElementState() == CustomElementState::kUndefined)
      candidates.push_back(root_element);
    if (auto* shadow_root = root_element.GetShadowRoot()) {
      if (shadow_root->GetType() != ShadowRootType::kUserAgent)
        CollectUpgradeCandidateInNode(*shadow_root, candidates);
    }
  }
  for (auto& element : Traversal<HTMLElement>::ChildrenOf(root))
    CollectUpgradeCandidateInNode(element, candidates);
}

// Returns true if |name| is invalid.
bool ThrowIfInvalidName(const AtomicString& name,
                        bool allow_embedder_names,
                        ExceptionState& exception_state) {
  if (CustomElement::IsValidName(name, allow_embedder_names))
    return false;
  exception_state.ThrowDOMException(
      DOMExceptionCode::kSyntaxError,
      "\"" + name + "\" is not a valid custom element name");
  return true;
}

// Returns true if |name| is valid.
bool ThrowIfValidName(const AtomicString& name,
                      ExceptionState& exception_state) {
  if (!CustomElement::IsValidName(name, false))
    return false;
  exception_state.ThrowDOMException(
      DOMExceptionCode::kNotSupportedError,
      "\"" + name + "\" is a valid custom element name");
  return true;
}

}  // namespace

CustomElementRegistry::CustomElementRegistry(const LocalDOMWindow* owner)
    : element_definition_is_running_(false),
      owner_(owner),
      v0_(MakeGarbageCollected<V0RegistrySet>()),
      upgrade_candidates_(MakeGarbageCollected<UpgradeCandidateMap>()),
      reaction_stack_(&CustomElementReactionStack::Current()) {
  Document* document = owner->document();
  if (V0CustomElementRegistrationContext* v0 =
          document ? document->RegistrationContext() : nullptr)
    Entangle(v0);
}

void CustomElementRegistry::Trace(Visitor* visitor) {
  visitor->Trace(definitions_);
  visitor->Trace(owner_);
  visitor->Trace(v0_);
  visitor->Trace(upgrade_candidates_);
  visitor->Trace(when_defined_promise_map_);
  visitor->Trace(reaction_stack_);
  ScriptWrappable::Trace(visitor);
}

CustomElementDefinition* CustomElementRegistry::define(
    ScriptState* script_state,
    const AtomicString& name,
    V8CustomElementConstructor* constructor,
    const ElementDefinitionOptions* options,
    ExceptionState& exception_state) {
  ScriptCustomElementDefinitionBuilder builder(script_state, this, constructor,
                                               exception_state);
  return DefineInternal(script_state, name, builder, options, exception_state);
}

// http://w3c.github.io/webcomponents/spec/custom/#dfn-element-definition
CustomElementDefinition* CustomElementRegistry::DefineInternal(
    ScriptState* script_state,
    const AtomicString& name,
    CustomElementDefinitionBuilder& builder,
    const ElementDefinitionOptions* options,
    ExceptionState& exception_state) {
  TRACE_EVENT1("blink", "CustomElementRegistry::define", "name", name.Utf8());
  if (!builder.CheckConstructorIntrinsics())
    return nullptr;

  const bool allow_embedder_names =
      WebCustomElement::EmbedderNamesAllowedScope::IsAllowed();
  if (ThrowIfInvalidName(name, allow_embedder_names, exception_state))
    return nullptr;

  if (NameIsDefined(name) || V0NameIsDefined(name)) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kNotSupportedError,
        "the name \"" + name + "\" has already been used with this registry");
    return nullptr;
  }

  if (!builder.CheckConstructorNotRegistered())
    return nullptr;

  // Polymer V2/V3 uses Custom Elements V1. <dom-module> is defined in its base
  // library and is a strong signal that this is a Polymer V2+.
  if (name == "dom-module") {
    if (Document* document = owner_->document())
      UseCounter::Count(*document, WebFeature::kPolymerV2Detected);
  }
  AtomicString local_name = name;

  // Step 7. customized built-in elements definition
  // element interface extends option checks
  if (options->hasExtends()) {
    // 7.1. If element interface is valid custom element name, throw exception
    const AtomicString& extends = AtomicString(options->extends());
    if (ThrowIfValidName(AtomicString(options->extends()), exception_state))
      return nullptr;
    // 7.2. If element interface is undefined element, throw exception
    if (htmlElementTypeForTag(extends) ==
        HTMLElementType::kHTMLUnknownElement) {
      exception_state.ThrowDOMException(
          DOMExceptionCode::kNotSupportedError,
          "\"" + extends + "\" is an HTMLUnknownElement");
      return nullptr;
    }
    // 7.3. Set localName to extends
    local_name = extends;
  }

  // 8. If this CustomElementRegistry's element definition is
  // running flag is set, then throw a "NotSupportedError"
  // DOMException and abort these steps.
  if (element_definition_is_running_) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kNotSupportedError,
        "an element definition is already being processed");
    return nullptr;
  }

  {
    // 9. Set this CustomElementRegistry's element definition is
    // running flag.
    base::AutoReset<bool> defining(&element_definition_is_running_, true);

    // 10. Run the following substeps while catching any exceptions: ...
    if (!builder.RememberOriginalProperties())
      return nullptr;

    // "Then, perform the following substep, regardless of whether
    // the above steps threw an exception or not: Unset this
    // CustomElementRegistry's element definition is running
    // flag."
    // (|defining|'s destructor does this.)
  }

  // During step 10, property getters might have detached the frame. Abort in
  // the case.
  if (!script_state->ContextIsValid()) {
    // Intentionally do not throw an exception so that, when Blink will support
    // detached frames, the behavioral change whether Blink throws or not will
    // not be observable from author.
    // TODO(yukishiino): Support detached frames.
    return nullptr;
  }

  CustomElementDescriptor descriptor(name, local_name);
  if (UNLIKELY(definitions_.size() >=
               std::numeric_limits<CustomElementDefinition::Id>::max()))
    return nullptr;
  CustomElementDefinition::Id id = definitions_.size() + 1;
  CustomElementDefinition* definition = builder.Build(descriptor, id);
  CHECK(!exception_state.HadException());
  CHECK(definition->Descriptor() == descriptor);
  if (RuntimeEnabledFeatures::CustomElementDefaultStyleEnabled() &&
      options->hasStyles())
    definition->SetDefaultStyleSheets(options->styles());
  definitions_.emplace_back(definition);
  NameIdMap::AddResult result = name_id_map_.insert(descriptor.GetName(), id);
  CHECK(result.is_new_entry);

  HeapVector<Member<Element>> candidates;
  CollectCandidates(descriptor, &candidates);
  for (Element* candidate : candidates)
    definition->EnqueueUpgradeReaction(*candidate);

  // 16: when-defined promise processing
  const auto& entry = when_defined_promise_map_.find(name);
  if (entry != when_defined_promise_map_.end()) {
    entry->value->Resolve();
    when_defined_promise_map_.erase(entry);
  }

  return definition;
}

// https://html.spec.whatwg.org/C/#dom-customelementsregistry-get
ScriptValue CustomElementRegistry::get(const AtomicString& name) {
  CustomElementDefinition* definition = DefinitionForName(name);
  if (!definition) {
    // Binding layer converts |ScriptValue()| to script specific value,
    // e.g. |undefined| for v8.
    return ScriptValue();
  }
  return definition->GetConstructorForScript();
}

// https://html.spec.whatwg.org/C/#look-up-a-custom-element-definition
// At this point, what the spec calls 'is' is 'name' from desc
CustomElementDefinition* CustomElementRegistry::DefinitionFor(
    const CustomElementDescriptor& desc) const {
  // desc.name() is 'is' attribute
  // 4. If definition in registry with name equal to local name...
  CustomElementDefinition* definition = DefinitionForName(desc.LocalName());
  // 5. If definition in registry with name equal to name...
  if (!definition)
    definition = DefinitionForName(desc.GetName());
  // 4&5. ...and local name equal to localName, return that definition
  if (definition and definition->Descriptor().LocalName() == desc.LocalName()) {
    return definition;
  }
  // 6. Return null
  return nullptr;
}

bool CustomElementRegistry::NameIsDefined(const AtomicString& name) const {
  return name_id_map_.Contains(name);
}

void CustomElementRegistry::Entangle(V0CustomElementRegistrationContext* v0) {
  v0_->insert(v0);
  v0->SetV1(this);
}

bool CustomElementRegistry::V0NameIsDefined(const AtomicString& name) {
  for (const auto& v0 : *v0_) {
    if (v0->NameIsDefined(name))
      return true;
  }
  return false;
}

CustomElementDefinition* CustomElementRegistry::DefinitionForName(
    const AtomicString& name) const {
  return DefinitionForId(name_id_map_.at(name));
}

CustomElementDefinition* CustomElementRegistry::DefinitionForId(
    CustomElementDefinition::Id id) const {
  return id ? definitions_[id - 1].Get() : nullptr;
}

void CustomElementRegistry::AddCandidate(Element& candidate) {
  AtomicString name = candidate.localName();
  if (!CustomElement::IsValidName(name)) {
    const AtomicString& is = candidate.IsValue();
    if (!is.IsNull())
      name = is;
  }
  if (NameIsDefined(name) || V0NameIsDefined(name))
    return;
  UpgradeCandidateMap::iterator it = upgrade_candidates_->find(name);
  UpgradeCandidateSet* set;
  if (it != upgrade_candidates_->end()) {
    set = it->value;
  } else {
    set = upgrade_candidates_
              ->insert(name, MakeGarbageCollected<UpgradeCandidateSet>())
              .stored_value->value;
  }
  set->insert(&candidate);
}

// https://html.spec.whatwg.org/C/#dom-customelementsregistry-whendefined
ScriptPromise CustomElementRegistry::whenDefined(
    ScriptState* script_state,
    const AtomicString& name,
    ExceptionState& exception_state) {
  if (ThrowIfInvalidName(name, false, exception_state))
    return ScriptPromise();
  CustomElementDefinition* definition = DefinitionForName(name);
  if (definition)
    return ScriptPromise::CastUndefined(script_state);
  ScriptPromiseResolver* resolver = when_defined_promise_map_.at(name);
  if (resolver)
    return resolver->Promise();
  auto* new_resolver =
      MakeGarbageCollected<ScriptPromiseResolver>(script_state);
  when_defined_promise_map_.insert(name, new_resolver);
  return new_resolver->Promise();
}

void CustomElementRegistry::CollectCandidates(
    const CustomElementDescriptor& desc,
    HeapVector<Member<Element>>* elements) {
  UpgradeCandidateMap::iterator it = upgrade_candidates_->find(desc.GetName());
  if (it == upgrade_candidates_->end())
    return;
  CustomElementUpgradeSorter sorter;
  for (Element* element : *it.Get()->value) {
    if (!element || !desc.Matches(*element))
      continue;
    sorter.Add(element);
  }

  upgrade_candidates_->erase(it);

  Document* document = owner_->document();
  if (!document)
    return;

  sorter.Sorted(elements, document);
}

// https://html.spec.whatwg.org/C/#dom-customelementregistry-upgrade
void CustomElementRegistry::upgrade(Node* root) {
  DCHECK(root);

  // 1. Let candidates be a list of all of root's shadow-including
  // inclusive descendant elements, in tree order.
  HeapVector<Member<Element>> candidates;
  CollectUpgradeCandidateInNode(*root, candidates);

  // 2. For each candidate of candidates, try to upgrade candidate.
  for (auto& candidate : candidates) {
    CustomElement::TryToUpgrade(*candidate,
                                true /* upgrade_invisible_elements */);
  }
}

}  // namespace blink