PluginProbe
Blockenberg — 600+ Advanced Gutenberg Blocks & AI Agent for WordPress Block Editor / 2.0.14
Blockenberg — 600+ Advanced Gutenberg Blocks & AI Agent for WordPress Block Editor v2.0.14
2.0.14 2.0.13 2.0.12 2.0.11 2.0.10 2.0.9 trunk 2.0.2 2.0.3 2.0.4 2.0.5 2.0.6 2.0.7 2.0.8
blockenberg / assets / js / template-catalog.js

template-catalog.js in Blockenberg — 600+ Advanced Gutenberg Blocks & AI Agent for WordPress Block Editor 2.0.14, at assets/js/template-catalog.js

382 lines 22.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 (function () {
2 'use strict';
3 var root = document.getElementById('bkbg-template-catalog');
4 if (!root) return;
5 var timer, controller, sequence = 0;
6 var dialog, frame, status, fallback, returnFocus, previewKey, previewOrigin, loadingTimer;
7 var deviceWidths = { desktop: null, tablet: 768, mobile: 375 };
8 var focusSelector = 'button:not([disabled]),a[href],iframe,input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]';
9 var liveAvailable = typeof window.fetch === 'function' && typeof window.AbortController === 'function' &&
10 typeof window.FormData === 'function' && typeof window.DOMParser === 'function';
11 if (liveAvailable) root.classList.add('has-live-search');
12
13 function focusables(container) {
14 return Array.from(container.querySelectorAll(focusSelector)).filter(function (node) {
15 return node.tabIndex >= 0 && !node.closest('[hidden],[inert]');
16 });
17 }
18
19 function previewURL(link) {
20 try {
21 var key = link.dataset.previewKey;
22 if (!/^[a-z0-9][a-z0-9-]{0,159}$/.test(key || '')) return null;
23 var url = new URL(link.href, location.href);
24 if (url.username || url.password || !/^https?:$/.test(url.protocol)) return null;
25 // Validate the raw href before URL normalization can hide traversal/escaping.
26 var source = link.getAttribute('href');
27 var publicMatch = /^https:\/\/templates\.blockenberg\.com\/template-library\/previews\/([A-Za-z0-9][A-Za-z0-9_-]{0,79})\/([a-z0-9][a-z0-9-]{0,159})\/$/.exec(source);
28 if (publicMatch && publicMatch[0] === source && publicMatch[2] === key) return url;
29 } catch (error) { /* A malformed URL cannot be embedded. */ }
30 return null;
31 }
32
33 function setDevice(device) {
34 if (!Object.prototype.hasOwnProperty.call(deviceWidths, device)) return;
35 var width = deviceWidths[device];
36 frame.style.width = width === null ? '100%' : width + 'px';
37 frame.setAttribute('width', width === null ? '100%' : width);
38 root.querySelector('[data-preview-stage]').dataset.device = device;
39 var size = dialog.querySelector('[data-preview-size]');
40 if (size) size.textContent = width === null ? 'Full width' : width + ' px';
41 root.querySelector('[data-preview-stage]').scrollLeft = 0;
42 dialog.querySelectorAll('[data-preview-device]').forEach(function (button) {
43 button.setAttribute('aria-pressed', String(button.dataset.previewDevice === device));
44 });
45 }
46
47 function closePreview() {
48 if (!dialog || !dialog.open) return;
49 dialog.close();
50 resetPreview();
51 }
52
53 function resetPreview() {
54 clearTimeout(loadingTimer);
55 frame.src = 'about:blank';
56 frame.removeAttribute('aria-busy');
57 document.documentElement.classList.remove('bkbg-preview-open');
58 var target = returnFocus;
59 if (!target || !target.isConnected) {
60 target = Array.from(root.querySelectorAll('[data-bkbg-preview]')).find(function (link) {
61 return link.dataset.previewKey === previewKey;
62 }) || root.querySelector('#bkbg-catalog-search') || root.querySelector('.bkbg-catalog-tabs a');
63 }
64 returnFocus = null;
65 previewOrigin = null;
66 if (target) target.focus({ preventScroll: true });
67 }
68
69 function openPreview(link, url) {
70 returnFocus = link;
71 previewKey = link.dataset.previewKey;
72 previewOrigin = url.origin;
73 var title = link.dataset.previewTitle || 'Template';
74 dialog.querySelector('#bkbg-preview-title').textContent = title;
75 frame.title = title + ' — native Blockenberg preview';
76 fallback.href = url.href;
77 setDevice('desktop');
78 status.textContent = 'Loading preview…';
79 dialog.classList.remove('is-ready', 'is-slow');
80 dialog.classList.add('is-loading');
81 frame.setAttribute('aria-busy', 'true');
82 dialog.showModal();
83 document.documentElement.classList.add('bkbg-preview-open');
84 dialog.querySelector('[data-preview-close]').focus();
85 frame.src = url.href;
86 clearTimeout(loadingTimer);
87 loadingTimer = setTimeout(function () {
88 if (dialog.open) {
89 dialog.classList.add('is-slow');
90 status.textContent = 'Preview is taking longer than expected. Use the open-page button above to view it directly.';
91 }
92 }, 15000);
93 }
94
95 function bindPreview() {
96 dialog = root.querySelector('#bkbg-template-preview');
97 if (!dialog) return;
98 frame = dialog.querySelector('iframe');
99 status = dialog.querySelector('.bkbg-preview-status');
100 fallback = dialog.querySelector('[data-preview-fallback]');
101 dialog.addEventListener('cancel', function (event) {
102 event.preventDefault();
103 closePreview();
104 });
105 dialog.addEventListener('close', function () {
106 // A queued close event must not clear a newly reopened preview.
107 if (!dialog.open && returnFocus) resetPreview();
108 });
109 frame.addEventListener('load', function () {
110 if (!dialog.open || frame.getAttribute('src') === 'about:blank') return;
111 clearTimeout(loadingTimer);
112 frame.removeAttribute('aria-busy');
113 dialog.classList.remove('is-loading', 'is-slow');
114 dialog.classList.add('is-ready');
115 status.textContent = 'Preview loaded.';
116 try {
117 var inner = frame.contentDocument;
118 if (!inner) return;
119 // Same-origin authoring previews can forward keyboard input directly.
120 inner.addEventListener('keydown', function (event) {
121 if (event.defaultPrevented || !dialog.open) return;
122 if (event.key === 'Escape') {
123 event.preventDefault();
124 closePreview();
125 } else if (event.key === 'Tab') {
126 var nodes = focusables(inner).filter(function (node) {
127 return node.getClientRects().length > 0;
128 });
129 var active = inner.activeElement;
130 if (!nodes.length || (event.shiftKey && active === nodes[0]) ||
131 (!event.shiftKey && active === nodes[nodes.length - 1])) {
132 var outer = focusables(dialog), index = outer.indexOf(frame);
133 var target = outer[(index + (event.shiftKey ? -1 : 1) + outer.length) % outer.length];
134 if (target) { event.preventDefault(); target.focus(); }
135 }
136 }
137 });
138 } catch (error) { /* Public previews use the validated postMessage bridge. */ }
139 });
140 }
141 bindPreview();
142
143 document.addEventListener('keydown', function (event) {
144 if (!dialog || !dialog.open || event.defaultPrevented) return;
145 if (event.key === 'Escape') {
146 event.preventDefault();
147 closePreview();
148 } else if (event.key === 'Tab') {
149 var nodes = focusables(dialog), first = nodes[0], last = nodes[nodes.length - 1];
150 var active = document.activeElement;
151 if (event.shiftKey && (active === first || active === dialog)) {
152 event.preventDefault(); last.focus();
153 } else if (!event.shiftKey && (active === last || active === dialog)) {
154 event.preventDefault(); first.focus();
155 }
156 }
157 });
158 document.addEventListener('focusin', function (event) {
159 if (dialog && dialog.open && !dialog.contains(event.target)) dialog.querySelector('[data-preview-close]').focus();
160 });
161 window.addEventListener('message', function (event) {
162 if (!dialog || !dialog.open || event.source !== frame.contentWindow || event.origin !== previewOrigin) return;
163 if (event.data && event.data.type === 'bkbg-template-preview:escape') closePreview();
164 });
165
166 // Match King Addons: a new search/category/collection/tag replaces the previous filter.
167 function resetOtherFilters(active) {
168 var form = root.querySelector('#bkbg-catalog-filters');
169 form.querySelectorAll('input[name="s"],select[name="category"],select[name="collection"],input[name="tags[]"],input[name="plan"]').forEach(function (node) {
170 if (node === active) return;
171 if (node.type === 'checkbox') node.checked = false;
172 else if (node.type === 'radio') node.checked = active.name !== 'plan' && node.value === '';
173 else node.value = '';
174 });
175 }
176
177 function filtersURL() {
178 var form = root.querySelector('#bkbg-catalog-filters'), url = new URL(form.action);
179 new FormData(form).forEach(function (value, key) { if (value !== '') url.searchParams.append(key, value); });
180 return url;
181 }
182 function sameFilters(first, second) {
183 function values(url) {
184 var tags = [];
185 url.searchParams.forEach(function (value, key) {
186 if (/^tags\[\d*\]$/.test(key) && value !== '') tags.push(value);
187 });
188 return ['view', 's', 'category', 'collection', 'plan'].map(function (key) {
189 return url.searchParams.get(key) || (key === 'view' ? 'templates' : '');
190 }).concat(tags.sort());
191 }
192 return JSON.stringify(values(first)) === JSON.stringify(values(second));
193 }
194 async function load(url, partial, historyMode) {
195 clearTimeout(timer);
196 if (controller) controller.abort();
197 controller = new AbortController();
198 var run = ++sequence, content = root.querySelector('.bkbg-catalog-content');
199 var requestController = controller, timedOut = false;
200 var requestTimer = setTimeout(function () { timedOut = true; requestController.abort(); }, 20000);
201 content.setAttribute('aria-busy', 'true');
202 try {
203 var response = await fetch(url, { credentials: 'same-origin', signal: requestController.signal });
204 if (!response.ok) throw new Error('Unable to load library');
205 var doc = new DOMParser().parseFromString(await response.text(), 'text/html');
206 var next = doc.querySelector('#bkbg-template-catalog');
207 if (run !== sequence) return;
208 var nextResults = next && next.querySelector('#bkbg-catalog-results');
209 var nextForms = next && next.querySelector('#bkbg-catalog-import-forms');
210 if (!nextResults || !nextForms || !next.querySelector('#bkbg-catalog-filters') ||
211 !next.querySelector('.bkbg-catalog-content')) throw new Error('Library is unavailable');
212 if (partial) {
213 var currentResults = root.querySelector('#bkbg-catalog-results');
214 var currentForms = root.querySelector('#bkbg-catalog-import-forms');
215 if (!currentResults || !currentForms) throw new Error('Library is unavailable');
216 var resultsHadFocus = currentResults.contains(document.activeElement);
217 // Validate both fragments first: card indices and import form keys must stay paired.
218 currentResults.replaceWith(nextResults);
219 currentForms.replaceWith(nextForms);
220 content.removeAttribute('aria-busy');
221 if (resultsHadFocus && (!dialog || !dialog.open)) {
222 nextResults.setAttribute('tabindex', '-1');
223 nextResults.focus({ preventScroll: true });
224 }
225 } else {
226 var previewWasOpen = dialog && dialog.open;
227 var catalogHadFocus = root.contains(document.activeElement);
228 closePreview();
229 root.replaceWith(next);
230 root = next;
231 root.classList.add('has-live-search');
232 bindPreview();
233 if (previewWasOpen || catalogHadFocus) {
234 var target = Array.from(root.querySelectorAll('[data-bkbg-preview]')).find(function (link) {
235 return previewWasOpen && link.dataset.previewKey === previewKey;
236 }) || root.querySelector('#bkbg-catalog-search');
237 if (target) target.focus({ preventScroll: true });
238 }
239 }
240 root.querySelector('.bkbg-catalog-load-error')?.remove();
241 root.classList.add('has-live-search');
242 if (historyMode === 'replace') history.replaceState({}, '', url);
243 else if (historyMode !== false) history.pushState({}, '', url);
244 } catch (error) {
245 if ((error.name === 'AbortError' && !timedOut) || run !== sequence) return;
246 content.removeAttribute('aria-busy');
247 var msg = document.createElement('p');
248 msg.className = 'bkbg-catalog-load-error';
249 msg.setAttribute('role', 'alert');
250 msg.textContent = timedOut ? 'Loading templates timed out. Use Search to try again.' : 'Unable to load templates. Use Search to try again.';
251 root.querySelector('.bkbg-catalog-load-error')?.remove();
252 content.prepend(msg);
253 root.classList.remove('has-live-search');
254 } finally {
255 clearTimeout(requestTimer);
256 }
257 }
258 document.addEventListener('input', function (event) {
259 if (liveAvailable && root.contains(event.target) && event.target.id === 'bkbg-catalog-search') {
260 clearTimeout(timer);
261 if (controller) controller.abort();
262 ++sequence;
263 resetOtherFilters(event.target);
264 timer = setTimeout(function () { load(filtersURL(), true, 'replace'); }, 250);
265 }
266 });
267 document.addEventListener('change', function (event) {
268 if (liveAvailable && root.contains(event.target) && event.target.closest('#bkbg-catalog-filters') && event.target.id !== 'bkbg-catalog-search') {
269 resetOtherFilters(event.target);
270 load(filtersURL(), true);
271 }
272 });
273 var importDialog, importBusy = false, importReturnFocus;
274 function showImport() {
275 if (!importDialog) {
276 importDialog = document.createElement('dialog');
277 importDialog.className = 'bkbg-import-dialog';
278 importDialog.setAttribute('aria-labelledby', 'bkbg-import-title');
279 importDialog.innerHTML = '<h2 id="bkbg-import-title"><span class="bkbg-import-indicator" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle class="bkbg-import-track" cx="12" cy="12" r="9"/><circle class="bkbg-import-spin" cx="12" cy="12" r="9"/><path class="bkbg-import-check" d="m6 12 4 4 8-8"/><path class="bkbg-import-error" d="M12 7v6m0 4h.01"/></svg></span>Import template</h2><p class="bkbg-import-message" role="status" aria-live="polite"></p><progress max="100" value="0" aria-label="Template import progress"></progress><p class="bkbg-import-percent">0%</p><p class="bkbg-import-note">Keep this window open while your draft is prepared.</p><div class="bkbg-import-actions"><a class="button button-primary" hidden>Open in editor</a><button type="button" class="button" disabled>Close</button></div>';
280 document.body.appendChild(importDialog);
281 importDialog.addEventListener('cancel', function(event) { if (importBusy) event.preventDefault(); });
282 importDialog.querySelector('button').addEventListener('click', function() { importDialog.close(); });
283 importDialog.addEventListener('close', function() { if (importReturnFocus?.isConnected) importReturnFocus.focus(); });
284 }
285 importDialog.dataset.state = 'loading';
286 importDialog.querySelector('a').hidden = true;
287 importDialog.querySelector('button').disabled = true;
288 importDialog.querySelector('progress').value = 0;
289 importDialog.querySelector('.bkbg-import-percent').textContent = '0%';
290 importDialog.querySelector('.bkbg-import-message').setAttribute('role', 'status');
291 importDialog.querySelector('.bkbg-import-message').textContent = 'Starting import…';
292 importDialog.querySelector('.bkbg-import-note').textContent = 'Keep this window open while your draft is prepared.';
293 if (!importDialog.open) importDialog.showModal();
294 }
295 async function importTemplate(form, submitter) {
296 if (importBusy) return;
297 importBusy = true; importReturnFocus = submitter;
298 if (submitter) submitter.disabled = true;
299 var completed = false, failed = false;
300 function message(row) {
301 if (row.type === 'progress') {
302 var percent = Math.max(0, Math.min(100, Number(row.percent) || 0));
303 importDialog.querySelector('progress').value = percent;
304 importDialog.querySelector('.bkbg-import-percent').textContent = percent + '%';
305 importDialog.querySelector('.bkbg-import-message').textContent = String(row.message || 'Importing…');
306 } else if (row.type === 'error') { failed = true; throw new Error(row.message || 'Import failed.'); }
307 else if (row.type === 'complete') {
308 var url = new URL(row.editUrl, location.href);
309 if (url.origin !== location.origin || !/\/wp-admin\/post\.php$/.test(url.pathname) || url.searchParams.get('action') !== 'edit' || url.searchParams.get('post') !== String(row.postId)) throw new Error('Invalid editor link.');
310 completed = true;
311 importDialog.dataset.state = 'complete';
312 importDialog.querySelector('progress').value = 100;
313 importDialog.querySelector('.bkbg-import-percent').textContent = '100%';
314 importDialog.querySelector('.bkbg-import-message').textContent = 'Your draft is ready.';
315 importDialog.querySelector('.bkbg-import-note').textContent = 'Open it in the editor when you are ready. The page has not been published.';
316 var link = importDialog.querySelector('a'); link.href = url.href; link.hidden = false; link.focus();
317 }
318 }
319 try {
320 showImport();
321 var response = await fetch(root.dataset.importUrl, { method: 'POST', credentials: 'same-origin', body: new FormData(form), headers: { Accept: 'application/x-ndjson' } });
322 if (!response.ok) throw new Error(response.status === 403 ? 'Import denied. Refresh the library and check your access.' : 'Import request failed (HTTP ' + response.status + ').');
323 var pending = '';
324 function consume(text, final) {
325 pending += text; var lines = pending.split('\n'); pending = lines.pop();
326 lines.forEach(function(line) { if (line.trim()) message(JSON.parse(line)); });
327 if (final && pending.trim()) { message(JSON.parse(pending)); pending = ''; }
328 }
329 if (response.body?.getReader && typeof TextDecoder === 'function') {
330 var reader = response.body.getReader(), decoder = new TextDecoder();
331 while (true) { var chunk = await reader.read(); if (chunk.done) break; consume(decoder.decode(chunk.value, {stream:true}), false); }
332 consume(decoder.decode(), true);
333 } else consume(await response.text(), true);
334 if (!completed) throw new Error('Import did not finish. Check Pages for a draft before retrying.');
335 } catch (error) {
336 importDialog.dataset.state = 'error';
337 importDialog.querySelector('a').hidden = true;
338 importDialog.querySelector('.bkbg-import-message').textContent = error.name === 'SyntaxError' ? 'Unexpected server response. Check Pages for a draft before retrying.' : (error.message || 'Import failed.');
339 importDialog.querySelector('.bkbg-import-message').setAttribute('role', 'alert');
340 importDialog.querySelector('.bkbg-import-note').textContent = failed ? 'Nothing was opened. Close this window to return to the library.' : 'Check Pages for a draft before retrying if the connection was interrupted.';
341 } finally {
342 importBusy = false; if (submitter?.isConnected) submitter.disabled = false;
343 importDialog.querySelector('button').disabled = false;
344 }
345 }
346 document.addEventListener('submit', function (event) {
347 if (root.contains(event.target) && event.target.id.indexOf('bkbg-catalog-import-') === 0 && typeof fetch === 'function' && typeof FormData === 'function' && typeof HTMLDialogElement !== 'undefined' && typeof HTMLDialogElement.prototype.showModal === 'function') { event.preventDefault(); importTemplate(event.target, event.submitter); return; }
348 if (liveAvailable && root.contains(event.target) && event.target.id === 'bkbg-catalog-filters') { event.preventDefault(); load(filtersURL(), true); }
349 });
350 document.addEventListener('click', function (event) {
351 if (!root.contains(event.target)) return;
352 var close = event.target.closest('[data-preview-close]');
353 if (close) { closePreview(); return; }
354 var device = event.target.closest('[data-preview-device]');
355 if (device) { setDevice(device.dataset.previewDevice); return; }
356 if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey || event.button) return;
357 var preview = event.target.closest('[data-bkbg-preview]');
358 if (preview) {
359 var url = previewURL(preview);
360 if (!url) { event.preventDefault(); return; }
361 // Unsupported browsers retain the safe, same-tab ordinary link.
362 if (!dialog || typeof dialog.showModal !== 'function') return;
363 event.preventDefault();
364 openPreview(preview, url);
365 return;
366 }
367 if (event.target === dialog && dialog.open) {
368 var rect = dialog.getBoundingClientRect();
369 if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) closePreview();
370 return;
371 }
372 var anchor = event.target.closest('.bkbg-catalog-pagination a,.bkbg-catalog-tabs a,.bkbg-catalog-reset,.bkbg-catalog-empty a,.bkbg-catalog-collection a');
373 if (!anchor || !liveAvailable) return;
374 event.preventDefault();
375 var pagination = !!anchor.closest('.bkbg-catalog-pagination'), url = new URL(anchor.href);
376 // A pending search/filter change makes old pagination links stale. Apply the current filters first.
377 if (pagination && !sameFilters(filtersURL(), url)) url = filtersURL();
378 load(url, pagination);
379 });
380 window.addEventListener('popstate', function () { if (liveAvailable) load(new URL(location.href), false, false); });
381 })();
382