]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/root-helpers/peertube-web-storage.ts
Fix table pagination responsive
[github/Chocobozzz/PeerTube.git] / client / src / root-helpers / peertube-web-storage.ts
1 // Thanks: https://github.com/capaj/localstorage-polyfill
2
3 const valuesMap = new Map()
4
5 function proxify (instance: MemoryStorage) {
6 return new Proxy(instance, {
7 set: function (obj, prop: string | symbol, value) {
8 if (Object.prototype.hasOwnProperty.call(MemoryStorage, prop)) {
9 // FIXME: remove cast on typescript upgrade
10 instance[prop as any] = value
11 } else {
12 instance.setItem(prop, value)
13 }
14
15 return true
16 },
17 get: function (target, name: string | symbol | number) {
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]
22 } else if (valuesMap.has(name)) {
23 return instance.getItem(name)
24 }
25 }
26 })
27 }
28
29 class MemoryStorage implements Storage {
30 [key: string]: any
31
32 getItem (key: any) {
33 const stringKey = String(key)
34 if (valuesMap.has(key)) {
35 return String(valuesMap.get(stringKey))
36 }
37
38 return null
39 }
40
41 setItem (key: any, val: any) {
42 valuesMap.set(String(key), String(val))
43 }
44
45 removeItem (key: any) {
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
67 let peertubeLocalStorage: Storage
68 let peertubeSessionStorage: Storage
69
70 function reinitStorage () {
71 const instanceLocalStorage = new MemoryStorage()
72 const instanceSessionStorage = new MemoryStorage()
73
74 peertubeLocalStorage = proxify(instanceLocalStorage)
75 peertubeSessionStorage = proxify(instanceSessionStorage)
76 }
77
78 try {
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
87 if (!peertubeLocalStorage || !peertubeSessionStorage) {
88 reinitStorage()
89 }
90
91 export {
92 peertubeLocalStorage,
93 peertubeSessionStorage
94 }