Skip to content
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

feat: added toast component #17

Merged
merged 6 commits into from
Sep 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@
"@react-aria/utils": "^3.2.1",
"@react-stately/toggle": "^3.2.0",
"emotion": "^10.0.27",
"react-use-gesture": "^7.0.16",
"reakit": "^1.2.4",
"reakit-system": "^0.14.4",
"reakit-utils": "^0.14.3"
"reakit-utils": "^0.14.3",
"uuid": "^8.3.0"
navin-moorthy marked this conversation as resolved.
Show resolved Hide resolved
},
"devDependencies": {
"@babel/core": "7.11.5",
Expand All @@ -48,6 +50,8 @@
"@storybook/react": "6.0.21",
"@types/react": "16.9.49",
"@types/react-dom": "16.9.8",
"@types/react-transition-group": "^4.4.0",
"@types/uuid": "^8.3.0",
"@typescript-eslint/eslint-plugin": "4.0.1",
"@typescript-eslint/parser": "4.0.1",
"babel-eslint": "10.1.0",
Expand All @@ -67,6 +71,8 @@
"prettier": "2.1.1",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-spring": "^8.0.27",
"react-transition-group": "^4.4.1",
"sort-package-json": "1.44.0",
"typescript": "4.0.2"
}
Expand Down
60 changes: 60 additions & 0 deletions src/toast/ToastController.tsx
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.
Show resolved Hide 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>;
};
116 changes: 116 additions & 0 deletions src/toast/ToastProvider.tsx
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.
Show resolved Hide 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.
Show resolved Hide resolved
type IToastProvider = {
toastTypes: ToastTypes;
autoDismiss?: boolean;
timeout?: number;
animationTimeout?: number;
anuraghazra marked this conversation as resolved.
Show resolved Hide 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>
);
};
143 changes: 143 additions & 0 deletions src/toast/ToastState.ts
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.
Show resolved Hide 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.
Show resolved Hide 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;
3 changes: 3 additions & 0 deletions src/toast/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from "./ToastController";
export * from "./ToastState";
export * from "./ToastProvider";
Loading