### Install Dependencies (npm) Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Installs project dependencies using npm. This is typically the first step before running any other commands. ```bash cd map npm install ``` -------------------------------- ### Start Development Server (mdye) Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Starts the development server with hot reload enabled. This command allows for rapid development and testing of the plugin. The server typically runs on a specific port, like http://localhost:3000. ```bash mdye dev ``` -------------------------------- ### Plugin SDK Initialization and Event Handling Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Demonstrates how to initialize the Ming Dao Cloud plugin SDK, access environment and configuration details, and subscribe to real-time events like filter updates and new record creation. ```APIDOC ## Plugin SDK Initialization and Event Handling ### Description Initializes the SDK, retrieves configuration, and sets up listeners for real-time updates from the Ming Dao Cloud platform. ### Method Initialization and Event Listeners ### Endpoint N/A (Client-side SDK) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { env, config, md_emitter } from 'mdye'; // Access environment configuration const pluginConfig = env.get(); console.log('Plugin Config:', pluginConfig); // Access worksheet metadata console.log('App ID:', config.appId); console.log('Worksheet ID:', config.worksheetId); console.log('View ID:', config.viewId); console.log('Controls:', config.controls); console.log('Filters:', config.filters); // Listen for real-time filter updates md_emitter.addListener('filters-update', (newFilters) => { console.log('Filters changed:', newFilters); // Implement logic to reload data based on newFilters // loadRecords(newFilters); }); // Listen for new record creation md_emitter.addListener('new-record', () => { console.log('New record created'); // Implement logic to refresh the view // refreshView(); }); ``` ### Response #### Success Response (N/A) Configuration data is logged to the console. Event listeners are set up. #### Response Example ```json { "config": { "appId": "60a1b2c3d4e5f6g7h8i9", "worksheetId": "70b2c3d4e5f6g7h8i9j0", "viewId": "80c3d4e5f6g7h8i9j0k1", "controls": [ { /* field definitions */ } ], "filters": [ /* current filter configuration */ ] }, "event": "filters-update", "data": [ /* new filter configuration */ ] } ``` ``` -------------------------------- ### Build and Deploy Plugin with mdye CLI Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Command-line instructions for building and deploying plugins to the Ming Dao Cloud platform using the `mdye` CLI tool. This is a bash command for the deployment process. ```bash # Placeholder for actual build and deploy command # Example: mdye plugin build --output dist # Example: mdye plugin deploy --file dist/plugin.zip ``` -------------------------------- ### Build Production Bundle (mdye) Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Builds the production-ready bundle for the plugin. The output is usually placed in a 'dist' directory. This command prepares the plugin for deployment. ```bash mdye build ``` -------------------------------- ### Initialize Ming Dao Cloud Plugin SDK and Access Config Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Initializes the Ming Dao Cloud plugin SDK to access environment configuration, worksheet metadata (appId, worksheetId, viewId, controls, filters), and subscribe to real-time platform events like filter updates and new record creation. ```javascript import { env, config, api, utils, md_emitter } from 'mdye'; // Access environment configuration const pluginConfig = env.get(); console.log(pluginConfig); // Output: { loadCount: 100, titleField: 'field_001', ... } // Access worksheet metadata console.log(config.appId); // '60a1b2c3d4e5f6g7h8i9' console.log(config.worksheetId); // '70b2c3d4e5f6g7h8i9j0' console.log(config.viewId); // '80c3d4e5f6g7h8i9j0k1' console.log(config.controls); // Array of field definitions console.log(config.filters); // Current filter configuration // Listen for real-time filter updates md_emitter.addListener('filters-update', (newFilters) => { console.log('Filters changed:', newFilters); // Reload data with new filters loadRecords(newFilters); }); // Listen for new record creation md_emitter.addListener('new-record', () => { console.log('New record created'); // Refresh the view refreshView(); }); ``` -------------------------------- ### Login to Ming Dao Cloud (mdye) Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Logs the user into the Ming Dao Cloud platform. This is a prerequisite for deploying or pushing plugins. It typically requires entering user credentials. ```bash mdye login ``` -------------------------------- ### Push Plugin to Ming Dao Cloud (mdye) Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Pushes the built plugin to Ming Dao Cloud. This command deploys the plugin and requires a commit message. The output includes a URL where the plugin can be accessed. ```bash mdye push -m "Initial map view implementation" ``` -------------------------------- ### Update Plugin (npm & mdye) Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Updates the plugin by first building the production bundle using npm and then pushing the changes to Ming Dao Cloud using `mdye push`. This is the standard workflow for deploying updates. ```bash npm run build mdye push -m "Fixed marker color issue" ``` -------------------------------- ### View Deployment Logs (mdye) Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Retrieves and displays recent deployment and error logs for the plugin. This is useful for debugging issues after deployment. ```bash mdye logs ``` -------------------------------- ### Sync Parameters (mdye) Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Synchronizes parameter configuration from a JSON file (`.config/params-config.json`) to the project. This command is part of the `mdye` SDK for managing plugin configurations. ```bash mdye sync-params ``` -------------------------------- ### Plugin Configuration Schema with JSON Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Defines the parameter schema for plugin configuration using a JSON format. This schema specifies input fields, their types, validation rules, and grouping for the plugin's settings UI. ```json { "version": "1.0.0", "params": [ { "id": "locationField", "label": "Location Field", "type": "control", "required": true, "controlTypes": [40], "hint": "Select the field containing geographic coordinates" }, { "id": "loadCount", "label": "Load Record Count", "type": "number", "required": false, "default": 100, "min": 10, "max": 1000, "hint": "Maximum number of records to load" }, { "id": "titleField", "label": "Title Field", "type": "control", "required": false, "controlTypes": [2], "hint": "Field to use as marker title" }, { "id": "displayFields", "label": "Display Fields", "type": "controls", "required": false, "hint": "Select fields to display in detail card" }, { "id": "tagType", "label": "Tag Display Style", "type": "select", "required": false, "default": "light", "options": [ { "value": "light", "label": "Light" }, { "value": "dark", "label": "Dark" }, { "value": "custom", "label": "Custom (from option field)" } ] }, { "id": "showFieldName", "label": "Show Field Names", "type": "boolean", "required": false, "default": true, "hint": "Display field names alongside values" }, { "id": "nodeColor", "label": "Timeline Node Color", "type": "select", "required": false, "default": "blue", "options": [ { "value": "blue", "label": "Blue" }, { "value": "red", "label": "Red" }, { "value": "yellow", "label": "Yellow" }, { "value": "green", "label": "Green" }, { "value": "custom", "label": "Custom (from option field)" } ], "visible": { "conditions": [ { "paramId": "tagType", "operator": "eq", "value": "custom" } ] } } ], "groups": [ { "title": "Basic Settings", "params": ["locationField", "loadCount", "titleField"] }, { "title": "Display Settings", "params": ["displayFields", "tagType", "showFieldName"] }, { "title": "Style Settings", "params": ["nodeColor"] } ] } ``` -------------------------------- ### Render Interactive Map with React and AMap Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Renders an interactive map component using React and the AMap library, displaying markers parsed from Ming Dao Cloud data. It fetches data using a hypothetical 'api' and 'config' object, processes it with 'parseRecord' and 'parseEnv' (assumed to be defined elsewhere), and calculates map center and zoom levels. Dependencies include React, '@amap/amap-react', and custom components like 'PinMarker'. Outputs an interactive map interface. ```javascript import React, { useState, useEffect } from 'react'; import { Map, Markers } from '@amap/amap-react'; import { api, config } from 'mdye'; import PinMarker from './components/PinMarker'; const MapView = () => { const [markers, setMarkers] = useState([]); const [center, setCenter] = useState({ lng: 116.397428, lat: 39.90923 }); const [zoom, setZoom] = useState(13); useEffect(() => { loadMapData(); }, []); const loadMapData = async () => { const response = await api.getFilterRows({ worksheetId: config.worksheetId, viewId: config.viewId, pageSize: 100, }); const parsed = response.data .map(record => parseRecord(record, parseEnv())) .filter(Boolean); setMarkers(parsed); const coords = parsed.map(m => m.location); setCenter(calculatePoleCenter(coords)); setZoom(calculateZoomLevel(coords)); }; return ( {markers.map(marker => ( showRecordDetail({ rowid: marker.recordId })} /> ))} ); }; export default MapView; ``` -------------------------------- ### Open Record Detail Modal using mdye utils Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Opens a modal dialog to display the full record detail interface for viewing or editing. It requires configuration details such as appId, worksheetId, and viewId, along with the specific recordId. This function is useful for creating interactive record lookup features. ```javascript import { utils, config } from 'mdye'; // Open a record's detail view const showRecordDetail = (record) => { utils.openRecordInfo({ appId: config.appId, worksheetId: config.worksheetId, viewId: config.viewId, recordId: record.rowid, }); }; // Example: Open record on table row click const handleRowClick = (event, record) => { event.stopPropagation(); showRecordDetail(record); console.log('Opened record:', record.rowid); }; // React component usage const RecordRow = ({ record }) => (
handleRowClick(e, record)}> {record.title}
); ``` -------------------------------- ### Parse Location Data with JavaScript Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Extracts geographic coordinates and associated data from Ming Dao Cloud location fields. It parses environment configuration, then processes individual records to extract location, color, title, and summary. Dependencies include '@ctrl/tinycolor' for color manipulation and a hypothetical 'env' and 'api' object for configuration and data fetching. Outputs a list of parsed markers suitable for map display. ```javascript import { tinycolor } from '@ctrl/tinycolor'; // Parse environment configuration const parseEnv = () => { const envConfig = env.get(); return { locationField: envConfig.locationField, loadCount: envConfig.loadCount || 100, titleField: envConfig.titleField, summaryField: envConfig.summaryField, coverField: envConfig.coverField, displayFields: envConfig.displayFields || [], showFieldName: envConfig.showFieldName !== false, tagType: envConfig.tagType || 'light', tagColorField: envConfig.tagColorField, }; }; // Parse record location and color const parseRecord = (record, config) => { const locationCell = record[config.locationField]; if (!locationCell?.value) return null; let location; try { const parsed = JSON.parse(locationCell.value); const [lng, lat] = parsed.split(',').map(Number); location = { lng, lat }; } catch (error) { return null; } // Get marker color from option field let color = '#2196F3'; // Default blue if (config.tagColorField) { const colorCell = record[config.tagColorField]; if (colorCell?.value) { try { const options = JSON.parse(colorCell.value); if (options[0]) { color = tinycolor(options[0]).toHexString(); } } catch (error) { console.error('Failed to parse color:', error); } } } return { recordId: record.rowid, location, color, title: record[config.titleField]?.value || 'Untitled', summary: record[config.summaryField]?.value || '', }; }; // Example usage const envConfig = parseEnv(); const records = await api.getFilterRows({ /* ... */ }); const markers = records.data .map(record => parseRecord(record, envConfig)) .filter(Boolean); console.log(`Parsed ${markers.length} valid map markers`); ``` -------------------------------- ### Fetch Filtered Records API Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Retrieves records from a specified worksheet and view, supporting filtering, sorting, and pagination. This is the primary method for fetching data to be visualized. ```APIDOC ## Fetch Filtered Records API ### Description Fetches records from a Ming Dao Cloud worksheet based on the current view's filters, sorting, and pagination settings. Useful for populating tables, maps, or other data visualizations. ### Method `GET` (Simulated via SDK method) ### Endpoint `/api/getFilterRows` (SDK internal) ### Parameters #### Path Parameters None #### Query Parameters - **worksheetId** (string) - Required - The ID of the worksheet to fetch records from. - **viewId** (string) - Required - The ID of the view to apply filters and settings from. - **pageIndex** (integer) - Optional - The index of the page to retrieve (defaults to 1). - **pageSize** (integer) - Optional - The number of records per page (defaults to 100). - **sortId** (string) - Optional - The ID of the field to sort by. - **isAsc** (boolean) - Optional - Specifies the sort order: `true` for ascending, `false` for descending. #### Request Body None ### Request Example ```javascript import { api, config } from 'mdye'; const loadRecords = async (pageIndex = 1, pageSize = 100) => { try { const response = await api.getFilterRows({ worksheetId: config.worksheetId, viewId: config.viewId, pageIndex: pageIndex, pageSize: pageSize, sortId: config.controls.length > 0 ? config.controls[0].controlId : undefined, // Sort by first field if available isAsc: false, // Descending order }); console.log('Total records:', response.total); console.log('Records:', response.data); // Expected output format: { total: 245, data: [{ rowid: '...', field_001: '...', ... }, ...] } return { records: response.data, total: response.total, hasMore: response.total > pageIndex * pageSize }; } catch (error) { console.error('Failed to load records:', error); return { records: [], total: 0, hasMore: false }; } }; // Example usage const page1Data = await loadRecords(1, 50); console.log(`Loaded ${page1Data.records.length} records out of ${page1Data.total} total.`); ``` ### Response #### Success Response (200) - **total** (integer) - The total number of records matching the filters. - **data** (array) - An array of record objects. Each object contains the `rowid` and field values. #### Response Example ```json { "total": 245, "data": [ { "rowid": "a1b2c3d4e5f6", "field_001": "Record Title 1", "field_002": "Some Value", "created_at": "2023-01-01T10:00:00Z" }, { "rowid": "f6e5d4c3b2a1", "field_001": "Record Title 2", "field_002": "Another Value", "created_at": "2023-01-02T11:00:00Z" } // ... more records ] } ``` ``` -------------------------------- ### Fetch Filtered Worksheet Records using MDYE API Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Fetches records from a Ming Dao Cloud worksheet with applied filters and pagination using the `api.getFilterRows` method. It requires `worksheetId`, `viewId`, and supports optional `pageIndex`, `pageSize`, sorting, and ordering. ```javascript import { api, config } from 'mdye'; // Fetch records with current view filters const loadRecords = async (pageIndex = 1, pageSize = 100) => { try { const response = await api.getFilterRows({ worksheetId: config.worksheetId, viewId: config.viewId, pageIndex: pageIndex, pageSize: pageSize, sortId: config.controls[0].controlId, // Sort by first field isAsc: false, // Descending order }); console.log('Total records:', response.total); console.log('Records:', response.data); // Output: { total: 245, data: [{ rowid: '...' }, ...] } return { records: response.data, total: response.total, hasMore: response.total > pageIndex * pageSize }; } catch (error) { console.error('Failed to load records:', error); return { records: [], total: 0, hasMore: false }; } }; // Example usage with pagination const page1 = await loadRecords(1, 50); console.log(`Loaded ${page1.records.length} of ${page1.total} records`); ``` -------------------------------- ### Render Field Values with mdye utils Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Converts raw field data from a record into a human-readable formatted string based on the field's control type. It takes control configuration and cell data as input and utilizes the `utils.renderText` method for formatting. This is essential for displaying data correctly in UIs. ```javascript import { utils } from 'mdye'; // Render different field types const renderFieldValue = (control, cell) => { const formatted = utils.renderText({ ...control, value: cell.value, }); return formatted; }; // Example: Render various field types const record = { field_001: { value: 'John Doe' }, // Text field_002: { value: '2024-11-25' }, // Date field_003: { value: '["opt_001","opt_002"]' }, // Options field_004: { value: '123.45' }, // Number }; const controls = [ { controlId: 'field_001', type: 2, controlName: 'Name' }, { controlId: 'field_002', type: 16, controlName: 'Date' }, { controlId: 'field_003', type: 11, controlName: 'Status' }, { controlId: 'field_004', type: 6, controlName: 'Amount' }, ]; controls.forEach(control => { const cell = record[control.controlId]; const text = renderFieldValue(control, cell); console.log(`${control.controlName}: ${text}`); }); // Output: // Name: John Doe // Date: 2024-11-25 // Status: Active, Verified // Amount: 123.45 ``` -------------------------------- ### Format Time and Group Records by Granularity (JavaScript) Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Formats timestamps according to a specified granularity (year, month, day, hour, minute, second) and generates human-readable labels for timeline grouping. It then groups an array of records based on these formatted times, returning an array of grouped objects, sorted by time with the newest first. Dependencies: moment.js. ```javascript import moment from 'moment'; // Format time based on granularity setting const formatTime = (timestamp, granularity) => { const date = moment(timestamp); const formats = { year: 'YYYY', month: 'YYYY-MM', day: 'YYYY-MM-DD', hour: 'YYYY-MM-DD HH:00', minute: 'YYYY-MM-DD HH:mm', second: 'YYYY-MM-DD HH:mm:ss', }; return date.format(formats[granularity] || formats.day); }; // Get display format for time labels const getTimeLabel = (timestamp, granularity) => { const date = moment(timestamp); const labels = { year: date.format('YYYY'), month: date.format('YYYY年MM月'), day: date.format('MM月DD日'), hour: date.format('MM月DD日 HH:00'), minute: date.format('HH:mm'), second: date.format('HH:mm:ss'), }; return labels[granularity] || labels.day; }; // Group records by time period const groupRecordsByTime = (records, timeFieldId, granularity) => { const groups = {}; records.forEach(record => { const timeCell = record[timeFieldId]; if (!timeCell?.value) return; const timeKey = formatTime(timeCell.value, granularity); if (!groups[timeKey]) { groups[timeKey] = { time: timeKey, label: getTimeLabel(timeCell.value, granularity), records: [], }; } groups[timeKey].records.push(record); }); return Object.values(groups).sort((a, b) => b.time.localeCompare(a.time) // Newest first ); }; // Example usage const records = [ { rowid: '1', field_date: { value: '2024-11-25 14:30:00' } }, { rowid: '2', field_date: { value: '2024-11-25 15:45:00' } }, { rowid: '3', field_date: { value: '2024-11-24 10:00:00' } }, ]; const dailyGroups = groupRecordsByTime(records, 'field_date', 'day'); console.log(dailyGroups); // Output: // [ // { time: '2024-11-25', label: '11月25日', records: [record1, record2] }, // { time: '2024-11-24', label: '11月24日', records: [record3] } // ] const hourlyGroups = groupRecordsByTime(records, 'field_date', 'hour'); console.log(hourlyGroups); // Output: // [ // { time: '2024-11-25 15:00', label: '11月25日 15:00', records: [record2] }, // { time: '2024-11-25 14:00', label: '11月25日 14:00', records: [record1] }, // { time: '2024-11-24 10:00', label: '11月24日 10:00', records: [record3] } // ] ``` -------------------------------- ### Timeline View Infinite Scroll with React Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Implements infinite scroll pagination for loading more timeline records in a React component. It uses `react-use` for viewport detection and `mdye` for API interactions and event handling. The component loads data incrementally as the user scrolls down. ```javascript import React, { useState, useEffect, useRef } from 'react'; import { useInViewport } from 'react-use'; import { api, config, md_emitter } from 'mdye'; const TimelineView = () => { const [records, setRecords] = useState([]); const [pageIndex, setPageIndex] = useState(1); const [hasMore, setHasMore] = useState(true); const [loading, setLoading] = useState(false); const loadMoreRef = useRef(null); const [inViewport] = useInViewport(loadMoreRef); // Load initial data useEffect(() => { loadRecords(1); // Listen for filter updates md_emitter.addListener('filters-update', () => { setRecords([]); setPageIndex(1); setHasMore(true); loadRecords(1); }); return () => { md_emitter.removeAllListeners('filters-update'); }; }, []); // Load more when scrolled to bottom useEffect(() => { if (inViewport && hasMore && !loading) { loadRecords(pageIndex + 1); } }, [inViewport, hasMore, loading]); const loadRecords = async (page) => { setLoading(true); try { const response = await api.getFilterRows({ worksheetId: config.worksheetId, viewId: config.viewId, pageIndex: page, pageSize: 20, sortId: config.timeFieldId, isAsc: false, // Newest first }); if (page === 1) { setRecords(response.data); } else { setRecords(prev => [...prev, ...response.data]); } setPageIndex(page); setHasMore(response.total > page * 20); } catch (error) { console.error('Failed to load records:', error); } finally { setLoading(false); } }; const groupedRecords = groupRecordsByTime( records, config.timeFieldId, config.granularity ); return (
{groupedRecords.map(group => ( ))} {hasMore && (
{loading ? 'Loading...' : 'Scroll for more'}
)} {!hasMore && records.length > 0 && (
No more records
)}
); }; export default TimelineView; ``` -------------------------------- ### Determine Node Colors for Timeline (JavaScript) Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Calculates the color for timeline nodes based on a configuration object. It supports predefined color palettes and custom colors defined in option fields associated with a record. The function also provides a utility to apply opacity to a given color for background styling. Dependencies: @ctrl/tinycolor. ```javascript import { tinycolor } from '@ctrl/tinycolor'; // Predefined color palette const COLOR_PALETTE = { blue: '#2196F3', red: '#F44336', yellow: '#FFC107', green: '#4CAF50', }; // Get node color based on settings const getNodeColor = (record, config) => { const { nodeColor, colorOptionField } = config; // Use predefined color if (nodeColor !== 'custom') { return COLOR_PALETTE[nodeColor] || COLOR_PALETTE.blue; } // Use color from option field if (colorOptionField) { const colorCell = record[colorOptionField]; if (colorCell?.value) { try { const options = JSON.parse(colorCell.value); if (options[0]) { const control = config.controls.find( c => c.controlId === colorOptionField ); const option = control?.options?.find( opt => opt.key === options[0] ); if (option?.color) { return tinycolor(option.color).toHexString(); } } } catch (error) { console.error('Failed to parse color option:', error); } } } // Fallback to default return COLOR_PALETTE.blue; }; // Apply color with opacity for backgrounds const getNodeBackgroundColor = (color, opacity = 0.1) => { return tinycolor(color).setAlpha(opacity).toRgbString(); }; // Example usage in timeline component const TimelineNode = ({ record, config }) => { const nodeColor = getNodeColor(record, config); const bgColor = getNodeBackgroundColor(nodeColor); return (
{record.title}
); }; // Example configuration const timelineConfig = { nodeColor: 'custom', colorOptionField: 'field_status', controls: [ { controlId: 'field_status', type: 11, options: [ { key: 'opt_001', value: 'Completed', color: '#4CAF50' }, { key: 'opt_002', value: 'In Progress', color: '#2196F3' }, { key: 'opt_003', value: 'Blocked', color: '#F44336' }, ], }, ], }; const record = { rowid: '123', title: 'Project Milestone', field_status: { value: '["opt_001"]' }, }; console.log(getNodeColor(record, timelineConfig)); // '#4CAF50' (green) ``` -------------------------------- ### Render Option Fields with Color Tags in Table Cells (JavaScript) Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt This JavaScript code snippet demonstrates how to render option fields as colored tags within table cells using React and styled-components. It parses JSON values to identify selected options, retrieves their associated colors, and displays them as styled tags. This is useful for visually distinguishing different states or categories in tabular data. ```javascript import React from 'react'; import styled from 'styled-components'; const OptionsTag = styled.span` display: inline-block; padding: 2px 8px; margin-right: 4px; border-radius: 3px; font-size: 12px; background-color: ${props => props.bgColor}; color: ${props => props.textColor}; `; const Options = ({ control, cell }) => { if (!cell?.value) return null; let options = []; try { const optionIds = JSON.parse(cell.value); options = control.options?.filter(opt => optionIds.includes(opt.key) ) || []; } catch (error) { console.error('Failed to parse options:', error); return null; } return (
{options.map(option => ( {option.value} ))}
); }; // Example usage in table cell const TableCell = ({ control, record }) => { const cell = record[control.controlId]; // Special rendering for option fields if (control.type === 11) { return ; } // Default text rendering return
{utils.renderText({ ...control, value: cell?.value })}
; }; // Example option control structure const optionControl = { controlId: 'field_005', type: 11, controlName: 'Status', options: [ { key: 'opt_001', value: 'Active', color: '#4CAF50' }, { key: 'opt_002', value: 'Pending', color: '#FF9800' }, { key: 'opt_003', value: 'Closed', color: '#9E9E9E' }, ], }; const record = { field_005: { value: '["opt_001","opt_002"]' }, }; // Renders: [Active (green)] [Pending (orange)] ``` -------------------------------- ### Load and Display Sub-sheet Records in Table Rows (JavaScript) Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt This JavaScript code snippet demonstrates how to expand table rows to reveal and load related records from sub-sheets. It utilizes React's useState hook to manage the expanded state of rows and the fetched sub-sheet data. An API call is made to fetch related records when a row is expanded, displaying them inline with pagination support. ```javascript import React, { useState } from 'react'; import { api, config } from 'mdye'; const TableWithSubsheet = () => { const [records, setRecords] = useState([]); const [expandedRows, setExpandedRows] = useState({}); const [subsheetData, setSubsheetData] = useState({}); const loadSubsheetRecords = async (recordId, controlId) => { const key = `${recordId}_${controlId}`; if (subsheetData[key]) return; // Already loaded const response = await api.getRowRelationRows({ worksheetId: config.worksheetId, rowId: recordId, controlId: controlId, pageIndex: 1, pageSize: 20, }); setSubsheetData(prev => ({ ...prev, [key]: { records: response.data, total: response.count, loaded: response.data.length, } })); }; const toggleExpand = async (recordId, subsheetControlId) => { const isExpanded = expandedRows[recordId]; setExpandedRows(prev => ({ ...prev, [recordId]: !isExpanded, })); if (!isExpanded) { await loadSubsheetRecords(recordId, subsheetControlId); } }; return (
{records.map(record => { const key = `${record.rowid}_${subsheetControlId}`; const isExpanded = expandedRows[record.rowid]; const subRecords = subsheetData[key]?.records || []; return (
toggleExpand(record.rowid, 'field_029')}> {record.title} {isExpanded ? '▼' : '▶'}
{isExpanded && (
{subRecords.map(subRecord => (
{subRecord.field_001?.value} - {subRecord.field_002?.value}
))} {subsheetData[key]?.total > subRecords.length && ( )}
)}
); })}
); }; export default TableWithSubsheet; ``` -------------------------------- ### Map View - Calculate Geographic Center and Zoom Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Calculates the geographic center (longitude and latitude) and an appropriate zoom level for a given set of map coordinates. It handles cases with no coordinates, a single coordinate, or multiple coordinates to determine the best fit for displaying markers on a map. ```javascript // Calculate center of multiple geographic coordinates const calculatePoleCenter = (coordinates) => { if (!coordinates || coordinates.length === 0) { return { lng: 116.397428, lat: 39.90923 }; // Beijing default } if (coordinates.length === 1) { return coordinates[0]; } let totalLng = 0; let totalLat = 0; coordinates.forEach(coord => { totalLng += coord.lng; totalLat += coord.lat; }); return { lng: totalLng / coordinates.length, lat: totalLat / coordinates.length, }; }; // Calculate appropriate zoom level based on coordinate spread const calculateZoomLevel = (coordinates) => { if (!coordinates || coordinates.length <= 1) return 13; const lngs = coordinates.map(c => c.lng); const lats = coordinates.map(c => c.lat); const lngSpread = Math.max(...lngs) - Math.min(...lngs); const latSpread = Math.max(...lats) - Math.min(...lats); const maxSpread = Math.max(lngSpread, latSpread); if (maxSpread > 10) return 5; if (maxSpread > 5) return 7; if (maxSpread > 1) return 9; if (maxSpread > 0.5) return 11; if (maxSpread > 0.1) return 13; return 15; }; // Example usage with map markers const locations = [ { lng: 116.404, lat: 39.915 }, // Beijing { lng: 121.473, lat: 31.230 }, // Shanghai { lng: 113.264, lat: 23.129 }, // Guangzhou ]; const center = calculatePoleCenter(locations); const zoom = calculateZoomLevel(locations); console.log(`Center: ${center.lng}, ${center.lat}`); console.log(`Zoom level: ${zoom}`); // Output: // Center: 117.047, 31.4246666666 // Zoom level: 7 ``` -------------------------------- ### Fetch Related Records from Sub-sheet using MDYE API Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Loads records from a related worksheet (sub-sheet) associated with a specific parent record. This function uses `api.getRowRelationRows` and requires the parent `recordId`, the `relationControlId` of the sub-sheet field, and an optional `pageIndex` for pagination. ```javascript import { api } from 'mdye'; // Load related records from a sub-sheet field const loadRelatedRecords = async (recordId, relationControlId, pageIndex = 1) => { try { const response = await api.getRowRelationRows({ worksheetId: config.worksheetId, rowId: recordId, controlId: relationControlId, pageIndex: pageIndex, pageSize: 20, }); console.log('Related records:', response.data); return { records: response.data, total: response.count, hasMore: response.count > pageIndex * 20 }; } catch (error) { console.error('Failed to load related records:', error); return { records: [], total: 0, hasMore: false }; } }; // Example: Load order items for a customer record const customerRecord = { rowid: 'abc123' }; const orderItemsField = 'field_029'; // Relation field ID const relatedData = await loadRelatedRecords( customerRecord.rowid, orderItemsField, 1 ); console.log(`Customer has ${relatedData.total} order items`); ``` -------------------------------- ### Fetch Related Records (Sub-sheet Data) API Source: https://context7.com/mingdaocom/plugin_view_samples/llms.txt Retrieves records from a related worksheet (sub-sheet) associated with a specific parent record through a relation field. Essential for displaying nested or linked data. ```APIDOC ## Fetch Related Records (Sub-sheet Data) API ### Description Fetches records from a related worksheet linked via a relation field to a specific parent record. This is commonly used for displaying sub-table data, like order items for a customer or tasks for a project. ### Method `GET` (Simulated via SDK method) ### Endpoint `/api/getRowRelationRows` (SDK internal) ### Parameters #### Path Parameters None #### Query Parameters - **worksheetId** (string) - Required - The ID of the worksheet where the parent record resides. - **rowId** (string) - Required - The `rowid` of the parent record. - **controlId** (string) - Required - The ID of the relation control field linking to the sub-sheet. - **pageIndex** (integer) - Optional - The page number for related records (defaults to 1). - **pageSize** (integer) - Optional - The number of related records per page (defaults to 20). #### Request Body None ### Request Example ```javascript import { api, config } from 'mdye'; const loadRelatedRecords = async (recordId, relationControlId, pageIndex = 1) => { try { const response = await api.getRowRelationRows({ worksheetId: config.worksheetId, // Assuming parent record is from the current worksheet context rowId: recordId, controlId: relationControlId, pageIndex: pageIndex, pageSize: 20, }); console.log('Related records:', response.data); // Expected output format: { count: 15, data: [{ rowid: '...', ... }, ...] } return { records: response.data, total: response.count, hasMore: response.count > pageIndex * 20 }; } catch (error) { console.error('Failed to load related records:', error); return { records: [], total: 0, hasMore: false }; } }; // Example: Load order items for a customer record const customerRecord = { rowid: 'abc123xyz' }; const orderItemsRelationFieldId = 'field_029'; // Example relation field ID for Order Items const relatedData = await loadRelatedRecords( customerRecord.rowid, orderItemsRelationFieldId, 1 ); console.log(`Customer has ${relatedData.total} order items.`); console.log('First order item:', relatedData.records.length > 0 ? relatedData.records[0] : 'None'); ``` ### Response #### Success Response (200) - **count** (integer) - The total number of related records. - **data** (array) - An array of related record objects. Each object contains the `rowid` and field values from the related worksheet. #### Response Example ```json { "count": 15, "data": [ { "rowid": "item1_a1b2c3d4", "field_item_name": "Product A", "field_quantity": 2, "field_price": 10.50 }, { "rowid": "item2_e5f6g7h8", "field_item_name": "Product B", "field_quantity": 1, "field_price": 25.00 } // ... more related records ] } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.