Theme Settings

The Settings module provides comprehensive theme management, UI customization, and user preference systems for B2Lib. It offers sophisticated visual theme switching, persistent configuration storage, advanced layout positioning, real-time preview capabilities, and extensive customization options for creating personalized user experiences with seamless integration across all UI components.

Dark Main Theme Page
Dark Component Styling Page
Dark Placement Selection Page
Dark UI Element Positioning Page
Dark Live Editing Panel

setTheme

Set the current theme mode for all B2Lib UI components with advanced options and validation.

-- Client-side
B2Lib.UI.setTheme(mode, options)

-- Server-side (via exports)
exports.b2lib:setPlayerTheme(playerId, mode, options)

Parameters:

  • mode (string, required): Theme mode - 'light', 'dark', 'transparent', or 'custom'

  • options (table, optional): Advanced theme configuration options

  • playerId (number, server-side only): Player server ID to set theme for

Configuration Options:

  • persist (boolean, optional): Save theme preference to server (default: true)

  • animate (boolean, optional): Animate theme transition (default: true)

  • duration (number, optional): Animation duration in milliseconds (default: 300)

  • customColors (table, optional): Custom color overrides for theme

  • components (table, optional): Component-specific theme overrides

  • accessibility (table, optional): Accessibility-specific theme adjustments

  • preview (boolean, optional): Preview mode without saving (default: false)

Returns: boolean - Success status indicating theme application completion

Example:

-- Basic theme setting
local success = B2Lib.UI.setTheme('dark')

-- Advanced theme setting with options
B2Lib.UI.setTheme('dark', {
    persist = true,
    animate = true,
    duration = 500,
    customColors = {
        primary = '#1e293b',
        accent = '#3b82f6',
        success = '#10b981',
        warning = '#f59e0b',
        error = '#ef4444'
    },
    components = {
        notifications = { opacity = 0.95 },
        menus = { borderRadius = '12px' }
    },
    accessibility = {
        highContrast = false,
        reducedMotion = false
    }
})

-- Custom theme with comprehensive configuration
B2Lib.UI.setTheme('custom', {
    customColors = {
        primary = '#0f172a',
        secondary = '#1e293b',
        tertiary = '#334155',
        accent = '#6366f1',
        success = '#059669',
        warning = '#d97706',
        error = '#dc2626',
        text = '#f8fafc',
        textSecondary = '#cbd5e1',
        border = '#475569',
        shadow = 'rgba(0,0,0,0.25)'
    },
    components = {
        notifications = {
            borderRadius = '8px',
            backdropBlur = '12px',
            shadow = '0 10px 25px rgba(0,0,0,0.3)'
        },
        progress = {
            height = '6px',
            borderRadius = '3px',
            glowEffect = true
        }
    }
})

-- Server-side theme setting
exports.b2lib:setPlayerTheme(playerId, 'dark', {
    persist = true,
    customColors = {
        accent = '#8b5cf6'
    }
})

-- Preview theme without saving
B2Lib.UI.setTheme('light', {
    preview = true,
    duration = 200
})

getTheme

Get comprehensive information about the currently active theme including mode, colors, and configuration.

B2Lib.UI.getTheme(detailed)

Parameters:

  • detailed (boolean, optional): Return detailed theme information including colors and settings (default: false)

Returns: string|table - Current theme mode or detailed theme information object

  • mode (string): Current theme mode ('dark', 'light', 'transparent', 'custom')

  • colors (table): Current color palette with all theme colors

  • settings (table): Current theme settings and configuration

  • customizations (table): User customizations and overrides

  • accessibility (table): Accessibility settings and adjustments

Example:

-- Get current theme mode
local currentTheme = B2Lib.UI.getTheme()
print('Current theme:', currentTheme) -- 'dark', 'light', 'transparent', or 'custom'

-- Get detailed theme information
local themeInfo = B2Lib.UI.getTheme(true)
print('Theme mode:', themeInfo.mode)
print('Primary color:', themeInfo.colors.primary)
print('Accent color:', themeInfo.colors.accent)
print('Animation duration:', themeInfo.settings.animationDuration)

-- Use theme in conditional logic
if B2Lib.UI.getTheme() == 'dark' then
    -- Dark theme specific logic
    print('Using dark theme')
    applyDarkThemeLogic()
