новые элементы

This commit is contained in:
2025-07-18 09:11:43 +03:00
parent fda99279d3
commit 021368f173
11 changed files with 1964 additions and 889 deletions

View File

@@ -1,166 +0,0 @@
# Архитектура системы элементов
## Обзор
Система была переработана для обеспечения универсальности и расширяемости. Теперь все элементы регистрируются в едином реестре, что позволяет легко добавлять новые типы элементов без изменения основного кода.
## Структура
### 1. Реестр элементов (`src/lib/element-registry.ts`)
Центральный реестр, который содержит все определения элементов:
```typescript
export interface ElementDefinition<Config = any, Value = any> {
type: ElementType; // Уникальный тип элемента
label: string; // Человекочитаемое имя
icon: ReactNode; // Иконка для UI
Editor: React.FC<{ config: Config; onChange(c: Config): void }>;
Preview: React.FC<{ config: Config }>;
Render: React.FC<{ config: Config; value: Value; onChange?(v: Value): void }>;
defaultConfig: Config; // Конфигурация по умолчанию
mapToCells?(config: Config): CellTarget[]; // Маппинг на ячейки Excel
}
```
### 2. Базовые элементы (`src/components/BasicElements/`)
Стандартные элементы формы:
- `TextElement.tsx` - текстовое поле
- `SelectElement.tsx` - выпадающий список
- `NumberElement.tsx` - числовое поле
- `DateElement.tsx` - поле даты
- `TextareaElement.tsx` - многострочный текст
- `CheckboxElement.tsx` - чекбокс
- `RadioElement.tsx` - радиокнопки
### 3. Специальные элементы (`src/components/StandardsElement/`)
Сложные элементы с собственной логикой:
- `StandardsDialog.tsx` - диалог выбора эталонов
- `StandardsEditor.tsx` - редактор настроек
- `StandardsPreview.tsx` - превью элемента
- `definition.tsx` - определение элемента
## Как добавить новый элемент
### 1. Создать компоненты
```typescript
// MyElement/MyElementEditor.tsx
export const MyElementEditor: React.FC<{ config: MyConfig; onChange: (config: MyConfig) => void }> = ({ config, onChange }) => {
// Логика редактирования
};
// MyElement/MyElementPreview.tsx
export const MyElementPreview: React.FC<{ config: MyConfig }> = ({ config }) => {
// Логика превью
};
// MyElement/MyElementRender.tsx
export const MyElementRender: React.FC<{ config: MyConfig; value: string; onChange?: (value: string) => void }> = ({ config, value, onChange }) => {
// Логика рендеринга
};
```
### 2. Создать определение
```typescript
// MyElement/definition.tsx
export const myElementDefinition: ElementDefinition<MyConfig, string> = {
type: "my_element",
label: "Мой элемент",
icon: <MyIcon className="h-4 w-4" />,
defaultConfig: {
// конфигурация по умолчанию
},
Editor: MyElementEditor,
Preview: MyElementPreview,
Render: MyElementRender,
mapToCells: (config) => {
// логика маппинга на ячейки Excel
return [];
},
};
```
### 3. Зарегистрировать в реестре
```typescript
// src/lib/element-registry-init.ts
import { myElementDefinition } from "@/components/MyElement/definition";
export function initializeElementRegistry() {
// ... существующие элементы
registerElement("my_element", myElementDefinition);
}
```
### 4. Добавить тип в types/template.ts
```typescript
export type ElementType =
| 'text' | 'select' | 'radio' | 'checkbox' | 'number'
| 'textarea' | 'date' | 'standards'
| 'my_element'; // <-- новый тип
```
## Особенности элемента "Измерительные эталоны"
### Конфигурация
```typescript
interface StandardsConfig {
registryNumber: string; // ГРСИ
sheet: string; // Лист Excel
startCell: string; // Первая ячейка (например "A10")
maxItems: number; // Обычно 7
targetCells: CellTarget[];
}
```
### Логика маппинга
Элемент автоматически генерирует ячейки для записи выбранных эталонов:
```typescript
mapToCells: (cfg) => {
const res: CellTarget[] = [];
const parsed = parseCellAddress(cfg.startCell);
if (!parsed) return res;
const { column, row } = parsed;
// Генерируем ячейки вертикально (A1, A2, A3...)
for (let i = 0; i < cfg.maxItems; i++) {
res.push({
sheet: cfg.sheet,
cell: `${column}${row + i}`,
displayName: `Эталон ${i + 1}`,
});
}
return res;
}
```
### Ограничения
- Максимум 7 эталонов (настраивается)
- Автоматическое заполнение только выбранных позиций
- Оставшиеся ячейки остаются пустыми
## Преимущества новой архитектуры
1. **Расширяемость**: Добавление новых элементов требует минимальных изменений
2. **Универсальность**: Единый интерфейс для всех элементов
3. **Типобезопасность**: TypeScript обеспечивает корректность типов
4. **Модульность**: Каждый элемент самодостаточен
5. **Переиспользование**: Компоненты можно использовать в разных контекстах
## Миграция
Старые элементы продолжают работать через fallback-логику в `ElementConstructor.tsx`. Для полной миграции рекомендуется перевести все элементы на новую архитектуру.

View File

