Notifications

The notification system provides toast-style notifications with support for multiple types, positions, and animations. Notifications are non-blocking and automatically dismiss after a specified durati

Transparent (Glass) Notifications

Notifications Module

The Notifications module provides a comprehensive toast-style notification system with support for multiple types, positions, animations, and advanced queue management. Notifications are non-blocking, automatically dismiss after a specified duration, and support both client-side and server-side triggering.

Features

  • Multiple Notification Types: Success, error, warning, info with distinct styling and icons

  • Flexible Positioning: 9-position grid system for precise screen placement

  • Auto-dismiss System: Configurable duration with automatic cleanup and queue management

  • Queue Management: Multiple notifications with smart positioning and overflow handling

  • Theme Support: Adapts to dark/light themes with customizable styling

  • Icon Support: Optional type-specific icons for visual clarity

  • Server Integration: Server-side functions to notify specific players or all players

  • State Management: Track active notifications and clear them programmatically

  • Performance Optimized: Efficient rendering and memory management

Available Functions

notify

Display a notification message with customizable options and styling.

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

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

Parameters:

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

  • options (table): Notification configuration options

    • message (string): The notification message text

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

    • title (string, optional): Notification title displayed above message

    • duration (number, optional): Display duration in milliseconds (default: from config)

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

    • showIcon (boolean, optional): Whether to show type-specific icon (default: from config)

    • playSound (boolean, optional): Whether to play notification sound (default: from config)

    • backgroundColor (string, optional): Custom background color override

    • textColor (string, optional): Custom text color override

    • borderColor (string, optional): Custom border color override

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

Example:

-- Client-side usage
local notificationId = B2Lib.UI.notify({
    type = 'success',
    title = 'Operation Complete',
    message = 'The task was completed successfully.',
    duration = 3000,
    position = 'top-right',
    showIcon = true
})

-- Server-side usage (sends to specific player)
B2Lib.UI.notify(playerId, {
    type = 'info',
    title = 'Server Message',
    message = 'Welcome to the server!',
    duration = 5000,
    position = 'top-center'
})

clearNotifications

Clear all active notifications immediately with optional fade animation.

B2Lib.UI.clearNotifications()

Returns: boolean - Success status

Example:

local success = B2Lib.UI.clearNotifications()
if success then
    print("All notifications cleared")
end

getNotifications

Get an array of all currently active notifications with their properties.

B2Lib.UI.getNotifications()

Returns: table - Array of active notification objects

  • id (number): Unique notification identifier

  • type (string): Notification type

  • title (string): Notification title

  • message (string): Notification message

  • duration (number): Display duration

  • position (string): Screen position

  • timestamp (number): Creation timestamp

  • showIcon (boolean): Icon visibility state

Example:

