mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-08-14 23:52:10 +02:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23e7229e63 | ||
|
|
1f91cddab9 | ||
|
|
be004425fa | ||
|
|
4f03c5c390 | ||
|
|
cb43f0b9b9 | ||
|
|
68671377fd | ||
|
|
2383f06e71 | ||
|
|
0068be9ffc | ||
|
|
def7d752db | ||
|
|
85aed740a8 | ||
|
|
d3055c64b3 | ||
|
|
912aaeb7a7 |
@@ -70,7 +70,7 @@ jobs:
|
||||
runtime: "wry"
|
||||
targets: "aarch64-pc-windows-msvc"
|
||||
runs-on: ${{ matrix.platform }}
|
||||
timeout-minutes: 40
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- name: Checkout yaakapp/app
|
||||
uses: actions/checkout@v4
|
||||
|
||||
Generated
+4
@@ -11034,6 +11034,7 @@ dependencies = [
|
||||
"yaak-mac-window",
|
||||
"yaak-models",
|
||||
"yaak-plugins",
|
||||
"yaak-rpc",
|
||||
"yaak-sse",
|
||||
"yaak-sync",
|
||||
"yaak-system-appearance",
|
||||
@@ -11201,6 +11202,7 @@ dependencies = [
|
||||
"tokio-stream",
|
||||
"tonic",
|
||||
"tonic-reflection",
|
||||
"ts-rs",
|
||||
"uuid",
|
||||
"yaak-common",
|
||||
"yaak-tls",
|
||||
@@ -11226,6 +11228,7 @@ dependencies = [
|
||||
"reqwest 0.12.20",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"thiserror 2.0.17",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
@@ -11441,6 +11444,7 @@ dependencies = [
|
||||
"thiserror 2.0.17",
|
||||
"url",
|
||||
"yaak-models",
|
||||
"yasna",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { HttpRequest } from "@yaakapp-internal/models";
|
||||
import { patchModelById } from "@yaakapp-internal/models";
|
||||
import { activeWorkspaceIdAtom } from "../hooks/useActiveWorkspace";
|
||||
import { createFastMutation } from "../hooks/useFastMutation";
|
||||
import { wasUpdatedExternally } from "../hooks/useRequestUpdateKey";
|
||||
import { createRequestAndNavigate } from "../lib/createRequestAndNavigate";
|
||||
import { jotaiStore } from "../lib/jotai";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { showToast } from "../lib/toast";
|
||||
|
||||
export function looksLikeCurl(text: string) {
|
||||
return text.trim().startsWith("curl ");
|
||||
}
|
||||
|
||||
export const importCurl = createFastMutation<
|
||||
void,
|
||||
string,
|
||||
{ overwriteRequestId?: string; command: string }
|
||||
>({
|
||||
mutationKey: ["import_curl"],
|
||||
mutationFn: async ({ overwriteRequestId, command }) => {
|
||||
const workspaceId = jotaiStore.get(activeWorkspaceIdAtom);
|
||||
const importedRequest: HttpRequest = await rpc("cmd_curl_to_request", {
|
||||
command,
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
let verb: string;
|
||||
if (overwriteRequestId == null) {
|
||||
verb = "Created";
|
||||
await createRequestAndNavigate(importedRequest);
|
||||
} else {
|
||||
verb = "Updated";
|
||||
await patchModelById(importedRequest.model, overwriteRequestId, (r: HttpRequest) => ({
|
||||
...importedRequest,
|
||||
id: r.id,
|
||||
createdAt: r.createdAt,
|
||||
workspaceId: r.workspaceId,
|
||||
folderId: r.folderId,
|
||||
name: r.name,
|
||||
sortPriority: r.sortPriority,
|
||||
}));
|
||||
|
||||
setTimeout(() => wasUpdatedExternally(overwriteRequestId), 100);
|
||||
}
|
||||
|
||||
showToast({
|
||||
color: "success",
|
||||
message: `${verb} request from Curl`,
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { activeWorkspaceIdAtom } from "../hooks/useActiveWorkspace";
|
||||
import { createFastMutation } from "../hooks/useFastMutation";
|
||||
import { jotaiStore } from "../lib/jotai";
|
||||
import { router } from "../lib/router";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
|
||||
// Allow tab with optional subtab (e.g., "plugins:installed")
|
||||
type SettingsTabWithSubtab = SettingsTab | `${SettingsTab}:${string}` | null;
|
||||
@@ -20,7 +20,7 @@ export const openSettings = createFastMutation<void, string, SettingsTabWithSubt
|
||||
search: { tab: (tab ?? undefined) as SettingsTab | undefined },
|
||||
});
|
||||
|
||||
await invokeCmd("cmd_new_child_window", {
|
||||
await rpc("cmd_new_child_window", {
|
||||
url: location.href,
|
||||
label: "settings",
|
||||
title: "Yaak Settings",
|
||||
|
||||
@@ -3,7 +3,7 @@ import { getRecentCookieJars } from "../hooks/useRecentCookieJars";
|
||||
import { getRecentEnvironments } from "../hooks/useRecentEnvironments";
|
||||
import { getRecentRequests } from "../hooks/useRecentRequests";
|
||||
import { router } from "../lib/router";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
|
||||
export const switchWorkspace = createFastMutation<
|
||||
void,
|
||||
@@ -30,7 +30,7 @@ export const switchWorkspace = createFastMutation<
|
||||
params: { workspaceId },
|
||||
search,
|
||||
});
|
||||
await invokeCmd<void>("cmd_new_main_window", { url: location.href });
|
||||
await rpc<void>("cmd_new_main_window", { url: location.href });
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { gitClone } from "@yaakapp-internal/git";
|
||||
import { Banner, VStack } from "@yaakapp-internal/ui";
|
||||
import { useState } from "react";
|
||||
@@ -11,6 +10,7 @@ import { Checkbox } from "./core/Checkbox";
|
||||
import { IconButton } from "./core/IconButton";
|
||||
import { PlainInput } from "./core/PlainInput";
|
||||
import { promptCredentials } from "./git/credentials";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
interface Props {
|
||||
hide: () => void;
|
||||
@@ -38,7 +38,7 @@ export function CloneGitRepositoryDialog({ hide }: Props) {
|
||||
hasSubdirectory && subdirectory ? `${directory}${sep}${subdirectory}` : directory;
|
||||
|
||||
const handleSelectDirectory = async () => {
|
||||
const dir = await open({
|
||||
const dir = await platform.dialog.open({
|
||||
title: "Select Directory",
|
||||
directory: true,
|
||||
multiple: false,
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { openUrl } from "@tauri-apps/plugin-opener";
|
||||
import type { LicenseCheckStatus } from "@yaakapp-internal/license";
|
||||
import { checkLicense } from "@yaakapp-internal/license";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useKeyValue } from "../hooks/useKeyValue";
|
||||
import { appInfo } from "../lib/appInfo";
|
||||
import { pricingUrl } from "../lib/pricingUrl";
|
||||
import { DismissibleBanner } from "./core/DismissibleBanner";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
const COMMERCIAL_USE_SNOOZE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
const COMMERCIAL_USE_BANNER_MESSAGE =
|
||||
@@ -95,7 +94,7 @@ async function shouldShowCommercialUsePrompt(): Promise<boolean> {
|
||||
}
|
||||
|
||||
try {
|
||||
const license = await invoke<LicenseCheckStatus>("plugin:yaak-license|check");
|
||||
const license = await checkLicense();
|
||||
return license.status === "personal_use";
|
||||
} catch (err) {
|
||||
console.log("Failed to check license before commercial-use prompt", err);
|
||||
@@ -104,7 +103,7 @@ async function shouldShowCommercialUsePrompt(): Promise<boolean> {
|
||||
}
|
||||
|
||||
async function openCommercialUsePricing(source: string): Promise<void> {
|
||||
await openUrl(pricingUrl(`app.commercial-use.${source}`)).catch(console.error);
|
||||
await platform.openUrl(pricingUrl(`app.commercial-use.${source}`)).catch(console.error);
|
||||
}
|
||||
|
||||
function isSnoozed(value: string | null, ms: number): boolean {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { VStack } from "@yaakapp-internal/ui";
|
||||
import { useState } from "react";
|
||||
import { router } from "../lib/router";
|
||||
import { setupOrConfigureEncryption } from "../lib/setupOrConfigureEncryption";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { showErrorToast } from "../lib/toast";
|
||||
import { Button } from "./core/Button";
|
||||
import { Checkbox } from "./core/Checkbox";
|
||||
@@ -39,7 +39,7 @@ export function CreateWorkspaceDialog({ hide }: Props) {
|
||||
|
||||
// Do getWorkspaceMeta instead of naively creating one because it might have
|
||||
// been created already when the store refreshes the workspace meta after
|
||||
const workspaceMeta = await invokeCmd<WorkspaceMeta>("cmd_get_workspace_meta", {
|
||||
const workspaceMeta = await rpc<WorkspaceMeta>("cmd_get_workspace_meta", {
|
||||
workspaceId,
|
||||
});
|
||||
await updateModel({
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { save } from "@tauri-apps/plugin-dialog";
|
||||
import type { Workspace } from "@yaakapp-internal/models";
|
||||
import { workspacesAtom } from "@yaakapp-internal/models";
|
||||
import { HStack, VStack } from "@yaakapp-internal/ui";
|
||||
@@ -7,12 +6,13 @@ import { useCallback, useMemo, useState } from "react";
|
||||
import slugify from "slugify";
|
||||
import { activeWorkspaceAtom } from "../hooks/useActiveWorkspace";
|
||||
import { pluralizeCount } from "../lib/pluralize";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { CommercialUseBanner } from "./CommercialUseBanner";
|
||||
import { Button } from "./core/Button";
|
||||
import { Checkbox } from "./core/Checkbox";
|
||||
import { DetailsBanner } from "./core/DetailsBanner";
|
||||
import { Link } from "./core/Link";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
interface Props {
|
||||
onHide: () => void;
|
||||
@@ -65,7 +65,7 @@ function ExportDataDialogContent({
|
||||
const ids = Object.keys(selectedWorkspaces).filter((k) => selectedWorkspaces[k]);
|
||||
const workspace = ids.length === 1 ? workspaces.find((w) => w.id === ids[0]) : undefined;
|
||||
const slug = workspace ? slugify(workspace.name, { lower: true }) : "workspaces";
|
||||
const exportPath = await save({
|
||||
const exportPath = await platform.dialog.save({
|
||||
title: "Export Data",
|
||||
defaultPath: `yaak.${slug}.json`,
|
||||
});
|
||||
@@ -73,7 +73,7 @@ function ExportDataDialogContent({
|
||||
return;
|
||||
}
|
||||
|
||||
await invokeCmd("cmd_export_data", {
|
||||
await rpc("cmd_export_data", {
|
||||
workspaceIds: ids,
|
||||
exportPath,
|
||||
includePrivateEnvironments: includePrivateEnvironments,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { HStack, VStack } from "@yaakapp-internal/ui";
|
||||
import { useRef, useState } from "react";
|
||||
import type { FeedbackFeature } from "../lib/featureFeedbackConstants";
|
||||
import { FEEDBACK_FEATURES } from "../lib/featureFeedbackConstants";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { hideToastById, showToast } from "../lib/toast";
|
||||
import { Button } from "./core/Button";
|
||||
import { Input } from "./core/Input";
|
||||
@@ -31,7 +31,7 @@ export function FeedbackToast({ feature, onDone }: Props) {
|
||||
onDone();
|
||||
|
||||
// Fire-and-forget; failures are intentionally ignored
|
||||
invokeCmd("cmd_send_feedback", { feature, text: trimmedText }).catch(() => {});
|
||||
rpc("cmd_send_feedback", { feature, text: trimmedText }).catch(() => {});
|
||||
showToast({
|
||||
id: `feature-feedback-${feature}`,
|
||||
timeout: 3000,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import type { GrpcRequest } from "@yaakapp-internal/models";
|
||||
import { Banner, HStack, Icon, InlineCode, VStack } from "@yaakapp-internal/ui";
|
||||
import { useActiveRequest } from "../hooks/useActiveRequest";
|
||||
@@ -8,6 +7,7 @@ import { pluralizeCount } from "../lib/pluralize";
|
||||
import { Button } from "./core/Button";
|
||||
import { IconButton } from "./core/IconButton";
|
||||
import { Link } from "./core/Link";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
interface Props {
|
||||
onDone: () => void;
|
||||
@@ -45,7 +45,7 @@ function GrpcProtoSelectionDialogWithRequest({ request }: Props & { request: Grp
|
||||
color="primary"
|
||||
variant="border"
|
||||
onClick={async () => {
|
||||
const selected = await open({
|
||||
const selected = await platform.dialog.open({
|
||||
title: "Select Proto Files",
|
||||
multiple: true,
|
||||
filters: [{ name: "Proto Files", extensions: ["proto"] }],
|
||||
@@ -63,7 +63,7 @@ function GrpcProtoSelectionDialogWithRequest({ request }: Props & { request: Grp
|
||||
variant="border"
|
||||
color="primary"
|
||||
onClick={async () => {
|
||||
const selected = await open({
|
||||
const selected = await platform.dialog.open({
|
||||
title: "Select Proto Directory",
|
||||
directory: true,
|
||||
});
|
||||
|
||||
@@ -5,11 +5,11 @@ import classNames from "classnames";
|
||||
import { atom, useAtomValue } from "jotai";
|
||||
import type { CSSProperties } from "react";
|
||||
import { lazy, Suspense, useCallback, useMemo, useRef, useState } from "react";
|
||||
import { importCurl, looksLikeCurl } from "../commands/importCurl";
|
||||
import { allRequestUrlsAtom } from "../hooks/useAllRequests";
|
||||
import { useAuthTab } from "../hooks/useAuthTab";
|
||||
import { useCancelHttpResponse } from "../hooks/useCancelHttpResponse";
|
||||
import { useHeadersTab } from "../hooks/useHeadersTab";
|
||||
import { useImportCurl } from "../hooks/useImportCurl";
|
||||
import { useInheritedHeaders } from "../hooks/useInheritedHeaders";
|
||||
import { usePinnedHttpResponse } from "../hooks/usePinnedHttpResponse";
|
||||
import { useRequestEditor, useRequestEditorEvent } from "../hooks/useRequestEditor";
|
||||
@@ -278,7 +278,6 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
||||
const { activeResponse } = usePinnedHttpResponse(activeRequestId);
|
||||
const { mutate: cancelResponse } = useCancelHttpResponse(activeResponse?.id ?? null);
|
||||
const updateKey = useRequestUpdateKey(activeRequestId);
|
||||
const { mutate: importCurl } = useImportCurl();
|
||||
|
||||
const handleBodyChange = useCallback(
|
||||
(body: HttpRequest["body"]) => patchModelDebounced(activeRequest, { body }),
|
||||
@@ -299,8 +298,8 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
||||
|
||||
const handlePaste = useCallback(
|
||||
async (e: ClipboardEvent, text: string) => {
|
||||
if (text.startsWith("curl ")) {
|
||||
importCurl({ overwriteRequestId: activeRequestId, command: text });
|
||||
if (looksLikeCurl(text)) {
|
||||
importCurl.mutate({ overwriteRequestId: activeRequestId, command: text });
|
||||
} else {
|
||||
const patch = prepareImportQuerystring(text);
|
||||
if (patch != null) {
|
||||
@@ -322,7 +321,7 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
||||
}
|
||||
}
|
||||
},
|
||||
[activeRequest, activeRequestId, forceParamsRefresh, forceUrlRefresh, importCurl],
|
||||
[activeRequest, activeRequestId, forceParamsRefresh, forceUrlRefresh],
|
||||
);
|
||||
const handleSend = useCallback(
|
||||
() => sendRequest(activeRequest.id ?? null),
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { platform, useCapability } from "@yaakapp-internal/platform";
|
||||
import { Icon } from "@yaakapp-internal/ui";
|
||||
import * as m from "motion/react-m";
|
||||
import { useEffect, useState } from "react";
|
||||
import { importCurl, looksLikeCurl } from "../commands/importCurl";
|
||||
import { useWindowFocus } from "../hooks/useWindowFocus";
|
||||
import { showToast } from "../lib/toast";
|
||||
import { Button } from "./core/Button";
|
||||
|
||||
/**
|
||||
* Offers to create a request from a Curl command on the clipboard. A host that can read
|
||||
* the clipboard on its own offers it whenever the window is focused; one that would have
|
||||
* to prompt for permission first waits for the user to paste instead.
|
||||
*/
|
||||
export function ImportCurl() {
|
||||
return useCapability("clipboardRead") ? <ImportCurlButton /> : <ImportCurlOnPaste />;
|
||||
}
|
||||
|
||||
function ImportCurlButton() {
|
||||
const focused = useWindowFocus();
|
||||
const [clipboardText, setClipboardText] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
// oxlint-disable-next-line react-hooks/exhaustive-deps -- none
|
||||
useEffect(() => {
|
||||
void platform.clipboard.readText().then(setClipboardText);
|
||||
}, [focused]);
|
||||
|
||||
if (!looksLikeCurl(clipboardText)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<m.div
|
||||
initial={{ opacity: 0, scale: 0 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ delay: 0.5 }}
|
||||
>
|
||||
<Button
|
||||
size="2xs"
|
||||
variant="border"
|
||||
color="success"
|
||||
className="rounded-full"
|
||||
rightSlot={<Icon icon="import" size="sm" />}
|
||||
isLoading={isLoading}
|
||||
title="Import Curl command from clipboard"
|
||||
onClick={async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await importCurl.mutateAsync({ command: clipboardText });
|
||||
setClipboardText(""); // Hide the button until the clipboard changes
|
||||
} catch (e) {
|
||||
console.log("Failed to import curl", e);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Import Curl
|
||||
</Button>
|
||||
</m.div>
|
||||
);
|
||||
}
|
||||
|
||||
function ImportCurlOnPaste() {
|
||||
useEffect(() => {
|
||||
const handlePaste = (e: ClipboardEvent) => {
|
||||
const command = e.clipboardData?.getData("text/plain") ?? "";
|
||||
if (!looksLikeCurl(command)) return;
|
||||
|
||||
// Editable targets keep the text as text. The URL editor imports it itself.
|
||||
if (isEditable(e.target)) return;
|
||||
|
||||
showToast({
|
||||
id: "curl-paste",
|
||||
color: "success",
|
||||
message: (
|
||||
<div>
|
||||
<h2 className="font-semibold">Curl command detected</h2>
|
||||
<p className="text-text-subtle text-sm">Create a request from the pasted command?</p>
|
||||
</div>
|
||||
),
|
||||
action: ({ hide }) => (
|
||||
<Button
|
||||
size="xs"
|
||||
color="success"
|
||||
className="mr-auto min-w-20"
|
||||
rightSlot={<Icon icon="import" size="sm" />}
|
||||
onClick={() => {
|
||||
hide();
|
||||
importCurl.mutate({ command });
|
||||
}}
|
||||
>
|
||||
Create Request
|
||||
</Button>
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
document.addEventListener("paste", handlePaste);
|
||||
return () => document.removeEventListener("paste", handlePaste);
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function isEditable(target: EventTarget | null) {
|
||||
if (!(target instanceof HTMLElement)) return false;
|
||||
if (target.isContentEditable) return true;
|
||||
if (target.closest(".cm-editor") != null) return true;
|
||||
return ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName);
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
import { clear, readText } from "@tauri-apps/plugin-clipboard-manager";
|
||||
import * as m from "motion/react-m";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useImportCurl } from "../hooks/useImportCurl";
|
||||
import { useWindowFocus } from "../hooks/useWindowFocus";
|
||||
import { Button } from "./core/Button";
|
||||
import { Icon } from "@yaakapp-internal/ui";
|
||||
|
||||
export function ImportCurlButton() {
|
||||
const focused = useWindowFocus();
|
||||
const [clipboardText, setClipboardText] = useState("");
|
||||
|
||||
const importCurl = useImportCurl();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
// oxlint-disable-next-line react-hooks/exhaustive-deps -- none
|
||||
useEffect(() => {
|
||||
void readText().then(setClipboardText);
|
||||
}, [focused]);
|
||||
|
||||
if (!clipboardText?.trim().startsWith("curl ")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<m.div
|
||||
initial={{ opacity: 0, scale: 0 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ delay: 0.5 }}
|
||||
>
|
||||
<Button
|
||||
size="2xs"
|
||||
variant="border"
|
||||
color="success"
|
||||
className="rounded-full"
|
||||
rightSlot={<Icon icon="import" size="sm" />}
|
||||
isLoading={isLoading}
|
||||
title="Import Curl command from clipboard"
|
||||
onClick={async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await importCurl.mutateAsync({ command: clipboardText });
|
||||
await clear(); // Clear the clipboard so the button goes away
|
||||
setClipboardText("");
|
||||
} catch (e) {
|
||||
console.log("Failed to import curl", e);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Import Curl
|
||||
</Button>
|
||||
</m.div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { openUrl } from "@tauri-apps/plugin-opener";
|
||||
import type { LicenseCheckStatus } from "@yaakapp-internal/license";
|
||||
import { useLicense } from "@yaakapp-internal/license";
|
||||
import { settingsAtom } from "@yaakapp-internal/models";
|
||||
@@ -14,6 +13,7 @@ import type { ButtonProps } from "./core/Button";
|
||||
import { Dropdown, type DropdownItem } from "./core/Dropdown";
|
||||
import { Icon } from "@yaakapp-internal/ui";
|
||||
import { PillButton } from "./core/PillButton";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
const dismissedAtom = atomWithKVStorage<string | null>("dismissed_license_expired", null);
|
||||
|
||||
@@ -52,7 +52,7 @@ function getDetail(
|
||||
leftSlot: <Icon icon="gift" />,
|
||||
rightSlot: <Icon icon="external_link" size="sm" className="opacity-disabled" />,
|
||||
hidden: data.data.changes === 0 || data.data.changesUrl == null,
|
||||
onSelect: () => openUrl(data.data.changesUrl ?? ""),
|
||||
onSelect: () => platform.openUrl(data.data.changesUrl ?? ""),
|
||||
},
|
||||
{
|
||||
type: "separator",
|
||||
@@ -63,7 +63,7 @@ function getDetail(
|
||||
leftSlot: <Icon icon="refresh" />,
|
||||
rightSlot: <Icon icon="external_link" size="sm" className="opacity-disabled" />,
|
||||
hidden: data.data.changesUrl == null,
|
||||
onSelect: () => openUrl(data.data.billingUrl),
|
||||
onSelect: () => platform.openUrl(data.data.billingUrl),
|
||||
},
|
||||
{
|
||||
label: "Enter License Key",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import { resolveResource } from "@tauri-apps/api/path";
|
||||
import classNames from "classnames";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
interface Props {
|
||||
src: string;
|
||||
@@ -12,8 +11,8 @@ export function LocalImage({ src: srcPath, className }: Props) {
|
||||
const src = useQuery({
|
||||
queryKey: ["local-image", srcPath],
|
||||
queryFn: async () => {
|
||||
const p = await resolveResource(srcPath);
|
||||
return convertFileSrc(p);
|
||||
const p = await platform.files.resolveResource(srcPath);
|
||||
return platform.files.url(p);
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { openUrl } from "@tauri-apps/plugin-opener";
|
||||
import type { HttpResponse } from "@yaakapp-internal/models";
|
||||
import { format, formatDistanceToNowStrict } from "date-fns";
|
||||
import { useMemo } from "react";
|
||||
@@ -6,6 +5,7 @@ import { CountBadge } from "./core/CountBadge";
|
||||
import { DetailsBanner } from "./core/DetailsBanner";
|
||||
import { IconButton } from "./core/IconButton";
|
||||
import { KeyValueRow, KeyValueRows } from "./core/KeyValueRow";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
interface Props {
|
||||
response: HttpResponse;
|
||||
@@ -45,7 +45,7 @@ export function ResponseHeaders({ response }: Props) {
|
||||
iconSize="sm"
|
||||
className="inline-block w-auto h-auto! opacity-50 hover:opacity-100"
|
||||
icon="external_link"
|
||||
onClick={() => openUrl(response.url)}
|
||||
onClick={() => platform.openUrl(response.url)}
|
||||
title="Open in browser"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { openUrl } from "@tauri-apps/plugin-opener";
|
||||
import type { HttpResponse } from "@yaakapp-internal/models";
|
||||
import { IconButton } from "./core/IconButton";
|
||||
import { KeyValueRow, KeyValueRows } from "./core/KeyValueRow";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
interface Props {
|
||||
response: HttpResponse;
|
||||
@@ -26,7 +26,7 @@ export function ResponseInfo({ response }: Props) {
|
||||
iconSize="sm"
|
||||
className="inline-block w-auto ml-1 h-auto! opacity-50 hover:opacity-100"
|
||||
icon="external_link"
|
||||
onClick={() => openUrl(response.url)}
|
||||
onClick={() => platform.openUrl(response.url)}
|
||||
title="Open in browser"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { HStack } from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import mime from "mime";
|
||||
@@ -41,7 +40,7 @@ export function SelectFile({
|
||||
...props
|
||||
}: Props) {
|
||||
const handleClick = async () => {
|
||||
const filePath = await open({
|
||||
const filePath = await platform.dialog.open({
|
||||
title: directory ? "Select Folder" : "Select File",
|
||||
multiple: false,
|
||||
directory,
|
||||
@@ -64,32 +63,21 @@ export function SelectFile({
|
||||
// NOTE: This doesn't work for Windows since native drag-n-drop can't work at the same tmie
|
||||
// as browser drag-n-drop.
|
||||
useEffect(() => {
|
||||
let unlisten: (() => void) | undefined;
|
||||
const setup = async () => {
|
||||
const webview = getCurrentWebviewWindow();
|
||||
unlisten = await webview.onDragDropEvent((event) => {
|
||||
if (event.payload.type === "over") {
|
||||
const p = event.payload.position;
|
||||
const r = ref.current?.getBoundingClientRect();
|
||||
if (r == null) return;
|
||||
const isOver = p.x >= r.left && p.x <= r.right && p.y >= r.top && p.y <= r.bottom;
|
||||
console.log("IS OVER", isOver);
|
||||
setIsHovering(isOver);
|
||||
} else if (event.payload.type === "drop" && isHovering) {
|
||||
console.log("User dropped", event.payload.paths);
|
||||
const p = event.payload.paths[0];
|
||||
if (p) onChange({ filePath: p, contentType: null });
|
||||
setIsHovering(false);
|
||||
} else {
|
||||
console.log("File drop cancelled");
|
||||
setIsHovering(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
setup().catch(console.error);
|
||||
return () => {
|
||||
if (unlisten) unlisten();
|
||||
};
|
||||
return platform.window.onDragDrop((event) => {
|
||||
if (event.type === "over") {
|
||||
const p = event.position;
|
||||
const r = ref.current?.getBoundingClientRect();
|
||||
if (r == null) return;
|
||||
const isOver = p.x >= r.left && p.x <= r.right && p.y >= r.top && p.y <= r.bottom;
|
||||
setIsHovering(isOver);
|
||||
} else if (event.type === "drop" && isHovering) {
|
||||
const p = event.paths[0];
|
||||
if (p) onChange({ filePath: p, contentType: null });
|
||||
setIsHovering(false);
|
||||
} else {
|
||||
setIsHovering(false);
|
||||
}
|
||||
});
|
||||
}, [isHovering, onChange]);
|
||||
|
||||
const filePathWithNameOverride = nameOverride ? `${filePath} (${nameOverride})` : filePath;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useSearch } from "@tanstack/react-router";
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { type } from "@tauri-apps/plugin-os";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { useLicense } from "@yaakapp-internal/license";
|
||||
import { pluginsAtom, settingsAtom } from "@yaakapp-internal/models";
|
||||
import { HeaderSize, HStack, Icon } from "@yaakapp-internal/ui";
|
||||
@@ -60,7 +59,7 @@ export default function Settings({ hide }: Props) {
|
||||
hide();
|
||||
} else {
|
||||
// It's being shown in a window, so close the window
|
||||
await getCurrentWebviewWindow().close();
|
||||
await platform.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -75,7 +74,7 @@ export default function Settings({ hide }: Props) {
|
||||
onlyXWindowControl
|
||||
size="md"
|
||||
className="x-theme-appHeader bg-surface text-text-subtle flex items-center justify-center border-b border-border-subtle text-sm font-semibold"
|
||||
osType={type()}
|
||||
osType={platform.osType()}
|
||||
hideWindowControls={settings.hideWindowControls}
|
||||
useNativeTitlebar={settings.useNativeTitlebar}
|
||||
interfaceScale={settings.interfaceScale}
|
||||
@@ -85,7 +84,7 @@ export default function Settings({ hide }: Props) {
|
||||
justifyContent="center"
|
||||
className="w-full h-full grid grid-cols-[1fr_auto] pointer-events-none"
|
||||
>
|
||||
<div className={classNames(type() === "macos" ? "text-center" : "pl-2")}>Settings</div>
|
||||
<div className={classNames(platform.osType() === "macos" ? "text-center" : "pl-2")}>Settings</div>
|
||||
</HStack>
|
||||
</HeaderSize>
|
||||
)}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { revealItemInDir } from "@tauri-apps/plugin-opener";
|
||||
import { patchModel, settingsAtom } from "@yaakapp-internal/models";
|
||||
import { Heading, VStack } from "@yaakapp-internal/ui";
|
||||
import { useAtomValue } from "jotai";
|
||||
@@ -9,6 +8,7 @@ import { CargoFeature } from "../CargoFeature";
|
||||
import { CommercialUseBanner } from "../CommercialUseBanner";
|
||||
import { DismissibleBanner } from "../core/DismissibleBanner";
|
||||
import { IconButton } from "../core/IconButton";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import {
|
||||
ModelSettingRowBoolean,
|
||||
ModelSettingSelectControl,
|
||||
@@ -152,7 +152,7 @@ export function SettingsGeneral() {
|
||||
{
|
||||
title: revealInFinderText,
|
||||
icon: "folder_open",
|
||||
onClick: () => revealItemInDir(appInfo.appDataDir),
|
||||
onClick: () => platform.revealItemInDir(appInfo.appDataDir),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
@@ -168,7 +168,7 @@ export function SettingsGeneral() {
|
||||
{
|
||||
title: revealInFinderText,
|
||||
icon: "folder_open",
|
||||
onClick: () => revealItemInDir(appInfo.appLogDir),
|
||||
onClick: () => platform.revealItemInDir(appInfo.appLogDir),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type } from "@tauri-apps/plugin-os";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { useFonts } from "@yaakapp-internal/fonts";
|
||||
import { useLicense } from "@yaakapp-internal/license";
|
||||
import type { EditorKeymap, Settings } from "@yaakapp-internal/models";
|
||||
@@ -9,7 +9,7 @@ import { useState } from "react";
|
||||
import { activeWorkspaceAtom } from "../../hooks/useActiveWorkspace";
|
||||
import { showConfirm } from "../../lib/confirm";
|
||||
import { pricingUrl } from "../../lib/pricingUrl";
|
||||
import { invokeCmd } from "../../lib/tauri";
|
||||
import { rpc } from "../../lib/rpc";
|
||||
import { CargoFeature } from "../CargoFeature";
|
||||
import { Button } from "../core/Button";
|
||||
import { Checkbox } from "../core/Checkbox";
|
||||
@@ -176,7 +176,7 @@ export function SettingsInterface() {
|
||||
|
||||
<SettingsSection title="Window">
|
||||
<NativeTitlebarSetting settings={settings} />
|
||||
{type() !== "macos" && (
|
||||
{platform.osType() !== "macos" && (
|
||||
<ModelSettingRowBoolean
|
||||
model={settings}
|
||||
modelKey="hideWindowControls"
|
||||
@@ -216,7 +216,7 @@ function NativeTitlebarSetting({ settings }: { settings: Settings }) {
|
||||
size="xs"
|
||||
onClick={async () => {
|
||||
await patchModel(settings, { useNativeTitlebar: nativeTitlebar });
|
||||
await invokeCmd("cmd_restart");
|
||||
await rpc("cmd_restart");
|
||||
}}
|
||||
>
|
||||
Apply and Restart
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { openUrl } from "@tauri-apps/plugin-opener";
|
||||
import { useLicense } from "@yaakapp-internal/license";
|
||||
import { Banner, HStack, Icon, VStack } from "@yaakapp-internal/ui";
|
||||
import { differenceInDays } from "date-fns";
|
||||
@@ -12,6 +11,7 @@ import { Button } from "../core/Button";
|
||||
import { Link } from "../core/Link";
|
||||
import { PlainInput } from "../core/PlainInput";
|
||||
import { Separator } from "../core/Separator";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
export function SettingsLicense() {
|
||||
return (
|
||||
@@ -135,7 +135,7 @@ function SettingsLicenseCmp() {
|
||||
<Button
|
||||
color="secondary"
|
||||
size="sm"
|
||||
onClick={() => openUrl("https://yaak.app/dashboard?intent=app.license.support")}
|
||||
onClick={() => platform.openUrl("https://yaak.app/dashboard?intent=app.license.support")}
|
||||
rightSlot={<Icon icon="external_link" />}
|
||||
>
|
||||
Direct Support
|
||||
@@ -151,7 +151,7 @@ function SettingsLicenseCmp() {
|
||||
color="primary"
|
||||
rightSlot={<Icon icon="external_link" />}
|
||||
onClick={() =>
|
||||
openUrl(pricingUrl(`app.license.purchase.${check.data?.status ?? "unknown"}`))
|
||||
platform.openUrl(pricingUrl(`app.license.purchase.${check.data?.status ?? "unknown"}`))
|
||||
}
|
||||
>
|
||||
Purchase License
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { openUrl } from "@tauri-apps/plugin-opener";
|
||||
import type { Plugin } from "@yaakapp-internal/models";
|
||||
import { patchModel, pluginsAtom } from "@yaakapp-internal/models";
|
||||
import type { PluginVersion } from "@yaakapp-internal/plugins";
|
||||
@@ -39,6 +38,7 @@ import { PlainInput } from "../core/PlainInput";
|
||||
import { TabContent, Tabs } from "../core/Tabs/Tabs";
|
||||
import { EmptyStateText } from "../EmptyStateText";
|
||||
import { SelectFile } from "../SelectFile";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
interface SettingsPluginsProps {
|
||||
defaultSubtab?: string;
|
||||
@@ -113,7 +113,7 @@ export function SettingsPlugins({ defaultSubtab }: SettingsPluginsProps) {
|
||||
icon="help"
|
||||
title="View documentation"
|
||||
onClick={() =>
|
||||
openUrl("https://yaak.app/docs/plugin-development/plugins-quick-start")
|
||||
platform.openUrl("https://yaak.app/docs/plugin-development/plugins-quick-start")
|
||||
}
|
||||
/>
|
||||
</HStack>
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { openUrl } from "@tauri-apps/plugin-opener";
|
||||
import { useLicense } from "@yaakapp-internal/license";
|
||||
import { useRef } from "react";
|
||||
import { openSettings } from "../commands/openSettings";
|
||||
@@ -13,6 +12,7 @@ import { Dropdown } from "./core/Dropdown";
|
||||
import { Icon } from "@yaakapp-internal/ui";
|
||||
import { IconButton } from "./core/IconButton";
|
||||
import { KeyboardShortcutsDialog } from "./KeyboardShortcutsDialog";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
export function SettingsDropdown() {
|
||||
const exportData = useExportData();
|
||||
@@ -62,7 +62,7 @@ export function SettingsDropdown() {
|
||||
{
|
||||
label: "Create Run Button",
|
||||
leftSlot: <Icon icon="rocket" />,
|
||||
onSelect: () => openUrl("https://yaak.app/button/new"),
|
||||
onSelect: () => platform.openUrl("https://yaak.app/button/new"),
|
||||
},
|
||||
{ type: "separator", label: `Yaak v${appInfo.version}` },
|
||||
{
|
||||
@@ -78,26 +78,26 @@ export function SettingsDropdown() {
|
||||
leftSlot: <Icon icon="circle_dollar_sign" />,
|
||||
rightSlot: <Icon icon="external_link" color="success" className="opacity-60" />,
|
||||
onSelect: () =>
|
||||
openUrl(pricingUrl(`app.menu.purchase.${check.data?.status ?? "unknown"}`)),
|
||||
platform.openUrl(pricingUrl(`app.menu.purchase.${check.data?.status ?? "unknown"}`)),
|
||||
},
|
||||
{
|
||||
label: "Install CLI",
|
||||
hidden: appInfo.cliVersion != null,
|
||||
leftSlot: <Icon icon="square_terminal" />,
|
||||
rightSlot: <Icon icon="external_link" color="secondary" />,
|
||||
onSelect: () => openUrl("https://yaak.app/docs/cli"),
|
||||
onSelect: () => platform.openUrl("https://yaak.app/docs/cli"),
|
||||
},
|
||||
{
|
||||
label: "Feedback",
|
||||
leftSlot: <Icon icon="chat" />,
|
||||
rightSlot: <Icon icon="external_link" color="secondary" />,
|
||||
onSelect: () => openUrl("https://yaak.app/feedback"),
|
||||
onSelect: () => platform.openUrl("https://yaak.app/feedback"),
|
||||
},
|
||||
{
|
||||
label: "Changelog",
|
||||
leftSlot: <Icon icon="cake" />,
|
||||
rightSlot: <Icon icon="external_link" color="secondary" />,
|
||||
onSelect: () => openUrl(`https://yaak.app/changelog/${appInfo.version}`),
|
||||
onSelect: () => platform.openUrl(`https://yaak.app/changelog/${appInfo.version}`),
|
||||
},
|
||||
]}
|
||||
>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { Compartment } from "@codemirror/state";
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { debounce } from "@yaakapp-internal/lib";
|
||||
import { gitMutations } from "@yaakapp-internal/git";
|
||||
import type { GitStatus } from "@yaakapp-internal/git";
|
||||
@@ -44,7 +43,8 @@ import { getFolderActions } from "../hooks/useFolderActions";
|
||||
import { getGrpcRequestActions } from "../hooks/useGrpcRequestActions";
|
||||
import { useHotKey } from "../hooks/useHotKey";
|
||||
import { getHttpRequestActions } from "../hooks/useHttpRequestActions";
|
||||
import { useListenToTauriEvent } from "../hooks/useListenToTauriEvent";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { usePlatformEvent } from "../hooks/usePlatformEvent";
|
||||
import { getModelAncestors } from "../hooks/useModelAncestors";
|
||||
import { sendAnyHttpRequest } from "../hooks/useSendAnyHttpRequest";
|
||||
import { useSidebarHidden } from "../hooks/useSidebarHidden";
|
||||
@@ -135,10 +135,10 @@ function Sidebar({ className }: { className?: string }) {
|
||||
// Focus new sidebar models created by the user in this window. Writes from other
|
||||
// sources (import, sync, CLI) can carry thousands of models and shouldn't move
|
||||
// the selection.
|
||||
useListenToTauriEvent<ModelPayload[]>("model_writes", ({ payload: payloads }) => {
|
||||
usePlatformEvent<ModelPayload[]>("model_writes", (payloads) => {
|
||||
for (const payload of payloads) {
|
||||
if (payload.updateSource.type !== "window") continue;
|
||||
if (payload.updateSource.label !== getCurrentWebviewWindow().label) continue;
|
||||
if (payload.updateSource.label !== platform.window.label) continue;
|
||||
if (!isSidebarLeafModel(payload.model)) continue;
|
||||
if (!(payload.change.type === "upsert" && payload.change.created)) continue;
|
||||
treeRef.current?.selectItem(payload.model.id, true);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { readDir } from "@tauri-apps/plugin-fs";
|
||||
import { Banner, VStack } from "@yaakapp-internal/ui";
|
||||
import { useState } from "react";
|
||||
import { openWorkspaceFromSyncDir } from "../commands/openWorkspaceFromSyncDir";
|
||||
@@ -6,6 +5,7 @@ import { Button } from "./core/Button";
|
||||
import { Checkbox } from "./core/Checkbox";
|
||||
import { SettingRowBoolean, SettingRowDirectory } from "./core/SettingRow";
|
||||
import { SelectFile } from "./SelectFile";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
export interface SyncToFilesystemSettingProps {
|
||||
layout?: "form" | "settings";
|
||||
@@ -24,7 +24,7 @@ export function SyncToFilesystemSetting({
|
||||
|
||||
const handleFilePathChange = async (filePath: string | null) => {
|
||||
if (filePath != null) {
|
||||
const files = await readDir(filePath);
|
||||
const files = await platform.files.readDir(filePath);
|
||||
if (files.length > 0) {
|
||||
setSyncDir(filePath);
|
||||
return;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type } from "@tauri-apps/plugin-os";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { settingsAtom, workspacesAtom } from "@yaakapp-internal/models";
|
||||
import { Banner, HeaderSize, HStack, SidebarLayout } from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
@@ -53,7 +53,7 @@ export function Workspace() {
|
||||
|
||||
const workspaces = useAtomValue(workspacesAtom);
|
||||
const settings = useAtomValue(settingsAtom);
|
||||
const osType = type();
|
||||
const osType = platform.osType();
|
||||
const [width, setWidth] = useSidebarWidth();
|
||||
const [sidebarHidden, setSidebarHidden] = useSidebarHidden();
|
||||
const [floatingSidebarHidden, setFloatingSidebarHidden] = useFloatingSidebarHidden();
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { revealItemInDir } from "@tauri-apps/plugin-opener";
|
||||
import { getModel, settingsAtom, workspacesAtom } from "@yaakapp-internal/models";
|
||||
import classNames from "classnames";
|
||||
import { useAtomValue } from "jotai";
|
||||
@@ -27,6 +25,7 @@ import { Icon } from "@yaakapp-internal/ui";
|
||||
import type { RadioDropdownItem } from "./core/RadioDropdown";
|
||||
import { RadioDropdown } from "./core/RadioDropdown";
|
||||
import { SwitchWorkspaceDialog } from "./SwitchWorkspaceDialog";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
type Props = Pick<ButtonProps, "className" | "justify" | "forDropdown" | "leftSlot">;
|
||||
|
||||
@@ -76,7 +75,7 @@ export const WorkspaceActionsDropdown = memo(function WorkspaceActionsDropdown({
|
||||
label: "Open Folder",
|
||||
leftSlot: <Icon icon="folder_open" />,
|
||||
onSelect: async () => {
|
||||
const dir = await open({
|
||||
const dir = await platform.dialog.open({
|
||||
title: "Select Workspace Directory",
|
||||
directory: true,
|
||||
multiple: false,
|
||||
@@ -120,7 +119,7 @@ export const WorkspaceActionsDropdown = memo(function WorkspaceActionsDropdown({
|
||||
leftSlot: <Icon icon="folder_symlink" />,
|
||||
onSelect: async () => {
|
||||
if (workspaceMeta?.settingSyncDir == null) return;
|
||||
await revealItemInDir(workspaceMeta.settingSyncDir);
|
||||
await platform.revealItemInDir(workspaceMeta.settingSyncDir);
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -10,7 +10,7 @@ import { CookieDropdown } from "./CookieDropdown";
|
||||
import { IconButton } from "./core/IconButton";
|
||||
import { PillButton } from "./core/PillButton";
|
||||
import { EnvironmentActionsDropdown } from "./EnvironmentActionsDropdown";
|
||||
import { ImportCurlButton } from "./ImportCurlButton";
|
||||
import { ImportCurl } from "./ImportCurl";
|
||||
import { LicenseBadge } from "./LicenseBadge";
|
||||
import { RecentRequestsDropdown } from "./RecentRequestsDropdown";
|
||||
import { SettingsDropdown } from "./SettingsDropdown";
|
||||
@@ -56,7 +56,7 @@ export const WorkspaceHeader = memo(function WorkspaceHeader({
|
||||
<RecentRequestsDropdown />
|
||||
</div>
|
||||
<div className="flex-1 flex gap-1 items-center h-full justify-end pointer-events-none pr-1">
|
||||
<ImportCurlButton />
|
||||
<ImportCurl />
|
||||
{showEncryptionSetup ? (
|
||||
<PillButton color="danger" onClick={setupOrConfigureEncryption}>
|
||||
Enter Encryption Key
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
useSensor,
|
||||
useSensors,
|
||||
} from "@dnd-kit/core";
|
||||
import { basename } from "@tauri-apps/api/path";
|
||||
import classNames from "classnames";
|
||||
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { WrappedEnvironmentVariable } from "../../hooks/useEnvironmentVariables";
|
||||
@@ -34,6 +33,7 @@ import { Input } from "./Input";
|
||||
import { ensurePairId } from "./PairEditor.util";
|
||||
import type { RadioDropdownItem } from "./RadioDropdown";
|
||||
import { RadioDropdown } from "./RadioDropdown";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
export interface PairEditorHandle {
|
||||
/**
|
||||
@@ -851,7 +851,7 @@ function FileActionsDropdown({
|
||||
leftSlot: <Icon icon="file_code" />,
|
||||
onSelect: async () => {
|
||||
console.log("PAIR", pair);
|
||||
const defaultFilename = await basename(pair.value ?? "");
|
||||
const defaultFilename = await platform.files.basename(pair.value ?? "");
|
||||
const filename = await showPrompt({
|
||||
id: "filename",
|
||||
title: "Override Filename",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type } from "@tauri-apps/plugin-os";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { HStack } from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import type { CSSProperties, ReactNode } from "react";
|
||||
@@ -66,7 +66,7 @@ export function Select<T extends string>({
|
||||
<Label htmlFor={id} visuallyHidden={hideLabel} className={labelClassName} help={help}>
|
||||
{label}
|
||||
</Label>
|
||||
{type() === "macos" && !filterable ? (
|
||||
{platform.osType() === "macos" && !filterable ? (
|
||||
<HStack
|
||||
space={2}
|
||||
className={classNames(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import { useEffect, useState } from "react";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
interface Props {
|
||||
bodyPath?: string;
|
||||
@@ -12,7 +12,7 @@ export function AudioViewer({ bodyPath, data, mimeType }: Props) {
|
||||
|
||||
useEffect(() => {
|
||||
if (bodyPath) {
|
||||
setSrc(convertFileSrc(bodyPath));
|
||||
setSrc(platform.files.url(bodyPath));
|
||||
} else if (data) {
|
||||
// The type matters here in a way it doesn't for an image: a media element goes by what
|
||||
// the blob declares rather than sniffing it, so an Ogg labelled as MP3 won't play
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import classNames from "classnames";
|
||||
import { useEffect, useState } from "react";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
type Props = { className?: string; mimeType?: string } & (
|
||||
| {
|
||||
@@ -18,7 +18,7 @@ export function ImageViewer({ className, mimeType, ...props }: Props) {
|
||||
|
||||
useEffect(() => {
|
||||
if (bodyPath != null) {
|
||||
setSrc(convertFileSrc(bodyPath));
|
||||
setSrc(platform.files.url(bodyPath));
|
||||
} else if (data != null) {
|
||||
const blob = new Blob([data], { type: mimeType ?? "image/png" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import "react-pdf/dist/Page/TextLayer.css";
|
||||
import "react-pdf/dist/Page/AnnotationLayer.css";
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import "./PdfViewer.css";
|
||||
import type { PDFDocumentProxy } from "pdfjs-dist";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { Document, Page } from "react-pdf";
|
||||
import { useContainerSize } from "@yaakapp-internal/ui";
|
||||
import { fireAndForget } from "../../lib/fireAndForget";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
fireAndForget(
|
||||
import("react-pdf").then(({ pdfjs }) => {
|
||||
@@ -37,7 +37,7 @@ export function PdfViewer({ bodyPath, data }: Props) {
|
||||
// `Document` renders its "Failed to load PDF file" state for that frame before recovering
|
||||
const src = useMemo(() => {
|
||||
if (bodyPath) {
|
||||
return convertFileSrc(bodyPath);
|
||||
return platform.files.url(bodyPath);
|
||||
}
|
||||
if (data) {
|
||||
// Create a copy to avoid "Buffer is already detached" errors
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import { useEffect, useState } from "react";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
interface Props {
|
||||
bodyPath?: string;
|
||||
@@ -12,7 +12,7 @@ export function VideoViewer({ bodyPath, data, mimeType }: Props) {
|
||||
|
||||
useEffect(() => {
|
||||
if (bodyPath) {
|
||||
setSrc(convertFileSrc(bodyPath));
|
||||
setSrc(platform.files.url(bodyPath));
|
||||
} else if (data) {
|
||||
// As in AudioViewer: a media element trusts the declared type instead of sniffing
|
||||
const blob = new Blob([new Uint8Array(data)], { type: mimeType ?? "video/mp4" });
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Listen for settings changes, the re-compute theme
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import type { ModelPayload } from "@yaakapp-internal/models";
|
||||
import { fireAndForget } from "./lib/fireAndForget";
|
||||
import { getSettings } from "./lib/settings";
|
||||
@@ -8,12 +8,12 @@ function setFontSizeOnDocument(fontSize: number) {
|
||||
document.documentElement.style.fontSize = `${fontSize}px`;
|
||||
}
|
||||
|
||||
listen<ModelPayload[]>("model_writes", async (event) => {
|
||||
for (const payload of event.payload) {
|
||||
platform.listen<ModelPayload[]>("model_writes", (payloads) => {
|
||||
for (const payload of payloads) {
|
||||
if (payload.change.type !== "upsert") continue;
|
||||
if (payload.model.model !== "settings") continue;
|
||||
setFontSizeOnDocument(payload.model.interfaceFontSize);
|
||||
}
|
||||
}).catch(console.error);
|
||||
});
|
||||
|
||||
fireAndForget(getSettings().then((settings) => setFontSizeOnDocument(settings.interfaceFontSize)));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Listen for settings changes, the re-compute theme
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import type { ModelPayload, Settings } from "@yaakapp-internal/models";
|
||||
import { fireAndForget } from "./lib/fireAndForget";
|
||||
import { getSettings } from "./lib/settings";
|
||||
@@ -12,12 +12,12 @@ function setFonts(settings: Settings) {
|
||||
);
|
||||
}
|
||||
|
||||
listen<ModelPayload[]>("model_writes", async (event) => {
|
||||
for (const payload of event.payload) {
|
||||
platform.listen<ModelPayload[]>("model_writes", (payloads) => {
|
||||
for (const payload of payloads) {
|
||||
if (payload.change.type !== "upsert") continue;
|
||||
if (payload.model.model !== "settings") continue;
|
||||
setFonts(payload.model);
|
||||
}
|
||||
}).catch(console.error);
|
||||
});
|
||||
|
||||
fireAndForget(getSettings().then((settings) => setFonts(settings)));
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { event } from "@tauri-apps/api";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { useFastMutation } from "./useFastMutation";
|
||||
|
||||
export function useCancelHttpResponse(id: string | null) {
|
||||
return useFastMutation<void>({
|
||||
mutationKey: ["cancel_http_response", id],
|
||||
mutationFn: () => event.emit(`cancel_http_response_${id}`),
|
||||
mutationFn: () => platform.emit(`cancel_http_response_${id}`),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3,13 +3,13 @@ import { InlineCode } from "@yaakapp-internal/ui";
|
||||
import { showAlert } from "../lib/alert";
|
||||
import { appInfo } from "../lib/appInfo";
|
||||
import { minPromiseMillis } from "../lib/minPromiseMillis";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
|
||||
export function useCheckForUpdates() {
|
||||
return useMutation({
|
||||
mutationKey: ["check_for_updates"],
|
||||
mutationFn: async () => {
|
||||
const hasUpdate: boolean = await minPromiseMillis(invokeCmd("cmd_check_for_updates"), 500);
|
||||
const hasUpdate: boolean = await minPromiseMillis(rpc("cmd_check_for_updates"), 500);
|
||||
if (!hasUpdate) {
|
||||
showAlert({
|
||||
id: "no-updates",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { useFastMutation } from "./useFastMutation";
|
||||
|
||||
export function useDeleteGrpcConnections(requestId?: string) {
|
||||
@@ -6,7 +6,7 @@ export function useDeleteGrpcConnections(requestId?: string) {
|
||||
mutationKey: ["delete_grpc_connections", requestId],
|
||||
mutationFn: async () => {
|
||||
if (requestId === undefined) return;
|
||||
await invokeCmd("cmd_delete_all_grpc_connections", { requestId });
|
||||
await rpc("cmd_delete_all_grpc_connections", { requestId });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { useFastMutation } from "./useFastMutation";
|
||||
|
||||
export function useDeleteHttpResponses(requestId?: string) {
|
||||
@@ -6,7 +6,7 @@ export function useDeleteHttpResponses(requestId?: string) {
|
||||
mutationKey: ["delete_http_responses", requestId],
|
||||
mutationFn: async () => {
|
||||
if (requestId === undefined) return;
|
||||
await invokeCmd("cmd_delete_all_http_responses", { requestId });
|
||||
await rpc("cmd_delete_all_http_responses", { requestId });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import { showAlert } from "../lib/alert";
|
||||
import { showConfirmDelete } from "../lib/confirm";
|
||||
import { jotaiStore } from "../lib/jotai";
|
||||
import { pluralizeCount } from "../lib/pluralize";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { activeWorkspaceIdAtom } from "./useActiveWorkspace";
|
||||
import { useFastMutation } from "./useFastMutation";
|
||||
|
||||
@@ -45,7 +45,7 @@ export function useDeleteSendHistory() {
|
||||
if (!confirmed) return false;
|
||||
|
||||
const workspaceId = jotaiStore.get(activeWorkspaceIdAtom);
|
||||
await invokeCmd("cmd_delete_send_history", { workspaceId });
|
||||
await rpc("cmd_delete_send_history", { workspaceId });
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -6,7 +6,7 @@ import type {
|
||||
GetFolderActionsResponse,
|
||||
} from "@yaakapp-internal/plugins";
|
||||
import { useMemo } from "react";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { usePluginsKey } from "./usePlugins";
|
||||
|
||||
export type CallableFolderAction = Pick<FolderAction, "label" | "icon"> & {
|
||||
@@ -30,7 +30,7 @@ export function useFolderActions() {
|
||||
}
|
||||
|
||||
export async function getFolderActions() {
|
||||
const responses = await invokeCmd<GetFolderActionsResponse[]>("cmd_folder_actions");
|
||||
const responses = await rpc<GetFolderActionsResponse[]>("cmd_folder_actions");
|
||||
const actions = responses.flatMap((r) =>
|
||||
r.actions.map((a, i) => ({
|
||||
label: a.label,
|
||||
@@ -41,7 +41,7 @@ export async function getFolderActions() {
|
||||
pluginRefId: r.pluginRefId,
|
||||
args: { folder },
|
||||
};
|
||||
await invokeCmd("cmd_call_folder_action", { req: payload });
|
||||
await rpc("cmd_call_folder_action", { req: payload });
|
||||
},
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { emit } from "@tauri-apps/api/event";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import type { GrpcConnection, GrpcRequest } from "@yaakapp-internal/models";
|
||||
import { flushAllModelWrites } from "@yaakapp-internal/models";
|
||||
import { jotaiStore } from "../lib/jotai";
|
||||
import { minPromiseMillis } from "../lib/minPromiseMillis";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { activeEnvironmentIdAtom, useActiveEnvironment } from "./useActiveEnvironment";
|
||||
import { useDebouncedValue } from "@yaakapp-internal/ui";
|
||||
|
||||
@@ -25,7 +25,7 @@ export function useGrpc(
|
||||
mutationKey: ["grpc_go", conn?.id],
|
||||
mutationFn: async () => {
|
||||
await flushAllModelWrites(); // The backend reads the request from the DB
|
||||
return invokeCmd<void>("cmd_grpc_go", {
|
||||
return rpc<void>("cmd_grpc_go", {
|
||||
requestId,
|
||||
environmentId: environment?.id,
|
||||
protoFiles,
|
||||
@@ -36,17 +36,17 @@ export function useGrpc(
|
||||
const send = useMutation({
|
||||
mutationKey: ["grpc_send", conn?.id],
|
||||
mutationFn: ({ message }: { message: string }) =>
|
||||
emit(`grpc_client_msg_${conn?.id ?? "none"}`, { Message: message }),
|
||||
platform.emit(`grpc_client_msg_${conn?.id ?? "none"}`, { Message: message }),
|
||||
});
|
||||
|
||||
const cancel = useMutation({
|
||||
mutationKey: ["grpc_cancel", conn?.id ?? "n/a"],
|
||||
mutationFn: () => emit(`grpc_client_msg_${conn?.id ?? "none"}`, "Cancel"),
|
||||
mutationFn: () => platform.emit(`grpc_client_msg_${conn?.id ?? "none"}`, "Cancel"),
|
||||
});
|
||||
|
||||
const commit = useMutation({
|
||||
mutationKey: ["grpc_commit", conn?.id ?? "n/a"],
|
||||
mutationFn: () => emit(`grpc_client_msg_${conn?.id ?? "none"}`, "Commit"),
|
||||
mutationFn: () => platform.emit(`grpc_client_msg_${conn?.id ?? "none"}`, "Commit"),
|
||||
});
|
||||
|
||||
const debouncedUrl = useDebouncedValue<string>(req?.url ?? "", 1000);
|
||||
@@ -61,7 +61,7 @@ export function useGrpc(
|
||||
queryFn: () => {
|
||||
const environmentId = jotaiStore.get(activeEnvironmentIdAtom);
|
||||
return minPromiseMillis<ReflectResponseService[]>(
|
||||
invokeCmd("cmd_grpc_reflect", { requestId, protoFiles, environmentId }),
|
||||
rpc("cmd_grpc_reflect", { requestId, protoFiles, environmentId }),
|
||||
300,
|
||||
);
|
||||
},
|
||||
|
||||
@@ -6,7 +6,7 @@ import type {
|
||||
GrpcRequestAction,
|
||||
} from "@yaakapp-internal/plugins";
|
||||
import { useMemo } from "react";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { getGrpcProtoFiles } from "./useGrpcProtoFiles";
|
||||
import { usePluginsKey } from "./usePlugins";
|
||||
|
||||
@@ -33,7 +33,7 @@ export function useGrpcRequestActions() {
|
||||
}
|
||||
|
||||
export async function getGrpcRequestActions() {
|
||||
const responses = await invokeCmd<GetGrpcRequestActionsResponse[]>("cmd_grpc_request_actions");
|
||||
const responses = await rpc<GetGrpcRequestActionsResponse[]>("cmd_grpc_request_actions");
|
||||
|
||||
return responses.flatMap((r) =>
|
||||
r.actions.map((a, i) => ({
|
||||
@@ -46,7 +46,7 @@ export async function getGrpcRequestActions() {
|
||||
pluginRefId: r.pluginRefId,
|
||||
args: { grpcRequest, protoFiles },
|
||||
};
|
||||
await invokeCmd("cmd_call_grpc_request_action", { req: payload });
|
||||
await rpc("cmd_call_grpc_request_action", { req: payload });
|
||||
},
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type } from "@tauri-apps/plugin-os";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { debounce } from "@yaakapp-internal/lib";
|
||||
import { settingsAtom } from "@yaakapp-internal/models";
|
||||
import { atom, useAtomValue } from "jotai";
|
||||
@@ -102,7 +102,7 @@ const defaultHotkeysOther: Record<HotkeyAction, string[]> = {
|
||||
|
||||
/** Get the default hotkeys for the current platform */
|
||||
export const defaultHotkeys: Record<HotkeyAction, string[]> =
|
||||
type() === "macos" ? defaultHotkeysMac : defaultHotkeysOther;
|
||||
platform.osType() === "macos" ? defaultHotkeysMac : defaultHotkeysOther;
|
||||
|
||||
/** Atom that provides the effective hotkeys by merging defaults with user settings */
|
||||
export const hotkeysAtom = atom((get) => {
|
||||
@@ -318,7 +318,7 @@ export function getHotkeyScope(action: HotkeyAction): string {
|
||||
}
|
||||
|
||||
export function formatHotkeyString(trigger: string): string[] {
|
||||
const os = type();
|
||||
const os = platform.osType();
|
||||
const parts = trigger.split("+");
|
||||
const labelParts: string[] = [];
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { GetHttpAuthenticationSummaryResponse } from "@yaakapp-internal/plu
|
||||
import { atom, useAtomValue } from "jotai";
|
||||
import { useState } from "react";
|
||||
import { jotaiStore } from "../lib/jotai";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { showErrorToast } from "../lib/toast";
|
||||
import { usePluginsKey } from "./usePlugins";
|
||||
|
||||
@@ -31,7 +31,7 @@ export function useSubscribeHttpAuthentication() {
|
||||
placeholderData: (prev) => prev, // Keep previous data on refetch
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const result = await invokeCmd<GetHttpAuthenticationSummaryResponse[]>(
|
||||
const result = await rpc<GetHttpAuthenticationSummaryResponse[]>(
|
||||
"cmd_get_http_authentication_summaries",
|
||||
);
|
||||
setNumResults(result.length);
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { GetHttpAuthenticationConfigResponse, JsonPrimitive } from "@yaakap
|
||||
import { useAtomValue } from "jotai";
|
||||
import { md5 } from "js-md5";
|
||||
import { useState } from "react";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { activeEnvironmentIdAtom } from "./useActiveEnvironment";
|
||||
import { activeWorkspaceIdAtom } from "./useActiveWorkspace";
|
||||
|
||||
@@ -48,7 +48,7 @@ export function useHttpAuthenticationConfig(
|
||||
placeholderData: (prev) => prev, // Keep previous data on refetch
|
||||
queryFn: async () => {
|
||||
if (authName == null || authName === "inherit") return null;
|
||||
const config = await invokeCmd<GetHttpAuthenticationConfigResponse>(
|
||||
const config = await rpc<GetHttpAuthenticationConfigResponse>(
|
||||
"cmd_get_http_authentication_config",
|
||||
{
|
||||
authName,
|
||||
@@ -65,7 +65,7 @@ export function useHttpAuthenticationConfig(
|
||||
call: async (
|
||||
model: HttpRequest | GrpcRequest | WebsocketRequest | Folder | Workspace,
|
||||
) => {
|
||||
await invokeCmd("cmd_call_http_authentication_action", {
|
||||
await rpc("cmd_call_http_authentication_action", {
|
||||
pluginRefId: config.pluginRefId,
|
||||
actionIndex: i,
|
||||
authName,
|
||||
|
||||
@@ -6,7 +6,7 @@ import type {
|
||||
HttpRequestAction,
|
||||
} from "@yaakapp-internal/plugins";
|
||||
import { useMemo } from "react";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { usePluginsKey } from "./usePlugins";
|
||||
|
||||
export type CallableHttpRequestAction = Pick<HttpRequestAction, "label" | "icon"> & {
|
||||
@@ -30,7 +30,7 @@ export function useHttpRequestActions() {
|
||||
}
|
||||
|
||||
export async function getHttpRequestActions() {
|
||||
const responses = await invokeCmd<GetHttpRequestActionsResponse[]>("cmd_http_request_actions");
|
||||
const responses = await rpc<GetHttpRequestActionsResponse[]>("cmd_http_request_actions");
|
||||
const actions = responses.flatMap((r) =>
|
||||
r.actions.map((a, i) => ({
|
||||
label: a.label,
|
||||
@@ -41,7 +41,7 @@ export async function getHttpRequestActions() {
|
||||
pluginRefId: r.pluginRefId,
|
||||
args: { httpRequest },
|
||||
};
|
||||
await invokeCmd("cmd_call_http_request_action", { req: payload });
|
||||
await rpc("cmd_call_http_request_action", { req: payload });
|
||||
},
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { HttpResponse } from "@yaakapp-internal/models";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
|
||||
export function useHttpRequestBody(response: HttpResponse | null) {
|
||||
return useQuery({
|
||||
@@ -18,7 +18,7 @@ export async function getRequestBodyText(response: HttpResponse | null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = await invokeCmd<number[] | null>("cmd_http_request_body", {
|
||||
const data = await rpc<number[] | null>("cmd_http_request_body", {
|
||||
responseId: response.id,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type { HttpResponse, HttpResponseEvent } from "@yaakapp-internal/models";
|
||||
import {
|
||||
httpResponseEventsAtom,
|
||||
@@ -8,6 +7,7 @@ import {
|
||||
import { useAtomValue } from "jotai";
|
||||
import { useEffect } from "react";
|
||||
import { fireAndForget } from "../lib/fireAndForget";
|
||||
import { rpc } from "../lib/rpc";
|
||||
|
||||
export function useHttpResponseEvents(response: HttpResponse | null) {
|
||||
const allEvents = useAtomValue(httpResponseEventsAtom);
|
||||
@@ -20,7 +20,7 @@ export function useHttpResponseEvents(response: HttpResponse | null) {
|
||||
|
||||
// Fetch events from database, filtering out events from other responses and merging atomically
|
||||
fireAndForget(
|
||||
invoke<HttpResponseEvent[]>("cmd_get_http_response_events", { responseId: response.id }).then(
|
||||
rpc<HttpResponseEvent[]>("cmd_get_http_response_events", { responseId: response.id }).then(
|
||||
(events) =>
|
||||
mergeModelsInStore("http_response_event", events, (e) => e.responseId === response.id),
|
||||
),
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import type { HttpRequest } from "@yaakapp-internal/models";
|
||||
import { patchModelById } from "@yaakapp-internal/models";
|
||||
import { createRequestAndNavigate } from "../lib/createRequestAndNavigate";
|
||||
import { jotaiStore } from "../lib/jotai";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { showToast } from "../lib/toast";
|
||||
import { activeWorkspaceIdAtom } from "./useActiveWorkspace";
|
||||
import { useFastMutation } from "./useFastMutation";
|
||||
import { wasUpdatedExternally } from "./useRequestUpdateKey";
|
||||
|
||||
export function useImportCurl() {
|
||||
return useFastMutation({
|
||||
mutationKey: ["import_curl"],
|
||||
mutationFn: async ({
|
||||
overwriteRequestId,
|
||||
command,
|
||||
}: {
|
||||
overwriteRequestId?: string;
|
||||
command: string;
|
||||
}) => {
|
||||
const workspaceId = jotaiStore.get(activeWorkspaceIdAtom);
|
||||
const importedRequest: HttpRequest = await invokeCmd("cmd_curl_to_request", {
|
||||
command,
|
||||
workspaceId,
|
||||
});
|
||||
|
||||
let verb: string;
|
||||
if (overwriteRequestId == null) {
|
||||
verb = "Created";
|
||||
await createRequestAndNavigate(importedRequest);
|
||||
} else {
|
||||
verb = "Updated";
|
||||
await patchModelById(importedRequest.model, overwriteRequestId, (r: HttpRequest) => ({
|
||||
...importedRequest,
|
||||
id: r.id,
|
||||
createdAt: r.createdAt,
|
||||
workspaceId: r.workspaceId,
|
||||
folderId: r.folderId,
|
||||
name: r.name,
|
||||
sortPriority: r.sortPriority,
|
||||
}));
|
||||
|
||||
setTimeout(() => wasUpdatedExternally(overwriteRequestId), 100);
|
||||
}
|
||||
|
||||
showToast({
|
||||
color: "success",
|
||||
message: `${verb} request from Curl`,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
|
||||
import type { GraphQlIntrospection, HttpRequest } from "@yaakapp-internal/models";
|
||||
import type { GraphQLSchema, IntrospectionQuery } from "graphql";
|
||||
import { buildClientSchema, getIntrospectionQuery } from "graphql";
|
||||
@@ -9,6 +9,7 @@ import { getResponseBodyText } from "../lib/responseBody";
|
||||
import { sendEphemeralRequest } from "../lib/sendEphemeralRequest";
|
||||
import { useActiveEnvironment } from "./useActiveEnvironment";
|
||||
import { useDebouncedValue } from "@yaakapp-internal/ui";
|
||||
import { rpc } from "../lib/rpc";
|
||||
|
||||
const introspectionRequestBody = JSON.stringify({
|
||||
query: getIntrospectionQuery(),
|
||||
@@ -32,7 +33,7 @@ export function useIntrospectGraphQL(
|
||||
|
||||
const upsertIntrospection = useCallback(
|
||||
async (content: string | null) => {
|
||||
const v = await invoke<GraphQlIntrospection>("models_upsert_graphql_introspection", {
|
||||
const v = await rpc<GraphQlIntrospection>("models_upsert_graphql_introspection", {
|
||||
requestId: baseRequest.id,
|
||||
workspaceId: baseRequest.workspaceId,
|
||||
content: content ?? "",
|
||||
@@ -119,7 +120,7 @@ function useIntrospectionResult(request: HttpRequest) {
|
||||
return useQuery({
|
||||
queryKey: ["introspection", request.id],
|
||||
queryFn: async () =>
|
||||
invoke<GraphQlIntrospection | null>("models_get_graphql_introspection", {
|
||||
rpc<GraphQlIntrospection | null>("models_get_graphql_introspection", {
|
||||
requestId: request.id,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { EventCallback, EventName } from "@tauri-apps/api/event";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
export function useListenToTauriEvent<T>(event: EventName, fn: EventCallback<T>) {
|
||||
const handlerRef = useRef(fn);
|
||||
useEffect(() => {
|
||||
handlerRef.current = fn;
|
||||
}, [fn]);
|
||||
|
||||
useEffect(() => {
|
||||
return listenToTauriEvent<T>(event, (p) => handlerRef.current(p));
|
||||
}, [event]);
|
||||
}
|
||||
|
||||
export function listenToTauriEvent<T>(event: EventName, fn: EventCallback<T>) {
|
||||
const unsubPromise = listen<T>(
|
||||
event,
|
||||
fn,
|
||||
// Listen to `emit_all()` events or events specific to the current window
|
||||
{ target: { label: getCurrentWebviewWindow().label, kind: "Window" } },
|
||||
);
|
||||
|
||||
return () => {
|
||||
unsubPromise.then((unsub) => unsub()).catch(console.error);
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type { GrpcConnection, GrpcEvent } from "@yaakapp-internal/models";
|
||||
import {
|
||||
grpcConnectionsAtom,
|
||||
@@ -11,6 +10,7 @@ import { useEffect, useMemo } from "react";
|
||||
import { fireAndForget } from "../lib/fireAndForget";
|
||||
import { atomWithKVStorage } from "../lib/atoms/atomWithKVStorage";
|
||||
import { activeRequestIdAtom } from "./useActiveRequestId";
|
||||
import { rpc } from "../lib/rpc";
|
||||
|
||||
const pinnedGrpcConnectionIdsAtom = atomWithKVStorage<Record<string, string | null>>(
|
||||
"pinned-grpc-connection-ids",
|
||||
@@ -71,7 +71,7 @@ export function useGrpcEvents(connectionId: string | null) {
|
||||
|
||||
// Fetch events from database, filtering out events from other connections and merging atomically
|
||||
fireAndForget(
|
||||
invoke<GrpcEvent[]>("models_grpc_events", { connectionId }).then((events) =>
|
||||
rpc<GrpcEvent[]>("models_grpc_events", { connectionId }).then((events) =>
|
||||
mergeModelsInStore("grpc_event", events, (e) => e.connectionId === connectionId),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type { WebsocketConnection, WebsocketEvent } from "@yaakapp-internal/models";
|
||||
import {
|
||||
mergeModelsInStore,
|
||||
@@ -12,6 +11,7 @@ import { fireAndForget } from "../lib/fireAndForget";
|
||||
import { atomWithKVStorage } from "../lib/atoms/atomWithKVStorage";
|
||||
import { jotaiStore } from "../lib/jotai";
|
||||
import { activeRequestIdAtom } from "./useActiveRequestId";
|
||||
import { rpc } from "../lib/rpc";
|
||||
|
||||
const pinnedWebsocketConnectionIdAtom = atomWithKVStorage<Record<string, string | null>>(
|
||||
"pinned-websocket-connection-ids",
|
||||
@@ -58,7 +58,7 @@ export function useWebsocketEvents(connectionId: string | null) {
|
||||
|
||||
// Fetch events from database, filtering out events from other connections and merging atomically
|
||||
fireAndForget(
|
||||
invoke<WebsocketEvent[]>("models_websocket_events", { connectionId }).then((events) =>
|
||||
rpc<WebsocketEvent[]>("models_websocket_events", { connectionId }).then((events) =>
|
||||
mergeModelsInStore("websocket_event", events, (e) => e.connectionId === connectionId),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { useEffect, useRef } from "react";
|
||||
|
||||
/** Subscribe to a backend event for the lifetime of the component. */
|
||||
export function usePlatformEvent<T>(event: string, fn: (payload: T) => void) {
|
||||
const handlerRef = useRef(fn);
|
||||
useEffect(() => {
|
||||
handlerRef.current = fn;
|
||||
}, [fn]);
|
||||
|
||||
useEffect(() => platform.listen<T>(event, (payload) => handlerRef.current(payload)), [event]);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { pluginsAtom } from "@yaakapp-internal/models";
|
||||
import type { PluginMetadata } from "@yaakapp-internal/plugins";
|
||||
import { useAtomValue } from "jotai";
|
||||
import { queryClient } from "../lib/queryClient";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
|
||||
function pluginInfoKey(id: string | null, plugin: Plugin | null) {
|
||||
return ["plugin_info", id ?? "n/a", plugin?.updatedAt ?? "n/a"];
|
||||
@@ -19,7 +19,7 @@ export function usePluginInfo(id: string | null) {
|
||||
placeholderData: (prev) => prev, // Keep previous data on refetch
|
||||
queryFn: () => {
|
||||
if (id == null) return null;
|
||||
return invokeCmd<PluginMetadata>("cmd_plugin_info", { id });
|
||||
return rpc<PluginMetadata>("cmd_plugin_info", { id });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { changeModelStoreWorkspace, pluginsAtom } from "@yaakapp-internal/models
|
||||
import { useAtomValue } from "jotai";
|
||||
import { jotaiStore } from "../lib/jotai";
|
||||
import { minPromiseMillis } from "../lib/minPromiseMillis";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { activeWorkspaceIdAtom } from "./useActiveWorkspace";
|
||||
import { useDebouncedValue } from "@yaakapp-internal/ui";
|
||||
import { invalidateAllPluginInfo } from "./usePluginInfo";
|
||||
@@ -26,7 +26,7 @@ export function useRefreshPlugins() {
|
||||
mutationFn: async () => {
|
||||
await minPromiseMillis(
|
||||
(async () => {
|
||||
await invokeCmd("cmd_reload_plugins");
|
||||
await rpc("cmd_reload_plugins");
|
||||
const workspaceId = jotaiStore.get(activeWorkspaceIdAtom);
|
||||
await changeModelStoreWorkspace(workspaceId); // Force refresh models
|
||||
invalidateAllPluginInfo();
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Appearance } from "@yaakapp-internal/theme";
|
||||
import { getCSSAppearance, subscribeToPreferredAppearance } from "@yaakapp-internal/theme";
|
||||
import {
|
||||
getCSSAppearance,
|
||||
getSystemAppearance,
|
||||
subscribeToPreferredAppearance,
|
||||
} from "@yaakapp-internal/theme";
|
||||
|
||||
export function usePreferredAppearance() {
|
||||
const [preferredAppearance, setPreferredAppearance] = useState<Appearance>(getCSSAppearance());
|
||||
const [preferredAppearance, setPreferredAppearance] = useState<Appearance>(
|
||||
getSystemAppearance() ?? getCSSAppearance(),
|
||||
);
|
||||
useEffect(() => subscribeToPreferredAppearance(setPreferredAppearance), []);
|
||||
return preferredAppearance;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import type { RenderPurpose } from "@yaakapp-internal/plugins";
|
||||
import { useAtomValue } from "jotai";
|
||||
import { minPromiseMillis } from "../lib/minPromiseMillis";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { useActiveEnvironment } from "./useActiveEnvironment";
|
||||
import { activeWorkspaceIdAtom } from "./useActiveWorkspace";
|
||||
|
||||
@@ -49,7 +49,7 @@ export async function renderTemplate({
|
||||
purpose: RenderPurpose;
|
||||
ignoreError?: boolean;
|
||||
}): Promise<string> {
|
||||
return invokeCmd("cmd_render_template", {
|
||||
return rpc("cmd_render_template", {
|
||||
template,
|
||||
workspaceId,
|
||||
environmentId,
|
||||
@@ -67,5 +67,5 @@ export async function decryptTemplate({
|
||||
workspaceId: string;
|
||||
environmentId: string | null;
|
||||
}): Promise<string> {
|
||||
return invokeCmd("cmd_decrypt_template", { template, workspaceId, environmentId });
|
||||
return rpc("cmd_decrypt_template", { template, workspaceId, environmentId });
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import type { ModelPayload } from "@yaakapp-internal/models";
|
||||
import { atom, useAtomValue } from "jotai";
|
||||
import { generateId } from "../lib/generateId";
|
||||
@@ -6,26 +6,24 @@ import { jotaiStore } from "../lib/jotai";
|
||||
|
||||
const requestUpdateKeyAtom = atom<Record<string, string>>({});
|
||||
|
||||
getCurrentWebviewWindow()
|
||||
.listen<ModelPayload[]>("model_writes", ({ payload: payloads }) => {
|
||||
const changedIds: string[] = [];
|
||||
for (const payload of payloads) {
|
||||
if (payload.change.type !== "upsert") continue;
|
||||
platform.listen<ModelPayload[]>("model_writes", (payloads) => {
|
||||
const changedIds: string[] = [];
|
||||
for (const payload of payloads) {
|
||||
if (payload.change.type !== "upsert") continue;
|
||||
|
||||
if (
|
||||
(payload.model.model === "http_request" ||
|
||||
payload.model.model === "grpc_request" ||
|
||||
payload.model.model === "websocket_request") &&
|
||||
((payload.updateSource.type === "window" &&
|
||||
payload.updateSource.label !== getCurrentWebviewWindow().label) ||
|
||||
payload.updateSource.type !== "window")
|
||||
) {
|
||||
changedIds.push(payload.model.id);
|
||||
}
|
||||
if (
|
||||
(payload.model.model === "http_request" ||
|
||||
payload.model.model === "grpc_request" ||
|
||||
payload.model.model === "websocket_request") &&
|
||||
((payload.updateSource.type === "window" &&
|
||||
payload.updateSource.label !== platform.window.label) ||
|
||||
payload.updateSource.type !== "window")
|
||||
) {
|
||||
changedIds.push(payload.model.id);
|
||||
}
|
||||
if (changedIds.length > 0) wasUpdatedExternally(changedIds);
|
||||
})
|
||||
.catch(console.error);
|
||||
}
|
||||
if (changedIds.length > 0) wasUpdatedExternally(changedIds);
|
||||
});
|
||||
|
||||
export function wasUpdatedExternally(changedRequestIds: string | string[]) {
|
||||
const ids = Array.isArray(changedRequestIds) ? changedRequestIds : [changedRequestIds];
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { save } from "@tauri-apps/plugin-dialog";
|
||||
import type { HttpResponse } from "@yaakapp-internal/models";
|
||||
import { getModel } from "@yaakapp-internal/models";
|
||||
import mime from "mime";
|
||||
import slugify from "slugify";
|
||||
import { InlineCode } from "@yaakapp-internal/ui";
|
||||
import { getContentTypeFromHeaders } from "../lib/model_util";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { showToast } from "../lib/toast";
|
||||
import { useFastMutation } from "./useFastMutation";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
export function useSaveResponse(response: HttpResponse | null) {
|
||||
return useFastMutation({
|
||||
@@ -21,11 +21,11 @@ export function useSaveResponse(response: HttpResponse | null) {
|
||||
const contentType = getContentTypeFromHeaders(response.headers) ?? "unknown";
|
||||
const ext = mime.getExtension(contentType);
|
||||
const slug = slugify(request.name || "response", { lower: true });
|
||||
const filepath = await save({
|
||||
const filepath = await platform.dialog.save({
|
||||
defaultPath: ext ? `${slug}.${ext}` : slug,
|
||||
title: "Save Response",
|
||||
});
|
||||
await invokeCmd("cmd_save_response", { responseId: response.id, filepath });
|
||||
await rpc("cmd_save_response", { responseId: response.id, filepath });
|
||||
showToast({
|
||||
message: (
|
||||
<>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { HttpResponse } from "@yaakapp-internal/models";
|
||||
import { flushAllModelWrites } from "@yaakapp-internal/models";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { getActiveCookieJar } from "./useActiveCookieJar";
|
||||
import { getActiveEnvironment } from "./useActiveEnvironment";
|
||||
import { createFastMutation, useFastMutation } from "./useFastMutation";
|
||||
@@ -12,7 +12,7 @@ async function sendAnyHttpRequestById(id: string | null): Promise<HttpResponse |
|
||||
|
||||
await flushAllModelWrites();
|
||||
|
||||
return invokeCmd("cmd_send_http_request", {
|
||||
return rpc("cmd_send_http_request", {
|
||||
requestId: id,
|
||||
environmentId: getActiveEnvironment()?.id,
|
||||
cookieJarId: getActiveCookieJar()?.id,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { type } from "@tauri-apps/plugin-os";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { useIsFullscreen } from "@yaakapp-internal/ui";
|
||||
|
||||
export function useStoplightsVisible() {
|
||||
const fullscreen = useIsFullscreen();
|
||||
const stoplightsVisible = type() === "macos" && !fullscreen;
|
||||
const stoplightsVisible = platform.osType() === "macos" && !fullscreen;
|
||||
return stoplightsVisible;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { settingsAtom } from "@yaakapp-internal/models";
|
||||
import { useAtomValue } from "jotai";
|
||||
import { useEffect } from "react";
|
||||
@@ -11,7 +11,7 @@ export function useSyncFontSizeSetting() {
|
||||
}
|
||||
|
||||
const { interfaceScale, editorFontSize } = settings;
|
||||
getCurrentWebviewWindow().setZoom(interfaceScale).catch(console.error);
|
||||
platform.window.setZoom(interfaceScale).catch(console.error);
|
||||
document.documentElement.style.setProperty("--editor-font-size", `${editorFontSize}px`);
|
||||
}, [settings]);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useHotKey } from "./useHotKey";
|
||||
import { useListenToTauriEvent } from "./useListenToTauriEvent";
|
||||
import { usePlatformEvent } from "./usePlatformEvent";
|
||||
import { useZoom } from "./useZoom";
|
||||
|
||||
export function useSyncZoomSetting() {
|
||||
@@ -8,9 +8,9 @@ export function useSyncZoomSetting() {
|
||||
// shortcuts for Windows/Linux
|
||||
const zoom = useZoom();
|
||||
useHotKey("app.zoom_in", zoom.zoomIn);
|
||||
useListenToTauriEvent("zoom_in", zoom.zoomIn);
|
||||
usePlatformEvent("zoom_in", zoom.zoomIn);
|
||||
useHotKey("app.zoom_out", zoom.zoomOut);
|
||||
useListenToTauriEvent("zoom_out", zoom.zoomOut);
|
||||
usePlatformEvent("zoom_out", zoom.zoomOut);
|
||||
useHotKey("app.zoom_reset", zoom.zoomReset);
|
||||
useListenToTauriEvent("zoom_reset", zoom.zoomReset);
|
||||
usePlatformEvent("zoom_reset", zoom.zoomReset);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
import type { GetTemplateFunctionConfigResponse, JsonPrimitive } from "@yaakapp-internal/plugins";
|
||||
import { useAtomValue } from "jotai";
|
||||
import { md5 } from "js-md5";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { activeEnvironmentIdAtom } from "./useActiveEnvironment";
|
||||
import { activeWorkspaceIdAtom } from "./useActiveWorkspace";
|
||||
|
||||
@@ -63,7 +63,7 @@ export async function getTemplateFunctionConfig(
|
||||
model: HttpRequest | GrpcRequest | WebsocketRequest | Folder | Workspace,
|
||||
environmentId: string | undefined,
|
||||
) {
|
||||
const config = await invokeCmd<GetTemplateFunctionConfigResponse>(
|
||||
const config = await rpc<GetTemplateFunctionConfigResponse>(
|
||||
"cmd_template_function_config",
|
||||
{
|
||||
functionName,
|
||||
|
||||
@@ -6,7 +6,7 @@ import type {
|
||||
import { atom, useAtomValue, useSetAtom } from "jotai";
|
||||
import { useMemo, useState } from "react";
|
||||
import type { TwigCompletionOption } from "../components/core/Editor/twig/completion";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { usePluginsKey } from "./usePlugins";
|
||||
|
||||
const templateFunctionsAtom = atom<TemplateFunction[]>([]);
|
||||
@@ -49,7 +49,7 @@ export function useSubscribeTemplateFunctions() {
|
||||
refetchInterval: numFns > 0 ? Number.POSITIVE_INFINITY : 1000,
|
||||
refetchOnMount: true,
|
||||
queryFn: async () => {
|
||||
const result = await invokeCmd<GetTemplateFunctionSummaryResponse[]>(
|
||||
const result = await rpc<GetTemplateFunctionSummaryResponse[]>(
|
||||
"cmd_template_function_summaries",
|
||||
);
|
||||
setNumFns(result.length);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { Tokens } from "@yaakapp-internal/templates";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
|
||||
export function useTemplateTokensToString(tokens: Tokens) {
|
||||
return useQuery<string>({
|
||||
@@ -11,5 +11,5 @@ export function useTemplateTokensToString(tokens: Tokens) {
|
||||
}
|
||||
|
||||
export async function templateTokensToString(tokens: Tokens): Promise<string> {
|
||||
return invokeCmd("cmd_template_tokens_to_string", { tokens });
|
||||
return rpc("cmd_template_tokens_to_string", { tokens });
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import type {
|
||||
WebsocketRequestAction,
|
||||
} from "@yaakapp-internal/plugins";
|
||||
import { useMemo } from "react";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { usePluginsKey } from "./usePlugins";
|
||||
|
||||
export type CallableWebSocketRequestAction = Pick<WebsocketRequestAction, "label" | "icon"> & {
|
||||
@@ -30,7 +30,7 @@ export function useWebsocketRequestActions() {
|
||||
}
|
||||
|
||||
export async function getWebsocketRequestActions() {
|
||||
const responses = await invokeCmd<GetWebsocketRequestActionsResponse[]>(
|
||||
const responses = await rpc<GetWebsocketRequestActionsResponse[]>(
|
||||
"cmd_websocket_request_actions",
|
||||
);
|
||||
const actions = responses.flatMap((r) =>
|
||||
@@ -43,7 +43,7 @@ export async function getWebsocketRequestActions() {
|
||||
pluginRefId: r.pluginRefId,
|
||||
args: { websocketRequest },
|
||||
};
|
||||
await invokeCmd("cmd_call_websocket_request_action", { req: payload });
|
||||
await rpc("cmd_call_websocket_request_action", { req: payload });
|
||||
},
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { useEffect, useState } from "react";
|
||||
import { fireAndForget } from "../lib/fireAndForget";
|
||||
|
||||
export function useWindowFocus() {
|
||||
const [visible, setVisible] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const unlisten = getCurrentWebviewWindow().onFocusChanged((e) => {
|
||||
setVisible(e.payload);
|
||||
});
|
||||
|
||||
return () => {
|
||||
fireAndForget(unlisten.then((fn) => fn()));
|
||||
};
|
||||
return platform.window.onFocusChanged(setVisible);
|
||||
}, []);
|
||||
|
||||
return visible;
|
||||
|
||||
@@ -6,7 +6,7 @@ import type {
|
||||
WorkspaceAction,
|
||||
} from "@yaakapp-internal/plugins";
|
||||
import { useMemo } from "react";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
import { rpc } from "../lib/rpc";
|
||||
import { usePluginsKey } from "./usePlugins";
|
||||
|
||||
export type CallableWorkspaceAction = Pick<WorkspaceAction, "label" | "icon"> & {
|
||||
@@ -30,7 +30,7 @@ export function useWorkspaceActions() {
|
||||
}
|
||||
|
||||
export async function getWorkspaceActions() {
|
||||
const responses = await invokeCmd<GetWorkspaceActionsResponse[]>("cmd_workspace_actions");
|
||||
const responses = await rpc<GetWorkspaceActionsResponse[]>("cmd_workspace_actions");
|
||||
const actions = responses.flatMap((r) =>
|
||||
r.actions.map((a, i) => ({
|
||||
label: a.label,
|
||||
@@ -41,7 +41,7 @@ export async function getWorkspaceActions() {
|
||||
pluginRefId: r.pluginRefId,
|
||||
args: { workspace },
|
||||
};
|
||||
await invokeCmd("cmd_call_workspace_action", { req: payload });
|
||||
await rpc("cmd_call_workspace_action", { req: payload });
|
||||
},
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { AnyModel, ModelPayload } from "@yaakapp-internal/models";
|
||||
import { watchWorkspaceFiles } from "@yaakapp-internal/sync";
|
||||
import { syncWorkspace } from "../commands/commands";
|
||||
import { activeWorkspaceIdAtom, activeWorkspaceMetaAtom } from "../hooks/useActiveWorkspace";
|
||||
import { listenToTauriEvent } from "../hooks/useListenToTauriEvent";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { jotaiStore } from "../lib/jotai";
|
||||
|
||||
export function initSync() {
|
||||
@@ -33,8 +33,8 @@ const syncAfterModelWrite = eagerDebounceAsync(sync, 1000);
|
||||
* simply add long-lived subscribers for the lifetime of the app.
|
||||
*/
|
||||
function initModelListeners() {
|
||||
listenToTauriEvent<ModelPayload[]>("model_writes", (p) => {
|
||||
if (p.payload.some((payload) => isModelRelevant(payload.model))) syncAfterModelWrite();
|
||||
platform.listen<ModelPayload[]>("model_writes", (payloads) => {
|
||||
if (payloads.some((payload) => isModelRelevant(payload.model))) syncAfterModelWrite();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { getIdentifier } from "@tauri-apps/api/app";
|
||||
import { invokeCmd } from "./tauri";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { rpc } from "./rpc";
|
||||
|
||||
export interface AppInfo {
|
||||
isDev: boolean;
|
||||
@@ -16,8 +16,8 @@ export interface AppInfo {
|
||||
}
|
||||
|
||||
export const appInfo = {
|
||||
...(await invokeCmd("cmd_metadata")),
|
||||
identifier: await getIdentifier(),
|
||||
...(await rpc("cmd_metadata")),
|
||||
identifier: await platform.appIdentifier(),
|
||||
} as AppInfo;
|
||||
|
||||
console.log("App info", appInfo);
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { clear, writeText } from "@tauri-apps/plugin-clipboard-manager";
|
||||
import { showToast } from "./toast";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
export function copyToClipboard(
|
||||
text: string | null,
|
||||
{ disableToast }: { disableToast?: boolean } = {},
|
||||
) {
|
||||
if (text == null) {
|
||||
clear().catch(console.error);
|
||||
platform.clipboard.clear().catch(console.error);
|
||||
} else {
|
||||
writeText(text).catch(console.error);
|
||||
platform.clipboard.writeText(text).catch(console.error);
|
||||
}
|
||||
|
||||
if (text !== "" && !disableToast) {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { HttpRequestHeader } from "@yaakapp-internal/models";
|
||||
import { invokeCmd } from "./tauri";
|
||||
import { rpc } from "./rpc";
|
||||
|
||||
/**
|
||||
* Global default headers fetched from the backend.
|
||||
* These are static and fetched once on module load.
|
||||
*/
|
||||
export const defaultHeaders: HttpRequestHeader[] = await invokeCmd("cmd_default_headers");
|
||||
export const defaultHeaders: HttpRequestHeader[] = await rpc("cmd_default_headers");
|
||||
|
||||
@@ -2,7 +2,7 @@ import { parseTemplate } from "@yaakapp-internal/templates";
|
||||
import { activeEnvironmentIdAtom } from "../hooks/useActiveEnvironment";
|
||||
import { activeWorkspaceIdAtom } from "../hooks/useActiveWorkspace";
|
||||
import { jotaiStore } from "./jotai";
|
||||
import { invokeCmd } from "./tauri";
|
||||
import { rpc } from "./rpc";
|
||||
|
||||
export function analyzeTemplate(template: string): "global_secured" | "local_secured" | "insecure" {
|
||||
let secureTags = 0;
|
||||
@@ -39,7 +39,7 @@ export async function convertTemplateToInsecure(template: string) {
|
||||
|
||||
const workspaceId = jotaiStore.get(activeWorkspaceIdAtom) ?? "n/a";
|
||||
const environmentId = jotaiStore.get(activeEnvironmentIdAtom) ?? null;
|
||||
return invokeCmd<string>("cmd_decrypt_template", { template, workspaceId, environmentId });
|
||||
return rpc<string>("cmd_decrypt_template", { template, workspaceId, environmentId });
|
||||
}
|
||||
|
||||
export async function convertTemplateToSecure(template: string): Promise<string> {
|
||||
@@ -53,5 +53,5 @@ export async function convertTemplateToSecure(template: string): Promise<string>
|
||||
|
||||
const workspaceId = jotaiStore.get(activeWorkspaceIdAtom) ?? "n/a";
|
||||
const environmentId = jotaiStore.get(activeEnvironmentIdAtom) ?? null;
|
||||
return invokeCmd<string>("cmd_secure_template", { template, workspaceId, environmentId });
|
||||
return rpc<string>("cmd_secure_template", { template, workspaceId, environmentId });
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import vkBeautify from "vkbeautify";
|
||||
import { invokeCmd } from "./tauri";
|
||||
import { rpc } from "./rpc";
|
||||
|
||||
export async function tryFormatJson(text: string): Promise<string> {
|
||||
if (text === "") return text;
|
||||
|
||||
try {
|
||||
const result = await invokeCmd<string>("cmd_format_json", { text });
|
||||
const result = await rpc<string>("cmd_format_json", { text });
|
||||
return result;
|
||||
} catch (err) {
|
||||
console.warn("Failed to format JSON", err);
|
||||
@@ -24,7 +24,7 @@ export async function tryFormatGraphql(text: string): Promise<string> {
|
||||
if (text === "") return text;
|
||||
|
||||
try {
|
||||
return await invokeCmd<string>("cmd_format_graphql", { text });
|
||||
return await rpc<string>("cmd_format_graphql", { text });
|
||||
} catch (err) {
|
||||
console.warn("Failed to format GraphQL", err);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { showDialog } from "./dialog";
|
||||
import { jotaiStore } from "./jotai";
|
||||
import { pluralizeCount } from "./pluralize";
|
||||
import { router } from "./router";
|
||||
import { invokeCmd } from "./tauri";
|
||||
import { rpc } from "./rpc";
|
||||
|
||||
export const importData = createFastMutation({
|
||||
mutationKey: ["import_data"],
|
||||
@@ -50,7 +50,7 @@ export const importData = createFastMutation({
|
||||
|
||||
async function performImport(filePath: string): Promise<boolean> {
|
||||
const activeWorkspace = jotaiStore.get(activeWorkspaceAtom);
|
||||
const imported = await invokeCmd<BatchUpsertResult>("cmd_import_data", {
|
||||
const imported = await rpc<BatchUpsertResult>("cmd_import_data", {
|
||||
filePath,
|
||||
workspaceId: activeWorkspace?.id,
|
||||
});
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { emit } from "@tauri-apps/api/event";
|
||||
import { openUrl } from "@tauri-apps/plugin-opener";
|
||||
import { debounce } from "@yaakapp-internal/lib";
|
||||
import type {
|
||||
FormInput,
|
||||
@@ -20,23 +18,23 @@ import { Button } from "../components/core/Button";
|
||||
import { ButtonInfiniteLoading } from "../components/core/ButtonInfiniteLoading";
|
||||
|
||||
// Listen for toasts
|
||||
import { listenToTauriEvent } from "../hooks/useListenToTauriEvent";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { updateAvailableAtom } from "./atoms";
|
||||
import { stringToColor } from "./color";
|
||||
import { generateId } from "./generateId";
|
||||
import { jotaiStore } from "./jotai";
|
||||
import { showPrompt } from "./prompt";
|
||||
import { showPromptForm } from "./prompt-form";
|
||||
import { invokeCmd } from "./tauri";
|
||||
import { rpc } from "./rpc";
|
||||
import { showToast } from "./toast";
|
||||
|
||||
export function initGlobalListeners() {
|
||||
listenToTauriEvent<ShowToastRequest>("show_toast", (event) => {
|
||||
showToast({ ...event.payload });
|
||||
platform.listen<ShowToastRequest>("show_toast", (payload) => {
|
||||
showToast({ ...payload });
|
||||
});
|
||||
|
||||
// Show errors for any plugins that failed to load during startup
|
||||
void invokeCmd<[string, string][]>("cmd_plugin_init_errors").then((errors) => {
|
||||
void rpc<[string, string][]>("cmd_plugin_init_errors").then((errors) => {
|
||||
for (const [dir, err] of errors) {
|
||||
const name = dir.split(/[/\\]/).pop() ?? dir;
|
||||
showToast({
|
||||
@@ -61,13 +59,13 @@ export function initGlobalListeners() {
|
||||
}
|
||||
});
|
||||
|
||||
listenToTauriEvent("settings", () => openSettings.mutate(null));
|
||||
platform.listen("settings", () => openSettings.mutate(null));
|
||||
|
||||
// Track active dynamic form dialogs so follow-up input updates can reach them
|
||||
const activeForms = new Map<string, (inputs: FormInput[]) => void>();
|
||||
|
||||
// Listen for plugin events
|
||||
listenToTauriEvent<InternalEvent>("plugin_event", async ({ payload: event }) => {
|
||||
platform.listen<InternalEvent>("plugin_event", async (event) => {
|
||||
if (event.payload.type === "prompt_text_request") {
|
||||
const value = await showPrompt(event.payload);
|
||||
const result: InternalEvent = {
|
||||
@@ -81,7 +79,7 @@ export function initGlobalListeners() {
|
||||
value,
|
||||
},
|
||||
};
|
||||
await emit(event.id, result);
|
||||
await platform.emit(event.id, result);
|
||||
} else if (event.payload.type === "prompt_form_request") {
|
||||
if (event.replyId != null) {
|
||||
// Follow-up update from plugin runtime — update the active dialog's inputs
|
||||
@@ -106,7 +104,7 @@ export function initGlobalListeners() {
|
||||
done,
|
||||
},
|
||||
};
|
||||
void emit(event.id, result);
|
||||
void platform.emit(event.id, result);
|
||||
};
|
||||
|
||||
const values = await showPromptForm({
|
||||
@@ -127,24 +125,24 @@ export function initGlobalListeners() {
|
||||
}
|
||||
});
|
||||
|
||||
listenToTauriEvent<string>("update_installed", async ({ payload: version }) => {
|
||||
platform.listen<string>("update_installed", async (version) => {
|
||||
console.log("Got update installed event", version);
|
||||
showUpdateInstalledToast(version);
|
||||
});
|
||||
|
||||
// Listen for update events
|
||||
listenToTauriEvent<UpdateInfo>("update_available", async ({ payload }) => {
|
||||
platform.listen<UpdateInfo>("update_available", async (payload) => {
|
||||
console.log("Got update available", payload);
|
||||
void showUpdateAvailableToast(payload);
|
||||
});
|
||||
|
||||
listenToTauriEvent<YaakNotification>("notification", ({ payload }) => {
|
||||
platform.listen<YaakNotification>("notification", (payload) => {
|
||||
console.log("Got notification event", payload);
|
||||
showNotificationToast(payload);
|
||||
});
|
||||
|
||||
// Listen for plugin update events
|
||||
listenToTauriEvent<PluginUpdateNotification>("plugin_updates_available", ({ payload }) => {
|
||||
platform.listen<PluginUpdateNotification>("plugin_updates_available", (payload) => {
|
||||
console.log("Got plugin updates event", payload);
|
||||
showPluginUpdatesToast(payload);
|
||||
});
|
||||
@@ -171,7 +169,7 @@ function showUpdateInstalledToast(version: string) {
|
||||
loadingChildren="Restarting..."
|
||||
onClick={() => {
|
||||
hide();
|
||||
setTimeout(() => invokeCmd("cmd_restart", {}), 200);
|
||||
setTimeout(() => rpc("cmd_restart", {}), 200);
|
||||
}}
|
||||
>
|
||||
Relaunch Yaak
|
||||
@@ -187,7 +185,7 @@ async function showUpdateAvailableToast(updateInfo: UpdateInfo) {
|
||||
jotaiStore.set(updateAvailableAtom, { version, downloaded });
|
||||
|
||||
// Acknowledge the event, so we don't time out and try the fallback update logic
|
||||
await emit<UpdateResponse>(replyEventId, { type: "ack" });
|
||||
await platform.emit(replyEventId, { type: "ack" } satisfies UpdateResponse);
|
||||
|
||||
showToast({
|
||||
id: UPDATE_TOAST_ID,
|
||||
@@ -209,10 +207,10 @@ async function showUpdateAvailableToast(updateInfo: UpdateInfo) {
|
||||
className="min-w-40"
|
||||
loadingChildren={downloaded ? "Installing..." : "Downloading..."}
|
||||
onClick={async () => {
|
||||
await emit<UpdateResponse>(replyEventId, {
|
||||
await platform.emit(replyEventId, {
|
||||
type: "action",
|
||||
action: "install",
|
||||
});
|
||||
} satisfies UpdateResponse);
|
||||
}}
|
||||
>
|
||||
{downloaded ? "Install Now" : "Download and Install"}
|
||||
@@ -223,7 +221,7 @@ async function showUpdateAvailableToast(updateInfo: UpdateInfo) {
|
||||
variant="border"
|
||||
rightSlot={<Icon icon="external_link" />}
|
||||
onClick={async () => {
|
||||
await openUrl(`https://yaak.app/changelog/${version}`);
|
||||
await platform.openUrl(`https://yaak.app/changelog/${version}`);
|
||||
}}
|
||||
>
|
||||
What's New
|
||||
@@ -304,7 +302,7 @@ function showNotificationToast(n: YaakNotification) {
|
||||
</VStack>
|
||||
),
|
||||
onClose: () => {
|
||||
invokeCmd("cmd_dismiss_notification", { notificationId: n.id }).catch(console.error);
|
||||
rpc("cmd_dismiss_notification", { notificationId: n.id }).catch(console.error);
|
||||
},
|
||||
action: ({ hide }) => {
|
||||
return actionLabel && actionUrl ? (
|
||||
@@ -315,7 +313,7 @@ function showNotificationToast(n: YaakNotification) {
|
||||
rightSlot={<Icon icon="external_link" />}
|
||||
onClick={() => {
|
||||
hide();
|
||||
return openUrl(actionUrl);
|
||||
return platform.openUrl(actionUrl);
|
||||
}}
|
||||
>
|
||||
{actionLabel}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { save } from "@tauri-apps/plugin-dialog";
|
||||
import { Icon } from "@yaakapp-internal/ui";
|
||||
import mime from "mime";
|
||||
import { createElement } from "react";
|
||||
@@ -7,8 +6,9 @@ import type { SniffedValue } from "../components/core/Editor/sniffValue";
|
||||
import { isEncodedRun } from "../components/core/Editor/sniffValue";
|
||||
import { copyToClipboard } from "./copy";
|
||||
import { fireAndForget } from "./fireAndForget";
|
||||
import { invokeCmd } from "./tauri";
|
||||
import { rpc } from "./rpc";
|
||||
import { showToast } from "./toast";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
/**
|
||||
* How the value is written, which is the thing worth knowing about it — that it is base64
|
||||
@@ -229,7 +229,7 @@ function toBase64(bytes: Uint8Array): string {
|
||||
*/
|
||||
export async function saveValue(text: string, sniffed: SniffedValue | null, name: string) {
|
||||
const ext = sniffed == null ? "txt" : (mime.getExtension(sniffed.mime) ?? "bin");
|
||||
const filepath = await save({ defaultPath: `${name}.${ext}`, title: "Save Value" });
|
||||
const filepath = await platform.dialog.save({ defaultPath: `${name}.${ext}`, title: "Save Value" });
|
||||
if (filepath == null) {
|
||||
return; // Cancelled
|
||||
}
|
||||
@@ -241,6 +241,6 @@ export async function saveValue(text: string, sniffed: SniffedValue | null, name
|
||||
? normalizeBase64(payloadOf(text, sniffed))
|
||||
: toBase64(decodeValue(text, sniffed));
|
||||
|
||||
await invokeCmd("cmd_save_base64_to_binary", { filepath, data });
|
||||
await rpc("cmd_save_base64_to_binary", { filepath, data });
|
||||
showToast({ message: `Saved to ${filepath}` });
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { readFile } from "@tauri-apps/plugin-fs";
|
||||
import type { HttpResponse } from "@yaakapp-internal/models";
|
||||
import type { FilterResponse } from "@yaakapp-internal/plugins";
|
||||
import type { ServerSentEvent, SseSummary } from "@yaakapp-internal/sse";
|
||||
import { candidateJsonPayloadsFromSseText, computeSseSummary } from "@yaakapp-internal/sse";
|
||||
import { invokeCmd } from "./tauri";
|
||||
import { rpc } from "./rpc";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
export async function getResponseBodyText({
|
||||
response,
|
||||
@@ -12,7 +12,7 @@ export async function getResponseBodyText({
|
||||
response: HttpResponse;
|
||||
filter: string | null;
|
||||
}): Promise<string | null> {
|
||||
const result = await invokeCmd<FilterResponse>("cmd_http_response_body", {
|
||||
const result = await rpc<FilterResponse>("cmd_http_response_body", {
|
||||
response,
|
||||
filter,
|
||||
});
|
||||
@@ -29,7 +29,7 @@ export async function getResponseBodyEventSource(
|
||||
): Promise<ServerSentEvent[]> {
|
||||
if (!response.bodyPath) return [];
|
||||
try {
|
||||
const events = await invokeCmd<ServerSentEvent[]>("cmd_get_sse_events", {
|
||||
const events = await rpc<ServerSentEvent[]>("cmd_get_sse_events", {
|
||||
filePath: response.bodyPath,
|
||||
});
|
||||
if (events.length > 0) {
|
||||
@@ -39,7 +39,7 @@ export async function getResponseBodyEventSource(
|
||||
// Fall back to raw JSON frame parsing for non-standard SSE-like responses.
|
||||
}
|
||||
|
||||
const bytes = await readFile(response.bodyPath);
|
||||
const bytes = await platform.files.readFile(response.bodyPath);
|
||||
const text = new TextDecoder("utf-8").decode(bytes);
|
||||
return candidateJsonPayloadsFromSseText(text).map((data, index) => ({
|
||||
data,
|
||||
@@ -55,7 +55,7 @@ export async function getResponseBodySseSummary(
|
||||
): Promise<SseSummary> {
|
||||
if (!response.bodyPath) return { fragmentCount: 0, summary: "" };
|
||||
|
||||
const bytes = await readFile(response.bodyPath);
|
||||
const bytes = await platform.files.readFile(response.bodyPath);
|
||||
const text = new TextDecoder("utf-8").decode(bytes);
|
||||
return computeSseSummary(text, resultKeyPath);
|
||||
}
|
||||
@@ -64,5 +64,5 @@ export async function getResponseBodyBytes(
|
||||
response: HttpResponse,
|
||||
): Promise<Uint8Array<ArrayBuffer> | null> {
|
||||
if (!response.bodyPath) return null;
|
||||
return readFile(response.bodyPath);
|
||||
return platform.files.readFile(response.bodyPath);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { type } from "@tauri-apps/plugin-os";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
|
||||
const os = type();
|
||||
const os = platform.osType();
|
||||
export const revealInFinderText =
|
||||
os === "macos"
|
||||
? "Reveal in Finder"
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { RpcPayload } from "@yaakapp-internal/platform";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import type { RpcSchema } from "@yaakapp-internal/tauri-client";
|
||||
|
||||
/**
|
||||
* Every backend command the app can call: the generated wire schema, one field
|
||||
* per `RpcRouter` registration on the Rust side. A typo'd or unregistered
|
||||
* command name is a compile error. Host plugin commands (license, fonts,
|
||||
* mac-window) don't appear here — each lives behind its own package's facade.
|
||||
*
|
||||
* `RpcSchema` also carries each command's request and response payload types;
|
||||
* adopting them at call sites is an incremental follow-up.
|
||||
*/
|
||||
type AppCmd = keyof RpcSchema;
|
||||
|
||||
/** Call a backend command. */
|
||||
export function rpc<T>(cmd: AppCmd, payload?: RpcPayload): Promise<T> {
|
||||
return platform.rpc<T>(cmd, payload);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { HttpRequest, HttpResponse } from "@yaakapp-internal/models";
|
||||
import { getActiveCookieJar } from "../hooks/useActiveCookieJar";
|
||||
import { invokeCmd } from "./tauri";
|
||||
import { rpc } from "./rpc";
|
||||
|
||||
export async function sendEphemeralRequest(
|
||||
request: HttpRequest,
|
||||
@@ -8,7 +8,7 @@ export async function sendEphemeralRequest(
|
||||
): Promise<HttpResponse> {
|
||||
// Remove some things that we don't want to associate
|
||||
const newRequest = { ...request };
|
||||
return invokeCmd("cmd_send_ephemeral_request", {
|
||||
return rpc("cmd_send_ephemeral_request", {
|
||||
request: newRequest,
|
||||
environmentId,
|
||||
cookieJarId: getActiveCookieJar()?.id,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type { Settings } from "@yaakapp-internal/models";
|
||||
import { rpc } from "./rpc";
|
||||
|
||||
export function getSettings(): Promise<Settings> {
|
||||
return invoke<Settings>("models_get_settings");
|
||||
return rpc<Settings>("models_get_settings");
|
||||
}
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import type { InvokeArgs } from "@tauri-apps/api/core";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
|
||||
type TauriCmd =
|
||||
| "cmd_call_grpc_request_action"
|
||||
| "cmd_call_http_authentication_action"
|
||||
| "cmd_call_http_request_action"
|
||||
| "cmd_call_websocket_request_action"
|
||||
| "cmd_call_workspace_action"
|
||||
| "cmd_call_folder_action"
|
||||
| "cmd_check_for_updates"
|
||||
| "cmd_curl_to_request"
|
||||
| "cmd_decrypt_template"
|
||||
| "cmd_default_headers"
|
||||
| "cmd_delete_all_grpc_connections"
|
||||
| "cmd_delete_all_http_responses"
|
||||
| "cmd_delete_send_history"
|
||||
| "cmd_dismiss_notification"
|
||||
| "cmd_export_data"
|
||||
| "cmd_format_graphql"
|
||||
| "cmd_format_json"
|
||||
| "cmd_get_http_authentication_config"
|
||||
| "cmd_get_http_authentication_summaries"
|
||||
| "cmd_get_http_response_events"
|
||||
| "cmd_get_sse_events"
|
||||
| "cmd_get_themes"
|
||||
| "cmd_get_workspace_meta"
|
||||
| "cmd_git_add_credential"
|
||||
| "cmd_git_clone"
|
||||
| "cmd_grpc_go"
|
||||
| "cmd_grpc_reflect"
|
||||
| "cmd_grpc_request_actions"
|
||||
| "cmd_http_request_actions"
|
||||
| "cmd_websocket_request_actions"
|
||||
| "cmd_workspace_actions"
|
||||
| "cmd_folder_actions"
|
||||
| "cmd_http_request_body"
|
||||
| "cmd_http_response_body"
|
||||
| "cmd_import_data"
|
||||
| "cmd_metadata"
|
||||
| "cmd_restart"
|
||||
| "cmd_new_child_window"
|
||||
| "cmd_new_main_window"
|
||||
| "cmd_plugin_info"
|
||||
| "cmd_plugin_init_errors"
|
||||
| "cmd_reload_plugins"
|
||||
| "cmd_render_template"
|
||||
| "cmd_save_base64_to_binary"
|
||||
| "cmd_save_response"
|
||||
| "cmd_secure_template"
|
||||
| "cmd_send_ephemeral_request"
|
||||
| "cmd_send_feedback"
|
||||
| "cmd_send_http_request"
|
||||
| "cmd_template_function_summaries"
|
||||
| "cmd_template_function_config"
|
||||
| "cmd_template_tokens_to_string";
|
||||
|
||||
export async function invokeCmd<T>(cmd: TauriCmd, args?: InvokeArgs): Promise<T> {
|
||||
// console.log('RUN COMMAND', cmd, args);
|
||||
try {
|
||||
return await invoke(cmd, args);
|
||||
} catch (err) {
|
||||
console.warn("Tauri command error", cmd, err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,10 @@ import {
|
||||
resolveAppearance,
|
||||
type Appearance,
|
||||
} from "@yaakapp-internal/theme";
|
||||
import { invokeCmd } from "./tauri";
|
||||
import { rpc } from "./rpc";
|
||||
|
||||
export async function getThemes() {
|
||||
const themes = (await invokeCmd<GetThemesResponse[]>("cmd_get_themes")).flatMap((t) => t.themes);
|
||||
const themes = (await rpc<GetThemesResponse[]>("cmd_get_themes")).flatMap((t) => t.themes);
|
||||
themes.sort((a, b) => a.label.localeCompare(b.label));
|
||||
// Remove duplicates, in case multiple plugins provide the same theme
|
||||
const uniqueThemes = Array.from(new Map(themes.map((t) => [t.id, t])).values());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import "./main.css";
|
||||
import { RouterProvider } from "@tanstack/react-router";
|
||||
import { type } from "@tauri-apps/plugin-os";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { changeModelStoreWorkspace, initModelStore } from "@yaakapp-internal/models";
|
||||
import { setPlatformOnDocument } from "@yaakapp-internal/theme";
|
||||
import { StrictMode } from "react";
|
||||
@@ -11,7 +11,7 @@ import { initGlobalListeners } from "./lib/initGlobalListeners";
|
||||
import { jotaiStore } from "./lib/jotai";
|
||||
import { router } from "./lib/router";
|
||||
|
||||
const osType = type();
|
||||
const osType = platform.osType();
|
||||
setPlatformOnDocument(osType);
|
||||
|
||||
window.addEventListener("keydown", (e) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { QueryClientProvider } from "@tanstack/react-query";
|
||||
import { createRootRoute, Outlet } from "@tanstack/react-router";
|
||||
import { type } from "@tauri-apps/plugin-os";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import classNames from "classnames";
|
||||
import { Provider as JotaiProvider } from "jotai";
|
||||
import { LazyMotion, MotionConfig } from "motion/react";
|
||||
@@ -46,7 +46,7 @@ function RouteComponent() {
|
||||
function Layout() {
|
||||
return (
|
||||
<div
|
||||
className={classNames("w-full h-full", type() === "linux" && "border border-border-subtle")}
|
||||
className={classNames("w-full h-full", platform.osType() === "linux" && "border border-border-subtle")}
|
||||
>
|
||||
<Outlet />
|
||||
</div>
|
||||
|
||||
+22
-35
@@ -1,36 +1,38 @@
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { type as osType } from "@tauri-apps/plugin-os";
|
||||
import { platform } from "@yaakapp-internal/platform";
|
||||
import { setWindowTheme } from "@yaakapp-internal/mac-window";
|
||||
import type { ModelPayload } from "@yaakapp-internal/models";
|
||||
import type { Appearance } from "@yaakapp-internal/theme";
|
||||
import {
|
||||
applyThemeToDocument,
|
||||
getCSSAppearance,
|
||||
getSystemAppearance,
|
||||
getWindowAppearance,
|
||||
subscribeToPreferredAppearanceChange,
|
||||
subscribeToSystemAppearanceChange,
|
||||
} from "@yaakapp-internal/theme";
|
||||
import { getSettings } from "./lib/settings";
|
||||
import { getResolvedTheme } from "./lib/themes";
|
||||
|
||||
// NOTE: CSS appearance isn't as accurate as getting it async from the window (next step), but we want
|
||||
// a good appearance guess so we're not waiting too long
|
||||
let preferredAppearance: Appearance = getInitialAppearance();
|
||||
let linuxSystemAppearanceAvailable =
|
||||
osType() === "linux" && window.__YAAK_INITIAL_APPEARANCE_SOURCE__ === "linux-system";
|
||||
// NOTE: The appearance the OS prefers (never the one the settings force). The backend
|
||||
// injects it on macOS and Linux; the CSS guess is only a fallback until the async
|
||||
// window value arrives below.
|
||||
let preferredAppearance: Appearance = getSystemAppearance() ?? getCSSAppearance();
|
||||
let configureThemeGeneration = 0;
|
||||
let windowShown = false;
|
||||
|
||||
configureThemeAndShow().catch((err) => console.log("Failed to configure theme", err));
|
||||
|
||||
subscribeToPreferredAppearanceChange(async (a) => {
|
||||
if (linuxSystemAppearanceAvailable) return;
|
||||
preferredAppearance = a;
|
||||
await configureThemeAndShow();
|
||||
});
|
||||
if (getSystemAppearance() == null) {
|
||||
// The initial appearance is only a guess, so confirm it with the window once it's available
|
||||
getWindowAppearance()
|
||||
.then(async (a) => {
|
||||
if (a === preferredAppearance) return;
|
||||
preferredAppearance = a;
|
||||
await configureThemeAndShow();
|
||||
})
|
||||
.catch((err) => console.log("Failed to get window appearance", err));
|
||||
}
|
||||
|
||||
subscribeToSystemAppearanceChange(async (a) => {
|
||||
linuxSystemAppearanceAvailable = true;
|
||||
subscribeToPreferredAppearanceChange(async (a) => {
|
||||
preferredAppearance = a;
|
||||
await configureThemeAndShow();
|
||||
});
|
||||
@@ -41,20 +43,20 @@ async function configureThemeAndShow() {
|
||||
windowShown = true;
|
||||
// To prevent theme flashing, the backend hides new windows by default, so we
|
||||
// need to show it here, after configuring the theme for the first time.
|
||||
await getCurrentWebviewWindow().show();
|
||||
await platform.window.show();
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for settings changes, the re-compute theme
|
||||
listen<ModelPayload[]>("model_writes", async (event) => {
|
||||
const relevant = event.payload.some(
|
||||
platform.listen<ModelPayload[]>("model_writes", async (payloads) => {
|
||||
const relevant = payloads.some(
|
||||
(p) =>
|
||||
p.change.type === "upsert" &&
|
||||
(p.model.model === "settings" || p.model.model === "plugin"),
|
||||
);
|
||||
if (!relevant) return;
|
||||
await configureThemeAndShow();
|
||||
}).catch(console.error);
|
||||
});
|
||||
|
||||
async function configureTheme(): Promise<boolean> {
|
||||
const generation = ++configureThemeGeneration;
|
||||
@@ -77,18 +79,3 @@ async function configureTheme(): Promise<boolean> {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function getInitialAppearance(): Appearance {
|
||||
const initialAppearance = window.__YAAK_INITIAL_APPEARANCE__;
|
||||
if (initialAppearance === "dark" || initialAppearance === "light") {
|
||||
return initialAppearance;
|
||||
}
|
||||
return getCSSAppearance();
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__YAAK_INITIAL_APPEARANCE__?: Appearance;
|
||||
__YAAK_INITIAL_APPEARANCE_SOURCE__?: "settings" | "linux-system";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,3 +170,6 @@ check the status.
|
||||
5. Never write a real secret into an environment variable on the user's behalf.
|
||||
Reference one and let them fill in the value.
|
||||
6. Verify what you built by sending it, and report the real HTTP status.
|
||||
7. If the CLI warns on stderr that a newer version is available, offer to run
|
||||
the upgrade command it prints, then re-run `yaak agent install` so this
|
||||
skill updates too.
|
||||
|
||||
@@ -585,7 +585,7 @@ async fn send_http_request_by_id(
|
||||
encryption_manager: ctx.encryption_manager.clone(),
|
||||
plugin_context: &plugin_context,
|
||||
cancelled_rx: None,
|
||||
connection_manager: None,
|
||||
connection_manager: ctx.connection_manager(),
|
||||
})
|
||||
.await;
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
use yaak_crypto::manager::EncryptionManager;
|
||||
use yaak_http::manager::HttpConnectionManager;
|
||||
use yaak_models::blob_manager::BlobManager;
|
||||
use yaak_models::client_db::ClientDb;
|
||||
use yaak_models::query_manager::QueryManager;
|
||||
@@ -31,6 +32,7 @@ pub struct CliContext {
|
||||
query_manager: QueryManager,
|
||||
blob_manager: BlobManager,
|
||||
pub encryption_manager: Arc<EncryptionManager>,
|
||||
connection_manager: Arc<HttpConnectionManager>,
|
||||
plugin_manager: Option<Arc<PluginManager>>,
|
||||
plugin_event_bridge: Mutex<Option<CliPluginEventBridge>>,
|
||||
}
|
||||
@@ -54,6 +56,7 @@ impl CliContext {
|
||||
query_manager,
|
||||
blob_manager,
|
||||
encryption_manager,
|
||||
connection_manager: Arc::new(HttpConnectionManager::new()),
|
||||
plugin_manager: None,
|
||||
plugin_event_bridge: Mutex::new(None),
|
||||
}
|
||||
@@ -91,6 +94,7 @@ impl CliContext {
|
||||
self.query_manager.clone(),
|
||||
self.blob_manager.clone(),
|
||||
self.encryption_manager.clone(),
|
||||
self.connection_manager.clone(),
|
||||
self.data_dir.clone(),
|
||||
execution_context,
|
||||
)
|
||||
@@ -120,6 +124,10 @@ impl CliContext {
|
||||
&self.blob_manager
|
||||
}
|
||||
|
||||
pub fn connection_manager(&self) -> &HttpConnectionManager {
|
||||
&self.connection_manager
|
||||
}
|
||||
|
||||
pub fn plugin_manager(&self) -> Arc<PluginManager> {
|
||||
self.plugin_manager.clone().expect("Plugin manager was not initialized for this command")
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ use yaak::render::{render_grpc_request, render_http_request};
|
||||
use yaak::send::{SendHttpRequestWithPluginsParams, send_http_request_with_plugins};
|
||||
use yaak_crypto::manager::EncryptionManager;
|
||||
use yaak_http::cookies::get_cookie_value_from_jar;
|
||||
use yaak_http::manager::HttpConnectionManager;
|
||||
use yaak_models::blob_manager::BlobManager;
|
||||
use yaak_models::models::Environment;
|
||||
use yaak_models::queries::any_request::AnyRequest;
|
||||
@@ -42,6 +43,7 @@ struct CliHostContext {
|
||||
blob_manager: BlobManager,
|
||||
plugin_manager: Arc<PluginManager>,
|
||||
encryption_manager: Arc<EncryptionManager>,
|
||||
connection_manager: Arc<HttpConnectionManager>,
|
||||
response_dir: PathBuf,
|
||||
execution_context: CliExecutionContext,
|
||||
}
|
||||
@@ -52,6 +54,7 @@ impl CliPluginEventBridge {
|
||||
query_manager: QueryManager,
|
||||
blob_manager: BlobManager,
|
||||
encryption_manager: Arc<EncryptionManager>,
|
||||
connection_manager: Arc<HttpConnectionManager>,
|
||||
data_dir: PathBuf,
|
||||
execution_context: CliExecutionContext,
|
||||
) -> Self {
|
||||
@@ -63,6 +66,7 @@ impl CliPluginEventBridge {
|
||||
blob_manager,
|
||||
plugin_manager,
|
||||
encryption_manager,
|
||||
connection_manager,
|
||||
response_dir: data_dir.join("responses"),
|
||||
execution_context,
|
||||
});
|
||||
@@ -214,7 +218,7 @@ async fn build_plugin_reply(
|
||||
encryption_manager: host_context.encryption_manager.clone(),
|
||||
plugin_context: &plugin_context,
|
||||
cancelled_rx: None,
|
||||
connection_manager: None,
|
||||
connection_manager: &host_context.connection_manager,
|
||||
})
|
||||
.await
|
||||
{
|
||||
|
||||
@@ -47,6 +47,8 @@ struct VersionCheckRequest<'a> {
|
||||
install_source: String,
|
||||
platform: &'a str,
|
||||
arch: &'a str,
|
||||
// False when stdout is piped, e.g. a coding agent driving the CLI
|
||||
interactive: bool,
|
||||
}
|
||||
|
||||
pub async fn maybe_check_for_updates() {
|
||||
@@ -102,11 +104,7 @@ fn should_skip_check() -> bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
if std::env::var("CI").is_ok() {
|
||||
return true;
|
||||
}
|
||||
|
||||
!std::io::stdout().is_terminal()
|
||||
std::env::var("CI").is_ok()
|
||||
}
|
||||
|
||||
async fn fetch_version_check() -> Option<VersionCheckResponse> {
|
||||
@@ -118,6 +116,7 @@ async fn fetch_version_check() -> Option<VersionCheckResponse> {
|
||||
install_source: install_source(),
|
||||
platform: std::env::consts::OS,
|
||||
arch: std::env::consts::ARCH,
|
||||
interactive: std::io::stdout().is_terminal(),
|
||||
};
|
||||
|
||||
let client = yaak_api_client(ApiClientKind::Cli, current_version).ok()?;
|
||||
|
||||
@@ -9,7 +9,7 @@ use log::warn;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use ts_rs::TS;
|
||||
use yaak_database::{ModelChangeEvent, UpdateSource};
|
||||
use yaak_proxy::{CapturedRequest, ProxyEvent, ProxyHandle, RequestState};
|
||||
@@ -17,15 +17,17 @@ use yaak_rpc::{RpcError, RpcEventEmitter, define_rpc};
|
||||
|
||||
// -- Context --
|
||||
|
||||
// Cloned once per dispatched command, so shared state lives behind an `Arc`.
|
||||
#[derive(Clone)]
|
||||
pub struct ProxyCtx {
|
||||
handle: Mutex<Option<ProxyHandle>>,
|
||||
handle: Arc<Mutex<Option<ProxyHandle>>>,
|
||||
pub db: ProxyQueryManager,
|
||||
pub events: RpcEventEmitter,
|
||||
}
|
||||
|
||||
impl ProxyCtx {
|
||||
pub fn new(db_path: &Path, events: RpcEventEmitter) -> Self {
|
||||
Self { handle: Mutex::new(None), db: ProxyQueryManager::new(db_path), events }
|
||||
Self { handle: Arc::new(Mutex::new(None)), db: ProxyQueryManager::new(db_path), events }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -72,6 +72,7 @@ tokio-tungstenite = { version = "0.26.2", default-features = false }
|
||||
url = "2"
|
||||
tokio-util = { version = "0.7", features = ["codec"] }
|
||||
ts-rs = { workspace = true }
|
||||
yaak-rpc = { workspace = true }
|
||||
uuid = "1.12.1"
|
||||
yaak-api = { workspace = true }
|
||||
yaak-common = { workspace = true }
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user