### React Menu Component Integration and Rendering
Source: https://context7.com/shenluwei/dplus-components/llms.txt
Demonstrates how to integrate the React Menu component into an application, including route setup, injecting menu props into components, and rendering the Menu with various configuration options like theme, logo, and WebSocket notifications.
```tsx
import React from 'react';
import ReactDOM from 'react-dom';
import { Menu } from '@dianplusjs/dp-components';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
// Define application routes
const App = () => (
} />
} />
} />
} />
);
// Dashboard component with menu injection
@Menu.inject
class Dashboard extends React.Component {
componentDidMount() {
const { menu } = this.props;
console.log('Menu display mode:', menu.displayMode());
}
toggleFullScreen = () => {
const { menu } = this.props;
menu.toggleDisplayMode();
};
render() {
return (
Dashboard
Toggle Full Screen
);
}
}
// Render application with Menu wrapper
Menu.render( , {
domId: 'root',
type: 'default',
theme: 'dark',
appLogo: '/logo.png',
allowFullScreen: true,
allowSettings: true,
allowI18n: true,
allowAppStore: true,
allowHelp: true,
changePasswordUrl: '/api/user/change-password',
// WebSocket configuration for real-time notifications
webSocketConfig: {
url: 'ws://localhost:8080/ws',
key: 'app_notifications',
onMessage: (message) => {
console.log('Received notification:', message);
},
},
// Custom audio for notifications
messageAudioSrc: '/audio/notification.mp3',
// Message popup component
messagePopup: (props) => (
{props.title}
{props.content}
),
// Custom toolbar elements
customElements: [
{
element: Custom Button ,
onClick: () => console.log('Custom action'),
},
],
// Drawer configuration
drawer: {
visible: false,
width: 400,
content: Drawer Content
,
},
// Menu filtering
menuFilter: (item) => {
// Hide admin menu for non-admin users
if (item.id === 'admin' && !window.isAdmin) {
return false;
}
return true;
},
// Menu data transformation
menusMap: (items) => {
return items.map(item => ({
...item,
name: item.name.toUpperCase(),
}));
},
});
// Alternative: Use Menu as component
const MenuComponent = () => (
);
```
--------------------------------
### Invoice Template Designer using PrintDesign (React/TSX)
Source: https://context7.com/shenluwei/dplus-components/llms.txt
This example demonstrates how to use the PrintDesign component to create and manage an invoice template. It includes functionality for saving changes, previewing the template with sample data, and defining data sources. Dependencies include React, Ant Design, and the @dianplusjs/dp-components library. The component takes template data, dimensions, object identifiers, and callback functions for save and preview actions.
```tsx
import React, { useState } from 'react';
import { PrintDesign } from '@dianplusjs/dp-components';
import { Button, message } from 'antd';
const InvoiceTemplateDesigner = () => {
const [templateData, setTemplateData] = useState({
id: 'TPL_001',
name: 'Invoice Template',
width: 210,
height: 297,
unit: 'mm',
pages: [{
id: 'page_1',
header: { height: 50, widgets: [] },
body: { widgets: [] },
footer: { height: 30, widgets: [] },
}],
dataSources: [
{
id: 'ds_order',
name: 'Order Data',
fields: ['orderNo', 'orderDate', 'customerName', 'totalAmount']
},
{
id: 'ds_items',
name: 'Order Items',
fields: ['productName', 'quantity', 'price', 'subtotal']
}
]
});
const handleSave = (updatedTemplate) => {
console.log('Saving template:', updatedTemplate);
setTemplateData(updatedTemplate);
// Simulate API call
setTimeout(() => {
message.success('Template saved successfully!');
}, 500);
};
const handlePreview = (template) => {
console.log('Previewing template:', template);
// Generate preview with sample data
const sampleData = {
orderNo: 'ORD20241221001',
orderDate: '2024-12-21',
customerName: 'ABC Corporation',
totalAmount: 1250.00,
items: [
{ productName: 'Product A', quantity: 2, price: 250.00, subtotal: 500.00 },
{ productName: 'Product B', quantity: 3, price: 250.00, subtotal: 750.00 },
]
};
// Open preview window
message.info('Opening print preview...');
};
const modalInfo = {
objectName: 'Sales Order',
templateName: 'Invoice',
};
return (
Invoice Template Designer
Design custom invoice templates with drag-and-drop widgets
message.info('Loading reference templates...')}
>
Load Template
}
/>
Available Widgets:
Text: Static or dynamic text fields
Image: Logos, product photos
Barcode: 1D/2D barcodes
Table: Line items, details
Line: Separators, borders
);
};
export default InvoiceTemplateDesigner;
```
--------------------------------
### Implement Multi-Method Payment with React
Source: https://context7.com/shenluwei/dplus-components/llms.txt
This React component demonstrates how to integrate and use the Payment component for handling multiple payment methods. It includes setting up order data, managing payment state, and handling payment results via callbacks. Dependencies include React and Dplus UI components.
```tsx
import React, { useState } from 'react';
import { Payment } from '@dianplusjs/dp-components';
import { Dialog } from '@dianplusjs/dp-components';
const CheckoutPage = () => {
const [showPayment, setShowPayment] = useState(false);
const [orderData] = useState({
orderId: 'ORD20241221001',
totalAmount: 299.99,
brandId: '10029',
applyId: 'POS_001',
bizUniqueId: 'ORDER_001',
});
const handlePaymentResult = (result) => {
console.log('Payment result:', result);
if (result === 'success') {
Dialog.success({
title: 'Payment Successful',
content: `Order ${orderData.orderId} has been paid successfully!`,
});
} else if (result === 'fail') {
Dialog.error({
title: 'Payment Failed',
content: 'Payment was unsuccessful. Please try again.',
});
} else if (result === 'timeout') {
Dialog.warning({
title: 'Payment Timeout',
content: 'Please check the order list for payment status.',
});
}
setShowPayment(false);
};
const handlePrint = () => {
console.log('Printing receipt for order:', orderData.orderId);
};
return (
Order Summary
Order ID: {orderData.orderId}
Total Amount: ${orderData.totalAmount}
setShowPayment(true)}>
Proceed to Payment
{showPayment && (
console.log('Open gift card:', amount)}
openCashCoupon={(amount) => console.log('Open cash coupon:', amount)}
currentState={(state) => console.log('Payment state:', state)}
loaded={() => console.log('Payment methods loaded')}
/>
)}
);
};
export default CheckoutPage;
```
--------------------------------
### Implement Draggable Dialog and Confirmation Modals
Source: https://context7.com/shenluwei/dplus-components/llms.txt
This React component demonstrates the usage of the enhanced Dialog component for managing users. It showcases how to open a draggable dialog for adding new users and utilizes utility methods like `Dialog.confirm`, `Dialog.success`, `Dialog.error`, and `Dialog.warning` for user interactions and feedback. It depends on React, `@dianplusjs/dp-components`, and `antd` for UI elements and modal functionalities.
```tsx
import React, { useState } from 'react';
import { Dialog } from '@dianplusjs/dp-components';
import { Button, Input, Form } from 'antd';
const UserManagement = () => {
const [visible, setVisible] = useState(false);
const [formData, setFormData] = useState({ name: '', email: '' });
const handleDelete = (userId) => {
Dialog.confirm({
title: 'Confirm Deletion',
content: (
Are you sure you want to delete this user?
This action cannot be undone.
),
okText: 'Delete',
okType: 'danger',
onOk: async (e, close) => {
try {
// Simulate API call
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('User deleted:', userId);
Dialog.success({
title: 'Success',
content: 'User deleted successfully!',
});
close();
} catch (error) {
Dialog.error({
title: 'Error',
content: 'Failed to delete user: ' + error.message,
});
return Promise.reject(error);
}
},
onCancel: (e, close) => {
close();
}
});
};
const handleSave = (e, close) => {
if (!formData.name || !formData.email) {
Dialog.warning({
title: 'Validation Error',
content: 'Please fill in all required fields',
});
return;
}
console.log('Saving user:', formData);
close();
setVisible(false);
};
return (
setVisible(true)}>
Add User
{
close();
setVisible(false);
}}
okText="Save"
cancelText="Cancel"
>
setFormData({ ...formData, name: e.target.value })}
placeholder="Enter user name"
/>
setFormData({ ...formData, email: e.target.value })}
placeholder="Enter email address"
/>
handleDelete('user123')}>
Delete User
);
};
export default UserManagement;
```
--------------------------------
### React Form with Business Data Selectors
Source: https://context7.com/shenluwei/dplus-components/llms.txt
This React component demonstrates how to use Easy Components for selecting business data within a form. It utilizes Ant Design for form management and integrates modal selectors for stores, products, channels, and warehouses. It handles state management for selections and includes submission logic.
```tsx
import React, { useState } from 'react';
import { Easy, Select } from '@dianplusjs/dp-components';
import { Form, Button } from 'antd';
const { StoreModal, GoodsSkuModal, ChannelModal, WarehouseModal } = Easy;
const BusinessDataForm = () => {
const [formRef] = Form.useForm();
const [selectedStore, setSelectedStore] = useState(null);
const [selectedProducts, setSelectedProducts] = useState([]);
const handleSubmit = () => {
const values = formRef.getFieldsValue();
console.log('Form values:', {
...values,
store: selectedStore,
products: selectedProducts,
});
};
return (
{Select.wrapModal({ placeholder: 'Choose a store', allowClear: true })(
{
setSelectedStore(selected);
formRef.setFieldsValue({ store: selected });
}}
queryConfig={{
disabled: ['storeName'],
initValues: { storeCode: 'ST' }
}}
/>
)}
{Select.wrapModal({ placeholder: 'Choose products', allowClear: true })(
{
setSelectedProducts(selected);
formRef.setFieldsValue({ products: selected });
}}
/>
)}
{Select.wrapModal({ placeholder: 'Choose channel' })(
formRef.setFieldsValue({ channel: selected })}
channelControl="ACCESS_CONTROL_KEY"
/>
)}
Submit Order
);
};
export default BusinessDataForm;
```
--------------------------------
### AppLayout Usage with Automatic Height Calculation in React
Source: https://context7.com/shenluwei/dplus-components/llms.txt
This React component demonstrates the usage of AppLayout with automatic height calculation for the content area. It utilizes Ant Design components for inputs, buttons, and pagination. The component fetches and displays data, simulating a dashboard page.
```tsx
import React, { useState, useEffect } from 'react';
import { AppLayout } from '@dianplusjs/dp-components';
import { Input, Button, Pagination } from 'antd';
// Extended component with automatic height calculation
const DashboardPage = AppLayout.extend((props) => {
const { maxContentHeight } = props;
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const [page, setPage] = useState(1);
const [language, setLanguage] = useState('en-US');
useEffect(() => {
// Simulate data loading
setLoading(true);
setTimeout(() => {
setData(Array.from({ length: 50 }, (_, i) => ({ id: i, name: `Item ${i}` })));
setLoading(false);
}, 1000);
}, [page]);
const routes = [
{ name: 'Home', href: '#/' },
{ name: 'Reports', href: '#/reports' },
{ name: 'Sales Dashboard', href: '' },
];
return (
Export
Settings
}
prompt={{
text: 'You have unsaved changes. Continue?',
visible: false
}}
/>
console.log('Search:', value)}
/>
Create New
Import
Export
{data.map(item => (
{item.name}
))}
`Total ${total} items`}
/>
);
});
export default DashboardPage;
```
--------------------------------
### React Component for Employee Data Management with DjExcel
Source: https://context7.com/shenluwei/dplus-components/llms.txt
This React component demonstrates the usage of DjExcel for managing employee data. It includes functionalities for exporting employee records with specified fields and importing employee data via Excel files. The component utilizes Ant Design components for UI elements and DjExcel's components for Excel operations. It also features a task window to monitor import/export job progress. Dependencies include 'react', '@dianplusjs/dp-components', and 'antd'.
```tsx
import React from 'react';
import { DjExcel, BooleanTrigger } from '@dianplusjs/dp-components';
import { Space, Button } from 'antd';
const EmployeeDataManagement = () => {
const currentBrandId = '10029';
const currentUserId = '100414';
const exportConfig = {
jobName: 'Export Employees',
bizType: '13051',
entId: currentBrandId,
userId: currentUserId,
titles: DjExcel.generateExcelXML([
{ key: 'storageCode', name: 'Store Code', width: 100 },
{ key: 'depCode', name: 'Department Code', width: 120 },
{ key: 'atom.jobNumber', name: 'Job Number', required: 'true', width: 100 },
{ key: 'atom.realName', name: 'Full Name', required: 'true', width: 150 },
{ key: 'atom.mobilePhone', name: 'Mobile Phone', width: 120 },
{ key: 'typeDesc', name: 'System Type', width: 100 },
{ key: 'roleName', name: 'Role', width: 120 },
{ key: 'statusDesc', name: 'Status', width: 80 },
{
key: 'photo',
name: 'Photo',
type: 6,
imageW: 50,
imageH: 50,
width: 80
},
]),
queryContent: JSON.stringify({
brandId: currentBrandId,
pageSize: 1000,
status: 'ACTIVE',
}),
};
const importConfig = {
entId: currentBrandId,
jobName: 'Import Employees',
bizType: '13051',
userId: currentUserId,
};
return (
Employee Data Management
{/* Export Button */}
Export Employees
{
console.log('Export job created:', jobId);
}}
/>
{/* Import Button */}
{
console.log('Import result:', result);
if (result.success) {
console.log(`Imported ${result.totalCount} employees`);
}
},
}}
>
Import Employees
{/* Task List */}
View Tasks
Export: Downloads all active employees with specified fields
Import: Upload Excel file to batch create/update employee records
Task List: Monitor import/export job progress and download results
);
};
export default EmployeeDataManagement;
```
--------------------------------
### Implement BigTable High-Performance Data Table in React
Source: https://context7.com/shenluwei/dplus-components/llms.txt
Demonstrates the implementation of the BigTable component, a high-performance data table supporting virtual scrolling, column filtering, sorting, and row selection. It requires React and the '@dianplusjs/dp-components' library. The component takes data source and column definitions as input and handles table state changes and row selection.
```tsx
import React, { useRef } from 'react';
import { BigTable } from '@dianplusjs/dp-components';
const MyDataTable = () => {
const tableRef = useRef(null);
// Generate sample data
const dataSource = Array.from({ length: 10000 }, (_, i) => ({
id: i,
region: `Region ${i % 10}`,
store: `Store ${i}`,
sales: Math.floor(Math.random() * 100000),
date: new Date(2024, i % 12, i % 28).toLocaleDateString(),
}));
const columns = [
{
key: 'region',
title: 'Region',
dataIndex: ['region'],
fixed: 'left',
sortEnabled: true,
filterEnabled: true,
filterDataType: 'TEXT',
width: 120,
},
{
key: 'store',
title: 'Store',
dataIndex: ['store'],
sortEnabled: true,
filterEnabled: true,
width: 160,
},
{
key: 'sales',
title: 'Sales Amount',
dataIndex: ['sales'],
sortEnabled: true,
filterEnabled: true,
filterDataType: 'NUMBER',
render: (value) => `$${value.toLocaleString()}`,
},
{
key: 'date',
title: 'Date',
dataIndex: ['date'],
sortEnabled: true,
filterEnabled: true,
filterDataType: 'DATE_RANGE',
},
];
const handleTableChange = (filters, sorters) => {
console.log('Filters:', filters);
console.log('Sorters:', sorters);
};
const handleExport = () => {
tableRef.current?.exportToExcel();
};
return (
Export to Excel
row.id}
dataSource={dataSource}
columns={columns}
options={{
tableHeadDragEnabled: true,
tableHeadFilterEnabled: true,
tableHeadSorterEnabled: true,
hoverRowEnable: true,
frozen: { rowCount: 1 },
}}
onTableChange={handleTableChange}
rowSelection={{
type: 'checkbox',
onChange: (selectedKeys, selectedRows) => {
console.log(`Selected ${selectedKeys.length} rows`);
},
}}
/>
);
};
export default MyDataTable;
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.