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

Add toasts to DS #3906

Merged
merged 2 commits into from
Oct 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
7 changes: 5 additions & 2 deletions design-system/packages/segmented-control/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@
"main": "dist/segmented-control.cjs.js",
"module": "dist/segmented-control.esm.js",
"devDependencies": {
"@types/react": "^16.9.51"
"@types/react": "^16.9.51",
"react": "^16.13.1"
},
"dependencies": {
"@babel/runtime": "^7.11.2",
"@emotion/core": "^10.0.35",
"@keystone-ui/core": "*",
"@keystone-ui/core": "*"
},
"peerDependencies": {
"react": "^16.13.1"
},
"engines": {
Expand Down
24 changes: 24 additions & 0 deletions design-system/packages/toast/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "@keystone-ui/toast",
"version": "1.0.0",
"private": true,
"license": "MIT",
"main": "dist/toast.cjs.js",
"module": "dist/toast.esm.js",
"devDependencies": {
"@types/react": "^16.9.51",
"react": "^16.13.1"
},
"dependencies": {
"@babel/runtime": "^7.11.2",
"@keystone-ui/core": "*",
"@keystone-ui/icons": "*"
},
"peerDependencies": {
"react": "^16.13.1"
},
"engines": {
"node": ">=10.0.0"
},
"repository": "https://github.com/keystonejs/keystone/tree/master/design-system/packages/toast"
}
213 changes: 213 additions & 0 deletions design-system/packages/toast/src/Toast.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
/** @jsx jsx */

import { HTMLAttributes, ReactNode, forwardRef, useEffect, useMemo, useState } from 'react';
import { jsx, keyframes, Portal, useTheme } from '@keystone-ui/core';
import { AlertOctagonIcon } from '@keystone-ui/icons/icons/AlertOctagonIcon';
import { AlertTriangleIcon } from '@keystone-ui/icons/icons/AlertTriangleIcon';
import { CheckCircleIcon } from '@keystone-ui/icons/icons/CheckCircleIcon';
import { InfoIcon } from '@keystone-ui/icons/icons/InfoIcon';
import { XIcon } from '@keystone-ui/icons/icons/XIcon';

import { ToastContext } from './context';
import { ToastProps, ToastPropsExact } from './types';

// Provider
// ------------------------------

export const ToastProvider = ({ children }: { children: ReactNode }) => {
const [toastStack, setToastStack] = useState<ToastPropsExact[]>([]);

const context = useMemo(
() => ({
addToast: (options: ToastProps) => {
setToastStack(currentStack => {
// only allow unique IDs in the toast stack
if (currentStack.some(toast => toast.id === options.id)) {
console.error(`You cannot add more than one toast with the same id ("${options.id}").`);
return currentStack;
}

// populate defaults and update state
let toast = populateDefaults(options);
return [...currentStack, toast];
});
},
removeToast: (id: string) => {
setToastStack(currentStack => currentStack.filter(t => t.id !== id));
},
}),
[]
);

return (
<ToastContext.Provider value={context}>
{children}
<ToastContainer>
{toastStack.map((props: ToastPropsExact) => {
const { id, message, preserve, title, tone } = props;
const onDismiss = () => context.removeToast(id);

return (
<ToastElement
key={id}
message={message}
preserve={preserve}
onDismiss={onDismiss}
title={title}
tone={tone}
/>
);
})}
</ToastContainer>
</ToastContext.Provider>
);
};

// Utils
// ------------------------------

let idCount = -1;
let genId = () => ++idCount;
function populateDefaults(props: ToastProps): ToastPropsExact {
return {
title: props.title,
message: props.message,
preserve: Boolean(props.preserve),
id: props.id || String(genId()),
tone: props.tone || 'help',
};
}

// Styled Components
// ------------------------------

// Container

const ToastContainer = (props: HTMLAttributes<HTMLDivElement>) => {
const { elevation } = useTheme();

return (
<Portal>
<div
css={{
position: 'fixed',
right: 0,
top: 0,
zIndex: elevation.e500,
}}
{...props}
/>
</Portal>
);
};

// Element

const AUTO_DISMISS_DURATION = 6000;
const slideInFrames = keyframes({
from: { transform: 'translateX(100%)' },
to: { transform: 'translateX(0)' },
});

type ToastElementProps = {
onDismiss: () => void;
} & Omit<ToastPropsExact, 'id'>;

