### Build and Run Development Server Source: https://github.com/sukarth/moderntoasts/blob/main/CONTRIBUTING.md Build the project and start the development server to view examples locally. ```bash npm run build npm run dev npm run serve ``` -------------------------------- ### Install and Use ModernToasts Source: https://github.com/sukarth/moderntoasts/blob/main/CHANGELOG.md Install the library using npm and import the toast function for basic usage. This snippet demonstrates the initial setup and a simple success notification. ```bash # Install npm install modern-toasts ``` ```javascript import toast from 'modern-toasts'; tost.success('Welcome to ModernToasts!'); ``` -------------------------------- ### Welcome Message Example Source: https://github.com/sukarth/moderntoasts/blob/main/examples/script-tag-example.html Displays an initial informational toast to welcome the user and guide them through the available features. ```javascript setTimeout(() => { toast.info('Welcome to ModernToasts! Try all the configuration options below.', { autoDismiss: }); }, 1000); ``` -------------------------------- ### Install Dependencies Source: https://github.com/sukarth/moderntoasts/blob/main/CONTRIBUTING.md Install project dependencies using npm. ```bash npm install ``` -------------------------------- ### Clone Repository and Setup Remotes Source: https://github.com/sukarth/moderntoasts/blob/main/CONTRIBUTING.md Clone your fork of the repository and add the upstream remote for tracking changes. ```bash git clone https://github.com/your-username/ModernToasts.git cd ModernToasts git remote add upstream https://github.com/sukarth/ModernToasts.git ``` -------------------------------- ### Basic and Advanced Toast Examples Source: https://github.com/sukarth/moderntoasts/blob/main/README.md Demonstrates showing various toast types (success, error, info, warning) and advanced usage with custom styling and options like auto-dismiss. ```javascript // Basic examples ttoast.success('🎉 Welcome to ModernToasts!'); ttoast.error('❌ Something went wrong'); ttoast.info('â„šī¸ Here is some information'); ttoast.warning('âš ī¸ Please be careful'); // Advanced examples ttoast.success('Custom styled toast', { autoDismiss: 0, // Won't auto-dismiss backgroundColor: '#1f2937', textColor: '#f9fafb', borderColor: '#10b981' }); // Configure globally ttoast.configure({ position: 'top-right', maxVisibleStackToasts: 4, enableBorderAnimation: true }); ``` -------------------------------- ### Install ModernToasts via NPM Source: https://github.com/sukarth/moderntoasts/blob/main/README.md Use npm to install the ModernToasts library. This is the standard method for Node.js projects. ```bash # NPM npm install modern-toasts # Yarn yarn add modern-toasts # PNPM pnpm add modern-toasts ``` -------------------------------- ### Custom Styled Toast Example Source: https://github.com/sukarth/moderntoasts/blob/main/examples/npm-example.html Demonstrates how to apply custom styling to a success toast, including background color, text color, and border color, to create a dark theme appearance. ```javascript window.testCustomStyling = () => { toast.success('🎨 Custom styled toast with dark theme!', { backgroundColor: '#0f172a', textColor: '#f1f5f9', borderColor: '#22d3ee', autoDismiss: 6000 }); }; ``` -------------------------------- ### Custom Styling Example Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Apply custom styling to individual toasts or globally using CSS classes and configuration. ```APIDOC ### Custom Styling ```javascript toa.success('Custom styled toast', { backgroundColor: '#1f2937', textColor: '#f9fafb', borderColor: '#10b981', className: 'my-custom-toast' }); // Global custom CSS toa.configure({ customCSS: ` .my-custom-toast { border-radius: 16px; backdrop-filter: blur(10px); } ` }); ``` ``` -------------------------------- ### Handle Toast Events for Tracking Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Implement event listeners for 'show' and 'dismiss' events to track toast activity. This example increments a counter for shown toasts and logs dismissed toast messages. ```javascript let toastCount = 0; ttoast.on('show', (toastData) => { toastCount++; console.log(`Total toasts shown: ${toastCount}`); }); ttoast.on('dismiss', (toastData) => { console.log(`Toast "${toastData.message}" was dismissed`); }); ``` -------------------------------- ### TypeScript Support for ModernToasts Source: https://github.com/sukarth/moderntoasts/blob/main/README.md Demonstrates how to import and use ModernToasts with TypeScript, including type definitions for options and toast IDs. Ensure 'modern-toasts' is installed. ```typescript import toast, { ToastType, ToastOptions, ToastConfig } from 'modern-toasts'; const options: ToastOptions = { autoDismiss: 5000, position: 'top-right', showCloseButton: true }; const id: string = toast.success('Typed toast!', options); ``` -------------------------------- ### Install ModernToasts with npm Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Use this command to add ModernToasts to your project dependencies. ```bash npm install modern-toasts ``` -------------------------------- ### Jest Test Structure Example Source: https://github.com/sukarth/moderntoasts/blob/main/CONTRIBUTING.md Example structure for writing tests using Jest, including arrange, act, and assert phases. ```typescript describe('ComponentName', () => { describe('methodName', () => { it('should do something specific', () => { // Arrange const input = 'test'; // Act const result = methodName(input); // Assert expect(result).toBe('expected'); }); }); }); ``` -------------------------------- ### Setup Toast Event Listeners Source: https://github.com/sukarth/moderntoasts/blob/main/coverage/lcov-report/ModernToasts.ts.html Attaches event listeners to a toast element for closing and pausing on hover. Includes logic for proper cleanup of listeners and timers. ```typescript private setupToastEventListeners(toastData: ToastData, toastEl: HTMLElement): void { // Close button listener const closeButton = toastEl.querySelector(`.${CSS_CLASSES.TOAST_CLOSE_BUTTON}`) as HTMLButtonElement; if (closeButton) { const closeListener = (e: Event): void => { e.preventDefault(); e.stopPropagation(); this.removeToast(toastData.id); }; closeButton.addEventListener('click', closeListener, { passive: false }); closeButton.addEventListener('mousedown', (e) => { e.preventDefault(); e.stopPropagation(); }, { passive: false }); // Store references for cleanup toastData.closeButton = closeButton; toastData.closeButtonListener = closeListener; } // Pause on hover functionality if (toastData.options.pauseOnHover && toastData.options.autoDismiss > 0) { let remainingTime = toastData.options.autoDismiss; let _pauseStartTime: number; const mouseEnterListener = (): void => { if (toastData.timer) { clearTimeout(toastData.timer); _pauseStartTime = Date.now(); } }; const mouseLeaveListener = (): void => { if (toastData.options.autoDismiss > 0 && !toastData.isRemoving) { const elapsed = Date.now() - toastData.createdAt; remainingTime = Math.max(1000, toastData.options.autoDismiss - elapsed); toastData.timer = window.setTimeout(() => { this.removeToast(toastData.id); }, remainingTime); } }; toastEl.addEventListener('mouseenter', mouseEnterListener); toastEl.addEventListener('mouseleave', mouseLeaveListener); // Store references for cleanup toastData.mouseEnterListener = mouseEnterListener; toastData.mouseLeaveListener = mouseLeaveListener; } } ``` -------------------------------- ### Get Current Global Configuration Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Retrieve the current global configuration object to inspect or log the active settings. ```javascript const currentConfig = toast.getConfig(); console.log('Current position:', currentConfig.position); ``` -------------------------------- ### Get Current Toast Configuration Source: https://github.com/sukarth/moderntoasts/blob/main/coverage/lcov-report/ModernToasts.ts.html Returns a copy of the current toast system configuration. Ensures that the returned configuration is a shallow copy to prevent external modifications from affecting the internal state. ```typescript getConfig(): ToastConfig { return { ...this.config }; } ``` -------------------------------- ### Build Project Source: https://github.com/sukarth/moderntoasts/blob/main/CONTRIBUTING.md Build the project to ensure it compiles successfully after making changes. ```bash npm run build ``` -------------------------------- ### Run Bundle Size Check Source: https://github.com/sukarth/moderntoasts/blob/main/scripts/README.md Execute this script to analyze bundle sizes of all build outputs and view compression ratios. It displays original file sizes, gzipped file sizes, and compression ratios. ```bash npm run size ``` -------------------------------- ### Package.json Entry Points Configuration Source: https://github.com/sukarth/moderntoasts/blob/main/PUBLISHING.md Defines the main, module, browser, types, and exports for different module systems and environments. ```json { "main": "dist/modern-toasts.cjs.js", // CommonJS entry "module": "dist/modern-toasts.esm.js", // ES modules entry "browser": "dist/modern-toasts.min.js", // Browser/UMD entry "types": "dist/types/index.d.ts", // TypeScript definitions "exports": { ".": { "import": "./dist/modern-toasts.esm.js", "require": "./dist/modern-toasts.cjs.js", "browser": "./dist/modern-toasts.min.js", "types": "./dist/types/index.d.ts" } } } ``` -------------------------------- ### Configuration Source: https://github.com/sukarth/moderntoasts/blob/main/CHANGELOG.md Explains how to globally configure the toast notification system's behavior and appearance. ```APIDOC ## Configuration Configure the global settings for all toast notifications. ### Method - `toast.configure(options)`: Applies global configuration settings. ### Parameters #### Options Object - **position** (string) - Optional - The position of the toasts on the screen (e.g., 'top-left', 'bottom-right'). - **maxVisibleStackToasts** (number) - Optional - The maximum number of toasts to display in the stack. - **defaultDuration** (number) - Optional - The default duration in milliseconds for toasts to be visible. - **enableBorderAnimation** (boolean) - Optional - Enables the signature animated borders. - **animationDirection** (string) - Optional - The direction of the toast animations (e.g., 'left-to-right'). ### Request Example ```javascript tost.configure({ position: 'bottom-right', maxVisibleStackToasts: 3, defaultDuration: 4000, enableBorderAnimation: true, animationDirection: 'left-to-right' }); ``` ``` -------------------------------- ### Basic Usage Source: https://github.com/sukarth/moderntoasts/blob/main/CHANGELOG.md Demonstrates the fundamental methods for displaying different types of toast notifications. ```APIDOC ## Basic Usage This section shows how to display different types of toast notifications using the `toast` object. ### Methods - `toast.success(message)`: Displays a success toast. - `toast.error(message)`: Displays an error toast. - `toast.info(message)`: Displays an informational toast. - `toast.warning(message)`: Displays a warning toast. ### Request Example ```javascript import toast from 'modern-toasts'; tost.success('Hello World!'); tost.error('Something went wrong'); tost.info('Here is some info'); tost.warning('Be careful!'); ``` ``` -------------------------------- ### Test Feature Example Source: https://github.com/sukarth/moderntoasts/blob/main/examples/script-tag-example.html This snippet is part of a test feature for the Modern Toasts project. It appears to be a closing section of a JavaScript function or timer. ```javascript 6000 }); }, 1000); ``` -------------------------------- ### Get Default Animation Direction Source: https://github.com/sukarth/moderntoasts/blob/main/coverage/lcov-report/ModernToasts.ts.html Determines the default animation direction for a toast based on its display position. This ensures consistent UI behavior. ```typescript function getDefaultAnimationDirection(position: ToastPosition): AnimationDirection { switch (position) { case 'top-left': case 'bottom-left': return 'right-to-left'; case 'top-right': case 'bottom-right': return 'left-to-right'; case 'top-center': return 'bottom-to-top'; case 'bottom-center': return 'top-to-bottom'; default: return 'left-to-right'; } } ``` -------------------------------- ### Configuration and Event Handling Source: https://github.com/sukarth/moderntoasts/blob/main/coverage/lcov-report/types.ts.html Methods for configuring the toast system globally and handling toast-related events. ```APIDOC ## configure ### Description Updates the global configuration of the ModernToasts system. ### Signature `configure(config: Partial): void` ### Parameters - **config** (Partial) - Required - An object containing partial configuration settings to update. ``` ```APIDOC ## getConfig ### Description Retrieves the current global configuration of the ModernToasts system. ### Signature `getConfig(): ToastConfig` ### Returns - (ToastConfig) - The current configuration object. ``` ```APIDOC ## on ### Description Adds an event listener for specific toast events. ### Signature `on(event: ToastEvent, callback: ToastEventCallback): void` ### Parameters - **event** (ToastEvent) - Required - The type of event to listen for (e.g., 'show', 'dismiss', 'click', 'hover'). - **callback** (ToastEventCallback) - Required - The function to execute when the event occurs. ``` ```APIDOC ## off ### Description Removes an event listener for a specific toast event. ### Signature `off(event: ToastEvent, callback: ToastEventCallback): void` ### Parameters - **event** (ToastEvent) - Required - The type of event to stop listening for. - **callback** (ToastEventCallback) - Required - The callback function to remove. ``` ```APIDOC ## destroy ### Description Destroys the toast system and performs necessary cleanup. ### Signature `destroy(): void` ``` -------------------------------- ### Publish Package to npm Registry Source: https://github.com/sukarth/moderntoasts/blob/main/PUBLISHING.md Log in to your npm account and publish the package. Use tags for pre-release versions like beta or alpha. ```bash # Login to npm (first time only) npm login # Publish the package npm publish # For beta/alpha releases npm publish --tag beta npm publish --tag alpha ``` -------------------------------- ### Package.json Files to Include Source: https://github.com/sukarth/moderntoasts/blob/main/PUBLISHING.md Specifies which files and directories should be included when the package is published to npm. ```json { "files": [ "dist/", "README.md", "LICENSE", "CONTRIBUTING.md" ] } ``` -------------------------------- ### Development and Build npm Scripts Source: https://github.com/sukarth/moderntoasts/blob/main/PUBLISHING.md Common npm scripts for development, building, testing, and linting the project. ```bash npm run dev # Watch mode for development npm run build # Build all formats npm test # Run test suite npm run test:watch # Watch mode for tests npm run test:coverage # Generate coverage report npm run lint # Run ESLint npm run lint:fix # Fix linting issues npm run serve # Serve examples locally ``` -------------------------------- ### Custom Toast Styling and Event Listeners Source: https://github.com/sukarth/moderntoasts/blob/main/CHANGELOG.md Illustrates how to apply custom styles to individual toasts and how to listen for toast lifecycle events like 'show'. ```javascript // Custom styling ttoast.success('Custom toast', { backgroundColor: '#1f2937', borderColor: '#10b981', autoDismiss: 0 }); // Event listeners ttoast.on('show', (toastData) => { console.log('Toast shown:', toastData); }); ``` -------------------------------- ### Run Quality Checks Before Publishing Source: https://github.com/sukarth/moderntoasts/blob/main/PUBLISHING.md Execute linting, testing, and build processes to ensure code quality and successful artifact generation. ```bash npm run lint npm test npm run build npm pack --dry-run ``` -------------------------------- ### Basic Methods Source: https://github.com/sukarth/moderntoasts/blob/main/README.md These methods allow you to display different types of toast notifications and manage them. ```APIDOC ## Basic Methods ### Description Show different types of toasts or a generic toast, and manage their display. ### Methods - `toast.success(message, options?)`: Displays a success toast. - `toast.error(message, options?)`: Displays an error toast. - `toast.info(message, options?)`: Displays an informational toast. - `toast.warning(message, options?)`: Displays a warning toast. - `toast.show(message, type, options?)`: Displays a toast with a specified type. - `toast.dismiss(id)`: Dismisses a specific toast by its ID. - `toast.dismissAll()`: Dismisses all currently visible toasts. ### Parameters - `message` (string): The content of the toast notification. - `type` (string): The type of toast (e.g., 'success', 'error', 'info', 'warning'). - `options` (ToastOptions?): Optional configuration for the toast. ``` -------------------------------- ### Get Border Configurations by Animation Direction Source: https://github.com/sukarth/moderntoasts/blob/main/coverage/lcov-report/ToastBuilder.ts.html Provides specific CSS classes and initial styles for border elements based on the toast's animation direction. Handles 'top-to-bottom', 'bottom-to-top', and default cases. ```typescript private getBorderConfigurations(): Array<{class: string; initialStyles: Record}> { switch (this.animationDirection) { case 'top-to-bottom': return [ { class: 'border-left-top', initialStyles: { height: '0%', top: '50%' } }, { class: 'border-left-bottom', initialStyles: { height: '0%', bottom: '50%' } }, { class: 'border-top', initialStyles: { width: '0%' } }, { class: 'border-right-top', initialStyles: { height: '0%', top: '0%' } }, { class: 'border-right-bottom', initialStyles: { height: '0%', bottom: '0%' } }, { class: 'border-bottom-left', initialStyles: { width: '0%' } }, { class: 'border-bottom-right', initialStyles: { width: '0%' } } ]; case 'bottom-to-top': return [ { class: 'border-left-top', initialStyles: { height: '0%', bottom: '0%' } }, { class: 'border-bottom', initialStyles: { width: '0%' } }, { class: 'border-right-top', initialStyles: { height: '0%', bottom: '0%' } }, { class: 'border-top-left', initialStyles: { width: '0%' } }, { class: 'border-top-right', initialStyles: { width: '0%' } } ]; default: // left-to-right and right-to-left return [ { class: 'border-left-top', initialStyles: { height: '0%', top: '50%' } }, { class: 'border-left-bottom', initialStyles: { height: '0%', bottom: '50%' } }, { class: 'border-top', initialStyles: { width: '0%' } }, { class: 'border-bottom', initialStyles: { width: '0%' } }, { class: 'border-right-top', initialStyles: { height: '0%', top: '0%' } }, { class: 'border-right-bottom', initialStyles: { height: '0%', bottom: '0%' } } ]; } } ``` -------------------------------- ### Configuration Source: https://github.com/sukarth/moderntoasts/blob/main/README.md Configure the global settings for all toast notifications. ```APIDOC ## Configuration ### Description Configure the global settings for toast notifications, such as position, maximum visible toasts, and default duration. ### Methods - `toast.configure(config)`: Sets global configuration options. - `toast.getConfig()`: Retrieves the current global configuration. ### Parameters - `config` (object): An object containing configuration options. - `position` (string): Position of toast container (e.g., 'bottom-right', 'top-right'). - `maxVisibleStackToasts` (number): Maximum number of toasts to display at once. - `defaultDuration` (number): Default auto-dismiss duration in milliseconds. - `enableBorderAnimation` (boolean): Whether to enable border animations. ### Return Value - `toast.getConfig()`: Returns an object with the current configuration. ``` -------------------------------- ### Configure Toast Defaults Source: https://github.com/sukarth/moderntoasts/blob/main/CHANGELOG.md Shows how to globally configure default settings for all toast notifications, such as position, maximum visible toasts, and animation. ```javascript toast.configure({ position: 'bottom-right', maxVisibleStackToasts: 3, defaultDuration: 4000, enableBorderAnimation: true, animationDirection: 'left-to-right' }); ``` -------------------------------- ### Run Tests and Linting Source: https://github.com/sukarth/moderntoasts/blob/main/CONTRIBUTING.md Execute tests and run the linter to ensure code quality and correctness. ```bash npm test npm run lint ``` -------------------------------- ### Create GitHub Release Source: https://github.com/sukarth/moderntoasts/blob/main/PUBLISHING.md Tag the current commit with a version number and push the tag to the origin repository. ```bash git tag v1.0.0 git push origin v1.0.0 ``` -------------------------------- ### Configure and Show Toasts with ES Modules Source: https://github.com/sukarth/moderntoasts/blob/main/examples/npm-example.html Import the toast library, configure global settings, and define functions to show different types of toasts with custom dismiss durations. These functions are made available globally for easy access from HTML buttons. ```javascript // Import from the built ES module import toast from '../dist/modern-toasts.esm.js'; // Configure toast.configure({ position: 'bottom-right', maxVisibleStackToasts: 4, defaultDuration: 4000 }); // Make functions available globally for the buttons window.showSuccess = () => { toast.success('ES Module import working perfectly! 🎉', { autoDismiss: 5000 }); }; window.showError = () => { toast.error('This is an error message from ES modules.', { autoDismiss: 6000 }); }; window.showInfo = () => { toast.info('ES modules provide better tree-shaking and modern bundling.', { autoDismiss: 5000 }); }; window.showWarning = () => { toast.warning('Remember to build your project for production!', { autoDismiss: 5000 }); }; ``` -------------------------------- ### Create Gzipped Build Outputs Source: https://github.com/sukarth/moderntoasts/blob/main/scripts/README.md This script generates pre-compressed gzipped versions of all build outputs for efficient CDN delivery. It can be run automatically during the build process or directly using Node.js. ```bash npm run build ``` ```bash node scripts/create-gzipped.cjs ``` -------------------------------- ### Test Custom Styling and Long Duration Source: https://github.com/sukarth/moderntoasts/blob/main/examples/script-tag-example.html Demonstrates creating a toast with custom background, text, and border colors, and another toast with an extended display duration. ```javascript function testCustomStyling() { toast.success('🎨 Custom styled toast with dark theme!', { backgroundColor: '#0f172a', textColor: '#f1f5f9', borderColor: '#22d3ee', autoDismiss: 6000 }); } function testLongDuration() { toast.info('This toast will stay for 10 seconds', { autoDismiss: 10000 }); } ``` -------------------------------- ### Automated Pre-Publish Checks Source: https://github.com/sukarth/moderntoasts/blob/main/PUBLISHING.md The `prepublishOnly` script automatically executes linting, testing, and building to ensure the package is ready for publication. ```bash npm run lint && npm test && npm run build ``` -------------------------------- ### Package.json Scripts for Publishing Source: https://github.com/sukarth/moderntoasts/blob/main/PUBLISHING.md Defines scripts that run automatically before publishing or packaging, ensuring build and quality checks are performed. ```json { "scripts": { "prepublishOnly": "npm run lint && npm test && npm run build", "prepack": "npm run build" } } ``` -------------------------------- ### Welcome Message Toast Source: https://github.com/sukarth/moderntoasts/blob/main/examples/npm-example.html Displays a welcome informational toast message shortly after the page loads, informing the user about the ES module import and interactive features. ```javascript // Show welcome message setTimeout(() => { toast.info('Welcome! This example uses ES module imports. Try the interactive features below!', { autoDismiss: 6000 }); }, 1000); ``` -------------------------------- ### Create Multiple Toast Instances Source: https://github.com/sukarth/moderntoasts/blob/main/CHANGELOG.md Demonstrates how to create separate instances of ModernToasts to manage different configurations or groups of toasts independently. ```javascript // Multiple instances const customToasts = new ModernToasts({ position: 'top-left', maxVisibleStackToasts: 5 }); ``` -------------------------------- ### Toast Display Methods Source: https://github.com/sukarth/moderntoasts/blob/main/coverage/lcov-report/types.ts.html Methods for displaying different types of toasts with optional configurations. ```APIDOC ## success ### Description Shows a success toast message. ### Signature `success(message: string, options?: ToastOptions): string` ### Parameters - **message** (string) - Required - The message content for the toast. - **options** (ToastOptions) - Optional - Configuration options for the toast. ### Returns - (string) - The unique ID of the displayed toast. ``` ```APIDOC ## error ### Description Shows an error toast message. ### Signature `error(message: string, options?: ToastOptions): string` ### Parameters - **message** (string) - Required - The message content for the toast. - **options** (ToastOptions) - Optional - Configuration options for the toast. ### Returns - (string) - The unique ID of the displayed toast. ``` ```APIDOC ## info ### Description Shows an informational toast message. ### Signature `info(message: string, options?: ToastOptions): string` ### Parameters - **message** (string) - Required - The message content for the toast. - **options** (ToastOptions) - Optional - Configuration options for the toast. ### Returns - (string) - The unique ID of the displayed toast. ``` ```APIDOC ## warning ### Description Shows a warning toast message. ### Signature `warning(message: string, options?: ToastOptions): string` ### Parameters - **message** (string) - Required - The message content for the toast. - **options** (ToastOptions) - Optional - Configuration options for the toast. ### Returns - (string) - The unique ID of the displayed toast. ``` ```APIDOC ## show ### Description Shows a custom toast with a specified type. ### Signature `show(message: string, type: ToastType, options?: ToastOptions): string` ### Parameters - **message** (string) - Required - The message content for the toast. - **type** (ToastType) - Required - The type of the toast (e.g., 'success', 'error', 'info', 'warning'). - **options** (ToastOptions) - Optional - Configuration options for the toast. ### Returns - (string) - The unique ID of the displayed toast. ``` -------------------------------- ### Show Different Toast Types Source: https://github.com/sukarth/moderntoasts/blob/main/examples/script-tag-example.html Demonstrates how to display success, error, info, and warning toasts with custom auto-dismiss durations. ```javascript function showSuccess() { toast.success('Operation completed successfully! 🎉', { autoDismiss: 5000 }); } function showError() { toast.error('Something went wrong. Please try again.', { autoDismiss: 6000 }); } function showInfo() { toast.info('Here is some useful information for you.', { autoDismiss: 4000 }); } function showWarning() { toast.warning('Please be aware of potential issues.', { autoDismiss: 5000 }); } ``` -------------------------------- ### Toast Configuration Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Configure global settings for all toasts. This includes positioning, stack limits, animation properties, and custom CSS. ```APIDOC ## ToastConfig Global configuration options: ```typescript interface ToastConfig { position?: ToastPosition; // Default position maxVisibleStackToasts?: number; // Max visible toasts (default: 3) stackOffsetY?: number; // Vertical offset (default: 10px) stackOffsetX?: number; // Horizontal offset (default: 4px) scaleDecrementPerLevel?: number; // Scale reduction (default: 0.05) opacityDecrementPerLevel?: number; // Opacity reduction (default: 0.2) maxRenderedToasts?: number; // Max rendered (default: 5) defaultDuration?: number; // Default duration (default: 3000ms) animationDuration?: number; // Animation duration (default: 300ms) enableBorderAnimation?: boolean; // Enable border animation (default: true) enableFillAnimation?: boolean; // Enable fill animation (default: true) animationDirection?: AnimationDirection; // Default animation direction customCSS?: string; // Custom CSS injection } ``` ``` -------------------------------- ### TypeScript Usage Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Demonstrates how to use ModernToasts with TypeScript, including type imports and usage. ```APIDOC ## TypeScript Support ModernToasts is written in TypeScript and provides full type definitions: ```typescript import toast, { ToastType, ToastOptions, ToastConfig } from 'modern-toasts'; const options: ToastOptions = { autoDismiss: 5000, position: 'top-right', showCloseButton: true }; const id: string = toast.success('Typed toast!', options); ``` ``` -------------------------------- ### Package Contents Source: https://github.com/sukarth/moderntoasts/blob/main/CHANGELOG.md Lists the build output files for ModernToasts, including UMD, ES modules, and CommonJS formats, along with TypeScript definitions. ```bash dist/ ├── modern-toasts.umd.js # UMD build for script tags ├── modern-toasts.min.js # Minified UMD build ├── modern-toasts.esm.js # ES modules build ├── modern-toasts.cjs.js # CommonJS build └── types/ # TypeScript definitions └── index.d.ts ``` -------------------------------- ### Initialize and Configure ModernToasts Source: https://github.com/sukarth/moderntoasts/blob/main/examples/script-tag-example.html Access the toast API from the global ModernToasts object and configure initial settings like position, duration, and animations. ```javascript const { toast } = window.ModernToasts; const defaultAnimations = { 'top-left': 'right-to-left', 'bottom-left': 'right-to-left', 'top-right': 'left-to-right', 'bottom-right': 'right-to-left', 'top-center': 'bottom-to-top', 'bottom-center': 'top-to-bottom' }; let currentConfig = { position: 'bottom-right', maxVisibleStackToasts: 3, defaultDuration: 4000, animationDirection: defaultAnimations ['bottom-right'], enableBorderAnimation: true, enableFillAnimation: true, animationDuration: 350 }; totoast.configure(currentConfig); ``` -------------------------------- ### Display Multiple Toasts Sequentially Source: https://github.com/sukarth/moderntoasts/blob/main/examples/npm-example.html Demonstrates how to queue and display multiple toast notifications of different types in quick succession with a slight delay between each, creating a sequence of messages. ```javascript window.testMultipleToasts = () => { const messages = [ 'First ES module toast', 'Second ES module toast', 'Third ES module toast', 'Fourth ES module toast' ]; const types = ['success', 'error', 'info', 'warning']; messages.forEach((message, index) => { setTimeout(() => { toast[types[index]](message, { autoDismiss: 3000 }); }, index * 500); }); }; ``` -------------------------------- ### Test All Animation Directions Source: https://github.com/sukarth/moderntoasts/blob/main/examples/script-tag-example.html Demonstrates how to apply different animation directions to toasts, showcasing left-to-right, right-to-left, top-to-bottom, and bottom-to-top effects. ```javascript function testAllDirections() { const directions = ['left-to-right', 'right-to-left', 'top-to-bottom', 'bottom-to-top']; const messages = [ 'Left to Right animation', 'Right to Left animation', 'Top to Bottom animation', 'Bottom to Top animation' ]; directions.forEach((direction, index) => { setTimeout(() => { toast.info(messages[index], { animationDirection: direction, autoDismiss: 4000 }); }, index * 1000); }); } ``` -------------------------------- ### File Organization Structure Source: https://github.com/sukarth/moderntoasts/blob/main/CONTRIBUTING.md Illustrates the recommended directory structure for the ModernToasts project. ```plaintext src/ ├── ModernToasts.ts # Main class ├── types.ts # TypeScript definitions ├── constants.ts # Constants and configuration ├── utils.ts # Utility functions ├── ToastBuilder.ts # Builder pattern implementation └── index.ts # Entry point ``` -------------------------------- ### toast.configure(config) Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Updates the global configuration for all future toast notifications. ```APIDOC ## toast.configure(config) ### Description Update global configuration for all future toasts. ### Parameters #### Path Parameters - `config` (Partial) - Required - Configuration object ### Request Example ```javascript t oast.configure({ position: 'top-right', maxVisibleStackToasts: 4, defaultDuration: 5000, enableBorderAnimation: true, animationDirection: 'left-to-right' }); ``` ``` -------------------------------- ### Manage Package Version with npm Source: https://github.com/sukarth/moderntoasts/blob/main/PUBLISHING.md Increment the package version according to Semantic Versioning (SemVer) for patch, minor, or major releases. ```bash # For patch release (1.0.1) npm version patch # For minor release (1.1.0) npm version minor # For major release (2.0.0) npm version major ``` -------------------------------- ### Advanced Features Source: https://github.com/sukarth/moderntoasts/blob/main/CHANGELOG.md Covers advanced usage patterns including custom styling, event listeners, and managing multiple toast instances. ```APIDOC ## Advanced Features Explore advanced functionalities like custom styling, event handling, and creating multiple toast instances. ### Custom Styling Apply custom styles to individual toasts. #### Method - `toast.success(message, options)` (and other toast types) #### Options Object for Custom Styling - **backgroundColor** (string) - Optional - Sets the background color of the toast. - **borderColor** (string) - Optional - Sets the border color of the toast. - **autoDismiss** (number | boolean) - Optional - Overrides the default auto-dismiss duration (0 to disable). ### Request Example (Custom Styling) ```javascript tost.success('Custom toast', { backgroundColor: '#1f2937', borderColor: '#10b981', autoDismiss: 0 }); ``` ### Event Listeners Listen to toast lifecycle events. #### Method - `toast.on(eventName, callback)` #### Parameters - **eventName** (string) - The name of the event to listen for (e.g., 'show', 'dismiss'). - **callback** (function) - The function to execute when the event is triggered. ### Request Example (Event Listener) ```javascript tost.on('show', (toastData) => { console.log('Toast shown:', toastData); }); ``` ### Multiple Instances Create separate instances of ModernToasts with different configurations. #### Constructor - `new ModernToasts(options)` #### Parameters - **options** (object) - Configuration options for the new instance. ### Request Example (Multiple Instances) ```javascript const customToasts = new ModernToasts({ position: 'top-left', maxVisibleStackToasts: 5 }); ``` ``` -------------------------------- ### ModernToasts API: Configuration Source: https://github.com/sukarth/moderntoasts/blob/main/README.md Details on how to globally configure ModernToasts, including setting default options and retrieving the current configuration. ```javascript // Configure globally ttoast.configure({ position: 'bottom-right', maxVisibleStackToasts: 3, defaultDuration: 4000, enableBorderAnimation: true }); // Get current config const config = toast.getConfig(); ``` -------------------------------- ### Test No Auto-Close and Multiple Toasts Source: https://github.com/sukarth/moderntoasts/blob/main/examples/script-tag-example.html Shows how to create a toast that requires manual dismissal and how to display a sequence of multiple toasts with different types and delays. ```javascript function testNoAutoClose() { toast.warning('This toast won\'t auto-close. Click X to dismiss.', { autoDismiss: 0 }); } function testMultipleToasts() { const messages = [ 'First toast', 'Second toast', 'Third toast', 'Fourth toast', 'Fifth toast' ]; const types = ['success', 'error', 'info', 'warning', 'success']; messages.forEach((message, index) => { setTimeout(() => { toast[types[index]](message, { autoDismiss: 3000 }); }, index * 500); }); } ``` -------------------------------- ### Utilize Different Animation Directions Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Demonstrates how to apply various animation directions to toasts. Each toast type is shown with a different predefined animation style. ```javascript // Different animation styles ttoast.success('Left to right', { animationDirection: 'left-to-right' }); ttoast.error('Right to left', { animationDirection: 'right-to-left' }); ttoast.info('Top to bottom', { animationDirection: 'top-to-bottom' }); ttoast.warning('Bottom to top', { animationDirection: 'bottom-to-top' }); ``` -------------------------------- ### Display a Success Toast (ES Modules) Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Import the toast function and use it to display a success message. This is the standard way to use the library in modern JavaScript projects. ```javascript import toast from 'modern-toasts'; toa st.success('Hello World!'); ``` -------------------------------- ### Toast Management Methods Source: https://github.com/sukarth/moderntoasts/blob/main/coverage/lcov-report/types.ts.html Methods for managing the lifecycle and visibility of toasts. ```APIDOC ## dismiss ### Description Dismisses a specific toast by its unique ID. ### Signature `dismiss(id: string): void` ### Parameters - **id** (string) - Required - The ID of the toast to dismiss. ``` ```APIDOC ## dismissAll ### Description Dismisses all currently displayed toasts. ### Signature `dismissAll(): void` ``` -------------------------------- ### ModernToasts API: Basic Methods Source: https://github.com/sukarth/moderntoasts/blob/main/README.md Reference for basic toast methods including showing different types of toasts and managing toast visibility. ```javascript // Show different types of toasts ttoast.success(message, options?) ttoast.error(message, options?) ttoast.info(message, options?) ttoast.warning(message, options?) // Generic method ttoast.show(message, type, options?) // Management ttoast.dismiss(id) // Dismiss specific toast ttoast.dismissAll() // Dismiss all toasts ``` -------------------------------- ### ModernToasts Class Initialization Source: https://github.com/sukarth/moderntoasts/blob/main/coverage/lcov-report/ModernToasts.ts.html Initializes the ModernToasts system by injecting necessary CSS, creating the main container element, and setting up initial CSS custom properties. ```typescript export class ModernToasts implements ModernToastsAPI { private config: Required; private toasts: ToastData[] = []; private container: HTMLElement | null = null; private containerInner: HTMLElement | null = null; private eventListeners: Map = new Map(); private isInitialized = false; constructor(config?: Partial) { this.config = { ...DEFAULT_CONFIG, ...config }; this.init(); } private init(): void { Iif (this.isInitialized) { return; } this.injectCSS(); this.createContainer(); this.updateCSSProperties(); this.isInitialized = true; } ``` -------------------------------- ### Basic Toast Notifications Source: https://github.com/sukarth/moderntoasts/blob/main/CHANGELOG.md Demonstrates how to import and display different types of toast notifications using the ModernToasts library. ```javascript import toast from 'modern-toasts'; ttoast.success('Hello World!'); ttoast.error('Something went wrong'); ttoast.info('Here is some info'); ttoast.warning('Be careful!'); ``` -------------------------------- ### Listen to Toast Events Source: https://github.com/sukarth/moderntoasts/blob/main/README.md Subscribe to toast lifecycle events like 'show' and 'dismiss' to react to toast appearances and disappearances. Use `toast.on()` to register listeners and `toast.off()` to remove them. ```javascript // Listen to toast events toa.on('show', (toastData) => { console.log('Toast shown:', toastData); }); toa.on('dismiss', (toastData) => { console.log('Toast dismissed:', toastData); }); ``` ```javascript // Remove event listeners toa.off('show', callback); ``` -------------------------------- ### Create Toast Element with Builder Pattern Source: https://github.com/sukarth/moderntoasts/blob/main/coverage/lcov-report/ModernToasts.ts.html Constructs a toast element using a builder pattern, applying various styles and content. It then sets up necessary event listeners for the created toast. ```typescript private createToastElement(toastData: ToastData): HTMLElement { const config = TYPE_CONFIG[toastData.type]; const builder = new ToastBuilder( toastData, config, { animationDirection: this.config.animationDirection, enableBorderAnimation: this.config.enableBorderAnimation, enableFillAnimation: this.config.enableFillAnimation }, ICONS ); const toastEl = builder .addBorders() .addFillProgress() .addContent() .applyCustomStyles() .build(); // Set up event listeners with proper cleanup this.setupToastEventListeners(toastData, toastEl); return toastEl; } ``` -------------------------------- ### Create Multiple ModernToasts Instances Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Instantiate ModernToasts multiple times to manage different sets of toasts independently. Configure each instance with unique settings like position and animation preferences. ```javascript import { ModernToasts } from 'modern-toasts'; const topToasts = new ModernToasts({ position: 'top-right', maxVisibleStackToasts: 2 }); const bottomToasts = new ModernToasts({ position: 'bottom-left', enableBorderAnimation: false }); topToasts.success('Top notification'); bottomToasts.info('Bottom notification'); ``` -------------------------------- ### Publishing npm Scripts Source: https://github.com/sukarth/moderntoasts/blob/main/PUBLISHING.md npm scripts specifically for the publishing process, including pre-publish hooks and packaging. ```bash npm run prepublishOnly # Runs automatically before publish npm run prepack # Runs before creating package npm pack # Create tarball for testing npm publish # Publish to npm registry ``` -------------------------------- ### CDN with SRI for ModernToasts Source: https://github.com/sukarth/moderntoasts/blob/main/SECURITY.md Use this snippet to load the minified ModernToasts library from a CDN in production. Ensure Subresource Integrity (SRI) is used for security. ```html ``` -------------------------------- ### toast.getConfig() Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Retrieves the current global configuration settings for toast notifications. ```APIDOC ## toast.getConfig() ### Description Get current global configuration. ### Response #### Success Response - `ToastConfig` - Current configuration object ### Request Example ```javascript const currentConfig = toast.getConfig(); console.log('Current position:', currentConfig.position); ``` ``` -------------------------------- ### Display Info Toast with Custom Icon and Class Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Display an informational toast, allowing for custom icons and CSS classes for styling. Returns a unique toast ID. ```javascript toast.info('Here is some useful information', { icon: '...', // Custom icon className: 'my-custom-toast' }); ``` -------------------------------- ### ToastBuilder Constructor Source: https://github.com/sukarth/moderntoasts/blob/main/coverage/lcov-report/ToastBuilder.ts.html Initializes the ToastBuilder with toast data, type configuration, global settings, and icons. Sets up internal properties based on provided data and configurations. ```typescript constructor( private toastData: ToastData, typeConfig: ToastTypeConfig, globalConfig: { animationDirection: AnimationDirection; enableBorderAnimation: boolean; enableFillAnimation: boolean; }, icons: Record ) { this.config = typeConfig; this.animationDirection = toastData.options.animationDirection || globalConfig.animationDirection; this.enableBorderAnimation = globalConfig.enableBorderAnimation; this.enableFillAnimation = globalConfig.enableFillAnimation; this.icons = icons; this.fragment = document.createDocumentFragment(); this.toastEl = this.createContainer(); } ``` -------------------------------- ### toast.info(message, options?) Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Displays an informational toast notification with a given message and optional configuration. Returns a unique ID for the toast. ```APIDOC ## toast.info(message, options?) ### Description Display an info toast notification. ### Parameters #### Path Parameters - `message` (string) - Required - The info message to display - `options` (ToastOptions) - Optional - Configuration options ### Response #### Success Response - `string` - Unique toast ID ### Request Example ```javascript t oast.info('Here is some useful information', { icon: '...', // Custom icon className: 'my-custom-toast' }); ``` ``` -------------------------------- ### Build and Return Toast Element Source: https://github.com/sukarth/moderntoasts/blob/main/coverage/lcov-report/ToastBuilder.ts.html Appends all constructed fragments to the main toast element and returns the complete toast HTMLElement. ```typescript build(): HTMLElement { // Append all fragments to the toast element this.toastEl.appendChild(this.fragment); return this.toastEl; } ``` -------------------------------- ### toast.warning(message, options?) Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Displays a warning toast notification with a given message and optional configuration. Returns a unique ID for the toast. ```APIDOC ## toast.warning(message, options?) ### Description Display a warning toast notification. ### Parameters #### Path Parameters - `message` (string) - Required - The warning message to display - `options` (ToastOptions) - Optional - Configuration options ### Response #### Success Response - `string` - Unique toast ID ### Request Example ```javascript t oast.warning('Please review your input', { pauseOnHover: false, borderColor: '#f59e0b' }); ``` ``` -------------------------------- ### Migration from react-hot-toast to ModernToasts Source: https://github.com/sukarth/moderntoasts/blob/main/README.md Shows the minimal code changes required to migrate from 'react-hot-toast' to 'modern-toasts'. Both libraries use a similar import and function call pattern. ```javascript // Before import toast from 'react-hot-toast'; toa st.success('Hello'); // After import toast from 'modern-toasts'; toast.success('Hello'); ``` -------------------------------- ### Show Toast Source: https://github.com/sukarth/moderntoasts/blob/main/coverage/lcov-report/ModernToasts.ts.html Displays a toast notification with a message, type, and optional configuration. ```APIDOC ## show ### Description Displays a toast notification with the specified message, type, and options. ### Method ```typescript show(message: string, type: ToastType, options?: ToastOptions): string ``` ### Parameters - **message** (string) - The content of the toast notification. - **type** (ToastType) - The type of the toast (e.g., Success, Error, Info, Warning). - **options** (ToastOptions, optional) - Additional configuration for the toast. ``` -------------------------------- ### Publish Patch Version Source: https://github.com/sukarth/moderntoasts/blob/main/PUBLISHING.md After fixing an issue, use this sequence of commands to publish a patch version. It increments the version, commits the change, and then publishes to npm. ```bash # Fix the issue npm version patch npm publish ``` -------------------------------- ### Secure Toast Configuration Source: https://github.com/sukarth/moderntoasts/blob/main/SECURITY.md When configuring toasts, use predefined safe values for options like position and stack limits. Be cautious with custom CSS, ensuring it originates from trusted sources. ```javascript // Good: Use predefined safe values toast.configure({ position: 'top-right', maxVisibleStackToasts: 3 }); // Be careful: Custom CSS should be from trusted sources only toast.configure({ customCSS: trustedCSSFromYourApp // Only use trusted CSS }); ``` -------------------------------- ### Configure Toasts Source: https://github.com/sukarth/moderntoasts/blob/main/coverage/lcov-report/ModernToasts.ts.html Updates the global configuration for toast notifications. ```APIDOC ## configure ### Description Updates the global configuration settings for the toast notifications. ### Method ```typescript configure(config: Partial): void ``` ### Parameters - **config** (Partial) - An object containing the configuration properties to update. ``` -------------------------------- ### Toast Configuration Interface Source: https://github.com/sukarth/moderntoasts/blob/main/API.md Defines the structure for global configuration options for ModernToasts. Customize aspects like toast position, visibility limits, offsets, animations, and durations. ```typescript interface ToastConfig { position?: ToastPosition; // Default position maxVisibleStackToasts?: number; // Max visible toasts (default: 3) stackOffsetY?: number; // Vertical offset (default: 10px) stackOffsetX?: number; // Horizontal offset (default: 4px) scaleDecrementPerLevel?: number; // Scale reduction (default: 0.05) opacityDecrementPerLevel?: number; // Opacity reduction (default: 0.2) maxRenderedToasts?: number; // Max rendered (default: 5) defaultDuration?: number; // Default duration (default: 3000ms) animationDuration?: number; // Animation duration (default: 300ms) enableBorderAnimation?: boolean; // Enable border animation (default: true) enableFillAnimation?: boolean; // Enable fill animation (default: true) animationDirection?: AnimationDirection; // Default animation direction customCSS?: string; // Custom CSS injection } ```