UNPKG

element-props

Version:

Normalize access to element attributes/properties

1 lines 1.73 kB
export const parse=(e,t)=>(t=t===Object?JSON.parse:t===Array?e=>JSON.parse("["===e[0]?e:`[${e}]`):t,""===e&&t!==String||(t?t(e):!e||isNaN(+e)?e:+e)),prop=(r,o,a)=>{if(o.startsWith("on")&&(o=o.toLowerCase()),r[o]!==a&&(r[o]=a),null==a||!1===a)r.removeAttribute(o);else if("function"!=typeof a)if(a=!0===a?"":"number"==typeof a||"string"==typeof a?a:"class"===o?(Array.isArray(a)?a.map((e=>e?.trim())):Object.entries(a).map((([e,t])=>t?e:""))).filter(Boolean).join(" "):"style"===o?Object.entries(a).map((([e,t])=>`${e}: ${t}`)).join(";"):a.toString?.()||"","@"===o[0]){e.innerHTML=`<x ${t(o)}/>`;let i=e.firstChild.attributes[0];e.firstChild.removeAttributeNode(i),i.value=a,r.setAttributeNode(i)}else r.setAttribute(t(o),a)},input=e=>["checkbox"===e.type?()=>e.checked:()=>e.value,"text"===e.type||""===e.type?t=>e.value=null==t?"":t:"checkbox"===e.type?t=>(e.value=t?"on":"",prop(e,"checked",t)):"select-one"===e.type?t=>([...e.options].map((e=>e.removeAttribute("selected"))),e.value=t,e.selectedOptions[0]?.setAttribute("selected","")):t=>e.value=t];export default(e,r,o)=>{const a="INPUT"===e.tagName||"SELECT"===e.tagName,[i,s]=input(e),n=new Proxy(e.attributes,{get:(o,s,n)=>a&&"value"===s?i():s in e?e[s]:(n=o[t(s)])&&(n.call?n:parse(n.value,r?.[s])),set:(t,i,n)=>(a&&"value"===i?s(n):prop(e,i,parse(n,r?.[i])),o?.(i,n,t),1),deleteProperty:(t,r,o)=>(e.removeAttribute(r),e[r]=o,delete e[r]),getOwnPropertyDescriptor:e=>({enumerable:!0,configurable:!0}),ownKeys:t=>Array.from(new Set([...Object.keys(e),...Object.getOwnPropertyNames(t)].filter((t=>e[t]!==n&&isNaN(+t)))))});return a&&s(i()),n};const e=document.createElement("div");function t(e){return e.replace(/[A-Z\u00C0-\u00D6\u00D8-\u00DE]/g,(e=>"-"+e.toLowerCase()))}