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

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 { dateDefinition } from "./DateElement";
export { numberDefinition } from "./NumberElement";
export { radioDefinition } from "./RadioElement";
export { selectDefinition } from "./SelectElement";
export { textareaDefinition } from "./TextareaElement";
export { textDefinition } from "./TextElement";
export { buttonGroupDefinition } from './ButtonGroupElement'
export { calibrationConditionsDefinition } from './CalibrationConditionsElement'
export { checkboxDefinition } from './CheckboxElement'
export { dateDefinition } from './DateElement'
export { numberDefinition } from './NumberElement'
export { radioDefinition } from './RadioElement'
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 { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Calendar, Check, FileText, Settings, X } from "lucide-react";
import { useState } from "react";
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Separator } from '@/components/ui/separator'
import { Calendar, Check, FileText, Settings } from 'lucide-react'
import { useState } from 'react'
interface MeasurementStandard {
id: string;
name: string;
shortName: string;
type: string;
registryNumber: string;
range: string;
accuracy: string;
certificateNumber: string;
validUntil: string;
id: string
name: string
shortName: string
type: string
registryNumber: string
range: string
accuracy: string
certificateNumber: string
validUntil: string
}
interface StandardsConfig {
registryId: string;
selectedStandards: string[];
lastUpdated: string;
registryId: string
selectedStandards: string[]
lastUpdated: string
}
interface StandardsDialogProps {
isOpen: boolean;
onClose: () => void;
standards: MeasurementStandard[];
config: StandardsConfig;
onSave: (config: StandardsConfig) => void;
registryNumber: string;
isOpen: boolean
onClose: () => void
standards: MeasurementStandard[]
config: StandardsConfig
onSave: (config: StandardsConfig) => void
registryNumber: string
}
export function StandardsDialog({
@@ -38,102 +38,106 @@ export function StandardsDialog({
standards,
config,
onSave,
registryNumber
registryNumber,
}: 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) => {
setSelectedStandards(prev => {
setSelectedStandards((prev) => {
if (prev.includes(standardId)) {
return prev.filter(id => id !== standardId);
return prev.filter((id) => id !== standardId)
} else if (prev.length < 7) {
return [...prev, standardId];
return [...prev, standardId]
}
return prev;
});
};
return prev
})
}
const handleSave = () => {
onSave({
...config,
selectedStandards,
lastUpdated: new Date().toISOString()
});
onClose();
};
lastUpdated: new Date().toISOString(),
})
onClose()
}
const isExpiringSoon = (validUntil: string) => {
const expiryDate = new Date(validUntil);
const now = new Date();
const monthsUntilExpiry = (expiryDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24 * 30);
return monthsUntilExpiry <= 3;
};
const expiryDate = new Date(validUntil)
const now = new Date()
const monthsUntilExpiry =
(expiryDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24 * 30)
return monthsUntilExpiry <= 3
}
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<Card className="w-full max-w-4xl max-h-[90vh] overflow-hidden">
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
<Card className="max-h-[90vh] w-full max-w-4xl overflow-hidden">
<CardHeader className="pb-4">
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-lg flex items-center gap-2">
<Settings className="w-5 h-5" />
<CardTitle className="flex items-center gap-2 text-lg">
<Settings className="h-5 w-5" />
Измерительные эталоны
</CardTitle>
<p className="text-sm text-muted-foreground mt-1">
<p className="mt-1 text-sm text-muted-foreground">
ГРСИ: {registryNumber} Выбрано: {selectedStandards.length}/7
</p>
</div>
<Button variant="ghost" size="sm" onClick={onClose}>
<X className="w-4 h-4" />
</Button>
</div>
</CardHeader>
<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) => {
const isSelected = selectedStandards.includes(standard.id);
const isExpiring = isExpiringSoon(standard.validUntil);
const isSelected = selectedStandards.includes(standard.id)
const isExpiring = isExpiringSoon(standard.validUntil)
return (
<div
key={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
? "border-primary bg-primary/10 shadow-sm"
: "border-border hover:border-primary/50 hover:bg-primary/5"
? 'border-primary bg-primary/10 shadow-sm'
: 'border-border hover:border-primary/50 hover:bg-primary/5'
}`}
>
<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 ${
isSelected
? "border-primary bg-primary"
: "border-border"
}`}>
{isSelected && <Check className="w-3 h-3 text-primary-foreground" />}
<div
className={`mt-1 flex h-5 w-5 items-center justify-center rounded-full border-2 transition-colors ${
isSelected
? 'border-primary bg-primary'
: 'border-border'
}`}
>
{isSelected && (
<Check className="h-3 w-3 text-primary-foreground" />
)}
</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-1">
<div className="font-medium text-sm text-foreground leading-tight">
<div className="text-sm font-medium leading-tight text-foreground">
{standard.shortName}
</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}
</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">
{standard.accuracy}
</Badge>
{isExpiring && (
<Badge variant="destructive" className="text-xs">
<Calendar className="w-3 h-3 mr-1" />
<Calendar className="mr-1 h-3 w-3" />
Истекает
</Badge>
)}
@@ -142,20 +146,23 @@ export function StandardsDialog({
<div className="mt-2 space-y-1">
<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}
</div>
<div className="text-xs text-muted-foreground">
Диапазон: {standard.range}
</div>
<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>
@@ -169,13 +176,11 @@ export function StandardsDialog({
<Button variant="outline" onClick={onClose}>
Отмена
</Button>
<Button onClick={handleSave}>
Сохранить
</Button>
<Button onClick={handleSave}>Сохранить</Button>
</div>
</div>
</CardContent>
</Card>
</div>
);
)
}

