import React, { useState } from 'react'; import { PencilIcon, CheckIcon, XMarkIcon } from '@heroicons/react/24/outline'; interface WeightEditorProps { /** 当前权重值 */ weight: number; /** 权重更新回调 */ onWeightUpdate: (newWeight: number) => Promise; /** 是否禁用编辑 */ disabled?: boolean; /** 自定义样式类名 */ className?: string; } /** * 权重编辑器组件 * 遵循前端开发规范的组件设计,提供内联编辑权重的功能 */ export const WeightEditor: React.FC = ({ weight, onWeightUpdate, disabled = false, className = '', }) => { const [isEditing, setIsEditing] = useState(false); const [editingWeight, setEditingWeight] = useState(weight); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const handleStartEdit = () => { if (disabled) return; setIsEditing(true); setEditingWeight(weight); setError(null); }; const handleSave = async () => { if (editingWeight < 0 || editingWeight > 100) { setError('权重值必须在 0-100 之间'); return; } setLoading(true); setError(null); try { await onWeightUpdate(editingWeight); setIsEditing(false); } catch (err) { setError(err instanceof Error ? err.message : '更新权重失败'); } finally { setLoading(false); } }; const handleCancel = () => { setIsEditing(false); setEditingWeight(weight); setError(null); }; const handleKeyPress = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { handleSave(); } else if (e.key === 'Escape') { handleCancel(); } }; if (!isEditing) { return (
权重: {weight} {!disabled && ( )}
); } return (
setEditingWeight(parseInt(e.target.value) || 0)} onKeyPress={handleKeyPress} disabled={loading} className="w-full px-2 py-1 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:opacity-50" placeholder="输入权重值" autoFocus />
{error && (
⚠️ {error}
)} {loading && (
正在保存权重...
)}
💡 权重越高的分类在按顺序匹配时优先级越高
); };