холст конструктор

This commit is contained in:
2025-07-16 17:25:33 +03:00
parent b77303fa97
commit 6933fab3bb
13 changed files with 1243 additions and 996 deletions

View File

@@ -95,17 +95,14 @@ export const ElementsCreation: FC = () => {
// Настройки отображения по умолчанию
const defaultLayoutSettings: FormLayoutSettings = {
columns: 2,
grouping: 'none',
elementSpacing: 'normal',
showLabels: true,
enableDragDrop: true,
gridSize: 20,
showGrid: true,
};
if (selectedTemplate) {
return (
<div className="h-full bg-gray-50">
<div className="bg-white border-b border-gray-200 p-4">
<div className="h-full">
<div className="bg-white border-b border-gray-200 p-4 sticky top-0 z-50">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<Button variant="ghost" onClick={handleBack}>
@@ -116,7 +113,7 @@ export const ElementsCreation: FC = () => {
Конструктор элементов: {selectedTemplate.name}
</h1>
<p className="text-sm text-gray-600 mt-1">
Создайте элементы формы для связи с ячейками шаблона. Используйте drag & drop для изменения порядка.
Создайте элементы формы и разместите их на холсте перетаскиванием
</p>
</div>
</div>
@@ -131,7 +128,7 @@ export const ElementsCreation: FC = () => {
</div>
</div>
<div className="flex-1">
<div className="h-[calc(100vh-104px)]">
<ElementConstructor
elements={selectedTemplate.elements}
layoutSettings={selectedTemplate.layoutSettings || defaultLayoutSettings}
@@ -192,17 +189,6 @@ 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('ru-RU')}
</div>

View File

@@ -1,6 +1,7 @@
import { ArrowLeft, Download, FileText, Plus, Save } from 'lucide-react';
import { FC, useState } from 'react';
import { FC, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Badge } from '../../../../components/ui/badge';
import { Button } from '../../../../components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../../../components/ui/card';
import { Checkbox } from '../../../../components/ui/checkbox';
@@ -9,7 +10,7 @@ import { RadioGroup, RadioGroupItem } from '../../../../components/ui/radio-grou
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';
import { Template, TemplateElement } from '../../../../types/template';
interface ProtocolFormProps {
template: Template;
@@ -21,11 +22,9 @@ 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 FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
const renderInput = () => {
switch (element.type) {
case 'text':
@@ -119,36 +118,30 @@ const FormElement: FC<FormElementProps> = ({ element, value, onChange, showLabel
}
};
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">
<div className="space-y-3">
<div className="flex items-center gap-2">
<label className="text-sm font-medium text-gray-900">
{element.label}
{element.required && <span className="text-red-500 ml-1">*</span>}
</label>
)}
{element.required && (
<Badge variant="required" className="text-xs">
!
</Badge>
)}
</div>
{renderInput()}
{element.targetCells && element.targetCells.length > 0 && (
<div className="flex flex-wrap gap-1 mt-1">
<div className="flex flex-wrap gap-1.5">
{element.targetCells.map((target, index) => (
<span
<Badge
key={index}
className="inline-block px-1.5 py-0.5 bg-blue-100 text-blue-700 text-xs rounded text-center"
variant="excel"
className="text-xs font-mono"
title={target.displayName}
>
{target.sheet}!{target.cell}
</span>
</Badge>
))}
</div>
)}
@@ -158,7 +151,6 @@ const FormElement: FC<FormElementProps> = ({ element, value, onChange, showLabel
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 => ({
@@ -168,6 +160,12 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
};
const handleSave = () => {
// Ищем элемент с названием протокола (должен иметь специальный тип или название)
const protocolNameElement = template.elements.find(el =>
el.name === 'protocolName' || el.label === 'Название протокола'
);
const protocolName = protocolNameElement ? formData[protocolNameElement.id] : 'Новый протокол';
const data = {
protocolName,
templateId: template.id,
@@ -178,84 +176,40 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
};
const handleExport = () => {
// Логика экспорта в Excel будет реализована позже
console.log('Экспорт в Excel:', { protocolName, formData });
console.log(кспорт в Excel:', { formData });
alert('Функция экспорта будет реализована в следующих версиях');
};
const canvasSize = useMemo(() => {
const PADDING_Y = 200;
const baseWidth = 1200;
const baseHeight = 800;
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);
if (template.elements.length === 0) {
return { width: baseWidth, height: baseHeight };
}
return [['Все элементы', sortedElements]];
};
const getSpacingClass = () => {
switch (layoutSettings.elementSpacing) {
case 'compact':
return 'gap-3';
case 'spacious':
return 'gap-8';
default:
return 'gap-6';
}
};
const contentHeight = Math.max(
0,
...template.elements.map((el) => (el.layout?.y || 0) + (el.layout?.height || 0)),
);
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';
}
};
return {
width: baseWidth,
height: Math.max(baseHeight, contentHeight + PADDING_Y),
};
}, [template.elements]);
const typeLabels: Record<ElementType, string> = {
text: 'Текстовые поля',
textarea: 'Многострочный текст',
number: 'Числовые поля',
date: 'Даты',
select: 'Выпадающие списки',
radio: 'Переключатели',
checkbox: 'Флажки',
};
// Проверяем есть ли кнопка сохранения (есть ли название протокола)
const protocolNameElement = template.elements.find(el =>
el.name === 'protocolName' || el.label === 'Название протокола'
);
const canSave = protocolNameElement ? !!formData[protocolNameElement.id]?.trim() : false;
return (
<div className="h-full bg-gray-50">
<div className="flex flex-col h-screen bg-gray-50">
{/* Заголовок */}
<div className="bg-white border-b border-gray-200 p-4">
<div className="bg-white border-b border-gray-200 p-4 shrink-0">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<Button variant="ghost" onClick={onBack}>
@@ -266,9 +220,6 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
<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">
@@ -276,7 +227,7 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
<Download className="h-4 w-4 mr-2" />
Экспорт в Excel
</Button>
<Button onClick={handleSave} disabled={!protocolName.trim()}>
<Button onClick={handleSave} disabled={!canSave}>
<Save className="h-4 w-4 mr-2" />
Сохранить протокол
</Button>
@@ -284,77 +235,49 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
</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 className="flex-1 overflow-auto">
<div
className="relative bg-white shadow-lg mx-auto my-8"
style={{ width: canvasSize.width, height: canvasSize.height }}
>
{template.elements.map((element) => {
const layout = element.layout || { x: 50, y: 50, width: 300, height: 80 };
return (
<div
key={element.id}
className="absolute"
style={{
left: layout.x,
top: layout.y,
width: layout.width,
minHeight: layout.height,
zIndex: layout.zIndex || 1,
}}
>
<FormElement
element={element}
value={formData[element.id]}
onChange={(value) => handleFieldChange(element.id, value)}
/>
</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>
))
)}
);
})}
{template.elements.length === 0 && (
<div className="absolute inset-0 flex items-center justify-center">
<div className="text-center text-gray-400">
<FileText className="h-16 w-16 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>
</div>
)}
</div>
</div>
</div>
@@ -437,17 +360,6 @@ 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('ru-RU')}
</div>