summaryrefslogtreecommitdiff
path: root/chromium/chrome/browser/resources/bookmark_manager/js/bmm/bookmark_list.js
blob: 089b77a70448aa673f88856568f61d8133d988f2 (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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
// Copyright (c) 2012 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.

// TODO(arv): Now that this is driven by a data model, implement a data model
//            that handles the loading and the events from the bookmark backend.

/**
 * @typedef {{childIds: Array<string>}}
 *
 * @see chrome/common/extensions/api/bookmarks.json
 */
var ReorderInfo;

/**
 * @typedef {{parentId: string,
 *            index: number,
 *            oldParentId: string,
 *            oldIndex: number}}
 *
 * @see chrome/common/extensions/api/bookmarks.json
 */
var MoveInfo;

cr.define('bmm', function() {
  'use strict';

  var List = cr.ui.List;
  var ListItem = cr.ui.ListItem;
  var ArrayDataModel = cr.ui.ArrayDataModel;
  var ContextMenuButton = cr.ui.ContextMenuButton;

  /**
   * Basic array data model for use with bookmarks.
   * @param {!Array<!BookmarkTreeNode>} items The bookmark items.
   * @constructor
   * @extends {ArrayDataModel}
   */
  function BookmarksArrayDataModel(items) {
    ArrayDataModel.call(this, items);
  }

  BookmarksArrayDataModel.prototype = {
    __proto__: ArrayDataModel.prototype,

    /**
     * Finds the index of the bookmark with the given ID.
     * @param {string} id The ID of the bookmark node to find.
     * @return {number} The index of the found node or -1 if not found.
     */
    findIndexById: function(id) {
      for (var i = 0; i < this.length; i++) {
        if (this.item(i).id == id)
          return i;
      }
      return -1;
    }
  };

  /**
   * Removes all children and appends a new child.
   * @param {!Node} parent The node to remove all children from.
   * @param {!Node} newChild The new child to append.
   */
  function replaceAllChildren(parent, newChild) {
    var n;
    while ((n = parent.lastChild)) {
      parent.removeChild(n);
    }
    parent.appendChild(newChild);
  }

  /**
   * Creates a new bookmark list.
   * @param {Object=} opt_propertyBag Optional properties.
   * @constructor
   * @extends {cr.ui.List}
   */
  var BookmarkList = cr.ui.define('list');

  BookmarkList.prototype = {
    __proto__: List.prototype,

    /** @override */
    decorate: function() {
      List.prototype.decorate.call(this);
      this.addEventListener('mousedown', this.handleMouseDown_);

      // HACK(arv): http://crbug.com/40902
      window.addEventListener('resize', this.redraw.bind(this));

      // We could add the ContextMenuButton in the BookmarkListItem but it slows
      // down redraws a lot so we do this on mouseovers instead.
      this.addEventListener('mouseover', this.handleMouseOver_.bind(this));

      bmm.list = this;
    },

    /**
     * @param {!BookmarkTreeNode} bookmarkNode
     * @override
     */
    createItem: function(bookmarkNode) {
      return new BookmarkListItem(bookmarkNode);
    },

    /** @private {string} */
    parentId_: '',

    /** @private {number} */
    loadCount_: 0,

    /**
     * Reloads the list from the bookmarks backend.
     */
    reload: function() {
      var parentId = this.parentId;

      var callback = this.handleBookmarkCallback_.bind(this);

      this.loadCount_++;

      if (!parentId)
        callback([]);
      else if (/^q=/.test(parentId))
        chrome.bookmarks.search(parentId.slice(2), callback);
      else
        chrome.bookmarks.getChildren(parentId, callback);
    },

    /**
     * Callback function for loading items.
     * @param {Array<!BookmarkTreeNode>} items The loaded items.
     * @private
     */
    handleBookmarkCallback_: function(items) {
      this.loadCount_--;
      if (this.loadCount_)
        return;

      if (!items) {
        // Failed to load bookmarks. Most likely due to the bookmark being
        // removed.
        cr.dispatchSimpleEvent(this, 'invalidId');
        return;
      }

      this.dataModel = new BookmarksArrayDataModel(items);

      this.fixWidth_();
      cr.dispatchSimpleEvent(this, 'load');

      // Use the same histogram configuration as UMA_HISTOGRAM_COUNTS_1000().
      chrome.metricsPrivate.recordValue({
        'metricName': 'Bookmarks.BookmarksInFolder',
        'type': chrome.metricsPrivate.MetricTypeType.HISTOGRAM_LOG,
        'min': 1,
        'max': 1000,
        'buckets': 50
      }, this.dataModel.length);
    },

    /**
     * The bookmark node that the list is currently displaying. If we are
     * currently displaying search this returns null.
     * @type {BookmarkTreeNode}
     */
    get bookmarkNode() {
      if (this.isSearch())
        return null;
      var treeItem = bmm.treeLookup[this.parentId];
      return treeItem && treeItem.bookmarkNode;
    },

    /**
     * @return {boolean} Whether we are currently showing search results.
     */
    isSearch: function() {
      return this.parentId_[0] == 'q';
    },

    /**
     * @return {boolean} Whether we are editing an ephemeral item.
     */
    hasEphemeral: function() {
      var dataModel = this.dataModel;
      for (var i = 0; i < dataModel.array_.length; i++) {
        if (dataModel.array_[i].id == 'new')
          return true;
      }
      return false;
    },

    /**
     * Handles mouseover on the list so that we can add the context menu button
     * lazily.
     * @private
     * @param {!Event} e The mouseover event object.
     */
    handleMouseOver_: function(e) {
      var el = e.target;
      while (el && el.parentNode != this) {
        el = el.parentNode;
      }

      if (el && el.parentNode == this &&
          !el.editing &&
          !(el.lastChild instanceof ContextMenuButton)) {
        el.appendChild(new ContextMenuButton);
      }
    },

    /**
     * Dispatches an urlClicked event which is used to open URLs in new
     * tabs etc.
     * @private
     * @param {string} url The URL that was clicked.
     * @param {!Event} originalEvent The original click event object.
     */
    dispatchUrlClickedEvent_: function(url, originalEvent) {
      var event = new Event('urlClicked', {bubbles: true});
      event.url = url;
      event.originalEvent = originalEvent;
      this.dispatchEvent(event);
    },

    /**
     * Handles mousedown events so that we can prevent the auto scroll as
     * necessary.
     * @private
     * @param {!Event} e The mousedown event object.
     */
    handleMouseDown_: function(e) {
      e = /** @type {!MouseEvent} */(e);
      if (e.button == 1) {
        // WebKit no longer fires click events for middle clicks so we manually
        // listen to mouse up to dispatch a click event.
        this.addEventListener('mouseup', this.handleMiddleMouseUp_);

        // When the user does a middle click we need to prevent the auto scroll
        // in case the user is trying to middle click to open a bookmark in a
        // background tab.
        // We do not do this in case the target is an input since middle click
        // is also paste on Linux and we don't want to break that.
        if (e.target.tagName != 'INPUT')
          e.preventDefault();
      }
    },

    /**
     * WebKit no longer dispatches click events for middle clicks so we need
     * to emulate it.
     * @private
     * @param {!Event} e The mouse up event object.
     */
    handleMiddleMouseUp_: function(e) {
      e = /** @type {!MouseEvent} */(e);
      this.removeEventListener('mouseup', this.handleMiddleMouseUp_);
      if (e.button == 1) {
        var el = e.target;
        while (el.parentNode != this) {
          el = el.parentNode;
        }
        var node = el.bookmarkNode;
        if (node && !bmm.isFolder(node))
          this.dispatchUrlClickedEvent_(node.url, e);
      }
      e.preventDefault();
    },

    // Bookmark model update callbacks
    handleBookmarkChanged: function(id, changeInfo) {
      var dataModel = this.dataModel;
      var index = dataModel.findIndexById(id);
      if (index != -1) {
        var bookmarkNode = this.dataModel.item(index);
        bookmarkNode.title = changeInfo.title;
        if ('url' in changeInfo)
          bookmarkNode.url = changeInfo['url'];

        dataModel.updateIndex(index);
      }
    },

    /**
     * @param {string} id
     * @param {ReorderInfo} reorderInfo
     */
    handleChildrenReordered: function(id, reorderInfo) {
      if (this.parentId == id) {
        // We create a new data model with updated items in the right order.
        var dataModel = this.dataModel;
        var items = {};
        for (var i = this.dataModel.length - 1; i >= 0; i--) {
          var bookmarkNode = dataModel.item(i);
          items[bookmarkNode.id] = bookmarkNode;
        }
        var newArray = [];
        for (var i = 0; i < reorderInfo.childIds.length; i++) {
          newArray[i] = items[reorderInfo.childIds[i]];
          newArray[i].index = i;
        }

        this.dataModel = new BookmarksArrayDataModel(newArray);
      }
    },

    handleCreated: function(id, bookmarkNode) {
      if (this.parentId == bookmarkNode.parentId)
        this.dataModel.splice(bookmarkNode.index, 0, bookmarkNode);
    },

    /**
     * @param {string} id
     * @param {MoveInfo} moveInfo
     */
    handleMoved: function(id, moveInfo) {
      if (moveInfo.parentId == this.parentId ||
          moveInfo.oldParentId == this.parentId) {

        var dataModel = this.dataModel;

        if (moveInfo.oldParentId == moveInfo.parentId) {
          // Reorder within this folder

          this.startBatchUpdates();

          var bookmarkNode = this.dataModel.item(moveInfo.oldIndex);
          this.dataModel.splice(moveInfo.oldIndex, 1);
          this.dataModel.splice(moveInfo.index, 0, bookmarkNode);

          this.endBatchUpdates();
        } else {
          if (moveInfo.oldParentId == this.parentId) {
            // Move out of this folder

            var index = dataModel.findIndexById(id);
            if (index != -1)
              dataModel.splice(index, 1);
          }

          if (moveInfo.parentId == this.parentId) {
            // Move to this folder
            var self = this;
            chrome.bookmarks.get(id, function(bookmarkNodes) {
              var bookmarkNode = bookmarkNodes[0];
              dataModel.splice(bookmarkNode.index, 0, bookmarkNode);
            });
          }
        }
      }
    },

    handleRemoved: function(id, removeInfo) {
      var dataModel = this.dataModel;
      var index = dataModel.findIndexById(id);
      if (index != -1)
        dataModel.splice(index, 1);
    },

    /**
     * Workaround for http://crbug.com/40902
     * @private
     */
    fixWidth_: function() {
      var list = bmm.list;
      if (this.loadCount_ || !list)
        return;

      // The width of the list is wrong after its content has changed.
      // Fortunately the reported offsetWidth is correct so we can detect the
      //incorrect width.
      if (list.offsetWidth != list.parentNode.clientWidth - list.offsetLeft) {
        // Set the width to the correct size. This causes the relayout.
        list.style.width = list.parentNode.clientWidth - list.offsetLeft + 'px';
        // Remove the temporary style.width in a timeout. Once the timer fires
        // the size should not change since we already fixed the width.
        window.setTimeout(function() {
          list.style.width = '';
        }, 0);
      }
    }
  };

  /**
   * The ID of the bookmark folder we are displaying.
   */
  cr.defineProperty(BookmarkList, 'parentId', cr.PropertyKind.JS,
                    function() {
                      this.reload();
                    });

  /**
   * The contextMenu property.
   */
  cr.ui.contextMenuHandler.addContextMenuProperty(BookmarkList);
  /** @type {cr.ui.Menu} */
  BookmarkList.prototype.contextMenu;

  /**
   * Creates a new bookmark list item.
   * @param {!BookmarkTreeNode} bookmarkNode The bookmark node this represents.
   * @constructor
   * @extends {cr.ui.ListItem}
   */
  function BookmarkListItem(bookmarkNode) {
    var el = cr.doc.createElement('div');
    el.bookmarkNode = bookmarkNode;
    BookmarkListItem.decorate(el);
    return el;
  }

  /**
   * Decorates an element as a bookmark list item.
   * @param {!HTMLElement} el The element to decorate.
   */
  BookmarkListItem.decorate = function(el) {
    el.__proto__ = BookmarkListItem.prototype;
    el.decorate();
  };

  BookmarkListItem.prototype = {
    __proto__: ListItem.prototype,

    /** @override */
    decorate: function() {
      ListItem.prototype.decorate.call(this);

      var bookmarkNode = this.bookmarkNode;

      this.draggable = true;

      var labelEl = this.ownerDocument.createElement('div');
      labelEl.className = 'label';
      var labelImgWrapper = this.ownerDocument.createElement('div');
      labelImgWrapper.className = 'label-img-wrapper';
      var labelImg = this.ownerDocument.createElement('div');
      var labelText = this.ownerDocument.createElement('div');
      labelText.className = 'label-text';
      labelText.textContent = bookmarkNode.title;

      var urlEl = this.ownerDocument.createElement('div');
      urlEl.className = 'url';

      if (bmm.isFolder(bookmarkNode)) {
        this.className = 'folder';
        // TODO(pkasting): Condense folder icon resources together.
        labelImg.style.content = cr.icon.getImage(
            cr.isMac ?
                'chrome://theme/IDR_BOOKMARK_BAR_FOLDER' :
                'chrome://theme/IDR_FOLDER_CLOSED');
      } else {
        labelImg.style.content = cr.icon.getFavicon(bookmarkNode.url);
        urlEl.textContent = bookmarkNode.url;
      }

      labelImgWrapper.appendChild(labelImg);
      labelEl.appendChild(labelImgWrapper);
      labelEl.appendChild(labelText);
      this.appendChild(labelEl);
      this.appendChild(urlEl);

      // Initially the ContextMenuButton was added here but it slowed down
      // rendering a lot so it is now added using mouseover.
    },

    /**
     * The ID of the bookmark folder we are currently showing or loading.
     * @type {string}
     */
    get bookmarkId() {
      return this.bookmarkNode.id;
    },

    /**
     * Whether the user is currently able to edit the list item.
     * @type {boolean}
     */
    get editing() {
      return this.hasAttribute('editing');
    },
    set editing(editing) {
      var oldEditing = this.editing;
      if (oldEditing == editing)
        return;

      var url = this.bookmarkNode.url;
      var title = this.bookmarkNode.title;
      var isFolder = bmm.isFolder(this.bookmarkNode);
      var listItem = this;
      var labelInput, urlInput;

      // Handles enter and escape which trigger reset and commit respectively.
      function handleKeydown(e) {
        // Make sure that the tree does not handle the key.
        e.stopPropagation();

        // Calling list.focus blurs the input which will stop editing the list
        // item.
        switch (e.key) {
          case 'Escape':  // Esc
            labelInput.value = title;
            if (!isFolder)
              urlInput.value = url;
            // fall through
            cr.dispatchSimpleEvent(listItem, 'canceledit', true);
          case 'Enter':
            if (listItem.parentNode)
              listItem.parentNode.focus();
            break;
          case 'Tab':  // Tab
            // urlInput is the last focusable element in the page.  If we
            // allowed Tab focus navigation and the page loses focus, we
            // couldn't give focus on urlInput programatically. So, we prevent
            // Tab focus navigation.
            if (document.activeElement == urlInput && !e.ctrlKey &&
                !e.metaKey && !e.shiftKey && !getValidURL(urlInput)) {
              e.preventDefault();
              urlInput.blur();
            }
            break;
        }
      }

      function getValidURL(input) {
        var originalValue = input.value;
        if (!originalValue)
          return null;
        if (input.validity.valid)
          return originalValue;
        // Blink does not do URL fix up so we manually test if prepending
        // 'http://' would make the URL valid.
        // https://bugs.webkit.org/show_bug.cgi?id=29235
        input.value = 'http://' + originalValue;
        if (input.validity.valid)
          return input.value;
        // still invalid
        input.value = originalValue;
        return null;
      }

      function handleBlur(e) {
        // When the blur event happens we do not know who is getting focus so we
        // delay this a bit since we want to know if the other input got focus
        // before deciding if we should exit edit mode.
        var doc = e.target.ownerDocument;
        window.setTimeout(function() {
          var activeElement = doc.hasFocus() && doc.activeElement;
          if (activeElement != urlInput && activeElement != labelInput) {
            listItem.editing = false;
          }
        }, 50);
      }

      var doc = this.ownerDocument;
      var labelTextEl = queryRequiredElement('.label-text', this);
      var urlEl = queryRequiredElement('.url', this);
      if (editing) {
        this.setAttribute('editing', '');
        this.draggable = false;

        labelInput = /** @type {HTMLElement} */(doc.createElement('input'));
        labelInput.placeholder =
            loadTimeData.getString('name_input_placeholder');
        replaceAllChildren(labelTextEl, labelInput);
        labelInput.value = title;

        if (!isFolder) {
          urlInput = /** @type {HTMLElement} */(doc.createElement('input'));
          urlInput.type = 'url';
          urlInput.required = true;
          urlInput.placeholder =
              loadTimeData.getString('url_input_placeholder');

          // We also need a name for the input for the CSS to work.
          urlInput.name = '-url-input-' + cr.createUid();
          replaceAllChildren(assert(urlEl), urlInput);
          urlInput.value = url;
        }

        var stopPropagation = function(e) {
          e.stopPropagation();
        };

        var eventsToStop =
            ['mousedown', 'mouseup', 'contextmenu', 'dblclick', 'paste'];
        eventsToStop.forEach(function(type) {
          labelInput.addEventListener(type, stopPropagation);
        });
        labelInput.addEventListener('keydown', handleKeydown);
        labelInput.addEventListener('blur', handleBlur);
        cr.ui.limitInputWidth(labelInput, this, 100, 0.5);
        labelInput.focus();
        labelInput.select();

        if (!isFolder) {
          eventsToStop.forEach(function(type) {
            urlInput.addEventListener(type, stopPropagation);
          });
          urlInput.addEventListener('keydown', handleKeydown);
          urlInput.addEventListener('blur', handleBlur);
          cr.ui.limitInputWidth(urlInput, this, 200, 0.5);
        }

      } else {
        // Check that we have a valid URL and if not we do not change the
        // editing mode.
        if (!isFolder) {
          var urlInput = this.querySelector('.url input');
          var newUrl = urlInput.value;
          if (!newUrl) {
            cr.dispatchSimpleEvent(this, 'canceledit', true);
            return;
          }

          newUrl = getValidURL(urlInput);
          if (!newUrl) {
            // In case the item was removed before getting here we should
            // not alert.
            if (listItem.parentNode) {
              // Select the item again.
              var dataModel = this.parentNode.dataModel;
              var index = dataModel.indexOf(this.bookmarkNode);
              var sm = this.parentNode.selectionModel;
              sm.selectedIndex = sm.leadIndex = sm.anchorIndex = index;

              alert(loadTimeData.getString('invalid_url'));
            }
            urlInput.focus();
            urlInput.select();
            return;
          }
          urlEl.textContent = this.bookmarkNode.url = newUrl;
        }

        this.removeAttribute('editing');
        this.draggable = true;

        labelInput = this.querySelector('.label input');
        var newLabel = labelInput.value;
        labelTextEl.textContent = this.bookmarkNode.title = newLabel;

        if (isFolder) {
          if (newLabel != title) {
            cr.dispatchSimpleEvent(this, 'rename', true);
          }
        } else if (newLabel != title || newUrl != url) {
          cr.dispatchSimpleEvent(this, 'edit', true);
        }
      }
    }
  };

  return {
    BookmarkList: BookmarkList,
    list: /** @type {Element} */(null),  // Set when decorated.
  };
});