export const ToastElement = forwardRef<HTMLDivElement, ToastElementProps>((props, ref) => {
const { message, onDismiss, preserve, title, tone, ...rest } = props;
const { radii, shadow, spacing, typography, colors, sizing, tones } = useTheme();

// auto-dismiss functionality
useEffect(() => {
if (!preserve) {
const timer = setTimeout(onDismiss, AUTO_DISMISS_DURATION);
return () => clearTimeout(timer);
}
// this is not like other components because the consumer cannot update the props once they `addToast()`
// we intentionally only want this to be run when the toast element mounts/unmounts
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const iconElement = {
positive: <CheckCircleIcon color={tones.positive.fill[0]} size="large" />,
negative: <AlertOctagonIcon color={tones.negative.fill[0]} size="large" />,
warning: <AlertTriangleIcon color={tones.warning.fill[0]} size="large" />,
help: <InfoIcon color={tones.help.fill[0]} size="large" />,
}[tone];

return (
<div
ref={ref}
css={{
alignItems: 'center',
animation: `${slideInFrames} 150ms cubic-bezier(0.2, 0, 0, 1)`,
background: colors.background,
borderRadius: radii.medium,
boxShadow: shadow.s500,
display: 'flex',
fontSize: typography.fontSize.small,
lineHeight: 1,
margin: spacing.medium,
padding: spacing.large,
}}
{...rest}
>
{iconElement}
<div
css={{
flex: 1,
maxWidth: 256, // less than desirable magic number, but not sure if this needs to be in theme...
paddingLeft: spacing.large,
paddingRight: spacing.large,
}}
>
<h3
css={{
fontSize: typography.fontSize.medium,
fontWeight: typography.fontWeight.bold,
margin: 0,
}}
>
{title}
</h3>
{message && (
<div
css={{
color: colors.foreground,
lineHeight: typography.leading.base,
marginTop: spacing.small,
}}
>
{message}
</div>
)}
</div>
<button
onClick={onDismiss}
css={{
alignItems: 'center',
background: 0,
border: 0,
borderRadius: '50%',
color: colors.foreground,
cursor: 'pointer',
display: 'flex',
height: sizing.small,
justifyContent: 'center',
outline: 0,
padding: 0,
width: sizing.small,

':hover, &.focus-visible': {
backgroundColor: colors.background,
},
':active': {
backgroundColor: colors.backgroundDim,
},
}}
>
<XIcon size="small" />
</button>
</div>
);
});
19 changes: 19 additions & 0 deletions design-system/packages/toast/src/context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { createContext, useContext } from 'react';

import { ToastProps } from './types';

function notInContext() {
throw new Error('This component must be used inside a <ToastProvider> component.');
}

type ContextType = {
addToast: (props: ToastProps) => void;
removeToast: (id: string) => void;
};

export const ToastContext = createContext<ContextType>({
addToast: notInContext,
removeToast: notInContext,
});

export const useToasts = () => useContext(ToastContext);
2 changes: 2 additions & 0 deletions design-system/packages/toast/src/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { ToastProvider } from './Toast';
export { useToasts } from './context';
14 changes: 14 additions & 0 deletions design-system/packages/toast/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export type ToneTypes = 'positive' | 'negative' | 'warning' | 'help';

type Common = {
title: string;
message?: string;
};
type NeedResolution = {
preserve: boolean;
id: string;
tone: ToneTypes;
};

export type ToastProps = Common & Partial<NeedResolution>;
export type ToastPropsExact = Common & NeedResolution;
1 change: 1 addition & 0 deletions design-system/website/components/Navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ export const Navigation = () => {
<NavItem href="/components/pill">Pill</NavItem>
<NavItem href="/components/options">Options</NavItem>
<NavItem href="/components/modals">Modals</NavItem>
<NavItem href="/components/toast">Toast</NavItem>
</Section>
</Fragment>
);
Expand Down
1 change: 1 addition & 0 deletions design-system/website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@keystone-ui/pill": "*",
"@keystone-ui/popover": "*",
"@keystone-ui/segmented-control": "*",
"@keystone-ui/toast": "*",
"@keystone-ui/tooltip": "*",
"@preconstruct/next": "^1.0.1",
"@types/react": "^16.9.51",
Expand Down
5 changes: 4 additions & 1 deletion design-system/website/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import React from 'react';
import { Core } from '@keystone-ui/core';
import { DrawerProvider } from '@keystone-ui/modals';
import { ToastProvider } from '@keystone-ui/toast';
import type { AppProps } from 'next/app';

export default function App({ Component, pageProps }: AppProps) {
return (
<Core>
<DrawerProvider>
<Component {...pageProps} />
<ToastProvider>
<Component {...pageProps} />
</ToastProvider>
</DrawerProvider>
</Core>
);
Expand Down
28 changes: 28 additions & 0 deletions design-system/website/pages/components/toast.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/** @jsx jsx */

import { Button } from '@keystone-ui/button';
import { jsx, Stack } from '@keystone-ui/core';
import { useToasts } from '@keystone-ui/toast';

import { Page } from '../../components/Page';

export default function OptionsPage() {
const { addToast } = useToasts();
return (
<Page>
<Stack marginTop="large" gap="small">
{(['positive', 'negative', 'warning', 'help'] as const).map(tone => {
return (
<Button
onClick={() => {
addToast({ title: 'Basic toast', tone });
}}
>
Add {tone} Toast
</Button>
);
})}
</Stack>
</Page>
);
}
2 changes: 1 addition & 1 deletion packages-next/admin-ui/TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
- [x] Drawer Package
- [x] Modals (specifically, confirm)
- [ ] Calendar / DateTime Picker
- [ ] Toasts
- [x] Toasts

## Dashboard

Expand Down