-
-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathDropdownButton.js
More file actions
497 lines (437 loc) · 18.6 KB
/
DropdownButton.js
File metadata and controls
497 lines (437 loc) · 18.6 KB
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
/*
* Copyright (c) 2021 - present core.ai . All rights reserved.
* Original work Copyright (c) 2014 - 2021 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
// @INCLUDE_IN_API_DOCS
/**
* Button that opens a dropdown list when clicked. More akin to a popup menu than a combobox. Compared to a
* simple <select> element:
* - There's no "selected" state
* - The button's label is not automatically changed when an item in the list is clicked
* - Its width is not the max of all the dropdown items' labels
* - The button & dropdown's appearance can be customized far more
* Events
* - listRendered -- This event is dispatched after the entire list is rendered so that custom event handlers can be
* set up for any custom UI in the list.
*
* TODO: merge DropdownEventHandler into this? Are there any other widgets that might want to use it separately?
*
*/
define(function (require, exports, module) {
// Load dependent modules
const DropdownEventHandler = require("utils/DropdownEventHandler").DropdownEventHandler,
EventDispatcher = require("utils/EventDispatcher"),
WorkspaceManager = require("view/WorkspaceManager"),
Menus = require("command/Menus"),
ViewUtils = require("utils/ViewUtils"),
_ = require("thirdparty/lodash");
/**
* Event triggered when an item is selected.
* @type {string}
* @const
*/
const EVENT_SELECTED = "select";
/**
* Event triggered when the list is rendered.
* @type {string}
* @const
*/
const EVENT_LIST_RENDERED = "listRendered";
/**
* Event triggered when the dropdown is shown.
* @type {string}
* @const
*/
const EVENT_DROPDOWN_SHOWN = "shown";
/**
* Event triggered when the dropdown is closed.
* @type {string}
* @const
*/
const EVENT_DROPDOWN_CLOSED = "closed";
/**
* Creates a single dropdown-button instance. The DOM node is created but not attached to
* the document anywhere - clients should append `this.$button` to the appropriate location.
*
* DropdownButton dispatches the following events:
* - "select" - triggered when an option in the dropdown is clicked. Passed item object and index.
*
* @param {!string} label - The label to display on the button.
* @param {!Array<*>} items - Items in the dropdown list. Items can have any type/value.
* An item with the value `"---"` will be treated as a divider, which is not clickable,
* and `itemRenderer()` will not be called for it.
* @param {?function(*, number): (string|{html: string, enabled: boolean})} [itemRenderer] -
* Optional function to convert a single item to HTML. If not provided, items are assumed
* to be plain text strings. The function receives the item and its index.
* @param {Object} [options] - Additional options for the dropdown.
* @param {boolean} [options.enableFilter=false] - Set to `true` to enable filtering by typing.
* @param {string} [options.cssClasses] - A space-separated list of CSS classes to apply to the button.
* @param {function(string, string, number): boolean} [options.customFilter] - Optional. When `enableFilter`
* is enabled, this function is used as a custom filtering callback. It receives the user's search text,
* the text of the element being filtered, and the element's index. Return `true` to display the list item,
* or `false` to hide it.
*/
function DropdownButton(label, items, itemRenderer, options) {
this.items = items;
options = options || {};
this.enableFilter = (typeof options.enableFilter === 'boolean' ? options.enableFilter : true);
this.customFilter = options.customFilter;
this.itemRenderer = itemRenderer || this.itemRenderer;
this._onClick = this._onClick.bind(this);
this.closeDropdown = this.closeDropdown.bind(this);
this._onClickOutside = this._onClickOutside.bind(this);
this.$button = $(`<button class='btn btn-dropdown ${options.cssClasses ? options.cssClasses : ''}'/>`)
.text(label)
.on("click", this._onClick);
}
EventDispatcher.makeEventDispatcher(DropdownButton.prototype);
/**
* Items in dropdown list - may be changed any time dropdown isn't open
* @type {!Array.<*>}
*/
DropdownButton.prototype.items = null;
/**
* This is filter text corresponding to each items. it will be used to filter the items based on
* the keyboard key presses the user does to enter search filter in popup.
* @type {null}
*/
DropdownButton.prototype.itemsSearchFilterText = null;
/**
* The clickable button. Available as soon as the DropdownButton is constructed.
* @type {!jQueryObject}
*/
DropdownButton.prototype.$button = null;
/**
* The dropdown element. Only non-null while open.
* @type {?jQueryObject}
*/
DropdownButton.prototype.$dropdown = null;
/**
* Extra CSS class(es) to apply to $dropdown
* @type {?string}
*/
DropdownButton.prototype.dropdownExtraClasses = null;
/**
* @private
* Where to restore focus when dropdown closed
* @type {?HTMLElement}
*/
DropdownButton.prototype._lastFocus = null;
/**
* @private
* Helper object for dropdown. Only non-null while open.
* @type {?DropdownEventHandler}
*/
DropdownButton.prototype._dropdownEventHandler = null;
/**
* @private
* Handle clicking button
*/
DropdownButton.prototype._onClick = function (event) {
if (!this.$button.hasClass("disabled")) {
this.toggleDropdown();
}
// Indicate click was handled (e.g. to shield from MultiRangeInlineEditor._onClick())
event.stopPropagation();
};
/**
* Update the button label.
* @param {string} label
*/
DropdownButton.prototype.setButtonLabel = function (label) {
if (!this.$button) {
return;
}
$(this.$button).text(label);
};
/**
* returns true if the dropdown is open
*/
DropdownButton.prototype.isOpen = function () {
if (this.$dropdown) {
return true;
}
return false;
};
/**
* Called for each item when rendering the dropdown.
* @param {*} item from items array
* @param {number} index in items array
* @return {!string|{html:string, enabled:boolean}} Formatted & escaped HTML, either as a simple string
* or as the 'html' field in an object that also conveys enabled state. Disabled items inherit gray
* text color and cannot be selected.
*/
DropdownButton.prototype.itemRenderer = function (item, index) {
return _.escape(String(item));
};
/**
* Converts the list of item objects into HTML list items in format required by DropdownEventHandler
* @private
* @param {!jQueryObject} $parent The dropdown element
* @return {!jQueryObject} The dropdown element with the rendered list items appended.
*/
DropdownButton.prototype._renderList = function ($parent) {
if (!$parent) {
return null;
}
const self = this;
this.itemsSearchFilterText = [];
let html = "";
this.searchStr = "";
if (self.enableFilter) {
$parent.append(`<li class="sticky-li-top forced-hidden"><a class='stylesheet-link'><i class="fa fa-search" aria-hidden="true"></i> <span class="searchTextSpan"></span></a></li>`);
}
this.items.forEach(function (item, i) {
self.itemsSearchFilterText[i] = "";
if (item === "---") {
$parent.append("<li class='divider'></li>");
} else {
let rendered = self.itemRenderer(item, i),
itemHtml = rendered.html || rendered || "",
disabledClass = (rendered.html && !rendered.enabled) ? "disabled" : "";
if (rendered.$html) {
const $atag = $(`<a class='stylesheet-link ${disabledClass}' data-index='${i}'></a>`);
$atag.append(rendered.$html);
const $itemHtml = $(`<li data-index='${i}'></li>`).append($atag);
self.itemsSearchFilterText[i] = $itemHtml.text();
$parent.append($itemHtml);
} else {
const $itemHtml = $(`<li data-index='${i}'><a class='stylesheet-link ${disabledClass}' data-index='${i}'>${itemHtml}</a></li>`);
self.itemsSearchFilterText[i] = $itemHtml.text();
$parent.append($itemHtml);
}
}
}.bind(this));
$parent.append(html);
// Also trigger listRendered handler so that custom event handlers can be
// set up for any custom UI in the list.
this.trigger(EVENT_LIST_RENDERED, $parent);
// Also need to re-register mouse event handlers with the updated list.
if (this._dropdownEventHandler) {
this._dropdownEventHandler.reRegisterMouseHandlers($parent);
}
return $parent;
};
/**
* Refresh the dropdown list by removing and re-creating all list items.
* Call this after deleting/adding any item in the dropdown list.
*/
DropdownButton.prototype.refresh = function () {
if (!this.$dropdown) {
return;
}
// Remove all list items and then re-create them from this.items.
$("li", this.$dropdown).remove();
this._renderList(this.$dropdown);
this._reposition();
};
/**
* Check/Uncheck the list item of the given index.
* @param {number} index The index of the list item to be checked or unchecked
* @param {boolean} checked True if the list item is to be checked, false to get check
* mark removed.
*/
DropdownButton.prototype.setChecked = function (index, checked) {
if (!this.$dropdown) {
return;
}
var listItems = $("li", this.$dropdown),
count = listItems.length;
if (index > -1 && index < count) {
$("a", listItems[index]).toggleClass("checked", checked);
}
};
DropdownButton.prototype._reposition = function () {
const $dropdown = this.$dropdown;
// Calculate position of dropdown
var toggleOffset = this.$button.offset(),
posLeft = toggleOffset.left,
posTop = toggleOffset.top + this.$button.outerHeight(),
elementRect = {
top: posTop,
left: posLeft,
height: $dropdown.height(),
width: $dropdown.width()
},
clip = ViewUtils.getElementClipSize($(window), elementRect);
if (clip.bottom > 0) {
// Bottom is clipped, so move entire menu above button
posTop = Math.max(0, toggleOffset.top - $dropdown.height() - 4);
}
// Take in consideration the scrollbar to prevent unexpected behaviours (see #10963).
var dropdownElement = this.$dropdown[0];
var scrollWidth = dropdownElement.offsetWidth - dropdownElement.clientWidth + 1;
if (clip.right > 0) {
// Right is clipped, so adjust left to fit menu in editor.
posLeft = Math.max(0, posLeft - clip.right - scrollWidth);
}
$dropdown.css({
left: posLeft,
top: posTop,
width: $dropdown.width() + scrollWidth
});
};
/**
* Pops open the dropdown if currently closed. Does nothing if items.length == 0
*/
DropdownButton.prototype.showDropdown = function () {
// Act like a plain old button if no items to show
if (!this.items.length) {
return;
}
if (this.$dropdown) {
return;
}
Menus.closeAll();
this.searchStr = "";
var $dropdown = $("<ul class='dropdown-menu dropdownbutton-popup' tabindex='-1'>")
.addClass(this.dropdownExtraClasses) // (no-op if unspecified)
.css("min-width", this.$button.outerWidth()); // do this before the clipping calcs below
this.$dropdown = $dropdown;
this._renderList(this.$dropdown)
.appendTo($("body"))
.data("attached-to", this.$button[0]); // keep ModalBar open while dropdown focused
this._reposition();
// Attach event handlers
this._dropdownEventHandler = new DropdownEventHandler($dropdown, this._onSelect.bind(this),
this._onDropdownClose.bind(this), this._onKeyDown.bind(this));
this._dropdownEventHandler.open();
window.document.body.addEventListener("mousedown", this._onClickOutside, true);
WorkspaceManager.on("workspaceUpdateLayout", this.closeDropdown);
// Manage focus
this._lastFocus = window.document.activeElement;
$dropdown.focus();
this.trigger(EVENT_DROPDOWN_SHOWN);
};
/**
* @private
* Clean up event handlers after dropdown closed & dispose old dropdown DOM. Called regardless of how the dropdown
* was closed.
*/
DropdownButton.prototype._onDropdownClose = function () {
window.document.body.removeEventListener("mousedown", this._onClickOutside, true);
WorkspaceManager.off("workspaceUpdateLayout", this.closeDropdown);
// Restore focus to old pos, unless "select" handler changed it
if (window.document.activeElement === this.$dropdown[0]) {
this._lastFocus.focus();
}
this._dropdownEventHandler = null;
this.$dropdown = null; // already remvoed from DOM automatically by PopUpManager
this.trigger(EVENT_DROPDOWN_CLOSED);
};
/**
* hides all elements in popup that doesn't match the given search string, also shows the search bar in popup
* @param searchString
*/
DropdownButton.prototype.filterDropdown = function (searchString) {
this.searchStr = searchString;
const $stickyLi = this.$dropdown.find('li.sticky-li-top');
for (let i = 0; i < this.itemsSearchFilterText.length; i++) {
const itemText = this.itemsSearchFilterText[i];
const $liElementAtIndex = this.$dropdown.find(`li[data-index='${i}']`);
let shouldShow = itemText && itemText.toLowerCase().includes(searchString.toLowerCase());
if (this.customFilter) {
shouldShow = this.customFilter(searchString, itemText, i);
}
if (shouldShow) {
$liElementAtIndex.removeClass('forced-hidden');
} else {
$liElementAtIndex.addClass('forced-hidden');
}
}
if (searchString) {
$stickyLi.removeClass('forced-hidden');
$stickyLi.find('.searchTextSpan').text(searchString);
} else {
$stickyLi.addClass('forced-hidden');
}
};
DropdownButton.prototype._onKeyDown = function (event) {
if (!this.enableFilter) {
return false;
}
const self = this;
if ((event.ctrlKey || event.metaKey) && event.key === 'v') {
Phoenix.app.clipboardReadText().then(text => {
self.searchStr += text;
self.filterDropdown(this.searchStr);
});
event.stopImmediatePropagation();
event.preventDefault();
return true;
} else if (event.key.length === 1) {
this.searchStr += event.key;
} else if (event.key === 'Backspace') {
// Remove the last character when Backspace is pressed
this.searchStr = this.searchStr.slice(0, -1);
} else {
// bubble up, not for us to handle
return false;
}
this.filterDropdown(this.searchStr);
event.stopImmediatePropagation();
event.preventDefault();
return true;
};
/** Closes the dropdown if currently open */
DropdownButton.prototype.closeDropdown = function () {
if (this._dropdownEventHandler) {
this._dropdownEventHandler.close();
}
};
/**
* @private
* Clicking outside the dropdown closes it
*/
DropdownButton.prototype._onClickOutside = function (event) {
var $container = $(event.target).closest(".dropdownbutton-popup");
// If click is outside dropdown list or dropdown button, then close dropdown list
if (!$(event.target).is(this.$button) &&
($container.length === 0 || $container[0] !== this.$dropdown[0])) {
this.closeDropdown();
event.stopPropagation();
event.preventDefault();
}
};
/** Opens the dropdown if closed; closes it if open */
DropdownButton.prototype.toggleDropdown = function () {
if (this.$dropdown) {
this.closeDropdown();
} else {
this.showDropdown();
}
};
/**
* @private
* Callback from DropdownEventHandler when item in dropdown list is selected (via mouse or keyboard)
* @param {!jQueryObject} $link The `a` element selected
*/
DropdownButton.prototype._onSelect = function ($link) {
var itemIndex = Number($link.data("index"));
this.trigger(EVENT_SELECTED, this.items[itemIndex], itemIndex);
};
exports.DropdownButton = DropdownButton;
// public events
exports.EVENT_SELECTED = EVENT_SELECTED;
exports.EVENT_LIST_RENDERED = EVENT_LIST_RENDERED;
exports.EVENT_DROPDOWN_SHOWN = EVENT_DROPDOWN_SHOWN;
exports.EVENT_DROPDOWN_CLOSED = EVENT_DROPDOWN_CLOSED;
});