|
1 | | -import {Temporal} from 'temporal-polyfill'; |
2 | | - |
3 | | -export function toAbsoluteLocaleDate(dateStr, lang, opts) { |
4 | | - return Temporal.PlainDate.from(dateStr).toLocaleString(lang ?? [], opts); |
| 1 | +export function toAbsoluteLocaleDate(date: string, lang: string, opts: Intl.DateTimeFormatOptions) { |
| 2 | + return new Date(date).toLocaleString(lang || [], opts); |
5 | 3 | } |
6 | 4 |
|
7 | 5 | window.customElements.define('absolute-date', class extends HTMLElement { |
8 | 6 | static observedAttributes = ['date', 'year', 'month', 'weekday', 'day']; |
9 | 7 |
|
| 8 | + initialized = false; |
| 9 | + |
10 | 10 | update = () => { |
11 | | - const year = this.getAttribute('year') ?? ''; |
12 | | - const month = this.getAttribute('month') ?? ''; |
13 | | - const weekday = this.getAttribute('weekday') ?? ''; |
14 | | - const day = this.getAttribute('day') ?? ''; |
| 11 | + const opt: Intl.DateTimeFormatOptions = {}; |
| 12 | + for (const attr of ['year', 'month', 'weekday', 'day']) { |
| 13 | + if (this.hasAttribute(attr)) opt[attr] = this.getAttribute(attr); |
| 14 | + } |
15 | 15 | const lang = this.closest('[lang]')?.getAttribute('lang') || |
16 | 16 | this.ownerDocument.documentElement.getAttribute('lang') || ''; |
17 | 17 |
|
18 | | - // only use the first 10 characters, e.g. the `yyyy-mm-dd` part |
19 | | - const dateStr = this.getAttribute('date').substring(0, 10); |
| 18 | + // only use the date part, it is guaranteed to be in ISO format (YYYY-MM-DDTHH:mm:ss.sssZ) |
| 19 | + let date = this.getAttribute('date'); |
| 20 | + let dateSep = date.indexOf('T'); |
| 21 | + dateSep = dateSep === -1 ? date.indexOf(' ') : dateSep; |
| 22 | + date = dateSep === -1 ? date : date.substring(0, dateSep); |
20 | 23 |
|
21 | 24 | if (!this.shadowRoot) this.attachShadow({mode: 'open'}); |
22 | | - this.shadowRoot.textContent = toAbsoluteLocaleDate(dateStr, lang, { |
23 | | - ...(year && {year}), |
24 | | - ...(month && {month}), |
25 | | - ...(weekday && {weekday}), |
26 | | - ...(day && {day}), |
27 | | - }); |
| 25 | + this.shadowRoot.textContent = toAbsoluteLocaleDate(date, lang, opt); |
28 | 26 | }; |
29 | 27 |
|
30 | 28 | attributeChangedCallback(_name, oldValue, newValue) { |
|
0 commit comments