-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
83 lines (74 loc) · 2.45 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/* global customElements, sessionStorage */
import FuturismElement from './futurism_element'
import FuturismTableRow from './futurism_table_row'
import FuturismLI from './futurism_li'
import { sha256 } from '../utils/crypto'
const polyfillCustomElements = () => {
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent)
if (customElements) {
if (isSafari) {
document.write(
'<script src="//unpkg.com/@ungap/custom-elements-builtin"><\x2fscript>'
)
} else {
try {
customElements.define(
'built-in',
document.createElement('tr').constructor,
{ extends: 'tr' }
)
} catch (_) {
document.write(
'<script src="//unpkg.com/@ungap/custom-elements-builtin"><\x2fscript>'
)
}
}
} else {
document.write(
'<script src="//unpkg.com/document-register-element"><\x2fscript>'
)
}
}
const defineElements = e => {
if (!customElements.get('futurism-element')) {
customElements.define('futurism-element', FuturismElement)
customElements.define('futurism-table-row', FuturismTableRow, {
extends: 'tr'
})
customElements.define('futurism-li', FuturismLI, { extends: 'li' })
}
}
const cachePlaceholders = e => {
sha256(e.detail.element.outerHTML).then(hashedContent => {
e.detail.element.setAttribute('keep', '')
sessionStorage.setItem(
`futurism-${hashedContent}`,
e.detail.element.outerHTML
)
e.target.dataset.futurismHash = hashedContent
})
}
const restorePlaceholders = e => {
const inNamespace = ([key, _payload]) => key.startsWith('futurism-')
Object.entries(sessionStorage)
.filter(inNamespace)
.forEach(([key, payload]) => {
const match = /^futurism-(.*)/.exec(key)
const targetElement = document.querySelector(
`[data-futurism-hash="${match[1]}"]`
)
if (targetElement) {
targetElement.outerHTML = payload
sessionStorage.removeItem(key)
}
})
}
export const initializeElements = () => {
polyfillCustomElements()
document.addEventListener('DOMContentLoaded', defineElements)
document.addEventListener('turbo:load', defineElements)
document.addEventListener('turbo:before-cache', restorePlaceholders)
document.addEventListener('turbolinks:load', defineElements)
document.addEventListener('turbolinks:before-cache', restorePlaceholders)
document.addEventListener('cable-ready:after-outer-html', cachePlaceholders)
}