ui-admin-lib 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +473 -477
  2. package/package.json +64 -64
package/README.md CHANGED
@@ -1,477 +1,473 @@
1
- # UI Admin Library
2
-
3
- Библиотека для быстрого создания административных панелей на React с полным CRUD функционалом. Создайте полноценную админку всего в несколько строк кода!
4
-
5
- ## Установка
6
-
7
- ```bash
8
- npm install ui-admin-lib
9
- ```
10
-
11
- ## Использование
12
-
13
- Создайте админ-панель в несколько строк:
14
-
15
- ```tsx
16
- import { AdminPanel, CrudService } from 'ui-admin-lib'
17
- import 'ui-admin-lib/styles'
18
-
19
- // 1. Создайте сервис для работы с API
20
- const userService = new CrudService({
21
- baseUrl: 'https://api.example.com/users',
22
- headers: {
23
- 'Authorization': 'Bearer YOUR_TOKEN'
24
- }
25
- })
26
-
27
- // 2. Определите модель
28
- const userModel = {
29
- name: 'users',
30
- label: 'Пользователи',
31
- service: userService,
32
- columns: [
33
- { key: 'id', title: 'ID', dataIndex: 'id' },
34
- { key: 'name', title: 'Имя', dataIndex: 'name' },
35
- { key: 'email', title: 'Email', dataIndex: 'email' },
36
- ],
37
- fields: [
38
- { name: 'name', label: 'Имя', type: 'text', required: true },
39
- { name: 'email', label: 'Email', type: 'email', required: true },
40
- ],
41
- }
42
-
43
- // 3. Используйте AdminPanel
44
- function App() {
45
- return (
46
- <AdminPanel
47
- title="Моя админка"
48
- models={[userModel]}
49
- login={{
50
- onSubmit: async (username, password) => {
51
- // Ваша логика авторизации
52
- },
53
- }}
54
- />
55
- )
56
- }
57
- ```
58
-
59
- Всё! AdminPanel автоматически создаст:
60
- - Страницу входа
61
- - Боковую навигацию
62
- - Таблицы с данными
63
- - Формы для создания/редактирования
64
- - Полный CRUD функционал
65
-
66
- ## Полный пример конфигурации
67
-
68
- Вот полный пример с несколькими моделями и всеми возможностями:
69
-
70
- ```tsx
71
- import { AdminPanel, CrudService, AdminModel } from 'ui-admin-lib'
72
- import type { Column, FormField } from 'ui-admin-lib'
73
- import 'ui-admin-lib/styles'
74
-
75
- // Типы данных
76
- interface User {
77
- id: number
78
- name: string
79
- email: string
80
- role: string
81
- active: boolean
82
- }
83
-
84
- interface Product {
85
- id: number
86
- title: string
87
- price: number
88
- category: string
89
- inStock: boolean
90
- }
91
-
92
- // Создание сервисов для работы с API
93
- const userService = new CrudService<User>({
94
- baseUrl: 'https://api.example.com/users',
95
- headers: {
96
- 'Authorization': 'Bearer YOUR_TOKEN',
97
- 'Content-Type': 'application/json'
98
- },
99
- // Опционально: кастомные URL для операций
100
- getListUrl: () => 'https://api.example.com/users',
101
- getDetailUrl: (id) => `https://api.example.com/users/${id}`,
102
- getCreateUrl: () => 'https://api.example.com/users',
103
- getUpdateUrl: (id) => `https://api.example.com/users/${id}`,
104
- getDeleteUrl: (id) => `https://api.example.com/users/${id}`,
105
- // Опционально: трансформация данных
106
- transformRequest: (data) => data, // Преобразование перед отправкой
107
- transformResponse: (data) => data, // Преобразование после получения
108
- })
109
-
110
- const productService = new CrudService<Product>({
111
- baseUrl: 'https://api.example.com/products',
112
- headers: {
113
- 'Authorization': 'Bearer YOUR_TOKEN'
114
- }
115
- })
116
-
117
- // Конфигурация модели пользователей
118
- const userModel: AdminModel<User> = {
119
- name: 'users',
120
- label: 'Пользователи',
121
- service: userService,
122
- columns: [
123
- { key: 'id', title: 'ID', dataIndex: 'id' },
124
- { key: 'name', title: 'Имя', dataIndex: 'name' },
125
- { key: 'email', title: 'Email', dataIndex: 'email' },
126
- {
127
- key: 'role',
128
- title: 'Роль',
129
- dataIndex: 'role',
130
- render: (value) => value.charAt(0).toUpperCase() + value.slice(1),
131
- },
132
- {
133
- key: 'active',
134
- title: 'Активен',
135
- dataIndex: 'active',
136
- render: (value) => (value ? 'Да' : 'Нет'),
137
- },
138
- ] as Column<User>[],
139
- fields: [
140
- { name: 'name', label: 'Имя', type: 'text', required: true, placeholder: 'Введите имя' },
141
- { name: 'email', label: 'Email', type: 'email', required: true, placeholder: 'Введите email' },
142
- {
143
- name: 'role',
144
- label: 'Роль',
145
- type: 'select',
146
- required: true,
147
- options: [
148
- { value: 'admin', label: 'Администратор' },
149
- { value: 'user', label: 'Пользователь' },
150
- ],
151
- },
152
- { name: 'active', label: 'Активен', type: 'checkbox' },
153
- ] as FormField[],
154
- // Опционально: кастомная функция получения ID
155
- getItemId: (item) => item.id,
156
- }
157
-
158
- // Конфигурация модели товаров
159
- const productModel: AdminModel<Product> = {
160
- name: 'products',
161
- label: 'Товары',
162
- service: productService,
163
- columns: [
164
- { key: 'id', title: 'ID', dataIndex: 'id' },
165
- { key: 'title', title: 'Название', dataIndex: 'title' },
166
- {
167
- key: 'price',
168
- title: 'Цена',
169
- dataIndex: 'price',
170
- render: (value) => `${value.toLocaleString('ru-RU')} ₽`,
171
- },
172
- { key: 'category', title: 'Категория', dataIndex: 'category' },
173
- {
174
- key: 'inStock',
175
- title: 'В наличии',
176
- dataIndex: 'inStock',
177
- render: (value) => (value ? 'Да' : 'Нет'),
178
- },
179
- ] as Column<Product>[],
180
- fields: [
181
- { name: 'title', label: 'Название', type: 'text', required: true },
182
- { name: 'price', label: 'Цена', type: 'number', required: true },
183
- { name: 'category', label: 'Категория', type: 'text', required: true },
184
- { name: 'inStock', label: 'В наличии', type: 'checkbox' },
185
- ] as FormField[],
186
- }
187
-
188
- // Использование
189
- function App() {
190
- return (
191
- <AdminPanel
192
- title="Админ панель"
193
- logo={<span>Мой Логотип</span>} // Опционально: кастомный логотип
194
- models={[userModel, productModel]}
195
- login={{
196
- onSubmit: async (username, password) => {
197
- // Ваша логика авторизации
198
- const response = await fetch('https://api.example.com/auth/login', {
199
- method: 'POST',
200
- headers: { 'Content-Type': 'application/json' },
201
- body: JSON.stringify({ username, password }),
202
- })
203
- if (!response.ok) {
204
- throw new Error('Неверное имя пользователя или пароль')
205
- }
206
- const data = await response.json()
207
- // Сохраните токен
208
- localStorage.setItem('token', data.token)
209
- },
210
- }}
211
- user={{
212
- name: 'Администратор', // Опционально: имя пользователя в header
213
- onLogout: () => {
214
- // Опционально: обработчик выхода
215
- localStorage.removeItem('token')
216
- },
217
- }}
218
- />
219
- )
220
- }
221
- ```
222
-
223
- ## Типы полей форм
224
-
225
- Поддерживаются следующие типы полей в `FormField`:
226
-
227
- - `text` - Текстовое поле
228
- - `email` - Email поле
229
- - `number` - Числовое поле
230
- - `password` - Поле пароля
231
- - `textarea` - Многострочное поле
232
- - `select` - Выпадающий список (требует `options`)
233
- - `checkbox` - Чекбокс
234
- - `radio` - Радиокнопки (требует `options`)
235
-
236
- Пример конфигурации поля:
237
-
238
- ```tsx
239
- {
240
- name: 'fieldName', // Имя поля (обязательно)
241
- label: 'Метка поля', // Метка поля (обязательно)
242
- type: 'text', // Тип поля (опционально, по умолчанию 'text')
243
- required: true, // Обязательное поле (опционально)
244
- placeholder: 'Подсказка', // Подсказка (опционально)
245
- disabled: false, // Отключено (опционально)
246
- options: [ // Опции для select/radio (обязательно для этих типов)
247
- { value: 'value1', label: 'Метка 1' },
248
- { value: 'value2', label: 'Метка 2' },
249
- ],
250
- }
251
- ```
252
-
253
- ## Быстрый старт
254
-
255
- ```bash
256
- npm install ui-admin-lib
257
- ```
258
-
259
- ```tsx
260
- import { AdminPanel, CrudService } from 'ui-admin-lib'
261
- import 'ui-admin-lib/styles'
262
-
263
- const userService = new CrudService({
264
- baseUrl: 'https://api.example.com/users',
265
- })
266
-
267
- const userModel = {
268
- name: 'users',
269
- label: 'Пользователи',
270
- service: userService,
271
- columns: [
272
- { key: 'id', title: 'ID', dataIndex: 'id' },
273
- { key: 'name', title: 'Имя', dataIndex: 'name' },
274
- ],
275
- fields: [
276
- { name: 'name', label: 'Имя', type: 'text', required: true },
277
- ],
278
- }
279
-
280
- function App() {
281
- return <AdminPanel models={[userModel]} />
282
- }
283
- ```
284
-
285
- ## Демо приложение
286
-
287
- Запустите демо приложение для просмотра всех возможностей:
288
-
289
- ```bash
290
- git clone <repository-url>
291
- cd ui-admin-lib
292
- npm install
293
- npm run demo
294
- ```
295
-
296
- Откройте http://localhost:3000 в браузере.
297
-
298
- **Вход:**
299
- - Логин: `admin`
300
- - Пароль: `admin`
301
-
302
- ## Основные компоненты
303
-
304
- ### AdminPanel
305
- Главный компонент для создания админ-панели. Принимает конфигурацию и автоматически создает:
306
- - Страницу входа
307
- - Боковую навигацию
308
- - Таблицы с данными
309
- - Формы создания/редактирования
310
- - Операции CRUD (Create, Read, Update, Delete)
311
-
312
- ### CrudService
313
- Утилита для работы с REST API. Поддерживает любые форматы ответов API.
314
-
315
- ### Низкоуровневые компоненты
316
-
317
- ### Layout (Макет)
318
- - `PageLayout` - Основной layout с header, sidebar и content
319
- - `Header` - Шапка страницы
320
- - `Sidebar` - Боковая панель
321
- - `Content` - Основная область контента
322
-
323
- ### Form (Формы)
324
- - `Button` - Кнопка (варианты: primary, success, danger, ghost)
325
- - `Input` - Поле ввода текста
326
- - `Select` - Выпадающий список
327
- - `Textarea` - Многострочное поле ввода
328
- - `Checkbox` - Чекбокс
329
- - `Radio` - Радиокнопка
330
- - `Label` - Метка для полей формы
331
-
332
- ### Table (Таблицы)
333
- - `DataTable` - Таблица данных с колонками и строками
334
-
335
- ### Modal (Модальные окна)
336
- - `Modal` - Модальное окно
337
-
338
- ### Navigation (Навигация)
339
- - `Menu` - Меню навигации
340
- - `Breadcrumbs` - Хлебные крошки
341
- - `Tabs` - Вкладки
342
-
343
- ### Utility (Утилиты)
344
- - `Card` - Карточка
345
- - `Toast` / `ToastContainer` - Уведомления
346
- - `Loading` - Индикатор загрузки
347
- - `Badge` - Значок/бейдж
348
-
349
- ## API Reference
350
-
351
- ### AdminPanel
352
-
353
- Главный компонент для создания админ-панели.
354
-
355
- ```tsx
356
- <AdminPanel
357
- title?: string // Заголовок админ-панели (по умолчанию "Админ панель")
358
- logo?: React.ReactNode // Кастомный логотип
359
- models: AdminModel[] // Массив моделей для отображения
360
- login?: { // Конфигурация авторизации (опционально)
361
- onSubmit: (username: string, password: string) => Promise<void> | void
362
- }
363
- user?: { // Информация о пользователе (опционально)
364
- name?: string // Имя пользователя в header
365
- onLogout?: () => void // Обработчик выхода
366
- }
367
- />
368
- ```
369
-
370
- ### AdminModel
371
-
372
- Конфигурация модели данных.
373
-
374
- ```tsx
375
- interface AdminModel<T = any> {
376
- name: string // Уникальное имя модели
377
- label: string // Отображаемое название
378
- service: CrudService<T> // Сервис для работы с API
379
- columns: Column<T>[] // Колонки таблицы
380
- fields: FormField[] // Поля формы
381
- getItemId?: (item: T) => string | number // Функция получения ID (опционально)
382
- }
383
- ```
384
-
385
- ### CrudService
386
-
387
- Класс для работы с REST API.
388
-
389
- ```tsx
390
- new CrudService<T>({
391
- baseUrl: string // Базовый URL API
392
- getListUrl?: (params?: any) => string // URL для получения списка (опционально)
393
- getDetailUrl?: (id) => string // URL для получения элемента (опционально)
394
- getCreateUrl?: () => string // URL для создания (опционально)
395
- getUpdateUrl?: (id) => string // URL для обновления (опционально)
396
- getDeleteUrl?: (id) => string // URL для удаления (опционально)
397
- transformRequest?: (data) => any // Трансформация запроса (опционально)
398
- transformResponse?: (data) => T // Трансформация ответа (опционально)
399
- headers?: Record<string, string> // Заголовки запросов (опционально)
400
- })
401
- ```
402
-
403
- Методы:
404
- - `getList(params?)` - Получить список элементов
405
- - `getDetail(id)` - Получить элемент по ID
406
- - `create(data)` - Создать новый элемент
407
- - `update(id, data)` - Обновить элемент
408
- - `delete(id)` - Удалить элемент
409
-
410
- ### Column
411
-
412
- Конфигурация колонки таблицы.
413
-
414
- ```tsx
415
- interface Column<T> {
416
- key: string // Уникальный ключ колонки
417
- title: string // Заголовок колонки
418
- dataIndex?: string // Поле данных для отображения
419
- render?: (value: any, record: T, index: number) => React.ReactNode // Кастомный рендер
420
- width?: number | string // Ширина колонки
421
- align?: 'left' | 'center' | 'right' // Выравнивание
422
- }
423
- ```
424
-
425
- ### FormField
426
-
427
- Конфигурация поля формы.
428
-
429
- ```tsx
430
- interface FormField {
431
- name: string // Имя поля
432
- label: string // Метка поля
433
- type?: 'text' | 'email' | 'number' | 'password' | 'textarea' | 'select' | 'checkbox' | 'radio'
434
- options?: Array<{ value: string | number; label: string }> // Опции для select/radio
435
- required?: boolean // Обязательное поле
436
- placeholder?: string // Подсказка
437
- disabled?: boolean // Отключено
438
- }
439
- ```
440
-
441
- ## Разработка
442
-
443
- ```bash
444
- # Установка зависимостей
445
- npm install
446
-
447
- # Сборка библиотеки
448
- npm run build
449
-
450
- # Запуск демо приложения
451
- npm run demo
452
-
453
- # Линтинг
454
- npm run lint
455
- ```
456
-
457
- ## Публикация в npm
458
-
459
- ```bash
460
- # Убедитесь что все изменения закоммичены
461
- git add .
462
- git commit -m "Prepare for release"
463
-
464
- # Обновите версию (если нужно)
465
- npm version patch # или minor, major
466
-
467
- # Соберите библиотеку
468
- npm run build
469
-
470
- # Опубликуйте
471
- npm publish
472
- ```
473
-
474
- ## Лицензия
475
-
476
- MIT
477
-
1
+ # UI Admin Library
2
+
3
+ Library for quickly creating admin panels in React with full CRUD functionality. Create a complete admin panel in just a few lines of code!
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install ui-admin-lib
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ Create an admin panel in a few lines:
14
+
15
+ ```tsx
16
+ import { AdminPanel, CrudService } from 'ui-admin-lib'
17
+ import 'ui-admin-lib/styles'
18
+
19
+ // 1. Create a service for working with API
20
+ const userService = new CrudService({
21
+ baseUrl: 'https://api.example.com/users',
22
+ })
23
+
24
+ // 2. Define a model
25
+ const userModel = {
26
+ name: 'users',
27
+ label: 'Users',
28
+ service: userService,
29
+ columns: [
30
+ { key: 'id', title: 'ID', dataIndex: 'id' },
31
+ { key: 'name', title: 'Name', dataIndex: 'name' },
32
+ { key: 'email', title: 'Email', dataIndex: 'email' },
33
+ ],
34
+ fields: [
35
+ { name: 'name', label: 'Name', type: 'text', required: true },
36
+ { name: 'email', label: 'Email', type: 'email', required: true },
37
+ ],
38
+ }
39
+
40
+ // 3. Use AdminPanel
41
+ function App() {
42
+ return (
43
+ <AdminPanel
44
+ title="My Admin"
45
+ models={[userModel]}
46
+ login={{
47
+ onSubmit: async (username, password) => {
48
+ // Your authorization logic
49
+ },
50
+ }}
51
+ />
52
+ )
53
+ }
54
+ ```
55
+
56
+ That's it! AdminPanel will automatically create:
57
+ - Login page
58
+ - Sidebar navigation
59
+ - Data tables
60
+ - Create/edit forms
61
+ - Full CRUD functionality
62
+
63
+ ## Full Configuration Example
64
+
65
+ Here's a complete example with multiple models and all features:
66
+
67
+ ```tsx
68
+ import { AdminPanel, CrudService, AdminModel } from 'ui-admin-lib'
69
+ import type { Column, FormField } from 'ui-admin-lib'
70
+ import 'ui-admin-lib/styles'
71
+
72
+ // Data types
73
+ interface User {
74
+ id: number
75
+ name: string
76
+ email: string
77
+ role: string
78
+ active: boolean
79
+ }
80
+
81
+ interface Product {
82
+ id: number
83
+ title: string
84
+ price: number
85
+ category: string
86
+ inStock: boolean
87
+ }
88
+
89
+ // Create services for working with API
90
+ const userService = new CrudService<User>({
91
+ baseUrl: 'https://api.example.com/users',
92
+ headers: {
93
+ 'Authorization': 'Bearer YOUR_TOKEN',
94
+ 'Content-Type': 'application/json'
95
+ },
96
+ // Optional: custom URLs for operations
97
+ getListUrl: () => 'https://api.example.com/users',
98
+ getDetailUrl: (id) => `https://api.example.com/users/${id}`,
99
+ getCreateUrl: () => 'https://api.example.com/users',
100
+ getUpdateUrl: (id) => `https://api.example.com/users/${id}`,
101
+ getDeleteUrl: (id) => `https://api.example.com/users/${id}`,
102
+ // Optional: data transformation
103
+ transformRequest: (data) => data, // Transform before sending
104
+ transformResponse: (data) => data, // Transform after receiving
105
+ })
106
+
107
+ const productService = new CrudService<Product>({
108
+ baseUrl: 'https://api.example.com/products',
109
+ headers: {
110
+ 'Authorization': 'Bearer YOUR_TOKEN'
111
+ }
112
+ })
113
+
114
+ // User model configuration
115
+ const userModel: AdminModel<User> = {
116
+ name: 'users',
117
+ label: 'Users',
118
+ service: userService,
119
+ columns: [
120
+ { key: 'id', title: 'ID', dataIndex: 'id' },
121
+ { key: 'name', title: 'Name', dataIndex: 'name' },
122
+ { key: 'email', title: 'Email', dataIndex: 'email' },
123
+ {
124
+ key: 'role',
125
+ title: 'Role',
126
+ dataIndex: 'role',
127
+ render: (value) => value.charAt(0).toUpperCase() + value.slice(1),
128
+ },
129
+ {
130
+ key: 'active',
131
+ title: 'Active',
132
+ dataIndex: 'active',
133
+ render: (value) => (value ? 'Yes' : 'No'),
134
+ },
135
+ ] as Column<User>[],
136
+ fields: [
137
+ { name: 'name', label: 'Name', type: 'text', required: true, placeholder: 'Enter name' },
138
+ { name: 'email', label: 'Email', type: 'email', required: true, placeholder: 'Enter email' },
139
+ {
140
+ name: 'role',
141
+ label: 'Role',
142
+ type: 'select',
143
+ required: true,
144
+ options: [
145
+ { value: 'admin', label: 'Administrator' },
146
+ { value: 'user', label: 'User' },
147
+ ],
148
+ },
149
+ { name: 'active', label: 'Active', type: 'checkbox' },
150
+ ] as FormField[],
151
+ // Optional: custom ID getter function
152
+ getItemId: (item) => item.id,
153
+ }
154
+
155
+ // Product model configuration
156
+ const productModel: AdminModel<Product> = {
157
+ name: 'products',
158
+ label: 'Products',
159
+ service: productService,
160
+ columns: [
161
+ { key: 'id', title: 'ID', dataIndex: 'id' },
162
+ { key: 'title', title: 'Title', dataIndex: 'title' },
163
+ {
164
+ key: 'price',
165
+ title: 'Price',
166
+ dataIndex: 'price',
167
+ render: (value) => `$${value.toLocaleString('en-US')}`,
168
+ },
169
+ { key: 'category', title: 'Category', dataIndex: 'category' },
170
+ {
171
+ key: 'inStock',
172
+ title: 'In Stock',
173
+ dataIndex: 'inStock',
174
+ render: (value) => (value ? 'Yes' : 'No'),
175
+ },
176
+ ] as Column<Product>[],
177
+ fields: [
178
+ { name: 'title', label: 'Title', type: 'text', required: true },
179
+ { name: 'price', label: 'Price', type: 'number', required: true },
180
+ { name: 'category', label: 'Category', type: 'text', required: true },
181
+ { name: 'inStock', label: 'In Stock', type: 'checkbox' },
182
+ ] as FormField[],
183
+ }
184
+
185
+ // Usage
186
+ function App() {
187
+ return (
188
+ <AdminPanel
189
+ title="Admin Panel"
190
+ logo={<span>My Logo</span>} // Optional: custom logo
191
+ models={[userModel, productModel]}
192
+ login={{
193
+ onSubmit: async (username, password) => {
194
+ // Your authorization logic
195
+ const response = await fetch('https://api.example.com/auth/login', {
196
+ method: 'POST',
197
+ headers: { 'Content-Type': 'application/json' },
198
+ body: JSON.stringify({ username, password }),
199
+ })
200
+ if (!response.ok) {
201
+ throw new Error('Invalid username or password')
202
+ }
203
+ const data = await response.json()
204
+ // Save token
205
+ localStorage.setItem('token', data.token)
206
+ },
207
+ }}
208
+ user={{
209
+ name: 'Administrator', // Optional: user name in header
210
+ onLogout: () => {
211
+ // Optional: logout handler
212
+ localStorage.removeItem('token')
213
+ },
214
+ }}
215
+ />
216
+ )
217
+ }
218
+ ```
219
+
220
+ ## Form Field Types
221
+
222
+ The following field types are supported in `FormField`:
223
+
224
+ - `text` - Text field
225
+ - `email` - Email field
226
+ - `number` - Number field
227
+ - `password` - Password field
228
+ - `textarea` - Multi-line field
229
+ - `select` - Dropdown list (requires `options`)
230
+ - `checkbox` - Checkbox
231
+ - `radio` - Radio buttons (requires `options`)
232
+
233
+ Field configuration example:
234
+
235
+ ```tsx
236
+ {
237
+ name: 'fieldName', // Field name (required)
238
+ label: 'Field Label', // Field label (required)
239
+ type: 'text', // Field type (optional, default 'text')
240
+ required: true, // Required field (optional)
241
+ placeholder: 'Hint', // Placeholder (optional)
242
+ disabled: false, // Disabled (optional)
243
+ options: [ // Options for select/radio (required for these types)
244
+ { value: 'value1', label: 'Label 1' },
245
+ { value: 'value2', label: 'Label 2' },
246
+ ],
247
+ }
248
+ ```
249
+
250
+ ## Quick Start
251
+
252
+ ```bash
253
+ npm install ui-admin-lib
254
+ ```
255
+
256
+ ```tsx
257
+ import { AdminPanel, CrudService } from 'ui-admin-lib'
258
+ import 'ui-admin-lib/styles'
259
+
260
+ const userService = new CrudService({
261
+ baseUrl: 'https://api.example.com/users',
262
+ })
263
+
264
+ const userModel = {
265
+ name: 'users',
266
+ label: 'Users',
267
+ service: userService,
268
+ columns: [
269
+ { key: 'id', title: 'ID', dataIndex: 'id' },
270
+ { key: 'name', title: 'Name', dataIndex: 'name' },
271
+ ],
272
+ fields: [
273
+ { name: 'name', label: 'Name', type: 'text', required: true },
274
+ ],
275
+ }
276
+
277
+ function App() {
278
+ return <AdminPanel models={[userModel]} />
279
+ }
280
+ ```
281
+
282
+ ## Demo Application
283
+
284
+ Run the demo application to see all features:
285
+
286
+ ```bash
287
+ git clone <repository-url>
288
+ cd ui-admin-lib
289
+ npm install
290
+ npm run demo
291
+ ```
292
+
293
+ Open http://localhost:3000 in your browser.
294
+
295
+ **Login:**
296
+ - Username: `admin`
297
+ - Password: `admin`
298
+
299
+ ## Core Components
300
+
301
+ ### AdminPanel
302
+ Main component for creating admin panels. Accepts configuration and automatically creates:
303
+ - Login page
304
+ - Sidebar navigation
305
+ - Data tables
306
+ - Create/edit forms
307
+ - CRUD operations (Create, Read, Update, Delete)
308
+
309
+ ### CrudService
310
+ Utility for working with REST API. Supports any API response formats.
311
+
312
+ ### Low-level Components
313
+
314
+ ### Layout
315
+ - `PageLayout` - Main layout with header, sidebar and content
316
+ - `Header` - Page header
317
+ - `Sidebar` - Sidebar panel
318
+ - `Content` - Main content area
319
+
320
+ ### Form
321
+ - `Button` - Button (variants: primary, success, danger, ghost)
322
+ - `Input` - Text input field
323
+ - `Select` - Dropdown list
324
+ - `Textarea` - Multi-line input field
325
+ - `Checkbox` - Checkbox
326
+ - `Radio` - Radio button
327
+ - `Label` - Form field label
328
+
329
+ ### Table
330
+ - `DataTable` - Data table with columns and rows
331
+
332
+ ### Modal
333
+ - `Modal` - Modal dialog
334
+
335
+ ### Navigation
336
+ - `Menu` - Navigation menu
337
+ - `Breadcrumbs` - Breadcrumb navigation
338
+ - `Tabs` - Tabs
339
+
340
+ ### Utility
341
+ - `Card` - Card component
342
+ - `Toast` / `ToastContainer` - Notifications
343
+ - `Loading` - Loading spinner
344
+ - `Badge` - Badge component
345
+
346
+ ## API Reference
347
+
348
+ ### AdminPanel
349
+
350
+ Main component for creating admin panels.
351
+
352
+ ```tsx
353
+ <AdminPanel
354
+ title?: string // Admin panel title (default: "Admin Panel")
355
+ logo?: React.ReactNode // Custom logo
356
+ models: AdminModel[] // Array of models to display
357
+ login?: { // Authorization configuration (optional)
358
+ onSubmit: (username: string, password: string) => Promise<void> | void
359
+ }
360
+ user?: { // User information (optional)
361
+ name?: string // User name in header
362
+ onLogout?: () => void // Logout handler
363
+ }
364
+ />
365
+ ```
366
+
367
+ ### AdminModel
368
+
369
+ Data model configuration.
370
+
371
+ ```tsx
372
+ interface AdminModel<T = any> {
373
+ name: string // Unique model name
374
+ label: string // Display name
375
+ service: CrudService<T> // Service for working with API
376
+ columns: Column<T>[] // Table columns
377
+ fields: FormField[] // Form fields
378
+ getItemId?: (item: T) => string | number // ID getter function (optional)
379
+ }
380
+ ```
381
+
382
+ ### CrudService
383
+
384
+ Class for working with REST API.
385
+
386
+ ```tsx
387
+ new CrudService<T>({
388
+ baseUrl: string // Base API URL
389
+ getListUrl?: (params?: any) => string // URL for getting list (optional)
390
+ getDetailUrl?: (id) => string // URL for getting item (optional)
391
+ getCreateUrl?: () => string // URL for creating (optional)
392
+ getUpdateUrl?: (id) => string // URL for updating (optional)
393
+ getDeleteUrl?: (id) => string // URL for deleting (optional)
394
+ transformRequest?: (data) => any // Request transformation (optional)
395
+ transformResponse?: (data) => T // Response transformation (optional)
396
+ headers?: Record<string, string> // Request headers (optional)
397
+ })
398
+ ```
399
+
400
+ Methods:
401
+ - `getList(params?)` - Get list of items
402
+ - `getDetail(id)` - Get item by ID
403
+ - `create(data)` - Create new item
404
+ - `update(id, data)` - Update item
405
+ - `delete(id)` - Delete item
406
+
407
+ ### Column
408
+
409
+ Table column configuration.
410
+
411
+ ```tsx
412
+ interface Column<T> {
413
+ key: string // Unique column key
414
+ title: string // Column title
415
+ dataIndex?: string // Data field to display
416
+ render?: (value: any, record: T, index: number) => React.ReactNode // Custom render
417
+ width?: number | string // Column width
418
+ align?: 'left' | 'center' | 'right' // Alignment
419
+ }
420
+ ```
421
+
422
+ ### FormField
423
+
424
+ Form field configuration.
425
+
426
+ ```tsx
427
+ interface FormField {
428
+ name: string // Field name
429
+ label: string // Field label
430
+ type?: 'text' | 'email' | 'number' | 'password' | 'textarea' | 'select' | 'checkbox' | 'radio'
431
+ options?: Array<{ value: string | number; label: string }> // Options for select/radio
432
+ required?: boolean // Required field
433
+ placeholder?: string // Placeholder
434
+ disabled?: boolean // Disabled
435
+ }
436
+ ```
437
+
438
+ ## Development
439
+
440
+ ```bash
441
+ # Install dependencies
442
+ npm install
443
+
444
+ # Build library
445
+ npm run build
446
+
447
+ # Run demo application
448
+ npm run demo
449
+
450
+ # Linting
451
+ npm run lint
452
+ ```
453
+
454
+ ## Publishing to npm
455
+
456
+ ```bash
457
+ # Make sure all changes are committed
458
+ git add .
459
+ git commit -m "Prepare for release"
460
+
461
+ # Update version (if needed)
462
+ npm version patch # or minor, major
463
+
464
+ # Build library
465
+ npm run build
466
+
467
+ # Publish
468
+ npm publish
469
+ ```
470
+
471
+ ## License
472
+
473
+ MIT
package/package.json CHANGED
@@ -1,64 +1,64 @@
1
- {
2
- "name": "ui-admin-lib",
3
- "version": "1.0.0",
4
- "description": "UI библиотека для создания административных панелей на React",
5
- "main": "./dist/index.js",
6
- "module": "./dist/index.esm.js",
7
- "types": "./dist/index.d.ts",
8
- "exports": {
9
- ".": {
10
- "import": "./dist/index.esm.js",
11
- "require": "./dist/index.js",
12
- "types": "./dist/index.d.ts"
13
- },
14
- "./styles": "./dist/styles.css"
15
- },
16
- "files": [
17
- "dist",
18
- "README.md"
19
- ],
20
- "scripts": {
21
- "dev": "vite",
22
- "build": "vite build",
23
- "preview": "vite preview",
24
- "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
25
- "demo": "cd demo && npm install && npm run dev",
26
- "demo:build": "cd demo && npm install && npm run build"
27
- },
28
- "peerDependencies": {
29
- "react": "^18.0.0",
30
- "react-dom": "^18.0.0"
31
- },
32
- "devDependencies": {
33
- "@types/react": "^18.2.43",
34
- "@types/react-dom": "^18.2.17",
35
- "@typescript-eslint/eslint-plugin": "^6.14.0",
36
- "@typescript-eslint/parser": "^6.14.0",
37
- "@vitejs/plugin-react": "^4.2.1",
38
- "eslint": "^8.55.0",
39
- "eslint-plugin-react-hooks": "^4.6.0",
40
- "eslint-plugin-react-refresh": "^0.4.5",
41
- "react": "^18.2.0",
42
- "react-dom": "^18.2.0",
43
- "typescript": "^5.2.2",
44
- "vite": "^5.0.8",
45
- "vite-plugin-dts": "^3.6.4"
46
- },
47
- "keywords": [
48
- "react",
49
- "admin",
50
- "crud",
51
- "admin-panel",
52
- "dashboard",
53
- "ui-library",
54
- "typescript",
55
- "react-components"
56
- ],
57
- "author": "",
58
- "license": "MIT",
59
- "repository": {
60
- "type": "git",
61
- "url": ""
62
- }
63
- }
64
-
1
+ {
2
+ "name": "ui-admin-lib",
3
+ "version": "1.1.0",
4
+ "description": "Library for quickly creating admin panels in React with full CRUD functionality",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.esm.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.esm.js",
11
+ "require": "./dist/index.js",
12
+ "types": "./dist/index.d.ts"
13
+ },
14
+ "./styles": "./dist/styles.css"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md"
19
+ ],
20
+ "scripts": {
21
+ "dev": "vite",
22
+ "build": "vite build",
23
+ "preview": "vite preview",
24
+ "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
25
+ "demo": "cd demo && npm install && npm run dev",
26
+ "demo:build": "cd demo && npm install && npm run build"
27
+ },
28
+ "peerDependencies": {
29
+ "react": "^18.0.0",
30
+ "react-dom": "^18.0.0"
31
+ },
32
+ "devDependencies": {
33
+ "@types/react": "^18.2.43",
34
+ "@types/react-dom": "^18.2.17",
35
+ "@typescript-eslint/eslint-plugin": "^6.14.0",
36
+ "@typescript-eslint/parser": "^6.14.0",
37
+ "@vitejs/plugin-react": "^4.2.1",
38
+ "eslint": "^8.55.0",
39
+ "eslint-plugin-react-hooks": "^4.6.0",
40
+ "eslint-plugin-react-refresh": "^0.4.5",
41
+ "react": "^18.2.0",
42
+ "react-dom": "^18.2.0",
43
+ "typescript": "^5.2.2",
44
+ "vite": "^5.0.8",
45
+ "vite-plugin-dts": "^3.6.4"
46
+ },
47
+ "keywords": [
48
+ "react",
49
+ "admin",
50
+ "crud",
51
+ "admin-panel",
52
+ "dashboard",
53
+ "ui-library",
54
+ "typescript",
55
+ "react-components"
56
+ ],
57
+ "author": "",
58
+ "license": "MIT",
59
+ "repository": {
60
+ "type": "git",
61
+ "url": ""
62
+ }
63
+ }
64
+