elseif B2Lib.UI.getTheme() == 'custom' then
    -- Custom theme logic
    local colors = B2Lib.UI.getTheme(true).colors
    applyCustomThemeLogic(colors)
end

-- Check for accessibility features
local themeDetails = B2Lib.UI.getTheme(true)
if themeDetails.accessibility.highContrast then
    enableHighContrastMode()
end

openThemeSettings

Open the comprehensive theme settings interface with advanced customization options and real-time preview.

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

-- Server-side (via exports)
exports.b2lib:openPlayerThemeSettings(playerId, options)

Parameters:

  • options (table, optional): Settings interface configuration options

  • playerId (number, server-side only): Player server ID to open settings for

Configuration Options:

  • tab (string, optional): Initial tab to open ('themes', 'colors', 'layout', 'components', 'accessibility') (default: 'themes')

  • component (string, optional): Focus on specific component settings

  • readonly (boolean, optional): Open in read-only mode for viewing (default: false)

  • adminMode (boolean, optional): Enable admin-only settings and options (default: false)

  • presets (table, optional): Custom preset themes to include

  • restrictions (table, optional): Restrict access to certain settings categories

  • callbacks (table, optional): Custom callback functions for settings events

Returns: boolean - Success status indicating settings interface opening

Features:

  • Theme Modes: Switch between light, dark, transparent, and custom themes with live preview

  • Color Customization: Advanced color picker with HSL controls, palette management, and accessibility validation

  • Typography Settings: Font family selection, size scaling, weight adjustment, and text rendering options

  • Layout Positioning: Drag-and-drop positioning for UI elements with grid snapping and alignment guides

  • Animation Controls: Configure animation speeds, easing functions, and transition effects with performance optimization

  • Component Styling: Individual customization for each UI component with advanced styling options and presets

  • Accessibility Options: High contrast modes, reduced motion, screen reader support, and visual accommodations

  • Import/Export: Settings backup, sharing, and restoration with version compatibility and validation

  • Real-Time Preview: Instant visual feedback for all customization changes with live component updates

  • Preset Management: Save, load, and share custom theme presets with community integration

Example:

-- Basic theme settings
local success = B2Lib.UI.openThemeSettings()

-- Open specific tab
B2Lib.UI.openThemeSettings({
    tab = 'colors'
})

-- Focus on specific component
B2Lib.UI.openThemeSettings({
    tab = 'components',
    component = 'notifications'
})

-- Admin mode with full access
B2Lib.UI.openThemeSettings({
    adminMode = true,
    tab = 'themes',
    presets = {
        {
            name = 'Server Theme',
            mode = 'custom',
            colors = getServerThemeColors(),
            locked = true
        }
    }
})

-- Restricted settings for specific users
B2Lib.UI.openThemeSettings({
    restrictions = {
        colors = false,        -- Disable color customization
        layout = true,         -- Allow layout changes
        components = false     -- Disable component styling
    },
    callbacks = {
        onSave = function(settings)
            print('Settings saved:', json.encode(settings))
            logUserSettingsChange(PlayerId(), settings)
        end,
        onReset = function()
            print('Settings reset to defaults')
            notifyAdmins('User reset theme settings: ' .. GetPlayerName(PlayerId()))
        end
    }
})

-- Server-side settings opening
exports.b2lib:openPlayerThemeSettings(playerId, {
    tab = 'accessibility',
    readonly = false,
    adminMode = isPlayerAdmin(playerId)
})

-- Bind to command
RegisterCommand('themesettings', function()
    B2Lib.UI.openThemeSettings()
end)

-- Bind to key
RegisterKeyMapping('themesettings', 'Open Theme Settings', 'keyboard', 'F7')

saveSettings

Save current theme and UI settings to server with validation and backup functionality.

-- Client-side
B2Lib.UI.saveSettings(settings, options)

-- Server-side (via exports)
exports.b2lib:savePlayerSettings(playerId, settings, options)

Parameters:

  • settings (table, optional): Specific settings to save (default: current settings)

  • options (table, optional): Save operation configuration

  • playerId (number, server-side only): Player server ID to save settings for

Configuration Options:

  • backup (boolean, optional): Create backup before saving (default: true)

  • validate (boolean, optional): Validate settings before saving (default: true)

  • notify (boolean, optional): Show save confirmation notification (default: true)

  • sync (boolean, optional): Synchronize with other connected clients (default: false)

