Refactor proxy codebase

This commit is contained in:
Gregory Schier
2026-03-12 08:31:05 -07:00
parent 4968237ece
commit 5e3ef70d93
21 changed files with 437 additions and 408 deletions

View File

@@ -1,4 +1,4 @@
import { useTimedBoolean } from '../hooks/useTimedBoolean';
import { useTimedBoolean } from '@yaakapp-internal/ui';
import { copyToClipboard } from '../lib/copy';
import { showToast } from '../lib/toast';
import type { ButtonProps } from './core/Button';

View File

@@ -1,8 +1,6 @@
import { useTimedBoolean } from '../hooks/useTimedBoolean';
import { IconButton, type IconButtonProps, useTimedBoolean } from '@yaakapp-internal/ui';
import { copyToClipboard } from '../lib/copy';
import { showToast } from '../lib/toast';
import type { IconButtonProps } from './core/IconButton';
import { IconButton } from './core/IconButton';
interface Props extends Omit<IconButtonProps, 'onClick' | 'icon'> {
text: string | (() => Promise<string | null>);

View File

@@ -1,93 +1,37 @@
import classNames from 'classnames';
import type { MouseEvent } from 'react';
import { forwardRef, useCallback } from 'react';
import { useTimedBoolean } from '../../hooks/useTimedBoolean';
import type { ButtonProps } from './Button';
import { Button } from './Button';
import { Icon, LoadingIcon, type IconProps } from '@yaakapp-internal/ui';
import {
IconButton as BaseIconButton,
type IconButtonProps as BaseIconButtonProps,
} from '@yaakapp-internal/ui';
import { forwardRef, useImperativeHandle, useRef } from 'react';
import type { HotkeyAction } from '../../hooks/useHotKey';
import { useFormattedHotkey, useHotKey } from '../../hooks/useHotKey';
export type IconButtonProps = IconProps &
ButtonProps & {
showConfirm?: boolean;
iconClassName?: string;
iconSize?: IconProps['size'];
iconColor?: IconProps['color'];
title: string;
showBadge?: boolean;
};
export type IconButtonProps = BaseIconButtonProps & {
hotkeyAction?: HotkeyAction;
hotkeyLabelOnly?: boolean;
hotkeyPriority?: number;
};
export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(function IconButton(
{
showConfirm,
icon,
color = 'default',
spin,
onClick,
className,
iconClassName,
tabIndex,
size = 'md',
iconSize,
showBadge,
iconColor,
isLoading,
type = 'button',
...props
}: IconButtonProps,
{ hotkeyAction, hotkeyPriority, hotkeyLabelOnly, title, ...props }: IconButtonProps,
ref,
) {
const [confirmed, setConfirmed] = useTimedBoolean();
const handleClick = useCallback(
(e: MouseEvent<HTMLButtonElement>) => {
if (showConfirm) setConfirmed();
onClick?.(e);
},
[onClick, setConfirmed, showConfirm],
const hotkeyTrigger = useFormattedHotkey(hotkeyAction ?? null)?.join('');
const fullTitle = hotkeyTrigger ? `${title ?? ''} ${hotkeyTrigger}`.trim() : title;
const buttonRef = useRef<HTMLButtonElement>(null);
useImperativeHandle<HTMLButtonElement | null, HTMLButtonElement | null>(
ref,
() => buttonRef.current,
);
return (
<Button
ref={ref}
aria-hidden={icon === 'empty'}
disabled={icon === 'empty'}
tabIndex={(tabIndex ?? icon === 'empty') ? -1 : undefined}
onClick={handleClick}
innerClassName="flex items-center justify-center"
size={size}
color={color}
type={type}
className={classNames(
className,
'group/button relative flex-shrink-0',
'!px-0',
size === 'md' && 'w-md',
size === 'sm' && 'w-sm',
size === 'xs' && 'w-xs',
size === '2xs' && 'w-5',
)}
{...props}
>
{showBadge && (
<div className="absolute top-0 right-0 w-1/2 h-1/2 flex items-center justify-center">
<div className="w-2.5 h-2.5 bg-pink-500 rounded-full" />
</div>
)}
{isLoading ? (
<LoadingIcon size={iconSize} className={iconClassName} />
) : (
<Icon
size={iconSize}
icon={confirmed ? 'check' : icon}
spin={spin}
color={iconColor}
className={classNames(
iconClassName,
'group-hover/button:text-text',
confirmed && '!text-success', // Don't use Icon.color here because it won't override the hover color
props.disabled && 'opacity-70',
)}
/>
)}
</Button>
useHotKey(
hotkeyAction ?? null,
() => {
buttonRef.current?.click();
},
{ priority: hotkeyPriority, enable: !hotkeyLabelOnly },
);
return <BaseIconButton ref={buttonRef} title={fullTitle} {...props} />;
});

View File

@@ -1,19 +0,0 @@
import { useRef, useState } from 'react';
import { useUnmount } from 'react-use';
/** Returns a boolean that is true for a given number of milliseconds. */
export function useTimedBoolean(millis = 1500): [boolean, () => void] {
const [value, setValue] = useState(false);
const timeout = useRef<NodeJS.Timeout | null>(null);
const reset = () => timeout.current && clearTimeout(timeout.current);
useUnmount(reset);
const setToTrue = () => {
setValue(true);
reset();
timeout.current = setTimeout(() => setValue(false), millis);
};
return [value, setToTrue];
}

View File

@@ -1,8 +1,8 @@
import type { ActionInvocation } from '@yaakapp-internal/proxy-lib';
import { Button, type ButtonProps } from '@yaakapp-internal/ui';
import { useCallback } from 'react';
import { useActionMetadata } from './hooks';
import { useRpcMutation } from './rpc-hooks';
import { useRpcMutation } from '../hooks/useRpcMutation';
import { useActionMetadata } from '../hooks/useActionMetadata';
type ActionButtonProps = Omit<ButtonProps, 'onClick' | 'children'> & {
action: ActionInvocation;

View File

@@ -0,0 +1,133 @@
import { type } from '@tauri-apps/plugin-os';
import type { ProxyHeader } from '@yaakapp-internal/proxy-lib';
import {
HeaderSize,
IconButton,
Table,
TableBody,
TableCell,
TableHead,
TableHeaderCell,
TableRow,
TruncatedWideTableCell,
} from '@yaakapp-internal/ui';
import classNames from 'classnames';
import { useAtomValue } from 'jotai';
import { useRpcQueryWithEvent } from '../hooks/useRpcQueryWithEvent';
import { ActionButton } from './ActionButton';
import { filteredExchangesAtom, Sidebar } from './Sidebar';
export function ProxyLayout() {
const osType = type();
const exchanges = useAtomValue(filteredExchangesAtom);
const { data: proxyState } = useRpcQueryWithEvent('get_proxy_state', {}, 'proxy_state_changed');
const isRunning = proxyState?.state === 'running';
return (
<div
className={classNames(
'h-full w-full grid grid-rows-[auto_1fr]',
osType === 'linux' && 'border border-border-subtle',
)}
>
<HeaderSize
size="lg"
osType={osType}
hideWindowControls={false}
useNativeTitlebar={false}
interfaceScale={1}
className="x-theme-appHeader bg-surface"
>
<div className="grid grid-cols-[minmax(0,1fr)_auto]">
<div data-tauri-drag-region className="flex items-center text-sm px-2">
Yaak Proxy
</div>
<div>
<IconButton icon="alarm_clock" title="Yo" />
</div>
</div>
</HeaderSize>
<div className="grid grid-cols-[auto_1fr] min-h-0">
<Sidebar />
<main className="overflow-auto p-4">
<div className="flex items-center gap-3 mb-4">
<ActionButton
action={{ scope: 'global', action: 'proxy_start' }}
size="sm"
tone="primary"
disabled={isRunning}
/>
<ActionButton
action={{ scope: 'global', action: 'proxy_stop' }}
size="sm"
variant="border"
disabled={!isRunning}
/>
<span
className={classNames(
'text-xs font-medium',
isRunning ? 'text-success' : 'text-text-subtlest',
)}
>
{isRunning ? 'Running on :9090' : 'Stopped'}
</span>
</div>
{exchanges.length === 0 ? (
<p className="text-text-subtlest text-sm">No traffic yet</p>
) : (
<Table scrollable>
<TableHead>
<TableRow>
<TableHeaderCell>Method</TableHeaderCell>
<TableHeaderCell>URL</TableHeaderCell>
<TableHeaderCell>Status</TableHeaderCell>
<TableHeaderCell>Type</TableHeaderCell>
</TableRow>
</TableHead>
<TableBody>
{exchanges.map((ex) => (
<TableRow key={ex.id}>
<TableCell className="font-mono text-2xs">{ex.method}</TableCell>
<TruncatedWideTableCell className="font-mono text-2xs">
{ex.url}
</TruncatedWideTableCell>
<TableCell>
<StatusBadge status={ex.resStatus} error={ex.error} />
</TableCell>
<TableCell className="text-text-subtle text-xs">
{getContentType(ex.resHeaders)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</main>
</div>
</div>
);
}
function StatusBadge({ status, error }: { status: number | null; error: string | null }) {
if (error) return <span className="text-xs text-danger">Error</span>;
if (status == null) return <span className="text-xs text-text-subtlest"></span>;
const color =
status >= 500
? 'text-danger'
: status >= 400
? 'text-warning'
: status >= 300
? 'text-notice'
: 'text-success';
return <span className={classNames('text-xs font-mono', color)}>{status}</span>;
}
function getContentType(headers: ProxyHeader[]): string {
const ct = headers.find((h) => h.name.toLowerCase() === 'content-type')?.value;
if (ct == null) return '—';
// Strip parameters (e.g. "; charset=utf-8")
return ct.split(';')[0]?.trim() ?? ct;
}

View File

@@ -1,10 +1,10 @@
import type { HttpExchange } from "@yaakapp-internal/proxy-lib";
import { selectedIdsFamily, Tree } from "@yaakapp-internal/ui";
import type { TreeNode } from "@yaakapp-internal/ui";
import { atom, useAtomValue } from "jotai";
import { atomFamily } from "jotai/utils";
import { useCallback } from "react";
import { httpExchangesAtom } from "./store";
import type { HttpExchange } from '@yaakapp-internal/proxy-lib';
import type { TreeNode } from '@yaakapp-internal/ui';
import { selectedIdsFamily, Tree } from '@yaakapp-internal/ui';
import { atom, useAtomValue } from 'jotai';
import { atomFamily } from 'jotai/utils';
import { useCallback } from 'react';
import { httpExchangesAtom } from '../lib/store';
/** A node in the sidebar tree — either a domain or a path segment. */
export type SidebarItem = {
@@ -13,11 +13,9 @@ export type SidebarItem = {
exchangeIds: string[];
};
const collapsedAtom = atomFamily((treeId: string) =>
atom<Record<string, boolean>>({}),
);
const collapsedAtom = atomFamily((_treeId: string) => atom<Record<string, boolean>>({}));
export const SIDEBAR_TREE_ID = "proxy-sidebar";
export const SIDEBAR_TREE_ID = 'proxy-sidebar';
const sidebarTreeAtom = atom<TreeNode<SidebarItem>>((get) => {
const exchanges = get(httpExchangesAtom);
@@ -31,7 +29,7 @@ export const filteredExchangesAtom = atom((get) => {
const selectedIds = get(selectedIdsFamily(SIDEBAR_TREE_ID));
// Nothing selected or root selected → show all
if (selectedIds.length === 0 || selectedIds.includes("root")) {
if (selectedIds.length === 0 || selectedIds.includes('root')) {
return exchanges;
}
@@ -75,7 +73,7 @@ function collectNodes(node: TreeNode<SidebarItem>, map: Map<string, SidebarItem>
* /orders
*/
function buildTree(exchanges: HttpExchange[]): TreeNode<SidebarItem> {
const root: SidebarItem = { id: "root", label: "All Traffic", exchangeIds: [] };
const root: SidebarItem = { id: 'root', label: 'All Traffic', exchangeIds: [] };
const rootNode: TreeNode<SidebarItem> = {
item: root,
parent: null,
@@ -100,7 +98,7 @@ function buildTree(exchanges: HttpExchange[]): TreeNode<SidebarItem> {
try {
const url = new URL(ex.url);
hostname = url.host;
segments = url.pathname.split("/").filter(Boolean);
segments = url.pathname.split('/').filter(Boolean);
} catch {
hostname = ex.url;
segments = [];
@@ -127,7 +125,7 @@ function buildTree(exchanges: HttpExchange[]): TreeNode<SidebarItem> {
let child = current.children.get(seg);
if (!child) {
child = {
id: `path:${hostname}/${pathSoFar.join("/")}`,
id: `path:${hostname}/${pathSoFar.join('/')}`,
label: `/${seg}`,
exchangeIds: [],
children: new Map(),
@@ -157,7 +155,7 @@ function buildTree(exchanges: HttpExchange[]): TreeNode<SidebarItem> {
draggable: false,
};
for (const child of trie.children.values()) {
node.children!.push(toTreeNode(child, node, depth + 1));
node.children?.push(toTreeNode(child, node, depth + 1));
}
return node;
}
@@ -165,21 +163,19 @@ function buildTree(exchanges: HttpExchange[]): TreeNode<SidebarItem> {
// Add a "Domains" folder between root and domain nodes
const allExchangeIds = exchanges.map((ex) => ex.id);
const domainsFolder: TreeNode<SidebarItem> = {
item: { id: "domains", label: "Domains", exchangeIds: allExchangeIds },
item: { id: 'domains', label: 'Domains', exchangeIds: allExchangeIds },
parent: rootNode,
depth: 1,
children: [],
draggable: false,
};
const sortedDomains = [...domainMap.values()].sort((a, b) =>
a.label.localeCompare(b.label),
);
const sortedDomains = [...domainMap.values()].sort((a, b) => a.label.localeCompare(b.label));
for (const domain of sortedDomains) {
domainsFolder.children!.push(toTreeNode(domain, domainsFolder, 2));
domainsFolder.children?.push(toTreeNode(domain, domainsFolder, 2));
}
rootNode.children!.push(domainsFolder);
rootNode.children?.push(domainsFolder);
return rootNode;
}
@@ -189,9 +185,7 @@ function ItemInner({ item }: { item: SidebarItem }) {
return (
<div className="flex items-center gap-2 w-full min-w-0">
<span className="truncate">{item.label}</span>
{count > 0 && (
<span className="text-text-subtlest text-2xs shrink-0">{count}</span>
)}
{count > 0 && <span className="text-text-subtlest text-2xs shrink-0">{count}</span>}
</div>
);
}
@@ -203,7 +197,7 @@ export function Sidebar() {
const getItemKey = useCallback((item: SidebarItem) => item.id, []);
return (
<aside className="x-theme-sidebar h-full w-[250px] min-w-0 overflow-y-auto border-r border-border-subtle">
<aside className="x-theme-sidebar bg-surface h-full w-[250px] min-w-0 overflow-y-auto border-r border-border-subtle">
<div className="pt-2 text-xs">
<Tree
treeId={treeId}

View File

@@ -1,25 +1,9 @@
import { useEffect, useState } from "react";
import type {
ActionInvocation,
ActionMetadata,
} from "@yaakapp-internal/proxy-lib";
import { rpc } from "./rpc";
let cachedActions: [ActionInvocation, ActionMetadata][] | null = null;
/** Fetch and cache all action metadata. */
async function getActions(): Promise<[ActionInvocation, ActionMetadata][]> {
if (!cachedActions) {
const { actions } = await rpc("list_actions", {});
cachedActions = actions;
}
return cachedActions;
}
import type { ActionInvocation, ActionMetadata } from '@yaakapp-internal/proxy-lib';
import { useEffect, useState } from 'react';
import { rpc } from '../lib/rpc';
/** Look up metadata for a specific action invocation. */
export function useActionMetadata(
action: ActionInvocation,
): ActionMetadata | null {
export function useActionMetadata(action: ActionInvocation): ActionMetadata | null {
const [meta, setMeta] = useState<ActionMetadata | null>(null);
useEffect(() => {
@@ -33,3 +17,14 @@ export function useActionMetadata(
return meta;
}
let cachedActions: [ActionInvocation, ActionMetadata][] | null = null;
/** Fetch and cache all action metadata. */
async function getActions(): Promise<[ActionInvocation, ActionMetadata][]> {
if (!cachedActions) {
const { actions } = await rpc('list_actions', {});
cachedActions = actions;
}
return cachedActions;
}

View File

@@ -0,0 +1,15 @@
import type { RpcEventSchema } from '@yaakapp-internal/proxy-lib';
import { useEffect } from 'react';
import { listen } from '../lib/rpc';
/**
* Subscribe to an RPC event. Cleans up automatically on unmount.
*/
export function useRpcEvent<K extends keyof RpcEventSchema>(
event: K & string,
callback: (payload: RpcEventSchema[K]) => void,
) {
useEffect(() => {
return listen(event, callback);
}, [event, callback]);
}

View File

@@ -0,0 +1,18 @@
import { type UseMutationOptions, useMutation } from '@tanstack/react-query';
import type { RpcSchema } from '@yaakapp-internal/proxy-lib';
import { minPromiseMillis } from '@yaakapp-internal/ui';
import type { Req, Res } from '../lib/rpc';
import { rpc } from '../lib/rpc';
/**
* React Query mutation wrapper for RPC commands.
*/
export function useRpcMutation<K extends keyof RpcSchema>(
cmd: K,
opts?: Omit<UseMutationOptions<Res<K>, Error, Req<K>>, 'mutationFn'>,
) {
return useMutation<Res<K>, Error, Req<K>>({
mutationFn: (payload) => minPromiseMillis(rpc(cmd, payload)),
...opts,
});
}

View File

@@ -0,0 +1,20 @@
import { type UseQueryOptions, useQuery } from '@tanstack/react-query';
import type { RpcSchema } from '@yaakapp-internal/proxy-lib';
import type { Req, Res } from '../lib/rpc';
import { rpc } from '../lib/rpc';
/**
* React Query wrapper for RPC commands.
* Automatically caches by [cmd, payload] and supports all useQuery options.
*/
export function useRpcQuery<K extends keyof RpcSchema>(
cmd: K,
payload: Req<K>,
opts?: Omit<UseQueryOptions<Res<K>>, 'queryKey' | 'queryFn'>,
) {
return useQuery<Res<K>>({
queryKey: [cmd, payload],
queryFn: () => rpc(cmd, payload),
...opts,
});
}

View File

@@ -0,0 +1,23 @@
import { type UseQueryOptions, useQueryClient } from '@tanstack/react-query';
import type { RpcEventSchema, RpcSchema } from '@yaakapp-internal/proxy-lib';
import type { Req, Res } from '../lib/rpc';
import { useRpcEvent } from './useRpcEvent';
import { useRpcQuery } from './useRpcQuery';
/**
* Combines useRpcQuery with an event listener that invalidates the query
* whenever the specified event fires, keeping data fresh automatically.
*/
export function useRpcQueryWithEvent<
K extends keyof RpcSchema,
E extends keyof RpcEventSchema & string,
>(cmd: K, payload: Req<K>, event: E, opts?: Omit<UseQueryOptions<Res<K>>, 'queryKey' | 'queryFn'>) {
const queryClient = useQueryClient();
const query = useRpcQuery(cmd, payload, opts);
useRpcEvent(event, () => {
queryClient.invalidateQueries({ queryKey: [cmd, payload] });
});
return query;
}

View File

@@ -1,8 +1,5 @@
import type {
ActionInvocation,
ActionMetadata,
} from "@yaakapp-internal/proxy-lib";
import { rpc } from "./rpc";
import type { ActionInvocation, ActionMetadata } from '@yaakapp-internal/proxy-lib';
import { rpc } from './rpc';
type ActionBinding = {
invocation: ActionInvocation;
@@ -11,20 +8,21 @@ type ActionBinding = {
};
/** Parse a hotkey string like "Ctrl+Shift+P" into its parts. */
function parseHotkey(hotkey: string): ActionBinding["keys"] {
const parts = hotkey.split("+").map((p) => p.trim().toLowerCase());
function parseHotkey(hotkey: string): ActionBinding['keys'] {
const parts = hotkey.split('+').map((p) => p.trim().toLowerCase());
return {
ctrl: parts.includes("ctrl") || parts.includes("control"),
shift: parts.includes("shift"),
alt: parts.includes("alt"),
meta: parts.includes("meta") || parts.includes("cmd") || parts.includes("command"),
key: parts.filter(
(p) => !["ctrl", "control", "shift", "alt", "meta", "cmd", "command"].includes(p),
)[0] ?? "",
ctrl: parts.includes('ctrl') || parts.includes('control'),
shift: parts.includes('shift'),
alt: parts.includes('alt'),
meta: parts.includes('meta') || parts.includes('cmd') || parts.includes('command'),
key:
parts.filter(
(p) => !['ctrl', 'control', 'shift', 'alt', 'meta', 'cmd', 'command'].includes(p),
)[0] ?? '',
};
}
function matchesEvent(binding: ActionBinding["keys"], e: KeyboardEvent): boolean {
function matchesEvent(binding: ActionBinding['keys'], e: KeyboardEvent): boolean {
return (
e.ctrlKey === binding.ctrl &&
e.shiftKey === binding.shift &&
@@ -36,7 +34,7 @@ function matchesEvent(binding: ActionBinding["keys"], e: KeyboardEvent): boolean
/** Fetch all actions from Rust and register a global keydown listener. */
export async function initHotkeys(): Promise<() => void> {
const { actions } = await rpc("list_actions", {});
const { actions } = await rpc('list_actions', {});
const bindings: ActionBinding[] = actions
.filter(
@@ -53,12 +51,12 @@ export async function initHotkeys(): Promise<() => void> {
for (const binding of bindings) {
if (matchesEvent(binding.keys, e)) {
e.preventDefault();
rpc("execute_action", binding.invocation);
rpc('execute_action', binding.invocation);
return;
}
}
}
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}

View File

@@ -0,0 +1,24 @@
import { invoke } from '@tauri-apps/api/core';
import { listen as tauriListen } from '@tauri-apps/api/event';
import type { RpcEventSchema, RpcSchema } from '@yaakapp-internal/proxy-lib';
export type Req<K extends keyof RpcSchema> = RpcSchema[K][0];
export type Res<K extends keyof RpcSchema> = RpcSchema[K][1];
export async function rpc<K extends keyof RpcSchema>(cmd: K, payload: Req<K>): Promise<Res<K>> {
return invoke('rpc', { cmd, payload }) as Promise<Res<K>>;
}
/** Subscribe to a backend event. Returns an unsubscribe function. */
export function listen<K extends keyof RpcEventSchema>(
event: K & string,
callback: (payload: RpcEventSchema[K]) => void,
): () => void {
let unsub: (() => void) | null = null;
tauriListen<RpcEventSchema[K]>(event, (e) => callback(e.payload))
.then((fn) => {
unsub = fn;
})
.catch(console.error);
return () => unsub?.();
}

View File

@@ -11,20 +11,22 @@ import {
type Appearance,
} from "@yaakapp-internal/theme";
setPlatformOnDocument(platformFromUserAgent(navigator.userAgent));
export function initTheme() {
setPlatformOnDocument(platformFromUserAgent(navigator.userAgent));
// Apply a quick initial theme based on CSS media query
let preferredAppearance: Appearance = getCSSAppearance();
applyTheme(preferredAppearance);
// Then subscribe to accurate OS appearance detection and changes
subscribeToPreferredAppearance((a) => {
preferredAppearance = a;
// Apply a quick initial theme based on CSS media query
let preferredAppearance: Appearance = getCSSAppearance();
applyTheme(preferredAppearance);
});
// Show window after initial theme is applied (window starts hidden to prevent flash)
getCurrentWebviewWindow().show().catch(console.error);
// Then subscribe to accurate OS appearance detection and changes
subscribeToPreferredAppearance((a) => {
preferredAppearance = a;
applyTheme(preferredAppearance);
});
// Show window after initial theme is applied (window starts hidden to prevent flash)
getCurrentWebviewWindow().show().catch(console.error);
}
function applyTheme(appearance: Appearance) {
const theme = appearance === "dark" ? defaultDarkTheme : defaultLightTheme;

View File

@@ -1,27 +1,15 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { type } from '@tauri-apps/plugin-os';
import {
HeaderSize,
Table,
TableBody,
TableCell,
TableHead,
TableHeaderCell,
TableRow,
TruncatedWideTableCell,
} from '@yaakapp-internal/ui';
import classNames from 'classnames';
import { createStore, Provider, useAtomValue } from 'jotai';
import { createStore, Provider } from 'jotai';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { ActionButton } from './ActionButton';
import { filteredExchangesAtom, Sidebar } from './Sidebar';
import { ProxyLayout } from './components/ProxyLayout';
import { listen, rpc } from './lib/rpc';
import { initHotkeys } from './lib/hotkeys';
import { applyChange, dataAtom, replaceAll } from './lib/store';
import { initTheme } from './lib/theme';
import './main.css';
import type { ProxyHeader } from '@yaakapp-internal/proxy-lib';
import { initHotkeys } from './hotkeys';
import { listen, rpc } from './rpc';
import { useRpcQueryWithEvent } from './rpc-hooks';
import { applyChange, dataAtom, replaceAll } from './store';
initTheme();
const queryClient = new QueryClient();
const jotaiStore = createStore();
@@ -41,124 +29,11 @@ listen('model_write', (payload) => {
);
});
function App() {
const osType = type();
const exchanges = useAtomValue(filteredExchangesAtom);
const { data: proxyState } = useRpcQueryWithEvent('get_proxy_state', {}, 'proxy_state_changed');
const isRunning = proxyState?.state === 'running';
return (
<div
className={classNames(
'h-full w-full grid grid-rows-[auto_1fr]',
osType === 'linux' && 'border border-border-subtle',
)}
>
<HeaderSize
size="lg"
osType={osType}
hideWindowControls={false}
useNativeTitlebar={false}
interfaceScale={1}
className="x-theme-appHeader bg-surface"
>
<div
data-tauri-drag-region
className="flex items-center px-2 text-sm font-semibold text-text-subtle"
>
Yaak Proxy
</div>
</HeaderSize>
<div className="grid grid-cols-[auto_1fr] min-h-0">
<Sidebar />
<main className="overflow-auto p-4">
<div className="flex items-center gap-3 mb-4">
<ActionButton
action={{ scope: 'global', action: 'proxy_start' }}
size="sm"
tone="primary"
disabled={isRunning}
/>
<ActionButton
action={{ scope: 'global', action: 'proxy_stop' }}
size="sm"
variant="border"
disabled={!isRunning}
/>
<span
className={classNames(
'text-xs font-medium',
isRunning ? 'text-success' : 'text-text-subtlest',
)}
>
{isRunning ? 'Running on :9090' : 'Stopped'}
</span>
</div>
{exchanges.length === 0 ? (
<p className="text-text-subtlest text-sm">No traffic yet</p>
) : (
<Table scrollable>
<TableHead>
<TableRow>
<TableHeaderCell>Method</TableHeaderCell>
<TableHeaderCell>URL</TableHeaderCell>
<TableHeaderCell>Status</TableHeaderCell>
<TableHeaderCell>Type</TableHeaderCell>
</TableRow>
</TableHead>
<TableBody>
{exchanges.map((ex) => (
<TableRow key={ex.id}>
<TableCell className="font-mono text-2xs">{ex.method}</TableCell>
<TruncatedWideTableCell className="font-mono text-2xs">
{ex.url}
</TruncatedWideTableCell>
<TableCell>
<StatusBadge status={ex.resStatus} error={ex.error} />
</TableCell>
<TableCell className="text-text-subtle text-xs">
{getContentType(ex.resHeaders)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</main>
</div>
</div>
);
}
function StatusBadge({ status, error }: { status: number | null; error: string | null }) {
if (error) return <span className="text-xs text-danger">Error</span>;
if (status == null) return <span className="text-xs text-text-subtlest"></span>;
const color =
status >= 500
? 'text-danger'
: status >= 400
? 'text-warning'
: status >= 300
? 'text-notice'
: 'text-success';
return <span className={classNames('text-xs font-mono', color)}>{status}</span>;
}
function getContentType(headers: ProxyHeader[]): string {
const ct = headers.find((h) => h.name.toLowerCase() === 'content-type')?.value;
if (ct == null) return '—';
// Strip parameters (e.g. "; charset=utf-8")
return ct.split(';')[0]?.trim() ?? ct;
}
createRoot(document.getElementById('root') as HTMLElement).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<Provider store={jotaiStore}>
<App />
<ProxyLayout />
</Provider>
</QueryClientProvider>
</StrictMode>,

View File

@@ -1,78 +0,0 @@
import {
useQuery,
useQueryClient,
useMutation,
type UseQueryOptions,
type UseMutationOptions,
} from "@tanstack/react-query";
import { useEffect } from "react";
import type { RpcEventSchema, RpcSchema } from "@yaakapp-internal/proxy-lib";
import { minPromiseMillis } from "@yaakapp-internal/ui";
import { listen, rpc } from "./rpc";
type Req<K extends keyof RpcSchema> = RpcSchema[K][0];
type Res<K extends keyof RpcSchema> = RpcSchema[K][1];
/**
* React Query wrapper for RPC commands.
* Automatically caches by [cmd, payload] and supports all useQuery options.
*/
export function useRpcQuery<K extends keyof RpcSchema>(
cmd: K,
payload: Req<K>,
opts?: Omit<UseQueryOptions<Res<K>>, "queryKey" | "queryFn">,
) {
return useQuery<Res<K>>({
queryKey: [cmd, payload],
queryFn: () => rpc(cmd, payload),
...opts,
});
}
/**
* React Query mutation wrapper for RPC commands.
*/
export function useRpcMutation<K extends keyof RpcSchema>(
cmd: K,
opts?: Omit<UseMutationOptions<Res<K>, Error, Req<K>>, "mutationFn">,
) {
return useMutation<Res<K>, Error, Req<K>>({
mutationFn: (payload) => minPromiseMillis(rpc(cmd, payload)),
...opts,
});
}
/**
* Subscribe to an RPC event. Cleans up automatically on unmount.
*/
export function useRpcEvent<K extends keyof RpcEventSchema>(
event: K & string,
callback: (payload: RpcEventSchema[K]) => void,
) {
useEffect(() => {
return listen(event, callback);
}, [event, callback]);
}
/**
* Combines useRpcQuery with an event listener that invalidates the query
* whenever the specified event fires, keeping data fresh automatically.
*/
export function useRpcQueryWithEvent<
K extends keyof RpcSchema,
E extends keyof RpcEventSchema & string,
>(
cmd: K,
payload: Req<K>,
event: E,
opts?: Omit<UseQueryOptions<Res<K>>, "queryKey" | "queryFn">,
) {
const queryClient = useQueryClient();
const query = useRpcQuery(cmd, payload, opts);
useRpcEvent(event, () => {
queryClient.invalidateQueries({ queryKey: [cmd, payload] });
});
return query;
}

View File

@@ -1,30 +0,0 @@
import { invoke } from "@tauri-apps/api/core";
import { listen as tauriListen } from "@tauri-apps/api/event";
import type {
RpcEventSchema,
RpcSchema,
} from "@yaakapp-internal/proxy-lib";
type Req<K extends keyof RpcSchema> = RpcSchema[K][0];
type Res<K extends keyof RpcSchema> = RpcSchema[K][1];
export async function rpc<K extends keyof RpcSchema>(
cmd: K,
payload: Req<K>,
): Promise<Res<K>> {
return invoke("rpc", { cmd, payload }) as Promise<Res<K>>;
}
/** Subscribe to a backend event. Returns an unsubscribe function. */
export function listen<K extends keyof RpcEventSchema>(
event: K & string,
callback: (payload: RpcEventSchema[K]) => void,
): () => void {
let unsub: (() => void) | null = null;
tauriListen<RpcEventSchema[K]>(event, (e) => callback(e.payload))
.then((fn) => {
unsub = fn;
})
.catch(console.error);
return () => unsub?.();
}