]> BookStack Code Mirror - bookstack/blobdiff - resources/js/services/dom.js
Update sponsor image URLs in readme
[bookstack] / resources / js / services / dom.js
index 17f5a803aad7a03e80f8b2a45936eba1205a1aaa..bcfd0b565da2ab9b9144af2243d2cdb2fe13cc50 100644 (file)
@@ -1,3 +1,33 @@
+/**
+ * Create a new element with the given attrs and children.
+ * Children can be a string for text nodes or other elements.
+ * @param {String} tagName
+ * @param {Object<String, String>} attrs
+ * @param {Element[]|String[]}children
+ * @return {*}
+ */
+export function elem(tagName, attrs = {}, children = []) {
+    const el = document.createElement(tagName);
+
+    for (const [key, val] of Object.entries(attrs)) {
+        if (val === null) {
+            el.removeAttribute(key);
+        } else {
+            el.setAttribute(key, val);
+        }
+    }
+
+    for (const child of children) {
+        if (typeof child === 'string') {
+            el.append(document.createTextNode(child));
+        } else {
+            el.append(child);
+        }
+    }
+
+    return el;
+}
+
 /**
  * Run the given callback against each element that matches the given selector.
  * @param {String} selector
@@ -45,22 +75,41 @@ export function onSelect(elements, callback) {
 }
 
 /**
- * Listen to enter press on the given element(s).
+ * Listen to key press on the given element(s).
+ * @param {String} key
  * @param {HTMLElement|Array} elements
  * @param {function} callback
  */
-export function onEnterPress(elements, callback) {
+function onKeyPress(key, elements, callback) {
     if (!Array.isArray(elements)) {
         elements = [elements];
     }
 
     const listener = event => {
-        if (event.key === 'Enter') {
+        if (event.key === key) {
             callback(event);
         }
     };
 
-    elements.forEach(e => e.addEventListener('keypress', listener));
+    elements.forEach(e => e.addEventListener('keydown', listener));
+}
+
+/**
+ * Listen to enter press on the given element(s).
+ * @param {HTMLElement|Array} elements
+ * @param {function} callback
+ */
+export function onEnterPress(elements, callback) {
+    onKeyPress('Enter', elements, callback);
+}
+
+/**
+ * Listen to escape press on the given element(s).
+ * @param {HTMLElement|Array} elements
+ * @param {function} callback
+ */
+export function onEscapePress(elements, callback) {
+    onKeyPress('Escape', elements, callback);
 }
 
 /**
@@ -108,6 +157,17 @@ export function showLoading(element) {
     element.innerHTML = '<div class="loading-container"><div></div><div></div><div></div></div>';
 }
 
+/**
+ * Get a loading element indicator element.
+ * @returns {Element}
+ */
+export function getLoading() {
+    const wrap = document.createElement('div');
+    wrap.classList.add('loading-container');
+    wrap.innerHTML = '<div></div><div></div><div></div>';
+    return wrap;
+}
+
 /**
  * Remove any loading indicators within the given element.
  * @param {Element} element