Skip to content

Commit

Permalink
avoid throwing errors for empty lang attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
keithamus committed Dec 16, 2022
1 parent fdba0e7 commit 371f127
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/relative-time-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,11 @@ export default class RelativeTimeElement extends HTMLElement implements Intl.Dat
#updating: false | Promise<void> = false

get #lang() {
return this.closest('[lang]')?.getAttribute('lang') ?? 'default'
return (
this.closest('[lang]')?.getAttribute('lang') ||
this.ownerDocument.documentElement.getAttribute('lang') ||
'default'
)
}

#renderRoot: Node = this.shadowRoot ? this.shadowRoot : this.attachShadow ? this.attachShadow({mode: 'open'}) : this
Expand Down
19 changes: 19 additions & 0 deletions test/relative-time.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ suite('relative-time', function () {
suiteSetup(() => {
fixture = document.createElement('div')
document.body.appendChild(fixture)
document.documentElement.lang = 'en'
})

teardown(() => {
Expand Down Expand Up @@ -249,6 +250,24 @@ suite('relative-time', function () {
assert.equal(time.shadowRoot.textContent, 'in 2 days')
})

test('uses html lang if given lang is invalid', async () => {
const time = document.createElement('relative-time')
time.setAttribute('datetime', new Date())
time.setAttribute('lang', '')
document.documentElement.lang = 'es'
await Promise.resolve()
assert.equal(time.shadowRoot.textContent, 'ahora')
})

test('ignores empty lang attributes', async () => {
const time = document.createElement('relative-time')
time.setAttribute('datetime', new Date())
time.setAttribute('lang', '')
document.documentElement.lang = ''
await Promise.resolve()
assert.equal(time.shadowRoot.textContent, 'now')
})

suite('[threshold]', function () {
test('switches to dates after 30 past days with default threshold', async () => {
const now = new Date(Date.now() - 31 * 60 * 60 * 24 * 1000).toISOString()
Expand Down

0 comments on commit 371f127

Please sign in to comment.