### Nexo Maker Asset References Example (JavaScript) Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/plugin-expansion/getting-started Shows examples of asset references for textures and models within the Nexo Maker data model. These are provided as arrays of relative file paths, crucial for loading visual assets associated with an item. ```javascript item.textures // string[]: Texture file paths (e.g., ["item/magic_sword.png"]) item.models // string[]: Model file paths (e.g., ["item/magic_sword.json"]) ``` -------------------------------- ### Register Export Format API Configuration (JavaScript) Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/plugin-expansion/getting-started An example demonstrating the full configuration object for registering an export format via the Nexo Maker API. It includes optional parameters like 'files' for file structure and 'hooks' for lifecycle management. ```javascript api.nexomaker.registerExportFormat({ id: 'my_format', name: 'My Custom Format', transform: (item) => ({ /* transformed data */ }), files: { /* file configuration */ }, hooks: { /* lifecycle hooks */ }, }); ``` -------------------------------- ### Nexo Maker Module Data Example (JavaScript) Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/plugin-expansion/getting-started Provides an example of how module data is exposed in Nexo Maker. Module data is a flat object containing all registered module values for a specific item, allowing access to custom properties defined by expansions. ```javascript { expansion_magic_power: 150, baseMaterial: "DIAMOND_SWORD", durability: 1000, // Additional module data as defined by active expansions } ``` -------------------------------- ### Register Export Format API Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/plugin-expansion/getting-started Demonstrates how to register a custom export format using the `registerExportFormat` method. ```APIDOC ## POST /api/nexomaker/registerExportFormat ### Description Registers a custom export format with the NexoMaker export system, allowing for custom data transformation and file handling. ### Method POST ### Endpoint /api/nexomaker/registerExportFormat ### Parameters #### Request Body - **config** (object) - Required - Export format configuration object - **id** (string) - Required - Unique identifier for the export format - **name** (string) - Required - Human-readable display name - **transform** (function) - Required - Item transformation function - **files** (object) - Optional - File structure configuration - **hooks** (object) - Optional - Lifecycle hook implementations ### Request Example ```json { "config": { "id": "my_format", "name": "My Custom Format", "transform": "(item) => ({ /* transformed data */ })", "files": "{ /* file configuration */ }", "hooks": "{ /* lifecycle hooks */ }" } } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating successful registration. #### Response Example ```json { "message": "Export format 'my_format' registered successfully." } ``` ``` -------------------------------- ### Basic useLibraries() Setup in JavaScript Source: https://nexo-maker.gitbook.io/nexo-maker-docs/modular/imports/libraries Shows the initial setup required to use the `useLibraries()` utility by including it in the `module.exports` function. This is a prerequisite for importing any libraries. ```javascript module.exports = ({ useLibraries }) => { // Your code here }; ``` -------------------------------- ### Nexo Maker Data Model Properties (JavaScript) Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/plugin-expansion/getting-started Illustrates the core properties guaranteed on normalized items processed by Nexo Maker. These include unique identifiers, display names, item types, and namespace information, essential for consistent data handling. ```javascript item.id // string: Unique identifier (e.g., "magic_sword") item.name // string: Display name (e.g., "Magic Sword") item.type // string: Item type - "item" | "block" | "entity" | "furniture" item.namespace // string: Namespace identifier (e.g., "nexo" or custom namespace) ``` -------------------------------- ### Simple Keybinding Example Source: https://nexo-maker.gitbook.io/nexo-maker-docs/modular/imports/libraries/keybinding Shows a basic implementation of the Keybinding component. It sets up a listener for the 'Ctrl + K' shortcut, which increments a counter when pressed. This example highlights the direct mapping of keys to actions. ```javascript module.exports = ({ useState, useLibraries }) => { const { KeyBinding } = useLibraries(); const [count, setCount] = useState(0); return (

Press Ctrl + K to increment: {count}

