Skip to content

Commit

Permalink
feat: allow custom attributes to be dynamic
Browse files Browse the repository at this point in the history
  • Loading branch information
jorenrui committed May 3, 2024
1 parent e4d8595 commit 17af79a
Showing 1 changed file with 27 additions and 17 deletions.
44 changes: 27 additions & 17 deletions lib/entity/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,16 @@ export class Attributes {
static FORBIDDEN_ATTRIBUTES = [':innerHTML', ':innerText']

static isValidAttribute(attribute, element) {
if (attribute === ':') return false
if (!attribute.startsWith(':')) return false
if (Attributes.FORBIDDEN_ATTRIBUTES.includes(attribute)) return false
if (Events.isValidEvent(attribute)) return false
if (Attributes.CUSTOM_ATTRIBUTES.includes(attribute)) return true

return true
}

static isValidNativeAttribute(attribute, element) {
if (!Attributes.isValidAttribute(attribute)) return false

const [nativeAttr] = attribute.replace(':', '').split('.')

Expand Down Expand Up @@ -241,27 +247,31 @@ export class Attributes {
for (const attr of this.dynamicAttributes) {
if (Attributes.CUSTOM_ATTRIBUTES.includes(attr)) continue

const expr = this.entity.element.getAttribute(attr)
const element = this.entity.element
const expr = element.getAttribute(attr)
if (!expr) return

try {
const newValue = await this._interpret(expr)
const nativeAttr = kebabToCamelCase(attr.slice(1))

if (attr.startsWith(':data-')) {
if (
this.entity.element.dataset[nativeAttr.slice(4)] !== newValue &&
newValue != null
) {
const datasetAttr =
nativeAttr[4].toLowerCase() + nativeAttr.slice(5)
this.entity.element.dataset[datasetAttr] = newValue

if (Attributes.isValidNativeAttribute(attr, element)) {
const nativeAttr = kebabToCamelCase(attr.slice(1))

if (attr.startsWith(':data-')) {
if (
element.dataset[nativeAttr.slice(4)] !== newValue &&
newValue != null
) {
const datasetAttr =
nativeAttr[4].toLowerCase() + nativeAttr.slice(5)
element.dataset[datasetAttr] = newValue
}
} else if (element[nativeAttr] !== newValue && newValue != null) {
element[nativeAttr] = newValue
}
} else if (
this.entity.element[nativeAttr] !== newValue &&
newValue != null
)
this.entity.element[nativeAttr] = newValue
} else {
element.setAttribute(attr.slice(1), newValue)
}
} catch (error) {
this._handleError(attr, expr, error)
}
Expand Down

0 comments on commit 17af79a

Please sign in to comment.