1 | 'use client';
|
---|
2 |
|
---|
3 | import isEqual from 'lodash/isEqual';
|
---|
4 | import { useEffect, useMemo, useCallback, useState } from 'react';
|
---|
5 | // hooks
|
---|
6 | import { useLocalStorage } from 'src/hooks/use-local-storage';
|
---|
7 | // utils
|
---|
8 | import { localStorageGetItem } from 'src/utils/storage-available';
|
---|
9 | //
|
---|
10 | import { SettingsValueProps } from '../types';
|
---|
11 | import { SettingsContext } from './settings-context';
|
---|
12 |
|
---|
13 | // ----------------------------------------------------------------------
|
---|
14 |
|
---|
15 | const STORAGE_KEY = 'settings';
|
---|
16 |
|
---|
17 | type SettingsProviderProps = {
|
---|
18 | children: React.ReactNode;
|
---|
19 | defaultSettings: SettingsValueProps;
|
---|
20 | };
|
---|
21 |
|
---|
22 | export function SettingsProvider({ children, defaultSettings }: SettingsProviderProps) {
|
---|
23 | const { state, update, reset } = useLocalStorage(STORAGE_KEY, defaultSettings);
|
---|
24 |
|
---|
25 | const [openDrawer, setOpenDrawer] = useState(false);
|
---|
26 |
|
---|
27 | const isArabic = localStorageGetItem('i18nextLng') === 'ar';
|
---|
28 |
|
---|
29 | useEffect(() => {
|
---|
30 | if (isArabic) {
|
---|
31 | onChangeDirectionByLang('ar');
|
---|
32 | }
|
---|
33 | // eslint-disable-next-line react-hooks/exhaustive-deps
|
---|
34 | }, [isArabic]);
|
---|
35 |
|
---|
36 | // Direction by lang
|
---|
37 | const onChangeDirectionByLang = useCallback(
|
---|
38 | (lang: string) => {
|
---|
39 | update('themeDirection', lang === 'ar' ? 'rtl' : 'ltr');
|
---|
40 | },
|
---|
41 | [update]
|
---|
42 | );
|
---|
43 |
|
---|
44 | // Drawer
|
---|
45 | const onToggleDrawer = useCallback(() => {
|
---|
46 | setOpenDrawer((prev) => !prev);
|
---|
47 | }, []);
|
---|
48 |
|
---|
49 | const onCloseDrawer = useCallback(() => {
|
---|
50 | setOpenDrawer(false);
|
---|
51 | }, []);
|
---|
52 |
|
---|
53 | const canReset = !isEqual(state, defaultSettings);
|
---|
54 |
|
---|
55 | const memoizedValue = useMemo(
|
---|
56 | () => ({
|
---|
57 | ...state,
|
---|
58 | onUpdate: update,
|
---|
59 | // Direction
|
---|
60 | onChangeDirectionByLang,
|
---|
61 | // Reset
|
---|
62 | canReset,
|
---|
63 | onReset: reset,
|
---|
64 | // Drawer
|
---|
65 | open: openDrawer,
|
---|
66 | onToggle: onToggleDrawer,
|
---|
67 | onClose: onCloseDrawer,
|
---|
68 | }),
|
---|
69 | [
|
---|
70 | reset,
|
---|
71 | update,
|
---|
72 | state,
|
---|
73 | canReset,
|
---|
74 | openDrawer,
|
---|
75 | onCloseDrawer,
|
---|
76 | onToggleDrawer,
|
---|
77 | onChangeDirectionByLang,
|
---|
78 | ]
|
---|
79 | );
|
---|
80 |
|
---|
81 | return <SettingsContext.Provider value={memoizedValue}>{children}</SettingsContext.Provider>;
|
---|
82 | }
|
---|