mirror of
https://github.com/jaandrle/deka-dom-el
synced 2024-11-21 15:39:36 +01:00
🎉
This commit is contained in:
parent
9ee4a36530
commit
7a17fa8e35
79
index.d.ts
vendored
Normal file
79
index.d.ts
vendored
Normal file
@ -0,0 +1,79 @@
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
type T_DOM_HETNM= HTMLElementTagNameMap & SVGElementTagNameMap & {
|
||||
'<>': DocumentFragment,
|
||||
'': HTMLElement,
|
||||
'zzz_text': Text
|
||||
}
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
type T_DOM_ATTRS_MODIFIED= {
|
||||
/**
|
||||
* In fact argumen for `*.setAttribute("style", *)`.
|
||||
*/
|
||||
style: string
|
||||
/**
|
||||
* Provide option to add/remove/toggle CSS clasess (index of object) using 1/0/-1. In fact `el.classList.toggle(class_name)` for `-1` and `el.classList.toggle(class_name, Boolean(...))` for others.
|
||||
*/
|
||||
classList: Record<string,-1|0|1>
|
||||
}
|
||||
/**
|
||||
* Just element attributtes
|
||||
*
|
||||
* In most cases, you can use native propertie such as [MDN WEB/API/Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) and so on (e.g. [`Text`](https://developer.mozilla.org/en-US/docs/Web/API/Text)).
|
||||
*
|
||||
* There is added support for `data[A-Z].*`/`aria[A-Z].*` to be converted to the kebab-case alternatives.
|
||||
* @private
|
||||
*/
|
||||
type T_DOM_ATTRS<T extends keyof T_DOM_HETNM | T_DOM_HETNM[keyof T_DOM_HETNM]>=
|
||||
T extends keyof T_DOM_HETNM ?
|
||||
Omit<T_DOM_HETNM[T],"classList"> & T_DOM_ATTRS_MODIFIED :
|
||||
Omit<T,"classList"> & T_DOM_ATTRS_MODIFIED;
|
||||
/**
|
||||
* Procedure for merging object into the element properties.
|
||||
* Very simple example: `$dom.assign(document.body, { className: "test" });` is equivalent to `document.body.className= "test";`.
|
||||
* It is not deep copy in general, but it supports `style`, `style_vars` and `dataset` objects (see below).
|
||||
*
|
||||
* **#1: All together**
|
||||
* ```javascript
|
||||
* const el= document.body;
|
||||
* const onclick= function(){ console.log(this.dataset.js_param); };
|
||||
* $dom.assign(el, { textContent: "BODY", style: "color: red;", dataset: { js_param: "CLICKED" }, onclick });
|
||||
* //result HTML: <body style="color: red;" data-js_param="CLICKED">BODY</body>
|
||||
* //console output on click: "CLICKED"
|
||||
* $dom.assign(el, { style: { color: "green" } });
|
||||
* //result HTML: <body style="color: green;" data-js_param="CLICKED">BODY</body>
|
||||
* //console output on click: "CLICKED"
|
||||
* ```
|
||||
*
|
||||
* **`\*.classList.toggle`**
|
||||
* ```javascript
|
||||
* const el= document.body;
|
||||
* $dom.assign(el, { classList: { testClass: -1 } });
|
||||
* //result HTML: <body class="testClass">…</body>
|
||||
* $dom.assign(el, { classList: { testClass: -1 } });
|
||||
* //result HTML: <body class="">…</body>
|
||||
*
|
||||
* $dom.assign(el, { classList: { testClass: true } });//or 1
|
||||
* //result HTML: <body class="testClass">…</body>
|
||||
* $dom.assign(el, { classList: { testClass: false } });//or 0
|
||||
* //result HTML: <body class="">…</body>
|
||||
* //...
|
||||
* ```
|
||||
*
|
||||
* **#3 Links and images**
|
||||
* ```javascript
|
||||
* $dom.assign(A_ELEMENT, { href: "www.google.com" });//=> <a href="www.google.com" …
|
||||
* $dom.assign(IMG_ELEMENT, { src: "image.png" });//=> <img src="image.png" …
|
||||
*
|
||||
* **#4 data\* and aria\***
|
||||
* $dom.assign(el, { ariaLabel: "The aria-label", dataExample: "data-example" });//=> <body aria-label="The aria-label" data-example="data-example">
|
||||
* ```
|
||||
* @category Public
|
||||
* @version 2.0.0
|
||||
*/
|
||||
export function assign<EL extends HTMLElement>(element: EL, ...attrs_array: T_DOM_ATTRS<EL>[]): EL
|
||||
|
||||
export function el<TAG extends keyof T_DOM_HETNM>(tag_name: TAG, attrs: T_DOM_ATTRS<T_DOM_HETNM[TAG]>): T_DOM_HETNM[TAG]
|
75
index.js
Normal file
75
index.js
Normal file
@ -0,0 +1,75 @@
|
||||
[ HTMLElement, DocumentFragment ].forEach(c=> {
|
||||
const { append }= c.prototype;
|
||||
c.prototype.append= function(...els){ append.apply(this, els); return this; };
|
||||
});
|
||||
|
||||
export function createElement(tag, attributes){
|
||||
if(tag==="<>") return document.createDocumentFragment();
|
||||
if(tag==="") return document.createTextNode(attributes.textContent ?? attributes.innerText ?? attributes.innerHTML);
|
||||
return assign(document.createElement(tag), attributes);
|
||||
}
|
||||
export { createElement as el };
|
||||
export function createElementNS(tag, attributes, attributes_todo){
|
||||
let namespace= "svg";
|
||||
if(typeof attributes_todo !== "undefined"){
|
||||
namespace= tag; tag= attributes; attributes= attributes_todo; }
|
||||
if(tag==="<>") return document.createDocumentFragment();
|
||||
if(tag==="") return document.createTextNode(attributes.textContent ?? attributes.innerText ?? attributes.innerHTML);
|
||||
return assign(document.createElementNS(namespace==="svg" ? "http://www.w3.org/2000/svg" : namespace, tag), attributes);
|
||||
}
|
||||
export { createElementNS as elNS };
|
||||
|
||||
export function assign(element, ...attributes){
|
||||
// prefers https://developer.mozilla.org/en-US/docs/Glossary/IDL
|
||||
if(!attributes.length) return element;
|
||||
const is_svg= element instanceof SVGElement;
|
||||
const setRemoveAttr= (is_svg ? setRemoveNS : setRemove).bind(null, element, "Attribute");
|
||||
|
||||
Object.entries(Object.assign({}, ...attributes)).forEach(function([ key, attr ]){
|
||||
if(key[0]==="=") return setRemoveAttr(key.slice(1), attr);
|
||||
if(key[0]===".") return setDelete(element, key.slice(1), attr);
|
||||
if(typeof attr === "object"){
|
||||
switch(key){
|
||||
case "style": return forEachEntries(attr, setRemove.bind(null, element.style, "Property"))
|
||||
case "dataset": return forEachEntries(attr, setDelete.bind(null, element.dataset));
|
||||
case "ariaset": return forEachEntries(attr, (key, val)=> setRemoveAttr("aria-"+key, val));
|
||||
case "classList": return classListDeclartive(element, attr);
|
||||
default: return Reflect.set(element, key, attr);
|
||||
}
|
||||
}
|
||||
if(/(aria|data)([A-Z])/.test(key)){
|
||||
key= key.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
|
||||
return setRemoveAttr(key, attr);
|
||||
}
|
||||
switch(key){
|
||||
case "href" || "src" || "style":
|
||||
return setRemoveAttr(key, attr);
|
||||
case "xlink:href":
|
||||
return setRemoveAttr(key, attr, "http://www.w3.org/1999/xlink");
|
||||
case "textContent" || "innerText":
|
||||
if(!is_svg) break;
|
||||
return element.appendChild(document.createTextNode(attr));
|
||||
}
|
||||
if(key in element && !is_svg)
|
||||
return setDelete(element, key, attr);
|
||||
return setRemoveAttr(key, attr);
|
||||
});
|
||||
return element;
|
||||
}
|
||||
export function classListDeclartive(element, toggle){
|
||||
if(typeof toggle !== "object") return element;
|
||||
|
||||
forEachEntries(toggle,
|
||||
(class_name, val)=>
|
||||
element.classList.toggle(class_name, val===-1 ? undefined : Boolean(val)))
|
||||
return element;
|
||||
}
|
||||
|
||||
export function empty(el){ Array.from(el.children).forEach(el=> el.remove()); return el; }
|
||||
|
||||
function forEachEntries(obj, cb){ return Object.entries(obj).forEach(([ key, val ])=> cb(key, val)); }
|
||||
function isUndef(value){ return typeof value==="undefined"; }
|
||||
|
||||
function setRemove(obj, prop, key, val){ return obj[ (isUndef(val) ? "remove" : "set") + prop ](key, val); }
|
||||
function setRemoveNS(obj, prop, key, val, ns= null){ return obj[ (isUndef(val) ? "remove" : "set") + prop + "NS" ](ns, key, val); }
|
||||
function setDelete(obj, prop, val){ return Reflect[ isUndef(val) ? "deleteProperty" : "set" ](obj, prop, val); }
|
16
test/index.html
Normal file
16
test/index.html
Normal file
@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html class="no-js" lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<!-- DEL CSP https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP | https://github.com/Prinzhorn/minimal-csp -->
|
||||
<!-- DEL https://github.com/jensimmons/cssremedy -->
|
||||
<link rel="stylesheet" href="https://github.com/jensimmons/cssremedy/raw/master/css/remedy.css">
|
||||
|
||||
<title>Small DOM element creation enhancements</title>
|
||||
<meta name="description" content="Making creatig elements easier">
|
||||
<script src="index.js" type="module"></script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
17
test/index.js
Normal file
17
test/index.js
Normal file
@ -0,0 +1,17 @@
|
||||
import { el, elNS, assign } from "../index.js";
|
||||
Object.assign(globalThis, { el, elNS, assign });
|
||||
|
||||
console.log(el("p", { className: "red", textContent: "Hello "}));
|
||||
console.log(el("p", { className: "red", textContent: "Hello "}) instanceof HTMLParagraphElement);
|
||||
|
||||
document.head.append(
|
||||
el("style", { textContent: `
|
||||
.red{ color: red; }
|
||||
` })
|
||||
)
|
||||
document.body.append(
|
||||
el("p", { className: "red" }).append(
|
||||
el("", { textContent: "Hello " }),
|
||||
el("strong", { textContent: "World" })
|
||||
)
|
||||
);
|
Loading…
Reference in New Issue
Block a user