-
-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathrelateditems.js
More file actions
728 lines (656 loc) · 27 KB
/
Copy pathrelateditems.js
File metadata and controls
728 lines (656 loc) · 27 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
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
import $ from "jquery";
import _ from "underscore";
import Base from "@patternslib/patternslib/src/core/base";
import _t from "../../core/i18n-wrapper";
import utils from "../../core/utils";
import registry from "@patternslib/patternslib/src/core/registry";
const KEY = {
LEFT: 37,
RIGHT: 39,
};
export default Base.extend({
name: "relateditems",
trigger: ".pat-relateditems",
parser: "mockup",
currentPath: undefined,
selectedUIDs: [],
openAfterInit: undefined,
defaults: {
// main option
vocabularyUrl: null, // must be set to work
// more options
attributes: [
"UID",
"Title",
"portal_type",
"path",
"getURL",
"getIcon",
"is_folderish",
"review_state",
], // used by utils.QueryHelper
basePath: "",
pageSize: 10,
browsing: undefined,
closeOnSelect: true,
contextPath: undefined,
dropdownCssClass: "pat-relateditems-dropdown",
favorites: [],
recentlyUsed: false,
recentlyUsedMaxItems: 20,
recentlyUsedKey: "relateditems_recentlyused",
maximumSelectionSize: -1,
minimumInputLength: 0,
mode: "browse", // possible values are 'auto', 'search' and 'browse'.
orderable: true, // mockup-patterns-select2
pathOperator: "plone.app.querystring.operation.string.path",
rootPath: "/",
rootUrl: "", // default to be relative.
scanSelection: false, // False, to no unnecessarily use CPU time on this.
selectableTypes: null, // null means everything is selectable, otherwise a list of strings to match types that are selectable
separator: ",",
sortOn: null,
sortOrder: "ascending",
tokenSeparators: [",", " "],
upload: false,
uploadAllowView: undefined,
// templates
breadcrumbTemplateSelector: null,
favoriteTemplateSelector: null,
recentlyusedTemplateSelector: null,
resultTemplateSelector: null,
selectionTemplateSelector: null,
toolbarTemplateSelector: null,
// needed
multiple: true,
// ajax settings
ajaxTimeout: 500,
},
recentlyUsed(filterSelectable) {
let ret = utils.storage.get(this.options.recentlyUsedKey) || [];
// hard-limit to 1000 entries
ret = ret.slice(ret.length - 1000, ret.length);
if (filterSelectable) {
// Filter out only selectable items.
// This is used only to create the list of items to be displayed.
// the list to be stored is unfiltered and can be reused among
// different instances of this widget with different settings.
ret.filter(this.isSelectable.bind(this));
}
// max is applied AFTER filtering selectable items.
const max = parseInt(this.options.recentlyUsedMaxItems, 10);
if (max) {
// return the slice from the end, as we want to display newest items first.
ret = ret.slice(ret.length - max, ret.length);
}
return ret;
},
applyTemplate(tpl, item) {
let template;
if (this.options[tpl + "TemplateSelector"]) {
template = $(this.options[tpl + "TemplateSelector"]).html();
}
if (!template) {
if (this.options[tpl + "Template"]) {
template = this.options[tpl + "Template"];
} else {
template = this[tpl + "Template"];
}
}
// let's give all the options possible to the template generation
const options = $.extend(true, {}, this.options, item, {
browsing: this.browsing,
open_folder: _t("Open folder"),
current_directory: _t("current directory:"),
one_level_up: _t("Go one level up"),
});
options._item = item;
return _.template(template)(options);
},
setAjax() {
const ajaxTimeout = parseInt(this.options.ajaxTimeout || 500, 10);
const ajax = {
url: this.options.vocabularyUrl,
dataType: "JSON",
quietMillis: ajaxTimeout,
data: (term, page) => {
const criterias = [];
if (term) {
term = "*" + term + "*";
criterias.push({
i: "SearchableText",
o: "plone.app.querystring.operation.string.contains",
v: term,
});
}
// We don't restrict for selectable types while browsing...
if (!this.browsing && this.options.selectableTypes) {
criterias.push({
i: "portal_type",
o: "plone.app.querystring.operation.selection.any",
v: this.options.selectableTypes,
});
}
criterias.push({
i: "path",
o: this.options.pathOperator,
v:
this.options.rootPath +
this.currentPath +
(this.browsing ? "::1" : ""),
});
let sort_on = this.options.sortOn;
let sort_order = sort_on ? this.options.sortOrder : null;
if (this.browsing && sort_on === null) {
sort_on = "getObjPositionInParent";
sort_order = "ascending";
}
const data = {
query: JSON.stringify({
criteria: criterias,
sort_on: sort_on,
sort_order: sort_order,
}),
attributes: JSON.stringify(this.options.attributes),
batch: JSON.stringify({
page: page ? page : 1,
size: this.options.pageSize,
}),
};
return data;
},
results: (data, page) => {
const more = page * this.options.pageSize < data.total;
let results = data.results;
this.selectedUIDs = (this.$el.select2("data") || []).map((el) => {
// populate current selection. Reuse in formatResult
return el.UID;
});
// Filter out items:
// While browsing: always include folderish items
// Browsing and searching: Only include selectable items which are not already selected, and all folders
// even if they're selected, as we need them available for browsing/selecting their children
results = results.filter((item) => {
if (
(this.browsing && item.is_folderish) ||
(this.isSelectable(item) &&
this.selectedUIDs.indexOf(item.UID) === -1)
) {
return true;
}
return false;
});
// Extend ``data`` with a ``oneLevelUp`` item when browsing
const path = this.currentPath.split("/");
if (
page === 1 && // Show level up only on top.
this.browsing && // only level up when browsing
path.length > 1 && // do not try to level up one level under root.
this.currentPath !== "/" // do not try to level up beyond root
) {
results = [
{
oneLevelUp: true,
Title: _t("One level up"),
path: path.slice(0, path.length - 1).join("/") || "/",
currentPath: this.currentPath,
is_folderish: true,
selectable: false,
},
].concat(results);
}
return {
results: results,
more: more,
};
},
};
this.options.ajax = ajax;
},
async renderToolbar() {
const path = this.currentPath;
let html;
const parts = path.split("/");
let itemPath = "";
let itemsHtml = "";
for (const part of parts) {
if (part !== "") {
const item = {};
item.path = itemPath = `${itemPath}/${part}`;
item.text = part;
itemsHtml = itemsHtml + this.applyTemplate("breadcrumb", item);
}
}
// favorites
let favoritesHtml = "";
for (const item of this.options.favorites) {
const item_copy = _.clone(item);
item_copy.path = item_copy.path.substr(this.options.rootPath.length) || "/";
favoritesHtml = favoritesHtml + this.applyTemplate("favorite", item_copy);
}
let recentlyUsedHtml = "";
if (this.options.recentlyUsed) {
const recentlyUsed = this.recentlyUsed(true); // filter out only those items which can actually be selected
for (const item of recentlyUsed.reverse()) {
// reverse to get newest first.
recentlyUsedHtml =
recentlyUsedHtml + this.applyTemplate("recentlyused", item);
}
}
html = this.applyTemplate("toolbar", {
items: itemsHtml,
favItems: favoritesHtml,
favText: _t("Favorites"),
searchText: _t("Current path:"),
searchModeText: _t("Search"),
browseModeText: _t("Browse"),
recentlyUsedItems: recentlyUsedHtml,
recentlyUsedText: _t("Recently Used"),
icon_root: await utils.resolveIcon("house-fill"),
icon_recently_used: await utils.resolveIcon("grid-fill"),
icon_favorites: await utils.resolveIcon("star-fill"),
icon_upload: await utils.resolveIcon("cloud-arrow-up"),
upload: this.options.upload,
upload_text: _t("Upload"),
});
this.$toolbar.html(html);
// unbind mouseup event from select2 to override the behavior:
$(".pat-relateditems-dropdown").off("mouseup");
$(".pat-relateditems-dropdown").on("mouseup", (e) => {
e.stopPropagation();
});
$("button.mode.search", this.$toolbar).on("click", (e) => {
e.preventDefault();
if (this.browsing) {
$("button.mode.search", this.$toolbar).toggleClass(
"btn-primary btn-secondary"
);
$("button.mode.browse", this.$toolbar).toggleClass(
"btn-primary btn-secondary"
);
this.browsing = false;
if (this.$el.select2("data").length > 0) {
// Have to call after initialization
this.openAfterInit = true;
}
if (!this.openAfterInit) {
this.$el.select2("close");
this.$el.select2("open");
}
} else {
// just open result list
this.$el.select2("close");
this.$el.select2("open");
}
});
$("button.mode.browse", this.$toolbar).on("click", (e) => {
e.preventDefault();
if (!this.browsing) {
$("button.mode.search", this.$toolbar).toggleClass(
"btn-primary btn-secondary"
);
$("button.mode.browse", this.$toolbar).toggleClass(
"btn-primary btn-secondary"
);
this.browsing = true;
if (this.$el.select2("data").length > 0) {
// Have to call after initialization
this.openAfterInit = true;
}
if (!this.openAfterInit) {
this.$el.select2("close");
this.$el.select2("open");
}
} else {
// just open result list
this.$el.select2("close");
this.$el.select2("open");
}
});
$("a.crumb", this.$toolbar).on("click", (e) => {
e.preventDefault();
e.stopPropagation();
this.browseTo($(e.currentTarget).attr("href"));
});
$("a.fav", this.$toolbar).on("click", (e) => {
e.preventDefault();
e.stopPropagation();
this.browseTo($(e.currentTarget).attr("href"));
});
if (this.options.recentlyUsed) {
$(".pat-relateditems-recentlyused-select", this.$toolbar).on(
"click",
(event) => {
event.preventDefault();
const uid = $(event.currentTarget).data("uid");
let item = this.recentlyUsed().filter((it) => {
return it.UID === uid;
});
if (item.length > 0) {
item = item[0];
} else {
return;
}
this.selectItem(item);
if (this.options.maximumSelectionSize > 0) {
const items = this.$el.select2("data");
if (items.length >= this.options.maximumSelectionSize) {
return;
}
}
}
);
}
// upload
if (
this.options.upload &&
utils.featureSupport.dragAndDrop() &&
utils.featureSupport.fileApi()
) {
if (this.options.uploadAllowView) {
// Check, if uploads are allowed in current context
$.ajax({
url: this.options.uploadAllowView,
// url: this.currentUrl() + this.options.uploadAllowView, // not working yet
dataType: "JSON",
data: {
path: this.options.rootPath + this.currentPath,
},
type: "GET",
success: (result) => {
this.initUploadView(!result.allowUpload);
},
});
} else {
// just initialize upload view without checking, if uploads are allowed.
this.initUploadView();
}
}
},
async initUploadView(disabled) {
let Upload = await import("../upload/upload--implementation");
Upload = Upload.default;
const upload_button = this.$toolbar[0].querySelector(".upload button");
upload_button.disabled = disabled;
const upload_el = this.$toolbar[0].querySelector(".upload .pat-upload");
const upload_config = {
success: (e, response) => {
const uid = response.UID;
if (uid) {
const query = new utils.QueryHelper({
vocabularyUrl: this.options.vocabularyUrl,
attributes: this.options.attributes,
});
query.search(
"UID",
"plone.app.querystring.operation.selection.is",
uid,
(e) => {
const data = this.$el.select2("data");
data.push.apply(data, e.results);
this.$el.select2("data", data, true);
this.emit("selected");
},
false
);
}
},
uloadMultiple: true,
allowPathSelection: false,
relativePath: "fileUpload",
baseUrl: this.options.rootUrl,
};
const upload = new Upload($(upload_el), upload_config);
upload_button.addEventListener("show.bs.dropdown", () => {
if (this.currentPath !== upload.currentPath) {
upload.setPath(this.currentPath);
}
});
},
browseTo(path) {
this.emit("before-browse");
this.currentPath = path;
this.$el.select2("close");
this.renderToolbar();
this.$el.select2("open");
this.emit("after-browse");
},
selectItem(item) {
this.emit("selecting");
const data = $(this.el).select2("data");
data.push(item);
$(this.el).select2("data", data, true);
if (this.options.recentlyUsed) {
// add to recently added items
const recentlyUsed = this.recentlyUsed(); // do not filter for selectable but get all. append to that list the new item.
const alreadyPresent = recentlyUsed.filter((it) => {
return it.UID === item.UID;
});
if (alreadyPresent.length > 0) {
recentlyUsed.splice(recentlyUsed.indexOf(alreadyPresent[0]), 1);
}
recentlyUsed.push(item);
utils.storage.set(this.options.recentlyUsedKey, recentlyUsed);
}
this.emit("selected");
},
deselectItem(item) {
this.emit("deselecting");
const data = this.$el.select2("data");
data.forEach((obj, i) => {
if (obj.UID === item.UID) {
data.splice(i, 1);
}
});
this.$el.select2("data", data, true);
this.emit("deselected");
},
isSelectable(item) {
if (item.selectable === false) {
return false;
}
if (this.options.selectableTypes === null) {
return true;
} else {
return this.options.selectableTypes.indexOf(item.portal_type) !== -1;
}
},
async init() {
// select2 methods are borrowed onto this instance; load them lazily so
// the select2 body stays out of the eager patterns chunk.
this._select2 = (await import("../select2/select2--implementation")).default;
(await import("bootstrap")).Dropdown;
import("./relateditems.scss");
// templates
this.breadcrumbTemplate = (await import("./templates/breadcrumb.xml")).default; // prettier-ignore
this.favoriteTemplate = (await import("./templates/favorite.xml")).default; // prettier-ignore
this.recentlyusedTemplate = (await import("./templates/recentlyused.xml")).default; // prettier-ignore
this.resultTemplate = (await import("./templates/result.xml")).default; // prettier-ignore
this.selectionTemplate = (await import("./templates/selection.xml")).default; // prettier-ignore
this.toolbarTemplate = (await import("./templates/toolbar.xml")).default; // prettier-ignore
this.browsing = this.options.mode !== "search";
// Remove trailing slash
this.options.rootPath = this.options.rootPath.replace(/\/$/, "");
// Substract rootPath from basePath with is the relative currentPath. Has a leading slash. Or use '/'
this.currentPath =
this.options.basePath.substr(this.options.rootPath.length) || "/";
this.setAjax();
this.$el.wrap('<div class="pat-relateditems-container" />');
this.$container = this.$el.parents(".pat-relateditems-container");
this._select2.initializeValues.call(this);
this._select2.initializeTags.call(this);
this.options.formatSelection = (item) => {
item = $.extend(
true,
{
Title: "",
getIcon: "",
getURL: "",
path: "",
portal_type: "",
review_state: "",
},
item
);
// activate petterns on the result set.
const $selection = $(this.applyTemplate("selection", item));
if (this.options.scanSelection) {
registry.scan($selection);
}
if (this.options.maximumSelectionSize == 1) {
// If this related field accepts only 1 item, the breadcrumbs should
// reflect the location for this particular item
let itemPath = item.path;
let path_split = itemPath.split("/");
path_split = path_split.slice(0, -1); // Remove last part of path, we always want the parent path
itemPath = path_split.join("/");
this.currentPath = itemPath;
this.renderToolbar();
}
return $selection;
};
const icon_level_up = await utils.resolveIcon("arrow-left-circle");
const icon_level_down = await utils.resolveIcon("arrow-right-circle");
this.options.formatResult = (item) => {
item.selectable = this.isSelectable(item);
item = $.extend(
true,
{
Title: "",
getIcon: "",
getURL: "",
is_folderish: false,
oneLevelUp: false,
iconLevelUp: icon_level_up,
iconLevelDown: icon_level_down,
path: "",
portal_type: "",
review_state: "",
selectable: false,
},
item
);
if (this.selectedUIDs.indexOf(item.UID) !== -1) {
// do not allow already selected items to be selected again.
item.selectable = false;
}
const result = $(this.applyTemplate("result", item));
$(".pat-relateditems-result-select", result).on("click", (event) => {
const _el = event.currentTarget;
event.preventDefault();
// event.stopPropagation();
if ($(_el).is(".selectable")) {
const $parent = $(_el).parents(".pat-relateditems-result");
if ($parent.is(".pat-relateditems-active")) {
$parent.removeClass("pat-relateditems-active");
this.deselectItem(item);
} else {
if (this.options.maximumSelectionSize > 0) {
const items = this.$el.select2("data");
if (items.length >= this.options.maximumSelectionSize) {
this.$el.select2("close");
}
}
this.selectItem(item);
$parent.addClass("pat-relateditems-active");
if (this.options.closeOnSelect) {
this.$el.select2("close");
}
}
}
});
$(".pat-relateditems-result-browse", result).on("click", (event) => {
event.preventDefault();
event.stopPropagation();
const path = $(event.currentTarget).data("path");
this.browseTo(path);
});
return $(result);
};
this.options.initSelection = (element, callback) => {
const value = $(element).val();
if (value !== "") {
const ids = value.split(this.options.separator);
const query = new utils.QueryHelper(
$.extend(true, {}, this.options, {
pattern: this,
})
);
query.search(
"UID",
"plone.app.querystring.operation.list.contains",
ids,
(data) => {
const results = data.results.reduce((prev, item) => {
prev[item.UID] = item;
return prev;
}, {});
try {
callback(
ids
.map((uid) => results[uid])
.filter((item) => item !== undefined)
);
} catch {
// Select2 3.5.4 throws an error in some cases in
// updateSelection, ``this.selection.find(".select2-search-choice").remove();``
// No idea why, hard to track.
}
if (this.openAfterInit) {
// open after initialization
this.$el.select2("open");
this.openAfterInit = undefined;
}
},
false
);
}
};
this.options.tokenizer = (input) => {
if (this.options.mode === "auto") {
this.browsing = input ? false : true;
}
};
this.options.id = (item) => item.UID;
await this._select2.initializeSelect2.call(this);
await this._select2.initializeOrdering.call(this);
this.$toolbar = $('<div class="toolbar d-flex" />');
this.$container.prepend(this.$toolbar);
this.$el.on("select2-selecting", (event) => {
if (!this.isSelectable(event.choice)) {
event.preventDefault();
}
});
this.renderToolbar();
this.$el.on("select2-loaded", () => {
let yMax = window.innerHeight || document.documentElement.clientHeight;
const relitem_rect = this.el.parentElement.getBoundingClientRect();
const element = $(
"#select2-drop.pat-relateditems-dropdown.select2-drop-active .select2-results"
)[0];
const rect = element.getBoundingClientRect();
const maxHeight = ((relitem_rect.top > rect.top) ? relitem_rect.top : yMax - rect.top) - 18;
$(element).css("max-height", `${maxHeight}px`);
});
$(document).on("keyup", this.$el, (event) => {
const isOpen = this._select2.opened.call(this);
if (!isOpen) {
return;
}
if (event.which === KEY.LEFT || event.which === KEY.RIGHT) {
event.stopPropagation();
const selectorContext =
event.which === KEY.LEFT
? ".pat-relateditems-result.one-level-up"
: ".select2-highlighted";
const browsableItemSelector = ".pat-relateditems-result-browse";
const browsableItem = $(browsableItemSelector, selectorContext);
if (browsableItem.length !== 1) {
return;
}
const path = browsableItem.data("path");
this.browseTo(path);
}
});
},
});