Alert Dialog

The Alert dialog system provides modal alert messages with support for different types, confirmation dialogs, and customizable buttons. Perfect for displaying important information and getting user confirmation.

Dark Mode Alert

alert

Display an alert dialog with customizable options and styling.

-- Client-side
B2Lib.UI.alert(options)

-- Server-side
B2Lib.UI.alert(playerId, options)

Parameters:

  • playerId (number, server-side only): Player server ID to send the alert to

  • options (table): Alert dialog configuration options

    • title (string, optional): Alert title (default: 'Alert')

    • message (string, optional): Alert message content (default: empty string)

    • type (string, optional): Alert type - 'info', 'success', 'warning', 'error', 'confirm' (default: 'info')

    • position (string, optional): Dialog position on screen (default: from config)

    • showBackground (boolean, optional): Show background overlay (default: from config)

    • showConfirm (boolean, optional): Show confirm button (default: auto-determined by type)

    • showCancel (boolean, optional): Show cancel button (default: false, true for confirm type)

    • confirmText (string, optional): Confirm button text (default: 'OK' or 'Confirm' for confirm type)

    • cancelText (string, optional): Cancel button text (default: 'Cancel')

    • icon (string, optional): Custom icon name override

    • confirmButtonType (string, optional): Confirm button styling type

    • cancelButtonType (string, optional): Cancel button styling type

    • duration (number, optional): Auto-dismiss duration in milliseconds (default: 5000 for non-interactive)

    • id (string, optional): Custom alert dialog ID (default: auto-generated)

    • size (string, optional): Dialog size - 'small', 'medium', 'large' (default: 'medium')

    • closable (boolean, optional): Whether alert can be closed with X button (default: true)

    • persistent (boolean, optional): Whether alert persists across resource restarts (default: false)

Returns: number|boolean - Alert dialog ID on success, false on failure

Example:

-- Client-side usage
local alertId = B2Lib.UI.alert({
    title = 'Information',
    message = 'This is an informational message with detailed content.',
    type = 'info',
    duration = 5000,
    showConfirm = true,
    confirmText = 'Got it'
})

-- Server-side usage (sends to specific player)
B2Lib.UI.alert(source, {
    title = 'Server Alert',
    message = 'Important server message for you.',
    type = 'warning',
    showConfirm = true,
    showCancel = false
})

hideAlert

Hide the currently active alert dialog immediately.

B2Lib.UI.hideAlert()

Returns: boolean - Success status

Example:

local success = B2Lib.UI.hideAlert()
if success then
    print("Alert dialog hidden")
end

showAlert

Alias for the alert() function providing the same functionality with identical parameters.

-- Client-side
B2Lib.UI.showAlert(options)

-- Server-side  
B2Lib.UI.showAlert(playerId, options)

Parameters: Same as alert() function

Returns: number|boolean - Alert dialog ID on success, false on failure

Example:

-- Same functionality as alert()
B2Lib.UI.showAlert({
    title = 'Notice',
    message = 'This is a notice using showAlert.',
    type = 'warning',
    confirmText = 'Understood'
})

getAlertState

Get the current state of active alert dialogs.

B2Lib.UI.getAlertState()

Returns: table - Alert state information

  • active (boolean): Whether an alert dialog is currently active

  • id (string): Current alert dialog ID

  • type (string): Current alert type

  • title (string): Current alert title

  • message (string): Current alert message

  • showConfirm (boolean): Whether confirm button is shown

  • showCancel (boolean): Whether cancel button is shown

  • duration (number): Auto-dismiss duration

  • startTime (number): Alert start timestamp

Example:

local state = B2Lib.UI.getAlertState()
if state.active then
    print(string.format("Active alert: %s - %s", state.type, state.title))
end

alertAll (Server-side only)

Send an alert dialog to all online players simultaneously.

B2Lib.UI.alertAll(options)

Parameters:

  • options (table): Alert dialog configuration options (same as alert function)

Returns: boolean - Success status

Example:

-- Server-side only
B2Lib.UI.alertAll({
    title = 'Server Announcement',
    message = 'Server will restart in 5 minutes. Please save your progress.',
    type = 'warning',
    duration = 10000,
    confirmText = 'Acknowledged'
})

hideAlertPlayer (Server-side only)