Returns: boolean - Success status indicating settings save completion

Example:

-- Save current settings
local success = B2Lib.UI.saveSettings()

-- Save specific settings with options
B2Lib.UI.saveSettings({
    theme = 'dark',
    colors = {
        accent = '#3b82f6'
    },
    layout = {
        notifications = 'top-right'
    }
}, {
    backup = true,
    notify = true
})

-- Server-side save
exports.b2lib:savePlayerSettings(playerId, playerSettings, {
    validate = true,
    backup = true
})

loadSettings

Load saved theme and UI settings from server with fallback and migration support.

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

-- Server-side (via exports)
exports.b2lib:loadPlayerSettings(playerId, options)

Parameters:

  • options (table, optional): Load operation configuration

  • playerId (number, server-side only): Player server ID to load settings for

Configuration Options:

  • fallback (table, optional): Fallback settings if load fails

  • migrate (boolean, optional): Migrate old settings format (default: true)

  • apply (boolean, optional): Automatically apply loaded settings (default: true)

  • notify (boolean, optional): Show load status notification (default: false)

Returns: table|boolean - Loaded settings object or false if failed

Example:

-- Load settings with auto-apply
local settings = B2Lib.UI.loadSettings()

-- Load with custom options
local settings = B2Lib.UI.loadSettings({
    fallback = {
        theme = 'dark',
        layout = getDefaultLayout()
    },
    migrate = true,
    apply = true,
    notify = true
})

-- Server-side load
local playerSettings = exports.b2lib:loadPlayerSettings(playerId, {
    migrate = true
})

resetSettings

Reset theme and UI settings to default values with selective reset options.

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

-- Server-side (via exports)
exports.b2lib:resetPlayerSettings(playerId, options)

Parameters:

  • options (table, optional): Reset operation configuration

  • playerId (number, server-side only): Player server ID to reset settings for

Configuration Options:

  • categories (table, optional): Specific categories to reset ('theme', 'colors', 'layout', 'components')

  • confirm (boolean, optional): Show confirmation dialog (default: true)

  • backup (boolean, optional): Create backup before reset (default: true)

  • apply (boolean, optional): Automatically apply reset settings (default: true)

Returns: boolean - Success status indicating settings reset completion

Example:

-- Reset all settings with confirmation
local success = B2Lib.UI.resetSettings()

-- Reset specific categories
B2Lib.UI.resetSettings({
    categories = { 'theme', 'colors' },
    confirm = true,
    backup = true
})

-- Silent reset without confirmation
B2Lib.UI.resetSettings({
    confirm = false,
    backup = false
})

-- Server-side reset
exports.b2lib:resetPlayerSettings(playerId, {
    categories = { 'layout' },
    backup = true
})

exportSettings

Export current settings to shareable format with encryption and validation.

B2Lib.UI.exportSettings(options)

Parameters:

  • options (table, optional): Export operation configuration

Configuration Options:

  • format (string, optional): Export format ('json', 'base64', 'encrypted') (default: 'json')

  • categories (table, optional): Specific categories to export

  • compress (boolean, optional): Compress exported data (default: true)

  • metadata (boolean, optional): Include metadata and version info (default: true)

Returns: string - Exported settings data in specified format

Example:

-- Basic export
local exportData = B2Lib.UI.exportSettings()

-- Export specific categories
local themeExport = B2Lib.UI.exportSettings({
    categories = { 'theme', 'colors' },
    format = 'base64',
    compress = true
})

-- Export for sharing
local shareData = B2Lib.UI.exportSettings({
    format = 'encrypted',
    metadata = true
})

importSettings

Import settings from exported data with validation and conflict resolution.

B2Lib.UI.importSettings(data, options)

Parameters:

  • data (string, required): Exported settings data to import

  • options (table, optional): Import operation configuration

Configuration Options:

  • merge (boolean, optional): Merge with existing settings (default: false)

  • validate (boolean, optional): Validate imported data (default: true)

  • apply (boolean, optional): Automatically apply imported settings (default: true)

  • backup (boolean, optional): Create backup before import (default: true)

  • conflicts (string, optional): Conflict resolution strategy ('overwrite', 'merge', 'skip') (default: 'overwrite')

