(defaultPosition: Position)
| 12 | }; |
| 13 | |
| 14 | function useStore(defaultPosition: Position) { |
| 15 | const [messageList, setMessageList] = useState<MessageList>({ ...initialState }); |
| 16 | |
| 17 | return { |
| 18 | messageList, |
| 19 | add: (messageProps: MessageProps) => { |
| 20 | const id = getId(messageProps); |
| 21 | setMessageList((preState) => { |
| 22 | if (messageProps?.id) { |
| 23 | const position = getMessagePosition(preState, messageProps.id); |
| 24 | if (position) return preState; |
| 25 | } |
| 26 | |
| 27 | const position = messageProps.position || defaultPosition; |
| 28 | const isTop = position.includes('top'); |
| 29 | const messages = isTop |
| 30 | ? [{ ...messageProps, id }, ...(preState[position] ?? [])] |
| 31 | : [...(preState[position] ?? []), { ...messageProps, id }]; |
| 32 | |
| 33 | return { |
| 34 | ...preState, |
| 35 | [position]: messages, |
| 36 | }; |
| 37 | }); |
| 38 | return id; |
| 39 | }, |
| 40 | |
| 41 | update: (id: number, messageProps: MessageProps) => { |
| 42 | if (!id) return; |
| 43 | |
| 44 | setMessageList((preState) => { |
| 45 | const nextState = { ...preState }; |
| 46 | const { position, index } = findMessage(nextState, id); |
| 47 | |
| 48 | if (position && index !== -1) { |
| 49 | nextState[position][index] = { |
| 50 | ...nextState[position][index], |
| 51 | ...messageProps, |
| 52 | }; |
| 53 | } |
| 54 | |
| 55 | return nextState; |
| 56 | }); |
| 57 | }, |
| 58 | |
| 59 | remove: (id: number) => { |
| 60 | setMessageList((prevState) => { |
| 61 | const position = getMessagePosition(prevState, id); |
| 62 | |
| 63 | if (!position) return prevState; |
| 64 | return { |
| 65 | ...prevState, |
| 66 | [position]: prevState[position].filter((notice) => notice.id !== id), |
| 67 | }; |
| 68 | }); |
| 69 | }, |
| 70 | |
| 71 | clearAll: () => { |
no test coverage detected