+/**
+ * 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
}
/**
- * 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);
}
/**
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