-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
33 lines (27 loc) · 1.02 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const durationRegex = /^P[A-Z0-9\.]+$/
export class TimeDuration extends HTMLElement {
static register(tagName = 'time-duration') {
customElements.define(tagName, TimeDuration)
}
async connectedCallback() {
const el = this.firstElementChild
const options = this.dataset
const value = (el.dateTime || el.textContent)?.trim()
const lang = el.closest('[lang]')?.lang
const duration = durationRegex.test(value)
? this.#getDurationFromDurationString(value)
: this.#getDurationFromDateTimeString(value, options)
el.textContent = duration.toLocaleString(lang, options)
el.dateTime = duration.toString()
}
#getDurationFromDurationString(duration) {
return Temporal.Duration.from(duration)
}
#getDurationFromDateTimeString(dateTime, options) {
const [from, to] = [
Temporal.PlainDateTime.from(dateTime),
Temporal.PlainDateTime.from(options.refDatetime || Temporal.Now.plainDateTimeISO()),
].sort(Temporal.PlainDateTime.compare)
return from.until(to, options)
}
}