Skip to content

Commit

Permalink
redux types, first slice, hook useLocalstorage, some adaptive fix
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkMelior committed Mar 22, 2024
1 parent c3a2027 commit a3ae283
Show file tree
Hide file tree
Showing 30 changed files with 290 additions and 197 deletions.
6 changes: 5 additions & 1 deletion src/app/providers/StoreProvider/config/StateSchema.ts
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
export interface StateSchema {}
import { SpaceState } from '@/shared/ui/SpaceCanvas';

export interface StateSchema {
spaceCanvas: SpaceState;
}
10 changes: 4 additions & 6 deletions src/app/providers/StoreProvider/config/store.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import { spaceSlice } from '@/shared/ui/SpaceCanvas';
import { configureStore } from '@reduxjs/toolkit';
import { StateSchema } from './StateSchema';

export const createReduxStore = (initialState?: StateSchema) => {
return configureStore<StateSchema>({
reducer: {},
reducer: {
spaceCanvas: spaceSlice.reducer,
},
// devTools: IS_DEV,
preloadedState: initialState,
});
};

// Infer the `RootState` and `AppDispatch` types from the store itself
// export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
// export type AppDispatch = typeof store.dispatch;

export type AppDispatch = ReturnType<typeof createReduxStore>['dispatch'];
1 change: 1 addition & 0 deletions src/shared/const/localstorage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export enum LocalstorageKeys {
LIKED = 'liked-products-id',
HISTORY = 'history-products-id',
SPACE = 'space-background',
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { LocalstorageKeys } from '@/shared/types';
import { LocalstorageKeys } from '@/shared/const/localstorage';
import { DataCardProps } from '@/shared/ui/Card';

export const getStorageData = (
Expand Down
5 changes: 3 additions & 2 deletions src/shared/lib/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export { getStorageData } from './getStorageData/getStorageData';
export { useCurrency } from './useCurrency/useCurrency';
export type { Currency } from './useCurrency/useCurrency';
export { getStorageData } from './useStorageData/getStorageData';
export { useStorageData } from './useStorageData/useStorageData';
export { useLocalstorage } from './useLocalstorage/useLocalstorage';
export { useLocalstorageArray } from './useLocalstorageArray/useLocalstorageArray';
30 changes: 30 additions & 0 deletions src/shared/lib/hooks/useLocalstorage/useLocalstorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'use client';

/* eslint-disable react-hooks/rules-of-hooks */
import { LocalstorageKeys } from '@/shared/const/localstorage';
import { useState } from 'react';

export const useLocalstorage = <T>(
key: LocalstorageKeys,
initialValue: T,
): [T, (value: T) => void] => {
const isBrowser = typeof window !== 'undefined';
if (!isBrowser) {
return [initialValue, () => {}];
}

// Попытка получить сохраненное значение из localStorage
const storedValue = localStorage.getItem(key);
const initial = storedValue ? JSON.parse(storedValue) : initialValue;

// Создание состояния для значения и функции для его обновления
const [value, updateValue] = useState<T>(initial);

// Функция для обновления значения в состоянии и сохранения его в localStorage
const setValue = (newValue: T) => {
updateValue(newValue);
localStorage.setItem(key, JSON.stringify(newValue));
};

return [value, setValue];
};
60 changes: 60 additions & 0 deletions src/shared/lib/hooks/useLocalstorageArray/useLocalstorageArray.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
'use client';

/* eslint-disable react-hooks/rules-of-hooks */
import { LocalstorageKeys } from '@/shared/const/localstorage';
import { MouseEvent, useState } from 'react';

export const useLocalstorageArray = <T>(
key: LocalstorageKeys,
initialValue: T,
) => {
const isBrowser = typeof window !== 'undefined';
if (!isBrowser) {
return [initialValue, () => {}];
}

const [isAdded, setIsAdded] = useState<boolean>(() => {
const storedItems: T[] = JSON.parse(localStorage.getItem(key) || '[]');

return storedItems.includes(initialValue);
});

const updateLocalStorage = (products: T[]) => {
localStorage.setItem(key, JSON.stringify(products));
setIsAdded(!isAdded);
};

const toggle = (e: MouseEvent) => {
e.preventDefault();

const storedItems: T[] = JSON.parse(localStorage.getItem(key) || '[]');

const updatedItems = isAdded
? storedItems.filter((item) => item !== initialValue)
: [...storedItems, initialValue];

updateLocalStorage(updatedItems);
};

const add = (e: MouseEvent) => {
e.preventDefault();

const storedItems: T[] = JSON.parse(localStorage.getItem(key) || '[]');

if (!isAdded) {
const updatedItems = [...storedItems, initialValue];
updateLocalStorage(updatedItems);
}
};

const remove = (e: MouseEvent) => {
e.preventDefault();

const storedItems: T[] = JSON.parse(localStorage.getItem(key) || '[]');

const updatedItems = storedItems.filter((item) => item !== initialValue);
updateLocalStorage(updatedItems);
};

return { isAdded, toggle, add, remove };
};
80 changes: 0 additions & 80 deletions src/shared/lib/hooks/useStorageData/useStorageData.tsx

This file was deleted.

2 changes: 1 addition & 1 deletion src/shared/ui/Blackhole/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { Blackhole } from './Blackhole';
export { Blackhole } from './ui/Blackhole';
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,34 @@ import cls from './Blackhole.module.scss';
interface BlackholeProps {
className?: string;
flip?: boolean;
disabledOnMobile?: boolean;
}

export const Blackhole: FC<BlackholeProps> = ({ className = '', flip }) => {
export const Blackhole: FC<BlackholeProps> = ({
className = '',
flip,
disabledOnMobile,
}) => {
const [mounted, setMounted] = useState(false);
const isMobile = useMediaQuery({ maxWidth: MediaSize.LG });
const isMobile = useMediaQuery({ maxWidth: MediaSize.MD });

useEffect(() => {
setMounted(true);
}, []);

if (!mounted) {
if ((isMobile && disabledOnMobile) || !mounted) {
return null;
}

return (
<div
className={cn(cls.wrapper, { [cls.flip]: flip }, className, 'noselect')}
className={cn(
cls.wrapper,
'content',
{ [cls.flip]: flip },
className,
'noselect',
)}
>
<div className={cls.circles}>
<div />
Expand Down
12 changes: 9 additions & 3 deletions src/shared/ui/Card/ui/Card/Card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { Link } from '@/shared/config/i18n/navigation';
import { MediaSize } from '@/shared/config/mediaQuery/sizes';
import { LocalstorageKeys } from '@/shared/const/localstorage';
import { Market, MarketType } from '@/shared/const/market';
import { Currency, useStorageData } from '@/shared/lib/hooks';
import { Currency, useLocalstorageArray } from '@/shared/lib/hooks';
import { Button } from '@/shared/ui/Button';
import { Tooltip } from '@nextui-org/react';
import crypto from 'crypto';
Expand Down Expand Up @@ -75,8 +75,14 @@ export const Card: FC<CardProps> = memo(({ data }) => {

const images = data.images.slice(0, 5);

const { isAdded, toggle } = useStorageData(data, LocalstorageKeys.LIKED);
const { add: addHistory } = useStorageData(data, LocalstorageKeys.HISTORY);
const { isAdded, toggle } = useLocalstorageArray<DataCardProps['id']>(
LocalstorageKeys.LIKED,
data.id,
);
const { add: addHistory } = useLocalstorageArray(
LocalstorageKeys.HISTORY,
data.id,
);

return (
<Link href={data.src} className={cls.wrapper}>
Expand Down
2 changes: 1 addition & 1 deletion src/shared/ui/HeadingSlide/SlideHeading.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,6 @@
@apply font-bold;

@media (max-width: theme('screens.sm')) {
@apply text-6xl;
@apply text-7xl;
}
}
4 changes: 3 additions & 1 deletion src/shared/ui/SpaceCanvas/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export { SpaceCanvas } from './SpaceCanvas';
export { spaceSlice } from './model/slice/SpaceSlice';
export type { SpaceState } from './model/slice/SpaceSlice';
export { SpaceCanvas } from './ui/SpaceCanvas';
32 changes: 32 additions & 0 deletions src/shared/ui/SpaceCanvas/model/slice/SpaceSlice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'use client';

/* eslint-disable react-hooks/rules-of-hooks */
import { createSlice } from '@reduxjs/toolkit';

export interface SpaceState {
value: boolean;
}

const initialState: SpaceState = {
value: false,
};

export const spaceSlice = createSlice({
name: 'space',
initialState,
reducers: {
enable: (state) => {
state.value = true;
},
disable: (state) => {
state.value = false;
},
toggle: (state) => {
state.value = !state.value;
},
},
});

export const { enable, disable, toggle } = spaceSlice.actions;

export default spaceSlice.reducer;
File renamed without changes.
2 changes: 2 additions & 0 deletions src/views/MainPage/MainPage.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Blackhole } from '@/shared/ui/Blackhole';
import { About } from '@/widgets/About';
import { Advantages } from '@/widgets/Advantages';
import { BestProduct } from '@/widgets/BestProduct';
Expand Down Expand Up @@ -31,6 +32,7 @@ const MainPage: FC<MainPageProps> = () => {
}
// compact
/>
<Blackhole disabledOnMobile />
<NavigationPanel />
<Advantages />
<About />
Expand Down
14 changes: 10 additions & 4 deletions src/views/ShopPage/ShopPage.module.scss
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
@import '@/app/styles/utils';

.navigationPanel {
margin-top: -200px !important;
}

.wrapper {
display: grid;
grid-template-columns: 300px 1fr;
Expand All @@ -18,6 +14,16 @@
}
}

.navigation {
margin-top: -200px;
margin-bottom: 80px;

@media (max-width: theme('screens.md')) {
margin-top: -140px;
margin-bottom: 0;
}
}

.sortWrapper {
display: flex;
flex-direction: column;
Expand Down
6 changes: 5 additions & 1 deletion src/views/ShopPage/ShopPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

/* eslint-disable i18next/no-literal-string */
import { cardData } from '@/db';
import { Blackhole } from '@/shared/ui/Blackhole';
import { Button } from '@/shared/ui/Button';
import { Cards } from '@/shared/ui/Card';
import { Input } from '@/shared/ui/Input';
Expand Down Expand Up @@ -37,7 +38,10 @@ export const ShopPage: FC = () => {
/>
}
/>
<NavigationPanel className={cls.navigationPanel} />
<div className={cls.navigation}>
<Blackhole />
<NavigationPanel />
</div>
<div className={cn(cls.wrapper, 'content')}>
<div className={cls.sortWrapper}>
<div className={cls.sort}>
Expand Down
Loading

0 comments on commit a3ae283

Please sign in to comment.