Returns: boolean - Success status indicating settings import completion

Example:

-- Basic import
local success = B2Lib.UI.importSettings(exportedData)

-- Import with merge
B2Lib.UI.importSettings(exportedData, {
    merge = true,
    conflicts = 'merge',
    backup = true
})

-- Import with validation
B2Lib.UI.importSettings(sharedSettings, {
    validate = true,
    apply = false,  -- Don't auto-apply, let user review
    backup = true
})

Theme Modes

Dark Theme

The default theme with dark backgrounds and light text, optimized for low-light environments.

B2Lib.UI.setTheme('dark')

Characteristics:

  • Dark backgrounds (#1a1a1a, #2d2d2d)

  • Light text (#ffffff, #e5e5e5)

  • Subtle borders and shadows

  • Reduced eye strain in dark environments

  • Professional appearance

Light Theme

A bright theme with light backgrounds and dark text, suitable for well-lit environments.

B2Lib.UI.setTheme('light')

Characteristics:

  • Light backgrounds (#ffffff, #f5f5f5)

  • Dark text (#1a1a1a, #333333)

  • Clean, modern appearance

  • High contrast for readability

  • Suitable for daytime use

Transparent Theme

A semi-transparent theme that blends with the game environment.

B2Lib.UI.setTheme('transparent')

Characteristics:

  • Semi-transparent backgrounds

  • Subtle borders and effects

  • Minimal visual interference

  • Immersive gaming experience

  • Maintains readability

Events

The Settings system triggers events for theme changes and settings updates:

b2lib:theme-changed

Triggered when the theme is changed.

AddEventHandler('b2lib:theme-changed', function(newTheme)
    print('Theme changed to:', newTheme)
    
    -- Update your script's UI based on theme
    if newTheme == 'dark' then
        -- Apply dark theme styles to custom UI
        updateCustomUITheme('dark')
    elseif newTheme == 'light' then
        -- Apply light theme styles to custom UI
        updateCustomUITheme('light')
    elseif newTheme == 'transparent' then
        -- Apply transparent theme styles to custom UI
        updateCustomUITheme('transparent')
    end
end)

b2lib:theme-settings-opened

Triggered when the theme settings interface is opened.

AddEventHandler('b2lib:theme-settings-opened', function()
    print('Theme settings opened')
    
    -- Pause certain game functions while settings are open
    pauseGameFeatures()
end)

b2lib:theme-settings-closed

Triggered when the theme settings interface is closed.

AddEventHandler('b2lib:theme-settings-closed', function()
    print('Theme settings closed')
    
    -- Resume game functions
    resumeGameFeatures()
end)

b2lib:theme-settings-saved

Triggered when theme settings are successfully saved.

AddEventHandler('b2lib:theme-settings-saved', function(settings)
    print('Theme settings saved:', json.encode(settings))
    
    -- Apply any custom logic based on saved settings
    applyCustomSettings(settings)
end)

b2lib:theme-settings-loaded

Triggered when theme settings are loaded from the server.

AddEventHandler('b2lib:theme-settings-loaded', function(settings)
    print('Theme settings loaded:', json.encode(settings))
    
    -- Initialize your script with loaded settings
    initializeWithSettings(settings)
end)

b2lib:theme-settings-reset

Triggered when theme settings are reset to defaults.

AddEventHandler('b2lib:theme-settings-reset', function()
    print('Theme settings reset to defaults')
    
    -- Reinitialize with default settings
    initializeWithDefaults()
end)

Component Styling

The theme settings interface provides comprehensive styling options for each UI component:

Available Components

  • Notifications: Toast-style notification styling

  • Progress: Progress bar appearance and animations

  • Menus: Menu layout, colors, and typography

  • TextUI: Contextual text display styling

  • Input: Input dialog appearance and validation styling

  • Alert: Alert dialog colors and layout

  • Context Menu: Right-click menu styling

  • Skillcheck: Minigame colors, sizes, and animations

  • Lockpicking: Lock interface styling and feedback

  • Hacking: Terminal interface appearance

  • Radial Menu: Circular menu styling and animations

Styling Categories

Each component offers styling options in two categories:

Basic Settings

  • Colors: Primary, background, text, and accent colors

  • Sizes: Width, height, padding, and spacing

  • Typography: Font size, weight, and line height

  • Borders: Border radius, width, and style

  • Shadows: Drop shadow intensity and blur

Advanced Settings

  • Animations: Duration, easing, and transition effects

  • Opacity: Transparency levels for different states

  • Positioning: Precise positioning and alignment

  • Interactive States: Hover, active, and disabled styling

  • Custom Properties: Component-specific advanced options

Live Preview

All styling changes include live preview functionality:

-- Component styling changes trigger preview updates
AddEventHandler('b2lib:component-style-changed', function(component, property, value)
    print(string.format('Component %s property %s changed to %s', component, property, value))
    
    -- Update your custom UI to match
    updateCustomComponentStyle(component, property, value)
end)

Slider Controls

Advanced settings use slider controls for precise value adjustment:

  • Size Controls: Pixel values with appropriate min/max ranges

  • Opacity Controls: 0-100% with real-time preview

  • Animation Speed: Millisecond precision for timing

  • Color Intensity: HSL adjustments for fine-tuning

  • Spacing Values: Consistent spacing scale

Reset and Export

  • Individual Reset: Reset specific component styling to defaults

  • Global Reset: Reset all components to default styling

  • Export Settings: Export current theme configuration

  • Import Settings: Import previously saved theme configurations

AddEventHandler('b2lib:theme-settings-reset', function()
    print('Theme settings reset to defaults')
    
    -- Reset any custom configurations
    resetCustomSettings()
end)

b2lib:layout-mode-started

Triggered when layout positioning mode is started.

AddEventHandler('b2lib:layout-mode-started', function(elementType, currentPosition)
    print('Layout mode started for:', elementType)
    print('Current position:', currentPosition)
    
    -- Show helpful instructions
    B2Lib.UI.notify({
        type = 'info',
        title = 'Layout Mode',
        message = 'Click on the grid to position ' .. elementType,
        duration = 5000
    })
end)

Configuration

Theme settings are configured in Config.lua:

-- Theme configuration - Simplified
Config.Theme = {
    mode = 'dark',                      -- Default theme mode
    allowUserCustomization = true,     -- Allow users to change themes
    persistSettings = true,            -- Save settings server-side
    
    -- Theme definitions
    themes = {
        dark = {
            primary = '#1a1a1a',       -- Primary background
            secondary = '#2d2d2d',     -- Secondary background
            accent = '#3b82f6',        -- Accent color
            text = '#ffffff',          -- Primary text
            textSecondary = '#e5e5e5', -- Secondary text
            border = '#404040',        -- Border color
            shadow = 'rgba(0,0,0,0.5)' -- Shadow color
        },
        light = {
            primary = '#ffffff',       -- Primary background
            secondary = '#f5f5f5',     -- Secondary background
            accent = '#3b82f6',        -- Accent color
            text = '#1a1a1a',          -- Primary text
            textSecondary = '#333333', -- Secondary text
            border = '#e5e5e5',        -- Border color
            shadow = 'rgba(0,0,0,0.1)' -- Shadow color
        },
        transparent = {
            primary = 'rgba(26,26,26,0.8)',     -- Primary background
            secondary = 'rgba(45,45,45,0.8)',   -- Secondary background
            accent = '#3b82f6',                  -- Accent color
            text = '#ffffff',                    -- Primary text
            textSecondary = '#e5e5e5',           -- Secondary text
            border = 'rgba(64,64,64,0.8)',      -- Border color
            shadow = 'rgba(0,0,0,0.3)'          -- Shadow color
        }
    },
    
    -- Animation settings
    animations = {
        duration = 200,                 -- Default animation duration
        easing = 'ease-in-out',        -- Default easing function
        enableTransitions = true        -- Enable smooth transitions
    },
    
    -- Layout grid settings
    layoutGrid = {
        enabled = true,                 -- Enable layout positioning
        gridSize = 12,                  -- Grid columns/rows
        snapToGrid = true,              -- Snap elements to grid
        showGrid = true,                -- Show grid in layout mode
        previewElements = true          -- Show preview elements
    }
}

-- Component positioning defaults
Config.ComponentPositions = {
    notifications = 'top-right',       -- Default notification position
    progress = 'bottom',                -- Default progress bar position
    textUI = 'bottom-center',          -- Default text UI position
    input = 'center',                  -- Default input dialog position
    alert = 'center',                  -- Default alert dialog position
    menu = 'center-left',              -- Default menu position
    contextMenu = 'mouse',             -- Default context menu position
    radialMenu = 'center'              -- Default radial menu position
}

Advanced Examples

Theme-Aware Custom UI

-- Create a custom UI that adapts to theme changes
local function createThemeAwareUI()
    local currentTheme = B2Lib.UI.getTheme()
    
    -- Define theme-specific styles
    local themeStyles = {
        dark = {
            backgroundColor = '#1a1a1a',
            textColor = '#ffffff',
            borderColor = '#404040'
        },
        light = {
            backgroundColor = '#ffffff',
            textColor = '#1a1a1a',
            borderColor = '#e5e5e5'
        },
        transparent = {
            backgroundColor = 'rgba(26,26,26,0.8)',
            textColor = '#ffffff',
            borderColor = 'rgba(64,64,64,0.8)'
        }
    }
    
    local styles = themeStyles[currentTheme] or themeStyles.dark
    
    -- Apply styles to your custom UI
    SendNUIMessage({
        type = 'updateCustomUITheme',
        data = {
            styles = styles,
            theme = currentTheme
        }
    })
    
    -- Listen for theme changes
    AddEventHandler('b2lib:theme-changed', function(newTheme)
        local newStyles = themeStyles[newTheme] or themeStyles.dark
        
        SendNUIMessage({
            type = 'updateCustomUITheme',
            data = {
                styles = newStyles,
                theme = newTheme
            }
        })
    end)
end

Settings Management System

-- Create a comprehensive settings management system
local playerSettings = {}

local function initializeSettings()
    -- Load settings when player joins
    AddEventHandler('b2lib:theme-settings-loaded', function(settings)
        playerSettings = settings or {}
        
        -- Apply loaded settings
        if playerSettings.theme then
            B2Lib.UI.setTheme(playerSettings.theme)
        end
        
        if playerSettings.notifications then
            applyNotificationSettings(playerSettings.notifications)
        end
        
        if playerSettings.ui then
            applyUISettings(playerSettings.ui)
        end
    end)
    
    -- Save settings when changed
    AddEventHandler('b2lib:theme-settings-saved', function(settings)
        playerSettings = settings
        print('Settings saved successfully')
    end)
    
    -- Handle theme changes
    AddEventHandler('b2lib:theme-changed', function(newTheme)
        playerSettings.theme = newTheme
        
        -- Auto-save theme changes
        TriggerServerEvent('b2lib:savePlayerSettings', playerSettings)
    end)
end

local function applyNotificationSettings(notifSettings)
    -- Apply notification-specific settings
    if notifSettings.position then
        Config.ComponentPositions.notifications = notifSettings.position
    end
    
    if notifSettings.duration then
        Config.Notifications.duration = notifSettings.duration
    end
    
    if notifSettings.sound then
        Config.Notifications.enableSound = notifSettings.sound
    end
end

local function applyUISettings(uiSettings)
    -- Apply UI-specific settings
    if uiSettings.animations then
        Config.Theme.animations.enableTransitions = uiSettings.animations
    end
    
    if uiSettings.scale then
        -- Apply UI scaling
        SendNUIMessage({
            type = 'setUIScale',
            data = { scale = uiSettings.scale }
        })
    end
end

-- Initialize on resource start
CreateThread(function()
    Wait(1000) -- Wait for B2Lib to initialize
    initializeSettings()
end)

Theme Switcher Command

-- Create a command to quickly switch themes
RegisterCommand('theme', function(source, args)
    local theme = args[1]
    
    if not theme then
        local currentTheme = B2Lib.UI.getTheme()
        B2Lib.UI.notify({
            type = 'info',
            title = 'Current Theme',
            message = 'Current theme: ' .. currentTheme .. '\nAvailable: dark, light, transparent'
        })
        return
    end
    
    if theme ~= 'dark' and theme ~= 'light' and theme ~= 'transparent' then
        B2Lib.UI.notify({
            type = 'error',
            title = 'Invalid Theme',
            message = 'Valid themes: dark, light, transparent'
        })
        return
    end
    
    local success = B2Lib.UI.setTheme(theme)
    
    if success then
        B2Lib.UI.notify({
            type = 'success',
            title = 'Theme Changed',
            message = 'Theme changed to: ' .. theme
        })
    else
        B2Lib.UI.notify({
            type = 'error',
            title = 'Theme Error',
            message = 'Failed to change theme'
        })
    end
end)

-- Add suggestions for the command
TriggerEvent('chat:addSuggestion', '/theme', 'Change B2Lib theme', {
    { name = 'mode', help = 'Theme mode: dark, light, transparent' }
})

Settings Menu Integration

-- Integrate theme settings into a custom settings menu
local function createSettingsMenu()
    local currentTheme = B2Lib.UI.getTheme()
    
    B2Lib.UI.registerMenu('game_settings', {
        title = 'Game Settings',
        subtitle = 'Configure your preferences',
        items = {
            {
                label = 'Theme',
                value = 'theme_submenu',
                submenu = 'theme_settings',
                description = 'Current: ' .. currentTheme,
                icon = 'palette'
            },
            {
                label = 'UI Layout',
                value = 'layout',
                description = 'Customize UI element positions',
                icon = 'layout'
            },
            {
                label = 'Notifications',
                value = 'notifications_submenu',
                submenu = 'notification_settings',
                icon = 'bell'
            },
            {
                label = 'Advanced Settings',
                value = 'advanced',
                description = 'Open advanced theme settings',
                icon = 'settings'
            }
        ]
    })
    
    B2Lib.UI.registerMenu('theme_settings', {
        title = 'Theme Settings',
        subtitle = 'Choose your preferred theme',
        items = {
            {
                label = 'Dark Theme',
                value = 'dark',
                description = 'Dark backgrounds, light text',
                icon = 'moon',
                type = 'radio',
                checked = currentTheme == 'dark'
            },
            {
                label = 'Light Theme',
                value = 'light',
                description = 'Light backgrounds, dark text',
                icon = 'sun',
                type = 'radio',
                checked = currentTheme == 'light'
            },
            {
                label = 'Transparent Theme',
                value = 'transparent',
                description = 'Semi-transparent, immersive',
                icon = 'eye',
                type = 'radio',
                checked = currentTheme == 'transparent'
            }
        ]
    })
    
    -- Handle theme selection
    AddEventHandler('b2lib:menu-item-selected', function(data)
        if data.menuId == 'theme_settings' then
            B2Lib.UI.setTheme(data.value)
            B2Lib.UI.hideMenu()
            
            B2Lib.UI.notify({
                type = 'success',
                message = 'Theme changed to: ' .. data.value
            })
        elseif data.menuId == 'game_settings' then
            if data.value == 'layout' then
                B2Lib.UI.openThemeSettings()
            elseif data.value == 'advanced' then
                B2Lib.UI.openThemeSettings()
            end
        end
    end)
    
    B2Lib.UI.showMenu('game_settings')
end

-- Bind to command
RegisterCommand('settings', function()
    createSettingsMenu()
end)

Best Practices

  1. Initialize early - Set up theme event handlers during resource startup

  2. Respect user preferences - Load and apply saved theme settings

  3. Provide feedback - Show notifications when themes change

  4. Test all themes - Ensure your UI works with all theme modes

  5. Use theme events - React to theme changes in your custom UI

  6. Save settings - Persist user preferences across sessions

  7. Provide defaults - Have fallback values for missing settings

  8. Handle errors gracefully - Check for valid theme modes before applying

Troubleshooting

Theme Not Changing

  1. Check that the theme mode is valid ('dark', 'light', 'transparent')

  2. Verify B2Lib is properly initialized

  3. Check console for error messages from B2Lib.Debug

  4. Ensure no other scripts are overriding theme settings

Settings Not Saving

  1. Verify server-side callback functions are working

  2. Check that the player has permission to save settings

  3. Ensure database/file storage is properly configured

  4. Check server console for save errors

Theme Settings UI Not Opening

  1. Check that no other modal dialogs are active

  2. Verify NUI focus is not blocked by other scripts

  3. Ensure the theme settings resource files are present

  4. Check for JavaScript errors in browser console

Custom UI Not Updating

  1. Verify theme change event handlers are registered

  2. Check that your custom UI is listening for theme updates

  3. Ensure theme styles are properly applied to custom elements

  4. Test theme changes with simple UI elements first


Last updated