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

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

@@ -32,6 +32,7 @@
"@types/lodash.isequal": "^4.5.8", "@types/lodash.isequal": "^4.5.8",
"@types/react-grid-layout": "^1.3.5", "@types/react-grid-layout": "^1.3.5",
"@types/react-window": "^1.8.8", "@types/react-window": "^1.8.8",
"@types/uuid": "^10.0.0",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"date-fns": "^4.1.0", "date-fns": "^4.1.0",
@@ -50,7 +51,8 @@
"redux": "^4.2.1", "redux": "^4.2.1",
"tailwind-merge": "^3.3.1", "tailwind-merge": "^3.3.1",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"use-debounce": "^10.0.5" "use-debounce": "^10.0.5",
"uuid": "^11.1.0"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^24.0.15", "@types/node": "^24.0.15",

View File

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

View File

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

View File

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

View File

@@ -9,6 +9,7 @@ import {
SelectValue, SelectValue,
} from '@/component/ui/select' } from '@/component/ui/select'
import { ElementDefinition } from '@/entitiy/element/model/interface' import { ElementDefinition } from '@/entitiy/element/model/interface'
import { CellsBadge } from '@/entitiy/element/ui/cellsBadge'
import { useToast } from '@/lib/hooks/useToast' import { useToast } from '@/lib/hooks/useToast'
import { ElementOption } from '@/type/template' import { ElementOption } from '@/type/template'
import { ChevronDown, Plus, Trash2 } from 'lucide-react' import { ChevronDown, Plus, Trash2 } from 'lucide-react'
@@ -200,6 +201,10 @@ export const selectDefinition: ElementDefinition<SelectConfig, string> = {
const currentValue = value || localStorage.getItem(storageKey) || '' const currentValue = value || localStorage.getItem(storageKey) || ''
return ( return (
<div className="relative">
{/* Бейдж ячеек */}
<CellsBadge targetCells={config.targetCells} />
<Select value={currentValue} onValueChange={handleValueChange}> <Select value={currentValue} onValueChange={handleValueChange}>
<SelectTrigger className="w-full min-w-32"> <SelectTrigger className="w-full min-w-32">
<SelectValue <SelectValue
@@ -218,6 +223,7 @@ export const selectDefinition: ElementDefinition<SelectConfig, string> = {
</SelectGroup> </SelectGroup>
</SelectContent> </SelectContent>
</Select> </Select>
</div>
) )
}, },
} }

View File

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

View File

@@ -1,13 +1,44 @@
import { Input } from '@/component/ui/input' import { Input } from '@/component/ui/input'
import { ElementDefinition } from '@/entitiy/element/model/interface' import { ElementDefinition } from '@/entitiy/element/model/interface'
import { CellsBadge } from '@/entitiy/element/ui/cellsBadge'
import { ExtraSettingsBadge } from '@/entitiy/element/ui/extraSettingsBadge' 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 { interface TextConfig {
placeholder?: string placeholder?: string
required?: boolean required?: boolean
targetCells: any[] targetCells: any[]
name?: string 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> = { export const textDefinition: ElementDefinition<TextConfig, string> = {
@@ -21,6 +52,14 @@ export const textDefinition: ElementDefinition<TextConfig, string> = {
targetCells: [], targetCells: [],
name: '', name: '',
}, },
getInitialValue: config => {
// Используем id из config (который приходит из TemplateElement)
if (config.id) {
const key = getLocalStorageKey('text', config.id)
return getFromLocalStorage(key)
}
return ''
},
mapToCells: config => config.targetCells || [], mapToCells: config => config.targetCells || [],
mapToCellValues: (config, value) => { mapToCellValues: (config, value) => {
const cells = config.targetCells || [] const cells = config.targetCells || []
@@ -38,20 +77,114 @@ export const textDefinition: ElementDefinition<TextConfig, string> = {
<Input placeholder={config.placeholder} className="w-full" /> <Input placeholder={config.placeholder} className="w-full" />
</div> </div>
), ),
Render: ({ config, value, onChange }) => ( Render: ({ config, value, onChange }) => {
<div className="space-y-1"> 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 && ( {config.name && (
<label className="text-sm font-medium text-gray-900"> <label className="text-sm font-medium text-gray-900">
{config.name} {config.name}
{config.required && <span className="ml-1 text-red-500">*</span>} {config.required && <span className="ml-1 text-red-500">*</span>}
</label> </label>
)} )}
{/* Поле ввода */}
<Input <Input
placeholder={config.placeholder} placeholder={config.placeholder}
value={value || ''} value={currentValue}
onChange={e => onChange?.(e.target.value)} onChange={e => handleValueChange(e.target.value)}
required={config.required} required={config.required}
/> />
</div> </div>
), )
},
} }

