Skip to content

Commit

Permalink
avoid updating during update call
Browse files Browse the repository at this point in the history
  • Loading branch information
keithamus committed Nov 25, 2022
1 parent c68fbe2 commit 7f73eab
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/relative-time-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ const dateObserver = new (class {

export default class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFormatOptions {
#customTitle = false
#updating = false

get #lang() {
return this.closest('[lang]')?.getAttribute('lang') ?? 'default'
Expand Down Expand Up @@ -336,22 +337,24 @@ export default class RelativeTimeElement extends HTMLElement implements Intl.Dat
// Internal: Refresh the time element's formatted date when an attribute changes.
attributeChangedCallback(attrName: string, oldValue: unknown, newValue: unknown): void {
if (oldValue === newValue) return
if (attrName === 'title') this.#customTitle = true
if (!this.#customTitle) this.update()
if (attrName === 'title') {
this.#customTitle = newValue !== null && this.getFormattedTitle() !== newValue
}
if (!this.#updating && !(attrName === 'title' && this.#customTitle)) {
this.update()
}
}

update() {
this.#updating = true
const oldText: string = this.#renderRoot.textContent || ''
const oldTitle: string = this.getAttribute('title') || ''
let newTitle: string = oldTitle
let newText: string = oldText
const now = new Date()
if (!this.#customTitle) {
newTitle = this.getFormattedTitle() || ''
if (newTitle) {
this.setAttribute('title', newTitle)
this.#customTitle = false
}
if (newTitle) this.setAttribute('title', newTitle)
}

newText = this.getFormattedDate(now) || ''
Expand All @@ -374,5 +377,6 @@ export default class RelativeTimeElement extends HTMLElement implements Intl.Dat
} else {
dateObserver.unobserve(this)
}
this.#updating = false
}
}
13 changes: 13 additions & 0 deletions test/relative-time.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,19 @@ suite('relative-time', function () {
assert.equal(counter, 1)
el.setAttribute('title', 'another custom')
assert.equal(counter, 1)
el.removeAttribute('title')
assert.equal(counter, 2)
})

test('sets title back to default if removed', () => {
const el = document.createElement('relative-time')
el.setAttribute('datetime', new Date().toISOString())
assert.ok(el.getAttribute('title'))
const text = el.getAttribute('title')
el.setAttribute('title', 'custom')
assert.equal(el.getAttribute('title'), 'custom')
el.removeAttribute('title')
assert.equal(el.getAttribute('title'), text)
})

test('shadowDOM reflects textContent with invalid date', () => {
Expand Down

0 comments on commit 7f73eab

Please sign in to comment.