Hide alert dialog for a specific player from server-side.

B2Lib.UI.hideAlertPlayer(playerId)

Parameters:

  • playerId (number): Player server ID

Returns: boolean - Success status

Example:

-- Server-side only
B2Lib.UI.hideAlertPlayer(playerId)

Alert Types

Info Alerts

Blue-themed alerts for general information and neutral messages.

-- Client-side
B2Lib.UI.alert({
    type = 'info',
    title = 'Information',
    message = 'Server maintenance will begin in 10 minutes.',
    duration = 8000,
    icon = 'info-circle'
})

-- Server-side
B2Lib.UI.alert(playerId, {
    type = 'info',
    title = 'Server Info',
    message = 'New features have been added to the server.',
    confirmText = 'Learn More'
})

Success Alerts

Green-themed alerts for positive feedback and successful operations.

-- Client-side
B2Lib.UI.alert({
    type = 'success',
    title = 'Success',
    message = 'Your settings have been saved successfully!',
    duration = 4000,
    confirmText = 'Great!'
})

-- Server-side
B2Lib.UI.alert(source, {
    type = 'success',
    title = 'Operation Complete',
    message = 'Your request has been processed successfully.',
    showConfirm = true
})

Warning Alerts

Orange-themed alerts for warnings, cautions, and important notices.

-- Client-side
B2Lib.UI.alert({
    type = 'warning',
    title = 'Warning',
    message = 'Your inventory is almost full. Consider selling some items.',
    duration = 6000,
    confirmText = 'I Understand'
})

-- Server-side
B2Lib.UI.alert(playerId, {
    type = 'warning',
    title = 'Account Warning',
    message = 'Unusual activity detected on your account.',
    showConfirm = true,
    confirmText = 'Review Activity'
})

Error Alerts

Red-themed alerts for errors, failures, and critical issues.

-- Client-side
B2Lib.UI.alert({
    type = 'error',
    title = 'Error',
    message = 'Failed to connect to the database. Please try again later.',
    confirmText = 'Retry',
    showCancel = true,
    cancelText = 'Cancel'
})

-- Server-side
B2Lib.UI.alert(source, {
    type = 'error',
    title = 'Access Denied',
    message = 'You do not have permission to perform this action.',
    confirmText = 'Understood'
})

Confirm Alerts

Interactive confirmation dialogs with confirm/cancel buttons for user decisions.

-- Client-side
B2Lib.UI.alert({
    type = 'confirm',
    title = 'Confirm Purchase',
    message = 'Do you want to buy this vehicle for $25,000?',
    confirmText = 'Buy Now',
    cancelText = 'Cancel',
    confirmButtonType = 'primary',
    cancelButtonType = 'secondary'
})

-- Server-side
B2Lib.UI.alert(playerId, {
    type = 'confirm',
    title = 'Confirm Action',
    message = 'This action will permanently delete your character. Are you sure?',
    confirmText = 'Delete Character',
    cancelText = 'Keep Character',
    confirmButtonType = 'danger'
})

Button Configuration

Custom Button Text and Styling

-- Custom confirm button with styling
B2Lib.UI.alert({
    type = 'confirm',
    title = 'Delete Character',
    message = 'This action cannot be undone. All progress will be lost.',
    confirmText = 'Delete Forever',
    cancelText = 'Keep Character',
    confirmButtonType = 'danger',
    cancelButtonType = 'secondary',
    size = 'large'
})

-- Info alert with custom OK button
B2Lib.UI.alert({
    type = 'info',
    title = 'Welcome to the Server',
    message = 'Thank you for joining our community! Please read the rules.',
    confirmText = 'Read Rules',
    confirmButtonType = 'primary'
})

Show/Hide Button Configuration

-- Alert with only confirm button
B2Lib.UI.alert({
    title = 'Important Notice',
    message = 'Please read the updated terms of service.',
    showConfirm = true,
    showCancel = false,
    confirmText = 'I Agree',
    type = 'info'
})

-- Alert with both buttons (non-confirm type)
B2Lib.UI.alert({
    type = 'warning',
    title = 'Unsaved Changes',
    message = 'You have unsaved changes that will be lost.',
    showConfirm = true,
    showCancel = true,
    confirmText = 'Save Changes',
    cancelText = 'Discard Changes'
})

