feat(webui): Add attribute editing dialog box and optimize editable attribute row component

This commit is contained in:
choizhang
2025-04-13 23:32:35 +08:00
parent 4900cf07d9
commit 5b1938e5b3
7 changed files with 173 additions and 80 deletions

View File

@@ -95,7 +95,6 @@ def create_graph_routes(rag, api_key: Optional[str] = None):
Dict: Updated entity information Dict: Updated entity information
""" """
try: try:
print(request.entity_name, request.updated_data, request.allow_rename)
result = await rag.aedit_entity( result = await rag.aedit_entity(
entity_name=request.entity_name, entity_name=request.entity_name,
updated_data=request.updated_data, updated_data=request.updated_data,

View File

@@ -1,12 +1,12 @@
import { useState, useEffect, useRef } from 'react' import { useState, useEffect } from 'react'
import { useRef } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import Text from '@/components/ui/Text' import Text from '@/components/ui/Text'
import Input from '@/components/ui/Input'
import { toast } from 'sonner' import { toast } from 'sonner'
import { updateEntity, updateRelation, checkEntityNameExists } from '@/api/lightrag' import { updateEntity, updateRelation, checkEntityNameExists } from '@/api/lightrag'
import { useGraphStore } from '@/stores/graph' import { useGraphStore } from '@/stores/graph'
import { PencilIcon } from 'lucide-react' import { PencilIcon } from 'lucide-react'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/Tooltip' import PropertyEditDialog from './PropertyEditDialog'
/** /**
* Interface for the EditablePropertyRow component props * Interface for the EditablePropertyRow component props
@@ -44,7 +44,6 @@ const EditablePropertyRow = ({
name, name,
value: initialValue, value: initialValue,
onClick, onClick,
tooltip,
entityId, entityId,
entityType, entityType,
sourceId, sourceId,
@@ -55,11 +54,11 @@ const EditablePropertyRow = ({
// Component state // Component state
const { t } = useTranslation() const { t } = useTranslation()
const [isEditing, setIsEditing] = useState(false) const [isEditing, setIsEditing] = useState(false)
const [editValue, setEditValue] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false) const [isSubmitting, setIsSubmitting] = useState(false)
const [currentValue, setCurrentValue] = useState(initialValue) const [currentValue, setCurrentValue] = useState(initialValue)
const inputRef = useRef<HTMLInputElement>(null) const inputRef = useRef<HTMLInputElement>(null)
/** /**
* Update currentValue when initialValue changes from parent * Update currentValue when initialValue changes from parent
*/ */
@@ -72,7 +71,6 @@ const EditablePropertyRow = ({
*/ */
useEffect(() => { useEffect(() => {
if (isEditing) { if (isEditing) {
setEditValue(String(currentValue))
// Focus the input element when entering edit mode with a small delay // Focus the input element when entering edit mode with a small delay
// to ensure the input is rendered before focusing // to ensure the input is rendered before focusing
setTimeout(() => { setTimeout(() => {
@@ -82,7 +80,7 @@ const EditablePropertyRow = ({
} }
}, 50) }, 50)
} }
}, [isEditing, currentValue]) }, [isEditing])
/** /**
* Get translated property name from i18n * Get translated property name from i18n
@@ -95,26 +93,20 @@ const EditablePropertyRow = ({
} }
/** /**
* Handle double-click event to enter edit mode * Handle edit icon click to open dialog
*/ */
const handleDoubleClick = () => { const handleEditClick = () => {
if (isEditable && !isEditing) { if (isEditable && !isEditing) {
setIsEditing(true) setIsEditing(true)
} }
} }
/** /**
* Handle keyboard events in the input field * Handle dialog close without saving
* - Enter: Save changes
* - Escape: Cancel editing
*/ */
const handleKeyDown = (e: React.KeyboardEvent) => { const handleCancel = () => {
if (e.key === 'Enter') {
handleSave()
} else if (e.key === 'Escape') {
setIsEditing(false) setIsEditing(false)
} }
}
/** /**
* Update node in the graph visualization after API update * Update node in the graph visualization after API update
@@ -300,12 +292,12 @@ const EditablePropertyRow = ({
* Save changes to the property value * Save changes to the property value
* Updates both the API and the graph visualization * Updates both the API and the graph visualization
*/ */
const handleSave = async () => { const handleSave = async (value: string) => {
// Prevent duplicate submissions // Prevent duplicate submissions
if (isSubmitting) return if (isSubmitting) return
// Skip if value hasn't changed // Skip if value hasn't changed
if (editValue === String(currentValue)) { if (value === String(currentValue)) {
setIsEditing(false) setIsEditing(false)
return return
} }
@@ -315,44 +307,44 @@ const EditablePropertyRow = ({
try { try {
// Handle node property updates // Handle node property updates
if (entityType === 'node' && entityId) { if (entityType === 'node' && entityId) {
let updatedData = { [name]: editValue } let updatedData = { [name]: value }
// Special handling for entity_id (name) changes // Special handling for entity_id (name) changes
if (name === 'entity_id') { if (name === 'entity_id') {
// Check if the new name already exists // Check if the new name already exists
const exists = await checkEntityNameExists(editValue) const exists = await checkEntityNameExists(value)
if (exists) { if (exists) {
toast.error(t('graphPanel.propertiesView.errors.duplicateName')) toast.error(t('graphPanel.propertiesView.errors.duplicateName'))
setIsSubmitting(false) setIsSubmitting(false)
return return
} }
// For entity_id, we update entity_name in the API // For entity_id, we update entity_name in the API
updatedData = { 'entity_name': editValue } updatedData = { 'entity_name': value }
} }
// Update entity in API // Update entity in API
await updateEntity(entityId, updatedData, true) await updateEntity(entityId, updatedData, true)
// Update graph visualization // Update graph visualization
await updateGraphNode(entityId, name, editValue) await updateGraphNode(entityId, name, value)
toast.success(t('graphPanel.propertiesView.success.entityUpdated')) toast.success(t('graphPanel.propertiesView.success.entityUpdated'))
} }
// Handle edge property updates // Handle edge property updates
else if (entityType === 'edge' && sourceId && targetId) { else if (entityType === 'edge' && sourceId && targetId) {
const updatedData = { [name]: editValue } const updatedData = { [name]: value }
// Update relation in API // Update relation in API
await updateRelation(sourceId, targetId, updatedData) await updateRelation(sourceId, targetId, updatedData)
// Update graph visualization // Update graph visualization
await updateGraphEdge(sourceId, targetId, name, editValue) await updateGraphEdge(sourceId, targetId, name, value)
toast.success(t('graphPanel.propertiesView.success.relationUpdated')) toast.success(t('graphPanel.propertiesView.success.relationUpdated'))
} }
// Update local state // Update local state
setIsEditing(false) setIsEditing(false)
setCurrentValue(editValue) setCurrentValue(value)
// Notify parent component if callback provided // Notify parent component if callback provided
if (onValueChange) { if (onValueChange) {
onValueChange(editValue) onValueChange(value)
} }
} catch (error) { } catch (error) {
console.error('Error updating property:', error) console.error('Error updating property:', error)
@@ -364,58 +356,43 @@ const EditablePropertyRow = ({
/** /**
* Render the property row with edit functionality * Render the property row with edit functionality
* Shows property name, edit icon, and either the editable input or the current value * Shows property name, edit icon, and the current value
*/ */
return ( return (
<div className="flex items-center gap-1" onDoubleClick={handleDoubleClick}> <div className="flex items-center gap-1">
{/* Property name with translation */} {/* Property name with translation */}
<span className="text-primary/60 tracking-wide whitespace-nowrap"> <span className="text-primary/60 tracking-wide whitespace-nowrap">
{getPropertyNameTranslation(name)} {getPropertyNameTranslation(name)}
</span> </span>
{/* Edit icon with tooltip */} {/* Edit icon without tooltip */}
<TooltipProvider delayDuration={200}>
<Tooltip>
<TooltipTrigger asChild>
<div> <div>
<PencilIcon <PencilIcon
className="h-3 w-3 text-gray-500 hover:text-gray-700 cursor-pointer" className="h-3 w-3 text-gray-500 hover:text-gray-700 cursor-pointer"
onClick={() => setIsEditing(true)} onClick={handleEditClick}
/> />
</div> </div>:
</TooltipTrigger>
<TooltipContent side="top">
{t('graphPanel.propertiesView.doubleClickToEdit')}
</TooltipContent>
</Tooltip>
</TooltipProvider>:
{/* Conditional rendering based on edit state */} {/* Text display */}
{isEditing ? (
// Input field for editing
<Input
ref={inputRef}
type="text"
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
onKeyDown={handleKeyDown}
onBlur={handleSave}
className="h-6 text-xs"
disabled={isSubmitting}
/>
) : (
// Text display when not editing
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<Text <Text
className="hover:bg-primary/20 rounded p-1 overflow-hidden text-ellipsis" className="hover:bg-primary/20 rounded p-1 overflow-hidden text-ellipsis"
tooltipClassName="max-w-80" tooltipClassName="max-w-80"
text={currentValue} text={currentValue}
tooltip={tooltip || (typeof currentValue === 'string' ? currentValue : JSON.stringify(currentValue, null, 2))}
side="left" side="left"
onClick={onClick} onClick={onClick}
/> />
</div> </div>
)}
{/* Edit dialog */}
<PropertyEditDialog
isOpen={isEditing}
onClose={handleCancel}
onSave={handleSave}
propertyName={name}
initialValue={String(currentValue)}
isSubmitting={isSubmitting}
/>
</div> </div>
) )
} }

View File

@@ -0,0 +1,105 @@
import { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter
} from '@/components/ui/Dialog'
import Button from '@/components/ui/Button'
import Input from '@/components/ui/Input'
interface PropertyEditDialogProps {
isOpen: boolean
onClose: () => void
onSave: (value: string) => void
propertyName: string
initialValue: string
isSubmitting?: boolean
}
/**
* Dialog component for editing property values
* Provides a modal with a title, multi-line text input, and save/cancel buttons
*/
const PropertyEditDialog = ({
isOpen,
onClose,
onSave,
propertyName,
initialValue,
isSubmitting = false
}: PropertyEditDialogProps) => {
const { t } = useTranslation()
const [value, setValue] = useState('')
// Initialize value when dialog opens
useEffect(() => {
if (isOpen) {
setValue(initialValue)
}
}, [isOpen, initialValue])
// Get translated property name
const getPropertyNameTranslation = (name: string) => {
const translationKey = `graphPanel.propertiesView.node.propertyNames.${name}`
const translation = t(translationKey)
return translation === translationKey ? name : translation
}
const handleSave = () => {
if (value.trim() !== '') {
onSave(value)
onClose()
}
}
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-md" aria-describedby="property-edit-description">
<DialogHeader>
<DialogTitle>
{t('graphPanel.propertiesView.editProperty', {
property: getPropertyNameTranslation(propertyName)
})}
</DialogTitle>
<p id="property-edit-description" className="text-sm text-muted-foreground">
{t('graphPanel.propertiesView.editPropertyDescription')}
</p>
</DialogHeader>
{/* Multi-line text input using textarea */}
<div className="grid gap-4 py-4">
<textarea
value={value}
onChange={(e) => setValue(e.target.value)}
rows={5}
className="border-input focus-visible:ring-ring flex w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-sm transition-colors focus-visible:ring-1 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
disabled={isSubmitting}
/>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={onClose}
disabled={isSubmitting}
>
{t('common.cancel')}
</Button>
<Button
type="button"
onClick={handleSave}
disabled={isSubmitting}
>
{t('common.save')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default PropertyEditDialog

View File

@@ -33,7 +33,8 @@
"guestMode": "وضع بدون تسجيل دخول" "guestMode": "وضع بدون تسجيل دخول"
}, },
"common": { "common": {
"cancel": "إلغاء" "cancel": "إلغاء",
"save": "حفظ"
}, },
"documentPanel": { "documentPanel": {
"clearDocuments": { "clearDocuments": {
@@ -236,12 +237,14 @@
"vectorStorage": "تخزين المتجهات" "vectorStorage": "تخزين المتجهات"
}, },
"propertiesView": { "propertiesView": {
"editProperty": "تعديل {{property}}",
"editPropertyDescription": "قم بتحرير قيمة الخاصية في منطقة النص أدناه.",
"errors": { "errors": {
"duplicateName": "اسم العقدة موجود بالفعل", "duplicateName": "اسم العقدة موجود بالفعل",
"updateFailed": "فشل تحديث العقدة", "updateFailed": "فشل تحديث العقدة",
"tryAgainLater": "يرجى المحاولة مرة أخرى لاحقًا" "tryAgainLater": "يرجى المحاولة مرة أخرى لاحقًا"
}, },
"doubleClickToEdit": "انقر نقرًا مزدوجًا للتعديل",
"success": { "success": {
"entityUpdated": "تم تحديث العقدة بنجاح", "entityUpdated": "تم تحديث العقدة بنجاح",
"relationUpdated": "تم تحديث العلاقة بنجاح" "relationUpdated": "تم تحديث العلاقة بنجاح"

View File

@@ -33,7 +33,8 @@
"guestMode": "Login Free" "guestMode": "Login Free"
}, },
"common": { "common": {
"cancel": "Cancel" "cancel": "Cancel",
"save": "Save"
}, },
"documentPanel": { "documentPanel": {
"clearDocuments": { "clearDocuments": {
@@ -235,12 +236,14 @@
"vectorStorage": "Vector Storage" "vectorStorage": "Vector Storage"
}, },
"propertiesView": { "propertiesView": {
"editProperty": "Edit {{property}}",
"editPropertyDescription": "Edit the property value in the text area below.",
"errors": { "errors": {
"duplicateName": "Node name already exists", "duplicateName": "Node name already exists",
"updateFailed": "Failed to update node", "updateFailed": "Failed to update node",
"tryAgainLater": "Please try again later" "tryAgainLater": "Please try again later"
}, },
"doubleClickToEdit": "Double click to edit",
"success": { "success": {
"entityUpdated": "Node updated successfully", "entityUpdated": "Node updated successfully",
"relationUpdated": "Relation updated successfully" "relationUpdated": "Relation updated successfully"

View File

@@ -33,7 +33,8 @@
"guestMode": "Mode sans connexion" "guestMode": "Mode sans connexion"
}, },
"common": { "common": {
"cancel": "Annuler" "cancel": "Annuler",
"save": "Sauvegarder"
}, },
"documentPanel": { "documentPanel": {
"clearDocuments": { "clearDocuments": {
@@ -236,6 +237,8 @@
"vectorStorage": "Stockage vectoriel" "vectorStorage": "Stockage vectoriel"
}, },
"propertiesView": { "propertiesView": {
"editProperty": "Modifier {{property}}",
"editPropertyDescription": "Modifiez la valeur de la propriété dans la zone de texte ci-dessous.",
"errors": { "errors": {
"duplicateName": "Le nom du nœud existe déjà", "duplicateName": "Le nom du nœud existe déjà",
"updateFailed": "Échec de la mise à jour du nœud", "updateFailed": "Échec de la mise à jour du nœud",

View File

@@ -33,7 +33,8 @@
"guestMode": "无需登陆" "guestMode": "无需登陆"
}, },
"common": { "common": {
"cancel": "取消" "cancel": "取消",
"save": "保存"
}, },
"documentPanel": { "documentPanel": {
"clearDocuments": { "clearDocuments": {
@@ -236,12 +237,14 @@
"vectorStorage": "向量存储" "vectorStorage": "向量存储"
}, },
"propertiesView": { "propertiesView": {
"editProperty": "编辑{{property}}",
"editPropertyDescription": "在下方文本区域编辑属性值。",
"errors": { "errors": {
"duplicateName": "节点名称已存在", "duplicateName": "节点名称已存在",
"updateFailed": "更新节点失败", "updateFailed": "更新节点失败",
"tryAgainLater": "请稍后重试" "tryAgainLater": "请稍后重试"
}, },
"doubleClickToEdit": "双击编辑",
"success": { "success": {
"entityUpdated": "节点更新成功", "entityUpdated": "节点更新成功",
"relationUpdated": "关系更新成功" "relationUpdated": "关系更新成功"