галочка сохранения инпутов

This commit is contained in:
2025-07-28 09:35:20 +03:00
parent 4c6deb4563
commit dc667092b3
12 changed files with 399 additions and 212 deletions

View File

@@ -123,13 +123,14 @@ export const CellRenderer = ({
: undefined
// Проверяем, является ли ячейка скопированной
const isCopied =
const isCopied = Boolean(
copiedCells &&
copiedCells.sourceSheet === sheetType &&
copiedCells.data.some(
cell => cell.row === rowIndex && cell.col === columnIndex
)
const isCut = isCopied && copiedCells?.isCut
copiedCells.sourceSheet === sheetType &&
copiedCells.data.some(
cell => cell.row === rowIndex && cell.col === columnIndex
)
)
const isCut = Boolean(isCopied && copiedCells?.isCut)
return (
<Cell

View File

@@ -23,6 +23,7 @@ import {
Type,
} from 'lucide-react'
import React, { useState } from 'react'
import { v4 as uuidv4 } from 'uuid'
import { Button } from '../ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '../ui/card'
import { Checkbox } from '../ui/checkbox'
@@ -516,7 +517,7 @@ export const ElementConstructor: React.FC<ElementConstructorProps> = ({
const newElement: TemplateElement = {
...formData, // Копируем все поля из formData, включая специфичные для элемента
id: Date.now().toString(),
id: uuidv4(),
type: formData.type as ElementType,
name: formData.label || '',
label: formData.label,

View File

@@ -1,6 +1,7 @@
import { Button } from '@/component/ui/button'
import { Input } from '@/component/ui/input'
import { ElementDefinition } from '@/entitiy/element/model/interface'
import { CellsBadge } from '@/entitiy/element/ui/cellsBadge'
import { ElementOption } from '@/type/template'
import { Plus, Square, Trash2 } from 'lucide-react'
@@ -194,7 +195,10 @@ export const buttonGroupDefinition: ElementDefinition<
</div>
),
Render: ({ config, value, onChange }) => (
<div className="space-y-3">
<div className="relative space-y-3">
{/* Бейдж ячеек */}
<CellsBadge targetCells={config.targetCells} />
{config.name && (
<label className="text-sm font-medium text-gray-900">
{config.name}

View File

@@ -9,6 +9,7 @@ import {
SelectValue,
} from '@/component/ui/select'
import { ElementDefinition } from '@/entitiy/element/model/interface'
import { CellsBadge } from '@/entitiy/element/ui/cellsBadge'
import { useToast } from '@/lib/hooks/useToast'
import { ElementOption } from '@/type/template'
import { ChevronDown, Plus, Trash2 } from 'lucide-react'
@@ -200,24 +201,29 @@ export const selectDefinition: ElementDefinition<SelectConfig, string> = {
const currentValue = value || localStorage.getItem(storageKey) || ''
return (
<Select value={currentValue} onValueChange={handleValueChange}>
<SelectTrigger className="w-full min-w-32">
<SelectValue
placeholder={config.placeholder || 'Выберите значение'}
/>
</SelectTrigger>
<SelectContent>
<SelectGroup>
{config.options
.filter(option => option.value.trim() !== '')
.map((option, index) => (
<SelectItem key={index} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
<div className="relative">
{/* Бейдж ячеек */}
<CellsBadge targetCells={config.targetCells} />
<Select value={currentValue} onValueChange={handleValueChange}>
<SelectTrigger className="w-full min-w-32">
<SelectValue
placeholder={config.placeholder || 'Выберите значение'}
/>
</SelectTrigger>
<SelectContent>
<SelectGroup>
{config.options
.filter(option => option.value.trim() !== '')
.map((option, index) => (
<SelectItem key={index} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
</div>
)
},
}

View File

@@ -2,6 +2,7 @@ import { Badge } from '@/component/ui/badge'
import { Button } from '@/component/ui/button'
import { Label } from '@/component/ui/label'
import { ElementDefinition } from '@/entitiy/element/model/interface'
import { CellsBadge } from '@/entitiy/element/ui/cellsBadge'
import { CellTarget } from '@/type/template'
import { FileText, Settings, Weight } from 'lucide-react'
import { useEffect, useState } from 'react'
@@ -96,7 +97,10 @@ export const standardsDefinition: ElementDefinition<
}, [standards, selectedStandardIds, value?.standardNames, onChange])
return (
<div className="space-y-2">
<div className="relative space-y-2">
{/* Бейдж ячеек */}
<CellsBadge targetCells={config.targetCells} />
{/* Блок с измерительными эталонами */}
<div>
<div className="mb-2 flex items-center justify-between">

View File

@@ -1,13 +1,44 @@
import { Input } from '@/component/ui/input'
import { ElementDefinition } from '@/entitiy/element/model/interface'
import { CellsBadge } from '@/entitiy/element/ui/cellsBadge'
import { ExtraSettingsBadge } from '@/entitiy/element/ui/extraSettingsBadge'
import { Type } from 'lucide-react'
import { Save, SaveOff, Type } from 'lucide-react'
import { useEffect, useState } from 'react'
interface TextConfig {
placeholder?: string
required?: boolean
targetCells: any[]
name?: string
id?: string // Добавляем id для совместимости с TemplateElement
}
// Утилиты для работы с localStorage
const getLocalStorageKey = (type: string, id: string) => `${type}_${id}`
const saveToLocalStorage = (key: string, value: string) => {
try {
localStorage.setItem(key, value)
} catch (error) {
console.warn('Failed to save to localStorage:', error)
}
}
const getFromLocalStorage = (key: string): string => {
try {
return localStorage.getItem(key) || ''
} catch (error) {
console.warn('Failed to get from localStorage:', error)
return ''
}
}
const removeFromLocalStorage = (key: string) => {
try {
localStorage.removeItem(key)
} catch (error) {
console.warn('Failed to remove from localStorage:', error)
}
}
export const textDefinition: ElementDefinition<TextConfig, string> = {
@@ -21,6 +52,14 @@ export const textDefinition: ElementDefinition<TextConfig, string> = {
targetCells: [],
name: '',
},
getInitialValue: config => {
// Используем id из config (который приходит из TemplateElement)
if (config.id) {
const key = getLocalStorageKey('text', config.id)
return getFromLocalStorage(key)
}
return ''
},
mapToCells: config => config.targetCells || [],
mapToCellValues: (config, value) => {
const cells = config.targetCells || []
@@ -38,20 +77,114 @@ export const textDefinition: ElementDefinition<TextConfig, string> = {
<Input placeholder={config.placeholder} className="w-full" />
</div>
),
Render: ({ config, value, onChange }) => (
<div className="space-y-1">
{config.name && (
<label className="text-sm font-medium text-gray-900">
{config.name}
{config.required && <span className="ml-1 text-red-500">*</span>}
</label>
)}
<Input
placeholder={config.placeholder}
value={value || ''}
onChange={e => onChange?.(e.target.value)}
required={config.required}
/>
</div>
),
Render: ({ config, value, onChange }) => {
const [localStorageEnabled, setLocalStorageEnabled] = useState(false)
const [currentValue, setCurrentValue] = useState(value || '')
// Инициализация состояния localStorage из сохраненных данных
useEffect(() => {
if (config.id) {
const key = getLocalStorageKey('text', config.id)
const savedValue = getFromLocalStorage(key)
// Если есть сохраненное значение, включаем localStorage и загружаем его
if (savedValue) {
setLocalStorageEnabled(true)
if (savedValue !== currentValue) {
setCurrentValue(savedValue)
onChange?.(savedValue)
}
}
}
}, [config.id])
// Синхронизация внешнего значения
useEffect(() => {
if (value !== currentValue) {
setCurrentValue(value || '')
}
}, [value])
const handleValueChange = (newValue: string) => {
setCurrentValue(newValue)
onChange?.(newValue)
// Сохранение в localStorage если включено
if (localStorageEnabled && config.id) {
const key = getLocalStorageKey('text', config.id)
saveToLocalStorage(key, newValue)
}
}
const handleLocalStorageToggle = () => {
const newEnabled = !localStorageEnabled
setLocalStorageEnabled(newEnabled)
if (config.id) {
const key = getLocalStorageKey('text', config.id)
if (newEnabled) {
// Включаем localStorage - сохраняем текущее значение
saveToLocalStorage(key, currentValue)
} else {
// Выключаем localStorage - удаляем сохраненное значение
removeFromLocalStorage(key)
}
}
}
return (
<div className="relative space-y-1">
{/* Бейджи в правом верхнем углу */}
<div className="absolute right-0 top-0 z-10 flex items-center gap-1">
{/* Галочка сохранения */}
{config.id && (
<div className="group/save">
<button
onClick={handleLocalStorageToggle}
className="cursor-pointer"
>
{localStorageEnabled ? (
<Save className="h-3 w-3 text-green-600 opacity-80 transition-opacity hover:opacity-100" />
) : (
<SaveOff className="h-3 w-3 cursor-help text-gray-500 opacity-60 transition-opacity hover:opacity-100" />
)}
</button>
<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/save:opacity-100">
<div className="font-medium">
{localStorageEnabled
? 'Автосохранение включено'
: 'Автосохранение выключено'}
</div>
<div className="text-gray-300">
{localStorageEnabled
? 'Значение сохраняется в браузере'
: 'Нажмите, чтобы включить автосохранение'}
</div>
</div>
</div>
)}
{/* Бейдж ячеек */}
<CellsBadge targetCells={config.targetCells} className="" />
</div>
{/* Лейбл поля */}
{config.name && (
<label className="text-sm font-medium text-gray-900">
{config.name}
{config.required && <span className="ml-1 text-red-500">*</span>}
</label>
)}
{/* Поле ввода */}
<Input
placeholder={config.placeholder}
value={currentValue}
onChange={e => handleValueChange(e.target.value)}
required={config.required}
/>
</div>
)
},
}

View File

@@ -9,6 +9,7 @@ import {
} from '@/component/ui/dialog'
import { Input } from '@/component/ui/input'
import { Label } from '@/component/ui/label'
import { CellsBadge } from '@/entitiy/element/ui/cellsBadge'
import {
AlertCircle,
Building2,
@@ -175,47 +176,164 @@ export function VerificationConditionsRender({
}
return (
<Card>
<CardHeader className="px-3 pb-1 pt-2">
<CardTitle className="flex items-center gap-1.5 text-sm">
<Building2 className="h-3.5 w-3.5" />
<span className="truncate">{selectedLab?.name || 'Лаборатория'}</span>
</CardTitle>
</CardHeader>
<div className="relative">
{/* Бейдж ячеек */}
<CellsBadge targetCells={config.targetCells || []} />
<CardContent className="space-y-2 px-3 pb-3">
{/* Выбор даты */}
<div className="flex items-center gap-2">
<CalendarIcon className="h-3.5 w-3.5 text-muted-foreground" />
<Input
type="date"
value={selectedDate}
onChange={handleDateChange}
lang="ru"
className="h-6 border-none bg-muted/50 px-2 text-xs font-normal hover:bg-muted/70 focus:bg-background"
/>
</div>
<Card>
<CardHeader className="px-3 pb-1 pt-2">
<CardTitle className="flex items-center gap-1.5 text-sm">
<Building2 className="h-3.5 w-3.5" />
<span className="truncate">
{selectedLab?.name || 'Лаборатория'}
</span>
</CardTitle>
</CardHeader>
{/* Статус и данные */}
<div className="border-t pt-2">
{hasConditions ? (
<div className="space-y-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-1.5 text-xs text-green-600">
<CheckCircle className="h-3.5 w-3.5" />
<span className="font-medium">Данные внесены</span>
<CardContent className="space-y-2 px-3 pb-3">
{/* Выбор даты */}
<div className="flex items-center gap-2">
<CalendarIcon className="h-3.5 w-3.5 text-muted-foreground" />
<Input
type="date"
value={selectedDate}
onChange={handleDateChange}
lang="ru"
className="h-6 border-none bg-muted/50 px-2 text-xs font-normal hover:bg-muted/70 focus:bg-background"
/>
</div>
{/* Статус и данные */}
<div className="border-t pt-2">
{hasConditions ? (
<div className="space-y-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-1.5 text-xs text-green-600">
<CheckCircle className="h-3.5 w-3.5" />
<span className="font-medium">Данные внесены</span>
</div>
<Dialog
open={editDialogOpen}
onOpenChange={setEditDialogOpen}
>
<DialogTrigger asChild>
<Button
size="sm"
variant="outline"
className="h-6 px-2 text-xs"
onClick={() => handleOpenEditDialog(false)}
>
<Settings className="mr-1 h-3 w-3" />
Настроить
</Button>
</DialogTrigger>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle className="text-base">
Условия поверки
</DialogTitle>
</DialogHeader>
<div className="space-y-3">
<div className="space-y-1 text-xs text-muted-foreground">
<div>{selectedLab?.name}</div>
<div>
{new Date(selectedDate).toLocaleDateString('ru-RU')}
</div>
</div>
<div className="space-y-2">
{labData.conditionTypes.map(conditionType => (
<div key={conditionType.id} className="space-y-1">
<Label className="text-xs font-medium">
{conditionType.name}
{conditionType.unit && (
<span className="ml-1 font-normal text-muted-foreground">
({conditionType.unit})
</span>
)}
</Label>
<Input
value={
editingConditions[conditionType.id] || ''
}
onChange={e =>
handleConditionChange(
conditionType.id,
e.target.value
)
}
placeholder="Значение"
className="h-7 text-xs"
/>
</div>
))}
</div>
<div className="flex gap-2">
<Button
onClick={handleSaveConditions}
disabled={isSaving}
size="sm"
className="h-7 flex-1 text-xs"
>
{isSaving ? 'Сохранение...' : 'Сохранить'}
</Button>
<Button
variant="outline"
onClick={() => setEditDialogOpen(false)}
size="sm"
className="h-7 flex-1 text-xs"
>
Отмена
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
<div className="space-y-1">
{labData.conditionTypes.map(conditionType => {
const conditionValue =
dailyCondition!.conditions[conditionType.id]
return (
<div
key={conditionType.id}
className="flex items-center justify-between rounded bg-muted/30 px-2 py-1 text-xs"
>
<span className="truncate font-medium">
{conditionType.name}
</span>
<span className="ml-2 font-mono text-muted-foreground">
{conditionValue || '—'}
{conditionValue && conditionType.unit && (
<span className="ml-1">{conditionType.unit}</span>
)}
</span>
</div>
)
})}
</div>
</div>
) : (
<div className="space-y-2">
<div className="flex items-center gap-1.5 text-xs text-orange-600">
<AlertCircle className="h-3.5 w-3.5" />
<span className="font-medium">Данные не внесены</span>
</div>
<Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}>
<DialogTrigger asChild>
<Button
onClick={() => handleOpenEditDialog(true)}
disabled={isSaving}
size="sm"
className="h-6 w-full text-xs"
variant="outline"
className="h-6 px-2 text-xs"
onClick={() => handleOpenEditDialog(false)}
>
<Settings className="mr-1 h-3 w-3" />
Настроить
<Plus className="mr-1.5 h-3 w-3" />
Внести данные
</Button>
</DialogTrigger>
<DialogContent className="max-w-sm">
@@ -280,115 +398,10 @@ export function VerificationConditionsRender({
</DialogContent>
</Dialog>
</div>
<div className="space-y-1">
{labData.conditionTypes.map(conditionType => {
const conditionValue =
dailyCondition!.conditions[conditionType.id]
return (
<div
key={conditionType.id}
className="flex items-center justify-between rounded bg-muted/30 px-2 py-1 text-xs"
>
<span className="truncate font-medium">
{conditionType.name}
</span>
<span className="ml-2 font-mono text-muted-foreground">
{conditionValue || '—'}
{conditionValue && conditionType.unit && (
<span className="ml-1">{conditionType.unit}</span>
)}
</span>
</div>
)
})}
</div>
</div>
) : (
<div className="space-y-2">
<div className="flex items-center gap-1.5 text-xs text-orange-600">
<AlertCircle className="h-3.5 w-3.5" />
<span className="font-medium">Данные не внесены</span>
</div>
<Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}>
<DialogTrigger asChild>
<Button
onClick={() => handleOpenEditDialog(true)}
disabled={isSaving}
size="sm"
className="h-6 w-full text-xs"
variant="outline"
>
<Plus className="mr-1.5 h-3 w-3" />
Внести данные
</Button>
</DialogTrigger>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle className="text-base">
Условия поверки
</DialogTitle>
</DialogHeader>
<div className="space-y-3">
<div className="space-y-1 text-xs text-muted-foreground">
<div>{selectedLab?.name}</div>
<div>
{new Date(selectedDate).toLocaleDateString('ru-RU')}
</div>
</div>
<div className="space-y-2">
{labData.conditionTypes.map(conditionType => (
<div key={conditionType.id} className="space-y-1">
<Label className="text-xs font-medium">
{conditionType.name}
{conditionType.unit && (
<span className="ml-1 font-normal text-muted-foreground">
({conditionType.unit})
</span>
)}
</Label>
<Input
value={editingConditions[conditionType.id] || ''}
onChange={e =>
handleConditionChange(
conditionType.id,
e.target.value
)
}
placeholder="Значение"
className="h-7 text-xs"
/>
</div>
))}
</div>
<div className="flex gap-2">
<Button
onClick={handleSaveConditions}
disabled={isSaving}
size="sm"
className="h-7 flex-1 text-xs"
>
{isSaving ? 'Сохранение...' : 'Сохранить'}
</Button>
<Button
variant="outline"
onClick={() => setEditDialogOpen(false)}
size="sm"
className="h-7 flex-1 text-xs"
>
Отмена
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
)}
</div>
</CardContent>
</Card>
)}
</div>
</CardContent>
</Card>
</div>
)
}

View File

@@ -17,6 +17,8 @@ export interface VerificationConditionsConfig {
conditionMappings?: ConditionMapping[]
// Показывать ли единицы измерения
showUnits?: boolean
// Целевые ячейки
targetCells?: any[]
}
// Значение элемента

View File

@@ -0,0 +1,33 @@
import { CellTarget } from '@/type/template'
import { Grid } from 'lucide-react'
interface CellsBadgeProps {
targetCells: CellTarget[]
className?: string
}
export const CellsBadge: React.FC<CellsBadgeProps> = ({
targetCells,
className = 'absolute right-0 top-0',
}) => {
if (!targetCells || targetCells.length === 0) {
return null
}
return (
<div className={`group/cells ${className}`}>
<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>
{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>
)
}

View File

@@ -37,8 +37,7 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
}
}
})
console.log('Инициализация формы:', initialData)
console.log(initialData)
if (Object.keys(initialData).length > 0) {
setFormData(initialData)
@@ -77,6 +76,8 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
})
engineRef.current.debouncedRecalc()
// Принудительно обновляем UI для отображения изменений
engineRef.current.updateRevision()
}
// Синхронизация с движком только когда он готов и есть данные
@@ -431,28 +432,5 @@ const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
/>
)
return (
<div className="relative space-y-3">
{/* Показываем индикатор ячеек для всех элементов */}
{element.targetCells && element.targetCells.length > 0 && (
<div className="group/cells absolute right-0 top-0">
<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>
)}
{renderElement()}
</div>
)
return <div className="relative space-y-3">{renderElement()}</div>
}