@@ -0,0 +1,237 @@
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { ElementDefinition } from '@/lib/element-registry'
import { ElementOption } from '@/types/template'
import { Plus, Square, Trash2 } from 'lucide-react'
interface ButtonGroupConfig {
placeholder?: string
required?: boolean
options: ElementOption[]
targetCells: any[]
layout?: 'horizontal' | 'vertical'
buttonStyle?: 'default' | 'outline' | 'ghost'
}
export const buttonGroupDefinition: ElementDefinition<
ButtonGroupConfig,
string
> = {
type: 'button-group',
label: 'Группа кнопок',
icon: <Square className="h-4 w-4" />,
defaultConfig: {
placeholder: '',
required: false,
options: [],
targetCells: [],
layout: 'horizontal',
buttonStyle: 'default',
},
Editor: ({ config, onChange }) => {
const handleAddOption = () => {
onChange({
...config,
options: [...config.options, { value: '', label: '' }],
})
}
const handleUpdateOption = (
index: number,
field: 'value' | 'label',
value: string,
) => {
onChange({
...config,
options: config.options.map((option, i) =>
i === index ? { ...option, [field]: value } : option,
),
})
}
const handleRemoveOption = (index: number) => {
onChange({
...config,
options: config.options.filter((_, i) => i !== index),
})
}
return (
<div className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">Подсказка</label>
<Input
placeholder="Выберите значение..."
value={config.placeholder || ''}
onChange={(e) =>
onChange({ ...config, placeholder: e.target.value })
}
/>
</div>
<div className="flex items-center space-x-2">
<input
type="checkbox"
id="required"
checked={config.required}
onChange={(e) =>
onChange({ ...config, required: e.target.checked })
}
/>
<label htmlFor="required" className="text-sm font-medium">
Обязательное поле
</label>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Расположение кнопок</label>
<div className="flex gap-2">
<Button
variant={config.layout === 'horizontal' ? 'default' : 'outline'}
size="sm"
onClick={() => onChange({ ...config, layout: 'horizontal' })}
>
Горизонтально
</Button>
<Button
variant={config.layout === 'vertical' ? 'default' : 'outline'}
size="sm"
onClick={() => onChange({ ...config, layout: 'vertical' })}
>
Вертикально
</Button>
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Стиль кнопок</label>
<div className="flex gap-2">
<Button
variant={config.buttonStyle === 'default' ? 'default' : 'outline'}
size="sm"
onClick={() => onChange({ ...config, buttonStyle: 'default' })}
>
Обычный
</Button>
<Button
variant={config.buttonStyle === 'outline' ? 'default' : 'outline'}
size="sm"
onClick={() => onChange({ ...config, buttonStyle: 'outline' })}
>
Контурный
</Button>
<Button
variant={config.buttonStyle === 'ghost' ? 'default' : 'outline'}
size="sm"
onClick={() => onChange({ ...config, buttonStyle: 'ghost' })}
>
Призрачный
</Button>
</div>
</div>
<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={handleAddOption}>
<Plus className="mr-1 h-4 w-4" />
Добавить кнопку
</Button>
</div>
<div className="max-h-32 space-y-2 overflow-y-auto">
{config.options.map((option, index) => (
<div key={index} className="flex gap-2">
<Input
placeholder="Значение"
value={option.value}
onChange={(e) =>
handleUpdateOption(index, 'value', e.target.value)
}
/>
<Input
placeholder="Текст кнопки"
value={option.label}
onChange={(e) =>
handleUpdateOption(index, 'label', e.target.value)
}
/>
<Button
variant="outline"
size="icon"
onClick={() => handleRemoveOption(index)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
))}
</div>
</div>
</div>
)
},
Preview: ({ config }) => (
<div className="space-y-3">
<div className="text-sm font-medium text-gray-700">Предпросмотр</div>
<div className="rounded-lg border border-gray-200 bg-white p-4">
<div
className={`flex ${
config.layout === 'vertical' ? 'flex-col' : 'flex-wrap'
} gap-1.5`}
>
{config.options.length > 0 ? (
config.options.map((option, index) => (
<button
key={index}
className={`rounded-md border px-3 py-1.5 text-sm font-medium transition-all duration-200 ${
config.buttonStyle === 'outline'
? 'border-border bg-background text-foreground hover:border-primary/30 hover:bg-primary/5'
: config.buttonStyle === 'ghost'
? 'border-transparent bg-transparent text-foreground hover:bg-accent hover:text-accent-foreground'
: 'border-primary bg-primary text-primary-foreground shadow-sm'
}`}
>
{option.label || `Кнопка ${index + 1}`}
</button>
))
) : (
<div className="rounded-md border border-dashed bg-muted/30 px-3 py-1.5 text-sm text-muted-foreground">
{config.placeholder || 'Добавьте кнопки'}
</div>
)}
</div>
</div>
</div>
),
Render: ({ config, value, onChange }) => (
<div className="space-y-2">
<div
className={`flex ${
config.layout === 'vertical' ? 'flex-col' : 'flex-wrap'
} gap-1.5`}
>
{config.options.map((option, index) => (
<button
key={index}
onClick={() => onChange?.(option.value)}
className={`rounded-md border px-3 py-1.5 text-sm font-medium transition-all duration-200 ${
value === option.value
? 'border-primary bg-primary text-primary-foreground shadow-sm'
: config.buttonStyle === 'outline'
? 'border-border bg-background text-foreground hover:border-primary/30 hover:bg-primary/5'
: config.buttonStyle === 'ghost'
? 'border-transparent bg-transparent text-foreground hover:bg-accent hover:text-accent-foreground'
: 'border-border bg-background text-foreground hover:border-primary/30 hover:bg-primary/5'
}`}
>
{option.label}
</button>
))}
</div>
{config.required && !value && (
<p className="text-sm text-red-500">
Это поле обязательно для заполнения
</p>
)}
</div>
),
}

View File

@@ -0,0 +1,642 @@
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { ElementDefinition } from '@/lib/element-registry'
import {
AlertCircle,
Check,
Droplets,
Edit3,
Gauge,
Radio,
Thermometer,
X,
Zap,
} from 'lucide-react'
import React, { useEffect, useState } from 'react'
interface CalibrationConditions {
temperature: string
humidity: string
pressure: string
voltage: string
frequency: string
lastUpdated: string
updatedBy?: string
}
interface ValidationResult {
isValid: boolean
message?: string
}
interface CalibrationCondInfoProps {
conditions: CalibrationConditions
isOutdated: boolean
onUpdate: (conditions: CalibrationConditions) => Promise<boolean>
}
// Валидационные правила
const validateField = (field: string, value: string): ValidationResult => {
const numValue = parseFloat(value)
if (!value.trim()) {
return { isValid: false, message: 'Поле обязательно' }
}
if (isNaN(numValue)) {
return { isValid: false, message: 'Введите число' }
}
switch (field) {
case 'temperature':
if (numValue < -40 || numValue > 85) {
return { isValid: false, message: 'Диапазон: -40...+85°C' }
}
break
case 'humidity':
if (numValue < 0 || numValue > 100) {
return { isValid: false, message: 'Диапазон: 0...100%' }
}
break
case 'pressure':
if (numValue < 80 || numValue > 120) {
return { isValid: false, message: 'Диапазон: 80...120 кПа' }
}
break
case 'voltage':
if (numValue < 180 || numValue > 250) {
return { isValid: false, message: 'Диапазон: 180...250 В' }
}
break
case 'frequency':
if (numValue < 45 || numValue > 65) {
return { isValid: false, message: 'Диапазон: 45...65 Гц' }
}
break
}
return { isValid: true }
}
const formatLastUpdated = (dateString: string) => {
const date = new Date(dateString)
const today = new Date()
const yesterday = new Date(today)
yesterday.setDate(yesterday.getDate() - 1)
const weekdayRu = date.toLocaleString('ru-RU', { weekday: 'long' })
const monthShortRu = date
.toLocaleString('ru-RU', { month: 'short' })
.replace(/\./, '')
.replace(/^./, (s) => s.toUpperCase())
const day = date.getDate()
const time: string = date.toLocaleString('ru-RU', {
hour: '2-digit',
minute: '2-digit',
})
if (date.toDateString() === today.toDateString()) {
return `Сегодня в ${time}`
} else if (date.toDateString() === yesterday.toDateString()) {
return `Вчера в ${time}`
} else {
return `${weekdayRu.replace(/^./, (s) =>
s.toUpperCase(),
)} ${day} ${monthShortRu} ${time}`
}
}
function CalibrationCondInfo({
conditions,
isOutdated,
onUpdate,
}: CalibrationCondInfoProps) {
const [showModal, setShowModal] = useState(false)
const [tempConditions, setTempConditions] =
useState<CalibrationConditions>(conditions)
const [validationErrors, setValidationErrors] = useState<
Record<string, string>
>({})
const [isLoading, setIsLoading] = useState(false)
useEffect(() => {
setTempConditions(conditions)
}, [conditions])
const validateForm = () => {
const errors: Record<string, string> = {}
const fields = [
'temperature',
'humidity',
'pressure',
'voltage',
'frequency',
]
fields.forEach((field) => {
const validation = validateField(
field,
tempConditions[field as keyof CalibrationConditions] as string,
)
if (!validation.isValid && validation.message) {
errors[field] = validation.message
}
})
setValidationErrors(errors)
return Object.keys(errors).length === 0
}
const handleFieldChange = (field: string, value: string) => {
setTempConditions((prev) => ({ ...prev, [field]: value }))
// Валидация в реальном времени
const validation = validateField(field, value)
setValidationErrors((prev) => ({
...prev,
[field]: validation.isValid ? '' : validation.message || '',
}))
}
const handleSave = async () => {
if (!validateForm()) return
setIsLoading(true)
const newConditions = {
...tempConditions,
lastUpdated: new Date().toISOString(),
}
const success = await onUpdate(newConditions)
setIsLoading(false)
if (success) {
setShowModal(false)
} else {
alert('Не удалось сохранить условия поверки')
}
}
const openModal = () => {
setTempConditions(conditions)
setValidationErrors({})
setShowModal(true)
// Устанавливаем фокус на первое поле через небольшую задержку
setTimeout(() => {
const firstInput = document.getElementById(
'modal-temperature',
) as HTMLInputElement
if (firstInput) {
firstInput.focus()
firstInput.select()
}
}, 100)
}
const handleKeyDown = (e: React.KeyboardEvent) => {
if (
e.key === 'Enter' &&
!Object.keys(validationErrors).some((key) => validationErrors[key])
) {
handleSave()
}
if (e.key === 'Escape') {
setShowModal(false)
}
}
const fieldConfigs = [
{
key: 'temperature',
label: 'Температура',
icon: Thermometer,
unit: '°C',
placeholder: '20',
},
{
key: 'humidity',
label: 'Влажность',
icon: Droplets,
unit: '%',
placeholder: '65',
},
{
key: 'pressure',
label: 'Давление',
icon: Gauge,
unit: 'кПа',
placeholder: '101.3',
},
{
key: 'voltage',
label: 'Напряжение',
icon: Zap,
unit: 'В',
placeholder: '220',
},
{
key: 'frequency',
label: 'Частота',
icon: Radio,
unit: 'Гц',
placeholder: '50',
},
]
return (
<>
{/* Компактное отображение */}
<div className="flex items-center gap-3 rounded-lg border bg-muted/50 px-3 py-2">
<div className="flex items-center gap-3 text-xs">
{fieldConfigs.map(({ key, icon: Icon, unit }) => (
<div key={key} className="flex items-center gap-1">
<Icon className="h-3 w-3 text-muted-foreground" />
<span className="text-foreground">
{conditions[key as keyof CalibrationConditions]}
{unit}
</span>
</div>
))}
</div>
<Button
variant="ghost"
size="icon"
onClick={openModal}
className={`h-6 w-6 p-0 ${
isOutdated ? 'text-yellow-600 hover:text-yellow-700' : ''
}`}
>
<Edit3 className="h-3 w-3" />
</Button>
{isOutdated && (
<div className="h-2 w-2 animate-pulse rounded-full bg-yellow-500" />
)}
</div>
{/* Модальное окно */}
{showModal && (
<div
className="fixed inset-0 z-50 flex items-center justify-center overflow-y-auto bg-black/50 p-4"
onKeyDown={handleKeyDown}
>
<div className="flex min-h-full items-center justify-center p-4">
<Card className="mx-auto my-8 w-full max-w-2xl">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
<CardTitle className="text-lg">Условия поверки</CardTitle>
<Button
variant="ghost"
size="sm"
onClick={() => setShowModal(false)}
>
<X className="h-4 w-4" />
</Button>
</CardHeader>
<CardContent className="space-y-6">
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
{fieldConfigs.map(
({ key, label, icon: Icon, unit, placeholder }) => {
const hasError = validationErrors[key]
const isValid =
tempConditions[key as keyof CalibrationConditions] &&
!hasError
return (
<div key={key} className="space-y-2">
<Label
htmlFor={`modal-${key}`}
className="flex items-center gap-2"
>
<Icon className="h-4 w-4 text-muted-foreground" />
{label}
</Label>
<div className="space-y-1">
<div className="flex items-center gap-2">
<Input
id={`modal-${key}`}
value={
tempConditions[
key as keyof CalibrationConditions
] as string
}
onChange={(e) =>
handleFieldChange(key, e.target.value)
}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
handleSave()
}
}}
className={`text-center [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none ${
hasError
? 'border-destructive focus-visible:ring-destructive'
: isValid
? 'border-green-500 focus-visible:ring-green-500'
: ''
}`}
placeholder={placeholder}
type="number"
step="0.1"
/>
<div className="flex min-w-[3rem] items-center gap-1">
<span className="text-sm text-muted-foreground">
{unit}
</span>
{isValid && (
<Check className="h-4 w-4 text-green-500" />
)}
{hasError && (
<div className="group relative">
<AlertCircle className="h-4 w-4 cursor-help text-destructive" />
<div className="pointer-events-none absolute bottom-full left-1/2 z-10 mb-2 -translate-x-1/2 transform whitespace-nowrap rounded border bg-popover px-2 py-1 text-xs text-popover-foreground opacity-0 shadow-md transition-opacity group-hover:opacity-100">
{hasError}
</div>
</div>
)}
</div>
</div>
</div>
</div>
)
},
)}
</div>
<div className="flex items-center justify-between border-t pt-4 text-xs">
<div className="flex items-center gap-4">
<span className="text-muted-foreground">
Обновлено: {formatLastUpdated(conditions.lastUpdated)}
</span>
</div>
{isOutdated && (
<Badge variant="destructive" className="text-xs">
Устарели
</Badge>
)}
</div>
<div className="flex gap-3 pt-2">
<Button
onClick={handleSave}
className="flex-1"
disabled={
isLoading ||
Object.keys(validationErrors).some(
(key) => validationErrors[key],
)
}
>
{isLoading ? 'Сохранение...' : 'Сохранить'}
</Button>
<Button
variant="outline"
onClick={() => setShowModal(false)}
className="flex-1"
disabled={isLoading}
>
Отмена
</Button>
</div>
</CardContent>
</Card>
</div>
</div>
)}
</>
)
}
interface CalibrationConditionsConfig {
targetCells: any[]
defaultConditions?: CalibrationConditions
}
export const calibrationConditionsDefinition: ElementDefinition<
CalibrationConditionsConfig,
CalibrationConditions
> = {
type: 'calibration-conditions',
label: 'Условия калибровки',
icon: <Thermometer className="h-4 w-4" />,
defaultConfig: {
targetCells: [],
defaultConditions: {
temperature: '20',
humidity: '65',
pressure: '101.3',
voltage: '220',
frequency: '50',
lastUpdated: new Date().toISOString(),
},
},
mapToCells: () => {
// Генерируем ячейки для каждого параметра калибровки
const cells = [
{ sheet: 'L', cell: 'B2', displayName: 'Температура' },
{ sheet: 'L', cell: 'B3', displayName: 'Влажность' },
{ sheet: 'L', cell: 'B4', displayName: 'Давление' },
{ sheet: 'L', cell: 'B5', displayName: 'Напряжение' },
{ sheet: 'L', cell: 'B6', displayName: 'Частота' },
{ sheet: 'L', cell: 'B7', displayName: 'Дата обновления' },
]
return cells
},
Editor: ({ config, onChange }) => (
<div className="space-y-4">
<div className="rounded-lg border border-gray-200 bg-gray-50 p-4">
<p className="text-sm text-gray-600">
Элемент "Условия калибровки" позволяет вводить и отслеживать параметры
окружающей среды при проведении измерений. Поддерживает валидацию
значений и отслеживание времени обновления.
</p>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Параметры по умолчанию</label>
<div className="grid grid-cols-2 gap-4 rounded-lg border border-gray-200 p-4">
<div className="space-y-2">
<label className="text-xs font-medium text-gray-600">
Температура (°C)
</label>
<Input
type="number"
value={config.defaultConditions?.temperature || '20'}
onChange={(e) =>
onChange({
...config,
defaultConditions: {
...config.defaultConditions,
temperature: e.target.value,
humidity: config.defaultConditions?.humidity || '65',
pressure: config.defaultConditions?.pressure || '101.3',
voltage: config.defaultConditions?.voltage || '220',
frequency: config.defaultConditions?.frequency || '50',
lastUpdated:
config.defaultConditions?.lastUpdated ||
new Date().toISOString(),
},
})
}
placeholder="20"
/>
</div>
<div className="space-y-2">
<label className="text-xs font-medium text-gray-600">
Влажность (%)
</label>
<Input
type="number"
value={config.defaultConditions?.humidity || '65'}
onChange={(e) =>
onChange({
...config,
defaultConditions: {
...config.defaultConditions,
temperature: config.defaultConditions?.temperature || '20',
humidity: e.target.value,
pressure: config.defaultConditions?.pressure || '101.3',
voltage: config.defaultConditions?.voltage || '220',
frequency: config.defaultConditions?.frequency || '50',
lastUpdated:
config.defaultConditions?.lastUpdated ||
new Date().toISOString(),
},
})
}
placeholder="65"
/>
</div>
<div className="space-y-2">
<label className="text-xs font-medium text-gray-600">
Давление (кПа)
</label>
<Input
type="number"
value={config.defaultConditions?.pressure || '101.3'}
onChange={(e) =>
onChange({
...config,
defaultConditions: {
...config.defaultConditions,
temperature: config.defaultConditions?.temperature || '20',
humidity: config.defaultConditions?.humidity || '65',
pressure: e.target.value,
voltage: config.defaultConditions?.voltage || '220',
frequency: config.defaultConditions?.frequency || '50',
lastUpdated:
config.defaultConditions?.lastUpdated ||
new Date().toISOString(),
},
})
}
placeholder="101.3"
/>
</div>
<div className="space-y-2">
<label className="text-xs font-medium text-gray-600">
Напряжение (В)
</label>
<Input
type="number"
value={config.defaultConditions?.voltage || '220'}
onChange={(e) =>
onChange({
...config,
defaultConditions: {
...config.defaultConditions,
temperature: config.defaultConditions?.temperature || '20',
humidity: config.defaultConditions?.humidity || '65',
pressure: config.defaultConditions?.pressure || '101.3',
voltage: e.target.value,
frequency: config.defaultConditions?.frequency || '50',
lastUpdated:
config.defaultConditions?.lastUpdated ||
new Date().toISOString(),
},
})
}
placeholder="220"
/>
</div>
<div className="space-y-2">
<label className="text-xs font-medium text-gray-600">
Частота (Гц)
</label>
<Input
type="number"
value={config.defaultConditions?.frequency || '50'}
onChange={(e) =>
onChange({
...config,
defaultConditions: {
...config.defaultConditions,
temperature: config.defaultConditions?.temperature || '20',
humidity: config.defaultConditions?.humidity || '65',
pressure: config.defaultConditions?.pressure || '101.3',
voltage: config.defaultConditions?.voltage || '220',
frequency: e.target.value,
lastUpdated:
config.defaultConditions?.lastUpdated ||
new Date().toISOString(),
},
})
}
placeholder="50"
/>
</div>
</div>
</div>
</div>
),
Preview: ({ config }) => (
<div className="space-y-3">
<div className="text-sm font-medium text-gray-700">Предпросмотр</div>
<div className="rounded-lg border border-gray-200 bg-white p-4">
<CalibrationCondInfo
conditions={
config.defaultConditions || {
temperature: '20',
humidity: '65',
pressure: '101.3',
voltage: '220',
frequency: '50',
lastUpdated: new Date().toISOString(),
}
}
isOutdated={false}
onUpdate={async () => true}
/>
</div>
</div>
),
Render: ({ config, value, onChange }) => {
const conditions = value ||
config.defaultConditions || {
temperature: '20',
humidity: '65',
pressure: '101.3',
voltage: '220',
frequency: '50',
lastUpdated: new Date().toISOString(),
}
// Проверяем, устарели ли условия (больше 24 часов)
const lastUpdated = new Date(conditions.lastUpdated)
const now = new Date()
const isOutdated =
now.getTime() - lastUpdated.getTime() > 24 * 60 * 60 * 1000
return (
<CalibrationCondInfo
conditions={conditions}
isOutdated={isOutdated}
onUpdate={async (newConditions) => {
onChange?.(newConditions)
return true
}}
/>
)
},
}

