Advanced Toast/Tooltip/Popover/Confirm/Modal Notification Library – toast-anchor

Advanced Toast/Tooltip/Popover/Confirm/Modal Notification Library – toast-anchor
Advanced Toast/Tooltip/Popover/Confirm/Modal Notification Library – toast-anchor
toast-anchor is a feature-rich popup & notification library that creates slide-in toast messages, tooltip-style anchored popups, inline confirmation dialogs, and centered modal overlays.

Features:

  • 4 notification types: success, error, warning, and info.
  • 9 position options for standard toast stacks, spanning top, middle, and bottom rows.
  • Tooltip-style anchored popup.
  • Inline Yes/No confirmation dialog.
  • Centered modal overlay.
  • Progress bar countdown.
  • Built-in audio chime.
  • Works with React.
  • Promise toast that moves through loading, success, and error states automatically based on a passed promise.
  • Persistent toast support with a returned dismiss function for full manual lifecycle control.

How To Use It:

1. Install and import toast-anchor into your vanilla JS or React project.

# Yarn
$ yarn add toast-anchor

# NPM
$ npm install toast-anchor

# PNPM
$ pnpm install toast-anchor
import { useToast } from 'toast-anchor';

// OR
import toast, { configure, ICONS } from "./dist/index.mjs";

2. Call the notification methods to create basic toast messages.

// Show a success notification (renders bottom-right by default)
toast.success('Account activated successfully.');

// Show an error notification
toast.error('Request timed out. Please try again.');

// Show a warning notification
toast.warning('Your session expires in 5 minutes.');

// Show an informational notification
toast.info('App version 2.1.0 is now available.');

3. You can also create toast notification in React apps using the useToast hook.

import { useToast } from 'toast-anchor';

function SaveButton() {
  const toast = useToast(); // Returns the full toast API for this component
  const handleSave = () => {
    toast.success('Your changes have been saved.');
  };
  return <button onClick={handleSave}>Save Changes</button>;
}

4. Create a Snackbar-style notification with customdescription and action button:

toast.error('Email delivery failed.', {
  description: 'The recipient address may be unreachable.',
  action: {
    label: 'Retry',
    onClick: () => retrySendEmail(), // Fired when the user clicks the action button
  },
});

5. Set showProgress: true to render a countdown bar. Set duration: 0 to keep the toast on screen until you dismiss it manually.

// Countdown toast with a visible progress bar
toast.info('Session expires in 10 seconds.', {
  showProgress: true,
  duration: 10000, // 10 seconds
});

// Persistent toast — stays visible until dismiss() is called
const dismiss = toast.info('Connecting to the server…', { duration: 0 });
serverConnect().then(() => {
  dismiss(); // Remove the persistent toast
  toast.success('Connection ready.');
});

6. Customize toast positions:

toast.success('Top left',      { position: 'top-left' });
toast.success('Top center',    { position: 'top-center' });
toast.success('Top right',     { position: 'top-right' });
toast.success('Middle left',   { position: 'middle-left' });
toast.success('Middle center', { position: 'middle-center' });
toast.success('Middle right',  { position: 'middle-right' });
toast.success('Bottom left',   { position: 'bottom-left' });
toast.success('Bottom center', { position: 'bottom-center' });
toast.success('Bottom right',  { position: 'bottom-right' }); // Default

7. Assign a custom id to any toast and dismiss it by ID from anywhere in the codebase.

import toast, { dismissToast } from 'toast-anchor';

// Tag the persistent upload toast with a known ID
toast.info('Uploading files to the server…', { id: 'file-upload', duration: 0 });

// Later — from any other module or function
dismissToast('file-upload'); // Removes the toast by its assigned ID

8. Override the default styles on init.

