-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpin-manager.js
98 lines (82 loc) · 2.17 KB
/
pin-manager.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* global HTMLElement, customElements, localStorage */
const PINNING_SERVICES = 'pinning_services'
export class PinManager extends HTMLElement {
constructor () {
super()
this.isInitialized = false
}
initialize () {
if (this.isInitialized) return
this.isInitialized = true
this.innerHTML = `
<button class="pin-manager-add-button">Add Service➕</button>
`
this.addButton.addEventListener('click', () => {
this.append(document.createElement('pin-list'))
})
window.addEventListener('beforeunload', () => this.save(this.existing))
}
connectedCallback () {
this.initialize()
this.load()
}
get addButton () {
return this.querySelector('.pin-manager-add-button')
}
load () {
const saved = this.saved
const fromInvite = this.fromInvite
const all = [...saved, ...fromInvite]
const hasSeen = new Set()
this.append(...all.map(({ service, protocol, auth }) => {
const seenKey = service + auth
if (hasSeen.has(seenKey)) return ''
hasSeen.add(seenKey)
const list = document.createElement('pin-list')
list.service = service
list.protocol = protocol
list.auth = auth
return list
}))
}
save (list) {
localStorage.setItem(PINNING_SERVICES, JSON.stringify(list))
}
get lists () {
return this.querySelectorAll('pin-list')
}
get saved () {
const raw = localStorage.getItem(PINNING_SERVICES)
if (raw) {
try {
return JSON.parse(raw)
} catch (e) {
console.log('Error parsing saved services', e)
return []
}
} else {
return []
}
}
get fromInvite () {
const { searchParams } = new URL(window.location.href)
if (searchParams.has('invite')) {
try {
const parsed = JSON.parse(searchParams.get('invite'))
if (!Array.isArray(parsed)) return []
return parsed
} catch {
return []
}
} else return []
}
get existing () {
const services = []
for (const list of this.lists) {
if (!list.isValid()) continue
services.push(list.toJSON())
}
return services
}
}
customElements.define('pin-manager', PinManager)