Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(preferences): allow to perform partial key update via update callback #376

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions src/core/contexts/PreferencesContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ export type CoursesPreferences = {
[courseId: number | string]: CoursePreferencesProps;
};

export interface PreferencesContextBase {
lastInstalledVersion: string | null;
export interface EditablePreferences {
lastInstalledVersion?: string;
username: string;
campusId?: string;
colorScheme: 'light' | 'dark' | 'system';
Expand All @@ -65,10 +65,27 @@ export interface PreferencesContextBase {
hideGrades?: boolean;
}

export interface PreferencesContextProps extends PreferencesContextBase {
updatePreference: <T extends PreferenceKey>(
key: T,
value: PreferencesContextBase[T],
/**
* A callback that receives the previous value of the preference and returns the next one
*/
type UpdatePreferenceCallback<
K extends PreferenceKey,
V extends EditablePreferences[K],
> = (prev: V | undefined) => V | undefined;

/**
* The value of a preference can be:
* - a value of the type of the preference
* - a callback that receives the previous value of the preference and returns the next one
*/
export type UpdatePreferenceValue<K extends PreferenceKey> =
| EditablePreferences[K]
| UpdatePreferenceCallback<K, EditablePreferences[K]>;

export interface PreferencesContextProps extends EditablePreferences {
updatePreference: <K extends PreferenceKey>(
key: K,
value: UpdatePreferenceValue<K>,
) => void;
}

Expand Down
56 changes: 38 additions & 18 deletions src/core/providers/PreferencesProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import { PropsWithChildren, useEffect, useRef, useState } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';

import {
EditablePreferences,
PreferenceKey,
PreferencesContext,
PreferencesContextProps,
UpdatePreferenceValue,
editablePreferenceKeys,
objectPreferenceKeys,
} from '../contexts/PreferencesContext';
Expand All @@ -15,7 +17,7 @@ export const PreferencesProvider = ({ children }: PropsWithChildren) => {
const deviceLanguage = useDeviceLanguage();
const [preferencesContext, setPreferencesContext] =
useState<PreferencesContextProps>({
lastInstalledVersion: null,
lastInstalledVersion: undefined,
username: '',
colorScheme: 'system',
courses: {},
Expand All @@ -37,35 +39,52 @@ export const PreferencesProvider = ({ children }: PropsWithChildren) => {

const preferencesInitialized = useRef<boolean>(false);

const updatePreference = (key: PreferenceKey, value: unknown) => {
const stringKey = key.toString();
if (value === null) {
AsyncStorage.removeItem(stringKey).then(() =>
setPreferencesContext(oldP => ({
...oldP,
[stringKey]: value,
})),
);
} else {
// Initialize preferences from AsyncStorage
useEffect(() => {
const updatePreference = <K extends PreferenceKey>(
key: K,
value: UpdatePreferenceValue<K>,
) => {
const stringKey = key.toString();

// if value is undefined, remove the preference
if (value === undefined) {
AsyncStorage.removeItem(stringKey).then(() =>
setPreferencesContext(oldP => ({
...oldP,
[stringKey]: value,
})),
);

return;
}

let storageValue: string;
let nextValue: EditablePreferences[PreferenceKey];

// if value is a callback, call it with the current value
if (typeof value === 'function') {
const currentValue = preferencesContext[key];
nextValue = value(currentValue);
} else {
nextValue = value;
}

// if value is an object, stringify it
if (objectPreferenceKeys.includes(key)) {
storageValue = JSON.stringify(value);
storageValue = JSON.stringify(nextValue);
} else {
storageValue = value as string;
storageValue = nextValue as string;
}

AsyncStorage.setItem(stringKey, storageValue).then(() =>
setPreferencesContext(oldP => ({
...oldP,
[stringKey]: value,
[stringKey]: nextValue,
})),
);
}
};
};

// Initialize preferences from AsyncStorage
useEffect(() => {
AsyncStorage.multiGet(editablePreferenceKeys).then(storagePreferences => {
const preferences: Partial<PreferencesContextProps> = {
updatePreference,
Expand All @@ -89,6 +108,7 @@ export const PreferencesProvider = ({ children }: PropsWithChildren) => {
return { ...oldP, ...preferences };
});
});
// eslint-disable-next-line react-hooks/exhaustive-deps -- only on mount
}, []);

// Preferences are loaded
Expand Down
4 changes: 2 additions & 2 deletions src/features/courses/screens/CourseIconPickerScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { NativeStackScreenProps } from '@react-navigation/native-stack';

import { BottomBarSpacer } from '../../../core/components/BottomBarSpacer';
import {
PreferencesContextBase,
EditablePreferences,
usePreferencesContext,
} from '../../../core/contexts/PreferencesContext';
import { useSafeAreaSpacing } from '../../../core/hooks/useSafeAreaSpacing';
Expand Down Expand Up @@ -96,7 +96,7 @@ export const CourseIconPickerScreen = ({ navigation, route }: Props) => {
...coursePrefs,
icon: null,
},
} as PreferencesContextBase['courses']);
} as EditablePreferences['courses']);
navigation.goBack();
}}
/>
Expand Down
6 changes: 3 additions & 3 deletions src/features/user/screens/SettingsScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import { version } from '../../../../package.json';
import { BottomBarSpacer } from '../../../core/components/BottomBarSpacer';
import { useFeedbackContext } from '../../../core/contexts/FeedbackContext';
import {
PreferencesContextBase,
EditablePreferences,
usePreferencesContext,
} from '../../../core/contexts/PreferencesContext';
import { useConfirmationDialog } from '../../../core/hooks/useConfirmationDialog';
Expand Down Expand Up @@ -178,7 +178,7 @@ const VisualizationListItem = () => {
onPressAction={({ nativeEvent: { event } }) => {
updatePreference(
'colorScheme',
event as PreferencesContextBase['colorScheme'],
event as EditablePreferences['colorScheme'],
);
}}
>
Expand Down Expand Up @@ -249,7 +249,7 @@ const Notifications = () => {
updatePreference('notifications', {
...notifications,
[notificationType]: value,
} as PreferencesContextBase['notifications']);
} as EditablePreferences['notifications']);
};

return (
Expand Down
Loading