8000 avoid throwing errors for empty lang attributes · github/relative-time-element@371f127 · GitHub
[go: up one dir, main page]

Skip to content

Commit 371f127

Browse files
committed
avoid throwing errors for empty lang attributes
1 parent fdba0e7 commit 371f127

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/relative-time-element.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,11 @@ export default class RelativeTimeElement extends HTMLElement implements Intl.Dat
7878
#updating: false | Promise<void> = false
7979

8080
get #lang() {
81-
return this.closest('[lang]')?.getAttribute('lang') ?? 'default'
81+
return (
82+
this.closest('[lang]')?.getAttribute('lang') ||
83+
this.ownerDocument.documentElement.getAttribute('lang') ||
84+ 'default'
85+
)
8286
}
8387

8488
#renderRoot: Node = this.shadowRoot ? this.shadowRoot : this.attachShadow ? this.attachShadow({mode: 'open'}) : this

test/relative-time.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ suite('relative-time', function () {
2727
suiteSetup(() => {
2828
fixture = document.createElement('div')
2929
document.body.appendChild(fixture)
30+
document.documentElement.lang = 'en'
3031
})
3132

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

253+
test('uses html lang if given lang is invalid', async () => {
254+
const time = document.createElement('relative-time')
255+
time.setAttribute('datetime', new Date())
256+
time.setAttribute('lang', '')
257+
document.documentElement.lang = 'es'
258+
await Promise.resolve()
259+
assert.equal(time.shadowRoot.textContent, 'ahora')
260+
})
261+
262+
test('ignores empty lang attributes', async () => {
263+
const time = document.createElement('relative-time')
264+
time.setAttribute('datetime', new Date())
265+
time.setAttribute('lang', '')
266+
document.documentElement.lang = ''
267+
await Promise.resolve()
268+
assert.equal(time.shadowRoot.textContent, 'now')
269+
})
270+
252271
suite('[threshold]', function () {
253272
test('switches to dates after 30 past days with default threshold', async () => {
254273
const now = new Date(Date.now() - 31 * 60 * 60 * 24 * 1000).toISOString()

0 commit comments

Comments
 (0)
0