toast.success('Theme applied.', {
  bg:            '#1a1a2e',  // Card background
  color:         '#e0e0ff',  // Title text color
  descColor:     '#9090bb',  // Description text color
  borderColor:   '#3a3a5c',  // Border color
  borderWidth:   '1px',
  borderRadius:  '10px',
  iconBg:        '#2a2a4e',  // Icon circle background
  iconColor:     '#90ee90',  // Icon color
  progressColor: '#90ee90',
  width:         '340px',
  fontSize:      '14px',
});

9. All Toast options.

  • type (string): Notification variant. Accepts success, error, warning, or info. Default: 'success'.
  • position (string): Screen position for the toast stack. Accepts top-left, top-center, top-right, middle-left, middle-center, middle-right, bottom-left, bottom-center, or bottom-right. Default: 'bottom-right'.
  • duration (number): Time in milliseconds before auto-dismiss. Set to 0 for a persistent toast. Default: 4000.
  • sound (boolean): Plays a chime when the toast appears. Default: false.
  • dismissOnClick (boolean): Dismisses the card when the user clicks anywhere on it. Default: false.
  • showProgress (boolean): Renders a countdown bar at the bottom of the card. Default: false.
  • id (string): Custom ID for programmatic dismissal via dismissToast(). Default: auto-generated.
  • description (string): Secondary text rendered below the title. Default: null.
  • action (object): Action button config. Accepts { label: string, onClick: () => void }. Default: null.
  • bg (string): Card background color. Default: '#ffffff'.
  • color (string): Title text color. Default: '#1e293b'.
  • descColor (string): Description text color. Default: '#64748b'.
  • borderColor (string): Card border color. Default: '#f1f5f9'.
  • borderWidth (string): Card border width. Default: '1px'.
  • borderRadius (string): Card border radius. Default: '14px'.
  • shadow (string): CSS box-shadow value. Default: library default.
  • padding (string): Card padding. Default: '13px 14px'.
  • width (string): Card width. Default: '316px'.
  • fontSize (string): Title font size. Default: '13.5px'.
  • fontWeight (string): Title font weight. Default: '600'.
  • descFontSize (string): Description font size. Default: '12px'.
  • showIcon (boolean): Shows or hides the icon circle. Default: true.
  • showClose (boolean): Shows or hides the close button. Default: true.
  • iconBg (string): Icon circle background. Defaults to the type’s light theme color.
  • iconColor (string): Icon color. Defaults to the type’s primary color.
  • iconSize (string): Icon circle diameter. Default: '32px'.
  • iconRadius (string): Icon circle border radius. Default: '50%'.
  • progressColor (string): Progress bar fill color. Defaults to the type’s primary color.
  • closeColor (string): Close button icon color. Default: '#cbd5e1'.
  • closeHoverColor (string): Close button hover color. Default: '#94a3b8'.
  • actionColor (string): Action button text color. Defaults to the type’s primary color.
  • actionFontSize (string): Action button font size. Default: '12px'.

10. toast.promise() accepts a promise and three message states. It creates a loading spinner until the promise settles, then transitions the card to success or error automatically.

// Basic promise toast — transitions through all three states automatically
toast.promise(fetch('/api/report').then(r => r.json()), {
  loading: 'Generating your report…',
  success: 'Report ready. Check your downloads.',
  error:   'Report generation failed. Please try again.',
});

// Success and error messages accept a function that receives the resolved value or error object:
// Dynamic messages using the settled promise value
toast.promise(registerUser(formData), {
  loading: 'Creating your account…',
  success: (user) => `Welcome, ${user.displayName}! Your account is ready.`,
  error:   (err)  => `Registration failed: ${err.message}`,
});

// The function returns a cancel handle:
// Cancel the promise toast manually by calling the returned function
const cancel = toast.promise(runBulkExport(), {
  loading: 'Exporting records…',
  success: 'Export complete.',
  error:   'Export interrupted.',
});

cancelButton.addEventListener('click', cancel);

