tiny-dream
Version:
A tiny Incremental DOM implementation for modern browsers.
79 lines (63 loc) • 1.56 kB
JavaScript
import { createEmptyObject, hasOwnProperty } from './utils'
const getNamespace = (name) => {
if (name.lastIndexOf('xml:', 0) === 0) {
return 'http://www.w3.org/XML/1998/namespace'
}
if (name.lastIndexOf('xlink:', 0) === 0) {
return 'http://www.w3.org/1999/xlink'
}
}
const applyAttr = (el, name, value) => {
if (value === null) {
el.removeAttribute(name)
return
}
const attrNS = getNamespace(name)
if (attrNS) {
el.setAttributeNS(attrNS, name, value)
return
}
el.setAttribute(name, value)
}
const applyProp = (el, name, value) => {
el[name] = value
}
const setStyleValue = (style, prop, value) => {
if (-1 < prop.indexOf('-')) {
style.setProperty(prop, value)
return
}
style[prop] = value
}
const applyStyle = (el, ignore, style) => {
if (typeof style === 'string') {
el.style.cssText = style
return
}
for (const prop in style) {
if (hasOwnProperty(style, prop)) {
setStyleValue(el.style, prop, style[prop])
}
}
}
const applyAttributeTyped = (el, name, value) => {
const type = typeof value
if (type === 'object' || type === 'function') {
applyProp(el, name, value)
} else {
applyAttr(el, name, value)
}
}
const attributes = createEmptyObject()
attributes['__TinyDream__'] = applyAttributeTyped
attributes['style'] = applyStyle
const updateAttribute = (el, name, value) => {
const mutator = attributes[name] || attributes['__TinyDream__']
mutator(el, name, value)
}
export {
updateAttribute,
applyProp,
applyAttr,
attributes
}