]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/root-helpers/peertube-web-storage.ts
Merge remote-tracking branch 'weblate/develop' into develop
[github/Chocobozzz/PeerTube.git] / client / src / root-helpers / peertube-web-storage.ts
CommitLineData
0bd78bf3
C
1// Thanks: https://github.com/capaj/localstorage-polyfill
2
3const valuesMap = new Map()
4
fd8f73cf
C
5function proxify (instance: MemoryStorage) {
6 return new Proxy(instance, {
0f01a8ba 7 set: function (obj, prop: string | symbol, value) {
9df52d66 8 if (Object.prototype.hasOwnProperty.call(MemoryStorage, prop)) {
52d1477a
C
9 // FIXME: remove cast on typescript upgrade
10 instance[prop as any] = value
fd8f73cf
C
11 } else {
12 instance.setItem(prop, value)
13 }
db9df9a7 14
fd8f73cf
C
15 return true
16 },
0f01a8ba 17 get: function (target, name: string | symbol | number) {
52d1477a
C
18 // FIXME: remove cast on typescript upgrade
19 if (typeof instance[name as any] === 'function') {
20 // FIXME: remove cast on typescript upgrade
21 return instance[name as any]
db9df9a7 22 } else if (valuesMap.has(name)) {
fd8f73cf
C
23 return instance.getItem(name)
24 }
25 }
26 })
27}
28
0f01a8ba 29class MemoryStorage implements Storage {
52d1477a 30 [key: string]: any
0bd78bf3 31
244b4ae3 32 getItem (key: any) {
0bd78bf3
C
33 const stringKey = String(key)
34 if (valuesMap.has(key)) {
35 return String(valuesMap.get(stringKey))
36 }
37
38 return null
39 }
40
244b4ae3 41 setItem (key: any, val: any) {
0bd78bf3
C
42 valuesMap.set(String(key), String(val))
43 }
44
244b4ae3 45 removeItem (key: any) {
0bd78bf3
C
46 valuesMap.delete(key)
47 }
48
49 clear () {
50 valuesMap.clear()
51 }
52
53 key (i: any) {
54 if (arguments.length === 0) {
55 throw new TypeError('Failed to execute "key" on "Storage": 1 argument required, but only 0 present.')
56 }
57
58 const arr = Array.from(valuesMap.keys())
59 return arr[i]
60 }
61
62 get length () {
63 return valuesMap.size
64 }
65}
66
67let peertubeLocalStorage: Storage
88a7f93f 68let peertubeSessionStorage: Storage
61379e43
RK
69
70function reinitStorage () {
6189b699
C
71 const instanceLocalStorage = new MemoryStorage()
72 const instanceSessionStorage = new MemoryStorage()
0bd78bf3 73
6189b699
C
74 peertubeLocalStorage = proxify(instanceLocalStorage)
75 peertubeSessionStorage = proxify(instanceSessionStorage)
0bd78bf3
C
76}
77
61379e43
RK
78try {
79 peertubeLocalStorage = localStorage
80 peertubeSessionStorage = sessionStorage
81} catch (err) {
82 // support Firefox and other browsers using an exception rather than null
83 reinitStorage()
84}
85
86// support Brave and other browsers using null rather than an exception
db9df9a7 87if (!peertubeLocalStorage || !peertubeSessionStorage) {
61379e43
RK
88 reinitStorage()
89}
90
88a7f93f
RK
91export {
92 peertubeLocalStorage,
93 peertubeSessionStorage
94}