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

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,11 +1,15 @@
import { Calendar, CheckSquare, ChevronDown, Edit, FileText, Hash, Plus, Trash2, Type } from 'lucide-react';
import { closestCenter, DndContext, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Calendar, CheckSquare, ChevronDown, Edit, FileText, GripVertical, Hash, LayoutGrid, Plus, Trash2, Type } from 'lucide-react';
import React, { useState } from 'react';
import { ElementType, TemplateElement } from '../../types/template';
import { CellTarget, ElementType, FormLayoutSettings, TemplateElement } from '../../types/template';
import { Button } from '../ui/button';
import { Card, CardContent, CardHeader } from '../ui/card';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/card';
import { Checkbox } from '../ui/checkbox';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '../ui/dialog';
import { Input } from '../ui/input';
import { RadioGroup, RadioGroupItem } from '../ui/radio-group';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
interface ElementFormProps {
@@ -13,6 +17,12 @@ interface ElementFormProps {
setFormData: React.Dispatch<React.SetStateAction<Partial<TemplateElement>>>;
}
interface SortableElementProps {
element: TemplateElement;
onEdit: (element: TemplateElement) => void;
onDelete: (elementId: string) => void;
}
const ELEMENT_TYPES: Array<{ type: ElementType; label: string; icon: React.ReactNode }> = [
{ type: 'text', label: 'Текстовое поле', icon: <Type className="h-4 w-4" /> },
{ type: 'textarea', label: 'Многострочный текст', icon: <FileText className="h-4 w-4" /> },
@@ -23,6 +33,179 @@ const ELEMENT_TYPES: Array<{ type: ElementType; label: string; icon: React.React
{ type: 'date', label: 'Дата', icon: <Calendar className="h-4 w-4" /> },
];
const SortableElement: React.FC<SortableElementProps> = ({ element, onEdit, onDelete }) => {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: element.id });
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
};
return (
<Card ref={setNodeRef} style={style} className="mb-4 bg-white border border-gray-200 hover:border-gray-300 transition-colors">
<CardHeader className="flex flex-row items-center justify-between p-4">
<div className="flex items-center gap-3 flex-1">
<div
className="cursor-grab active:cursor-grabbing p-1 rounded hover:bg-gray-100"
{...attributes}
{...listeners}
>
<GripVertical className="h-4 w-4 text-gray-400" />
</div>
<div className="flex items-center gap-2">
{ELEMENT_TYPES.find(t => t.type === element.type)?.icon}
<div>
<p className="font-semibold text-sm">{element.label}</p>
<p className="text-xs text-gray-500">{element.name}</p>
</div>
</div>
</div>
<div className="flex items-center gap-2">
<div className="text-xs text-gray-500">
{element.targetCells?.length || 0} ячеек
</div>
<Button variant="ghost" size="icon" onClick={() => onEdit(element)}>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="icon"
className="text-red-500 hover:text-red-600"
onClick={() => onDelete(element.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</CardHeader>
<CardContent className="px-4 pb-4">
<div className="text-sm text-gray-600">
<div className="mb-2">
<strong>Тип:</strong> {ELEMENT_TYPES.find(t => t.type === element.type)?.label}
</div>
<div className="mb-2">
<strong>Ячейки:</strong>
<div className="mt-1 flex flex-wrap gap-1">
{element.targetCells?.map((target, index) => (
<span
key={index}
className="inline-block px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded"
>
{target.sheet}!{target.cell}
{target.displayName && ` (${target.displayName})`}
</span>
)) || (
<span className="text-gray-400 text-xs">Ячейки не настроены</span>
)}
</div>
</div>
{element.category && (
<div>
<strong>Категория:</strong> {element.category}
</div>
)}
</div>
</CardContent>
</Card>
);
};
const CellTargetEditor: React.FC<{
targets: CellTarget[];
onChange: (targets: CellTarget[]) => void;
}> = ({ targets, onChange }) => {
const handleAddTarget = () => {
onChange([...targets, { sheet: 'L', cell: '', displayName: '' }]);
};
const handleUpdateTarget = (index: number, field: keyof CellTarget, value: string) => {
const updatedTargets = targets.map((target, i) =>
i === index ? { ...target, [field]: value } : target
);
onChange(updatedTargets);
};
const handleRemoveTarget = (index: number) => {
onChange(targets.filter((_, i) => i !== index));
};
return (
<div className="space-y-2">
<div className="flex items-center justify-between">
<label className="text-sm font-medium">Целевые ячейки</label>
<Button variant="outline" size="sm" onClick={handleAddTarget}>
<Plus className="h-4 w-4 mr-1" />
Добавить ячейку
</Button>
</div>
<div className="space-y-3 max-h-48 overflow-y-auto">
{targets.map((target, index) => (
<div key={index} className="p-3 border rounded-lg bg-gray-50">
<div className="grid grid-cols-3 gap-2 mb-2">
<div className="space-y-1">
<label className="text-xs font-medium text-gray-600">Лист</label>
<Select
value={target.sheet}
onValueChange={(value) => handleUpdateTarget(index, 'sheet', value)}
>
<SelectTrigger className="h-8">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="L">L (Левый)</SelectItem>
<SelectItem value="R">R (Правый)</SelectItem>
<SelectItem value="Report">Report</SelectItem>
<SelectItem value="Calculations">Calculations</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<label className="text-xs font-medium text-gray-600">Ячейка</label>
<Input
placeholder="A1, B5..."
value={target.cell}
onChange={(e) => handleUpdateTarget(index, 'cell', e.target.value)}
className="h-8"
/>
</div>
<div className="space-y-1">
<label className="text-xs font-medium text-gray-600">Название</label>
<Input
placeholder="Описание"
value={target.displayName || ''}
onChange={(e) => handleUpdateTarget(index, 'displayName', e.target.value)}
className="h-8"
/>
</div>
</div>
<Button
variant="outline"
size="sm"
onClick={() => handleRemoveTarget(index)}
className="h-6 text-xs text-red-600 hover:text-red-700"
>
<Trash2 className="h-3 w-3 mr-1" />
Удалить
</Button>
</div>
))}
{targets.length === 0 && (
<p className="text-sm text-gray-500 text-center py-4">
Добавьте ячейки для связи с элементом
</p>
)}
</div>
</div>
);
};
const ElementForm: React.FC<ElementFormProps> = ({ formData, setFormData }) => {
const handleAddOption = () => {
setFormData(prev => ({
@@ -48,7 +231,7 @@ const ElementForm: React.FC<ElementFormProps> = ({ formData, setFormData }) => {
const needsOptions = formData.type === 'select' || formData.type === 'radio';
return (
<div className="space-y-4">
<div className="space-y-6">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<label className="text-sm font-medium">Тип элемента</label>
@@ -73,12 +256,20 @@ const ElementForm: React.FC<ElementFormProps> = ({ formData, setFormData }) => {
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Ячейка отчета</label>
<Input
placeholder="A1, B5, C10..."
value={formData.targetCell}
onChange={e => setFormData(prev => ({ ...prev, targetCell: e.target.value }))}
/>
<label className="text-sm font-medium">Ширина элемента</label>
<Select
value={formData.width || 'auto'}
onValueChange={value => setFormData(prev => ({ ...prev, width: value as 'auto' | 'half' | 'full' }))}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="auto">Авто</SelectItem>
<SelectItem value="half">Половина ширины</SelectItem>
<SelectItem value="full">Полная ширина</SelectItem>
</SelectContent>
</Select>
</div>
</div>
@@ -102,6 +293,20 @@ const ElementForm: React.FC<ElementFormProps> = ({ formData, setFormData }) => {
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Категория (для группировки)</label>
<Input
placeholder="Основные данные, Дополнительно..."
value={formData.category}
onChange={e => setFormData(prev => ({ ...prev, category: e.target.value }))}
/>
</div>
<CellTargetEditor
targets={formData.targetCells || []}
onChange={(targets) => setFormData(prev => ({ ...prev, targetCells: targets }))}
/>
<div className="space-y-2">
<label className="text-sm font-medium">Подсказка</label>
<Input
@@ -156,55 +361,313 @@ const ElementForm: React.FC<ElementFormProps> = ({ formData, setFormData }) => {
);
};
interface LayoutSettingsProps {
settings: FormLayoutSettings;
onChange: (settings: FormLayoutSettings) => void;
}
const LayoutSettings: React.FC<LayoutSettingsProps> = ({ settings, onChange }) => {
return (
<div className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">Количество столбцов</label>
<Select
value={settings.columns.toString()}
onValueChange={(value) => onChange({ ...settings, columns: parseInt(value) })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">1 столбец</SelectItem>
<SelectItem value="2">2 столбца</SelectItem>
<SelectItem value="3">3 столбца</SelectItem>
<SelectItem value="4">4 столбца</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Группировка элементов</label>
<RadioGroup
value={settings.grouping}
onValueChange={(value) => onChange({ ...settings, grouping: value as FormLayoutSettings['grouping'] })}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="none" id="none" />
<label htmlFor="none" className="text-sm">Без группировки</label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="by-type" id="by-type" />
<label htmlFor="by-type" className="text-sm">По типу элемента</label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="by-category" id="by-category" />
<label htmlFor="by-category" className="text-sm">По категориям</label>
</div>
</RadioGroup>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Расстояние между элементами</label>
<Select
value={settings.elementSpacing}
onValueChange={(value) => onChange({ ...settings, elementSpacing: value as FormLayoutSettings['elementSpacing'] })}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="compact">Компактно</SelectItem>
<SelectItem value="normal">Обычно</SelectItem>
<SelectItem value="spacious">Просторно</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="showLabels"
checked={settings.showLabels}
onCheckedChange={(checked) => onChange({ ...settings, showLabels: !!checked })}
/>
<label htmlFor="showLabels" className="text-sm font-medium">
Показывать подписи элементов
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="enableDragDrop"
checked={settings.enableDragDrop}
onCheckedChange={(checked) => onChange({ ...settings, enableDragDrop: !!checked })}
/>
<label htmlFor="enableDragDrop" className="text-sm font-medium">
Включить перетаскивание элементов
</label>
</div>
</div>
);
};
interface FormPreviewProps {
elements: TemplateElement[];
layoutSettings: FormLayoutSettings;
}
const FormPreview: React.FC<FormPreviewProps> = ({ elements, layoutSettings }) => {
// Группировка элементов для предварительного просмотра
const groupedElements = () => {
const sortedElements = [...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: 'Флажки',
};
const renderPreviewElement = (element: TemplateElement) => {
const getWidthClass = () => {
switch (element.width) {
case 'half':
return 'col-span-1';
case 'full':
return 'col-span-full';
default:
return 'col-span-1';
}
};
return (
<div key={element.id} className={`space-y-2 ${getWidthClass()}`}>
{layoutSettings.showLabels && (
<label className="text-sm font-medium text-gray-700">
{element.label}
{element.required && <span className="text-red-500 ml-1">*</span>}
</label>
)}
<div className="p-2 border border-gray-200 rounded bg-gray-50 text-sm text-gray-500">
{element.type === 'text' && 'Текстовое поле'}
{element.type === 'textarea' && 'Многострочный текст'}
{element.type === 'number' && 'Числовое поле'}
{element.type === 'date' && 'Выбор даты'}
{element.type === 'select' && `Выпадающий список (${element.options?.length || 0} вариантов)`}
{element.type === 'radio' && `Радиокнопки (${element.options?.length || 0} вариантов)`}
{element.type === 'checkbox' && 'Флажок'}
</div>
{element.targetCells && element.targetCells.length > 0 && (
<div className="flex flex-wrap gap-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"
title={target.displayName}
>
{target.sheet}!{target.cell}
</span>
))}
</div>
)}
</div>
);
};
return (
<div className="space-y-6 max-h-96 overflow-y-auto">
{elements.length === 0 ? (
<div className="text-center py-8">
<p className="text-gray-500">Добавьте элементы для предварительного просмотра</p>
</div>
) : (
groupedElements().map(([groupName, groupElements]) => (
<Card key={groupName} className="border-dashed">
<CardHeader className="pb-3">
<CardTitle className="text-base">
{layoutSettings.grouping === 'by-type'
? typeLabels[groupName as ElementType] || groupName
: groupName
}
</CardTitle>
{layoutSettings.grouping !== 'none' && (
<p className="text-xs text-gray-500">
{groupElements.length} элемент{groupElements.length > 1 ? 'ов' : ''}
</p>
)}
</CardHeader>
<CardContent>
<div className={`grid ${getGridCols()} ${getSpacingClass()}`}>
{groupElements.map(renderPreviewElement)}
</div>
</CardContent>
</Card>
))
)}
</div>
);
};
interface ElementConstructorProps {
elements: TemplateElement[];
layoutSettings: FormLayoutSettings;
onElementAdd: (element: TemplateElement) => void;
onElementUpdate: (elementId: string, updates: Partial<TemplateElement>) => void;
onElementDelete: (elementId: string) => void;
onElementsReorder: (elements: TemplateElement[]) => void;
onLayoutSettingsChange: (settings: FormLayoutSettings) => void;
}
export const ElementConstructor: React.FC<ElementConstructorProps> = ({
elements,
layoutSettings,
onElementAdd,
onElementUpdate,
onElementDelete,
onElementsReorder,
onLayoutSettingsChange,
}) => {
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
const [isLayoutDialogOpen, setIsLayoutDialogOpen] = useState(false);
const [isPreviewOpen, setIsPreviewOpen] = useState(false);
const [editingElement, setEditingElement] = useState<TemplateElement | null>(null);
const [formData, setFormData] = useState<Partial<TemplateElement>>({
type: 'text',
name: '',
label: '',
targetCell: '',
targetCells: [],
placeholder: '',
required: false,
options: [],
width: 'auto',
category: '',
});
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
})
);
const resetForm = () => {
setFormData({
type: 'text',
name: '',
label: '',
targetCell: '',
targetCells: [],
placeholder: '',
required: false,
options: [],
width: 'auto',
category: '',
});
};
const handleAddElement = () => {
if (!formData.name || !formData.label || !formData.targetCell) return;
if (!formData.name || !formData.label || !formData.targetCells?.length) return;
const newElement: TemplateElement = {
id: Date.now().toString(),
type: formData.type as ElementType,
name: formData.name,
label: formData.label,
targetCell: formData.targetCell,
targetCells: formData.targetCells,
placeholder: formData.placeholder,
required: formData.required,
options: formData.options,
order: elements.length,
category: formData.category,
width: formData.width,
};
onElementAdd(newElement);
@@ -218,7 +681,7 @@ export const ElementConstructor: React.FC<ElementConstructorProps> = ({
};
const handleUpdateElement = () => {
if (!editingElement || !formData.name || !formData.label || !formData.targetCell) return;
if (!editingElement || !formData.name || !formData.label || !formData.targetCells?.length) return;
onElementUpdate(editingElement.id, formData);
setEditingElement(null);
@@ -230,112 +693,157 @@ export const ElementConstructor: React.FC<ElementConstructorProps> = ({
resetForm();
};
const handleDragEnd = (event: any) => {
const { active, over } = event;
if (active.id !== over.id) {
const oldIndex = elements.findIndex((item) => item.id === active.id);
const newIndex = elements.findIndex((item) => item.id === over.id);
const reorderedElements = arrayMove(elements, oldIndex, newIndex);
onElementsReorder(reorderedElements);
}
};
// Сортировка элементов по порядку
const sortedElements = [...elements].sort((a, b) => (a.order || 0) - (b.order || 0));
return (
<div className="h-full flex flex-col">
<div className="flex items-center justify-between p-4 bg-white">
<h3 className="text-lg font-semibold">Элементы формы</h3>
<Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
<DialogTrigger asChild>
<Button size="sm" onClick={() => resetForm()}>
<Plus className="h-4 w-4 mr-2" />
Добавить элемент
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[600px]">
<DialogHeader>
<DialogTitle>Добавить элемент</DialogTitle>
<DialogDescription>
Создайте новый элемент формы для связи с ячейкой Excel
</DialogDescription>
</DialogHeader>
<ElementForm formData={formData} setFormData={setFormData} />
<div className="flex justify-end gap-2 mt-4">
<Button variant="outline" onClick={() => setIsAddDialogOpen(false)}>
Отмена
<div className="h-full flex flex-col bg-gray-50">
<div className="flex items-center justify-between p-4 bg-white border-b">
<h3 className="text-lg font-semibold text-gray-800">Конструктор элементов</h3>
<div className="flex gap-2">
<Dialog open={isPreviewOpen} onOpenChange={setIsPreviewOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm">
<FileText className="h-4 w-4 mr-2" />
Предпросмотр формы
</Button>
<Button onClick={handleAddElement}>Добавить</Button>
</div>
</DialogContent>
</Dialog>
</DialogTrigger>
<DialogContent className="sm:max-w-[800px] max-h-[90vh]">
<DialogHeader>
<DialogTitle>Предпросмотр формы создания протокола</DialogTitle>
<DialogDescription>
Так будет выглядеть форма для пользователей при создании протокола
</DialogDescription>
</DialogHeader>
<FormPreview elements={elements} layoutSettings={layoutSettings} />
<div className="flex justify-end mt-4">
<Button onClick={() => setIsPreviewOpen(false)}>Закрыть</Button>
</div>
</DialogContent>
</Dialog>
<Dialog open={isLayoutDialogOpen} onOpenChange={setIsLayoutDialogOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm">
<LayoutGrid className="h-4 w-4 mr-2" />
Настройки отображения
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle>Настройки отображения элементов</DialogTitle>
<DialogDescription>
Настройте внешний вид формы создания протокола
</DialogDescription>
</DialogHeader>
<LayoutSettings settings={layoutSettings} onChange={onLayoutSettingsChange} />
<div className="flex justify-end mt-4">
<Button onClick={() => setIsLayoutDialogOpen(false)}>Готово</Button>
</div>
</DialogContent>
</Dialog>
<Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
<DialogTrigger asChild>
<Button size="sm" onClick={() => resetForm()}>
<Plus className="h-4 w-4 mr-2" />
Добавить элемент
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Добавить элемент</DialogTitle>
<DialogDescription>
Создайте новый элемент формы с привязкой к ячейкам Excel
</DialogDescription>
</DialogHeader>
<ElementForm formData={formData} setFormData={setFormData} />
<div className="flex justify-end gap-2 mt-4">
<Button variant="outline" onClick={() => setIsAddDialogOpen(false)}>
Отмена
</Button>
<Button onClick={handleAddElement} disabled={!formData.name || !formData.label || !formData.targetCells?.length}>
Добавить
</Button>
</div>
</DialogContent>
</Dialog>
</div>
</div>
<div className="flex-1 overflow-y-auto p-4 bg-white">
<div className="flex-1 overflow-y-auto p-4">
{elements.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-center">
<div className="rounded-full bg-gray-100 p-4 mb-4">
<Plus className="h-8 w-8 text-gray-400" />
<div className="flex flex-col items-center justify-center py-12 text-center">
<div className="rounded-full bg-gray-100 p-6 mb-4">
<Plus className="h-12 w-12 text-gray-400" />
</div>
<h3 className="text-lg font-medium text-gray-900 mb-2">Нет элементов интерфейса</h3>
<p className="text-sm text-gray-500 mb-4">
Создайте элементы формы для связи с ячейками Excel
<h3 className="text-xl font-medium text-gray-900 mb-2">Нет элементов интерфейса</h3>
<p className="text-gray-500 mb-6 max-w-md">
Создайте элементы формы для связи с ячейками Excel. Элементы будут отображаться
пользователям при создании протокола.
</p>
<Button onClick={() => setIsAddDialogOpen(true)} className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Добавить первый элемент
Создать первый элемент
</Button>
</div>
) : (
elements.map(element => (
<Card key={element.id} className="mb-4">
<CardHeader className="flex flex-row items-center justify-between p-4">
<div className="flex items-center gap-2">
{ELEMENT_TYPES.find(t => t.type === element.type)?.icon}
<p className="font-semibold">{element.label}</p>
</div>
<div className="flex items-center gap-2">
<Dialog
open={editingElement?.id === element.id}
onOpenChange={isOpen => !isOpen && handleCancelEdit()}
>
<DialogTrigger asChild>
<Button variant="ghost" size="icon" onClick={() => handleEditElement(element)}>
<Edit className="h-4 w-4" />
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[600px]">
<DialogHeader>
<DialogTitle>Редактировать элемент</DialogTitle>
<DialogDescription>
Измените настройки элемента формы
</DialogDescription>
</DialogHeader>
<ElementForm formData={formData} setFormData={setFormData} />
<div className="flex justify-end gap-2 mt-4">
<Button variant="outline" onClick={handleCancelEdit}>
Отмена
</Button>
<Button onClick={handleUpdateElement}>Сохранить</Button>
</div>
</DialogContent>
</Dialog>
<Button
variant="ghost"
size="icon"
className="text-red-500 hover:text-red-600"
onClick={() => onElementDelete(element.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</CardHeader>
<CardContent className="p-4 pt-0">
<div className="text-sm text-muted-foreground">
<p>
<strong>Тип:</strong> {ELEMENT_TYPES.find(t => t.type === element.type)?.label}
</p>
<p>
<strong>Имя:</strong> {element.name}
</p>
<p>
<strong>Ячейка:</strong> {element.targetCell}
</p>
</div>
</CardContent>
</Card>
))
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext items={sortedElements.map(e => e.id)} strategy={verticalListSortingStrategy}>
<div className="space-y-4">
{sortedElements.map(element => (
<SortableElement
key={element.id}
element={element}
onEdit={handleEditElement}
onDelete={onElementDelete}
/>
))}
</div>
</SortableContext>
</DndContext>
)}
</div>
{/* Dialog для редактирования элемента */}
<Dialog
open={!!editingElement}
onOpenChange={isOpen => !isOpen && handleCancelEdit()}
>
<DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Редактировать элемент</DialogTitle>
<DialogDescription>
Измените настройки элемента формы
</DialogDescription>
</DialogHeader>
<ElementForm formData={formData} setFormData={setFormData} />
<div className="flex justify-end gap-2 mt-4">
<Button variant="outline" onClick={handleCancelEdit}>
Отмена
</Button>
<Button onClick={handleUpdateElement} disabled={!formData.name || !formData.label || !formData.targetCells?.length}>
Сохранить
</Button>
</div>
</DialogContent>
</Dialog>
</div>
);
};

View File

@@ -1,4 +1,5 @@
import React, { createContext, ReactNode, useContext, useState } from 'react';
import { getDefaultLayoutSettings, migrateTemplateElement } from '../lib/utils';
import { Template } from '../types/template';
interface TemplateContextType {
@@ -23,16 +24,27 @@ interface TemplateProviderProps {
children: ReactNode;
}
// Функция миграции шаблона
function migrateTemplate(template: any): Template {
return {
...template,
elements: template.elements?.map(migrateTemplateElement) || [],
layoutSettings: template.layoutSettings || getDefaultLayoutSettings(),
};
}
export const TemplateProvider: React.FC<TemplateProviderProps> = ({ children }) => {
const [templates, setTemplates] = useState<Template[]>([]);
const addTemplate = (template: Template) => {
setTemplates(prev => [...prev, template]);
const migratedTemplate = migrateTemplate(template);
setTemplates(prev => [...prev, migratedTemplate]);
};
const updateTemplate = (updatedTemplate: Template) => {
const migratedTemplate = migrateTemplate(updatedTemplate);
setTemplates(prev => prev.map(t =>
t.id === updatedTemplate.id ? updatedTemplate : t
t.id === migratedTemplate.id ? migratedTemplate : t
));
};
@@ -41,16 +53,17 @@ export const TemplateProvider: React.FC<TemplateProviderProps> = ({ children })
};
const getTemplate = (templateId: string) => {
return templates.find(t => t.id === templateId);
const template = templates.find(t => t.id === templateId);
return template ? migrateTemplate(template) : undefined;
};
return (
<TemplateContext.Provider value={{
templates,
templates: templates.map(migrateTemplate), // Применяем миграцию при получении
addTemplate,
updateTemplate,
deleteTemplate,
getTemplate
getTemplate,
}}>
{children}
</TemplateContext.Provider>

View File

@@ -1,6 +1,70 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
import { CellTarget, FormLayoutSettings, TemplateElement } from "../types/template";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
// Миграция элементов из старого формата в новый
export function migrateTemplateElement(element: any): TemplateElement {
// Если элемент уже в новом формате
if (element.targetCells && Array.isArray(element.targetCells)) {
return element as TemplateElement;
}
// Миграция из старого формата
const targetCells: CellTarget[] = [];
if (element.targetCell) {
// Парсим старый формат targetCell (например "A1", "B5")
const cellMatch = element.targetCell.match(/^([A-Z]+)(\d+)$/);
if (cellMatch) {
targetCells.push({
sheet: 'Report', // По умолчанию используем Report
cell: element.targetCell,
displayName: `Ячейка ${element.targetCell}`,
});
}
}
return {
...element,
targetCells,
order: element.order || 0,
category: element.category || '',
width: element.width || 'auto',
} as TemplateElement;
}
// Получение настроек отображения по умолчанию
export function getDefaultLayoutSettings(): FormLayoutSettings {
return {
columns: 2,
grouping: 'none',
elementSpacing: 'normal',
showLabels: true,
enableDragDrop: true,
};
}
// Валидация адреса ячейки
export function validateCellAddress(cell: string): boolean {
return /^[A-Z]+\d+$/.test(cell);
}
// Парсинг адреса ячейки в компоненты
export function parseCellAddress(cell: string): { column: string; row: number } | null {
const match = cell.match(/^([A-Z]+)(\d+)$/);
if (!match) return null;
return {
column: match[1],
row: parseInt(match[2], 10),
};
}
// Генерация уникального ID для элемента
export function generateElementId(): string {
return `element_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}

View File

@@ -5,13 +5,12 @@ import { ElementConstructor } from '../../../../components/TemplateManager/Eleme
import { Button } from '../../../../components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../../../components/ui/card';
import { useTemplateContext } from '../../../../contexts/TemplateContext';
import { Template, TemplateElement } from '../../../../types/template';
import { FormLayoutSettings, Template, TemplateElement } from '../../../../types/template';
export const ElementsCreation: FC = () => {
const navigate = useNavigate();
const { templates, updateTemplate } = useTemplateContext();
const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(null);
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const handleTemplateSelect = (template: Template) => {
setSelectedTemplate(template);
@@ -58,10 +57,51 @@ export const ElementsCreation: FC = () => {
setSelectedTemplate(updatedTemplate);
};
const handleElementsReorder = (reorderedElements: TemplateElement[]) => {
if (!selectedTemplate) return;
// Обновляем порядок элементов
const elementsWithOrder = reorderedElements.map((element, index) => ({
...element,
order: index,
}));
const updatedTemplate = {
...selectedTemplate,
elements: elementsWithOrder,
updatedAt: new Date(),
};
updateTemplate(updatedTemplate);
setSelectedTemplate(updatedTemplate);
};
const handleLayoutSettingsChange = (settings: FormLayoutSettings) => {
if (!selectedTemplate) return;
const updatedTemplate = {
...selectedTemplate,
layoutSettings: settings,
updatedAt: new Date(),
};
updateTemplate(updatedTemplate);
setSelectedTemplate(updatedTemplate);
};
const handleBack = () => {
setSelectedTemplate(null);
};
// Настройки отображения по умолчанию
const defaultLayoutSettings: FormLayoutSettings = {
columns: 2,
grouping: 'none',
elementSpacing: 'normal',
showLabels: true,
enableDragDrop: true,
};
if (selectedTemplate) {
return (
<div className="h-full bg-gray-50">
@@ -73,25 +113,33 @@ export const ElementsCreation: FC = () => {
</Button>
<div>
<h1 className="text-xl font-semibold text-gray-800">
Создание элементов: {selectedTemplate.name}
Конструктор элементов: {selectedTemplate.name}
</h1>
<p className="text-sm text-gray-600 mt-1">
Создайте элементы формы для связи с ячейками шаблона
Создайте элементы формы для связи с ячейками шаблона. Используйте drag & drop для изменения порядка.
</p>
</div>
</div>
<Button onClick={() => navigate('/templates')} variant="outline">
Перейти к шаблонам
</Button>
<div className="flex gap-2">
<Button onClick={() => navigate('/create-protocol')} variant="outline">
Предпросмотр формы
</Button>
<Button onClick={() => navigate('/templates')} variant="outline">
К шаблонам
</Button>
</div>
</div>
</div>
<div className="flex-1 bg-blue-50">
<div className="flex-1">
<ElementConstructor
elements={selectedTemplate.elements}
layoutSettings={selectedTemplate.layoutSettings || defaultLayoutSettings}
onElementAdd={handleElementAdd}
onElementUpdate={handleElementUpdate}
onElementDelete={handleElementDelete}
onElementsReorder={handleElementsReorder}
onLayoutSettingsChange={handleLayoutSettingsChange}
/>
</div>
</div>
@@ -120,7 +168,7 @@ export const ElementsCreation: FC = () => {
<div className="text-center py-12">
<Wrench 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-6">Создайте шаблон для начала работы с элементами</p>
<p className="text-gray-600 mb-6">Создайте шаблон протокола для начала работы с элементами</p>
<Button onClick={() => navigate('/templates')}>
<Plus className="h-4 w-4 mr-2" />
Создать шаблон
@@ -144,8 +192,19 @@ export const ElementsCreation: FC = () => {
<Wrench 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.updatedAt.toLocaleDateString()}
Обновлен: {template.updatedAt.toLocaleDateString('ru-RU')}
</div>
</div>
<div className="mt-4">

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>

View File

@@ -13,16 +13,35 @@ export interface ElementOption {
label: string
}
// Расширенный тип для ячейки с указанием листа
export interface CellTarget {
sheet: string // название листа, например "L" или "R"
cell: string // адрес ячейки, например "A2" или "B4"
displayName?: string // отображаемое имя для пользователя
}
// Настройки отображения элементов в форме
export interface FormLayoutSettings {
columns: number // количество столбцов в сетке
grouping: 'none' | 'by-type' | 'by-category' // группировка элементов
elementSpacing: 'compact' | 'normal' | 'spacious' // расстояние между элементами
showLabels: boolean // показывать ли подписи элементов
enableDragDrop: boolean // включить drag & drop для изменения порядка
}
export interface TemplateElement {
id: string
type: ElementType
name: string
label: string
targetCell: string // например "A1", "B5"
targetCells: CellTarget[] // множественные ячейки вместо одной targetCell
options?: ElementOption[] // для select и radio
required?: boolean
defaultValue?: string
placeholder?: string
order?: number // порядок отображения в форме
category?: string // категория для группировки
width?: 'auto' | 'half' | 'full' // ширина элемента в форме
}
// Типы шаблонов
@@ -33,6 +52,7 @@ export interface Template {
excelFile?: File
excelData?: Record<string, any> // данные из Excel
elements: TemplateElement[]
layoutSettings?: FormLayoutSettings // настройки отображения формы
createdAt: Date
updatedAt: Date
}