Skip to content

Commit

Permalink
Merge pull request #26 from Group-One-Technology/feature/allow-custom…
Browse files Browse the repository at this point in the history
…-attributes

feat: allow custom attributes to be dynamic
  • Loading branch information
tonyennis145 authored Jun 18, 2024
2 parents e4d8595 + 17af79a commit eced283
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 eced283

Please sign in to comment.