View File

@@ -9,6 +9,7 @@ import {
} from '@/component/ui/dialog' } from '@/component/ui/dialog'
import { Input } from '@/component/ui/input' import { Input } from '@/component/ui/input'
import { Label } from '@/component/ui/label' import { Label } from '@/component/ui/label'
import { CellsBadge } from '@/entitiy/element/ui/cellsBadge'
import { import {
AlertCircle, AlertCircle,
Building2, Building2,
@@ -175,11 +176,17 @@ export function VerificationConditionsRender({
} }
return ( return (
<div className="relative">
{/* Бейдж ячеек */}
<CellsBadge targetCells={config.targetCells || []} />
<Card> <Card>
<CardHeader className="px-3 pb-1 pt-2"> <CardHeader className="px-3 pb-1 pt-2">
<CardTitle className="flex items-center gap-1.5 text-sm"> <CardTitle className="flex items-center gap-1.5 text-sm">
<Building2 className="h-3.5 w-3.5" /> <Building2 className="h-3.5 w-3.5" />
<span className="truncate">{selectedLab?.name || 'Лаборатория'}</span> <span className="truncate">
{selectedLab?.name || 'Лаборатория'}
</span>
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
@@ -206,7 +213,10 @@ export function VerificationConditionsRender({
<span className="font-medium">Данные внесены</span> <span className="font-medium">Данные внесены</span>
</div> </div>
<Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}> <Dialog
open={editDialogOpen}
onOpenChange={setEditDialogOpen}
>
<DialogTrigger asChild> <DialogTrigger asChild>
<Button <Button
size="sm" size="sm"
@@ -244,7 +254,9 @@ export function VerificationConditionsRender({
)} )}
</Label> </Label>
<Input <Input
value={editingConditions[conditionType.id] || ''} value={
editingConditions[conditionType.id] || ''
}
onChange={e => onChange={e =>
handleConditionChange( handleConditionChange(
conditionType.id, conditionType.id,
@@ -390,5 +402,6 @@ export function VerificationConditionsRender({
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
</div>
) )
} }

View File

@@ -17,6 +17,8 @@ export interface VerificationConditionsConfig {
conditionMappings?: ConditionMapping[] conditionMappings?: ConditionMapping[]
// Показывать ли единицы измерения // Показывать ли единицы измерения
showUnits?: boolean 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) { if (Object.keys(initialData).length > 0) {
setFormData(initialData) setFormData(initialData)
@@ -77,6 +76,8 @@ const ProtocolForm: FC<ProtocolFormProps> = ({ template, onSave, onBack }) => {
}) })
engineRef.current.debouncedRecalc() engineRef.current.debouncedRecalc()
// Принудительно обновляем UI для отображения изменений
engineRef.current.updateRevision()
} }
// Синхронизация с движком только когда он готов и есть данные // Синхронизация с движком только когда он готов и есть данные
@@ -431,28 +432,5 @@ const FormElement: FC<FormElementProps> = ({ element, value, onChange }) => {
/> />
) )
return ( return <div className="relative space-y-3">{renderElement()}</div>
<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>
)
} }

View File

@@ -982,6 +982,11 @@
resolved "https://registry.yarnpkg.com/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz#b6725d5f4af24ace33b36fafd295136e75509f43" resolved "https://registry.yarnpkg.com/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz#b6725d5f4af24ace33b36fafd295136e75509f43"
integrity sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA== integrity sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA==
"@types/uuid@^10.0.0":
version "10.0.0"
resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-10.0.0.tgz#e9c07fe50da0f53dc24970cca94d619ff03f6f6d"
integrity sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==
"@typescript-eslint/eslint-plugin@^5.59.0": "@typescript-eslint/eslint-plugin@^5.59.0":
version "5.62.0" version "5.62.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.62.0.tgz#aeef0328d172b9e37d9bab6dbc13b87ed88977db" resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.62.0.tgz#aeef0328d172b9e37d9bab6dbc13b87ed88977db"
@@ -4055,6 +4060,11 @@ util@^0.10.3:
dependencies: dependencies:
inherits "2.0.3" inherits "2.0.3"
uuid@^11.1.0:
version "11.1.0"
resolved "https://registry.yarnpkg.com/uuid/-/uuid-11.1.0.tgz#9549028be1753bb934fc96e2bca09bb4105ae912"
integrity sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==
vite@^4.3.9: vite@^4.3.9:
version "4.5.14" version "4.5.14"
resolved "https://registry.yarnpkg.com/vite/-/vite-4.5.14.tgz#2e652bc1d898265d987d6543ce866ecd65fa4086" resolved "https://registry.yarnpkg.com/vite/-/vite-4.5.14.tgz#2e652bc1d898265d987d6543ce866ecd65fa4086"