refactor: format code with prettier and fix quotation marks

This commit is contained in:
vffuunnyy
2025-08-16 15:23:43 +07:00
parent 9c33f007a1
commit e26f500ad0
32 changed files with 1636 additions and 1490 deletions

6
.github/FUNDING.yml vendored
View File

@@ -1 +1,5 @@
custom: ['https://t.me/tribute/app?startapp=dtfk','https://t.me/tribute/app?startapp=dtLE'] custom:
[
"https://t.me/tribute/app?startapp=dtfk",
"https://t.me/tribute/app?startapp=dtLE",
]

View File

@@ -91,17 +91,17 @@ jobs:
> :warning: **Warning** > :warning: **Warning**
If you get a notification that the application is corrupted when you run it on macOS, run this command:<br> If you get a notification that the application is corrupted when you run it on macOS, run this command:<br>
<code>sudo xattr -r -c /Applications/Koala\ Clash.app</code> <code>sudo xattr -r -c /Applications/Koala\ Clash.app</code>
### Linux ### Linux
<a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash_amd64.deb"><img src="https://img.shields.io/badge/x64-default?style=flat&logo=debian&label=DEB"> </a><br> <a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash_amd64.deb"><img src="https://img.shields.io/badge/x64-default?style=flat&logo=debian&label=DEB"> </a><br>
<a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash.x86_64.rpm"><img src="https://img.shields.io/badge/x64-default?style=flat&logo=fedora&label=RPM"> </a> <a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash.x86_64.rpm"><img src="https://img.shields.io/badge/x64-default?style=flat&logo=fedora&label=RPM"> </a>
<a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash_arm64.deb"><img src="https://img.shields.io/badge/arm64-default?style=flat&logo=debian&label=DEB"> </a><br> <a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash_arm64.deb"><img src="https://img.shields.io/badge/arm64-default?style=flat&logo=debian&label=DEB"> </a><br>
<a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash.aarch64.rpm"><img src="https://img.shields.io/badge/aarch64-default?style=flat&logo=fedora&label=RPM"> </a> <a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash.aarch64.rpm"><img src="https://img.shields.io/badge/aarch64-default?style=flat&logo=fedora&label=RPM"> </a>
<a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash_armhf.deb"><img src="https://img.shields.io/badge/armhf-default?style=flat&logo=debian&label=DEB"> </a><br> <a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash_armhf.deb"><img src="https://img.shields.io/badge/armhf-default?style=flat&logo=debian&label=DEB"> </a><br>
<a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash.armhfp.rpm"><img src="https://img.shields.io/badge/armhfp-default?style=flat&logo=fedora&label=RPM"> </a> <a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash.armhfp.rpm"><img src="https://img.shields.io/badge/armhfp-default?style=flat&logo=fedora&label=RPM"> </a>
### Windows (Win7 is no longer supported) ### Windows (Win7 is no longer supported)
#### Normal version (recommended) #### Normal version (recommended)
<a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash_x64-setup.exe"><img src="https://badgen.net/badge/icon/x64?icon=windows&label=exe"></a><br> <a href="https://github.com/coolcoala/clash-verge-rev-lite/releases/download/v${{ env.VERSION }}/Koala.Clash_x64-setup.exe"><img src="https://badgen.net/badge/icon/x64?icon=windows&label=exe"></a><br>
@@ -217,11 +217,11 @@ jobs:
shell: bash shell: bash
run: | run: |
TARGET_DIR="src-tauri/target/${{ matrix.target }}/release/bundle" TARGET_DIR="src-tauri/target/${{ matrix.target }}/release/bundle"
if [ ! -d "$TARGET_DIR" ]; then if [ ! -d "$TARGET_DIR" ]; then
exit 1 exit 1
fi fi
find "$TARGET_DIR" -type f \( -name "*.dmg" -o -name "*.deb" -o -name "*.rpm" \) -print0 | while IFS= read -r -d '' old_path; do find "$TARGET_DIR" -type f \( -name "*.dmg" -o -name "*.deb" -o -name "*.rpm" \) -print0 | while IFS= read -r -d '' old_path; do
dir_path=$(dirname "$old_path") dir_path=$(dirname "$old_path")
old_filename=$(basename "$old_path") old_filename=$(basename "$old_path")
@@ -365,11 +365,11 @@ jobs:
shell: bash shell: bash
run: | run: |
TARGET_DIR="src-tauri/target/${{ matrix.target }}/release/bundle" TARGET_DIR="src-tauri/target/${{ matrix.target }}/release/bundle"
if [ ! -d "$TARGET_DIR" ]; then if [ ! -d "$TARGET_DIR" ]; then
exit 1 exit 1
fi fi
find "$TARGET_DIR" -type f \( -name "*.dmg" -o -name "*.deb" -o -name "*.rpm" \) -print0 | while IFS= read -r -d '' old_path; do find "$TARGET_DIR" -type f \( -name "*.dmg" -o -name "*.deb" -o -name "*.rpm" \) -print0 | while IFS= read -r -d '' old_path; do
dir_path=$(dirname "$old_path") dir_path=$(dirname "$old_path")
old_filename=$(basename "$old_path") old_filename=$(basename "$old_path")
@@ -578,14 +578,14 @@ jobs:
echo "Using found update logs" echo "Using found update logs"
UPDATE_LOGS=$(echo "$UPDATE_LOGS" | sed 's/^## \(v.*\)/\*\1\*/') UPDATE_LOGS=$(echo "$UPDATE_LOGS" | sed 's/^## \(v.*\)/\*\1\*/')
fi fi
cat > release.txt << EOF cat > release.txt << EOF
Вышло обновление! Вышло обновление!
$UPDATE_LOGS $UPDATE_LOGS
[Ссылка на релиз](https://github.com/coolcoala/clash-verge-rev-lite/releases/latest) [Ссылка на релиз](https://github.com/coolcoala/clash-verge-rev-lite/releases/latest)
EOF EOF
- name: notify to channel - name: notify to channel
@@ -603,4 +603,3 @@ jobs:
token: ${{ secrets.TELEGRAM_TOKEN }} token: ${{ secrets.TELEGRAM_TOKEN }}
message_file: release.txt message_file: release.txt
format: markdown format: markdown

View File

@@ -1,7 +1,7 @@
## v0.2.5 ## v0.2.5
- new main page - new main page
- fixed issue with opening via shortcut - fixed issue with opening via shortcut
- fixed logo in sidebar - fixed logo in sidebar
- fixed issue with changing tray settings - fixed issue with changing tray settings
- name changed to koala clash - name changed to koala clash
@@ -27,7 +27,6 @@
- corrected side menu in compressed window - corrected side menu in compressed window
- added check at the main toggle switch, now it cannot be enabled if there are no profiles. - added check at the main toggle switch, now it cannot be enabled if there are no profiles.
## v0.2.1 ## v0.2.1
- added headers "announce-url", "update-always" - added headers "announce-url", "update-always"

View File

@@ -1,19 +1,21 @@
import * as React from "react" import * as React from "react";
const MOBILE_BREAKPOINT = 768 const MOBILE_BREAKPOINT = 768;
export function useIsMobile() { export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined) const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
undefined,
);
React.useEffect(() => { React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`) const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => { const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
} };
mql.addEventListener("change", onChange) mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange) return () => mql.removeEventListener("change", onChange);
}, []) }, []);
return !!isMobile return !!isMobile;
} }

View File

@@ -31,4 +31,3 @@
} }
} }
} }

View File

@@ -3,9 +3,9 @@ import Layout from "./pages/_layout";
function App() { function App() {
return ( return (
<AppDataProvider> <AppDataProvider>
<Layout /> <Layout />
</AppDataProvider> </AppDataProvider>
); );
} }
export default App; export default App;

View File

@@ -73,21 +73,25 @@ interface Props {
scrollerRef: (element: HTMLElement | Window | null) => void; scrollerRef: (element: HTMLElement | Window | null) => void;
} }
const ColumnResizer = ({ header }: { header: Header<ConnectionRow, unknown> }) => { const ColumnResizer = ({
header,
}: {
header: Header<ConnectionRow, unknown>;
}) => {
return ( return (
<div <div
onMouseDown={header.getResizeHandler()} onMouseDown={header.getResizeHandler()}
onTouchStart={header.getResizeHandler()} onTouchStart={header.getResizeHandler()}
className={cn( className={cn(
"absolute right-0 top-0 h-full w-1 cursor-col-resize select-none touch-none", "absolute right-0 top-0 h-full w-1 cursor-col-resize select-none touch-none",
"bg-transparent hover:bg-primary/50 active:bg-primary", "bg-transparent hover:bg-primary/50 active:bg-primary",
"transition-colors duration-150", "transition-colors duration-150",
header.column.getIsResizing() && "bg-primary" header.column.getIsResizing() && "bg-primary",
)} )}
style={{ style={{
transform: header.column.getIsResizing() ? `translateX(0px)` : "", transform: header.column.getIsResizing() ? `translateX(0px)` : "",
}} }}
/> />
); );
}; };
@@ -105,8 +109,8 @@ export const ConnectionTable = (props: Props) => {
try { try {
const saved = localStorage.getItem("connection-table-widths"); const saved = localStorage.getItem("connection-table-widths");
return saved return saved
? JSON.parse(saved) ? JSON.parse(saved)
: { : {
host: 220, host: 220,
download: 88, download: 88,
upload: 88, upload: 88,
@@ -140,8 +144,8 @@ export const ConnectionTable = (props: Props) => {
useEffect(() => { useEffect(() => {
localStorage.setItem( localStorage.setItem(
"connection-table-widths", "connection-table-widths",
JSON.stringify(columnSizing) JSON.stringify(columnSizing),
); );
}, [columnSizing]); }, [columnSizing]);
@@ -151,13 +155,13 @@ export const ConnectionTable = (props: Props) => {
const chains = [...each.chains].reverse().join(" / "); const chains = [...each.chains].reverse().join(" / ");
const rule = rulePayload ? `${each.rule}(${rulePayload})` : each.rule; const rule = rulePayload ? `${each.rule}(${rulePayload})` : each.rule;
const Destination = metadata.destinationIP const Destination = metadata.destinationIP
? `${metadata.destinationIP}:${metadata.destinationPort}` ? `${metadata.destinationIP}:${metadata.destinationPort}`
: `${metadata.remoteDestination}:${metadata.destinationPort}`; : `${metadata.remoteDestination}:${metadata.destinationPort}`;
return { return {
id: each.id, id: each.id,
host: metadata.host host: metadata.host
? `${metadata.host}:${metadata.destinationPort}` ? `${metadata.host}:${metadata.destinationPort}`
: `${metadata.remoteDestination}:${metadata.destinationPort}`, : `${metadata.remoteDestination}:${metadata.destinationPort}`,
download: each.download, download: each.download,
upload: each.upload, upload: each.upload,
dlSpeed: each.curDownload ?? 0, dlSpeed: each.curDownload ?? 0,
@@ -175,118 +179,118 @@ export const ConnectionTable = (props: Props) => {
}, [connections]); }, [connections]);
const columns = useMemo<ColumnDef<ConnectionRow>[]>( const columns = useMemo<ColumnDef<ConnectionRow>[]>(
() => [ () => [
{ {
accessorKey: "host", accessorKey: "host",
header: () => t("Host"), header: () => t("Host"),
size: columnSizing?.host || 220, size: columnSizing?.host || 220,
minSize: 180, minSize: 180,
maxSize: 400, maxSize: 400,
}, },
{ {
accessorKey: "download", accessorKey: "download",
header: () => t("Downloaded"), header: () => t("Downloaded"),
size: columnSizing?.download || 88, size: columnSizing?.download || 88,
minSize: 80, minSize: 80,
maxSize: 150, maxSize: 150,
cell: ({ getValue }) => ( cell: ({ getValue }) => (
<div className="text-right font-mono text-sm"> <div className="text-right font-mono text-sm">
{parseTraffic(getValue<number>()).join(" ")} {parseTraffic(getValue<number>()).join(" ")}
</div> </div>
), ),
}, },
{ {
accessorKey: "upload", accessorKey: "upload",
header: () => t("Uploaded"), header: () => t("Uploaded"),
size: columnSizing?.upload || 88, size: columnSizing?.upload || 88,
minSize: 80, minSize: 80,
maxSize: 150, maxSize: 150,
cell: ({ getValue }) => ( cell: ({ getValue }) => (
<div className="text-right font-mono text-sm"> <div className="text-right font-mono text-sm">
{parseTraffic(getValue<number>()).join(" ")} {parseTraffic(getValue<number>()).join(" ")}
</div> </div>
), ),
}, },
{ {
accessorKey: "dlSpeed", accessorKey: "dlSpeed",
header: () => t("DL Speed"), header: () => t("DL Speed"),
size: columnSizing?.dlSpeed || 88, size: columnSizing?.dlSpeed || 88,
minSize: 80, minSize: 80,
maxSize: 150, maxSize: 150,
cell: ({ getValue }) => ( cell: ({ getValue }) => (
<div className="text-right font-mono text-sm"> <div className="text-right font-mono text-sm">
{parseTraffic(getValue<number>()).join(" ")}/s {parseTraffic(getValue<number>()).join(" ")}/s
</div> </div>
), ),
}, },
{ {
accessorKey: "ulSpeed", accessorKey: "ulSpeed",
header: () => t("UL Speed"), header: () => t("UL Speed"),
size: columnSizing?.ulSpeed || 88, size: columnSizing?.ulSpeed || 88,
minSize: 80, minSize: 80,
maxSize: 150, maxSize: 150,
cell: ({ getValue }) => ( cell: ({ getValue }) => (
<div className="text-right font-mono text-sm"> <div className="text-right font-mono text-sm">
{parseTraffic(getValue<number>()).join(" ")}/s {parseTraffic(getValue<number>()).join(" ")}/s
</div> </div>
), ),
}, },
{ {
accessorKey: "chains", accessorKey: "chains",
header: () => t("Chains"), header: () => t("Chains"),
size: columnSizing?.chains || 340, size: columnSizing?.chains || 340,
minSize: 180, minSize: 180,
maxSize: 500, maxSize: 500,
}, },
{ {
accessorKey: "rule", accessorKey: "rule",
header: () => t("Rule"), header: () => t("Rule"),
size: columnSizing?.rule || 280, size: columnSizing?.rule || 280,
minSize: 180, minSize: 180,
maxSize: 400, maxSize: 400,
}, },
{ {
accessorKey: "process", accessorKey: "process",
header: () => t("Process"), header: () => t("Process"),
size: columnSizing?.process || 220, size: columnSizing?.process || 220,
minSize: 180, minSize: 180,
maxSize: 350, maxSize: 350,
}, },
{ {
accessorKey: "time", accessorKey: "time",
header: () => t("Time"), header: () => t("Time"),
size: columnSizing?.time || 120, size: columnSizing?.time || 120,
minSize: 100, minSize: 100,
maxSize: 180, maxSize: 180,
cell: ({ getValue }) => ( cell: ({ getValue }) => (
<div className="text-right font-mono text-sm"> <div className="text-right font-mono text-sm">
{dayjs(getValue<string>()).fromNow()} {dayjs(getValue<string>()).fromNow()}
</div> </div>
), ),
}, },
{ {
accessorKey: "source", accessorKey: "source",
header: () => t("Source"), header: () => t("Source"),
size: columnSizing?.source || 200, size: columnSizing?.source || 200,
minSize: 130, minSize: 130,
maxSize: 300, maxSize: 300,
}, },
{ {
accessorKey: "remoteDestination", accessorKey: "remoteDestination",
header: () => t("Destination"), header: () => t("Destination"),
size: columnSizing?.remoteDestination || 200, size: columnSizing?.remoteDestination || 200,
minSize: 130, minSize: 130,
maxSize: 300, maxSize: 300,
}, },
{ {
accessorKey: "type", accessorKey: "type",
header: () => t("Type"), header: () => t("Type"),
size: columnSizing?.type || 160, size: columnSizing?.type || 160,
minSize: 100, minSize: 100,
maxSize: 220, maxSize: 220,
}, },
], ],
[columnSizing] [columnSizing],
); );
const table = useReactTable({ const table = useReactTable({
@@ -305,82 +309,82 @@ export const ConnectionTable = (props: Props) => {
if (connRows.length === 0) { if (connRows.length === 0) {
return ( return (
<div className="flex h-full items-center justify-center"> <div className="flex h-full items-center justify-center">
<p className="text-muted-foreground">{t("No connections")}</p> <p className="text-muted-foreground">{t("No connections")}</p>
</div> </div>
); );
} }
return ( return (
<div className="rounded-md border relative bg-background"> <div className="rounded-md border relative bg-background">
<Table <Table
className="w-full border-collapse table-fixed" className="w-full border-collapse table-fixed"
style={{ style={{
width: totalTableWidth, width: totalTableWidth,
minWidth: "100%", minWidth: "100%",
}} }}
> >
<TableHeader> <TableHeader>
{table.getHeaderGroups().map((headerGroup) => ( {table.getHeaderGroups().map((headerGroup) => (
<TableRow <TableRow
key={headerGroup.id} key={headerGroup.id}
className="hover:bg-transparent border-b-0 h-10" className="hover:bg-transparent border-b-0 h-10"
>
{headerGroup.headers.map((header) => (
<TableHead
key={header.id}
className={cn(
"sticky top-0 z-10",
"p-2 text-xs font-semibold select-none border-r last:border-r-0 bg-background h-10",
)}
style={{
width: header.getSize(),
minWidth: header.column.columnDef.minSize,
maxWidth: header.column.columnDef.maxSize,
}}
> >
{headerGroup.headers.map((header) => ( <div className="flex items-center justify-between h-full">
<TableHead {header.isPlaceholder
key={header.id} ? null
className={cn( : flexRender(
"sticky top-0 z-10", header.column.columnDef.header,
"p-2 text-xs font-semibold select-none border-r last:border-r-0 bg-background h-10" header.getContext(),
)}
style={{
width: header.getSize(),
minWidth: header.column.columnDef.minSize,
maxWidth: header.column.columnDef.maxSize,
}}
>
<div className="flex items-center justify-between h-full">
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</div>
{header.column.getCanResize() && (
<ColumnResizer header={header} />
)} )}
</TableHead> </div>
))} {header.column.getCanResize() && (
</TableRow> <ColumnResizer header={header} />
))} )}
</TableHeader> </TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody> <TableBody>
{table.getRowModel().rows.map((row) => ( {table.getRowModel().rows.map((row) => (
<TableRow <TableRow
key={row.id} key={row.id}
data-state={row.getIsSelected() && "selected"} data-state={row.getIsSelected() && "selected"}
className="cursor-pointer hover:bg-muted/50 transition-colors" className="cursor-pointer hover:bg-muted/50 transition-colors"
onClick={() => onShowDetail(row.original.connectionData)} onClick={() => onShowDetail(row.original.connectionData)}
>
{row.getVisibleCells().map((cell) => (
<TableCell
key={cell.id}
className="p-2 whitespace-nowrap overflow-hidden text-ellipsis text-sm border-r last:border-r-0"
style={{
width: cell.column.getSize(),
minWidth: cell.column.columnDef.minSize,
maxWidth: cell.column.columnDef.maxSize,
}}
> >
{row.getVisibleCells().map((cell) => ( {flexRender(cell.column.columnDef.cell, cell.getContext())}
<TableCell </TableCell>
key={cell.id} ))}
className="p-2 whitespace-nowrap overflow-hidden text-ellipsis text-sm border-r last:border-r-0" </TableRow>
style={{ ))}
width: cell.column.getSize(), </TableBody>
minWidth: cell.column.columnDef.minSize, </Table>
maxWidth: cell.column.columnDef.maxSize, </div>
}}
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
); );
}; };

View File

@@ -1,64 +1,72 @@
import React from 'react'; import React from "react";
import { cn } from '@root/lib/utils'; import { cn } from "@root/lib/utils";
import { Power } from 'lucide-react'; import { Power } from "lucide-react";
export interface PowerButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { export interface PowerButtonProps
checked?: boolean; extends React.ButtonHTMLAttributes<HTMLButtonElement> {
loading?: boolean; checked?: boolean;
loading?: boolean;
} }
export const PowerButton = React.forwardRef<HTMLButtonElement, PowerButtonProps>( export const PowerButton = React.forwardRef<
({ className, checked = false, loading = false, ...props }, ref) => { HTMLButtonElement,
const state = checked ? 'on' : 'off'; PowerButtonProps
>(({ className, checked = false, loading = false, ...props }, ref) => {
const state = checked ? "on" : "off";
return ( return (
<div className="relative flex items-center justify-center h-44 w-44"> <div className="relative flex items-center justify-center h-44 w-44">
<div
className={cn(
"absolute h-28 w-28 rounded-full blur-3xl transition-all duration-500",
state === "on" ? "bg-green-400/60" : "bg-red-500/40",
props.disabled && "opacity-0",
)}
/>
<div <button
className={cn( ref={ref}
'absolute h-28 w-28 rounded-full blur-3xl transition-all duration-500', type="button"
state === 'on' ? 'bg-green-400/60' : 'bg-red-500/40', disabled={loading || props.disabled}
props.disabled && 'opacity-0' data-state={state}
)} className={cn(
/> "relative z-10 flex items-center justify-center h-36 w-36 rounded-full border-2",
"backdrop-blur-sm bg-white/10 border-white/20",
"text-red-500 shadow-[0_0_30px_rgba(239,68,68,0.6)]",
"data-[state=on]:text-green-500 dark:data-[state=on]:text-white",
"data-[state=on]:shadow-[0_0_50px_rgba(34,197,94,1)]",
"transition-all duration-300 hover:scale-105 active:scale-95 focus:outline-none",
"disabled:cursor-not-allowed disabled:scale-100",
<button // Стили ТОЛЬКО для отключенного состояния (но не для загрузки)
ref={ref} props.disabled &&
type="button" !loading &&
disabled={loading || props.disabled} "grayscale opacity-50 shadow-none bg-slate-100/70 border-slate-300/80",
data-state={state} className,
className={cn( )}
'relative z-10 flex items-center justify-center h-36 w-36 rounded-full border-2', {...props}
'backdrop-blur-sm bg-white/10 border-white/20', >
'text-red-500 shadow-[0_0_30px_rgba(239,68,68,0.6)]', <Power
'data-[state=on]:text-green-500 dark:data-[state=on]:text-white', className={cn(
'data-[state=on]:shadow-[0_0_50px_rgba(34,197,94,1)]', "h-20 w-20",
'transition-all duration-300 hover:scale-105 active:scale-95 focus:outline-none', !props.disabled &&
'disabled:cursor-not-allowed disabled:scale-100', "active:scale-90 transition-transform duration-300",
)}
/>
</button>
// Стили ТОЛЬКО для отключенного состояния (но не для загрузки) {loading && (
(props.disabled && !loading) && 'grayscale opacity-50 shadow-none bg-slate-100/70 border-slate-300/80', <div className="absolute inset-0 flex items-center justify-center z-20">
className <div
)} className={cn(
{...props} "h-full w-full animate-spin rounded-full border-4",
> "border-transparent",
<Power className={cn( checked ? "border-t-green-500" : "border-t-red-500",
"h-20 w-20", "blur-xs",
!props.disabled && "active:scale-90 transition-transform duration-300" )}
)} /> />
</button> </div>
)}
{loading && ( </div>
<div className="absolute inset-0 flex items-center justify-center z-20"> );
<div className={cn( });
'h-full w-full animate-spin rounded-full border-4',
'border-transparent',
checked ? 'border-t-green-500' : 'border-t-red-500',
'blur-xs'
)} />
</div>
)}
</div>
);
}
);

View File

@@ -1,16 +1,18 @@
import { Link } from 'react-router-dom'; import { Link } from "react-router-dom";
import { import {
Sidebar, Sidebar,
SidebarContent, SidebarFooter, SidebarContent,
SidebarFooter,
SidebarGroup, SidebarGroup,
SidebarGroupContent, SidebarGroupContent,
SidebarHeader, SidebarHeader,
SidebarMenu, SidebarMenu,
SidebarMenuButton, SidebarMenuButton,
SidebarMenuItem, useSidebar, SidebarMenuItem,
} from "@/components/ui/sidebar" useSidebar,
import { t } from 'i18next'; } from "@/components/ui/sidebar";
import { cn } from '@root/lib/utils'; import { t } from "i18next";
import { cn } from "@root/lib/utils";
import { import {
Home, Home,
@@ -19,21 +21,22 @@ import {
Cable, Cable,
ListChecks, ListChecks,
FileText, FileText,
Settings, EarthLock, Settings,
} from 'lucide-react'; EarthLock,
} from "lucide-react";
import { UpdateButton } from "@/components/layout/update-button"; import { UpdateButton } from "@/components/layout/update-button";
import React from "react"; import React from "react";
import { SheetClose } from '@/components/ui/sheet'; import { SheetClose } from "@/components/ui/sheet";
import logo from "@/assets/image/logo.png" import logo from "@/assets/image/logo.png";
const menuItems = [ const menuItems = [
{ title: 'Home', url: '/home', icon: Home }, { title: "Home", url: "/home", icon: Home },
{ title: 'Profiles', url: '/profile', icon: Users }, { title: "Profiles", url: "/profile", icon: Users },
{ title: 'Proxies', url: '/proxies', icon: Server }, { title: "Proxies", url: "/proxies", icon: Server },
{ title: 'Connections', url: '/connections', icon: Cable }, { title: "Connections", url: "/connections", icon: Cable },
{ title: 'Rules', url: '/rules', icon: ListChecks }, { title: "Rules", url: "/rules", icon: ListChecks },
{ title: 'Logs', url: '/logs', icon: FileText }, { title: "Logs", url: "/logs", icon: FileText },
{ title: 'Settings', url: '/settings', icon: Settings }, { title: "Settings", url: "/settings", icon: Settings },
]; ];
export function AppSidebar() { export function AppSidebar() {
@@ -41,18 +44,15 @@ export function AppSidebar() {
return ( return (
<Sidebar variant="floating" collapsible="icon"> <Sidebar variant="floating" collapsible="icon">
<SidebarHeader> <SidebarHeader>
<SidebarMenuButton size="lg" <SidebarMenuButton
size="lg"
className={cn( className={cn(
"flex h-12 items-center transition-all duration-200", "flex h-12 items-center transition-all duration-200",
"group-data-[state=expanded]:w-full group-data-[state=expanded]:gap-2 group-data-[state=expanded]:px-3", "group-data-[state=expanded]:w-full group-data-[state=expanded]:gap-2 group-data-[state=expanded]:px-3",
"group-data-[state=collapsed]:w-full group-data-[state=collapsed]:justify-center" "group-data-[state=collapsed]:w-full group-data-[state=collapsed]:justify-center",
)} )}
> >
<img <img src={logo} alt="logo" className="h-6 w-6 flex-shrink-0" />
src={logo}
alt="logo"
className="h-6 w-6 flex-shrink-0"
/>
<span className="font-semibold whitespace-nowrap group-data-[state=collapsed]:hidden"> <span className="font-semibold whitespace-nowrap group-data-[state=collapsed]:hidden">
Koala Clash Koala Clash
</span> </span>
@@ -69,30 +69,29 @@ export function AppSidebar() {
key={item.title} key={item.title}
to={item.url} to={item.url}
className={cn( className={cn(
'flex items-center gap-3 rounded-lg px-3 py-2 text-muted-foreground transition-all hover:text-primary', "flex items-center gap-3 rounded-lg px-3 py-2 text-muted-foreground transition-all hover:text-primary",
'data-[active=true]:font-semibold data-[active=true]:border' "data-[active=true]:font-semibold data-[active=true]:border",
)} )}
> >
<item.icon className="h-4 w-4 drop-shadow-md" /> <item.icon className="h-4 w-4 drop-shadow-md" />
{t(item.title)} {t(item.title)}
</Link> </Link>
) );
return ( return (
<SidebarMenuItem key={item.title} className="my-1"> <SidebarMenuItem key={item.title} className="my-1">
<SidebarMenuButton <SidebarMenuButton
asChild asChild
isActive={isActive} isActive={isActive}
tooltip={t(item.title)}> tooltip={t(item.title)}
{isMobile ? ( >
<SheetClose asChild> {isMobile ? (
{linkElement} <SheetClose asChild>{linkElement}</SheetClose>
</SheetClose>
) : ( ) : (
linkElement linkElement
)} )}
</SidebarMenuButton> </SidebarMenuButton>
</SidebarMenuItem> </SidebarMenuItem>
) );
})} })}
</SidebarMenu> </SidebarMenu>
</SidebarGroupContent> </SidebarGroupContent>
@@ -104,5 +103,5 @@ export function AppSidebar() {
</div> </div>
</SidebarFooter> </SidebarFooter>
</Sidebar> </Sidebar>
) );
} }

View File

@@ -6,7 +6,7 @@ import { DialogRef } from "../base";
import { useVerge } from "@/hooks/use-verge"; import { useVerge } from "@/hooks/use-verge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { t } from "i18next"; import { t } from "i18next";
import {Download, RefreshCw} from "lucide-react"; import { Download, RefreshCw } from "lucide-react";
import { useSidebar } from "../ui/sidebar"; import { useSidebar } from "../ui/sidebar";
interface Props { interface Props {
@@ -17,7 +17,7 @@ export const UpdateButton = (props: Props) => {
const { className } = props; const { className } = props;
const { verge } = useVerge(); const { verge } = useVerge();
const { auto_check_update } = verge || {}; const { auto_check_update } = verge || {};
const { state: sidebarState } = useSidebar(); const { state: sidebarState } = useSidebar();
const viewerRef = useRef<DialogRef>(null); const viewerRef = useRef<DialogRef>(null);
@@ -36,7 +36,7 @@ export const UpdateButton = (props: Props) => {
return ( return (
<> <>
<UpdateViewer ref={viewerRef} /> <UpdateViewer ref={viewerRef} />
{sidebarState === 'collapsed' ? ( {sidebarState === "collapsed" ? (
<Button <Button
variant="outline" variant="outline"
size="icon" size="icon"

View File

@@ -1,7 +1,10 @@
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { useSetThemeMode, useThemeMode } from "@/services/states"; import { useSetThemeMode, useThemeMode } from "@/services/states";
import { useVerge } from "@/hooks/use-verge"; import { useVerge } from "@/hooks/use-verge";
import { getCurrentWebviewWindow, WebviewWindow } from "@tauri-apps/api/webviewWindow"; import {
getCurrentWebviewWindow,
WebviewWindow,
} from "@tauri-apps/api/webviewWindow";
import { Theme } from "@tauri-apps/api/window"; import { Theme } from "@tauri-apps/api/window";
export const useCustomTheme = () => { export const useCustomTheme = () => {
@@ -12,26 +15,28 @@ export const useCustomTheme = () => {
const mode = useThemeMode(); const mode = useThemeMode();
const setMode = useSetThemeMode(); const setMode = useSetThemeMode();
const [systemTheme, setSystemTheme] = useState( const [systemTheme, setSystemTheme] = useState(() =>
() => window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light",
); );
useEffect(() => { useEffect(() => {
setMode( setMode(
theme_mode === "light" || theme_mode === "dark" ? theme_mode : "system", theme_mode === "light" || theme_mode === "dark" ? theme_mode : "system",
); );
}, [theme_mode, setMode]); }, [theme_mode, setMode]);
useEffect(() => { useEffect(() => {
if (mode !== 'system') return; if (mode !== "system") return;
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)"); const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleChange = (e: MediaQueryListEvent) => { const handleChange = (e: MediaQueryListEvent) => {
setSystemTheme(e.matches ? "dark" : "light"); setSystemTheme(e.matches ? "dark" : "light");
}; };
mediaQuery.addEventListener('change', handleChange); mediaQuery.addEventListener("change", handleChange);
return () => mediaQuery.removeEventListener('change', handleChange); return () => mediaQuery.removeEventListener("change", handleChange);
}, [mode]); }, [mode]);
useEffect(() => { useEffect(() => {
@@ -45,8 +50,7 @@ export const useCustomTheme = () => {
} else { } else {
appWindow.setTheme(activeTheme as Theme).catch(console.error); appWindow.setTheme(activeTheme as Theme).catch(console.error);
} }
}, [mode, systemTheme, appWindow, theme_mode]); }, [mode, systemTheme, appWindow, theme_mode]);
return {}; return {};
}; };

View File

@@ -1,12 +1,12 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from "react";
import { useTranslation } from 'react-i18next'; import { useTranslation } from "react-i18next";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
DialogDescription, DialogDescription,
DialogFooter DialogFooter,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { AlertTriangle } from "lucide-react"; import { AlertTriangle } from "lucide-react";
@@ -21,10 +21,10 @@ export const HwidErrorDialog = () => {
setErrorMessage(customEvent.detail); setErrorMessage(customEvent.detail);
}; };
window.addEventListener('show-hwid-error', handleShowHwidError); window.addEventListener("show-hwid-error", handleShowHwidError);
return () => { return () => {
window.removeEventListener('show-hwid-error', handleShowHwidError); window.removeEventListener("show-hwid-error", handleShowHwidError);
}; };
}, []); }, []);

View File

@@ -65,7 +65,8 @@ import {
ListTree, ListTree,
CheckCircle, CheckCircle,
Infinity, Infinity,
RefreshCw, Network, RefreshCw,
Network,
} from "lucide-react"; } from "lucide-react";
import { t } from "i18next"; import { t } from "i18next";
@@ -299,7 +300,8 @@ export const ProfileItem = (props: Props) => {
}; };
const MAX_NAME_LENGTH = 25; const MAX_NAME_LENGTH = 25;
const truncatedName = name.length > MAX_NAME_LENGTH const truncatedName =
name.length > MAX_NAME_LENGTH
? `${name.slice(0, MAX_NAME_LENGTH)}...` ? `${name.slice(0, MAX_NAME_LENGTH)}...`
: name; : name;
@@ -344,10 +346,7 @@ export const ProfileItem = (props: Props) => {
) : null} ) : null}
</div> </div>
<div className="flex items-center flex-shrink-0"> <div className="flex items-center flex-shrink-0">
<Badge <Badge variant="outline" className="text-xs shadow-sm">
variant="outline"
className="text-xs shadow-sm"
>
{type} {type}
</Badge> </Badge>
</div> </div>
@@ -389,14 +388,13 @@ export const ProfileItem = (props: Props) => {
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center"> <div className="flex items-center">
<Download className="h-3 w-3 inline mr-1.5" /> <Download className="h-3 w-3 inline mr-1.5" />
<span className="pr-5"> <span className="pr-5">{parseTraffic(download)}</span>
{parseTraffic(download)}
</span>
<Network className="h-3 w-3 inline mr-1.5" /> <Network className="h-3 w-3 inline mr-1.5" />
{total > 0 ? ( {total > 0 ? (
<span>{parseTraffic(total)}</span> <span>{parseTraffic(total)}</span>
) : <Infinity className="h-3 w-3 inline mr-1.5" />} ) : (
<Infinity className="h-3 w-3 inline mr-1.5" />
)}
</div> </div>
</div> </div>
</div> </div>
@@ -510,11 +508,11 @@ export const ProfileItem = (props: Props) => {
)} )}
<ConfirmViewer <ConfirmViewer
open={confirmOpen} open={confirmOpen}
onOpenChange={setConfirmOpen} onOpenChange={setConfirmOpen}
onConfirm={onDelete} onConfirm={onDelete}
title={t("Delete Profile", { name: truncatedName })} title={t("Delete Profile", { name: truncatedName })}
description={t("This action cannot be undone.")} description={t("This action cannot be undone.")}
/> />
</div> </div>
); );

View File

@@ -12,7 +12,8 @@ import {
createProfile, createProfile,
patchProfile, patchProfile,
importProfile, importProfile,
enhanceProfiles, createProfileFromShareLink, enhanceProfiles,
createProfileFromShareLink,
} from "@/services/cmds"; } from "@/services/cmds";
import { useProfiles } from "@/hooks/use-profiles"; import { useProfiles } from "@/hooks/use-profiles";
import { showNotice } from "@/services/noticeService"; import { showNotice } from "@/services/noticeService";
@@ -138,7 +139,9 @@ export const ProfileViewer = forwardRef<ProfileViewerRef, Props>(
setIsCheckingUrl(true); setIsCheckingUrl(true);
const handler = setTimeout(() => { const handler = setTimeout(() => {
const isValid = /^(https?|vmess|vless|ss|socks|trojan):\/\//.test(importUrl); const isValid = /^(https?|vmess|vless|ss|socks|trojan):\/\//.test(
importUrl,
);
setIsUrlValid(isValid); setIsUrlValid(isValid);
setIsCheckingUrl(false); setIsCheckingUrl(false);
}, 500); }, 500);
@@ -165,23 +168,35 @@ export const ProfileViewer = forwardRef<ProfileViewerRef, Props>(
await enhanceProfiles(); await enhanceProfiles();
setOpen(false); setOpen(false);
} catch (err: any) { } catch (err: any) {
const errorMessage = typeof err === 'string' ? err : (err.message || String(err)); const errorMessage =
typeof err === "string" ? err : err.message || String(err);
const lowerErrorMessage = errorMessage.toLowerCase(); const lowerErrorMessage = errorMessage.toLowerCase();
if (lowerErrorMessage.includes('device') || lowerErrorMessage.includes('устройств')) { if (
window.dispatchEvent(new CustomEvent('show-hwid-error', { detail: errorMessage })); lowerErrorMessage.includes("device") ||
lowerErrorMessage.includes("устройств")
) {
window.dispatchEvent(
new CustomEvent("show-hwid-error", { detail: errorMessage }),
);
} else if (!isShareLink && errorMessage.includes("failed to fetch")) { } else if (!isShareLink && errorMessage.includes("failed to fetch")) {
showNotice("info", t("Import failed, retrying with Clash proxy...")); showNotice("info", t("Import failed, retrying with Clash proxy..."));
try { try {
await importProfile(importUrl, { with_proxy: false, self_proxy: true }); await importProfile(importUrl, {
showNotice("success", t("Profile Imported with Clash proxy")); with_proxy: false,
props.onChange(); self_proxy: true,
await enhanceProfiles(); });
setOpen(false); showNotice("success", t("Profile Imported with Clash proxy"));
} catch (retryErr: any) { props.onChange();
showNotice("error", `${t("Import failed even with Clash proxy")}: ${retryErr?.message || retryErr.toString()}`); await enhanceProfiles();
} setOpen(false);
} catch (retryErr: any) {
showNotice(
"error",
`${t("Import failed even with Clash proxy")}: ${retryErr?.message || retryErr.toString()}`,
);
}
} else { } else {
showNotice("error", errorMessage); showNotice("error", errorMessage);
} }
} finally { } finally {
setIsImporting(false); setIsImporting(false);
@@ -302,19 +317,26 @@ export const ProfileViewer = forwardRef<ProfileViewerRef, Props>(
</div> </div>
{/^(vmess|vless|ss|socks|trojan):\/\//.test(importUrl) && ( {/^(vmess|vless|ss|socks|trojan):\/\//.test(importUrl) && (
<div className="space-y-2"> <div className="space-y-2">
<Label>{t("Template")}</Label> <Label>{t("Template")}</Label>
<Select value={selectedTemplate} onValueChange={setSelectedTemplate}> <Select
<SelectTrigger> value={selectedTemplate}
<SelectValue placeholder="Select a template..." /> onValueChange={setSelectedTemplate}
</SelectTrigger> >
<SelectContent> <SelectTrigger>
<SelectItem value="default">{t("Default Template")}</SelectItem> <SelectValue placeholder="Select a template..." />
<SelectItem value="without_ru">{t("Template without RU Rules")}</SelectItem> </SelectTrigger>
</SelectContent> <SelectContent>
<SelectItem value="default">
{t("Default Template")}
</SelectItem>
<SelectItem value="without_ru">
{t("Template without RU Rules")}
</SelectItem>
</SelectContent>
</Select> </Select>
</div> </div>
)} )}
<Button <Button
variant="outline" variant="outline"
@@ -473,15 +495,15 @@ export const ProfileViewer = forwardRef<ProfileViewerRef, Props>(
control={control} control={control}
name="option.update_always" name="option.update_always"
render={({ field }) => ( render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between"> <FormItem className="flex flex-row items-center justify-between">
<FormLabel>{t("Update on Startup")}</FormLabel> <FormLabel>{t("Update on Startup")}</FormLabel>
<FormControl> <FormControl>
<Switch <Switch
checked={field.value} checked={field.value}
onCheckedChange={field.onChange} onCheckedChange={field.onChange}
/> />
</FormControl> </FormControl>
</FormItem> </FormItem>
)} )}
/> />
<FormField <FormField

View File

@@ -24,7 +24,6 @@ import delayManager from "@/services/delay";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { ScrollTopButton } from "../layout/scroll-top-button"; import { ScrollTopButton } from "../layout/scroll-top-button";
function throttle<T extends (...args: any[]) => any>( function throttle<T extends (...args: any[]) => any>(
func: T, func: T,
wait: number, wait: number,
@@ -53,7 +52,6 @@ function throttle<T extends (...args: any[]) => any>(
}; };
} }
interface Props { interface Props {
mode: string; mode: string;
} }
@@ -72,7 +70,6 @@ export const ProxyGroups = memo((props: Props) => {
const scrollerRef = useRef<Element | null>(null); const scrollerRef = useRef<Element | null>(null);
const [showScrollTop, setShowScrollTop] = useState(false); const [showScrollTop, setShowScrollTop] = useState(false);
// Обработчик скролла для показа/скрытия кнопки "Наверх" // Обработчик скролла для показа/скрытия кнопки "Наверх"
const handleScroll = useCallback( const handleScroll = useCallback(
throttle((e: any) => { throttle((e: any) => {

View File

@@ -112,7 +112,7 @@ export const LayoutViewer = forwardRef<DialogRef>((props, ref) => {
})); }));
const handleConfigChange = (patch: Partial<IVergeConfig>) => { const handleConfigChange = (patch: Partial<IVergeConfig>) => {
setLocalConfig(prev => ({ ...prev, ...patch })); setLocalConfig((prev) => ({ ...prev, ...patch }));
}; };
const handleIconChange = useLockFn( const handleIconChange = useLockFn(
@@ -133,7 +133,8 @@ export const LayoutViewer = forwardRef<DialogRef>((props, ref) => {
handleConfigChange({ [key]: true }); handleConfigChange({ [key]: true });
} }
} }
}); },
);
const handleSave = useLockFn(async () => { const handleSave = useLockFn(async () => {
setLoading(true); setLoading(true);
@@ -149,75 +150,112 @@ export const LayoutViewer = forwardRef<DialogRef>((props, ref) => {
}); });
return ( return (
<Dialog open={open} onOpenChange={setOpen}> <Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="sm:max-w-md"> <DialogContent className="sm:max-w-md">
<DialogHeader> <DialogHeader>
<DialogTitle>{t("Layout Setting")}</DialogTitle> <DialogTitle>{t("Layout Setting")}</DialogTitle>
</DialogHeader> </DialogHeader>
<div className="py-4 space-y-1"> <div className="py-4 space-y-1">
{OS === "macos" && ( {OS === "macos" && (
<> <>
<SettingRow label={t("Tray Icon")}> <SettingRow label={t("Tray Icon")}>
<Select <Select
onValueChange={(value) => handleConfigChange({ tray_icon: value as any })} onValueChange={(value) =>
value={localConfig.tray_icon ?? "monochrome"} handleConfigChange({ tray_icon: value as any })
> }
<SelectTrigger className="w-40 h-8"><SelectValue /></SelectTrigger> value={localConfig.tray_icon ?? "monochrome"}
<SelectContent> >
<SelectItem value="monochrome">{t("Monochrome")}</SelectItem> <SelectTrigger className="w-40 h-8">
<SelectItem value="colorful">{t("Colorful")}</SelectItem> <SelectValue />
</SelectContent> </SelectTrigger>
</Select> <SelectContent>
</SettingRow> <SelectItem value="monochrome">
{t("Monochrome")}
</SelectItem>
<SelectItem value="colorful">{t("Colorful")}</SelectItem>
</SelectContent>
</Select>
</SettingRow>
<SettingRow label={t("Enable Tray Icon")}> <SettingRow label={t("Enable Tray Icon")}>
<Switch <Switch
checked={localConfig.enable_tray_icon ?? true} checked={localConfig.enable_tray_icon ?? true}
onCheckedChange={(checked) => handleConfigChange({ enable_tray_icon: checked })} onCheckedChange={(checked) =>
/> handleConfigChange({ enable_tray_icon: checked })
</SettingRow> }
</> />
)} </SettingRow>
</>
)}
<SettingRow label={t("Common Tray Icon")}> <SettingRow label={t("Common Tray Icon")}>
<Button variant="outline" size="sm" className="h-8" onClick={() => handleIconChange("common")}> <Button
{localConfig.common_tray_icon && commonIcon && ( variant="outline"
<img src={convertFileSrc(commonIcon)} className="h-5 mr-2" alt="common tray icon" /> size="sm"
)} className="h-8"
{localConfig.common_tray_icon ? t("Clear") : t("Browse")} onClick={() => handleIconChange("common")}
</Button> >
</SettingRow> {localConfig.common_tray_icon && commonIcon && (
<img
<SettingRow label={t("System Proxy Tray Icon")}> src={convertFileSrc(commonIcon)}
<Button variant="outline" size="sm" className="h-8" onClick={() => handleIconChange("sysproxy")}> className="h-5 mr-2"
{localConfig.sysproxy_tray_icon && sysproxyIcon && ( alt="common tray icon"
<img src={convertFileSrc(sysproxyIcon)} className="h-5 mr-2" alt="system proxy tray icon" /> />
)} )}
{localConfig.sysproxy_tray_icon ? t("Clear") : t("Browse")} {localConfig.common_tray_icon ? t("Clear") : t("Browse")}
</Button>
</SettingRow>
<SettingRow label={t("Tun Tray Icon")}>
<Button variant="outline" size="sm" className="h-8" onClick={() => handleIconChange("tun")}>
{localConfig.tun_tray_icon && tunIcon && (
<img src={convertFileSrc(tunIcon)} className="h-5 mr-2" alt="tun mode tray icon" />
)}
{localConfig.tun_tray_icon ? t("Clear") : t("Browse")}
</Button>
</SettingRow>
</div>
<DialogFooter>
<DialogClose asChild>
<Button type="button" variant="outline">{t("Cancel")}</Button>
</DialogClose>
<Button type="button" onClick={handleSave} disabled={loading}>
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{t("Save")}
</Button> </Button>
</DialogFooter> </SettingRow>
</DialogContent>
</Dialog> <SettingRow label={t("System Proxy Tray Icon")}>
<Button
variant="outline"
size="sm"
className="h-8"
onClick={() => handleIconChange("sysproxy")}
>
{localConfig.sysproxy_tray_icon && sysproxyIcon && (
<img
src={convertFileSrc(sysproxyIcon)}
className="h-5 mr-2"
alt="system proxy tray icon"
/>
)}
{localConfig.sysproxy_tray_icon ? t("Clear") : t("Browse")}
</Button>
</SettingRow>
<SettingRow label={t("Tun Tray Icon")}>
<Button
variant="outline"
size="sm"
className="h-8"
onClick={() => handleIconChange("tun")}
>
{localConfig.tun_tray_icon && tunIcon && (
<img
src={convertFileSrc(tunIcon)}
className="h-5 mr-2"
alt="tun mode tray icon"
/>
)}
{localConfig.tun_tray_icon ? t("Clear") : t("Browse")}
</Button>
</SettingRow>
</div>
<DialogFooter>
<DialogClose asChild>
<Button type="button" variant="outline">
{t("Cancel")}
</Button>
</DialogClose>
<Button type="button" onClick={handleSave} disabled={loading}>
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{t("Save")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
); );
}); });

View File

@@ -1,4 +1,4 @@
import {useMemo, useRef, useState} from "react"; import { useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { mutate } from "swr"; import { mutate } from "swr";
@@ -43,7 +43,7 @@ import {
Power, Power,
BellOff, BellOff,
Repeat, Repeat,
Fingerprint Fingerprint,
} from "lucide-react"; } from "lucide-react";
// Модальные окна // Модальные окна
@@ -56,7 +56,7 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import {useProfiles} from "@/hooks/use-profiles"; import { useProfiles } from "@/hooks/use-profiles";
const isWIN = getSystem() === "windows"; const isWIN = getSystem() === "windows";
interface Props { interface Props {
@@ -110,7 +110,7 @@ const SettingSystem = ({ onError }: Props) => {
const { profiles } = useProfiles(); const { profiles } = useProfiles();
const hasProfiles = useMemo(() => { const hasProfiles = useMemo(() => {
const items = profiles?.items ?? []; const items = profiles?.items ?? [];
return items.some(p => p.type === 'local' || p.type === 'remote'); return items.some((p) => p.type === "local" || p.type === "remote");
}, [profiles]); }, [profiles]);
const { const {
@@ -261,7 +261,10 @@ const SettingSystem = ({ onError }: Props) => {
); );
} }
if (e) { if (e) {
return patchVerge({ enable_tun_mode: true, enable_system_proxy: false }); return patchVerge({
enable_tun_mode: true,
enable_system_proxy: false,
});
} else { } else {
return patchVerge({ enable_tun_mode: false }); return patchVerge({ enable_tun_mode: false });
} }

View File

@@ -188,20 +188,20 @@ const SettingVergeBasic = ({ onError }: Props) => {
{OS !== "linux" && ( {OS !== "linux" && (
<SettingRow <SettingRow
label={ label={
<LabelWithIcon <LabelWithIcon
icon={MousePointerClick} icon={MousePointerClick}
text={t("Tray Click Event")} text={t("Tray Click Event")}
/> />
} }
> >
<GuardState <GuardState
value={tray_event ?? "main_window"} value={tray_event ?? "main_window"}
onCatch={onError} onCatch={onError}
onFormat={(v) => v} onFormat={(v) => v}
onChange={(e) => onChangeData({ tray_event: e })} onChange={(e) => onChangeData({ tray_event: e })}
onGuard={(e) => patchVerge({ tray_event: e })} onGuard={(e) => patchVerge({ tray_event: e })}
onChangeProps="onValueChange" onChangeProps="onValueChange"
> >
<Select> <Select>
<SelectTrigger className="w-40 h-8"> <SelectTrigger className="w-40 h-8">

View File

@@ -5,263 +5,263 @@ import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "@root/lib/utils"; import { cn } from "@root/lib/utils";
function DropdownMenu({ function DropdownMenu({
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />; return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
} }
function DropdownMenuPortal({ function DropdownMenuPortal({
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return ( return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} /> <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
); );
} }
function DropdownMenuTrigger({ function DropdownMenuTrigger({
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return ( return (
<DropdownMenuPrimitive.Trigger <DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger" data-slot="dropdown-menu-trigger"
{...props} {...props}
/> />
); );
} }
function DropdownMenuContent({ function DropdownMenuContent({
className, className,
sideOffset = 4, sideOffset = 4,
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return ( return (
<DropdownMenuPrimitive.Portal> <DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content <DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content" data-slot="dropdown-menu-content"
sideOffset={sideOffset} sideOffset={sideOffset}
className={cn( className={cn(
"z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md p-1", "z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md p-1",
"backdrop-blur-sm bg-white/70 border border-white/40", "backdrop-blur-sm bg-white/70 border border-white/40",
"dark:bg-white/10 dark:border-white/20", "dark:bg-white/10 dark:border-white/20",
"shadow-[0_8px_32px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_32px_rgba(255,255,255,0.05)]", "shadow-[0_8px_32px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_32px_rgba(255,255,255,0.05)]",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className, className,
)} )}
{...props} {...props}
/> />
</DropdownMenuPrimitive.Portal> </DropdownMenuPrimitive.Portal>
); );
} }
function DropdownMenuGroup({ function DropdownMenuGroup({
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return ( return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} /> <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
); );
} }
function DropdownMenuItem({ function DropdownMenuItem({
className, className,
inset, inset,
variant = "default", variant = "default",
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & { }: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean; inset?: boolean;
variant?: "default" | "destructive"; variant?: "default" | "destructive";
}) { }) {
return ( return (
<DropdownMenuPrimitive.Item <DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item" data-slot="dropdown-menu-item"
data-inset={inset} data-inset={inset}
data-variant={variant} data-variant={variant}
className={cn( className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8", "relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8",
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80", "hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
"dark:hover:bg-white/20 dark:focus:bg-white/20", "dark:hover:bg-white/20 dark:focus:bg-white/20",
"data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-red-200/80 data-[variant=destructive]:focus:bg-red-200/80", "data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-red-200/80 data-[variant=destructive]:focus:bg-red-200/80",
"dark:data-[variant=destructive]:hover:bg-destructive/20 dark:data-[variant=destructive]:focus:bg-destructive/20", "dark:data-[variant=destructive]:hover:bg-destructive/20 dark:data-[variant=destructive]:focus:bg-destructive/20",
"data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive", "data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive",
"[&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", "[&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className, className,
)} )}
{...props} {...props}
/> />
); );
} }
function DropdownMenuCheckboxItem({ function DropdownMenuCheckboxItem({
className, className,
children, children,
checked, checked,
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return ( return (
<DropdownMenuPrimitive.CheckboxItem <DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item" data-slot="dropdown-menu-checkbox-item"
className={cn( className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50", "relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80", "hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
"dark:hover:bg-white/20 dark:focus:bg-white/20", "dark:hover:bg-white/20 dark:focus:bg-white/20",
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className, className,
)} )}
checked={checked} checked={checked}
{...props} {...props}
> >
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center"> <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator> <DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" /> <CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator> </DropdownMenuPrimitive.ItemIndicator>
</span> </span>
{children} {children}
</DropdownMenuPrimitive.CheckboxItem> </DropdownMenuPrimitive.CheckboxItem>
); );
} }
function DropdownMenuRadioGroup({ function DropdownMenuRadioGroup({
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return ( return (
<DropdownMenuPrimitive.RadioGroup <DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group" data-slot="dropdown-menu-radio-group"
{...props} {...props}
/> />
); );
} }
function DropdownMenuRadioItem({ function DropdownMenuRadioItem({
className, className,
children, children,
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return ( return (
<DropdownMenuPrimitive.RadioItem <DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item" data-slot="dropdown-menu-radio-item"
className={cn( className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50", "relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80", "hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
"dark:hover:bg-white/20 dark:focus:bg-white/20", "dark:hover:bg-white/20 dark:focus:bg-white/20",
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className, className,
)} )}
{...props} {...props}
> >
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center"> <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator> <DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" /> <CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator> </DropdownMenuPrimitive.ItemIndicator>
</span> </span>
{children} {children}
</DropdownMenuPrimitive.RadioItem> </DropdownMenuPrimitive.RadioItem>
); );
} }
function DropdownMenuLabel({ function DropdownMenuLabel({
className, className,
inset, inset,
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & { }: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean; inset?: boolean;
}) { }) {
return ( return (
<DropdownMenuPrimitive.Label <DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label" data-slot="dropdown-menu-label"
data-inset={inset} data-inset={inset}
className={cn( className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8", "px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
"text-foreground/80", "text-foreground/80",
className, className,
)} )}
{...props} {...props}
/> />
); );
} }
function DropdownMenuSeparator({ function DropdownMenuSeparator({
className, className,
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return ( return (
<DropdownMenuPrimitive.Separator <DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator" data-slot="dropdown-menu-separator"
className={cn( className={cn(
"-mx-1 my-1 h-px", "-mx-1 my-1 h-px",
"bg-gray-400/50 dark:bg-white/20", "bg-gray-400/50 dark:bg-white/20",
className className,
)} )}
{...props} {...props}
/> />
); );
} }
function DropdownMenuShortcut({ function DropdownMenuShortcut({
className, className,
...props ...props
}: React.ComponentProps<"span">) { }: React.ComponentProps<"span">) {
return ( return (
<span <span
data-slot="dropdown-menu-shortcut" data-slot="dropdown-menu-shortcut"
className={cn( className={cn(
"ml-auto text-xs tracking-widest", "ml-auto text-xs tracking-widest",
"text-foreground/60", "text-foreground/60",
className, className,
)} )}
{...props} {...props}
/> />
); );
} }
function DropdownMenuSub({ function DropdownMenuSub({
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />; return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
} }
function DropdownMenuSubTrigger({ function DropdownMenuSubTrigger({
className, className,
inset, inset,
children, children,
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & { }: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean; inset?: boolean;
}) { }) {
return ( return (
<DropdownMenuPrimitive.SubTrigger <DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger" data-slot="dropdown-menu-sub-trigger"
data-inset={inset} data-inset={inset}
className={cn( className={cn(
"flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8", "flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80", "hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
"data-[state=open]:backdrop-blur-sm data-[state=open]:bg-gray-200/80", "data-[state=open]:backdrop-blur-sm data-[state=open]:bg-gray-200/80",
"dark:hover:bg-white/20 dark:focus:bg-white/20 dark:data-[state=open]:bg-white/20", "dark:hover:bg-white/20 dark:focus:bg-white/20 dark:data-[state=open]:bg-white/20",
className, className,
)} )}
{...props} {...props}
> >
{children} {children}
<ChevronRightIcon className="ml-auto size-4" /> <ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger> </DropdownMenuPrimitive.SubTrigger>
); );
} }
function DropdownMenuSubContent({ function DropdownMenuSubContent({
className, className,
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return ( return (
<DropdownMenuPrimitive.SubContent <DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content" data-slot="dropdown-menu-sub-content"
className={cn( className={cn(
"z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md p-1", "z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md p-1",
"backdrop-blur-sm bg-white/70 border border-white/40", "backdrop-blur-sm bg-white/70 border border-white/40",
"dark:bg-white/10 dark:border-white/20", "dark:bg-white/10 dark:border-white/20",
"shadow-[0_8px_32px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_32px_rgba(255,255,255,0.05)]", "shadow-[0_8px_32px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_32px_rgba(255,255,255,0.05)]",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className, className,
)} )}
{...props} {...props}
/> />
); );
} }
@@ -281,4 +281,4 @@ export {
DropdownMenuSub, DropdownMenuSub,
DropdownMenuSubTrigger, DropdownMenuSubTrigger,
DropdownMenuSubContent, DropdownMenuSubContent,
}; };

View File

@@ -5,191 +5,191 @@ import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import { cn } from "@root/lib/utils"; import { cn } from "@root/lib/utils";
function Select({ function Select({
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) { }: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />; return <SelectPrimitive.Root data-slot="select" {...props} />;
} }
function SelectGroup({ function SelectGroup({
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) { }: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />; return <SelectPrimitive.Group data-slot="select-group" {...props} />;
} }
function SelectValue({ function SelectValue({
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) { }: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />; return <SelectPrimitive.Value data-slot="select-value" {...props} />;
} }
function SelectTrigger({ function SelectTrigger({
className, className,
size = "default", size = "default",
children, children,
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & { }: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"; size?: "sm" | "default";
}) { }) {
return ( return (
<SelectPrimitive.Trigger <SelectPrimitive.Trigger
data-slot="select-trigger" data-slot="select-trigger"
data-size={size} data-size={size}
className={cn( className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive flex w-fit items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow,background-color] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", "border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive flex w-fit items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow,background-color] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"backdrop-blur-sm bg-white/80 border-gray-300/60", "backdrop-blur-sm bg-white/80 border-gray-300/60",
"dark:bg-white/5 dark:border-white/15", "dark:bg-white/5 dark:border-white/15",
"hover:bg-white/90 hover:border-gray-400/70", "hover:bg-white/90 hover:border-gray-400/70",
"dark:hover:bg-white/10 dark:hover:border-white/20", "dark:hover:bg-white/10 dark:hover:border-white/20",
className, className,
)} )}
{...props} {...props}
> >
{children} {children}
<SelectPrimitive.Icon asChild> <SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" /> <ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon> </SelectPrimitive.Icon>
</SelectPrimitive.Trigger> </SelectPrimitive.Trigger>
); );
} }
function SelectContent({ function SelectContent({
className, className,
children, children,
position = "popper", position = "popper",
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) { }: React.ComponentProps<typeof SelectPrimitive.Content>) {
return ( return (
<SelectPrimitive.Portal> <SelectPrimitive.Portal>
<SelectPrimitive.Content <SelectPrimitive.Content
data-slot="select-content" data-slot="select-content"
className={cn( className={cn(
"relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md", "relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md",
"backdrop-blur-sm bg-white/70 border border-white/40", "backdrop-blur-sm bg-white/70 border border-white/40",
"dark:bg-white/10 dark:border-white/20", "dark:bg-white/10 dark:border-white/20",
"shadow-[0_8px_32px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_32px_rgba(255,255,255,0.05)]", "shadow-[0_8px_32px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_32px_rgba(255,255,255,0.05)]",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
position === "popper" && position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1", "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className, className,
)} )}
position={position} position={position}
{...props} {...props}
> >
<SelectScrollUpButton /> <SelectScrollUpButton />
<SelectPrimitive.Viewport <SelectPrimitive.Viewport
className={cn( className={cn(
"p-1", "p-1",
position === "popper" && position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1", "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
)} )}
> >
{children} {children}
</SelectPrimitive.Viewport> </SelectPrimitive.Viewport>
<SelectScrollDownButton /> <SelectScrollDownButton />
</SelectPrimitive.Content> </SelectPrimitive.Content>
</SelectPrimitive.Portal> </SelectPrimitive.Portal>
); );
} }
function SelectLabel({ function SelectLabel({
className, className,
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) { }: React.ComponentProps<typeof SelectPrimitive.Label>) {
return ( return (
<SelectPrimitive.Label <SelectPrimitive.Label
data-slot="select-label" data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)} className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props} {...props}
/> />
); );
} }
function SelectItem({ function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
"dark:hover:bg-white/20 dark:focus:bg-white/20",
"transition-all duration-200",
"[&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className, className,
children, )}
...props {...props}
}: React.ComponentProps<typeof SelectPrimitive.Item>) { >
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
"dark:hover:bg-white/20 dark:focus:bg-white/20",
"transition-all duration-200",
"[&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className,
)}
{...props}
>
<span className="absolute right-2 flex size-3.5 items-center justify-center"> <span className="absolute right-2 flex size-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator> <SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" /> <CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator> </SelectPrimitive.ItemIndicator>
</span> </span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText> <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item> </SelectPrimitive.Item>
); );
} }
function SelectSeparator({ function SelectSeparator({
className, className,
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) { }: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return ( return (
<SelectPrimitive.Separator <SelectPrimitive.Separator
data-slot="select-separator" data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)} className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props} {...props}
/> />
); );
} }
function SelectScrollUpButton({ function SelectScrollUpButton({
className, className,
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) { }: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return ( return (
<SelectPrimitive.ScrollUpButton <SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button" data-slot="select-scroll-up-button"
className={cn( className={cn(
"flex cursor-default items-center justify-center py-1", "flex cursor-default items-center justify-center py-1",
className, className,
)} )}
{...props} {...props}
> >
<ChevronUpIcon className="size-4" /> <ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton> </SelectPrimitive.ScrollUpButton>
); );
} }
function SelectScrollDownButton({ function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className, className,
...props )}
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) { {...props}
return ( >
<SelectPrimitive.ScrollDownButton <ChevronDownIcon className="size-4" />
data-slot="select-scroll-down-button" </SelectPrimitive.ScrollDownButton>
className={cn( );
"flex cursor-default items-center justify-center py-1",
className,
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
);
} }
export { export {
Select, Select,
SelectContent, SelectContent,
SelectGroup, SelectGroup,
SelectItem, SelectItem,
SelectLabel, SelectLabel,
SelectScrollDownButton, SelectScrollDownButton,
SelectScrollUpButton, SelectScrollUpButton,
SelectSeparator, SelectSeparator,
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
}; };

View File

@@ -1,54 +1,54 @@
import * as React from "react" import * as React from "react";
import { Slot } from "@radix-ui/react-slot" import { Slot } from "@radix-ui/react-slot";
import { cva, VariantProps } from "class-variance-authority" import { cva, VariantProps } from "class-variance-authority";
import { PanelLeftIcon } from "lucide-react" import { PanelLeftIcon } from "lucide-react";
import { useIsMobile } from "@root/hooks/use-mobile" import { useIsMobile } from "@root/hooks/use-mobile";
import { cn } from "@root/lib/utils" import { cn } from "@root/lib/utils";
import { Button } from "@root/src/components/ui/button" import { Button } from "@root/src/components/ui/button";
import { Input } from "@root/src/components/ui/input" import { Input } from "@root/src/components/ui/input";
import { Separator } from "@root/src/components/ui/separator" import { Separator } from "@root/src/components/ui/separator";
import { import {
Sheet, Sheet,
SheetContent, SheetContent,
SheetDescription, SheetDescription,
SheetHeader, SheetHeader,
SheetTitle, SheetTitle,
} from "@root/src/components/ui/sheet" } from "@root/src/components/ui/sheet";
import { Skeleton } from "@root/src/components/ui/skeleton" import { Skeleton } from "@root/src/components/ui/skeleton";
import { import {
Tooltip, Tooltip,
TooltipContent, TooltipContent,
TooltipProvider, TooltipProvider,
TooltipTrigger, TooltipTrigger,
} from "@root/src/components/ui/tooltip" } from "@root/src/components/ui/tooltip";
const SIDEBAR_COOKIE_NAME = "sidebar_state" const SIDEBAR_COOKIE_NAME = "sidebar_state";
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7 const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
const SIDEBAR_WIDTH = "16rem" const SIDEBAR_WIDTH = "16rem";
const SIDEBAR_WIDTH_MOBILE = "18rem" const SIDEBAR_WIDTH_MOBILE = "18rem";
const SIDEBAR_WIDTH_ICON = "3rem" const SIDEBAR_WIDTH_ICON = "3rem";
const SIDEBAR_KEYBOARD_SHORTCUT = "b" const SIDEBAR_KEYBOARD_SHORTCUT = "b";
type SidebarContextProps = { type SidebarContextProps = {
state: "expanded" | "collapsed" state: "expanded" | "collapsed";
open: boolean open: boolean;
setOpen: (open: boolean) => void setOpen: (open: boolean) => void;
openMobile: boolean openMobile: boolean;
setOpenMobile: (open: boolean) => void setOpenMobile: (open: boolean) => void;
isMobile: boolean isMobile: boolean;
toggleSidebar: () => void toggleSidebar: () => void;
} };
const SidebarContext = React.createContext<SidebarContextProps | null>(null) const SidebarContext = React.createContext<SidebarContextProps | null>(null);
function useSidebar() { function useSidebar() {
const context = React.useContext(SidebarContext) const context = React.useContext(SidebarContext);
if (!context) { if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.") throw new Error("useSidebar must be used within a SidebarProvider.");
} }
return context return context;
} }
function SidebarProvider({ function SidebarProvider({
@@ -60,36 +60,36 @@ function SidebarProvider({
children, children,
...props ...props
}: React.ComponentProps<"div"> & { }: React.ComponentProps<"div"> & {
defaultOpen?: boolean defaultOpen?: boolean;
open?: boolean open?: boolean;
onOpenChange?: (open: boolean) => void onOpenChange?: (open: boolean) => void;
}) { }) {
const isMobile = useIsMobile() const isMobile = useIsMobile();
const [openMobile, setOpenMobile] = React.useState(false) const [openMobile, setOpenMobile] = React.useState(false);
// This is the internal state of the sidebar. // This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component. // We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen) const [_open, _setOpen] = React.useState(defaultOpen);
const open = openProp ?? _open const open = openProp ?? _open;
const setOpen = React.useCallback( const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => { (value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value const openState = typeof value === "function" ? value(open) : value;
if (setOpenProp) { if (setOpenProp) {
setOpenProp(openState) setOpenProp(openState);
} else { } else {
_setOpen(openState) _setOpen(openState);
} }
// This sets the cookie to keep the sidebar state. // This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}` document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
}, },
[setOpenProp, open] [setOpenProp, open],
) );
// Helper to toggle the sidebar. // Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => { const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open) return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
}, [isMobile, setOpen, setOpenMobile]) }, [isMobile, setOpen, setOpenMobile]);
// Adds a keyboard shortcut to toggle the sidebar. // Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => { React.useEffect(() => {
@@ -98,18 +98,18 @@ function SidebarProvider({
event.key === SIDEBAR_KEYBOARD_SHORTCUT && event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey) (event.metaKey || event.ctrlKey)
) { ) {
event.preventDefault() event.preventDefault();
toggleSidebar() toggleSidebar();
} }
} };
window.addEventListener("keydown", handleKeyDown) window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown) return () => window.removeEventListener("keydown", handleKeyDown);
}, [toggleSidebar]) }, [toggleSidebar]);
// We add a state so that we can do data-state="expanded" or "collapsed". // We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes. // This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed" const state = open ? "expanded" : "collapsed";
const contextValue = React.useMemo<SidebarContextProps>( const contextValue = React.useMemo<SidebarContextProps>(
() => ({ () => ({
@@ -121,8 +121,8 @@ function SidebarProvider({
setOpenMobile, setOpenMobile,
toggleSidebar, toggleSidebar,
}), }),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar] [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar],
) );
return ( return (
<SidebarContext.Provider value={contextValue}> <SidebarContext.Provider value={contextValue}>
@@ -138,7 +138,7 @@ function SidebarProvider({
} }
className={cn( className={cn(
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full", "group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
className className,
)} )}
{...props} {...props}
> >
@@ -146,7 +146,7 @@ function SidebarProvider({
</div> </div>
</TooltipProvider> </TooltipProvider>
</SidebarContext.Provider> </SidebarContext.Provider>
) );
} }
function Sidebar({ function Sidebar({
@@ -157,11 +157,11 @@ function Sidebar({
children, children,
...props ...props
}: React.ComponentProps<"div"> & { }: React.ComponentProps<"div"> & {
side?: "left" | "right" side?: "left" | "right";
variant?: "sidebar" | "floating" | "inset" variant?: "sidebar" | "floating" | "inset";
collapsible?: "offcanvas" | "icon" | "none" collapsible?: "offcanvas" | "icon" | "none";
}) { }) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar() const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
if (collapsible === "none") { if (collapsible === "none") {
return ( return (
@@ -169,13 +169,13 @@ function Sidebar({
data-slot="sidebar" data-slot="sidebar"
className={cn( className={cn(
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col", "bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
className className,
)} )}
{...props} {...props}
> >
{children} {children}
</div> </div>
) );
} }
if (isMobile) { if (isMobile) {
@@ -200,7 +200,7 @@ function Sidebar({
<div className="flex h-full w-full flex-col">{children}</div> <div className="flex h-full w-full flex-col">{children}</div>
</SheetContent> </SheetContent>
</Sheet> </Sheet>
) );
} }
return ( return (
@@ -221,7 +221,7 @@ function Sidebar({
"group-data-[side=right]:rotate-180", "group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset" variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]" ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)" : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
)} )}
/> />
<div <div
@@ -235,7 +235,7 @@ function Sidebar({
variant === "floating" || variant === "inset" variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]" ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l", : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
className className,
)} )}
{...props} {...props}
> >
@@ -248,7 +248,7 @@ function Sidebar({
</div> </div>
</div> </div>
</div> </div>
) );
} }
function SidebarTrigger({ function SidebarTrigger({
@@ -256,7 +256,7 @@ function SidebarTrigger({
onClick, onClick,
...props ...props
}: React.ComponentProps<typeof Button>) { }: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar() const { toggleSidebar } = useSidebar();
return ( return (
<Button <Button
@@ -266,19 +266,19 @@ function SidebarTrigger({
size="icon" size="icon"
className={cn("size-7", className)} className={cn("size-7", className)}
onClick={(event) => { onClick={(event) => {
onClick?.(event) onClick?.(event);
toggleSidebar() toggleSidebar();
}} }}
{...props} {...props}
> >
<PanelLeftIcon /> <PanelLeftIcon />
<span className="sr-only">Toggle Sidebar</span> <span className="sr-only">Toggle Sidebar</span>
</Button> </Button>
) );
} }
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) { function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { toggleSidebar } = useSidebar() const { toggleSidebar } = useSidebar();
return ( return (
<button <button
@@ -295,11 +295,11 @@ function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full", "hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2", "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2", "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) { function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
@@ -309,11 +309,11 @@ function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
className={cn( className={cn(
"bg-background relative flex w-full flex-1 flex-col", "bg-background relative flex w-full flex-1 flex-col",
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2", "md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function SidebarInput({ function SidebarInput({
@@ -327,7 +327,7 @@ function SidebarInput({
className={cn("bg-background h-8 w-full shadow-none", className)} className={cn("bg-background h-8 w-full shadow-none", className)}
{...props} {...props}
/> />
) );
} }
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) { function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
@@ -338,7 +338,7 @@ function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
className={cn("flex flex-col gap-2 p-2", className)} className={cn("flex flex-col gap-2 p-2", className)}
{...props} {...props}
/> />
) );
} }
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) { function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
@@ -349,7 +349,7 @@ function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
className={cn("flex flex-col gap-2 p-2", className)} className={cn("flex flex-col gap-2 p-2", className)}
{...props} {...props}
/> />
) );
} }
function SidebarSeparator({ function SidebarSeparator({
@@ -363,7 +363,7 @@ function SidebarSeparator({
className={cn("bg-sidebar-border mx-2 w-auto", className)} className={cn("bg-sidebar-border mx-2 w-auto", className)}
{...props} {...props}
/> />
) );
} }
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) { function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
@@ -373,11 +373,11 @@ function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
data-sidebar="content" data-sidebar="content"
className={cn( className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden", "flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) { function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
@@ -388,7 +388,7 @@ function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
className={cn("relative flex w-full min-w-0 flex-col p-2", className)} className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props} {...props}
/> />
) );
} }
function SidebarGroupLabel({ function SidebarGroupLabel({
@@ -396,7 +396,7 @@ function SidebarGroupLabel({
asChild = false, asChild = false,
...props ...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) { }: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "div" const Comp = asChild ? Slot : "div";
return ( return (
<Comp <Comp
@@ -405,11 +405,11 @@ function SidebarGroupLabel({
className={cn( className={cn(
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0", "text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0", "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function SidebarGroupAction({ function SidebarGroupAction({
@@ -417,7 +417,7 @@ function SidebarGroupAction({
asChild = false, asChild = false,
...props ...props
}: React.ComponentProps<"button"> & { asChild?: boolean }) { }: React.ComponentProps<"button"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "button" const Comp = asChild ? Slot : "button";
return ( return (
<Comp <Comp
@@ -428,11 +428,11 @@ function SidebarGroupAction({
// Increases the hit area of the button on mobile. // Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden", "after:absolute after:-inset-2 md:after:hidden",
"group-data-[collapsible=icon]:hidden", "group-data-[collapsible=icon]:hidden",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function SidebarGroupContent({ function SidebarGroupContent({
@@ -446,7 +446,7 @@ function SidebarGroupContent({
className={cn("w-full text-sm", className)} className={cn("w-full text-sm", className)}
{...props} {...props}
/> />
) );
} }
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) { function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
@@ -457,7 +457,7 @@ function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
className={cn("flex w-full min-w-0 flex-col gap-1", className)} className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props} {...props}
/> />
) );
} }
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) { function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
@@ -468,7 +468,7 @@ function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
className={cn("group/menu-item relative", className)} className={cn("group/menu-item relative", className)}
{...props} {...props}
/> />
) );
} }
const sidebarMenuButtonVariants = cva( const sidebarMenuButtonVariants = cva(
@@ -490,8 +490,8 @@ const sidebarMenuButtonVariants = cva(
variant: "default", variant: "default",
size: "default", size: "default",
}, },
} },
) );
function SidebarMenuButton({ function SidebarMenuButton({
asChild = false, asChild = false,
@@ -502,12 +502,12 @@ function SidebarMenuButton({
className, className,
...props ...props
}: React.ComponentProps<"button"> & { }: React.ComponentProps<"button"> & {
asChild?: boolean asChild?: boolean;
isActive?: boolean isActive?: boolean;
tooltip?: string | React.ComponentProps<typeof TooltipContent> tooltip?: string | React.ComponentProps<typeof TooltipContent>;
} & VariantProps<typeof sidebarMenuButtonVariants>) { } & VariantProps<typeof sidebarMenuButtonVariants>) {
const Comp = asChild ? Slot : "button" const Comp = asChild ? Slot : "button";
const { isMobile, state } = useSidebar() const { isMobile, state } = useSidebar();
const button = ( const button = (
<Comp <Comp
@@ -518,16 +518,16 @@ function SidebarMenuButton({
className={cn(sidebarMenuButtonVariants({ variant, size }), className)} className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props} {...props}
/> />
) );
if (!tooltip) { if (!tooltip) {
return button return button;
} }
if (typeof tooltip === "string") { if (typeof tooltip === "string") {
tooltip = { tooltip = {
children: tooltip, children: tooltip,
} };
} }
return ( return (
@@ -540,7 +540,7 @@ function SidebarMenuButton({
{...tooltip} {...tooltip}
/> />
</Tooltip> </Tooltip>
) );
} }
function SidebarMenuAction({ function SidebarMenuAction({
@@ -549,10 +549,10 @@ function SidebarMenuAction({
showOnHover = false, showOnHover = false,
...props ...props
}: React.ComponentProps<"button"> & { }: React.ComponentProps<"button"> & {
asChild?: boolean asChild?: boolean;
showOnHover?: boolean showOnHover?: boolean;
}) { }) {
const Comp = asChild ? Slot : "button" const Comp = asChild ? Slot : "button";
return ( return (
<Comp <Comp
@@ -568,11 +568,11 @@ function SidebarMenuAction({
"group-data-[collapsible=icon]:hidden", "group-data-[collapsible=icon]:hidden",
showOnHover && showOnHover &&
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0", "peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function SidebarMenuBadge({ function SidebarMenuBadge({
@@ -590,11 +590,11 @@ function SidebarMenuBadge({
"peer-data-[size=default]/menu-button:top-1.5", "peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5", "peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden", "group-data-[collapsible=icon]:hidden",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function SidebarMenuSkeleton({ function SidebarMenuSkeleton({
@@ -602,12 +602,12 @@ function SidebarMenuSkeleton({
showIcon = false, showIcon = false,
...props ...props
}: React.ComponentProps<"div"> & { }: React.ComponentProps<"div"> & {
showIcon?: boolean showIcon?: boolean;
}) { }) {
// Random width between 50 to 90%. // Random width between 50 to 90%.
const width = React.useMemo(() => { const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%` return `${Math.floor(Math.random() * 40) + 50}%`;
}, []) }, []);
return ( return (
<div <div
@@ -632,7 +632,7 @@ function SidebarMenuSkeleton({
} }
/> />
</div> </div>
) );
} }
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) { function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
@@ -643,11 +643,11 @@ function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
className={cn( className={cn(
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5", "border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden", "group-data-[collapsible=icon]:hidden",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function SidebarMenuSubItem({ function SidebarMenuSubItem({
@@ -661,7 +661,7 @@ function SidebarMenuSubItem({
className={cn("group/menu-sub-item relative", className)} className={cn("group/menu-sub-item relative", className)}
{...props} {...props}
/> />
) );
} }
function SidebarMenuSubButton({ function SidebarMenuSubButton({
@@ -671,11 +671,11 @@ function SidebarMenuSubButton({
className, className,
...props ...props
}: React.ComponentProps<"a"> & { }: React.ComponentProps<"a"> & {
asChild?: boolean asChild?: boolean;
size?: "sm" | "md" size?: "sm" | "md";
isActive?: boolean isActive?: boolean;
}) { }) {
const Comp = asChild ? Slot : "a" const Comp = asChild ? Slot : "a";
return ( return (
<Comp <Comp
@@ -689,11 +689,11 @@ function SidebarMenuSubButton({
size === "sm" && "text-xs", size === "sm" && "text-xs",
size === "md" && "text-sm", size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden", "group-data-[collapsible=icon]:hidden",
className className,
)} )}
{...props} {...props}
/> />
) );
} }
export { export {
@@ -721,4 +721,4 @@ export {
SidebarSeparator, SidebarSeparator,
SidebarTrigger, SidebarTrigger,
useSidebar, useSidebar,
} };

View File

@@ -1,4 +1,4 @@
import { cn } from "@root/lib/utils" import { cn } from "@root/lib/utils";
function Skeleton({ className, ...props }: React.ComponentProps<"div">) { function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return ( return (
@@ -7,7 +7,7 @@ function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
className={cn("bg-accent animate-pulse rounded-md", className)} className={cn("bg-accent animate-pulse rounded-md", className)}
{...props} {...props}
/> />
) );
} }
export { Skeleton } export { Skeleton };

View File

@@ -1,5 +1,5 @@
import { useEffect, useState, useCallback } from 'react'; import { useEffect, useState, useCallback } from "react";
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'; import { WebviewWindow } from "@tauri-apps/api/webviewWindow";
// Константы для управления масштабом // Константы для управления масштабом
const ZOOM_STEP = 0.1; const ZOOM_STEP = 0.1;
@@ -22,7 +22,9 @@ export const useZoomControls = () => {
let initialZoom = 1.0; let initialZoom = 1.0;
console.log(`Physical width: ${size.width}, Scale Factor: ${scaleFactor}, Logical width: ${logicalWidth}`); console.log(
`Physical width: ${size.width}, Scale Factor: ${scaleFactor}, Logical width: ${logicalWidth}`,
);
// 3. Используем логическую ширину для принятия решения // 3. Используем логическую ширину для принятия решения
if (logicalWidth < 1300) { if (logicalWidth < 1300) {
@@ -38,18 +40,24 @@ export const useZoomControls = () => {
setInitialZoom(); setInitialZoom();
}, []); }, []);
const handleZoom = useCallback((delta: number, isReset = false) => { const handleZoom = useCallback(
setZoomLevel(currentZoom => { (delta: number, isReset = false) => {
const newZoom = isReset ? 1.0 : currentZoom + delta; setZoomLevel((currentZoom) => {
const clampedZoom = Math.max(MIN_ZOOM, Math.min(newZoom, MAX_ZOOM)); const newZoom = isReset ? 1.0 : currentZoom + delta;
const roundedZoom = Math.round(clampedZoom * 100) / 100; const clampedZoom = Math.max(MIN_ZOOM, Math.min(newZoom, MAX_ZOOM));
const roundedZoom = Math.round(clampedZoom * 100) / 100;
appWindow.setZoom(roundedZoom); appWindow.setZoom(roundedZoom);
const newStrokeWidth = 2 / roundedZoom; const newStrokeWidth = 2 / roundedZoom;
document.documentElement.style.setProperty('--icon-stroke-width', newStrokeWidth.toString()); document.documentElement.style.setProperty(
return roundedZoom; "--icon-stroke-width",
}); newStrokeWidth.toString(),
}, [appWindow]); );
return roundedZoom;
});
},
[appWindow],
);
useEffect(() => { useEffect(() => {
const handleWheel = (event: WheelEvent) => { const handleWheel = (event: WheelEvent) => {
@@ -63,18 +71,18 @@ export const useZoomControls = () => {
const handleKeyDown = (event: KeyboardEvent) => { const handleKeyDown = (event: KeyboardEvent) => {
if (event.ctrlKey || event.metaKey) { if (event.ctrlKey || event.metaKey) {
switch (event.code) { switch (event.code) {
case 'Equal': case "Equal":
case 'NumpadAdd': case "NumpadAdd":
event.preventDefault(); event.preventDefault();
handleZoom(ZOOM_STEP); handleZoom(ZOOM_STEP);
break; break;
case 'Minus': case "Minus":
case 'NumpadSubtract': case "NumpadSubtract":
event.preventDefault(); event.preventDefault();
handleZoom(-ZOOM_STEP); handleZoom(-ZOOM_STEP);
break; break;
case 'Digit0': case "Digit0":
case 'Numpad0': case "Numpad0":
event.preventDefault(); event.preventDefault();
handleZoom(0, true); handleZoom(0, true);
break; break;
@@ -82,12 +90,12 @@ export const useZoomControls = () => {
} }
}; };
window.addEventListener('wheel', handleWheel, { passive: false }); window.addEventListener("wheel", handleWheel, { passive: false });
window.addEventListener('keydown', handleKeyDown); window.addEventListener("keydown", handleKeyDown);
return () => { return () => {
window.removeEventListener('wheel', handleWheel); window.removeEventListener("wheel", handleWheel);
window.removeEventListener('keydown', handleKeyDown); window.removeEventListener("keydown", handleKeyDown);
}; };
}, [handleZoom]); }, [handleZoom]);
}; };

View File

@@ -2,7 +2,7 @@
@import "tw-animate-css"; @import "tw-animate-css";
@theme { @theme {
--tailwind-darkMode: 'class'; --tailwind-darkMode: "class";
} }
@theme inline { @theme inline {
@@ -132,7 +132,6 @@ svg {
stroke-width: var(--icon-stroke-width, 2); stroke-width: var(--icon-stroke-width, 2);
} }
@keyframes gradient-wave { @keyframes gradient-wave {
0% { 0% {
background-position: -200% center; background-position: -200% center;

View File

@@ -27,7 +27,6 @@ import { AppSidebar } from "@/components/layout/sidebar";
import { useZoomControls } from "@/hooks/useZoomControls"; import { useZoomControls } from "@/hooks/useZoomControls";
import { HwidErrorDialog } from "@/components/profile/hwid-error-dialog"; import { HwidErrorDialog } from "@/components/profile/hwid-error-dialog";
const appWindow = getCurrentWebviewWindow(); const appWindow = getCurrentWebviewWindow();
export let portableFlag = false; export let portableFlag = false;
@@ -49,16 +48,21 @@ const handleNoticeMessage = (
mutate("getProfiles"); mutate("getProfiles");
navigate("/"); navigate("/");
showNotice("success", t("Import Subscription Successful")); showNotice("success", t("Import Subscription Successful"));
sessionStorage.setItem('activateProfile', msg); sessionStorage.setItem("activateProfile", msg);
break; break;
case "import_sub_url::error": case "import_sub_url::error":
console.log(msg); console.log(msg);
if (msg.toLowerCase().includes('device') || msg.toLowerCase().includes('устройств')) { if (
window.dispatchEvent(new CustomEvent('show-hwid-error', { detail: msg })); msg.toLowerCase().includes("device") ||
} else { msg.toLowerCase().includes("устройств")
showNotice("error", msg); ) {
} window.dispatchEvent(
break; new CustomEvent("show-hwid-error", { detail: msg }),
);
} else {
showNotice("error", msg);
}
break;
case "set_config::error": case "set_config::error":
showNotice("error", msg); showNotice("error", msg);
break; break;
@@ -172,7 +176,10 @@ const Layout = () => {
try { try {
handleNoticeMessage(status, msg, t, navigate); handleNoticeMessage(status, msg, t, navigate);
} catch (error) { } catch (error) {
console.error("[Layout] Failure to process a notification message:", error); console.error(
"[Layout] Failure to process a notification message:",
error,
);
} }
}, 0); }, 0);
}, },
@@ -233,11 +240,17 @@ const Layout = () => {
try { try {
unlisten(); unlisten();
} catch (error) { } catch (error) {
console.error("[Layout] Failed to clear event listener:", error); console.error(
"[Layout] Failed to clear event listener:",
error,
);
} }
}) })
.catch((error) => { .catch((error) => {
console.error("[Layout] Failed to get unlisten function:", error); console.error(
"[Layout] Failed to get unlisten function:",
error,
);
}); });
} }
}); });
@@ -259,7 +272,9 @@ const Layout = () => {
useEffect(() => { useEffect(() => {
if (initRef.current) { if (initRef.current) {
console.log("[Layout] Initialization code has already been executed, skip"); console.log(
"[Layout] Initialization code has already been executed, skip",
);
return; return;
} }
console.log("[Layout] Begin executing initialization code"); console.log("[Layout] Begin executing initialization code");
@@ -305,7 +320,9 @@ const Layout = () => {
} }
initializationAttempts++; initializationAttempts++;
console.log(`[Layout] Start ${initializationAttempts} for the first time`); console.log(
`[Layout] Start ${initializationAttempts} for the first time`,
);
try { try {
removeLoadingOverlay(); removeLoadingOverlay();
@@ -326,7 +343,9 @@ const Layout = () => {
checkReactMount(); checkReactMount();
setTimeout(() => { setTimeout(() => {
console.log("[Layout] React components mount check timeout, continue execution"); console.log(
"[Layout] React components mount check timeout, continue execution",
);
resolve(); resolve();
}, 2000); }, 2000);
}); });
@@ -342,7 +361,9 @@ const Layout = () => {
await notifyBackend("UI ready"); await notifyBackend("UI ready");
isInitialized = true; isInitialized = true;
console.log(`[Layout] The ${initializationAttempts} initialization is complete`); console.log(
`[Layout] The ${initializationAttempts} initialization is complete`,
);
} catch (error) { } catch (error) {
console.error( console.error(
`[Layout] Initialization failure at ${initializationAttempts}:`, `[Layout] Initialization failure at ${initializationAttempts}:`,
@@ -355,7 +376,9 @@ const Layout = () => {
); );
setTimeout(performInitialization, 500); setTimeout(performInitialization, 500);
} else { } else {
console.error("[Layout] All initialization attempts fail, perform emergency initialization"); console.error(
"[Layout] All initialization attempts fail, perform emergency initialization",
);
removeLoadingOverlay(); removeLoadingOverlay();
try { try {
@@ -375,14 +398,19 @@ const Layout = () => {
console.log("[Layout] Start listening for startup completion events"); console.log("[Layout] Start listening for startup completion events");
const unlisten = await listen("verge://startup-completed", () => { const unlisten = await listen("verge://startup-completed", () => {
if (!hasEventTriggered) { if (!hasEventTriggered) {
console.log("[Layout] Receive startup completion event, start initialization"); console.log(
"[Layout] Receive startup completion event, start initialization",
);
hasEventTriggered = true; hasEventTriggered = true;
performInitialization(); performInitialization();
} }
}); });
return unlisten; return unlisten;
} catch (err) { } catch (err) {
console.error("[Layout] Failed to listen for startup completion event:", err); console.error(
"[Layout] Failed to listen for startup completion event:",
err,
);
return () => {}; return () => {};
} }
}; };
@@ -393,18 +421,24 @@ const Layout = () => {
await invoke("update_ui_stage", { stage: "Loading" }); await invoke("update_ui_stage", { stage: "Loading" });
if (!hasEventTriggered && !isInitialized) { if (!hasEventTriggered && !isInitialized) {
console.log("[Layout] Backend is ready, start initialization immediately"); console.log(
"[Layout] Backend is ready, start initialization immediately",
);
hasEventTriggered = true; hasEventTriggered = true;
performInitialization(); performInitialization();
} }
} catch (err) { } catch (err) {
console.log("[Layout] Backend not yet ready, waiting for startup completion event"); console.log(
"[Layout] Backend not yet ready, waiting for startup completion event",
);
} }
}; };
const backupInitialization = setTimeout(() => { const backupInitialization = setTimeout(() => {
if (!hasEventTriggered && !isInitialized) { if (!hasEventTriggered && !isInitialized) {
console.warn("[Layout] Standby initialization trigger: initialization not started within 1.5 seconds"); console.warn(
"[Layout] Standby initialization trigger: initialization not started within 1.5 seconds",
);
hasEventTriggered = true; hasEventTriggered = true;
performInitialization(); performInitialization();
} }
@@ -412,7 +446,9 @@ const Layout = () => {
const emergencyInitialization = setTimeout(() => { const emergencyInitialization = setTimeout(() => {
if (!isInitialized) { if (!isInitialized) {
console.error("[Layout] Emergency initialization trigger: initialization not completed within 5 seconds"); console.error(
"[Layout] Emergency initialization trigger: initialization not completed within 5 seconds",
);
removeLoadingOverlay(); removeLoadingOverlay();
notifyBackend("UI ready").catch(() => {}); notifyBackend("UI ready").catch(() => {});
isInitialized = true; isInitialized = true;
@@ -445,7 +481,7 @@ const Layout = () => {
}, [start_page]); }, [start_page]);
if (!routersEles) { if (!routersEles) {
return <div className="h-screen w-screen bg-background" />; return <div className="h-screen w-screen bg-background" />;
} }
const AppLayout = () => { const AppLayout = () => {
@@ -454,21 +490,18 @@ const Layout = () => {
const routersEles = useRoutes(routers); const routersEles = useRoutes(routers);
return ( return (
<> <>
<AppSidebar /> <AppSidebar />
<main <main className="h-screen w-full overflow-y-auto transition-[margin] duration-200 ease-linear">
className="h-screen w-full overflow-y-auto transition-[margin] duration-200 ease-linear" <div className="h-full w-full relative">
> {routersEles &&
<div className="h-full w-full relative"> React.cloneElement(routersEles, { key: location.pathname })}
{routersEles && React.cloneElement(routersEles, { key: location.pathname })} </div>
</div> </main>
</main> <HwidErrorDialog />
<HwidErrorDialog /> </>
</>
); );
}; };
return ( return (
<SWRConfig value={{ errorRetryCount: 3 }}> <SWRConfig value={{ errorRetryCount: 3 }}>

View File

@@ -22,9 +22,7 @@ import {
ConnectionDetail, ConnectionDetail,
ConnectionDetailRef, ConnectionDetailRef,
} from "@/components/connection/connection-detail"; } from "@/components/connection/connection-detail";
import { import { BaseSearchBox } from "@/components/base/base-search-box";
BaseSearchBox,
} from "@/components/base/base-search-box";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { import {
Select, Select,
@@ -50,7 +48,7 @@ import {
ArrowDown, ArrowDown,
ArrowUp, ArrowUp,
} from "lucide-react"; } from "lucide-react";
import {SidebarTrigger} from "@/components/ui/sidebar"; import { SidebarTrigger } from "@/components/ui/sidebar";
interface IConnectionsItem { interface IConnectionsItem {
id: string; id: string;
@@ -91,14 +89,15 @@ const ConnectionsPage = () => {
const orderOpts: Record<string, OrderFunc> = { const orderOpts: Record<string, OrderFunc> = {
Default: (list) => Default: (list) =>
list.sort( list.sort(
(a, b) => (a, b) =>
new Date(b.start || "0").getTime()! - new Date(b.start || "0").getTime()! -
new Date(a.start || "0").getTime()!, new Date(a.start || "0").getTime()!,
), ),
"Upload Speed": (list) => list.sort((a, b) => (b.curUpload ?? 0) - (a.curUpload ?? 0)), "Upload Speed": (list) =>
list.sort((a, b) => (b.curUpload ?? 0) - (a.curUpload ?? 0)),
"Download Speed": (list) => "Download Speed": (list) =>
list.sort((a, b) => (b.curDownload ?? 0) - (a.curDownload ?? 0)), list.sort((a, b) => (b.curDownload ?? 0) - (a.curDownload ?? 0)),
}; };
const [isPaused, setIsPaused] = useState(false); const [isPaused, setIsPaused] = useState(false);
@@ -121,7 +120,7 @@ const ConnectionsPage = () => {
let conns = displayData.connections.filter((conn) => { let conns = displayData.connections.filter((conn) => {
const { host, destinationIP, process } = conn.metadata; const { host, destinationIP, process } = conn.metadata;
return ( return (
match(host || "") || match(destinationIP || "") || match(process || "") match(host || "") || match(destinationIP || "") || match(process || "")
); );
}); });
if (orderFunc) conns = orderFunc(conns); if (orderFunc) conns = orderFunc(conns);
@@ -129,24 +128,24 @@ const ConnectionsPage = () => {
}, [displayData, match, curOrderOpt]); }, [displayData, match, curOrderOpt]);
const [scrollingElement, setScrollingElement] = useState< const [scrollingElement, setScrollingElement] = useState<
HTMLElement | Window | null HTMLElement | Window | null
>(null); >(null);
const [isScrolled, setIsScrolled] = useState(false); const [isScrolled, setIsScrolled] = useState(false);
const scrollerRefCallback = useCallback( const scrollerRefCallback = useCallback(
(node: HTMLElement | Window | null) => { (node: HTMLElement | Window | null) => {
setScrollingElement(node); setScrollingElement(node);
}, },
[], [],
); );
useEffect(() => { useEffect(() => {
if (!scrollingElement) return; if (!scrollingElement) return;
const handleScroll = () => { const handleScroll = () => {
const scrollTop = const scrollTop =
scrollingElement instanceof Window scrollingElement instanceof Window
? scrollingElement.scrollY ? scrollingElement.scrollY
: scrollingElement.scrollTop; : scrollingElement.scrollTop;
setIsScrolled(scrollTop > 5); setIsScrolled(scrollTop > 5);
}; };
@@ -157,8 +156,8 @@ const ConnectionsPage = () => {
const onCloseAll = useLockFn(closeAllConnections); const onCloseAll = useLockFn(closeAllConnections);
const detailRef = useRef<ConnectionDetailRef>(null!); const detailRef = useRef<ConnectionDetailRef>(null!);
const handleSearch = useCallback( const handleSearch = useCallback(
(m: (content: string) => boolean) => setMatch(() => m), (m: (content: string) => boolean) => setMatch(() => m),
[], [],
); );
const handlePauseToggle = useCallback(() => { const handlePauseToggle = useCallback(() => {
setIsPaused((prev) => { setIsPaused((prev) => {
@@ -179,135 +178,135 @@ const ConnectionsPage = () => {
const headerHeight = "7rem"; const headerHeight = "7rem";
return ( return (
<div className="relative h-full w-full"> <div className="relative h-full w-full">
<div <div
className="absolute top-0 left-0 right-0 z-20 p-4 bg-background/80 backdrop-blur-sm" className="absolute top-0 left-0 right-0 z-20 p-4 bg-background/80 backdrop-blur-sm"
style={{ height: headerHeight }} style={{ height: headerHeight }}
> >
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
<div className="w-10"> <div className="w-10">
<SidebarTrigger /> <SidebarTrigger />
</div> </div>
<h2 className="text-2xl font-semibold tracking-tight"> <h2 className="text-2xl font-semibold tracking-tight">
{t("Connections")} {t("Connections")}
</h2> </h2>
<TooltipProvider delayDuration={100}> <TooltipProvider delayDuration={100}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<div className="flex items-center gap-4 text-sm text-muted-foreground"> <div className="flex items-center gap-4 text-sm text-muted-foreground">
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<ArrowDown className="h-4 w-4 text-green-500" /> <ArrowDown className="h-4 w-4 text-green-500" />
{parseTraffic(displayData.downloadTotal)} {parseTraffic(displayData.downloadTotal)}
</div> </div>
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<ArrowUp className="h-4 w-4 text-sky-500" /> <ArrowUp className="h-4 w-4 text-sky-500" />
{parseTraffic(displayData.uploadTotal)} {parseTraffic(displayData.uploadTotal)}
</div>
</div> </div>
<Separator orientation="vertical" className="h-6 mx-2" />
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={() =>
setSetting((o) =>
o?.layout !== "table"
? { ...o, layout: "table" }
: { ...o, layout: "list" },
)
}
>
{isTableLayout ? (
<List className="h-5 w-5" />
) : (
<Table2 className="h-5 w-5" />
)}
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{isTableLayout ? t("List View") : t("Table View")}</p>
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={handlePauseToggle}
>
{isPaused ? (
<PlayCircle className="h-5 w-5" />
) : (
<PauseCircle className="h-5 w-5" />
)}
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{isPaused ? t("Resume") : t("Pause")}</p>
</TooltipContent>
</Tooltip>
<Button size="sm" variant="destructive" onClick={onCloseAll}>
{t("Close All")}
</Button>
</div> </div>
</TooltipProvider> <Separator orientation="vertical" className="h-6 mx-2" />
</div> <Tooltip>
<div className="flex items-center gap-2 mt-2"> <TooltipTrigger asChild>
{!isTableLayout && ( <Button
<Select variant="ghost"
value={curOrderOpt} size="icon"
onValueChange={(value) => setOrderOpt(value)} onClick={() =>
> setSetting((o) =>
<SelectTrigger className="w-[180px]"> o?.layout !== "table"
<SelectValue placeholder={t("Sort by")} /> ? { ...o, layout: "table" }
</SelectTrigger> : { ...o, layout: "list" },
<SelectContent> )
{Object.keys(orderOpts).map((opt) => ( }
<SelectItem key={opt} value={opt}> >
{t(opt)} {isTableLayout ? (
</SelectItem> <List className="h-5 w-5" />
))} ) : (
</SelectContent> <Table2 className="h-5 w-5" />
</Select> )}
)} </Button>
<div className="flex-1"> </TooltipTrigger>
<BaseSearchBox onSearch={handleSearch} /> <TooltipContent>
<p>{isTableLayout ? t("List View") : t("Table View")}</p>
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={handlePauseToggle}
>
{isPaused ? (
<PlayCircle className="h-5 w-5" />
) : (
<PauseCircle className="h-5 w-5" />
)}
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{isPaused ? t("Resume") : t("Pause")}</p>
</TooltipContent>
</Tooltip>
<Button size="sm" variant="destructive" onClick={onCloseAll}>
{t("Close All")}
</Button>
</div> </div>
</div> </TooltipProvider>
</div> </div>
<div className="flex items-center gap-2 mt-2">
<div {!isTableLayout && (
ref={scrollerRefCallback} <Select
className="absolute left-0 right-0 bottom-0 overflow-y-auto" value={curOrderOpt}
style={{ top: headerHeight }} onValueChange={(value) => setOrderOpt(value)}
> >
{filterConn.length === 0 ? ( <SelectTrigger className="w-[180px]">
<BaseEmpty /> <SelectValue placeholder={t("Sort by")} />
) : isTableLayout ? ( </SelectTrigger>
<div className="p-4 pt-0"> <SelectContent>
<ConnectionTable {Object.keys(orderOpts).map((opt) => (
connections={filterConn} <SelectItem key={opt} value={opt}>
onShowDetail={(detail) => detailRef.current?.open(detail)} {t(opt)}
scrollerRef={scrollerRefCallback} </SelectItem>
/> ))}
</div> </SelectContent>
) : ( </Select>
<Virtuoso
scrollerRef={scrollerRefCallback}
data={filterConn}
className="h-full w-full"
itemContent={(_, item) => (
<ConnectionItem
value={item}
onShowDetail={() => detailRef.current?.open(item)}
/>
)}
/>
)} )}
<ConnectionDetail ref={detailRef} /> <div className="flex-1">
<BaseSearchBox onSearch={handleSearch} />
</div>
</div> </div>
</div> </div>
<div
ref={scrollerRefCallback}
className="absolute left-0 right-0 bottom-0 overflow-y-auto"
style={{ top: headerHeight }}
>
{filterConn.length === 0 ? (
<BaseEmpty />
) : isTableLayout ? (
<div className="p-4 pt-0">
<ConnectionTable
connections={filterConn}
onShowDetail={(detail) => detailRef.current?.open(detail)}
scrollerRef={scrollerRefCallback}
/>
</div>
) : (
<Virtuoso
scrollerRef={scrollerRefCallback}
data={filterConn}
className="h-full w-full"
itemContent={(_, item) => (
<ConnectionItem
value={item}
onShowDetail={() => detailRef.current?.open(item)}
/>
)}
/>
)}
<ConnectionDetail ref={detailRef} />
</div>
</div>
); );
}; };
export default ConnectionsPage; export default ConnectionsPage;

View File

@@ -1,4 +1,10 @@
import React, {useRef, useMemo, useCallback, useState, useEffect} from "react"; import React, {
useRef,
useMemo,
useCallback,
useState,
useEffect,
} from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { toast } from "sonner"; import { toast } from "sonner";
@@ -25,7 +31,11 @@ import {
AlertTriangle, AlertTriangle,
Loader2, Loader2,
Globe, Globe,
Send, ExternalLink, RefreshCw, ArrowDown, ArrowUp, Send,
ExternalLink,
RefreshCw,
ArrowDown,
ArrowUp,
} from "lucide-react"; } from "lucide-react";
import { useVerge } from "@/hooks/use-verge"; import { useVerge } from "@/hooks/use-verge";
import { useSystemState } from "@/hooks/use-system-state"; import { useSystemState } from "@/hooks/use-system-state";
@@ -34,7 +44,12 @@ import { Switch } from "@/components/ui/switch";
import { ProxySelectors } from "@/components/home/proxy-selectors"; import { ProxySelectors } from "@/components/home/proxy-selectors";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { closeAllConnections } from "@/services/api"; import { closeAllConnections } from "@/services/api";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { updateProfile } from "@/services/cmds"; import { updateProfile } from "@/services/cmds";
import { SidebarTrigger } from "@/components/ui/sidebar"; import { SidebarTrigger } from "@/components/ui/sidebar";
import parseTraffic from "@/utils/parse-traffic"; import parseTraffic from "@/utils/parse-traffic";
@@ -48,45 +63,45 @@ const MinimalHomePage: React.FC = () => {
const [isToggling, setIsToggling] = useState(false); const [isToggling, setIsToggling] = useState(false);
const [isUpdating, setIsUpdating] = useState(false); const [isUpdating, setIsUpdating] = useState(false);
const { profiles, patchProfiles, activateSelected, mutateProfiles } = const { profiles, patchProfiles, activateSelected, mutateProfiles } =
useProfiles(); useProfiles();
const viewerRef = useRef<ProfileViewerRef>(null); const viewerRef = useRef<ProfileViewerRef>(null);
const [uidToActivate, setUidToActivate] = useState<string | null>(null); const [uidToActivate, setUidToActivate] = useState<string | null>(null);
const { connections } = useAppData(); const { connections } = useAppData();
const profileItems = useMemo(() => { const profileItems = useMemo(() => {
const items = const items =
profiles && Array.isArray(profiles.items) ? profiles.items : []; profiles && Array.isArray(profiles.items) ? profiles.items : [];
const allowedTypes = ["local", "remote"]; const allowedTypes = ["local", "remote"];
return items.filter((i: any) => i && allowedTypes.includes(i.type!)); return items.filter((i: any) => i && allowedTypes.includes(i.type!));
}, [profiles]); }, [profiles]);
const currentProfile = useMemo(() => { const currentProfile = useMemo(() => {
return profileItems.find(p => p.uid === profiles?.current); return profileItems.find((p) => p.uid === profiles?.current);
}, [profileItems, profiles?.current]); }, [profileItems, profiles?.current]);
const currentProfileName = currentProfile?.name || profiles?.current; const currentProfileName = currentProfile?.name || profiles?.current;
const activateProfile = useCallback( const activateProfile = useCallback(
async (uid: string, notifySuccess: boolean) => { async (uid: string, notifySuccess: boolean) => {
try { try {
await patchProfiles({ current: uid }); await patchProfiles({ current: uid });
await closeAllConnections(); await closeAllConnections();
await activateSelected(); await activateSelected();
if (notifySuccess) { if (notifySuccess) {
toast.success(t("Profile Switched")); toast.success(t("Profile Switched"));
}
} catch (err: any) {
toast.error(err.message || err.toString());
mutateProfiles();
} }
}, } catch (err: any) {
[patchProfiles, activateSelected, mutateProfiles, t], toast.error(err.message || err.toString());
mutateProfiles();
}
},
[patchProfiles, activateSelected, mutateProfiles, t],
); );
useEffect(() => { useEffect(() => {
const uidToActivate = sessionStorage.getItem('activateProfile'); const uidToActivate = sessionStorage.getItem("activateProfile");
if (uidToActivate && profileItems.some(p => p.uid === uidToActivate)) { if (uidToActivate && profileItems.some((p) => p.uid === uidToActivate)) {
activateProfile(uidToActivate, false); activateProfile(uidToActivate, false);
sessionStorage.removeItem('activateProfile'); sessionStorage.removeItem("activateProfile");
} }
}, [profileItems, activateProfile]); }, [profileItems, activateProfile]);
@@ -101,7 +116,7 @@ const MinimalHomePage: React.FC = () => {
const isTunAvailable = isServiceMode || isAdminMode; const isTunAvailable = isServiceMode || isAdminMode;
const isProxyEnabled = verge?.enable_system_proxy || verge?.enable_tun_mode; const isProxyEnabled = verge?.enable_system_proxy || verge?.enable_tun_mode;
const showTunAlert = const showTunAlert =
(verge?.primary_action ?? "tun-mode") === "tun-mode" && !isTunAvailable; (verge?.primary_action ?? "tun-mode") === "tun-mode" && !isTunAvailable;
const handleToggleProxy = useLockFn(async () => { const handleToggleProxy = useLockFn(async () => {
const turningOn = !isProxyEnabled; const turningOn = !isProxyEnabled;
@@ -143,7 +158,7 @@ const MinimalHomePage: React.FC = () => {
}); });
const handleUpdateProfile = useLockFn(async () => { const handleUpdateProfile = useLockFn(async () => {
if (!currentProfile?.uid || currentProfile.type !== 'remote') return; if (!currentProfile?.uid || currentProfile.type !== "remote") return;
setIsUpdating(true); setIsUpdating(true);
try { try {
await updateProfile(currentProfile.uid); await updateProfile(currentProfile.uid);
@@ -159,316 +174,325 @@ const MinimalHomePage: React.FC = () => {
const statusInfo = useMemo(() => { const statusInfo = useMemo(() => {
if (isToggling) { if (isToggling) {
return { return {
text: isProxyEnabled ? t('Disconnecting...') : t('Connecting...'), text: isProxyEnabled ? t("Disconnecting...") : t("Connecting..."),
color: isProxyEnabled ? '#f59e0b' : '#84cc16', color: isProxyEnabled ? "#f59e0b" : "#84cc16",
isAnimating: true, isAnimating: true,
}; };
} }
if (isProxyEnabled) { if (isProxyEnabled) {
return { return {
text: t('Connected'), text: t("Connected"),
color: '#22c55e', color: "#22c55e",
isAnimating: false, isAnimating: false,
}; };
} }
return { return {
text: t('Disconnected'), text: t("Disconnected"),
color: '#ef4444', color: "#ef4444",
isAnimating: false, isAnimating: false,
}; };
}, [isToggling, isProxyEnabled, t]); }, [isToggling, isProxyEnabled, t]);
return ( return (
<div className="h-full w-full flex flex-col"> <div className="h-full w-full flex flex-col">
<div className="absolute inset-0 opacity-20 pointer-events-none z-0 [transform:translateZ(0)]"> <div className="absolute inset-0 opacity-20 pointer-events-none z-0 [transform:translateZ(0)]">
<img <img src={map} alt="World map" className="w-full h-full object-cover" />
src={map}
alt="World map"
className="w-full h-full object-cover"
/>
</div>
{isProxyEnabled && (
<div
className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-[500px] w-[500px] rounded-full pointer-events-none z-0 transition-opacity duration-500"
style={{
background: 'radial-gradient(circle, rgba(34,197,94,0.3) 0%, transparent 70%)',
filter: 'blur(100px)',
}}
/>
)}
<header className="flex-shrink-0 p-5 grid grid-cols-3 items-center z-10">
<div className="flex justify-start">
<SidebarTrigger />
</div>
<div className="justify-self-center flex flex-col items-center gap-2">
<div className="relative flex items-center justify-center">
{profileItems.length > 0 ? (
<>
<div className="absolute right-full mr-2">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="icon"
onClick={() => viewerRef.current?.create()}
className={cn(
"backdrop-blur-sm bg-white/80 border-gray-300/60",
"dark:bg-white/5 dark:border-white/15",
"hover:bg-white/90 hover:border-gray-400/70",
"dark:hover:bg-white/10 dark:hover:border-white/20",
"transition-all duration-200"
)}
>
<PlusCircle className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{t("Add Profile")}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
className={cn(
"w-full max-w-[250px] sm:max-w-xs",
"backdrop-blur-sm bg-white/80 border-gray-300/60",
"dark:bg-white/5 dark:border-white/15",
"hover:bg-white/90 hover:border-gray-400/70",
"dark:hover:bg-white/10 dark:hover:border-white/20",
"transition-all duration-200"
)}
>
<span className="truncate">{currentProfileName}</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[--radix-dropdown-menu-trigger-width]">
<DropdownMenuLabel>{t("Profiles")}</DropdownMenuLabel>
<DropdownMenuSeparator />
{profileItems.map((p) => (
<DropdownMenuItem
key={p.uid}
onSelect={() => handleProfileChange(p.uid)}
>
<span className="flex-1 truncate">{p.name}</span>
{profiles?.current === p.uid && (
<Check className="ml-4 h-4 w-4" />
)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{currentProfile?.type === 'remote' && (
<div className="absolute left-full ml-2">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={handleUpdateProfile}
disabled={isUpdating}
className={cn(
"flex-shrink-0",
"backdrop-blur-sm bg-white/70 border border-gray-300/50",
"dark:bg-white/5 dark:border-white/10",
"hover:bg-white/85 hover:border-gray-400/60",
"dark:hover:bg-white/10 dark:hover:border-white/15",
"transition-all duration-200"
)}
>
{isUpdating ? <Loader2 className="h-5 w-5 animate-spin" /> : <RefreshCw className="h-5 w-5" />}
</Button>
</TooltipTrigger>
<TooltipContent><p>{t("Update Profile")}</p></TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
)}
</>
) : (
<>
<div className="absolute right-full mr-2">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="icon"
onClick={() => viewerRef.current?.create()}
className={cn(
"backdrop-blur-sm bg-white/80 border-gray-300/60",
"dark:bg-white/5 dark:border-white/15",
"hover:bg-white/90 hover:border-gray-400/70",
"dark:hover:bg-white/10 dark:hover:border-white/20",
"transition-all duration-200"
)}
>
<PlusCircle className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{t("Add Profile")}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<Button
variant="outline"
disabled
className={cn(
"max-w-[250px] sm:max-w-xs opacity-50 cursor-not-allowed",
"backdrop-blur-sm bg-white/50 border-gray-300/40",
"dark:bg-white/3 dark:border-white/10"
)}
>
<span className="truncate">{t("No profiles available")}</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-30" />
</Button>
</>
)}
</div>
</div>
<div className="flex justify-end">
</div>
</header>
<main className="flex-1 overflow-y-auto flex items-center justify-center">
<div className="relative flex flex-col items-center gap-8 py-10 w-full max-w-4xl px-4">
{currentProfile?.announce && (
<div className="absolute -top-15 w-full flex justify-center text-center max-w-lg">
{currentProfile.announce_url ? (
<a
href={currentProfile.announce_url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-2 text-base font-semibold text-foreground hover:underline hover:opacity-80 transition-all whitespace-pre-wrap"
title={currentProfile.announce_url.replace(/\\n/g, '\n')}
>
<span>{currentProfile.announce.replace(/\\n/g, '\n')}</span>
<ExternalLink className="h-4 w-4 flex-shrink-0" />
</a>
) : (
<p className="text-base font-semibold text-foreground whitespace-pre-wrap">
{currentProfile.announce}
</p>
)}
</div>
)}
<div className="relative text-center">
<h1
className={cn(
"text-4xl mb-2 font-semibold transition-colors duration-300",
statusInfo.isAnimating && "animate-pulse"
)}
style={{ color: statusInfo.color }}
>
{statusInfo.text}
</h1>
{isProxyEnabled && (
<div className="absolute top-full left-1/2 -translate-x-1/2 mt-52 flex justify-center items-center text-sm text-muted-foreground gap-6">
<div className="flex items-center gap-1">
<ArrowDown className="h-4 w-4 text-green-500" />
{parseTraffic(connections.downloadTotal)}
</div>
<div className="flex items-center gap-1">
<ArrowUp className="h-4 w-4 text-sky-500" />
{parseTraffic(connections.uploadTotal)}
</div>
</div>
)}
</div>
<div className="relative -translate-y-6">
<PowerButton
loading={isToggling}
checked={!!isProxyEnabled}
onClick={handleToggleProxy}
disabled={showTunAlert || isToggling || profileItems.length === 0}
aria-label={t("Toggle Proxy")}
/>
</div>
{showTunAlert && (
<div className="w-full max-w-sm">
<Alert
variant="destructive"
className="flex flex-col items-center gap-2 text-center"
>
<AlertTriangle className="h-4 w-4" />
<AlertTitle>{t("Attention Required")}</AlertTitle>
<AlertDescription className="text-xs">
{t("TUN requires Service Mode or Admin Mode")}
</AlertDescription>
{!isServiceMode && !isAdminMode && (
<Button
size="sm"
className="mt-2"
onClick={installServiceAndRestartCore}
>
<Wrench className="mr-2 h-4 w-4" />
{t("Install Service")}
</Button>
)}
</Alert>
</div>
)}
<div className="w-full max-w-sm mt-4 flex justify-center">
{profileItems.length > 0 ? (
<ProxySelectors />
) : (
<Alert className="flex flex-col items-center gap-2 text-center">
<PlusCircle className="h-4 w-4" />
<AlertTitle>{t("Get Started")}</AlertTitle>
<AlertDescription className="whitespace-pre-wrap">
{t(
"You don't have any profiles yet. Add your first one to begin.",
)}
</AlertDescription>
<Button
className="mt-2"
onClick={() => viewerRef.current?.create()}
>
{t("Add Profile")}
</Button>
</Alert>
)}
</div>
</div>
</main>
<footer className="flex justify-center p-4 flex-shrink-0">
{currentProfile?.support_url && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span>{t("Support")}:</span>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<a href={currentProfile.support_url} target="_blank" rel="noopener noreferrer" className="transition-colors hover:text-primary">
{(currentProfile.support_url.includes('t.me') || currentProfile.support_url.includes('telegram') || currentProfile.support_url.startsWith('tg://')) ? (
<Send className="h-5 w-5" />
) : (
<Globe className="h-5 w-5" />
)}
</a>
</TooltipTrigger>
<TooltipContent>
<p>{currentProfile.support_url}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
)}
</footer>
<ProfileViewer ref={viewerRef} onChange={() => mutateProfiles()} />
</div> </div>
{isProxyEnabled && (
<div
className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-[500px] w-[500px] rounded-full pointer-events-none z-0 transition-opacity duration-500"
style={{
background:
"radial-gradient(circle, rgba(34,197,94,0.3) 0%, transparent 70%)",
filter: "blur(100px)",
}}
/>
)}
<header className="flex-shrink-0 p-5 grid grid-cols-3 items-center z-10">
<div className="flex justify-start">
<SidebarTrigger />
</div>
<div className="justify-self-center flex flex-col items-center gap-2">
<div className="relative flex items-center justify-center">
{profileItems.length > 0 ? (
<>
<div className="absolute right-full mr-2">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="icon"
onClick={() => viewerRef.current?.create()}
className={cn(
"backdrop-blur-sm bg-white/80 border-gray-300/60",
"dark:bg-white/5 dark:border-white/15",
"hover:bg-white/90 hover:border-gray-400/70",
"dark:hover:bg-white/10 dark:hover:border-white/20",
"transition-all duration-200",
)}
>
<PlusCircle className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{t("Add Profile")}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
className={cn(
"w-full max-w-[250px] sm:max-w-xs",
"backdrop-blur-sm bg-white/80 border-gray-300/60",
"dark:bg-white/5 dark:border-white/15",
"hover:bg-white/90 hover:border-gray-400/70",
"dark:hover:bg-white/10 dark:hover:border-white/20",
"transition-all duration-200",
)}
>
<span className="truncate">{currentProfileName}</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[--radix-dropdown-menu-trigger-width]">
<DropdownMenuLabel>{t("Profiles")}</DropdownMenuLabel>
<DropdownMenuSeparator />
{profileItems.map((p) => (
<DropdownMenuItem
key={p.uid}
onSelect={() => handleProfileChange(p.uid)}
>
<span className="flex-1 truncate">{p.name}</span>
{profiles?.current === p.uid && (
<Check className="ml-4 h-4 w-4" />
)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{currentProfile?.type === "remote" && (
<div className="absolute left-full ml-2">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
onClick={handleUpdateProfile}
disabled={isUpdating}
className={cn(
"flex-shrink-0",
"backdrop-blur-sm bg-white/70 border border-gray-300/50",
"dark:bg-white/5 dark:border-white/10",
"hover:bg-white/85 hover:border-gray-400/60",
"dark:hover:bg-white/10 dark:hover:border-white/15",
"transition-all duration-200",
)}
>
{isUpdating ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<RefreshCw className="h-5 w-5" />
)}
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{t("Update Profile")}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
)}
</>
) : (
<>
<div className="absolute right-full mr-2">
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="icon"
onClick={() => viewerRef.current?.create()}
className={cn(
"backdrop-blur-sm bg-white/80 border-gray-300/60",
"dark:bg-white/5 dark:border-white/15",
"hover:bg-white/90 hover:border-gray-400/70",
"dark:hover:bg-white/10 dark:hover:border-white/20",
"transition-all duration-200",
)}
>
<PlusCircle className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{t("Add Profile")}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<Button
variant="outline"
disabled
className={cn(
"max-w-[250px] sm:max-w-xs opacity-50 cursor-not-allowed",
"backdrop-blur-sm bg-white/50 border-gray-300/40",
"dark:bg-white/3 dark:border-white/10",
)}
>
<span className="truncate">{t("No profiles available")}</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-30" />
</Button>
</>
)}
</div>
</div>
<div className="flex justify-end"></div>
</header>
<main className="flex-1 overflow-y-auto flex items-center justify-center">
<div className="relative flex flex-col items-center gap-8 py-10 w-full max-w-4xl px-4">
{currentProfile?.announce && (
<div className="absolute -top-15 w-full flex justify-center text-center max-w-lg">
{currentProfile.announce_url ? (
<a
href={currentProfile.announce_url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-2 text-base font-semibold text-foreground hover:underline hover:opacity-80 transition-all whitespace-pre-wrap"
title={currentProfile.announce_url.replace(/\\n/g, "\n")}
>
<span>{currentProfile.announce.replace(/\\n/g, "\n")}</span>
<ExternalLink className="h-4 w-4 flex-shrink-0" />
</a>
) : (
<p className="text-base font-semibold text-foreground whitespace-pre-wrap">
{currentProfile.announce}
</p>
)}
</div>
)}
<div className="relative text-center">
<h1
className={cn(
"text-4xl mb-2 font-semibold transition-colors duration-300",
statusInfo.isAnimating && "animate-pulse",
)}
style={{ color: statusInfo.color }}
>
{statusInfo.text}
</h1>
{isProxyEnabled && (
<div className="absolute top-full left-1/2 -translate-x-1/2 mt-52 flex justify-center items-center text-sm text-muted-foreground gap-6">
<div className="flex items-center gap-1">
<ArrowDown className="h-4 w-4 text-green-500" />
{parseTraffic(connections.downloadTotal)}
</div>
<div className="flex items-center gap-1">
<ArrowUp className="h-4 w-4 text-sky-500" />
{parseTraffic(connections.uploadTotal)}
</div>
</div>
)}
</div>
<div className="relative -translate-y-6">
<PowerButton
loading={isToggling}
checked={!!isProxyEnabled}
onClick={handleToggleProxy}
disabled={showTunAlert || isToggling || profileItems.length === 0}
aria-label={t("Toggle Proxy")}
/>
</div>
{showTunAlert && (
<div className="w-full max-w-sm">
<Alert
variant="destructive"
className="flex flex-col items-center gap-2 text-center"
>
<AlertTriangle className="h-4 w-4" />
<AlertTitle>{t("Attention Required")}</AlertTitle>
<AlertDescription className="text-xs">
{t("TUN requires Service Mode or Admin Mode")}
</AlertDescription>
{!isServiceMode && !isAdminMode && (
<Button
size="sm"
className="mt-2"
onClick={installServiceAndRestartCore}
>
<Wrench className="mr-2 h-4 w-4" />
{t("Install Service")}
</Button>
)}
</Alert>
</div>
)}
<div className="w-full max-w-sm mt-4 flex justify-center">
{profileItems.length > 0 ? (
<ProxySelectors />
) : (
<Alert className="flex flex-col items-center gap-2 text-center">
<PlusCircle className="h-4 w-4" />
<AlertTitle>{t("Get Started")}</AlertTitle>
<AlertDescription className="whitespace-pre-wrap">
{t(
"You don't have any profiles yet. Add your first one to begin.",
)}
</AlertDescription>
<Button
className="mt-2"
onClick={() => viewerRef.current?.create()}
>
{t("Add Profile")}
</Button>
</Alert>
)}
</div>
</div>
</main>
<footer className="flex justify-center p-4 flex-shrink-0">
{currentProfile?.support_url && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span>{t("Support")}:</span>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<a
href={currentProfile.support_url}
target="_blank"
rel="noopener noreferrer"
className="transition-colors hover:text-primary"
>
{currentProfile.support_url.includes("t.me") ||
currentProfile.support_url.includes("telegram") ||
currentProfile.support_url.startsWith("tg://") ? (
<Send className="h-5 w-5" />
) : (
<Globe className="h-5 w-5" />
)}
</a>
</TooltipTrigger>
<TooltipContent>
<p>{currentProfile.support_url}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
)}
</footer>
<ProfileViewer ref={viewerRef} onChange={() => mutateProfiles()} />
</div>
); );
}; };
export default MinimalHomePage; export default MinimalHomePage;

View File

@@ -31,7 +31,7 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import {SidebarTrigger} from "@/components/ui/sidebar"; import { SidebarTrigger } from "@/components/ui/sidebar";
const LogPage = () => { const LogPage = () => {
const { t } = useTranslation(); const { t } = useTranslation();

View File

@@ -55,13 +55,7 @@ import {
TooltipTrigger, TooltipTrigger,
} from "@/components/ui/tooltip"; } from "@/components/ui/tooltip";
import { import { PlusCircle, RefreshCw, Zap, FileText, Loader2 } from "lucide-react";
PlusCircle,
RefreshCw,
Zap,
FileText,
Loader2,
} from "lucide-react";
import { SidebarTrigger } from "@/components/ui/sidebar"; import { SidebarTrigger } from "@/components/ui/sidebar";
const ProfilePage = () => { const ProfilePage = () => {

View File

@@ -1,4 +1,10 @@
import React, { useState, useMemo, useRef, useEffect, useCallback } from "react"; import React, {
useState,
useMemo,
useRef,
useEffect,
useCallback,
} from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Virtuoso, VirtuosoHandle } from "react-virtuoso"; import { Virtuoso, VirtuosoHandle } from "react-virtuoso";
import { useAppData } from "@/providers/app-data-provider"; import { useAppData } from "@/providers/app-data-provider";

View File

@@ -401,6 +401,9 @@ export async function getNextUpdateTime(uid: string) {
return invoke<number | null>("get_next_update_time", { uid }); return invoke<number | null>("get_next_update_time", { uid });
} }
export async function createProfileFromShareLink(link: string, templateName: string) { export async function createProfileFromShareLink(
link: string,
templateName: string,
) {
return invoke<void>("create_profile_from_share_link", { link, templateName }); return invoke<void>("create_profile_from_share_link", { link, templateName });
} }

View File

@@ -1,25 +1,29 @@
import { toast } from "sonner"; import { toast } from "sonner";
type NoticeType = 'success' | 'error' | 'info' | 'warning'; type NoticeType = "success" | "error" | "info" | "warning";
export const showNotice = (type: NoticeType, message: string, duration?: number) => { export const showNotice = (
type: NoticeType,
message: string,
duration?: number,
) => {
const options = duration ? { duration } : {}; const options = duration ? { duration } : {};
switch (type) { switch (type) {
case 'success': case "success":
toast.success(message, options); toast.success(message, options);
break; break;
case 'error': case "error":
toast.error(message, options); toast.error(message, options);
break; break;
case 'info': case "info":
toast.info(message, options); toast.info(message, options);
break; break;
case 'warning': case "warning":
toast.warning(message, options); toast.warning(message, options);
break; break;
default: default:
toast(message, options); toast(message, options);
break; break;
} }
}; };