X-Git-Url: http://source.bookstackapp.com/bookstack/blobdiff_plain/58cadce052f5cc3c9ce2bc12f88a93cac310699a..refs/pull/5280/head:/resources/js/services/dom.js diff --git a/resources/js/services/dom.js b/resources/js/services/dom.js index 17f5a803a..bcfd0b565 100644 --- a/resources/js/services/dom.js +++ b/resources/js/services/dom.js @@ -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} 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 = '
'; } +/** + * Get a loading element indicator element. + * @returns {Element} + */ +export function getLoading() { + const wrap = document.createElement('div'); + wrap.classList.add('loading-container'); + wrap.innerHTML = '
'; + return wrap; +} + /** * Remove any loading indicators within the given element. * @param {Element} element