WebOrbiton
v3.1.0.0

FlatlyPage

1,262 lines · 75.0 KB
  1. const BLOCK_UI_ICONS = {
  2. check: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="20 6 9 17 4 12"/></svg>',
  3. cross: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',
  4. close: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',
  5. prev: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="15 18 9 12 15 6"/></svg>',
  6. next: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="9 18 15 12 9 6"/></svg>',
  7. pin: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>',
  8. phone: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/></svg>',
  9. mail: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>',
  10. clock: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>',
  11. info: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>',
  12. success: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
  13. warning: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
  14. accent: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>',
  15. download: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>',
  16. file: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>',
  17. quote: '<svg viewBox="0 0 32 32" fill="currentColor" aria-hidden="true" focusable="false"><path d="M9.3 26C5.4 26 3 23 3 19.3 3 12.6 7.6 7.3 13.7 6l1 2.4c-3.6 1.3-6 4.2-6.3 7.3.5-.2 1.1-.3 1.8-.3 3 0 5.2 2.2 5.2 5.2S13 26 9.3 26zm15.7 0c-3.9 0-6.3-3-6.3-6.7 0-6.7 4.6-12 10.7-13.3l1 2.4c-3.6 1.3-6 4.2-6.3 7.3.5-.2 1.1-.3 1.8-.3 3 0 5.2 2.2 5.2 5.2S28.7 26 25 26z"/></svg>'
  18. };
  19. ​
  20. const BLOCK_EDITOR_ICONS = {
  21. up: '<svg fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24" width="14" height="14"><polyline points="18 15 12 9 6 15"/></svg>',
  22. down: '<svg fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24" width="14" height="14"><polyline points="6 9 12 15 18 9"/></svg>',
  23. plus: '<svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" width="16" height="16"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>',
  24. trash: '<svg fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24" width="14" height="14"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>'
  25. };
  26. ​
  27. const COMPARISON_YES = ['yes', 'y', 'true', 'tak', 'ja', 'oui', 'sí', 'si', 'sim', 'да', '✓', '✔', '✅', '+'];
  28. const COMPARISON_NO = ['no', 'n', 'false', 'nie', 'nein', 'non', 'não', 'нет', '✗', '✕', '✘', 'x', '❌'];
  29. const COMPARISON_DASH = ['', '-', '–', '—'];
  30. ​
  31. function bEsc(value) {
  32. if (value === null || value === undefined) return '';
  33. return String(value)
  34. .replace(/&/g, '&amp;')
  35. .replace(/</g, '&lt;')
  36. .replace(/>/g, '&gt;')
  37. .replace(/"/g, '&quot;')
  38. .replace(/'/g, '&#39;');
  39. }
  40. ​
  41. function bText(value) {
  42. if (value === null || value === undefined || typeof value === 'object') return '';
  43. return String(value).trim();
  44. }
  45. ​
  46. function bLines(value) {
  47. return bEsc(bText(value)).replace(/\r\n|\r|\n/g, '<br>');
  48. }
  49. ​
  50. function bList(value) {
  51. return Array.isArray(value) ? value.filter(item => item && typeof item === 'object' && !Array.isArray(item)) : [];
  52. }
  53. ​
  54. function bChoice(value, allowed, fallback) {
  55. return allowed.includes(value) ? value : fallback;
  56. }
  57. ​
  58. function bInt(value, min, max, fallback) {
  59. const number = typeof value === 'number' ? value : (/^-?\d+$/.test(String(value ?? '').trim()) ? parseInt(value, 10) : NaN);
  60. if (!Number.isFinite(number)) return fallback;
  61. return Math.max(min, Math.min(max, Math.round(number)));
  62. }
  63. ​
  64. function bFlag(data, key, fallback) {
  65. if (!data || !(key in data)) return fallback;
  66. const value = data[key];
  67. if (typeof value === 'string') return !['', '0', 'false', 'no', 'off'].includes(value.trim().toLowerCase());
  68. return !!value;
  69. }
  70. ​
  71. function bIsExternal(url) {
  72. return /^(?:https?:)?\/\//i.test(bText(url));
  73. }
  74. ​
  75. function bTarget(url) {
  76. return bIsExternal(url) ? ' target="_blank" rel="noopener"' : '';
  77. }
  78. ​
  79. function bHeader(d) {
  80. const title = bText(d.title);
  81. const subtitle = bText(d.subtitle);
  82. if (!title && !subtitle) return '';
  83. return `<div class="section-header">${title ? `<h2>${bEsc(title)}</h2>` : ''}${subtitle ? `<p>${bLines(subtitle)}</p>` : ''}</div>`;
  84. }
  85. ​
  86. function blockPlatformLabel(platform) {
  87. const found = (typeof SOCIAL_PLATFORMS !== 'undefined' ? SOCIAL_PLATFORMS : []).find(entry => entry[0] === platform);
  88. if (platform === 'twitter') return 'X';
  89. return found ? found[1] : platform;
  90. }
  91. ​
  92. function defaultBlockTimezone() {
  93. const zones = typeof BLOCK_TIMEZONES !== 'undefined' && Array.isArray(BLOCK_TIMEZONES) ? BLOCK_TIMEZONES : [];
  94. try {
  95. const local = Intl.DateTimeFormat().resolvedOptions().timeZone;
  96. if (local && zones.includes(local)) return local;
  97. } catch (e) {}
  98. return zones.includes('Europe/Warsaw') ? 'Europe/Warsaw' : 'UTC';
  99. }
  100. ​
  101. function zonedTimeToUtc(date, time, timezone) {
  102. const d = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date || '');
  103. if (!d) return null;
  104. const t = /^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/.exec(time || '') || [null, '00', '00', '00'];
  105. const guess = Date.UTC(+d[1], +d[2] - 1, +d[3], +t[1], +t[2], +(t[3] || 0));
  106. let formatter;
  107. try {
  108. formatter = new Intl.DateTimeFormat('en-US', {
  109. timeZone: timezone || 'UTC', hourCycle: 'h23',
  110. year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'
  111. });
  112. } catch (e) {
  113. return guess;
  114. }
  115. const offset = stamp => {
  116. const parts = {};
  117. formatter.formatToParts(new Date(stamp)).forEach(part => { parts[part.type] = part.value; });
  118. return Date.UTC(+parts.year, +parts.month - 1, +parts.day, +parts.hour % 24, +parts.minute, +parts.second) - stamp;
  119. };
  120. const first = guess - offset(guess);
  121. return guess - offset(first);
  122. }
  123. ​
  124. function bfLabel(text) {
  125. return `<label class="block-field-label">${text}</label>`;
  126. }
  127. ​
  128. function bfRow(...cells) {
  129. return `<div class="form-row">${cells.join('')}</div>`;
  130. }
  131. ​
  132. function bfHint(text) {
  133. return `<p class="block-field-hint">${text}</p>`;
  134. }
  135. ​
  136. function bfInput(bi, key, label, value, extra = '') {
  137. return `<div class="block-field">${bfLabel(label)}<input type="text" class="block-field-input" value="${bEsc(value)}" ${extra} oninput="updateBlockData(${bi}, '${key}', this.value)"></div>`;
  138. }
  139. ​
  140. function bfTextarea(bi, key, label, value, extra = '', rich = true) {
  141. return `<div class="block-field">${bfLabel(label)}<textarea ${rich ? 'data-rich="1" ' : ''}class="block-field-input block-field-textarea" ${extra} oninput="updateBlockData(${bi}, '${key}', this.value)">${bEsc(value)}</textarea></div>`;
  142. }
  143. ​
  144. function bfNumber(bi, key, label, value, min, max, step = 1) {
  145. return `<div class="block-field">${bfLabel(label)}<input type="number" class="block-field-input" data-no-translate value="${bEsc(value)}" min="${min}" max="${max}" step="${step}" oninput="updateBlockData(${bi}, '${key}', this.value === '' ? '' : Number(this.value))"></div>`;
  146. }
  147. ​
  148. function bfSelect(bi, key, label, value, options, rerender = false) {
  149. return `<div class="block-field">${bfLabel(label)}<select class="block-field-input" onchange="updateBlockData(${bi}, '${key}', this.value)${rerender ? '; renderBlocks()' : ''}">${options.map(([optionValue, optionLabel]) => `<option value="${bEsc(optionValue)}" ${String(value) === String(optionValue) ? 'selected' : ''}>${bEsc(optionLabel)}</option>`).join('')}</select></div>`;
  150. }
  151. ​
  152. function bfCheck(bi, key, label, checked, rerender = false) {
  153. return `<div class="block-field"><label class="block-field-label block-field-check"><input type="checkbox" ${checked ? 'checked' : ''} onchange="updateBlockData(${bi}, '${key}', this.checked)${rerender ? '; renderBlocks()' : ''}">${label}</label></div>`;
  154. }
  155. ​
  156. function bfMedia(bi, key, label, value, kind, placeholder = 'https://...') {
  157. return `<div class="block-field">${bfLabel(label)}<input type="text" data-media="${kind}" class="block-field-input" value="${bEsc(value)}" placeholder="${bEsc(placeholder)}" oninput="updateBlockData(${bi}, '${key}', this.value)"></div>`;
  158. }
  159. ​
  160. function bfLink(bi, key, label, value) {
  161. return `<div class="block-field">${bfLabel(label)}${renderLinkInput(value || '', `updateBlockData(${bi}, '${key}', VALUE)`)}</div>`;
  162. }
  163. ​
  164. function rfInput(bi, list, i, key, label, value, extra = '') {
  165. return `<div class="block-field">${bfLabel(label)}<input type="text" class="block-field-input" value="${bEsc(value)}" ${extra} oninput="updateRepeaterItem(${bi}, '${list}', ${i}, '${key}', this.value)"></div>`;
  166. }
  167. ​
  168. function rfTextarea(bi, list, i, key, label, value, extra = '') {
  169. return `<div class="block-field">${bfLabel(label)}<textarea data-rich="1" class="block-field-input block-field-textarea" ${extra} oninput="updateRepeaterItem(${bi}, '${list}', ${i}, '${key}', this.value)">${bEsc(value)}</textarea></div>`;
  170. }
  171. ​
  172. function rfMedia(bi, list, i, key, label, value, kind, placeholder = 'https://...') {
  173. return `<div class="block-field">${bfLabel(label)}<input type="text" data-media="${kind}" class="block-field-input" value="${bEsc(value)}" placeholder="${bEsc(placeholder)}" oninput="updateRepeaterItem(${bi}, '${list}', ${i}, '${key}', this.value)"></div>`;
  174. }
  175. ​
  176. function rfLink(bi, list, i, key, label, value) {
  177. return `<div class="block-field">${bfLabel(label)}${renderLinkInput(value || '', `updateRepeaterItem(${bi}, '${list}', ${i}, '${key}', VALUE)`)}</div>`;
  178. }
  179. ​
  180. function rfSelect(bi, list, i, key, label, value, options) {
  181. return `<div class="block-field">${bfLabel(label)}<select class="block-field-input" onchange="updateRepeaterItem(${bi}, '${list}', ${i}, '${key}', this.value); renderBlocks()">${options.map(([optionValue, optionLabel]) => `<option value="${bEsc(optionValue)}" ${String(value) === String(optionValue) ? 'selected' : ''}>${bEsc(optionLabel)}</option>`).join('')}</select></div>`;
  182. }
  183. ​
  184. function bfRepeater(bi, list, items, options) {
  185. const count = items.length;
  186. return `
  187. <div class="block-field">
  188. ${bfLabel(options.label)}
  189. <div class="repeater-items" data-key="${list}">
  190. ${items.map((item, i) => `
  191. <div class="repeater-item">
  192. <div class="repeater-item-header" onclick="this.parentElement.classList.toggle('expanded')">
  193. <span class="repeater-item-title">${bEsc(options.itemTitle(item, i))}</span>
  194. <div class="repeater-item-actions">
  195. <button type="button" class="btn btn-ghost btn-sm repeater-move" title="Move up" ${i === 0 ? 'disabled' : ''} onclick="event.stopPropagation(); moveRepeaterItem(${bi}, '${list}', ${i}, -1)">${BLOCK_EDITOR_ICONS.up}</button>
  196. <button type="button" class="btn btn-ghost btn-sm repeater-move" title="Move down" ${i >= count - 1 ? 'disabled' : ''} onclick="event.stopPropagation(); moveRepeaterItem(${bi}, '${list}', ${i}, 1)">${BLOCK_EDITOR_ICONS.down}</button>
  197. <button type="button" class="btn btn-ghost btn-sm" onclick="event.stopPropagation(); removeRepeaterItem(${bi}, '${list}', ${i})" style="color: var(--error);">Remove</button>
  198. </div>
  199. </div>
  200. <div class="repeater-item-content">${options.fields(item, i)}</div>
  201. </div>`).join('')}
  202. </div>
  203. <button type="button" class="repeater-add" onclick="addRepeaterItem(${bi}, '${list}', ${bEsc(JSON.stringify(options.defaults))})">${BLOCK_EDITOR_ICONS.plus} ${options.addLabel}</button>
  204. </div>`;
  205. }
  206. ​
  207. function bfSectionHeader(bi, d) {
  208. return bfRow(
  209. bfInput(bi, 'title', 'Section Title', d.title || ''),
  210. bfInput(bi, 'subtitle', 'Section Subtitle', d.subtitle || '')
  211. );
  212. }
  213. ​
  214. function moveRepeaterItem(blockIndex, key, itemIndex, dir) {
  215. const list = blocks[blockIndex]?.data?.[key];
  216. const target = itemIndex + dir;
  217. if (!Array.isArray(list) || target < 0 || target >= list.length) return;
  218. [list[itemIndex], list[target]] = [list[target], list[itemIndex]];
  219. renderBlocks();
  220. schedulePreviewUpdate();
  221. }
  222. ​
  223. function comparisonData(blockIndex) {
  224. const data = blocks[blockIndex].data || (blocks[blockIndex].data = {});
  225. if (!Array.isArray(data.columns)) data.columns = [];
  226. if (!Array.isArray(data.rows)) data.rows = [];
  227. return data;
  228. }
  229. ​
  230. function updateComparisonColumn(blockIndex, columnIndex, value) {
  231. const data = comparisonData(blockIndex);
  232. data.columns[columnIndex] = value;
  233. const block = document.querySelector(`.block-item[data-index="${blockIndex}"]`);
  234. if (block) {
  235. block.querySelectorAll(`[data-cmp-col="${columnIndex}"]`).forEach(el => { el.textContent = value || 'Column ' + (columnIndex + 1); });
  236. }
  237. schedulePreviewUpdate();
  238. }
  239. ​
  240. function addComparisonColumn(blockIndex) {
  241. const data = comparisonData(blockIndex);
  242. data.columns.push('');
  243. data.rows.forEach(row => {
  244. if (!Array.isArray(row.values)) row.values = [];
  245. while (row.values.length < data.columns.length) row.values.push('');
  246. });
  247. renderBlocks();
  248. schedulePreviewUpdate();
  249. const inputs = document.querySelectorAll(`.block-item[data-index="${blockIndex}"] .cmp-column-input`);
  250. if (inputs.length) inputs[inputs.length - 1].focus();
  251. }
  252. ​
  253. function removeComparisonColumn(blockIndex, columnIndex) {
  254. const data = comparisonData(blockIndex);
  255. data.columns.splice(columnIndex, 1);
  256. data.rows.forEach(row => {
  257. if (Array.isArray(row.values)) row.values.splice(columnIndex, 1);
  258. });
  259. const highlight = bInt(data.highlight, -1, 99, -1);
  260. if (highlight === columnIndex) data.highlight = -1;
  261. else if (highlight > columnIndex) data.highlight = highlight - 1;
  262. renderBlocks();
  263. schedulePreviewUpdate();
  264. }
  265. ​
  266. function moveComparisonColumn(blockIndex, columnIndex, dir) {
  267. const data = comparisonData(blockIndex);
  268. const target = columnIndex + dir;
  269. if (target < 0 || target >= data.columns.length) return;
  270. const swap = list => {
  271. while (list.length <= Math.max(columnIndex, target)) list.push('');
  272. [list[columnIndex], list[target]] = [list[target], list[columnIndex]];
  273. };
  274. swap(data.columns);
  275. data.rows.forEach(row => {
  276. if (!Array.isArray(row.values)) row.values = [];
  277. swap(row.values);
  278. });
  279. const highlight = bInt(data.highlight, -1, 99, -1);
  280. if (highlight === columnIndex) data.highlight = target;
  281. else if (highlight === target) data.highlight = columnIndex;
  282. renderBlocks();
  283. schedulePreviewUpdate();
  284. }
  285. ​
  286. function updateComparisonValue(blockIndex, rowIndex, columnIndex, value) {
  287. const data = comparisonData(blockIndex);
  288. const row = data.rows[rowIndex] || (data.rows[rowIndex] = { feature: '', values: [] });
  289. if (!Array.isArray(row.values)) row.values = [];
  290. while (row.values.length <= columnIndex) row.values.push('');
  291. row.values[columnIndex] = value;
  292. schedulePreviewUpdate();
  293. }
  294. ​
  295. function comparisonCellPreview(value, yesText, noText) {
  296. const raw = bText(value);
  297. const key = raw.toLowerCase();
  298. if (COMPARISON_YES.includes(key)) return `<span class="cmp-mark cmp-yes" title="${bEsc(yesText)}">${BLOCK_UI_ICONS.check}<span class="visually-hidden">${bEsc(yesText)}</span></span>`;
  299. if (COMPARISON_NO.includes(key)) return `<span class="cmp-mark cmp-no" title="${bEsc(noText)}">${BLOCK_UI_ICONS.cross}<span class="visually-hidden">${bEsc(noText)}</span></span>`;
  300. if (COMPARISON_DASH.includes(key)) return '<span class="cmp-dash" aria-hidden="true">—</span>';
  301. return `<span class="cmp-text">${bEsc(raw)}</span>`;
  302. }
  303. ​
  304. function contactPhoneHref(phone) {
  305. let digits = bText(phone).replace(/[^0-9+]/g, '');
  306. if (!digits) return '';
  307. let plus = digits[0] === '+';
  308. digits = digits.replace(/\+/g, '');
  309. if (!plus && digits.startsWith('00')) {
  310. plus = true;
  311. digits = digits.slice(2);
  312. }
  313. return digits ? 'tel:' + (plus ? '+' : '') + digits : '';
  314. }
  315. ​
  316. function contactMapEmbed(d) {
  317. const provider = bChoice(d.map_provider, ['none', 'osm', 'google'], 'none');
  318. const zoom = bInt(d.map_zoom, 3, 19, 15);
  319. if (provider === 'osm') {
  320. const latText = bText(d.map_lat);
  321. const lngText = bText(d.map_lng);
  322. if (latText === '' || lngText === '' || isNaN(Number(latText)) || isNaN(Number(lngText))) return null;
  323. const lat = Number(latText);
  324. const lng = Number(lngText);
  325. if (lat < -85 || lat > 85 || lng < -180 || lng > 180) return null;
  326. const lngSpan = 900 / Math.pow(2, zoom);
  327. const latSpan = lngSpan * Math.max(0.2, Math.cos(lat * Math.PI / 180)) * 0.6;
  328. const bbox = [lng - lngSpan / 2, lat - latSpan / 2, lng + lngSpan / 2, lat + latSpan / 2].map(n => n.toFixed(6)).join(',');
  329. return {
  330. src: `https://www.openstreetmap.org/export/embed.html?bbox=${encodeURIComponent(bbox)}&layer=mapnik&marker=${encodeURIComponent(lat.toFixed(6) + ',' + lng.toFixed(6))}`,
  331. link: `https://www.openstreetmap.org/?mlat=${lat.toFixed(6)}&mlon=${lng.toFixed(6)}#map=${zoom}/${lat.toFixed(6)}/${lng.toFixed(6)}`
  332. };
  333. }
  334. if (provider === 'google') {
  335. const query = bText(d.map_query) || bText(d.address).replace(/\s*\n\s*/g, ', ');
  336. if (!query) return null;
  337. return {
  338. src: `https://www.google.com/maps?q=${encodeURIComponent(query)}&z=${zoom}&output=embed`,
  339. link: `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`
  340. };
  341. }
  342. return null;
  343. }
  344. ​
  345. const BLOCK_EXTENSIONS = {
  346. countdown: {
  347. title: block => block.data?.title || 'Countdown Timer',
  348. defaults: () => ({
  349. title: 'Coming Soon', subtitle: '', target_date: '', target_time: '00:00', timezone: defaultBlockTimezone(),
  350. label_days: 'Days', label_hours: 'Hours', label_minutes: 'Minutes', label_seconds: 'Seconds',
  351. expired_action: 'zeros', expired_text: ''
  352. }),
  353. fields(block, bi) {
  354. const d = block.data || {};
  355. const zones = typeof BLOCK_TIMEZONES !== 'undefined' && Array.isArray(BLOCK_TIMEZONES) ? BLOCK_TIMEZONES : ['UTC'];
  356. const timezone = d.timezone && zones.includes(d.timezone) ? d.timezone : 'UTC';
  357. const action = bChoice(d.expired_action, ['zeros', 'message', 'hide'], 'zeros');
  358. return bfSectionHeader(bi, d) +
  359. `<div class="form-row-3">
  360. <div class="block-field">${bfLabel('Target Date')}<input type="date" class="block-field-input" value="${bEsc(d.target_date || '')}" oninput="updateBlockData(${bi}, 'target_date', this.value)"></div>
  361. <div class="block-field">${bfLabel('Target Time')}<input type="time" class="block-field-input" value="${bEsc(d.target_time || '00:00')}" oninput="updateBlockData(${bi}, 'target_time', this.value)"></div>
  362. ${bfSelect(bi, 'timezone', 'Timezone', timezone, zones.map(zone => [zone, zone]))}
  363. </div>` +
  364. bfHint('The timer ends at this date and time in the chosen timezone, the same moment for every visitor.') +
  365. `<div class="form-row-4">
  366. ${bfInput(bi, 'label_days', 'Days label', d.label_days ?? 'Days')}
  367. ${bfInput(bi, 'label_hours', 'Hours label', d.label_hours ?? 'Hours')}
  368. ${bfInput(bi, 'label_minutes', 'Minutes label', d.label_minutes ?? 'Minutes')}
  369. ${bfInput(bi, 'label_seconds', 'Seconds label', d.label_seconds ?? 'Seconds')}
  370. </div>` +
  371. bfSelect(bi, 'expired_action', 'When the countdown ends', action, [['zeros', 'Show 00:00:00:00'], ['message', 'Show a message'], ['hide', 'Hide the whole block']], true) +
  372. (action === 'message' ? bfTextarea(bi, 'expired_text', 'Message after the end', d.expired_text || '') : '');
  373. },
  374. preview(d, id) {
  375. if (!/^\d{4}-\d{2}-\d{2}$/.test(d.target_date || '')) return '';
  376. const zones = typeof BLOCK_TIMEZONES !== 'undefined' && Array.isArray(BLOCK_TIMEZONES) ? BLOCK_TIMEZONES : ['UTC'];
  377. const timezone = d.timezone && zones.includes(d.timezone) ? d.timezone : 'UTC';
  378. const target = zonedTimeToUtc(d.target_date, d.target_time || '00:00', timezone);
  379. if (target === null) return '';
  380. let action = bChoice(d.expired_action, ['zeros', 'message', 'hide'], 'zeros');
  381. const message = bText(d.expired_text);
  382. if (action === 'message' && !message) action = 'zeros';
  383. const labels = [
  384. ['days', bText(d.label_days) || 'Days'],
  385. ['hours', bText(d.label_hours) || 'Hours'],
  386. ['minutes', bText(d.label_minutes) || 'Minutes'],
  387. ['seconds', bText(d.label_seconds) || 'Seconds']
  388. ];
  389. const expired = target <= Date.now();
  390. const showMessage = expired && action === 'message';
  391. return `<section class="countdown-section"${id} data-countdown data-target="${target}" data-expired="${action}">
  392. <div class="container">
  393. ${bHeader(d)}
  394. <div class="countdown-timer" role="timer"${showMessage ? ' hidden' : ''}>
  395. ${labels.map(([unit, label]) => `<div class="countdown-item"><div class="countdown-value" data-${unit}>00</div><div class="countdown-label">${bEsc(label)}</div></div>`).join('')}
  396. </div>
  397. ${action === 'message' ? `<p class="countdown-expired"${showMessage ? '' : ' hidden'}>${bLines(message)}</p>` : ''}
  398. </div>
  399. </section>`;
  400. }
  401. },
  402. ​
  403. 'logo-cloud': {
  404. title: block => block.data?.title || 'Logo Cloud',
  405. defaults: () => ({
  406. title: 'Trusted by teams everywhere', subtitle: '', layout: 'grid', grayscale: true,
  407. logos: [1, 2, 3, 4, 5].map(n => ({ image: `https://placehold.co/200x80?text=Logo+${n}`, alt: `Logo ${n}`, url: '' }))
  408. }),
  409. fields(block, bi) {
  410. const d = block.data || {};
  411. return bfSectionHeader(bi, d) +
  412. bfRow(
  413. bfSelect(bi, 'layout', 'Layout', bChoice(d.layout, ['grid', 'marquee'], 'grid'), [['grid', 'Grid'], ['marquee', 'Scrolling row']]),
  414. bfCheck(bi, 'grayscale', 'Show logos in grey, in color on hover', bFlag(d, 'grayscale', true))
  415. ) +
  416. bfRepeater(bi, 'logos', bList(d.logos), {
  417. label: 'Logos',
  418. addLabel: 'Add Logo',
  419. defaults: { image: '', alt: '', url: '' },
  420. itemTitle: (item, i) => item.alt || 'Logo ' + (i + 1),
  421. fields: (item, i) =>
  422. rfMedia(bi, 'logos', i, 'image', 'Logo image', item.image || '', 'image') +
  423. bfRow(
  424. rfInput(bi, 'logos', i, 'alt', 'Company name (alt text)', item.alt || ''),
  425. rfLink(bi, 'logos', i, 'url', 'Link (optional)', item.url || '')
  426. )
  427. });
  428. },
  429. preview(d, id) {
  430. const logos = bList(d.logos).filter(logo => bText(logo.image));
  431. if (!logos.length) return '';
  432. const layout = bChoice(d.layout, ['grid', 'marquee'], 'grid');
  433. const muted = bFlag(d, 'grayscale', true);
  434. const item = (logo, decorative) => {
  435. const img = `<img src="${bEsc(bText(logo.image))}" alt="${decorative ? '' : bEsc(bText(logo.alt))}" loading="lazy" decoding="async">`;
  436. const url = bText(logo.url);
  437. if (!url || url === '#') return `<span class="logo-cloud-item"${decorative ? ' aria-hidden="true"' : ''}>${img}</span>`;
  438. return `<a class="logo-cloud-item" href="${bEsc(url)}"${bTarget(url)}${decorative ? ' tabindex="-1" aria-hidden="true"' : ''}>${img}</a>`;
  439. };
  440. let inner;
  441. if (layout === 'marquee') {
  442. const repeat = Math.max(1, Math.ceil(8 / logos.length));
  443. const duration = Math.max(18, logos.length * repeat * 3);
  444. let groups = '';
  445. for (let group = 0; group < 2; group++) {
  446. let items = '';
  447. for (let r = 0; r < repeat; r++) logos.forEach(logo => { items += item(logo, group > 0 || r > 0); });
  448. groups += `<div class="logo-marquee-group"${group > 0 ? ' aria-hidden="true"' : ''}>${items}</div>`;
  449. }
  450. inner = `<div class="logo-marquee" style="--logo-duration: ${duration}s"><div class="logo-marquee-track">${groups}</div></div>`;
  451. } else {
  452. inner = `<div class="logo-cloud-grid">${logos.map(logo => item(logo, false)).join('')}</div>`;
  453. }
  454. return `<section class="logo-cloud logo-cloud-${layout}${muted ? ' logo-cloud-muted' : ''}"${id}><div class="container">${bHeader(d)}${inner}</div></section>`;
  455. }
  456. },
  457. ​
  458. steps: {
  459. title: block => block.data?.title || 'Steps',
  460. defaults: () => ({
  461. title: 'How it works', subtitle: '', layout: 'horizontal', items: [
  462. { label: '', title: 'Sign up', description: 'Create your account in less than a minute.' },
  463. { label: '', title: 'Set it up', description: 'Pick a template and add your content.' },
  464. { label: '', title: 'Go live', description: 'Publish your site and share it with the world.' }
  465. ]
  466. }),
  467. fields(block, bi) {
  468. const d = block.data || {};
  469. return bfSectionHeader(bi, d) +
  470. bfSelect(bi, 'layout', 'Layout', bChoice(d.layout, ['horizontal', 'vertical'], 'horizontal'), [['horizontal', 'Steps in a row'], ['vertical', 'Vertical timeline']]) +
  471. bfRepeater(bi, 'items', bList(d.items), {
  472. label: 'Steps',
  473. addLabel: 'Add Step',
  474. defaults: { label: '', title: '', description: '' },
  475. itemTitle: (item, i) => item.title || 'Step ' + (i + 1),
  476. fields: (item, i) =>
  477. bfRow(
  478. rfInput(bi, 'items', i, 'title', 'Title', item.title || ''),
  479. rfInput(bi, 'items', i, 'label', 'Marker (optional)', item.label || '', 'placeholder="Empty = 01, 02, 03… or type a date"')
  480. ) +
  481. rfTextarea(bi, 'items', i, 'description', 'Description', item.description || '')
  482. });
  483. },
  484. preview(d, id) {
  485. const items = bList(d.items).filter(item => bText(item.title) || bText(item.description));
  486. if (!items.length) return '';
  487. const layout = bChoice(d.layout, ['horizontal', 'vertical'], 'horizontal');
  488. const cols = Math.min(4, items.length);
  489. return `<section class="steps-section"${id}><div class="container">${bHeader(d)}
  490. <ol class="steps-list steps-${layout} steps-cols-${cols}">
  491. ${items.map((item, i) => `<li class="step-item">
  492. <div class="step-marker" aria-hidden="true">${bEsc(bText(item.label) || String(i + 1).padStart(2, '0'))}</div>
  493. <div class="step-body"><span class="step-eyebrow">${bEsc(bText(item.label) || String(i + 1).padStart(2, '0'))}</span>${bText(item.title) ? `<h3>${bEsc(bText(item.title))}</h3>` : ''}${bText(item.description) ? `<p>${bLines(item.description)}</p>` : ''}</div>
  494. </li>`).join('')}
  495. </ol></div></section>`;
  496. }
  497. },
  498. ​
  499. comparison: {
  500. title: block => block.data?.title || 'Comparison Table',
  501. defaults: () => ({
  502. title: 'Compare plans', subtitle: '', feature_label: 'Features', columns: ['Free', 'Pro', 'Business'], highlight: 1,
  503. yes_text: 'Included', no_text: 'Not included', rows: [
  504. { feature: 'Projects', values: ['1', '10', 'Unlimited'] },
  505. { feature: 'Custom domain', values: ['no', 'yes', 'yes'] },
  506. { feature: 'Priority support', values: ['no', 'no', 'yes'] }
  507. ]
  508. }),
  509. fields(block, bi) {
  510. const d = block.data || {};
  511. const columns = Array.isArray(d.columns) ? d.columns : [];
  512. const highlight = bInt(d.highlight, -1, Math.max(-1, columns.length - 1), -1);
  513. const columnName = (name, ci) => bText(name) || 'Column ' + (ci + 1);
  514. return bfSectionHeader(bi, d) +
  515. `<div class="form-row-3">
  516. ${bfInput(bi, 'feature_label', 'First column heading', d.feature_label || '')}
  517. ${bfInput(bi, 'yes_text', 'Screen reader text for ✓', d.yes_text ?? 'Included')}
  518. ${bfInput(bi, 'no_text', 'Screen reader text for ✗', d.no_text ?? 'Not included')}
  519. </div>` +
  520. `<div class="block-field">
  521. ${bfLabel('Columns')}
  522. <div class="cmp-columns-editor">
  523. ${columns.map((name, ci) => `<div class="cmp-column-row">
  524. <input type="text" class="block-field-input cmp-column-input" value="${bEsc(name)}" placeholder="Column ${ci + 1}" oninput="updateComparisonColumn(${bi}, ${ci}, this.value)">
  525. <button type="button" class="btn btn-ghost btn-sm repeater-move" title="Move left" ${ci === 0 ? 'disabled' : ''} onclick="moveComparisonColumn(${bi}, ${ci}, -1)">${BLOCK_EDITOR_ICONS.up}</button>
  526. <button type="button" class="btn btn-ghost btn-sm repeater-move" title="Move right" ${ci >= columns.length - 1 ? 'disabled' : ''} onclick="moveComparisonColumn(${bi}, ${ci}, 1)">${BLOCK_EDITOR_ICONS.down}</button>
  527. <button type="button" class="btn btn-ghost btn-sm" style="color: var(--error);" onclick="removeComparisonColumn(${bi}, ${ci})">Remove</button>
  528. </div>`).join('')}
  529. </div>
  530. <button type="button" class="repeater-add" onclick="addComparisonColumn(${bi})">${BLOCK_EDITOR_ICONS.plus} Add Column</button>
  531. </div>` +
  532. `<div class="block-field">${bfLabel('Highlighted column')}<select class="block-field-input" onchange="updateBlockData(${bi}, 'highlight', parseInt(this.value, 10))">
  533. <option value="-1" ${highlight === -1 ? 'selected' : ''}>None</option>
  534. ${columns.map((name, ci) => `<option value="${ci}" ${highlight === ci ? 'selected' : ''} data-cmp-col="${ci}">${bEsc(columnName(name, ci))}</option>`).join('')}
  535. </select></div>` +
  536. bfRepeater(bi, 'rows', bList(d.rows), {
  537. label: 'Rows',
  538. addLabel: 'Add Row',
  539. defaults: { feature: '', values: columns.map(() => '') },
  540. itemTitle: (row, i) => row.feature || 'Row ' + (i + 1),
  541. fields: (row, i) =>
  542. rfInput(bi, 'rows', i, 'feature', 'Feature', row.feature || '') +
  543. (columns.length ? `<div class="cmp-values-grid">${columns.map((name, ci) => `<div class="block-field">
  544. <label class="block-field-label" data-cmp-col="${ci}">${bEsc(columnName(name, ci))}</label>
  545. <input type="text" class="block-field-input" value="${bEsc(Array.isArray(row.values) ? (row.values[ci] ?? '') : '')}" placeholder="yes / no / text" oninput="updateComparisonValue(${bi}, ${i}, ${ci}, this.value)">
  546. </div>`).join('')}</div>` + bfHint('Type yes for ✓, no for ✗, leave empty for —, or write any text.') : bfHint('Add a column first.'))
  547. });
  548. },
  549. preview(d, id) {
  550. const columns = (Array.isArray(d.columns) ? d.columns : []).map(bText);
  551. while (columns.length && columns[columns.length - 1] === '') columns.pop();
  552. if (!columns.length) return '';
  553. const rows = bList(d.rows).map(row => ({ feature: bText(row.feature), values: Array.isArray(row.values) ? row.values : [] }))
  554. .filter(row => row.feature || row.values.some(value => bText(value)));
  555. if (!rows.length) return '';
  556. const highlight = bInt(d.highlight, -1, columns.length - 1, -1);
  557. const yes = bText(d.yes_text) || 'Included';
  558. const no = bText(d.no_text) || 'Not included';
  559. const regionLabel = bText(d.title) || 'Comparison';
  560. const featureLabel = bText(d.feature_label);
  561. const hl = ci => ci === highlight ? ' class="is-highlight"' : '';
  562. return `<section class="comparison-section"${id}><div class="container">${bHeader(d)}
  563. <div class="comparison-scroll" role="region" aria-label="${bEsc(regionLabel)}" tabindex="0">
  564. <table class="comparison-table">
  565. <thead><tr><th scope="col" class="cmp-feature-head">${featureLabel ? bEsc(featureLabel) : `<span class="visually-hidden">${bEsc(regionLabel)}</span>`}</th>${columns.map((name, ci) => `<th scope="col"${hl(ci)}>${bEsc(name)}</th>`).join('')}</tr></thead>
  566. <tbody>${rows.map(row => `<tr><th scope="row">${bEsc(row.feature)}</th>${columns.map((name, ci) => `<td${hl(ci)}>${comparisonCellPreview(row.values[ci], yes, no)}</td>`).join('')}</tr>`).join('')}</tbody>
  567. </table>
  568. </div></div></section>`;
  569. }
  570. },
  571. ​
  572. 'contact-info': {
  573. title: block => block.data?.title || 'Contact Info',
  574. defaults: () => ({
  575. title: 'Get in touch', subtitle: '', address: '', phone: '', email: '', hours: '',
  576. label_address: 'Address', label_phone: 'Phone', label_email: 'Email', label_hours: 'Opening hours',
  577. map_provider: 'none', map_lat: '', map_lng: '', map_zoom: 15, map_query: '', map_link_text: 'Open larger map'
  578. }),
  579. fields(block, bi) {
  580. const d = block.data || {};
  581. const provider = bChoice(d.map_provider, ['none', 'osm', 'google'], 'none');
  582. let map = bfSelect(bi, 'map_provider', 'Map', provider, [['none', 'No map'], ['osm', 'OpenStreetMap (no cookies)'], ['google', 'Google Maps']], true);
  583. if (provider === 'osm') {
  584. map += `<div class="form-row-3">
  585. ${bfInput(bi, 'map_lat', 'Latitude', d.map_lat ?? '', 'data-no-translate placeholder="52.229676"')}
  586. ${bfInput(bi, 'map_lng', 'Longitude', d.map_lng ?? '', 'data-no-translate placeholder="21.012229"')}
  587. ${bfNumber(bi, 'map_zoom', 'Zoom (3–19)', d.map_zoom ?? 15, 3, 19)}
  588. </div>` + bfHint('Find the coordinates by right-clicking the place on openstreetmap.org and choosing "Show address".');
  589. } else if (provider === 'google') {
  590. map += bfRow(
  591. bfInput(bi, 'map_query', 'Place to show', d.map_query || '', 'placeholder="Empty = use the address above"'),
  592. bfNumber(bi, 'map_zoom', 'Zoom (3–19)', d.map_zoom ?? 15, 3, 19)
  593. ) + bfHint('Google Maps can set cookies in your visitors\' browsers.');
  594. }
  595. if (provider !== 'none') map += bfInput(bi, 'map_link_text', 'Map link text', d.map_link_text ?? 'Open larger map');
  596. return bfSectionHeader(bi, d) +
  597. bfTextarea(bi, 'address', 'Address', d.address || '', 'rows="3"', false) +
  598. bfRow(
  599. bfInput(bi, 'phone', 'Phone', d.phone || '', 'data-no-translate placeholder="+48 123 456 789"'),
  600. bfInput(bi, 'email', 'Email', d.email || '', 'data-no-translate placeholder="hello@example.com"')
  601. ) +
  602. bfTextarea(bi, 'hours', 'Opening hours (one per line)', d.hours || '', 'rows="3" placeholder="Mon–Fri: 9:00–17:00"', false) +
  603. `<div class="form-row-4">
  604. ${bfInput(bi, 'label_address', 'Address label', d.label_address ?? 'Address')}
  605. ${bfInput(bi, 'label_phone', 'Phone label', d.label_phone ?? 'Phone')}
  606. ${bfInput(bi, 'label_email', 'Email label', d.label_email ?? 'Email')}
  607. ${bfInput(bi, 'label_hours', 'Hours label', d.label_hours ?? 'Opening hours')}
  608. </div>` + map;
  609. },
  610. preview(d, id) {
  611. const address = bText(d.address);
  612. const phone = bText(d.phone);
  613. const email = bText(d.email);
  614. const hours = bText(d.hours).split(/\r\n|\r|\n/).map(line => line.trim()).filter(Boolean);
  615. const map = contactMapEmbed(d);
  616. if (!address && !phone && !email && !hours.length && !map) return '';
  617. const labels = {
  618. address: bText(d.label_address) || 'Address',
  619. phone: bText(d.label_phone) || 'Phone',
  620. email: bText(d.label_email) || 'Email',
  621. hours: bText(d.label_hours) || 'Opening hours'
  622. };
  623. const phoneHref = contactPhoneHref(phone);
  624. const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  625. const row = (icon, label, value) => `<li class="contact-info-item"><span class="contact-info-icon">${BLOCK_UI_ICONS[icon]}</span><div><span class="contact-info-label">${bEsc(label)}</span>${value}</div></li>`;
  626. let list = '';
  627. if (address) list += row('pin', labels.address, `<address class="contact-info-value">${bLines(address)}</address>`);
  628. if (phone) list += row('phone', labels.phone, phoneHref ? `<a class="contact-info-value" href="${bEsc(phoneHref)}">${bEsc(phone)}</a>` : `<span class="contact-info-value">${bEsc(phone)}</span>`);
  629. if (email) list += row('mail', labels.email, emailValid ? `<a class="contact-info-value" href="mailto:${bEsc(email)}">${bEsc(email)}</a>` : `<span class="contact-info-value">${bEsc(email)}</span>`);
  630. if (hours.length) {
  631. list += row('clock', labels.hours, `<ul class="contact-hours">${hours.map(line => {
  632. const match = /^(.*?):\s+(.*)$/.exec(line);
  633. return match
  634. ? `<li class="contact-hours-row"><span class="contact-hours-day">${bEsc(match[1])}</span><span class="contact-hours-time">${bEsc(match[2])}</span></li>`
  635. : `<li class="contact-hours-row"><span class="contact-hours-time">${bEsc(line)}</span></li>`;
  636. }).join('')}</ul>`);
  637. }
  638. const mapHtml = map ? `<div class="contact-map"><iframe src="${bEsc(map.src)}" title="${bEsc(bText(d.title) || labels.address)}" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe><a class="contact-map-link" href="${bEsc(map.link)}" target="_blank" rel="noopener">${bEsc(bText(d.map_link_text) || 'Open larger map')}</a></div>` : '';
  639. return `<section class="contact-info-section"${id}><div class="container">${bHeader(d)}
  640. <div class="contact-info-grid${map ? ' has-map' : ''}">${list ? `<ul class="contact-info-list">${list}</ul>` : ''}${mapHtml}</div>
  641. </div></section>`;
  642. }
  643. },
  644. ​
  645. tabs: {
  646. title: block => block.data?.title || 'Tabs',
  647. defaults: () => ({
  648. title: '', subtitle: '', items: [
  649. { label: 'Overview', content: 'Describe the main idea here.', image: '', image_alt: '' },
  650. { label: 'Details', content: 'Add more information in this tab.', image: '', image_alt: '' }
  651. ]
  652. }),
  653. fields(block, bi) {
  654. const d = block.data || {};
  655. return bfSectionHeader(bi, d) +
  656. bfRepeater(bi, 'items', bList(d.items), {
  657. label: 'Tabs',
  658. addLabel: 'Add Tab',
  659. defaults: { label: '', content: '', image: '', image_alt: '' },
  660. itemTitle: (item, i) => item.label || 'Tab ' + (i + 1),
  661. fields: (item, i) =>
  662. rfInput(bi, 'items', i, 'label', 'Tab name', item.label || '') +
  663. rfTextarea(bi, 'items', i, 'content', 'Content', item.content || '', 'style="min-height: 140px;"') +
  664. bfRow(
  665. rfMedia(bi, 'items', i, 'image', 'Image (optional)', item.image || '', 'image'),
  666. rfInput(bi, 'items', i, 'image_alt', 'Image alt text', item.image_alt || '')
  667. )
  668. });
  669. },
  670. preview(d, id) {
  671. const items = bList(d.items).filter(item => bText(item.label) || bText(item.content) || bText(item.image));
  672. if (!items.length) return '';
  673. const uid = 'tabs-preview-' + Math.random().toString(36).slice(2, 9);
  674. const label = (item, i) => bText(item.label) || 'Tab ' + (i + 1);
  675. return `<section class="tabs-section"${id}><div class="container">${bHeader(d)}
  676. <div class="tabs-block" data-tabs>
  677. <div class="tabs-list" role="tablist" aria-label="${bEsc(bText(d.title) || 'Tabs')}">
  678. ${items.map((item, i) => `<button type="button" class="tabs-tab${i === 0 ? ' is-active' : ''}" role="tab" id="${uid}-tab-${i}" aria-controls="${uid}-panel-${i}" aria-selected="${i === 0}" tabindex="${i === 0 ? 0 : -1}">${bEsc(label(item, i))}</button>`).join('')}
  679. </div>
  680. ${items.map((item, i) => `<div class="tabs-panel${i === 0 ? ' is-active' : ''}" role="tabpanel" id="${uid}-panel-${i}" aria-labelledby="${uid}-tab-${i}" tabindex="0">
  681. <h3 class="tabs-panel-title">${bEsc(label(item, i))}</h3>
  682. <div class="tabs-panel-body${bText(item.image) ? ' has-image' : ''}">
  683. ${bText(item.content) ? `<div class="text-content">${bLines(item.content)}</div>` : ''}
  684. ${bText(item.image) ? `<img src="${bEsc(bText(item.image))}" alt="${bEsc(bText(item.image_alt))}" loading="lazy">` : ''}
  685. </div>
  686. </div>`).join('')}
  687. </div></div></section>`;
  688. }
  689. },
  690. ​
  691. carousel: {
  692. title: block => block.data?.title || 'Carousel',
  693. defaults: () => ({
  694. title: '', subtitle: '', ratio: '16-9', autoplay: false, interval: 5,
  695. slides: [1, 2, 3].map(n => ({ image: `https://placehold.co/1600x900?text=Slide+${n}`, alt: `Slide ${n}`, caption: '', url: '' }))
  696. }),
  697. fields(block, bi) {
  698. const d = block.data || {};
  699. const autoplay = bFlag(d, 'autoplay', false);
  700. return bfSectionHeader(bi, d) +
  701. `<div class="form-row-3">
  702. ${bfSelect(bi, 'ratio', 'Image shape', bChoice(d.ratio, ['16-9', '21-9', '4-3', '3-2', '1-1'], '16-9'), [['16-9', 'Wide 16:9'], ['21-9', 'Panorama 21:9'], ['4-3', 'Classic 4:3'], ['3-2', 'Photo 3:2'], ['1-1', 'Square 1:1']])}
  703. ${bfCheck(bi, 'autoplay', 'Play automatically', autoplay, true)}
  704. ${autoplay ? bfNumber(bi, 'interval', 'Seconds per slide', d.interval ?? 5, 2, 30) : ''}
  705. </div>` +
  706. bfRepeater(bi, 'slides', bList(d.slides), {
  707. label: 'Slides',
  708. addLabel: 'Add Slide',
  709. defaults: { image: '', alt: '', caption: '', url: '' },
  710. itemTitle: (item, i) => item.caption || item.alt || 'Slide ' + (i + 1),
  711. fields: (item, i) =>
  712. rfMedia(bi, 'slides', i, 'image', 'Image', item.image || '', 'image') +
  713. bfRow(
  714. rfInput(bi, 'slides', i, 'alt', 'Alt text', item.alt || ''),
  715. rfInput(bi, 'slides', i, 'caption', 'Caption (optional)', item.caption || '')
  716. ) +
  717. rfLink(bi, 'slides', i, 'url', 'Link (optional)', item.url || '')
  718. });
  719. },
  720. preview(d, id) {
  721. const slides = bList(d.slides).filter(slide => bText(slide.image));
  722. if (!slides.length) return '';
  723. const ratio = bChoice(d.ratio, ['16-9', '21-9', '4-3', '3-2', '1-1'], '16-9');
  724. const autoplay = slides.length > 1 && bFlag(d, 'autoplay', false);
  725. const interval = bInt(d.interval, 2, 30, 5);
  726. const total = slides.length;
  727. return `<section class="carousel-section"${id}><div class="container">${bHeader(d)}
  728. <div class="carousel carousel-ratio-${ratio}" data-carousel data-autoplay="${autoplay ? 1 : 0}" data-interval="${interval * 1000}" role="region" aria-roledescription="carousel" aria-label="${bEsc(bText(d.title) || 'Image carousel')}">
  729. <ul class="carousel-track" aria-live="${autoplay ? 'off' : 'polite'}">
  730. ${slides.map((slide, i) => {
  731. const img = `<img src="${bEsc(bText(slide.image))}" alt="${bEsc(bText(slide.alt))}"${i === 0 ? '' : ' loading="lazy"'} decoding="async">`;
  732. const url = bText(slide.url);
  733. return `<li class="carousel-slide" role="group" aria-roledescription="slide" aria-label="${i + 1} / ${total}"><figure>
  734. ${url && url !== '#' ? `<a class="carousel-media" href="${bEsc(url)}"${bTarget(url)}>${img}</a>` : `<div class="carousel-media">${img}</div>`}
  735. ${bText(slide.caption) ? `<figcaption>${bEsc(bText(slide.caption))}</figcaption>` : ''}
  736. </figure></li>`;
  737. }).join('')}
  738. </ul>
  739. ${total > 1 ? `<button type="button" class="carousel-btn carousel-prev" data-carousel-prev aria-label="Previous slide">${BLOCK_UI_ICONS.prev}</button>
  740. <button type="button" class="carousel-btn carousel-next" data-carousel-next aria-label="Next slide">${BLOCK_UI_ICONS.next}</button>
  741. <div class="carousel-dots">${slides.map((slide, i) => `<button type="button" class="carousel-dot${i === 0 ? ' is-active' : ''}" data-carousel-dot="${i}" aria-label="Slide ${i + 1}"${i === 0 ? ' aria-current="true"' : ''}></button>`).join('')}</div>` : ''}
  742. </div></div></section>`;
  743. }
  744. },
  745. ​
  746. announcement: {
  747. title: block => bText(block.data?.text).slice(0, 60) || 'Announcement Bar',
  748. defaults: () => ({ style: 'info', text: 'Free shipping on all orders this week.', link_text: 'Learn more', link_url: '#', dismissible: true, close_label: 'Dismiss' }),
  749. fields(block, bi) {
  750. const d = block.data || {};
  751. const dismissible = bFlag(d, 'dismissible', true);
  752. return bfSelect(bi, 'style', 'Style', bChoice(d.style, ['info', 'success', 'warning', 'accent'], 'info'), [['info', 'Info (blue)'], ['success', 'Success (green)'], ['warning', 'Warning (amber)'], ['accent', 'Accent (site colors)']]) +
  753. bfTextarea(bi, 'text', 'Message', d.text || '', 'rows="2"') +
  754. bfRow(
  755. bfInput(bi, 'link_text', 'Link text (optional)', d.link_text || ''),
  756. bfLink(bi, 'link_url', 'Link URL', d.link_url || '')
  757. ) +
  758. bfRow(
  759. bfCheck(bi, 'dismissible', 'Visitors can close it', dismissible, true),
  760. dismissible ? bfInput(bi, 'close_label', 'Close button label (for screen readers)', d.close_label ?? 'Dismiss') : ''
  761. ) +
  762. (dismissible ? bfHint('A closed bar stays hidden for that visitor until you change the message.') : '') +
  763. bfHint('Place it first on the page to show it right under the menu.');
  764. },
  765. preview(d, id) {
  766. const text = bText(d.text);
  767. if (!text) return '';
  768. const style = bChoice(d.style, ['info', 'success', 'warning', 'accent'], 'info');
  769. const linkText = bText(d.link_text);
  770. const linkUrl = bText(d.link_url);
  771. const dismissible = bFlag(d, 'dismissible', true);
  772. return `<div class="announcement-bar announcement-${style}"${id}${dismissible ? ' data-announcement="preview"' : ''}>
  773. <div class="container announcement-inner">
  774. <span class="announcement-icon">${BLOCK_UI_ICONS[style]}</span>
  775. <p class="announcement-text"><span>${bEsc(text)}</span>${linkText && linkUrl ? ` <a class="announcement-link" href="${bEsc(linkUrl)}"${bTarget(linkUrl)}>${bEsc(linkText)}</a>` : ''}</p>
  776. ${dismissible ? `<button type="button" class="announcement-close" data-announcement-close aria-label="${bEsc(bText(d.close_label) || 'Dismiss')}">${BLOCK_UI_ICONS.close}</button>` : ''}
  777. </div>
  778. </div>`;
  779. }
  780. },
  781. ​
  782. quote: {
  783. title: block => block.data?.author || 'Quote',
  784. defaults: () => ({ quote: 'Design is not just what it looks like and feels like. Design is how it works.', author: 'Author Name', role: 'Role, Company', image: '', align: 'center', size: 'large' }),
  785. fields(block, bi) {
  786. const d = block.data || {};
  787. return bfTextarea(bi, 'quote', 'Quote', d.quote || '', 'style="min-height: 120px;"') +
  788. bfRow(
  789. bfInput(bi, 'author', 'Author', d.author || ''),
  790. bfInput(bi, 'role', 'Role or company', d.role || '')
  791. ) +
  792. bfMedia(bi, 'image', 'Author photo (optional)', d.image || '', 'image') +
  793. bfRow(
  794. bfSelect(bi, 'align', 'Alignment', bChoice(d.align, ['center', 'left'], 'center'), [['center', 'Centered'], ['left', 'Left']]),
  795. bfSelect(bi, 'size', 'Text size', bChoice(d.size, ['large', 'medium'], 'large'), [['large', 'Large'], ['medium', 'Medium']])
  796. );
  797. },
  798. preview(d, id) {
  799. const quote = bText(d.quote);
  800. if (!quote) return '';
  801. const author = bText(d.author);
  802. const role = bText(d.role);
  803. const image = bText(d.image);
  804. const align = bChoice(d.align, ['center', 'left'], 'center');
  805. const size = bChoice(d.size, ['large', 'medium'], 'large');
  806. return `<section class="quote-section"${id}><div class="container">
  807. <figure class="quote-figure quote-${align} quote-${size}">
  808. <span class="quote-mark">${BLOCK_UI_ICONS.quote}</span>
  809. <blockquote class="quote-text"><p>${bLines(quote)}</p></blockquote>
  810. ${author || role ? `<figcaption class="quote-author">
  811. ${image ? `<img class="quote-avatar" src="${bEsc(image)}" alt="" width="56" height="56">` : ''}
  812. <span class="quote-author-text">${author ? `<cite class="quote-name">${bEsc(author)}</cite>` : ''}${role ? `<span class="quote-role">${bEsc(role)}</span>` : ''}</span>
  813. </figcaption>` : ''}
  814. </figure></div></section>`;
  815. }
  816. },
  817. ​
  818. downloads: {
  819. title: block => block.data?.title || 'Downloads',
  820. defaults: () => ({ title: 'Downloads', subtitle: '', button_text: 'Download', files: [] }),
  821. fields(block, bi) {
  822. const d = block.data || {};
  823. return bfSectionHeader(bi, d) +
  824. bfInput(bi, 'button_text', 'Button text', d.button_text ?? 'Download') +
  825. bfRepeater(bi, 'files', bList(d.files), {
  826. label: 'Files',
  827. addLabel: 'Add File',
  828. defaults: { url: '', name: '', description: '' },
  829. itemTitle: (item, i) => item.name || bText(item.url).split('/').pop() || 'File ' + (i + 1),
  830. fields: (item, i) =>
  831. rfMedia(bi, 'files', i, 'url', 'File', item.url || '', 'document', 'Upload a file or paste a link') +
  832. bfRow(
  833. rfInput(bi, 'files', i, 'name', 'Display name', item.name || '', 'placeholder="Empty = file name"'),
  834. rfInput(bi, 'files', i, 'description', 'Short description (optional)', item.description || '')
  835. )
  836. }) +
  837. bfHint('The file type and size are shown automatically for files uploaded here.');
  838. },
  839. preview(d, id) {
  840. const files = bList(d.files).map(file => {
  841. const url = bText(file.url);
  842. if (!url || url === '#' || /^\s*(javascript|vbscript|data|file):/i.test(url)) return null;
  843. const path = url.split('#')[0].split('?')[0];
  844. let base = path.split('/').pop() || '';
  845. try { base = decodeURIComponent(base); } catch (e) {}
  846. const extMatch = /\.([a-z0-9]{1,5})$/i.exec(base);
  847. const ext = extMatch ? extMatch[1].toLowerCase() : '';
  848. return {
  849. url,
  850. ext,
  851. name: bText(file.name) || base.replace(/-[a-f0-9]{8}(\.[a-z0-9]+)$/i, '$1'),
  852. description: bText(file.description),
  853. local: !bIsExternal(url)
  854. };
  855. }).filter(Boolean);
  856. if (!files.length) return '';
  857. const button = bText(d.button_text) || 'Download';
  858. return `<section class="downloads-section"${id}><div class="container">${bHeader(d)}
  859. <ul class="downloads-list">${files.map(file => `<li>
  860. <a class="download-item" href="${bEsc(file.url)}"${file.local ? ' download' : ' target="_blank" rel="noopener"'}>
  861. <span class="download-icon">${BLOCK_UI_ICONS.file}${file.ext ? `<span class="download-ext">${bEsc(file.ext.toUpperCase().slice(0, 4))}</span>` : ''}</span>
  862. <span class="download-info">
  863. <span class="download-name">${bEsc(file.name)}</span>
  864. ${file.description ? `<span class="download-desc">${bEsc(file.description)}</span>` : ''}
  865. ${file.ext ? `<span class="download-meta">${bEsc(file.ext.toUpperCase())}</span>` : ''}
  866. </span>
  867. <span class="download-action">${BLOCK_UI_ICONS.download}<span>${bEsc(button)}</span></span>
  868. </a>
  869. </li>`).join('')}</ul></div></section>`;
  870. }
  871. },
  872. ​
  873. 'social-follow': {
  874. title: block => block.data?.title || 'Social Follow',
  875. defaults: () => ({
  876. title: 'Follow us', subtitle: '', style: 'buttons', links: [
  877. { platform: 'instagram', url: '', label: '' },
  878. { platform: 'facebook', url: '', label: '' },
  879. { platform: 'youtube', url: '', label: '' }
  880. ]
  881. }),
  882. fields(block, bi) {
  883. const d = block.data || {};
  884. const platforms = (typeof SOCIAL_PLATFORMS !== 'undefined' ? SOCIAL_PLATFORMS : []).filter(([value]) => typeof SOCIAL_ICON_SVGS === 'undefined' || SOCIAL_ICON_SVGS[value]);
  885. return bfSectionHeader(bi, d) +
  886. bfSelect(bi, 'style', 'Style', bChoice(d.style, ['buttons', 'icons'], 'buttons'), [['buttons', 'Buttons with names'], ['icons', 'Icons only']]) +
  887. bfRepeater(bi, 'links', bList(d.links), {
  888. label: 'Profiles',
  889. addLabel: 'Add Profile',
  890. defaults: { platform: 'twitter', url: '', label: '' },
  891. itemTitle: (item, i) => item.label || blockPlatformLabel(item.platform) || 'Profile ' + (i + 1),
  892. fields: (item, i) =>
  893. bfRow(
  894. rfSelect(bi, 'links', i, 'platform', 'Platform', item.platform || 'twitter', platforms),
  895. rfInput(bi, 'links', i, 'url', 'Profile URL', item.url || '', 'placeholder="https://"')
  896. ) +
  897. rfInput(bi, 'links', i, 'label', 'Button text (optional)', item.label || '', `placeholder="${bEsc(blockPlatformLabel(item.platform || 'twitter'))}"`)
  898. }) +
  899. bfHint('Profiles without a URL are not shown on the site.');
  900. },
  901. preview(d, id) {
  902. const icons = typeof SOCIAL_ICON_SVGS !== 'undefined' ? SOCIAL_ICON_SVGS : {};
  903. const links = bList(d.links).map(link => {
  904. const platform = bText(link.platform).toLowerCase().replace(/[^a-z_-]/g, '');
  905. const url = bText(link.url);
  906. if (!platform || !icons[platform] || !url || url === '#' || /^\s*(javascript|vbscript|data|file):/i.test(url)) return null;
  907. return { platform, url, label: bText(link.label) || blockPlatformLabel(platform) };
  908. }).filter(Boolean);
  909. if (!links.length) return '';
  910. const style = bChoice(d.style, ['buttons', 'icons'], 'buttons');
  911. return `<section class="social-follow-section"${id}><div class="container">${bHeader(d)}
  912. <ul class="social-follow-list social-follow-${style}">${links.map(link => `<li>
  913. <a class="social-follow-link social-${link.platform}" href="${bEsc(link.url)}" target="_blank" rel="noopener me"${style === 'icons' ? ` aria-label="${bEsc(link.label)}" title="${bEsc(link.label)}"` : ''}>
  914. <span class="social-follow-icon">${icons[link.platform]}</span>${style === 'buttons' ? `<span class="social-follow-label">${bEsc(link.label)}</span>` : ''}
  915. </a>
  916. </li>`).join('')}</ul></div></section>`;
  917. }
  918. },
  919. ​
  920. spacer: {
  921. title: block => {
  922. const height = bInt(block.data?.height, 0, 400, 64);
  923. const divider = bChoice(block.data?.divider, ['none', 'line', 'dashed', 'dotted', 'wave'], 'none');
  924. return `Spacer · ${height}px${divider !== 'none' ? ' · ' + divider : ''}`;
  925. },
  926. defaults: () => ({ height: 64, divider: 'none' }),
  927. fields(block, bi) {
  928. const d = block.data || {};
  929. return bfRow(
  930. bfNumber(bi, 'height', 'Height in pixels (0–400)', d.height ?? 64, 0, 400, 4),
  931. bfSelect(bi, 'divider', 'Divider', bChoice(d.divider, ['none', 'line', 'dashed', 'dotted', 'wave'], 'none'), [['none', 'None, just space'], ['line', 'Line'], ['dashed', 'Dashed line'], ['dotted', 'Dotted line'], ['wave', 'Wave']])
  932. );
  933. },
  934. preview(d, id) {
  935. const height = bInt(d.height, 0, 400, 64);
  936. const divider = bChoice(d.divider, ['none', 'line', 'dashed', 'dotted', 'wave'], 'none');
  937. let inner = '';
  938. if (divider === 'wave') {
  939. inner = '<svg class="spacer-wave" viewBox="0 0 1200 24" preserveAspectRatio="none" focusable="false"><path d="M0 12 C 50 0, 100 0, 150 12 S 250 24, 300 12 S 400 0, 450 12 S 550 24, 600 12 S 700 0, 750 12 S 850 24, 900 12 S 1000 0, 1050 12 S 1150 24, 1200 12" fill="none" stroke="currentColor" stroke-width="2" vector-effect="non-scaling-stroke"/></svg>';
  940. } else if (divider !== 'none') {
  941. inner = '<div class="container"><hr class="spacer-line"></div>';
  942. }
  943. return `<div class="spacer-block spacer-${divider}"${id} style="--spacer-height: ${height}px" aria-hidden="true">${inner}</div>`;
  944. }
  945. }
  946. };
  947. ​
  948. const BLOCK_CLIPBOARD_KEY = 'flatly-block-clipboard';
  949. ​
  950. function blockTypeExists(type) {
  951. return typeof type === 'string' && (BLOCK_EXTENSIONS[type] !== undefined || ['hero', 'blog-hero', 'stats', 'features', 'testimonials', 'pricing', 'cta', 'text', 'image', 'image-text', 'product-cards', 'video', 'gallery', 'faq', 'team', 'audio', 'newsletter', 'html'].includes(type));
  952. }
  953. ​
  954. function readBlockClipboard() {
  955. try {
  956. const raw = localStorage.getItem(BLOCK_CLIPBOARD_KEY);
  957. if (!raw) return null;
  958. const parsed = JSON.parse(raw);
  959. if (!parsed || !parsed.block || !blockTypeExists(parsed.block.type)) return null;
  960. return parsed;
  961. } catch (e) {
  962. return null;
  963. }
  964. }
  965. ​
  966. function showEditorToast(message, type = 'success') {
  967. let toast = document.getElementById('editorToast');
  968. if (!toast) {
  969. toast = document.createElement('div');
  970. toast.id = 'editorToast';
  971. toast.className = 'editor-toast';
  972. toast.setAttribute('role', 'status');
  973. toast.setAttribute('aria-live', 'polite');
  974. document.body.appendChild(toast);
  975. }
  976. toast.textContent = message;
  977. toast.className = 'editor-toast visible ' + type;
  978. clearTimeout(toast._timer);
  979. toast._timer = setTimeout(() => { toast.className = 'editor-toast ' + type; }, 2600);
  980. }
  981. ​
  982. function copyBlock(index) {
  983. const block = blocks[index];
  984. if (!block) return;
  985. const payload = {
  986. version: 1,
  987. copiedAt: Date.now(),
  988. title: getBlockTitle(block),
  989. block: { type: block.type, data: JSON.parse(JSON.stringify(block.data || {})) }
  990. };
  991. try {
  992. localStorage.setItem(BLOCK_CLIPBOARD_KEY, JSON.stringify(payload));
  993. } catch (e) {
  994. showEditorToast("Couldn't copy the block. Your browser blocked local storage.", 'error');
  995. return;
  996. }
  997. refreshPasteButtons();
  998. showEditorToast(`Copied "${payload.title}". Open any page and click "Paste block".`);
  999. }
  1000. ​
  1001. function pasteBlock() {
  1002. const clip = readBlockClipboard();
  1003. if (!clip) {
  1004. refreshPasteButtons();
  1005. showEditorToast('There is no copied block to paste.', 'error');
  1006. return;
  1007. }
  1008. const type = clip.block.type;
  1009. blocks.push({ id: getDefaultBlockId(type), type, data: JSON.parse(JSON.stringify(clip.block.data || {})) });
  1010. renderBlocks();
  1011. schedulePreviewUpdate();
  1012. setTimeout(() => {
  1013. const items = document.querySelectorAll('.block-item');
  1014. const last = items[items.length - 1];
  1015. if (last) {
  1016. last.classList.add('expanded');
  1017. last.scrollIntoView({ behavior: 'smooth', block: 'center' });
  1018. }
  1019. }, 50);
  1020. showEditorToast(`Pasted "${clip.title || type}".`);
  1021. }
  1022. ​
  1023. function clearBlockClipboard() {
  1024. try { localStorage.removeItem(BLOCK_CLIPBOARD_KEY); } catch (e) {}
  1025. refreshPasteButtons();
  1026. }
  1027. ​
  1028. function refreshPasteButtons() {
  1029. const clip = readBlockClipboard();
  1030. document.querySelectorAll('.paste-block-wrap').forEach(wrap => {
  1031. wrap.hidden = !clip;
  1032. const label = wrap.querySelector('.paste-block-name');
  1033. if (label && clip) label.textContent = clip.title || clip.block.type;
  1034. });
  1035. }
  1036. ​
  1037. function toggleBlockHidden(index) {
  1038. const block = blocks[index];
  1039. if (!block) return;
  1040. if (block.hidden) {
  1041. delete block.hidden;
  1042. } else {
  1043. block.hidden = true;
  1044. }
  1045. renderBlocks();
  1046. schedulePreviewUpdate();
  1047. }
  1048. ​
  1049. document.addEventListener('DOMContentLoaded', () => {
  1050. document.querySelectorAll('.add-block-btn').forEach(button => {
  1051. if (button.parentElement.querySelector('.paste-block-wrap')) return;
  1052. const wrap = document.createElement('div');
  1053. wrap.className = 'paste-block-wrap';
  1054. wrap.hidden = true;
  1055. wrap.innerHTML = `
  1056. <button type="button" class="add-block-btn paste-block-btn" onclick="pasteBlock()">
  1057. <svg fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24" width="18" height="18"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1"/></svg>
  1058. Paste block: <span class="paste-block-name"></span>
  1059. </button>
  1060. <button type="button" class="paste-block-clear" title="Forget the copied block" aria-label="Forget the copied block" onclick="clearBlockClipboard()">${BLOCK_UI_ICONS.close}</button>`;
  1061. button.insertAdjacentElement('afterend', wrap);
  1062. });
  1063. refreshPasteButtons();
  1064. });
  1065. ​
  1066. const BLOCK_SEARCH_KEYWORDS = {
  1067. hero: 'header banner intro top headline main nagłówek baner wstęp',
  1068. 'blog-hero': 'article post blog header cover artykuł wpis okładka',
  1069. text: 'paragraph content copy article write tekst akapit treść',
  1070. 'image-text': 'media split picture photo side zdjęcie obraz obok',
  1071. image: 'picture photo media figure zdjęcie obraz grafika',
  1072. features: 'benefits services cards grid icons usługi zalety funkcje karty',
  1073. stats: 'numbers counters facts results metrics liczby statystyki wyniki',
  1074. pricing: 'plans prices packages subscription cost cennik ceny plany pakiety',
  1075. 'product-cards': 'shop store items catalog products sklep produkty katalog',
  1076. testimonials: 'reviews opinions feedback clients social proof opinie recenzje klienci',
  1077. team: 'people staff members about us employees zespół ludzie pracownicy',
  1078. faq: 'questions answers help accordion pytania odpowiedzi pomoc',
  1079. gallery: 'photos images grid portfolio galeria zdjęcia',
  1080. video: 'youtube facebook movie film clip media wideo',
  1081. audio: 'music podcast sound player muzyka dźwięk',
  1082. cta: 'call to action button signup convert wezwanie przycisk',
  1083. newsletter: 'email subscribe signup mailing list form zapis subskrypcja',
  1084. countdown: 'timer clock launch event deadline sale odliczanie licznik zegar',
  1085. announcement: 'banner alert notice message bar promo info ogłoszenie komunikat pasek',
  1086. 'logo-cloud': 'logos clients partners brands trusted sponsors loga klienci partnerzy marki',
  1087. steps: 'timeline process how it works roadmap history kroki proces oś czasu historia',
  1088. comparison: 'table compare plans features matrix versus tabela porównanie',
  1089. tabs: 'tabbed switcher sections panels zakładki karty',
  1090. carousel: 'slider slideshow images gallery swipe karuzela suwak pokaz slajdów',
  1091. quote: 'citation testimonial blockquote saying cytat',
  1092. 'contact-info': 'address phone email map location hours opening kontakt adres telefon mapa godziny',
  1093. downloads: 'files pdf documents attachments zip pliki dokumenty do pobrania',
  1094. 'social-follow': 'social media instagram facebook twitter follow profiles społecznościowe obserwuj',
  1095. spacer: 'divider gap space line separator break odstęp linia separator przerwa',
  1096. html: 'code embed custom script iframe kod osadzenie'
  1097. };
  1098. ​
  1099. function normalizeBlockSearch(text) {
  1100. return String(text || '')
  1101. .toLowerCase()
  1102. .replace(/ł/g, 'l')
  1103. .normalize('NFD')
  1104. .replace(/[̀-ͯ]/g, '')
  1105. .replace(/\s+/g, ' ')
  1106. .trim();
  1107. }
  1108. ​
  1109. function blockSearchCards() {
  1110. return Array.from(document.querySelectorAll('#addBlockModal .block-type-card'));
  1111. }
  1112. ​
  1113. function blockCardType(card) {
  1114. const match = /addBlock\('([^']+)'\)/.exec(card.getAttribute('onclick') || '');
  1115. return match ? match[1] : '';
  1116. }
  1117. ​
  1118. function visibleBlockCards() {
  1119. return blockSearchCards()
  1120. .filter(card => !card.hidden)
  1121. .sort((a, b) => (parseInt(a.style.order, 10) || 0) - (parseInt(b.style.order, 10) || 0));
  1122. }
  1123. ​
  1124. function filterBlockTypes(query) {
  1125. const terms = normalizeBlockSearch(query).split(' ').filter(Boolean);
  1126. let shown = 0;
  1127. ​
  1128. blockSearchCards().forEach(card => {
  1129. if (!terms.length) {
  1130. card.hidden = false;
  1131. card.style.order = '';
  1132. shown++;
  1133. return;
  1134. }
  1135. ​
  1136. const title = card.dataset.searchTitle || '';
  1137. const haystack = card.dataset.search || '';
  1138. const matches = terms.every(term => haystack.startsWith(term) || haystack.includes(' ' + term));
  1139. card.hidden = !matches;
  1140. if (!matches) return;
  1141. ​
  1142. shown++;
  1143. const first = terms[0];
  1144. let score = 3;
  1145. if (title.startsWith(first) || (card.dataset.searchType || '').startsWith(first)) score = 0;
  1146. else if (title.split(' ').some(word => word.startsWith(first))) score = 1;
  1147. else if (title.includes(first)) score = 2;
  1148. card.style.order = String(score);
  1149. });
  1150. ​
  1151. const empty = document.getElementById('blockSearchEmpty');
  1152. if (empty) {
  1153. empty.hidden = shown > 0;
  1154. const label = empty.querySelector('[data-block-search-query]');
  1155. if (label) label.textContent = query.trim();
  1156. }
  1157. ​
  1158. const count = document.getElementById('blockSearchCount');
  1159. if (count) count.textContent = terms.length ? (shown === 1 ? '1 block' : shown + ' blocks') : '';
  1160. ​
  1161. const body = document.querySelector('#addBlockModal .modal-body');
  1162. if (body) body.scrollTop = 0;
  1163. }
  1164. ​
  1165. function resetBlockSearch(focus) {
  1166. const input = document.getElementById('blockSearchInput');
  1167. if (!input) return;
  1168. input.value = '';
  1169. filterBlockTypes('');
  1170. if (focus) setTimeout(() => input.focus({ preventScroll: true }), 30);
  1171. }
  1172. ​
  1173. function moveBlockCardFocus(current, step) {
  1174. const cards = visibleBlockCards();
  1175. const index = cards.indexOf(current);
  1176. const target = index + step;
  1177. if (target < 0) {
  1178. document.getElementById('blockSearchInput')?.focus();
  1179. return;
  1180. }
  1181. if (cards[target]) cards[target].focus();
  1182. }
  1183. ​
  1184. function initBlockSearch() {
  1185. const modal = document.getElementById('addBlockModal');
  1186. const grid = modal ? modal.querySelector('.block-types-grid') : null;
  1187. const body = modal ? modal.querySelector('.modal-body') : null;
  1188. if (!grid || !body || document.getElementById('blockSearchInput')) return;
  1189. ​
  1190. const bar = document.createElement('div');
  1191. bar.className = 'block-search';
  1192. bar.innerHTML = `
  1193. <svg class="block-search-icon" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
  1194. <input type="search" id="blockSearchInput" class="block-search-input" placeholder="Search blocks, e.g. map, slider, pricing" aria-label="Search blocks" aria-controls="blockTypesGrid" autocomplete="off" spellcheck="false" data-no-translate>
  1195. <span class="block-search-count" id="blockSearchCount" aria-live="polite"></span>
  1196. <kbd class="block-search-hint">Enter</kbd>`;
  1197. body.parentNode.insertBefore(bar, body);
  1198. ​
  1199. grid.id = 'blockTypesGrid';
  1200. const empty = document.createElement('div');
  1201. empty.id = 'blockSearchEmpty';
  1202. empty.className = 'block-search-empty';
  1203. empty.hidden = true;
  1204. empty.innerHTML = 'No blocks match “<span data-block-search-query></span>”. Try another word, or use <strong>Custom HTML</strong>.';
  1205. grid.insertAdjacentElement('afterend', empty);
  1206. ​
  1207. blockSearchCards().forEach(card => {
  1208. const type = blockCardType(card);
  1209. const title = card.querySelector('h4')?.textContent || '';
  1210. const description = card.querySelector('p')?.textContent || '';
  1211. card.dataset.searchType = normalizeBlockSearch(type.replace(/-/g, ' '));
  1212. card.dataset.searchTitle = normalizeBlockSearch(title);
  1213. card.dataset.search = normalizeBlockSearch([type, type.replace(/-/g, ' '), title, description, BLOCK_SEARCH_KEYWORDS[type] || ''].join(' '));
  1214. card.tabIndex = 0;
  1215. card.setAttribute('role', 'button');
  1216. card.setAttribute('aria-label', 'Add ' + title + ' block');
  1217. card.addEventListener('keydown', event => {
  1218. if (event.key === 'Enter' || event.key === ' ') {
  1219. event.preventDefault();
  1220. card.click();
  1221. } else if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
  1222. event.preventDefault();
  1223. moveBlockCardFocus(card, event.key === 'ArrowDown' ? blockGridColumns(grid) : 1);
  1224. } else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
  1225. event.preventDefault();
  1226. moveBlockCardFocus(card, event.key === 'ArrowUp' ? -blockGridColumns(grid) : -1);
  1227. } else if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
  1228. const input = document.getElementById('blockSearchInput');
  1229. input.focus();
  1230. }
  1231. });
  1232. });
  1233. ​
  1234. const input = document.getElementById('blockSearchInput');
  1235. input.addEventListener('input', () => filterBlockTypes(input.value));
  1236. input.addEventListener('keydown', event => {
  1237. if (event.key === 'Enter') {
  1238. event.preventDefault();
  1239. const first = visibleBlockCards()[0];
  1240. if (first && input.value.trim()) first.click();
  1241. } else if (event.key === 'ArrowDown') {
  1242. event.preventDefault();
  1243. visibleBlockCards()[0]?.focus();
  1244. } else if (event.key === 'Escape' && input.value) {
  1245. event.preventDefault();
  1246. event.stopPropagation();
  1247. resetBlockSearch(true);
  1248. }
  1249. });
  1250. }
  1251. ​
  1252. function blockGridColumns(grid) {
  1253. const columns = getComputedStyle(grid).gridTemplateColumns.split(' ').filter(Boolean).length;
  1254. return Math.max(1, columns);
  1255. }
  1256. ​
  1257. document.addEventListener('DOMContentLoaded', initBlockSearch);
  1258. ​
  1259. window.addEventListener('storage', event => {
  1260. if (event.key === BLOCK_CLIPBOARD_KEY || event.key === null) refreshPasteButtons();
  1261. });
  1262. ​