// Pass style overrides as the third argument:
toast.promise(uploadFile(file), {
  loading: `Uploading ${file.name}…`,
  success: (res) => `Uploaded — ${res.bytes} bytes transferred`,
  error:   'Upload failed.',
}, { position: 'top-center', borderRadius: '8px' });

11. Create a tooltip-style popup using the toast.anchored() method. The directional arrow and entry animation adapt to the chosen side automatically. All Anchored Toast options:

  • type (string): Notification variant. Accepts success, error, warning, or info. Default: 'success'.
  • position (string): Popup side relative to the anchor element. Accepts top, bottom, left, or right. Default: 'top'.
  • duration (number): Time in milliseconds before auto-dismiss. Set to 0 for manual-only dismiss. Default: 2500.
  • sound (boolean): Plays a chime on appearance. Default: false.
  • icon (string): Custom HTML or SVG string to replace the default icon. Default: auto-derived from type.
  • gap (number): Pixel gap between the popup and the anchor element. Default: 13.
  • showArrow (boolean): Shows or hides the directional caret. Default: true.
  • arrowSize (number): Arrow diamond side length in pixels. Default: 10.
  • bg (string): Popup background color. Default: '#0f172a'.
  • color (string): Text color. Default: '#ffffff'.
  • borderColor (string): Border color. Default: transparent.
  • borderWidth (string): Border width. Default: '0px'.
  • borderRadius (string): Border radius. Default: '10px'.
  • shadow (string): CSS box-shadow value. Default: library default.
  • padding (string): Popup padding. Default: '8px 14px'.
  • fontSize (string): Font size. Default: '13px'.
  • fontWeight (string): Font weight. Default: '600'.
  • showIcon (boolean): Shows or hides the icon. Default: true.
const actionBtn = document.getElementById('publish-btn');

// Attach the popup above the element (default)
toast.anchored('Published to production.', actionBtn, { position: 'top' });

// Attach below the element
toast.anchored('Draft auto-saved.', actionBtn, { position: 'bottom' });

// Attach to the left
toast.anchored('Validation passed.', actionBtn, { position: 'left' });

// Attach to the right
toast.anchored('Sync complete.', actionBtn, { position: 'right' });

12. Attaches a Yes/No confirm popover to a target element using the toast.anchoredConfirm() method. All Anchored Confirm options:

  • confirmLabel (string): Confirm button label. Default: 'Yes'.
  • cancelLabel (string): Cancel button label. Default: 'No'.
  • position (string): Popup side relative to the anchor. Accepts top, bottom, left, or right. Default: 'top'.
  • sound (boolean): Plays a warning chime on open. Default: false.
  • gap (number): Pixel gap between the popup and anchor element. Default: 13.
  • showArrow (boolean): Shows the caret arrow. Default: true.
  • arrowSize (number): Arrow size in pixels. Default: 10.
  • bg (string): Popup background color. Default: '#0f172a'.
  • color (string): Message text color. Default: '#f8fafc'.
  • borderColor (string): Border color. Default: transparent.
  • borderWidth (string): Border width. Default: '0px'.
  • borderRadius (string): Popup border radius. Default: '12px'.
  • shadow (string): CSS box-shadow value. Default: library default.
  • minWidth (string): Popup minimum width. Default: '160px'.
  • padding (string): Popup padding. Default: '12px 14px'.
  • fontSize (string): Message font size. Default: '13px'.
  • confirmBg (string): Confirm button background. Default: '#ef4444'.
  • confirmColor (string): Confirm button text color. Default: '#ffffff'.
  • confirmHoverBg (string): Confirm button hover background. Default: '#dc2626'.
  • cancelBg (string): Cancel button background. Default: '#1e293b'.
  • cancelColor (string): Cancel button text color. Default: '#94a3b8'.
  • cancelHoverBg (string): Cancel button hover background. Default: '#334155'.
  • cancelBorder (string): Cancel button border color. Default: '#334155'.
  • btnRadius (string): Button border radius. Default: '8px'.
  • btnFontSize (string): Button font size. Default: '12px'.
  • btnFontWeight (string): Button font weight. Default: '700'.
  • btnPadding (string): Button padding. Default: '6px 0'.
