WebOrbiton
v1.0.0.3

StocketBase

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