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