-- Alert with no buttons (auto-dismiss only)
B2Lib.UI.alert({
    type = 'success',
    title = 'Auto-Save',
    message = 'Your progress has been automatically saved.',
    showConfirm = false,
    showCancel = false,
    duration = 3000
})

Dialog Sizing and Positioning

Size Variants

-- Small alert for brief messages
B2Lib.UI.alert({
    title = 'Quick Notice',
    message = 'Task completed.',
    type = 'success',
    size = 'small',
    duration = 2000
})

-- Medium alert (default)
B2Lib.UI.alert({
    title = 'Standard Alert',
    message = 'This is a standard sized alert with normal content.',
    type = 'info',
    size = 'medium'
})

-- Large alert for detailed content
B2Lib.UI.alert({
    title = 'Detailed Information',
    message = 'This is a large alert that can contain more detailed information and longer messages that require more space to display properly.',
    type = 'info',
    size = 'large',
    confirmText = 'Got It'
})

Position Configuration

-- Center position (default)
B2Lib.UI.alert({
    title = 'Centered Alert',
    message = 'This alert appears in the center of the screen.',
    position = 'center',
    type = 'info'
})

-- Top center for non-intrusive alerts
B2Lib.UI.alert({
    title = 'Non-Intrusive',
    message = 'This alert appears at the top center.',
    position = 'top-center',
    type = 'info',
    duration = 4000
})

-- Custom positioning for specific use cases
B2Lib.UI.alert({
    title = 'Corner Alert',
    message = 'This alert appears in the top-right corner.',
    position = 'top-right',
    type = 'warning',
    size = 'small'
})

Server-Side Usage

Alert Specific Player

-- Alert for the player who triggered an event
RegisterNetEvent('player:achievement')
AddEventHandler('player:achievement', function(achievementName)
    local source = source
    
    B2Lib.UI.alert(source, {
        type = 'success',
        title = 'Achievement Unlocked!',
        message = string.format('You have unlocked: %s', achievementName),
        confirmText = 'Awesome!',
        duration = 8000,
        size = 'large'
    })
end)

Alert All Players

-- Send alert to all online players
local function alertAllPlayers(data)
    B2Lib.UI.alertAll(data)
end

-- Server announcement example
alertAllPlayers({
    type = 'warning',
    title = 'Server Restart',
    message = 'The server will restart in 10 minutes for maintenance.',
    confirmText = 'Acknowledged',
    duration = 15000,
    persistent = true
})

Conditional Server Alerts

-- Alert based on player permissions or conditions
local function conditionalAlert(playerId, alertType, data)
    if alertType == 'admin' then
        if IsPlayerAceAllowed(playerId, 'admin') then
            B2Lib.UI.alert(playerId, {
                type = 'info',
                title = 'Admin Notice',
                message = 'You have administrative privileges.',
                confirmText = 'Access Admin Panel',
                ...data
            })
        else
            B2Lib.UI.alert(playerId, {
                type = 'error',
                title = 'Access Denied',
                message = 'Administrative privileges required.',
                confirmText = 'Understood'
            })
        end
    end
end

-- Usage
conditionalAlert(playerId, 'admin', {
    message = "Welcome to the admin panel",
    duration = 5000
})

Bulk Alert Operations

-- Send different alerts to multiple players
local function sendBulkAlerts(playerList, alerts)
    for i, playerId in ipairs(playerList) do
        local alert = alerts[i] or alerts[1]
        B2Lib.UI.alert(playerId, alert)
    end
end

-- Usage
sendBulkAlerts({1, 2, 3}, {
    {title = "Welcome Player 1!", message = "Custom message 1", type = "success"},
    {title = "Welcome Player 2!", message = "Custom message 2", type = "info"},
    {title = "Welcome Player 3!", message = "Custom message 3", type = "warning"}
})

Event System

The Alert system provides comprehensive event handling for user interactions:

b2lib:alert-response

Triggered when user interacts with alert buttons or when alerts auto-dismiss.