local activeNotifications = B2Lib.UI.getNotifications()
print('Active notifications:', #activeNotifications)

for _, notification in ipairs(activeNotifications) do
    print(string.format("ID: %d, Type: %s, Message: %s", 
        notification.id, notification.type, notification.message))
end

notifyAll (Server-side only)

Send a notification to all online players simultaneously.

B2Lib.UI.notifyAll(options)

Parameters:

  • options (table): Notification configuration options (same as notify function)

Returns: boolean - Success status

Example:

-- Server-side only
B2Lib.UI.notifyAll({
    type = 'warning',
    title = 'Server Announcement',
    message = 'Server restart in 10 minutes.',
    duration = 10000,
    position = 'center'
})

notifyPlayer (Server-side only)

Convenience function to send a notification to a specific player with simplified parameters.

B2Lib.UI.notifyPlayer(playerId, message, type, title)

Parameters:

  • playerId (number): Player server ID

  • message (string|table): Message text or full options table

  • type (string, optional): Notification type (default: 'info')

  • title (string, optional): Notification title

Returns: boolean - Success status

Example:

-- Server-side only
B2Lib.UI.notifyPlayer(playerId, "Welcome to the server!", "success", "Welcome")

-- Or with full options
B2Lib.UI.notifyPlayer(playerId, {
    message = "Custom notification",
    type = "warning",
    duration = 8000
})

clearNotificationsPlayer (Server-side only)

Clear all notifications for a specific player from server-side.

B2Lib.UI.clearNotificationsPlayer(playerId)

Parameters:

  • playerId (number): Player server ID

Returns: boolean - Success status

Example:

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

Notification Types

Success Notifications

Used for positive feedback and successful operations.

-- Client-side
B2Lib.UI.notify({
    type = 'success',
    title = 'Success',
    message = 'Player data saved successfully!',
    duration = 3000
})

-- Server-side
B2Lib.UI.notify(source, {
    type = 'success',
    title = 'Success',
    message = 'Data saved to database!',
    showIcon = true
})

Error Notifications

Used for error messages and failed operations.

-- Client-side
B2Lib.UI.notify({
    type = 'error',
    title = 'Error',
    message = 'Failed to connect to database.',
    duration = 5000
})

-- Server-side
B2Lib.UI.notify(playerId, {
    type = 'error',
    title = 'Access Denied',
    message = 'Insufficient permissions.',
    duration = 4000
})

Warning Notifications

Used for warnings and cautionary messages.

-- Client-side
B2Lib.UI.notify({
    type = 'warning',
    title = 'Warning',
    message = 'Low health detected!',
    duration = 4000
})

-- Server-side
B2Lib.UI.notify(playerId, {
    type = 'warning',
    title = 'Server Warning',
    message = 'Server restart in 5 minutes.',
    duration = 8000
})

Info Notifications

Used for general information and neutral messages.

-- Client-side
B2Lib.UI.notify({
    type = 'info',
    title = 'Information',
    message = 'New update available.',
    duration = 5000
})

-- Server-side
B2Lib.UI.notify(playerId, {
    type = 'info',
    title = 'Server Info',
    message = 'Welcome to the server!',
    position = 'top-center'
})

Positioning System

Notifications support a comprehensive 9-position grid system for precise placement:

Corner Positions:

  • 'top-left' - Upper left corner

  • 'top-right' - Upper right corner

  • 'bottom-left' - Lower left corner

  • 'bottom-right' - Lower right corner

Center Positions:

  • 'center' - Screen center

  • 'top-center' - Top center

  • 'bottom-center' - Bottom center

Side Positions:

  • 'center-left' - Left side center

  • 'center-right' - Right side center

-- Different positioning examples
B2Lib.UI.notify({
    message = 'Top right notification',
    position = 'top-right',
    type = 'info'
})

B2Lib.UI.notify({
    message = 'Center screen notification',
    position = 'center',
    type = 'warning',
    duration = 3000
})

B2Lib.UI.notify({
    message = 'Bottom left notification',
    position = 'bottom-left',
    type = 'success'
})

Server-Side Usage

Notify Specific Player

-- Notify the player who triggered an event
RegisterNetEvent('myevent')
AddEventHandler('myevent', function()
    B2Lib.UI.notify(source, {
        type = 'success',
        title = 'Event Triggered',
        message = 'Your action was successful!',
        duration = 3000
    })
end)

Notify All Players

-- Send notification to all online players
local function notifyAllPlayers(data)
    B2Lib.UI.notifyAll(data)
end

notifyAllPlayers({
    type = 'info',
    title = 'Server Announcement',
    message = 'Server restart in 10 minutes.',
    duration = 10000,
    position = 'center'
})

Conditional Server Notifications

-- Notify based on player permissions or conditions
local function notifyIfAllowed(playerId, data)
    if IsPlayerAceAllowed(playerId, 'admin') then
        B2Lib.UI.notify(playerId, {
            type = 'info',
            title = 'Admin Notice',
            message = 'You have admin privileges.',
            ...data
        })
    end
end

-- Usage
notifyIfAllowed(playerId, {
    message = "Admin panel access granted",
    duration = 5000
})

Bulk Notifications

-- Send different notifications to multiple players
local function sendBulkNotifications(playerList, notifications)
    for i, playerId in ipairs(playerList) do
        local notification = notifications[i] or notifications[1]
        B2Lib.UI.notify(playerId, notification)
    end
end

-- Usage
sendBulkNotifications({1, 2, 3}, {
    {message = "Welcome player 1!", type = "success"},
    {message = "Welcome player 2!", type = "info"},
    {message = "Welcome player 3!", type = "warning"}
})

Configuration

Configure notification defaults in config.lua:

Config.Notifications = {
    defaultDuration = 5000,        -- Default display duration in milliseconds
    defaultPosition = 'top-right', -- Default screen position
    maxVisible = 5,                -- Maximum visible notifications
    showIcon = true,               -- Show type icons by default
    playSound = true,              -- Play notification sounds
    fadeTime = 400,                -- Fade animation duration
    spacing = 10,                  -- Spacing between notifications
    enableQueue = true,            -- Enable notification queuing
    queueLimit = 20               -- Maximum queued notifications
}

Config.NotificationStyles = {
    success = {
        backgroundColor = '#10B981',
        textColor = '#FFFFFF',
        borderColor = '#059669',
        icon = 'check-circle'
    },
    error = {
        backgroundColor = '#EF4444',
        textColor = '#FFFFFF', 
        borderColor = '#DC2626',
        icon = 'x-circle'
    },
    warning = {
        backgroundColor = '#F59E0B',
        textColor = '#FFFFFF',
        borderColor = '#D97706',
        icon = 'exclamation-triangle'
    },
    info = {
        backgroundColor = '#3B82F6',
        textColor = '#FFFFFF',
        borderColor = '#2563EB',
        icon = 'information-circle'
    }
}

Advanced Examples

Conditional Notifications with Health Monitoring

-- Show different notifications based on player health
local function showHealthNotification(health)
    if health <= 20 then
        B2Lib.UI.notify({
            type = 'error',
            title = 'Critical Health',
            message = 'Seek medical attention immediately!',
            duration = 8000,
            position = 'center'
        })
    elseif health <= 50 then
        B2Lib.UI.notify({
            type = 'warning',
            title = 'Low Health',
            message = 'Consider using a health kit.',
            duration = 5000,
            position = 'top-right'
        })
    elseif health >= 100 then
        B2Lib.UI.notify({
            type = 'success',
            title = 'Full Health',
            message = 'You are at maximum health.',
            duration = 3000
        })
    end
end

-- Monitor health changes
CreateThread(function()
    local lastHealth = GetEntityHealth(PlayerPedId())
    
    while true do
        local currentHealth = GetEntityHealth(PlayerPedId())
        
        if currentHealth ~= lastHealth then
            showHealthNotification(currentHealth)
            lastHealth = currentHealth
        end
        
        Wait(1000)
    end
end)

Progress Notifications with Chaining

-- Show progress through multiple chained notifications
local function showProgressNotifications()
    B2Lib.UI.notify({
        type = 'info',
        title = 'Process Started',
        message = 'Initializing system...',
        duration = 2000,
        position = 'top-center'
    })
    
    SetTimeout(2000, function()
        B2Lib.UI.notify({
            type = 'info',
            title = 'Processing',
            message = 'Analyzing data...',
            duration = 3000,
            position = 'top-center'
        })
    end)
    
    SetTimeout(5000, function()
        B2Lib.UI.notify({
            type = 'warning',
            title = 'Almost Done',
            message = 'Finalizing results...',
            duration = 2000,
            position = 'top-center'
        })
    end)
    
    SetTimeout(7000, function()
        B2Lib.UI.notify({
            type = 'success',
            title = 'Complete',
            message = 'Process completed successfully!',
            duration = 4000,
            position = 'top-center'
        })
    end)
end

Notification with State Tracking and Management

-- Track notification IDs for advanced management
local activeNotifications = {}

local function showManagedNotification(key, options)
    -- Clear existing notification with this key
    if activeNotifications[key] then
        -- Note: Individual notification clearing requires custom implementation
        -- For now, we track and replace notifications
        print(string.format("Replacing notification: %s", key))
    end
    
    local notificationId = B2Lib.UI.notify(options)
    if notificationId then
        activeNotifications[key] = {
            id = notificationId,
            timestamp = GetGameTimer(),
            options = options
        }
        
        -- Auto-cleanup after duration
        SetTimeout(options.duration or 5000, function()
            activeNotifications[key] = nil
        end)
    end
    
    return notificationId
end

-- Usage examples
showManagedNotification('health_warning', {
    type = 'warning',
    title = 'Health Warning',
    message = 'Your health is low!',
    duration = 5000
})

showManagedNotification('money_update', {
    type = 'success',
    title = 'Money Received',
    message = 'You received $500',
    duration = 3000
})

Server-Side Event-Driven Notifications

-- Server-side: Comprehensive notification system for events
RegisterNetEvent('player:moneyChanged')
AddEventHandler('player:moneyChanged', function(amount, reason)
    local source = source
    local notificationType = 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.notify(source, {
        type = notificationType,
        title = title,
        message = message,
        duration = 4000,
        position = 'top-right'
    })
end)

RegisterNetEvent('player:levelUp')
AddEventHandler('player:levelUp', function(newLevel, skillName)
    local source = source
    
    B2Lib.UI.notify(source, {
        type = 'success',
        title = 'Level Up!',
        message = string.format('%s reached level %d', skillName, newLevel),
        duration = 6000,
        position = 'center'
    })
end)

RegisterNetEvent('server:broadcast')
AddEventHandler('server:broadcast', function(message, type, title)
    B2Lib.UI.notifyAll({
        type = type or 'info',
        title = title or 'Server Message',
        message = message,
        duration = 8000,
        position = 'top-center'
    })
end)

Custom Styled Notifications

-- Notifications with custom styling
local function showCustomNotification(options)
    local customOptions = {
        type = options.type or 'info',
        title = options.title,
        message = options.message,
        duration = options.duration or 5000,
        position = options.position or 'top-right',
        backgroundColor = options.backgroundColor,
        textColor = options.textColor,
        borderColor = options.borderColor
    }
    
    return B2Lib.UI.notify(customOptions)
end

-- Usage with custom colors
showCustomNotification({
    title = 'Custom Notification',
    message = 'This notification has custom styling',
    backgroundColor = '#8B5CF6',
    textColor = '#FFFFFF',
    borderColor = '#7C3AED',
    duration = 4000
})

Events

The notification system triggers the following events:

Client-Side Events

  • b2lib:notification:shown - Triggered when a notification is displayed

  • b2lib:notification:hidden - Triggered when a notification is dismissed

  • b2lib:notification:clicked - Triggered when a notification is clicked (if enabled)

Server-Side Events

  • b2lib:server:notify - Internal event for server-to-client notifications

  • b2lib:server:notifyAll - Internal event for broadcasting notifications

Best Practices

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

  2. Keep Messages Concise - Short, clear messages are more effective and readable

  3. Consider Duration - Important messages should have longer durations, routine messages shorter

  4. Avoid Notification Spam - Don't overwhelm users with too many notifications at once

  5. Use Positioning Wisely - Place notifications where they won't obstruct important gameplay elements

  6. Provide Context with Titles - Use titles to give immediate context to the message content

  7. Test with Different Themes - Ensure notifications are readable in both dark and light themes

  8. Handle Edge Cases - Always validate input parameters and handle failures gracefully

  9. Use Server-Side for Important Messages - Critical notifications should come from server to ensure delivery

  10. Implement Cleanup - Clear notifications when appropriate to prevent UI clutter

Troubleshooting

Notifications Not Showing

  1. Check Message Parameter: Ensure the message parameter is provided and not empty

  2. Verify B2Lib Initialization: Confirm B2Lib is properly initialized before calling functions

  3. Validate Position: Ensure the position value is valid (check Config.ValidPositions)

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

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

-- Simple test notification
B2Lib.UI.notify({
    message = "Test notification"
})

Notifications Overlapping or Positioning Issues

  1. Use Different Positions: Assign different positions for concurrent notifications

  2. Adjust maxVisible Config: Modify the maxVisible value in Config.Notifications

  3. Clear Old Notifications: Use clearNotifications() before showing new important ones

  4. Check Spacing Configuration: Verify spacing settings in notification config

Performance Issues

  1. Limit Notification Frequency: Avoid showing too many notifications rapidly

  2. Use Reasonable Durations: Set appropriate durations to prevent buildup

  3. Clear When Appropriate: Clear notifications when no longer needed

  4. Monitor Active Count: Use getNotifications() to monitor active notification count

  5. Implement Queuing: Use the built-in queue system for high-frequency notifications

Server-Side Issues

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

  2. Handle Disconnections: Account for players disconnecting during notification sending

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

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

Theme and Styling Issues

  1. Test Both Themes: Verify notifications work in both dark and light themes

  2. Check Custom Colors: Ensure custom colors have sufficient contrast

  3. Validate CSS: Check that custom styling doesn't break the notification layout

  4. Test on Different Resolutions: Verify positioning works on various screen sizes


Last updated