]> BookStack Code Mirror - bookstack/blob - resources/js/editor/node-views/node-view-utils.js
Started work on details/summary blocks
[bookstack] / resources / js / editor / node-views / node-view-utils.js
1 import crel from "crelt";
2
3 /**
4  * Render grab handles at the corners of the given element.
5  * @param {Element} elem
6  * @return {Element[]}
7  */
8 export function renderHandlesAtCorners(elem) {
9     const handles = [];
10     const baseClass = 'ProseMirror-grabhandle';
11
12     for (let i = 0; i < 4; i++) {
13         const y = (i < 2) ? 'top' : 'bottom';
14         const x = (i === 0 || i === 3) ? 'left' : 'right';
15         const handle = crel('div', {
16             class: `${baseClass} ${baseClass}-${x}-${y}`,
17         });
18         handle.dataset.y = y;
19         handle.dataset.x = x;
20         handles.push(handle);
21         elem.parentNode.appendChild(handle);
22     }
23
24     positionHandlesAtCorners(elem, handles);
25     return handles;
26 }
27
28 /**
29  * @param {Element[]} handles
30  */
31 export function removeHandles(handles) {
32     for (const handle of handles) {
33         handle.remove();
34     }
35 }
36
37 /**
38  *
39  * @param {Element} element
40  * @param {[Element, Element, Element, Element]}handles
41  */
42 export function positionHandlesAtCorners(element, handles) {
43     const bounds = element.getBoundingClientRect();
44     const parentBounds = element.parentElement.getBoundingClientRect();
45     const positions = [
46         {x: bounds.left - parentBounds.left, y: bounds.top - parentBounds.top},
47         {x: bounds.right - parentBounds.left, y: bounds.top - parentBounds.top},
48         {x: bounds.right - parentBounds.left, y: bounds.bottom - parentBounds.top},
49         {x: bounds.left - parentBounds.left, y: bounds.bottom - parentBounds.top},
50     ];
51
52     for (let i = 0; i < 4; i++) {
53         const {x, y} = positions[i];
54         const handle = handles[i];
55         handle.style.left = (x - 6) + 'px';
56         handle.style.top = (y - 6) + 'px';
57     }
58 }