Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/pkoutsogiannis/dialog.js
https://github.com/pkoutsogiannis/dialog.js
dialog javascript responsive responsive-design responsive-web-design ui-components ui-design
Last synced: about 8 hours ago
JSON representation
- Host: GitHub
- URL: https://github.com/pkoutsogiannis/dialog.js
- Owner: pkoutsogiannis
- Created: 2025-01-27T17:09:10.000Z (7 days ago)
- Default Branch: main
- Last Pushed: 2025-01-27T17:46:29.000Z (7 days ago)
- Last Synced: 2025-01-27T18:31:08.326Z (7 days ago)
- Topics: dialog, javascript, responsive, responsive-design, responsive-web-design, ui-components, ui-design
- Language: JavaScript
- Homepage: https://ai.datasteam.com/aichat/
- Size: 34.2 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
# Documentation
## Overview
The dialog module provides a flexible and feature-rich dialog system for creating modal dialogs in web applications. It offers:
- Customizable dialog windows with title and content
- Built-in form handling and validation with real-time feedback
- Promise-based async/await support for modern JavaScript applications
- Keyboard navigation (Escape for cancel, Enter for submit)
- Automatic focus management with dialog-focus class
- Event lifecycle hooks (onLoad, onUnload, onSubmit, onCancel)
- Extensive button customization with predefined types
- HTML content support with built-in XSS protection via escapeHtml()
- Scoped query selector $ for safe DOM manipulation
- Transition animations for smooth user experience## API Reference
### Scoped Query Selector $
The dialog module provides a scoped query selector utility `$` to all event handlers (onLoad, onUnload, onSubmit, onClick, onCancel). This utility ensures that DOM queries are limited to elements within the current dialog, preventing conflicts with the main document.
```javascript
// $ is passed to all event handlers
onLoad: ($) => {
// Query a single element by selector (scoped to dialog)
const input = $('#email');
// Query all elements matching selector (scoped to dialog)
const errors = $.all('.error');
// Safe to use without worrying about ID conflicts
// with the main document
const form = $('#myForm');
}
```Key features:
- Scoped to current dialog content
- Prevents conflicts with main document
- Supports all standard CSS selectors
- Two methods:
- `$(selector)`: Returns first matching element (like querySelector)
- `$.all(selector)`: Returns all matching elements (like querySelectorAll)Note: All $ calls are automatically memoized/cached within each dialog instance for optimal performance. This means repeated calls with the same selector will return the cached result rather than performing a new DOM query.
### Class: `dialog`
#### Static Properties
- `POSTPONE`: Symbol used to postpone dialog closure
- `className`: Object containing button type classes
- `left`: 'dialog-left'
- `submit`: 'dialog-submit'
- `cancel`: 'dialog-cancel'#### Static Methods
##### Button Creation
```javascript
dialog.button.submit(text = 'OK')
dialog.button.close(text = 'Close') // same as dialog.button.submit
dialog.button.cancel(text = 'Cancel')
```##### Core Methods
###### createTitle(title, spacer = true)
Creates a title element for the dialog.
```javascript
// Create a title with default spacing
const titleHtml = dialog.createTitle('Welcome');// Create a title without spacing
const compactTitleHtml = dialog.createTitle('Welcome', false);
```###### createButton(options)
Creates a button element for the dialog.
```javascript
const buttonHtml = dialog.createButton({
id: 'save-btn', // Custom ID (auto-generated if not provided)
className: 'custom-class', // CSS classes (default: '')
style: 'color: red', // Inline styles (default: '')
text: 'Save', // Button text (default: 'OK')
onClick: ($) => { // Click handler (optional)
console.log('Button clicked');
}
});
```###### createButtons(buttons, spacer = true)
Creates a container with multiple buttons for the dialog.
```javascript
const buttonsHtml = dialog.createButtons([
{ text: 'Save', className: 'dialog-submit' },
{ text: 'Delete', className: 'dialog-cancel', style: 'color: red' },
dialog.button.custom({
text: 'Custom',
className: 'custom-class',
onClick: ($) => console.log('Custom clicked')
})
], true); // true adds spacing above buttons
```###### show(options)
Creates and displays a dialog with the specified options.
```javascript
const result = await dialog.show({
title: string, // Dialog title (default: '')
content: string, // HTML content (required)
buttons: array, // Array of button configurations (default: [])
spacer: { // Control spacing around title and buttons
top: boolean, // Add space below title (default: false)
bottom: boolean // Add space above buttons (default: true)
},
onLoad: ($) => void, // Called when dialog is created (optional)
onUnload: ($) => void, // Called before dialog is destroyed (optional)
onSubmit: ($) => any, // Called when submit button is clicked (optional)
onCancel: ($) => any, // Called when cancel button is clicked (optional)
onClick: ($) => void // Called when any other button is clicked (optional)
});
```Note: The content parameter is required and must be provided. All other parameters are optional with their respective default values.
###### alert(options)
Shows a simple alert dialog with a title, message, optional icon, and a single button.
```javascript
// Basic alert with just a message
await dialog.alert({ message: "Operation completed" });// Alert with predefined icon
await dialog.alert({
title: "Success", // Dialog title (default: '')
message: "Task completed", // Message to display
buttonText: "Got it", // Custom button text (default: 'OK')
iconClass: dialog.iconClass.success // Use predefined icon class
});// Alert with custom icon
await dialog.alert({
title: "Custom",
message: "Custom icon alert",
iconClass: dialog.iconClass.custom, // Use custom icon class
icon: "★" // Custom icon content
});
```The alert method supports two ways to specify icons:
1. Predefined Icons:
Use `iconClass` with dialog.iconClass properties:
- `dialog.iconClass.success`: Modern checkmark SVG icon with green gradient - For successful operations
- `dialog.iconClass.error`: Modern X SVG icon with red gradient - For error messages
- `dialog.iconClass.warning`: Modern exclamation triangle SVG icon with orange gradient - For warnings
- `dialog.iconClass.info`: Modern info circle SVG icon with blue gradient - For informational messages2. Custom Icons:
Use these parameters:
- `iconClass: dialog.iconClass.custom`: Indicates a custom icon
- `icon`: The custom icon content (text, symbol, or HTML)Icons are styled with:
- Modern Material Design SVG icons for consistent, professional appearance
- Large size (48px) for optimal visibility
- Beautiful color gradients for visual appeal
- Subtle drop shadow for depth
- Smooth pop-in animation when dialog opens
- Perfect centering with flexbox
- Consistent rendering across all platforms and browsersExample usage for different alert types:
```javascript
// Success alert
await dialog.alert({
title: "Success",
message: "Operation completed successfully!",
icon: "success"
});// Error alert
await dialog.alert({
title: "Error",
message: "Something went wrong.",
icon: "error"
});// Warning alert
await dialog.alert({
title: "Warning",
message: "Please proceed with caution.",
icon: "warning"
});// Info alert
await dialog.alert({
title: "Information",
message: "This is an informational message.",
icon: "info"
});
```Note: Alert dialogs have bottom spacer disabled by default for a more compact appearance.
###### prompt(options)
Shows a prompt dialog for user input. This is a convenience method that wraps `show()` with a standardized prompt interface.
```javascript
// Basic prompt usage
const name = await dialog.prompt({
title: "Hi!",
message: "What's your name?",
defaultValue: "John Doe"
});// Advanced prompt with custom options
const input = await dialog.prompt({
title: "Custom Prompt",
message: "Enter value:",
defaultValue: "",
okText: "Save", // Custom OK button text (default: 'OK')
cancelText: "Exit", // Custom Cancel button text (default: 'Cancel')
spacerTop: true, // Add space below title (default: false)
spacerBottom: true // Add space above buttons (default: false)
});// Returns:
// - The input value when OK is clicked
// - null when cancelled or Escape is pressed// The input field automatically:
// - Receives focus via dialog-focus class
// - Takes 100% width of the dialog
// - Has 8px padding below the message text
```###### close(value = null)
Closes the currently open dialog.
```javascript
// Close dialog without a return value
await dialog.close();// Close dialog with a specific value
await dialog.close('selected-value');// Note: The value will be returned as the resolution
// of the show() promise that created the dialog
```##### Keyboard Navigation
The dialog system provides built-in keyboard navigation for improved accessibility and user experience:
###### Enter Key Behavior
When the Enter key is pressed:
1. If pressed within a form:
- The form's default submission is prevented
- The dialog system looks for the first submit button (any button with `dialog-submit` class, created via `dialog.button.submit()` or `dialog.button.close()`)
- If found, simulates a click on that button
2. If pressed outside a form:
- The dialog system looks for a submit button (created via `dialog.button.submit()` or `dialog.button.close()`)
- If found, simulates a click on that button
3. In both cases, when the submit handler is triggered:
- Executes the `onSubmit` callback if defined
- If the callback returns `dialog.POSTPONE`, the dialog remains open
- Otherwise, returns the callback's result as the dialog's resolution value and closes the dialogNote: The enter key behavior can be prevented on specific elements by adding the `dialog-stop-propagation` class, useful for textarea elements or other cases where you want to allow multi-line input or special handling.
###### Escape Key Behavior
When the Escape key is pressed:
1. The dialog system looks for the first cancel button (any button with the `dialog-cancel` class, created via `dialog.button.cancel()`)
2. If found, it simulates a click on that button, which:
- Triggers the `onCancel` callback if defined
- If the callback returns `dialog.POSTPONE`, the dialog remains open
- Otherwise, closes the dialog and returns `null` as the resolution value
3. If no cancel button exists:
- The dialog is closed immediately
- Returns `null` as the resolution value###### Special Considerations
- The enter key behavior can be prevented on specific elements by adding the `dialog-stop-propagation` class. This is useful for textarea elements or other cases where you want to allow multi-line input without triggering dialog submission.
- Cancel operations can be postponed by returning `dialog.POSTPONE` from the onCancel callback, useful for showing confirmation prompts or handling unsaved changes.## Examples
All examples are showcased in the `index.html` file. Open it in a browser to see and interact with various dialog implementations.
## Best Practices
1. **Form Handling**
- Always prevent default form submission
- Use `dialog.POSTPONE` for validation
- Provide clear error messages2. **Button Configuration**
- Use predefined button types when possible
- Position primary actions on the right
- Use clear, action-oriented button text3. **Content Structure**
- Wrap content in a form element for better keyboard handling
- Use the dialog-focus class for initial focus
- Keep content concise and focused4. **Event Handling**
- Clean up event listeners in onUnload
- Use the $ selector for scoped queries
- Handle both success and error cases## Dialog Interaction Features
### Dragging and Moving
The dialog can be dragged and moved around the screen by clicking and dragging the title bar:
- Click and hold the dialog title to start dragging
- The dialog will automatically stay within the visible bounds of the screen
- The cursor changes to 'grabbing' while dragging
- The dialog maintains its position when the window is resized
- Clicking outside the title bar does not initiate dragging
- The dialog returns to center position if it hasn't been dragged### Template Content
The dialog system supports using predefined HTML templates as dialog content. This feature allows you to:
- Define reusable dialog content templates in your HTML
- Reference templates using the `::` prefix syntax
- Keep complex dialog structures organized and maintainable#### Using Templates
1. Define your templates in HTML using a container with the `dialog-templates` class:
```html
```2. Reference the template in your dialog by using the `::` prefix followed by the template ID:
```javascript
await dialog.show({
title: 'Login',
content: '::login-form', // References the template with id="login-form"
buttons: [
dialog.button.submit('Login'),
dialog.button.cancel()
],
onSubmit: ($) => {
return {
userName: $('input[type="text"]').value,
passord: $('input[type="password"]').value
};
}
});// Returns: { username: 'entered_username', password: 'entered_password' }
```The template's content will be automatically inserted into the dialog. This is particularly useful for:
- Complex form structures
- Reusable dialog layouts
- Maintaining consistent dialog content across your application## Dialog Lifecycle
1. **Creation**
- Dialog instance created
- onLoad callback executed
- Initial focus set2. **Interaction**
- User interacts with dialog
- Event handlers process interactions
- Dynamic updates possible
- onSubmit/onCancel triggered3. **Closure**
- onUnload callback executed
- Result returned to caller## Security Considerations
1. Always escape user input using `dialog.escapeHtml()`
2. Validate form inputs on both client and server
3. Be cautious with dynamic content injection## Error Handling
1. Use try-catch blocks for async operations
2. Return dialog.POSTPONE to prevent closure on error
3. Provide clear error feedback to users---
Copyright 2025 Periklis Koutsogiannis
Licensed under the Apache License, Version 2.0
Original Project: Dialog.js