setCount(count + 1)} />
); }; ``` -------------------------------- ### YAML Key Best Practices Examples Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/settings/project-settings Provides examples of recommended YAML keys for configuration, emphasizing their use for main configuration, environment-specific settings, and server properties. These keys are crucial for saving and loading settings correctly. ```javascript // ✅ Good - Main configuration yamlKey: "configs" // ✅ Good - Environment-specific yamlKey: "environment" // ✅ Good - Server properties yamlKey: "serverProperties" ``` -------------------------------- ### Register Custom Export Format (JavaScript) Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/plugin-expansion/getting-started Demonstrates the minimal configuration to register a custom export format using the Nexo Maker API. This includes defining the format ID, name, and a transform function for item normalization. It assumes the 'api' object is globally available. ```javascript module.exports.init = async () => { api.nexomaker.registerExportFormat({ id: 'my_plugin', name: 'My Plugin Format', transform: (item) => ({ item_id: item.id, display_name: item.name, item_type: item.type, }), }); }; ``` -------------------------------- ### Initialize Blockly Workspace with React Hooks Source: https://nexo-maker.gitbook.io/nexo-maker-docs/modular/imports/libraries/blockly Sets up a Blockly workspace within a React component using `useRef` for DOM referencing and `useState` for managing code and output. It leverages `useLibraries` to load Blockly and includes placeholders for integration with external APIs. This snippet focuses on the initial setup and state management for a Blockly environment. ```javascript module.exports = ({ useEffect, useRef, api, usePlaceholders, useState, useLibraries }) => { const blocklyDiv = useRef(null); const workspace = useRef(null); const [code, setCode] = useState(''); const [output, setOutput] = useState(''); const placeholders = usePlaceholders(); const { Blockly } = useLibraries(); // Example initialization code... }; ``` -------------------------------- ### Create App Settings Tab - Complete Example Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/settings/app-settings A comprehensive example of creating an app settings tab, including various input types like text, checkbox, dropdown, and number. It showcases advanced options like placeholders, descriptions, and input validation. ```javascript api.nexomaker.postAppSettingsTab({ id: "expansion-global", expansionId: "my_expansion", title: "My Expansion", description: "Global expansion settings", order: 100, elements: [ { id: "api-key", label: "API Key", type: "text", placeholder: "XXXX-XXXX-XXXX-XXXX", description: "Your API key for external services", default: "", required: true }, { id: "auto-update", label: "Automatic Updates", type: "checkbox", description: "Automatically check for updates", default: true }, { id: "update-channel", label: "Update Channel", type: "dropdown", options: [ { value: "stable", label: "Stable" }, { value: "beta", label: "Beta" }, { value: "dev", label: "Development" } ], default: "stable" }, { id: "cache-size", label: "Cache Size (MB)", type: "number", min: 10, max: 1000, default: 100 } ] }); ``` -------------------------------- ### useProjectState Summary Example (JavaScript) Source: https://nexo-maker.gitbook.io/nexo-maker-docs/modular/hooks/useprojectstate A concise example illustrating the fundamental usage of the useProjectState hook. It shows how to declare a state variable and its corresponding setter function using a unique key and an initial value. ```javascript const [value, setValue] = useProjectState('my-key', initialValue); ``` -------------------------------- ### JavaScript: Logical Ordering of Settings Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/settings/best-practices Provides an example in JavaScript of how to logically order settings, placing the most important or commonly used ones first, followed by more advanced options, separated by visual breaks. ```javascript // ✅ Good - Common first, advanced last elements: [ { id: "enabled", label: "Enable Feature", type: "checkbox" }, { id: "mode", label: "Mode", type: "dropdown" }, { type: "separator" }, { id: "debug-level", label: "Debug Level", type: "dropdown" }, { id: "custom-config", label: "Custom Config", type: "textarea" } ] ``` -------------------------------- ### Create App Settings Tab - Basic Example Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/settings/app-settings This snippet demonstrates the basic structure for creating an app settings tab using the NexoMaker API. It defines essential elements like an API key and a feature toggle. ```javascript api.nexomaker.postAppSettingsTab({ id: "my-expansion", title: "My Expansion", description: "Global settings for My Expansion", order: 100, elements: [ { id: "api-key", label: "API Key", type: "text", placeholder: "Enter your API key", default: "", required: true }, { id: "enabled", label: "Enable Feature", type: "checkbox", default: true } ] }); ``` -------------------------------- ### Setup Project with Specific Logic Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/settings/reading-settings Illustrates a pattern for setting up project-specific logic by reading configuration from a project's YAML file. If the configuration is loaded successfully and the expansion is enabled within that project, it proceeds to set up the expansion with the project's mode. ```javascript async function setupProject(project) { const config = await api.nexomaker.yaml.read({ projectID: project.id, yamlKey: 'configs' }); if (!config.success) { console.error('Failed to load project config'); return; } // Use project-specific settings if (config.data['expansion-enabled']) { const mode = config.data['expansion-mode'] || 'normal'; setupExpansion(project, mode); } } ``` -------------------------------- ### JavaScript: Consistent Naming Patterns for Settings Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/settings/best-practices Illustrates the importance of consistent naming patterns for settings in JavaScript to maintain uniformity across an extension. It provides examples of good and bad naming conventions. ```javascript // ✅ Good - Consistent pattern "expansion-api-key" "expansion-api-endpoint" "expansion-api-timeout" // ❌ Bad - Inconsistent "expansionAPIKey" "api_endpoint" "timeout-expansion" ``` -------------------------------- ### Read JSON Configuration File with JavaScript Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/loaders/load-file An example of using loadFile() to read a JSON configuration file. It specifies 'utf-8' encoding to get the file content as a string, which is then parsed into a JavaScript object. This pattern is common for loading settings and configurations. ```javascript const jsonString = await api.nexomaker.loadFile(__dirname + "/config.json", "utf-8"); const config = JSON.parse(jsonString); ``` -------------------------------- ### Nexo Maker Console Logging Source: https://nexo-maker.gitbook.io/nexo-maker-docs/modular/overlay-system/overlay-example Demonstrates how to log messages to the console using `api.console.log`. This is helpful for debugging and inspecting the state of the application during development. It supports logging strings and objects, and can be used to track the flow of execution. ```javascript api.console.log('🧪 Testing background APIs...') ``` ```javascript api.console.log('Context:', placeholders.context) ``` ```javascript api.console.log('Project ID:', placeholders.projectId) ``` ```javascript api.console.log('Global data test:', retrievedData) ``` -------------------------------- ### JavaScript: Descriptive IDs for Settings Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/settings/best-practices Demonstrates the use of descriptive and namespaced IDs for settings in JavaScript, emphasizing clarity and avoiding conflicts with other expansions. It contrasts good practices with bad examples. ```javascript // ✅ Good - Descriptive and namespaced { id: "my-expansion-api-key", label: "API Key" } { id: "my-expansion-enable-sync", label: "Enable Sync" } { id: "my-expansion-max-items", label: "Maximum Items" } // ❌ Bad - Generic and prone to conflicts { id: "key", label: "API Key" } { id: "enabled", label: "Enable Sync" } { id: "max", label: "Maximum Items" } ``` -------------------------------- ### JavaScript: Providing Default Values for Settings Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/settings/best-practices Explains the necessity of providing sensible default values for all settings in JavaScript to ensure a predictable user experience. It shows examples of settings with and without defaults. ```javascript // ✅ Good { id: "max-items", label: "Maximum Items", type: "number", min: 1, max: 1000, default: 100 // Clear default } // ❌ Bad { id: "max-items", label: "Maximum Items", type: "number", min: 1, max: 1000 // No default - will be undefined } ``` -------------------------------- ### Animated List with TransitionGroup Example Source: https://nexo-maker.gitbook.io/nexo-maker-docs/modular/imports/libraries/reacttransitiongroup Illustrates how to create an animated list where items are added with transitions using TransitionGroup and CSSTransition. This example shows managing a dynamic list of items and animating their appearance. ```javascript module.exports = ({ useState, useLibraries }) => { const { ReactTransitionGroup } = useLibraries(); const { TransitionGroup, CSSTransition } = ReactTransitionGroup; const [items, setItems] = useState(["First", "Second"]); return (
{items.map((item, i) => (
{item}
))}
); }; ``` -------------------------------- ### Modularjs useState Toggle Switch Example Source: https://nexo-maker.gitbook.io/nexo-maker-docs/modular/hooks/usestate Illustrates using the useState hook in Modularjs to manage a boolean state for a toggle switch. The example shows how to initialize the state, display its status, and toggle it using a button. ```javascript module.exports = ({ useState }) => { const [isOn, setIsOn] = useState(false); return (

Toggle Switch

The switch is {isOn ? 'ON' : 'OFF'}

); }; ``` -------------------------------- ### Nexo Maker Background API Notifications Source: https://nexo-maker.gitbook.io/nexo-maker-docs/modular/overlay-system/overlay-example Demonstrates how to send notifications from the background script using the `api.nexomaker.background.notify` function. This function allows for customizable alerts with different types (success, info, error), titles, messages, durations, and even custom actions. ```javascript api.nexomaker.background.notify({ type: 'success', title: 'Test Overlay', message: 'Statistics reset successfully', duration: 2000 }); ``` ```javascript api.nexomaker.background.notify({ type: 'info', title: 'Overlay Clicked', message: `You clicked the overlay. Total clicks: ${stats.clicks + 1}` }); ``` ```javascript api.nexomaker.background.notify({ type: 'info', title: 'Statistics', message: `Clicks: ${stats.clicks}, Toggles: ${stats.toggles}`, duration: 5000, actions: [ { text: 'Close Statistics', onClick: () => { /* logic to close stats */ }, style: { background: 'rgba(255,255,255,0.2)', color: 'white', border: '1px solid rgba(255,255,255,0.3)', padding: '12px 24px', borderRadius: '8px', cursor: 'pointer', fontSize: '14px', width: '100%', marginTop: '16px' } } ] }); ``` ```javascript api.nexomaker.background.notify({ type: 'success', title: 'API Test Complete', message: 'All background APIs working correctly!', duration: 3000 }); ``` -------------------------------- ### Example Usage of postAsset() with Image Conversion - JavaScript Source: https://nexo-maker.gitbook.io/nexo-maker-docs/themes/themes/replace-assets This example shows a practical application of posting an asset, specifically an image. It first converts a local image file to a base64 string using `api.nexomaker.imgconvert` and then posts this converted asset using `nm.postAsset()`. Requires the Nexo Maker API and a local image file. ```javascript const icon = await api.nexomaker.imgconvert(__dirname + "/assets/add-icon.png"); nm.postAsset({ Add: icon }); ``` -------------------------------- ### Nexo Maker Background API Global Data Storage Source: https://nexo-maker.gitbook.io/nexo-maker-docs/modular/overlay-system/overlay-example This snippet illustrates the usage of global data storage within the Nexo Maker background script. It shows how to set arbitrary data using `setGlobalData` and retrieve it later with `getGlobalData`. This is useful for persisting state or sharing information between different parts of the extension. ```javascript api.nexomaker.background.setGlobalData('testData', { timestamp: new Date().toISOString(), clicks: stats.clicks, context: placeholders.context }); ``` ```javascript const retrievedData = api.nexomaker.background.getGlobalData('testData'); ``` -------------------------------- ### JavaScript Interactive Overlay Component Source: https://nexo-maker.gitbook.io/nexo-maker-docs/modular/overlay-system/overlay-example This JavaScript component demonstrates a dynamic overlay with features for visibility toggling, drag-and-drop positioning, and statistics tracking. It utilizes React hooks such as useState, useEffect, and useRef, along with global state management and API calls for notifications and overlay management. It listens for global keyboard shortcuts for enhanced user interaction. ```javascript /** * Test Overlay - Background Module Example * This demonstrates a background overlay that runs outside of project context */ module.exports = ({ useState, useEffect, useRef, useGlobalState, api, usePlaceholders }) => { const [isVisible, setIsVisible] = useGlobalState('overlayVisible', true); const [position, setPosition] = useGlobalState('overlayPosition', { x: 100, y: 100 }); const [isDragging, setIsDragging] = useState(false); const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 }); const [stats, setStats] = useGlobalState('overlayStats', { clicks: 0, toggles: 0, lastInteraction: null }); const overlayRef = useRef(null); const placeholders = usePlaceholders(); // Listen for global keyboard shortcuts useEffect(() => { const handleKeyPress = (e) => { // Ctrl+Shift+O to toggle overlay if (e.ctrlKey && e.shiftKey && e.key === 'O') { e.preventDefault(); setIsVisible(prev => { const newState = !prev; setStats(prev => ({ ...prev, toggles: prev.toggles + 1, lastInteraction: new Date().toISOString() })); api.nexomaker.background.notify({ type: newState ? 'success' : 'info', title: 'Test Overlay', message: `Overlay ${newState ? 'shown' : 'hidden'} via keyboard shortcut`, duration: 2000 }); return newState; }); } // Ctrl+Shift+R to reset overlay position if (e.ctrlKey && e.shiftKey && e.key === 'R') { e.preventDefault(); setPosition({ x: 100, y: 100 }); api.nexomaker.background.notify({ type: 'info', title: 'Test Overlay', message: 'Position reset to default', duration: 2000 }); } }; window.addEventListener('keydown', handleKeyPress); return () => window.removeEventListener('keydown', handleKeyPress); }, []); // Handle dragging const handleMouseDown = (e) => { setIsDragging(true); const rect = overlayRef.current.getBoundingClientRect(); setDragOffset({ x: e.clientX - rect.left, y: e.clientY - rect.top }); }; useEffect(() => { const handleMouseMove = (e) => { if (isDragging) { setPosition({ x: e.clientX - dragOffset.x, y: e.clientY - dragOffset.y }); } }; const handleMouseUp = () => { setIsDragging(false); }; if (isDragging) { window.addEventListener('mousemove', handleMouseMove); window.addEventListener('mouseup', handleMouseUp); } return () => { window.removeEventListener('mousemove', handleMouseMove); window.removeEventListener('mouseup', handleMouseUp); }; }, [isDragging, dragOffset]); const handleClick = () => { setStats(prev => ({ ...prev, clicks: prev.clicks + 1, lastInteraction: new Date().toISOString() })); }; const showStatsOverlay = () => { api.nexomaker.background.showOverlay('stats-overlay', "

