-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessImageLibrary.js
More file actions
5483 lines (5210 loc) · 223 KB
/
Copy pathProcessImageLibrary.js
File metadata and controls
5483 lines (5210 loc) · 223 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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ProcessImageLibrary — admin script.
*
* Inline-edit for cells marked with .ml-cell-editable + AJAX re-render
* of the results region (.ml-results) on filter / sort / pagination.
*
* Save queue per pageId serializes saves to the same page; AJAX
* re-render preserves the filter form (it lives outside .ml-results),
* and event delegation on .ml-results survives the innerHTML swaps.
*/
(function () {
'use strict';
function init() {
var root = document.querySelector('.ml-root');
if (!root) return;
root.classList.add('ml-js-loaded');
var pwCfg = (window.ProcessWire && window.ProcessWire.config && window.ProcessWire.config.ProcessImageLibrary) || {};
// Start from everything the server pushed via $config->js so
// new PHP-side keys (userPrefs, userPrefsUrl, defaultHiddenColumns,
// …) land in JS without a whitelist update. Fall back to
// root.dataset for the boot-critical URLs + CSRF token on
// admin themes that don't populate window.ProcessWire.config.
var config = Object.assign({
tplFields: {},
labels: {}
}, pwCfg);
config.saveUrl = config.saveUrl || root.dataset.saveUrl || '';
config.renderUrl = config.renderUrl || root.dataset.renderUrl || '';
config.bulkUrl = config.bulkUrl || root.dataset.bulkUrl || '';
config.adminUrl = config.adminUrl || root.dataset.adminUrl || '';
config.clusterUrl = config.clusterUrl || root.dataset.clusterUrl || '';
config.csrf = config.csrf || {
name: root.dataset.csrfName || '',
value: root.dataset.csrfValue || ''
};
if (!Array.isArray(config.languages)) config.languages = [];
if (config.currentLangId == null) config.currentLangId = null;
if (!config.saveUrl) return;
var labels = config.labels;
var saveQueues = new Map();
var results = root.querySelector('.ml-results');
var filterForm = root.querySelector('.ml-filter-bar');
var isReplacing = false;
var isBulking = false;
var selection = new Set();
// Pure collections/bookmarks tree model — implementations live in
// assets/collections-model.js (window.MLCollectionsModel), unit-tested
// separately. Aliased here so every existing call site stays unchanged.
var collKey = MLCollectionsModel.collKey,
collIndexOf = MLCollectionsModel.collIndexOf,
collById = MLCollectionsModel.collById,
collChildren = MLCollectionsModel.collChildren,
collIsParent = MLCollectionsModel.collIsParent,
collDepth = MLCollectionsModel.collDepth,
collHeight = MLCollectionsModel.collHeight,
collIsDescendant = MLCollectionsModel.collIsDescendant,
collSubtreeSet = MLCollectionsModel.collSubtreeSet,
collFlatten = MLCollectionsModel.collFlatten,
collPrevSibling = MLCollectionsModel.collPrevSibling;
// Write a value back into a cell. Textarea-backed cells
// (description + custom textareas) render their text inside a
// .ml-clamp box so CSS can cap the visible height; write into
// that box (creating it on demand) so the clamp survives an
// inline save, and drop it when the value is empty so the cell's
// :empty "—" placeholder returns. Reads stay on td.textContent —
// which still returns the full value through the box — so the
// editor always opens with the complete text. Non-textarea cells
// (tags, text customs) keep their plain text node.
function setCellText(td, val) {
val = String(val == null ? '' : val);
if (td.dataset.input === 'textarea') {
var box = td.querySelector('.ml-clamp');
if (val === '') { if (box) box.remove(); else td.textContent = ''; return; }
if (!box) {
td.textContent = '';
box = document.createElement('div');
box.className = 'ml-clamp';
td.appendChild(box);
}
box.textContent = val;
} else {
td.textContent = val;
}
}
// Append the CSRF token to a FormData (no-op when the page
// didn't ship one). Centralises the guard every POST endpoint
// repeated verbatim.
function appendCsrf(fd) {
if (config.csrf && config.csrf.name) fd.append(config.csrf.name, config.csrf.value);
return fd;
}
// One place for the POST boilerplate every AJAX endpoint repeated:
// FormData (from a plain {key:value} object OR an already-built
// FormData) + CSRF token + same-origin + X-Requested-With. Returns the
// raw fetch Promise so each caller keeps its own .then()/.catch().
function postForm(url, data) {
var fd;
if (data instanceof FormData) {
fd = data;
} else {
fd = new FormData();
if (data) Object.keys(data).forEach(function (k) { fd.append(k, data[k]); });
}
appendCsrf(fd);
return fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: { 'X-Requested-With': 'XMLHttpRequest' },
body: fd
});
}
// -- Picker mode ------------------------------------------------
// When the library is embedded as a picker (modal iframe in the page
// editor), images are chosen via the normal selection checkboxes (in
// BOTH the table and the masonry view). A "Use selected" button at the
// top and bottom copies every selected image into the target field,
// then messages the parent editor to refresh that field.
if (root.dataset.picker === '1') {
root.classList.add('ml-picker');
var assignUrl = root.dataset.assignUrl || '';
// Insert mode (rich-text embed): "Use selected" returns the chosen
// image URLs to the opener instead of assigning to a field.
var insertMode = root.dataset.pickMode === 'insert';
function pickKeys() {
return Array.prototype.map.call(
(results || document).querySelectorAll('.ml-select-row:checked'),
function (cb) { return cb.dataset.key || ''; }
).filter(Boolean);
}
function syncPickBar() {
var n = pickKeys().length;
root.querySelectorAll('.ml-pick-count').forEach(function (el) {
el.textContent = '(' + n + ')';
});
root.querySelectorAll('.ml-pick-confirm').forEach(function (btn) {
btn.disabled = n === 0;
});
}
// Selection changes (checkbox / select-all) update the bar.
results && results.addEventListener('change', function (e) {
if (e.target && e.target.classList &&
(e.target.classList.contains('ml-select-row') ||
e.target.classList.contains('ml-select-all'))) {
setTimeout(syncPickBar, 0); // after the row handler ran
}
});
// In the picker, clicking ANYWHERE on a tile toggles its selection —
// the natural gesture when you're choosing an image, not just the
// small checkbox. Skip the checkbox/label itself (it toggles
// natively) and any link/button so those keep their own behaviour.
results && results.addEventListener('click', function (e) {
if (!e.target.closest) return;
if (e.target.closest('.ml-card-select') || e.target.closest('a, button')) return;
var card = e.target.closest('.ml-card');
if (!card) return;
var cb = card.querySelector('.ml-select-row');
if (!cb) return;
e.preventDefault();
cb.checked = !cb.checked;
cb.dispatchEvent(new Event('change', { bubbles: true }));
});
// Assign one (pageId:field:basename) key to the target field.
function assignKey(key) {
var parts = String(key).split(':');
var pageId = parts.shift();
var field = parts.shift();
var basename = parts.join(':'); // basenames may contain ':'? keep the rest
var fd = new FormData();
fd.append('srcPageId', pageId || '');
fd.append('srcField', field || '');
fd.append('srcBasename', basename || '');
fd.append('targetPageId', root.dataset.targetPage || '');
fd.append('targetField', root.dataset.targetField || '');
// Editing a page version → assign into that version, not live.
fd.append('targetVersion', root.dataset.targetVersion || '');
return postForm(assignUrl, fd).then(function (r) { return r.json(); }).then(function (d) {
return !!(d && d.ok);
}).catch(function () { return false; });
}
root.addEventListener('click', function (e) {
// Cancel just dismisses the modal the picker is embedded in — tell
// the opener (library-pick.js / insert-common.js) to close it.
var cancelBtn = e.target.closest && e.target.closest('.ml-pick-cancel');
if (cancelBtn) {
e.preventDefault();
if (window.parent && window.parent !== window) {
window.parent.postMessage({ mlCancel: true }, location.origin);
}
return;
}
var btn = e.target.closest && e.target.closest('.ml-pick-confirm');
if (!btn) return;
e.preventDefault();
// Insert mode: gather the selected tiles' image URLs (+ alt) and
// hand them to the rich-text editor that opened the picker.
if (insertMode) {
var items = [];
(results || document).querySelectorAll('.ml-select-row:checked').forEach(function (cb) {
var card = cb.closest && cb.closest('.ml-card');
if (card && card.dataset.insertUrl) {
items.push({ url: card.dataset.insertUrl, alt: card.dataset.insertAlt || '' });
}
});
if (!items.length) return;
if (window.parent && window.parent !== window) {
window.parent.postMessage({ mlInsert: true, items: items }, location.origin);
}
return;
}
if (!assignUrl) return;
var keys = pickKeys();
if (!keys.length) return;
root.querySelectorAll('.ml-pick-confirm').forEach(function (b) { b.disabled = true; });
// Assign sequentially so the target field's saves don't race.
var ok = 0;
keys.reduce(function (p, k) {
return p.then(function () { return assignKey(k).then(function (good) { if (good) ok++; }); });
}, Promise.resolve()).then(function () {
if (window.parent && window.parent !== window) {
window.parent.postMessage({
mlPicked: true,
targetField: root.dataset.targetField,
targetPage: root.dataset.targetPage,
count: ok
}, location.origin);
} else {
window.alert((labels.done || 'Added') + ' (' + ok + ')');
}
});
});
syncPickBar();
}
// -- Inline edit ------------------------------------------------
function enqueueSave(pageId, task) {
var prev = saveQueues.get(pageId) || Promise.resolve();
var next = prev.catch(function () { return null; }).then(task);
saveQueues.set(pageId, next);
return next;
}
function postSave(payload) {
var fd = new FormData();
Object.keys(payload).forEach(function (k) { fd.append(k, payload[k]); });
// Send the current filter URL state so the server can
// tell us whether the saved row still belongs in this view.
fd.append('filterQs', location.search || '');
return postForm(config.saveUrl, fd).then(function (res) {
return res.json().then(function (data) { return { status: res.status, data: data }; });
});
}
function flashCell(td, ok) {
var cls = ok ? 'ml-cell-saved' : 'ml-cell-error';
td.classList.add(cls);
setTimeout(function () { td.classList.remove(cls); }, 1200);
announce((ok ? (labels.saved || 'Saved') : (labels.error || 'Save failed')));
}
// For a batch save, collect the matching subfield cell on every
// currently-selected row. The originating cell is included, so
// the caller can flash + optimistic-update the whole set in one
// pass and the visual feedback covers every row the broadcast
// will touch.
function batchCellsForSubfield(subfield) {
if (!results || !subfield) return [];
var out = [];
results.querySelectorAll('.ml-row').forEach(function (tr) {
var cb = tr.querySelector('.ml-select-row');
if (!cb || !cb.dataset.key || !selection.has(cb.dataset.key)) return;
var c = tr.querySelector('[data-subfield="' + subfield + '"]');
if (c) out.push(c);
});
return out;
}
// Mirror of the server-side resolveRenamePattern token grammar
// so the batch-save optimistic update can show the resolved
// per-row value instead of the raw template string. Same
// tokens, same per-row context inputs (n / total / pageTitle /
// pageName / date / field). The server still gets the raw
// template + does its own resolution; this is purely visual.
function resolveTemplateClient(template, ctx) {
if (template == null || !/\(([nN]|n[2-5]|t|d|p|f)\)/.test(template)) {
return template;
}
var n = ctx.n || 0;
var total = ctx.total || 0;
return template.replace(/\((n[2-5]?|N|t|d|p|f)\)/g, function (_m, tok) {
switch (tok) {
case 'n': return String(n);
case 'n2': return String(n).padStart(2, '0');
case 'n3': return String(n).padStart(3, '0');
case 'n4': return String(n).padStart(4, '0');
case 'n5': return String(n).padStart(5, '0');
case 'N': return String(total);
case 't': return ctx.pageTitle || '';
case 'd': return ctx.date || '';
case 'p': return ctx.pageName || '';
case 'f': return ctx.field || '';
}
return _m;
});
}
// Today's date in the same YYYY-MM-DD form the server uses for
// the (d) placeholder. Memoised per init so every cell in a
// batch resolves to the same string.
var todayIso = (function () {
var d = new Date();
var mm = String(d.getMonth() + 1).padStart(2, '0');
var dd = String(d.getDate()).padStart(2, '0');
return d.getFullYear() + '-' + mm + '-' + dd;
})();
// Visible "Page X of Y — Z images" string — patch the count
// after a row falls out of the filtered view so the summary
// reflects DOM state without a full re-render.
function updatePaginationTotal(newTotal) {
if (typeof newTotal !== 'number' || newTotal < 0) return;
document.querySelectorAll('.ml-pagination-summary').forEach(function (el) {
el.textContent = el.textContent.replace(/\b\d+\s+image/, newTotal + ' image');
});
}
// Sequence after a successful save: flash green for 1200 ms so
// the user SEES the value applied, brief 200 ms breath so the
// post-flash state registers, then fade the row out over 250 ms,
// then drop from DOM + bump the pagination total. Used by the
// inline-edit success branch when the server says the row no
// longer matches the active filter set.
function fadeRowIfMismatched(td, data) {
if (!td || !data || data.stillMatches !== false) return;
setTimeout(function () {
var tr = td.closest('tr');
if (!tr || !tr.isConnected) return;
tr.classList.add('ml-row-deleting');
setTimeout(function () {
var cb = tr.querySelector('.ml-select-row');
if (cb && cb.dataset && cb.dataset.key) {
selection.delete(cb.dataset.key);
}
var tbody = tr.parentNode;
tr.remove();
updatePaginationTotal(data.newTotal);
syncSelectAllHeader();
// Last row gone? Replace just the table wrapper
// with the empty-state paragraph, matching what
// the server emits for a zero-result filter URL.
// The pagination above/below stays — it's still
// shown on the no-results server render too.
if (tbody && tbody.children.length === 0) {
var tableWrap = root.querySelector('.ml-results .ml-table-scroll');
if (tableWrap) {
var msg = labels.emptyResult || 'No images match the current filters.';
var p = document.createElement('p');
p.className = 'ml-empty';
p.textContent = msg;
tableWrap.replaceWith(p);
}
}
}, 250);
}, 1400);
}
// Push a short message into the visually-hidden live region so
// screen readers pick up state changes (saves, errors) that the
// sighted UI signals only with a colour flash.
var liveRegion = root.querySelector('.ml-live-region');
var announceTimer = null;
function announce(msg) {
if (!liveRegion || !msg) return;
// Clearing first forces re-announcement even when the same
// message fires twice in a row (e.g. two saves landed at the
// same instant).
liveRegion.textContent = '';
clearTimeout(announceTimer);
announceTimer = setTimeout(function () {
liveRegion.textContent = msg;
}, 30);
}
// Visible, auto-dismissing message anchored to the ROW it concerns —
// chiefly a failed replace, which used to fail completely silently (the
// only signal went to the hidden aria-live region). Floats next to the
// row's thumbnail so the feedback is where the action happened, and
// mirrors to announce() so screen-reader users still get it. The
// element is absolutely positioned in document space so it scrolls with
// the row; left is clamped so a right-edge thumbnail (grid view) can't
// push it off-screen. type: 'error' | 'ok'.
function rowToast(tr, msg, type, sticky) {
if (!msg) return function () {};
announce(msg);
var anchor = (tr && tr.querySelector && tr.querySelector('.ml-cell-thumb')) || tr;
if (!anchor || !anchor.getBoundingClientRect) return function () {};
var rect = anchor.getBoundingClientRect();
var t = document.createElement('div');
t.className = 'ml-row-toast ' + (type === 'error' ? 'ml-row-toast-error' : 'ml-row-toast-ok');
t.textContent = msg;
document.body.appendChild(t);
// Use the free space between the thumbnail and the right edge of the
// results area: width grows to fit the message on one line where the
// row allows (the table), and only wraps once it hits that bound —
// rather than a fixed narrow cap. left is pulled in if the available
// band is too small (a right-edge grid thumbnail) so it stays on-screen.
var boundsRight = results ? results.getBoundingClientRect().right : document.documentElement.clientWidth;
var gap = 8, margin = 12, minW = 160;
var avail = Math.max(minW, boundsRight - rect.right - gap - margin);
var left = window.scrollX + Math.min(rect.right + gap, boundsRight - margin - avail);
t.style.maxWidth = avail + 'px';
t.style.top = (window.scrollY + rect.top + rect.height / 2) + 'px';
t.style.left = left + 'px';
requestAnimationFrame(function () { t.classList.add('ml-row-toast-show'); });
var dismissed = false;
function dismiss() {
if (dismissed) return;
dismissed = true;
t.classList.remove('ml-row-toast-show');
setTimeout(function () { if (t.parentNode) t.parentNode.removeChild(t); }, 250);
}
// Sticky toasts (e.g. "Preparing ZIP…") stay until the caller dismisses
// them; everything else auto-dismisses. Always return a dismiss handle.
if (!sticky) setTimeout(dismiss, type === 'error' ? 6000 : 2500);
return dismiss;
}
// --- Tooltips: one styled pill, event-delegated on document so it covers
// the admin page AND the body-level <dialog>s. Reads data-tip; the per-row
// action icons get batch-aware text from the live selection. aria-label
// stays the accessible name; native title= was dropped so there's no double
// (slow, unstyled) browser tooltip.
(function () {
var tip = null, timer = null, current = null;
// A modal <dialog> (showModal) paints in the top layer, above every
// body-level node, so a tip appended to <body> would hide BEHIND the
// cluster modal. Park the tip inside the open dialog the anchor lives
// in (also top layer) when there is one, else on <body>; .ml-tip is
// position:fixed so the coordinates stay viewport-relative either way.
function host(node) {
var dlg = node && node.closest && node.closest('dialog');
return (dlg && dlg.open) ? dlg : document.body;
}
function el(node) {
if (!tip) { tip = document.createElement('div'); tip.className = 'ml-tip'; tip.setAttribute('role', 'tooltip'); }
var h = host(node);
if (tip.parentNode !== h) h.appendChild(tip);
return tip;
}
function textFor(node) {
var base = node.getAttribute('data-tip') || '';
var row = node.closest && node.closest('.ml-row[data-page-id]');
if (row && selection.size > 1 && selection.has(itemKey(rowItem(row)))) {
if (node.classList.contains('ml-download-btn')) return (labels.tipDownloadBatch || 'Download %d as ZIP').replace('%d', selection.size);
if (node.classList.contains('ml-delete-btn')) return (labels.tipDeleteBatch || 'Delete %d').replace('%d', selection.size);
}
return base;
}
function place(node) {
var t = el(node), r = node.getBoundingClientRect();
var tw = t.offsetWidth, th = t.offsetHeight;
// position:fixed → viewport coordinates, no scroll offset.
var left = r.left + r.width / 2 - tw / 2;
var top = r.top - th - 8;
if (r.top - th - 8 < 4) top = r.bottom + 8;
var maxL = document.documentElement.clientWidth - tw - 6;
left = Math.max(6, Math.min(left, maxL));
t.style.left = left + 'px';
t.style.top = top + 'px';
}
function show(node) {
var txt = textFor(node);
if (!txt) return;
var t = el(node);
t.textContent = txt;
place(node);
t.classList.add('ml-tip-show');
}
function hide() { clearTimeout(timer); timer = null; current = null; if (tip) tip.classList.remove('ml-tip-show'); }
document.addEventListener('mouseover', function (e) {
var node = e.target.closest && e.target.closest('[data-tip]');
if (!node) { if (current) hide(); return; }
if (node === current) return;
current = node; clearTimeout(timer);
timer = setTimeout(function () { show(node); }, 350);
});
document.addEventListener('mouseout', function (e) {
var node = e.target.closest && e.target.closest('[data-tip]');
if (node && node === current) hide();
});
document.addEventListener('focusin', function (e) {
var node = e.target.closest && e.target.closest('[data-tip]');
if (node) { current = node; show(node); }
});
document.addEventListener('focusout', hide);
window.addEventListener('scroll', hide, true);
document.addEventListener('keydown', function (e) { if (e.key === 'Escape') hide(); });
})();
// Column header text for the cell, used as the popup dialog's
// label. Falls back to the raw subfield name if the <th> isn't
// findable (defensive — shouldn't happen with the current table).
function columnLabelFor(td) {
var row = td.parentNode;
if (!row) return td.dataset.subfield || '';
var idx = Array.prototype.indexOf.call(row.children, td);
var table = td.closest('table');
var th = table && table.querySelectorAll('thead th')[idx];
return th ? th.textContent.trim() : (td.dataset.subfield || '');
}
// Build the in-popup editor widget for a cell, dispatching by
// subfield + tags mode + input type. Returns
// { element, getValue, focus }. The popup container handles save /
// cancel / batch radios so widgets only care about their own value.
function buildPopupWidget(td, original) {
var subfield = td.dataset.subfield;
var tagsMode = parseInt(td.dataset.tagsMode || '0', 10);
// Filename rename has its own widget — text input + locked
// extension. Routed through commit()'s rename branch.
if (td.dataset.input === 'filename') {
return buildPopupFilename(td);
}
if (subfield === 'tags' && tagsMode === 2) {
return buildPopupCheckboxes(td, original);
}
if (subfield === 'tags' && tagsMode === 3) {
return buildPopupTagsAddable(td, original);
}
if (subfield === 'tags' && tagsMode === 1) {
return buildPopupTextInput(original, td.dataset.tagsListId || '');
}
// Multilang inputs get language tabs — one textarea / input
// per language, prefilled from the cell's data-lang-<id>
// attrs. Only kick in when there are actually >1 languages
// installed AND this cell carries lang attrs (i.e. the
// underlying subfield is configured multilang).
var langs = config.languages || [];
// hasAttribute is the reliable check for data-lang-<id>;
// `in` on DOMStringMap can be flaky across browsers.
var hasLangData = langs.length > 1 && langs.some(function (l) {
return td.hasAttribute('data-lang-' + l.id);
});
if (hasLangData) {
return buildPopupMultilang(td, original, td.dataset.input === 'textarea');
}
if (td.dataset.input === 'checkbox') {
return buildPopupCheckbox(original);
}
if (td.dataset.input === 'date') {
return buildPopupDate(td, original);
}
if (td.dataset.input === 'number') {
return buildPopupNumber(original);
}
if (td.dataset.input === 'select') {
return buildPopupSelect(td, original);
}
if (td.dataset.input === 'page') {
return buildPopupPageRef(td, original);
}
if (td.dataset.input === 'textarea') {
return buildPopupTextarea(original);
}
return buildPopupTextInput(original, '');
}
// Page-reference widget: ask the server to render whatever
// Inputfield the field's own config specifies (PageAutocomplete /
// PageListSelect / ASMSelect / …), inject the HTML, load any
// new scripts / styles the render added, then fire the
// 'reloaded' DOM event so each inputfield's own JS module
// initialises on the new nodes. getValue() walks every input
// inside the container and joins the values it finds — the
// shape works for hidden-input-based pickers (PageAutocomplete),
// <select multiple> (ASM), and single <select> alike.
function buildPopupPageRef(td, original) {
var wrap = document.createElement('div');
wrap.className = 'ml-popup-pageref';
var status = document.createElement('div');
status.className = 'ml-popup-pageref-loading';
status.textContent = labels.loading || 'Loading…';
wrap.appendChild(status);
function loadAsset(url, kind) {
return new Promise(function (resolve) {
if (kind === 'script') {
if (document.querySelector('script[src="' + url + '"]')) return resolve();
var s = document.createElement('script');
s.src = url;
s.onload = resolve;
s.onerror = resolve;
document.head.appendChild(s);
} else {
if (document.querySelector('link[href="' + url + '"]')) return resolve();
var l = document.createElement('link');
l.rel = 'stylesheet';
l.href = url;
l.onload = resolve;
l.onerror = resolve;
document.head.appendChild(l);
}
});
}
if (!config.widgetUrl) {
status.textContent = 'No widget endpoint configured.';
return {
element: wrap,
getValue: function () { return original; },
focus: function () {}
};
}
var url = config.widgetUrl
+ '?pageId=' + encodeURIComponent(td.dataset.pageId || '')
+ '&fieldName='+ encodeURIComponent(td.dataset.field || '')
+ '&basename=' + encodeURIComponent(td.dataset.basename || '')
+ '&subfield=' + encodeURIComponent(td.dataset.subfield || '');
fetch(url, { credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' } })
.then(function (r) { return r.json(); })
.then(function (data) {
if (!data || !data.ok || !data.html) {
status.textContent = (data && data.error) || 'Widget load failed.';
return;
}
var styleLoads = (data.styles || []).map(function (u) { return loadAsset(u, 'style'); });
var scriptLoads = (data.scripts || []).map(function (u) { return loadAsset(u, 'script'); });
return Promise.all(styleLoads.concat(scriptLoads)).then(function () {
status.remove();
var holder = document.createElement('div');
holder.className = 'ml-popup-pageref-holder';
holder.innerHTML = data.html;
wrap.appendChild(holder);
// PW's inputfield JS modules hook the 'reloaded'
// DOM event via delegated jQuery handlers on
// document, scoped to selectors like
// .InputfieldPageAutocomplete / .InputfieldPage.
// Delegated events fire only when the event
// originates from a matching descendant, so we
// trigger 'reloaded' on EACH .Inputfield in the
// injected fragment (mirroring what ProcessPage-
// Edit does after AJAX-loading a tab). Falls
// back to a CustomEvent burst when jQuery isn't
// available, although in the PW admin it
// always is.
var jq = window.jQuery;
if (jq) {
var $fields = jq(holder).find('.Inputfield').addBack('.Inputfield');
$fields.trigger('reloaded', ['ml-widget']);
} else {
holder.querySelectorAll('.Inputfield').forEach(function (el) {
el.dispatchEvent(new CustomEvent('reloaded', { bubbles: true, detail: ['ml-widget'] }));
});
}
wrap._mlWidgetName = data.name || (td.dataset.subfield || '');
wrap._mlWidgetId = data.id || '';
});
})
.catch(function () { status.textContent = 'Widget load failed.'; });
return {
element: wrap,
getValue: function () {
// Collect every input value inside the widget holder
// whose name starts with the subfield name. Covers
// hidden-input pickers, multi-selects and singles.
var subfield = td.dataset.subfield || '';
var ids = [];
wrap.querySelectorAll('input, select').forEach(function (el) {
var name = el.name || '';
if (!name) return;
if (name !== subfield && name.indexOf(subfield) !== 0) return;
if (el.type === 'checkbox' || el.type === 'radio') {
if (el.checked && el.value) ids.push(el.value);
return;
}
if (el.tagName === 'SELECT' && el.multiple) {
Array.prototype.forEach.call(el.options, function (o) {
if (o.selected && o.value) ids.push(o.value);
});
return;
}
if (el.value) ids.push(el.value);
});
// Dedup + drop blanks; comma-join for the save path.
var seen = Object.create(null);
return ids.filter(function (v) {
v = String(v).trim();
if (!v || seen[v]) return false;
seen[v] = true;
return true;
}).join(',');
},
focus: function () {
var first = wrap.querySelector('input, select, button');
if (first) first.focus();
}
};
}
// Tabbed-textarea widget for multilang subfields. Reads each
// language's starting value from the matching data-lang-<id>
// attribute on the cell, keeps the per-tab DOM in a small map
// keyed by lang id, and reports back getValue() as a
// {langId: value} object so commit() can ship every language
// in one POST. getPrimaryValue() returns whatever the
// currently-active tab holds, used for the cell's optimistic
// post-save display.
function buildPopupMultilang(td, original, isTextarea) {
var langs = config.languages || [];
var wrap = document.createElement('div');
wrap.className = 'ml-langtabs';
var bar = document.createElement('div');
bar.className = 'ml-langtabs-bar';
var panes = document.createElement('div');
panes.className = 'ml-langtabs-panes';
var byId = Object.create(null);
var activeId = null;
// Pre-pick the tab to land on: server tells us the editor's
// current admin-language id (matching the same 0=default
// scheme as data-lang-<id>). Falls back to the first
// language in the list if no match.
var preferredId = null;
if (config.currentLangId !== null) {
var found = langs.some(function (l) {
return Number(l.id) === Number(config.currentLangId);
});
if (found) preferredId = Number(config.currentLangId);
}
if (preferredId === null && langs.length) preferredId = Number(langs[0].id);
langs.forEach(function (lang) {
var tab = document.createElement('button');
tab.type = 'button';
tab.className = 'ml-langtabs-tab';
tab.dataset.langId = String(lang.id);
tab.textContent = lang.title || lang.name;
bar.appendChild(tab);
var pane;
if (isTextarea) {
pane = document.createElement('textarea');
pane.rows = 6;
} else {
pane = document.createElement('input');
pane.type = 'text';
}
pane.className = 'ml-langtabs-pane';
pane.dataset.langId = String(lang.id);
// data-lang-<id> attr is the stored value; the cell's
// textContent reflects the current user-lang display,
// so only that tab gets "original" as a fallback when
// no attr is set.
var stored = td.getAttribute('data-lang-' + lang.id);
var isPreferred = Number(lang.id) === preferredId;
pane.value = (stored !== null) ? stored : (isPreferred ? original : '');
panes.appendChild(pane);
byId[lang.id] = pane;
if (isPreferred) {
tab.classList.add('ml-langtabs-tab-active');
activeId = lang.id;
} else {
pane.style.display = 'none';
}
tab.addEventListener('click', function () {
Array.prototype.forEach.call(
bar.querySelectorAll('.ml-langtabs-tab'),
function (t) { t.classList.remove('ml-langtabs-tab-active'); }
);
tab.classList.add('ml-langtabs-tab-active');
Object.keys(byId).forEach(function (id) {
byId[id].style.display = (String(id) === String(lang.id)) ? '' : 'none';
});
activeId = lang.id;
byId[lang.id].focus();
});
});
wrap.appendChild(bar);
wrap.appendChild(panes);
return {
element: wrap,
multilang: true,
getValue: function () {
var out = {};
Object.keys(byId).forEach(function (id) {
out[id] = byId[id].value;
});
return out;
},
getPrimaryValue: function () {
return (activeId !== null && byId[activeId]) ? byId[activeId].value : '';
},
focus: function () {
var pane = (activeId !== null) ? byId[activeId] : null;
if (pane) { pane.focus(); pane.select(); }
}
};
}
function buildPopupTextarea(original) {
var ta = document.createElement('textarea');
ta.value = original;
ta.rows = 6;
return {
element: ta,
getValue: function () { return ta.value; },
focus: function () { ta.focus(); ta.select(); }
};
}
function buildPopupTextInput(original, datalistId) {
var input = document.createElement('input');
input.type = 'text';
input.value = original;
input.className = 'ml-popup-input';
if (datalistId) input.setAttribute('list', datalistId);
return {
element: input,
getValue: function () { return input.value; },
focus: function () { input.focus(); input.select(); }
};
}
// Typed custom-subfield widgets. They round-trip the editor-RAW
// value (data-value): checkbox → "1"/"0", date → "Y-m-d", select
// → option id. The cell's visible text is a glyph / label, not
// the value, so these never read it.
function buildPopupCheckbox(original) {
var label = document.createElement('label');
label.className = 'ml-popup-checkbox';
var cb = document.createElement('input');
cb.type = 'checkbox';
cb.className = 'uk-checkbox';
cb.checked = (original === '1' || original === 'on' || original === 'true');
label.appendChild(cb);
label.appendChild(document.createTextNode(' ' + (labels.enabled || 'Enabled')));
return {
element: label,
getValue: function () { return cb.checked ? '1' : '0'; },
focus: function () { cb.focus(); }
};
}
function buildPopupDate(td, original) {
var input = document.createElement('input');
input.type = (td && td.dataset.datetime === '1') ? 'datetime-local' : 'date';
input.className = 'ml-popup-input';
input.value = original || '';
return {
element: input,
getValue: function () { return input.value; },
focus: function () { input.focus(); }
};
}
function buildPopupSelect(td, original) {
var options = [];
try { options = JSON.parse(td.dataset.options || '[]'); }
catch (e) { options = []; }
var multiple = td.dataset.multiple === '1';
var current = String(original || '').split(',').filter(Boolean);
// Multi-select renders as a checkbox list — <select multiple>
// is a UX nightmare (ctrl/cmd-click discoverability, no
// touch-friendly behaviour, broken under uk-select's
// appearance:none reset). Single keeps the native <select>.
if (multiple) {
var wrap = document.createElement('div');
wrap.className = 'ml-popup-checklist';
options.forEach(function (o) {
var lbl = document.createElement('label');
lbl.className = 'ml-popup-checklist-item';
var cb = document.createElement('input');
cb.type = 'checkbox';
cb.className = 'uk-checkbox';
cb.value = String(o.value);
if (current.indexOf(String(o.value)) !== -1) cb.checked = true;
lbl.appendChild(cb);
lbl.appendChild(document.createTextNode(' ' + o.label));
wrap.appendChild(lbl);
});
return {
element: wrap,
getValue: function () {
return Array.prototype.filter
.call(wrap.querySelectorAll('input[type="checkbox"]'), function (cb) { return cb.checked; })
.map(function (cb) { return cb.value; })
.join(',');
},
focus: function () {
var first = wrap.querySelector('input[type="checkbox"]');
if (first) first.focus();
}
};
}
var select = document.createElement('select');
select.className = 'ml-popup-input uk-select';
var blank = document.createElement('option');
blank.value = '';
blank.textContent = '—';
select.appendChild(blank);
options.forEach(function (o) {
var opt = document.createElement('option');
opt.value = String(o.value);
opt.textContent = o.label;
if (current.indexOf(String(o.value)) !== -1) opt.selected = true;
select.appendChild(opt);
});
return {
element: select,
getValue: function () { return select.value; },
focus: function () { select.focus(); }
};
}
function buildPopupNumber(original) {
var input = document.createElement('input');
input.type = 'number';
input.className = 'ml-popup-input';
input.step = 'any';
input.value = original || '';
return {
element: input,
getValue: function () { return input.value; },
focus: function () { input.focus(); input.select(); }
};
}
// Filename rename: text input for the stem with the original
// extension visible-but-locked beside it. The widget only ever
// reports the stem back; commit() reattaches the extension on
// the server side using the original basename it has on file.
function buildPopupFilename(td) {
var wrap = document.createElement('div');
wrap.className = 'ml-popup-filename';
var input = document.createElement('input');
input.type = 'text';
input.className = 'ml-popup-input';
input.value = td.dataset.stem || '';
input.setAttribute('aria-label', labels.rename || 'New filename');
input.setAttribute('autocomplete', 'off');
input.setAttribute('spellcheck', 'false');
var extSpan = document.createElement('span');
extSpan.className = 'ml-popup-filename-ext';
extSpan.textContent = td.dataset.ext || '';
wrap.appendChild(input);
wrap.appendChild(extSpan);
return {
element: wrap,
rename: true,
getValue: function () { return input.value; },
focus: function () { input.focus(); input.select(); }
};
}
// POST to the tag-bulk endpoint (preview count or apply).
function tagBulkFetch(params) {
var fd = new FormData();
Object.keys(params).forEach(function (k) { fd.append(k, params[k]); });
return postForm(config.tagBulkUrl, fd)
.then(function (r) { return r.json(); });
}
// A small icon button for the manage controls on a predefined-tag chip.
function mkTagBtn(cls, icon, title, onClick) {
var b = document.createElement('button');
b.type = 'button';
b.className = 'ml-tag-manage ' + cls;
b.dataset.tip = title;
b.setAttribute('aria-label', title);
b.innerHTML = '<i class="fa ' + icon + '" aria-hidden="true"></i>';
// mousedown preventDefault keeps focus on the inline-edit input so a
// click on ✓ commits instead of blurring (which would cancel).