Skip to content

Commit

Permalink
useToast: Support dynamic dismiss timeout duration
Browse files Browse the repository at this point in the history
  • Loading branch information
felixhabib committed Oct 22, 2024
1 parent 1422b36 commit 8f98dd1
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 7 deletions.
13 changes: 13 additions & 0 deletions .changeset/great-houses-grin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'braid-design-system': minor
---

---
updated:
- useToast
---

**useToast**: Support dynamic dismiss timeout duration

Previously, all toasts would automatically dismiss after 10 seconds.
This update adjusts the timeout duration for toasts based on their content length, ensuring users have enough time to read the message, while minimising the time content is obscured the toast.
16 changes: 13 additions & 3 deletions packages/braid-design-system/src/lib/components/useToast/Toast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@ import { lineHeightContainer } from '../../css/lineHeightContainer.css';
import buildDataAttributes from '../private/buildDataAttributes';
import * as styles from './Toast.css';

const minimumToastDuration = 5 * 1000;
const actionableToastDuration = 10 * 1000;

const toastCharactersPerSecond = 120;

const toneToIcon = {
critical: IconCritical,
positive: IconPositive,
};

export const toastDuration = 10000;

const borderRadius = 'large';

interface ActionProps extends ToastAction {
Expand Down Expand Up @@ -81,12 +84,19 @@ const Toast = React.forwardRef<HTMLDivElement, ToastProps>(
},
ref,
) => {
const toastCharacterCount =
message.length + (description ? description.length : 0);

const toastLength =
minimumToastDuration +
Math.ceil(toastCharacterCount / toastCharactersPerSecond) * 1000;

const remove = useCallback(
() => onClose(dedupeKey, id),
[onClose, dedupeKey, id],
);
const { stopTimeout, startTimeout } = useTimeout({
duration: toastDuration,
duration: action ? actionableToastDuration : toastLength,
onTimeout: remove,
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
} from '..';
import { useThemeSettings } from 'site/App/ThemeSetting';
import Code from 'site/App/Code/Code';
import Toast, { toastDuration } from './Toast';
import Toast from './Toast';
import source from '@braid-design-system/source.macro';

const docs: ComponentDocs = {
Expand Down Expand Up @@ -428,9 +428,9 @@ const docs: ComponentDocs = {
description: (
<>
<Text>
{`A toast message can be dismissed via the close button or automatically after ${
toastDuration / 1000
} seconds.`}
A toast message can be dismissed via the close button or
automatically after a timeout period depending on its content
length.
</Text>

<Text tone="promote" id="translations">
Expand Down

0 comments on commit 8f98dd1

Please sign in to comment.