summaryrefslogtreecommitdiffstats
path: root/dom/base/CustomElementRegistry.h
blob: d3dfef682118631c4e587c8960601fa6330c58ff (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
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* 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/. */

#ifndef mozilla_dom_CustomElementRegistry_h
#define mozilla_dom_CustomElementRegistry_h

#include "js/GCHashTable.h"
#include "js/TypeDecls.h"
#include "mozilla/Attributes.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/dom/BindingDeclarations.h"
#include "mozilla/dom/FunctionBinding.h"
#include "mozilla/dom/WebComponentsBinding.h"
#include "nsCycleCollectionParticipant.h"
#include "nsGenericHTMLElement.h"
#include "nsWrapperCache.h"

class nsDocument;

namespace mozilla {
namespace dom {

struct CustomElementData;
struct ElementDefinitionOptions;
class CallbackFunction;
class CustomElementReaction;
class Function;
class Promise;

struct LifecycleCallbackArgs
{
  nsString name;
  nsString oldValue;
  nsString newValue;
  nsString namespaceURI;
};

struct LifecycleAdoptedCallbackArgs
{
  nsCOMPtr<nsIDocument> mOldDocument;
  nsCOMPtr<nsIDocument> mNewDocument;
};

class CustomElementCallback
{
public:
  CustomElementCallback(Element* aThisObject,
                        nsIDocument::ElementCallbackType aCallbackType,
                        CallbackFunction* aCallback,
                        CustomElementData* aOwnerData);
  void Traverse(nsCycleCollectionTraversalCallback& aCb) const;
  void Call();
  void SetArgs(LifecycleCallbackArgs& aArgs)
  {
    MOZ_ASSERT(mType == nsIDocument::eAttributeChanged,
               "Arguments are only used by attribute changed callback.");
    mArgs = aArgs;
  }

  void SetAdoptedCallbackArgs(LifecycleAdoptedCallbackArgs& aAdoptedCallbackArgs)
  {
    MOZ_ASSERT(mType == nsIDocument::eAdopted,
      "Arguments are only used by adopted callback.");
    mAdoptedCallbackArgs = aAdoptedCallbackArgs;
  }

private:
  // The this value to use for invocation of the callback.
  RefPtr<Element> mThisObject;
  RefPtr<CallbackFunction> mCallback;
  // The type of callback (eCreated, eAttached, etc.)
  nsIDocument::ElementCallbackType mType;
  // Arguments to be passed to the callback,
  // used by the attribute changed callback.
  LifecycleCallbackArgs mArgs;
  LifecycleAdoptedCallbackArgs mAdoptedCallbackArgs;
  // CustomElementData that contains this callback in the
  // callback queue.
  CustomElementData* mOwnerData;
};

class CustomElementConstructor final : public CallbackFunction
{
public:
  explicit CustomElementConstructor(CallbackFunction* aOther)
    : CallbackFunction(aOther)
  {
    MOZ_ASSERT(JS::IsConstructor(mCallback));
  }

  already_AddRefed<Element> Construct(const char* aExecutionReason, ErrorResult& aRv);
};

// Each custom element has an associated callback queue and an element is
// being created flag.
struct CustomElementData
{
  NS_INLINE_DECL_REFCOUNTING(CustomElementData)

  // https://dom.spec.whatwg.org/#concept-element-custom-element-state
  // CustomElementData is only created on the element which is a custom element
  // or an upgrade candidate, so the state of an element without
  // CustomElementData is "uncustomized".
  enum class State {
    eUndefined,
    eFailed,
    eCustom
  };

  explicit CustomElementData(nsIAtom* aType);
  CustomElementData(nsIAtom* aType, State aState);
  // Custom element type, for <button is="x-button"> or <x-button>
  // this would be x-button.
  nsCOMPtr<nsIAtom> mType;
  // Element is being created flag as described in the custom elements spec.
  bool mElementIsBeingCreated;
  // Flag to determine if the created callback has been invoked, thus it
  // determines if other callbacks can be enqueued.
  bool mCreatedCallbackInvoked;
  // Custom element state as described in the custom element spec.
  State mState;
  // custom element reaction queue as described in the custom element spec.
  // There is 1 reaction in reaction queue, when 1) it becomes disconnected,
  // 2) it’s adopted into a new document, 3) its attributes are changed,
  // appended, removed, or replaced.
  // There are 3 reactions in reaction queue when doing upgrade operation,
  // e.g., create an element, insert a node.
  AutoTArray<UniquePtr<CustomElementReaction>, 3> mReactionQueue;

  void SetCustomElementDefinition(CustomElementDefinition* aDefinition);
  CustomElementDefinition* GetCustomElementDefinition();

  void Traverse(nsCycleCollectionTraversalCallback& aCb) const;
  void Unlink();

private:
  virtual ~CustomElementData() {}

  RefPtr<CustomElementDefinition> mCustomElementDefinition;
};

#define ALEADY_CONSTRUCTED_MARKER nullptr

// The required information for a custom element as defined in:
// https://html.spec.whatwg.org/multipage/scripting.html#custom-element-definition
struct CustomElementDefinition
{
  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_NATIVE_CLASS(CustomElementDefinition)
  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(CustomElementDefinition)

  CustomElementDefinition(nsIAtom* aType,
                          nsIAtom* aLocalName,
                          Function* aConstructor,
                          nsCOMArray<nsIAtom>&& aObservedAttributes,
                          JSObject* aPrototype,
                          mozilla::dom::LifecycleCallbacks* aCallbacks,
                          uint32_t aDocOrder);

  // The type (name) for this custom element, for <button is="x-foo"> or <x-foo>
  // this would be x-foo.
  nsCOMPtr<nsIAtom> mType;

  // The localname to (e.g. <button is=type> -- this would be button).
  nsCOMPtr<nsIAtom> mLocalName;

  // The custom element constructor.
  RefPtr<CustomElementConstructor> mConstructor;

  // The list of attributes that this custom element observes.
  nsCOMArray<nsIAtom> mObservedAttributes;

  // The prototype to use for new custom elements of this type.
  JS::Heap<JSObject *> mPrototype;

  // The lifecycle callbacks to call for this custom element.
  UniquePtr<mozilla::dom::LifecycleCallbacks> mCallbacks;

  // A construction stack. Use nullptr to represent an "already constructed marker".
  nsTArray<RefPtr<nsGenericHTMLElement>> mConstructionStack;

  // The document custom element order.
  uint32_t mDocOrder;

  bool IsCustomBuiltIn()
  {
    return mType != mLocalName;
  }

  bool IsInObservedAttributeList(nsIAtom* aName)
  {
    if (mObservedAttributes.IsEmpty()) {
      return false;
    }

    return mObservedAttributes.Contains(aName);
  }

private:
  ~CustomElementDefinition() {}
};

class CustomElementReaction
{
public:
  virtual ~CustomElementReaction() = default;
  virtual void Invoke(Element* aElement, ErrorResult& aRv) = 0;
  virtual void Traverse(nsCycleCollectionTraversalCallback& aCb) const
  {
  }

#if DEBUG
  bool IsUpgradeReaction()
  {
    return mIsUpgradeReaction;
  }

protected:
  bool mIsUpgradeReaction = false;
#endif
};

class CustomElementUpgradeReaction final : public CustomElementReaction
{
public:
  explicit CustomElementUpgradeReaction(CustomElementDefinition* aDefinition)
    : mDefinition(aDefinition)
  {
#if DEBUG
    mIsUpgradeReaction = true;
#endif
  }

private:
   virtual void Invoke(Element* aElement, ErrorResult& aRv) override;

   CustomElementDefinition* mDefinition;
};

class CustomElementCallbackReaction final : public CustomElementReaction
{
  public:
    explicit CustomElementCallbackReaction(UniquePtr<CustomElementCallback> aCustomElementCallback)
      : mCustomElementCallback(Move(aCustomElementCallback))
    {
    }

    virtual void Traverse(nsCycleCollectionTraversalCallback& aCb) const override
    {
      mCustomElementCallback->Traverse(aCb);
    }

  private:
    virtual void Invoke(Element* aElement, ErrorResult& aRv) override;
    UniquePtr<CustomElementCallback> mCustomElementCallback;
};

// https://html.spec.whatwg.org/multipage/scripting.html#custom-element-reactions-stack
class CustomElementReactionsStack
{
public:
  NS_INLINE_DECL_REFCOUNTING(CustomElementReactionsStack)

  CustomElementReactionsStack()
    : mIsBackupQueueProcessing(false)
  {
  }

  // Hold a strong reference of Element so that it does not get cycle collected
  // before the reactions in its reaction queue are invoked.
  // The element reaction queues are stored in CustomElementData.
  // We need to lookup ElementReactionQueueMap again to get relevant reaction queue.
  // The choice of 1 for the auto size here is based on gut feeling.
  typedef AutoTArray<RefPtr<Element>, 1> ElementQueue;

  /**
   * Enqueue a custom element upgrade reaction
   * https://html.spec.whatwg.org/multipage/scripting.html#enqueue-a-custom-element-upgrade-reaction
   */
  void EnqueueUpgradeReaction(Element* aElement,
                              CustomElementDefinition* aDefinition);

  /**
   * Enqueue a custom element callback reaction
   * https://html.spec.whatwg.org/multipage/scripting.html#enqueue-a-custom-element-callback-reaction
   */
  void EnqueueCallbackReaction(Element* aElement,
                               UniquePtr<CustomElementCallback> aCustomElementCallback);

  // [CEReactions] Before executing the algorithm's steps
  // Push a new element queue onto the custom element reactions stack.
  void CreateAndPushElementQueue();

  // [CEReactions] After executing the algorithm's steps
  // Pop the element queue from the custom element reactions stack,
  // and invoke custom element reactions in that queue.
  void PopAndInvokeElementQueue();

private:
  ~CustomElementReactionsStack() {};

  // The choice of 8 for the auto size here is based on gut feeling.
  AutoTArray<UniquePtr<ElementQueue>, 8> mReactionsStack;
  ElementQueue mBackupQueue;
  // https://html.spec.whatwg.org/#enqueue-an-element-on-the-appropriate-element-queue
  bool mIsBackupQueueProcessing;

  void InvokeBackupQueue();

  /**
   * Invoke custom element reactions
   * https://html.spec.whatwg.org/multipage/scripting.html#invoke-custom-element-reactions
   */
  void InvokeReactions(ElementQueue* aElementQueue, nsIGlobalObject* aGlobal);

  void Enqueue(Element* aElement, CustomElementReaction* aReaction);

private:
  class ProcessBackupQueueRunnable : public mozilla::Runnable {
    public:
      explicit ProcessBackupQueueRunnable(CustomElementReactionsStack* aReactionStack)
        : mReactionStack(aReactionStack)
      {
        MOZ_ASSERT(!mReactionStack->mIsBackupQueueProcessing,
                   "mIsBackupQueueProcessing should be initially false");
        mReactionStack->mIsBackupQueueProcessing = true;
      }

      NS_IMETHOD Run() override
      {
        mReactionStack->InvokeBackupQueue();
        mReactionStack->mIsBackupQueueProcessing = false;
        return NS_OK;
      }

    private:
      RefPtr<CustomElementReactionsStack> mReactionStack;
  };
};

class CustomElementRegistry final : public nsISupports,
                                    public nsWrapperCache
{
  // Allow nsDocument to access mCustomDefinitions and mCandidatesMap.
  friend class ::nsDocument;

public:
  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(CustomElementRegistry)

public:
  static bool IsCustomElementEnabled(JSContext* aCx = nullptr,
                                     JSObject* aObject = nullptr);

  explicit CustomElementRegistry(nsPIDOMWindowInner* aWindow);

  /**
   * Looking up a custom element definition.
   * https://html.spec.whatwg.org/#look-up-a-custom-element-definition
   */
  CustomElementDefinition* LookupCustomElementDefinition(
    const nsAString& aLocalName, const nsAString* aIs = nullptr) const;

  CustomElementDefinition* LookupCustomElementDefinition(
    JSContext* aCx, JSObject *aConstructor) const;

  /**
   * Enqueue created callback or register upgrade candidate for
   * newly created custom elements, possibly extending an existing type.
   * ex. <x-button>, <button is="x-button> (type extension)
   */
  void SetupCustomElement(Element* aElement, const nsAString* aTypeExtension);

  static void EnqueueLifecycleCallback(nsIDocument::ElementCallbackType aType,
                                       Element* aCustomElement,
                                       LifecycleCallbackArgs* aArgs,
                                       LifecycleAdoptedCallbackArgs* aAdoptedCallbackArgs,
                                       CustomElementDefinition* aDefinition);

  void GetCustomPrototype(nsIAtom* aAtom,
                          JS::MutableHandle<JSObject*> aPrototype);

  /**
   * Upgrade an element.
   * https://html.spec.whatwg.org/multipage/scripting.html#upgrades
   */
  static void Upgrade(Element* aElement, CustomElementDefinition* aDefinition, ErrorResult& aRv);

private:
  ~CustomElementRegistry();

  static UniquePtr<CustomElementCallback> CreateCustomElementCallback(
    nsIDocument::ElementCallbackType aType, Element* aCustomElement,
    LifecycleCallbackArgs* aArgs,
    LifecycleAdoptedCallbackArgs* aAdoptedCallbackArgs,
    CustomElementDefinition* aDefinition);

  /**
   * Registers an unresolved custom element that is a candidate for
   * upgrade when the definition is registered via registerElement.
   * |aTypeName| is the name of the custom element type, if it is not
   * provided, then element name is used. |aTypeName| should be provided
   * when registering a custom element that extends an existing
   * element. e.g. <button is="x-button">.
   */
  void RegisterUnresolvedElement(Element* aElement,
                                 nsIAtom* aTypeName = nullptr);

  void UpgradeCandidates(nsIAtom* aKey,
                         CustomElementDefinition* aDefinition,
                         ErrorResult& aRv);

  typedef nsRefPtrHashtable<nsISupportsHashKey, CustomElementDefinition>
    DefinitionMap;
  typedef nsClassHashtable<nsISupportsHashKey, nsTArray<nsWeakPtr>>
    CandidateMap;
  typedef JS::GCHashMap<JS::Heap<JSObject*>,
                        nsCOMPtr<nsIAtom>,
                        js::MovableCellHasher<JS::Heap<JSObject*>>,
                        js::SystemAllocPolicy> ConstructorMap;

  // Hashtable for custom element definitions in web components.
  // Custom prototypes are stored in the compartment where
  // registerElement was called.
  DefinitionMap mCustomDefinitions;

  // Hashtable for looking up definitions by using constructor as key.
  // Custom elements' name are stored here and we need to lookup
  // mCustomDefinitions again to get definitions.
  ConstructorMap mConstructors;

  typedef nsRefPtrHashtable<nsISupportsHashKey, Promise>
    WhenDefinedPromiseMap;
  WhenDefinedPromiseMap mWhenDefinedPromiseMap;

  // The "upgrade candidates map" from the web components spec. Maps from a
  // namespace id and local name to a list of elements to upgrade if that
  // element is registered as a custom element.
  CandidateMap mCandidatesMap;

  nsCOMPtr<nsPIDOMWindowInner> mWindow;

  // It is used to prevent reentrant invocations of element definition.
  bool mIsCustomDefinitionRunning;

private:
  class MOZ_RAII AutoSetRunningFlag final {
    public:
      explicit AutoSetRunningFlag(CustomElementRegistry* aRegistry)
        : mRegistry(aRegistry)
      {
        MOZ_ASSERT(!mRegistry->mIsCustomDefinitionRunning,
                   "IsCustomDefinitionRunning flag should be initially false");
        mRegistry->mIsCustomDefinitionRunning = true;
      }

      ~AutoSetRunningFlag() {
        mRegistry->mIsCustomDefinitionRunning = false;
      }

    private:
      CustomElementRegistry* mRegistry;
  };

public:
  nsISupports* GetParentObject() const;

  virtual JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;

  void Define(const nsAString& aName, Function& aFunctionConstructor,
              const ElementDefinitionOptions& aOptions, ErrorResult& aRv);

  void Get(JSContext* cx, const nsAString& name,
           JS::MutableHandle<JS::Value> aRetVal);

  already_AddRefed<Promise> WhenDefined(const nsAString& aName, ErrorResult& aRv);
};

class MOZ_RAII AutoCEReaction final {
  public:
    explicit AutoCEReaction(CustomElementReactionsStack* aReactionsStack)
      : mReactionsStack(aReactionsStack) {
      mReactionsStack->CreateAndPushElementQueue();
    }
    ~AutoCEReaction() {
      mReactionsStack->PopAndInvokeElementQueue();
    }
  private:
    RefPtr<CustomElementReactionsStack> mReactionsStack;
};

} // namespace dom
} // namespace mozilla


#endif // mozilla_dom_CustomElementRegistry_h