### MtDzr Component: Drag, Resize, Rotate with Vue Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt This Vue 3 script setup demonstrates the usage of the MtDzr component from the 'maotu' library. It showcases how to manage element positioning, dimensions, and rotation, with event handlers for drag, resize, and rotate actions. The component supports features like grid alignment, boundary constraints, and proportional scaling. ```vue ``` -------------------------------- ### MaTu WebTopo: Component Manipulation and Data Binding (JavaScript) Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt Utilizes global `window` functions to interact with UI components in MaTu WebTopo's preview mode. It allows setting and getting component attributes by ID, performing value comparisons for conditional logic, triggering custom events, and displaying various types of message notifications and confirmation dialogs. Includes examples for real-time data updates via WebSockets and polling via REST APIs. ```javascript // Available in preview mode (MtPreview component) // Set component attribute by ID window.$setItemAttrByID('sensor-1', 'temperature', 28.5) window.$setItemAttrByID('alarm-icon', 'hide', false) window.$setItemAttrByID('status-text', 'text', 'System Online') // Get component attribute by ID const currentTemp = window.$getItemAttrByID('sensor-1', 'temperature') console.log('Current temperature:', currentTemp) // Compare values for conditional logic const isHighTemp = window.$previewCompareVal(currentTemp, '>', 30) if (isHighTemp) { window.$setItemAttrByID('alarm-icon', 'color', '#ff0000') } // Trigger custom event callbacks window.$mtEventCallBack('alarmTriggered', 'sensor-1', { value: 35, threshold: 30, timestamp: Date.now() }) // Show message notifications window.$mtElMessage.success('Data updated successfully') window.$mtElMessage.error('Connection failed') window.$mtElMessage.warning('Temperature exceeds threshold') window.$mtElMessage.info('System status: normal') // Show confirmation dialogs window.$mtElMessageBox.confirm('Are you sure to reset all sensors?', 'Warning', { confirmButtonText: 'OK', cancelButtonText: 'Cancel', type: 'warning' }).then(() => { // Reset logic window.$setItemAttrByID('sensor-1', 'temperature', 0) window.$mtElMessage.success('Reset complete') }).catch(() => { window.$mtElMessage.info('Reset cancelled') }) // Real-world example: WebSocket data binding const ws = new WebSocket('ws://localhost:8080/sensor-data') ws.onmessage = (event) => { const data = JSON.parse(event.data) // Update multiple sensors data.sensors.forEach(sensor => { window.$setItemAttrByID(sensor.id, 'temperature', sensor.value) window.$setItemAttrByID(sensor.id, 'color', sensor.value > 30 ? '#ff0000' : '#00ff00' ) }) // Update status indicator window.$setItemAttrByID('system-status', 'text', `Last update: ${new Date().toLocaleTimeString()}` ) } // Example: REST API polling setInterval(async () => { try { const response = await fetch('/api/realtime-data') const data = await response.json() window.$setItemAttrByID('pressure-gauge', 'value', data.pressure) window.$setItemAttrByID('flow-meter', 'value', data.flow) window.$setItemAttrByID('valve-status', 'text', data.valve.isOpen ? 'OPEN' : 'CLOSED' ) } catch (error) { console.error('Failed to fetch data:', error) window.$mtElMessage.error('Data fetch failed') } }, 5000) ``` -------------------------------- ### Global Store API Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt Provides access to reactive global state management for the editor, including canvas configuration, selected items, component data, and various editor states. ```APIDOC ## Global Store API ### globalStore Reactive global state management for the editor including canvas configuration, selected items, component data, and various editor states. ### Methods - **`setSingleSelect(itemId: string)`**: Selects a single item by its ID. - **`setSelectItems(itemIds: Array)`**: Selects multiple items by their IDs. - **`cancelAllSelect()`**: Deselects all currently selected items. - **`deleteSelectedItems()`**: Deletes all currently selected components. - **`setIntention(intention: string)`**: Sets the current editor intention (e.g., 'create', 'none', 'beginMulSelect'). - **`setRealTimeData(data: object)`**: Updates the real-time data display. ### Properties - **`canvasCfg`** (object) - Canvas configuration including `width`, `height`, `scale`, `color`. - **`selected_items_id`** (Array) - An array of IDs of the currently selected items. - **`done_json`** (Array) - An array representing all components currently in the editor. - **`lock`** (boolean) - Global lock state for all components. - **`realTimeData`** (object) - Object containing data for real-time display. ### Request Example ```javascript import { globalStore } from 'maotu'; // Access canvas configuration console.log('Canvas scale:', globalStore.canvasCfg.scale); // Select components globalStore.setSelectItems(['uuid-1', 'uuid-2']); // Add a new component const newComponent = { id: 'new-uuid-' + Date.now(), title: 'New Component', type: 'svg', binfo: { left: 50, top: 50, width: 100, height: 100, angle: 0 }, props: {}, events: [] }; globalStore.done_json.push(newComponent); // Update a component's position const component = globalStore.done_json.find(c => c.id === 'component-1'); if (component) { component.binfo.left = 150; } // Set editor intention globalStore.setIntention('create'); ``` ### Response #### Success Response (200) Direct modification and access to the `globalStore` properties and methods. No explicit response object is returned for most operations, but the state is updated reactively. #### Response Example N/A (State management) ``` -------------------------------- ### Configure Component Events and Add to Editor (TypeScript) Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt Defines a component with various interactive events (click, dblclick, mouseover, mouseout) and their associated actions (changeAttr, customCode). This configuration is then added to the global store's done_json array. It demonstrates how to set up attribute changes and execute custom JavaScript for event responses. ```typescript const componentWithEvents = { id: 'button-1', title: 'Control Button', type: 'svg', binfo: { left: 100, top: 100, width: 120, height: 50, angle: 0 }, props: { text: { title: 'Text', type: 'input', val: 'Start' }, bgColor: { title: 'Background', type: 'color', val: '#409eff' } }, events: [ { id: 'event-1', type: 'click', action: 'changeAttr', change_attr: [ { id: 'change-1', target_id: 'motor-1', target_attr: 'running', target_value: true }, { id: 'change-2', target_id: 'status-light', target_attr: 'color', target_value: '#00ff00' } ], custom_code: '', trigger_rule: { trigger_id: 'button-1', trigger_attr: 'enabled', operator: '==', value: true } }, { id: 'event-2', type: 'dblclick', action: 'customCode', change_attr: [], custom_code: "\n console.log('Button double clicked');\n window.$mtElMessageBox.confirm('Reset system?', 'Confirm', {\n confirmButtonText: 'Yes',\n cancelButtonText: 'No'\n }).then(() => {\n window.$setItemAttrByID('motor-1', 'running', false);\n window.$setItemAttrByID('status-light', 'color', '#ff0000');\n window.$mtElMessage.success('System reset');\n });\n ", trigger_rule: {} }, { id: 'event-3', type: 'mouseover', action: 'changeAttr', change_attr: [ { id: 'change-3', target_id: 'button-1', target_attr: 'bgColor', target_value: '#66b1ff' } ], custom_code: '', trigger_rule: {} }, { id: 'event-4', type: 'mouseout', action: 'changeAttr', change_attr: [ { id: 'change-4', target_id: 'button-1', target_attr: 'bgColor', target_value: '#409eff' } ], custom_code: '', trigger_rule: {} } ], resize: false, rotate: false, lock: false, active: false, hide: false, common_animations: { val: '', delay: 'delay-0s', speed: 'slow', repeat: 'infinite' } } // Add component to editor globalStore.done_json.push(componentWithEvents) ``` -------------------------------- ### Vue 3 - Maotu MtEdit Component for Visual Topology Editing Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt Demonstrates the integration and basic usage of the MtEdit component in Vue 3. It handles saving and previewing the topology project and loading existing configurations from localStorage. This component provides a full-featured visual editor interface. ```vue ``` -------------------------------- ### Window Global Functions Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt This section describes the global JavaScript functions exposed in the Webtopo preview mode. These functions allow for dynamic data binding, component attribute manipulation, conditional logic, event callbacks, and UI notifications from custom code or external scripts. ```APIDOC ## Window Global Functions This section details the global JavaScript functions available in the Webtopo preview environment. These functions provide capabilities for interacting with and manipulating UI components dynamically. ### Available Functions - **$setItemAttrByID(id, attribute, value)** - **Description**: Sets a specific attribute of a component identified by its ID. - **Parameters**: - `id` (string) - The unique identifier of the component. - `attribute` (string) - The name of the attribute to set (e.g., 'temperature', 'hide', 'text', 'color', 'value'). - `value` (any) - The new value for the attribute. - **Example**: ```javascript window.$setItemAttrByID('sensor-1', 'temperature', 28.5) window.$setItemAttrByID('alarm-icon', 'hide', false) window.$setItemAttrByID('status-text', 'text', 'System Online') ``` - **$getItemAttrByID(id, attribute)** - **Description**: Retrieves the current value of a specific attribute of a component identified by its ID. - **Parameters**: - `id` (string) - The unique identifier of the component. - `attribute` (string) - The name of the attribute to retrieve. - **Returns**: The current value of the specified attribute. - **Example**: ```javascript const currentTemp = window.$getItemAttrByID('sensor-1', 'temperature') console.log('Current temperature:', currentTemp) ``` - **$previewCompareVal(value1, operator, value2)** - **Description**: Compares two values using a specified operator. Useful for implementing conditional logic. - **Parameters**: - `value1` (any) - The first value to compare. - `operator` (string) - The comparison operator (e.g., '>', '<', '===', '!==', '>=', '<='). - `value2` (any) - The second value to compare. - **Returns**: A boolean indicating whether the comparison is true. - **Example**: ```javascript const isHighTemp = window.$previewCompareVal(currentTemp, '>', 30) if (isHighTemp) { window.$setItemAttrByID('alarm-icon', 'color', '#ff0000') } ``` - **$mtEventCallBack(eventName, componentId, eventData)** - **Description**: Triggers a custom event callback, allowing for custom event handling within the preview environment. - **Parameters**: - `eventName` (string) - The name of the custom event. - `componentId` (string) - The ID of the component associated with the event. - `eventData` (object) - An object containing data related to the event. - **Example**: ```javascript window.$mtEventCallBack('alarmTriggered', 'sensor-1', { value: 35, threshold: 30, timestamp: Date.now() }) ``` ### Message Notifications (`$mtElMessage`) Provides methods for displaying various types of message notifications to the user. - **$mtElMessage.success(message)** - **$mtElMessage.error(message)** - **$mtElMessage.warning(message)** - **$mtElMessage.info(message)** - **Parameters**: - `message` (string) - The message content to display. - **Example**: ```javascript window.$mtElMessage.success('Data updated successfully') window.$mtElMessage.error('Connection failed') ``` ### Confirmation Dialogs (`$mtElMessageBox`) Provides a method for displaying a confirmation dialog box to the user. - **$mtElMessageBox.confirm(message, title, options)** - **Description**: Shows a confirmation dialog with "OK" and "Cancel" buttons. - **Parameters**: - `message` (string) - The message to display in the dialog. - `title` (string) - The title of the dialog window. - `options` (object) - Configuration options for the dialog (e.g., `confirmButtonText`, `cancelButtonText`, `type`). - **Returns**: A Promise that resolves if the user confirms, or rejects if the user cancels. - **Example**: ```javascript window.$mtElMessageBox.confirm('Are you sure to reset all sensors?', 'Warning', { confirmButtonText: 'OK', cancelButtonText: 'Cancel', type: 'warning' }).then(() => { // Reset logic window.$setItemAttrByID('sensor-1', 'temperature', 0) window.$mtElMessage.success('Reset complete') }).catch(() => { window.$mtElMessage.info('Reset cancelled') }) ``` ### Real-world Examples #### WebSocket Data Binding This example demonstrates how to bind real-time data from a WebSocket connection to UI components. ```javascript const ws = new WebSocket('ws://localhost:8080/sensor-data') ws.onmessage = (event) => { const data = JSON.parse(event.data) // Update multiple sensors data.sensors.forEach(sensor => { window.$setItemAttrByID(sensor.id, 'temperature', sensor.value) window.$setItemAttrByID(sensor.id, 'color', sensor.value > 30 ? '#ff0000' : '#00ff00' ) }) // Update status indicator window.$setItemAttrByID('system-status', 'text', `Last update: ${new Date().toLocaleTimeString()}` ) } ``` #### REST API Polling This example shows how to periodically fetch data from a REST API and update UI components. ```javascript setInterval(async () => { try { const response = await fetch('/api/realtime-data') const data = await response.json() window.$setItemAttrByID('pressure-gauge', 'value', data.pressure) window.$setItemAttrByID('flow-meter', 'value', data.flow) window.$setItemAttrByID('valve-status', 'text', data.valve.isOpen ? 'OPEN' : 'CLOSED' ) } catch (error) { console.error('Failed to fetch data:', error) window.$mtElMessage.error('Data fetch failed') } }, 5000) ``` ``` -------------------------------- ### leftAsideStore.registerConfig Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt Register custom SVG or Vue components to the left sidebar component library for drag-and-drop usage in the editor. This allows users to add custom elements to their diagrams. ```APIDOC ## leftAsideStore.registerConfig ### Description Register custom SVG or Vue components to the left sidebar component library for drag-and-drop usage in the editor. ### Method `leftAsideStore.registerConfig(categoryName: string, components: Array) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **categoryName** (string) - Required - The name of the category for the components in the sidebar. - **components** (Array) - Required - An array of component configurations to register. Each component object should have: - **id** (string) - Unique identifier for the component. - **title** (string) - Display name for the component. - **type** (string) - Type of the component ('svg' or 'vue'). - **thumbnail** (string) - URL path to the component's thumbnail image. - **svg** (string) - (For type 'svg') The SVG markup for the component. - **props** (Object) - Configuration for the component's properties, including title, type, default value, and options. ### Request Example ```javascript import { leftAsideStore } from 'maotu' // Register custom SVG components leftAsideStore.registerConfig('Custom Sensors', [ { id: 'temperature-sensor', title: 'Temperature Sensor', type: 'svg', thumbnail: '/thumbnails/temp-sensor.png', svg: ` T `, props: { temperature: { title: 'Temperature', type: 'number', val: 25, disabled: false }, color: { title: 'Color', type: 'color', val: '#ff6b6b', disabled: false }, label: { title: 'Label', type: 'input', val: 'Temp', disabled: false }, unit: { title: 'Unit', type: 'select', val: 'C', options: [ { label: 'Celsius', value: 'C' }, { label: 'Fahrenheit', value: 'F' } ], disabled: false }, showValue: { title: 'Show Value', type: 'switch', val: true, disabled: false } } } ]) // Register Vue components leftAsideStore.registerConfig('Custom Vue Components', [ { id: 'data-table', title: 'Data Table', type: 'vue', thumbnail: '/thumbnails/table.png', props: { tableData: { title: 'Table Data', type: 'jsonEdit', val: [{ name: 'Item 1', value: 100 }], disabled: false }, headerColor: { title: 'Header Color', type: 'color', val: '#409eff', disabled: false } } } ]) ``` ### Response None ``` -------------------------------- ### Manage Global State with 'globalStore' API in TypeScript Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt The 'globalStore' object provides reactive global state management for the editor. It handles canvas configuration, selected items, component data, and various editor states. It's part of the 'maotu' library. This API allows direct access and modification of state properties and provides methods for managing selections, deleting items, and updating component data. ```typescript import { globalStore } from 'maotu' // Access and modify canvas configuration console.log('Canvas size:', globalStore.canvasCfg.width, 'x', globalStore.canvasCfg.height) globalStore.canvasCfg.scale = 1.5 globalStore.canvasCfg.color = '#2c3e50' // Manage component selection console.log('Selected items:', globalStore.selected_items_id) globalStore.setSingleSelect('element-uuid-1') // Select single item globalStore.setSelectItems(['uuid-1', 'uuid-2', 'uuid-3']) // Multi-select globalStore.cancelAllSelect() // Deselect all // Delete selected components globalStore.deleteSelectedItems() // Access all components globalStore.done_json.forEach(item => { console.log(`Component: ${item.title}, Position: (${item.binfo.left}, ${item.binfo.top})`) }) // Add new component programmatically const newComponent = { id: 'new-uuid-' + Date.now(), title: 'New Sensor', type: 'svg', binfo: { left: 200, top: 200, width: 100, height: 100, angle: 0 }, props: { value: { title: 'Value', type: 'number', val: 0 } }, resize: true, rotate: true, lock: false, active: false, hide: false, common_animations: { val: '', delay: 'delay-0s', speed: 'slow', repeat: 'infinite' }, events: [] } globalStore.done_json.push(newComponent) // Update component properties const component = globalStore.done_json.find(c => c.id === 'element-uuid-1') if (component) { component.binfo.left += 50 component.props.temperature.val = 30 component.lock = true } // Set editor intention/mode globalStore.setIntention('create') // 'none' | 'create' | 'beginMulSelect' | 'drawSysLineStart' // Control global lock globalStore.lock = true // Lock all components // Show real-time data display globalStore.setRealTimeData({ show: true, text: 'X: 250, Y: 180' }) ``` -------------------------------- ### useExportJsonToDoneJson Utility Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt Converts exported JSON data back to the internal format required by the editor or preview components, restoring all component configurations and properties. ```APIDOC ## useExportJsonToDoneJson ### Description Converts exported JSON data back to the internal format required by the editor or preview components, restoring all component configurations and properties. ### Method `useExportJsonToDoneJson(exportJson: any) => { canvasCfg: object, gridCfg: object, importDoneJson: Array }` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Example usage within a loadProject function const response = await fetch(`/api/projects/${projectId}`); const savedData = await response.json(); const exportJson = savedData.data; const { canvasCfg, gridCfg, importDoneJson } = useExportJsonToDoneJson(exportJson); console.log('Canvas config:', canvasCfg); console.log('Grid config:', gridCfg); console.log('Components:', importDoneJson); ``` ### Response #### Success Response (200) Returns an object containing: - **canvasCfg** (object) - Configuration for the canvas. - **gridCfg** (object) - Configuration for the grid. - **importDoneJson** (Array) - The converted internal JSON data representing components. #### Response Example ```json { "canvasCfg": { "width": 1920, "height": 1080, "scale": 1, "color": "#ffffff" }, "gridCfg": { "show": true, "size": 20, "color": "#e0e0e0" }, "importDoneJson": [ { "id": "component-1", "title": "Chart", "type": "chart", "binfo": { "left": 100, "top": 100, "width": 300, "height": 200, "angle": 0 }, "props": { ... }, "events": [] } ] } ``` ``` -------------------------------- ### Vue 3 - Maotu MtPreview Component for Runtime Topology Display Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt Illustrates the use of the MtPreview component in a Vue 3 application for displaying topology diagrams at runtime. It shows how to load project data, handle custom events, and dynamically update component attributes. This component does not include editing capabilities. ```vue ``` -------------------------------- ### genExportJson Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt Export the current editor state including canvas configuration, grid settings, and all components to a JSON structure for saving or transmission. ```APIDOC ## genExportJson ### Description Export the current editor state including canvas configuration, grid settings, and all components to a JSON structure for saving or transmission. ### Method `genExportJson(canvasConfig: Object, gridConfig: Object, components: Array): Object ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (This function is called directly with arguments). - **canvasConfig** (Object) - The current canvas configuration settings. - **gridConfig** (Object) - The current grid configuration settings. - **components** (Array) - An array representing all the components currently in the editor. ### Request Example ```javascript import { genExportJson } from 'maotu' import { globalStore } from 'maotu' const exportProject = () => { const { exportJson } = genExportJson( globalStore.canvasCfg, globalStore.gridCfg, globalStore.done_json ) console.log('Export JSON structure:', exportJson) // Example: Save to backend fetch('/api/projects', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'My Topology Project', data: exportJson, timestamp: Date.now() }) }) .then(response => response.json()) .then(result => { console.log('Project saved:', result.id) }) .catch(error => { console.error('Save failed:', error) }) // Example: Download as file const blob = new Blob([JSON.stringify(exportJson, null, 2)], { type: 'application/json' }) const url = URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = `project-${Date.now()}.json` link.click() URL.revokeObjectURL(url) } ``` ### Response #### Success Response (200) - **exportJson** (Object) - The exported JSON structure representing the current editor state. #### Response Example ```json { "canvasCfg": { "width": 1920, "height": 1080, "scale": 1, "color": "#1a1a1a", "img": "", "guide": true, "adsorp": true, "adsorp_diff": 5, "transform_origin": { "x": 0, "y": 0 }, "drag_offset": { "x": 0, "y": 0 } }, "gridCfg": { "enabled": true, "align": true, "size": 10 }, "json": [ { "id": "element-uuid-1", "title": "Temperature Sensor", "type": "svg", "binfo": { "left": 100, "top": 100, "width": 120, "height": 120, "angle": 0 }, "props": { "temperature": 25.5, "color": "#ff6b6b", "label": "Sensor A" }, "resize": true, "rotate": true, "lock": false, "active": false, "hide": false, "common_animations": { "val": "pulse", "delay": "delay-0s", "speed": "slow", "repeat": "infinite" }, "events": [] } ] } ``` ``` -------------------------------- ### Handle Event Callbacks in MtPreview (TypeScript) Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt Demonstrates a callback function 'handleEventCallback' designed to receive and process various event types triggered in the MtPreview environment. It logs the event type, the triggering item ID, and any arguments, with a switch statement to handle specific event types like 'buttonClick', 'alarmTriggered', and 'dataChanged'. ```typescript const handleEventCallback = (type, itemId, ...args) => { console.log('Event type:', type) console.log('Triggered by:', itemId) console.log('Arguments:', args) // Handle different event types switch(type) { case 'buttonClick': // Process button click break case 'alarmTriggered': // Handle alarm break case 'dataChanged': // Update related components break } } ``` -------------------------------- ### Register Custom Components in Left Sidebar - TypeScript Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt Registers custom SVG or Vue components to the left sidebar's component library for drag-and-drop use in the editor. It takes a configuration array, specifying component IDs, titles, types (svg or vue), thumbnails, and customizable properties. ```typescript import { leftAsideStore } from 'maotu' // Register custom SVG components leftAsideStore.registerConfig('Custom Sensors', [ { id: 'temperature-sensor', title: 'Temperature Sensor', type: 'svg', thumbnail: '/thumbnails/temp-sensor.png', svg: ` T `, props: { temperature: { title: 'Temperature', type: 'number', val: 25, disabled: false }, color: { title: 'Color', type: 'color', val: '#ff6b6b', disabled: false }, label: { title: 'Label', type: 'input', val: 'Temp', disabled: false }, unit: { title: 'Unit', type: 'select', val: 'C', options: [ { label: 'Celsius', value: 'C' }, { label: 'Fahrenheit', value: 'F' } ], disabled: false }, showValue: { title: 'Show Value', type: 'switch', val: true, disabled: false } } }, { id: 'pressure-gauge', title: 'Pressure Gauge', type: 'svg', thumbnail: '/thumbnails/pressure.png', svg: ` `, props: { value: { title: 'Pressure Value', type: 'number', val: 0, disabled: false }, maxValue: { title: 'Max Value', type: 'number', val: 100, disabled: false }, config: { title: 'Configuration', type: 'jsonEdit', val: { min: 0, max: 100, step: 1 }, disabled: false }, description: { title: 'Description', type: 'textArea', val: 'Pressure sensor description', disabled: false } } } ]) // Register Vue components leftAsideStore.registerConfig('Custom Vue Components', [ { id: 'data-table', title: 'Data Table', type: 'vue', thumbnail: '/thumbnails/table.png', props: { tableData: { title: 'Table Data', type: 'jsonEdit', val: [ { name: 'Item 1', value: 100 }, { name: 'Item 2', value: 200 } ], disabled: false }, headerColor: { title: 'Header Color', type: 'color', val: '#409eff', disabled: false } } } ]) ``` -------------------------------- ### Convert Exported JSON to Internal Format using TypeScript Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt The 'useExportJsonToDoneJson' function converts exported JSON data into the internal format required by editor or preview components. It restores component configurations and properties. Dependencies include the 'maotu' library. It takes exported JSON as input and returns canvas configuration, grid configuration, and the internal JSON representation. ```typescript import { useExportJsonToDoneJson } from 'maotu' // Load project from saved data const loadProject = async (projectId) => { try { // Fetch from backend const response = await fetch(`/api/projects/${projectId}`) const savedData = await response.json() const exportJson = savedData.data // Convert to internal format const { canvasCfg, gridCfg, importDoneJson } = useExportJsonToDoneJson(exportJson) console.log('Canvas config:', canvasCfg) console.log('Grid config:', gridCfg) console.log('Components:', importDoneJson) // Apply to editor if (mtEditRef.value) { mtEditRef.value.setImportJson(exportJson) } // Or apply to preview if (mtPreviewRef.value) { mtPreviewRef.value.setImportJson(exportJson) } // Or manually set to globalStore globalStore.canvasCfg = canvasCfg globalStore.gridCfg = gridCfg globalStore.setGlobalStoreDoneJson(importDoneJson) return { success: true, data: importDoneJson } } catch (error) { console.error('Failed to load project:', error) return { success: false, error: error.message } } } // Import from file upload const handleFileImport = (event) => { const file = event.target.files[0] if (!file) return const reader = new FileReader() reader.onload = (e) => { try { const exportJson = JSON.parse(e.target.result) const { canvasCfg, gridCfg, importDoneJson } = useExportJsonToDoneJson(exportJson) // Validate imported data if (!importDoneJson || importDoneJson.length === 0) { console.warn('No components found in imported file') } // Apply to editor mtEditRef.value?.setImportJson(exportJson) console.log('Import successful') } catch (error) { console.error('Invalid JSON file:', error) alert('Failed to import: Invalid file format') } } reader.readAsText(file) } ``` -------------------------------- ### Export Editor State to JSON - TypeScript Source: https://context7.com/yaolunmao/maotu-webtopo/llms.txt Exports the current editor state, including canvas and grid configurations, along with all components, into a JSON structure. This JSON can be used for saving or transmitting project data. It also demonstrates how to save to a backend API or download as a JSON file. ```typescript import { genExportJson } from 'maotu' import { globalStore } from 'maotu' // Inside MtEdit component or composable const exportProject = () => { const { exportJson } = genExportJson( globalStore.canvasCfg, globalStore.gridCfg, globalStore.done_json ) console.log('Export JSON structure:', exportJson) // Save to backend fetch('/api/projects', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'My Topology Project', data: exportJson, timestamp: Date.now() }) }) .then(response => response.json()) .then(result => { console.log('Project saved:', result.id) }) .catch(error => { console.error('Save failed:', error) }) // Or download as file const blob = new Blob([JSON.stringify(exportJson, null, 2)], { type: 'application/json' }) const url = URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = `project-${Date.now()}.json` link.click() URL.revokeObjectURL(url) } // Example exported JSON structure const exampleExportJson = { canvasCfg: { width: 1920, height: 1080, scale: 1, color: '#1a1a1a', img: '', guide: true, adsorp: true, adsorp_diff: 5, transform_origin: { x: 0, y: 0 }, drag_offset: { x: 0, y: 0 } }, gridCfg: { enabled: true, align: true, size: 10 }, json: [ { id: 'element-uuid-1', title: 'Temperature Sensor', type: 'svg', binfo: { left: 100, top: 100, width: 120, height: 120, angle: 0 }, props: { temperature: 25.5, color: '#ff6b6b', label: 'Sensor A' }, resize: true, rotate: true, lock: false, active: false, hide: false, common_animations: { val: 'pulse', delay: 'delay-0s', speed: 'slow', repeat: 'infinite' }, events: [] } ] } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.