summaryrefslogtreecommitdiffstats
path: root/devtools/server/actors/resources/css-registered-properties.js
blob: 7ac2871a11feda9eff7b26d0daa30a271f426f4e (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
/* 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/. */

"use strict";

const {
  TYPES: { CSS_REGISTERED_PROPERTIES },
} = require("resource://devtools/server/actors/resources/index.js");

/**
 * @typedef InspectorCSSPropertyDefinition (see InspectorUtils.webidl)
 * @type {object}
 * @property {string} name
 * @property {string} syntax
 * @property {boolean} inherits
 * @property {string} initialValue
 * @property {boolean} fromJS - true if property was registered via CSS.registerProperty
 */

class CSSRegisteredPropertiesWatcher {
  #abortController;
  #onAvailable;
  #onUpdated;
  #onDestroyed;
  #registeredPropertiesCache = new Map();
  #styleSheetsManager;
  #targetActor;

  /**
   * Start watching for all registered CSS properties (@property/CSS.registerProperty)
   * related to a given Target Actor.
   *
   * @param TargetActor targetActor
   *        The target actor from which we should observe css changes.
   * @param Object options
   *        Dictionary object with following attributes:
   *        - onAvailable: mandatory function
   *        - onUpdated: mandatory function
   *        - onDestroyed: mandatory function
   *          This will be called for each resource.
   */
  async watch(targetActor, { onAvailable, onUpdated, onDestroyed }) {
    this.#targetActor = targetActor;
    this.#onAvailable = onAvailable;
    this.#onUpdated = onUpdated;
    this.#onDestroyed = onDestroyed;

    // Notify about existing properties
    const registeredProperties = this.#getRegisteredProperties();
    for (const registeredProperty of registeredProperties) {
      this.#registeredPropertiesCache.set(
        registeredProperty.name,
        registeredProperty
      );
    }

    this.#notifyResourcesAvailable(registeredProperties);

    // Listen for new properties being registered via CSS.registerProperty
    this.#abortController = new AbortController();
    const { signal } = this.#abortController;
    this.#targetActor.chromeEventHandler.addEventListener(
      "csscustompropertyregistered",
      this.#onCssCustomPropertyRegistered,
      { capture: true, signal }
    );

    // Watch for stylesheets being added/modified or destroyed, but don't handle existing
    // stylesheets, as we already have the existing properties from this.#getRegisteredProperties.
    this.#styleSheetsManager = targetActor.getStyleSheetsManager();
    await this.#styleSheetsManager.watch({
      onAvailable: this.#refreshCacheAndNotify,
      onUpdated: this.#refreshCacheAndNotify,
      onDestroyed: this.#refreshCacheAndNotify,
      ignoreExisting: true,
    });
  }

  /**
   * Get all the registered properties for the target actor document.
   *
   * @returns Array<InspectorCSSPropertyDefinition>
   */
  #getRegisteredProperties() {
    return InspectorUtils.getCSSRegisteredProperties(
      this.#targetActor.window.document
    );
  }

  /**
   * Compute a resourceId from a given property definition
   *
   * @param {InspectorCSSPropertyDefinition} propertyDefinition
   * @returns string
   */
  #getRegisteredPropertyResourceId(propertyDefinition) {
    return `${this.#targetActor.actorID}:css-registered-property:${
      propertyDefinition.name
    }`;
  }

  /**
   * Called when a stylesheet is added, removed or modified.
   * This will retrieve the registered properties at this very moment, and notify
   * about new, updated and removed registered properties.
   */
  #refreshCacheAndNotify = async () => {
    const registeredProperties = this.#getRegisteredProperties();
    const existingPropertiesNames = new Set(
      this.#registeredPropertiesCache.keys()
    );

    const added = [];
    const updated = [];
    const removed = [];

    for (const registeredProperty of registeredProperties) {
      // If the property isn't in the cache already, this is a new one.
      if (!this.#registeredPropertiesCache.has(registeredProperty.name)) {
        added.push(registeredProperty);
        this.#registeredPropertiesCache.set(
          registeredProperty.name,
          registeredProperty
        );
        continue;
      }

      // Removing existing property from the Set so we can then later get the properties
      // that don't exist anymore.
      existingPropertiesNames.delete(registeredProperty.name);

      // The property already existed, so we need to check if its definition was modified
      const cachedRegisteredProperty = this.#registeredPropertiesCache.get(
        registeredProperty.name
      );

      const resourceUpdates = {};
      let wasUpdated = false;
      if (registeredProperty.syntax !== cachedRegisteredProperty.syntax) {
        resourceUpdates.syntax = registeredProperty.syntax;
        wasUpdated = true;
      }
      if (registeredProperty.inherits !== cachedRegisteredProperty.inherits) {
        resourceUpdates.inherits = registeredProperty.inherits;
        wasUpdated = true;
      }
      if (
        registeredProperty.initialValue !==
        cachedRegisteredProperty.initialValue
      ) {
        resourceUpdates.initialValue = registeredProperty.initialValue;
        wasUpdated = true;
      }

      if (wasUpdated === true) {
        updated.push({
          registeredProperty,
          resourceUpdates,
        });
        this.#registeredPropertiesCache.set(
          registeredProperty.name,
          registeredProperty
        );
      }
    }

    // If there are items left in the Set, it means they weren't processed in the for loop
    // before, meaning they don't exist anymore.
    for (const registeredPropertyName of existingPropertiesNames) {
      removed.push(this.#registeredPropertiesCache.get(registeredPropertyName));
      this.#registeredPropertiesCache.delete(registeredPropertyName);
    }

    this.#notifyResourcesAvailable(added);
    this.#notifyResourcesUpdated(updated);
    this.#notifyResourcesDestroyed(removed);
  };

  /**
   * csscustompropertyregistered event listener callback (fired when a property
   * is registered via CSS.registerProperty).
   *
   * @param {CSSCustomPropertyRegisteredEvent} event
   */
  #onCssCustomPropertyRegistered = event => {
    // Ignore event if property was registered from a global different from the target global.
    if (
      this.#targetActor.ignoreSubFrames &&
      event.target.ownerGlobal !== this.#targetActor.window
    ) {
      return;
    }

    const registeredProperty = event.propertyDefinition;
    this.#registeredPropertiesCache.set(
      registeredProperty.name,
      registeredProperty
    );
    this.#notifyResourcesAvailable([registeredProperty]);
  };

  /**
   * @param {Array<InspectorCSSPropertyDefinition>} registeredProperties
   */
  #notifyResourcesAvailable = registeredProperties => {
    if (!registeredProperties.length) {
      return;
    }

    for (const registeredProperty of registeredProperties) {
      registeredProperty.resourceId =
        this.#getRegisteredPropertyResourceId(registeredProperty);
      registeredProperty.resourceType = CSS_REGISTERED_PROPERTIES;
    }
    this.#onAvailable(registeredProperties);
  };

  /**
   * @param {Array<Object>} updates: Array of update object, which have the following properties:
   *        - {InspectorCSSPropertyDefinition} registeredProperty: The property definition
   *                                            of the updated property
   *        - {Object} resourceUpdates: An object containing all the fields that are
   *                                    modified for the registered property.
   */
  #notifyResourcesUpdated = updates => {
    if (!updates.length) {
      return;
    }

    for (const update of updates) {
      update.resourceId = this.#getRegisteredPropertyResourceId(
        update.registeredProperty
      );
      update.resourceType = CSS_REGISTERED_PROPERTIES;
      // We don't need to send the property definition
      delete update.registeredProperty;
    }

    this.#onUpdated(updates);
  };

  /**
   * @param {Array<InspectorCSSPropertyDefinition>} registeredProperties
   */
  #notifyResourcesDestroyed = registeredProperties => {
    if (!registeredProperties.length) {
      return;
    }

    this.#onDestroyed(
      registeredProperties.map(registeredProperty => ({
        resourceType: CSS_REGISTERED_PROPERTIES,
        resourceId: this.#getRegisteredPropertyResourceId(registeredProperty),
      }))
    );
  };

  destroy() {
    this.#styleSheetsManager.unwatch({
      onAvailable: this.#refreshCacheAndNotify,
      onUpdated: this.#refreshCacheAndNotify,
      onDestroyed: this.#refreshCacheAndNotify,
    });

    this.#abortController.abort();
  }
}

module.exports = CSSRegisteredPropertiesWatcher;