2024-10-30 09:50:19 +00:00
|
|
|
export function toAbsoluteLocaleDate(date, lang, opts) {
|
|
|
|
return new Date(date).toLocaleString(lang || [], opts);
|
2024-03-15 09:13:01 +00:00
|
|
|
}
|
|
|
|
|
2024-03-15 02:05:31 +00:00
|
|
|
window.customElements.define('absolute-date', class extends HTMLElement {
|
2024-03-12 22:37:02 +00:00
|
|
|
static observedAttributes = ['date', 'year', 'month', 'weekday', 'day'];
|
|
|
|
|
2024-10-30 09:50:19 +00:00
|
|
|
initialized = false;
|
|
|
|
|
2024-03-12 22:37:02 +00:00
|
|
|
update = () => {
|
2024-10-30 09:50:19 +00:00
|
|
|
const opt = {};
|
|
|
|
for (const attr of ['year', 'month', 'weekday', 'day']) {
|
|
|
|
if (this.getAttribute(attr)) opt[attr] = this.getAttribute(attr);
|
|
|
|
}
|
2024-03-12 22:37:02 +00:00
|
|
|
const lang = this.closest('[lang]')?.getAttribute('lang') ||
|
2024-03-15 09:13:01 +00:00
|
|
|
this.ownerDocument.documentElement.getAttribute('lang') || '';
|
2024-03-12 22:37:02 +00:00
|
|
|
|
2024-10-30 09:50:19 +00:00
|
|
|
// only use the date part, it is guaranteed to be in ISO format (YYYY-MM-DDTHH:mm:ss.sssZ)
|
|
|
|
let date = this.getAttribute('date');
|
|
|
|
let dateSep = date.indexOf('T');
|
|
|
|
dateSep = dateSep === -1 ? date.indexOf(' ') : dateSep;
|
|
|
|
date = dateSep === -1 ? date : date.substring(0, dateSep);
|
2024-03-12 22:37:02 +00:00
|
|
|
|
|
|
|
if (!this.shadowRoot) this.attachShadow({mode: 'open'});
|
2024-10-30 09:50:19 +00:00
|
|
|
this.shadowRoot.textContent = toAbsoluteLocaleDate(date, lang, opt);
|
2024-03-12 22:37:02 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
attributeChangedCallback(_name, oldValue, newValue) {
|
|
|
|
if (!this.initialized || oldValue === newValue) return;
|
|
|
|
this.update();
|
|
|
|
}
|
|
|
|
|
|
|
|
connectedCallback() {
|
|
|
|
this.initialized = false;
|
|
|
|
this.update();
|
|
|
|
this.initialized = true;
|
|
|
|
}
|
|
|
|
});
|