AddEventHandler('b2lib:alert-response', function(data)
    print('Alert Response Data:', json.encode(data))
    
    if data.action == 'confirm' then
        print('User confirmed the alert')
        -- Handle confirmation logic
        
    elseif data.action == 'cancel' then
        print('User cancelled the alert')
        -- Handle cancellation logic
        
    elseif data.action == 'dismiss' then
        print('Alert was auto-dismissed')
        -- Handle auto-dismiss logic
        
    elseif data.action == 'close' then
        print('Alert was closed via X button')
        -- Handle close button logic
    end
    
    -- Access alert metadata
    print('Alert ID:', data.alertId)
    print('Alert Type:', data.type)
    print('Alert Title:', data.title)
    print('Response Time:', data.responseTime) -- Time taken to respond
end)

b2lib:alert-shown

Triggered when an alert dialog is displayed.

AddEventHandler('b2lib:alert-shown', function(data)
    print('Alert shown:', data.alertId, data.type, data.title)
    
    -- Track alert analytics
    -- Start timers
    -- Update UI state
end)

b2lib:alert-hidden

Triggered when an alert dialog is hidden or dismissed.

AddEventHandler('b2lib:alert-hidden', function(data)
    print('Alert hidden:', data.alertId, data.reason)
    
    -- Cleanup operations
    -- Reset UI state
    -- Log alert completion
end)

Configuration

Configure alert dialog defaults in config.lua:

Config.Alert = {
    position = 'center',              -- Default position
    showBackground = true,            -- Show background overlay by default
    enableConfirm = true,             -- Enable confirmation dialogs
    defaultDuration = 5000,           -- Default auto-dismiss duration
    defaultSize = 'medium',           -- Default dialog size
    enableKeyboardNav = true,         -- Enable keyboard navigation
    enableSounds = true,              -- Enable alert sounds
    fadeTime = 300,                   -- Fade in/out duration
    maxConcurrent = 1,                -- Maximum concurrent alerts
    queueAlerts = true                -- Queue alerts when max reached
}

Config.AlertStyles = {
    sizes = {
        small = { width: '300px', padding: '16px' },
        medium = { width: '400px', padding: '24px' },
        large = { width: '500px', padding: '32px' }
    },
    
    types = {
        info = {
            backgroundColor = '#3B82F6',
            borderColor = '#2563EB',
            iconColor = '#FFFFFF',
            icon = 'info-circle'
        },
        success = {
            backgroundColor = '#10B981',
            borderColor = '#059669',
            iconColor = '#FFFFFF',
            icon = 'check-circle'
        },
        warning = {
            backgroundColor = '#F59E0B',
            borderColor = '#D97706',
            iconColor = '#FFFFFF',
            icon = 'exclamation-triangle'
        },
        error = {
            backgroundColor = '#EF4444',
            borderColor = '#DC2626',
            iconColor = '#FFFFFF',
            icon = 'x-circle'
        },
        confirm = {
            backgroundColor = '#6B7280',
            borderColor = '#4B5563',
            iconColor = '#FFFFFF',
            icon = 'question-circle'
        }
    },
    
    buttons = {
        primary = { backgroundColor: '#3B82F6', textColor: '#FFFFFF' },
        secondary = { backgroundColor: '#6B7280', textColor: '#FFFFFF' },
        success = { backgroundColor: '#10B981', textColor: '#FFFFFF' },
        danger = { backgroundColor: '#EF4444', textColor: '#FFFFFF' },
        warning = { backgroundColor: '#F59E0B', textColor: '#FFFFFF' }
    }
}

Config.ComponentStyles.alertDialog = {
    width = '400px',                  -- Dialog width
    padding = '24px',                 -- Internal padding
    borderRadius = 'xl',              -- Border radius
    shadow = 'xl',                    -- Shadow style
    borderWidth = '1px',              -- Border width
    backdropBlur = true,              -- Enable backdrop blur
    
    title = {
        fontSize = 'lg',              -- Title font size
        fontWeight = 'semibold',      -- Title font weight
        marginBottom = '12px'         -- Title bottom margin
    },
    
    message = {
        fontSize = 'sm',              -- Message font size
        fontWeight = 'normal',        -- Message font weight
        lineHeight = 'relaxed',       -- Message line height
        marginBottom = '20px'         -- Message bottom margin
    },
    
    icon = {
        size = '24px',                -- Icon size
        marginBottom = '16px'         -- Icon bottom margin
    },
    
    button = {
        padding = '10px 20px',        -- Button padding
        borderRadius = 'lg',          -- Button border radius
        fontSize = 'sm',              -- Button font size
        fontWeight = 'medium',        -- Button font weight
        spacing = '12px',             -- Button spacing
        hoverTransition = 'fast'      -- Button hover transition
    }
}

