-
Notifications
You must be signed in to change notification settings - Fork 9
feat: added toast component #17
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
68d4b53
feat: added toast component
anuraghazra 68c66c9
chore: review updates
anuraghazra c0d80bf
fix(toast): touch drag autoDismiss
anuraghazra 5802252
refactor: delete context file
anuraghazra dbf93d6
chore(deps): move deps to dev dep
anuraghazra f44c1a1
chore: review updates
anuraghazra File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import React from "react"; | ||
| import { useTimeout } from "@chakra-ui/hooks"; | ||
| import { useGesture } from "react-use-gesture"; | ||
|
|
||
| interface ToastControllerProps { | ||
| id: string; | ||
| onRequestRemove: (id: string) => void; | ||
| duration?: number; | ||
| autoDismiss?: boolean; | ||
| } | ||
|
|
||
| export const ToastController: React.FC<ToastControllerProps> = ({ | ||
| id, | ||
| duration = 0, | ||
|
anuraghazra marked this conversation as resolved.
|
||
| autoDismiss, | ||
| onRequestRemove, | ||
| children, | ||
| }) => { | ||
| const [delay, setDelay] = React.useState<number | null>(duration); | ||
| const [x, setX] = React.useState(0); | ||
|
|
||
| const bind = useGesture({ | ||
| onDrag: ({ down, movement: [x] }: any) => { | ||
| if (!down) setX(0); | ||
|
|
||
| setX(x); | ||
| setDelay(null); | ||
|
|
||
| if (x > 100 || x < -100) { | ||
| onRequestRemove(id); | ||
| } | ||
| }, | ||
| onMouseUp: () => setX(0), | ||
| }); | ||
|
|
||
| const onMouseEnter = React.useCallback(() => { | ||
| autoDismiss && setDelay(null); | ||
| }, [autoDismiss]); | ||
|
|
||
| const onMouseLeave = React.useCallback(() => { | ||
| autoDismiss && setDelay(duration); | ||
| }, [autoDismiss, duration]); | ||
|
|
||
| useTimeout(() => { | ||
| if (autoDismiss) { | ||
| onRequestRemove(id); | ||
| } | ||
| }, delay); | ||
|
|
||
| const props = { | ||
| id, | ||
| onMouseLeave, | ||
| onMouseEnter, | ||
| className: "toast", | ||
| style: { transform: `translateX(${x}px)` }, | ||
| ...bind(), | ||
| }; | ||
|
|
||
| return <div {...props}>{children}</div>; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| import React from "react"; | ||
|
navin-moorthy marked this conversation as resolved.
|
||
| import ReactDOM from "react-dom"; | ||
|
|
||
| import useToastState, { IToast } from "./ToastState"; | ||
| import { ToastController } from "./ToastController"; | ||
| import { ToastStateReturn } from "./ToastState"; | ||
| import { canUseDOM } from "reakit-utils"; | ||
| import { createContext } from "@chakra-ui/utils"; | ||
|
|
||
| const DEFAULT_TIMEOUT = 5000; | ||
| const PLACEMENTS = { | ||
| "top-left": { top: 0, left: 0 }, | ||
| "top-center": { top: 0, left: "50%", transform: "translateX(-50%)" }, | ||
| "top-right": { top: 0, right: 0 }, | ||
| "bottom-left": { bottom: 0, left: 0 }, | ||
| "bottom-center": { bottom: 0, left: "50%", transform: "translateX(-50%)" }, | ||
| "bottom-right": { bottom: 0, right: 0 }, | ||
| }; | ||
|
|
||
| // let's infer the union types from the placement values instead of hardcoding them | ||
| export type Placements = keyof typeof PLACEMENTS; | ||
|
|
||
| interface IToastContext extends ToastStateReturn { | ||
| toastTypes: ToastTypes; | ||
| } | ||
|
|
||
| export const [ToastContextProvider, useToast] = createContext<IToastContext>({ | ||
| name: "useToast", | ||
| errorMessage: | ||
| "The `useToasts` hook must be called from a descendent of the `ToastProvider`.", | ||
| strict: true, | ||
| }); | ||
|
|
||
| export type ToastTypes = Record< | ||
| string, | ||
| React.FC< | ||
| Pick<IToast, "content" | "id" | "isVisible"> & { | ||
| remove: ToastStateReturn["remove"]; | ||
| } | ||
| > | ||
| >; | ||
|
|
||
| export type TToastWrapper = (props: any) => React.ReactElement<any>; | ||
|
anuraghazra marked this conversation as resolved.
|
||
| type IToastProvider = { | ||
| toastTypes: ToastTypes; | ||
| autoDismiss?: boolean; | ||
| timeout?: number; | ||
| animationTimeout?: number; | ||
|
anuraghazra marked this conversation as resolved.
|
||
| toastWrapper?: TToastWrapper; | ||
| placement?: Placements; | ||
| }; | ||
|
|
||
| export const ToastProvider: React.FC<IToastProvider> = ({ | ||
| children, | ||
| toastTypes, | ||
| toastWrapper: ToastWrapperComponent = ({ children }) => children, | ||
| animationTimeout, | ||
| autoDismiss: providerAutoDismiss, | ||
| timeout: providerTimeout = DEFAULT_TIMEOUT, | ||
| placement: providerPlacement = "bottom-center", | ||
| }) => { | ||
| const portalTarget = canUseDOM ? document.body : null; | ||
| const state = useToastState({ animationTimeout }); | ||
|
|
||
| const Toasts = state.getToastToRender( | ||
| providerPlacement, | ||
| (position, toastList) => { | ||
| return ( | ||
| <div | ||
| key={position} | ||
| className={`toast__container toast__container--${position}`} | ||
| style={{ | ||
| position: "fixed", | ||
| ...PLACEMENTS[position], | ||
| }} | ||
| > | ||
| {toastList.map( | ||
| ({ id, type, content, timeout, autoDismiss, isVisible }) => { | ||
| return ( | ||
| <ToastWrapperComponent | ||
| key={id} | ||
| id={id} | ||
| isVisible={isVisible} | ||
| placement={position} | ||
| > | ||
| <ToastController | ||
| id={id} | ||
| onRequestRemove={state.hide} | ||
| duration={timeout ?? providerTimeout} | ||
| autoDismiss={autoDismiss ?? providerAutoDismiss} | ||
| > | ||
| {typeof content === "function" | ||
| ? content({ id, isVisible, remove: state.hide }) | ||
| : toastTypes[type || ""]?.({ | ||
| content, | ||
| id, | ||
| remove: state.hide, | ||
| isVisible, | ||
| }) || content} | ||
| </ToastController> | ||
| </ToastWrapperComponent> | ||
| ); | ||
| }, | ||
| )} | ||
| </div> | ||
| ); | ||
| }, | ||
| ); | ||
|
|
||
| return ( | ||
| <ToastContextProvider value={{ ...state, toastTypes }}> | ||
| {children} | ||
| {portalTarget ? ReactDOM.createPortal(Toasts, portalTarget) : Toasts} | ||
| </ToastContextProvider> | ||
| ); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| import React from "react"; | ||
| import { v4 as uuidv4 } from "uuid"; | ||
| import { Placements } from "./ToastProvider"; | ||
|
|
||
| type JSXFunction = (props: any) => JSX.Element; | ||
| type StringOrElement = string | JSXFunction; | ||
|
|
||
| export interface IToast { | ||
| id: string; | ||
| type?: string; | ||
| content: StringOrElement; | ||
| timeout?: number; | ||
| placement?: Placements; | ||
| autoDismiss?: boolean; | ||
| isVisible?: boolean; | ||
| } | ||
|
|
||
| export type ToastList = Record<string, IToast>; | ||
|
|
||
| type GetToastToRenderType = ( | ||
| defaultPlacement: Placements, | ||
| callback: (position: Placements, toastList: IToast[]) => void, | ||
| ) => Array<any>; | ||
|
|
||
| interface ToastStateProps { | ||
| animationTimeout?: number; | ||
| } | ||
|
|
||
| const useToastState = ({ animationTimeout = 0 }: ToastStateProps) => { | ||
| const [toasts, setToasts] = React.useState<ToastList>({}); | ||
|
|
||
| // toggle can be used to just hide/show the toast instead of removing it. | ||
| // used for animations, since we don't want to unmount the component directly | ||
| const toggle = React.useCallback( | ||
| ({ id, isVisible }: { id: string; isVisible: boolean }) => { | ||
| setToasts(queue => ({ | ||
| ...queue, | ||
| [id]: { | ||
| ...queue[id], | ||
| isVisible, | ||
| }, | ||
| })); | ||
| }, | ||
| [], | ||
| ); | ||
|
|
||
| const show = React.useCallback( | ||
| ({ | ||
| type = "", | ||
| content, | ||
| timeout, | ||
| autoDismiss, | ||
| placement, | ||
| }: Omit<IToast, "id" | "isVisible">) => { | ||
| const uid = uuidv4(); | ||
|
navin-moorthy marked this conversation as resolved.
|
||
| /* | ||
| wait until the next frame so we can animate | ||
| wierd bug while using CSSTrasition | ||
| works fine without RAF & double render when using react spring. | ||
| maybe because of this:- https://youtu.be/mmq-KVeO-uU?t=842 | ||
| */ | ||
| requestAnimationFrame(() => { | ||
| setToasts(toasts => ({ | ||
| ...toasts, | ||
| [uid]: { | ||
| type, | ||
| id: uid, | ||
| content, | ||
| timeout, | ||
| placement, | ||
| autoDismiss, | ||
| isVisible: false, | ||
| }, | ||
| })); | ||
|
|
||
| // causes rerender in order to trigger | ||
| // the animation after mount in CSSTrasition | ||
| toggle({ id: uid, isVisible: true }); | ||
| }); | ||
| }, | ||
| [toggle], | ||
| ); | ||
|
|
||
| const remove = React.useCallback((id: string) => { | ||
| // need to use callback based setState otherwise | ||
| // the remove function would take the queue as dependency | ||
| // and cause render when changed which would effectively | ||
| // cause the animations to behave strangly. | ||
| setToasts(queue => { | ||
| const newQueue = { ...queue }; | ||
| delete newQueue[id]; | ||
|
|
||
| return newQueue; | ||
| }); | ||
| }, []); | ||
|
|
||
| const hide = React.useCallback( | ||
| (id: string) => { | ||
| toggle({ id, isVisible: false }); | ||
|
|
||
| window.setTimeout(() => { | ||
| remove(id); | ||
| }, animationTimeout); | ||
|
anuraghazra marked this conversation as resolved.
|
||
| }, | ||
| [toggle, animationTimeout, remove], | ||
| ); | ||
|
|
||
| // The idea here is to normalize the [...] single array to object with | ||
| // position keys & arrays containing the toasts | ||
| const getToastToRender: GetToastToRenderType = ( | ||
| defaultPlacement, | ||
| callback, | ||
| ) => { | ||
| const toastToRender = {}; | ||
| const toastList = Object.keys(toasts); | ||
|
|
||
| for (let i = 0; i < toastList.length; i++) { | ||
| const toast = toasts[toastList[i]]; | ||
| const { placement = defaultPlacement } = toast; | ||
| toastToRender[placement] || (toastToRender[placement] = []); | ||
|
|
||
| toastToRender[placement].push(toast); | ||
| } | ||
|
|
||
| return Object.keys(toastToRender).map(position => | ||
| callback(position as Placements, toastToRender[position]), | ||
| ); | ||
| }; | ||
|
|
||
| return { | ||
| setToasts, | ||
| getToastToRender, | ||
| toasts, | ||
| toggle, | ||
| show, | ||
| hide, | ||
| remove, | ||
| }; | ||
| }; | ||
|
|
||
| export type ToastStateReturn = ReturnType<typeof useToastState>; | ||
|
|
||
| export default useToastState; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| export * from "./ToastController"; | ||
| export * from "./ToastState"; | ||
| export * from "./ToastProvider"; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.