Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | 1x 1x | const REGEX_LITERAL = /(\${.+?})/gi
const BOOLEAN_ATTRIBUTES = [
'allowfullscreen',
'allowpaymentrequest',
'async',
'autofocus',
'autoplay',
'checked',
'controls',
'default',
'defer',
'disabled',
'formnovalidate',
'hidden',
'ismap',
'itemscope',
'loop',
'multiple',
'muted',
'nomodule',
'novalidate',
'open',
'readonly',
'required',
'reversed',
'selected',
'typemustmatch'
]
export default class HtmlMarker {
constructor(defaultModel) {
this.referenceNodes = new Set()
this.uuid = new Date().getTime().toString(36) + performance.now().toString().replace(/[^0-9]/g, '') + '@'
this.model = {}
this.updateModel(defaultModel)
}
async render(target, templateString) {
/* remove comments that are found in the string since we use them as markers */
templateString = templateString.replace(/<!--[\s\S]*?-->/gm, '')
const rootElement = this._fragmentFromString(templateString)
const frag = this._markerTree(rootElement)
if (target) { /* allow for shadowRoot */
target.appendChild(frag)
await this._referenceTree(target)
await this.update()
}
return Promise.resolve(true)
}
updateModel(obj = {}) {
Object.assign(this.model, obj)
return this.update()
}
_fragmentFromString(strHTML) {
const template = document.createElement('template')
template.innerHTML = strHTML
return template.content.cloneNode(true)
}
_markChildNodes(childNodes) {
let expressions = []
Array.from(childNodes).forEach(node => {
if (node.hasChildNodes()) {
expressions = expressions.concat(this._markChildNodes(node.childNodes))
}
if (node.nodeValue && node.nodeValue.trim().length) {
const matches = node.nodeValue.trim().match(REGEX_LITERAL)
if (matches) {
expressions = expressions.concat(matches)
const template = node.nodeValue.trim()
const html = this._interpolate({ params: this.model, template, useMarkers: true })
const newNode = this._parseHTML(html)
node.parentNode.replaceChild(newNode, node)
}
}
})
return expressions
}
_markerTree(rootElement) {
const walker = document.createTreeWalker(
rootElement,
NodeFilter.SHOW_ALL,
null,
false
)
let expressions = []
while (walker.nextNode()) {
const node = walker.currentNode
if (node.nodeType === Node.ELEMENT_NODE && (window.customElements.get(node.tagName) || node.tagName.includes('-'))) {
continue
}
if (node.hasChildNodes()) {
expressions = expressions.concat(this._markChildNodes(node.childNodes))
}
if (node.nodeValue && node.nodeValue.trim().length) {
const matches = node.nodeValue.trim().match(REGEX_LITERAL)
if (matches) {
expressions = expressions.concat(matches)
const template = node.nodeValue.trim()
const html = this._interpolate({ params: this.model, template, useMarkers: true })
const newNode = this._parseHTML(html)
node.parentNode.replaceChild(newNode, node)
}
}
}
const walkerComments = document.createTreeWalker(
rootElement,
NodeFilter.SHOW_COMMENT,
null,
false
)
let i = 0
while (walkerComments.nextNode()) {
walkerComments.currentNode.textContent = `${this.uuid}${expressions[i++]}`
}
return rootElement
}
_parseHTML(html) {
const t = document.createElement('template')
t.innerHTML = html
return t.content.cloneNode(true)
}
_interpolate({ params, template, useMarkers = false }) {
const keys = Object.keys(params)
let keyValues = Object.values(params)
const returnFn = useMarkers ? `function markers (template, ...expressions) {
return template.reduce((accumulator, part, i) =>
\`\${accumulator}<!----><span>\${expressions[i - 1]}</span>\${part}\`
)
} return markers\`${template}\`` : `return \`${template}\``
return new Function(...keys, returnFn)(...keyValues)
}
_referenceTree(rootElement) {
const walker = document.createTreeWalker(
rootElement,
NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_ELEMENT,
null,
false
)
while (walker.nextNode()) {
const node = walker.currentNode
/* Do not filter custom elements to allow attribute updates */
if (node.nodeType === Node.ELEMENT_NODE && node.hasAttributes()) {
const attrs = [...node.attributes]
attrs.forEach(attr => {
const hasLiteral = attr.value.match(REGEX_LITERAL)
const isBooleanAttr = BOOLEAN_ATTRIBUTES.includes(attr.name)
if (hasLiteral) {
this.referenceNodes.add({
isBooleanAttr,
name: attr.name,
node: isBooleanAttr ? node : attr,
oldValue: null,
value: attr.value
})
if (isBooleanAttr) {
node.setAttribute(attr.name, '')
}
}
})
}
if (node.nodeType === Node.COMMENT_NODE) {
if (node.nodeValue.includes(this.uuid)) {
const nodeValue = node.nodeValue.replace(this.uuid, '')
if (node.parentElement.tagName === 'TEXTAREA') {
this.referenceNodes.add({ node: node.parentElement, oldValue: null, value: nodeValue })
} else {
this.referenceNodes.add({ node, oldValue: null, value: nodeValue })
}
}
}
}
return Promise.resolve(true)
}
update() {
this.referenceNodes.forEach(({ isBooleanAttr = false, name = '', node, oldValue = null, value }, reference) => {
if (!document.body.contains(node)) {
this.referenceNodes.delete(reference)
} else {
let newValue = this._interpolate({ params: this.model, template: value })
if (!isBooleanAttr && newValue !== oldValue) {
if (node.nodeType === Node.COMMENT_NODE) {
const newNode = this._parseHTML(`<span>${newValue}</span>`)
node.parentNode.replaceChild(newNode, node.nextSibling)
} else if (node.nodeType === Node.ATTRIBUTE_NODE) {
if (node.nodeName === 'class') {
newValue = this._handleClassValue({ node, oldValue, value })
} else {
node.value = newValue
}
} else if (node.tagName === 'TEXTAREA') {
node.value = newValue
}
}
if (isBooleanAttr) {
node.toggleAttribute(name, !!newValue.toString().length)
}
reference.oldValue = newValue
}
})
return Promise.resolve(true)
}
_handleClassValue({ node, oldValue = '', value }) {
const ownerElement = this._getNodeOwnerElement(node)
const values = value.split(' ').filter(cls => null !== cls.match(REGEX_LITERAL))
let newValFiltered = []
let newVal = []
if (values) {
/* remove starting literal values */
ownerElement.classList.remove(...values)
newVal = this._interpolate({ params: this.model, template: values.join(' ') })
newVal = newVal.split(' ').filter(className => className.length)
if (Array.isArray(newVal)) {
oldValue = Array.isArray(oldValue) ? oldValue : []
/* any old class in the new value can be ignored */
const intersection = newVal.filter(className => oldValue.includes(className))
oldValue = oldValue.filter(className => !intersection.includes(className))
newValFiltered = newVal.filter(className => !intersection.includes(className))
}
}
if (Array.isArray(oldValue) && oldValue.length) {
ownerElement.classList.remove(...oldValue)
}
if (Array.isArray(newValFiltered) && newValFiltered.length) {
ownerElement.classList.add(...newValFiltered)
}
return newVal
}
_getNodeOwnerElement(node) {
let ownerElement = node.ownerElement
while (ownerElement && !ownerElement.tagName) {
ownerElement = ownerElement.ownerElement
}
return ownerElement
}
}
|