📊 Test Overlay Statistics

Total Clicks: ${stats.clicks}

Total Toggles: ${stats.toggles}

Current Position: (${Math.round(position.x)}, ${Math.round(position.y)})

Last Interaction: ${stats.lastInteraction ? new Date(stats.lastInteraction).toLocaleString() : 'Never'}

Overlay Visible: ${isVisible ? '✅ Yes' : '❌ No'}

Context: ${placeholders.context}

Project ID: ${placeholders.projectId}

🔥 Shortcuts:

• Ctrl+Shift+O: Toggle overlay

• Ctrl+Shift+R: Reset position

• Drag to move overlay

Background overlay running in {placeholders.context} context
📊 Clicks: {stats.clicks}
🔄 Toggles: {stats.toggles}
📍 Position: ({Math.round(position.x)}, {Math.round(position.y)})
🎯 Project: {placeholders.projectId}
); }; ``` -------------------------------- ### Global State Management for Overlays in Nexo Maker Source: https://nexo-maker.gitbook.io/nexo-maker-docs/modular/overlay-system Shows how to use the `useGlobalState` hook provided by Nexo Maker for managing persistent state within overlays. This state survives route changes and application restarts, ensuring data continuity. Examples include managing visibility and position of an overlay. ```javascript const [isVisible, setIsVisible] = useGlobalState('overlayVisible', true); const [position, setPosition] = useGlobalState('overlayPosition', { x: 100, y: 100 }); ``` -------------------------------- ### Define Project Settings Element: Clear Labels and Descriptions Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/settings/project-settings Illustrates the definition of a single project settings element, focusing on providing clear labels and descriptions for user understanding. This example shows a number input for maximum entities with defined min, max, and default values. ```javascript { id: "max-entities", label: "Maximum Entities", type: "number", description: "Maximum number of custom entities per chunk", min: 1, max: 100, default: 10 } ``` -------------------------------- ### JavaScript: Basic Item Transformation Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/plugin-expansion/transform-function A fundamental example of the transform function in JavaScript. It maps basic properties like id, name, and type from a normalized item object to a new object for export. This serves as a starting point for more complex transformations. ```javascript transform: (item) => ({ id: item.id, name: item.name, type: item.type, }) ``` -------------------------------- ### Accessing Nexo Maker API and Loading Assets (JavaScript) Source: https://nexo-maker.gitbook.io/nexo-maker-docs/getting-started/basic-concepts/starting-a-expansion Demonstrates how to create a shorthand reference for the Nexo Maker API and use it to load assets within your expansion. The `api.nexomaker` object provides access to various platform functions. __dirname helps in resolving the asset path relative to the current expansion file. ```javascript const nm = api.nexomaker; const customIMG = await nm.loadAsset(__dirname + "/assets/customImg.png"); ``` -------------------------------- ### Fade Animation with CSSTransition Example Source: https://nexo-maker.gitbook.io/nexo-maker-docs/modular/imports/libraries/reacttransitiongroup Provides an example of implementing a fade-in/fade-out animation using the CSSTransition component. It includes a button to toggle the visibility of an element and the corresponding CSS classes for the transition. ```javascript module.exports = ({ useState, useLibraries }) => { const { ReactTransitionGroup } = useLibraries(); const { CSSTransition } = ReactTransitionGroup; const [show, setShow] = useState(false); return (
Hello with Fade
); }; ``` ```css .fade-enter { opacity: 0; } .fade-enter-active { opacity: 1; transition: opacity 300ms; } .fade-exit { opacity: 1; } .fade-exit-active { opacity: 0; transition: opacity 300ms; } ``` -------------------------------- ### Document Complex Settings with Descriptions and Hints Source: https://nexo-maker.gitbook.io/nexo-maker-docs/main.js/api/settings/best-practices Provides guidance on documenting complex configuration settings, such as those requiring YAML format. It shows how to combine `description`, `hint`, and `placeholder` for clarity. ```javascript // ✅ Good { id: "custom-config", label: "Custom Configuration", type: "textarea", description: "Advanced YAML configuration. Use with caution!", hint: "Example:\nkey: value\nlist:\n - item1\n - item2", placeholder: "Enter YAML configuration..." } ```