Advanced Examples

Confirmation with Callback Handling

-- Handle confirmation responses with detailed logic
local function deleteItem(itemId, itemName)
    B2Lib.UI.alert({
        type = 'confirm',
        title = 'Delete Item',
        message = string.format('Are you sure you want to delete "%s"? This action cannot be undone.', itemName),
        confirmText = 'Delete',
        cancelText = 'Cancel',
        confirmButtonType = 'danger',
        size = 'medium'
    })
end

AddEventHandler('b2lib:alert-response', function(data)
    if data.action == 'confirm' and data.title == 'Delete Item' then
        -- User confirmed deletion
        print('Deleting item...')
        
        -- Simulate deletion process
        B2Lib.UI.progress({
            duration = 2000,
            label = 'Deleting item...',
            type = 'linear'
        })
        
        SetTimeout(2000, function()
            B2Lib.UI.alert({
                type = 'success',
                title = 'Item Deleted',
                message = 'The item has been deleted successfully.',
                duration = 3000,
                confirmText = 'OK'
            })
        end)
        
    elseif data.action == 'cancel' and data.title == 'Delete Item' then
        print('Deletion cancelled by user')
        
        B2Lib.UI.notify({
            type = 'info',
            message = 'Deletion cancelled',
            duration = 2000
        })
    end
end)

-- Usage
deleteItem(123, "Rare Weapon")

Multi-Step Confirmation Process

-- Multi-step confirmation for dangerous actions
local confirmationState = {
    step = 1,
    action = nil,
    data = nil
}

local function confirmDangerousAction(action, actionData)
    confirmationState.action = action
    confirmationState.data = actionData
    confirmationState.step = 1
    
    B2Lib.UI.alert({
        type = 'warning',
        title = 'Warning',
        message = 'This action is potentially dangerous and may have serious consequences. Are you sure you want to continue?',
        confirmText = 'Continue',
        cancelText = 'Cancel',
        size = 'large'
    })
end

AddEventHandler('b2lib:alert-response', function(data)
    if confirmationState.step == 1 and data.action == 'confirm' then
        -- First confirmation passed, show second
        confirmationState.step = 2
        
        B2Lib.UI.alert({
            type = 'error',
            title = 'Final Confirmation',
            message = string.format('You are about to execute: %s\n\nThis action CANNOT be undone. Are you absolutely certain?', confirmationState.action),
            confirmText = 'Yes, I Understand',
            cancelText = 'Cancel',
            confirmButtonType = 'danger',
            size = 'large'
        })
        
    elseif confirmationState.step == 2 and data.action == 'confirm' then
        -- Final confirmation, execute action
        print('Executing dangerous action:', confirmationState.action)
        
        -- Show progress
        B2Lib.UI.progress({
            duration = 3000,
            label = 'Executing action...',
            type = 'linear',
            canCancel = false
        })
        
        SetTimeout(3000, function()
            B2Lib.UI.alert({
                type = 'success',
                title = 'Action Complete',
                message = 'The action has been executed successfully.',
                duration = 5000,
                confirmText = 'OK'
            })
        end)
        
        -- Reset state
        confirmationState = { step = 1, action = nil, data = nil }
        
    else
        -- Cancelled at any step
        print('Action cancelled')
        confirmationState = { step = 1, action = nil, data = nil }
        
        B2Lib.UI.notify({
            type = 'info',
            message = 'Action cancelled',
            duration = 2000
        })
    end
end)

-- Usage
confirmDangerousAction('Reset Database', { tables: ['users', 'vehicles'] })

Timed Alerts with Dynamic Content

