|
| 1 | +import React, { FunctionComponent, useCallback } from 'react'; |
| 2 | +import PageContainer from '../../layouts/pages/pageContainer/PageContainer'; |
| 3 | +import getLocalStorageKey from '../../utils/getLocalStorageKey'; |
| 4 | +import useArrayStateMutator from '../../hooks/useArrayStateMutator'; |
| 5 | +import { Counter } from './types'; |
| 6 | +import CounterItem from './components/counterItem/CounterItem'; |
| 7 | +import { Button, Modal } from 'antd'; |
| 8 | +import { CloseOutlined, PlusOutlined } from '@ant-design/icons'; |
| 9 | +import Flex from '../../components/flex/Flex'; |
| 10 | +import useWriteableLocalstorageState from '../../hooks/useWriteableLocalstorageState'; |
| 11 | + |
| 12 | +const createCounter = (name = '', count = 0): Counter => ({ |
| 13 | + name: '', |
| 14 | + count: 0 |
| 15 | +}); |
| 16 | + |
| 17 | +const initialCounters: Counter[] = [createCounter('Count')]; |
| 18 | + |
| 19 | +const CounterPage: FunctionComponent = () => { |
| 20 | + const [counters, setCounters] = useWriteableLocalstorageState<Counter[]>( |
| 21 | + getLocalStorageKey('counter', 'counters'), |
| 22 | + initialCounters |
| 23 | + ); |
| 24 | + const { |
| 25 | + fpChangeByIndex: handleItemChange, |
| 26 | + fpRemoveByIndex: handleItemRemove, |
| 27 | + add: addItem, |
| 28 | + clear: clearItems |
| 29 | + } = useArrayStateMutator(setCounters); |
| 30 | + |
| 31 | + const handleAddItem = useCallback(() => { |
| 32 | + addItem(createCounter()); |
| 33 | + }, [addItem]); |
| 34 | + |
| 35 | + const handleClear = useCallback(() => { |
| 36 | + Modal.warn({ |
| 37 | + title: 'Clear counters', |
| 38 | + content: 'Are you sure you want to delete all counters?', |
| 39 | + onOk: clearItems, |
| 40 | + okCancel: true |
| 41 | + }); |
| 42 | + }, [clearItems]); |
| 43 | + |
| 44 | + return ( |
| 45 | + <PageContainer title="Counters"> |
| 46 | + <Flex column gap={8}> |
| 47 | + {counters.length > 0 && ( |
| 48 | + <> |
| 49 | + <Flex column> |
| 50 | + <Button icon={<CloseOutlined />} size="large" onClick={handleClear}> |
| 51 | + Clear counters list |
| 52 | + </Button> |
| 53 | + </Flex> |
| 54 | + <Flex column gap={8}> |
| 55 | + {counters.map((counter, index) => ( |
| 56 | + <CounterItem |
| 57 | + key={index} |
| 58 | + counter={counter} |
| 59 | + onChange={handleItemChange(index)} |
| 60 | + onRemove={handleItemRemove(index)} |
| 61 | + /> |
| 62 | + ))} |
| 63 | + </Flex> |
| 64 | + </> |
| 65 | + )} |
| 66 | + <Button icon={<PlusOutlined />} type="dashed" onClick={handleAddItem} size="large"> |
| 67 | + Add counter |
| 68 | + </Button> |
| 69 | + </Flex> |
| 70 | + </PageContainer> |
| 71 | + ); |
| 72 | +}; |
| 73 | + |
| 74 | +export default CounterPage; |
0 commit comments