toast.anchoredConfirm(
  'Permanently delete this record?',
  document.getElementById('delete-record-btn'),
  () => deleteRecord(), // Fired on confirm
  () => console.log('Deletion cancelled.'), // Fired on cancel (optional)
  {
    // options here
  }
);

13. toast.modal() opens a centered overlay dialog and returns a Promise<boolean>. The promise resolves to true on confirmation and false on cancellation. Pressing Escape cancels. All Modal options:

  • confirmVariant (string): Auto-derives the icon and button color scheme. Accepts danger or primary. Default: 'danger'.
  • position (string): Modal vertical alignment. Accepts center or top. Default: 'center'.
  • confirmLabel (string): Confirm button text. Default: 'Confirm'.
  • cancelLabel (string): Cancel button text. Default: 'Cancel'.
  • icon (string): Custom icon HTML or SVG string. Default: warning SVG.
  • sound (boolean): Plays a warning chime on open. Default: false.
  • overlayBg (string): Backdrop background color. Default: rgba(15,23,42,0.55).
  • overlayBlur (string): Backdrop blur amount. Default: '5px'.
  • bg (string): Modal card background. Default: '#ffffff'.
  • borderColor (string): Card border color. Default: transparent.
  • borderWidth (string): Card border width. Default: '0px'.
  • borderRadius (string): Card border radius. Default: '20px'.
  • shadow (string): Card box-shadow. Default: library default.
  • maxWidth (string): Card maximum width. Default: '420px'.
  • padding (string): Card body padding. Default: '24px'.
  • iconSize (string): Icon circle diameter. Default: '48px'.
  • iconRadius (string): Icon circle border radius. Default: '50%'.
  • iconBg (string): Icon circle background. Auto-derived from confirmVariant.
  • iconColor (string): Icon color. Auto-derived from confirmVariant.
  • titleColor (string): Title text color. Default: '#0f172a'.
  • titleSize (string): Title font size. Default: '17px'.
  • titleWeight (string): Title font weight. Default: '700'.
  • messageColor (string): Message text color. Default: '#64748b'.
  • messageSize (string): Message font size. Default: '14px'.
  • footerBg (string): Footer section background. Default: '#f8fafc'.
  • footerBorder (string): Footer top border color. Default: '#f1f5f9'.
  • confirmBg (string): Confirm button background. Auto-derived from confirmVariant.
  • confirmColor (string): Confirm button text color. Default: '#ffffff'.
  • confirmHoverBg (string): Confirm button hover background. Auto-derived.
  • confirmRadius (string): Confirm button border radius. Default: '10px'.
  • confirmPadding (string): Confirm button padding. Default: '9px 22px'.
  • confirmSize (string): Confirm button font size. Default: '13.5px'.
  • confirmWeight (string): Confirm button font weight. Default: '600'.
  • cancelBg (string): Cancel button background. Default: transparent.
  • cancelColor (string): Cancel button text color. Default: '#475569'.
  • cancelHoverBg (string): Cancel button hover background. Default: '#f1f5f9'.
  • cancelRadius (string): Cancel button border radius. Default: '10px'.
  • cancelPadding (string): Cancel button padding. Default: '9px 18px'.
  • cancelBorder (string): Cancel button border. Default: none.
  • cancelSize (string): Cancel button font size. Default: '13.5px'.
  • cancelWeight (string): Cancel button font weight. Default: '500'.
// Await the modal before executing the destructive action
const confirmed = await toast.modal(
  'Deactivate this workspace?',
  'All team members will immediately lose access.',
);
if (confirmed) {
  await deactivateWorkspace();
  toast.success('Workspace deactivated.');
}

