Skip to content

Conversation

@PrayagCodes
Copy link

@PrayagCodes PrayagCodes commented Nov 3, 2025

Enhanced Alert System with Multi-Type Support and Custom UI

PR Overview

This pull request introduces a comprehensive enhancement to the Puter alert system, transforming it from a single-type warning dialog into a flexible, multi-purpose notification framework. The implementation adds support for five distinct alert types (info, success, warning, error, question), enables simplified button configuration through string arrays, introduces custom UI content injection, and provides a modern object-based API while maintaining complete backward compatibility with existing codebases.

Branch: feat/enhanced-alert-system
Type: Feature Enhancement
Complexity: Moderate

Closes Feature

Closes Issue #3 - [FEATURE] Add multiple alert box types and customization options #7

##Before
Video: https://cap.link/v677g7a9ps1c0nj

image

Key Changes

1. Multi-Type Alert System

Introduced five semantic alert types with distinct visual identities:

  • Info: General informational messages (reminder icon)
  • Success: Action confirmation and completion (checkmark icon)
  • Warning: Cautionary messages requiring attention (warning sign icon)
  • Error: Critical failures and error states (danger icon)
  • Question: User decision prompts (reminder icon)

2. Intelligent Default Button Sets

Type-aware default button configurations eliminate boilerplate code:

  • Question alerts default to Yes/No buttons
  • Warning alerts default to OK/Cancel buttons
  • Info/Success/Error alerts default to OK button only

3. String Array Button Syntax

Simplified button definition through string arrays with automatic conversion:

  • First button receives primary styling automatically
  • Button value returns the clicked button's text
  • Maintains full compatibility with existing object-based button definitions

4. Object-Based API

Modern fluent API design with single object parameter:

  • All options passed as named properties in a single object
  • Improved code readability and IDE autocomplete support
  • Complete backward compatibility with legacy positional parameters

5. Custom UI Content Injection

Extensible content area between message and buttons:

  • HTML content support with sanitization
  • Safe tag allowlist (<strong>, <p>, <br>)
  • XSS protection through HTML encoding

Implementation

Video: https://cap.link/yc7j6957rfn3hmx

image

Architecture Overview

The alert system follows a three-layer architecture with cross-iframe communication:

┌──────────────────────────────────────────────────────────────┐
│                    Application Layer (SDK)                    │
│                   puter.ui.alert() invocation                 │
└──────────────────┬───────────────────────────────────────────┘
                   │
                   │ postMessage (Cross-Frame IPC)
                   │ { msg: 'ALERT', message: {...}, type, buttons, customUI }
                   │
                   ▼
┌──────────────────────────────────────────────────────────────┐
│              IPC Layer (Message Router/Handler)               │
│           Normalizes and forwards alert parameters            │
└──────────────────┬───────────────────────────────────────────┘
                   │
                   │ UIAlert() invocation
                   │ { message, type, buttons, customUI, window_options }
                   │
                   ▼
┌──────────────────────────────────────────────────────────────┐
│                 UI Renderer Layer (UIAlert)                   │
│                                                               │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  1. Parameter Normalization                           │  │
│  │     └─ Backward compatibility for legacy signatures   │  │
│  │                                                        │  │
│  │  2. Type-Specific Default Buttons                     │  │
│  │     ├─ Question → Yes/No                              │  │
│  │     ├─ Warning → OK/Cancel                            │  │
│  │     └─ Others → OK                                    │  │
│  │                                                        │  │
│  │  3. Button Format Conversion                          │  │
│  │     └─ String[] → Object[] with metadata              │  │
│  │                                                        │  │
│  │  4. Icon Selection                                    │  │
│  │     ├─ Type-to-Icon Mapping (iconMap)                 │  │
│  │     ├─ Custom override support (body_icon)            │  │
│  │     └─ Default fallback (warning)                     │  │
│  │                                                        │  │
│  │  5. HTML Assembly                                     │  │
│  │     ├─ Icon rendering                                 │  │
│  │     ├─ Message sanitization                           │  │
│  │     ├─ Custom UI injection (sanitized)                │  │
│  │     └─ Button generation                              │  │
│  │                                                        │  │
│  │  6. Window Creation & Event Binding                   │  │
│  │     ├─ UIWindow() delegation                          │  │
│  │     ├─ Click handlers on buttons                      │  │
│  │     └─ Promise resolution on interaction              │  │
│  └────────────────────────────────────────────────────────┘  │
└──────────────────┬───────────────────────────────────────────┘
                   │
                   │ Returns Promise<button_value>
                   │
                   ▼
             User Interaction → Promise Resolution

Implementation Details

Type-Specific Default Buttons

  • Alert type determines appropriate button sets when none provided
  • Question types receive Yes/No buttons
  • Warning types receive OK/Cancel buttons
  • Informational types (info, success, error) receive single OK button
  • Internationalization handled via i18n() function

String Array Conversion

  • Type detection on first button element triggers transformation
  • String array converts to button objects with label, value, and type properties
  • First button automatically receives primary styling
  • Remaining buttons receive default styling

Icon Mapping System

  • Static mapping object associates alert types with pre-loaded base64 icons
  • Selection priority: custom body_icon override → type-based lookup → warning default
  • All icons loaded at application startup for zero network latency

API Flexibility

  • SDK entry point implements parameter polymorphism
  • Object arguments trigger modern API path
  • Non-object arguments trigger legacy positional parameter path
  • Both paths produce identical postMessage payload
  • Seamless support for mixed usage patterns

