summaryrefslogtreecommitdiffstats
path: root/comm/mail/base/content/widgets/customizable-toolbar.js
blob: 350e814716b6a19db4737707121f48526214d9cf (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
/* 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";

/* globals MozXULElement */

// Wrap in a block to prevent leaking to window scope.
{
  /**
   * Extends the built-in `toolbar` element to allow it to be customized.
   *
   * @augments {MozXULElement}
   */
  class CustomizableToolbar extends MozXULElement {
    connectedCallback() {
      if (this.delayConnectedCallback() || this._hasConnected) {
        return;
      }
      this._hasConnected = true;

      this._toolbox = null;
      this._newElementCount = 0;

      // Search for the toolbox palette in the toolbar binding because
      // toolbars are constructed first.
      let toolbox = this.toolbox;
      if (!toolbox) {
        return;
      }

      if (!toolbox.palette) {
        // Look to see if there is a toolbarpalette.
        let node = toolbox.firstElementChild;
        while (node) {
          if (node.localName == "toolbarpalette") {
            break;
          }
          node = node.nextElementSibling;
        }

        if (!node) {
          return;
        }

        // Hold on to the palette but remove it from the document.
        toolbox.palette = node;
        toolbox.removeChild(node);
      }

      // Build up our contents from the palette.
      let currentSet =
        this.getAttribute("currentset") || this.getAttribute("defaultset");

      if (currentSet) {
        this.currentSet = currentSet;
      }
    }

    /**
     * Get the toolbox element connected to this toolbar.
     *
     * @returns {Element?} The toolbox element or null.
     */
    get toolbox() {
      if (this._toolbox) {
        return this._toolbox;
      }

      let toolboxId = this.getAttribute("toolboxid");
      if (toolboxId) {
        let toolbox = document.getElementById(toolboxId);
        if (!toolbox) {
          let tbName = this.hasAttribute("toolbarname")
            ? ` (${this.getAttribute("toolbarname")})`
            : "";

          throw new Error(
            `toolbar ID ${this.id}${tbName}: toolboxid attribute '${toolboxId}' points to a toolbox that doesn't exist`
          );
        }
        this._toolbox = toolbox;
        return this._toolbox;
      }

      this._toolbox =
        this.parentNode && this.parentNode.localName == "toolbox"
          ? this.parentNode
          : null;

      return this._toolbox;
    }

    /**
     * Sets the current set of items in the toolbar.
     *
     * @param {string} val - Comma-separated list of IDs or "__empty".
     * @returns {string} Comma-separated list of IDs or "__empty".
     */
    set currentSet(val) {
      if (val == this.currentSet) {
        return;
      }

      // Build a cache of items in the toolbarpalette.
      let palette = this.toolbox ? this.toolbox.palette : null;
      let paletteChildren = palette ? palette.children : [];

      let paletteItems = {};

      for (let item of paletteChildren) {
        paletteItems[item.id] = item;
      }

      let ids = val == "__empty" ? [] : val.split(",");
      let children = this.children;
      let nodeidx = 0;
      let added = {};

      // Iterate over the ids to use on the toolbar.
      for (let id of ids) {
        // Iterate over the existing nodes on the toolbar. nodeidx is the
        // spot where we want to insert items.
        let found = false;
        for (let i = nodeidx; i < children.length; i++) {
          let curNode = children[i];
          if (this._idFromNode(curNode) == id) {
            // The node already exists. If i equals nodeidx, we haven't
            // iterated yet, so the item is already in the right position.
            // Otherwise, insert it here.
            if (i != nodeidx) {
              this.insertBefore(curNode, children[nodeidx]);
            }

            added[curNode.id] = true;
            nodeidx++;
            found = true;
            break;
          }
        }
        if (found) {
          // Move on to the next id.
          continue;
        }

        // The node isn't already on the toolbar, so add a new one.
        let nodeToAdd = paletteItems[id] || this._getToolbarItem(id);
        if (nodeToAdd && !(nodeToAdd.id in added)) {
          added[nodeToAdd.id] = true;
          this.insertBefore(nodeToAdd, children[nodeidx] || null);
          nodeToAdd.setAttribute("removable", "true");
          nodeidx++;
        }
      }

      // Remove any leftover removable nodes.
      for (let i = children.length - 1; i >= nodeidx; i--) {
        let curNode = children[i];

        let curNodeId = this._idFromNode(curNode);
        // Skip over fixed items.
        if (curNodeId && curNode.getAttribute("removable") == "true") {
          if (palette) {
            palette.appendChild(curNode);
          } else {
            this.removeChild(curNode);
          }
        }
      }
    }

    /**
     * Gets the current set of items in the toolbar.
     *
     * @returns {string} Comma-separated list of IDs or "__empty".
     */
    get currentSet() {
      let node = this.firstElementChild;
      let currentSet = [];
      while (node) {
        let id = this._idFromNode(node);
        if (id) {
          currentSet.push(id);
        }
        node = node.nextElementSibling;
      }

      return currentSet.join(",") || "__empty";
    }

    /**
     * Return the ID for a given toolbar item node, with special handling for
     * some cases.
     *
     * @param {Element} node - Return the ID of this node.
     * @returns {string} The ID of the node.
     */
    _idFromNode(node) {
      if (node.getAttribute("skipintoolbarset") == "true") {
        return "";
      }
      const specialItems = {
        toolbarseparator: "separator",
        toolbarspring: "spring",
        toolbarspacer: "spacer",
      };
      return specialItems[node.localName] || node.id;
    }

    /**
     * Returns a toolbar item based on the given ID.
     *
     * @param {string} id - The ID for the new toolbar item.
     * @returns {Element?} The toolbar item corresponding to the ID, or null.
     */
    _getToolbarItem(id) {
      // Handle special cases.
      if (["separator", "spring", "spacer"].includes(id)) {
        let newItem = document.createXULElement("toolbar" + id);
        // Due to timers resolution Date.now() can be the same for
        // elements created in small timeframes.  So ids are
        // differentiated through a unique count suffix.
        newItem.id = id + Date.now() + ++this._newElementCount;
        if (id == "spring") {
          newItem.flex = 1;
        }
        return newItem;
      }

      let toolbox = this.toolbox;
      if (!toolbox) {
        return null;
      }

      // Look for an item with the same id, as the item may be
      // in a different toolbar.
      let item = document.getElementById(id);
      if (
        item &&
        item.parentNode &&
        item.parentNode.localName == "toolbar" &&
        item.parentNode.toolbox == toolbox
      ) {
        return item;
      }

      if (toolbox.palette) {
        // Attempt to locate an item with a matching ID within the palette.
        let paletteItem = toolbox.palette.firstElementChild;
        while (paletteItem) {
          if (paletteItem.id == id) {
            return paletteItem;
          }
          paletteItem = paletteItem.nextElementSibling;
        }
      }
      return null;
    }

    /**
     * Insert an item into the toolbar.
     *
     * @param {string} id - The ID of the item to insert.
     * @param {Element?} beforeElt - Optional element to insert the item before.
     * @param {Element?} wrapper - Optional wrapper element.
     * @returns {Element} The inserted item.
     */
    insertItem(id, beforeElt, wrapper) {
      let newItem = this._getToolbarItem(id);
      if (!newItem) {
        return null;
      }

      let insertItem = newItem;
      // Make sure added items are removable.
      newItem.setAttribute("removable", "true");

      // Wrap the item in another node if so inclined.
      if (wrapper) {
        wrapper.appendChild(newItem);
        insertItem = wrapper;
      }

      // Insert the palette item into the toolbar.
      if (beforeElt) {
        this.insertBefore(insertItem, beforeElt);
      } else {
        this.appendChild(insertItem);
      }
      return newItem;
    }

    /**
     * Determine whether the current set of toolbar items has custom
     * interactive items or not.
     *
     * @param {string} currentSet - Comma-separated list of IDs or "__empty".
     * @returns {boolean} Whether the current set has custom interactive items.
     */
    hasCustomInteractiveItems(currentSet) {
      if (currentSet == "__empty") {
        return false;
      }

      let defaultOrNoninteractive = (this.getAttribute("defaultset") || "")
        .split(",")
        .concat(["separator", "spacer", "spring"]);

      return currentSet
        .split(",")
        .some(item => !defaultOrNoninteractive.includes(item));
    }
  }

  customElements.define("customizable-toolbar", CustomizableToolbar, {
    extends: "toolbar",
  });
}