-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelement.js
46 lines (39 loc) · 1.27 KB
/
element.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
34
35
36
37
38
39
40
41
42
43
44
45
46
import timeago from 'timeago.js'
export default class TimeagoElement extends HTMLElement {
attributeChangedCallback(name, oldValue, newValue) {
if (this.rendered) { this.updateRendering() }
}
connectedCallback() {
if (this.querySelector('time')) {
this.init()
} else {
window.requestAnimationFrame(() => {
this.init()
})
}
}
init() {
this.timeElement = this.querySelector('time')
this.timeElement.style.display = 'none'
this.timeagoInstance = new timeago()
this.span = document.createElement('span')
this.appendChild(this.span)
if (MutationObserver) {
this.observer = new MutationObserver((mutations) => {
this.updateRendering()
})
const observerConfig = { attributes: true, childList: true, characterData: true, subtree: true }
this.observer.observe(this.timeElement, observerConfig)
}
this.updateRendering()
}
updateRendering() {
this.timeagoInstance.cancel()
this.span.setAttribute('datetime', trim(this.timeElement.textContent))
const language = window.navigator.userLanguage || window.navigator.language
this.timeagoInstance.render(this.span, language)
}
}
function trim (string) {
return string.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '')
}