diff options
Diffstat (limited to 'packages/ui/src/pages')
| -rw-r--r-- | packages/ui/src/pages/assistant-view.tsx.bk | 485 | ||||
| -rw-r--r-- | packages/ui/src/pages/home.tsx (renamed from packages/ui/src/pages/home-view.tsx) | 100 | ||||
| -rw-r--r-- | packages/ui/src/pages/index.tsx | 22 | ||||
| -rw-r--r-- | packages/ui/src/pages/instances/create.tsx | 746 | ||||
| -rw-r--r-- | packages/ui/src/pages/instances/index.tsx (renamed from packages/ui/src/pages/instances-view.tsx) | 73 | ||||
| -rw-r--r-- | packages/ui/src/pages/instances/routes.ts | 19 | ||||
| -rw-r--r-- | packages/ui/src/pages/routes.ts | 25 |
7 files changed, 851 insertions, 619 deletions
diff --git a/packages/ui/src/pages/assistant-view.tsx.bk b/packages/ui/src/pages/assistant-view.tsx.bk deleted file mode 100644 index 56f827b..0000000 --- a/packages/ui/src/pages/assistant-view.tsx.bk +++ /dev/null @@ -1,485 +0,0 @@ -import { - AlertTriangle, - Bot, - Brain, - ChevronDown, - Loader2, - RefreshCw, - Send, - Settings, - Trash2, -} from "lucide-react"; -import { marked } from "marked"; -import { useCallback, useEffect, useRef, useState } from "react"; -import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; -import { Card, CardContent } from "@/components/ui/card"; -import { ScrollArea } from "@/components/ui/scroll-area"; -import { Separator } from "@/components/ui/separator"; -import { Textarea } from "@/components/ui/textarea"; -import { toNumber } from "@/lib/tsrs-utils"; -import { type Message, useAssistantStore } from "../stores/assistant-store"; -import { useSettingsStore } from "../stores/settings-store"; -import { useUiStore } from "../stores/ui-store"; - -interface ParsedMessage { - thinking: string | null; - content: string; - isThinking: boolean; -} - -function parseMessageContent(content: string): ParsedMessage { - if (!content) return { thinking: null, content: "", isThinking: false }; - - // Support both <thinking> and <think> (DeepSeek uses <think>) - let startTag = "<thinking>"; - let endTag = "</thinking>"; - let startIndex = content.indexOf(startTag); - - if (startIndex === -1) { - startTag = "<think>"; - endTag = "</think>"; - startIndex = content.indexOf(startTag); - } - - // Also check for encoded tags if they weren't decoded properly - if (startIndex === -1) { - startTag = "\u003cthink\u003e"; - endTag = "\u003c/think\u003e"; - startIndex = content.indexOf(startTag); - } - - if (startIndex !== -1) { - const endIndex = content.indexOf(endTag, startIndex); - - if (endIndex !== -1) { - // Completed thinking block - const before = content.substring(0, startIndex); - const thinking = content - .substring(startIndex + startTag.length, endIndex) - .trim(); - const after = content.substring(endIndex + endTag.length); - - return { - thinking, - content: (before + after).trim(), - isThinking: false, - }; - } else { - // Incomplete thinking block (still streaming) - const before = content.substring(0, startIndex); - const thinking = content.substring(startIndex + startTag.length).trim(); - - return { - thinking, - content: before.trim(), - isThinking: true, - }; - } - } - - return { thinking: null, content, isThinking: false }; -} - -function renderMarkdown(content: string): string { - if (!content) return ""; - try { - return marked(content, { breaks: true, gfm: true }) as string; - } catch { - return content; - } -} - -export function AssistantView() { - const { - messages, - isProcessing, - isProviderHealthy, - streamingContent, - init, - checkHealth, - sendMessage, - clearHistory, - } = useAssistantStore(); - const { settings } = useSettingsStore(); - const { setView } = useUiStore(); - - const [input, setInput] = useState(""); - const messagesEndRef = useRef<HTMLDivElement>(null); - const messagesContainerRef = useRef<HTMLDivElement>(null); - - const provider = settings.assistant.llmProvider; - const endpoint = - provider === "ollama" - ? settings.assistant.ollamaEndpoint - : settings.assistant.openaiEndpoint; - const model = - provider === "ollama" - ? settings.assistant.ollamaModel - : settings.assistant.openaiModel; - - const getProviderName = (): string => { - if (provider === "ollama") { - return `Ollama (${model})`; - } else if (provider === "openai") { - return `OpenAI (${model})`; - } - return provider; - }; - - const getProviderHelpText = (): string => { - if (provider === "ollama") { - return `Please ensure Ollama is installed and running at ${endpoint}.`; - } else if (provider === "openai") { - return "Please check your OpenAI API key in Settings > AI Assistant."; - } - return ""; - }; - - const scrollToBottom = useCallback(() => { - if (messagesContainerRef.current) { - setTimeout(() => { - if (messagesContainerRef.current) { - messagesContainerRef.current.scrollTop = - messagesContainerRef.current.scrollHeight; - } - }, 0); - } - }, []); - - useEffect(() => { - init(); - }, [init]); - - useEffect(() => { - if (messages.length > 0 || isProcessing) { - scrollToBottom(); - } - }, [messages.length, isProcessing, scrollToBottom]); - - const handleSubmit = async () => { - if (!input.trim() || isProcessing) return; - const text = input; - setInput(""); - await sendMessage(text, settings.assistant.enabled, provider, endpoint); - }; - - const handleKeyDown = (e: React.KeyboardEvent) => { - if (e.key === "Enter" && !e.shiftKey) { - e.preventDefault(); - handleSubmit(); - } - }; - - const renderMessage = (message: Message, index: number) => { - const isUser = message.role === "user"; - const parsed = parseMessageContent(message.content); - - return ( - <div - key={index} - className={`flex ${isUser ? "justify-end" : "justify-start"} mb-4`} - > - <div - className={`max-w-[80%] rounded-2xl px-4 py-3 ${ - isUser - ? "bg-indigo-500 text-white rounded-br-none" - : "bg-zinc-800 text-zinc-100 rounded-bl-none" - }`} - > - {!isUser && parsed.thinking && ( - <div className="mb-3 max-w-full overflow-hidden"> - <details className="group" open={parsed.isThinking}> - <summary className="list-none cursor-pointer flex items-center gap-2 text-zinc-500 hover:text-zinc-300 transition-colors text-xs font-medium select-none bg-black/20 p-2 rounded-lg border border-white/5 w-fit mb-2 outline-none"> - <Brain className="h-3 w-3" /> - <span>Thinking Process</span> - <ChevronDown className="h-3 w-3 transition-transform duration-200 group-open:rotate-180" /> - </summary> - <div className="pl-3 border-l-2 border-zinc-700 text-zinc-500 text-xs italic leading-relaxed whitespace-pre-wrap font-mono max-h-96 overflow-y-auto custom-scrollbar bg-black/10 p-2 rounded-r-md"> - {parsed.thinking} - {parsed.isThinking && ( - <span className="inline-block w-1.5 h-3 bg-zinc-500 ml-1 animate-pulse align-middle" /> - )} - </div> - </details> - </div> - )} - <div - className="prose prose-invert max-w-none" - dangerouslySetInnerHTML={{ - __html: renderMarkdown(parsed.content), - }} - /> - {!isUser && message.stats && ( - <div className="mt-2 pt-2 border-t border-zinc-700/50"> - <div className="text-xs text-zinc-400"> - {message.stats.evalCount} tokens ·{" "} - {Math.round(toNumber(message.stats.totalDuration) / 1000000)} - ms - </div> - </div> - )} - </div> - </div> - ); - }; - - return ( - <div className="h-full w-full flex flex-col gap-4 p-4 lg:p-8"> - <div className="flex items-center justify-between mb-2"> - <div className="flex items-center gap-3"> - <div className="p-2 bg-indigo-500/20 rounded-lg text-indigo-400"> - <Bot size={24} /> - </div> - <div> - <h2 className="text-2xl font-bold">Game Assistant</h2> - <p className="text-zinc-400 text-sm"> - Powered by {getProviderName()} - </p> - </div> - </div> - - <div className="flex items-center gap-2"> - {!settings.assistant.enabled ? ( - <Badge - variant="outline" - className="bg-zinc-500/10 text-zinc-400 border-zinc-500/20" - > - <AlertTriangle className="h-3 w-3 mr-1" /> - Disabled - </Badge> - ) : !isProviderHealthy ? ( - <Badge - variant="outline" - className="bg-red-500/10 text-red-400 border-red-500/20" - > - <AlertTriangle className="h-3 w-3 mr-1" /> - Offline - </Badge> - ) : ( - <Badge - variant="outline" - className="bg-emerald-500/10 text-emerald-400 border-emerald-500/20" - > - <div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse mr-1" /> - Online - </Badge> - )} - - <Button - variant="ghost" - size="icon" - onClick={checkHealth} - title="Check Connection" - disabled={isProcessing} - > - <RefreshCw - className={`h-4 w-4 ${isProcessing ? "animate-spin" : ""}`} - /> - </Button> - - <Button - variant="ghost" - size="icon" - onClick={clearHistory} - title="Clear History" - disabled={isProcessing} - > - <Trash2 className="h-4 w-4" /> - </Button> - - <Button - variant="ghost" - size="icon" - onClick={() => setView("settings")} - title="Settings" - > - <Settings className="h-4 w-4" /> - </Button> - </div> - </div> - - {/* Chat Area */} - <div className="flex-1 bg-black/20 border border-white/5 rounded-xl overflow-hidden flex flex-col relative"> - {/* Warning when assistant is disabled */} - {!settings.assistant.enabled && ( - <div className="absolute top-4 left-1/2 transform -translate-x-1/2 z-10"> - <Card className="bg-yellow-500/10 border-yellow-500/20"> - <CardContent className="p-3 flex items-center gap-2"> - <AlertTriangle className="h-4 w-4 text-yellow-500" /> - <span className="text-yellow-500 text-sm font-medium"> - Assistant is disabled. Enable it in Settings > AI - Assistant. - </span> - </CardContent> - </Card> - </div> - )} - - {/* Provider offline warning */} - {settings.assistant.enabled && !isProviderHealthy && ( - <div className="absolute top-4 left-1/2 transform -translate-x-1/2 z-10"> - <Card className="bg-red-500/10 border-red-500/20"> - <CardContent className="p-3 flex items-center gap-2"> - <AlertTriangle className="h-4 w-4 text-red-500" /> - <div className="flex flex-col"> - <span className="text-red-500 text-sm font-medium"> - Assistant is offline - </span> - <span className="text-red-400 text-xs"> - {getProviderHelpText()} - </span> - </div> - </CardContent> - </Card> - </div> - )} - - {/* Messages Container */} - <ScrollArea className="flex-1 p-4 lg:p-6" ref={messagesContainerRef}> - {messages.length === 0 ? ( - <div className="flex flex-col items-center justify-center h-full text-zinc-400 gap-4 mt-8"> - <div className="p-4 bg-zinc-800/50 rounded-full"> - <Bot className="h-12 w-12" /> - </div> - <h3 className="text-xl font-medium">How can I help you today?</h3> - <p className="text-center max-w-md text-sm"> - I can analyze your game logs, diagnose crashes, or explain mod - features. - {!settings.assistant.enabled && ( - <span className="block mt-2 text-yellow-500"> - Assistant is disabled. Enable it in{" "} - <button - type="button" - onClick={() => setView("settings")} - className="text-indigo-400 hover:underline" - > - Settings > AI Assistant - </button> - . - </span> - )} - </p> - <div className="mt-4 grid grid-cols-1 md:grid-cols-2 gap-2 max-w-lg"> - <Button - variant="outline" - className="text-left h-auto py-3" - onClick={() => - setInput("How do I fix Minecraft crashing on launch?") - } - disabled={isProcessing} - > - <div className="text-sm"> - How do I fix Minecraft crashing on launch? - </div> - </Button> - <Button - variant="outline" - className="text-left h-auto py-3" - onClick={() => - setInput("What's the best way to improve FPS?") - } - disabled={isProcessing} - > - <div className="text-sm"> - What's the best way to improve FPS? - </div> - </Button> - <Button - variant="outline" - className="text-left h-auto py-3" - onClick={() => - setInput( - "Can you help me install Fabric for Minecraft 1.20.4?", - ) - } - disabled={isProcessing} - > - <div className="text-sm"> - Can you help me install Fabric for 1.20.4? - </div> - </Button> - <Button - variant="outline" - className="text-left h-auto py-3" - onClick={() => - setInput("What mods do you recommend for performance?") - } - disabled={isProcessing} - > - <div className="text-sm"> - What mods do you recommend for performance? - </div> - </Button> - </div> - </div> - ) : ( - <> - {messages.map((message, index) => renderMessage(message, index))} - {isProcessing && streamingContent && ( - <div className="flex justify-start mb-4"> - <div className="max-w-[80%] bg-zinc-800 text-zinc-100 rounded-2xl rounded-bl-none px-4 py-3"> - <div - className="prose prose-invert max-w-none" - dangerouslySetInnerHTML={{ - __html: renderMarkdown(streamingContent), - }} - /> - <div className="flex items-center gap-1 mt-2 text-xs text-zinc-400"> - <Loader2 className="h-3 w-3 animate-spin" /> - <span>Assistant is typing...</span> - </div> - </div> - </div> - )} - </> - )} - <div ref={messagesEndRef} /> - </ScrollArea> - - <Separator /> - - {/* Input Area */} - <div className="p-3 lg:p-4"> - <div className="flex gap-2"> - <Textarea - placeholder={ - settings.assistant.enabled - ? "Ask about your game..." - : "Assistant is disabled. Enable it in Settings to use." - } - value={input} - onChange={(e) => setInput(e.target.value)} - onKeyDown={handleKeyDown} - className="min-h-11 max-h-50 resize-none border-zinc-700 bg-zinc-900/50 focus:bg-zinc-900/80" - disabled={!settings.assistant.enabled || isProcessing} - /> - <Button - onClick={handleSubmit} - disabled={ - !settings.assistant.enabled || !input.trim() || isProcessing - } - className="px-6 bg-indigo-600 hover:bg-indigo-700 text-white" - > - {isProcessing ? ( - <Loader2 className="h-4 w-4 animate-spin" /> - ) : ( - <Send className="h-4 w-4" /> - )} - </Button> - </div> - <div className="mt-2 flex items-center justify-between"> - <div className="text-xs text-zinc-500"> - {settings.assistant.enabled - ? "Press Enter to send, Shift+Enter for new line" - : "Enable the assistant in Settings to use"} - </div> - <div className="text-xs text-zinc-500"> - Model: {model} • Provider: {provider} - </div> - </div> - </div> - </div> - </div> - ); -} diff --git a/packages/ui/src/pages/home-view.tsx b/packages/ui/src/pages/home.tsx index 4f80cb0..dc1413d 100644 --- a/packages/ui/src/pages/home-view.tsx +++ b/packages/ui/src/pages/home.tsx @@ -1,18 +1,11 @@ -import { useEffect, useState } from "react"; +import { useState } from "react"; import { BottomBar } from "@/components/bottom-bar"; -import type { SaturnEffect } from "@/lib/effects/SaturnEffect"; -import { useGameStore } from "../stores/game-store"; -import { useReleasesStore } from "../stores/releases-store"; +import { useSaturnEffect } from "@/components/particle-background"; -export function HomeView() { - const gameStore = useGameStore(); - const releasesStore = useReleasesStore(); +export function HomePage() { const [mouseX, setMouseX] = useState(0); const [mouseY, setMouseY] = useState(0); - - useEffect(() => { - releasesStore.loadReleases(); - }, [releasesStore.loadReleases]); + const saturn = useSaturnEffect(); const handleMouseMove = (e: React.MouseEvent) => { const x = (e.clientX / window.innerWidth) * 2 - 1; @@ -21,100 +14,42 @@ export function HomeView() { setMouseY(y); // Forward mouse move to SaturnEffect (if available) for parallax/rotation interactions - try { - const saturn = ( - window as unknown as { - getSaturnEffect?: () => SaturnEffect; - } - ).getSaturnEffect?.(); - if (saturn?.handleMouseMove) { - saturn.handleMouseMove(e.clientX); - } - } catch { - /* best-effort, ignore errors from effect */ - } + saturn?.handleMouseMove(e.clientX); }; const handleSaturnMouseDown = (e: React.MouseEvent) => { - try { - const saturn = (window as any).getSaturnEffect?.(); - if (saturn?.handleMouseDown) { - saturn.handleMouseDown(e.clientX); - } - } catch { - /* ignore */ - } + saturn?.handleMouseDown(e.clientX); }; const handleSaturnMouseUp = () => { - try { - const saturn = (window as any).getSaturnEffect?.(); - if (saturn?.handleMouseUp) { - saturn.handleMouseUp(); - } - } catch { - /* ignore */ - } + saturn?.handleMouseUp(); }; const handleSaturnMouseLeave = () => { // Treat leaving the area as mouse-up for the effect - try { - const saturn = (window as any).getSaturnEffect?.(); - if (saturn?.handleMouseUp) { - saturn.handleMouseUp(); - } - } catch { - /* ignore */ - } + saturn?.handleMouseUp(); }; const handleSaturnTouchStart = (e: React.TouchEvent) => { if (e.touches && e.touches.length === 1) { - try { - const clientX = e.touches[0].clientX; - const saturn = (window as any).getSaturnEffect?.(); - if (saturn?.handleTouchStart) { - saturn.handleTouchStart(clientX); - } - } catch { - /* ignore */ - } + const clientX = e.touches[0].clientX; + saturn?.handleTouchStart(clientX); } }; const handleSaturnTouchMove = (e: React.TouchEvent) => { if (e.touches && e.touches.length === 1) { - try { - const clientX = e.touches[0].clientX; - const saturn = (window as any).getSaturnEffect?.(); - if (saturn?.handleTouchMove) { - saturn.handleTouchMove(clientX); - } - } catch { - /* ignore */ - } + const clientX = e.touches[0].clientX; + saturn?.handleTouchMove(clientX); } }; const handleSaturnTouchEnd = () => { - try { - const saturn = (window as any).getSaturnEffect?.(); - if (saturn?.handleTouchEnd) { - saturn.handleTouchEnd(); - } - } catch { - /* ignore */ - } + saturn?.handleTouchEnd(); }; return ( - <div - className="relative z-10 h-full overflow-y-auto custom-scrollbar scroll-smooth" - style={{ - overflow: releasesStore.isLoading ? "hidden" : "auto", - }} - > + <div className="relative z-10 h-full overflow-y-auto custom-scrollbar scroll-smooth"> {/* Hero Section (Full Height) - Interactive area */} <div role="tab" @@ -150,13 +85,6 @@ export function HomeView() { <div className="bg-white/10 backdrop-blur-md border border-white/10 px-3 py-1 rounded-sm text-xs font-bold uppercase tracking-widest text-white shadow-sm"> Java Edition </div> - <div className="h-4 w-px bg-white/20"></div> - <div className="text-sm text-zinc-400"> - Latest Release{" "} - <span className="text-white font-medium"> - {gameStore.latestRelease?.id || "..."} - </span> - </div> </div> </div> diff --git a/packages/ui/src/pages/index.tsx b/packages/ui/src/pages/index.tsx index b93bb9b..d12646b 100644 --- a/packages/ui/src/pages/index.tsx +++ b/packages/ui/src/pages/index.tsx @@ -5,13 +5,11 @@ import { Sidebar } from "@/components/sidebar"; import { useAuthStore } from "@/models/auth"; import { useInstanceStore } from "@/models/instance"; import { useSettingsStore } from "@/models/settings"; -import { useGameStore } from "@/stores/game-store"; export function IndexPage() { const authStore = useAuthStore(); const settingsStore = useSettingsStore(); const instanceStore = useInstanceStore(); - const initGameLifecycle = useGameStore((state) => state.initLifecycle); const location = useLocation(); @@ -19,15 +17,7 @@ export function IndexPage() { authStore.init(); settingsStore.refresh(); instanceStore.refresh(); - void initGameLifecycle().catch((error) => { - console.error("Failed to initialize game lifecycle:", error); - }); - }, [ - authStore.init, - settingsStore.refresh, - instanceStore.refresh, - initGameLifecycle, - ]); + }, [authStore.init, settingsStore.refresh, instanceStore.refresh]); return ( <div className="relative h-screen w-full overflow-hidden bg-background font-sans"> @@ -55,8 +45,6 @@ export function IndexPage() { <div className="absolute inset-0 opacity-100 bg-linear-to-br from-emerald-100 via-gray-100 to-indigo-100"></div> )} - {location.pathname === "/" && <ParticleBackground />} - <div className="absolute inset-0 bg-linear-to-t from-zinc-900 via-transparent to-black/50 dark:from-zinc-900 dark:to-black/50"></div> </> )} @@ -81,7 +69,13 @@ export function IndexPage() { <Sidebar /> <main className="size-full overflow-hidden"> - <Outlet /> + {location.pathname === "/" ? ( + <ParticleBackground> + <Outlet /> + </ParticleBackground> + ) : ( + <Outlet /> + )} </main> </div> </div> diff --git a/packages/ui/src/pages/instances/create.tsx b/packages/ui/src/pages/instances/create.tsx new file mode 100644 index 0000000..57efea2 --- /dev/null +++ b/packages/ui/src/pages/instances/create.tsx @@ -0,0 +1,746 @@ +import { zodResolver } from "@hookform/resolvers/zod"; +import { defineStepper } from "@stepperize/react"; +import { open } from "@tauri-apps/plugin-shell"; +import { ArrowLeftIcon, Link2Icon, XIcon } from "lucide-react"; +import React, { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useState, +} from "react"; +import { + Controller, + FormProvider, + useForm, + useFormContext, + Watch, +} from "react-hook-form"; +import { useNavigate } from "react-router"; +import { toast } from "sonner"; +import z from "zod"; +import { + getFabricLoadersForVersion, + getForgeVersionsForGame, + getVersions, + installFabric, + installForge, + installVersion, + updateInstance, +} from "@/client"; +import { + Accordion, + AccordionContent, + AccordionItem, + AccordionTrigger, +} from "@/components/ui/accordion"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { + Field, + FieldContent, + FieldDescription, + FieldError, + FieldLabel, + FieldSet, + FieldTitle, +} from "@/components/ui/field"; +import { Input } from "@/components/ui/input"; +import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"; +import { ScrollArea } from "@/components/ui/scroll-area"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Separator } from "@/components/ui/separator"; +import { Spinner } from "@/components/ui/spinner"; +import { Textarea } from "@/components/ui/textarea"; +import { cn } from "@/lib/utils"; +import { useInstanceStore } from "@/models/instance"; +import type { FabricLoaderEntry, ForgeVersion, Version } from "@/types"; + +const versionSchema = z.object({ + versionId: z.string("Version is required"), +}); + +function VersionComponent() { + const { + control, + formState: { errors }, + } = useFormContext<z.infer<typeof versionSchema>>(); + + const [versionSearch, setVersionSearch] = useState<string>(""); + const [versionFilter, setVersionFilter] = useState< + "all" | "release" | "snapshot" | "old_alpha" | "old_beta" | null + >("release"); + + const [versions, setVersions] = useState<Version[] | null>(null); + const [isLoading, setIsLoading] = useState(false); + const [errorMessage, setErrorMessage] = useState<string | null>(null); + const loadVersions = useCallback(async () => { + setErrorMessage(null); + setIsLoading(true); + try { + const versions = await getVersions(); + setVersions(versions); + } catch (e) { + console.error("Failed to load versions:", e); + setErrorMessage(`Failed to load versions: ${String(e)}`); + return; + } finally { + setIsLoading(false); + } + }, []); + useEffect(() => { + if (!versions) loadVersions(); + }, [versions, loadVersions]); + + const filteredVersions = useMemo(() => { + if (!versions) return null; + const all = versions; + let list = all.slice(); + if (versionFilter !== "all") { + list = list.filter((v) => v.type === versionFilter); + } + if (versionSearch.trim()) { + const q = versionSearch.trim().toLowerCase().replace(/。/g, "."); + list = list.filter((v) => v.id.toLowerCase().includes(q)); + } + return list; + }, [versions, versionFilter, versionSearch]); + + return ( + <div className="flex flex-col min-h-0 h-full overflow-hidden"> + <div className="flex flex-row items-center mb-4 space-x-2"> + <div className="flex flex-row space-x-2 w-full"> + <FieldLabel className="text-nowrap">Versions</FieldLabel> + <Input + placeholder="Search versions..." + value={versionSearch} + onChange={(e) => setVersionSearch(e.target.value)} + /> + </div> + <div className="flex flex-row space-x-2"> + <FieldLabel className="text-nowrap">Type</FieldLabel> + <Select + value={versionFilter} + onValueChange={(value) => setVersionFilter(value)} + > + <SelectTrigger> + <SelectValue placeholder="Filter by type" /> + </SelectTrigger> + <SelectContent alignItemWithTrigger={false}> + <SelectItem value="all">All Versions</SelectItem> + <SelectItem value="release">Release Versions</SelectItem> + <SelectItem value="snapshot">Snapshot Versions</SelectItem> + <SelectItem value="old_alpha">Old Alpha Versions</SelectItem> + <SelectItem value="old_beta">Old Beta Versions</SelectItem> + </SelectContent> + </Select> + </div> + <Button onClick={loadVersions} disabled={isLoading}> + Refresh + </Button> + </div> + {errorMessage && ( + <div className="size-full flex flex-col items-center justify-center space-y-2"> + <p className="text-red-500">{errorMessage}</p> + <Button variant="outline" onClick={loadVersions}> + Retry + </Button> + </div> + )} + {isLoading && !errorMessage ? ( + <div className="size-full flex flex-col items-center justify-center"> + <Spinner /> + <p>Loading versions...</p> + </div> + ) : ( + <div className="flex-1 overflow-hidden"> + <ScrollArea className="size-full pr-2"> + <Controller + name="versionId" + control={control} + render={({ field }) => ( + <RadioGroup + {...field} + value={field.value || ""} + className="space-y-2" + > + {filteredVersions?.map((version) => ( + <FieldLabel key={version.id} htmlFor={version.id}> + <Field orientation="horizontal" className="py-2"> + <FieldContent> + <FieldTitle> + {version.id} + <Badge variant="outline">{version.type}</Badge> + </FieldTitle> + <FieldDescription> + {new Date(version.releaseTime).toLocaleString()} + </FieldDescription> + </FieldContent> + <div className="flex flex-row space-x-2 items-center"> + <Button + size="icon" + variant="ghost" + onClick={() => { + open( + `https://zh.minecraft.wiki/w/Java%E7%89%88${version.id}`, + ); + }} + > + <Link2Icon /> + </Button> + <RadioGroupItem value={version.id} id={version.id} /> + </div> + </Field> + </FieldLabel> + ))} + </RadioGroup> + )} + ></Controller> + </ScrollArea> + </div> + )} + {errors.versionId && <FieldError errors={[errors.versionId]} />} + </div> + ); +} + +const instanceSchema = z.object({ + name: z.string().min(1, "Instance name is required"), + notes: z.string().max(100, "Notes must be at most 100 characters").optional(), + modLoader: z.enum(["fabric", "forge"]).optional(), + modLoaderVersion: z.string().optional(), +}); + +function InstanceComponent() { + const { + control, + register, + formState: { errors }, + } = useFormContext<z.infer<typeof instanceSchema>>(); + + const versionId = useVersionId(); + + const [forgeVersions, setForgeVersions] = useState<ForgeVersion[] | null>( + null, + ); + const [fabricVersions, setFabricVersions] = useState< + FabricLoaderEntry[] | null + >(null); + + const [isLoadingForge, setIsLoadingForge] = useState(false); + const [isLoadingFabric, setIsLoadingFabric] = useState(false); + const loadForgeVersions = useCallback(async () => { + if (forgeVersions) return; + if (!versionId) return toast.error("Version ID is not set"); + setIsLoadingForge(true); + try { + const versions = await getForgeVersionsForGame(versionId); + setForgeVersions(versions); + } catch (e) { + console.error("Failed to load Forge versions:", e); + toast.error(`Failed to load Forge versions: ${String(e)}`); + } finally { + setIsLoadingForge(false); + } + }, [versionId, forgeVersions]); + const loadFabricVersions = useCallback(async () => { + if (fabricVersions) return; + if (!versionId) return toast.error("Version ID is not set"); + setIsLoadingFabric(true); + try { + const versions = await getFabricLoadersForVersion(versionId); + setFabricVersions(versions); + } catch (e) { + console.error("Failed to load Fabric versions:", e); + toast.error(`Failed to load Fabric versions: ${String(e)}`); + } finally { + setIsLoadingFabric(false); + } + }, [versionId, fabricVersions]); + + const modLoaderField = register("modLoader"); + const modLoaderVersionField = register("modLoaderVersion"); + + return ( + <ScrollArea className="size-full pr-2"> + <div className="h-full flex flex-col space-y-4"> + <div className="bg-card w-full p-6 shadow shrink-0"> + <FieldSet className="w-full"> + <Field orientation="horizontal"> + <FieldLabel htmlFor="name" className="text-nowrap" required> + Instance Name + </FieldLabel> + <Input {...register("name")} aria-invalid={!!errors.name} /> + {errors.name && <FieldError errors={[errors.name]} />} + </Field> + <Field> + <FieldLabel htmlFor="notes" className="text-nowrap"> + Instance Notes + </FieldLabel> + <Textarea + className="resize-none min-h-0" + {...register("notes")} + rows={1} + /> + {errors.notes && <FieldError errors={[errors.notes]} />} + </Field> + </FieldSet> + </div> + + <Accordion className="border"> + <AccordionItem + value="forge" + onOpenChange={(open) => { + if (open) loadForgeVersions(); + }} + > + <Watch + control={control} + render={({ modLoader, modLoaderVersion }) => ( + <AccordionTrigger + className="border-b px-4 py-3" + disabled={modLoader && modLoader !== "forge"} + > + <div className="flex flex-row w-full items-center space-x-4"> + <span className="font-bold">Forge</span> + {modLoader === "forge" && ( + <> + <span className="text-nowrap font-bold"> + {modLoaderVersion} + </span> + <Button + size="icon" + variant="ghost" + nativeButton={false} + onClick={(e) => { + e.stopPropagation(); + modLoaderField.onChange({ + target: { + name: modLoaderField.name, + value: null, + }, + }); + modLoaderVersionField.onChange({ + target: { + name: modLoaderVersionField.name, + value: null, + }, + }); + }} + render={(domProps) => ( + <div {...domProps}> + <XIcon /> + </div> + )} + /> + </> + )} + </div> + </AccordionTrigger> + )} + /> + <AccordionContent> + {isLoadingForge ? ( + <div className="h-full flex flex-col items-center justify-center"> + <Spinner /> + <p>Loading Forge versions...</p> + </div> + ) : ( + <div className="h-full flex flex-col"> + {forgeVersions?.map((version, idx) => ( + <React.Fragment + key={`forge-${version.version}-${version.minecraftVersion}`} + > + <Button + variant="ghost" + className="p-3 py-6 border-b justify-start" + onClick={() => { + modLoaderField.onChange({ + target: { + name: modLoaderField.name, + value: "forge", + }, + }); + modLoaderVersionField.onChange({ + target: { + name: modLoaderVersionField.name, + value: version.version, + }, + }); + }} + > + Forge {version.version} for Minecraft{" "} + {version.minecraftVersion} + </Button> + {idx !== forgeVersions.length - 1 && <Separator />} + </React.Fragment> + ))} + </div> + )} + </AccordionContent> + </AccordionItem> + <AccordionItem + value="fabric" + onOpenChange={(open) => { + if (open) loadFabricVersions(); + }} + > + <Watch + control={control} + render={({ modLoader, modLoaderVersion }) => ( + <AccordionTrigger + className="border-b px-4 py-3" + disabled={modLoader && modLoader !== "fabric"} + > + <div className="flex flex-row w-full items-center space-x-4"> + <span className="font-bold">Fabric</span> + {modLoader === "fabric" && ( + <> + <span className="text-nowrap font-bold"> + {modLoaderVersion} + </span> + <Button + size="icon" + variant="ghost" + nativeButton={false} + onClick={(e) => { + e.stopPropagation(); + modLoaderField.onChange({ + target: { + name: modLoaderField.name, + value: null, + }, + }); + modLoaderVersionField.onChange({ + target: { + name: modLoaderVersionField.name, + value: null, + }, + }); + }} + render={(domProps) => ( + <div {...domProps}> + <XIcon /> + </div> + )} + /> + </> + )} + </div> + </AccordionTrigger> + )} + /> + + <AccordionContent> + {isLoadingFabric ? ( + <div className="h-full flex flex-col items-center justify-center"> + <Spinner /> + <p>Loading Fabric versions...</p> + </div> + ) : ( + <div className="h-full flex flex-col"> + {fabricVersions?.map((version, idx) => ( + <React.Fragment + key={`fabric-${version.loader.version}-${version.intermediary.version}`} + > + <Button + variant="ghost" + className="p-3 py-6 border-b justify-start" + onClick={() => { + modLoaderField.onChange({ + target: { + name: modLoaderField.name, + value: "fabric", + }, + }); + modLoaderVersionField.onChange({ + target: { + name: modLoaderVersionField.name, + value: version.loader.version, + }, + }); + }} + > + Fabric {version.loader.version} for Minecraft{" "} + {version.intermediary.version} + </Button> + {idx !== fabricVersions.length - 1 && <Separator />} + </React.Fragment> + ))} + </div> + )} + </AccordionContent> + </AccordionItem> + </Accordion> + </div> + </ScrollArea> + ); +} + +const VersionIdContext = createContext<string | null>(null); +export const useVersionId = () => useContext(VersionIdContext); + +const { useStepper, Stepper } = defineStepper( + { + id: "version", + title: "Version", + Component: VersionComponent, + schema: versionSchema, + }, + { + id: "instance", + title: "Instance", + Component: InstanceComponent, + schema: instanceSchema, + }, +); + +export function CreateInstancePage() { + const stepper = useStepper(); + const schema = stepper.state.current.data.schema; + const form = useForm<z.infer<typeof schema>>({ + resolver: zodResolver(schema), + }); + const navigate = useNavigate(); + + const instanceStore = useInstanceStore(); + + const [versions, setVersions] = useState<Version[] | null>(null); + useEffect(() => { + const loadVersions = async () => { + const versions = await getVersions(); + setVersions(versions); + }; + if (!versions) loadVersions(); + }, [versions]); + + // Step 2 + const [versionId, setVersionId] = useState<string | null>(null); + + // Step 2 + // 这里不要动,后面会做一个download页面,需要迁移到download-models + const [_instanceMeta, setInstanceMeta] = useState<z.infer< + typeof instanceSchema + > | null>(null); + + const [isCreating, setIsCreating] = useState(false); + const handleSubmit = useCallback( + async (data: z.infer<typeof schema>) => { + switch (stepper.state.current.data.id) { + case "version": + setVersionId((data as z.infer<typeof versionSchema>).versionId); + return await stepper.navigation.next(); + case "instance": + setInstanceMeta(data as z.infer<typeof instanceSchema>); + } + + if (!versionId) return toast.error("Please select a version first"); + + setIsCreating(true); + + // 这里不要动,React数据是异步更新,直接用的数据才是实时的 + const instanceMeta = data as z.infer<typeof instanceSchema>; + + try { + const instance = await instanceStore.create(instanceMeta.name); + instance.notes = instanceMeta.notes ?? null; + await updateInstance(instance); + + await installVersion(instance.id, versionId); + switch (instanceMeta.modLoader) { + case "fabric": + if (!instanceMeta.modLoaderVersion) { + toast.error("Please select a Fabric loader version"); + return; + } + await installFabric( + instance.id, + versionId, + instanceMeta.modLoaderVersion, + ); + break; + case "forge": + if (!instanceMeta.modLoaderVersion) { + toast.error("Please select a Forge loader version"); + return; + } + await installForge( + instance.id, + versionId, + instanceMeta.modLoaderVersion, + ); + break; + default: + toast.error("Unsupported mod loader"); + break; + } + + navigate("/instances"); + } catch (error) { + console.error(error); + toast.error("Failed to create instance"); + } finally { + setIsCreating(false); + } + }, + [stepper, instanceStore.create, versionId, navigate], + ); + + return ( + <FormProvider {...form}> + <Stepper.List className="w-full flex list-none flex-row items-center justify-center px-6 mb-6"> + {stepper.state.all.map((step, idx) => { + const current = stepper.state.current; + const isInactive = stepper.state.current.data.id !== step.id; + const isLast = stepper.lookup.getLast().id === step.id; + return ( + <React.Fragment key={`stepper-item-${step.id}`}> + <Stepper.Item step={step.id}> + <Stepper.Trigger + render={(domProps) => ( + <Button + className="rounded-full" + variant={isInactive ? "secondary" : "default"} + size="icon" + disabled={isInactive} + {...domProps} + > + <Stepper.Indicator>{idx + 1}</Stepper.Indicator> + </Button> + )} + /> + </Stepper.Item> + {!isLast && ( + <Stepper.Separator + orientation="horizontal" + data-status={current.status} + className={cn( + "w-full h-0.5 mx-2", + "bg-muted data-[status=success]:bg-primary data-disabled:opacity-50", + "transition-all duration-300 ease-in-out", + )} + /> + )} + </React.Fragment> + ); + })} + </Stepper.List> + <form + className="flex flex-col flex-1 min-h-0 space-y-4 px-6" + onSubmit={form.handleSubmit(handleSubmit)} + > + <div className="flex-1 overflow-hidden w-full max-w-xl mx-auto"> + <VersionIdContext.Provider value={versionId}> + {stepper.flow.switch({ + version: ({ Component }) => <Component />, + instance: ({ Component }) => <Component />, + })} + </VersionIdContext.Provider> + </div> + <div className="w-full flex flex-row justify-between"> + <Stepper.Prev + render={(domProps) => ( + <Button + type="button" + variant="secondary" + disabled={isCreating} + {...domProps} + > + Previous + </Button> + )} + /> + {stepper.state.isLast ? ( + <Button type="submit" disabled={isCreating}> + {isCreating ? ( + <> + <Spinner /> + Creating + </> + ) : ( + "Create" + )} + </Button> + ) : ( + <Button type="submit">Next</Button> + )} + </div> + </form> + </FormProvider> + ); +} + +function PageWrapper() { + const navigate = useNavigate(); + const [showCancelDialog, setShowCancelDialog] = useState(false); + + return ( + <div className="flex size-full overflow-hidden px-6 py-8"> + <Stepper.Root + className="flex flex-col flex-1 space-y-4" + orientation="horizontal" + > + {({ stepper }) => ( + <> + <div className="flex flex-row space-x-4"> + <Button + variant="secondary" + size="icon" + onClick={() => { + if (stepper.state.isFirst) return navigate(-1); + setShowCancelDialog(true); + }} + > + <ArrowLeftIcon /> + </Button> + <h1 className="text-2xl font-bold">Create Instance</h1> + </div> + <p className="text-sm text-muted-foreground"> + Create a new Minecraft instance. + </p> + <CreateInstancePage /> + </> + )} + </Stepper.Root> + + <AlertDialog open={showCancelDialog} onOpenChange={setShowCancelDialog}> + <AlertDialogContent> + <AlertDialogHeader> + <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle> + <AlertDialogDescription> + All your progress will be lost. + </AlertDialogDescription> + </AlertDialogHeader> + <AlertDialogFooter> + <AlertDialogCancel>Cancel</AlertDialogCancel> + <AlertDialogAction + variant="destructive" + onClick={() => navigate(-1)} + > + Continue + </AlertDialogAction> + </AlertDialogFooter> + </AlertDialogContent> + </AlertDialog> + </div> + ); +} + +export default PageWrapper; diff --git a/packages/ui/src/pages/instances-view.tsx b/packages/ui/src/pages/instances/index.tsx index 7bb3302..e6cd734 100644 --- a/packages/ui/src/pages/instances-view.tsx +++ b/packages/ui/src/pages/instances/index.tsx @@ -2,6 +2,7 @@ import { open, save } from "@tauri-apps/plugin-dialog"; import { CopyIcon, EditIcon, + EllipsisIcon, FolderOpenIcon, Plus, RocketIcon, @@ -9,9 +10,9 @@ import { XIcon, } from "lucide-react"; import { useEffect, useState } from "react"; +import { useNavigate } from "react-router"; import { toast } from "sonner"; import { openFileExplorer } from "@/client"; -import InstanceCreationModal from "@/components/instance-creation-modal"; import InstanceEditorModal from "@/components/instance-editor-modal"; import { Button } from "@/components/ui/button"; import { @@ -25,30 +26,31 @@ import { import { Input } from "@/components/ui/input"; import { cn } from "@/lib/utils"; import { useAuthStore } from "@/models/auth"; +import { useGameStore } from "@/models/game"; import { useInstanceStore } from "@/models/instance"; -import { useGameStore } from "@/stores/game-store"; import type { Instance } from "@/types"; -export function InstancesView() { - const account = useAuthStore((state) => state.account); +export function InstancesPage() { const instancesStore = useInstanceStore(); - const startGame = useGameStore((state) => state.startGame); - const stopGame = useGameStore((state) => state.stopGame); - const runningInstanceId = useGameStore((state) => state.runningInstanceId); - const launchingInstanceId = useGameStore( - (state) => state.launchingInstanceId, - ); - const stoppingInstanceId = useGameStore((state) => state.stoppingInstanceId); - const [isImporting, setIsImporting] = useState(false); - const [repairing, setRepairing] = useState(false); - const [exportingId, setExportingId] = useState<string | null>(null); + const navigate = useNavigate(); + + const account = useAuthStore((state) => state.account); + const { + startGame, + runningInstanceId, + stoppingInstanceId, + launchingInstanceId, + stopGame, + } = useGameStore(); - // Modal / UI state - const [showCreateModal, setShowCreateModal] = useState(false); const [showEditModal, setShowEditModal] = useState(false); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [showDuplicateModal, setShowDuplicateModal] = useState(false); + const [isImporting, setIsImporting] = useState(false); + const [repairing, setRepairing] = useState(false); + const [exportingId, setExportingId] = useState<string | null>(null); + // Selected / editing instance state const [selectedInstance, setSelectedInstance] = useState<Instance | null>( null, @@ -64,7 +66,7 @@ export function InstancesView() { // Handlers to open modals const openCreate = () => { - setShowCreateModal(true); + navigate("/instances/create"); }; const openEdit = (instance: Instance) => { @@ -151,7 +153,7 @@ export function InstancesView() { <h1 className="text-2xl font-bold text-gray-900 dark:text-white"> Instances </h1> - <div className="flex items-center gap-2"> + <div className="flex flex-row space-x-2"> <Button type="button" variant="outline" @@ -190,11 +192,9 @@ export function InstancesView() { <ul className="flex flex-col space-y-3"> {instancesStore.instances.map((instance) => { const isActive = instancesStore.activeInstance?.id === instance.id; - const isRunning = runningInstanceId === instance.id; const isLaunching = launchingInstanceId === instance.id; const isStopping = stoppingInstanceId === instance.id; - const otherInstanceRunning = - runningInstanceId !== null && !isRunning; + const isRunning = runningInstanceId === instance.id; return ( <li @@ -280,22 +280,27 @@ export function InstancesView() { return; } - await startGame( - account, - () => { - toast.info("Please login first"); - }, - instance.id, - instance.versionId, - () => undefined, - ); + if (!account) { + toast.info("Please login first"); + return; + } + + try { + await startGame(instance.id, instance.versionId); + } catch (error) { + console.error("Failed to start game:", error); + toast.error("Error starting game"); + } }} disabled={ - otherInstanceRunning || isLaunching || isStopping + (!!runningInstanceId && + runningInstanceId !== instance.id) || + isLaunching || + isStopping } > {isLaunching || isStopping ? ( - <span className="text-xs">...</span> + <EllipsisIcon /> ) : isRunning ? ( <XIcon /> ) : ( @@ -364,10 +369,10 @@ export function InstancesView() { </ul> )} - <InstanceCreationModal + {/*<InstanceCreationModal open={showCreateModal} onOpenChange={setShowCreateModal} - /> + />*/} <InstanceEditorModal open={showEditModal} diff --git a/packages/ui/src/pages/instances/routes.ts b/packages/ui/src/pages/instances/routes.ts new file mode 100644 index 0000000..cd1255d --- /dev/null +++ b/packages/ui/src/pages/instances/routes.ts @@ -0,0 +1,19 @@ +import type { RouteObject } from "react-router"; +import CreateInstancePage from "./create"; +import { InstancesPage } from "./index"; + +const routes = { + path: "/instances", + children: [ + { + index: true, + Component: InstancesPage, + }, + { + path: "create", + Component: CreateInstancePage, + }, + ], +} satisfies RouteObject; + +export default routes; diff --git a/packages/ui/src/pages/routes.ts b/packages/ui/src/pages/routes.ts new file mode 100644 index 0000000..55eb8fd --- /dev/null +++ b/packages/ui/src/pages/routes.ts @@ -0,0 +1,25 @@ +import { createHashRouter } from "react-router"; +import { HomePage } from "./home"; +import { IndexPage } from "./index"; +import instanceRoute from "./instances/routes"; +import { SettingsPage } from "./settings"; + +const router = createHashRouter([ + { + path: "/", + Component: IndexPage, + children: [ + { + index: true, + Component: HomePage, + }, + { + path: "settings", + Component: SettingsPage, + }, + instanceRoute, + ], + }, +]); + +export default router; |