This commit is contained in:
freedakgmail
2025-11-30 13:09:52 +08:00
parent 0281885f73
commit 89f1e061d4
146 changed files with 692 additions and 356 deletions
+100 -7
View File
@@ -2,7 +2,7 @@
import type React from "react"
import { useState } from "react"
import { useState, useEffect } from "react"
import type { FamilyMember, FamilyPhoto } from "@/types/family"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
@@ -93,7 +93,62 @@ export function MemberForm({ initialData, existingMembers = [], onSubmit, onCanc
const [errors, setErrors] = useState<string[]>([])
// 监听 initialData 变化,更新 formData
useEffect(() => {
if (!initialData) return
setFormData((prev) => {
const normalizedPhotos: FamilyPhoto[] = initialData.photos && initialData.photos.length > 0
? initialData.photos
: (initialData.photoIds || []).map((url) => ({
url,
uploadedAt: initialData.updatedAt || new Date().toISOString(),
}))
const newMotherId = initialData.motherId !== undefined ? initialData.motherId : prev.motherId
console.log('Calculating new motherId:', {
initial: initialData.motherId,
prev: prev.motherId,
result: newMotherId,
hasInitialMother: initialData.motherId !== undefined
})
return {
...prev,
...initialData,
// 确保特定字段被正确更新
gender: initialData.gender ? (initialData.gender.toUpperCase() as "MALE" | "FEMALE") : prev.gender,
spouseIds: initialData.spouseIds || prev.spouseIds || [],
childrenIds: initialData.childrenIds || prev.childrenIds || [],
tags: initialData.tags || prev.tags || [],
fatherId: initialData.fatherId || prev.fatherId,
motherId: newMotherId,
photos: initialData.photos ? normalizedPhotos : prev.photos,
photoIds: initialData.photoIds || (initialData.photos ? normalizedPhotos.map((p) => p.url) : prev.photoIds),
}
})
}, [initialData])
const handleChange = (field: keyof FamilyMember, value: any) => {
console.log('handleChange:', field, value)
// 防御性检查:防止 Select 组件意外清空 initialData 中已有的值
// 这可能是由于 Select 组件在某些情况下(如选项尚未完全渲染)触发了无效的 onChange
if ((field === 'motherId' || field === 'fatherId') && !value) {
const initialValue = initialData?.[field]
const currentValue = formData[field]
// 只有当当前值等于初始值且尝试清空时才阻止
if (initialValue && currentValue === initialValue) {
console.warn(`Prevented accidental clearing of ${field}`)
return
}
// 如果当前值不为空,但尝试清空为空字符串,也阻止(因为Select组件可能发送空字符串而不是undefined)
if (currentValue && value === '') {
console.warn(`Prevented clearing of ${field} to empty string`)
return
}
}
setFormData((prev) => {
const newData = { ...prev, [field]: value }
@@ -108,7 +163,11 @@ export function MemberForm({ initialData, existingMembers = [], onSubmit, onCanc
if (father && father.spouseIds && father.spouseIds.length > 0) {
// 找到父亲的配偶(母亲)
const motherId = father.spouseIds[0]
newData.motherId = motherId
// 只有当前母亲ID为空时才自动设置
if (!newData.motherId) {
newData.motherId = motherId
console.log('Auto-set mother from father:', { fatherId: value, motherId })
}
}
}
@@ -118,7 +177,11 @@ export function MemberForm({ initialData, existingMembers = [], onSubmit, onCanc
if (mother && mother.spouseIds && mother.spouseIds.length > 0) {
// 找到母亲的配偶(父亲)
const fatherId = mother.spouseIds[0]
newData.fatherId = fatherId
// 只有当前父亲ID为空时才自动设置
if (!newData.fatherId) {
newData.fatherId = fatherId
console.log('Auto-set father from mother:', { motherId: value, fatherId })
}
}
}
@@ -274,6 +337,13 @@ export function MemberForm({ initialData, existingMembers = [], onSubmit, onCanc
}
const potentialRelatives = existingMembers.filter((m) => m.id !== formData.id)
// 调试日志
console.log('MemberForm render:', {
motherId: formData.motherId,
existingMembersCount: existingMembers.length,
motherInList: existingMembers.find(m => m.id === formData.motherId)
})
return (
<form onSubmit={handleSubmit} className="space-y-8 max-w-4xl mx-auto p-6">
@@ -373,7 +443,11 @@ export function MemberForm({ initialData, existingMembers = [], onSubmit, onCanc
<div className="flex gap-2">
<Select
value={formData.fatherId || "none"}
onValueChange={(val) => handleChange("fatherId", val === "none" ? undefined : val)}
onValueChange={(val) => {
const newValue = val === "none" ? undefined : val
console.log('Father select change:', { val, newValue })
handleChange("fatherId", newValue)
}}
>
<SelectTrigger className="flex-1">
<SelectValue placeholder="选择父亲" />
@@ -381,7 +455,11 @@ export function MemberForm({ initialData, existingMembers = [], onSubmit, onCanc
<SelectContent>
<SelectItem value="none"></SelectItem>
{potentialRelatives
.filter((m) => m.gender === "MALE" && m.generation === (formData.generation || 1) - 1)
.filter((m) => {
// 如果已经被选中,必须显示
if (m.id === formData.fatherId) return true
return m.gender === "MALE" && m.generation === (formData.generation || 1) - 1
})
.map((m) => (
<SelectItem key={m.id} value={m.id}>
<MemberNameWithStatus
@@ -416,7 +494,11 @@ export function MemberForm({ initialData, existingMembers = [], onSubmit, onCanc
<div className="flex gap-2">
<Select
value={formData.motherId || "none"}
onValueChange={(val) => handleChange("motherId", val === "none" ? undefined : val)}
onValueChange={(val) => {
const newValue = val === "none" ? undefined : val
console.log('Mother select change:', { val, newValue })
handleChange("motherId", newValue)
}}
>
<SelectTrigger className="flex-1">
<SelectValue placeholder="选择母亲" />
@@ -424,7 +506,18 @@ export function MemberForm({ initialData, existingMembers = [], onSubmit, onCanc
<SelectContent>
<SelectItem value="none"></SelectItem>
{potentialRelatives
.filter((m) => m.gender === "FEMALE" && m.generation === (formData.generation || 1) - 1)
.filter((m) => {
// 如果已经被选中,必须显示
if (m.id === formData.motherId) {
console.log('Mother already selected, showing:', { id: m.id, name: m.fullName })
return true
}
const isMatch = m.gender === "FEMALE" && m.generation === (formData.generation || 1) - 1
if (isMatch) {
console.log('Mother match found:', { id: m.id, name: m.fullName, gender: m.gender, generation: m.generation })
}
return isMatch
})
.map((m) => (
<SelectItem key={m.id} value={m.id}>
<MemberNameWithStatus
+198 -7
View File
@@ -3,8 +3,18 @@
import type { FamilyMember } from "@/types/family"
import { cn } from "@/lib/utils"
import { useAvatarCache } from "@/hooks/use-avatar-cache"
import { CircleUser, CircleUserRound, Heart } from "lucide-react"
import { CircleUser, CircleUserRound, Heart, UserPlus, Users, Baby } from "lucide-react"
import { MemberNameWithStatus } from "@/components/member-name-with-status"
import { useRouter } from "next/navigation"
import { useFamily } from "@/context/family-context"
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuLabel,
ContextMenuTrigger,
} from "@/components/ui/context-menu"
interface FamilyNodeProps {
member: FamilyMember
@@ -15,6 +25,7 @@ interface FamilyNodeProps {
isHighlighted?: boolean
relationMode?: boolean
isSelected?: boolean
canEdit?: boolean
}
// 格式化日期显示(只显示年份)
@@ -42,8 +53,28 @@ function calculateAge(birthDate?: string, deathDate?: string): number | null {
}
// 单个人员卡片组件
function PersonCard({ member, isRoot, isSpouse, onSelect, isHighlighted, relationMode, isSelected }: { member: FamilyMember; isRoot?: boolean; isSpouse?: boolean; onSelect?: (member: FamilyMember) => void; isHighlighted?: boolean; relationMode?: boolean; isSelected?: boolean }) {
function PersonCard({
member,
isRoot,
isSpouse,
onSelect,
isHighlighted,
relationMode,
isSelected,
canEdit = true
}: {
member: FamilyMember
isRoot?: boolean
isSpouse?: boolean
onSelect?: (member: FamilyMember) => void
isHighlighted?: boolean
relationMode?: boolean
isSelected?: boolean
canEdit?: boolean
}) {
const { avatarUrl: avatarBlobUrl } = useAvatarCache(member?.avatarUrl)
const router = useRouter()
const { currentTree } = useFamily()
const birthYear = formatYear(member.birthDate)
const deathYear = formatYear(member.deathDate)
@@ -60,8 +91,92 @@ function PersonCard({ member, isRoot, isSpouse, onSelect, isHighlighted, relatio
? `享年${age}`
: `${age}`
: ''
// 判断可以添加的关系
const canAddFather = !member.fatherId
const canAddMother = !member.motherId
const canAddSpouse = true // 配偶总是可以添加
const canAddChild = true // 子女总是可以添加
// 构建新增成员的 URL
const buildAddUrl = (type: 'father' | 'mother' | 'spouse' | 'child') => {
const params = new URLSearchParams()
if (currentTree?.id) {
params.set('treeId', currentTree.id)
}
switch (type) {
case 'father':
params.set('childId', member.id)
params.set('gender', 'MALE')
params.set('generation', (member.generation - 1).toString())
// 如果已有母亲,设为配偶
if (member.motherId) {
params.set('spouseId', member.motherId)
}
break
case 'mother':
params.set('childId', member.id)
params.set('gender', 'FEMALE')
params.set('generation', (member.generation - 1).toString())
// 如果已有父亲,设为配偶
if (member.fatherId) {
params.set('spouseId', member.fatherId)
}
break
case 'spouse':
params.set('spouseId', member.id)
params.set('generation', member.generation.toString())
// 配偶性别与当前成员相反
params.set('gender', member.gender === 'MALE' ? 'FEMALE' : 'MALE')
// 如果当前成员有子女,将他们也作为新配偶的子女
if (member.childrenIds && member.childrenIds.length > 0) {
// 传递所有子女ID
member.childrenIds.forEach(id => {
params.append('childrenIds', id)
})
}
break
case 'child':
// 根据当前成员性别设置父/母
if (member.gender === 'MALE') {
params.set('fatherId', member.id)
// 如果父亲有配偶,设置配偶为母亲
if (member.spouseIds && member.spouseIds.length > 0) {
params.set('motherId', member.spouseIds[0])
}
} else {
params.set('motherId', member.id)
// 如果母亲有配偶,设置配偶为父亲
if (member.spouseIds && member.spouseIds.length > 0) {
params.set('fatherId', member.spouseIds[0])
}
}
params.set('generation', (member.generation + 1).toString())
break
}
return `/members/new?${params.toString()}`
}
const handleAddMember = (type: 'father' | 'mother' | 'spouse' | 'child') => {
const url = buildAddUrl(type)
console.log('handleAddMember called:', type, url)
// 使用 setTimeout 延迟跳转,确保菜单关闭后再执行
setTimeout(() => {
console.log('Navigating to:', url)
window.location.href = url
}, 100)
}
// 是否显示右键菜单(有可添加的选项时才显示)
const hasAddOptions = canEdit && (canAddFather || canAddMother || canAddSpouse || canAddChild)
return (
// 调试日志
console.log('PersonCard render:', member.fullName, { canEdit, hasAddOptions, relationMode })
const cardContent = (
<div
className={cn(
"family-node-card relative flex flex-col items-center gap-2 p-3 rounded-lg transition-all cursor-pointer hover:scale-105 shadow-sm w-32",
@@ -126,24 +241,100 @@ function PersonCard({ member, isRoot, isSpouse, onSelect, isHighlighted, relatio
</div>
</div>
)
// 如果没有可添加的选项或在关系模式下,直接返回卡片
if (!hasAddOptions || relationMode) {
return cardContent
}
// 有可添加选项时,包裹右键菜单
return (
<ContextMenu>
<ContextMenuTrigger>
{cardContent}
</ContextMenuTrigger>
<ContextMenuContent className="w-48">
<ContextMenuLabel className="text-xs text-muted-foreground">
{member.fullName}
</ContextMenuLabel>
<ContextMenuSeparator />
{canAddFather && (
<ContextMenuItem
className="gap-2 cursor-pointer"
onPointerDown={(e) => {
e.preventDefault()
handleAddMember('father')
}}
>
<UserPlus className="h-4 w-4 text-blue-500" />
</ContextMenuItem>
)}
{canAddMother && (
<ContextMenuItem
className="gap-2 cursor-pointer"
onPointerDown={(e) => {
e.preventDefault()
handleAddMember('mother')
}}
>
<UserPlus className="h-4 w-4 text-pink-500" />
</ContextMenuItem>
)}
{(canAddFather || canAddMother) && (canAddSpouse || canAddChild) && (
<ContextMenuSeparator />
)}
{canAddSpouse && (
<ContextMenuItem
className="gap-2 cursor-pointer"
onPointerDown={(e) => {
e.preventDefault()
handleAddMember('spouse')
}}
>
<Users className="h-4 w-4 text-red-500" />
</ContextMenuItem>
)}
{canAddChild && (
<ContextMenuItem
className="gap-2 cursor-pointer"
onPointerDown={(e) => {
e.preventDefault()
handleAddMember('child')
}}
>
<Baby className="h-4 w-4 text-green-500" />
</ContextMenuItem>
)}
</ContextMenuContent>
</ContextMenu>
)
}
export function FamilyNode({ member, spouse, spouses, isRoot, onSelect, isHighlighted, relationMode, isSelected }: FamilyNodeProps) {
export function FamilyNode({ member, spouse, spouses, isRoot, onSelect, isHighlighted, relationMode, isSelected, canEdit = true }: FamilyNodeProps) {
// 优先使用 spouses 数组,如果没有则使用单个 spouse
const spouseList = spouses || (spouse ? [spouse] : [])
if (spouseList.length === 0) {
return <PersonCard member={member} isRoot={isRoot} onSelect={onSelect} isHighlighted={isHighlighted} relationMode={relationMode} isSelected={isSelected} />
return <PersonCard member={member} isRoot={isRoot} onSelect={onSelect} isHighlighted={isHighlighted} relationMode={relationMode} isSelected={isSelected} canEdit={canEdit} />
}
// 有配偶时,并排显示所有配偶
return (
<div className="flex items-center gap-2">
<PersonCard member={member} isRoot={isRoot} onSelect={onSelect} isHighlighted={isHighlighted} relationMode={relationMode} isSelected={isSelected} />
<PersonCard member={member} isRoot={isRoot} onSelect={onSelect} isHighlighted={isHighlighted} relationMode={relationMode} isSelected={isSelected} canEdit={canEdit} />
{spouseList.map((spouseMember, index) => (
<div key={spouseMember.id} className="flex items-center gap-2">
<Heart className="h-4 w-4 text-red-400 flex-shrink-0" />
<PersonCard member={spouseMember} isSpouse={true} onSelect={onSelect} relationMode={relationMode} />
<PersonCard member={spouseMember} isSpouse={true} onSelect={onSelect} relationMode={relationMode} canEdit={canEdit} />
</div>
))}
</div>
+6 -1
View File
@@ -4,6 +4,7 @@ import { FamilyNode } from "./family-node"
import { useFamily } from "@/context/family-context"
import { useEffect, useRef, useState, useCallback, useMemo, memo } from "react"
import { useRouter } from "next/navigation"
import { permissions } from "@/lib/permissions"
interface TreeLayoutProps {
rootId: string
@@ -26,7 +27,10 @@ export function TreeLayout({
selectedMembers = [],
onMemberClick
}: TreeLayoutProps) {
const { getMember, treeData, highlightedMemberId } = useFamily()
const { getMember, treeData, highlightedMemberId, currentTree } = useFamily()
// 检查用户是否有创建权限
const canEdit = permissions.canCreate(currentTree?.currentUserRole)
const root = getMember(rootId)
const router = useRouter()
const containerRef = useRef<HTMLDivElement>(null)
@@ -192,6 +196,7 @@ export function TreeLayout({
isHighlighted={member.id === highlightedMemberId}
relationMode={relationMode}
isSelected={selectedMembers.includes(member.id)}
canEdit={canEdit}
/>
</div>
+3 -1
View File
@@ -50,13 +50,15 @@ function DialogContent({
className,
children,
showCloseButton = true,
overlayClassName,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
overlayClassName?: string
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogOverlay className={overlayClassName} />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(