Custom UI Sanitization

  • HTML content undergoes full encoding first
  • Selective de-encoding of allowlisted tags (strong, p, br)
  • Allowlist approach prevents XSS attacks
  • Enables rich formatting while maintaining security

IPC Message Normalization

  • Message handler wraps legacy string messages into object format
  • Modern object payloads pass through directly
  • Ensures consistent structure for UIAlert() processing
  • Transparent handling of both formats

Design Philosophy

Non-Breaking Evolution - Every enhancement layers atop existing functionality rather than replacing it. Type system added through icon lookup, button arrays through preprocessing, custom UI through template injection.

Security-First - Custom UI uses allowlist-based sanitization assuming all input is malicious. Only explicitly verified formatting tags render, preventing XSS vulnerabilities.

Semantic Type System - Alert types match universal UX patterns (info, success, warning, error, question) found across all major platforms for immediate developer intuitiveness.

Progressive API - Object-based API introduced as alternative, not replacement. Developers can use positional parameters indefinitely, adopt object syntax selectively, or mix both styles.

Testing

After: https://cap.link/fv5wvbnhrptwxbs

image

Manual Testing Checklist

Type System Verification:

  • Info alert displays reminder icon
  • Success alert displays checkmark icon
  • Warning alert displays warning sign icon
  • Error alert displays danger icon
  • Question alert displays reminder icon

Button Functionality:

  • Multiple string buttons render with correct primary/default styling
  • First string button receives primary styling automatically
  • Button click returns expected value to caller

Default Button Behavior:

  • Question type without buttons shows Yes/No
  • Warning type without buttons shows OK/Cancel

API Compatibility:

  • Legacy alert('message') string syntax works
  • Modern alert({ message, type, buttons }) syntax works

Custom UI:

  • Safe tags (<strong>, <p>, <br>) render correctly
  • Custom UI appears between message and buttons

Integration:

  • All features work together (type + customUI + string buttons)
  • Response values propagate correctly
  • Multiple sequential alerts work properly

Breaking Changes

None. This implementation maintains complete backward compatibility.

Compatibility Analysis

Existing Call Patterns:

  • puter.ui.alert('message') - Continues to work identically
  • puter.ui.alert('message', [buttons]) - Continues to work identically
  • puter.ui.alert('message', [buttons], {options}) - Continues to work identically
  • UIAlert('message') - Internal usage unaffected
  • UIAlert({message, buttons}) - Internal usage unaffected

Behavioral Consistency:

  • Alerts without explicit type default to warning appearance (historical behavior)
  • Alerts without explicit buttons default to single OK button (historical behavior)
  • Button return values maintain identical format
  • Promise resolution timing unchanged
  • Window styling and positioning unchanged

Risk Assessment:

  • Low Risk: Type-aware defaults only activate when buttons are undefined, preserving explicit button configurations
  • Low Risk: Icon mapping uses existing icon assets without external dependencies
  • Low Risk: Custom UI is opt-in and has no effect on existing alerts
  • Low Risk: IPC normalization handles both legacy and modern formats transparently

Migration Path: None required. Applications can adopt new features incrementally without modifying existing alert calls.


Files Modified:

  • src/gui/src/UI/UIAlert.js - Core alert rendering logic
  • src/puter-js/src/modules/UI.js - SDK public API
  • src/gui/src/IPC.js - Cross-frame message handling

…ation

Implement comprehensive alert system supporting multiple alert types (info,
success, warning, error, question) with type-specific icons and buttons,
string array button syntax, and custom UI content injection.

Features Added:
- Multiple alert types with appropriate icons
  * Info: reminder icon
  * Success: checkmark icon
  * Warning: warning sign icon
  * Error: danger icon
  * Question: reminder icon

- Type-specific default buttons
  * Question alerts default to Yes/No
  * Warning alerts default to OK/Cancel
  * Other types default to OK only

- String array button support
  * Simple syntax: buttons: ['Save', 'Cancel']
  * Auto-converts to button objects
  * First button gets primary styling
  * Returns clicked button text as value

- Modern SDK API with backward compatibility
  * Object-style parameters: puter.ui.alert({ type, message, buttons })
  * Legacy string/array parameters still supported

- Custom UI content injection
  * Inject custom HTML between message and buttons
  * HTML sanitization with safe tag allowlist (<strong>, <p>, <br>)
  * Prevents XSS attacks while allowing basic formatting

Files modified:
- src/gui/src/UI/UIAlert.js: Icon mapping, button conversion, custom UI
- src/puter-js/src/modules/UI.js: Object-based API
- src/gui/src/IPC.js: CustomUI parameter forwarding

Breaking Changes: for exisitng alert usage

Example Usage:
  // Typed alert with string array buttons
  const choice = await puter.ui.alert({
    type: 'question',
    message: 'Save changes?',
    buttons: ['Save', "Don't Save", 'Cancel']
  });

  // Custom UI content
  puter.ui.alert({
    type: 'info',
    message: 'Upload Progress',
    customUI: '<p><strong>File:</strong> doc.pdf</p><p>75% complete</p>'
  });
@PrayagCodes PrayagCodes changed the title feat: Enhanced alert system with multiple types and flexible configur… feat: Enhanced alert system with multiple types and flexible configuration Nov 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Issue #3 - [FEATURE] Add multiple alert box types and customization options

1 participant