ContextMenu

The Context Menu System provides contextual menus that appear at specific screen positions, perfect for right-click interactions, entity-specific actions, and location-based options.

Dark Context Menu

registerContextMenu

Register a context menu definition that can be shown at specific positions with comprehensive configuration options.

Parameters:

  • contextId (string, required): Unique context menu identifier for registration and management

  • menuData (table, required): Comprehensive context menu configuration object

Menu Data Options:

  • title (string, optional): Context menu title displayed at the top (default: empty string)

  • items (table, optional): Array of context menu items with full configuration (default: empty array)

  • maxWidth (number, optional): Maximum menu width in pixels with responsive scaling (default: 250)

  • minWidth (number, optional): Minimum menu width in pixels (default: 180)

  • showIcons (boolean, optional): Display item icons with proper spacing (default: true)

  • showShortcuts (boolean, optional): Display keyboard shortcuts for items (default: true)

  • autoClose (boolean, optional): Auto-close menu after item selection (default: true)

  • position (string, optional): Default positioning strategy ('auto', 'fixed', 'follow-cursor')

  • animation (string, optional): Animation type ('fade', 'slide', 'scale', 'none')

  • theme (string, optional): Theme override ('auto', 'light', 'dark')

  • zIndex (number, optional): Z-index for menu layering (default: 1000)

Returns: boolean - Success status indicating registration completion

Example:

showContextMenu

Display a registered context menu at specific screen coordinates with dynamic context data and smart positioning.

Parameters:

  • playerId (number, server-side only): Player server ID to show context menu to

  • contextId (string, required): Registered context menu identifier to display

  • position (table, required): Position coordinates with smart boundary detection

    • x (number): X coordinate in pixels from left edge of screen

    • y (number): Y coordinate in pixels from top edge of screen

    • anchor (string, optional): Anchor point ('top-left', 'top-right', 'bottom-left', 'bottom-right')

  • contextData (table, optional): Dynamic context data passed to menu items and event handlers

Returns: boolean - Success status indicating menu display completion

Example:

hideContextMenu

Hide the currently active context menu with smooth animation and proper cleanup.

Parameters:

  • playerId (number, server-side only): Player server ID to hide context menu for

Returns: boolean - Success status indicating menu hide completion

Example:

updateContextData

Update context data for the currently active context menu with real-time data refresh.

Parameters:

  • contextData (table, required): Updated context data object with new values

Returns: boolean - Success status indicating data update completion

Example:

isContextMenuVisible

Check if a context menu is currently visible and get active menu information.

Returns: boolean|table - False if no context menu is active, or table with active menu data

  • contextId (string): Current context menu identifier

  • position (table): Current menu position coordinates

  • contextData (table): Current context data

  • itemCount (number): Number of menu items

Example:

updateContextMenu

Update a registered context menu's configuration and items dynamically.

Parameters:

  • contextId (string, required): Context menu identifier to update

  • menuData (table, required): Updated menu configuration object

Returns: boolean - Success status indicating menu update completion

Example:

Context Menu Item Structure

Context menu items support comprehensive properties for advanced functionality and visual customization:

Server-Side Usage

The Context Menu module provides comprehensive server-side functionality for managing player-specific context menus and administrative tools:

Events

The Context Menu module provides comprehensive event handling for monitoring and responding to context menu interactions:

Client Events

Server Events

Event Usage Examples

Configuration

Complete Context Menu configuration options in config.lua:

Advanced Examples

Comprehensive Player Interaction System

Advanced Vehicle Context System

Dynamic Inventory Context Menu

Vehicle Context Menu System

World Interaction Context Menu

Best Practices

  1. Register Menus Early - Register all context menus during resource startup to ensure availability when needed

  2. Use Descriptive IDs - Choose meaningful, consistent context menu identifiers that reflect their purpose and scope

  3. Implement Smart Positioning - Consider screen boundaries, menu size, and user interface elements when positioning menus

  4. Provide Rich Context Data - Pass comprehensive, relevant information to menu handlers for dynamic behavior

  5. Leverage Visual Hierarchy - Use icons, colors, separators, and grouping to create clear visual organization

  6. Validate Permissions Dynamically - Use condition functions to show/hide items based on real-time permission checks

  7. Handle State Changes - Update context data and menu items when underlying conditions change

  8. Optimize Performance - Use reasonable update intervals and avoid excessive menu registrations or data processing

  9. Implement Proper Cleanup - Clean up event handlers, timers, and resources when menus are closed or no longer needed

  10. Use Consistent Styling - Maintain visual consistency across different context menus in your resource

  11. Provide Keyboard Shortcuts - Include keyboard shortcuts for frequently used actions to improve accessibility

  12. Test Edge Cases - Verify menu behavior with invalid entities, disconnected players, and boundary conditions

  13. Implement Error Handling - Add proper error handling for failed actions and invalid context data

  14. Use Submenu Strategically - Organize complex actions into logical submenu structures without overwhelming users

  15. Consider Mobile Compatibility - Ensure context menus work well on different screen sizes and input methods

