You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GiteaAbsoluteDate.js 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. window.customElements.define('gitea-absolute-date', class extends HTMLElement {
  2. static observedAttributes = ['date', 'year', 'month', 'weekday', 'day'];
  3. update = () => {
  4. const year = this.getAttribute('year') ?? '';
  5. const month = this.getAttribute('month') ?? '';
  6. const weekday = this.getAttribute('weekday') ?? '';
  7. const day = this.getAttribute('day') ?? '';
  8. const lang = this.closest('[lang]')?.getAttribute('lang') ||
  9. this.ownerDocument.documentElement.getAttribute('lang') ||
  10. '';
  11. // only extract the `yyyy-mm-dd` part. When converting to Date, it will become midnight UTC and when rendered
  12. // as localized date, will have a offset towards UTC, which we remove to shift the timestamp to midnight in the
  13. // localized date. We should eventually use `Temporal.PlainDate` which will make the correction unnecessary.
  14. // - https://stackoverflow.com/a/14569783/808699
  15. // - https://tc39.es/proposal-temporal/docs/plaindate.html
  16. const date = new Date(this.getAttribute('date').substring(0, 10));
  17. const correctedDate = new Date(date.getTime() - date.getTimezoneOffset() * -60000);
  18. if (!this.shadowRoot) this.attachShadow({mode: 'open'});
  19. this.shadowRoot.textContent = correctedDate.toLocaleString(lang ?? [], {
  20. ...(year && {year}),
  21. ...(month && {month}),
  22. ...(weekday && {weekday}),
  23. ...(day && {day}),
  24. });
  25. };
  26. attributeChangedCallback(_name, oldValue, newValue) {
  27. if (!this.initialized || oldValue === newValue) return;
  28. this.update();
  29. }
  30. connectedCallback() {
  31. this.initialized = false;
  32. this.update();
  33. this.initialized = true;
  34. }
  35. });