View File

@@ -1,7 +1,9 @@
export { checkboxDefinition } from "./CheckboxElement"; export { buttonGroupDefinition } from './ButtonGroupElement'
export { dateDefinition } from "./DateElement"; export { calibrationConditionsDefinition } from './CalibrationConditionsElement'
export { numberDefinition } from "./NumberElement"; export { checkboxDefinition } from './CheckboxElement'
export { radioDefinition } from "./RadioElement"; export { dateDefinition } from './DateElement'
export { selectDefinition } from "./SelectElement"; export { numberDefinition } from './NumberElement'
export { textareaDefinition } from "./TextareaElement"; export { radioDefinition } from './RadioElement'
export { textDefinition } from "./TextElement"; export { selectDefinition } from './SelectElement'
export { textareaDefinition } from './TextareaElement'
export { textDefinition } from './TextElement'

View File

@@ -1,35 +1,35 @@
import { Badge } from "@/components/ui/badge"; import { Badge } from '@/components/ui/badge'
import { Button } from "@/components/ui/button"; import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Separator } from "@/components/ui/separator"; import { Separator } from '@/components/ui/separator'
import { Calendar, Check, FileText, Settings, X } from "lucide-react"; import { Calendar, Check, FileText, Settings } from 'lucide-react'
import { useState } from "react"; import { useState } from 'react'
interface MeasurementStandard { interface MeasurementStandard {
id: string; id: string
name: string; name: string
shortName: string; shortName: string
type: string; type: string
registryNumber: string; registryNumber: string
range: string; range: string
accuracy: string; accuracy: string
certificateNumber: string; certificateNumber: string
validUntil: string; validUntil: string
} }
interface StandardsConfig { interface StandardsConfig {
registryId: string; registryId: string
selectedStandards: string[]; selectedStandards: string[]
lastUpdated: string; lastUpdated: string
} }
interface StandardsDialogProps { interface StandardsDialogProps {
isOpen: boolean; isOpen: boolean
onClose: () => void; onClose: () => void
standards: MeasurementStandard[]; standards: MeasurementStandard[]
config: StandardsConfig; config: StandardsConfig
onSave: (config: StandardsConfig) => void; onSave: (config: StandardsConfig) => void
registryNumber: string; registryNumber: string
} }
export function StandardsDialog({ export function StandardsDialog({
@@ -38,129 +38,136 @@ export function StandardsDialog({
standards, standards,
config, config,
onSave, onSave,
registryNumber registryNumber,
}: StandardsDialogProps) { }: StandardsDialogProps) {
const [selectedStandards, setSelectedStandards] = useState<string[]>(config.selectedStandards); const [selectedStandards, setSelectedStandards] = useState<string[]>(
config.selectedStandards,
)
if (!isOpen) return null; if (!isOpen) return null
const toggleStandard = (standardId: string) => { const toggleStandard = (standardId: string) => {
setSelectedStandards(prev => { setSelectedStandards((prev) => {
if (prev.includes(standardId)) { if (prev.includes(standardId)) {
return prev.filter(id => id !== standardId); return prev.filter((id) => id !== standardId)
} else if (prev.length < 7) { } else if (prev.length < 7) {
return [...prev, standardId]; return [...prev, standardId]
} }
return prev; return prev
}); })
}; }
const handleSave = () => { const handleSave = () => {
onSave({ onSave({
...config, ...config,
selectedStandards, selectedStandards,
lastUpdated: new Date().toISOString() lastUpdated: new Date().toISOString(),
}); })
onClose(); onClose()
}; }
const isExpiringSoon = (validUntil: string) => { const isExpiringSoon = (validUntil: string) => {
const expiryDate = new Date(validUntil); const expiryDate = new Date(validUntil)
const now = new Date(); const now = new Date()
const monthsUntilExpiry = (expiryDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24 * 30); const monthsUntilExpiry =
return monthsUntilExpiry <= 3; (expiryDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24 * 30)
}; return monthsUntilExpiry <= 3
}
return ( return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"> <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
<Card className="w-full max-w-4xl max-h-[90vh] overflow-hidden"> <Card className="max-h-[90vh] w-full max-w-4xl overflow-hidden">
<CardHeader className="pb-4"> <CardHeader className="pb-4">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<CardTitle className="text-lg flex items-center gap-2"> <CardTitle className="flex items-center gap-2 text-lg">
<Settings className="w-5 h-5" /> <Settings className="h-5 w-5" />
Измерительные эталоны Измерительные эталоны
</CardTitle> </CardTitle>
<p className="text-sm text-muted-foreground mt-1"> <p className="mt-1 text-sm text-muted-foreground">
ГРСИ: {registryNumber} Выбрано: {selectedStandards.length}/7 ГРСИ: {registryNumber} Выбрано: {selectedStandards.length}/7
</p> </p>
</div> </div>
<Button variant="ghost" size="sm" onClick={onClose}>
<X className="w-4 h-4" />
</Button>
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="space-y-4"> <CardContent className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-96 overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 dark:scrollbar-thumb-gray-600 scrollbar-track-transparent"> <div className="scrollbar-thin scrollbar-thumb-gray-300 dark:scrollbar-thumb-gray-600 scrollbar-track-transparent grid max-h-96 grid-cols-1 gap-3 overflow-y-auto md:grid-cols-2">
{standards.map((standard) => { {standards.map((standard) => {
const isSelected = selectedStandards.includes(standard.id); const isSelected = selectedStandards.includes(standard.id)
const isExpiring = isExpiringSoon(standard.validUntil); const isExpiring = isExpiringSoon(standard.validUntil)
return ( return (
<div <div
key={standard.id} key={standard.id}
onClick={() => toggleStandard(standard.id)} onClick={() => toggleStandard(standard.id)}
className={`p-3 rounded-lg border cursor-pointer transition-all duration-200 ${ className={`cursor-pointer rounded-lg border p-3 transition-all duration-200 ${
isSelected isSelected
? "border-primary bg-primary/10 shadow-sm" ? 'border-primary bg-primary/10 shadow-sm'
: "border-border hover:border-primary/50 hover:bg-primary/5" : 'border-border hover:border-primary/50 hover:bg-primary/5'
}`} }`}
> >
<div className="flex items-start gap-3"> <div className="flex items-start gap-3">
<div className={`mt-1 w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors ${ <div
isSelected className={`mt-1 flex h-5 w-5 items-center justify-center rounded-full border-2 transition-colors ${
? "border-primary bg-primary" isSelected
: "border-border" ? 'border-primary bg-primary'
}`}> : 'border-border'
{isSelected && <Check className="w-3 h-3 text-primary-foreground" />} }`}
>
{isSelected && (
<Check className="h-3 w-3 text-primary-foreground" />
)}
</div> </div>
<div className="flex-1 min-w-0"> <div className="min-w-0 flex-1">
<div className="flex items-start justify-between gap-2"> <div className="flex items-start justify-between gap-2">
<div className="flex-1"> <div className="flex-1">
<div className="font-medium text-sm text-foreground leading-tight"> <div className="text-sm font-medium leading-tight text-foreground">
{standard.shortName} {standard.shortName}
</div> </div>
<div className="text-xs text-muted-foreground mt-1 line-clamp-2"> <div className="mt-1 line-clamp-2 text-xs text-muted-foreground">
{standard.name} {standard.name}
</div> </div>
</div> </div>
<div className="flex flex-col gap-1 shrink-0"> <div className="flex shrink-0 flex-col gap-1">
<Badge variant="secondary" className="text-xs"> <Badge variant="secondary" className="text-xs">
{standard.accuracy} {standard.accuracy}
</Badge> </Badge>
{isExpiring && ( {isExpiring && (
<Badge variant="destructive" className="text-xs"> <Badge variant="destructive" className="text-xs">
<Calendar className="w-3 h-3 mr-1" /> <Calendar className="mr-1 h-3 w-3" />
Истекает Истекает
</Badge> </Badge>
)} )}
</div> </div>
</div> </div>
<div className="mt-2 space-y-1"> <div className="mt-2 space-y-1">
<div className="flex items-center gap-1 text-xs text-muted-foreground"> <div className="flex items-center gap-1 text-xs text-muted-foreground">
<FileText className="w-3 h-3" /> <FileText className="h-3 w-3" />
{standard.registryNumber} {standard.registryNumber}
</div> </div>
<div className="text-xs text-muted-foreground"> <div className="text-xs text-muted-foreground">
Диапазон: {standard.range} Диапазон: {standard.range}
</div> </div>
<div className="text-xs text-muted-foreground"> <div className="text-xs text-muted-foreground">
Действует до: {new Date(standard.validUntil).toLocaleDateString('ru-RU')} Действует до:{' '}
{new Date(standard.validUntil).toLocaleDateString(
'ru-RU',
)}
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
); )
})} })}
</div> </div>
<Separator /> <Separator />
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="text-sm text-muted-foreground"> <div className="text-sm text-muted-foreground">
Максимум 7 эталонов. Выбрано: {selectedStandards.length} Максимум 7 эталонов. Выбрано: {selectedStandards.length}
@@ -169,13 +176,11 @@ export function StandardsDialog({
<Button variant="outline" onClick={onClose}> <Button variant="outline" onClick={onClose}>
Отмена Отмена
</Button> </Button>
<Button onClick={handleSave}> <Button onClick={handleSave}>Сохранить</Button>
Сохранить
</Button>
</div> </div>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
); )
} }

View File

@@ -1,56 +1,57 @@
import { ElementDefinition } from "@/lib/element-registry"; import { ElementDefinition } from '@/lib/element-registry'
import { parseCellAddress } from "@/lib/utils"; import { parseCellAddress } from '@/lib/utils'
import { CellTarget } from "@/types/template"; import { CellTarget } from '@/types/template'
import { Calendar } from "lucide-react"; import { Weight } from 'lucide-react'
import { StandardsEditor } from "./StandardsEditor"; import { StandardsEditor } from './StandardsEditor'
import { StandardsPreview } from "./StandardsPreview"; import { StandardsPreview } from './StandardsPreview'
interface StandardsConfig { interface StandardsConfig {
registryNumber: string; // ГРСИ registryNumber: string // ГРСИ
sheet: string; // Лист Excel sheet: string // Лист Excel
startCell: string; // Первая ячейка (например "A10") startCell: string // Первая ячейка (например "A10")
maxItems: number; // Обычно 7 maxItems: number // Обычно 7
targetCells: CellTarget[]; targetCells: CellTarget[]
} }
export const standardsDefinition: ElementDefinition<StandardsConfig, string[]> = { export const standardsDefinition: ElementDefinition<StandardsConfig, string[]> =
type: "standards", {
label: "Измерительные эталоны", type: 'standards',
icon: <Calendar className="h-4 w-4" />, label: 'Измерительные эталоны',
defaultConfig: { icon: <Weight className="h-4 w-4" />,
registryNumber: "", defaultConfig: {
sheet: "Report", registryNumber: '',
startCell: "A1", sheet: 'Report',
maxItems: 7, startCell: 'A1',
targetCells: [], maxItems: 7,
}, targetCells: [],
Editor: StandardsEditor, },
Preview: StandardsPreview, Editor: StandardsEditor,
Render: () => { Preview: StandardsPreview,
// Здесь нужно создать обертку для StandardsDialog Render: () => {
// Пока возвращаем null, так как StandardsDialog требует дополнительные пропсы // Здесь нужно создать обертку для StandardsDialog
return null; // Пока возвращаем null, так как StandardsDialog требует дополнительные пропсы
}, return null
mapToCells: (cfg) => { },
const res: CellTarget[] = []; mapToCells: (cfg) => {
const parsed = parseCellAddress(cfg.startCell); const res: CellTarget[] = []
const parsed = parseCellAddress(cfg.startCell)
if (!parsed) {
// Если не удалось распарсить, возвращаем пустой массив if (!parsed) {
return res; // Если не удалось распарсить, возвращаем пустой массив
} return res
}
const { column, row } = parsed;
const { column, row } = parsed
// Генерируем ячейки вертикально (A1, A2, A3...)
for (let i = 0; i < cfg.maxItems; i++) { // Генерируем ячейки вертикально (A1, A2, A3...)
res.push({ for (let i = 0; i < cfg.maxItems; i++) {
sheet: cfg.sheet, res.push({
cell: `${column}${row + i}`, sheet: cfg.sheet,
displayName: `Эталон ${i + 1}`, cell: `${column}${row + i}`,
}); displayName: `Эталон ${i + 1}`,
} })
}
return res;
}, return res
}; },
}

View File

@@ -1,4 +1,16 @@
import { Calendar, LayoutGrid, Plus, Settings, Trash2 } from 'lucide-react' import {
Calendar,
Droplets,
Edit3,
Gauge,
LayoutGrid,
Plus,
Radio,
Settings,
Thermometer,
Trash2,
Zap,
} from 'lucide-react'
import React, { useState } from 'react' import React, { useState } from 'react'
import { import {
getAvailableElementTypes, getAvailableElementTypes,
@@ -251,6 +263,61 @@ const ElementPreview: React.FC<{ element: Partial<TemplateElement> }> = ({
</div> </div>
) )
case 'calibration-conditions':
return (
<div className="space-y-2">
<div className="flex items-center gap-3 rounded-lg border bg-muted/50 px-3 py-2">
<div className="flex items-center gap-3 text-xs">
<div className="flex items-center gap-1">
<Thermometer className="h-3 w-3 text-muted-foreground" />
<span className="text-foreground">20°C</span>
</div>
<div className="flex items-center gap-1">
<Droplets className="h-3 w-3 text-muted-foreground" />
<span className="text-foreground">65%</span>
</div>
<div className="flex items-center gap-1">
<Gauge className="h-3 w-3 text-muted-foreground" />
<span className="text-foreground">101.3кПа</span>
</div>
<div className="flex items-center gap-1">
<Zap className="h-3 w-3 text-muted-foreground" />
<span className="text-foreground">220В</span>
</div>
<div className="flex items-center gap-1">
<Radio className="h-3 w-3 text-muted-foreground" />
<span className="text-foreground">50Гц</span>
</div>
</div>
<Button variant="ghost" size="icon" className="h-6 w-6 p-0">
<Edit3 className="h-3 w-3" />
</Button>
</div>
</div>
)
case 'button-group':
return (
<div className="space-y-2">
<div className="flex flex-wrap gap-1.5">
{element.options?.length ? (
element.options.map((option, index) => (
<button
key={index}
className="rounded-md border border-border bg-background px-3 py-1.5 text-sm font-medium text-foreground transition-all duration-200 hover:border-primary/30 hover:bg-primary/5"
>
{option.label || `Кнопка ${index + 1}`}
</button>
))
) : (
<div className="rounded-md border border-dashed bg-muted/30 px-3 py-1.5 text-sm text-muted-foreground">
{element.placeholder || 'Добавьте кнопки'}
</div>
)}
</div>
</div>
)
default: default:
return ( return (
<div className="rounded border border-gray-200 bg-gray-50 p-3 text-center text-sm text-gray-500"> <div className="rounded border border-gray-200 bg-gray-50 p-3 text-center text-sm text-gray-500">
@@ -321,7 +388,10 @@ const ElementForm: React.FC<ElementFormProps> = ({ formData, setFormData }) => {
})) }))
} }
const needsOptions = formData.type === 'select' || formData.type === 'radio' const needsOptions =
formData.type === 'select' ||
formData.type === 'radio' ||
formData.type === 'button-group'
// Если есть определение элемента в реестре, используем его редактор // Если есть определение элемента в реестре, используем его редактор
if (elementDefinition && elementDefinition.Editor) { if (elementDefinition && elementDefinition.Editor) {
@@ -340,12 +410,15 @@ const ElementForm: React.FC<ElementFormProps> = ({ formData, setFormData }) => {
setFormData((prev) => { setFormData((prev) => {
const updates: Partial<TemplateElement> = { type: newType } const updates: Partial<TemplateElement> = { type: newType }
// Если выбран тип "standards", устанавливаем значения по умолчанию // Если выбран тип "standards" или "calibration-conditions", устанавливаем значения по умолчанию
if (newType === 'standards') { if (
newType === 'standards' ||
newType === 'calibration-conditions'
) {
console.log( console.log(
'Standards type selected, getting element definition', `${newType} type selected, getting element definition`,
) )
const elementDefinition = getElementDefinition('standards') const elementDefinition = getElementDefinition(newType)
console.log('Element definition:', elementDefinition) console.log('Element definition:', elementDefinition)
if (elementDefinition && elementDefinition.defaultConfig) { if (elementDefinition && elementDefinition.defaultConfig) {
@@ -444,12 +517,15 @@ const ElementForm: React.FC<ElementFormProps> = ({ formData, setFormData }) => {
setFormData((prev) => { setFormData((prev) => {
const updates: Partial<TemplateElement> = { type: newType } const updates: Partial<TemplateElement> = { type: newType }
// Если выбран тип "standards", устанавливаем значения по умолчанию // Если выбран тип "standards" или "calibration-conditions", устанавливаем значения по умолчанию
if (newType === 'standards') { if (
newType === 'standards' ||
newType === 'calibration-conditions'
) {
console.log( console.log(
'Standards type selected (fallback), getting element definition', `${newType} type selected (fallback), getting element definition`,
) )
const elementDefinition = getElementDefinition('standards') const elementDefinition = getElementDefinition(newType)
console.log( console.log(
'Element definition (fallback):', 'Element definition (fallback):',
elementDefinition, elementDefinition,
@@ -696,10 +772,15 @@ export const ElementConstructor: React.FC<ElementConstructorProps> = ({
return return
} }
// Для элемента типа "standards" не требуем targetCells, так как они генерируются автоматически // Для элементов типа "standards", "calibration-conditions" и "button-group" не требуем targetCells, так как они генерируются автоматически или не нужны
if (formData.type !== 'standards' && !formData.targetCells?.length) { if (
formData.type !== 'standards' &&
formData.type !== 'calibration-conditions' &&
formData.type !== 'button-group' &&
!formData.targetCells?.length
) {
console.log( console.log(
'Validation failed: missing targetCells for non-standards element', 'Validation failed: missing targetCells for element that requires manual targetCells',
) )
return return
} }
@@ -714,12 +795,15 @@ export const ElementConstructor: React.FC<ElementConstructorProps> = ({
layoutSettings.gridSize, layoutSettings.gridSize,
) )
// Специальная обработка для эталонов // Специальная обработка для элементов с автоматической генерацией targetCells
let targetCells = formData.targetCells || [] let targetCells = formData.targetCells || []
if (formData.type === 'standards') { if (
// Для эталонов генерируем targetCells автоматически, если их нет formData.type === 'standards' ||
formData.type === 'calibration-conditions'
) {
// Генерируем targetCells автоматически, если их нет
if (!targetCells.length) { if (!targetCells.length) {
const elementDefinition = getElementDefinition('standards') const elementDefinition = getElementDefinition(formData.type)
if (elementDefinition && elementDefinition.defaultConfig) { if (elementDefinition && elementDefinition.defaultConfig) {
const defaultConfig = elementDefinition.defaultConfig as any const defaultConfig = elementDefinition.defaultConfig as any
targetCells = elementDefinition.mapToCells?.(defaultConfig) || [] targetCells = elementDefinition.mapToCells?.(defaultConfig) || []
@@ -727,6 +811,11 @@ export const ElementConstructor: React.FC<ElementConstructorProps> = ({
} }
} }
// Для button-group не нужны targetCells, так как это UI элемент
if (formData.type === 'button-group') {
targetCells = []
}
const newElement: TemplateElement = { const newElement: TemplateElement = {
id: Date.now().toString(), id: Date.now().toString(),
type: formData.type as ElementType, type: formData.type as ElementType,
@@ -753,8 +842,14 @@ export const ElementConstructor: React.FC<ElementConstructorProps> = ({
const handleUpdateElement = () => { const handleUpdateElement = () => {
if (!editingElement || !formData.name || !formData.label) return if (!editingElement || !formData.name || !formData.label) return
// Для элемента типа "standards" не требуем targetCells, так как они генерируются автоматически // Для элементов типа "standards", "calibration-conditions" и "button-group" не требуем targetCells, так как они генерируются автоматически или не нужны
if (formData.type !== 'standards' && !formData.targetCells?.length) return if (
formData.type !== 'standards' &&
formData.type !== 'calibration-conditions' &&
formData.type !== 'button-group' &&
!formData.targetCells?.length
)
return
onElementUpdate(editingElement.id, formData) onElementUpdate(editingElement.id, formData)
setEditingElement(null) setEditingElement(null)
@@ -828,6 +923,8 @@ export const ElementConstructor: React.FC<ElementConstructorProps> = ({
!formData.name || !formData.name ||
!formData.label || !formData.label ||
(formData.type !== 'standards' && (formData.type !== 'standards' &&
formData.type !== 'calibration-conditions' &&
formData.type !== 'button-group' &&
!formData.targetCells?.length) !formData.targetCells?.length)
} }
> >

View File

@@ -1,37 +1,50 @@
import { import {
Calendar, Calendar,
ChevronDown, ChevronDown,
Edit, Droplets,
Eye, Edit,
EyeOff, Edit3,
Grid, Eye,
Move, EyeOff,
Trash2 Gauge,
} from 'lucide-react'; Grid,
import React, { useCallback, useMemo, useState } from 'react'; Move,
import { Rnd } from 'react-rnd'; Radio,
import { ElementLayout, FormLayoutSettings, TemplateElement } from '../../types/template'; Thermometer,
import { Button } from '../ui/button'; Trash2,
import { Input } from '../ui/input'; Zap,
import { Textarea } from '../ui/textarea'; } from 'lucide-react'
import React, { useCallback, useMemo, useState } from 'react'
import { Rnd } from 'react-rnd'
import {
ElementLayout,
FormLayoutSettings,
TemplateElement,
} from '../../types/template'
import { Button } from '../ui/button'
import { Input } from '../ui/input'
import { Textarea } from '../ui/textarea'
interface VisualLayoutEditorProps { interface VisualLayoutEditorProps {
elements: TemplateElement[]; elements: TemplateElement[]
layoutSettings: FormLayoutSettings; layoutSettings: FormLayoutSettings
onElementUpdate: (elementId: string, updates: Partial<TemplateElement>) => void; onElementUpdate: (
onElementDelete: (elementId: string) => void; elementId: string,
onLayoutSettingsChange: (settings: FormLayoutSettings) => void; updates: Partial<TemplateElement>,
onElementEdit?: (element: TemplateElement) => void; ) => void
onElementDelete: (elementId: string) => void
onLayoutSettingsChange: (settings: FormLayoutSettings) => void
onElementEdit?: (element: TemplateElement) => void
} }
interface DraggableElementProps { interface DraggableElementProps {
element: TemplateElement; element: TemplateElement
isSelected: boolean; isSelected: boolean
onSelect: () => void; onSelect: () => void
onUpdate: (layout: ElementLayout) => void; onUpdate: (layout: ElementLayout) => void
onDelete: () => void; onDelete: () => void
onEdit?: () => void; onEdit?: () => void
gridSize: number; gridSize: number
} }
// const ELEMENT_ICONS: Record<ElementType, React.ReactNode> = { // const ELEMENT_ICONS: Record<ElementType, React.ReactNode> = {
@@ -54,44 +67,61 @@ interface DraggableElementProps {
// checkbox: 'bg-teal-100 border-teal-300 text-teal-800', // checkbox: 'bg-teal-100 border-teal-300 text-teal-800',
// }; // };
const DraggableElement: React.FC<DraggableElementProps> = React.memo(({ const DraggableElement: React.FC<DraggableElementProps> = React.memo(
element, ({ element, isSelected, onSelect, onUpdate, onDelete, onEdit, gridSize }) => {
isSelected, const layout = element.layout || {
onSelect, x: 50,
onUpdate, y: 50,
onDelete, width: 300,
onEdit, height: 80,
gridSize, zIndex: 1,
}) => { }
const layout = element.layout || { x: 50, y: 50, width: 300, height: 80, zIndex: 1 };
const handleDragStop = useCallback((_e: any, d: { x: number; y: number }) => { const handleDragStop = useCallback(
(_e: any, d: { x: number; y: number }) => {
// Вызываем onUpdate только если позиция действительно изменилась, // Вызываем onUpdate только если позиция действительно изменилась,
// чтобы избежать ложных срабатываний при клике. // чтобы избежать ложных срабатываний при клике.
if (d.x !== layout.x || d.y !== layout.y) { if (d.x !== layout.x || d.y !== layout.y) {
onUpdate({ ...layout, x: d.x, y: d.y }); onUpdate({ ...layout, x: d.x, y: d.y })
} }
}, [layout, onUpdate]); },
[layout, onUpdate],
)
const handleResizeStop = useCallback((_e: any, _dir: any, ref: HTMLElement, _delta: any, pos: { x: number; y: number }) => { const handleResizeStop = useCallback(
(
_e: any,
_dir: any,
ref: HTMLElement,
_delta: any,
pos: { x: number; y: number },
) => {
onUpdate({ onUpdate({
...layout, ...layout,
width: parseInt(ref.style.width, 10), width: parseInt(ref.style.width, 10),
height: parseInt(ref.style.height, 10), height: parseInt(ref.style.height, 10),
x: pos.x, x: pos.x,
y: pos.y, y: pos.y,
}); })
}, [layout, onUpdate]); },
[layout, onUpdate],
)
const handleDeleteClick = useCallback((e: React.MouseEvent) => { const handleDeleteClick = useCallback(
e.stopPropagation(); (e: React.MouseEvent) => {
onDelete(); e.stopPropagation()
}, [onDelete]); onDelete()
},
[onDelete],
)
const handleEditClick = useCallback((e: React.MouseEvent) => { const handleEditClick = useCallback(
e.stopPropagation(); (e: React.MouseEvent) => {
onEdit?.(); e.stopPropagation()
}, [onEdit]); onEdit?.()
},
[onEdit],
)
/* /*
* Render a lightweight, disabled preview of the element so that the user can * Render a lightweight, disabled preview of the element so that the user can
@@ -101,256 +131,371 @@ const DraggableElement: React.FC<DraggableElementProps> = React.memo(({
* behaviour of Rnd and keeps rendering costs minimal. * behaviour of Rnd and keeps rendering costs minimal.
*/ */
const previewControl = useMemo(() => { const previewControl = useMemo(() => {
switch (element.type) { switch (element.type) {
case 'text': case 'text':
return <Input readOnly placeholder={element.placeholder || 'Введите текст'} className="pointer-events-none w-full bg-white" />; return (
case 'textarea': <Input
return <Textarea readOnly rows={3} placeholder={element.placeholder || 'Введите текст'} className="pointer-events-none w-full resize-none bg-white" />; readOnly
case 'number': placeholder={element.placeholder || 'Введите текст'}
return <Input type="number" readOnly placeholder={element.placeholder || '0'} className="pointer-events-none w-full bg-white" />; className="pointer-events-none w-full bg-white"
case 'date': />
return <Input type="date" readOnly className="pointer-events-none w-full bg-white" />; )
case 'select': case 'textarea':
return ( return (
<div className="pointer-events-none w-full"> <Textarea
<div className="flex h-10 w-full items-center justify-between rounded-md border border-input bg-white px-3 py-2 text-sm"> readOnly
<span className="text-gray-500"> rows={3}
{element.placeholder || 'Выберите значение'} placeholder={element.placeholder || 'Введите текст'}
</span> className="pointer-events-none w-full resize-none bg-white"
<ChevronDown className="h-4 w-4 opacity-50" /> />
</div> )
</div> case 'number':
); return (
case 'radio': <Input
return ( type="number"
<div className="space-y-2 pointer-events-none"> readOnly
{(element.options?.length ? element.options : [{ label: 'Вариант 1' }]).map((opt, idx) => ( placeholder={element.placeholder || '0'}
<div key={idx} className="flex items-center gap-2"> className="pointer-events-none w-full bg-white"
<div className="w-4 h-4 border-2 border-gray-300 rounded-full bg-white" /> />
<span className="text-sm text-gray-900">{opt.label || `Вариант ${idx + 1}`}</span> )
</div> case 'date':
))} return (
</div> <Input
); type="date"
case 'checkbox': readOnly
return ( className="pointer-events-none w-full bg-white"
<div className="flex items-center gap-2 pointer-events-none"> />
<div className="w-4 h-4 border-2 border-gray-300 rounded bg-white" /> )
<span className="text-sm text-gray-900">{element.placeholder || element.label || 'Отметить'}</span> case 'select':
</div> return (
); <div className="pointer-events-none w-full">
case 'standards': <div className="flex h-10 w-full items-center justify-between rounded-md border border-input bg-white px-3 py-2 text-sm">
return ( <span className="text-gray-500">
<div className="pointer-events-none w-full"> {element.placeholder || 'Выберите значение'}
<div className="flex h-10 w-full items-center justify-between rounded-md border border-input bg-white px-3 py-2 text-sm"> </span>
<span className="text-gray-500"> <ChevronDown className="h-4 w-4 opacity-50" />
{element.placeholder || 'Выберите эталоны'} </div>
</span> </div>
<Calendar className="h-4 w-4 opacity-50" /> )
</div> case 'radio':
</div> return (
); <div className="pointer-events-none space-y-2">
default: {(element.options?.length
return null; ? element.options
} : [{ label: 'Вариант 1' }]
}, [element]); ).map((opt, idx) => (
<div key={idx} className="flex items-center gap-2">
<div className="h-4 w-4 rounded-full border-2 border-gray-300 bg-white" />
<span className="text-sm text-gray-900">
{opt.label || `Вариант ${idx + 1}`}
</span>
</div>
))}
</div>
)
case 'checkbox':
return (
<div className="pointer-events-none flex items-center gap-2">
<div className="h-4 w-4 rounded border-2 border-gray-300 bg-white" />
<span className="text-sm text-gray-900">
{element.placeholder || element.label || 'Отметить'}
</span>
</div>
)
case 'standards':
return (
<div className="pointer-events-none w-full">
<div className="flex h-10 w-full items-center justify-between rounded-md border border-input bg-white px-3 py-2 text-sm">
<span className="text-gray-500">
{element.placeholder || 'Выберите эталоны'}
</span>
<Calendar className="h-4 w-4 opacity-50" />
</div>
</div>
)
case 'calibration-conditions':
return (
<div className="pointer-events-none w-full">
<div className="flex items-center gap-3 rounded-lg border bg-muted/50 px-3 py-2">
<div className="flex items-center gap-3 text-xs">
<div className="flex items-center gap-1">
<Thermometer className="h-3 w-3 text-muted-foreground" />
<span className="text-foreground">20°C</span>
</div>
<div className="flex items-center gap-1">
<Droplets className="h-3 w-3 text-muted-foreground" />
<span className="text-foreground">65%</span>
</div>
<div className="flex items-center gap-1">
<Gauge className="h-3 w-3 text-muted-foreground" />
<span className="text-foreground">101.3кПа</span>
</div>
<div className="flex items-center gap-1">
<Zap className="h-3 w-3 text-muted-foreground" />
<span className="text-foreground">220В</span>
</div>
<div className="flex items-center gap-1">
<Radio className="h-3 w-3 text-muted-foreground" />
<span className="text-foreground">50Гц</span>
</div>
</div>
<Button variant="ghost" size="icon" className="h-6 w-6 p-0">
<Edit3 className="h-3 w-3" />
</Button>
</div>
</div>
)
case 'button-group':
return (
<div className="pointer-events-none w-full">
<div className="flex flex-wrap gap-1.5">
{(element.options?.length
? element.options
: [{ label: 'Кнопка 1' }, { label: 'Кнопка 2' }]
).map((opt, idx) => (
<button
key={idx}
className="rounded-md border border-border bg-background px-3 py-1.5 text-sm font-medium text-foreground transition-all duration-200"
>
{opt.label || `Кнопка ${idx + 1}`}
</button>
))}
</div>
</div>
)
default:
return null
}
}, [element])
return ( return (
<Rnd <Rnd
dragGrid={[gridSize, gridSize]} dragGrid={[gridSize, gridSize]}
resizeGrid={[gridSize, gridSize]} resizeGrid={[gridSize, gridSize]}
default={{ default={{
x: layout.x, x: layout.x,
y: layout.y, y: layout.y,
width: layout.width, width: layout.width,
height: layout.height, height: layout.height,
}} }}
onDragStop={handleDragStop} onDragStop={handleDragStop}
onResizeStop={handleResizeStop} onResizeStop={handleResizeStop}
minWidth={120} minWidth={120}
minHeight={32} minHeight={32}
bounds="parent" bounds="parent"
className={`group ${isSelected ? 'ring-2 ring-blue-500 ring-offset-2 z-20' : 'z-10'}`} className={`group ${
onClick={onSelect} isSelected ? 'z-20 ring-2 ring-blue-500 ring-offset-2' : 'z-10'
}`}
onClick={onSelect}
>
<div
className={`h-full cursor-move ${
isSelected
? 'rounded-md border border-blue-200/50 bg-blue-50/20 p-2'
: 'rounded-md border border-transparent bg-transparent p-1 hover:bg-gray-50/10'
}`}
> >
<div className={`h-full cursor-move ${ {/* Label and controls (only visible when selected or hovered) */}
isSelected <div
? 'bg-blue-50/20 border border-blue-200/50 rounded-md p-2' className={`mb-1 flex items-center justify-between ${
: 'bg-transparent border border-transparent rounded-md hover:bg-gray-50/10 p-1' isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-60'
}`}> }`}
{/* Label and controls (only visible when selected or hovered) */} >
<div className={`flex items-center justify-between mb-1 ${ <div className="flex items-start gap-2">
isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-60' <div className="flex items-center gap-1">
}`}> <span className="truncate text-xs font-medium text-gray-600">
<div className="flex items-start gap-2"> {element.label || element.name || `${element.type} элемент`}
<div className="flex items-center gap-1"> </span>
<span className="font-medium text-xs text-gray-600 truncate"> {element.required && (
{element.label || element.name || `${element.type} элемент`} <span className="-mt-1.5 inline-block h-1 w-1 rounded-full bg-red-500" />
</span>
{element.required && <span className="inline-block w-1 h-1 bg-red-500 rounded-full -mt-1.5" />}
</div>
</div>
<div className="flex items-center gap-1">
{/* Индикатор ячеек */}
{element.targetCells && element.targetCells.length > 0 && (
<div className="relative group/cells">
<Grid className="w-3 h-3 text-gray-500 opacity-60 hover:opacity-100 cursor-help transition-opacity" />
<div className="absolute top-full right-0 mt-2 p-2 bg-gray-900 text-white text-xs rounded shadow-lg opacity-0 group-hover/cells:opacity-100 transition-opacity pointer-events-none whitespace-nowrap z-50">
<div className="font-medium mb-1">Целевые ячейки:</div>
{element.targetCells.map((cell, i) => (
<div key={i} className="font-mono">
{cell.sheet}!{cell.cell}
{cell.displayName && <span className="text-gray-300 ml-1">({cell.displayName})</span>}
</div>
))}
</div>
</div>
)}
{onEdit && (
<Button
variant="ghost"
size="icon"
className="h-4 w-4 cursor-pointer hover:bg-blue-100"
onClick={handleEditClick}
>
<Edit className="h-2.5 w-2.5 text-blue-600" />
</Button>
)}
<Button
variant="ghost"
size="icon"
className="h-4 w-4 cursor-pointer hover:bg-red-100"
onClick={handleDeleteClick}
>
<Trash2 className="h-2.5 w-2.5 text-red-600" />
</Button>
</div>
</div>
{/* Real element preview */}
{previewControl && (
<div className="space-y-1 flex-1">
{element.label && (
<label className="block text-sm font-medium text-gray-900 pointer-events-none">
{element.label}
</label>
)}
{previewControl}
</div>
)}
{/* Additional info (only visible on selection to preserve visual clarity & perf) */}
{isSelected && (
<div className="text-xs opacity-75 space-y-1 mt-1">
{/* Здесь можно добавить дополнительную информацию при необходимости */}
</div>
)} )}
</div>
</div> </div>
</Rnd> <div className="flex items-center gap-1">
); {/* Индикатор ячеек */}
}); {element.targetCells && element.targetCells.length > 0 && (
<div className="group/cells relative">
<Grid className="h-3 w-3 cursor-help text-gray-500 opacity-60 transition-opacity hover:opacity-100" />
<div className="pointer-events-none absolute right-0 top-full z-50 mt-2 whitespace-nowrap rounded bg-gray-900 p-2 text-xs text-white opacity-0 shadow-lg transition-opacity group-hover/cells:opacity-100">
<div className="mb-1 font-medium">Целевые ячейки:</div>
{element.targetCells.map((cell, i) => (
<div key={i} className="font-mono">
{cell.sheet}!{cell.cell}
{cell.displayName && (
<span className="ml-1 text-gray-300">
({cell.displayName})
</span>
)}
</div>
))}
</div>
</div>
)}
{onEdit && (
<Button
variant="ghost"
size="icon"
className="h-4 w-4 cursor-pointer hover:bg-blue-100"
onClick={handleEditClick}
>
<Edit className="h-2.5 w-2.5 text-blue-600" />
</Button>
)}
<Button
variant="ghost"
size="icon"
className="h-4 w-4 cursor-pointer hover:bg-red-100"
onClick={handleDeleteClick}
>
<Trash2 className="h-2.5 w-2.5 text-red-600" />
</Button>
</div>
</div>
{/* Real element preview */}
{previewControl && (
<div className="flex-1 space-y-1">
{element.label && (
<label className="pointer-events-none block text-sm font-medium text-gray-900">
{element.label}
</label>
)}
{previewControl}
</div>
)}
{/* Additional info (only visible on selection to preserve visual clarity & perf) */}
{isSelected && (
<div className="mt-1 space-y-1 text-xs opacity-75">
{/* Здесь можно добавить дополнительную информацию при необходимости */}
</div>
)}
</div>
</Rnd>
)
},
)
export const VisualLayoutEditor: React.FC<VisualLayoutEditorProps> = ({ export const VisualLayoutEditor: React.FC<VisualLayoutEditorProps> = ({
elements, elements,
layoutSettings, layoutSettings,
onElementUpdate, onElementUpdate,
onElementDelete, onElementDelete,
onLayoutSettingsChange, onLayoutSettingsChange,
onElementEdit, onElementEdit,
}) => { }) => {
console.log('VisualLayoutEditor render with elements:', elements); console.log('VisualLayoutEditor render with elements:', elements)
const [selectedElementId, setSelectedElementId] = useState<string | null>(null); const [selectedElementId, setSelectedElementId] = useState<string | null>(
null,
)
const canvasSize = useMemo(() => { const canvasSize = useMemo(() => {
const PADDING_Y = 200; const PADDING_Y = 200
const baseWidth = 1200; const baseWidth = 1200
const baseHeight = 800; const baseHeight = 800
if (elements.length === 0) { if (elements.length === 0) {
return { width: baseWidth, height: baseHeight }; return { width: baseWidth, height: baseHeight }
} }
const contentHeight = Math.max( const contentHeight = Math.max(
0, 0,
...elements.map((el) => (el.layout?.y || 0) + (el.layout?.height || 0)), ...elements.map((el) => (el.layout?.y || 0) + (el.layout?.height || 0)),
); )
return { return {
width: baseWidth, width: baseWidth,
height: Math.max(baseHeight, contentHeight + PADDING_Y), height: Math.max(baseHeight, contentHeight + PADDING_Y),
}; }
}, [elements]); }, [elements])
const GridPattern = useMemo(() => { const GridPattern = useMemo(() => {
if (!layoutSettings.showGrid) return null; if (!layoutSettings.showGrid) return null
const gridSize = layoutSettings.gridSize; const gridSize = layoutSettings.gridSize
return (
<div
className="absolute inset-0 pointer-events-none"
style={{
backgroundImage: `radial-gradient(circle, #e5e7eb 1px, transparent 1px)`,
backgroundSize: `${gridSize}px ${gridSize}px`,
}}
/>
);
}, [layoutSettings.showGrid, layoutSettings.gridSize]);
const handleElementUpdateCallback = useCallback((elementId: string, layout: ElementLayout) => {
onElementUpdate(elementId, { layout });
}, [onElementUpdate]);
const handleCanvasClick = useCallback((e: React.MouseEvent) => {
// Снимаем выделение при клике по пустому месту
if (e.target === e.currentTarget) {
setSelectedElementId(null);
}
}, []);
const toggleGrid = useCallback(() => {
onLayoutSettingsChange({ ...layoutSettings, showGrid: !layoutSettings.showGrid });
}, [layoutSettings, onLayoutSettingsChange]);
return ( return (
<div className="flex flex-col h-full bg-gray-50"> <div
<div className="flex items-center justify-between p-2 bg-white border-b shrink-0"> className="pointer-events-none absolute inset-0"
<span className="text-sm text-gray-600 px-2">{elements.length} элементов на холсте</span> style={{
<Button variant="outline" size="sm" onClick={toggleGrid}> backgroundImage: `radial-gradient(circle, #e5e7eb 1px, transparent 1px)`,
{layoutSettings.showGrid ? <EyeOff className="h-4 w-4 mr-2" /> : <Eye className="h-4 w-4 mr-2" />} backgroundSize: `${gridSize}px ${gridSize}px`,
{layoutSettings.showGrid ? 'Скрыть сетку' : 'Показать сетку'} }}
</Button> />
</div> )
}, [layoutSettings.showGrid, layoutSettings.gridSize])
<div className="flex-1 relative overflow-auto" onClick={handleCanvasClick}> const handleElementUpdateCallback = useCallback(
<div (elementId: string, layout: ElementLayout) => {
className="relative bg-white shadow-lg mx-auto my-8" onElementUpdate(elementId, { layout })
style={{ width: canvasSize.width, height: canvasSize.height }} },
onClick={handleCanvasClick} [onElementUpdate],
> )
{GridPattern}
{elements.map((element) => ( const handleCanvasClick = useCallback((e: React.MouseEvent) => {
<DraggableElement // Снимаем выделение при клике по пустому месту
key={element.id} if (e.target === e.currentTarget) {
element={element} setSelectedElementId(null)
isSelected={selectedElementId === element.id} }
onSelect={() => setSelectedElementId(element.id)} }, [])
onUpdate={(layout) => handleElementUpdateCallback(element.id, layout)}
onDelete={() => onElementDelete(element.id)} const toggleGrid = useCallback(() => {
onEdit={onElementEdit ? () => onElementEdit(element) : undefined} onLayoutSettingsChange({
gridSize={layoutSettings.gridSize} ...layoutSettings,
/> showGrid: !layoutSettings.showGrid,
))} })
{elements.length === 0 && ( }, [layoutSettings, onLayoutSettingsChange])
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<div className="text-center text-gray-400"> return (
<Move className="h-16 w-16 mx-auto mb-4" /> <div className="flex h-full flex-col bg-gray-50">
<p className="text-xl font-medium mb-2">Холст пуст</p> <div className="flex shrink-0 items-center justify-between border-b bg-white p-2">
<p className="text-sm">Добавьте свой первый элемент</p> <span className="px-2 text-sm text-gray-600">
</div> {elements.length} элементов на холсте
</div> </span>
)} <Button variant="outline" size="sm" onClick={toggleGrid}>
</div> {layoutSettings.showGrid ? (
<EyeOff className="mr-2 h-4 w-4" />
) : (
<Eye className="mr-2 h-4 w-4" />
)}
{layoutSettings.showGrid ? 'Скрыть сетку' : 'Показать сетку'}
</Button>
</div>
<div
className="relative flex-1 overflow-auto"
onClick={handleCanvasClick}
>
<div
className="relative mx-auto my-8 bg-white shadow-lg"
style={{ width: canvasSize.width, height: canvasSize.height }}
onClick={handleCanvasClick}
>
{GridPattern}
{elements.map((element) => (
<DraggableElement
key={element.id}
element={element}
isSelected={selectedElementId === element.id}
onSelect={() => setSelectedElementId(element.id)}
onUpdate={(layout) =>
handleElementUpdateCallback(element.id, layout)
}
onDelete={() => onElementDelete(element.id)}
onEdit={onElementEdit ? () => onElementEdit(element) : undefined}
gridSize={layoutSettings.gridSize}
/>
))}
{elements.length === 0 && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="text-center text-gray-400">
<Move className="mx-auto mb-4 h-16 w-16" />
<p className="mb-2 text-xl font-medium">Холст пуст</p>
<p className="text-sm">Добавьте свой первый элемент</p>
</div>
</div> </div>
)}
</div> </div>
); </div>
}; </div>
)
}

View File

@@ -1,26 +1,30 @@
import { import {
checkboxDefinition, buttonGroupDefinition,
dateDefinition, calibrationConditionsDefinition,
numberDefinition, checkboxDefinition,
radioDefinition, dateDefinition,
selectDefinition, numberDefinition,
textareaDefinition, radioDefinition,
textDefinition selectDefinition,
} from "@/components/BasicElements"; textareaDefinition,
import { standardsDefinition } from "@/components/StandardsElement/definition"; textDefinition,
import { registerElement } from "./element-registry"; } from '@/components/BasicElements'
import { standardsDefinition } from '@/components/StandardsElement/definition'
import { registerElement } from './element-registry'
// Регистрация всех элементов // Регистрация всех элементов
export function initializeElementRegistry() { export function initializeElementRegistry() {
// Базовые элементы // Базовые элементы
registerElement("text", textDefinition); registerElement('text', textDefinition)
registerElement("select", selectDefinition); registerElement('select', selectDefinition)
registerElement("number", numberDefinition); registerElement('number', numberDefinition)
registerElement("date", dateDefinition); registerElement('date', dateDefinition)
registerElement("textarea", textareaDefinition); registerElement('textarea', textareaDefinition)
registerElement("checkbox", checkboxDefinition); registerElement('checkbox', checkboxDefinition)
registerElement("radio", radioDefinition); registerElement('radio', radioDefinition)
registerElement('button-group', buttonGroupDefinition)
registerElement('calibration-conditions', calibrationConditionsDefinition)
// Специальные элементы // Специальные элементы
registerElement("standards", standardsDefinition); registerElement('standards', standardsDefinition)
} }

View File

@@ -1,109 +1,134 @@
import { ArrowLeft, Download, FileText, Grid, Plus, Save, Settings, Wrench } from 'lucide-react'; import {
import { FC, useMemo, useState } from 'react'; ArrowLeft,
import { useNavigate } from 'react-router-dom'; Download,
import { StandardsSelector } from '../../../../components/StandardsElement/StandardsSelector'; FileText,
import { Badge } from '../../../../components/ui/badge'; Grid,
import { Button } from '../../../../components/ui/button'; Plus,
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../../../components/ui/card'; Save,
import { Checkbox } from '../../../../components/ui/checkbox'; Settings,
import { Input } from '../../../../components/ui/input'; Wrench,
import { Label } from '../../../../components/ui/label'; } from 'lucide-react'
import { RadioGroup, RadioGroupItem } from '../../../../components/ui/radio-group'; import { FC, useMemo, useState } from 'react'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../../../../components/ui/select'; import { useNavigate } from 'react-router-dom'
import { Textarea } from '../../../../components/ui/textarea'; import { StandardsSelector } from '../../../../components/StandardsElement/StandardsSelector'
import { useTemplateContext } from '../../../../contexts/TemplateContext'; import { Badge } from '../../../../components/ui/badge'
import { Template, TemplateElement } from '../../../../types/template'; 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 { Label } from '../../../../components/ui/label'
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 { getElementDefinition } from '../../../../lib/element-registry'
import { Template, TemplateElement } from '../../../../types/template'
// Моковые данные для эталонов (такие же как в StandardsSelector) // Моковые данные для эталонов (такие же как в StandardsSelector)
const mockStandards = [ const mockStandards = [
{ {
id: "1", id: '1',
name: "Эталон массы 1 кг", name: 'Эталон массы 1 кг',
shortName: "ЭМ-1кг", shortName: 'ЭМ-1кг',
type: "Масса", type: 'Масса',
registryNumber: "ГРСИ 12345-01", registryNumber: 'ГРСИ 12345-01',
range: "0.5-2 кг", range: '0.5-2 кг',
accuracy: "±0.001 г", accuracy: '±0.001 г',
certificateNumber: "СИ-2024-001", certificateNumber: 'СИ-2024-001',
validUntil: "2025-12-31", validUntil: '2025-12-31',
}, },
{ {
id: "2", id: '2',
name: "Эталон длины 1 м", name: 'Эталон длины 1 м',
shortName: "ЭД-1м", shortName: 'ЭД-1м',
type: "Длина", type: 'Длина',
registryNumber: "ГРСИ 12345-02", registryNumber: 'ГРСИ 12345-02',
range: "0.5-2 м", range: '0.5-2 м',
accuracy: "±0.001 мм", accuracy: '±0.001 мм',
certificateNumber: "СИ-2024-002", certificateNumber: 'СИ-2024-002',
validUntil: "2025-06-30", validUntil: '2025-06-30',
}, },
{ {
id: "3", id: '3',
name: "Эталон температуры 20°C", name: 'Эталон температуры 20°C',
shortName: "ЭТ-20°C", shortName: 'ЭТ-20°C',
type: "Температура", type: 'Температура',
registryNumber: "ГРСИ 12345-03", registryNumber: 'ГРСИ 12345-03',
range: "15-25°C", range: '15-25°C',
accuracy: "±0.01°C", accuracy: '±0.01°C',
certificateNumber: "СИ-2024-003", certificateNumber: 'СИ-2024-003',
validUntil: "2025-03-15", validUntil: '2025-03-15',
}, },
{ {
id: "4", id: '4',
name: "Эталон давления 1 Па", name: 'Эталон давления 1 Па',
shortName: "ЭД-1Па", shortName: 'ЭД-1Па',
type: "Давление", type: 'Давление',
registryNumber: "ГРСИ 12345-04", registryNumber: 'ГРСИ 12345-04',
range: "0.5-2 Па", range: '0.5-2 Па',
accuracy: "±0.001 Па", accuracy: '±0.001 Па',
certificateNumber: "СИ-2024-004", certificateNumber: 'СИ-2024-004',
validUntil: "2025-09-20", validUntil: '2025-09-20',
}, },
{ {
id: "5", id: '5',
name: "Эталон времени 1 с", name: 'Эталон времени 1 с',
shortName: "ЭВ-1с", shortName: 'ЭВ-1с',
type: "Время", type: 'Время',
registryNumber: "ГРСИ 12345-05", registryNumber: 'ГРСИ 12345-05',
range: "0.5-2 с", range: '0.5-2 с',
accuracy: "±0.000001 с", accuracy: '±0.000001 с',
certificateNumber: "СИ-2024-005", certificateNumber: 'СИ-2024-005',
validUntil: "2025-12-01", validUntil: '2025-12-01',
}, },
]; ]
// Функция для получения данных эталона по ID // Функция для получения данных эталона по ID
const getStandardById = (id: string) => { const getStandardById = (id: string) => {
return mockStandards.find(standard => standard.id === id); return mockStandards.find((standard) => standard.id === id)
}; }
// Функция для получения типа эталона в сокращенном виде // Функция для получения типа эталона в сокращенном виде
const getStandardTypeBadge = (type: string) => { const getStandardTypeBadge = (type: string) => {
switch (type) { switch (type) {
case "Манометр грузопоршневой": case 'Манометр грузопоршневой':
return "МГП"; return 'МГП'
case "Калибратор давления": case 'Калибратор давления':
return "КД"; return 'КД'
default: default:
return "МО"; return 'МО'
} }
}; }
interface ProtocolFormProps { interface ProtocolFormProps {
template: Template; template: Template
onSave: (data: Record<string, any>) => void; onSave: (data: Record<string, any>) => void
onBack: () => void; onBack: () => void
} }
interface FormElementProps { interface FormElementProps {
element: TemplateElement; element: TemplateElement
value: any; value: any
onChange: (value: any) => void; onChange: (value: any) => void
} }
const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => { const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
const [isStandardsDialogOpen, setIsStandardsDialogOpen] = useState(false); const [isStandardsDialogOpen, setIsStandardsDialogOpen] = useState(false)
const renderInput = () => { const renderInput = () => {
switch (element.type) { switch (element.type) {
@@ -115,8 +140,8 @@ const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
onChange={(e) => onChange(e.target.value)} onChange={(e) => onChange(e.target.value)}
required={element.required} required={element.required}
/> />
); )
case 'textarea': case 'textarea':
return ( return (
<Textarea <Textarea
@@ -126,19 +151,21 @@ const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
required={element.required} required={element.required}
rows={3} rows={3}
/> />
); )
case 'number': case 'number':
return ( return (
<Input <Input
type="number" type="number"
placeholder={element.placeholder} placeholder={element.placeholder}
value={value || ''} value={value || ''}
onChange={(e) => onChange(e.target.value ? parseFloat(e.target.value) : '')} onChange={(e) =>
onChange(e.target.value ? parseFloat(e.target.value) : '')
}
required={element.required} required={element.required}
/> />
); )
case 'date': case 'date':
return ( return (
<Input <Input
@@ -147,13 +174,15 @@ const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
onChange={(e) => onChange(e.target.value)} onChange={(e) => onChange(e.target.value)}
required={element.required} required={element.required}
/> />
); )
case 'select': case 'select':
return ( return (
<Select value={value || ''} onValueChange={onChange}> <Select value={value || ''} onValueChange={onChange}>
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder={element.placeholder || 'Выберите значение'} /> <SelectValue
placeholder={element.placeholder || 'Выберите значение'}
/>
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{element.options?.map((option) => ( {element.options?.map((option) => (
@@ -163,22 +192,28 @@ const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
))} ))}
</SelectContent> </SelectContent>
</Select> </Select>
); )
case 'radio': case 'radio':
return ( return (
<RadioGroup value={value || ''} onValueChange={onChange}> <RadioGroup value={value || ''} onValueChange={onChange}>
{element.options?.map((option) => ( {element.options?.map((option) => (
<div key={option.value} className="flex items-center space-x-2"> <div key={option.value} className="flex items-center space-x-2">
<RadioGroupItem value={option.value} id={`${element.id}-${option.value}`} /> <RadioGroupItem
<label htmlFor={`${element.id}-${option.value}`} className="text-sm font-medium"> value={option.value}
id={`${element.id}-${option.value}`}
/>
<label
htmlFor={`${element.id}-${option.value}`}
className="text-sm font-medium"
>
{option.label} {option.label}
</label> </label>
</div> </div>
))} ))}
</RadioGroup> </RadioGroup>
); )
case 'checkbox': case 'checkbox':
return ( return (
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2">
@@ -191,19 +226,19 @@ const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
{element.placeholder || 'Отметить'} {element.placeholder || 'Отметить'}
</label> </label>
</div> </div>
); )
case 'standards': case 'standards':
const selectedStandards = Array.isArray(value) ? value : []; const selectedStandards = Array.isArray(value) ? value : []
const selectedStandardsData = selectedStandards const selectedStandardsData = selectedStandards
.map(id => getStandardById(id)) .map((id) => getStandardById(id))
.filter(Boolean); .filter(Boolean)
return ( return (
<div className="space-y-2"> <div className="space-y-2">
{/* Блок с измерительными эталонами */} {/* Блок с измерительными эталонами */}
<div> <div>
<div className="flex items-center justify-between mb-2"> <div className="mb-2 flex items-center justify-between">
<Label className="text-sm font-medium">Эталоны</Label> <Label className="text-sm font-medium">Эталоны</Label>
<Button <Button
variant="outline" variant="outline"
@@ -211,62 +246,98 @@ const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
onClick={() => setIsStandardsDialogOpen(true)} onClick={() => setIsStandardsDialogOpen(true)}
className="h-7 px-2" className="h-7 px-2"
> >
<Settings className="w-3 h-3 mr-1" /> <Settings className="mr-1 h-3 w-3" />
Настроить Настроить
</Button> </Button>
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
{selectedStandardsData.length > 0 ? ( {selectedStandardsData.length > 0 ? (
<div className="space-y-1.5"> <div className="space-y-1.5">
{selectedStandardsData.map((standard, index) => ( {selectedStandardsData.map(
standard && ( (standard, index) =>
<div standard && (
key={standard.id} <div
className="flex items-center gap-2 p-2 bg-muted/30 rounded-md text-sm" key={standard.id}
> className="flex items-center gap-2 rounded-md bg-muted/30 p-2 text-sm"
<div className="w-5 h-5 rounded-full bg-primary/10 flex items-center justify-center shrink-0"> >
<span className="text-xs font-medium text-primary">{index + 1}</span> <div className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary/10">
</div> <span className="text-xs font-medium text-primary">
<div className="flex-1 min-w-0"> {index + 1}
<div className="font-medium text-xs text-foreground truncate"> </span>
{standard.shortName}
</div> </div>
<div className="text-xs text-muted-foreground"> <div className="min-w-0 flex-1">
{standard.accuracy} {standard.range} <div className="truncate text-xs font-medium text-foreground">
{standard.shortName}
</div>
<div className="text-xs text-muted-foreground">
{standard.accuracy} {standard.range}
</div>
</div> </div>
<Badge
variant="secondary"
className="shrink-0 text-xs"
>
<Wrench className="mr-1 h-3 w-3" />
{getStandardTypeBadge(standard.type)}
</Badge>
</div> </div>
<Badge variant="secondary" className="text-xs shrink-0"> ),
<Wrench className="w-3 h-3 mr-1" /> )}
{getStandardTypeBadge(standard.type)}
</Badge>
</div>
)
))}
</div> </div>
) : ( ) : (
<div className="text-sm text-muted-foreground bg-muted/30 rounded-md p-3 border border-dashed text-center"> <div className="rounded-md border border-dashed bg-muted/30 p-3 text-center text-sm text-muted-foreground">
<Settings className="w-4 h-4 mx-auto mb-1 opacity-50" /> <Settings className="mx-auto mb-1 h-4 w-4 opacity-50" />
Эталоны не выбраны Эталоны не выбраны
</div> </div>
)} )}
</div> </div>
</div> </div>
<StandardsSelector <StandardsSelector
isOpen={isStandardsDialogOpen} isOpen={isStandardsDialogOpen}
onClose={() => setIsStandardsDialogOpen(false)} onClose={() => setIsStandardsDialogOpen(false)}
value={selectedStandards} value={selectedStandards}
onChange={onChange} onChange={onChange}
registryNumber={element.targetCells?.[0]?.displayName || "ГРСИ 12345"} registryNumber={
element.targetCells?.[0]?.displayName || 'ГРСИ 12345'
}
/> />
</div> </div>
); )
case 'calibration-conditions':
// Используем определение элемента из реестра для рендеринга
const elementDefinition = getElementDefinition('calibration-conditions')
if (elementDefinition && elementDefinition.Render) {
return (
<elementDefinition.Render
config={element as any}
value={value}
onChange={onChange}
/>
)
}
return null
case 'button-group':
// Используем определение элемента из реестра для рендеринга
const buttonGroupDefinition = getElementDefinition('button-group')
if (buttonGroupDefinition && buttonGroupDefinition.Render) {
return (
<buttonGroupDefinition.Render
config={element as any}
value={value}
onChange={onChange}
/>
)
}
return null
default: default:
return null; return null
} }
}; }
return ( return (
<div className="space-y-3"> <div className="space-y-3">
@@ -275,18 +346,24 @@ const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
<label className="text-sm font-medium text-gray-900"> <label className="text-sm font-medium text-gray-900">
{element.label} {element.label}
</label> </label>
{element.required && <span className="inline-block w-1 h-1 bg-red-500 rounded-full -mt-1.5" />} {element.required && (
<span className="-mt-1.5 inline-block h-1 w-1 rounded-full bg-red-500" />
)}
</div> </div>
{/* Индикатор ячеек */} {/* Индикатор ячеек */}
{element.targetCells && element.targetCells.length > 0 && ( {element.targetCells && element.targetCells.length > 0 && (
<div className="relative group/cells"> <div className="group/cells relative">
<Grid className="w-3 h-3 text-gray-500 opacity-60 hover:opacity-100 cursor-help transition-opacity" /> <Grid className="h-3 w-3 cursor-help text-gray-500 opacity-60 transition-opacity hover:opacity-100" />
<div className="absolute top-full right-0 mt-2 p-2 bg-gray-900 text-white text-xs rounded shadow-lg opacity-0 group-hover/cells:opacity-100 transition-opacity pointer-events-none whitespace-nowrap z-50"> <div className="pointer-events-none absolute right-0 top-full z-50 mt-2 whitespace-nowrap rounded bg-gray-900 p-2 text-xs text-white opacity-0 shadow-lg transition-opacity group-hover/cells:opacity-100">
<div className="font-medium mb-1">Целевые ячейки:</div> <div className="mb-1 font-medium">Целевые ячейки:</div>
{element.targetCells.map((cell, i) => ( {element.targetCells.map((cell, i) => (
<div key={i} className="font-mono"> <div key={i} className="font-mono">
{cell.sheet}!{cell.cell} {cell.sheet}!{cell.cell}
{cell.displayName && <span className="text-gray-300 ml-1">({cell.displayName})</span>} {cell.displayName && (
<span className="ml-1 text-gray-300">
({cell.displayName})
</span>
)}
</div> </div>
))} ))}
</div> </div>
@@ -295,74 +372,80 @@ const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
</div> </div>
{renderInput()} {renderInput()}
</div> </div>
); )
}; }
const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => { const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
const [formData, setFormData] = useState<Record<string, any>>({}); const [formData, setFormData] = useState<Record<string, any>>({})
const handleFieldChange = (elementId: string, value: any) => { const handleFieldChange = (elementId: string, value: any) => {
setFormData(prev => ({ setFormData((prev) => ({
...prev, ...prev,
[elementId]: value [elementId]: value,
})); }))
}; }
const handleSave = () => { const handleSave = () => {
// Ищем элемент с названием протокола (должен иметь специальный тип или название) // Ищем элемент с названием протокола (должен иметь специальный тип или название)
const protocolNameElement = template.elements.find(el => const protocolNameElement = template.elements.find(
el.name === 'protocolName' || el.label === 'Название протокола' (el) => el.name === 'protocolName' || el.label === 'Название протокола',
); )
const protocolName = protocolNameElement ? formData[protocolNameElement.id] : 'Новый протокол'; const protocolName = protocolNameElement
? formData[protocolNameElement.id]
: 'Новый протокол'
const data = { const data = {
protocolName, protocolName,
templateId: template.id, templateId: template.id,
formData, formData,
createdAt: new Date(), createdAt: new Date(),
}; }
onSave(data); onSave(data)
}; }
const handleExport = () => { const handleExport = () => {
console.log('Экспорт в Excel:', { formData }); console.log('Экспорт в Excel:', { formData })
alert('Функция экспорта будет реализована в следующих версиях'); alert('Функция экспорта будет реализована в следующих версиях')
}; }
const canvasSize = useMemo(() => { const canvasSize = useMemo(() => {
const PADDING_Y = 200; const PADDING_Y = 200
const baseWidth = 1200; const baseWidth = 1200
const baseHeight = 800; const baseHeight = 800
if (template.elements.length === 0) { if (template.elements.length === 0) {
return { width: baseWidth, height: baseHeight }; return { width: baseWidth, height: baseHeight }
} }
const contentHeight = Math.max( const contentHeight = Math.max(
0, 0,
...template.elements.map((el) => (el.layout?.y || 0) + (el.layout?.height || 0)), ...template.elements.map(
); (el) => (el.layout?.y || 0) + (el.layout?.height || 0),
),
)
return { return {
width: baseWidth, width: baseWidth,
height: Math.max(baseHeight, contentHeight + PADDING_Y), height: Math.max(baseHeight, contentHeight + PADDING_Y),
}; }
}, [template.elements]); }, [template.elements])
// Проверяем есть ли кнопка сохранения (есть ли название протокола) // Проверяем есть ли кнопка сохранения (есть ли название протокола)
const protocolNameElement = template.elements.find(el => const protocolNameElement = template.elements.find(
el.name === 'protocolName' || el.label === 'Название протокола' (el) => el.name === 'protocolName' || el.label === 'Название протокола',
); )
const canSave = protocolNameElement ? !!formData[protocolNameElement.id]?.trim() : false; const canSave = protocolNameElement
? !!formData[protocolNameElement.id]?.trim()
: false
return ( return (
<div className="flex flex-col h-screen bg-gray-50"> <div className="flex h-screen flex-col bg-gray-50">
{/* Заголовок */} {/* Заголовок */}
<div className="bg-white border-b border-gray-200 p-4 shrink-0"> <div className="shrink-0 border-b border-gray-200 bg-white p-4">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<Button variant="ghost" onClick={onBack}> <Button variant="ghost" onClick={onBack}>
<ArrowLeft className="h-4 w-4 mr-2" /> <ArrowLeft className="mr-2 h-4 w-4" />
Назад Назад
</Button> </Button>
<div> <div>
@@ -373,11 +456,11 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
</div> </div>
<div className="flex gap-2"> <div className="flex gap-2">
<Button variant="outline" onClick={handleExport}> <Button variant="outline" onClick={handleExport}>
<Download className="h-4 w-4 mr-2" /> <Download className="mr-2 h-4 w-4" />
Экспорт в Excel Экспорт в Excel
</Button> </Button>
<Button onClick={handleSave} disabled={!canSave}> <Button onClick={handleSave} disabled={!canSave}>
<Save className="h-4 w-4 mr-2" /> <Save className="mr-2 h-4 w-4" />
Сохранить протокол Сохранить протокол
</Button> </Button>
</div> </div>
@@ -390,89 +473,102 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
className="relative mx-auto my-8" className="relative mx-auto my-8"
style={{ width: canvasSize.width, height: canvasSize.height }} style={{ width: canvasSize.width, height: canvasSize.height }}
> >
{template.elements.map((element) => { {template.elements.map((element) => {
const layout = element.layout || { x: 50, y: 50, width: 300, height: 80 }; const layout = element.layout || {
return ( x: 50,
<div y: 50,
key={element.id} width: 300,
className="absolute" height: 80,
style={{ }
left: layout.x, return (
top: layout.y, <div
width: layout.width, key={element.id}
minHeight: layout.height, className="absolute"
zIndex: layout.zIndex || 1, style={{
}} left: layout.x,
> top: layout.y,
<FormElement width: layout.width,
element={element} minHeight: layout.height,
value={formData[element.id]} zIndex: layout.zIndex || 1,
onChange={(value) => handleFieldChange(element.id, value)} }}
/> >
</div> <FormElement
); element={element}
})} value={formData[element.id]}
onChange={(value) => handleFieldChange(element.id, value)}
{template.elements.length === 0 && ( />
<div className="absolute inset-0 flex items-center justify-center"> </div>
<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"> {template.elements.length === 0 && (
В этом шаблоне пока не созданы элементы формы <div className="absolute inset-0 flex items-center justify-center">
</p> <div className="text-center text-gray-400">
<Button variant="outline" onClick={() => window.history.back()}> <FileText className="mx-auto mb-4 h-16 w-16" />
Настроить шаблон <h3 className="mb-2 text-lg font-medium text-gray-900">
</Button> Нет элементов формы
</div> </h3>
</div> <p className="mb-4 text-gray-600">
)} В этом шаблоне пока не созданы элементы формы
</p>
<Button variant="outline" onClick={() => window.history.back()}>
Настроить шаблон
</Button>
</div>
</div>
)}
</div> </div>
</div> </div>
</div> </div>
); )
}; }
export const ProtocolCreation: FC = () => { export const ProtocolCreation: FC = () => {
const navigate = useNavigate(); const navigate = useNavigate()
const { templates } = useTemplateContext(); const { templates } = useTemplateContext()
const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(null); const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(
null,
)
const handleTemplateSelect = (template: Template) => { const handleTemplateSelect = (template: Template) => {
setSelectedTemplate(template); setSelectedTemplate(template)
}; }
const handleProtocolSave = (data: Record<string, any>) => { const handleProtocolSave = (data: Record<string, any>) => {
console.log('Сохранение протокола:', data); console.log('Сохранение протокола:', data)
// Здесь будет логика сохранения протокола // Здесь будет логика сохранения протокола
alert(`Протокол "${data.protocolName}" сохранен!`); alert(`Протокол "${data.protocolName}" сохранен!`)
navigate('/'); navigate('/')
}; }
const handleBack = () => { const handleBack = () => {
setSelectedTemplate(null); setSelectedTemplate(null)
}; }
if (selectedTemplate) { if (selectedTemplate) {
return ( return (
<ProtocolForm <ProtocolForm
template={selectedTemplate} template={selectedTemplate}
onSave={handleProtocolSave} onSave={handleProtocolSave}
onBack={handleBack} onBack={handleBack}
/> />
); )
} }
return ( return (
<div className="p-6 max-w-7xl mx-auto"> <div className="mx-auto max-w-7xl p-6">
<div className="flex items-center justify-between mb-6"> <div className="mb-6 flex items-center justify-between">
<div> <div>
<h1 className="text-3xl font-bold text-gray-900">Создание протокола</h1> <h1 className="text-3xl font-bold text-gray-900">
<p className="text-gray-600 mt-2">Выберите шаблон для создания нового протокола</p> Создание протокола
</h1>
<p className="mt-2 text-gray-600">
Выберите шаблон для создания нового протокола
</p>
</div> </div>
<Button <Button
variant="outline" variant="outline"
onClick={() => navigate('/templates')} onClick={() => navigate('/templates')}
className="flex items-center gap-2" className="flex items-center gap-2"
> >
@@ -482,19 +578,26 @@ export const ProtocolCreation: FC = () => {
</div> </div>
{templates.length === 0 ? ( {templates.length === 0 ? (
<div className="text-center py-12"> <div className="py-12 text-center">
<FileText className="h-16 w-16 text-gray-400 mx-auto mb-4" /> <FileText className="mx-auto mb-4 h-16 w-16 text-gray-400" />
<h3 className="text-lg font-medium text-gray-900 mb-2">Нет доступных шаблонов</h3> <h3 className="mb-2 text-lg font-medium text-gray-900">
<p className="text-gray-600 mb-6">Создайте шаблон протокола для начала работы</p> Нет доступных шаблонов
</h3>
<p className="mb-6 text-gray-600">
Создайте шаблон протокола для начала работы
</p>
<Button onClick={() => navigate('/templates')}> <Button onClick={() => navigate('/templates')}>
<Plus className="h-4 w-4 mr-2" /> <Plus className="mr-2 h-4 w-4" />
Создать шаблон Создать шаблон
</Button> </Button>
</div> </div>
) : ( ) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"> <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
{templates.map((template) => ( {templates.map((template) => (
<Card key={template.id} className="hover:shadow-lg transition-shadow cursor-pointer"> <Card
key={template.id}
className="cursor-pointer transition-shadow hover:shadow-lg"
>
<CardHeader> <CardHeader>
<CardTitle className="text-lg">{template.name}</CardTitle> <CardTitle className="text-lg">{template.name}</CardTitle>
{template.description && ( {template.description && (
@@ -507,9 +610,11 @@ export const ProtocolCreation: FC = () => {
<div className="space-y-2 text-sm text-gray-600"> <div className="space-y-2 text-sm text-gray-600">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<FileText className="h-4 w-4" /> <FileText className="h-4 w-4" />
<span>{template.elements.length} элементов для заполнения</span> <span>
{template.elements.length} элементов для заполнения
</span>
</div> </div>
<div className="text-xs text-gray-500 mt-2"> <div className="mt-2 text-xs text-gray-500">
Создан: {template.createdAt.toLocaleDateString('ru-RU')} Создан: {template.createdAt.toLocaleDateString('ru-RU')}
</div> </div>
</div> </div>
@@ -517,14 +622,15 @@ export const ProtocolCreation: FC = () => {
<Button <Button
className="w-full" className="w-full"
onClick={() => handleTemplateSelect(template)} onClick={() => handleTemplateSelect(template)}
disabled={!template.excelFile || template.elements.length === 0} disabled={
> !template.excelFile || template.elements.length === 0
{template.excelFile
? template.elements.length > 0
? 'Создать протокол'
: 'Нет элементов формы'
: 'Шаблон не настроен'
} }
>
{template.excelFile
? template.elements.length > 0
? 'Создать протокол'
: 'Нет элементов формы'
: 'Шаблон не настроен'}
</Button> </Button>
</div> </div>
</CardContent> </CardContent>
@@ -533,5 +639,5 @@ export const ProtocolCreation: FC = () => {
</div> </div>
)} )}
</div> </div>
); )
}; }

View File

@@ -8,6 +8,8 @@ export type ElementType =
| 'textarea' | 'textarea'
| 'date' | 'date'
| 'standards' | 'standards'
| 'calibration-conditions'
| 'button-group'
export interface ElementOption { export interface ElementOption {
value: string value: string