diff options
Diffstat (limited to 'packages/ui/src')
20 files changed, 299 insertions, 1163 deletions
diff --git a/packages/ui/src/components/instance-editor-modal.tsx b/packages/ui/src/components/instance-editor-modal.tsx index d964185..2a2bd7d 100644 --- a/packages/ui/src/components/instance-editor-modal.tsx +++ b/packages/ui/src/components/instance-editor-modal.tsx @@ -1,8 +1,8 @@ -import { invoke } from "@tauri-apps/api/core"; + +import { toNumber } from "es-toolkit/compat"; import { Folder, Loader2, Save, Trash2, X } from "lucide-react"; import { useCallback, useEffect, useState } from "react"; import { toast } from "sonner"; - import { Button } from "@/components/ui/button"; import { Dialog, @@ -14,12 +14,11 @@ import { } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; - -import { toNumber } from "@/lib/tsrs-utils"; import { useInstanceStore } from "@/models/instance"; import { useSettingsStore } from "@/models/settings"; import type { FileInfo } from "../types/bindings/core"; import type { Instance } from "../types/bindings/instance"; +import { deleteInstanceFile, listInstanceDirectory, openFileExplorer } from "@/client"; type Props = { open: boolean; @@ -94,11 +93,8 @@ export function InstanceEditorModal({ open, instance, onOpenChange }: Props) { if (!instance) return; setLoadingFiles(true); try { - const files = await invoke<FileInfo[]>("list_instance_directory", { - instanceId: instance.id, - folder, - }); - setFileList(files || []); + const files = await listInstanceDirectory(instance.id, folder); + setFileList(files); } catch (err) { console.error("Failed to load files:", err); toast.error("Failed to load files: " + String(err)); @@ -135,7 +131,7 @@ export function InstanceEditorModal({ open, instance, onOpenChange }: Props) { } setDeletingPath(filePath); try { - await invoke("delete_instance_file", { path: filePath }); + await deleteInstanceFile(filePath); // refresh the currently selected folder await loadFileList(selectedFileFolder); toast.success("Deleted"); @@ -149,7 +145,7 @@ export function InstanceEditorModal({ open, instance, onOpenChange }: Props) { async function openInExplorer(filePath: string) { try { - await invoke("open_file_explorer", { path: filePath }); + await openFileExplorer(filePath); } catch (err) { console.error("Failed to open in explorer:", err); toast.error("Failed to open file explorer: " + String(err)); diff --git a/packages/ui/src/components/particle-background.tsx b/packages/ui/src/components/particle-background.tsx index 2e0b15a..2bf6793 100644 --- a/packages/ui/src/components/particle-background.tsx +++ b/packages/ui/src/components/particle-background.tsx @@ -1,63 +1,55 @@ -import { useEffect, useRef } from "react"; -import { SaturnEffect } from "../lib/effects/SaturnEffect"; +import { createContext, useContext, useEffect, useRef, useState } from "react"; +import { SaturnEffect } from "@/lib/effects/saturn"; -export function ParticleBackground() { +const SaturnEffectContext = createContext<SaturnEffect | null>(null); + +export function useSaturnEffect() { + return useContext(SaturnEffectContext); +} + +export function ParticleBackground({ + children, +}: { + children?: React.ReactNode; +}) { const canvasRef = useRef<HTMLCanvasElement | null>(null); - const effectRef = useRef<SaturnEffect | null>(null); + const [effect, setEffect] = useState<SaturnEffect | null>(null); useEffect(() => { const canvas = canvasRef.current; if (!canvas) return; - // Instantiate SaturnEffect and attach to canvas - let effect: SaturnEffect | null = null; + let saturnEffect: SaturnEffect | null = null; try { - effect = new SaturnEffect(canvas); - effectRef.current = effect; + saturnEffect = new SaturnEffect(canvas); + setEffect(saturnEffect); } catch (err) { - // If effect fails, silently degrade (keep background blank) - // eslint-disable-next-line no-console console.warn("SaturnEffect initialization failed:", err); } const resizeHandler = () => { - if (effectRef.current) { - try { - effectRef.current.resize(window.innerWidth, window.innerHeight); - } catch { - // ignore - } - } + saturnEffect?.resize(window.innerWidth, window.innerHeight); }; window.addEventListener("resize", resizeHandler); - // Expose getter for HomeView interactions (getSaturnEffect) - // HomeView will call window.getSaturnEffect()?.handleMouseDown/Move/Up - ( - window as unknown as { getSaturnEffect?: () => SaturnEffect | null } - ).getSaturnEffect = () => effectRef.current; - return () => { window.removeEventListener("resize", resizeHandler); - if (effectRef.current) { - try { - effectRef.current.destroy(); - } catch { - // ignore - } - } - effectRef.current = null; - ( - window as unknown as { getSaturnEffect?: () => SaturnEffect | null } - ).getSaturnEffect = undefined; + saturnEffect?.destroy(); + + setEffect(null); }; }, []); return ( - <canvas - ref={canvasRef} - className="absolute inset-0 z-0 pointer-events-none" - /> + <SaturnEffectContext.Provider value={effect}> + <canvas + ref={canvasRef} + className="absolute inset-0 -z-10 pointer-events-none" + /> + {children} + </SaturnEffectContext.Provider> ); } + +export default ParticleBackground; diff --git a/packages/ui/src/components/sidebar.tsx b/packages/ui/src/components/sidebar.tsx index d81156f..e615274 100644 --- a/packages/ui/src/components/sidebar.tsx +++ b/packages/ui/src/components/sidebar.tsx @@ -23,10 +23,6 @@ function NavItem({ Icon, label, to }: NavItemProps) { const location = useLocation(); const isActive = location.pathname === to; - const handleClick = () => { - navigate(to); - }; - return ( <Button variant="ghost" @@ -35,7 +31,7 @@ function NavItem({ Icon, label, to }: NavItemProps) { isActive && "relative bg-accent", )} size="lg" - onClick={handleClick} + onClick={() => navigate(to)} > <Icon className="size-5" strokeWidth={isActive ? 2.5 : 2} /> <span className="hidden lg:block text-sm relative z-10">{label}</span> @@ -185,7 +181,11 @@ export function Sidebar() { <div className="w-full lg:px-3 flex-1 flex flex-col justify-end"> <DropdownMenu> - <DropdownMenuTrigger render={renderUserAvatar()} className="w-full"> + <DropdownMenuTrigger + render={renderUserAvatar()} + nativeButton={false} + className="w-full" + > Open </DropdownMenuTrigger> <DropdownMenuContent align="end" side="right" sideOffset={20}> diff --git a/packages/ui/src/components/ui/alert-dialog.tsx b/packages/ui/src/components/ui/alert-dialog.tsx new file mode 100644 index 0000000..27c9f77 --- /dev/null +++ b/packages/ui/src/components/ui/alert-dialog.tsx @@ -0,0 +1,186 @@ +"use client"; + +import { AlertDialog as AlertDialogPrimitive } from "@base-ui/react/alert-dialog"; +import type * as React from "react"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; + +function AlertDialog({ ...props }: AlertDialogPrimitive.Root.Props) { + return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />; +} + +function AlertDialogTrigger({ ...props }: AlertDialogPrimitive.Trigger.Props) { + return ( + <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} /> + ); +} + +function AlertDialogPortal({ ...props }: AlertDialogPrimitive.Portal.Props) { + return ( + <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} /> + ); +} + +function AlertDialogOverlay({ + className, + ...props +}: AlertDialogPrimitive.Backdrop.Props) { + return ( + <AlertDialogPrimitive.Backdrop + data-slot="alert-dialog-overlay" + className={cn( + "fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0", + className, + )} + {...props} + /> + ); +} + +function AlertDialogContent({ + className, + size = "default", + ...props +}: AlertDialogPrimitive.Popup.Props & { + size?: "default" | "sm"; +}) { + return ( + <AlertDialogPortal> + <AlertDialogOverlay /> + <AlertDialogPrimitive.Popup + data-slot="alert-dialog-content" + data-size={size} + className={cn( + "group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-4 rounded-none bg-background p-4 ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", + className, + )} + {...props} + /> + </AlertDialogPortal> + ); +} + +function AlertDialogHeader({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( + <div + data-slot="alert-dialog-header" + className={cn( + "grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-4 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]", + className, + )} + {...props} + /> + ); +} + +function AlertDialogFooter({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( + <div + data-slot="alert-dialog-footer" + className={cn( + "flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end", + className, + )} + {...props} + /> + ); +} + +function AlertDialogMedia({ + className, + ...props +}: React.ComponentProps<"div">) { + return ( + <div + data-slot="alert-dialog-media" + className={cn( + "mb-2 inline-flex size-10 items-center justify-center rounded-none bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-6", + className, + )} + {...props} + /> + ); +} + +function AlertDialogTitle({ + className, + ...props +}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) { + return ( + <AlertDialogPrimitive.Title + data-slot="alert-dialog-title" + className={cn( + "text-sm font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2", + className, + )} + {...props} + /> + ); +} + +function AlertDialogDescription({ + className, + ...props +}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) { + return ( + <AlertDialogPrimitive.Description + data-slot="alert-dialog-description" + className={cn( + "text-xs/relaxed text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground", + className, + )} + {...props} + /> + ); +} + +function AlertDialogAction({ + className, + ...props +}: React.ComponentProps<typeof Button>) { + return ( + <Button + data-slot="alert-dialog-action" + className={cn(className)} + {...props} + /> + ); +} + +function AlertDialogCancel({ + className, + variant = "outline", + size = "default", + ...props +}: AlertDialogPrimitive.Close.Props & + Pick<React.ComponentProps<typeof Button>, "variant" | "size">) { + return ( + <AlertDialogPrimitive.Close + data-slot="alert-dialog-cancel" + className={cn(className)} + render={<Button variant={variant} size={size} />} + {...props} + /> + ); +} + +export { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogMedia, + AlertDialogOverlay, + AlertDialogPortal, + AlertDialogTitle, + AlertDialogTrigger, +}; diff --git a/packages/ui/src/components/ui/field.tsx b/packages/ui/src/components/ui/field.tsx index ab9fb71..10bd9c9 100644 --- a/packages/ui/src/components/ui/field.tsx +++ b/packages/ui/src/components/ui/field.tsx @@ -9,7 +9,7 @@ function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) { <fieldset data-slot="field-set" className={cn( - "gap-4 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3 flex flex-col", + "flex flex-col gap-4 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3", className, )} {...props} @@ -40,7 +40,7 @@ function FieldGroup({ className, ...props }: React.ComponentProps<"div">) { <div data-slot="field-group" className={cn( - "gap-5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4 group/field-group @container/field-group flex w-full flex-col", + "group/field-group @container/field-group flex w-full flex-col gap-5 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4", className, )} {...props} @@ -49,15 +49,15 @@ function FieldGroup({ className, ...props }: React.ComponentProps<"div">) { } const fieldVariants = cva( - "data-[invalid=true]:text-destructive gap-2 group/field flex w-full", + "group/field flex w-full gap-2 data-[invalid=true]:text-destructive", { variants: { orientation: { vertical: "flex-col *:w-full [&>.sr-only]:w-auto", horizontal: - "flex-row items-center *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px", + "flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px", responsive: - "flex-col *:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:*:data-[slot=field-label]:flex-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px", + "flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px", }, }, defaultVariants: { @@ -72,7 +72,9 @@ function Field({ ...props }: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) { return ( + // biome-ignore lint/a11y/useSemanticElements: shadcn component <div + role="group" data-slot="field" data-orientation={orientation} className={cn(fieldVariants({ orientation }), className)} @@ -86,7 +88,7 @@ function FieldContent({ className, ...props }: React.ComponentProps<"div">) { <div data-slot="field-content" className={cn( - "gap-0.5 group/field-content flex flex-1 flex-col leading-snug", + "group/field-content flex flex-1 flex-col gap-0.5 leading-snug", className, )} {...props} @@ -102,7 +104,7 @@ function FieldLabel({ <Label data-slot="field-label" className={cn( - "has-data-checked:bg-primary/5 has-data-checked:border-primary/30 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10 gap-2 group-data-[disabled=true]/field:opacity-50 has-[>[data-slot=field]]:rounded-none has-[>[data-slot=field]]:border *:data-[slot=field]:p-2 group/field-label peer/field-label flex w-fit leading-snug", + "group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-none has-[>[data-slot=field]]:border *:data-[slot=field]:p-2 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10", "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col", className, )} @@ -116,7 +118,7 @@ function FieldTitle({ className, ...props }: React.ComponentProps<"div">) { <div data-slot="field-label" className={cn( - "gap-2 text-xs/relaxed group-data-[disabled=true]/field:opacity-50 flex w-fit items-center leading-snug", + "flex w-fit items-center gap-2 text-xs/relaxed leading-snug group-data-[disabled=true]/field:opacity-50", className, )} {...props} @@ -129,9 +131,9 @@ function FieldDescription({ className, ...props }: React.ComponentProps<"p">) { <p data-slot="field-description" className={cn( - "text-muted-foreground text-left text-xs/relaxed [[data-variant=legend]+&]:-mt-1.5 leading-normal font-normal group-has-data-horizontal/field:text-balance", + "text-left text-xs/relaxed leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5", "last:mt-0 nth-last-2:-mt-1", - "[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4", + "[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary", className, )} {...props} @@ -151,7 +153,7 @@ function FieldSeparator({ data-slot="field-separator" data-content={!!children} className={cn( - "-my-2 h-5 text-xs group-data-[variant=outline]/field-group:-mb-2 relative", + "relative -my-2 h-5 text-xs group-data-[variant=outline]/field-group:-mb-2", className, )} {...props} @@ -159,7 +161,7 @@ function FieldSeparator({ <Separator className="absolute inset-0 top-1/2" /> {children && ( <span - className="text-muted-foreground px-2 bg-background relative mx-auto block w-fit" + className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground" data-slot="field-separator-content" > {children} @@ -197,11 +199,9 @@ function FieldError({ return ( <ul className="ml-4 flex list-disc flex-col gap-1"> {uniqueErrors.map( - (error, index) => + (error) => error?.message && ( - <li key={`${error.message.slice(6)}-${index}`}> - {error.message} - </li> + <li key={`field-error-${error}`}>{error.message}</li> ), )} </ul> @@ -216,7 +216,7 @@ function FieldError({ <div role="alert" data-slot="field-error" - className={cn("text-destructive text-xs font-normal", className)} + className={cn("text-xs font-normal text-destructive", className)} {...props} > {content} diff --git a/packages/ui/src/components/ui/label.tsx b/packages/ui/src/components/ui/label.tsx index 9a998c7..0d40c81 100644 --- a/packages/ui/src/components/ui/label.tsx +++ b/packages/ui/src/components/ui/label.tsx @@ -8,7 +8,7 @@ function Label({ className, ...props }: React.ComponentProps<"label">) { <label data-slot="label" className={cn( - "gap-2 text-xs leading-none group-data-[disabled=true]:opacity-50 peer-disabled:opacity-50 flex items-center select-none group-data-[disabled=true]:pointer-events-none peer-disabled:cursor-not-allowed", + "flex items-center gap-2 text-xs leading-none select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50", className, )} {...props} diff --git a/packages/ui/src/components/ui/radio-group.tsx b/packages/ui/src/components/ui/radio-group.tsx index d8b39dd..df831e8 100644 --- a/packages/ui/src/components/ui/radio-group.tsx +++ b/packages/ui/src/components/ui/radio-group.tsx @@ -1,7 +1,7 @@ -import { Radio as RadioPrimitive } from "@base-ui/react/radio" -import { RadioGroup as RadioGroupPrimitive } from "@base-ui/react/radio-group" +import { Radio as RadioPrimitive } from "@base-ui/react/radio"; +import { RadioGroup as RadioGroupPrimitive } from "@base-ui/react/radio-group"; -import { cn } from "@/lib/utils" +import { cn } from "@/lib/utils"; function RadioGroup({ className, ...props }: RadioGroupPrimitive.Props) { return ( @@ -10,7 +10,7 @@ function RadioGroup({ className, ...props }: RadioGroupPrimitive.Props) { className={cn("grid w-full gap-2", className)} {...props} /> - ) + ); } function RadioGroupItem({ className, ...props }: RadioPrimitive.Root.Props) { @@ -19,7 +19,7 @@ function RadioGroupItem({ className, ...props }: RadioPrimitive.Root.Props) { data-slot="radio-group-item" className={cn( "border-input dark:bg-input/30 data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary data-checked:border-primary aria-invalid:aria-checked:border-primary aria-invalid:border-destructive focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 dark:aria-invalid:border-destructive/50 group/radio-group-item peer relative flex aspect-square size-4 shrink-0 rounded-full border outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:ring-3 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:ring-3", - className + className, )} {...props} > @@ -30,7 +30,7 @@ function RadioGroupItem({ className, ...props }: RadioPrimitive.Root.Props) { <span className="bg-primary-foreground absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full" /> </RadioPrimitive.Indicator> </RadioPrimitive.Root> - ) + ); } -export { RadioGroup, RadioGroupItem } +export { RadioGroup, RadioGroupItem }; diff --git a/packages/ui/src/lib/effects/SaturnEffect.ts b/packages/ui/src/lib/effects/saturn.ts index 497a340..f7fcfe5 100644 --- a/packages/ui/src/lib/effects/SaturnEffect.ts +++ b/packages/ui/src/lib/effects/saturn.ts @@ -1,21 +1,3 @@ -/** - * Ported SaturnEffect for the React UI (ui-new). - * Adapted from the original Svelte implementation but written as a standalone - * TypeScript class that manages a 2D canvas particle effect resembling a - * rotating "Saturn" with rings. Designed to be instantiated and controlled - * from a React component (e.g. ParticleBackground). - * - * Usage: - * const effect = new SaturnEffect(canvasElement); - * effect.handleMouseDown(clientX); - * effect.handleMouseMove(clientX); - * effect.handleMouseUp(); - * // on resize: - * effect.resize(width, height); - * // on unmount: - * effect.destroy(); - */ - export class SaturnEffect { private canvas: HTMLCanvasElement; private ctx: CanvasRenderingContext2D; diff --git a/packages/ui/src/lib/tsrs-utils.ts b/packages/ui/src/lib/tsrs-utils.ts deleted file mode 100644 index f48f851..0000000 --- a/packages/ui/src/lib/tsrs-utils.ts +++ /dev/null @@ -1,67 +0,0 @@ -export type Maybe<T> = T | null | undefined; - -export function toNumber( - value: Maybe<number | bigint | string>, - fallback = 0, -): number { - if (value === null || value === undefined) return fallback; - - if (typeof value === "number") { - if (Number.isFinite(value)) return value; - return fallback; - } - - if (typeof value === "bigint") { - // safe conversion for typical values (timestamps, sizes). Might overflow for huge bigint. - return Number(value); - } - - if (typeof value === "string") { - const n = Number(value); - return Number.isFinite(n) ? n : fallback; - } - - return fallback; -} - -/** - * Like `toNumber` but ensures non-negative result (clamps at 0). - */ -export function toNonNegativeNumber( - value: Maybe<number | bigint | string>, - fallback = 0, -): number { - const n = toNumber(value, fallback); - return n < 0 ? 0 : n; -} - -export function toDate( - value: Maybe<number | bigint | string>, - opts?: { isSeconds?: boolean }, -): Date | null { - if (value === null || value === undefined) return null; - - const isSeconds = opts?.isSeconds ?? true; - - // accept bigint, number, numeric string - const n = toNumber(value, NaN); - if (Number.isNaN(n)) return null; - - const ms = isSeconds ? Math.floor(n) * 1000 : Math.floor(n); - return new Date(ms); -} - -/** - * Convert a binding boolean-ish value (0/1, "true"/"false", boolean) to boolean. - */ -export function toBoolean(value: unknown, fallback = false): boolean { - if (value === null || value === undefined) return fallback; - if (typeof value === "boolean") return value; - if (typeof value === "number") return value !== 0; - if (typeof value === "string") { - const s = value.toLowerCase().trim(); - if (s === "true" || s === "1") return true; - if (s === "false" || s === "0") return false; - } - return fallback; -} diff --git a/packages/ui/src/main.tsx b/packages/ui/src/main.tsx index c5cbfc8..912fea8 100644 --- a/packages/ui/src/main.tsx +++ b/packages/ui/src/main.tsx @@ -1,33 +1,9 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import "./index.css"; -import { createHashRouter, RouterProvider } from "react-router"; +import { RouterProvider } from "react-router"; import { Toaster } from "./components/ui/sonner"; -import { HomeView } from "./pages/home-view"; -import { IndexPage } from "./pages/index"; -import { InstancesView } from "./pages/instances-view"; -import { SettingsPage } from "./pages/settings"; - -const router = createHashRouter([ - { - path: "/", - element: <IndexPage />, - children: [ - { - index: true, - element: <HomeView />, - }, - { - path: "instances", - element: <InstancesView />, - }, - { - path: "settings", - element: <SettingsPage />, - }, - ], - }, -]); +import router from "./pages/routes"; const root = createRoot(document.getElementById("root") as HTMLElement); root.render( diff --git a/packages/ui/src/stores/assistant-store.ts b/packages/ui/src/models/assistant-store.ts.bk index 180031b..180031b 100644 --- a/packages/ui/src/stores/assistant-store.ts +++ b/packages/ui/src/models/assistant-store.ts.bk diff --git a/packages/ui/src/stores/logs-store.ts b/packages/ui/src/models/logs-store.ts.bk index b19f206..b19f206 100644 --- a/packages/ui/src/stores/logs-store.ts +++ b/packages/ui/src/models/logs-store.ts.bk diff --git a/packages/ui/src/stores/settings-store.ts b/packages/ui/src/models/settings-store.ts.bk index 0bfc1e1..0bfc1e1 100644 --- a/packages/ui/src/stores/settings-store.ts +++ b/packages/ui/src/models/settings-store.ts.bk 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-view.tsx index 4f80cb0..6060370 100644 --- a/packages/ui/src/pages/home-view.tsx +++ b/packages/ui/src/pages/home-view.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(); 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 */ - } + 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 */ - } + 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 209a1b2..bccca22 100644 --- a/packages/ui/src/pages/index.tsx +++ b/packages/ui/src/pages/index.tsx @@ -50,8 +50,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> </> )} @@ -76,7 +74,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/routes.ts b/packages/ui/src/pages/routes.ts new file mode 100644 index 0000000..8d105d4 --- /dev/null +++ b/packages/ui/src/pages/routes.ts @@ -0,0 +1,25 @@ +import { createHashRouter } from "react-router"; +import { IndexPage } from "."; +import { HomeView } from "./home-view"; +import instanceRoute from "./instances/routes"; +import { SettingsPage } from "./settings"; + +const router = createHashRouter([ + { + path: "/", + Component: IndexPage, + children: [ + { + index: true, + Component: HomeView, + }, + { + path: "settings", + Component: SettingsPage, + }, + instanceRoute, + ], + }, +]); + +export default router; diff --git a/packages/ui/src/stores/auth-store.ts b/packages/ui/src/stores/auth-store.ts deleted file mode 100644 index bf7e3c5..0000000 --- a/packages/ui/src/stores/auth-store.ts +++ /dev/null @@ -1,296 +0,0 @@ -import { invoke } from "@tauri-apps/api/core"; -import { listen, type UnlistenFn } from "@tauri-apps/api/event"; -import { open } from "@tauri-apps/plugin-shell"; -import { toast } from "sonner"; -import { create } from "zustand"; -import type { Account, DeviceCodeResponse } from "../types/bindings/auth"; - -interface AuthState { - // State - currentAccount: Account | null; - isLoginModalOpen: boolean; - isLogoutConfirmOpen: boolean; - loginMode: "select" | "offline" | "microsoft"; - offlineUsername: string; - deviceCodeData: DeviceCodeResponse | null; - msLoginLoading: boolean; - msLoginStatus: string; - - // Private state - pollInterval: ReturnType<typeof setInterval> | null; - isPollingRequestActive: boolean; - authProgressUnlisten: UnlistenFn | null; - - // Actions - checkAccount: () => Promise<void>; - openLoginModal: () => void; - openLogoutConfirm: () => void; - cancelLogout: () => void; - confirmLogout: () => Promise<void>; - closeLoginModal: () => void; - resetLoginState: () => void; - performOfflineLogin: () => Promise<void>; - startMicrosoftLogin: () => Promise<void>; - checkLoginStatus: (deviceCode: string) => Promise<void>; - stopPolling: () => void; - cancelMicrosoftLogin: () => void; - setLoginMode: (mode: "select" | "offline" | "microsoft") => void; - setOfflineUsername: (username: string) => void; -} - -export const useAuthStore = create<AuthState>((set, get) => ({ - // Initial state - currentAccount: null, - isLoginModalOpen: false, - isLogoutConfirmOpen: false, - loginMode: "select", - offlineUsername: "", - deviceCodeData: null, - msLoginLoading: false, - msLoginStatus: "Waiting for authorization...", - - // Private state - pollInterval: null, - isPollingRequestActive: false, - authProgressUnlisten: null, - - // Actions - checkAccount: async () => { - try { - const acc = await invoke<Account | null>("get_active_account"); - set({ currentAccount: acc }); - } catch (error) { - console.error("Failed to check account:", error); - } - }, - - openLoginModal: () => { - const { currentAccount } = get(); - if (currentAccount) { - // Show custom logout confirmation dialog - set({ isLogoutConfirmOpen: true }); - return; - } - get().resetLoginState(); - set({ isLoginModalOpen: true }); - }, - - openLogoutConfirm: () => { - set({ isLogoutConfirmOpen: true }); - }, - - cancelLogout: () => { - set({ isLogoutConfirmOpen: false }); - }, - - confirmLogout: async () => { - set({ isLogoutConfirmOpen: false }); - try { - await invoke("logout"); - set({ currentAccount: null }); - } catch (error) { - console.error("Logout failed:", error); - } - }, - - closeLoginModal: () => { - get().stopPolling(); - set({ isLoginModalOpen: false }); - }, - - resetLoginState: () => { - set({ - loginMode: "select", - offlineUsername: "", - deviceCodeData: null, - msLoginLoading: false, - msLoginStatus: "Waiting for authorization...", - }); - }, - - performOfflineLogin: async () => { - const { offlineUsername } = get(); - if (!offlineUsername.trim()) return; - - try { - const account = await invoke<Account>("login_offline", { - username: offlineUsername, - }); - set({ - currentAccount: account, - isLoginModalOpen: false, - offlineUsername: "", - }); - } catch (error) { - // Keep UI-friendly behavior consistent with prior code - alert("Login failed: " + String(error)); - } - }, - - startMicrosoftLogin: async () => { - // Prepare UI state - set({ - msLoginLoading: true, - msLoginStatus: "Waiting for authorization...", - loginMode: "microsoft", - deviceCodeData: null, - }); - - // Listen to general launcher logs so we can display progress to the user. - // The backend emits logs via "launcher-log"; using that keeps this store decoupled - // from a dedicated auth event channel (backend may reuse launcher-log). - try { - const unlisten = await listen("launcher-log", (event) => { - const payload = event.payload; - // Normalize payload to string if possible - const message = - typeof payload === "string" - ? payload - : (payload?.toString?.() ?? JSON.stringify(payload)); - set({ msLoginStatus: message }); - }); - set({ authProgressUnlisten: unlisten }); - } catch (err) { - console.warn("Failed to attach launcher-log listener:", err); - } - - try { - const deviceCodeData = await invoke<DeviceCodeResponse>( - "start_microsoft_login", - ); - set({ deviceCodeData }); - - if (deviceCodeData) { - // Try to copy user code to clipboard for convenience (best-effort) - try { - await navigator.clipboard?.writeText(deviceCodeData.userCode ?? ""); - } catch (err) { - // ignore clipboard errors - console.debug("Clipboard copy failed:", err); - } - - // Open verification URI in default browser - try { - if (deviceCodeData.verificationUri) { - await open(deviceCodeData.verificationUri); - } - } catch (err) { - console.debug("Failed to open verification URI:", err); - } - - // Start polling for completion - // `interval` from the bindings is a bigint (seconds). Convert safely to number. - const intervalSeconds = - deviceCodeData.interval !== undefined && - deviceCodeData.interval !== null - ? Number(deviceCodeData.interval) - : 5; - const intervalMs = intervalSeconds * 1000; - const pollInterval = setInterval( - () => get().checkLoginStatus(deviceCodeData.deviceCode), - intervalMs, - ); - set({ pollInterval }); - } - } catch (error) { - toast.error(`Failed to start Microsoft login: ${error}`); - set({ loginMode: "select" }); - // cleanup listener if present - const { authProgressUnlisten } = get(); - if (authProgressUnlisten) { - authProgressUnlisten(); - set({ authProgressUnlisten: null }); - } - } finally { - set({ msLoginLoading: false }); - } - }, - - checkLoginStatus: async (deviceCode: string) => { - const { isPollingRequestActive } = get(); - if (isPollingRequestActive) return; - - set({ isPollingRequestActive: true }); - - try { - const account = await invoke<Account>("complete_microsoft_login", { - deviceCode, - }); - - // On success, stop polling and cleanup listener - get().stopPolling(); - const { authProgressUnlisten } = get(); - if (authProgressUnlisten) { - authProgressUnlisten(); - set({ authProgressUnlisten: null }); - } - - set({ - currentAccount: account, - isLoginModalOpen: false, - }); - } catch (error: unknown) { - const errStr = String(error); - if (errStr.includes("authorization_pending")) { - // Still waiting — keep polling - } else { - set({ msLoginStatus: "Error: " + errStr }); - - if ( - errStr.includes("expired_token") || - errStr.includes("access_denied") - ) { - // Terminal errors — stop polling and reset state - get().stopPolling(); - const { authProgressUnlisten } = get(); - if (authProgressUnlisten) { - authProgressUnlisten(); - set({ authProgressUnlisten: null }); - } - alert("Login failed: " + errStr); - set({ loginMode: "select" }); - } - } - } finally { - set({ isPollingRequestActive: false }); - } - }, - - stopPolling: () => { - const { pollInterval, authProgressUnlisten } = get(); - if (pollInterval) { - try { - clearInterval(pollInterval); - } catch (err) { - console.debug("Failed to clear poll interval:", err); - } - set({ pollInterval: null }); - } - if (authProgressUnlisten) { - try { - authProgressUnlisten(); - } catch (err) { - console.debug("Failed to unlisten auth progress:", err); - } - set({ authProgressUnlisten: null }); - } - }, - - cancelMicrosoftLogin: () => { - get().stopPolling(); - set({ - deviceCodeData: null, - msLoginLoading: false, - msLoginStatus: "", - loginMode: "select", - }); - }, - - setLoginMode: (mode: "select" | "offline" | "microsoft") => { - set({ loginMode: mode }); - }, - - setOfflineUsername: (username: string) => { - set({ offlineUsername: username }); - }, -})); diff --git a/packages/ui/src/stores/releases-store.ts b/packages/ui/src/stores/releases-store.ts deleted file mode 100644 index 56afa08..0000000 --- a/packages/ui/src/stores/releases-store.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { invoke } from "@tauri-apps/api/core"; -import { create } from "zustand"; -import type { GithubRelease } from "@/types/bindings/core"; - -interface ReleasesState { - // State - releases: GithubRelease[]; - isLoading: boolean; - isLoaded: boolean; - error: string | null; - - // Actions - loadReleases: () => Promise<void>; - setReleases: (releases: GithubRelease[]) => void; - setIsLoading: (isLoading: boolean) => void; - setIsLoaded: (isLoaded: boolean) => void; - setError: (error: string | null) => void; -} - -export const useReleasesStore = create<ReleasesState>((set, get) => ({ - // Initial state - releases: [], - isLoading: false, - isLoaded: false, - error: null, - - // Actions - loadReleases: async () => { - const { isLoaded, isLoading } = get(); - - // If already loaded or currently loading, skip to prevent duplicate requests - if (isLoaded || isLoading) return; - - set({ isLoading: true, error: null }); - - try { - const releases = await invoke<GithubRelease[]>("get_github_releases"); - set({ releases, isLoaded: true }); - } catch (e) { - const error = e instanceof Error ? e.message : String(e); - console.error("Failed to load releases:", e); - set({ error }); - } finally { - set({ isLoading: false }); - } - }, - - setReleases: (releases) => { - set({ releases }); - }, - - setIsLoading: (isLoading) => { - set({ isLoading }); - }, - - setIsLoaded: (isLoaded) => { - set({ isLoaded }); - }, - - setError: (error) => { - set({ error }); - }, -})); diff --git a/packages/ui/src/stores/ui-store.ts b/packages/ui/src/stores/ui-store.ts deleted file mode 100644 index 89b9191..0000000 --- a/packages/ui/src/stores/ui-store.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { create } from "zustand"; - -export type ViewType = "home" | "versions" | "settings" | "guide" | "instances"; - -interface UIState { - // State - currentView: ViewType; - showConsole: boolean; - appVersion: string; - - // Actions - toggleConsole: () => void; - setView: (view: ViewType) => void; - setAppVersion: (version: string) => void; -} - -export const useUIStore = create<UIState>((set) => ({ - // Initial state - currentView: "home", - showConsole: false, - appVersion: "...", - - // Actions - toggleConsole: () => { - set((state) => ({ showConsole: !state.showConsole })); - }, - - setView: (view: ViewType) => { - set({ currentView: view }); - }, - - setAppVersion: (version: string) => { - set({ appVersion: version }); - }, -})); - -// Provide lowercase alias for compatibility with existing imports. -// Use a function wrapper to ensure the named export exists as a callable value -// at runtime (some bundlers/tree-shakers may remove simple aliases). -export function useUiStore() { - return useUIStore(); -} |