-- Alert with countdown timer
local function showCountdownAlert(message, countdownSeconds)
    local remainingTime = countdownSeconds
    
    local function updateAlert()
        if remainingTime > 0 then
            B2Lib.UI.alert({
                type = 'warning',
                title = 'Countdown Alert',
                message = string.format('%s\n\nTime remaining: %d seconds', message, remainingTime),
                duration = 1000,
                showConfirm = false,
                showCancel = false,
                id = 'countdown-alert'
            })
            
            remainingTime = remainingTime - 1
            SetTimeout(1000, updateAlert)
        else
            B2Lib.UI.alert({
                type = 'error',
                title = 'Time Expired',
                message = 'The countdown has reached zero!',
                confirmText = 'OK',
                size = 'medium'
            })
        end
    end
    
    updateAlert()
end

-- Auto-dismissing alerts with custom durations
local function showTimedAlert(message, duration, type)
    B2Lib.UI.alert({
        type = type or 'info',
        title = 'Timed Message',
        message = message,
        duration = duration or 5000,
        showConfirm = false,
        showCancel = false
    })
end

-- Persistent alert that requires acknowledgment
B2Lib.UI.alert({
    type = 'error',
    title = 'Critical Error',
    message = 'A critical error has occurred that requires your immediate attention.',
    duration = nil, -- No auto-dismiss
    confirmText = 'Acknowledge',
    closable = false, -- Cannot be closed with X button
    persistent = true
})

-- Usage
showCountdownAlert("Server restart incoming!", 10)
showTimedAlert("Auto-save completed", 3000, "success")

Custom Alert Types and Styling

-- Create custom styled alerts for specific use cases
local function showAchievementAlert(achievementData)
    B2Lib.UI.alert({
        title = 'Achievement Unlocked!',
        message = string.format('πŸ† %s\n\n%s\n\nReward: %s XP', 
            achievementData.name, 
            achievementData.description, 
            achievementData.xp),
        type = 'success',
        icon = 'trophy',
        confirmText = 'Awesome!',
        confirmButtonType = 'primary',
        size = 'large',
        duration = 8000
    })
end

local function showLevelUpAlert(newLevel, skillName)
    B2Lib.UI.alert({
        title = 'Level Up!',
        message = string.format('πŸŽ‰ Congratulations!\n\nYour %s skill has reached level %d!', skillName, newLevel),
        type = 'success',
        confirmText = 'Continue',
        size = 'medium',
        duration = 6000
    })
end

local function showErrorAlert(errorCode, errorMessage)
    B2Lib.UI.alert({
        title = string.format('Error %s', errorCode),
        message = string.format('An error has occurred:\n\n%s\n\nPlease contact support if this persists.', errorMessage),
        type = 'error',
        confirmText = 'Report Bug',
        cancelText = 'Dismiss',
        showCancel = true,
        confirmButtonType = 'danger',
        size = 'large'
    })
end

-- Usage
showAchievementAlert({
    name = "First Steps",
    description = "Complete your first mission",
    xp = 100
})

showLevelUpAlert(25, "Driving")

showErrorAlert("DB001", "Database connection failed")

Server-Side Event-Driven Alerts

-- Server-side: Comprehensive alert system for events
RegisterNetEvent('player:moneyChanged')
AddEventHandler('player:moneyChanged', function(amount, reason)
    local source = source
    local alertType = amount > 0 and 'success' or 'warning'
    local title = amount > 0 and 'Money Received' or 'Money Spent'
    local message = string.format('$%d - %s', math.abs(amount), reason or 'Unknown')
    
    B2Lib.UI.alert(source, {
        type = alertType,
        title = title,
        message = message,
        duration = 4000,
        confirmText = 'OK'
    })
end)

RegisterNetEvent('player:banned')
AddEventHandler('player:banned', function(reason, duration)
    local source = source
    
    B2Lib.UI.alert(source, {
        type = 'error',
        title = 'Account Suspended',
        message = string.format('Your account has been suspended.\n\nReason: %s\nDuration: %s', reason, duration),
        confirmText = 'Understood',
        closable = false,
        persistent = true,
        size = 'large'
    })
end)

RegisterNetEvent('server:maintenance')
AddEventHandler('server:maintenance', function(minutes)
    B2Lib.UI.alertAll({
        type = 'warning',
        title = 'Scheduled Maintenance',
        message = string.format('The server will undergo maintenance in %d minutes. Please save your progress.', minutes),
        confirmText = 'Acknowledged',
        duration = 15000,
        size = 'large'
    })
end)

Alert Queue Management

-- Queue system for multiple alerts
local alertQueue = {}
local isProcessingQueue = false

