WebOrbiton
v2.0.0.8

Publisium

2,236 lines · 80.5 KB
  1. (function (global) {
  2. 'use strict';
  3. ​
  4. const BLOCK_LABELS = {
  5. paragraph: 'Text',
  6. heading2: 'Heading 2',
  7. heading3: 'Heading 3',
  8. image: 'Image',
  9. video: 'Video',
  10. quote: 'Quote',
  11. list: 'List',
  12. code: 'Code',
  13. table: 'Table',
  14. checklist: 'Checklist',
  15. callout: 'Note box',
  16. separator: 'Divider',
  17. embed: 'Embed',
  18. contact_form: 'Contact form',
  19. };
  20. ​
  21. const BLOCK_ICONS = {
  22. paragraph: 'text',
  23. heading2: 'heading2',
  24. heading3: 'heading3',
  25. image: 'image',
  26. video: 'video',
  27. quote: 'quote',
  28. list: 'list',
  29. code: 'code',
  30. table: 'table',
  31. checklist: 'checklist',
  32. callout: 'callout',
  33. separator: 'separator',
  34. embed: 'embed',
  35. contact_form: 'mail',
  36. };
  37. ​
  38. const SYSTEM_BLOCKS = {
  39. home: {
  40. home_featured: {
  41. label: 'Featured articles',
  42. icon: 'star',
  43. description: 'The Featured banner with the articles you picked in Settings. You can move it, but it always stays on the home page.',
  44. },
  45. home_articles: {
  46. label: 'Latest articles',
  47. icon: 'grid',
  48. description: 'Your newest articles, with page numbers or endless scrolling. You can move it, but it always stays on the home page.',
  49. },
  50. },
  51. };
  52. ​
  53. function iconSvg(name, cls) {
  54. return '<svg class="' + (cls || 'icon icon-sm') + '" aria-hidden="true"><use href="#icon-' + name + '"></use></svg>';
  55. }
  56. ​
  57. function uid() {
  58. return 'b' + Math.random().toString(16).slice(2) + Date.now().toString(16);
  59. }
  60. ​
  61. const LIST_MARKER = /^\s*(?:[-*•–]|\d+[.)])\s+/;
  62. ​
  63. let rowDrag = null;
  64. ​
  65. function clearDropMarks() {
  66. document.querySelectorAll('.be-drop-before, .be-drop-after').forEach((node) => {
  67. node.classList.remove('be-drop-before', 'be-drop-after');
  68. });
  69. }
  70. ​
  71. function makeDraggableRow(row, grip, group, index, onMove) {
  72. const release = () => {
  73. row.draggable = false;
  74. };
  75. grip.addEventListener('mousedown', () => {
  76. row.draggable = true;
  77. });
  78. grip.addEventListener('mouseup', release);
  79. row.addEventListener('dragstart', (event) => {
  80. if (!row.draggable) {
  81. event.preventDefault();
  82. return;
  83. }
  84. rowDrag = { group: group, index: index };
  85. event.dataTransfer.effectAllowed = 'move';
  86. try {
  87. event.dataTransfer.setData('text/plain', String(index));
  88. } catch (error) {
  89. }
  90. row.classList.add('is-dragging');
  91. });
  92. row.addEventListener('dragend', () => {
  93. release();
  94. row.classList.remove('is-dragging');
  95. clearDropMarks();
  96. rowDrag = null;
  97. });
  98. row.addEventListener('dragover', (event) => {
  99. if (!rowDrag || rowDrag.group !== group) {
  100. return;
  101. }
  102. event.preventDefault();
  103. event.dataTransfer.dropEffect = 'move';
  104. const rect = row.getBoundingClientRect();
  105. const after = event.clientY > rect.top + rect.height / 2;
  106. clearDropMarks();
  107. row.classList.add(after ? 'be-drop-after' : 'be-drop-before');
  108. row.dataset.dropAfter = after ? '1' : '0';
  109. });
  110. row.addEventListener('drop', (event) => {
  111. if (!rowDrag || rowDrag.group !== group) {
  112. return;
  113. }
  114. event.preventDefault();
  115. const from = rowDrag.index;
  116. let to = index + (row.dataset.dropAfter === '1' ? 1 : 0);
  117. if (from < to) {
  118. to -= 1;
  119. }
  120. clearDropMarks();
  121. rowDrag = null;
  122. if (to !== from) {
  123. onMove(from, to);
  124. }
  125. });
  126. }
  127. ​
  128. function moveInArray(list, from, to) {
  129. if (to < 0 || to >= list.length || from === to) {
  130. return false;
  131. }
  132. list.splice(to, 0, list.splice(from, 1)[0]);
  133. return true;
  134. }
  135. ​
  136. function stripListMarkers(root) {
  137. root.querySelectorAll('li').forEach((li) => {
  138. let node = li.firstChild;
  139. while (node && node.nodeType === 1 && node.nodeName !== 'UL' && node.nodeName !== 'OL') {
  140. node = node.firstChild;
  141. }
  142. if (node && node.nodeType === 3 && LIST_MARKER.test(node.textContent)) {
  143. node.textContent = node.textContent.replace(LIST_MARKER, '');
  144. }
  145. });
  146. }
  147. ​
  148. function closestWithin(node, selector, root) {
  149. let current = node && node.nodeType === 3 ? node.parentNode : node;
  150. while (current && current !== root) {
  151. if (current.nodeType === 1 && current.matches(selector)) {
  152. return current;
  153. }
  154. current = current.parentNode;
  155. }
  156. return null;
  157. }
  158. ​
  159. function smallButton(className, html, title) {
  160. const button = document.createElement('button');
  161. button.type = 'button';
  162. button.className = className;
  163. button.innerHTML = html;
  164. if (title) {
  165. button.title = title;
  166. button.setAttribute('aria-label', title);
  167. }
  168. return button;
  169. }
  170. ​
  171. const BLOCK_ICONS_KEY = 'publisium_dashboard_block_icons';
  172. ​
  173. function blockIconsEnabled() {
  174. try {
  175. return global.localStorage.getItem(BLOCK_ICONS_KEY) !== '0';
  176. } catch (error) {
  177. return true;
  178. }
  179. }
  180. ​
  181. const SPELLCHECK_KEY = 'publisium_dashboard_spellcheck';
  182. ​
  183. function spellcheckEnabled() {
  184. try {
  185. return global.localStorage.getItem(SPELLCHECK_KEY) !== '0';
  186. } catch (error) {
  187. return true;
  188. }
  189. }
  190. ​
  191. const PASTE_CLEANUP_KEY = 'publisium_dashboard_paste_cleanup';
  192. ​
  193. function pasteCleanupEnabled() {
  194. try {
  195. return global.localStorage.getItem(PASTE_CLEANUP_KEY) === '1';
  196. } catch (error) {
  197. return false;
  198. }
  199. }
  200. ​
  201. let forceCleanPaste = false;
  202. document.addEventListener('keydown', (event) => {
  203. if ((event.ctrlKey || event.metaKey) && event.shiftKey && (event.key === 'V' || event.key === 'v')) {
  204. forceCleanPaste = true;
  205. }
  206. });
  207. ​
  208. function attachCleanPaste(el) {
  209. el.addEventListener('paste', (event) => {
  210. const shouldClean = pasteCleanupEnabled() || forceCleanPaste;
  211. forceCleanPaste = false;
  212. if (!shouldClean) {
  213. return;
  214. }
  215. event.preventDefault();
  216. const clipboard = event.clipboardData || global.clipboardData;
  217. const text = clipboard ? clipboard.getData('text/plain') : '';
  218. document.execCommand('insertText', false, text);
  219. });
  220. }
  221. ​
  222. const RECENT_COLORS_KEY = 'publisium_editor_recent_colors';
  223. const PRESET_COLORS = ['#f0546a', '#eab23d', '#34c48c', '#4fb2e8', '#7c6df2', '#e85fd0', '#f2f2f4', '#8f8f9a', '#0a0a0c'];
  224. ​
  225. function loadRecentColors() {
  226. try {
  227. const raw = JSON.parse(global.localStorage.getItem(RECENT_COLORS_KEY) || '[]');
  228. return Array.isArray(raw) ? raw.filter((color) => typeof color === 'string').slice(0, 8) : [];
  229. } catch (error) {
  230. return [];
  231. }
  232. }
  233. ​
  234. function saveRecentColor(color) {
  235. try {
  236. const list = loadRecentColors().filter((existing) => existing.toLowerCase() !== color.toLowerCase());
  237. list.unshift(color);
  238. global.localStorage.setItem(RECENT_COLORS_KEY, JSON.stringify(list.slice(0, 8)));
  239. } catch (error) {
  240. }
  241. }
  242. ​
  243. function clamp01(value) {
  244. return Math.min(1, Math.max(0, value));
  245. }
  246. ​
  247. function hexToRgb(hex) {
  248. const clean = hex.replace('#', '');
  249. const num = parseInt(clean, 16);
  250. return { r: (num >> 16) & 255, g: (num >> 8) & 255, b: num & 255 };
  251. }
  252. ​
  253. function rgbToHex(r, g, b) {
  254. return '#' + [r, g, b].map((channel) => {
  255. return Math.round(clamp01(channel / 255) * 255).toString(16).padStart(2, '0');
  256. }).join('');
  257. }
  258. ​
  259. function rgbToHsv(r, g, b) {
  260. r /= 255;
  261. g /= 255;
  262. b /= 255;
  263. const max = Math.max(r, g, b);
  264. const min = Math.min(r, g, b);
  265. const delta = max - min;
  266. let h = 0;
  267. if (delta !== 0) {
  268. if (max === r) {
  269. h = ((g - b) / delta) % 6;
  270. } else if (max === g) {
  271. h = (b - r) / delta + 2;
  272. } else {
  273. h = (r - g) / delta + 4;
  274. }
  275. h *= 60;
  276. if (h < 0) {
  277. h += 360;
  278. }
  279. }
  280. return { h, s: max === 0 ? 0 : delta / max, v: max };
  281. }
  282. ​
  283. function hsvToRgb(h, s, v) {
  284. const c = v * s;
  285. const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
  286. const m = v - c;
  287. let r = 0;
  288. let g = 0;
  289. let b = 0;
  290. if (h < 60) {
  291. r = c; g = x; b = 0;
  292. } else if (h < 120) {
  293. r = x; g = c; b = 0;
  294. } else if (h < 180) {
  295. r = 0; g = c; b = x;
  296. } else if (h < 240) {
  297. r = 0; g = x; b = c;
  298. } else if (h < 300) {
  299. r = x; g = 0; b = c;
  300. } else {
  301. r = c; g = 0; b = x;
  302. }
  303. return { r: (r + m) * 255, g: (g + m) * 255, b: (b + m) * 255 };
  304. }
  305. ​
  306. function positionFloating(el, anchorRect, options) {
  307. const opts = options || {};
  308. const margin = 8;
  309. const width = el.offsetWidth;
  310. const height = el.offsetHeight;
  311. ​
  312. let left = window.scrollX + anchorRect.left;
  313. const maxLeft = window.scrollX + window.innerWidth - width - margin;
  314. const minLeft = window.scrollX + margin;
  315. left = Math.min(left, maxLeft);
  316. left = Math.max(left, minLeft);
  317. ​
  318. let top;
  319. if (opts.placement === 'above') {
  320. top = window.scrollY + anchorRect.top - height - (opts.gap || 0);
  321. if (anchorRect.top - height - (opts.gap || 0) < margin) {
  322. top = window.scrollY + anchorRect.bottom + (opts.gap || 0);
  323. }
  324. } else {
  325. top = window.scrollY + anchorRect.bottom + (opts.gap || 0);
  326. const viewportBottom = window.scrollY + window.innerHeight;
  327. if (top + height > viewportBottom - margin && anchorRect.top - height - (opts.gap || 0) >= margin) {
  328. top = window.scrollY + anchorRect.top - height - (opts.gap || 0);
  329. }
  330. }
  331. ​
  332. el.style.left = left + 'px';
  333. el.style.top = top + 'px';
  334. }
  335. ​
  336. function uploadFile(file, onSuccess, onError) {
  337. const csrfInput = document.querySelector('input[name="csrf_token"]');
  338. const formData = new FormData();
  339. formData.append('file', file);
  340. if (csrfInput) {
  341. formData.append('csrf_token', csrfInput.value);
  342. }
  343. ​
  344. fetch('media-upload.php', { method: 'POST', body: formData })
  345. .then((response) => response.json())
  346. .then((data) => {
  347. if (data.success) {
  348. onSuccess(data.url);
  349. } else {
  350. onError(data.error || 'The upload didn’t work. Please try again.');
  351. }
  352. })
  353. .catch(() => onError('The upload didn’t work. Please try again.'));
  354. }
  355. ​
  356. function defaultDataFor(type) {
  357. switch (type) {
  358. case 'paragraph':
  359. case 'quote':
  360. return { text: '' };
  361. case 'heading2':
  362. case 'heading3':
  363. return { text: '' };
  364. case 'image':
  365. return { src: '', alt: '', caption: '' };
  366. case 'video':
  367. return { src: '', caption: '' };
  368. case 'list':
  369. return { style: 'unordered', items: [''] };
  370. case 'code':
  371. return { language: 'text', code: '' };
  372. case 'table':
  373. return { rows: [['', ''], ['', '']] };
  374. case 'checklist':
  375. return { items: [{ text: '', checked: false }] };
  376. case 'callout':
  377. return { style: 'info', text: '' };
  378. case 'embed':
  379. return { url: '' };
  380. case 'separator':
  381. return {};
  382. default:
  383. return {};
  384. }
  385. }
  386. ​
  387. class BlockEditor {
  388. constructor(rootElement) {
  389. this.root = rootElement;
  390. this.contactFormMode = rootElement.dataset.contactForm || '';
  391. this.systemBlocks = SYSTEM_BLOCKS[rootElement.dataset.systemBlocks || ''] || {};
  392. this.blocks = [];
  393. this.hiddenInput = document.getElementById('blocks_json_input');
  394. this.root.classList.toggle('be-hide-block-icons', !blockIconsEnabled());
  395. this.draftTimer = null;
  396. ​
  397. const form = this.root.closest('form');
  398. this.form = form || null;
  399. const idField = this.form ? this.form.querySelector('[name="article_id"]') : null;
  400. this.draftKey = rootElement.dataset.draftKey || ('publisium_article_draft_' + (idField && idField.value ? idField.value : '0'));
  401. ​
  402. this.statsBar = document.createElement('div');
  403. this.statsBar.className = 'be-stats-bar';
  404. this.statsText = document.createElement('span');
  405. this.statsBar.appendChild(this.statsText);
  406. this.focusToggleBtn = document.createElement('button');
  407. this.focusToggleBtn.type = 'button';
  408. this.focusToggleBtn.className = 'be-focus-toggle-btn';
  409. this.focusToggleBtn.textContent = 'Focus mode';
  410. this.focusToggleBtn.addEventListener('click', () => this.toggleFocusMode());
  411. this.statsBar.appendChild(this.focusToggleBtn);
  412. this.root.insertAdjacentElement('afterend', this.statsBar);
  413. ​
  414. document.addEventListener('keydown', (event) => {
  415. if (event.key === 'Escape' && document.body.classList.contains('be-focus-mode')) {
  416. this.toggleFocusMode();
  417. }
  418. });
  419. ​
  420. this.loadInitial();
  421. this.offerDraftRecovery();
  422. this.isInitialRender = true;
  423. this.render();
  424. this.isInitialRender = false;
  425. ​
  426. if (this.form) {
  427. this.form.addEventListener('submit', () => {
  428. this.syncHiddenInput();
  429. try {
  430. global.localStorage.removeItem(this.draftKey);
  431. } catch (error) {
  432. }
  433. });
  434. }
  435. ​
  436. this.attachShortcuts();
  437. }
  438. ​
  439. toggleFocusMode() {
  440. const active = document.body.classList.toggle('be-focus-mode');
  441. this.focusToggleBtn.textContent = active ? 'Exit focus mode' : 'Focus mode';
  442. }
  443. ​
  444. scheduleDraftSave() {
  445. if (this.isInitialRender) {
  446. return;
  447. }
  448. if (this.draftTimer) {
  449. clearTimeout(this.draftTimer);
  450. }
  451. this.draftTimer = setTimeout(() => {
  452. try {
  453. global.localStorage.setItem(this.draftKey, JSON.stringify({ blocks: this.blocks, savedAt: Date.now() }));
  454. } catch (error) {
  455. }
  456. }, 1000);
  457. }
  458. ​
  459. offerDraftRecovery() {
  460. let saved = null;
  461. try {
  462. saved = JSON.parse(global.localStorage.getItem(this.draftKey) || 'null');
  463. } catch (error) {
  464. saved = null;
  465. }
  466. if (!saved || !Array.isArray(saved.blocks) || !saved.blocks.length) {
  467. return;
  468. }
  469. ​
  470. const banner = document.createElement('div');
  471. banner.className = 'be-draft-banner';
  472. ​
  473. const label = document.createElement('span');
  474. label.textContent = 'You have unsaved changes from ' + new Date(saved.savedAt).toLocaleString();
  475. banner.appendChild(label);
  476. ​
  477. const restoreBtn = document.createElement('button');
  478. restoreBtn.type = 'button';
  479. restoreBtn.textContent = 'Restore';
  480. restoreBtn.addEventListener('click', () => {
  481. this.blocks = this.normalizeBlocks(saved.blocks);
  482. this.render();
  483. banner.remove();
  484. });
  485. banner.appendChild(restoreBtn);
  486. ​
  487. const discardBtn = document.createElement('button');
  488. discardBtn.type = 'button';
  489. discardBtn.textContent = 'Discard';
  490. discardBtn.addEventListener('click', () => {
  491. try {
  492. global.localStorage.removeItem(this.draftKey);
  493. } catch (error) {
  494. }
  495. banner.remove();
  496. });
  497. banner.appendChild(discardBtn);
  498. ​
  499. this.root.insertAdjacentElement('beforebegin', banner);
  500. }
  501. ​
  502. getActiveBlockId() {
  503. const active = document.activeElement;
  504. const wrapper = active && active.closest ? active.closest('.be-block') : null;
  505. if (wrapper) {
  506. return wrapper.dataset.blockId;
  507. }
  508. return this.blocks.length ? this.blocks[this.blocks.length - 1].id : null;
  509. }
  510. ​
  511. getBlocks() {
  512. return JSON.parse(JSON.stringify(this.blocks));
  513. }
  514. ​
  515. limitContactForms(blocks) {
  516. let contactFormSeen = false;
  517. return (Array.isArray(blocks) ? blocks : []).filter((block) => {
  518. if (!block || block.type !== 'contact_form') {
  519. return true;
  520. }
  521. if (!this.contactFormMode || contactFormSeen) {
  522. return false;
  523. }
  524. contactFormSeen = true;
  525. return true;
  526. });
  527. }
  528. ​
  529. isSystemType(type) {
  530. return Object.prototype.hasOwnProperty.call(this.systemBlocks, type);
  531. }
  532. ​
  533. isSystemBlock(block) {
  534. return !!block && this.isSystemType(block.type);
  535. }
  536. ​
  537. enforceSystemBlocks(blocks) {
  538. if (!Object.keys(this.systemBlocks).length) {
  539. return blocks;
  540. }
  541. const seen = {};
  542. const next = (Array.isArray(blocks) ? blocks : []).filter((block) => {
  543. if (!block || typeof block.type !== 'string') {
  544. return false;
  545. }
  546. if (!this.isSystemType(block.type)) {
  547. return true;
  548. }
  549. if (seen[block.type]) {
  550. return false;
  551. }
  552. seen[block.type] = true;
  553. block.id = 'sys_' + block.type;
  554. block.data = {};
  555. return true;
  556. });
  557. Object.keys(this.systemBlocks).forEach((type) => {
  558. if (!seen[type]) {
  559. next.push({ id: 'sys_' + type, type: type, data: {} });
  560. }
  561. });
  562. return next;
  563. }
  564. ​
  565. normalizeBlocks(blocks) {
  566. return this.enforceSystemBlocks(this.limitContactForms(blocks));
  567. }
  568. ​
  569. replaceBlocks(blocks) {
  570. const next = this.normalizeBlocks(Array.isArray(blocks) ? JSON.parse(JSON.stringify(blocks)) : []);
  571. if (next.length === 0) {
  572. next.push({ id: uid(), type: 'paragraph', data: defaultDataFor('paragraph') });
  573. }
  574. this.blocks = next;
  575. this.render();
  576. }
  577. ​
  578. attachShortcuts() {
  579. if (!global.PublisiumShortcuts) {
  580. return;
  581. }
  582. ​
  583. document.addEventListener('keydown', (event) => {
  584. if (!this.root.isConnected) {
  585. return;
  586. }
  587. ​
  588. const activeEl = document.activeElement;
  589. const withinEditor = activeEl && this.root.contains(activeEl);
  590. const withinForm = this.form && activeEl && this.form.contains(activeEl);
  591. ​
  592. const shortcuts = global.PublisiumShortcuts.getShortcuts();
  593. const action = global.PublisiumShortcuts.findMatchingAction(event, shortcuts);
  594. if (!action) {
  595. return;
  596. }
  597. ​
  598. switch (action) {
  599. case 'bold':
  600. case 'italic':
  601. case 'underline':
  602. case 'strikethrough':
  603. if (!withinEditor) {
  604. return;
  605. }
  606. event.preventDefault();
  607. this.applyFormatShortcut(action);
  608. break;
  609. ​
  610. case 'add_block': {
  611. if (!withinEditor) {
  612. return;
  613. }
  614. event.preventDefault();
  615. const blockId = this.getActiveBlockId();
  616. const index = this.blocks.findIndex((b) => b.id === blockId);
  617. this.addBlock(index === -1 ? this.blocks.length - 1 : index, 'paragraph');
  618. break;
  619. }
  620. ​
  621. case 'remove_block': {
  622. if (!withinEditor) {
  623. return;
  624. }
  625. event.preventDefault();
  626. const blockId = this.getActiveBlockId();
  627. if (blockId) {
  628. this.removeBlock(blockId);
  629. }
  630. break;
  631. }
  632. ​
  633. case 'move_block_up': {
  634. if (!withinEditor) {
  635. return;
  636. }
  637. event.preventDefault();
  638. const blockId = this.getActiveBlockId();
  639. if (blockId) {
  640. this.moveBlock(blockId, -1);
  641. }
  642. break;
  643. }
  644. ​
  645. case 'move_block_down': {
  646. if (!withinEditor) {
  647. return;
  648. }
  649. event.preventDefault();
  650. const blockId = this.getActiveBlockId();
  651. if (blockId) {
  652. this.moveBlock(blockId, 1);
  653. }
  654. break;
  655. }
  656. ​
  657. case 'save':
  658. if (!withinForm && !withinEditor) {
  659. return;
  660. }
  661. event.preventDefault();
  662. if (this.form) {
  663. this.syncHiddenInput();
  664. if (this.form.requestSubmit) {
  665. this.form.requestSubmit();
  666. } else {
  667. this.form.submit();
  668. }
  669. }
  670. break;
  671. ​
  672. default:
  673. break;
  674. }
  675. });
  676. }
  677. ​
  678. applyFormatShortcut(action) {
  679. const commandMap = {
  680. bold: 'bold',
  681. italic: 'italic',
  682. underline: 'underline',
  683. strikethrough: 'strikeThrough',
  684. };
  685. const command = commandMap[action];
  686. if (!command) {
  687. return;
  688. }
  689. const selection = window.getSelection();
  690. if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
  691. return;
  692. }
  693. document.execCommand(command, false, null);
  694. }
  695. ​
  696. loadInitial() {
  697. const raw = this.root.dataset.initialBlocks || '{"blocks":[]}';
  698. try {
  699. const parsed = JSON.parse(raw);
  700. this.blocks = Array.isArray(parsed.blocks) ? parsed.blocks : [];
  701. } catch (error) {
  702. this.blocks = [];
  703. }
  704. ​
  705. this.blocks = this.normalizeBlocks(this.blocks);
  706. ​
  707. if (this.blocks.length === 0) {
  708. this.blocks.push({ id: uid(), type: 'paragraph', data: defaultDataFor('paragraph') });
  709. }
  710. }
  711. ​
  712. syncHiddenInput() {
  713. if (this.hiddenInput) {
  714. this.hiddenInput.value = JSON.stringify({ blocks: this.blocks });
  715. }
  716. this.updateStats();
  717. this.scheduleDraftSave();
  718. }
  719. ​
  720. updateStats() {
  721. if (!this.statsText) {
  722. return;
  723. }
  724. const stripHtml = (html) => {
  725. const tmp = document.createElement('div');
  726. tmp.innerHTML = html || '';
  727. return tmp.textContent || '';
  728. };
  729. const parts = [];
  730. this.blocks.forEach((block) => {
  731. const data = block.data || {};
  732. if (typeof data.text === 'string') {
  733. parts.push(stripHtml(data.text));
  734. }
  735. if (typeof data.caption === 'string') {
  736. parts.push(data.caption);
  737. }
  738. if (Array.isArray(data.items)) {
  739. data.items.forEach((item) => {
  740. parts.push(typeof item === 'string' ? item : (item.text || ''));
  741. });
  742. }
  743. if (Array.isArray(data.rows)) {
  744. data.rows.forEach((row) => {
  745. row.forEach((cell) => parts.push(cell || ''));
  746. });
  747. }
  748. });
  749. const text = parts.join(' ').trim();
  750. const words = text ? text.split(/\s+/).length : 0;
  751. const chars = text.replace(/\s+/g, '').length;
  752. const minutes = Math.max(1, Math.round(words / 200));
  753. this.statsText.textContent = words + ' words · ' + chars + ' characters · ' + minutes + ' min read';
  754. }
  755. ​
  756. hasContactForm() {
  757. return this.blocks.some((b) => b.type === 'contact_form');
  758. }
  759. ​
  760. canInsertType(type) {
  761. if (this.isSystemType(type)) {
  762. return false;
  763. }
  764. if (type !== 'contact_form') {
  765. return true;
  766. }
  767. return this.contactFormMode === 'enabled' && !this.hasContactForm();
  768. }
  769. ​
  770. addBlock(afterIndex, type) {
  771. if (!this.canInsertType(type)) {
  772. return;
  773. }
  774. const block = { id: uid(), type: type, data: defaultDataFor(type) };
  775. this.blocks.splice(afterIndex + 1, 0, block);
  776. this.render();
  777. this.focusBlock(block.id);
  778. }
  779. ​
  780. transformBlock(id, type) {
  781. const index = this.blocks.findIndex((b) => b.id === id);
  782. if (index === -1 || this.isSystemBlock(this.blocks[index]) || !this.canInsertType(type)) {
  783. return;
  784. }
  785. const block = { id: uid(), type: type, data: defaultDataFor(type) };
  786. this.blocks.splice(index, 1, block);
  787. this.render();
  788. this.focusBlock(block.id);
  789. }
  790. ​
  791. removeBlock(id) {
  792. if (this.blocks.length <= 1 || this.isSystemBlock(this.blocks.find((b) => b.id === id))) {
  793. return;
  794. }
  795. this.blocks = this.blocks.filter((b) => b.id !== id);
  796. this.render();
  797. }
  798. ​
  799. moveBlock(id, direction) {
  800. const index = this.blocks.findIndex((b) => b.id === id);
  801. const targetIndex = index + direction;
  802. if (index === -1 || targetIndex < 0 || targetIndex >= this.blocks.length) {
  803. return;
  804. }
  805. const [block] = this.blocks.splice(index, 1);
  806. this.blocks.splice(targetIndex, 0, block);
  807. this.render();
  808. }
  809. ​
  810. focusIn(blockId, selector, caret) {
  811. requestAnimationFrame(() => {
  812. const input = this.root.querySelector('[data-block-id="' + blockId + '"] ' + selector);
  813. if (!input) {
  814. return;
  815. }
  816. input.focus();
  817. const length = (input.value || '').length;
  818. const position = caret === 'start' ? 0 : (typeof caret === 'number' ? Math.min(caret, length) : length);
  819. try {
  820. input.setSelectionRange(position, position);
  821. } catch (error) {
  822. }
  823. });
  824. }
  825. ​
  826. attachListTyping(el, onChange) {
  827. el.addEventListener('keydown', (event) => {
  828. const selection = window.getSelection();
  829. if (!selection || selection.rangeCount === 0) {
  830. return;
  831. }
  832. const range = selection.getRangeAt(0);
  833. ​
  834. if (event.key === 'Tab' && !event.ctrlKey && !event.altKey && !event.metaKey) {
  835. if (!closestWithin(range.startContainer, 'li', el)) {
  836. return;
  837. }
  838. event.preventDefault();
  839. document.execCommand(event.shiftKey ? 'outdent' : 'indent', false, null);
  840. onChange();
  841. return;
  842. }
  843. ​
  844. if (event.key !== ' ' || event.ctrlKey || event.altKey || event.metaKey || !selection.isCollapsed) {
  845. return;
  846. }
  847. const node = range.startContainer;
  848. if (node.nodeType !== 3 || closestWithin(node, 'li', el)) {
  849. return;
  850. }
  851. const before = node.textContent.slice(0, range.startOffset);
  852. const bullet = /^[-*•]$/.test(before);
  853. const numbered = /^1[.)]$/.test(before);
  854. if (!bullet && !numbered) {
  855. return;
  856. }
  857. const previous = node.previousSibling;
  858. const parent = node.parentNode;
  859. const atLineStart = (!previous || previous.nodeName === 'BR')
  860. && (parent === el || ((parent.nodeName === 'DIV' || parent.nodeName === 'P') && parent.parentNode === el));
  861. if (!atLineStart) {
  862. return;
  863. }
  864. event.preventDefault();
  865. const markerRange = document.createRange();
  866. markerRange.setStart(node, 0);
  867. markerRange.setEnd(node, range.startOffset);
  868. selection.removeAllRanges();
  869. selection.addRange(markerRange);
  870. document.execCommand('delete', false, null);
  871. document.execCommand(numbered ? 'insertOrderedList' : 'insertUnorderedList', false, null);
  872. onChange();
  873. });
  874. }
  875. ​
  876. focusBlock(id) {
  877. requestAnimationFrame(() => {
  878. const el = this.root.querySelector('[data-block-id="' + id + '"] [data-focus-target]');
  879. if (el) {
  880. el.focus();
  881. }
  882. });
  883. }
  884. ​
  885. attachInlineToolbar(el, onChange) {
  886. let toolbar = null;
  887. let savedRange = null;
  888. let colorSpan = null;
  889. let colorPopover = null;
  890. let colorPopoverOutsideClick = null;
  891. let lastAppliedColor = '';
  892. ​
  893. const closeColorPopover = () => {
  894. if (colorPopoverOutsideClick) {
  895. document.removeEventListener('mousedown', colorPopoverOutsideClick, true);
  896. colorPopoverOutsideClick = null;
  897. }
  898. if (colorPopover) {
  899. colorPopover.remove();
  900. colorPopover = null;
  901. }
  902. };
  903. ​
  904. const removeToolbar = () => {
  905. if (toolbar) {
  906. toolbar.remove();
  907. toolbar = null;
  908. }
  909. colorSpan = null;
  910. closeColorPopover();
  911. closeLinkPopover();
  912. };
  913. ​
  914. const selectionInsideEl = () => {
  915. const selection = window.getSelection();
  916. if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
  917. return null;
  918. }
  919. const range = selection.getRangeAt(0);
  920. if (!el.contains(range.commonAncestorContainer)) {
  921. return null;
  922. }
  923. return range;
  924. };
  925. ​
  926. const wrapSelection = (range, tagName, styleValue) => {
  927. const wrapper = document.createElement(tagName);
  928. if (styleValue) {
  929. wrapper.setAttribute('style', styleValue);
  930. }
  931. try {
  932. range.surroundContents(wrapper);
  933. } catch (error) {
  934. wrapper.appendChild(range.extractContents());
  935. range.insertNode(wrapper);
  936. }
  937. const newSelection = window.getSelection();
  938. newSelection.removeAllRanges();
  939. const newRange = document.createRange();
  940. newRange.selectNodeContents(wrapper);
  941. newSelection.addRange(newRange);
  942. return wrapper;
  943. };
  944. ​
  945. const applyFormat = (command) => {
  946. const range = selectionInsideEl();
  947. if (!range) {
  948. return;
  949. }
  950. document.execCommand(command, false, null);
  951. el.focus();
  952. onChange();
  953. showToolbar();
  954. };
  955. ​
  956. const clearFormat = () => {
  957. const range = selectionInsideEl();
  958. if (!range) {
  959. return;
  960. }
  961. document.execCommand('removeFormat', false, null);
  962. document.execCommand('unlink', false, null);
  963. el.focus();
  964. onChange();
  965. colorSpan = null;
  966. lastAppliedColor = '';
  967. showToolbar();
  968. };
  969. ​
  970. const applyList = (ordered) => {
  971. const range = selectionInsideEl();
  972. if (!range) {
  973. return;
  974. }
  975. document.execCommand(ordered ? 'insertOrderedList' : 'insertUnorderedList', false, null);
  976. stripListMarkers(el);
  977. el.focus();
  978. onChange();
  979. showToolbar();
  980. };
  981. ​
  982. const applyColor = (color) => {
  983. lastAppliedColor = color;
  984. if (colorSpan && colorSpan.isConnected) {
  985. colorSpan.style.color = color;
  986. onChange();
  987. return;
  988. }
  989. if (!savedRange) {
  990. return;
  991. }
  992. colorSpan = wrapSelection(savedRange, 'span', 'color:' + color);
  993. onChange();
  994. };
  995. ​
  996. const resetColor = () => {
  997. if (colorSpan && colorSpan.isConnected) {
  998. const parent = colorSpan.parentNode;
  999. while (colorSpan.firstChild) {
  1000. parent.insertBefore(colorSpan.firstChild, colorSpan);
  1001. }
  1002. parent.removeChild(colorSpan);
  1003. colorSpan = null;
  1004. onChange();
  1005. }
  1006. lastAppliedColor = '';
  1007. };
  1008. ​
  1009. const openColorPopover = (anchorEl) => {
  1010. closeColorPopover();
  1011. ​
  1012. const popover = document.createElement('div');
  1013. popover.className = 'be-color-popover';
  1014. ​
  1015. const buildSwatchRow = (label, colors, onPick) => {
  1016. if (!colors.length) {
  1017. return null;
  1018. }
  1019. const row = document.createElement('div');
  1020. row.className = 'be-color-popover-row';
  1021. const rowLabel = document.createElement('span');
  1022. rowLabel.className = 'be-color-popover-label';
  1023. rowLabel.textContent = label;
  1024. row.appendChild(rowLabel);
  1025. const swatches = document.createElement('div');
  1026. swatches.className = 'be-color-popover-swatches';
  1027. colors.forEach((color) => {
  1028. const swatch = document.createElement('button');
  1029. swatch.type = 'button';
  1030. swatch.className = 'be-color-swatch';
  1031. swatch.style.background = color;
  1032. swatch.title = color;
  1033. swatch.addEventListener('mousedown', (event) => event.preventDefault());
  1034. swatch.addEventListener('click', () => onPick(color));
  1035. swatches.appendChild(swatch);
  1036. });
  1037. row.appendChild(swatches);
  1038. return row;
  1039. };
  1040. ​
  1041. let hue = 0;
  1042. let sat = 0;
  1043. let val = 0;
  1044. let suppressSync = false;
  1045. ​
  1046. if (lastAppliedColor) {
  1047. const startRgb = hexToRgb(lastAppliedColor);
  1048. const startHsv = rgbToHsv(startRgb.r, startRgb.g, startRgb.b);
  1049. hue = startHsv.h;
  1050. sat = startHsv.s;
  1051. val = startHsv.v;
  1052. }
  1053. ​
  1054. const pickColor = (color, remember) => {
  1055. applyColor(color);
  1056. if (remember !== false) {
  1057. saveRecentColor(color);
  1058. }
  1059. hexInput.value = color;
  1060. hexPreview.style.background = color;
  1061. const bar = anchorEl.querySelector('.be-color-trigger-bar');
  1062. if (bar) {
  1063. bar.style.background = color;
  1064. }
  1065. if (!suppressSync) {
  1066. const rgb = hexToRgb(color);
  1067. const hsv = rgbToHsv(rgb.r, rgb.g, rgb.b);
  1068. hue = hsv.h;
  1069. sat = hsv.s;
  1070. val = hsv.v;
  1071. positionPickerHandles();
  1072. }
  1073. };
  1074. ​
  1075. const recentRow = buildSwatchRow('Recent', loadRecentColors(), pickColor);
  1076. if (recentRow) {
  1077. popover.appendChild(recentRow);
  1078. }
  1079. const presetsRow = buildSwatchRow('Colors', PRESET_COLORS, pickColor);
  1080. const customTrigger = document.createElement('button');
  1081. customTrigger.type = 'button';
  1082. customTrigger.className = 'be-color-swatch be-color-swatch-custom';
  1083. customTrigger.title = 'Pick any color';
  1084. customTrigger.addEventListener('mousedown', (event) => event.preventDefault());
  1085. customTrigger.addEventListener('click', () => {
  1086. customPanel.classList.toggle('open');
  1087. });
  1088. presetsRow.querySelector('.be-color-popover-swatches').appendChild(customTrigger);
  1089. popover.appendChild(presetsRow);
  1090. ​
  1091. const hexRow = document.createElement('div');
  1092. hexRow.className = 'be-color-popover-hex-row';
  1093. ​
  1094. const hexPreview = document.createElement('span');
  1095. hexPreview.className = 'be-color-swatch be-color-swatch-preview';
  1096. hexPreview.style.background = lastAppliedColor || 'transparent';
  1097. ​
  1098. const hexInput = document.createElement('input');
  1099. hexInput.type = 'text';
  1100. hexInput.className = 'be-color-hex-input';
  1101. hexInput.placeholder = '#000000';
  1102. hexInput.value = lastAppliedColor;
  1103. hexInput.maxLength = 7;
  1104. hexInput.spellcheck = false;
  1105. ​
  1106. const commitHex = () => {
  1107. const value = hexInput.value.trim();
  1108. if (/^#[0-9a-fA-F]{6}$/.test(value)) {
  1109. pickColor(value);
  1110. }
  1111. };
  1112. hexInput.addEventListener('input', () => {
  1113. const value = hexInput.value.trim();
  1114. hexPreview.style.background = /^#[0-9a-fA-F]{6}$/.test(value) ? value : 'transparent';
  1115. });
  1116. hexInput.addEventListener('change', commitHex);
  1117. hexInput.addEventListener('keydown', (event) => {
  1118. if (event.key === 'Enter') {
  1119. event.preventDefault();
  1120. commitHex();
  1121. }
  1122. });
  1123. ​
  1124. hexRow.appendChild(hexPreview);
  1125. hexRow.appendChild(hexInput);
  1126. popover.appendChild(hexRow);
  1127. ​
  1128. const customPanel = document.createElement('div');
  1129. customPanel.className = 'be-color-custom-panel';
  1130. ​
  1131. const svArea = document.createElement('div');
  1132. svArea.className = 'be-color-sv-area';
  1133. const svCursor = document.createElement('div');
  1134. svCursor.className = 'be-color-sv-cursor';
  1135. svArea.appendChild(svCursor);
  1136. ​
  1137. const hueSlider = document.createElement('div');
  1138. hueSlider.className = 'be-color-hue-slider';
  1139. const hueHandle = document.createElement('div');
  1140. hueHandle.className = 'be-color-hue-handle';
  1141. hueSlider.appendChild(hueHandle);
  1142. ​
  1143. customPanel.appendChild(svArea);
  1144. customPanel.appendChild(hueSlider);
  1145. popover.appendChild(customPanel);
  1146. ​
  1147. const positionPickerHandles = () => {
  1148. const rgb = hsvToRgb(hue, sat, val);
  1149. svArea.style.background = 'linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, hsl(' + hue + ',100%,50%))';
  1150. svCursor.style.left = (sat * 100) + '%';
  1151. svCursor.style.top = ((1 - val) * 100) + '%';
  1152. svCursor.style.background = rgbToHex(rgb.r, rgb.g, rgb.b);
  1153. hueHandle.style.left = (hue / 360 * 100) + '%';
  1154. hueHandle.style.background = 'hsl(' + hue + ',100%,50%)';
  1155. };
  1156. ​
  1157. const updateFromPicker = (remember) => {
  1158. suppressSync = true;
  1159. const rgb = hsvToRgb(hue, sat, val);
  1160. const hex = rgbToHex(rgb.r, rgb.g, rgb.b);
  1161. pickColor(hex, remember);
  1162. suppressSync = false;
  1163. positionPickerHandles();
  1164. };
  1165. ​
  1166. const dragHandler = (area, onMove) => (startEvent) => {
  1167. startEvent.preventDefault();
  1168. area.setPointerCapture(startEvent.pointerId);
  1169. const move = (event) => onMove(event);
  1170. const stop = (event) => {
  1171. onMove(event);
  1172. area.removeEventListener('pointermove', move);
  1173. area.removeEventListener('pointerup', stop);
  1174. saveRecentColor(hexInput.value);
  1175. };
  1176. onMove(startEvent);
  1177. area.addEventListener('pointermove', move);
  1178. area.addEventListener('pointerup', stop);
  1179. };
  1180. ​
  1181. svArea.addEventListener('pointerdown', dragHandler(svArea, (event) => {
  1182. const rect = svArea.getBoundingClientRect();
  1183. sat = clamp01((event.clientX - rect.left) / rect.width);
  1184. val = 1 - clamp01((event.clientY - rect.top) / rect.height);
  1185. updateFromPicker(false);
  1186. }));
  1187. ​
  1188. hueSlider.addEventListener('pointerdown', dragHandler(hueSlider, (event) => {
  1189. const rect = hueSlider.getBoundingClientRect();
  1190. hue = clamp01((event.clientX - rect.left) / rect.width) * 360;
  1191. updateFromPicker(false);
  1192. }));
  1193. ​
  1194. positionPickerHandles();
  1195. ​
  1196. const resetBtn = document.createElement('button');
  1197. resetBtn.type = 'button';
  1198. resetBtn.className = 'be-color-reset-btn';
  1199. resetBtn.textContent = 'Reset color';
  1200. resetBtn.addEventListener('mousedown', (event) => event.preventDefault());
  1201. resetBtn.addEventListener('click', () => {
  1202. resetColor();
  1203. hexInput.value = '';
  1204. hexPreview.style.background = 'transparent';
  1205. const bar = anchorEl.querySelector('.be-color-trigger-bar');
  1206. if (bar) {
  1207. bar.style.background = 'currentColor';
  1208. }
  1209. closeColorPopover();
  1210. });
  1211. popover.appendChild(resetBtn);
  1212. ​
  1213. document.body.appendChild(popover);
  1214. const rect = anchorEl.getBoundingClientRect();
  1215. positionFloating(popover, rect, { placement: 'below', gap: 6 });
  1216. colorPopover = popover;
  1217. ​
  1218. colorPopoverOutsideClick = (event) => {
  1219. if (!popover.contains(event.target) && event.target !== anchorEl) {
  1220. closeColorPopover();
  1221. }
  1222. };
  1223. setTimeout(() => document.addEventListener('mousedown', colorPopoverOutsideClick, true), 0);
  1224. };
  1225. ​
  1226. let linkPopover = null;
  1227. let linkPopoverOutsideClick = null;
  1228. ​
  1229. const closeLinkPopover = () => {
  1230. if (linkPopoverOutsideClick) {
  1231. document.removeEventListener('mousedown', linkPopoverOutsideClick, true);
  1232. linkPopoverOutsideClick = null;
  1233. }
  1234. if (linkPopover) {
  1235. linkPopover.remove();
  1236. linkPopover = null;
  1237. }
  1238. };
  1239. ​
  1240. const linkInRange = (range) => {
  1241. let node = range ? range.commonAncestorContainer : null;
  1242. while (node && node !== el) {
  1243. if (node.nodeType === 1 && node.tagName === 'A') {
  1244. return node;
  1245. }
  1246. node = node.parentNode;
  1247. }
  1248. return null;
  1249. };
  1250. ​
  1251. const normaliseUrl = (value) => {
  1252. const url = value.trim();
  1253. if (url === '' || /^(https?:|mailto:|tel:|\/|#)/i.test(url)) {
  1254. return url;
  1255. }
  1256. return /^[\w.-]+\.[a-z]{2,}(\/|$)/i.test(url) ? 'https://' + url : url;
  1257. };
  1258. ​
  1259. const openLinkPopover = (anchorEl) => {
  1260. closeLinkPopover();
  1261. const range = savedRange ? savedRange.cloneRange() : null;
  1262. if (!range) {
  1263. return;
  1264. }
  1265. const existing = linkInRange(range);
  1266. ​
  1267. const popover = document.createElement('div');
  1268. popover.className = 'be-link-popover';
  1269. popover.innerHTML =
  1270. '<label class="be-link-label">Link address</label>' +
  1271. '<input type="url" class="be-link-input" placeholder="https://example.com" spellcheck="false">' +
  1272. '<label class="be-link-newtab"><input type="checkbox" class="be-link-newtab-input"> Open in a new tab</label>' +
  1273. '<div class="be-link-actions">' +
  1274. '<button type="button" class="be-link-apply">Apply</button>' +
  1275. (existing ? '<button type="button" class="be-link-remove">Remove link</button>' : '') +
  1276. '</div>';
  1277. const input = popover.querySelector('.be-link-input');
  1278. const newTab = popover.querySelector('.be-link-newtab-input');
  1279. input.value = existing ? (existing.getAttribute('href') || '') : '';
  1280. newTab.checked = existing ? existing.getAttribute('target') === '_blank' : false;
  1281. ​
  1282. const restoreSelection = () => {
  1283. el.focus();
  1284. const selection = window.getSelection();
  1285. selection.removeAllRanges();
  1286. selection.addRange(range);
  1287. };
  1288. ​
  1289. const apply = () => {
  1290. const url = normaliseUrl(input.value);
  1291. if (url === '') {
  1292. input.focus();
  1293. return;
  1294. }
  1295. let link = existing;
  1296. if (!link) {
  1297. restoreSelection();
  1298. const marker = 'https://publisium-link-' + Date.now() + '.invalid/';
  1299. document.execCommand('createLink', false, marker);
  1300. link = el.querySelector('a[href="' + marker + '"]');
  1301. el.querySelectorAll('a[href="' + marker + '"]').forEach((extra) => {
  1302. if (extra !== link) {
  1303. extra.setAttribute('href', url);
  1304. extra.dataset.pending = '1';
  1305. }
  1306. });
  1307. }
  1308. const links = link ? [link].concat(Array.prototype.slice.call(el.querySelectorAll('a[data-pending="1"]'))) : [];
  1309. links.forEach((item) => {
  1310. item.removeAttribute('data-pending');
  1311. item.setAttribute('href', url);
  1312. if (newTab.checked) {
  1313. item.setAttribute('target', '_blank');
  1314. item.setAttribute('rel', 'noopener noreferrer');
  1315. } else {
  1316. item.removeAttribute('target');
  1317. item.removeAttribute('rel');
  1318. }
  1319. });
  1320. closeLinkPopover();
  1321. onChange();
  1322. };
  1323. ​
  1324. popover.querySelector('.be-link-apply').addEventListener('click', apply);
  1325. input.addEventListener('keydown', (event) => {
  1326. if (event.key === 'Enter') {
  1327. event.preventDefault();
  1328. apply();
  1329. } else if (event.key === 'Escape') {
  1330. event.preventDefault();
  1331. closeLinkPopover();
  1332. restoreSelection();
  1333. }
  1334. });
  1335. const removeBtn = popover.querySelector('.be-link-remove');
  1336. if (removeBtn) {
  1337. removeBtn.addEventListener('click', () => {
  1338. const parent = existing.parentNode;
  1339. while (existing.firstChild) {
  1340. parent.insertBefore(existing.firstChild, existing);
  1341. }
  1342. parent.removeChild(existing);
  1343. closeLinkPopover();
  1344. onChange();
  1345. });
  1346. }
  1347. ​
  1348. document.body.appendChild(popover);
  1349. positionFloating(popover, anchorEl.getBoundingClientRect(), { placement: 'below', gap: 6 });
  1350. input.focus();
  1351. ​
  1352. linkPopoverOutsideClick = (event) => {
  1353. if (!popover.contains(event.target) && event.target !== anchorEl) {
  1354. closeLinkPopover();
  1355. }
  1356. };
  1357. setTimeout(() => document.addEventListener('mousedown', linkPopoverOutsideClick, true), 0);
  1358. linkPopover = popover;
  1359. };
  1360. ​
  1361. const showToolbar = () => {
  1362. if (linkPopover) {
  1363. return;
  1364. }
  1365. const range = selectionInsideEl();
  1366. removeToolbar();
  1367. if (!range) {
  1368. savedRange = null;
  1369. return;
  1370. }
  1371. savedRange = range.cloneRange();
  1372. ​
  1373. toolbar = document.createElement('div');
  1374. toolbar.className = 'be-inline-toolbar';
  1375. ​
  1376. const shortcutTitle = (action, fallback) => {
  1377. if (global.PublisiumShortcuts) {
  1378. const combo = global.PublisiumShortcuts.getShortcuts()[action];
  1379. if (combo) {
  1380. return fallback + ' (' + combo.combo + ')';
  1381. }
  1382. }
  1383. return fallback;
  1384. };
  1385. ​
  1386. const boldBtn = document.createElement('button');
  1387. boldBtn.type = 'button';
  1388. boldBtn.textContent = 'B';
  1389. boldBtn.title = shortcutTitle('bold', 'Bold');
  1390. boldBtn.addEventListener('mousedown', (event) => {
  1391. event.preventDefault();
  1392. applyFormat('bold');
  1393. });
  1394. ​
  1395. const italicBtn = document.createElement('button');
  1396. italicBtn.type = 'button';
  1397. italicBtn.textContent = 'I';
  1398. italicBtn.title = shortcutTitle('italic', 'Italic');
  1399. italicBtn.style.fontStyle = 'italic';
  1400. italicBtn.addEventListener('mousedown', (event) => {
  1401. event.preventDefault();
  1402. applyFormat('italic');
  1403. });
  1404. ​
  1405. const underlineBtn = document.createElement('button');
  1406. underlineBtn.type = 'button';
  1407. underlineBtn.textContent = 'U';
  1408. underlineBtn.title = shortcutTitle('underline', 'Underline');
  1409. underlineBtn.style.textDecoration = 'underline';
  1410. underlineBtn.addEventListener('mousedown', (event) => {
  1411. event.preventDefault();
  1412. applyFormat('underline');
  1413. });
  1414. ​
  1415. const strikeBtn = document.createElement('button');
  1416. strikeBtn.type = 'button';
  1417. strikeBtn.textContent = 'S';
  1418. strikeBtn.title = shortcutTitle('strikethrough', 'Strikethrough');
  1419. strikeBtn.style.textDecoration = 'line-through';
  1420. strikeBtn.addEventListener('mousedown', (event) => {
  1421. event.preventDefault();
  1422. applyFormat('strikeThrough');
  1423. });
  1424. ​
  1425. const clearFormatBtn = document.createElement('button');
  1426. clearFormatBtn.type = 'button';
  1427. clearFormatBtn.className = 'be-clear-format-btn';
  1428. clearFormatBtn.textContent = 'Tx';
  1429. clearFormatBtn.title = shortcutTitle('clearFormat', 'Clear formatting');
  1430. clearFormatBtn.addEventListener('mousedown', (event) => {
  1431. event.preventDefault();
  1432. clearFormat();
  1433. });
  1434. ​
  1435. const colorTriggerBtn = document.createElement('button');
  1436. colorTriggerBtn.type = 'button';
  1437. colorTriggerBtn.className = 'be-color-trigger';
  1438. colorTriggerBtn.title = 'Text color';
  1439. colorTriggerBtn.innerHTML = '<span class="be-color-trigger-letter">A</span><span class="be-color-trigger-bar" style="background:' + (lastAppliedColor || 'currentColor') + '"></span>';
  1440. colorTriggerBtn.addEventListener('mousedown', (event) => event.preventDefault());
  1441. colorTriggerBtn.addEventListener('click', () => openColorPopover(colorTriggerBtn));
  1442. ​
  1443. toolbar.appendChild(boldBtn);
  1444. toolbar.appendChild(italicBtn);
  1445. toolbar.appendChild(underlineBtn);
  1446. toolbar.appendChild(strikeBtn);
  1447. const linkBtn = document.createElement('button');
  1448. linkBtn.type = 'button';
  1449. linkBtn.className = 'be-link-trigger';
  1450. linkBtn.title = 'Link';
  1451. linkBtn.innerHTML = '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.07 0l2.83-2.83a5 5 0 0 0-7.07-7.07l-1.42 1.41"/><path d="M14 11a5 5 0 0 0-7.07 0L4.1 13.83a5 5 0 0 0 7.07 7.07l1.41-1.41"/></svg>';
  1452. linkBtn.addEventListener('mousedown', (event) => event.preventDefault());
  1453. linkBtn.addEventListener('click', () => openLinkPopover(linkBtn));
  1454. ​
  1455. const listState = (tag) => {
  1456. const node = range.commonAncestorContainer;
  1457. const list = closestWithin(node, 'ul, ol', el);
  1458. return !!list && list.nodeName.toLowerCase() === tag;
  1459. };
  1460. ​
  1461. const bulletBtn = document.createElement('button');
  1462. bulletBtn.type = 'button';
  1463. bulletBtn.className = 'be-list-format-btn' + (listState('ul') ? ' is-active' : '');
  1464. bulletBtn.title = 'Bullet list (or type "- " at the start of a line)';
  1465. bulletBtn.innerHTML = '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M9 6h11M9 12h11M9 18h11"/><circle cx="4" cy="6" r="1.2" fill="currentColor"/><circle cx="4" cy="12" r="1.2" fill="currentColor"/><circle cx="4" cy="18" r="1.2" fill="currentColor"/></svg>';
  1466. bulletBtn.addEventListener('mousedown', (event) => {
  1467. event.preventDefault();
  1468. applyList(false);
  1469. });
  1470. ​
  1471. const numberBtn = document.createElement('button');
  1472. numberBtn.type = 'button';
  1473. numberBtn.className = 'be-list-format-btn' + (listState('ol') ? ' is-active' : '');
  1474. numberBtn.title = 'Numbered list (or type "1. " at the start of a line)';
  1475. numberBtn.innerHTML = '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 6h10M10 12h10M10 18h10"/><path d="M4 4.5h1.2V9" stroke-width="1.6"/><path d="M3.6 14.2c.4-.6 1.9-.7 2 .3.1.8-2 1.8-2 3h2.2" stroke-width="1.6"/></svg>';
  1476. numberBtn.addEventListener('mousedown', (event) => {
  1477. event.preventDefault();
  1478. applyList(true);
  1479. });
  1480. ​
  1481. toolbar.appendChild(bulletBtn);
  1482. toolbar.appendChild(numberBtn);
  1483. toolbar.appendChild(clearFormatBtn);
  1484. toolbar.appendChild(linkBtn);
  1485. toolbar.appendChild(colorTriggerBtn);
  1486. ​
  1487. document.body.appendChild(toolbar);
  1488. const rect = range.getBoundingClientRect();
  1489. positionFloating(toolbar, rect, { placement: 'above', gap: 6 });
  1490. };
  1491. ​
  1492. el.addEventListener('mouseup', () => setTimeout(showToolbar, 0));
  1493. el.addEventListener('keyup', (event) => {
  1494. if (event.shiftKey || event.key === 'Shift') {
  1495. setTimeout(showToolbar, 0);
  1496. }
  1497. });
  1498. el.addEventListener('blur', () => {
  1499. setTimeout(() => {
  1500. if (toolbar && toolbar.contains(document.activeElement)) {
  1501. return;
  1502. }
  1503. if (colorPopover && colorPopover.contains(document.activeElement)) {
  1504. return;
  1505. }
  1506. if (linkPopover) {
  1507. return;
  1508. }
  1509. removeToolbar();
  1510. }, 150);
  1511. });
  1512. }
  1513. ​
  1514. render() {
  1515. this.root.innerHTML = '';
  1516. this.blocks.forEach((block, index) => {
  1517. this.root.appendChild(this.renderBlock(block, index));
  1518. });
  1519. ​
  1520. const addRow = document.createElement('div');
  1521. addRow.className = 'be-add-row';
  1522. const addButton = document.createElement('button');
  1523. addButton.type = 'button';
  1524. addButton.className = 'dash-btn-small be-add-button';
  1525. addButton.innerHTML = iconSvg('plus') + 'Add block';
  1526. addButton.addEventListener('click', () => this.openBlockMenu(addButton, this.blocks.length - 1));
  1527. addRow.appendChild(addButton);
  1528. this.root.appendChild(addRow);
  1529. ​
  1530. this.syncHiddenInput();
  1531. }
  1532. ​
  1533. renderBlock(block, index) {
  1534. const wrapper = document.createElement('div');
  1535. const systemInfo = this.isSystemBlock(block) ? this.systemBlocks[block.type] : null;
  1536. const blockLabel = systemInfo ? systemInfo.label : (BLOCK_LABELS[block.type] || '');
  1537. const blockIcon = systemInfo ? systemInfo.icon : (BLOCK_ICONS[block.type] || 'text');
  1538. wrapper.className = 'be-block' + (systemInfo ? ' be-block-system' : '');
  1539. wrapper.dataset.blockId = block.id;
  1540. ​
  1541. const typeIcon = document.createElement('span');
  1542. typeIcon.className = 'be-block-icon-badge';
  1543. typeIcon.title = blockLabel;
  1544. typeIcon.innerHTML = iconSvg(blockIcon);
  1545. wrapper.appendChild(typeIcon);
  1546. ​
  1547. const toolbar = document.createElement('div');
  1548. toolbar.className = 'be-block-toolbar';
  1549. const titleFor = (action, fallback) => {
  1550. if (global.PublisiumShortcuts) {
  1551. const entry = global.PublisiumShortcuts.getShortcuts()[action];
  1552. if (entry) {
  1553. return fallback + ' (' + entry.combo + ')';
  1554. }
  1555. }
  1556. return fallback;
  1557. };
  1558. toolbar.innerHTML =
  1559. '<span class="be-block-type">' + iconSvg(blockIcon) + blockLabel + '</span>' +
  1560. '<button type="button" data-action="up" title="' + titleFor('move_block_up', 'Move up') + '">' + iconSvg('arrow-up') + '</button>' +
  1561. '<button type="button" data-action="down" title="' + titleFor('move_block_down', 'Move down') + '">' + iconSvg('arrow-down') + '</button>' +
  1562. '<button type="button" data-action="add" title="' + titleFor('add_block', 'Add block below') + '">' + iconSvg('plus') + '</button>' +
  1563. (systemInfo
  1564. ? '<span class="be-block-lock" title="This block always stays on the home page">' + iconSvg('lock') + '</span>'
  1565. : '<button type="button" data-action="remove" title="' + titleFor('remove_block', 'Remove block') + '">' + iconSvg('x') + '</button>');
  1566. ​
  1567. toolbar.querySelector('[data-action="up"]').addEventListener('click', () => this.moveBlock(block.id, -1));
  1568. toolbar.querySelector('[data-action="down"]').addEventListener('click', () => this.moveBlock(block.id, 1));
  1569. const removeButton = toolbar.querySelector('[data-action="remove"]');
  1570. if (removeButton) {
  1571. removeButton.addEventListener('click', () => this.removeBlock(block.id));
  1572. }
  1573. toolbar.querySelector('[data-action="add"]').addEventListener('click', (event) => {
  1574. this.openBlockMenu(event.currentTarget, index);
  1575. });
  1576. ​
  1577. wrapper.appendChild(toolbar);
  1578. wrapper.appendChild(this.renderBlockBody(block));
  1579. ​
  1580. return wrapper;
  1581. }
  1582. ​
  1583. openBlockMenu(anchorEl, afterIndex, onPick) {
  1584. const existing = document.querySelector('.be-block-menu');
  1585. if (existing) {
  1586. existing.remove();
  1587. }
  1588. ​
  1589. const menu = document.createElement('div');
  1590. menu.className = 'be-block-menu';
  1591. Object.keys(BLOCK_LABELS).forEach((type) => {
  1592. if (type === 'contact_form' && this.contactFormMode !== 'enabled') {
  1593. return;
  1594. }
  1595. const item = document.createElement('button');
  1596. item.type = 'button';
  1597. item.className = 'be-block-menu-item';
  1598. item.innerHTML = iconSvg(BLOCK_ICONS[type] || 'text') + '<span>' + BLOCK_LABELS[type] + '</span>';
  1599. if (!this.canInsertType(type)) {
  1600. item.disabled = true;
  1601. item.title = 'This page already has a contact form. You can only add one.';
  1602. item.innerHTML += '<span class="be-block-menu-note">Already added</span>';
  1603. menu.appendChild(item);
  1604. return;
  1605. }
  1606. item.addEventListener('click', () => {
  1607. if (onPick) {
  1608. onPick(type);
  1609. } else {
  1610. this.addBlock(afterIndex, type);
  1611. }
  1612. menu.remove();
  1613. });
  1614. menu.appendChild(item);
  1615. });
  1616. ​
  1617. document.body.appendChild(menu);
  1618. const rect = anchorEl.getBoundingClientRect();
  1619. positionFloating(menu, rect, { placement: 'below', gap: 4 });
  1620. ​
  1621. const closeHandler = (event) => {
  1622. if (!menu.contains(event.target) && event.target !== anchorEl) {
  1623. menu.remove();
  1624. document.removeEventListener('click', closeHandler);
  1625. }
  1626. };
  1627. setTimeout(() => document.addEventListener('click', closeHandler), 0);
  1628. }
  1629. ​
  1630. renderBlockBody(block) {
  1631. const container = document.createElement('div');
  1632. container.className = 'be-block-body';
  1633. ​
  1634. const update = (patch) => {
  1635. Object.assign(block.data, patch);
  1636. this.syncHiddenInput();
  1637. };
  1638. ​
  1639. if (this.isSystemBlock(block)) {
  1640. const info = this.systemBlocks[block.type];
  1641. const note = document.createElement('div');
  1642. note.className = 'be-contact-form be-system-note';
  1643. note.innerHTML = iconSvg(info.icon) + '<div><strong>' + info.label + '</strong><span>' + info.description + '</span>' +
  1644. (block.type === 'home_featured' && this.root.dataset.featuredEnabled !== '1'
  1645. ? '<span class="be-contact-form-off">The Featured banner is switched off in Settings, so this block won’t show on the site.</span>'
  1646. : '') +
  1647. '</div>';
  1648. container.appendChild(note);
  1649. return container;
  1650. }
  1651. ​
  1652. switch (block.type) {
  1653. case 'paragraph':
  1654. case 'quote': {
  1655. const el = document.createElement('div');
  1656. el.className = 'be-editable';
  1657. el.contentEditable = 'true';
  1658. el.spellcheck = spellcheckEnabled();
  1659. el.dataset.focusTarget = '1';
  1660. el.innerHTML = block.data.text || '';
  1661. el.addEventListener('input', () => {
  1662. update({ text: el.innerHTML });
  1663. if (el.textContent === '/') {
  1664. this.openBlockMenu(el, -1, (type) => this.transformBlock(block.id, type));
  1665. }
  1666. });
  1667. this.attachInlineToolbar(el, () => update({ text: el.innerHTML }));
  1668. this.attachListTyping(el, () => update({ text: el.innerHTML }));
  1669. attachCleanPaste(el);
  1670. container.appendChild(el);
  1671. break;
  1672. }
  1673. case 'heading2':
  1674. case 'heading3': {
  1675. const el = document.createElement('div');
  1676. el.className = 'be-editable be-heading';
  1677. el.contentEditable = 'true';
  1678. el.spellcheck = spellcheckEnabled();
  1679. el.dataset.focusTarget = '1';
  1680. el.textContent = block.data.text || '';
  1681. el.addEventListener('input', () => update({ text: el.textContent }));
  1682. attachCleanPaste(el);
  1683. container.appendChild(el);
  1684. break;
  1685. }
  1686. case 'image': {
  1687. container.appendChild(this.buildInput('Image link', block.data.src, (val) => update({ src: val }), true));
  1688. container.appendChild(this.buildUploadButton('image', (url) => {
  1689. block.data.src = url;
  1690. this.render();
  1691. }));
  1692. container.appendChild(this.buildInput('Describe the image (helps blind readers and search engines)', block.data.alt, (val) => update({ alt: val })));
  1693. container.appendChild(this.buildInput('Caption', block.data.caption, (val) => update({ caption: val })));
  1694. if (block.data.src) {
  1695. const preview = document.createElement('img');
  1696. preview.src = block.data.src;
  1697. preview.className = 'be-preview-image';
  1698. container.appendChild(preview);
  1699. }
  1700. break;
  1701. }
  1702. case 'video': {
  1703. container.appendChild(this.buildInput('Video file or link (YouTube, X, Facebook, Instagram, TikTok, Vimeo...)', block.data.src, (val) => update({ src: val }), true));
  1704. container.appendChild(this.buildUploadButton('video', (url) => {
  1705. block.data.src = url;
  1706. this.render();
  1707. }));
  1708. container.appendChild(this.buildInput('Caption', block.data.caption, (val) => update({ caption: val })));
  1709. if (block.data.src && !/^https?:\/\/([^/]+\.)?(youtube\.com|youtu\.be|youtube-nocookie\.com|vimeo\.com|x\.com|twitter\.com|facebook\.com|fb\.watch|instagram\.com|tiktok\.com|dailymotion\.com|dai\.ly|twitch\.tv|spotify\.com|soundcloud\.com|streamable\.com)\//i.test(block.data.src)) {
  1710. const preview = document.createElement('video');
  1711. preview.src = block.data.src;
  1712. preview.controls = true;
  1713. preview.className = 'be-preview-video';
  1714. container.appendChild(preview);
  1715. }
  1716. break;
  1717. }
  1718. case 'list': {
  1719. if (!Array.isArray(block.data.items) || block.data.items.length === 0) {
  1720. block.data.items = [''];
  1721. }
  1722. const segmented = document.createElement('div');
  1723. segmented.className = 'be-segmented';
  1724. [['unordered', 'Bullets'], ['ordered', 'Numbers']].forEach(([style, label]) => {
  1725. const active = (block.data.style || 'unordered') === style;
  1726. const marker = style === 'ordered' ? '<span class="be-segmented-mark">1.</span>' : '<span class="be-segmented-mark">•</span>';
  1727. const button = smallButton('be-segmented-btn' + (active ? ' is-active' : ''), marker + label);
  1728. button.setAttribute('aria-pressed', active ? 'true' : 'false');
  1729. button.addEventListener('click', () => {
  1730. if (active) {
  1731. return;
  1732. }
  1733. update({ style: style });
  1734. this.render();
  1735. });
  1736. segmented.appendChild(button);
  1737. });
  1738. container.appendChild(segmented);
  1739. container.appendChild(this.buildItemRows(block, 'list'));
  1740. break;
  1741. }
  1742. case 'code': {
  1743. container.appendChild(this.buildInput('Code language (e.g. php, js)', block.data.language, (val) => update({ language: val })));
  1744. const textarea = document.createElement('textarea');
  1745. textarea.className = 'be-code';
  1746. textarea.value = block.data.code || '';
  1747. textarea.spellcheck = false;
  1748. textarea.addEventListener('input', () => update({ code: textarea.value }));
  1749. container.appendChild(textarea);
  1750. break;
  1751. }
  1752. case 'table': {
  1753. if (!Array.isArray(block.data.rows) || block.data.rows.length === 0) {
  1754. block.data.rows = [['', ''], ['', '']];
  1755. }
  1756. const rows = block.data.rows;
  1757. const columnCount = Math.max(1, ...rows.map((row) => (Array.isArray(row) ? row.length : 0)));
  1758. rows.forEach((row, rowIndex) => {
  1759. if (!Array.isArray(row)) {
  1760. rows[rowIndex] = [];
  1761. }
  1762. while (rows[rowIndex].length < columnCount) {
  1763. rows[rowIndex].push('');
  1764. }
  1765. });
  1766. const cellSelector = (r, c) => '[data-cell="' + r + '-' + c + '"]';
  1767. const rerender = (selector) => {
  1768. this.render();
  1769. if (selector) {
  1770. this.focusIn(block.id, selector);
  1771. }
  1772. };
  1773. const moveRow = (from, to) => {
  1774. if (moveInArray(rows, from, to)) {
  1775. rerender(cellSelector(to, 0));
  1776. }
  1777. };
  1778. const moveColumn = (from, to) => {
  1779. if (to < 0 || to >= columnCount) {
  1780. return;
  1781. }
  1782. rows.forEach((row) => moveInArray(row, from, to));
  1783. rerender(cellSelector(0, to));
  1784. };
  1785. ​
  1786. const table = document.createElement('table');
  1787. table.className = 'be-table';
  1788. ​
  1789. const colBar = document.createElement('tr');
  1790. colBar.className = 'be-table-colbar';
  1791. colBar.appendChild(document.createElement('th'));
  1792. for (let c = 0; c < columnCount; c++) {
  1793. const th = document.createElement('th');
  1794. const tools = document.createElement('div');
  1795. tools.className = 'be-table-tools';
  1796. const left = smallButton('be-item-action', iconSvg('arrow-up'), 'Move column left');
  1797. left.classList.add('be-rotate-left');
  1798. left.disabled = c === 0;
  1799. left.addEventListener('click', () => moveColumn(c, c - 1));
  1800. const right = smallButton('be-item-action', iconSvg('arrow-down'), 'Move column right');
  1801. right.classList.add('be-rotate-left');
  1802. right.disabled = c === columnCount - 1;
  1803. right.addEventListener('click', () => moveColumn(c, c + 1));
  1804. const remove = smallButton('be-item-action be-item-remove', iconSvg('x'), 'Delete column');
  1805. remove.disabled = columnCount <= 1;
  1806. remove.addEventListener('click', () => {
  1807. rows.forEach((row) => row.splice(c, 1));
  1808. rerender(cellSelector(0, Math.max(0, c - 1)));
  1809. });
  1810. tools.appendChild(left);
  1811. tools.appendChild(right);
  1812. tools.appendChild(remove);
  1813. th.appendChild(tools);
  1814. colBar.appendChild(th);
  1815. }
  1816. colBar.appendChild(document.createElement('th'));
  1817. table.appendChild(colBar);
  1818. ​
  1819. rows.forEach((row, rowIndex) => {
  1820. const tr = document.createElement('tr');
  1821. tr.className = 'be-table-row';
  1822. ​
  1823. const gripCell = document.createElement('td');
  1824. gripCell.className = 'be-table-grip-cell';
  1825. const grip = smallButton('be-item-grip', iconSvg('menu'), 'Drag to move the row (or Alt + ↑/↓)');
  1826. grip.tabIndex = -1;
  1827. gripCell.appendChild(grip);
  1828. tr.appendChild(gripCell);
  1829. ​
  1830. row.forEach((cell, cellIndex) => {
  1831. const td = document.createElement('td');
  1832. const input = document.createElement('input');
  1833. input.type = 'text';
  1834. input.value = cell;
  1835. input.dataset.cell = rowIndex + '-' + cellIndex;
  1836. if (rowIndex === 0 && cellIndex === 0) {
  1837. input.dataset.focusTarget = '1';
  1838. }
  1839. input.setAttribute('aria-label', 'Row ' + (rowIndex + 1) + ', column ' + (cellIndex + 1));
  1840. input.addEventListener('input', () => {
  1841. rows[rowIndex][cellIndex] = input.value;
  1842. this.syncHiddenInput();
  1843. });
  1844. input.addEventListener('keydown', (event) => {
  1845. if (event.altKey && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) {
  1846. event.preventDefault();
  1847. moveRow(rowIndex, rowIndex + (event.key === 'ArrowUp' ? -1 : 1));
  1848. return;
  1849. }
  1850. if (event.key === 'Enter' && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
  1851. event.preventDefault();
  1852. if (rowIndex === rows.length - 1) {
  1853. rows.push(new Array(columnCount).fill(''));
  1854. rerender(cellSelector(rowIndex + 1, cellIndex));
  1855. } else {
  1856. this.focusIn(block.id, cellSelector(rowIndex + 1, cellIndex));
  1857. }
  1858. }
  1859. });
  1860. td.appendChild(input);
  1861. tr.appendChild(td);
  1862. });
  1863. ​
  1864. const actions = document.createElement('td');
  1865. actions.className = 'be-table-row-actions';
  1866. const tools = document.createElement('div');
  1867. tools.className = 'be-table-tools';
  1868. const up = smallButton('be-item-action', iconSvg('arrow-up'), 'Move row up');
  1869. up.disabled = rowIndex === 0;
  1870. up.addEventListener('click', () => moveRow(rowIndex, rowIndex - 1));
  1871. const down = smallButton('be-item-action', iconSvg('arrow-down'), 'Move row down');
  1872. down.disabled = rowIndex === rows.length - 1;
  1873. down.addEventListener('click', () => moveRow(rowIndex, rowIndex + 1));
  1874. const remove = smallButton('be-item-action be-item-remove', iconSvg('x'), 'Delete row');
  1875. remove.disabled = rows.length <= 1;
  1876. remove.addEventListener('click', () => {
  1877. rows.splice(rowIndex, 1);
  1878. rerender(cellSelector(Math.max(0, rowIndex - 1), 0));
  1879. });
  1880. tools.appendChild(up);
  1881. tools.appendChild(down);
  1882. tools.appendChild(remove);
  1883. actions.appendChild(tools);
  1884. tr.appendChild(actions);
  1885. ​
  1886. makeDraggableRow(tr, grip, block.id + ':rows', rowIndex, moveRow);
  1887. table.appendChild(tr);
  1888. });
  1889. ​
  1890. const tableScroll = document.createElement('div');
  1891. tableScroll.className = 'be-table-scroll';
  1892. tableScroll.appendChild(table);
  1893. container.appendChild(tableScroll);
  1894. ​
  1895. const controls = document.createElement('div');
  1896. controls.className = 'be-table-controls';
  1897. const addRowBtn = smallButton('be-add-item', iconSvg('plus') + 'Row');
  1898. addRowBtn.addEventListener('click', () => {
  1899. rows.push(new Array(columnCount).fill(''));
  1900. rerender(cellSelector(rows.length - 1, 0));
  1901. });
  1902. const addColBtn = smallButton('be-add-item', iconSvg('plus') + 'Column');
  1903. addColBtn.addEventListener('click', () => {
  1904. rows.forEach((row) => row.push(''));
  1905. rerender(cellSelector(0, columnCount));
  1906. });
  1907. controls.appendChild(addRowBtn);
  1908. controls.appendChild(addColBtn);
  1909. container.appendChild(controls);
  1910. break;
  1911. }
  1912. case 'checklist': {
  1913. if (!Array.isArray(block.data.items) || block.data.items.length === 0) {
  1914. block.data.items = [{ text: '', checked: false }];
  1915. }
  1916. container.appendChild(this.buildItemRows(block, 'checklist'));
  1917. break;
  1918. }
  1919. case 'callout': {
  1920. const styleSelect = document.createElement('select');
  1921. const calloutLabels = { info: 'Info', warning: 'Warning', success: 'Success', danger: 'Danger' };
  1922. ['info', 'warning', 'success', 'danger'].forEach((style) => {
  1923. const option = document.createElement('option');
  1924. option.value = style;
  1925. option.textContent = calloutLabels[style];
  1926. option.selected = block.data.style === style;
  1927. styleSelect.appendChild(option);
  1928. });
  1929. styleSelect.className = 'be-callout-select';
  1930. container.classList.add('be-callout', 'be-callout-' + (block.data.style || 'info'));
  1931. styleSelect.addEventListener('change', () => {
  1932. container.classList.remove('be-callout-info', 'be-callout-warning', 'be-callout-success', 'be-callout-danger');
  1933. container.classList.add('be-callout-' + styleSelect.value);
  1934. update({ style: styleSelect.value });
  1935. });
  1936. container.appendChild(styleSelect);
  1937. ​
  1938. const text = document.createElement('div');
  1939. text.className = 'be-editable be-callout-text';
  1940. text.contentEditable = 'true';
  1941. text.spellcheck = spellcheckEnabled();
  1942. text.dataset.focusTarget = '1';
  1943. text.textContent = block.data.text || '';
  1944. text.addEventListener('input', () => update({ text: text.textContent }));
  1945. attachCleanPaste(text);
  1946. container.appendChild(text);
  1947. break;
  1948. }
  1949. case 'embed': {
  1950. container.appendChild(this.buildInput('Link to embed (e.g. YouTube or a map)', block.data.url, (val) => update({ url: val }), true));
  1951. break;
  1952. }
  1953. case 'separator':
  1954. container.appendChild(document.createElement('hr'));
  1955. break;
  1956. case 'contact_form': {
  1957. const note = document.createElement('div');
  1958. note.className = 'be-contact-form';
  1959. note.innerHTML = iconSvg('mail') + '<div><strong>Contact form</strong><span>Visitors leave their name, email and message, type the security code, and it lands in the inbox set in Settings &rarr; General &rarr; Contact form. You can add one per page.</span>' +
  1960. (this.contactFormMode === 'enabled' ? '' : '<span class="be-contact-form-off">The contact form is switched off in Settings, so this block won’t show on the site.</span>') +
  1961. '</div>';
  1962. container.appendChild(note);
  1963. break;
  1964. }
  1965. default:
  1966. break;
  1967. }
  1968. ​
  1969. return container;
  1970. }
  1971. ​
  1972. buildItemRows(block, kind) {
  1973. const isChecklist = kind === 'checklist';
  1974. const items = block.data.items;
  1975. const ordered = !isChecklist && block.data.style === 'ordered';
  1976. const textOf = (i) => (isChecklist ? String(items[i].text || '') : String(items[i] || ''));
  1977. const setText = (i, value) => {
  1978. if (isChecklist) {
  1979. items[i].text = value;
  1980. } else {
  1981. items[i] = value;
  1982. }
  1983. };
  1984. const blank = (text) => (isChecklist ? { text: text || '', checked: false } : (text || ''));
  1985. const itemSelector = (i) => '[data-item-index="' + i + '"]';
  1986. const rerender = (focusIndex, caret) => {
  1987. this.render();
  1988. this.focusIn(block.id, itemSelector(focusIndex), caret);
  1989. };
  1990. const move = (from, to) => {
  1991. if (moveInArray(items, from, to)) {
  1992. rerender(to);
  1993. }
  1994. };
  1995. ​
  1996. const wrap = document.createElement('div');
  1997. wrap.className = 'be-items' + (isChecklist ? ' is-checklist' : (ordered ? ' is-ordered' : ' is-bullets'));
  1998. ​
  1999. items.forEach((item, index) => {
  2000. const row = document.createElement('div');
  2001. row.className = 'be-item-row';
  2002. ​
  2003. const grip = smallButton('be-item-grip', iconSvg('menu'), 'Drag to move (or Alt + ↑/↓)');
  2004. grip.tabIndex = -1;
  2005. row.appendChild(grip);
  2006. ​
  2007. if (isChecklist) {
  2008. const checkbox = document.createElement('input');
  2009. checkbox.type = 'checkbox';
  2010. checkbox.className = 'be-item-check';
  2011. checkbox.checked = !!item.checked;
  2012. checkbox.setAttribute('aria-label', 'Done');
  2013. checkbox.addEventListener('change', () => {
  2014. items[index].checked = checkbox.checked;
  2015. row.classList.toggle('is-done', checkbox.checked);
  2016. this.syncHiddenInput();
  2017. });
  2018. row.classList.toggle('is-done', checkbox.checked);
  2019. row.appendChild(checkbox);
  2020. } else {
  2021. const marker = document.createElement('span');
  2022. marker.className = 'be-item-marker';
  2023. marker.textContent = ordered ? (index + 1) + '.' : '•';
  2024. row.appendChild(marker);
  2025. }
  2026. ​
  2027. const input = document.createElement('input');
  2028. input.type = 'text';
  2029. input.className = 'be-item-input';
  2030. input.value = textOf(index);
  2031. input.placeholder = index === 0 ? (isChecklist ? 'Task' : 'List item') : '';
  2032. input.dataset.itemIndex = String(index);
  2033. if (index === 0) {
  2034. input.dataset.focusTarget = '1';
  2035. }
  2036. input.addEventListener('input', () => {
  2037. setText(index, input.value);
  2038. this.syncHiddenInput();
  2039. });
  2040. input.addEventListener('keydown', (event) => {
  2041. if (event.altKey && (event.key === 'ArrowUp' || event.key === 'ArrowDown')) {
  2042. event.preventDefault();
  2043. move(index, index + (event.key === 'ArrowUp' ? -1 : 1));
  2044. return;
  2045. }
  2046. if (event.key === 'Enter' && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
  2047. event.preventDefault();
  2048. const start = input.selectionStart || 0;
  2049. const value = input.value;
  2050. setText(index, value.slice(0, start));
  2051. items.splice(index + 1, 0, blank(value.slice(input.selectionEnd || start)));
  2052. rerender(index + 1, 'start');
  2053. return;
  2054. }
  2055. if (event.key === 'Backspace' && input.selectionStart === 0 && input.selectionEnd === 0 && index > 0) {
  2056. event.preventDefault();
  2057. const previousLength = textOf(index - 1).length;
  2058. setText(index - 1, textOf(index - 1) + input.value);
  2059. items.splice(index, 1);
  2060. rerender(index - 1, previousLength);
  2061. return;
  2062. }
  2063. if (event.key === 'Delete' && input.value === '' && items.length > 1) {
  2064. event.preventDefault();
  2065. items.splice(index, 1);
  2066. rerender(Math.min(index, items.length - 1), 'start');
  2067. return;
  2068. }
  2069. if ((event.key === 'ArrowUp' && index > 0) || (event.key === 'ArrowDown' && index < items.length - 1)) {
  2070. event.preventDefault();
  2071. this.focusIn(block.id, itemSelector(index + (event.key === 'ArrowUp' ? -1 : 1)));
  2072. }
  2073. });
  2074. input.addEventListener('paste', (event) => {
  2075. const clipboard = event.clipboardData || global.clipboardData;
  2076. const text = clipboard ? clipboard.getData('text/plain') : '';
  2077. const lines = text.split(/\r?\n/).map((line) => line.replace(LIST_MARKER, '').trim()).filter((line) => line !== '');
  2078. if (lines.length < 2) {
  2079. return;
  2080. }
  2081. event.preventDefault();
  2082. const start = input.selectionStart || 0;
  2083. const value = input.value;
  2084. const head = value.slice(0, start);
  2085. const tail = value.slice(input.selectionEnd || start);
  2086. setText(index, head + lines[0]);
  2087. const extra = lines.slice(1).map((line) => blank(line));
  2088. const lastIndex = index + extra.length;
  2089. items.splice(index + 1, 0, ...extra);
  2090. setText(lastIndex, textOf(lastIndex) + tail);
  2091. rerender(lastIndex, textOf(lastIndex).length - tail.length);
  2092. });
  2093. row.appendChild(input);
  2094. ​
  2095. const actions = document.createElement('div');
  2096. actions.className = 'be-item-actions';
  2097. const up = smallButton('be-item-action', iconSvg('arrow-up'), 'Move up');
  2098. up.disabled = index === 0;
  2099. up.addEventListener('click', () => move(index, index - 1));
  2100. const down = smallButton('be-item-action', iconSvg('arrow-down'), 'Move down');
  2101. down.disabled = index === items.length - 1;
  2102. down.addEventListener('click', () => move(index, index + 1));
  2103. const remove = smallButton('be-item-action be-item-remove', iconSvg('x'), 'Remove item');
  2104. remove.addEventListener('click', () => {
  2105. if (items.length === 1) {
  2106. items[0] = blank('');
  2107. } else {
  2108. items.splice(index, 1);
  2109. }
  2110. rerender(Math.max(0, Math.min(index, items.length - 1)));
  2111. });
  2112. actions.appendChild(up);
  2113. actions.appendChild(down);
  2114. actions.appendChild(remove);
  2115. row.appendChild(actions);
  2116. ​
  2117. makeDraggableRow(row, grip, block.id + ':items', index, move);
  2118. wrap.appendChild(row);
  2119. });
  2120. ​
  2121. const addButton = smallButton('be-add-item', iconSvg('plus') + 'Add item');
  2122. addButton.addEventListener('click', () => {
  2123. items.push(blank(''));
  2124. rerender(items.length - 1);
  2125. });
  2126. const fragment = document.createElement('div');
  2127. fragment.className = 'be-items-wrap';
  2128. fragment.appendChild(wrap);
  2129. fragment.appendChild(addButton);
  2130. const hint = document.createElement('p');
  2131. hint.className = 'be-items-hint';
  2132. hint.textContent = 'Enter adds an item · Backspace at the start joins it with the one above · Alt + ↑/↓ moves it';
  2133. fragment.appendChild(hint);
  2134. return fragment;
  2135. }
  2136. ​
  2137. buildUploadButton(kind, onUploaded) {
  2138. const wrapper = document.createElement('div');
  2139. wrapper.className = 'be-upload-wrapper';
  2140. ​
  2141. const fileInput = document.createElement('input');
  2142. fileInput.type = 'file';
  2143. fileInput.accept = kind === 'image' ? 'image/jpeg,image/png,image/gif,image/webp' : 'video/mp4,video/webm';
  2144. fileInput.style.display = 'none';
  2145. ​
  2146. const button = document.createElement('button');
  2147. button.type = 'button';
  2148. button.textContent = 'Upload ' + kind;
  2149. button.addEventListener('click', () => {
  2150. if (window.PublisiumMedia) {
  2151. window.PublisiumMedia.open({ type: kind === 'image' ? 'image' : 'video', onSelect: onUploaded });
  2152. } else {
  2153. fileInput.click();
  2154. }
  2155. });
  2156. ​
  2157. const status = document.createElement('span');
  2158. status.className = 'be-upload-status';
  2159. ​
  2160. fileInput.addEventListener('change', () => {
  2161. const file = fileInput.files[0];
  2162. if (!file) {
  2163. return;
  2164. }
  2165. status.textContent = 'Uploading…';
  2166. uploadFile(
  2167. file,
  2168. (url) => {
  2169. status.textContent = '';
  2170. onUploaded(url);
  2171. },
  2172. (error) => {
  2173. status.textContent = error;
  2174. }
  2175. );
  2176. });
  2177. ​
  2178. wrapper.appendChild(button);
  2179. wrapper.appendChild(fileInput);
  2180. wrapper.appendChild(status);
  2181. return wrapper;
  2182. }
  2183. ​
  2184. buildInput(placeholder, value, onInput, autofocus) {
  2185. const input = document.createElement('input');
  2186. input.type = 'text';
  2187. input.placeholder = placeholder;
  2188. input.value = value || '';
  2189. if (autofocus) {
  2190. input.dataset.focusTarget = '1';
  2191. }
  2192. input.addEventListener('input', () => onInput(input.value));
  2193. return input;
  2194. }
  2195. }
  2196. ​
  2197. function ensureBlockEditorIconStyles() {
  2198. if (document.getElementById('be-icon-styles')) {
  2199. return;
  2200. }
  2201. const style = document.createElement('style');
  2202. style.id = 'be-icon-styles';
  2203. style.textContent =
  2204. '.be-block-type{display:inline-flex;align-items:center;gap:6px;}' +
  2205. '.be-block-toolbar button svg.icon{display:block;}' +
  2206. '.be-block-menu-item{display:flex;align-items:center;gap:10px;width:100%;text-align:left;}' +
  2207. '.be-block-menu-item svg.icon{flex-shrink:0;}' +
  2208. '.be-block-menu-item:disabled{opacity:.55;cursor:not-allowed;}' +
  2209. '.be-block-menu-note{margin-left:auto;font-size:11px;opacity:.8;}' +
  2210. '.be-contact-form{display:flex;gap:10px;align-items:flex-start;padding:12px 14px;border:1px dashed var(--border);border-radius:8px;font-size:13px;line-height:1.5;}' +
  2211. '.be-contact-form svg.icon{flex-shrink:0;margin-top:2px;}' +
  2212. '.be-contact-form strong,.be-contact-form span{display:block;}' +
  2213. '.be-contact-form-off{margin-top:6px;color:var(--warning);}' +
  2214. '.be-link-popover{position:absolute;z-index:1000;width:300px;padding:12px;border:1px solid var(--border);border-radius:12px;background:var(--panel);box-shadow:0 12px 32px rgba(0,0,0,.25);font-size:13px;}' +
  2215. '.be-link-label{display:block;margin:0 0 6px;font-weight:600;color:var(--muted);}' +
  2216. '.be-link-input{width:100%;box-sizing:border-box;}' +
  2217. '.be-link-newtab{display:flex;align-items:center;gap:8px;margin:10px 0;}' +
  2218. '.be-link-actions{display:flex;gap:8px;}' +
  2219. '.be-link-actions button{flex:1;padding:7px 10px;border-radius:8px;border:1px solid var(--border);background:transparent;color:inherit;cursor:pointer;font:inherit;}' +
  2220. '.be-link-actions .be-link-apply{background:var(--accent);border-color:var(--accent);color:#fff;}' +
  2221. '.be-link-trigger svg{display:block;}' +
  2222. '.be-editable a{color:var(--accent);text-decoration:underline;}' +
  2223. '.be-block-lock{display:inline-flex;align-items:center;padding:0 4px;opacity:.6;}' +
  2224. '.be-block-lock svg.icon{display:block;}';
  2225. document.head.appendChild(style);
  2226. }
  2227. ​
  2228. document.addEventListener('DOMContentLoaded', function () {
  2229. const root = document.getElementById('block-editor-root');
  2230. if (root) {
  2231. ensureBlockEditorIconStyles();
  2232. window.publisiumBlockEditor = new BlockEditor(root);
  2233. }
  2234. });
  2235. })(window);
  2236. ​