Browse Source

Add context async storage logic

This isn't implemented yet, but the necessary files are here
Arnaud Vergnet 2 years ago
parent
commit
1d2ec83619

+ 4
- 4
package-lock.json View File

@@ -1998,10 +1998,10 @@
1998 1998
         "fastq": "^1.6.0"
1999 1999
       }
2000 2000
     },
2001
-    "@react-native-community/async-storage": {
2002
-      "version": "1.12.1",
2003
-      "resolved": "https://registry.npmjs.org/@react-native-community/async-storage/-/async-storage-1.12.1.tgz",
2004
-      "integrity": "sha512-70WGaH3PKYASi4BThuEEKMkyAgE9k7VytBqmgPRx3MzJx9/MkspwqJGmn3QLCgHLIFUgF1pit2mWICbRJ3T3lg==",
2001
+    "@react-native-async-storage/async-storage": {
2002
+      "version": "1.15.4",
2003
+      "resolved": "https://registry.npmjs.org/@react-native-async-storage/async-storage/-/async-storage-1.15.4.tgz",
2004
+      "integrity": "sha512-pC0MS6UBuv/YiVAxtzi7CgUed8oCQNYMtGt0yb/I9fI/BWTiJK5cj4YtW2XtL95K5IuvPX/6uGWaouZ8KqXwdg==",
2005 2005
       "requires": {
2006 2006
         "deep-assign": "^3.0.0"
2007 2007
       }

+ 1
- 1
package.json View File

@@ -20,7 +20,7 @@
20 20
   },
21 21
   "dependencies": {
22 22
     "@nartc/react-native-barcode-mask": "1.2.0",
23
-    "@react-native-community/async-storage": "1.12.1",
23
+    "@react-native-async-storage/async-storage": "^1.15.4",
24 24
     "@react-native-community/masked-view": "0.1.11",
25 25
     "@react-native-community/push-notification-ios": "1.8.0",
26 26
     "@react-native-community/slider": "3.0.3",

+ 67
- 0
src/components/providers/PreferencesProvider.tsx View File

@@ -0,0 +1,67 @@
1
+import React, { useState } from 'react';
2
+import {
3
+  defaultPreferences,
4
+  PreferenceKeys,
5
+  PreferencesType,
6
+  setPreference,
7
+} from '../../utils/asyncStorage';
8
+import {
9
+  PreferencesContext,
10
+  PreferencesContextType,
11
+} from '../../utils/preferencesContext';
12
+
13
+type Props = {
14
+  children: React.ReactChild;
15
+  initialPreferences: PreferencesType;
16
+};
17
+
18
+export default function PreferencesProvider(props: Props) {
19
+  const updatePreferences = (
20
+    key: PreferenceKeys,
21
+    value: number | string | boolean | object | Array<any>
22
+  ) => {
23
+    setPreferencesState((prevState) => {
24
+      const prevPreferences = { ...prevState.preferences };
25
+      const newPrefs = setPreference(key, value, prevPreferences);
26
+      const newSate = {
27
+        ...prevState,
28
+        preferences: { ...newPrefs },
29
+      };
30
+      return newSate;
31
+    });
32
+  };
33
+
34
+  const resetPreferences = () => {
35
+    setPreferencesState((prevState) => {
36
+      const prevPreferences = { ...prevState.preferences };
37
+      let newPreferences = { ...prevPreferences };
38
+      Object.values(PreferenceKeys).forEach((key) => {
39
+        newPreferences = setPreference(
40
+          key,
41
+          defaultPreferences[key],
42
+          prevPreferences
43
+        );
44
+      });
45
+      const newSate = {
46
+        ...prevState,
47
+        preferences: { ...newPreferences },
48
+      };
49
+      return newSate;
50
+    });
51
+  };
52
+
53
+  const [
54
+    preferencesState,
55
+    setPreferencesState,
56
+  ] = useState<PreferencesContextType>({
57
+    preferences: { ...props.initialPreferences },
58
+    updatePreferences: updatePreferences,
59
+    resetPreferences: resetPreferences,
60
+  });
61
+
62
+  return (
63
+    <PreferencesContext.Provider value={preferencesState}>
64
+      {props.children}
65
+    </PreferencesContext.Provider>
66
+  );
67
+}

+ 1
- 1
src/managers/AsyncStorageManager.ts View File

@@ -17,7 +17,7 @@
17 17
  * along with Campus INSAT.  If not, see <https://www.gnu.org/licenses/>.
18 18
  */
19 19
 
20
-import AsyncStorage from '@react-native-community/async-storage';
20
+import AsyncStorage from '@react-native-async-storage/async-storage';
21 21
 import { SERVICES_KEY } from './ServicesManager';
22 22
 
23 23
 /**

+ 170
- 0
src/utils/asyncStorage.ts View File

@@ -0,0 +1,170 @@
1
+import AsyncStorage from '@react-native-async-storage/async-storage';
2
+import { SERVICES_KEY } from '../managers/ServicesManager';
3
+
4
+export enum PreferenceKeys {
5
+  debugUnlocked = 'debugUnlocked',
6
+  showIntro = 'showIntro',
7
+  updateNumber = 'updateNumber',
8
+  proxiwashNotifications = 'proxiwashNotifications',
9
+  nightModeFollowSystem = 'nightModeFollowSystem',
10
+  nightMode = 'nightMode',
11
+  defaultStartScreen = 'defaultStartScreen',
12
+  servicesShowMascot = 'servicesShowMascot',
13
+  proxiwashShowMascot = 'proxiwashShowMascot',
14
+  homeShowMascot = 'homeShowMascot',
15
+  eventsShowMascot = 'eventsShowMascot',
16
+  planexShowMascot = 'planexShowMascot',
17
+  loginShowMascot = 'loginShowMascot',
18
+  voteShowMascot = 'voteShowMascot',
19
+  equipmentShowMascot = 'equipmentShowMascot',
20
+  gameStartMascot = 'gameStartMascot',
21
+  proxiwashWatchedMachines = 'proxiwashWatchedMachines',
22
+  showAprilFoolsStart = 'showAprilFoolsStart',
23
+  planexCurrentGroup = 'planexCurrentGroup',
24
+  planexFavoriteGroups = 'planexFavoriteGroups',
25
+  dashboardItems = 'dashboardItems',
26
+  gameScores = 'gameScores',
27
+  selectedWash = 'selectedWash',
28
+}
29
+
30
+export type PreferencesType = { [key in PreferenceKeys]: string };
31
+
32
+export const defaultPreferences: { [key in PreferenceKeys]: string } = {
33
+  [PreferenceKeys.debugUnlocked]: '0',
34
+  [PreferenceKeys.showIntro]: '1',
35
+  [PreferenceKeys.updateNumber]: '0',
36
+  [PreferenceKeys.proxiwashNotifications]: '5',
37
+  [PreferenceKeys.nightModeFollowSystem]: '1',
38
+  [PreferenceKeys.nightMode]: '1',
39
+  [PreferenceKeys.defaultStartScreen]: 'home',
40
+  [PreferenceKeys.servicesShowMascot]: '1',
41
+  [PreferenceKeys.proxiwashShowMascot]: '1',
42
+  [PreferenceKeys.homeShowMascot]: '1',
43
+  [PreferenceKeys.eventsShowMascot]: '1',
44
+  [PreferenceKeys.planexShowMascot]: '1',
45
+  [PreferenceKeys.loginShowMascot]: '1',
46
+  [PreferenceKeys.voteShowMascot]: '1',
47
+  [PreferenceKeys.equipmentShowMascot]: '1',
48
+  [PreferenceKeys.gameStartMascot]: '1',
49
+  [PreferenceKeys.proxiwashWatchedMachines]: '[]',
50
+  [PreferenceKeys.showAprilFoolsStart]: '1',
51
+  [PreferenceKeys.planexCurrentGroup]: '',
52
+  [PreferenceKeys.planexFavoriteGroups]: '[]',
53
+  [PreferenceKeys.dashboardItems]: JSON.stringify([
54
+    SERVICES_KEY.EMAIL,
55
+    SERVICES_KEY.WASHERS,
56
+    SERVICES_KEY.PROXIMO,
57
+    SERVICES_KEY.TUTOR_INSA,
58
+    SERVICES_KEY.RU,
59
+  ]),
60
+  [PreferenceKeys.gameScores]: '[]',
61
+  [PreferenceKeys.selectedWash]: 'washinsa',
62
+};
63
+
64
+/**
65
+ * Set preferences object current values from AsyncStorage.
66
+ * This function should be called once on start.
67
+ *
68
+ * @return {Promise<PreferencesType>}
69
+ */
70
+export function retrievePreferences(
71
+  keys: Array<PreferenceKeys>,
72
+  defaults: PreferencesType
73
+): Promise<PreferencesType> {
74
+  return new Promise((resolve: (preferences: PreferencesType) => void) => {
75
+    AsyncStorage.multiGet(Object.values(keys))
76
+      .then((result) => {
77
+        const preferences = { ...defaults };
78
+        result.forEach((item) => {
79
+          let [key, value] = item;
80
+          if (value !== null) {
81
+            preferences[key as PreferenceKeys] = value;
82
+          }
83
+        });
84
+        resolve(preferences);
85
+      })
86
+      .catch(() => resolve(defaults));
87
+  });
88
+}
89
+
90
+/**
91
+ * Saves the value associated to the given key to preferences.
92
+ * This updates the preferences object and saves it to AsyncStorage.
93
+ *
94
+ * @param key
95
+ * @param value
96
+ */
97
+export function setPreference(
98
+  key: PreferenceKeys,
99
+  value: number | string | boolean | object | Array<any>,
100
+  prevPreferences: PreferencesType
101
+): PreferencesType {
102
+  let convertedValue: string;
103
+  if (typeof value === 'string') {
104
+    convertedValue = value;
105
+  } else if (typeof value === 'boolean' || typeof value === 'number') {
106
+    convertedValue = value.toString();
107
+  } else {
108
+    convertedValue = JSON.stringify(value);
109
+  }
110
+  prevPreferences[key] = convertedValue;
111
+  AsyncStorage.setItem(key, convertedValue)
112
+    .then(undefined)
113
+    .catch(() => console.debug('save error: ' + convertedValue));
114
+  return prevPreferences;
115
+}
116
+
117
+/**
118
+ * Gets the boolean value of the given preference
119
+ *
120
+ * @param key
121
+ * @returns {boolean}
122
+ */
123
+export function getPreferenceString(
124
+  key: PreferenceKeys,
125
+  preferences: PreferencesType
126
+): string | undefined {
127
+  return preferences[key];
128
+}
129
+
130
+/**
131
+ * Gets the boolean value of the given preference
132
+ *
133
+ * @param key
134
+ * @returns {boolean}
135
+ */
136
+export function getPreferenceBool(
137
+  key: PreferenceKeys,
138
+  preferences: PreferencesType
139
+): boolean | undefined {
140
+  const value = preferences[key];
141
+  return value ? value === '1' || value === 'true' : undefined;
142
+}
143
+
144
+/**
145
+ * Gets the number value of the given preference
146
+ *
147
+ * @param key
148
+ * @returns {number}
149
+ */
150
+export function getPreferenceNumber(
151
+  key: PreferenceKeys,
152
+  preferences: PreferencesType
153
+): number | undefined {
154
+  const value = preferences[key];
155
+  return value !== undefined ? parseFloat(value) : undefined;
156
+}
157
+
158
+/**
159
+ * Gets the object value of the given preference
160
+ *
161
+ * @param key
162
+ * @returns {{...}}
163
+ */
164
+export function getPreferenceObject(
165
+  key: PreferenceKeys,
166
+  preferences: PreferencesType
167
+): object | Array<any> | undefined {
168
+  const value = preferences[key];
169
+  return value ? JSON.parse(value) : undefined;
170
+}

+ 25
- 0
src/utils/preferencesContext.ts View File

@@ -0,0 +1,25 @@
1
+import React, { useContext } from 'react';
2
+import {
3
+  defaultPreferences,
4
+  PreferenceKeys,
5
+  PreferencesType,
6
+} from './asyncStorage';
7
+
8
+export type PreferencesContextType = {
9
+  preferences: PreferencesType;
10
+  updatePreferences: (
11
+    key: PreferenceKeys,
12
+    value: number | string | boolean | object | Array<any>
13
+  ) => void;
14
+  resetPreferences: () => void;
15
+};
16
+
17
+export const PreferencesContext = React.createContext<PreferencesContextType>({
18
+  preferences: defaultPreferences,
19
+  updatePreferences: () => undefined,
20
+  resetPreferences: () => undefined,
21
+});
22
+
23
+export function usePreferences() {
24
+  return useContext(PreferencesContext);
25
+}

Loading…
Cancel
Save