// Use `confirmVariant: 'primary'` for non-destructive confirmations:
const confirmed = await toast.modal(
  'Publish this article?',
  'The post becomes visible to all subscribers immediately.',
  { confirmVariant: 'primary', confirmLabel: 'Publish Now' }
);

// Pass a custom SVG icon string to match the action context:
const archiveIcon = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
  <polyline points="21 8 21 21 3 21 3 8"/>
  <rect x="1" y="3" width="22" height="5"/>
  <line x1="10" y1="12" x2="14" y2="12"/>
</svg>`;
const confirmed = await toast.modal(
  'Archive this project?',
  'You can restore it later from the archive section.',
  {
    icon:           archiveIcon,  // Custom SVG replaces the default warning icon
    confirmLabel:   'Archive',
    confirmVariant: 'primary',
  }
);

// Full dark override:
const confirmed = await toast.modal(
  'Revoke API access?',
  'All integrations using this key will stop working immediately.',
  {
    overlayBg:      'rgba(0,0,0,0.75)',
    overlayBlur:    '8px',
    bg:             '#18181b',      // Modal card background
    borderColor:    '#3f3f46',
    borderWidth:    '1px',
    borderRadius:   '16px',
    titleColor:     '#f4f4f5',
    messageColor:   '#a1a1aa',
    footerBg:       '#111113',
    confirmBg:      '#dc2626',
    confirmHoverBg: '#b91c1c',
    cancelColor:    '#a1a1aa',
    cancelHoverBg:  '#27272a',
  }
);

14. Call configure() once in your app entry file to set defaults across all notification types. Per-call options take precedence over global defaults.

import { configure } from 'toast-anchor';

// Set once in main.js or index.js before rendering the app
configure({
  position:  'top-right', // Default position for all standard toasts
  duration:  5000, // 5 seconds before auto-dismiss
  sound:     false,
  maxToasts: 4, // Maximum concurrent toasts on screen
  toast: {
    borderRadius: '10px',
    width:        '320px',
  },
  modal: {
    borderRadius: '14px',
    overlayBlur:  '8px',
  },
});

// Override the default color palette for all four types globally:
configure({
  theme: {
    success: { bg: '#22c55e', light: '#dcfce7' },
    error:   { bg: '#ef4444', light: '#fee2e2' },
    warning: { bg: '#f97316', light: '#ffedd5' },
    info:    { bg: '#6366f1', light: '#e0e7ff' },
  },
});

// Style each notification type globally through its sub-object key:
configure({
  anchored: {
    bg:           '#7c3aed',
    color:        '#ede9fe',
    borderRadius: '8px',
    fontSize:     '12px',
    arrowSize:    8,
  },
  anchoredConfirm: {
    bg:         '#18181b',
    color:      '#f4f4f5',
    borderColor:'#3f3f46',
    borderWidth:'1px',
    confirmBg:  '#7c3aed',
    cancelBg:   '#27272a',
  },
});

15. All named exports from toast-anchor:

import {
  createToast,      // (message, options?) → dismiss fn
  promiseToast,     // (promise, messages, options?) → dismiss fn
  dismissToast,     // (id: string) → void
  dismissAll,       // () → void
  anchoredToast,    // (message, anchorEl, options?) → dismiss fn
  anchoredConfirm,  // (message, anchorEl, onConfirm, onCancel?, options?) → void
  modalConfirm,     // (title, message, options?) → Promise<boolean>
  configure,        // (options) → void
  DEFAULTS,         // Mutable global defaults object — readable and writable
  ICONS,            // { success, error, warning, info, loading } — SVG strings
  useToast,         // (hookDefaults?) → full toast API
} from 'toast-anchor';

Alternatives:

The post Advanced Toast/Tooltip/Popover/Confirm/Modal Notification Library – toast-anchor appeared first on CSS Script.


Discover more from RSS Feeds Cloud

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from RSS Feeds Cloud

Subscribe now to keep reading and get access to the full archive.

Continue reading