View File

@@ -1,56 +1,57 @@
import { ElementDefinition } from "@/lib/element-registry";
import { parseCellAddress } from "@/lib/utils";
import { CellTarget } from "@/types/template";
import { Calendar } from "lucide-react";
import { StandardsEditor } from "./StandardsEditor";
import { StandardsPreview } from "./StandardsPreview";
import { ElementDefinition } from '@/lib/element-registry'
import { parseCellAddress } from '@/lib/utils'
import { CellTarget } from '@/types/template'
import { Weight } from 'lucide-react'
import { StandardsEditor } from './StandardsEditor'
import { StandardsPreview } from './StandardsPreview'
interface StandardsConfig {
registryNumber: string; // ГРСИ
sheet: string; // Лист Excel
startCell: string; // Первая ячейка (например "A10")
maxItems: number; // Обычно 7
targetCells: CellTarget[];
registryNumber: string // ГРСИ
sheet: string // Лист Excel
startCell: string // Первая ячейка (например "A10")
maxItems: number // Обычно 7
targetCells: CellTarget[]
}
export const standardsDefinition: ElementDefinition<StandardsConfig, string[]> = {
type: "standards",
label: "Измерительные эталоны",
icon: <Calendar className="h-4 w-4" />,
defaultConfig: {
registryNumber: "",
sheet: "Report",
startCell: "A1",
maxItems: 7,
targetCells: [],
},
Editor: StandardsEditor,
Preview: StandardsPreview,
Render: () => {
// Здесь нужно создать обертку для StandardsDialog
// Пока возвращаем null, так как StandardsDialog требует дополнительные пропсы
return null;
},
mapToCells: (cfg) => {
const res: CellTarget[] = [];
const parsed = parseCellAddress(cfg.startCell);
export const standardsDefinition: ElementDefinition<StandardsConfig, string[]> =
{
type: 'standards',
label: 'Измерительные эталоны',
icon: <Weight className="h-4 w-4" />,
defaultConfig: {
registryNumber: '',
sheet: 'Report',
startCell: 'A1',
maxItems: 7,
targetCells: [],
},
Editor: StandardsEditor,
Preview: StandardsPreview,
Render: () => {
// Здесь нужно создать обертку для StandardsDialog
// Пока возвращаем null, так как StandardsDialog требует дополнительные пропсы
return null
},
mapToCells: (cfg) => {
const res: CellTarget[] = []
const parsed = parseCellAddress(cfg.startCell)
if (!parsed) {
// Если не удалось распарсить, возвращаем пустой массив
return res;
}
if (!parsed) {
// Если не удалось распарсить, возвращаем пустой массив
return res
}
const { column, row } = parsed;
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}`,
});
}
// Генерируем ячейки вертикально (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;
},
};
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 {
getAvailableElementTypes,
@@ -251,6 +263,61 @@ const ElementPreview: React.FC<{ element: Partial<TemplateElement> }> = ({
</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:
return (
<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) {
@@ -340,12 +410,15 @@ const ElementForm: React.FC<ElementFormProps> = ({ formData, setFormData }) => {
setFormData((prev) => {
const updates: Partial<TemplateElement> = { type: newType }
// Если выбран тип "standards", устанавливаем значения по умолчанию
if (newType === 'standards') {
// Если выбран тип "standards" или "calibration-conditions", устанавливаем значения по умолчанию
if (
newType === 'standards' ||
newType === 'calibration-conditions'
) {
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)
if (elementDefinition && elementDefinition.defaultConfig) {
@@ -444,12 +517,15 @@ const ElementForm: React.FC<ElementFormProps> = ({ formData, setFormData }) => {
setFormData((prev) => {
const updates: Partial<TemplateElement> = { type: newType }
// Если выбран тип "standards", устанавливаем значения по умолчанию
if (newType === 'standards') {
// Если выбран тип "standards" или "calibration-conditions", устанавливаем значения по умолчанию
if (
newType === 'standards' ||
newType === 'calibration-conditions'
) {
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(
'Element definition (fallback):',
elementDefinition,
@@ -696,10 +772,15 @@ export const ElementConstructor: React.FC<ElementConstructorProps> = ({
return
}
// Для элемента типа "standards" не требуем targetCells, так как они генерируются автоматически
if (formData.type !== 'standards' && !formData.targetCells?.length) {
// Для элементов типа "standards", "calibration-conditions" и "button-group" не требуем targetCells, так как они генерируются автоматически или не нужны
if (
formData.type !== 'standards' &&
formData.type !== 'calibration-conditions' &&
formData.type !== 'button-group' &&
!formData.targetCells?.length
) {
console.log(
'Validation failed: missing targetCells for non-standards element',
'Validation failed: missing targetCells for element that requires manual targetCells',
)
return
}
@@ -714,12 +795,15 @@ export const ElementConstructor: React.FC<ElementConstructorProps> = ({
layoutSettings.gridSize,
)
// Специальная обработка для эталонов
// Специальная обработка для элементов с автоматической генерацией targetCells
let targetCells = formData.targetCells || []
if (formData.type === 'standards') {
// Для эталонов генерируем targetCells автоматически, если их нет
if (
formData.type === 'standards' ||
formData.type === 'calibration-conditions'
) {
// Генерируем targetCells автоматически, если их нет
if (!targetCells.length) {
const elementDefinition = getElementDefinition('standards')
const elementDefinition = getElementDefinition(formData.type)
if (elementDefinition && elementDefinition.defaultConfig) {
const defaultConfig = elementDefinition.defaultConfig as any
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 = {
id: Date.now().toString(),
type: formData.type as ElementType,
@@ -753,8 +842,14 @@ export const ElementConstructor: React.FC<ElementConstructorProps> = ({
const handleUpdateElement = () => {
if (!editingElement || !formData.name || !formData.label) return
// Для элемента типа "standards" не требуем targetCells, так как они генерируются автоматически
if (formData.type !== 'standards' && !formData.targetCells?.length) return
// Для элементов типа "standards", "calibration-conditions" и "button-group" не требуем targetCells, так как они генерируются автоматически или не нужны
if (
formData.type !== 'standards' &&
formData.type !== 'calibration-conditions' &&
formData.type !== 'button-group' &&
!formData.targetCells?.length
)
return
onElementUpdate(editingElement.id, formData)
setEditingElement(null)
@@ -828,6 +923,8 @@ export const ElementConstructor: React.FC<ElementConstructorProps> = ({
!formData.name ||
!formData.label ||
(formData.type !== 'standards' &&
formData.type !== 'calibration-conditions' &&
formData.type !== 'button-group' &&
!formData.targetCells?.length)
}
>

View File

@@ -1,37 +1,50 @@
import {
Calendar,
ChevronDown,
Edit,
Eye,
EyeOff,
Grid,
Move,
Trash2
} 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';
Calendar,
ChevronDown,
Droplets,
Edit,
Edit3,
Eye,
EyeOff,
Gauge,
Grid,
Move,
Radio,
Thermometer,
Trash2,
Zap,
} 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 {
elements: TemplateElement[];
layoutSettings: FormLayoutSettings;
onElementUpdate: (elementId: string, updates: Partial<TemplateElement>) => void;
onElementDelete: (elementId: string) => void;
onLayoutSettingsChange: (settings: FormLayoutSettings) => void;
onElementEdit?: (element: TemplateElement) => void;
elements: TemplateElement[]
layoutSettings: FormLayoutSettings
onElementUpdate: (
elementId: string,
updates: Partial<TemplateElement>,
) => void
onElementDelete: (elementId: string) => void
onLayoutSettingsChange: (settings: FormLayoutSettings) => void
onElementEdit?: (element: TemplateElement) => void
}
interface DraggableElementProps {
element: TemplateElement;
isSelected: boolean;
onSelect: () => void;
onUpdate: (layout: ElementLayout) => void;
onDelete: () => void;
onEdit?: () => void;
gridSize: number;
element: TemplateElement
isSelected: boolean
onSelect: () => void
onUpdate: (layout: ElementLayout) => void
onDelete: () => void
onEdit?: () => void
gridSize: number
}
// const ELEMENT_ICONS: Record<ElementType, React.ReactNode> = {
@@ -54,44 +67,61 @@ interface DraggableElementProps {
// checkbox: 'bg-teal-100 border-teal-300 text-teal-800',
// };
const DraggableElement: React.FC<DraggableElementProps> = React.memo(({
element,
isSelected,
onSelect,
onUpdate,
onDelete,
onEdit,
gridSize,
}) => {
const layout = element.layout || { x: 50, y: 50, width: 300, height: 80, zIndex: 1 };
const DraggableElement: React.FC<DraggableElementProps> = React.memo(
({ element, isSelected, onSelect, onUpdate, onDelete, onEdit, gridSize }) => {
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 только если позиция действительно изменилась,
// чтобы избежать ложных срабатываний при клике.
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({
...layout,
width: parseInt(ref.style.width, 10),
height: parseInt(ref.style.height, 10),
x: pos.x,
y: pos.y,
});
}, [layout, onUpdate]);
...layout,
width: parseInt(ref.style.width, 10),
height: parseInt(ref.style.height, 10),
x: pos.x,
y: pos.y,
})
},
[layout, onUpdate],
)
const handleDeleteClick = useCallback((e: React.MouseEvent) => {
e.stopPropagation();
onDelete();
}, [onDelete]);
const handleDeleteClick = useCallback(
(e: React.MouseEvent) => {
e.stopPropagation()
onDelete()
},
[onDelete],
)
const handleEditClick = useCallback((e: React.MouseEvent) => {
e.stopPropagation();
onEdit?.();
}, [onEdit]);
const handleEditClick = useCallback(
(e: React.MouseEvent) => {
e.stopPropagation()
onEdit?.()
},
[onEdit],
)
/*
* 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.
*/
const previewControl = useMemo(() => {
switch (element.type) {
case 'text':
return <Input readOnly placeholder={element.placeholder || 'Введите текст'} className="pointer-events-none w-full bg-white" />;
case 'textarea':
return <Textarea readOnly rows={3} placeholder={element.placeholder || 'Введите текст'} className="pointer-events-none w-full resize-none bg-white" />;
case 'number':
return <Input type="number" readOnly placeholder={element.placeholder || '0'} 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':
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>
<ChevronDown className="h-4 w-4 opacity-50" />
</div>
</div>
);
case 'radio':
return (
<div className="space-y-2 pointer-events-none">
{(element.options?.length ? element.options : [{ label: 'Вариант 1' }]).map((opt, idx) => (
<div key={idx} className="flex items-center gap-2">
<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>
))}
</div>
);
case 'checkbox':
return (
<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>
</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>
);
default:
return null;
}
}, [element]);
switch (element.type) {
case 'text':
return (
<Input
readOnly
placeholder={element.placeholder || 'Введите текст'}
className="pointer-events-none w-full bg-white"
/>
)
case 'textarea':
return (
<Textarea
readOnly
rows={3}
placeholder={element.placeholder || 'Введите текст'}
className="pointer-events-none w-full resize-none bg-white"
/>
)
case 'number':
return (
<Input
type="number"
readOnly
placeholder={element.placeholder || '0'}
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':
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>
<ChevronDown className="h-4 w-4 opacity-50" />
</div>
</div>
)
case 'radio':
return (
<div className="pointer-events-none space-y-2">
{(element.options?.length
? element.options
: [{ label: 'Вариант 1' }]
).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 (
<Rnd
dragGrid={[gridSize, gridSize]}
resizeGrid={[gridSize, gridSize]}
default={{
x: layout.x,
y: layout.y,
width: layout.width,
height: layout.height,
}}
onDragStop={handleDragStop}
onResizeStop={handleResizeStop}
minWidth={120}
minHeight={32}
bounds="parent"
className={`group ${isSelected ? 'ring-2 ring-blue-500 ring-offset-2 z-20' : 'z-10'}`}
onClick={onSelect}
<Rnd
dragGrid={[gridSize, gridSize]}
resizeGrid={[gridSize, gridSize]}
default={{
x: layout.x,
y: layout.y,
width: layout.width,
height: layout.height,
}}
onDragStop={handleDragStop}
onResizeStop={handleResizeStop}
minWidth={120}
minHeight={32}
bounds="parent"
className={`group ${
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 ${
isSelected
? 'bg-blue-50/20 border border-blue-200/50 rounded-md p-2'
: 'bg-transparent border border-transparent rounded-md hover:bg-gray-50/10 p-1'
}`}>
{/* Label and controls (only visible when selected or hovered) */}
<div className={`flex items-center justify-between mb-1 ${
isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-60'
}`}>
<div className="flex items-start gap-2">
<div className="flex items-center gap-1">
<span className="font-medium text-xs text-gray-600 truncate">
{element.label || element.name || `${element.type} элемент`}
</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>
{/* Label and controls (only visible when selected or hovered) */}
<div
className={`mb-1 flex items-center justify-between ${
isSelected ? 'opacity-100' : 'opacity-0 group-hover:opacity-60'
}`}
>
<div className="flex items-start gap-2">
<div className="flex items-center gap-1">
<span className="truncate text-xs font-medium text-gray-600">
{element.label || element.name || `${element.type} элемент`}
</span>
{element.required && (
<span className="-mt-1.5 inline-block h-1 w-1 rounded-full bg-red-500" />
)}
</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> = ({
elements,
layoutSettings,
onElementUpdate,
onElementDelete,
onLayoutSettingsChange,
onElementEdit,
elements,
layoutSettings,
onElementUpdate,
onElementDelete,
onLayoutSettingsChange,
onElementEdit,
}) => {
console.log('VisualLayoutEditor render with elements:', elements);
const [selectedElementId, setSelectedElementId] = useState<string | null>(null);
console.log('VisualLayoutEditor render with elements:', elements)
const [selectedElementId, setSelectedElementId] = useState<string | null>(
null,
)
const canvasSize = useMemo(() => {
const PADDING_Y = 200;
const canvasSize = useMemo(() => {
const PADDING_Y = 200
const baseWidth = 1200;
const baseHeight = 800;
const baseWidth = 1200
const baseHeight = 800
if (elements.length === 0) {
return { width: baseWidth, height: baseHeight };
}
if (elements.length === 0) {
return { width: baseWidth, height: baseHeight }
}
const contentHeight = Math.max(
0,
...elements.map((el) => (el.layout?.y || 0) + (el.layout?.height || 0)),
);
const contentHeight = Math.max(
0,
...elements.map((el) => (el.layout?.y || 0) + (el.layout?.height || 0)),
)
return {
width: baseWidth,
height: Math.max(baseHeight, contentHeight + PADDING_Y),
};
}, [elements]);
const GridPattern = useMemo(() => {
if (!layoutSettings.showGrid) return null;
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 {
width: baseWidth,
height: Math.max(baseHeight, contentHeight + PADDING_Y),
}
}, [elements])
const GridPattern = useMemo(() => {
if (!layoutSettings.showGrid) return null
const gridSize = layoutSettings.gridSize
return (
<div className="flex flex-col h-full bg-gray-50">
<div className="flex items-center justify-between p-2 bg-white border-b shrink-0">
<span className="text-sm text-gray-600 px-2">{elements.length} элементов на холсте</span>
<Button variant="outline" size="sm" onClick={toggleGrid}>
{layoutSettings.showGrid ? <EyeOff className="h-4 w-4 mr-2" /> : <Eye className="h-4 w-4 mr-2" />}
{layoutSettings.showGrid ? 'Скрыть сетку' : 'Показать сетку'}
</Button>
</div>
<div
className="pointer-events-none absolute inset-0"
style={{
backgroundImage: `radial-gradient(circle, #e5e7eb 1px, transparent 1px)`,
backgroundSize: `${gridSize}px ${gridSize}px`,
}}
/>
)
}, [layoutSettings.showGrid, layoutSettings.gridSize])
<div className="flex-1 relative overflow-auto" onClick={handleCanvasClick}>
<div
className="relative bg-white shadow-lg mx-auto my-8"
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="absolute inset-0 flex items-center justify-center pointer-events-none">
<div className="text-center text-gray-400">
<Move className="h-16 w-16 mx-auto mb-4" />
<p className="text-xl font-medium mb-2">Холст пуст</p>
<p className="text-sm">Добавьте свой первый элемент</p>
</div>
</div>
)}
</div>
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 (
<div className="flex h-full flex-col bg-gray-50">
<div className="flex shrink-0 items-center justify-between border-b bg-white p-2">
<span className="px-2 text-sm text-gray-600">
{elements.length} элементов на холсте
</span>
<Button variant="outline" size="sm" onClick={toggleGrid}>
{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>
)
}

View File

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

View File

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