Skip to content

Commit

Permalink
Merge pull request #297 from github/francinelucca/fix/locale-error
Browse files Browse the repository at this point in the history
fix: wrap Intl.<>() calls in try/catch
  • Loading branch information
francinelucca authored Dec 10, 2024
2 parents bc1b8b7 + b6dbae3 commit a80c1bf
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/relative-time-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,12 @@ export class RelativeTimeElement extends HTMLElement implements Intl.DateTimeFor
#updating: false | Promise<void> = false

get #lang() {
return (
this.closest('[lang]')?.getAttribute('lang') ||
this.ownerDocument.documentElement.getAttribute('lang') ||
'default'
)
const lang = this.closest('[lang]')?.getAttribute('lang') || this.ownerDocument.documentElement.getAttribute('lang')
try {
return new Intl.Locale(lang ?? '').toString()
} catch {
return 'default'
}
}

#renderRoot: Node = this.shadowRoot ? this.shadowRoot : this.attachShadow ? this.attachShadow({mode: 'open'}) : this
Expand Down
11 changes: 11 additions & 0 deletions test/relative-time.js
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,17 @@ suite('relative-time', function () {
})
}

test('renders correctly when given an invalid lang', async () => {
const now = new Date().toISOString()

const element = document.createElement('relative-time')
element.setAttribute('datetime', now)
element.setAttribute('lang', 'does-not-exist')

await Promise.resolve()
assert.equal(element.shadowRoot.textContent, 'now')
})

suite('[tense=past]', function () {
test('always uses relative dates', async () => {
freezeTime(new Date(2033, 1, 1))
Expand Down

0 comments on commit a80c1bf

Please sign in to comment.