бета настраиваемого интерфейса

This commit is contained in:
2025-07-16 15:00:45 +03:00
parent 75141f5e88
commit b77303fa97
8 changed files with 1226 additions and 130 deletions

View File

@@ -1,14 +1,396 @@
import { FileText, Plus } from 'lucide-react';
import { FC } from 'react';
import { ArrowLeft, Download, FileText, Plus, Save } from 'lucide-react';
import { FC, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '../../../../components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../../../components/ui/card';
import { Checkbox } from '../../../../components/ui/checkbox';
import { Input } from '../../../../components/ui/input';
import { RadioGroup, RadioGroupItem } from '../../../../components/ui/radio-group';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../../../components/ui/select';
import { Textarea } from '../../../../components/ui/textarea';
import { useTemplateContext } from '../../../../contexts/TemplateContext';
import { ElementType, Template, TemplateElement } from '../../../../types/template';
interface ProtocolFormProps {
template: Template;
onSave: (data: Record<string, any>) => void;
onBack: () => void;
}
interface FormElementProps {
element: TemplateElement;
value: any;
onChange: (value: any) => void;
showLabel?: boolean;
width?: 'auto' | 'half' | 'full';
}
const FormElement: FC<FormElementProps> = ({ element, value, onChange, showLabel = true, width = 'auto' }) => {
const renderInput = () => {
switch (element.type) {
case 'text':
return (
<Input
placeholder={element.placeholder}
value={value || ''}
onChange={(e) => onChange(e.target.value)}
required={element.required}
/>
);
case 'textarea':
return (
<Textarea
placeholder={element.placeholder}
value={value || ''}
onChange={(e) => onChange(e.target.value)}
required={element.required}
rows={3}
/>
);
case 'number':
return (
<Input
type="number"
placeholder={element.placeholder}
value={value || ''}
onChange={(e) => onChange(e.target.value ? parseFloat(e.target.value) : '')}
required={element.required}
/>
);
case 'date':
return (
<Input
type="date"
value={value || ''}
onChange={(e) => onChange(e.target.value)}
required={element.required}
/>
);
case 'select':
return (
<Select value={value || ''} onValueChange={onChange}>
<SelectTrigger>
<SelectValue placeholder={element.placeholder || 'Выберите значение'} />
</SelectTrigger>
<SelectContent>
{element.options?.map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
);
case 'radio':
return (
<RadioGroup value={value || ''} onValueChange={onChange}>
{element.options?.map((option) => (
<div key={option.value} className="flex items-center space-x-2">
<RadioGroupItem value={option.value} id={`${element.id}-${option.value}`} />
<label htmlFor={`${element.id}-${option.value}`} className="text-sm font-medium">
{option.label}
</label>
</div>
))}
</RadioGroup>
);
case 'checkbox':
return (
<div className="flex items-center space-x-2">
<Checkbox
checked={!!value}
onCheckedChange={onChange}
id={element.id}
/>
<label htmlFor={element.id} className="text-sm font-medium">
{element.placeholder || 'Отметить'}
</label>
</div>
);
default:
return null;
}
};
const getWidthClass = () => {
switch (width) {
case 'half':
return 'col-span-1';
case 'full':
return 'col-span-full';
default:
return 'col-span-1';
}
};
return (
<div className={`space-y-2 ${getWidthClass()}`}>
{showLabel && (
<label className="text-sm font-medium text-gray-700">
{element.label}
{element.required && <span className="text-red-500 ml-1">*</span>}
</label>
)}
{renderInput()}
{element.targetCells && element.targetCells.length > 0 && (
<div className="flex flex-wrap gap-1 mt-1">
{element.targetCells.map((target, index) => (
<span
key={index}
className="inline-block px-1.5 py-0.5 bg-blue-100 text-blue-700 text-xs rounded text-center"
title={target.displayName}
>
{target.sheet}!{target.cell}
</span>
))}
</div>
)}
</div>
);
};
const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
const [formData, setFormData] = useState<Record<string, any>>({});
const [protocolName, setProtocolName] = useState('');
const handleFieldChange = (elementId: string, value: any) => {
setFormData(prev => ({
...prev,
[elementId]: value
}));
};
const handleSave = () => {
const data = {
protocolName,
templateId: template.id,
formData,
createdAt: new Date(),
};
onSave(data);
};
const handleExport = () => {
// Логика экспорта в Excel будет реализована позже
console.log('Экспорт в Excel:', { protocolName, formData });
alert('Функция экспорта будет реализована в следующих версиях');
};
const layoutSettings = template.layoutSettings || {
columns: 2,
grouping: 'none',
elementSpacing: 'normal',
showLabels: true,
enableDragDrop: false,
};
// Группировка элементов
const groupedElements = () => {
const sortedElements = [...template.elements].sort((a, b) => (a.order || 0) - (b.order || 0));
if (layoutSettings.grouping === 'by-category') {
const groups: Record<string, TemplateElement[]> = {};
sortedElements.forEach(element => {
const category = element.category || 'Без категории';
if (!groups[category]) groups[category] = [];
groups[category].push(element);
});
return Object.entries(groups);
}
if (layoutSettings.grouping === 'by-type') {
const groups: Record<string, TemplateElement[]> = {};
sortedElements.forEach(element => {
const type = element.type;
if (!groups[type]) groups[type] = [];
groups[type].push(element);
});
return Object.entries(groups);
}
return [['Все элементы', sortedElements]];
};
const getSpacingClass = () => {
switch (layoutSettings.elementSpacing) {
case 'compact':
return 'gap-3';
case 'spacious':
return 'gap-8';
default:
return 'gap-6';
}
};
const getGridCols = () => {
switch (layoutSettings.columns) {
case 1:
return 'grid-cols-1';
case 3:
return 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3';
case 4:
return 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4';
default:
return 'grid-cols-1 md:grid-cols-2';
}
};
const typeLabels: Record<ElementType, string> = {
text: 'Текстовые поля',
textarea: 'Многострочный текст',
number: 'Числовые поля',
date: 'Даты',
select: 'Выпадающие списки',
radio: 'Переключатели',
checkbox: 'Флажки',
};
return (
<div className="h-full bg-gray-50">
{/* Заголовок */}
<div className="bg-white border-b border-gray-200 p-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<Button variant="ghost" onClick={onBack}>
<ArrowLeft className="h-4 w-4 mr-2" />
Назад
</Button>
<div>
<h1 className="text-xl font-semibold text-gray-800">
Создание протокола: {template.name}
</h1>
<p className="text-sm text-gray-600 mt-1">
Заполните форму для создания нового протокола
</p>
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={handleExport}>
<Download className="h-4 w-4 mr-2" />
Экспорт в Excel
</Button>
<Button onClick={handleSave} disabled={!protocolName.trim()}>
<Save className="h-4 w-4 mr-2" />
Сохранить протокол
</Button>
</div>
</div>
</div>
{/* Форма */}
<div className="flex-1 overflow-y-auto p-6">
<div className="max-w-6xl mx-auto space-y-6">
{/* Название протокола */}
<Card>
<CardHeader>
<CardTitle>Основная информация</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-2">
<label className="text-sm font-medium text-gray-700">
Название протокола <span className="text-red-500">*</span>
</label>
<Input
placeholder="Введите название протокола"
value={protocolName}
onChange={(e) => setProtocolName(e.target.value)}
/>
</div>
</CardContent>
</Card>
{/* Элементы формы */}
{template.elements.length === 0 ? (
<Card>
<CardContent className="py-12">
<div className="text-center">
<FileText className="h-16 w-16 text-gray-400 mx-auto mb-4" />
<h3 className="text-lg font-medium text-gray-900 mb-2">Нет элементов формы</h3>
<p className="text-gray-600 mb-4">
В этом шаблоне пока не созданы элементы формы
</p>
<Button variant="outline" onClick={() => window.history.back()}>
Настроить шаблон
</Button>
</div>
</CardContent>
</Card>
) : (
groupedElements().map(([groupName, elements]) => (
<Card key={groupName}>
<CardHeader>
<CardTitle className="text-lg">
{layoutSettings.grouping === 'by-type'
? typeLabels[groupName as ElementType] || groupName
: groupName
}
</CardTitle>
{layoutSettings.grouping !== 'none' && (
<CardDescription>
{elements.length} элемент{elements.length > 1 ? 'ов' : ''}
</CardDescription>
)}
</CardHeader>
<CardContent>
<div className={`grid ${getGridCols()} ${getSpacingClass()}`}>
{elements.map((element) => (
<FormElement
key={element.id}
element={element}
value={formData[element.id]}
onChange={(value) => handleFieldChange(element.id, value)}
showLabel={layoutSettings.showLabels}
width={element.width}
/>
))}
</div>
</CardContent>
</Card>
))
)}
</div>
</div>
</div>
);
};
export const ProtocolCreation: FC = () => {
const navigate = useNavigate();
const { templates } = useTemplateContext();
const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(null);
const handleTemplateSelect = (template: Template) => {
setSelectedTemplate(template);
};
const handleProtocolSave = (data: Record<string, any>) => {
console.log('Сохранение протокола:', data);
// Здесь будет логика сохранения протокола
alert(`Протокол "${data.protocolName}" сохранен!`);
navigate('/');
};
const handleBack = () => {
setSelectedTemplate(null);
};
if (selectedTemplate) {
return (
<ProtocolForm
template={selectedTemplate}
onSave={handleProtocolSave}
onBack={handleBack}
/>
);
}
return (
<div className="p-6 max-w-7xl mx-auto">
<div className="flex items-center justify-between mb-6">
@@ -55,17 +437,33 @@ export const ProtocolCreation: FC = () => {
<FileText className="h-4 w-4" />
<span>{template.elements.length} элементов для заполнения</span>
</div>
{template.layoutSettings && (
<div className="flex items-center gap-2">
<span className="text-xs bg-blue-100 text-blue-800 px-2 py-1 rounded">
{template.layoutSettings.columns} столбца
</span>
<span className="text-xs bg-green-100 text-green-800 px-2 py-1 rounded">
{template.layoutSettings.grouping === 'none' ? 'Без группировки' :
template.layoutSettings.grouping === 'by-type' ? 'По типу' : 'По категориям'}
</span>
</div>
)}
<div className="text-xs text-gray-500 mt-2">
Создан: {template.createdAt.toLocaleDateString()}
Создан: {template.createdAt.toLocaleDateString('ru-RU')}
</div>
</div>
<div className="mt-4">
<Button
className="w-full"
onClick={() => handleTemplateSelect(template)}
disabled={!template.excelFile}
disabled={!template.excelFile || template.elements.length === 0}
>
{template.excelFile ? 'Создать протокол' : 'Шаблон не настроен'}
{template.excelFile
? template.elements.length > 0
? 'Создать протокол'
: 'Нет элементов формы'
: 'Шаблон не настроен'
}
</Button>
</div>
</CardContent>