summaryrefslogtreecommitdiffstats
path: root/browser/components/places/tests/browser/browser_bookmarksProperties.js
blob: c493a21a6288d7a1394a21f8a335bf8f1a985933 (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
/* 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/. */

/**
 * Tests the bookmarks Properties dialog.
 */

// DOM ids of Places sidebar trees.
const SIDEBAR_HISTORY_TREE_ID = "historyTree";
const SIDEBAR_BOOKMARKS_TREE_ID = "bookmarks-view";

const SIDEBAR_HISTORY_ID = "viewHistorySidebar";
const SIDEBAR_BOOKMARKS_ID = "viewBookmarksSidebar";

// For history sidebar.
const SIDEBAR_HISTORY_BYLASTVISITED_VIEW = "bylastvisited";
const SIDEBAR_HISTORY_BYMOSTVISITED_VIEW = "byvisited";
const SIDEBAR_HISTORY_BYDATE_VIEW = "byday";
const SIDEBAR_HISTORY_BYSITE_VIEW = "bysite";
const SIDEBAR_HISTORY_BYDATEANDSITE_VIEW = "bydateandsite";

// Action to execute on the current node.
const ACTION_EDIT = 0;
const ACTION_ADD = 1;

// If action is ACTION_ADD, set type to one of those, to define what do you
// want to create.
const TYPE_FOLDER = 0;
const TYPE_BOOKMARK = 1;

const TEST_URL = "http://www.example.com/";

const DIALOG_URL = "chrome://browser/content/places/bookmarkProperties.xhtml";

function add_bookmark(url) {
  return PlacesUtils.bookmarks.insert({
    parentGuid: PlacesUtils.bookmarks.unfiledGuid,
    url,
    title: `bookmark/${url}`,
  });
}

// Each test is an obj w/ a desc property and run method.
var gTests = [];

// ------------------------------------------------------------------------------
// Bug 462662 - Pressing Enter to select tag from autocomplete closes bookmarks properties dialog

gTests.push({
  desc: "Bug 462662 - Pressing Enter to select tag from autocomplete closes bookmarks properties dialog",
  sidebar: SIDEBAR_BOOKMARKS_ID,
  action: ACTION_EDIT,
  itemType: null,
  window: null,
  _bookmark: null,
  _cleanShutdown: false,

  async setup() {
    // Add a bookmark in unsorted bookmarks folder.
    this._bookmark = await add_bookmark(TEST_URL);
    Assert.ok(this._bookmark, "Correctly added a bookmark");

    // Add a tag to this bookmark.
    PlacesUtils.tagging.tagURI(Services.io.newURI(TEST_URL), ["testTag"]);
    var tags = PlacesUtils.tagging.getTagsForURI(Services.io.newURI(TEST_URL));
    Assert.equal(tags[0], "testTag", "Correctly added a tag");
  },

  selectNode(tree) {
    tree.selectItems([PlacesUtils.bookmarks.unfiledGuid]);
    PlacesUtils.asContainer(tree.selectedNode).containerOpen = true;
    tree.selectItems([this._bookmark.guid]);
    Assert.equal(
      tree.selectedNode.bookmarkGuid,
      this._bookmark.guid,
      "Bookmark has been selected"
    );
  },

  async run() {
    // open tags autocomplete and press enter
    var tagsField = this.window.document.getElementById(
      "editBMPanel_tagsField"
    );
    var self = this;

    let unloadPromise = new Promise(resolve => {
      this.window.addEventListener(
        "unload",
        function (event) {
          tagsField.popup.removeEventListener(
            "popuphidden",
            popupListener,
            true
          );
          Assert.ok(
            self._cleanShutdown,
            "Dialog window should not be closed by pressing Enter on the autocomplete popup"
          );
          executeSoon(function () {
            resolve();
          });
        },
        { capture: true, once: true }
      );
    });

    var popupListener = {
      handleEvent(aEvent) {
        switch (aEvent.type) {
          case "popuphidden":
            // Everything worked fine, we can stop observing the window.
            self._cleanShutdown = true;
            self.window.document
              .getElementById("bookmarkpropertiesdialog")
              .cancelDialog();
            break;
          case "popupshown":
            tagsField.popup.removeEventListener("popupshown", this, true);
            // In case this test fails the window will close, the test will fail
            // since we didn't set _cleanShutdown.
            let richlistbox = tagsField.popup.richlistbox;
            // Focus and select first result.
            Assert.equal(
              richlistbox.itemCount,
              1,
              "We have 1 autocomplete result"
            );
            tagsField.popup.selectedIndex = 0;
            Assert.equal(
              richlistbox.selectedItems.length,
              1,
              "We have selected a tag from the autocomplete popup"
            );
            info("About to focus the autocomplete results");
            richlistbox.focus();
            EventUtils.synthesizeKey("VK_RETURN", {}, self.window);
            break;
          default:
            Assert.ok(false, "unknown event: " + aEvent.type);
        }
      },
    };
    tagsField.popup.addEventListener("popupshown", popupListener, true);
    tagsField.popup.addEventListener("popuphidden", popupListener, true);

    // Open tags autocomplete popup.
    info("About to focus the tagsField");
    executeSoon(() => {
      tagsField.focus();
      tagsField.value = "";
      EventUtils.synthesizeKey("t", {}, this.window);
    });
    await unloadPromise;
  },

  finish() {
    SidebarUI.hide();
  },

  async cleanup() {
    // Check tags have not changed.
    var tags = PlacesUtils.tagging.getTagsForURI(Services.io.newURI(TEST_URL));
    Assert.equal(tags[0], "testTag", "Tag on node has not changed");

    // Cleanup.
    PlacesUtils.tagging.untagURI(Services.io.newURI(TEST_URL), ["testTag"]);
    await PlacesUtils.bookmarks.remove(this._bookmark);
    let bm = await PlacesUtils.bookmarks.fetch(this._bookmark.guid);
    Assert.ok(!bm, "should have been removed");
  },
});

// ------------------------------------------------------------------------------
// Bug 476020 - Pressing Esc while having the tag autocomplete open closes the bookmarks panel

gTests.push({
  desc: "Bug 476020 - Pressing Esc while having the tag autocomplete open closes the bookmarks panel",
  sidebar: SIDEBAR_BOOKMARKS_ID,
  action: ACTION_EDIT,
  itemType: null,
  window: null,
  _bookmark: null,
  _cleanShutdown: false,

  async setup() {
    // Add a bookmark in unsorted bookmarks folder.
    this._bookmark = await add_bookmark(TEST_URL);
    Assert.ok(this._bookmark, "Correctly added a bookmark");

    // Add a tag to this bookmark.
    PlacesUtils.tagging.tagURI(Services.io.newURI(TEST_URL), ["testTag"]);
    var tags = PlacesUtils.tagging.getTagsForURI(Services.io.newURI(TEST_URL));
    Assert.equal(tags[0], "testTag", "Correctly added a tag");
  },

  selectNode(tree) {
    tree.selectItems([PlacesUtils.bookmarks.unfiledGuid]);
    PlacesUtils.asContainer(tree.selectedNode).containerOpen = true;
    tree.selectItems([this._bookmark.guid]);
    Assert.equal(
      tree.selectedNode.bookmarkGuid,
      this._bookmark.guid,
      "Bookmark has been selected"
    );
  },

  async run() {
    // open tags autocomplete and press enter
    var tagsField = this.window.document.getElementById(
      "editBMPanel_tagsField"
    );
    var self = this;

    let hiddenPromise = new Promise(resolve => {
      this.window.addEventListener(
        "unload",
        function (event) {
          tagsField.popup.removeEventListener(
            "popuphidden",
            popupListener,
            true
          );
          Assert.ok(
            self._cleanShutdown,
            "Dialog window should not be closed by pressing Escape on the autocomplete popup"
          );
          executeSoon(function () {
            resolve();
          });
        },
        { capture: true, once: true }
      );
    });

    var popupListener = {
      handleEvent(aEvent) {
        switch (aEvent.type) {
          case "popuphidden":
            // Everything worked fine.
            self._cleanShutdown = true;
            self.window.document
              .getElementById("bookmarkpropertiesdialog")
              .cancelDialog();
            break;
          case "popupshown":
            tagsField.popup.removeEventListener("popupshown", this, true);
            // In case this test fails the window will close, the test will fail
            // since we didn't set _cleanShutdown.
            let richlistbox = tagsField.popup.richlistbox;
            // Focus and select first result.
            Assert.equal(
              richlistbox.itemCount,
              1,
              "We have 1 autocomplete result"
            );
            tagsField.popup.selectedIndex = 0;
            Assert.equal(
              richlistbox.selectedItems.length,
              1,
              "We have selected a tag from the autocomplete popup"
            );
            info("About to focus the autocomplete results");
            richlistbox.focus();
            EventUtils.synthesizeKey("VK_ESCAPE", {}, self.window);
            break;
          default:
            Assert.ok(false, "unknown event: " + aEvent.type);
        }
      },
    };
    tagsField.popup.addEventListener("popupshown", popupListener, true);
    tagsField.popup.addEventListener("popuphidden", popupListener, true);

    // Open tags autocomplete popup.
    info("About to focus the tagsField");
    tagsField.focus();
    tagsField.value = "";
    EventUtils.synthesizeKey("t", {}, this.window);
    await hiddenPromise;
  },

  finish() {
    SidebarUI.hide();
  },

  async cleanup() {
    // Check tags have not changed.
    var tags = PlacesUtils.tagging.getTagsForURI(Services.io.newURI(TEST_URL));
    Assert.equal(tags[0], "testTag", "Tag on node has not changed");

    // Cleanup.
    PlacesUtils.tagging.untagURI(Services.io.newURI(TEST_URL), ["testTag"]);
    await PlacesUtils.bookmarks.remove(this._bookmark);
    let bm = await PlacesUtils.bookmarks.fetch(this._bookmark.guid);
    Assert.ok(!bm, "should have been removed");
  },
});

// ------------------------------------------------------------------------------
//  Bug 491269 - Test that editing folder name in bookmarks properties dialog does not accept the dialog

gTests.push({
  desc: `Bug 491269 - Test that editing folder name in bookmarks properties dialog does not accept the dialog`,
  sidebar: SIDEBAR_HISTORY_ID,
  dialogUrl: DIALOG_URL,
  action: ACTION_ADD,
  historyView: SIDEBAR_HISTORY_BYLASTVISITED_VIEW,
  window: null,

  async setup() {
    // Add a visit.
    await PlacesTestUtils.addVisits(TEST_URL);
  },

  selectNode(tree) {
    var visitNode = tree.view.nodeForTreeIndex(0);
    tree.selectNode(visitNode);
    Assert.equal(
      tree.selectedNode.uri,
      TEST_URL,
      "The correct visit has been selected"
    );
    Assert.equal(
      tree.selectedNode.itemId,
      -1,
      "The selected node is not bookmarked"
    );
  },

  async run() {
    // Open folder selector.
    var foldersExpander = this.window.document.getElementById(
      "editBMPanel_foldersExpander"
    );
    var folderTree = this.window.gEditItemOverlay._folderTree;
    var self = this;

    let unloadPromise = new Promise(resolve => {
      this.window.addEventListener(
        "unload",
        event => {
          Assert.ok(
            self._cleanShutdown,
            "Dialog window should not be closed by pressing ESC in folder name textbox"
          );
          executeSoon(() => {
            resolve();
          });
        },
        { capture: true, once: true }
      );
    });

    folderTree.addEventListener(
      "DOMAttrModified",
      function onDOMAttrModified(event) {
        if (event.attrName != "place") {
          return;
        }
        folderTree.removeEventListener("DOMAttrModified", onDOMAttrModified);
        executeSoon(async function () {
          // Create a new folder.
          var newFolderButton = self.window.document.getElementById(
            "editBMPanel_newFolderButton"
          );
          newFolderButton.doCommand();

          // Wait for the folder to be created and for editing to start.
          await TestUtils.waitForCondition(
            () => folderTree.hasAttribute("editing"),
            "We are editing new folder name in folder tree"
          );

          // Press Escape to discard editing new folder name.
          EventUtils.synthesizeKey("VK_ESCAPE", {}, self.window);
          Assert.ok(
            !folderTree.hasAttribute("editing"),
            "We have finished editing folder name in folder tree"
          );

          self._cleanShutdown = true;

          self.window.document
            .getElementById("bookmarkpropertiesdialog")
            .cancelDialog();
        });
      }
    );
    foldersExpander.doCommand();
    await unloadPromise;
  },

  finish() {
    SidebarUI.hide();
  },

  async cleanup() {
    await PlacesTestUtils.promiseAsyncUpdates();

    await PlacesUtils.history.clear();
  },
});

// ------------------------------------------------------------------------------

add_task(async function test_setup() {
  // This test can take some time, if we timeout too early it could run
  // in the middle of other tests, or hang them.
  requestLongerTimeout(2);
});

add_task(async function test_run() {
  for (let test of gTests) {
    info(`Start of test: ${test.desc}`);
    await test.setup();

    await execute_test_in_sidebar(test);
    await test.run();

    await test.cleanup();
    await test.finish();

    info(`End of test: ${test.desc}`);
  }
});

/**
 * Global functions to run a test in Properties dialog context.
 */

function execute_test_in_sidebar(test) {
  return new Promise(resolve => {
    var sidebar = document.getElementById("sidebar");
    sidebar.addEventListener(
      "load",
      function () {
        // Need to executeSoon since the tree is initialized on sidebar load.
        executeSoon(async () => {
          await open_properties_dialog(test);
          resolve();
        });
      },
      { capture: true, once: true }
    );
    SidebarUI.show(test.sidebar);
  });
}

async function promise_properties_window(dialogUrl = DIALOG_URL) {
  let win = await BrowserTestUtils.promiseAlertDialogOpen(null, dialogUrl, {
    isSubDialog: true,
  });
  await SimpleTest.promiseFocus(win);
  await win.document.mozSubdialogReady;
  return win;
}

async function open_properties_dialog(test) {
  var sidebar = document.getElementById("sidebar");

  // If this is history sidebar, set the required view.
  if (test.sidebar == SIDEBAR_HISTORY_ID) {
    sidebar.contentDocument.getElementById(test.historyView).doCommand();
  }

  // Get sidebar's Places tree.
  var sidebarTreeID =
    test.sidebar == SIDEBAR_BOOKMARKS_ID
      ? SIDEBAR_BOOKMARKS_TREE_ID
      : SIDEBAR_HISTORY_TREE_ID;
  var tree = sidebar.contentDocument.getElementById(sidebarTreeID);
  // The sidebar may take a moment to open from the doCommand, therefore wait
  // until it has opened before continuing.
  await TestUtils.waitForCondition(() => tree, "Sidebar tree has been loaded");

  // Ask current test to select the node to edit.
  test.selectNode(tree);
  Assert.ok(
    tree.selectedNode,
    "We have a places node selected: " + tree.selectedNode.title
  );

  return new Promise(resolve => {
    var command = null;
    switch (test.action) {
      case ACTION_EDIT:
        command = "placesCmd_show:info";
        break;
      case ACTION_ADD:
        if (test.sidebar == SIDEBAR_BOOKMARKS_ID) {
          if (test.itemType == TYPE_FOLDER) {
            command = "placesCmd_new:folder";
          } else if (test.itemType == TYPE_BOOKMARK) {
            command = "placesCmd_new:bookmark";
          } else {
            Assert.ok(
              false,
              "You didn't set a valid itemType for adding an item"
            );
          }
        } else {
          command = "placesCmd_createBookmark";
        }
        break;
      default:
        Assert.ok(false, "You didn't set a valid action for this test");
    }
    // Ensure command is enabled for this node.
    Assert.ok(
      tree.controller.isCommandEnabled(command),
      " command '" + command + "' on current selected node is enabled"
    );

    promise_properties_window(test.dialogUrl).then(win => {
      test.window = win;
      resolve();
    });
    // This will open the dialog. For some reason this needs to be executed
    // later, as otherwise opening the dialog throws an exception.
    executeSoon(() => {
      tree.controller.doCommand(command);
    });
  });
}