local function queueAlert(alertData)
    table.insert(alertQueue, alertData)
    processAlertQueue()
end

local function processAlertQueue()
    if isProcessingQueue or #alertQueue == 0 then
        return
    end
    
    isProcessingQueue = true
    local alertData = table.remove(alertQueue, 1)
    
    B2Lib.UI.alert(alertData)
    
    -- Wait for alert to be dismissed before showing next
    AddEventHandler('b2lib:alert-response', function(data)
        isProcessingQueue = false
        
        -- Process next alert in queue
        SetTimeout(500, function()
            processAlertQueue()
        end)
    end)
end

-- Usage
queueAlert({
    title = "First Alert",
    message = "This is the first alert in the queue",
    type = "info"
})

queueAlert({
    title = "Second Alert", 
    message = "This is the second alert in the queue",
    type = "success"
})

queueAlert({
    title = "Third Alert",
    message = "This is the third alert in the queue", 
    type = "warning"
})

Best Practices

  1. Use Appropriate Types - Match alert type to the message context for better user experience

  2. Keep Messages Clear - Use concise, actionable language that users can quickly understand

  3. Provide Context - Use descriptive titles to set proper expectations for the alert content

  4. Handle Responses Properly - Always listen for alert response events and handle them appropriately

  5. Use Confirmations Wisely - Reserve confirm type for destructive or important actions only

  6. Set Appropriate Durations - Important messages should stay longer, routine messages shorter

  7. Test User Flows - Ensure alert sequences make logical sense to users

  8. Avoid Alert Spam - Don't overwhelm users with too many alerts at once

  9. Consider Accessibility - Ensure alerts work with keyboard navigation and screen readers

  10. Use Server-Side for Critical Alerts - Important alerts should come from server to ensure delivery

Troubleshooting

Alert Not Showing

  1. Check B2Lib Initialization: Verify B2Lib is properly initialized before calling functions

  2. Check Modal Conflicts: Ensure no other modal dialogs are currently active

  3. Validate Parameters: Ensure all required parameters are provided and valid

  4. Check Console Errors: Look for error messages from B2Lib.Debug in the console

  5. Test with Simple Example: Try a basic alert without optional parameters

-- Simple test alert
B2Lib.UI.alert({
    title = "Test Alert",
    message = "This is a test alert"
})

Buttons Not Working

  1. Verify Event Handlers: Ensure event handlers are registered before showing alerts

  2. Check JavaScript Errors: Look for errors in the browser console (F12)

  3. Test NUI Focus: Ensure NUI focus is properly managed and not blocked

  4. Validate Button Configuration: Check showConfirm and showCancel settings

  5. Test with Minimal Setup: Start with a simple confirmation alert

Auto-dismiss Not Working

  1. Check Duration Setting: Ensure duration is set correctly and is a positive number

  2. Verify Alert Type: Confirm alert type allows auto-dismiss (non-interactive alerts)

  3. Check for Conflicts: Ensure no other code is hiding the alert prematurely

  4. Test Timing: Verify there are no timing conflicts with other UI elements

  5. Monitor State: Use getAlertState() to check alert status

Event Handling Issues

  1. Register Handlers Early: Register event handlers before showing any alerts

  2. Check Handler Logic: Verify event handler functions don't contain errors

  3. Validate Event Data: Ensure event data structure matches expectations

  4. Test Incrementally: Start with minimal event handlers and add complexity

  5. Debug Event Flow: Add logging to track event triggering and handling

Server-Side Issues

  1. Check Player Validity: Ensure player ID is valid before sending alerts

  2. Handle Disconnections: Account for players disconnecting during alert display

  3. Validate Permissions: Check player permissions before sending sensitive alerts

  4. Test Event Registration: Verify server events are properly registered and triggered

  5. Monitor Network Issues: Check for network problems affecting client-server communication

Performance Issues

  1. Limit Concurrent Alerts: Avoid showing multiple alerts simultaneously

  2. Use Alert Queuing: Implement queuing system for multiple alerts

  3. Optimize Event Handlers: Ensure event handlers are efficient and don't block

  4. Monitor Memory Usage: Check for memory leaks with long-running alerts

  5. Test with Multiple Players: Verify performance with many concurrent users

Last updated