UNPKG

@weareconceptstudio/cs-admin

Version:

A comprehensive React-based admin panel system with dynamic actions, form components, and design system

802 lines (660 loc) 19.5 kB
# CS Admin [![npm version](https://badge.fury.io/js/%40weareconceptstudio%2Fcs-admin.svg)](https://badge.fury.io/js/%40weareconceptstudio%2Fcs-admin) [![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC) A comprehensive React-based admin panel system built with modern technologies and designed for scalability and flexibility. ## ✨ Features - **🚀 Resource Management**: Full CRUD operations with dynamic actions - **📝 Form Builder**: Advanced form components with validation - **📁 Media Management**: File upload, organization, and manipulation - **👥 User Management**: Authentication, authorization, and user roles - **🌍 Internationalization**: Multi-language support - **📱 Responsive Design**: Mobile-first approach - **🔧 Extensible Architecture**: Plugin system and custom components - **🎨 Design System**: Comprehensive UI component library - **⚡ Performance**: Optimized for large datasets - **🔒 Security**: Built-in security best practices ## 📋 Table of Contents - [Installation](#-installation) - [Quick Start](#-quick-start) - [Architecture](#architecture) - [Core Features](#core-features) - [Form Components](#form-components) - [Design System](#design-system) - [Configuration](#configuration) - [Advanced Features](#advanced-features) - [Styling](#styling) - [Documentation](#-documentation) - [API Reference](#api-reference) - [Migration Guide](#migration-guide) - [Contributing](#contributing) - [License](#license) ## 📦 Installation ```bash npm install @weareconceptstudio/cs-admin ``` ### Peer Dependencies ```bash npm install react react-dom react-router-dom ``` ### Required Icons ```bash # Download and include icon fonts # Place in your public directory and import in your main CSS @import './icons/style.css'; ``` ## Quick Start ```jsx import React from 'react'; import { render } from 'react-dom'; import { Admin, Resource } from '@weareconceptstudio/cs-admin'; // Import icons import './icons/style.css'; // Admin configuration const config = { siteName: 'My Admin Panel', apiPrefix: 'http://localhost:8000/api/admin/', adminPrefix: '/admin', languages: [ { id: 'en', name: 'English' }, { id: 'es', name: 'Spanish' }, ], menu: { main: [ { title: 'Content', children: [ { title: 'Posts', path: '/admin/posts', icon: 'posts', key: 'posts', }, ], }, ], }, }; // Resource configuration const postConfig = { title: 'Posts', path: 'posts/*', name: 'posts', columns: [ { title: 'Title', dataIndex: 'title', key: 'title' }, { title: 'Status', dataIndex: 'status', key: 'status' }, { title: 'Created', dataIndex: 'created_at', key: 'created_at' }, ], form: PostForm, }; render( <Admin {...config}> <Resource {...postConfig} /> </Admin>, document.getElementById('root') ); ``` ## Architecture CS Admin is built with a modular architecture consisting of three main packages: ### 1. `@weareconceptstudio/cs-admin-core` Core functionality and utilities: - **State Management**: Zustand-based stores for data and media - **API Layer**: Axios-based HTTP client with interceptors - **Hooks**: Custom React hooks for common operations - **Context Providers**: React context for global state - **Utilities**: Helper functions and data manipulation ### 2. `@weareconceptstudio/cs-admin-ui` UI components and layouts: - **Design System**: Reusable UI components - **Form Components**: Advanced form fields and validation - **Resource Management**: List, create, edit, and show views - **Layout Components**: Header, sidebar, and page layouts - **Media Manager**: File upload and management interface ### 3. `@weareconceptstudio/cs-admin` Main package that combines core and UI: - **Admin Component**: Main admin panel wrapper - **Resource Component**: CRUD resource management - **Pages Component**: Custom page management - **Exports**: All components and utilities ## Core Features ### Resource Management Create full CRUD interfaces with minimal configuration: ```jsx <Resource title='Users' path='users/*' name='users' columns={[ { title: 'Name', dataIndex: 'name' }, { title: 'Email', dataIndex: 'email' }, { title: 'Role', dataIndex: 'role' }, ]} form={UserForm} // Dynamic actions dynamicActions={{ edit: (record) => ({ show: record.canEdit, disabled: record.isLocked, }), delete: { condition: (record) => record.canDelete, }, }} // Custom actions customActions={[ { key: 'activate', iconName: 'check', text: 'Activate', condition: (record) => record.status === 'inactive', onClick: (record) => activateUser(record.id), }, ]} /> ``` ### Dynamic Actions System The new dynamic actions system allows for sophisticated action management: ```jsx // Conditional actions based on record data dynamicActions: { edit: (record, context) => ({ show: record.status !== 'archived', disabled: record.isLocked, iconColor: record.isDraft ? 'orange' : 'black' }), delete: { condition: (record) => record.canDelete && record.orderCount === 0, iconColor: 'red' } } // Custom actions with full flexibility customActions: [ { key: 'approve', iconName: 'check', text: 'Approve', condition: (record) => record.status === 'pending', onClick: (record, context) => { approveRecord(record.id); context.refreshList?.(); } } ] ``` ### Form Builder Advanced form components with validation and media support: ```jsx import { FormContainer, InputField, SelectField, MediaPicker, Editor, DateTimePicker, ColorPicker, } from '@weareconceptstudio/cs-admin'; const PostForm = ({ action, current, onFinish }) => { return ( <FormContainer onFinish={onFinish} initialValues={current} layout='vertical'> <InputField name='title' label='Title' rules={[{ required: true, message: 'Title is required' }]} /> <Editor name='content' label='Content' config={{ toolbar: ['heading', 'bold', 'italic', 'link'], }} /> <MediaPicker name='featured_image' label='Featured Image' accept={['image/*']} maxFiles={1} /> <SelectField name='category' label='Category' options={categoryOptions} mode='multiple' /> <DateTimePicker name='publish_date' label='Publish Date' showTime /> </FormContainer> ); }; ``` ### Media Management Comprehensive media handling with file organization: ```jsx import { MediaPicker, MediaManager } from '@weareconceptstudio/cs-admin'; // In forms <MediaPicker name="gallery" label="Gallery" accept={['image/*', 'video/*']} maxFiles={10} multiple /> // Standalone media manager <MediaManager onSelect={(files) => console.log('Selected files:', files)} accept={['image/*']} maxFiles={5} /> ``` ### Internationalization Built-in multi-language support: ```jsx const config = { languages: [ { id: 'en', name: 'English' }, { id: 'es', name: 'Spanish' }, { id: 'fr', name: 'French' }, ], defaultLanguage: 'en', }; // In forms <FormContainer trans={true}> <InputField name='title' label='Title' trans={true} // Enables translation fields /> </FormContainer>; ``` ### User Management Complete user management system: ```jsx // User management is built-in const config = { menu: { main: [ { title: 'Users', children: [ { title: 'All Users', path: '/admin/users', key: 'users', }, { title: 'My Account', path: '/admin/account/my-account', key: 'my-account', }, ], }, ], }, }; ``` ## Design System CS Admin includes a comprehensive design system: ### Components - **Button**: Various button styles and sizes - **InputField**: Text inputs with validation - **SelectField**: Dropdown and multi-select - **Table**: Data tables with sorting and filtering - **Modal**: Popups and confirmations - **Status**: Status indicators - **Loader**: Loading states - **Icon**: Icon system - **Color**: Color picker and display - **Container**: Layout containers - **Tabs**: Tab navigation - **Switch**: Toggle switches - **Pagination**: Page navigation ### Form Components CS Admin includes a comprehensive set of form components for building complex admin interfaces: - **FormContainer**: Main form wrapper with layout, validation, and form management - **InputField**: Versatile input component supporting text, textarea, number, search, checkbox, and switch types - **SelectField**: Dropdown selection with single/multiple selection and option grouping - **Editor**: Rich text editor based on CKEditor 5 with image upload support - **MediaPicker**: File upload and media selection with dimension requirements - **DateTimePicker**: Date and time selection with multiple picker types - **ColorPicker**: Visual color selection with color picker interface - **ColorField**: Color selection from predefined color options - **ArrayField**: Dynamic array fields with drag-and-drop reordering - **TreeSelectField**: Hierarchical selection for tree-structured data - **SlugField**: Automatic URL-friendly slug generation - **MetaInputs**: Predefined SEO meta fields (title, description, image) > 📖 **Complete Form Components Documentation**: See [FORM_COMPONENTS.md](./FORM_COMPONENTS.md) for detailed API reference, usage examples, and best practices for all form components. ## Configuration ### Admin Configuration ```jsx const config = { // Basic settings siteName: 'My Admin Panel', logo: '/path/to/logo.png', // API configuration apiPrefix: 'http://localhost:8000/api/admin/', adminPrefix: '/admin', // Internationalization languages: [ { id: 'en', name: 'English' }, { id: 'es', name: 'Spanish' }, ], defaultLanguage: 'en', // Navigation menu: { main: [ { title: 'Content', children: [ { title: 'Posts', path: '/admin/posts', icon: 'posts', key: 'posts', }, ], }, ], collapsed: { settings: { title: 'Settings', children: [ { title: 'General', path: '/admin/settings/general', }, ], }, }, }, // Custom pages homePage: '/admin/dashboard', loginRedirectPage: '/admin/dashboard', // Media settings mediaLibraryPath: '/admin/media', canMediaDimensionChange: true, // Notifications notification: true, notificationStatusPath: 'notification-status', notificationsPath: 'notifications', }; ``` ### Resource Configuration ```jsx const resourceConfig = { // Basic settings title: 'Posts', name: 'posts', path: 'posts/*', primaryKey: 'id', // Display options hasList: true, hasCreate: { path: true, button: true }, hasEdit: true, hasShow: true, hasDelete: true, hasReplicate: false, // Table configuration columns: [ { title: 'Title', dataIndex: 'title', key: 'title' }, { title: 'Status', dataIndex: 'status', key: 'status' }, ], tableProps: { expandable: true, scroll: { x: 1000 }, }, // Pagination hasPagination: true, defaultPage: 1, defaultPageSize: 15, // Filtering and search hasFilter: true, hasSearch: true, hasSortBy: true, // Form configuration form: PostForm, // Dynamic actions dynamicActions: { edit: (record) => ({ show: record.canEdit }), delete: { condition: (record) => record.canDelete }, }, // Custom actions customActions: [ { key: 'publish', iconName: 'check', text: 'Publish', condition: (record) => record.status === 'draft', onClick: (record) => publishPost(record.id), }, ], }; ``` ## Advanced Features ### Custom Hooks ```jsx import { useList, useCurrent, useMedia, useNotification, useUpload } from '@weareconceptstudio/cs-admin'; // Data management const { list, loading, getList, create, update, delete: deleteItem } = useList(); // Media management const { upload, uploads, remove } = useMedia(); // Notifications const { openNotification } = useNotification(); // File upload const { uploadFile, progress } = useUpload(); ``` ### Custom Components ```jsx import { withUIContext } from '@weareconceptstudio/cs-admin-core'; const CustomComponent = ({ openPopup, winWidth }) => { return ( <div> <h3>Custom Component</h3> <button onClick={() => openPopup(<MyModal />)}>Open Modal</button> </div> ); }; export default withUIContext(CustomComponent, ['openPopup', 'winWidth']); ``` ### API Integration ```jsx import { api } from '@weareconceptstudio/cs-admin-core'; // Custom API calls const fetchCustomData = async () => { try { const response = await api.get('/custom-endpoint'); return response.data; } catch (error) { console.error('API Error:', error); } }; ``` ## Styling CS Admin uses styled-components for styling and supports: - **Theme Customization**: Override default colors and styles - **Responsive Design**: Mobile-first approach - **Component Styling**: Individual component customization - **Global Styles**: Site-wide style overrides ```jsx import { ThemeProvider } from 'styled-components'; const theme = { colors: { primary: '#1890ff', secondary: '#52c41a', danger: '#ff4d4f', }, fonts: { primary: 'Inter, sans-serif', }, }; <ThemeProvider theme={theme}> <Admin {...config}>{/* Your admin content */}</Admin> </ThemeProvider>; ``` ## 📚 Documentation ### Form Components 📖 **[Complete Form Components Documentation](./FORM_COMPONENTS.md)** - Detailed API reference, usage examples, and best practices for all form components including FormContainer, InputField, SelectField, Editor, MediaPicker, and more. ### Resource Structure 📖 **[Resource Structure Documentation](./RESOURCE_STRUCTURE.md)** - Comprehensive guide to the Resource component, including configuration options, dynamic actions, custom actions, and usage examples. ### DesignSystem Components 📖 **[DesignSystem Components Documentation](./DESIGNSYSTEM_COMPONENTS.md)** - Complete reference for all reusable UI components including Button, Table, Status, Switch, and more. ### Core Stores 📖 **[Core Stores Documentation](./CORE_STORES_DOCUMENTATION.md)** - Comprehensive guide to state management with Global Store, List Store, Current Store, Media Store, and Core Context. ### Examples Check the `examples/` directory for complete working examples: - **demo-admin**: Basic admin panel setup - **demo-murakami**: E-commerce admin interface - **demo-uniqueorn**: Content management system ## 🚀 Quick Start ### Basic Setup ```jsx import React from 'react'; import { render } from 'react-dom'; import { Admin, Resource } from '@weareconceptstudio/cs-admin'; // Import icons import './icons/style.css'; const config = { siteName: 'My Admin Panel', apiPrefix: 'http://localhost:8000/api/admin/', adminPrefix: '/admin', languages: [ { id: 'en', name: 'English' }, { id: 'es', name: 'Spanish' }, ], menu: { main: [ { title: 'Content', children: [ { title: 'Posts', path: '/admin/posts', icon: 'posts', key: 'posts', }, ], }, ], }, }; render( <Admin {...config}> <Resource title='Posts' path='posts/*' name='posts' columns={[ { title: 'Title', dataIndex: 'title' }, { title: 'Status', dataIndex: 'status' }, ]} form={PostForm} /> </Admin>, document.getElementById('root') ); ``` ### Dynamic Actions Example ```jsx <Resource title='Users' path='users/*' name='users' columns={[ { title: 'Name', dataIndex: 'name' }, { title: 'Email', dataIndex: 'email' }, { title: 'Role', dataIndex: 'role' }, ]} form={UserForm} // Dynamic actions based on record data dynamicActions={{ edit: (record) => ({ show: record.canEdit, disabled: record.isLocked, }), delete: { condition: (record) => record.canDelete, }, }} // Custom actions customActions={[ { key: 'activate', iconName: 'check', text: 'Activate', condition: (record) => record.status === 'inactive', onClick: (record) => activateUser(record.id), }, ]} /> ``` ## Migration Guide ### From showOptions to Dynamic Actions ```jsx // Old (showOptions - deprecated) const oldConfig = { showOptions: { url: (record) => `/articles/${record.slug}`, onClick: (record) => openInModal(record), }, }; // New (dynamicActions.show) const newConfig = { dynamicActions: { show: { path: (record) => `/articles/${record.slug}`, onClick: (record, context) => openInModal(record, context), condition: (record) => record.isPublic, iconColor: 'blue', }, }, }; ``` ## API Reference ### Admin Component Props | Prop | Type | Default | Description | | ------------------- | ------- | -------- | ----------------------------- | | `siteName` | string | - | Site name displayed in header | | `logo` | string | - | Logo image path | | `apiPrefix` | string | - | API base URL | | `adminPrefix` | string | `/admin` | Admin route prefix | | `languages` | array | `[]` | Available languages | | `defaultLanguage` | string | `'en'` | Default language | | `menu` | object | `{}` | Navigation menu configuration | | `homePage` | string | - | Home page route | | `loginRedirectPage` | string | - | Post-login redirect | | `mediaLibraryPath` | string | `/` | Media library route | | `notification` | boolean | `false` | Enable notifications | ### Resource Component Props | Prop | Type | Default | Description | | ---------------- | -------------- | ------- | ---------------------------- | | `title` | string | - | Resource title | | `name` | string | - | Resource name (API endpoint) | | `path` | string | - | Route path pattern | | `primaryKey` | string | `'id'` | Primary key field | | `columns` | array | `[]` | Table columns configuration | | `form` | component | - | Form component | | `hasList` | boolean | `true` | Enable list view | | `hasCreate` | boolean/object | `true` | Enable create view | | `hasEdit` | boolean | `true` | Enable edit view | | `hasShow` | boolean | `false` | Enable show view | | `hasDelete` | boolean | `true` | Enable delete action | | `hasReplicate` | boolean | `false` | Enable replicate action | | `dynamicActions` | object | `{}` | Dynamic action configuration | | `customActions` | array | `[]` | Custom action definitions | ## 📄 License This project is licensed under the ISC License - see the [LICENSE](LICENSE) file for details. ## 🆘 Support - 📖 **Documentation**: Check our comprehensive docs above - 📧 **Email**: info@conceptstudio.am ## 🙏 Acknowledgments - Built with [React](https://reactjs.org/) - UI components based on [Ant Design](https://ant.design/) - Rich text editing powered by [CKEditor 5](https://ckeditor.com/) - State management with [Zustand](https://github.com/pmndrs/zustand) --- <div align="center"> <strong>Built with ❤️ by <a href="https://conceptstudio.com">Concept Studio</a></strong> </div>