fix: refactor wizard edit mode to use lazy state init instead of effect setState

This commit is contained in:
2026-04-28 09:51:26 +08:00
parent d8d0e8f826
commit d6a9601591
8 changed files with 868 additions and 97 deletions
+348
View File
@@ -0,0 +1,348 @@
"use client"
import { useState, useCallback } from "react"
import Image from "next/image"
import {
ThumbsUpIcon,
ReplyIcon,
MoreHorizontalIcon,
TrashIcon,
ChevronDownIcon,
ChevronUpIcon,
} from "lucide-react"
import { useSession } from "@/lib/auth-client"
import { TiptapRenderer } from "@/components/tiptap-renderer"
import { TiptapEditor } from "@/components/tiptap-editor"
export interface CommentData {
id: string
gameId: string
userId: string
parentId: string | null
content: Record<string, unknown>
upvotes: number
createdAt: string
updatedAt: string
userName: string | null
userImage: string | null
}
function formatDate(value: string | null | undefined): string {
if (!value) return ""
return new Date(value).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
})
}
function getInitial(name: string | null | undefined): string {
return name?.charAt(0)?.toUpperCase() || "?"
}
interface CommentItemProps {
comment: CommentData
depth?: number
onReplyPosted: () => void
gameId: string
}
export function CommentItem({
comment,
depth = 0,
onReplyPosted,
gameId,
}: CommentItemProps) {
const { data: session } = useSession()
const [upvotes, setUpvotes] = useState(comment.upvotes)
const [hasUpvoted, setHasUpvoted] = useState(false)
const [isReplying, setIsReplying] = useState(false)
const [replyContent, setReplyContent] = useState<Record<string, unknown> | null>(null)
const [replySubmitting, setReplySubmitting] = useState(false)
const [showReplies, setShowReplies] = useState(false)
const [replies, setReplies] = useState<CommentData[]>([])
const [loadingReplies, setLoadingReplies] = useState(false)
const [menuOpen, setMenuOpen] = useState(false)
const [isDeleted, setIsDeleted] = useState(false)
const isOwner = session?.user?.id === comment.userId
const isAdmin = session?.user?.role === "admin"
const canModerate = isOwner || isAdmin
const handleUpvote = useCallback(async () => {
if (!session) return
try {
const res = await fetch(
`/api/games/${gameId}/comments/${comment.id}/upvote`,
{ method: "POST" },
)
if (res.ok) {
setUpvotes((prev) => (hasUpvoted ? prev - 1 : prev + 1))
setHasUpvoted((prev) => !prev)
}
} catch (err) {
console.error("Failed to upvote comment:", err)
}
}, [session, gameId, comment.id, hasUpvoted])
const handleReplySubmit = useCallback(async () => {
if (!replyContent || !session) return
setReplySubmitting(true)
try {
const res = await fetch(`/api/games/${gameId}/comments`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ parentId: comment.id, content: replyContent }),
})
if (res.ok) {
setIsReplying(false)
setReplyContent(null)
onReplyPosted()
if (showReplies) {
// Refresh replies
setLoadingReplies(true)
const repliesRes = await fetch(
`/api/games/${gameId}/comments/${comment.id}/replies`,
)
if (repliesRes.ok) {
const data = (await repliesRes.json()) as CommentData[]
setReplies(data)
}
setLoadingReplies(false)
}
}
} catch (err) {
console.error("Failed to post reply:", err)
} finally {
setReplySubmitting(false)
}
}, [replyContent, session, gameId, comment.id, onReplyPosted, showReplies])
const handleDelete = useCallback(async () => {
if (!canModerate) return
try {
const res = await fetch(
`/api/games/${gameId}/comments/${comment.id}`,
{ method: "DELETE" },
)
if (res.ok) {
setIsDeleted(true)
}
} catch (err) {
console.error("Failed to delete comment:", err)
}
}, [canModerate, gameId, comment.id])
const handleLoadReplies = useCallback(async () => {
if (showReplies) {
setShowReplies(false)
return
}
setLoadingReplies(true)
try {
const res = await fetch(
`/api/games/${gameId}/comments/${comment.id}/replies`,
)
if (res.ok) {
const data = (await res.json()) as CommentData[]
setReplies(data)
setShowReplies(true)
}
} catch (err) {
console.error("Failed to load replies:", err)
} finally {
setLoadingReplies(false)
}
}, [showReplies, gameId, comment.id])
if (isDeleted) {
return (
<div className="py-3 text-sm text-text/40 italic">
Comment removed
</div>
)
}
return (
<div className={depth > 0 ? "ml-8 border-l border-border pl-4" : ""}>
<div className="flex gap-3 py-3">
{/* Avatar */}
<div className="shrink-0">
{comment.userImage ? (
<Image
src={comment.userImage}
alt={comment.userName || "User"}
width={36}
height={36}
className="h-9 w-9 rounded-full object-cover"
unoptimized
/>
) : (
<div className="h-9 w-9 rounded-full bg-text/10 flex items-center justify-center text-sm font-medium text-text/70">
{getInitial(comment.userName)}
</div>
)}
</div>
{/* Content */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-sm font-semibold text-text">
{comment.userName || "Unknown"}
</span>
<span className="text-xs text-text/40">
{formatDate(comment.createdAt)}
</span>
</div>
<div className="mt-1">
<TiptapRenderer content={JSON.stringify(comment.content)} />
</div>
{/* Actions */}
<div className="flex items-center gap-4 mt-2">
<button
onClick={handleUpvote}
className={`flex items-center gap-1 text-xs transition-colors cursor-pointer ${
hasUpvoted
? "text-primary"
: "text-text/50 hover:text-text/80"
}`}
title="Upvote"
>
<ThumbsUpIcon className="h-3.5 w-3.5" />
<span>{upvotes}</span>
</button>
{session && depth === 0 && (
<button
onClick={() => setIsReplying((prev) => !prev)}
className="flex items-center gap-1 text-xs text-text/50 hover:text-text/80 transition-colors cursor-pointer"
title="Reply"
>
<ReplyIcon className="h-3.5 w-3.5" />
<span>Reply</span>
</button>
)}
{canModerate && (
<div className="relative">
<button
onClick={() => setMenuOpen((prev) => !prev)}
className="flex items-center gap-1 text-xs text-text/50 hover:text-text/80 transition-colors cursor-pointer"
title="More options"
>
<MoreHorizontalIcon className="h-3.5 w-3.5" />
</button>
{menuOpen && (
<>
<div
className="fixed inset-0 z-10"
onClick={() => setMenuOpen(false)}
/>
<div className="absolute right-0 z-20 mt-1 w-32 rounded-md border border-border bg-background shadow-lg overflow-hidden">
<button
onClick={() => {
setMenuOpen(false)
handleDelete()
}}
className="w-full flex items-center gap-2 px-3 py-2 text-xs text-red-400 hover:bg-red-500/10 transition-colors cursor-pointer"
>
<TrashIcon className="h-3.5 w-3.5" />
Delete
</button>
</div>
</>
)}
</div>
)}
</div>
{/* Reply form */}
{isReplying && (
<div className="mt-3 flex flex-col gap-2">
<TiptapEditor
placeholder="Write a reply..."
onChange={(json) => setReplyContent(json)}
className="min-h-[100px]"
/>
<div className="flex items-center gap-2">
<button
onClick={handleReplySubmit}
disabled={!replyContent || replySubmitting}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium bg-primary text-white hover:bg-primary/90 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
>
{replySubmitting ? "Posting..." : "Post Reply"}
</button>
<button
onClick={() => {
setIsReplying(false)
setReplyContent(null)
}}
className="px-3 py-1.5 rounded-md text-xs font-medium bg-text/5 text-text/70 hover:bg-text/10 transition-colors cursor-pointer"
>
Cancel
</button>
</div>
</div>
)}
{/* Load replies */}
{depth === 0 && (
<div className="mt-2">
{replies.length > 0 && !showReplies && (
<button
onClick={() => setShowReplies(true)}
className="flex items-center gap-1 text-xs text-primary hover:text-primary/80 transition-colors cursor-pointer"
>
<ChevronDownIcon className="h-3.5 w-3.5" />
Show {replies.length} replies
</button>
)}
{showReplies && replies.length > 0 && (
<button
onClick={() => setShowReplies(false)}
className="flex items-center gap-1 text-xs text-primary hover:text-primary/80 transition-colors cursor-pointer"
>
<ChevronUpIcon className="h-3.5 w-3.5" />
Hide replies
</button>
)}
{replies.length === 0 && !showReplies && (
<button
onClick={handleLoadReplies}
disabled={loadingReplies}
className="flex items-center gap-1 text-xs text-primary hover:text-primary/80 transition-colors cursor-pointer disabled:opacity-50"
>
{loadingReplies ? (
"Loading..."
) : (
<>
<ChevronDownIcon className="h-3.5 w-3.5" />
Load replies
</>
)}
</button>
)}
</div>
)}
{/* Replies list */}
{depth === 0 && showReplies && replies.length > 0 && (
<div className="mt-2">
{replies.map((reply) => (
<CommentItem
key={reply.id}
comment={reply}
depth={depth + 1}
onReplyPosted={onReplyPosted}
gameId={gameId}
/>
))}
</div>
)}
</div>
</div>
</div>
)
}
+209
View File
@@ -0,0 +1,209 @@
"use client"
import { useState, useCallback, useEffect } from "react"
import Link from "next/link"
import { MessageSquareIcon, Loader2 } from "lucide-react"
import { useSession } from "@/lib/auth-client"
import { TiptapEditor } from "@/components/tiptap-editor"
import { CommentItem, CommentData } from "./comment-item"
interface CommentSectionProps {
gameId: string
initialCount: number
}
interface CommentsApiResponse {
data: CommentData[]
total: number
limit: number
offset: number
}
export function CommentSection({ gameId, initialCount }: CommentSectionProps) {
const { data: session } = useSession()
const [comments, setComments] = useState<CommentData[]>([])
const [total, setTotal] = useState(initialCount)
const [offset, setOffset] = useState(0)
const [loading, setLoading] = useState(true)
const [commentContent, setCommentContent] = useState<Record<string, unknown> | null>(null)
const [submitting, setSubmitting] = useState(false)
const limit = 20
// Initial load
useEffect(() => {
let cancelled = false
async function fetchInitial() {
setLoading(true)
try {
const res = await fetch(
`/api/games/${gameId}/comments?limit=${limit}&offset=0`,
)
if (!cancelled && res.ok) {
const json = (await res.json()) as CommentsApiResponse
setComments(json.data)
setTotal(json.total)
}
} catch (err) {
console.error("Failed to load comments:", err)
} finally {
if (!cancelled) setLoading(false)
}
}
fetchInitial()
return () => {
cancelled = true
}
}, [gameId])
const refreshComments = useCallback(async () => {
try {
const res = await fetch(
`/api/games/${gameId}/comments?limit=${limit}&offset=0`,
)
if (res.ok) {
const json = (await res.json()) as CommentsApiResponse
setComments(json.data)
setTotal(json.total)
}
} catch (err) {
console.error("Failed to refresh comments:", err)
}
}, [gameId])
const handleSubmit = useCallback(async () => {
if (!commentContent || !session) return
setSubmitting(true)
try {
const res = await fetch(`/api/games/${gameId}/comments`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content: commentContent }),
})
if (res.ok) {
setCommentContent(null)
await refreshComments()
}
} catch (err) {
console.error("Failed to post comment:", err)
} finally {
setSubmitting(false)
}
}, [commentContent, session, gameId, refreshComments])
const handleLoadMore = useCallback(async () => {
const newOffset = offset + limit
setLoading(true)
try {
const res = await fetch(
`/api/games/${gameId}/comments?limit=${limit}&offset=${newOffset}`,
)
if (res.ok) {
const json = (await res.json()) as CommentsApiResponse
setComments((prev) => [...prev, ...json.data])
setTotal(json.total)
setOffset(newOffset)
}
} catch (err) {
console.error("Failed to load more comments:", err)
} finally {
setLoading(false)
}
}, [offset, gameId])
const handleReplyPosted = useCallback(() => {
refreshComments()
}, [refreshComments])
const hasMore = comments.length < total
return (
<div className="flex flex-col gap-4">
{/* Header */}
<div className="flex items-center gap-2">
<MessageSquareIcon className="h-5 w-5 text-text/70" />
<h2 className="text-lg font-semibold text-text">Comments</h2>
<span className="text-sm text-text/50">({total})</span>
</div>
{/* Compose */}
{session ? (
<div className="flex flex-col gap-2">
<TiptapEditor
placeholder="Leave a comment..."
onChange={(json) => setCommentContent(json)}
/>
<div className="flex justify-end">
<button
onClick={handleSubmit}
disabled={!commentContent || submitting}
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg text-sm font-medium bg-primary text-white hover:bg-primary/90 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
>
{submitting ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Posting...
</>
) : (
"Post Comment"
)}
</button>
</div>
</div>
) : (
<div className="p-4 rounded-lg border border-border bg-text/3 text-center">
<p className="text-sm text-text/70">
<Link
href="/auth/sign-in"
className="text-primary hover:text-primary/80 transition-colors"
>
Sign in
</Link>{" "}
to leave a comment
</p>
</div>
)}
{/* Comment list */}
<div className="flex flex-col">
{loading && comments.length === 0 ? (
<div className="py-8 text-center text-sm text-text/50">
<Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />
Loading comments...
</div>
) : comments.length === 0 ? (
<div className="py-8 text-center text-sm text-text/50">
No comments yet. Be the first to share your thoughts!
</div>
) : (
comments.map((comment) => (
<CommentItem
key={comment.id}
comment={comment}
depth={0}
onReplyPosted={handleReplyPosted}
gameId={gameId}
/>
))
)}
</div>
{/* Load more */}
{hasMore && !loading && (
<div className="flex justify-center">
<button
onClick={handleLoadMore}
className="px-4 py-2 rounded-lg text-sm font-medium bg-text/5 text-text/70 hover:bg-text/10 transition-colors cursor-pointer"
>
Load more comments
</button>
</div>
)}
{loading && comments.length > 0 && (
<div className="py-4 text-center text-sm text-text/50">
<Loader2 className="h-5 w-5 animate-spin mx-auto" />
</div>
)}
</div>
)
}
+86 -32
View File
@@ -1,6 +1,6 @@
"use client"
import { useState, useCallback } from "react"
import { useState, useCallback, useEffect } from "react"
import { useRouter } from "next/navigation"
import { motion, AnimatePresence } from "motion/react"
import { StepIndicator } from "@/components/wizard/step-indicator"
@@ -10,6 +10,7 @@ import { SettingsStep } from "@/components/wizard/steps/settings-step"
import { EnvironmentStep, type EnvironmentData } from "@/components/wizard/steps/environment-step"
import { ReviewStep } from "@/components/wizard/steps/review-step"
import type { SettingCategory } from "@/components/wizard/settings-editor"
import { performanceEntries } from "@/lib/db/schema"
const STEPS = [
{ label: "Hardware", tooltip: "Choose the hardware you tested this game on" },
@@ -22,9 +23,10 @@ const STEPS = [
interface GameEntryWizardProps {
gameId: string
gameVersionId: string
editEntry?: typeof performanceEntries.$inferSelect | null
}
export function GameEntryWizard({ gameId, gameVersionId }: GameEntryWizardProps) {
export function GameEntryWizard({ gameId, gameVersionId, editEntry }: GameEntryWizardProps) {
const router = useRouter()
const [currentStep, setCurrentStep] = useState(0)
const [isSubmitting, setIsSubmitting] = useState(false)
@@ -32,23 +34,48 @@ export function GameEntryWizard({ gameId, gameVersionId }: GameEntryWizardProps)
const [success, setSuccess] = useState(false)
// Step 1: Hardware
const [hardwareSlug, setHardwareSlug] = useState("")
const [hardwareSlug, setHardwareSlug] = useState(editEntry?.hardwareSlug ?? "")
const [hardwareName, setHardwareName] = useState("")
// Step 2: Performance
const [performance, setPerformance] = useState<PerformanceData>({})
const [performance, setPerformance] = useState<PerformanceData>(
editEntry
? {
fpsAvg: editEntry.fpsAvg,
fpsLow: editEntry.fpsLow ?? undefined,
fpsHigh: editEntry.fpsHigh ?? undefined,
loadTimeSsd: editEntry.loadTimeSsd ?? undefined,
loadTimeSd: editEntry.loadTimeSd ?? undefined,
}
: {},
)
// Step 3: Settings
const [settingsJson, setSettingsJson] = useState<SettingCategory[]>([])
const [settingsJson, setSettingsJson] = useState<SettingCategory[]>(
editEntry?.settingsJson ?? [],
)
// Step 4: Environment
const [environment, setEnvironment] = useState<EnvironmentData>({
upscalerType: "none",
frameGenMethod: "none",
})
const [environment, setEnvironment] = useState<EnvironmentData>(
editEntry
? {
protonVersion: editEntry.protonVersion ?? undefined,
osVersion: editEntry.osVersion ?? undefined,
upscalerType: editEntry.upscalerType ?? "none",
upscalerVersion: editEntry.upscalerVersion ?? undefined,
frameGenMethod: editEntry.frameGenMethod ?? "none",
launchOptions: editEntry.launchOptions ?? undefined,
estimatedBatteryMin: editEntry.estimatedBatteryMin ?? undefined,
customSystem: editEntry.customSystem ?? false,
}
: {
upscalerType: "none",
frameGenMethod: "none",
},
)
// Step 5: Notes
const [userNotes, setUserNotes] = useState("")
const [userNotes, setUserNotes] = useState(editEntry?.userNotes ?? "")
// Fetch hardware name when slug changes
const handleHardwareChange = useCallback(async (slug: string) => {
@@ -69,6 +96,26 @@ export function GameEntryWizard({ gameId, gameVersionId }: GameEntryWizardProps)
}
}, [])
// Fetch hardware name when in edit mode
useEffect(() => {
if (!editEntry || !hardwareSlug) return
let cancelled = false
async function fetchName() {
try {
const res = await fetch("/api/performance/hardware")
if (res.ok && !cancelled) {
const data = await res.json() as { data: Array<{ slug: string; name: string }> }
const device = data.data.find((d) => d.slug === hardwareSlug)
if (device && !cancelled) setHardwareName(device.name)
}
} catch {
// ignore
}
}
fetchName()
return () => { cancelled = true }
}, [editEntry, hardwareSlug])
const canProceed = () => {
switch (currentStep) {
case 0:
@@ -109,33 +156,40 @@ export function GameEntryWizard({ gameId, gameVersionId }: GameEntryWizardProps)
setError(null)
try {
const res = await fetch("/api/performance/submit", {
method: "POST",
const payload = {
versionId: gameVersionId,
hardwareSlug,
fpsAvg: Number(performance.fpsAvg),
fpsLow: performance.fpsLow !== undefined ? Number(performance.fpsLow) : null,
fpsHigh: performance.fpsHigh !== undefined ? Number(performance.fpsHigh) : null,
loadTimeSsd: performance.loadTimeSsd !== undefined ? Number(performance.loadTimeSsd) : null,
loadTimeSd: performance.loadTimeSd !== undefined ? Number(performance.loadTimeSd) : null,
protonVersion: environment.protonVersion || null,
osVersion: environment.osVersion || null,
upscalerType: environment.upscalerType ?? "none",
upscalerVersion: environment.upscalerVersion || null,
frameGenMethod: environment.frameGenMethod ?? "none",
launchOptions: environment.launchOptions || null,
estimatedBatteryMin: environment.estimatedBatteryMin ?? null,
customSystem: environment.customSystem ?? false,
settingsJson: settingsJson.length > 0 ? settingsJson : null,
userNotes: userNotes || null,
}
const url = editEntry
? `/api/performance/${editEntry.id}/edit`
: "/api/performance/submit"
const method = editEntry ? "PATCH" : "POST"
const res = await fetch(url, {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
versionId: gameVersionId,
hardwareSlug,
fpsAvg: Number(performance.fpsAvg),
fpsLow: performance.fpsLow !== undefined ? Number(performance.fpsLow) : null,
fpsHigh: performance.fpsHigh !== undefined ? Number(performance.fpsHigh) : null,
loadTimeSsd: performance.loadTimeSsd !== undefined ? Number(performance.loadTimeSsd) : null,
loadTimeSd: performance.loadTimeSd !== undefined ? Number(performance.loadTimeSd) : null,
protonVersion: environment.protonVersion || null,
osVersion: environment.osVersion || null,
upscalerType: environment.upscalerType ?? "none",
upscalerVersion: environment.upscalerVersion || null,
frameGenMethod: environment.frameGenMethod ?? "none",
launchOptions: environment.launchOptions || null,
estimatedBatteryMin: environment.estimatedBatteryMin ?? null,
customSystem: environment.customSystem ?? false,
settingsJson: settingsJson.length > 0 ? settingsJson : null,
userNotes: userNotes || null,
}),
body: JSON.stringify(payload),
})
if (!res.ok) {
const data = await res.json()
throw new Error(data.error || "Failed to submit entry")
throw new Error(data.error || `Failed to ${editEntry ? "update" : "submit"} entry`)
}
setSuccess(true)
+62 -42
View File
@@ -42,6 +42,12 @@ const DEFAULT_CATEGORIES: SettingCategory[] = [
},
]
const typeOptions = [
{ value: "text", label: "Abc" },
{ value: "number", label: "123" },
{ value: "boolean", label: "\u2713/\u2717" },
] as const
interface SettingsEditorProps {
value: SettingCategory[]
onChange: (categories: SettingCategory[]) => void
@@ -59,6 +65,7 @@ export function SettingsEditor({
const [newCategoryName, setNewCategoryName] = useState("")
const [newSettingNames, setNewSettingNames] = useState<Record<string, string>>({})
const [newSettingTypes, setNewSettingTypes] = useState<Record<string, string>>({})
const addSettingInputRefs = useRef<Record<string, HTMLInputElement | null>>({})
const toggleCategory = (category: string) => {
setCollapsedCategories((prev) => {
@@ -106,6 +113,8 @@ export function SettingsEditor({
})
)
setNewSettingNames((prev) => ({ ...prev, [category]: "" }))
// Refocus after React re-renders
setTimeout(() => addSettingInputRefs.current[category]?.focus(), 0)
}
const moveCategoryUp = (category: string) => {
@@ -326,6 +335,59 @@ export function SettingsEditor({
className="overflow-hidden"
>
<div className="px-4 pb-4 pt-2 space-y-3">
{/* Add setting row at the top */}
<div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2">
<div className="flex items-center gap-1">
{typeOptions.map((opt) => (
<button
key={opt.value}
type="button"
onClick={() =>
setNewSettingTypes((prev) => ({
...prev,
[cat.category]: opt.value,
}))
}
className={`px-2 py-1.5 rounded-md text-xs font-medium border transition-colors cursor-pointer ${
(newSettingTypes[cat.category] || "text") === opt.value
? "bg-primary text-white border-primary"
: "border-border text-text/60 hover:bg-text/5"
}`}
>
{opt.label}
</button>
))}
</div>
<input
ref={(el) => {
addSettingInputRefs.current[cat.category] = el
}}
type="text"
value={newSettingNames[cat.category] || ""}
onChange={(e) =>
setNewSettingNames((prev) => ({
...prev,
[cat.category]: e.target.value,
}))
}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault()
addSetting(cat.category)
}
}}
placeholder="Add setting..."
className="flex-1 px-3 py-1.5 rounded-md border border-border bg-text/5 text-text text-sm placeholder:text-text/40 outline-none focus:border-primary focus:ring-2 focus:ring-primary/50 transition-colors"
/>
<button
onClick={() => addSetting(cat.category)}
className="p-1.5 rounded-md bg-primary text-white hover:bg-primary/90 transition-colors cursor-pointer flex-shrink-0"
title="Add setting"
>
<Plus className="h-4 w-4" />
</button>
</div>
<AnimatePresence initial={false}>
{cat.settings.map((setting) => (
<motion.div
@@ -408,48 +470,6 @@ export function SettingsEditor({
</motion.div>
))}
</AnimatePresence>
<div className="flex items-center gap-2 pt-1">
<select
value={newSettingTypes[cat.category] || "text"}
onChange={(e) =>
setNewSettingTypes((prev) => ({
...prev,
[cat.category]: e.target.value,
}))
}
className="text-xs px-2 py-1.5 rounded-md border border-border bg-text/5 text-text/60 outline-none focus:border-primary"
>
<option value="text">Text</option>
<option value="number">Number</option>
<option value="boolean">Boolean</option>
</select>
<input
type="text"
value={newSettingNames[cat.category] || ""}
onChange={(e) =>
setNewSettingNames((prev) => ({
...prev,
[cat.category]: e.target.value,
}))
}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault()
addSetting(cat.category)
}
}}
placeholder="Add setting..."
className="flex-1 px-3 py-1.5 rounded-md border border-border bg-text/5 text-text text-sm placeholder:text-text/40 outline-none focus:border-primary focus:ring-2 focus:ring-primary/50 transition-colors"
/>
<button
onClick={() => addSetting(cat.category)}
className="p-1.5 rounded-md bg-primary text-white hover:bg-primary/90 transition-colors cursor-pointer"
title="Add setting"
>
<Plus className="h-4 w-4" />
</button>
</div>
</div>
</motion.div>
)}
+21 -17
View File
@@ -18,14 +18,18 @@ interface PerformanceStepProps {
export function PerformanceStep({ value, onChange }: PerformanceStepProps) {
const error = useMemo(() => {
if (value.fpsAvg !== undefined && value.fpsAvg !== null && value.fpsAvg <= 0) {
if (value.fpsAvg !== undefined && value.fpsAvg !== null && (isNaN(value.fpsAvg) || value.fpsAvg <= 0)) {
return "FPS Average must be greater than 0"
}
return null
}, [value.fpsAvg])
const update = (field: keyof PerformanceData, val: string) => {
const num = val === "" ? undefined : Number(val)
const isDecimalField = field === "loadTimeSsd" || field === "loadTimeSd"
const cleaned = isDecimalField
? val.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1")
: val.replace(/[^0-9]/g, "")
const num = cleaned === "" || cleaned === "." ? undefined : Number(cleaned)
onChange({ ...value, [field]: num })
}
@@ -44,9 +48,9 @@ export function PerformanceStep({ value, onChange }: PerformanceStepProps) {
FPS Average <span className="text-red-400">*</span>
</label>
<input
type="number"
min={1}
step={1}
type="text"
inputMode="numeric"
pattern="[0-9]*"
value={value.fpsAvg ?? ""}
onChange={(e) => update("fpsAvg", e.target.value)}
placeholder="e.g. 45"
@@ -58,9 +62,9 @@ export function PerformanceStep({ value, onChange }: PerformanceStepProps) {
<div className="space-y-1.5">
<label className="text-xs font-medium text-text/60">FPS Low</label>
<input
type="number"
min={1}
step={1}
type="text"
inputMode="numeric"
pattern="[0-9]*"
value={value.fpsLow ?? ""}
onChange={(e) => update("fpsLow", e.target.value)}
placeholder="e.g. 30"
@@ -71,9 +75,9 @@ export function PerformanceStep({ value, onChange }: PerformanceStepProps) {
<div className="space-y-1.5">
<label className="text-xs font-medium text-text/60">FPS High</label>
<input
type="number"
min={1}
step={1}
type="text"
inputMode="numeric"
pattern="[0-9]*"
value={value.fpsHigh ?? ""}
onChange={(e) => update("fpsHigh", e.target.value)}
placeholder="e.g. 60"
@@ -98,9 +102,9 @@ export function PerformanceStep({ value, onChange }: PerformanceStepProps) {
<div className="space-y-1.5">
<label className="text-xs font-medium text-text/60">Load Time SSD (seconds)</label>
<input
type="number"
min={0}
step={0.1}
type="text"
inputMode="numeric"
pattern="[0-9]*"
value={value.loadTimeSsd ?? ""}
onChange={(e) => update("loadTimeSsd", e.target.value)}
placeholder="e.g. 12.5"
@@ -111,9 +115,9 @@ export function PerformanceStep({ value, onChange }: PerformanceStepProps) {
<div className="space-y-1.5">
<label className="text-xs font-medium text-text/60">Load Time SD Card (seconds)</label>
<input
type="number"
min={0}
step={0.1}
type="text"
inputMode="numeric"
pattern="[0-9]*"
value={value.loadTimeSd ?? ""}
onChange={(e) => update("loadTimeSd", e.target.value)}
placeholder="e.g. 35.0"