Troubleshooting

Context Menu Not Showing

  1. Registration Issues

    • Verify the context menu is registered before attempting to show it

    • Check that the contextId matches exactly between registration and show calls

    • Ensure registration occurs during resource startup or before first use

  2. Position Problems

    • Verify position coordinates are valid numbers within screen bounds

    • Check that x/y values are positive and not NaN or nil

    • Test with fixed coordinates (e.g., {x: 400, y: 300}) before using dynamic positioning

  3. Blocking Elements

    • Ensure no other modal dialogs or UI elements are blocking the display

    • Check for conflicting z-index values with other UI components

    • Verify the menu isn't being hidden immediately after being shown

  4. Debug Information

    • Check console for error messages from B2Lib.Debug

    • Enable debug mode to see detailed context menu operations

    • Verify B2Lib is properly initialized and loaded

  1. Boundary Detection

    • Implement boundary padding to prevent menus from appearing outside screen edges

    • Use anchor points to control how menus position relative to coordinates

    • Test positioning on different screen resolutions and aspect ratios

  2. Dynamic Positioning

    • Consider using GetNuiCursorPosition() for mouse-based positioning

    • Account for menu dimensions when calculating optimal position

    • Implement fallback positioning for edge cases

  3. Multi-Monitor Setup

    • Test context menu positioning on multi-monitor configurations

    • Ensure menus appear on the correct monitor

    • Handle negative coordinates appropriately

Context Data Not Working

  1. Data Structure

    • Ensure context data is passed as a properly structured table

    • Verify that event handlers access data.contextData correctly

    • Check for typos in context data property names

  2. Data Validation

    • Implement validation for critical context data properties

    • Handle cases where expected data is missing or invalid

    • Use default values for optional context data

  3. Dynamic Updates

    • Verify that updateContextData() is called when underlying data changes

    • Check that condition functions receive updated context data

    • Ensure event handlers can access the latest context information

Performance Issues

  1. Menu Frequency

    • Avoid showing/hiding context menus too frequently (< 100ms intervals)

    • Implement debouncing for rapid menu operations

    • Use reasonable update intervals for dynamic context data

  2. Resource Management

    • Clean up event handlers when they're no longer needed

    • Limit the number of registered context menus

    • Optimize context data calculations and avoid expensive operations

  3. Item Count Optimization

    • Use reasonable item counts in context menus (< 15 items recommended)

    • Implement scrolling for menus with many items

    • Consider using submenus to organize large sets of actions

  4. Memory Leaks

    • Properly clean up context menu references and event handlers

    • Avoid storing large objects in context data

    • Monitor memory usage during extended context menu usage

Condition Function Errors

  1. Function Validation

    • Ensure condition functions return boolean values

    • Handle errors within condition functions gracefully

    • Test condition functions with various context data scenarios

  2. Performance Optimization

    • Keep condition functions lightweight and fast

    • Avoid expensive operations in condition functions

    • Cache results when appropriate to improve performance

  3. Error Handling

    • Implement try-catch blocks in condition functions

    • Provide fallback behavior when condition functions fail

    • Log condition function errors for debugging

Server-Side Issues

  1. Player Validation

    • Verify player exists and is connected before showing server-side context menus

    • Handle player disconnections gracefully

    • Implement proper permission checks on the server side

  2. Network Synchronization

    • Account for network latency when showing context menus to players

    • Implement proper error handling for failed network operations

    • Use appropriate timeouts for server-side context menu operations

  3. Resource Conflicts

    • Check for conflicts with other resources using context menus

    • Ensure proper resource dependencies are declared

    • Test context menu functionality after resource restarts

Last updated