mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-11-20 15:31:37 +01:00
Merge main into feat/request-versioning
Conflicts were all at registration points; both sides are kept. Main now routes every write through one connection (#642): ClientDb only reads and writes go through `with_tx` on a WriteDb. Versioning follows: snapshot, restore, prune and the cascade delete move to WriteDb, while the lookups and the "has it changed" check stay on ClientDb. Callers take a write transaction the way their neighbours do: - The HTTP send snapshots in its own transaction from `resolve_send_inputs`, and a failure there (including not getting the writer) is still logged and swallowed, so the response just has no version. - gRPC and WebSocket connect snapshot inside the transaction that upserts the connection. - The snapshot and restore RPCs, on the desktop and in the browser host, each run in a transaction. - The request and workspace cascades live on main's WriteDb deletes. The Request Changed dropdown moves into the response pane's `statusLineRight` slot, since main moved the status line into the shared pane view. The plugin runtime's copy of the model bindings picks up `versionId`, and `gen_rpc.ts` is regenerated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
1b0a196c50
794 files changed
+76953
-18061
No files matched your search
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { contentTypeCharset, decodeBodyText, strictUtf8Text } from "./decodeBodyText";
|
||||
|
||||
const latin1 = (text: string) => Uint8Array.from(text, (c) => c.charCodeAt(0));
|
||||
// "こんにちは、世界" in Shift_JIS
|
||||
const shiftJis = new Uint8Array([
|
||||
0x82, 0xb1, 0x82, 0xf1, 0x82, 0xc9, 0x82, 0xbf, 0x82, 0xcd, 0x81, 0x41, 0x90, 0xa2, 0x8a, 0x45,
|
||||
]);
|
||||
const french = "Accès refusé : vous n'avez pas l'autorisation d'accéder à cette page.";
|
||||
|
||||
describe("decodeBodyText", () => {
|
||||
test("decodes in the charset the content type names", () => {
|
||||
const body = latin1(french);
|
||||
expect(decodeBodyText(body, "text/html; charset=iso-8859-1")).toBe(french);
|
||||
expect(decodeBodyText(body, 'text/plain; CHARSET="ISO-8859-1"')).toBe(french);
|
||||
expect(decodeBodyText(shiftJis, "text/plain; charset=Shift_JIS")).toBe("こんにちは、世界");
|
||||
});
|
||||
|
||||
test("reads an unlabeled body that isn't UTF-8 as windows-1252", () => {
|
||||
expect(decodeBodyText(latin1(french), "text/html")).toBe(french);
|
||||
expect(decodeBodyText(latin1(french), null)).toBe(french);
|
||||
expect(decodeBodyText(new Uint8Array([0x93, 0x68, 0x69, 0x94]), null)).toBe("“hi”");
|
||||
});
|
||||
|
||||
test("reads UTF-8 as UTF-8, labeled or not", () => {
|
||||
const utf8 = new TextEncoder().encode(`{"city":"Zürich","greeting":"こんにちは"}`);
|
||||
const text = `{"city":"Zürich","greeting":"こんにちは"}`;
|
||||
expect(decodeBodyText(utf8, null)).toBe(text);
|
||||
expect(decodeBodyText(utf8, "application/json")).toBe(text);
|
||||
expect(decodeBodyText(utf8, "application/json; charset=utf-8")).toBe(text);
|
||||
// A body labeled UTF-8 stays UTF-8, with what isn't replaced, as before
|
||||
expect(decodeBodyText(new Uint8Array([0x61, 0xff]), "text/plain; charset=utf-8")).toBe("a�");
|
||||
});
|
||||
|
||||
test("treats a charset TextDecoder doesn't know as no charset", () => {
|
||||
expect(contentTypeCharset("text/plain; charset=not-a-charset")).toBeNull();
|
||||
expect(decodeBodyText(latin1(french), "text/plain; charset=not-a-charset")).toBe(french);
|
||||
});
|
||||
|
||||
test("keeps a truncated UTF-8 body UTF-8 when it ends partway through a character", () => {
|
||||
const cut = new TextEncoder().encode("abc€").subarray(0, 5);
|
||||
expect(strictUtf8Text(cut)).toBeNull();
|
||||
expect(decodeBodyText(cut, null, { truncated: true })).toBe("abc");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* The charset a content type names, as `TextDecoder` calls it (`windows-1252` for
|
||||
* `iso-8859-1`), or null when it names none or one `TextDecoder` doesn't know.
|
||||
*/
|
||||
export function contentTypeCharset(contentType: string | null): string | null {
|
||||
const label = contentType?.match(/;\s*charset\s*=\s*"?([^";\s]+)"?/i)?.[1];
|
||||
if (label == null) return null;
|
||||
try {
|
||||
return new TextDecoder(label).encoding;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The bytes as UTF-8, or null when they aren't valid UTF-8. A truncated body may end partway
|
||||
* through a character, so up to three trailing bytes are dropped before giving up on it.
|
||||
*/
|
||||
export function strictUtf8Text(bytes: Uint8Array, truncated = false): string | null {
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
const maxTrim = truncated ? Math.min(3, bytes.length) : 0;
|
||||
for (let trim = 0; trim <= maxTrim; trim++) {
|
||||
try {
|
||||
return decoder.decode(bytes.subarray(0, bytes.length - trim));
|
||||
} catch {
|
||||
// Try again without the last byte
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A body's text in the charset its content type names. Without one it is UTF-8, unless the
|
||||
* bytes aren't valid UTF-8, when it is windows-1252, as browsers read unlabeled text.
|
||||
*/
|
||||
export function decodeBodyText(
|
||||
bytes: Uint8Array,
|
||||
contentType: string | null,
|
||||
{ truncated = false }: { truncated?: boolean } = {},
|
||||
): string {
|
||||
const charset = contentTypeCharset(contentType);
|
||||
if (charset != null) return new TextDecoder(charset).decode(bytes);
|
||||
return strictUtf8Text(bytes, truncated) ?? new TextDecoder("windows-1252").decode(bytes);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { customAlphabet } from "nanoid";
|
||||
|
||||
const nanoid = customAlphabet("023456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ", 10);
|
||||
|
||||
export function generateId(): string {
|
||||
return nanoid();
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
export * from "./debounce";
|
||||
export * from "./decodeBodyText";
|
||||
export * from "./eagerDebounceAsync";
|
||||
export * from "./formatSize";
|
||||
export * from "./templateFunction";
|
||||
@@ -0,0 +1,39 @@
|
||||
/** Literal steps into a JSON response, distinct from JSONPath operators. */
|
||||
export type JsonPathSegment =
|
||||
| { readonly kind: "key"; readonly key: string }
|
||||
| { readonly kind: "index"; readonly index: number };
|
||||
|
||||
const PATH_SEGMENT = /^(?:\.([A-Za-z_$][A-Za-z0-9_$]*)|\[(0|[1-9]\d*)\]|\[("(?:[^"\\]|\\.)*")\])/;
|
||||
|
||||
/**
|
||||
* Parse a single location with JSON-quoted keys (`$.a[0]["b.c"]`). Other
|
||||
* JSONPath expressions belong to the filter engine, not to the breadcrumb trail.
|
||||
*/
|
||||
export function jsonPathToSegments(path: string): JsonPathSegment[] | null {
|
||||
let rest = path.trim();
|
||||
if (!rest.startsWith("$")) return null;
|
||||
rest = rest.slice(1);
|
||||
|
||||
const segments: JsonPathSegment[] = [];
|
||||
while (rest.length > 0) {
|
||||
const match = PATH_SEGMENT.exec(rest);
|
||||
if (match == null) return null;
|
||||
const [whole, bareKey, index, quotedKey] = match;
|
||||
if (bareKey != null) {
|
||||
if (bareKey === "$") return null; // The library's root operator, not a literal key.
|
||||
segments.push({ kind: "key", key: bareKey });
|
||||
} else if (index != null) {
|
||||
const value = Number(index);
|
||||
if (!Number.isSafeInteger(value)) return null;
|
||||
segments.push({ kind: "index", index: value });
|
||||
} else if (quotedKey != null) {
|
||||
try {
|
||||
segments.push({ kind: "key", key: JSON.parse(quotedKey) as string });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
rest = rest.slice(whole.length);
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
export function pluralize(word: string, count: number): string {
|
||||
if (count === 1) {
|
||||
return word;
|
||||
}
|
||||
return `${word}s`;
|
||||
}
|
||||
|
||||
export function pluralizeCount(
|
||||
word: string,
|
||||
count: number,
|
||||
opt: { omitSingle?: boolean; noneWord?: string } = {},
|
||||
): string {
|
||||
if (opt.omitSingle && count === 1) {
|
||||
return word;
|
||||
}
|
||||
if (opt.noneWord && count === 0) {
|
||||
return opt.noneWord;
|
||||
}
|
||||
return `${count} ${pluralize(word, count)}`;
|
||||
}
|
||||
@@ -13,11 +13,11 @@
|
||||
"@yaakapp-internal/rpc-schema": "^1.0.0",
|
||||
"@yaakapp-internal/web": "^1.0.0",
|
||||
"@yaakapp-internal/wasm": "^1.0.0",
|
||||
"@tauri-apps/api": "^2.11.0",
|
||||
"@tauri-apps/plugin-clipboard-manager": "^2.3.2",
|
||||
"@tauri-apps/plugin-dialog": "^2.7.1",
|
||||
"@tauri-apps/plugin-fs": "^2.5.1",
|
||||
"@tauri-apps/plugin-opener": "^2.5.4",
|
||||
"@tauri-apps/plugin-os": "^2.3.2"
|
||||
"@tauri-apps/api": "^2.12.4",
|
||||
"@tauri-apps/plugin-clipboard-manager": "^2.5.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.8.4",
|
||||
"@tauri-apps/plugin-fs": "^2.7.1",
|
||||
"@tauri-apps/plugin-opener": "^2.7.2",
|
||||
"@tauri-apps/plugin-os": "^2.4.0"
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,9 @@ function host(): Platform {
|
||||
* and cannot be made to wait.
|
||||
*/
|
||||
export const platform: Platform = {
|
||||
get httpProxyUrl() {
|
||||
return host().httpProxyUrl;
|
||||
},
|
||||
get capabilities() {
|
||||
return host().capabilities;
|
||||
},
|
||||
|
||||
@@ -4,7 +4,7 @@ import { emit as tauriEmit, listen as tauriListen } from "@tauri-apps/api/event"
|
||||
import { basename, resolveResource } from "@tauri-apps/api/path";
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { clear, readText, writeText } from "@tauri-apps/plugin-clipboard-manager";
|
||||
import { open, save } from "@tauri-apps/plugin-dialog";
|
||||
import { open, save as saveDialog } from "@tauri-apps/plugin-dialog";
|
||||
import { readDir, readFile, readTextFile } from "@tauri-apps/plugin-fs";
|
||||
import { openUrl, revealItemInDir } from "@tauri-apps/plugin-opener";
|
||||
import { type as osType } from "@tauri-apps/plugin-os";
|
||||
@@ -67,6 +67,7 @@ const ALL_CAPABILITIES: PlatformCapabilities = {
|
||||
clipboardRead: true,
|
||||
systemFonts: true,
|
||||
license: true,
|
||||
agents: true,
|
||||
};
|
||||
|
||||
function createWindow(): PlatformWindow {
|
||||
@@ -119,11 +120,25 @@ function storedBodyPath(id: string): Promise<string | null> {
|
||||
return rpc<string | null>("cmd_http_response_body_path", { responseId: id });
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64 for the trip over IPC, in chunks so a few megabytes don't blow the
|
||||
* argument limit. The engine's write command speaks base64; only this host has
|
||||
* to care.
|
||||
*/
|
||||
function toBase64(bytes: Uint8Array): string {
|
||||
let binary = "";
|
||||
for (let i = 0; i < bytes.length; i += 0x8000) {
|
||||
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
export function createTauriPlatform(): Platform {
|
||||
const window = createWindow();
|
||||
|
||||
return {
|
||||
capabilities: ALL_CAPABILITIES,
|
||||
httpProxyUrl: null,
|
||||
window,
|
||||
|
||||
clipboard: {
|
||||
@@ -135,7 +150,7 @@ export function createTauriPlatform(): Platform {
|
||||
dialog: {
|
||||
// Overloaded on the interface; one implementation covers both shapes.
|
||||
open: ((options?: OpenDialogOptions) => open(options)) as Platform["dialog"]["open"],
|
||||
save: (options) => save(options ?? {}),
|
||||
save: (options) => saveDialog(options ?? {}),
|
||||
},
|
||||
|
||||
files: {
|
||||
@@ -144,6 +159,18 @@ export function createTauriPlatform(): Platform {
|
||||
url: (path) => convertFileSrc(path),
|
||||
basename: (path) => basename(path),
|
||||
resolveResource: (path) => resolveResource(path),
|
||||
|
||||
async save(suggestedName, content, filters) {
|
||||
const path = await saveDialog({ defaultPath: suggestedName, filters });
|
||||
if (path == null) return null;
|
||||
// Not the fs plugin: its ACL is read-only and scoped to the app's own
|
||||
// directories, and a path the user just picked is neither. The engine
|
||||
// writes it, which is where the desktop has always written it — and it
|
||||
// speaks base64, so content that is already base64 goes straight over.
|
||||
const data = content instanceof Uint8Array ? toBase64(content) : content.base64;
|
||||
await rpc("cmd_save_base64_to_binary", { filepath: path, data });
|
||||
return path;
|
||||
},
|
||||
},
|
||||
|
||||
blobs: {
|
||||
|
||||
@@ -40,6 +40,17 @@ export interface RpcStreamHandle<T> {
|
||||
unlisten: Unsubscribe;
|
||||
}
|
||||
|
||||
/**
|
||||
* What to save: the bytes, or base64 of them for a caller that already has it
|
||||
* that way.
|
||||
*
|
||||
* Both forms exist because both hosts want a different one, and a value that
|
||||
* arrives base64 should not be decoded and re-encoded to get back where it
|
||||
* started. Whichever a caller has is the one to pass; each host converts only
|
||||
* when it has to.
|
||||
*/
|
||||
export type SaveContent = Uint8Array | { base64: string };
|
||||
|
||||
export interface DialogFilter {
|
||||
name: string;
|
||||
extensions: string[];
|
||||
@@ -157,6 +168,25 @@ export interface PlatformFiles {
|
||||
|
||||
/** Resolve a path bundled with the app itself, rather than one from the backend. */
|
||||
resolveResource(path: string): Promise<string>;
|
||||
|
||||
/**
|
||||
* Put bytes somewhere the user chooses. Returns where they went — a path, a
|
||||
* filename, whatever this host can say — or null if the user backed out.
|
||||
*
|
||||
* The caller supplies the bytes, which is the whole point: the alternative
|
||||
* shape, where a dialog mints a path and a separate backend command writes to
|
||||
* it, can only work on a host that has both a filesystem and a backend. A tab
|
||||
* has neither, so every one of those call sites was a dead control. Whoever
|
||||
* produces the bytes already knows what they are; the host only has to know
|
||||
* where they go.
|
||||
*
|
||||
* `suggestedName` is what the save dialog opens with, extension included.
|
||||
*/
|
||||
save(
|
||||
suggestedName: string,
|
||||
content: SaveContent,
|
||||
filters?: DialogFilter[],
|
||||
): Promise<string | null>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -186,6 +216,8 @@ export interface PlatformBlobs {
|
||||
|
||||
export interface Platform {
|
||||
readonly capabilities: PlatformCapabilities;
|
||||
/** Web request relay, or null when this host executes requests itself. */
|
||||
readonly httpProxyUrl: string | null;
|
||||
readonly window: PlatformWindow;
|
||||
readonly clipboard: PlatformClipboard;
|
||||
readonly dialog: PlatformDialog;
|
||||
@@ -281,6 +313,8 @@ export interface PlatformCapabilities {
|
||||
systemFonts: boolean;
|
||||
/** Commercial licence activation. */
|
||||
license: boolean;
|
||||
/** Connecting local AI agents through the Yaak CLI on this machine. */
|
||||
agents: boolean;
|
||||
}
|
||||
|
||||
export type CapabilityName = keyof PlatformCapabilities;
|
||||
@@ -5,10 +5,11 @@ model layer — `yaak-models`, SQLite included — runs compiled to wasm inside
|
||||
worker the tab talks to, so a browser stores exactly what a desktop install
|
||||
stores, migrations and all.
|
||||
|
||||
Select it at build time and run the frontend alone:
|
||||
Select it at build time. `vp run web:dev` does that and starts the send server
|
||||
alongside the frontend:
|
||||
|
||||
```shell
|
||||
YAAK_TARGET=web npm run dev --workspace @yaakapp/yaak-client
|
||||
vp run web:dev
|
||||
```
|
||||
|
||||
The flag resolves `@yaakapp-internal/platform` to `../index.web.ts`, which
|
||||
@@ -30,17 +31,17 @@ tab (index.ts, commands.ts) ──MessagePort──▶ worker.ts ──▶ @yaak
|
||||
◀── NDJSON: events, response, body, cookies ──
|
||||
```
|
||||
|
||||
| File | What it is |
|
||||
| --- | --- |
|
||||
| `index.ts` | The `Platform` implementation. |
|
||||
| `commands.ts` | The command table: model commands forward to the worker; the rest is fixed answers and refusals-with-a-reason. |
|
||||
| `connection.ts` | A tab's end of the wire: request/response over a `MessagePort`, event delivery, and the tab's identity (`label`). |
|
||||
| `send.ts` | Sending: the worker renders (`prepare_http_send`), the server executes, this file stores what comes back where the desktop stores it. |
|
||||
| `server.ts` | Where the Yaak server is, and the wire shapes it speaks (generated from `crates-server/yaak-web/src/wire.rs`). |
|
||||
| `worker.ts` | The process that owns the database. Loads the wasm, opens the DB once, answers each port, fans `model_writes` out to every port. |
|
||||
| `protocol.ts` | The message shapes both sides import. |
|
||||
| `errors.ts` | `UnsupportedCommandError`, the structured refusal. |
|
||||
| `storage.ts` | `navigator.storage.persist()`. |
|
||||
| File | What it is |
|
||||
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `index.ts` | The `Platform` implementation. |
|
||||
| `commands.ts` | The command table: model commands forward to the worker; the rest is fixed answers and refusals-with-a-reason. |
|
||||
| `connection.ts` | A tab's end of the wire: request/response over a `MessagePort`, event delivery, and the tab's identity (`label`). |
|
||||
| `send.ts` | Sending: the worker renders (`prepare_http_send`), the server executes, this file stores what comes back where the desktop stores it. |
|
||||
| `server.ts` | Where the Yaak server is, and the wire shapes it speaks (generated from `crates-server/yaak-web/src/wire.rs`). |
|
||||
| `worker.ts` | The process that owns the database. Loads the wasm, opens the DB once, answers each port, fans `model_writes` out to every port. |
|
||||
| `protocol.ts` | The message shapes both sides import. |
|
||||
| `errors.ts` | `UnsupportedCommandError`, the structured refusal. |
|
||||
| `storage.ts` | `navigator.storage.persist()`. |
|
||||
|
||||
The Rust side is `crates/yaak-wasm` (`@yaakapp-internal/wasm`): `boot()`,
|
||||
`rpc(cmd, payload, label)` returning `{ result, events }`, blob get/put, and
|
||||
@@ -70,7 +71,7 @@ Behaviours worth knowing before changing anything:
|
||||
store's echo handling is unchanged.
|
||||
- **Cascade rules, duplicate naming, id generation, serde defaults, and the
|
||||
lazy first-run bootstrap are all the Rust code's.** Nothing about what a
|
||||
model *is* is decided in TypeScript.
|
||||
model _is_ is decided in TypeScript.
|
||||
- **Persistence is `relaxed-idb`**: SQLite pages live in IndexedDB, writes land
|
||||
in memory and flush shortly after. A tab closing mid-flush loses at most the
|
||||
last few writes.
|
||||
@@ -82,14 +83,14 @@ Behaviours worth knowing before changing anything:
|
||||
|
||||
### Implemented (32)
|
||||
|
||||
| Group | Commands |
|
||||
| --- | --- |
|
||||
| Models | `models_workspace_models`, `models_upsert`, `models_delete`, `models_duplicate`, `models_get_settings`, `models_get_graphql_introspection`, `models_upsert_graphql_introspection`, `models_grpc_events`, `models_websocket_events` |
|
||||
| Sending | `cmd_send_http_request` (through the Yaak server; see below) |
|
||||
| App | `cmd_metadata`, `cmd_get_workspace_meta`, `cmd_default_headers`, `cmd_get_themes`, `cmd_check_for_updates`, `cmd_dismiss_notification`, `cmd_plugin_init_errors` |
|
||||
| Bodies | `cmd_http_response_body`, `cmd_http_response_body_path`, `cmd_http_request_body`, `cmd_get_http_response_events`, `cmd_get_sse_events` |
|
||||
| Group | Commands |
|
||||
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Models | `models_workspace_models`, `models_upsert`, `models_delete`, `models_duplicate`, `models_get_settings`, `models_get_graphql_introspection`, `models_upsert_graphql_introspection`, `models_grpc_events`, `models_websocket_events` |
|
||||
| Sending | `cmd_send_http_request` (through the Yaak server; see below) |
|
||||
| App | `cmd_metadata`, `cmd_get_workspace_meta`, `cmd_default_headers`, `cmd_get_themes`, `cmd_check_for_updates`, `cmd_dismiss_notification`, `cmd_plugin_init_errors` |
|
||||
| Bodies | `cmd_http_response_body`, `cmd_http_response_body_path`, `cmd_http_request_body`, `cmd_get_http_response_events`, `cmd_get_sse_events` |
|
||||
| Plugin surfaces (empty results) | `cmd_http_request_actions`, `cmd_websocket_request_actions`, `cmd_grpc_request_actions`, `cmd_workspace_actions`, `cmd_folder_actions`, `cmd_template_function_summaries`, `cmd_get_http_authentication_summaries`, `cmd_get_http_authentication_config` |
|
||||
| Text | `cmd_format_json`, `cmd_render_template` |
|
||||
| Text | `cmd_format_json`, `cmd_render_template` |
|
||||
|
||||
Some of these answer honestly rather than fully, and the difference matters:
|
||||
|
||||
@@ -112,15 +113,15 @@ Each returns an `UnsupportedCommandError` carrying `cmd`, a user-facing
|
||||
`message`, and the `capability` a caller should have checked. The UI turns it
|
||||
into a toast.
|
||||
|
||||
| Reason | Commands |
|
||||
| --- | --- |
|
||||
| Sending, the parts not wired yet | `cmd_send_ephemeral_request`, `cmd_delete_send_history`, `cmd_delete_all_http_responses`, `cmd_import_url` |
|
||||
| No plugin runtime | `cmd_reload_plugins`, `cmd_plugin_info`, `cmd_plugins_search`, `cmd_plugins_install`, `cmd_plugins_install_from_directory`, `cmd_plugins_uninstall`, `cmd_plugins_updates`, `cmd_plugins_update_all`, `cmd_template_function_config`, `cmd_template_tokens_to_string`, `cmd_call_http_request_action`, `cmd_call_websocket_request_action`, `cmd_call_grpc_request_action`, `cmd_call_workspace_action`, `cmd_call_folder_action`, `cmd_call_http_authentication_action`, `cmd_curl_to_request`, `cmd_format_graphql` |
|
||||
| No filesystem | `cmd_import_data`, `cmd_export_data`, `cmd_save_response`, `cmd_save_base64_to_binary` |
|
||||
| Needs a real socket | `cmd_grpc_reflect`, `cmd_grpc_go`, `cmd_delete_all_grpc_connections`, `cmd_ws_connect`, `cmd_ws_send`, `cmd_ws_close`, `cmd_ws_delete_connections` |
|
||||
| Workspace encryption | `cmd_enable_encryption`, `cmd_disable_encryption`, `cmd_reveal_workspace_key`, `cmd_set_workspace_key`, `cmd_secure_template`, `cmd_decrypt_template` |
|
||||
| One tab, no windows | `cmd_new_child_window`, `cmd_new_main_window`, `cmd_restart` |
|
||||
| Other | `cmd_send_feedback` |
|
||||
| Reason | Commands |
|
||||
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Sending, the parts not wired yet | `cmd_send_ephemeral_request`, `cmd_delete_send_history`, `cmd_delete_all_http_responses`, `cmd_import_url` |
|
||||
| No plugin runtime | `cmd_reload_plugins`, `cmd_plugin_info`, `cmd_plugins_search`, `cmd_plugins_install`, `cmd_plugins_install_from_directory`, `cmd_plugins_uninstall`, `cmd_plugins_updates`, `cmd_plugins_update_all`, `cmd_template_function_config`, `cmd_template_tokens_to_string`, `cmd_call_http_request_action`, `cmd_call_websocket_request_action`, `cmd_call_grpc_request_action`, `cmd_call_workspace_action`, `cmd_call_folder_action`, `cmd_call_http_authentication_action`, `cmd_curl_to_request`, `cmd_format_graphql` |
|
||||
| No filesystem | `cmd_import_data`, `cmd_export_data`, `cmd_save_response`, `cmd_save_base64_to_binary` |
|
||||
| Needs a real socket | `cmd_grpc_reflect`, `cmd_grpc_go`, `cmd_delete_all_grpc_connections`, `cmd_ws_connect`, `cmd_ws_send`, `cmd_ws_close`, `cmd_ws_delete_connections` |
|
||||
| Workspace encryption | `cmd_enable_encryption`, `cmd_disable_encryption`, `cmd_reveal_workspace_key`, `cmd_set_workspace_key`, `cmd_secure_template`, `cmd_decrypt_template` |
|
||||
| One tab, no windows | `cmd_new_child_window`, `cmd_new_main_window`, `cmd_restart` |
|
||||
| Other | `cmd_send_feedback` |
|
||||
|
||||
### Refused generically (34)
|
||||
|
||||
@@ -136,14 +137,14 @@ should be able to see which.
|
||||
|
||||
Reported honestly, so callers gate on the question rather than on the host:
|
||||
|
||||
| True | False |
|
||||
| --- | --- |
|
||||
| True | False |
|
||||
| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `httpSending`, `timeline`, `cookieJar` | `grpc`, `websocket`, `git`, `sync`, `tlsOptions`, `localFiles`, `multiWindow`, `windowChrome`, `interfaceZoom`, `plugins`, `encryption`, `updater`, `clipboardRead`, `systemFonts`, `license` |
|
||||
|
||||
`interfaceZoom: false` leaves Cmd/Ctrl `+`, `-` and `0` to the browser instead
|
||||
of swallowing them, and drops those three rows from the hotkeys screen.
|
||||
|
||||
`multiWindow: false` means the host cannot open a *second window* on demand —
|
||||
`multiWindow: false` means the host cannot open a _second window_ on demand —
|
||||
what `cmd_new_child_window` does for Settings and workspace switching. It is not
|
||||
a claim that nothing else is looking: other tabs may well be open on the same
|
||||
worker, and it pushes every write to all of them regardless.
|
||||
@@ -159,7 +160,7 @@ for the desktop's window label. The worker fans each write out to every
|
||||
connected tab, and the receiving tab's store applies or ignores it exactly as a
|
||||
desktop window would.
|
||||
|
||||
The label is deliberately *not* kept in `sessionStorage`: duplicating a tab
|
||||
The label is deliberately _not_ kept in `sessionStorage`: duplicating a tab
|
||||
copies session storage, and two tabs sharing one identity would each mistake the
|
||||
other's writes for an echo of their own and drop them.
|
||||
|
||||
@@ -207,7 +208,7 @@ network half of a send runs on a small stateless server,
|
||||
|
||||
**What sends today:** any saved request whose templates are variables and whose
|
||||
authentication is none, or an inline header. Sending a request that needs a
|
||||
template *function* (`${[ timestamp() ]}`) or an authentication plugin (bearer,
|
||||
template _function_ (`${[ timestamp() ]}`) or an authentication plugin (bearer,
|
||||
basic, OAuth, …) is refused before anything leaves the tab, with a message naming
|
||||
what it needs; those light up when plugins run in the browser. Requests with a
|
||||
file body or multipart file fields are refused by the server (it has no access to
|
||||
@@ -217,11 +218,11 @@ private ranges outright — that is what the desktop app is for. A self-hosted
|
||||
server on your own network can be started with `--allow-private-networks`, which
|
||||
is the one case where those addresses are the user's to reach.
|
||||
|
||||
**Where the tab sends** (`server.ts`): a production build posts to `/v1/http/send`
|
||||
on its own origin, because the server can serve the app itself
|
||||
(`yaak-web --serve dist/apps/yaak-client`, which is what the
|
||||
`ghcr.io/mountain-loop/yaak-web` image runs) — same origin, so no CORS and
|
||||
nothing to configure. A dev build falls back to `http://127.0.0.1:9227`, since
|
||||
the Vite server is a different origin and serves no `/v1`; run one with
|
||||
`cargo run -p yaak-web`. `VITE_YAAK_WEB_URL` overrides both, for a
|
||||
deployment that keeps the app and the server apart.
|
||||
**Where the tab sends** (`server.ts`): its own origin, in development as well as
|
||||
production, so there is no address to learn and no CORS in the loop. A
|
||||
production build is served by the sender itself (`yaak-web --serve
|
||||
dist/apps/yaak-client`, which is what the `ghcr.io/mountain-loop/yaak-web`
|
||||
image runs). In development the Vite server passes `/v1` through to `yaak-web`
|
||||
instead, following `PORT` to find it — `vp run web:dev` starts both.
|
||||
`VITE_YAAK_WEB_URL` overrides this, for a deployment that keeps the app and the
|
||||
server apart.
|
||||
@@ -203,7 +203,7 @@ const HANDLERS: Partial<Record<AppCmd, Handler>> = {
|
||||
if (str(payload, "filter") != null) {
|
||||
return {
|
||||
content: "",
|
||||
error: "Response filters come from a plugin, which this host doesn't run yet",
|
||||
error: "Response filters are not available in the browser yet",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -228,6 +228,16 @@ const HANDLERS: Partial<Record<AppCmd, Handler>> = {
|
||||
// The rows the sender wrote for that response, same table as the desktop.
|
||||
cmd_get_http_response_events: (payload, db) => db.rpc("cmd_get_http_response_events", payload),
|
||||
|
||||
/* ------------------------------- export -------------------------------- */
|
||||
|
||||
// Built by the model layer, exactly as the desktop and the CLI build it. Where
|
||||
// the document goes is not decided here: the caller hands it to `files.save`,
|
||||
// which is the one thing each host answers differently.
|
||||
cmd_export_data: (payload, db) => db.rpc("cmd_export_data", payload),
|
||||
|
||||
// The same example the desktop creates, built by the model layer in the worker.
|
||||
cmd_create_example_workspace: (payload, db) => db.rpc("cmd_create_example_workspace", payload),
|
||||
|
||||
async cmd_get_sse_events() {
|
||||
return [];
|
||||
},
|
||||
@@ -243,6 +253,7 @@ const HTTP_AUTHENTICATION_SUMMARIES = [
|
||||
{ name: "aws", label: "AWS SigV4", shortLabel: "AWS" },
|
||||
{ name: "basic", label: "Basic Auth", shortLabel: "Basic" },
|
||||
{ name: "bearer", label: "Bearer Token", shortLabel: "Bearer" },
|
||||
{ name: "digest", label: "Digest Auth", shortLabel: "Digest" },
|
||||
{ name: "jwt", label: "JWT Bearer", shortLabel: "JWT" },
|
||||
{ name: "ntlm", label: "NTLM", shortLabel: "NTLM" },
|
||||
{ name: "oauth1", label: "OAuth 1.0", shortLabel: "OAuth 1" },
|
||||
@@ -281,11 +292,10 @@ const DECLINED: Partial<Record<AppCmd, [reason: string, capability: CapabilityNa
|
||||
"Importing from a file needs a filesystem, which a browser tab has no",
|
||||
"localFiles",
|
||||
],
|
||||
cmd_import_url: ["Importing from a URL needs the Yaak server, which isn't available yet", null],
|
||||
cmd_commit_import: ["Importing needs a plugin, which this host doesn't run", null],
|
||||
cmd_list_import_sources: ["Importing isn't available in the browser yet", null],
|
||||
cmd_import_sources_for_origin: ["Importing isn't available in the browser yet", null],
|
||||
cmd_export_data: ["Exporting to a file isn't available in the browser yet", "localFiles"],
|
||||
cmd_detect_import_source: ["Importing isn't available in the browser yet", null],
|
||||
cmd_save_response: ["Saving a response to disk isn't available in the browser", "localFiles"],
|
||||
cmd_save_base64_to_binary: ["Saving to disk isn't available in the browser", "localFiles"],
|
||||
cmd_format_graphql: ["Formatting GraphQL needs a plugin, which this host doesn't run", null],
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
|
||||
import type { Unsubscribe } from "../types";
|
||||
import { randomId } from "./ids";
|
||||
import { type FromWorker, type ToWorker, WORKER_NAME } from "./protocol";
|
||||
|
||||
/**
|
||||
@@ -45,7 +46,7 @@ export class WorkerConnection {
|
||||
* and two tabs claiming one identity would each drop the other's writes as
|
||||
* echoes.
|
||||
*/
|
||||
readonly label = `tab_${crypto.randomUUID().slice(0, 8)}`;
|
||||
readonly label = `tab_${randomId(4)}`;
|
||||
|
||||
/** True once the worker has said anything at all. */
|
||||
private heard = false;
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Random ids that do not need a secure context.
|
||||
*
|
||||
* `crypto.randomUUID` exists only on HTTPS and localhost, so a tab opened at
|
||||
* `http://some-host:1424` — a self-hosted instance reached from another machine —
|
||||
* throws on it before anything renders. `crypto.getRandomValues` carries no such
|
||||
* restriction, and nothing here needs UUID semantics: these ids identify a tab and
|
||||
* a stream within one page, and only have to not collide with each other.
|
||||
*/
|
||||
export function randomId(bytes = 8): string {
|
||||
const buf = new Uint8Array(bytes);
|
||||
crypto.getRandomValues(buf);
|
||||
return Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
@@ -16,6 +16,7 @@
|
||||
*/
|
||||
|
||||
import type {
|
||||
DialogFilter,
|
||||
DragDropEvent,
|
||||
OsType,
|
||||
Platform,
|
||||
@@ -23,11 +24,14 @@ import type {
|
||||
PlatformWindow,
|
||||
RpcPayload,
|
||||
RpcStreamHandle,
|
||||
SaveContent,
|
||||
Unsubscribe,
|
||||
} from "../types";
|
||||
import { commandSupport, runCommand } from "./commands";
|
||||
import { WorkerConnection } from "./connection";
|
||||
import { unsupported } from "./errors";
|
||||
import { randomId } from "./ids";
|
||||
import { serverBaseUrl } from "./server";
|
||||
import { requestPersistence } from "./storage";
|
||||
|
||||
/** What this host can do, reported honestly. */
|
||||
@@ -68,6 +72,8 @@ function capabilitiesFor(): PlatformCapabilities {
|
||||
clipboardRead: false,
|
||||
systemFonts: false,
|
||||
license: false,
|
||||
// No local CLI to find and no app process to serve MCP from.
|
||||
agents: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -106,6 +112,91 @@ async function hostPluginCommand<T>(cmd: string, payload?: RpcPayload): Promise<
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The File System Access API, where the browser has it. Chromium does; Firefox
|
||||
* and Safari do not, and fall through to a download below.
|
||||
*/
|
||||
interface SaveFilePicker {
|
||||
(options: {
|
||||
suggestedName?: string;
|
||||
types?: { description: string; accept: Record<string, string[]> }[];
|
||||
}): Promise<{
|
||||
name: string;
|
||||
createWritable(): Promise<{ write(data: Uint8Array): Promise<void>; close(): Promise<void> }>;
|
||||
}>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saving, the only way a page can: a real save dialog where the browser offers
|
||||
* one, and a download everywhere else.
|
||||
*
|
||||
* The return value is a name rather than a path because a name is all a tab
|
||||
* ever learns. Callers show it back to the user and nothing more, which is why
|
||||
* the interface promises "where they went" rather than a path.
|
||||
*/
|
||||
function toBytes(content: SaveContent): Uint8Array {
|
||||
if (content instanceof Uint8Array) return content;
|
||||
const binary = atob(content.base64);
|
||||
const out = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
||||
return out;
|
||||
}
|
||||
|
||||
async function saveBytes(
|
||||
suggestedName: string,
|
||||
content: SaveContent,
|
||||
filters?: DialogFilter[],
|
||||
): Promise<string | null> {
|
||||
const picker = (window as unknown as { showSaveFilePicker?: SaveFilePicker }).showSaveFilePicker;
|
||||
const bytes = toBytes(content);
|
||||
|
||||
if (picker != null) {
|
||||
let handle;
|
||||
try {
|
||||
handle = await picker({
|
||||
suggestedName,
|
||||
types: filters?.map((f) => ({
|
||||
description: f.name,
|
||||
// The API keys accepted extensions by MIME type. Nothing here knows
|
||||
// the real one, and it only labels the dialog's filter, so the
|
||||
// catch-all is honest enough.
|
||||
accept: { "application/octet-stream": f.extensions.map((e) => `.${e}`) },
|
||||
})),
|
||||
});
|
||||
} catch (err) {
|
||||
// Only choosing a file is allowed to fall back. Backing out is not a
|
||||
// failure and must not become a download nobody asked for; anything else
|
||||
// here is a browser that won't show the dialog, which a download covers.
|
||||
if ((err as { name?: string } | null)?.name === "AbortError") return null;
|
||||
console.warn("Save dialog unavailable, falling back to a download", err);
|
||||
}
|
||||
|
||||
// Past the dialog, the user has named a destination. A write that fails
|
||||
// there is a failed save, and saying so beats quietly putting the file
|
||||
// somewhere else and reporting success.
|
||||
if (handle != null) {
|
||||
const writable = await handle.createWritable();
|
||||
await writable.write(bytes);
|
||||
await writable.close();
|
||||
return handle.name;
|
||||
}
|
||||
}
|
||||
|
||||
// No dialog: the file lands wherever the browser puts downloads, under the
|
||||
// name we suggested. The user is not asked, so there is nothing to cancel.
|
||||
const url = URL.createObjectURL(new Blob([bytes as BlobPart]));
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = suggestedName;
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
// Revoked on a later turn: revoking while the browser is still reading the
|
||||
// blob cancels the download in some of them.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 30_000);
|
||||
return suggestedName;
|
||||
}
|
||||
|
||||
function createWindow(db: WorkerConnection): PlatformWindow {
|
||||
const noop = async () => {};
|
||||
|
||||
@@ -177,15 +268,24 @@ export function createWebPlatform(): Platform {
|
||||
|
||||
return {
|
||||
capabilities,
|
||||
httpProxyUrl: serverBaseUrl() || window.location.origin,
|
||||
window: createWindow(db),
|
||||
|
||||
clipboard: {
|
||||
writeText: (text) => navigator.clipboard.writeText(text),
|
||||
readText: async () => {
|
||||
throw unsupported("clipboard.readText", "Paste instead — Yaak in a browser can't read the clipboard on its own", "clipboardRead");
|
||||
throw unsupported(
|
||||
"clipboard.readText",
|
||||
"Paste instead — Yaak in a browser can't read the clipboard on its own",
|
||||
"clipboardRead",
|
||||
);
|
||||
},
|
||||
clear: async () => {
|
||||
throw unsupported("clipboard.clear", "Yaak in a browser can't modify the clipboard", "clipboardRead");
|
||||
throw unsupported(
|
||||
"clipboard.clear",
|
||||
"Yaak in a browser can't modify the clipboard",
|
||||
"clipboardRead",
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -198,7 +298,11 @@ export function createWebPlatform(): Platform {
|
||||
|
||||
files: {
|
||||
readDir: async () => {
|
||||
throw unsupported("files.readDir", "A browser tab can't browse your filesystem", "localFiles");
|
||||
throw unsupported(
|
||||
"files.readDir",
|
||||
"A browser tab can't browse your filesystem",
|
||||
"localFiles",
|
||||
);
|
||||
},
|
||||
readText: async () => {
|
||||
throw unsupported("files.readText", "A browser tab can't read local files", "localFiles");
|
||||
@@ -207,6 +311,8 @@ export function createWebPlatform(): Platform {
|
||||
url: (path) => path,
|
||||
basename: async (path) => path.split(/[/\\]/).pop() ?? path,
|
||||
resolveResource: async (path) => path,
|
||||
|
||||
save: saveBytes,
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -241,7 +347,7 @@ export function createWebPlatform(): Platform {
|
||||
): Promise<RpcStreamHandle<T>> {
|
||||
// Same shape as the desktop — subscribe first, then dispatch — so that a
|
||||
// command which grows the ability to stream here needs no caller changes.
|
||||
const streamId = crypto.randomUUID();
|
||||
const streamId = randomId();
|
||||
const unlisten = db.listen(`stream_${streamId}`, (p) => onMessage(p as M));
|
||||
try {
|
||||
const result = (await runCommand(cmd, { ...payload, streamId }, db)) as T;
|
||||
@@ -266,7 +372,11 @@ export function createWebPlatform(): Platform {
|
||||
},
|
||||
|
||||
revealItemInDir: async () => {
|
||||
throw unsupported("revealItemInDir", "A browser tab can't open your file manager", "localFiles");
|
||||
throw unsupported(
|
||||
"revealItemInDir",
|
||||
"A browser tab can't open your file manager",
|
||||
"localFiles",
|
||||
);
|
||||
},
|
||||
|
||||
osType: detectOsType,
|
||||
|
||||
@@ -16,16 +16,16 @@ import type { Frame } from "@yaakapp-internal/web";
|
||||
* (`yaak-web --serve`), and then a send is a request to a path on the
|
||||
* page's own origin — no CORS, and nothing for a self-hoster to configure.
|
||||
*
|
||||
* `VITE_YAAK_WEB_URL` overrides it at build time, for a deployment that
|
||||
* keeps the two apart. The dev server is one of those: it serves the app on its
|
||||
* own origin and knows nothing about `/v1`, so a dev build falls back to a server
|
||||
* running locally (`cargo run -p yaak-web`).
|
||||
* `VITE_YAAK_WEB_URL` overrides it at build time, for a deployment that keeps the
|
||||
* two apart. Nothing else needs to: the dev server passes `/v1` through to
|
||||
* `yaak-web` (see the client's vite config), so a dev build and a production
|
||||
* build are both talking to their own origin, and neither has an address to
|
||||
* learn. A tab opened from another machine therefore works unchanged.
|
||||
*/
|
||||
export function serverBaseUrl(): string {
|
||||
const env = (import.meta as unknown as { env?: Record<string, string | undefined> }).env;
|
||||
const configured = env?.VITE_YAAK_WEB_URL?.trim();
|
||||
if (configured) return configured.replace(/\/+$/, "");
|
||||
return env?.DEV ? "http://127.0.0.1:9227" : "";
|
||||
return configured ? configured.replace(/\/+$/, "") : "";
|
||||
}
|
||||
|
||||
export function serverSendUrl(): string {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# Importers
|
||||
|
||||
Implement **`onImportSource(ctx, { source })`**. The source is one of two things:
|
||||
|
||||
- `{ type: "text", name, text }`: a single UTF-8 document, or pasted text (named `input`).
|
||||
- `{ type: "directory", files }`: a directory or a ZIP archive, read as one file tree.
|
||||
|
||||
Return `null` or `undefined` when the source isn't your format. Only one importer's result is used per source.
|
||||
|
||||
```ts
|
||||
import type { PluginDefinition } from "@yaakapp/api";
|
||||
|
||||
export const plugin: PluginDefinition = {
|
||||
importer: {
|
||||
name: "Example",
|
||||
async onImportSource(ctx, { source }) {
|
||||
if (source.type === "text") return convertDocument(source.text);
|
||||
for (const entry of await source.files.readDir()) {
|
||||
if (entry.name === "example.json") {
|
||||
return convertDocument(await source.files.readTextFile(entry.path));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
The older `onImport(ctx, { text })` hook still works but is deprecated. It only receives single text documents and is ignored when `onImportSource` is defined.
|
||||
|
||||
## The file tree
|
||||
|
||||
- `files.kind` is `"directory"` or `"zip"`; `files.name` is the selected basename.
|
||||
- `readDir(path = "")` lists immediate children. `readFile(path)` returns bytes. `readTextFile(path)` decodes UTF-8 strictly.
|
||||
- Paths use `/` and are relative to the root. Absolute paths, `..`, and backslashes are rejected. Symbolic links are skipped in listings and rejected on read. Nothing is extracted to disk.
|
||||
- ZIPs are detected by signature, not extension. A ZIP made by compressing a folder is rooted at that folder, so plugins see the same tree as for the directory. Directory reads are not a snapshot: a symlink swapped in under a validated path can redirect a read outside the root, so treat directory imports as trusted input.
|
||||
- Limits: 64 MiB per source file or download, 32 MiB per file read, 10,000 entries, 256 MiB declared ZIP expansion. Encrypted ZIPs are unsupported.
|
||||
- The tree is read-only and only valid until the hook settles.
|
||||
|
||||
Plugins run with the normal Node.js permissions of the plugin runtime; the tree scopes convenience, not security.
|
||||
@@ -30,9 +30,9 @@
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/node": "^24.0.13"
|
||||
"@types/node": "^22.20.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"cpy-cli": "^5.0.0"
|
||||
"cpy-cli": "^7.0.0"
|
||||
}
|
||||
}
|
||||
+24
-3
@@ -84,10 +84,17 @@ export type FileFilter = { name: string,
|
||||
*/
|
||||
extensions: Array<string>, };
|
||||
|
||||
export type FilterLanguage = "jsonpath" | "xpath";
|
||||
|
||||
export type FilterRequest = { content: string, filter: string, };
|
||||
|
||||
export type FilterResponse = { content: string, error?: string, };
|
||||
|
||||
/**
|
||||
* A plugin asking the host to run a JSONPath or XPath query over some text.
|
||||
*/
|
||||
export type FilterTextRequest = { language: FilterLanguage, text: string, query: string, };
|
||||
|
||||
export type FindHttpResponsesRequest = { requestId: string, limit?: number, };
|
||||
|
||||
export type FindHttpResponsesResponse = { httpResponses: Array<HttpResponse>, };
|
||||
@@ -470,7 +477,16 @@ export type HttpRequestAction = { label: string, icon?: Icon, };
|
||||
|
||||
export type Icon = "alert_triangle" | "check" | "check_circle" | "chevron_down" | "copy" | "info" | "pin" | "search" | "trash" | "_unknown";
|
||||
|
||||
export type ImportRequest = { content: string, };
|
||||
/**
|
||||
* Transport descriptor; plugins see a scoped ImportFiles API, not this representation.
|
||||
*/
|
||||
export type ImportFileSource = { "type": "file", name: string, base64: string, } | { "type": "directory", path: string, };
|
||||
|
||||
export type ImportRequest = {
|
||||
/**
|
||||
* Kept for text-only importers and older runtimes.
|
||||
*/
|
||||
content: string, source?: ImportFileSource, };
|
||||
|
||||
export type ImportResources = { workspaces: Array<Workspace>, environments: Array<Environment>, folders: Array<Folder>, httpRequests: Array<HttpRequest>, grpcRequests: Array<GrpcRequest>, websocketRequests: Array<WebsocketRequest>, };
|
||||
|
||||
@@ -489,7 +505,7 @@ sourceKeys?: { [key in string]?: string }, };
|
||||
|
||||
export type InternalEvent = { id: string, pluginRefId: string, pluginName: string, replyId: string | null, context: PluginContext, payload: InternalEventPayload, };
|
||||
|
||||
export type InternalEventPayload = { "type": "boot_request" } & BootRequest | { "type": "boot_response" } | { "type": "reload_response" } & ReloadResponse | { "type": "terminate_request" } | { "type": "terminate_response" } | { "type": "import_request" } & ImportRequest | { "type": "import_response" } & ImportResponse | { "type": "filter_request" } & FilterRequest | { "type": "filter_response" } & FilterResponse | { "type": "export_http_request_request" } & ExportHttpRequestRequest | { "type": "export_http_request_response" } & ExportHttpRequestResponse | { "type": "send_http_request_request" } & SendHttpRequestRequest | { "type": "send_http_request_response" } & SendHttpRequestResponse | { "type": "list_cookie_names_request" } & ListCookieNamesRequest | { "type": "list_cookie_names_response" } & ListCookieNamesResponse | { "type": "get_cookie_value_request" } & GetCookieValueRequest | { "type": "get_cookie_value_response" } & GetCookieValueResponse | { "type": "get_http_request_actions_request" } & EmptyPayload | { "type": "get_http_request_actions_response" } & GetHttpRequestActionsResponse | { "type": "call_http_request_action_request" } & CallHttpRequestActionRequest | { "type": "get_websocket_request_actions_request" } & EmptyPayload | { "type": "get_websocket_request_actions_response" } & GetWebsocketRequestActionsResponse | { "type": "call_websocket_request_action_request" } & CallWebsocketRequestActionRequest | { "type": "get_workspace_actions_request" } & EmptyPayload | { "type": "get_workspace_actions_response" } & GetWorkspaceActionsResponse | { "type": "call_workspace_action_request" } & CallWorkspaceActionRequest | { "type": "get_folder_actions_request" } & EmptyPayload | { "type": "get_folder_actions_response" } & GetFolderActionsResponse | { "type": "call_folder_action_request" } & CallFolderActionRequest | { "type": "get_grpc_request_actions_request" } & EmptyPayload | { "type": "get_grpc_request_actions_response" } & GetGrpcRequestActionsResponse | { "type": "call_grpc_request_action_request" } & CallGrpcRequestActionRequest | { "type": "get_template_function_summary_request" } & EmptyPayload | { "type": "get_template_function_summary_response" } & GetTemplateFunctionSummaryResponse | { "type": "get_template_function_config_request" } & GetTemplateFunctionConfigRequest | { "type": "get_template_function_config_response" } & GetTemplateFunctionConfigResponse | { "type": "call_template_function_request" } & CallTemplateFunctionRequest | { "type": "call_template_function_response" } & CallTemplateFunctionResponse | { "type": "get_http_authentication_summary_request" } & EmptyPayload | { "type": "get_http_authentication_summary_response" } & GetHttpAuthenticationSummaryResponse | { "type": "get_http_authentication_config_request" } & GetHttpAuthenticationConfigRequest | { "type": "get_http_authentication_config_response" } & GetHttpAuthenticationConfigResponse | { "type": "call_http_authentication_request" } & CallHttpAuthenticationRequest | { "type": "call_http_authentication_response" } & CallHttpAuthenticationResponse | { "type": "call_http_authentication_action_request" } & CallHttpAuthenticationActionRequest | { "type": "call_http_authentication_action_response" } & EmptyPayload | { "type": "copy_text_request" } & CopyTextRequest | { "type": "copy_text_response" } & EmptyPayload | { "type": "render_http_request_request" } & RenderHttpRequestRequest | { "type": "render_http_request_response" } & RenderHttpRequestResponse | { "type": "render_grpc_request_request" } & RenderGrpcRequestRequest | { "type": "render_grpc_request_response" } & RenderGrpcRequestResponse | { "type": "template_render_request" } & TemplateRenderRequest | { "type": "template_render_response" } & TemplateRenderResponse | { "type": "get_key_value_request" } & GetKeyValueRequest | { "type": "get_key_value_response" } & GetKeyValueResponse | { "type": "set_key_value_request" } & SetKeyValueRequest | { "type": "set_key_value_response" } & SetKeyValueResponse | { "type": "delete_key_value_request" } & DeleteKeyValueRequest | { "type": "delete_key_value_response" } & DeleteKeyValueResponse | { "type": "open_window_request" } & OpenWindowRequest | { "type": "window_navigate_event" } & WindowNavigateEvent | { "type": "window_close_event" } | { "type": "close_window_request" } & CloseWindowRequest | { "type": "open_external_url_request" } & OpenExternalUrlRequest | { "type": "open_external_url_response" } & EmptyPayload | { "type": "show_toast_request" } & ShowToastRequest | { "type": "show_toast_response" } & EmptyPayload | { "type": "prompt_text_request" } & PromptTextRequest | { "type": "prompt_text_response" } & PromptTextResponse | { "type": "prompt_form_request" } & PromptFormRequest | { "type": "prompt_form_response" } & PromptFormResponse | { "type": "window_info_request" } & WindowInfoRequest | { "type": "window_info_response" } & WindowInfoResponse | { "type": "list_open_workspaces_request" } & ListOpenWorkspacesRequeLine truncated
|
||||
export type InternalEventPayload = { "type": "boot_request" } & BootRequest | { "type": "boot_response" } | { "type": "reload_response" } & ReloadResponse | { "type": "terminate_request" } | { "type": "terminate_response" } | { "type": "import_request" } & ImportRequest | { "type": "import_response" } & ImportResponse | { "type": "filter_request" } & FilterRequest | { "type": "filter_response" } & FilterResponse | { "type": "filter_text_request" } & FilterTextRequest | { "type": "filter_text_response" } & FilterResponse | { "type": "export_http_request_request" } & ExportHttpRequestRequest | { "type": "export_http_request_response" } & ExportHttpRequestResponse | { "type": "send_http_request_request" } & SendHttpRequestRequest | { "type": "send_http_request_response" } & SendHttpRequestResponse | { "type": "list_cookie_names_request" } & ListCookieNamesRequest | { "type": "list_cookie_names_response" } & ListCookieNamesResponse | { "type": "get_cookie_value_request" } & GetCookieValueRequest | { "type": "get_cookie_value_response" } & GetCookieValueResponse | { "type": "get_http_request_actions_request" } & EmptyPayload | { "type": "get_http_request_actions_response" } & GetHttpRequestActionsResponse | { "type": "call_http_request_action_request" } & CallHttpRequestActionRequest | { "type": "get_websocket_request_actions_request" } & EmptyPayload | { "type": "get_websocket_request_actions_response" } & GetWebsocketRequestActionsResponse | { "type": "call_websocket_request_action_request" } & CallWebsocketRequestActionRequest | { "type": "get_workspace_actions_request" } & EmptyPayload | { "type": "get_workspace_actions_response" } & GetWorkspaceActionsResponse | { "type": "call_workspace_action_request" } & CallWorkspaceActionRequest | { "type": "get_folder_actions_request" } & EmptyPayload | { "type": "get_folder_actions_response" } & GetFolderActionsResponse | { "type": "call_folder_action_request" } & CallFolderActionRequest | { "type": "get_grpc_request_actions_request" } & EmptyPayload | { "type": "get_grpc_request_actions_response" } & GetGrpcRequestActionsResponse | { "type": "call_grpc_request_action_request" } & CallGrpcRequestActionRequest | { "type": "get_template_function_summary_request" } & EmptyPayload | { "type": "get_template_function_summary_response" } & GetTemplateFunctionSummaryResponse | { "type": "get_template_function_config_request" } & GetTemplateFunctionConfigRequest | { "type": "get_template_function_config_response" } & GetTemplateFunctionConfigResponse | { "type": "call_template_function_request" } & CallTemplateFunctionRequest | { "type": "call_template_function_response" } & CallTemplateFunctionResponse | { "type": "get_http_authentication_summary_request" } & EmptyPayload | { "type": "get_http_authentication_summary_response" } & GetHttpAuthenticationSummaryResponse | { "type": "get_http_authentication_config_request" } & GetHttpAuthenticationConfigRequest | { "type": "get_http_authentication_config_response" } & GetHttpAuthenticationConfigResponse | { "type": "call_http_authentication_request" } & CallHttpAuthenticationRequest | { "type": "call_http_authentication_response" } & CallHttpAuthenticationResponse | { "type": "call_http_authentication_action_request" } & CallHttpAuthenticationActionRequest | { "type": "call_http_authentication_action_response" } & EmptyPayload | { "type": "copy_text_request" } & CopyTextRequest | { "type": "copy_text_response" } & EmptyPayload | { "type": "render_http_request_request" } & RenderHttpRequestRequest | { "type": "render_http_request_response" } & RenderHttpRequestResponse | { "type": "render_grpc_request_request" } & RenderGrpcRequestRequest | { "type": "render_grpc_request_response" } & RenderGrpcRequestResponse | { "type": "template_render_request" } & TemplateRenderRequest | { "type": "template_render_response" } & TemplateRenderResponse | { "type": "get_key_value_request" } & GetKeyValueRequest | { "type": "get_key_value_response" } & GetKeyValueResponse | { "type": "set_key_value_request" } & SetKeyValueRequest | { "type": "set_key_value_response" } & SetKeyValueResponse | { "type": "delete_key_value_request" } & DeleteKeyValueRequest | { "type": "delete_key_value_response" } & DeleteKeyValueResponse | { "type": "open_window_request" } & OpenWindowRequest | { "type": "window_navigate_event" } & WindowNavigateEvent | { "type": "window_close_event" } | { "type": "close_window_request" } & CloseWindowRequest | { "type": "open_external_url_request" } & OpenExternalUrlRequest | { "type": "open_external_url_response" } & EmptyPayload | { "type": "show_toast_request" } & ShowToastRequest | { "type": "show_toast_response" } & EmptyPayload | { "type": "prompt_text_request" } & PromptTextRequest | { "type": "prompt_text_response" } & PromptTextResponse | { "type": "prompt_form_request" } & PromptFormRequest | { "type": "prompt_form_response" } & PromptFormResponse | { "type": "window_info_request" } & WindowInfoRequest | { "type": "windoLine truncated
|
||||
|
||||
export type JsonPrimitive = string | number | boolean | null;
|
||||
|
||||
@@ -572,7 +588,12 @@ export type RenderHttpRequestResponse = { httpRequest: HttpRequest, };
|
||||
|
||||
export type RenderPurpose = "send" | "preview";
|
||||
|
||||
export type SendHttpRequestRequest = { httpRequest: Partial<HttpRequest>, };
|
||||
export type SendHttpRequestRequest = { httpRequest: Partial<HttpRequest>,
|
||||
/**
|
||||
* Override the environment for this send without changing the active selection.
|
||||
* When omitted, use the host's active environment.
|
||||
*/
|
||||
environmentId?: string, };
|
||||
|
||||
export type SendHttpRequestResponse = { httpResponse: HttpResponse,
|
||||
/**
|
||||
|
||||
@@ -11,6 +11,7 @@ export type AnyModel =
|
||||
| HttpRequest
|
||||
| HttpResponse
|
||||
| HttpResponseEvent
|
||||
| ImportSource
|
||||
| KeyValue
|
||||
| Plugin
|
||||
| Settings
|
||||
@@ -137,6 +138,10 @@ export type GrpcConnection = {
|
||||
state: GrpcConnectionState;
|
||||
trailers: { [key in string]?: string };
|
||||
url: string;
|
||||
/**
|
||||
* The request version this connection was opened from, when one was captured.
|
||||
*/
|
||||
versionId: string | null;
|
||||
};
|
||||
|
||||
export type GrpcConnectionState = "initialized" | "connected" | "closed";
|
||||
@@ -241,6 +246,10 @@ export type HttpResponse = {
|
||||
state: HttpResponseState;
|
||||
url: string;
|
||||
version: string | null;
|
||||
/**
|
||||
* The request version this response was sent from, when one was captured.
|
||||
*/
|
||||
versionId: string | null;
|
||||
};
|
||||
|
||||
export type HttpResponseEvent = {
|
||||
@@ -318,6 +327,18 @@ export type HttpUrlParameter = {
|
||||
|
||||
export type HttpVersion = "auto" | "http1" | "http2";
|
||||
|
||||
export type ImportSource = {
|
||||
model: "import_source";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
workspaceId: string;
|
||||
importer: string;
|
||||
origin: string;
|
||||
originLabel: string;
|
||||
lastImportedAt: string;
|
||||
};
|
||||
|
||||
export type InheritedBoolSetting = { enabled?: boolean; value: boolean };
|
||||
|
||||
export type InheritedHttpVersionSetting = { enabled?: boolean; value: HttpVersion };
|
||||
@@ -385,6 +406,7 @@ export type Settings = {
|
||||
updateChannel: string;
|
||||
hideLicenseBadge: boolean;
|
||||
promptFeedback: boolean;
|
||||
mcpServerEnabled: boolean;
|
||||
autoupdate: boolean;
|
||||
autoDownloadUpdates: boolean;
|
||||
checkNotifications: boolean;
|
||||
@@ -417,6 +439,10 @@ export type WebsocketConnection = {
|
||||
state: WebsocketConnectionState;
|
||||
status: number;
|
||||
url: string;
|
||||
/**
|
||||
* The request version this connection was opened from, when one was captured.
|
||||
*/
|
||||
versionId: string | null;
|
||||
};
|
||||
|
||||
export type WebsocketConnectionState = "initialized" | "connected" | "closing" | "closed";
|
||||
|
||||
+6
-2
@@ -1,5 +1,9 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type PluginMetadata = { version: string, name: string, displayName: string, description: string | null, homepageUrl: string | null, repositoryUrl: string | null, };
|
||||
export type PluginMetadata = { version: string, name: string, displayName: string, description: string | null, homepageUrl: string | null, repositoryUrl: string | null,
|
||||
/**
|
||||
* Why the plugin should no longer be used, from `deprecated` in its package.json
|
||||
*/
|
||||
deprecated: string | null, };
|
||||
|
||||
export type PluginVersion = { id: string, version: string, url: string, description: string | null, name: string, displayName: string, homepageUrl: string | null, repositoryUrl: string | null, checksum: string, readme: string | null, yanked: boolean, };
|
||||
export type PluginVersion = { id: string, version: string, url: string, description: string | null, name: string, displayName: string, homepageUrl: string | null, repositoryUrl: string | null, checksum: string, readme: string | null, yanked: boolean, deprecated: string | null, };
|
||||
@@ -6,4 +6,10 @@ export * from "./bindings/gen_events";
|
||||
|
||||
// Some extras for utility
|
||||
|
||||
export type { PartialImportResources } from "./plugins/ImporterPlugin";
|
||||
export type {
|
||||
PartialImportResources,
|
||||
ImportFiles,
|
||||
ImportFileEntry,
|
||||
ImportSource,
|
||||
ImportSourceHandler,
|
||||
} from "./plugins/ImporterPlugin";
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
FilterResponse,
|
||||
FindHttpResponsesRequest,
|
||||
FindHttpResponsesResponse,
|
||||
FormInput,
|
||||
@@ -226,6 +227,16 @@ export interface Context {
|
||||
templates: {
|
||||
render<T extends JsonValue>(args: TemplateRenderRequest & { data: T }): Promise<T>;
|
||||
};
|
||||
/**
|
||||
* Query text the way the response filter box does. A query or document
|
||||
* that can't be read comes back as `error`, with empty `content`.
|
||||
*/
|
||||
filter: {
|
||||
/** RFC 9535 JSONPath. Every match, as a pretty-printed JSON array. */
|
||||
jsonPath(text: string, query: string): Promise<FilterResponse>;
|
||||
/** XPath 1.0. Matched nodes as XML, one per line, or a scalar result as text. */
|
||||
xPath(text: string, query: string): Promise<FilterResponse>;
|
||||
};
|
||||
plugin: {
|
||||
reload(): void;
|
||||
};
|
||||
|
||||
@@ -21,11 +21,45 @@ export type ImportPluginResponse =
|
||||
resources: PartialImportResources;
|
||||
});
|
||||
|
||||
/** A read-only view of a selected directory or ZIP archive. Paths are relative and use
|
||||
* forward slashes. Directory path checks are best-effort under concurrent filesystem
|
||||
* changes, not a security boundary. Valid only while onImportSource runs. */
|
||||
export interface ImportFiles {
|
||||
readonly name: string;
|
||||
readonly kind: "zip" | "directory";
|
||||
/** List immediate children. The root directory is "" (the default). */
|
||||
readDir(path?: string): Promise<ImportFileEntry[]>;
|
||||
readFile(path: string): Promise<Uint8Array>;
|
||||
/** Decode UTF-8 strictly; binary or invalid UTF-8 content throws. */
|
||||
readTextFile(path: string): Promise<string>;
|
||||
}
|
||||
|
||||
export interface ImportFileEntry {
|
||||
name: string;
|
||||
path: string;
|
||||
type: "file" | "directory";
|
||||
}
|
||||
|
||||
/** What the user chose to import: one text document, or a directory or ZIP read as a tree. */
|
||||
export type ImportSource =
|
||||
| { type: "text"; name: string; text: string }
|
||||
| { type: "directory"; files: ImportFiles };
|
||||
|
||||
type ImportTextHandler = (
|
||||
ctx: Context,
|
||||
args: { text: string },
|
||||
) => MaybePromise<ImportPluginResponse | undefined>;
|
||||
|
||||
export type ImportSourceHandler = (
|
||||
ctx: Context,
|
||||
args: { source: ImportSource },
|
||||
) => MaybePromise<ImportPluginResponse | undefined>;
|
||||
|
||||
export type ImporterPlugin = {
|
||||
name: string;
|
||||
description?: string;
|
||||
onImport(
|
||||
ctx: Context,
|
||||
args: { text: string },
|
||||
): MaybePromise<ImportPluginResponse | null | undefined>;
|
||||
/** Return null when the source isn't this importer's format. Takes precedence over onImport. */
|
||||
onImportSource?: ImportSourceHandler;
|
||||
/** @deprecated Use onImportSource. Only receives single text documents. */
|
||||
onImport?: ImportTextHandler;
|
||||
};
|
||||
@@ -1 +1 @@
|
||||
24.11.1
|
||||
24.22.2
|
||||
@@ -6,11 +6,13 @@
|
||||
"build:main": "esbuild src/index.ts --bundle --platform=node --outfile=../../crates-tauri/yaak-app-client/vendored/plugin-runtime/index.cjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"ws": "^8.21.0"
|
||||
"ws": "^8.22.0",
|
||||
"yauzl": "^3.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.0.13",
|
||||
"@types/ws": "^8.5.13",
|
||||
"@types/node": "^22.20.5",
|
||||
"@types/ws": "^8.18.2",
|
||||
"@types/yauzl": "^3.4.0",
|
||||
"esbuild": "^0.28.0"
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@ import type {
|
||||
BootRequest,
|
||||
DeleteKeyValueResponse,
|
||||
DeleteModelResponse,
|
||||
FilterLanguage,
|
||||
FilterResponse,
|
||||
FindHttpResponsesResponse,
|
||||
Folder,
|
||||
FormInput,
|
||||
@@ -51,6 +53,7 @@ import type {
|
||||
} from "@yaakapp-internal/plugins";
|
||||
import { applyDynamicFormInput } from "./common";
|
||||
import { EventChannel } from "./EventChannel";
|
||||
import { runImporter } from "./importFiles";
|
||||
import { migrateTemplateFunctionSelectOptions } from "./migrations";
|
||||
import { createResponseBody, decodeBase64Chunk } from "./responseBody";
|
||||
|
||||
@@ -157,19 +160,14 @@ export class PluginInstance {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
payload.type === "import_request" &&
|
||||
typeof this.#mod?.importer?.onImport === "function"
|
||||
) {
|
||||
const reply = await this.#mod.importer.onImport(ctx, {
|
||||
text: payload.content,
|
||||
});
|
||||
if (payload.type === "import_request" && this.#mod?.importer != null) {
|
||||
const reply = await runImporter(this.#mod.importer, ctx, payload);
|
||||
if (reply != null) {
|
||||
const replyPayload: InternalEventPayload = {
|
||||
type: "import_response",
|
||||
importer: this.#mod.importer.name,
|
||||
resources: reply.resources as ImportResources,
|
||||
sourceKeys: reply.sourceKeys ?? null,
|
||||
sourceKeys: reply.sourceKeys,
|
||||
};
|
||||
this.#sendPayload(context, replyPayload, replyId);
|
||||
return;
|
||||
@@ -649,16 +647,26 @@ export class PluginInstance {
|
||||
complete: info.complete,
|
||||
},
|
||||
async (offset, length) => {
|
||||
const chunk = await this.#sendForReply<ReadHttpResponseBodyChunkResponse>(
|
||||
context,
|
||||
{ type: "read_http_response_body_chunk_request", responseId, offset, length },
|
||||
);
|
||||
const chunk = await this.#sendForReply<ReadHttpResponseBodyChunkResponse>(context, {
|
||||
type: "read_http_response_body_chunk_request",
|
||||
responseId,
|
||||
offset,
|
||||
length,
|
||||
});
|
||||
return decodeBase64Chunk(chunk.data);
|
||||
},
|
||||
{ refresh: bodyInfo },
|
||||
);
|
||||
};
|
||||
|
||||
const filterText = (language: FilterLanguage, text: string, query: string) =>
|
||||
this.#sendForReply<FilterResponse>(context, {
|
||||
type: "filter_text_request",
|
||||
language,
|
||||
text,
|
||||
query,
|
||||
});
|
||||
|
||||
const _windowInfo = async () => {
|
||||
if (context.label == null) {
|
||||
throw new Error("Can't get window context without an active window");
|
||||
@@ -853,7 +861,10 @@ export class PluginInstance {
|
||||
// carries the only copy of its body. A saved one is read back from
|
||||
// the host like any other. Callers get the same thing either way.
|
||||
if (body == null) {
|
||||
return { httpResponse: forPlugin(httpResponse), body: await storedBody(httpResponse.id) };
|
||||
return {
|
||||
httpResponse: forPlugin(httpResponse),
|
||||
body: await storedBody(httpResponse.id),
|
||||
};
|
||||
}
|
||||
|
||||
const bytes = decodeBase64Chunk(body);
|
||||
@@ -1002,6 +1013,10 @@ export class PluginInstance {
|
||||
return result.data as any;
|
||||
},
|
||||
},
|
||||
filter: {
|
||||
jsonPath: (text: string, query: string) => filterText("jsonpath", text, query),
|
||||
xPath: (text: string, query: string) => filterText("xpath", text, query),
|
||||
},
|
||||
store: {
|
||||
get: async <T>(key: string) => {
|
||||
const payload = { type: "get_key_value_request", key } as const;
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,224 @@
|
||||
import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { Context, ImportRequest, ImportSource } from "@yaakapp/api";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vite-plus/test";
|
||||
import { createImportFiles, runImporter } from "./importFiles";
|
||||
|
||||
const dirs: string[] = [];
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
});
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
|
||||
});
|
||||
const input = (name: string, data: Uint8Array): ImportRequest => ({
|
||||
content: "",
|
||||
source: { type: "file", name, base64: Buffer.from(data).toString("base64") },
|
||||
});
|
||||
async function zip(name = "import-files.zip") {
|
||||
return input(name, await readFile(new URL(`./fixtures/${name}`, import.meta.url)));
|
||||
}
|
||||
const ctx = {} as Context;
|
||||
|
||||
describe("import file tree", () => {
|
||||
test("exposes legacy text and single binary files through the same read API", async () => {
|
||||
const session = await createImportFiles({ content: "café" });
|
||||
expect(session.text).toBe("café");
|
||||
expect(await session.files.readDir()).toEqual([{ name: "input", path: "input", type: "file" }]);
|
||||
expect(await session.files.readTextFile("input")).toBe("café");
|
||||
session.close();
|
||||
await expect(session.files.readFile("input")).rejects.toThrow("closed");
|
||||
const binary = await createImportFiles(input("body.bin", Uint8Array.from([255, 0, 128])));
|
||||
expect(binary.isText).toBe(false);
|
||||
expect([...(await binary.files.readFile("body.bin"))]).toEqual([255, 0, 128]);
|
||||
await expect(binary.files.readTextFile("body.bin")).rejects.toThrow();
|
||||
binary.close();
|
||||
});
|
||||
|
||||
test("lists immediate ZIP children, including implicit/empty directories, and reads binary/UTF-8", async () => {
|
||||
const session = await createImportFiles(await zip());
|
||||
expect(session.files.kind).toBe("zip");
|
||||
expect(session.text).toBe("");
|
||||
expect(await session.files.readDir()).toEqual([
|
||||
{ name: "binary.bin", path: "binary.bin", type: "file" },
|
||||
{ name: "collection", path: "collection", type: "directory" },
|
||||
]);
|
||||
expect((await session.files.readDir("collection")).map((e) => e.name)).toEqual([
|
||||
"café.yml",
|
||||
"empty",
|
||||
"nested",
|
||||
]);
|
||||
expect(await session.files.readDir("collection/empty")).toEqual([]);
|
||||
expect(await session.files.readTextFile("collection/café.yml")).toBe("name: café\n");
|
||||
expect([...(await session.files.readFile("binary.bin"))]).toEqual([0, 255, 128]);
|
||||
await expect(session.files.readFile("collection")).rejects.toThrow("not found");
|
||||
await expect(session.files.readDir("missing")).rejects.toThrow("not found");
|
||||
session.close();
|
||||
});
|
||||
|
||||
test("a misleading ZIP suffix still dispatches as text", async () => {
|
||||
const content = '{"openapi":"3.0.0","info":{"title":"Example","version":"1"},"paths":{}}';
|
||||
const source = input("api.zip", Buffer.from(content));
|
||||
const onImport = vi.fn().mockResolvedValue(null);
|
||||
await runImporter({ name: "Text", onImport }, ctx, source);
|
||||
expect(onImport).toHaveBeenCalledExactlyOnceWith(ctx, { text: content });
|
||||
const onImportSource = vi.fn().mockResolvedValue(null);
|
||||
await runImporter({ name: "Source", onImportSource }, ctx, source);
|
||||
expect(onImportSource).toHaveBeenCalledExactlyOnceWith(ctx, {
|
||||
source: { type: "text", name: "api.zip", text: content },
|
||||
});
|
||||
});
|
||||
|
||||
test("ZIP signatures take precedence over names, including empty archives", async () => {
|
||||
const bytes = await readFile(new URL("./fixtures/import-files.zip", import.meta.url));
|
||||
const empty = Buffer.alloc(22);
|
||||
empty.writeUInt32LE(0x06054b50);
|
||||
for (const data of [bytes, empty]) {
|
||||
const source = input("collection.yaml", data);
|
||||
const session = await createImportFiles(source);
|
||||
try {
|
||||
expect(session.files.kind).toBe("zip");
|
||||
if (data === empty) expect(await session.files.readDir()).toEqual([]);
|
||||
else expect(await session.files.readTextFile("collection/café.yml")).toBe("name: café\n");
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
const onImport = vi.fn().mockResolvedValue(null);
|
||||
expect(await runImporter({ name: "Text", onImport }, ctx, source)).toBeNull();
|
||||
expect(onImport).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
test("a ZIP made by compressing a folder is rooted at that folder", async () => {
|
||||
const session = await createImportFiles(await zip("wrapped.zip"));
|
||||
try {
|
||||
expect((await session.files.readDir()).map((e) => e.name)).toEqual(["nested", "root.txt"]);
|
||||
expect(await session.files.readTextFile("nested/file.txt")).toBe("inner\n");
|
||||
await expect(session.files.readDir("Demo")).rejects.toThrow("not found");
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("malformed input with a ZIP signature still fails archive validation", async () => {
|
||||
const source = input("broken.zip", Buffer.from([0x50, 0x4b, 0x03, 0x04]));
|
||||
await expect(createImportFiles(source)).rejects.toThrow();
|
||||
});
|
||||
|
||||
test("directory view reads lazily and blocks links and escaping paths", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "yaak-import-"));
|
||||
dirs.push(root);
|
||||
await mkdir(path.join(root, "nested"));
|
||||
await writeFile(path.join(root, "nested", "file"), "first");
|
||||
await symlink(tmpdir(), path.join(root, "escape"));
|
||||
const session = await createImportFiles({
|
||||
content: "",
|
||||
source: { type: "directory", path: root },
|
||||
});
|
||||
expect(await session.files.readDir()).toEqual([
|
||||
{ name: "nested", path: "nested", type: "directory" },
|
||||
]);
|
||||
await writeFile(path.join(root, "nested", "file"), "updated");
|
||||
expect(await session.files.readTextFile("nested/file")).toBe("updated");
|
||||
await expect(session.files.readDir("escape")).rejects.toThrow("symbolic");
|
||||
for (const p of [
|
||||
"../outside",
|
||||
"/absolute",
|
||||
"C:/outside",
|
||||
"nested/../../outside",
|
||||
"nested\\file",
|
||||
]) {
|
||||
await expect(session.files.readFile(p)).rejects.toThrow();
|
||||
}
|
||||
session.close();
|
||||
});
|
||||
|
||||
test.each(["import-traversal.zip", "import-duplicate.zip", "import-symlink.zip"])(
|
||||
"rejects unsafe ZIP %s",
|
||||
async (name) => {
|
||||
await expect(createImportFiles(await zip(name))).rejects.toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
test("ZIP entries are decompressed only on read, with a read-size limit", async () => {
|
||||
const session = await createImportFiles(await zip("import-large.zip"));
|
||||
expect((await session.files.readDir())[0]?.name).toBe("large.txt");
|
||||
await expect(session.files.readFile("large.txt")).rejects.toThrow("32 MiB");
|
||||
session.close();
|
||||
});
|
||||
|
||||
test("the deprecated text hook preserves its arguments and skips other input", async () => {
|
||||
const onImport = vi.fn().mockResolvedValue(null);
|
||||
const importer = { name: "Legacy", onImport };
|
||||
await runImporter(importer, ctx, { content: "original" });
|
||||
expect(onImport).toHaveBeenCalledExactlyOnceWith(ctx, { text: "original" });
|
||||
onImport.mockClear();
|
||||
await runImporter(importer, ctx, input("empty.txt", new Uint8Array()));
|
||||
expect(onImport).toHaveBeenCalledExactlyOnceWith(ctx, { text: "" });
|
||||
onImport.mockClear();
|
||||
for (const source of [
|
||||
await zip(),
|
||||
input("binary", Uint8Array.from([255])),
|
||||
{
|
||||
content: "",
|
||||
source: { type: "directory", path: "/does-not-exist" },
|
||||
} satisfies ImportRequest,
|
||||
]) {
|
||||
expect(await runImporter(importer, ctx, source)).toBeNull();
|
||||
}
|
||||
expect(onImport).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("the source hook gets text for documents and a tree for directories and ZIPs", async () => {
|
||||
const onImport = vi.fn().mockResolvedValue(null);
|
||||
const onImportSource = vi.fn().mockResolvedValue(null);
|
||||
const importer = { name: "Both", onImport, onImportSource };
|
||||
const root = await mkdtemp(path.join(tmpdir(), "yaak-import-hooks-"));
|
||||
dirs.push(root);
|
||||
const cases: [ImportRequest, ImportSource["type"] | null, string?][] = [
|
||||
[{ content: "pasted" }, "text", "pasted"],
|
||||
[input("text.txt", Buffer.from("text")), "text", "text"],
|
||||
[input("empty.txt", new Uint8Array()), "text", ""],
|
||||
[input("binary", Uint8Array.from([255])), null],
|
||||
[await zip(), "directory"],
|
||||
[{ content: "", source: { type: "directory", path: root } }, "directory"],
|
||||
];
|
||||
for (const [request, type, text] of cases) {
|
||||
onImportSource.mockClear();
|
||||
expect(await runImporter(importer, ctx, request)).toBeNull();
|
||||
if (type == null) {
|
||||
expect(onImportSource).not.toHaveBeenCalled();
|
||||
continue;
|
||||
}
|
||||
expect(onImportSource).toHaveBeenCalledOnce();
|
||||
const { source } = onImportSource.mock.calls[0]![1] as { source: ImportSource };
|
||||
expect(source.type).toBe(type);
|
||||
if (source.type === "text") expect(source.text).toBe(text);
|
||||
else await expect(source.files.readDir()).rejects.toThrow("closed");
|
||||
}
|
||||
onImportSource.mockResolvedValue(undefined);
|
||||
await runImporter(importer, ctx, { content: "pasted" });
|
||||
expect(onImport).not.toHaveBeenCalled();
|
||||
expect(console.warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("closes file access even if the importer throws", async () => {
|
||||
let saved: import("@yaakapp/api").ImportFiles | undefined;
|
||||
await expect(
|
||||
runImporter(
|
||||
{
|
||||
name: "Fails",
|
||||
onImportSource(_ctx, { source }) {
|
||||
if (source.type === "directory") saved = source.files;
|
||||
throw new Error("failure");
|
||||
},
|
||||
},
|
||||
ctx,
|
||||
await zip(),
|
||||
),
|
||||
).rejects.toThrow("failure");
|
||||
await expect(saved!.readDir()).rejects.toThrow("closed");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,326 @@
|
||||
import { constants } from "node:fs";
|
||||
import { lstat, open, opendir, realpath } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { Context, ImportFileEntry, ImportFiles, ImportRequest } from "@yaakapp/api";
|
||||
import type { ImporterPlugin, ImportSource } from "@yaakapp/api/lib/plugins/ImporterPlugin";
|
||||
import { type Entry, fromBuffer, type ZipFile } from "yauzl";
|
||||
|
||||
const MAX_FILE_BYTES = 32 * 1024 * 1024;
|
||||
const MAX_SOURCE_BYTES = 64 * 1024 * 1024;
|
||||
const MAX_ENTRIES = 10_000;
|
||||
const MAX_EXPANDED_BYTES = 256 * 1024 * 1024;
|
||||
|
||||
function relativePath(value: string): string {
|
||||
if (
|
||||
value.includes("\\") ||
|
||||
value.includes("\0") ||
|
||||
value.startsWith("/") ||
|
||||
/^[a-z]:/i.test(value)
|
||||
) {
|
||||
throw new Error(`Invalid import path: ${value}`);
|
||||
}
|
||||
const parts = value.split("/");
|
||||
if (parts.includes("..")) throw new Error("Import paths cannot leave the selected source");
|
||||
return parts.filter((p) => p !== "" && p !== ".").join("/");
|
||||
}
|
||||
|
||||
function isZip(bytes: Buffer): boolean {
|
||||
// Names are hints only: a text specification can legitimately be named *.zip.
|
||||
return (
|
||||
bytes[0] === 0x50 &&
|
||||
bytes[1] === 0x4b &&
|
||||
((bytes[2] === 3 && bytes[3] === 4) ||
|
||||
(bytes[2] === 5 && bytes[3] === 6) ||
|
||||
(bytes[2] === 7 && bytes[3] === 8))
|
||||
);
|
||||
}
|
||||
|
||||
export interface ImportFileSession {
|
||||
files: ImportFiles;
|
||||
kind: "file" | ImportFiles["kind"];
|
||||
name: string;
|
||||
text: string;
|
||||
/** Whether text-only plugins can handle this input, including an empty text file. */
|
||||
isText: boolean;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/** Construct one scoped view for one invocation. No ZIP entries are extracted to disk. */
|
||||
export async function createImportFiles(input: ImportRequest): Promise<ImportFileSession> {
|
||||
let closed = false;
|
||||
let zip: ZipFile | undefined;
|
||||
let zipError: Error | undefined;
|
||||
const assertOpen = () => {
|
||||
if (closed) throw new Error("Import source is closed");
|
||||
if (zipError) throw zipError;
|
||||
};
|
||||
let kind: ImportFileSession["kind"] = "file";
|
||||
let name = "input";
|
||||
let text = input.content;
|
||||
let isText = true;
|
||||
let readDir: ImportFiles["readDir"];
|
||||
let readFile: ImportFiles["readFile"];
|
||||
|
||||
if (input.source?.type === "directory") {
|
||||
kind = "directory";
|
||||
isText = false;
|
||||
text = "";
|
||||
const root = await realpath(input.source.path);
|
||||
name = path.basename(root);
|
||||
const resolve = async (value: string) => {
|
||||
assertOpen();
|
||||
const rel = relativePath(value);
|
||||
let candidate = root;
|
||||
// Reject links visible during validation, including intermediate components.
|
||||
// These path checks are not atomic with open/opendir: concurrent filesystem
|
||||
// changes can redirect a later operation. This is not a confinement boundary.
|
||||
for (const component of rel.split("/").filter(Boolean)) {
|
||||
candidate = path.join(candidate, component);
|
||||
if ((await lstat(candidate)).isSymbolicLink())
|
||||
throw new Error("Import sources do not follow symbolic links");
|
||||
}
|
||||
const canonical = await realpath(candidate);
|
||||
const within = path.relative(root, canonical);
|
||||
if (within === ".." || within.startsWith(`..${path.sep}`) || path.isAbsolute(within))
|
||||
throw new Error("Import path is outside the selected source");
|
||||
return canonical;
|
||||
};
|
||||
readDir = async (value = "") => {
|
||||
const rel = relativePath(value);
|
||||
const entries: ImportFileEntry[] = [];
|
||||
for await (const entry of await opendir(await resolve(rel))) {
|
||||
if (!entry.isFile() && !entry.isDirectory()) continue;
|
||||
entries.push({
|
||||
name: entry.name,
|
||||
path: rel ? `${rel}/${entry.name}` : entry.name,
|
||||
type: entry.isDirectory() ? "directory" : "file",
|
||||
});
|
||||
if (entries.length > MAX_ENTRIES)
|
||||
throw new Error("Import directory contains too many entries");
|
||||
}
|
||||
assertOpen();
|
||||
return entries.sort((a, b) => a.path.localeCompare(b.path));
|
||||
};
|
||||
readFile = async (value) => {
|
||||
const handle = await open(
|
||||
await resolve(value),
|
||||
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),
|
||||
);
|
||||
try {
|
||||
const stat = await handle.stat();
|
||||
if (!stat.isFile()) throw new Error("Import path is not a regular file");
|
||||
if (stat.size > MAX_FILE_BYTES)
|
||||
throw new Error("Import file exceeds the 32 MiB read limit");
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
for await (const chunk of handle.createReadStream({ autoClose: false })) {
|
||||
const bytes = Buffer.from(chunk as Uint8Array);
|
||||
total += bytes.length;
|
||||
if (total > MAX_FILE_BYTES) throw new Error("Import file exceeds the 32 MiB read limit");
|
||||
chunks.push(bytes);
|
||||
}
|
||||
assertOpen();
|
||||
return Buffer.concat(chunks);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
};
|
||||
} else {
|
||||
const source = input.source;
|
||||
if (source && source.base64.length > Math.ceil(MAX_SOURCE_BYTES / 3) * 4)
|
||||
throw new Error("Import source exceeds the 64 MiB limit");
|
||||
const bytes = source ? Buffer.from(source.base64, "base64") : Buffer.from(input.content);
|
||||
name = source?.name || "input";
|
||||
if (bytes.length > MAX_SOURCE_BYTES) throw new Error("Import source exceeds the 64 MiB limit");
|
||||
const entries = new Map<string, { type: "file" | "directory"; entry?: Entry; data?: Buffer }>([
|
||||
["", { type: "directory" }],
|
||||
]);
|
||||
if (source && isZip(bytes)) {
|
||||
kind = "zip";
|
||||
text = "";
|
||||
isText = false;
|
||||
zip = await new Promise<ZipFile>((resolve, reject) => {
|
||||
fromBuffer(
|
||||
bytes,
|
||||
{ lazyEntries: true, autoClose: false, strictFileNames: false, validateEntrySizes: true },
|
||||
(err, result) => (err ? reject(err) : resolve(result)),
|
||||
);
|
||||
});
|
||||
zip.on("error", (err: Error) => {
|
||||
zipError = err;
|
||||
});
|
||||
const archive = zip;
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
let count = 0;
|
||||
let expandedBytes = 0;
|
||||
archive.once("error", reject);
|
||||
archive.once("end", () => {
|
||||
archive.removeListener("error", reject);
|
||||
resolve();
|
||||
});
|
||||
archive.on("entry", (entry: Entry) => {
|
||||
try {
|
||||
if (++count > MAX_ENTRIES) throw new Error("ZIP contains too many entries");
|
||||
expandedBytes += entry.uncompressedSize;
|
||||
if (expandedBytes > MAX_EXPANDED_BYTES)
|
||||
throw new Error("ZIP expanded size exceeds the 256 MiB limit");
|
||||
if (entry.isEncrypted()) throw new Error("Encrypted ZIP entries are not supported");
|
||||
const mode = (entry.externalFileAttributes >>> 16) & 0xf000;
|
||||
if (mode === 0xa000) throw new Error("ZIP symbolic links are not supported");
|
||||
const entryPath = relativePath(entry.fileName);
|
||||
if (!entryPath) throw new Error("ZIP contains an empty entry path");
|
||||
const type = entry.fileName.endsWith("/") ? "directory" : "file";
|
||||
const previous = entries.get(entryPath);
|
||||
if (previous && (type !== "directory" || previous.type !== "directory"))
|
||||
throw new Error(`Duplicate ZIP path: ${entryPath}`);
|
||||
entries.set(entryPath, { type, entry });
|
||||
let parent = path.posix.dirname(entryPath);
|
||||
while (parent !== ".") {
|
||||
if (entries.get(parent)?.type === "file")
|
||||
throw new Error(`ZIP file/directory conflict: ${parent}`);
|
||||
if (!entries.has(parent)) entries.set(parent, { type: "directory" });
|
||||
parent = path.posix.dirname(parent);
|
||||
}
|
||||
if (entries.size > MAX_ENTRIES) throw new Error("ZIP contains too many paths");
|
||||
archive.readEntry();
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
archive.readEntry();
|
||||
});
|
||||
} catch (err) {
|
||||
archive.close();
|
||||
throw err;
|
||||
}
|
||||
unwrapSingleRoot(entries);
|
||||
} else {
|
||||
const entryPath = relativePath(name);
|
||||
if (!entryPath || entryPath.includes("/"))
|
||||
throw new Error("Single import files must have a basename");
|
||||
entries.set(entryPath, { type: "file", data: bytes });
|
||||
try {
|
||||
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
||||
} catch {
|
||||
text = "";
|
||||
isText = false;
|
||||
}
|
||||
}
|
||||
readDir = async (value = "") => {
|
||||
assertOpen();
|
||||
const rel = relativePath(value);
|
||||
if (entries.get(rel)?.type !== "directory")
|
||||
throw new Error(`Import directory not found: ${rel}`);
|
||||
return [...entries]
|
||||
.filter(
|
||||
([p]) => p !== "" && (path.posix.dirname(p) === "." ? "" : path.posix.dirname(p)) === rel,
|
||||
)
|
||||
.map(([p, entry]) => ({ name: path.posix.basename(p), path: p, type: entry.type }))
|
||||
.sort((a, b) => a.path.localeCompare(b.path));
|
||||
};
|
||||
readFile = async (value) => {
|
||||
assertOpen();
|
||||
const found = entries.get(relativePath(value));
|
||||
if (!found || found.type !== "file") throw new Error(`Import file not found: ${value}`);
|
||||
if (found.data) {
|
||||
if (found.data.length > MAX_FILE_BYTES)
|
||||
throw new Error("Import file exceeds the 32 MiB read limit");
|
||||
return Buffer.from(found.data);
|
||||
}
|
||||
const entry = found.entry!;
|
||||
if (entry.uncompressedSize > MAX_FILE_BYTES)
|
||||
throw new Error("Import file exceeds the 32 MiB read limit");
|
||||
const stream = await new Promise<import("node:stream").Readable>((resolve, reject) => {
|
||||
zip!.openReadStream(entry, (err, result) => (err ? reject(err) : resolve(result)));
|
||||
});
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
for await (const chunk of stream) {
|
||||
const bytes = Buffer.from(chunk as Uint8Array);
|
||||
total += bytes.length;
|
||||
if (total > MAX_FILE_BYTES) {
|
||||
stream.destroy();
|
||||
throw new Error("Import file exceeds the 32 MiB read limit");
|
||||
}
|
||||
chunks.push(bytes);
|
||||
}
|
||||
assertOpen();
|
||||
return Buffer.concat(chunks);
|
||||
};
|
||||
}
|
||||
return {
|
||||
text,
|
||||
isText,
|
||||
kind,
|
||||
name,
|
||||
files: {
|
||||
// A lone file is only ever handed to plugins as text, never as a tree
|
||||
kind: kind === "file" ? "directory" : kind,
|
||||
name,
|
||||
readDir,
|
||||
readFile,
|
||||
async readTextFile(value) {
|
||||
return new TextDecoder("utf-8", { fatal: true }).decode(await readFile(value));
|
||||
},
|
||||
},
|
||||
close() {
|
||||
closed = true;
|
||||
zip?.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Compressing a folder puts everything under that folder inside the archive. Present the
|
||||
* folder's contents as the root so plugins see the same tree they would for the directory.
|
||||
*/
|
||||
function unwrapSingleRoot<T extends { type: "file" | "directory" }>(entries: Map<string, T>) {
|
||||
const tops = new Set<string>();
|
||||
for (const entryPath of entries.keys()) {
|
||||
if (entryPath === "") continue;
|
||||
const top = entryPath.split("/")[0]!;
|
||||
if (top === "__MACOSX" || top.startsWith(".")) continue;
|
||||
tops.add(top);
|
||||
}
|
||||
if (tops.size !== 1) return;
|
||||
const [root] = tops;
|
||||
if (entries.get(root!)?.type !== "directory") return;
|
||||
const prefix = `${root}/`;
|
||||
const snapshot = Array.from(entries);
|
||||
for (const [entryPath, value] of snapshot) {
|
||||
if (entryPath === "") continue;
|
||||
entries.delete(entryPath);
|
||||
if (entryPath === root) continue;
|
||||
if (entryPath.startsWith(prefix)) entries.set(entryPath.slice(prefix.length), value);
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep legacy text plugins out of directories, archives, and arbitrary binary inputs. */
|
||||
export async function runImporter(importer: ImporterPlugin, ctx: Context, input: ImportRequest) {
|
||||
if (!importer.onImportSource && input.source?.type === "directory") return null;
|
||||
// Avoid opening archives once for every legacy importer.
|
||||
if (!importer.onImportSource && input.source?.type === "file") {
|
||||
const bytes = Buffer.from(input.source.base64, "base64");
|
||||
if (isZip(bytes)) return null;
|
||||
}
|
||||
const session = await createImportFiles(input);
|
||||
try {
|
||||
if (importer.onImportSource) {
|
||||
const source: ImportSource | null =
|
||||
session.kind === "file"
|
||||
? session.isText
|
||||
? { type: "text", name: session.name, text: session.text }
|
||||
: null
|
||||
: { type: "directory", files: session.files };
|
||||
if (source == null) return null;
|
||||
return await importer.onImportSource(ctx, { source });
|
||||
}
|
||||
if (session.isText && importer.onImport) {
|
||||
return await importer.onImport(ctx, { text: session.text });
|
||||
}
|
||||
return null;
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { InternalEvent, InternalEventPayload } from "@yaakapp/api";
|
||||
import { expect, test } from "vite-plus/test";
|
||||
import { EventChannel } from "../src/EventChannel";
|
||||
import { PluginInstance } from "../src/PluginInstance";
|
||||
|
||||
test("ctx.filter asks the host and hands back its reply", async () => {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "yaak-filter-"));
|
||||
await mkdir(path.join(dir, "build"));
|
||||
await writeFile(
|
||||
path.join(dir, "build/index.js"),
|
||||
`exports.plugin = { async init(ctx) {
|
||||
const results = [
|
||||
await ctx.filter.jsonPath('{"a":1}', "$.a"),
|
||||
await ctx.filter.xPath("<a/>", "//b["),
|
||||
];
|
||||
await ctx.toast.show({ message: JSON.stringify(results) });
|
||||
} };`,
|
||||
);
|
||||
const channel = new EventChannel();
|
||||
const context = { workspaceId: null, label: null };
|
||||
const bootRequest = { dir, watch: false };
|
||||
const instance = new PluginInstance({ bootRequest, pluginRefId: "test", context }, channel);
|
||||
const requests: InternalEventPayload[] = [];
|
||||
const reply = (event: InternalEvent, payload: InternalEventPayload) =>
|
||||
instance.postMessage({ ...event, id: `reply-${event.id}`, replyId: event.id, payload });
|
||||
|
||||
const toast = new Promise<string>((resolve, reject) => {
|
||||
channel.listen((event) => {
|
||||
const { payload } = event;
|
||||
if (payload.type === "filter_text_request") {
|
||||
// Match the JSON transport used by the real plugin host.
|
||||
requests.push(JSON.parse(JSON.stringify(payload)) as InternalEventPayload);
|
||||
reply(
|
||||
event,
|
||||
payload.language === "jsonpath"
|
||||
? { type: "filter_text_response", content: "[\n 1\n]" }
|
||||
: { type: "filter_text_response", content: "", error: "Invalid filter: bad" },
|
||||
);
|
||||
} else if (payload.type === "show_toast_request") {
|
||||
resolve(payload.message);
|
||||
} else if (payload.type === "error_response") {
|
||||
reject(new Error(payload.error));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
try {
|
||||
instance.postMessage({
|
||||
id: "boot",
|
||||
replyId: null,
|
||||
pluginRefId: "test",
|
||||
pluginName: "test",
|
||||
context,
|
||||
payload: { type: "boot_request", ...bootRequest },
|
||||
});
|
||||
expect(JSON.parse(await toast)).toEqual([
|
||||
{ content: "[\n 1\n]" },
|
||||
{ content: "", error: "Invalid filter: bad" },
|
||||
]);
|
||||
expect(requests).toEqual([
|
||||
{ type: "filter_text_request", language: "jsonpath", text: '{"a":1}', query: "$.a" },
|
||||
{ type: "filter_text_request", language: "xpath", text: "<a/>", query: "//b[" },
|
||||
]);
|
||||
} finally {
|
||||
await instance.terminate();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import type { InternalEvent } from "@yaakapp/api";
|
||||
import { expect, test } from "vite-plus/test";
|
||||
import { EventChannel } from "../src/EventChannel";
|
||||
import { PluginInstance } from "../src/PluginInstance";
|
||||
|
||||
test("the runtime forwards per-send environments without changing plugin context", async () => {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "yaak-send-environment-"));
|
||||
await mkdir(path.join(dir, "build"));
|
||||
await writeFile(
|
||||
path.join(dir, "build/index.js"),
|
||||
`exports.plugin = { async init(ctx) {
|
||||
await Promise.all(["ev_a", "ev_b", undefined].map(environmentId =>
|
||||
ctx.httpRequest.send({ httpRequest: { id: "rq_test" }, environmentId })
|
||||
));
|
||||
} };`,
|
||||
);
|
||||
const channel = new EventChannel();
|
||||
const context = { workspaceId: "wk_test", label: "test-window" };
|
||||
const bootRequest = { dir, watch: false };
|
||||
const instance = new PluginInstance({ bootRequest, pluginRefId: "test", context }, channel);
|
||||
const sends: InternalEvent[] = [];
|
||||
const booted = new Promise<void>((resolve, reject) => {
|
||||
channel.listen((event) => {
|
||||
if (event.payload.type === "send_http_request_request") {
|
||||
// Match the JSON transport used by the real plugin host.
|
||||
sends.push(JSON.parse(JSON.stringify(event)) as InternalEvent);
|
||||
instance.postMessage({
|
||||
...event,
|
||||
id: `reply-${event.id}`,
|
||||
replyId: event.id,
|
||||
payload: { type: "error_response", error: "test host received send" },
|
||||
});
|
||||
} else if (event.payload.type === "error_response") {
|
||||
// The stub host rejects the sends after capturing them.
|
||||
if (event.payload.error === "test host received send") resolve();
|
||||
else reject(new Error(event.payload.error));
|
||||
} else if (event.payload.type === "boot_response") {
|
||||
reject(new Error("Expected the test host's send error"));
|
||||
}
|
||||
});
|
||||
});
|
||||
try {
|
||||
instance.postMessage({
|
||||
id: "boot",
|
||||
replyId: null,
|
||||
pluginRefId: "test",
|
||||
pluginName: "test",
|
||||
context,
|
||||
payload: { type: "boot_request", ...bootRequest },
|
||||
});
|
||||
await booted;
|
||||
expect(sends.map((event) => event.payload)).toEqual([
|
||||
{ type: "send_http_request_request", httpRequest: { id: "rq_test" }, environmentId: "ev_a" },
|
||||
{ type: "send_http_request_request", httpRequest: { id: "rq_test" }, environmentId: "ev_b" },
|
||||
{ type: "send_http_request_request", httpRequest: { id: "rq_test" } },
|
||||
]);
|
||||
expect(sends.map((event) => event.context)).toEqual([context, context, context]);
|
||||
} finally {
|
||||
await instance.terminate();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -6,7 +6,7 @@
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.11.0",
|
||||
"@tauri-apps/api": "^2.12.4",
|
||||
"@yaakapp-internal/plugins": "^1.0.0",
|
||||
"parse-color": "^1.0.0"
|
||||
}
|
||||
|
||||
@@ -3,9 +3,23 @@
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"sideEffects": [
|
||||
"*.css"
|
||||
],
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./editor": "./src/editor.ts",
|
||||
"./httpTypes": "./src/components/http/types.ts",
|
||||
"./mimeType": "./src/lib/mimeType.ts",
|
||||
"./resolvedModelName": "./src/lib/resolvedModelName.ts",
|
||||
"./templateTags": "./src/lib/templateTags.ts",
|
||||
"./toast": "./src/lib/toast.ts",
|
||||
"./useToggle": "./src/hooks/useToggle.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"hexy": "^0.4.0",
|
||||
"jotai-family": "^1.0.1"
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ export type ButtonProps = Omit<HTMLAttributes<HTMLButtonElement>, "color" | "onC
|
||||
size?: ButtonSize;
|
||||
justify?: "start" | "center";
|
||||
type?: "button" | "submit";
|
||||
/** Submit a form the button is not inside, by that form's id */
|
||||
form?: string;
|
||||
forDropdown?: boolean;
|
||||
disabled?: boolean;
|
||||
title?: string;
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import classNames from "classnames";
|
||||
import type { ReactNode } from "react";
|
||||
import { Icon } from "./Icon";
|
||||
import { IconTooltip } from "./IconTooltip";
|
||||
import { HStack } from "./Stacks";
|
||||
|
||||
export interface CheckboxProps {
|
||||
checked: boolean | "indeterminate";
|
||||
title: ReactNode;
|
||||
onChange: (checked: boolean) => void;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
inputWrapperClassName?: string;
|
||||
hideLabel?: boolean;
|
||||
fullWidth?: boolean;
|
||||
help?: ReactNode;
|
||||
size?: "sm" | "md";
|
||||
}
|
||||
|
||||
export function Checkbox({
|
||||
checked,
|
||||
onChange,
|
||||
className,
|
||||
inputWrapperClassName,
|
||||
disabled,
|
||||
title,
|
||||
hideLabel,
|
||||
fullWidth,
|
||||
help,
|
||||
size = "sm",
|
||||
}: CheckboxProps) {
|
||||
return (
|
||||
<HStack
|
||||
as="label"
|
||||
alignItems="center"
|
||||
space={2}
|
||||
className={classNames(className, "text-text mr-auto")}
|
||||
>
|
||||
<div className={classNames(inputWrapperClassName, "x-theme-input", "relative flex mr-0.5")}>
|
||||
<input
|
||||
aria-hidden
|
||||
className={classNames(
|
||||
"appearance-none shrink-0 border border-border",
|
||||
size === "sm" && "w-4 h-4",
|
||||
size === "md" && "w-5 h-5",
|
||||
"rounded-sm outline-hidden ring-0",
|
||||
!disabled && "hocus:border-border-focus hocus:bg-focus/[5%]",
|
||||
disabled && "border-dotted",
|
||||
)}
|
||||
type="checkbox"
|
||||
disabled={disabled}
|
||||
onChange={() => {
|
||||
onChange(checked === "indeterminate" ? true : !checked);
|
||||
}}
|
||||
/>
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<Icon
|
||||
size={size}
|
||||
className={classNames(disabled && "opacity-disabled")}
|
||||
icon={checked === "indeterminate" ? "minus" : checked ? "check" : "empty"}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{!hideLabel && (
|
||||
<div
|
||||
className={classNames("text-sm", fullWidth && "w-full", disabled && "opacity-disabled")}
|
||||
>
|
||||
{title}
|
||||
</div>
|
||||
)}
|
||||
{help && <IconTooltip content={help} />}
|
||||
</HStack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useTimedBoolean } from "../hooks/useTimedBoolean";
|
||||
import { IconButton, type IconButtonProps } from "./IconButton";
|
||||
|
||||
export interface CopyIconButtonProps extends Omit<IconButtonProps, "onClick" | "icon"> {
|
||||
text: string | (() => Promise<string | null>);
|
||||
copy: (text: string) => void;
|
||||
/** Called when `text` resolves to nothing */
|
||||
onCopyFailed?: () => void;
|
||||
}
|
||||
|
||||
export function CopyIconButton({ text, copy, onCopyFailed, ...props }: CopyIconButtonProps) {
|
||||
const [copied, setCopied] = useTimedBoolean();
|
||||
return (
|
||||
<IconButton
|
||||
{...props}
|
||||
icon={copied ? "check" : "copy"}
|
||||
showConfirm
|
||||
onClick={async () => {
|
||||
const content = typeof text === "function" ? await text() : text;
|
||||
if (content == null) {
|
||||
onCopyFailed?.();
|
||||
} else {
|
||||
copy(content);
|
||||
setCopied();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { Color } from "@yaakapp-internal/plugins";
|
||||
import classNames from "classnames";
|
||||
|
||||
interface Props {
|
||||
count: number | true;
|
||||
count2?: number | true;
|
||||
className?: string;
|
||||
color?: Color;
|
||||
showZero?: boolean;
|
||||
}
|
||||
|
||||
export function CountBadge({ count, count2, className, color, showZero }: Props) {
|
||||
if (count === 0 && !showZero) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
aria-hidden
|
||||
className={classNames(
|
||||
className,
|
||||
"flex items-center",
|
||||
"opacity-70 border text-4xs rounded-sm mb-0.5 px-1 ml-1 h-4 font-mono",
|
||||
color == null && "border-border-subtle",
|
||||
color === "primary" && "text-primary",
|
||||
color === "secondary" && "text-secondary",
|
||||
color === "success" && "text-success",
|
||||
color === "notice" && "text-notice",
|
||||
color === "warning" && "text-warning",
|
||||
color === "danger" && "text-danger",
|
||||
)}
|
||||
>
|
||||
{count === true ? (
|
||||
<div aria-hidden className="rounded-full h-1 w-1 bg-[currentColor]" />
|
||||
) : (
|
||||
count
|
||||
)}
|
||||
{count2 != null && (
|
||||
<>
|
||||
/
|
||||
{count2 === true ? (
|
||||
<div aria-hidden className="rounded-full h-1 w-1 bg-[currentColor]" />
|
||||
) : (
|
||||
count2
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import classNames from "classnames";
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import { useInMemoryStoredValue, type UseStoredValue } from "../hooks/useStoredValue";
|
||||
import type { BannerProps } from "./Banner";
|
||||
import { Banner } from "./Banner";
|
||||
|
||||
export interface DetailsBannerProps extends HTMLAttributes<HTMLDetailsElement> {
|
||||
summary: ReactNode;
|
||||
color?: BannerProps["color"];
|
||||
defaultOpen?: boolean;
|
||||
storageKey?: string;
|
||||
/** Where the open state of a banner with a `storageKey` is kept */
|
||||
useStoredValue?: UseStoredValue;
|
||||
}
|
||||
|
||||
export function DetailsBanner({
|
||||
className,
|
||||
color,
|
||||
summary,
|
||||
children,
|
||||
defaultOpen,
|
||||
storageKey,
|
||||
useStoredValue = useInMemoryStoredValue,
|
||||
...extraProps
|
||||
}: DetailsBannerProps) {
|
||||
const [isOpen, setIsOpen] = useStoredValue<boolean>(storageKey || null, defaultOpen ?? false);
|
||||
|
||||
const handleToggle = (e: React.SyntheticEvent<HTMLDetailsElement>) => {
|
||||
if (storageKey) {
|
||||
void setIsOpen(e.currentTarget.open);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Banner color={color} className={className}>
|
||||
<details className="group list-none" open={isOpen} onToggle={handleToggle} {...extraProps}>
|
||||
<summary className="cursor-default! select-none! list-none flex items-center gap-3 focus:outline-hidden opacity-70">
|
||||
<div
|
||||
className={classNames(
|
||||
"transition-transform",
|
||||
"group-open:rotate-90",
|
||||
"w-0 h-0 border-t-[0.3em] border-b-[0.3em] border-l-[0.5em] border-r-0",
|
||||
"border-t-transparent border-b-transparent border-l-text-subtle",
|
||||
)}
|
||||
/>
|
||||
{summary}
|
||||
</summary>
|
||||
<div className="mt-1.5 pb-2">{children}</div>
|
||||
</details>
|
||||
</Banner>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import type { DialogSize } from "@yaakapp-internal/plugins";
|
||||
import classNames from "classnames";
|
||||
import * as m from "motion/react-m";
|
||||
import type { ReactNode } from "react";
|
||||
import { createContext, useContext, useMemo, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Button, type ButtonProps } from "./Button";
|
||||
import { Heading } from "./Heading";
|
||||
import { IconButton } from "./IconButton";
|
||||
import { Overlay } from "./Overlay";
|
||||
import { HStack } from "./Stacks";
|
||||
|
||||
export interface DialogProps {
|
||||
children: ReactNode;
|
||||
open: boolean;
|
||||
onClose?: () => void;
|
||||
/** Block dismissal from the backdrop, Escape key, and built-in close button. */
|
||||
disableClose?: boolean;
|
||||
title?: ReactNode;
|
||||
description?: ReactNode;
|
||||
className?: string;
|
||||
size?: DialogSize;
|
||||
/** Hide the built-in close button without changing backdrop or Escape behavior. */
|
||||
hideX?: boolean;
|
||||
noPadding?: boolean;
|
||||
noScroll?: boolean;
|
||||
vAlign?: "top" | "center";
|
||||
}
|
||||
|
||||
export function Dialog({
|
||||
children,
|
||||
className,
|
||||
size = "full",
|
||||
open,
|
||||
onClose,
|
||||
disableClose,
|
||||
title,
|
||||
description,
|
||||
hideX,
|
||||
noPadding,
|
||||
noScroll,
|
||||
vAlign = "center",
|
||||
}: DialogProps) {
|
||||
const titleId = useMemo(() => Math.random().toString(36).slice(2), []);
|
||||
const [footerEl, setFooterEl] = useState<HTMLDivElement | null>(null);
|
||||
const descriptionId = useMemo(
|
||||
() => (description ? Math.random().toString(36).slice(2) : undefined),
|
||||
[description],
|
||||
);
|
||||
|
||||
return (
|
||||
<Overlay open={open} onClose={disableClose ? undefined : onClose} portalName="dialog">
|
||||
<div
|
||||
role="dialog"
|
||||
className={classNames(
|
||||
"py-4 x-theme-dialog absolute inset-0 pointer-events-none",
|
||||
"h-full flex flex-col items-center justify-center",
|
||||
vAlign === "top" && "justify-start",
|
||||
vAlign === "center" && "justify-center",
|
||||
)}
|
||||
aria-labelledby={titleId}
|
||||
aria-describedby={descriptionId}
|
||||
tabIndex={-1}
|
||||
onKeyDown={(e) => {
|
||||
// NOTE: We handle Escape on the element itself so that it doesn't close multiple
|
||||
// dialogs and can be intercepted by children if needed.
|
||||
if (e.key === "Escape") {
|
||||
if (!disableClose) onClose?.();
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<m.div
|
||||
initial={{ top: 5, scale: 0.97 }}
|
||||
animate={{ top: 0, scale: 1 }}
|
||||
className={classNames(
|
||||
className,
|
||||
"grid grid-rows-[auto_auto_minmax(0,1fr)_auto]",
|
||||
"grid-cols-1", // must be here for inline code blocks to correctly break words
|
||||
"relative bg-surface pointer-events-auto",
|
||||
"rounded-lg",
|
||||
"border border-border-subtle shadow-lg shadow-[rgba(0,0,0,0.1)]",
|
||||
"min-h-40",
|
||||
"max-w-[calc(100vw-5rem)] max-h-[calc(100vh-5rem)]",
|
||||
size === "sm" && "w-120",
|
||||
size === "md" && "w-200",
|
||||
size === "lg" && "w-280",
|
||||
size === "full" && "w-screen h-screen",
|
||||
size === "dynamic" && "min-w-80 max-w-[100vw]",
|
||||
)}
|
||||
>
|
||||
{title ? (
|
||||
<Heading className="px-6 mt-4 mb-2" level={1} id={titleId}>
|
||||
{title}
|
||||
</Heading>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
|
||||
{description ? (
|
||||
<div className="min-h-0 px-6 text-text-subtle mb-3" id={descriptionId}>
|
||||
{description}
|
||||
</div>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
|
||||
<div
|
||||
className={classNames(
|
||||
"h-full w-full grid grid-cols-[minmax(0,1fr)] grid-rows-1",
|
||||
!noPadding && "px-6 py-2",
|
||||
!noScroll && "overflow-y-auto overflow-x-hidden",
|
||||
)}
|
||||
>
|
||||
<DialogFooterSlot.Provider value={footerEl}>{children}</DialogFooterSlot.Provider>
|
||||
</div>
|
||||
|
||||
<div ref={setFooterEl} className="contents" />
|
||||
|
||||
{/*Put close at the end so that it's the last thing to be tabbed to*/}
|
||||
{!disableClose && !hideX && (
|
||||
<div className="ml-auto absolute right-1 top-1">
|
||||
<IconButton
|
||||
className="opacity-70 hover:opacity-100"
|
||||
onClick={onClose}
|
||||
title="Close dialog (Esc)"
|
||||
aria-label="Close"
|
||||
size="sm"
|
||||
icon="x"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</m.div>
|
||||
</div>
|
||||
</Overlay>
|
||||
);
|
||||
}
|
||||
|
||||
const DialogFooterSlot = createContext<HTMLDivElement | null>(null);
|
||||
|
||||
export interface DialogFooterAction {
|
||||
label: string;
|
||||
onClick?: () => void;
|
||||
/** Submit the form with this id, which can be anywhere in the dialog body */
|
||||
form?: string;
|
||||
color?: ButtonProps["color"];
|
||||
variant?: ButtonProps["variant"];
|
||||
disabled?: boolean;
|
||||
isLoading?: boolean;
|
||||
autoFocus?: boolean;
|
||||
leftSlot?: ReactNode;
|
||||
rightSlot?: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* The action row at the bottom of a dialog. Render it anywhere in the dialog's content and it is
|
||||
* placed below the scrolling body, outside its padding. `inline` drops the divider for small
|
||||
* dialogs whose body never scrolls.
|
||||
*/
|
||||
export function DialogFooter({
|
||||
actions,
|
||||
leftSlot,
|
||||
inline,
|
||||
}: {
|
||||
actions: DialogFooterAction[];
|
||||
leftSlot?: ReactNode;
|
||||
inline?: boolean;
|
||||
}) {
|
||||
const slot = useContext(DialogFooterSlot);
|
||||
const footer = (
|
||||
<footer
|
||||
className={classNames(
|
||||
"px-6 flex items-center gap-3",
|
||||
inline ? "pt-1 pb-4" : "py-3 border-t border-border-subtle",
|
||||
)}
|
||||
>
|
||||
{leftSlot != null && <div className="mr-auto min-w-0">{leftSlot}</div>}
|
||||
<HStack space={2} justifyContent="end" className="ml-auto shrink-0">
|
||||
{actions.map((action, i) => (
|
||||
<Button
|
||||
// Labels change with state ("Cloning...", "Apply 3 Changes"), so they can't be keys
|
||||
key={i}
|
||||
type={action.form != null ? "submit" : "button"}
|
||||
form={action.form}
|
||||
color={action.color ?? "secondary"}
|
||||
variant={action.variant ?? (action.color == null ? "border" : "solid")}
|
||||
disabled={action.disabled}
|
||||
isLoading={action.isLoading}
|
||||
autoFocus={action.autoFocus}
|
||||
leftSlot={action.leftSlot}
|
||||
rightSlot={action.rightSlot}
|
||||
onClick={action.onClick}
|
||||
>
|
||||
{action.label}
|
||||
</Button>
|
||||
))}
|
||||
</HStack>
|
||||
</footer>
|
||||
);
|
||||
return slot == null ? footer : createPortal(footer, slot);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,194 @@
|
||||
import type { Completion } from "@codemirror/autocomplete";
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import type { GenericCompletionOption } from "@yaakapp-internal/plugins";
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { createContext, useContext, useMemo } from "react";
|
||||
import type { SetStoredValue, StoredValue, UseStoredValue } from "../hooks/useStoredValue";
|
||||
import { useInMemoryStoredValue } from "../hooks/useStoredValue";
|
||||
import type { HttpBodyLoader } from "./http/types";
|
||||
import type { MultipartViewerProps } from "./viewers/MultipartViewer";
|
||||
import { MultipartViewer } from "./viewers/MultipartViewer";
|
||||
import type { TextViewerProps } from "./viewers/TextViewer";
|
||||
import { TextViewer } from "./viewers/TextViewer";
|
||||
import type { ButtonProps } from "./Button";
|
||||
import type { DialogProps } from "./Dialog";
|
||||
import type { CodeEditorProps } from "./editor/CodeEditor";
|
||||
import { ErrorBoundary } from "./ErrorBoundary";
|
||||
import { LazyCodeEditor } from "./editor/LazyCodeEditor";
|
||||
import type { InputProps } from "./Input";
|
||||
import { Input } from "./Input";
|
||||
|
||||
export type GenericCompletion = GenericCompletionOption & {
|
||||
apply?: Completion["apply"];
|
||||
};
|
||||
|
||||
export interface GenericCompletionConfig {
|
||||
minMatch?: number;
|
||||
options: GenericCompletion[];
|
||||
}
|
||||
|
||||
/** A template variable, as far as shared components need to know one */
|
||||
export interface TemplateVariableRef {
|
||||
variable: { name: string };
|
||||
}
|
||||
|
||||
/**
|
||||
* What a host's editor adds on top of `CodeEditor`, like the client's template tags and
|
||||
* environment variables. Shared components pass these through; a host without templating
|
||||
* ignores them.
|
||||
*/
|
||||
export interface TemplatingProps {
|
||||
autocomplete?: GenericCompletionConfig;
|
||||
autocompleteFunctions?: boolean;
|
||||
autocompleteVariables?: boolean | ((v: TemplateVariableRef) => boolean);
|
||||
forcedEnvironmentId?: string;
|
||||
extraExtensions?: Extension[] | Extension;
|
||||
}
|
||||
|
||||
/** `CodeEditor`'s languages, plus the host-only ones it may know (the client's URL and pairs) */
|
||||
export type HostEditorLanguage = CodeEditorProps["language"] | "pairs" | "url";
|
||||
|
||||
export type HostEditorProps = Omit<CodeEditorProps, "language" | "extensions" | "keymap"> &
|
||||
TemplatingProps & { language?: HostEditorLanguage };
|
||||
|
||||
export type HostInputProps = Omit<
|
||||
InputProps,
|
||||
"language" | "extensions" | "renderEditor" | "renderOptionsPicker"
|
||||
> &
|
||||
TemplatingProps & {
|
||||
language?: HostEditorLanguage;
|
||||
/** Show a chevron that opens the `autocomplete` options as a menu */
|
||||
showOptionsPicker?: boolean;
|
||||
};
|
||||
|
||||
export type SelectFileProps = Omit<ButtonProps, "type" | "onChange"> & {
|
||||
onChange: (value: { filePath: string | null; contentType: string | null }) => void;
|
||||
filePath: string | null;
|
||||
nameOverride?: string | null;
|
||||
inline?: boolean;
|
||||
};
|
||||
|
||||
export interface HostPromptArgs {
|
||||
id: string;
|
||||
title: ReactNode;
|
||||
label: string;
|
||||
description?: ReactNode;
|
||||
placeholder?: string;
|
||||
defaultValue?: string;
|
||||
confirmText?: string;
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
export type HostDialogArgs = {
|
||||
id: string;
|
||||
render: ComponentType<{ hide: () => void }>;
|
||||
} & Omit<DialogProps, "open" | "children" | "onClose">;
|
||||
|
||||
export type StoredValueNamespace = "global" | "no_sync";
|
||||
|
||||
/** Like `UseStoredValue`, but told whether the value is a synced preference or local state */
|
||||
export type UseHostStoredValue = <T extends StoredValue>(
|
||||
key: string | string[] | null,
|
||||
fallback: T,
|
||||
namespace?: StoredValueNamespace,
|
||||
) => readonly [T, SetStoredValue<T>];
|
||||
|
||||
/**
|
||||
* What shared editing components get from the app they run in. The client provides its
|
||||
* templated editor, file picker, dialogs and key-value store; anything else (the proxy) gets
|
||||
* plain `CodeEditor`s, in-memory state, and no dialogs.
|
||||
*/
|
||||
export interface EditorHost {
|
||||
Editor: ComponentType<HostEditorProps>;
|
||||
Input: ComponentType<HostInputProps>;
|
||||
SelectFile: ComponentType<SelectFileProps> | null;
|
||||
showDialog: ((args: HostDialogArgs) => void) | null;
|
||||
showPrompt: ((args: HostPromptArgs) => Promise<string | null>) | null;
|
||||
basename: (path: string) => Promise<string | null>;
|
||||
useStoredValue: UseHostStoredValue;
|
||||
/** Where a `DetailsBanner` with a `storageKey` keeps whether it's open */
|
||||
useDetailsBannerStoredValue: UseStoredValue;
|
||||
ErrorBoundary: ComponentType<{ name: string; children: ReactNode }>;
|
||||
/** The text viewer, with whatever the app adds to it (formatting, links) */
|
||||
TextViewer: ComponentType<TextViewerProps>;
|
||||
/** The multipart viewer, with whatever the app adds to it (a PDF viewer) */
|
||||
MultipartViewer: ComponentType<MultipartViewerProps>;
|
||||
/** Viewers only the app has, like the client's PDF viewer; null to use the shared ones */
|
||||
renderBodyViewer?: (args: HostBodyViewerArgs) => ReactNode | null;
|
||||
/** Open a URL outside the app */
|
||||
openUrl: ((url: string) => void) | null;
|
||||
/** Copy text to the clipboard, quietly, as rows of values do */
|
||||
copy: (text: string) => void;
|
||||
}
|
||||
|
||||
export interface HostBodyViewerArgs {
|
||||
/** Which body: a response's, or the request body it was sent with */
|
||||
source: "response" | "request";
|
||||
/** The media type, without parameters */
|
||||
mimeType: string | null;
|
||||
viewMode: "pretty" | "raw";
|
||||
body: HttpBodyLoader;
|
||||
/** Whether the whole body has arrived */
|
||||
complete: boolean;
|
||||
}
|
||||
|
||||
const defaultEditorHost: EditorHost = {
|
||||
ErrorBoundary,
|
||||
useDetailsBannerStoredValue: useInMemoryStoredValue,
|
||||
TextViewer,
|
||||
MultipartViewer,
|
||||
openUrl: null,
|
||||
copy: (text) => {
|
||||
navigator.clipboard.writeText(text).catch(console.error);
|
||||
},
|
||||
Editor: PlainEditor,
|
||||
Input: PlainInputEditor,
|
||||
SelectFile: null,
|
||||
showDialog: null,
|
||||
showPrompt: null,
|
||||
basename: async (path) => path.split(/[\\/]/).pop() ?? null,
|
||||
useStoredValue: useInMemoryStoredValue,
|
||||
};
|
||||
|
||||
const EditorHostContext = createContext<EditorHost>(defaultEditorHost);
|
||||
|
||||
export function EditorHostProvider({
|
||||
value,
|
||||
children,
|
||||
}: {
|
||||
value: Partial<EditorHost>;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const parent = useContext(EditorHostContext);
|
||||
const merged = useMemo(() => ({ ...parent, ...value }), [parent, value]);
|
||||
return <EditorHostContext.Provider value={merged}>{children}</EditorHostContext.Provider>;
|
||||
}
|
||||
|
||||
export function useEditorHost(): EditorHost {
|
||||
return useContext(EditorHostContext);
|
||||
}
|
||||
|
||||
/** Drops what only a host's editor understands, leaving what `CodeEditor` does */
|
||||
function stripTemplating<T extends TemplatingProps & { language?: HostEditorLanguage }>({
|
||||
autocomplete: _autocomplete,
|
||||
autocompleteFunctions: _autocompleteFunctions,
|
||||
autocompleteVariables: _autocompleteVariables,
|
||||
forcedEnvironmentId: _forcedEnvironmentId,
|
||||
extraExtensions,
|
||||
language,
|
||||
...props
|
||||
}: T) {
|
||||
return {
|
||||
...props,
|
||||
extensions: extraExtensions,
|
||||
language: language === "pairs" || language === "url" ? null : language,
|
||||
};
|
||||
}
|
||||
|
||||
function PlainEditor(props: HostEditorProps) {
|
||||
return <LazyCodeEditor {...stripTemplating(props)} />;
|
||||
}
|
||||
|
||||
function PlainInputEditor({ showOptionsPicker: _showOptionsPicker, ...props }: HostInputProps) {
|
||||
return <Input {...stripTemplating(props)} />;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import classNames from "classnames";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
wrapperClassName?: string;
|
||||
}
|
||||
|
||||
export function EmptyStateText({ children, className, wrapperClassName }: Props) {
|
||||
return (
|
||||
<div className={classNames("w-full h-full pb-2", wrapperClassName)}>
|
||||
<div
|
||||
className={classNames(
|
||||
className,
|
||||
"rounded-lg border border-dashed border-border-subtle",
|
||||
"h-full py-2 text-text-subtlest flex items-center justify-center italic",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { ErrorInfo, ReactNode } from "react";
|
||||
import { Component } from "react";
|
||||
import { Banner } from "./Banner";
|
||||
import { Button } from "./Button";
|
||||
import { InlineCode } from "./InlineCode";
|
||||
|
||||
export interface ErrorBoundaryProps {
|
||||
name: string;
|
||||
children: ReactNode;
|
||||
/** Shows a button that hands the error over, eg. to open it in a dialog. Without it the message shows inline. */
|
||||
onShowError?: (error: unknown) => void;
|
||||
}
|
||||
|
||||
interface ErrorBoundaryState {
|
||||
hasError: boolean;
|
||||
error: unknown;
|
||||
}
|
||||
|
||||
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
|
||||
constructor(props: ErrorBoundaryProps) {
|
||||
super(props);
|
||||
this.state = { hasError: false, error: null };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: unknown): ErrorBoundaryState {
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
componentDidCatch(error: unknown, info: ErrorInfo) {
|
||||
console.warn("Error caught by ErrorBoundary:", error, info);
|
||||
}
|
||||
|
||||
render() {
|
||||
const { hasError, error } = this.state;
|
||||
if (!hasError) {
|
||||
return this.props.children;
|
||||
}
|
||||
|
||||
const { name, onShowError } = this.props;
|
||||
return (
|
||||
<Banner color="danger" className="flex items-center gap-2 overflow-auto">
|
||||
<div>
|
||||
Error rendering <InlineCode>{name}</InlineCode> component
|
||||
{onShowError == null && `: ${error instanceof Error ? error.message : String(error)}`}
|
||||
</div>
|
||||
{onShowError && (
|
||||
<Button
|
||||
className="inline-flex"
|
||||
variant="border"
|
||||
color="danger"
|
||||
size="2xs"
|
||||
onClick={() => onShowError(error)}
|
||||
>
|
||||
Show
|
||||
</Button>
|
||||
)}
|
||||
</Banner>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { useMemo } from "react";
|
||||
import type { UseStoredValue } from "../hooks/useStoredValue";
|
||||
import { CountBadge } from "./CountBadge";
|
||||
import { DetailsBanner } from "./DetailsBanner";
|
||||
import { KeyValueRow, type KeyValueRowProps, KeyValueRows } from "./KeyValueRow";
|
||||
|
||||
export interface HeadersTableProps {
|
||||
title: ReactNode;
|
||||
headers: { name: string; value: string }[];
|
||||
labelColor?: KeyValueRowProps["labelColor"];
|
||||
defaultOpen?: boolean;
|
||||
storageKey?: string;
|
||||
useStoredValue?: UseStoredValue;
|
||||
}
|
||||
|
||||
export function HeadersTable({
|
||||
title,
|
||||
headers,
|
||||
labelColor,
|
||||
defaultOpen,
|
||||
storageKey,
|
||||
useStoredValue,
|
||||
}: HeadersTableProps) {
|
||||
const sortedHeaders = useMemo(
|
||||
() =>
|
||||
[...headers].sort((a, b) =>
|
||||
a.name.toLocaleLowerCase().localeCompare(b.name.toLocaleLowerCase()),
|
||||
),
|
||||
[headers],
|
||||
);
|
||||
|
||||
return (
|
||||
<DetailsBanner
|
||||
defaultOpen={defaultOpen}
|
||||
storageKey={storageKey}
|
||||
useStoredValue={useStoredValue}
|
||||
summary={
|
||||
<h2 className="flex items-center">
|
||||
{title} <CountBadge showZero count={sortedHeaders.length} />
|
||||
</h2>
|
||||
}
|
||||
>
|
||||
{sortedHeaders.length === 0 ? (
|
||||
<span className="text-text-subtlest text-sm italic">No Headers</span>
|
||||
) : (
|
||||
<KeyValueRows>
|
||||
{sortedHeaders.map((h, i) => (
|
||||
// oxlint-disable-next-line react/no-array-index-key
|
||||
<KeyValueRow labelColor={labelColor} key={i} label={h.name}>
|
||||
{h.value}
|
||||
</KeyValueRow>
|
||||
))}
|
||||
</KeyValueRows>
|
||||
)}
|
||||
</DetailsBanner>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { HStack } from "./Stacks";
|
||||
import classNames from "classnames";
|
||||
import type { HotkeyAction } from "../hooks/useHotKey";
|
||||
import { useFormattedHotkey } from "../hooks/useHotKey";
|
||||
|
||||
interface Props {
|
||||
action: HotkeyAction | null;
|
||||
className?: string;
|
||||
variant?: "text" | "with-bg";
|
||||
}
|
||||
|
||||
export function Hotkey({ action, className, variant }: Props) {
|
||||
const labelParts = useFormattedHotkey(action);
|
||||
if (labelParts === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <HotkeyRaw labelParts={labelParts} className={className} variant={variant} />;
|
||||
}
|
||||
|
||||
interface HotkeyRawProps {
|
||||
labelParts: string[];
|
||||
className?: string;
|
||||
variant?: "text" | "with-bg";
|
||||
}
|
||||
|
||||
export function HotkeyRaw({ labelParts, className, variant }: HotkeyRawProps) {
|
||||
return (
|
||||
<HStack
|
||||
className={classNames(
|
||||
className,
|
||||
variant === "with-bg" &&
|
||||
"rounded-sm bg-surface-highlight px-1 border border-border text-text-subtle",
|
||||
variant === "text" && "text-text-subtlest",
|
||||
)}
|
||||
>
|
||||
{labelParts.map((char, index) => (
|
||||
// oxlint-disable-next-line react/no-array-index-key
|
||||
<div key={index} className="min-w-[1em] text-center">
|
||||
{char}
|
||||
</div>
|
||||
))}
|
||||
</HStack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import classNames from "classnames";
|
||||
import type { HotkeyAction } from "../hooks/useHotKey";
|
||||
import { useHotkeyLabel } from "../hooks/useHotKey";
|
||||
|
||||
interface Props {
|
||||
action: HotkeyAction;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function HotkeyLabel({ action, className }: Props) {
|
||||
const label = useHotkeyLabel(action);
|
||||
return (
|
||||
<span className={classNames(className, "text-text-subtle whitespace-nowrap")}>{label}</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, test, vi } from "vite-plus/test";
|
||||
import type { HotkeyAction } from "../hooks/useHotKey";
|
||||
import { HotkeyList } from "./HotkeyList";
|
||||
|
||||
vi.mock("./Hotkey", () => ({
|
||||
Hotkey: ({ action }: { action: HotkeyAction }) =>
|
||||
action === "sidebar.selected.move" ? null : <span>{action}</span>,
|
||||
}));
|
||||
|
||||
vi.mock("./HotkeyLabel", () => ({
|
||||
HotkeyLabel: ({ action }: { action: HotkeyAction }) => <span>{action}</span>,
|
||||
}));
|
||||
|
||||
describe("HotkeyList", () => {
|
||||
test("keeps a grid cell for actions without a shortcut", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<HotkeyList hotkeys={["sidebar.selected.move", "request.send"]} />,
|
||||
);
|
||||
|
||||
expect(markup).toContain(
|
||||
'<span>sidebar.selected.move</span><div class="ml-4"></div><span>request.send</span>',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import classNames from "classnames";
|
||||
import type { ReactNode } from "react";
|
||||
import { Fragment } from "react";
|
||||
import type { HotkeyAction } from "../hooks/useHotKey";
|
||||
import { Hotkey } from "./Hotkey";
|
||||
import { HotkeyLabel } from "./HotkeyLabel";
|
||||
|
||||
interface Props {
|
||||
hotkeys: HotkeyAction[];
|
||||
bottomSlot?: ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const HotkeyList = ({ hotkeys, bottomSlot, className }: Props) => {
|
||||
return (
|
||||
<div className={classNames(className, "h-full flex items-center justify-center")}>
|
||||
<div className="grid gap-2 grid-cols-[auto_auto]">
|
||||
{hotkeys.map((hotkey) => (
|
||||
<Fragment key={hotkey}>
|
||||
<HotkeyLabel className="truncate" action={hotkey} />
|
||||
{/* Keep this grid cell when Hotkey renders nothing so later rows stay aligned. */}
|
||||
<div className="ml-4">
|
||||
<Hotkey action={hotkey} />
|
||||
</div>
|
||||
</Fragment>
|
||||
))}
|
||||
{bottomSlot}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
ArrowUpFromLineIcon,
|
||||
ArrowUpIcon,
|
||||
BadgeCheckIcon,
|
||||
BookmarkIcon,
|
||||
BookOpenText,
|
||||
BoxIcon,
|
||||
CakeIcon,
|
||||
@@ -118,6 +119,7 @@ import {
|
||||
RotateCcwIcon,
|
||||
Rows2Icon,
|
||||
SaveIcon,
|
||||
ScissorsIcon,
|
||||
SearchIcon,
|
||||
SendHorizontalIcon,
|
||||
SettingsIcon,
|
||||
@@ -165,6 +167,7 @@ const icons = {
|
||||
arrow_up_from_dot: ArrowUpFromDotIcon,
|
||||
arrow_up_from_line: ArrowUpFromLineIcon,
|
||||
badge_check: BadgeCheckIcon,
|
||||
bookmark: BookmarkIcon,
|
||||
book_open_text: BookOpenText,
|
||||
box: BoxIcon,
|
||||
cake: CakeIcon,
|
||||
@@ -264,6 +267,7 @@ const icons = {
|
||||
rotate_ccw: RotateCcwIcon,
|
||||
rows_2: Rows2Icon,
|
||||
save: SaveIcon,
|
||||
scissors: ScissorsIcon,
|
||||
search: SearchIcon,
|
||||
send_horizontal: SendHorizontalIcon,
|
||||
settings: SettingsIcon,
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Icon, type IconProps } from "./Icon";
|
||||
import type { TooltipProps } from "./Tooltip";
|
||||
import { Tooltip } from "./Tooltip";
|
||||
|
||||
type Props = Omit<TooltipProps, "children"> & {
|
||||
icon?: IconProps["icon"];
|
||||
iconSize?: IconProps["size"];
|
||||
iconColor?: IconProps["color"];
|
||||
className?: string;
|
||||
tabIndex?: number;
|
||||
};
|
||||
|
||||
export function IconTooltip({
|
||||
content,
|
||||
icon = "info",
|
||||
iconColor,
|
||||
iconSize,
|
||||
...tooltipProps
|
||||
}: Props) {
|
||||
return (
|
||||
<Tooltip content={content} {...tooltipProps}>
|
||||
<Icon
|
||||
className="opacity-60 hover:opacity-100"
|
||||
icon={icon}
|
||||
size={iconSize}
|
||||
color={iconColor}
|
||||
/>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { generateId } from "@yaakapp-internal/lib/generateId";
|
||||
import type { Color } from "@yaakapp-internal/plugins";
|
||||
import classNames from "classnames";
|
||||
import type { ReactNode } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useStateWithDeps } from "../hooks/useStateWithDeps";
|
||||
import type { CodeEditorProps } from "./editor/CodeEditor";
|
||||
import { LazyCodeEditor } from "./editor/LazyCodeEditor";
|
||||
import { IconButton } from "./IconButton";
|
||||
import { Label } from "./Label";
|
||||
import { HStack } from "./Stacks";
|
||||
|
||||
export type InputProps = Pick<
|
||||
CodeEditorProps,
|
||||
| "language"
|
||||
| "forceUpdateKey"
|
||||
| "disabled"
|
||||
| "autoFocus"
|
||||
| "autoSelect"
|
||||
| "extensions"
|
||||
| "onKeyDown"
|
||||
| "readOnly"
|
||||
> & {
|
||||
className?: string;
|
||||
containerClassName?: string;
|
||||
inputWrapperClassName?: string;
|
||||
defaultValue?: string | null;
|
||||
disableObscureToggle?: boolean;
|
||||
fullHeight?: boolean;
|
||||
hideLabel?: boolean;
|
||||
help?: ReactNode;
|
||||
label: ReactNode;
|
||||
labelClassName?: string;
|
||||
labelPosition?: "top" | "left";
|
||||
leftSlot?: ReactNode;
|
||||
multiLine?: boolean;
|
||||
name?: string;
|
||||
onBlur?: () => void;
|
||||
onChange?: (value: string) => void;
|
||||
onFocus?: () => void;
|
||||
onPaste?: (value: string) => void;
|
||||
onPasteOverwrite?: CodeEditorProps["onPasteOverwrite"];
|
||||
placeholder?: string;
|
||||
/** Renders the editor, for a host whose editor builds on CodeEditor */
|
||||
renderEditor?: (props: CodeEditorProps) => ReactNode;
|
||||
/** Rendered beside the right slot, given a way to replace the whole value */
|
||||
renderOptionsPicker?: (insert: (value: string) => void) => ReactNode;
|
||||
required?: boolean;
|
||||
rightSlot?: ReactNode;
|
||||
size?: "2xs" | "xs" | "sm" | "md" | "auto";
|
||||
stateKey: CodeEditorProps["stateKey"];
|
||||
tint?: Color;
|
||||
type?: "text" | "password";
|
||||
validate?: boolean | ((v: string) => boolean);
|
||||
wrapLines?: boolean;
|
||||
setRef?: (h: InputHandle | null) => void;
|
||||
};
|
||||
|
||||
export interface InputHandle {
|
||||
focus: () => void;
|
||||
isFocused: () => boolean;
|
||||
value: () => string;
|
||||
selectAll: () => void;
|
||||
dispatch: EditorView["dispatch"];
|
||||
}
|
||||
|
||||
function renderCodeEditor(props: CodeEditorProps) {
|
||||
return <LazyCodeEditor {...props} />;
|
||||
}
|
||||
|
||||
export function Input({
|
||||
className,
|
||||
containerClassName,
|
||||
defaultValue,
|
||||
disableObscureToggle,
|
||||
disabled,
|
||||
forceUpdateKey,
|
||||
fullHeight,
|
||||
help,
|
||||
hideLabel,
|
||||
inputWrapperClassName,
|
||||
label,
|
||||
labelClassName,
|
||||
labelPosition = "top",
|
||||
leftSlot,
|
||||
multiLine,
|
||||
onBlur,
|
||||
onChange,
|
||||
onFocus,
|
||||
onPaste,
|
||||
onPasteOverwrite,
|
||||
placeholder,
|
||||
readOnly,
|
||||
required,
|
||||
renderEditor,
|
||||
renderOptionsPicker,
|
||||
rightSlot,
|
||||
size = "md",
|
||||
stateKey,
|
||||
tint,
|
||||
type = "text",
|
||||
validate,
|
||||
wrapLines,
|
||||
setRef,
|
||||
...props
|
||||
}: InputProps) {
|
||||
const [focused, setFocused] = useState(false);
|
||||
const [obscured, setObscured] = useStateWithDeps(type === "password", [type]);
|
||||
const [hasChanged, setHasChanged] = useStateWithDeps<boolean>(false, [forceUpdateKey]);
|
||||
const editorRef = useRef<EditorView | null>(null);
|
||||
const skipNextFocus = useRef<boolean>(false);
|
||||
|
||||
const handle = useMemo<InputHandle>(
|
||||
() => ({
|
||||
focus: () => {
|
||||
if (editorRef.current == null) return;
|
||||
const anchor = editorRef.current.state.doc.length;
|
||||
skipNextFocus.current = true;
|
||||
editorRef.current.focus();
|
||||
editorRef.current.dispatch({ selection: { anchor, head: anchor }, scrollIntoView: true });
|
||||
},
|
||||
isFocused: () => editorRef.current?.hasFocus ?? false,
|
||||
value: () => editorRef.current?.state.doc.toString() ?? "",
|
||||
dispatch: (...args) => {
|
||||
// oxlint-disable-next-line no-explicit-any
|
||||
editorRef.current?.dispatch(...(args as any));
|
||||
},
|
||||
selectAll() {
|
||||
if (editorRef.current == null) return;
|
||||
editorRef.current.focus();
|
||||
editorRef.current.dispatch({
|
||||
selection: { anchor: 0, head: editorRef.current.state.doc.length },
|
||||
});
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
// Replace the whole value with a picked option. Dispatching runs it through the editor's
|
||||
// onChange, same as typing, so callers see one consistent change path.
|
||||
const insertOption = useCallback((value: string) => {
|
||||
const view = editorRef.current;
|
||||
if (view == null) return;
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } });
|
||||
view.focus();
|
||||
}, []);
|
||||
|
||||
const setEditorRef = useCallback(
|
||||
(h: EditorView | null) => {
|
||||
editorRef.current = h;
|
||||
setRef?.(handle);
|
||||
},
|
||||
[handle, setRef],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const fn = () => {
|
||||
skipNextFocus.current = true;
|
||||
};
|
||||
window.addEventListener("focus", fn);
|
||||
return () => {
|
||||
window.removeEventListener("focus", fn);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleFocus = useCallback(() => {
|
||||
if (readOnly) return;
|
||||
|
||||
if (!skipNextFocus.current) {
|
||||
editorRef.current?.dispatch({
|
||||
selection: { anchor: 0, head: editorRef.current.state.doc.length },
|
||||
});
|
||||
}
|
||||
|
||||
setFocused(true);
|
||||
onFocus?.();
|
||||
skipNextFocus.current = false;
|
||||
}, [onFocus, readOnly]);
|
||||
|
||||
const handleBlur = useCallback(async () => {
|
||||
setFocused(false);
|
||||
// Move selection to the end on blur
|
||||
const anchor = editorRef.current?.state.doc.length ?? 0;
|
||||
editorRef.current?.dispatch({
|
||||
selection: { anchor, head: anchor },
|
||||
});
|
||||
onBlur?.();
|
||||
}, [onBlur]);
|
||||
|
||||
const id = useRef(`input-${generateId()}`);
|
||||
const editorClassName = classNames(
|
||||
className,
|
||||
"bg-transparent! min-w-0 h-auto w-full focus:outline-hidden placeholder:text-placeholder",
|
||||
);
|
||||
|
||||
const isValid = useMemo(() => {
|
||||
if (required && !validateRequire(defaultValue ?? "")) return false;
|
||||
if (typeof validate === "boolean") return validate;
|
||||
if (typeof validate === "function" && !validate(defaultValue ?? "")) return false;
|
||||
return true;
|
||||
}, [required, defaultValue, validate]);
|
||||
|
||||
const handleChange = useCallback(
|
||||
(value: string) => {
|
||||
onChange?.(value);
|
||||
setHasChanged(true);
|
||||
},
|
||||
[onChange, setHasChanged],
|
||||
);
|
||||
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Submit the nearest form on Enter key press
|
||||
const handleKeyDown = useCallback(
|
||||
(e: KeyboardEvent) => {
|
||||
if (e.key !== "Enter") return;
|
||||
|
||||
const form = wrapperRef.current?.closest("form");
|
||||
if (!isValid || form == null) return;
|
||||
|
||||
form?.dispatchEvent(new Event("submit", { cancelable: true, bubbles: true }));
|
||||
},
|
||||
[isValid],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={wrapperRef}
|
||||
className={classNames(
|
||||
"pointer-events-auto", // Just in case we're placing in disabled parent
|
||||
"w-full",
|
||||
fullHeight && "h-full",
|
||||
labelPosition === "left" && "flex items-center gap-2",
|
||||
labelPosition === "top" && "flex-row gap-0.5",
|
||||
)}
|
||||
>
|
||||
<Label
|
||||
htmlFor={id.current}
|
||||
help={help}
|
||||
required={required}
|
||||
visuallyHidden={hideLabel}
|
||||
className={classNames(labelClassName)}
|
||||
>
|
||||
{label}
|
||||
</Label>
|
||||
<HStack
|
||||
alignItems="stretch"
|
||||
className={classNames(
|
||||
containerClassName,
|
||||
fullHeight && "h-full",
|
||||
"x-theme-input",
|
||||
"relative w-full rounded-md text overflow-hidden",
|
||||
"border",
|
||||
focused && !disabled ? "border-border-focus" : "border-border",
|
||||
disabled && "border-dotted",
|
||||
!isValid && hasChanged && "border-danger!",
|
||||
size === "md" && "min-h-md",
|
||||
size === "sm" && "min-h-sm",
|
||||
size === "xs" && "min-h-xs",
|
||||
size === "2xs" && "min-h-2xs",
|
||||
)}
|
||||
>
|
||||
{tint != null && (
|
||||
<div
|
||||
aria-hidden
|
||||
className={classNames(
|
||||
"absolute inset-0 opacity-5 pointer-events-none",
|
||||
tint === "primary" && "bg-primary",
|
||||
tint === "secondary" && "bg-secondary",
|
||||
tint === "info" && "bg-info",
|
||||
tint === "success" && "bg-success",
|
||||
tint === "notice" && "bg-notice",
|
||||
tint === "warning" && "bg-warning",
|
||||
tint === "danger" && "bg-danger",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{leftSlot}
|
||||
<HStack
|
||||
className={classNames(
|
||||
inputWrapperClassName,
|
||||
"flex-1 min-w-0 px-2",
|
||||
fullHeight && "h-full",
|
||||
leftSlot ? "pl-0" : null,
|
||||
rightSlot ? "pr-0" : null,
|
||||
)}
|
||||
>
|
||||
{(renderEditor ?? renderCodeEditor)({
|
||||
setRef: setEditorRef,
|
||||
id: id.current,
|
||||
hideGutter: true,
|
||||
singleLine: !multiLine,
|
||||
containerOnly: true,
|
||||
stateKey,
|
||||
wrapLines,
|
||||
heightMode: "auto",
|
||||
onKeyDown: handleKeyDown,
|
||||
type: type === "password" && !obscured ? "text" : type,
|
||||
defaultValue,
|
||||
forceUpdateKey,
|
||||
placeholder,
|
||||
onChange: handleChange,
|
||||
onPaste,
|
||||
onPasteOverwrite,
|
||||
disabled,
|
||||
className: classNames(
|
||||
editorClassName,
|
||||
multiLine && size === "md" && "py-1.5",
|
||||
multiLine && size === "sm" && "py-1",
|
||||
multiLine && (size === "xs" || size === "2xs") && "py-0.5",
|
||||
),
|
||||
onFocus: handleFocus,
|
||||
onBlur: handleBlur,
|
||||
readOnly,
|
||||
...props,
|
||||
})}
|
||||
</HStack>
|
||||
{type === "password" && !disableObscureToggle && (
|
||||
<IconButton
|
||||
title={
|
||||
obscured
|
||||
? `Show ${typeof label === "string" ? label : "field"}`
|
||||
: `Obscure ${typeof label === "string" ? label : "field"}`
|
||||
}
|
||||
size="xs"
|
||||
className={classNames("mr-0.5 h-auto! my-0.5", disabled && "opacity-disabled")}
|
||||
color={tint}
|
||||
// iconClassName={classNames(
|
||||
// tint === 'primary' && 'text-primary',
|
||||
// tint === 'secondary' && 'text-secondary',
|
||||
// tint === 'info' && 'text-info',
|
||||
// tint === 'success' && 'text-success',
|
||||
// tint === 'notice' && 'text-notice',
|
||||
// tint === 'warning' && 'text-warning',
|
||||
// tint === 'danger' && 'text-danger',
|
||||
// )}
|
||||
iconSize="sm"
|
||||
icon={obscured ? "eye" : "eye_closed"}
|
||||
onClick={() => setObscured((o) => !o)}
|
||||
/>
|
||||
)}
|
||||
{renderOptionsPicker?.(insertOption)}
|
||||
{rightSlot}
|
||||
</HStack>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function validateRequire(v: string) {
|
||||
return v.length > 0;
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import classNames from "classnames";
|
||||
import type { HTMLAttributes, ReactElement, ReactNode } from "react";
|
||||
import { CopyIconButton } from "./CopyIconButton";
|
||||
|
||||
interface Props {
|
||||
children:
|
||||
| ReactElement<HTMLAttributes<HTMLTableColElement>>
|
||||
| (ReactElement<HTMLAttributes<HTMLTableColElement>> | null)[];
|
||||
selectable?: boolean;
|
||||
}
|
||||
|
||||
export function KeyValueRows({ children, selectable }: Props) {
|
||||
const childArray = Array.isArray(children) ? children.filter(Boolean) : [children];
|
||||
return (
|
||||
<table
|
||||
className={classNames(
|
||||
"text-editor font-mono min-w-0 w-full mb-auto",
|
||||
selectable &&
|
||||
"[&_td]:select-auto [&_td]:cursor-auto [&_td_*]:select-auto [&_td_*]:cursor-auto",
|
||||
)}
|
||||
>
|
||||
<tbody className="divide-y divide-surface-highlight">
|
||||
{childArray.map((child, i) => (
|
||||
// oxlint-disable-next-line react/no-array-index-key
|
||||
<tr key={i}>{child}</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
export interface KeyValueRowProps {
|
||||
label: ReactNode;
|
||||
children: ReactNode;
|
||||
rightSlot?: ReactNode;
|
||||
leftSlot?: ReactNode;
|
||||
align?: "top" | "middle";
|
||||
labelClassName?: string;
|
||||
labelColor?: "secondary" | "primary" | "info";
|
||||
enableCopy?: boolean;
|
||||
copyText?: string;
|
||||
/** Copies a value for `enableCopy`, which shows no button without it */
|
||||
copy?: (text: string) => void;
|
||||
}
|
||||
|
||||
export function KeyValueRow({
|
||||
label,
|
||||
children,
|
||||
rightSlot,
|
||||
leftSlot,
|
||||
align = "top",
|
||||
labelColor = "secondary",
|
||||
labelClassName,
|
||||
enableCopy,
|
||||
copyText,
|
||||
copy,
|
||||
}: KeyValueRowProps) {
|
||||
const textToCopy =
|
||||
copyText ??
|
||||
(typeof children === "string" || typeof children === "number" ? `${children}` : null);
|
||||
const copyTitle =
|
||||
typeof label === "string" || typeof label === "number" ? `Copy ${label}` : "Copy value";
|
||||
const resolvedRightSlot =
|
||||
rightSlot ??
|
||||
(enableCopy && copy != null && textToCopy != null ? (
|
||||
<CopyIconButton
|
||||
text={textToCopy}
|
||||
copy={copy}
|
||||
className="text-text-subtle"
|
||||
size="2xs"
|
||||
title={copyTitle}
|
||||
iconSize="sm"
|
||||
/>
|
||||
) : null);
|
||||
|
||||
return (
|
||||
<>
|
||||
<td
|
||||
className={classNames(
|
||||
"select-none py-0.5 pr-2 h-full max-w-40",
|
||||
align === "top" && "align-top",
|
||||
align === "middle" && "align-middle",
|
||||
labelClassName,
|
||||
labelColor === "primary" && "text-primary",
|
||||
labelColor === "secondary" && "text-text-subtle",
|
||||
labelColor === "info" && "text-info",
|
||||
)}
|
||||
>
|
||||
<span className="select-text cursor-text">{label}</span>
|
||||
</td>
|
||||
<td
|
||||
className={classNames(
|
||||
"select-none py-0.5 break-all max-w-60",
|
||||
align === "top" && "align-top",
|
||||
align === "middle" && "align-middle",
|
||||
)}
|
||||
>
|
||||
<div className="select-text cursor-text max-h-48 overflow-y-auto grid grid-cols-[auto_minmax(0,1fr)_auto]">
|
||||
{leftSlot ?? <span aria-hidden />}
|
||||
{children}
|
||||
{resolvedRightSlot ? (
|
||||
<div className="ml-1.5">{resolvedRightSlot}</div>
|
||||
) : (
|
||||
<span aria-hidden />
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import classNames from "classnames";
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import { IconTooltip } from "./IconTooltip";
|
||||
|
||||
export function Label({
|
||||
htmlFor,
|
||||
className,
|
||||
children,
|
||||
visuallyHidden,
|
||||
tags = [],
|
||||
required,
|
||||
rightSlot,
|
||||
help,
|
||||
...props
|
||||
}: HTMLAttributes<HTMLLabelElement> & {
|
||||
htmlFor: string | null;
|
||||
required?: boolean;
|
||||
tags?: string[];
|
||||
visuallyHidden?: boolean;
|
||||
rightSlot?: ReactNode;
|
||||
children: ReactNode;
|
||||
help?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<label
|
||||
htmlFor={htmlFor ?? undefined}
|
||||
className={classNames(
|
||||
className,
|
||||
visuallyHidden && "sr-only",
|
||||
"shrink-0 text-sm",
|
||||
"text-text-subtle whitespace-nowrap flex items-center gap-1 mb-0.5",
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span>
|
||||
{children}
|
||||
{required === true && <span className="text-text-subtlest">*</span>}
|
||||
</span>
|
||||
{tags.map((tag, i) => (
|
||||
// oxlint-disable-next-line react/no-array-index-key
|
||||
<span key={i} className="text-xs text-text-subtlest">
|
||||
({tag})
|
||||
</span>
|
||||
))}
|
||||
{help && <IconTooltip tabIndex={-1} content={help} />}
|
||||
{rightSlot && <div className="ml-auto">{rightSlot}</div>}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import classNames from "classnames";
|
||||
import type { ButtonProps } from "./Button";
|
||||
import { Button } from "./Button";
|
||||
|
||||
export function PillButton({ className, ...props }: ButtonProps) {
|
||||
return (
|
||||
<Button
|
||||
size="2xs"
|
||||
variant="border"
|
||||
className={classNames(className, "rounded-full! mx-1 px-3!")}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import classNames from "classnames";
|
||||
import type { FocusEvent, InputHTMLAttributes, ReactNode } from "react";
|
||||
import {
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { generateId } from "@yaakapp-internal/lib/generateId";
|
||||
import { useRandomKey } from "../hooks/useRandomKey";
|
||||
import { useStateWithDeps } from "../hooks/useStateWithDeps";
|
||||
import { IconButton } from "./IconButton";
|
||||
import type { InputProps } from "./Input";
|
||||
import { Label } from "./Label";
|
||||
import { HStack } from "./Stacks";
|
||||
|
||||
export type PlainInputProps = Omit<
|
||||
InputProps,
|
||||
| "wrapLines"
|
||||
| "onKeyDown"
|
||||
| "type"
|
||||
| "stateKey"
|
||||
| "extensions"
|
||||
| "renderEditor"
|
||||
| "renderOptionsPicker"
|
||||
| "language"
|
||||
> &
|
||||
Pick<InputHTMLAttributes<HTMLInputElement>, "inputMode" | "onKeyDownCapture" | "step"> & {
|
||||
onFocusRaw?: InputHTMLAttributes<HTMLInputElement>["onFocus"];
|
||||
type?: "text" | "password" | "number";
|
||||
hideObscureToggle?: boolean;
|
||||
labelRightSlot?: ReactNode;
|
||||
/** Ignored, so a field's props can go to `Input` or `PlainInput` alike */
|
||||
language?: string | null;
|
||||
/** Ignored, as `language` is */
|
||||
showOptionsPicker?: boolean;
|
||||
};
|
||||
|
||||
declare module "react" {
|
||||
interface HTMLAttributes<T> {
|
||||
// Not in @types/react yet; opts editable elements out of macOS Writing Tools
|
||||
writingsuggestions?: "true" | "false";
|
||||
}
|
||||
}
|
||||
|
||||
export const PlainInput = forwardRef<{ focus: () => void }, PlainInputProps>(function PlainInput(
|
||||
{
|
||||
autoFocus,
|
||||
autoSelect,
|
||||
className,
|
||||
containerClassName,
|
||||
defaultValue,
|
||||
disabled,
|
||||
forceUpdateKey: forceUpdateKeyFromAbove,
|
||||
help,
|
||||
hideLabel,
|
||||
hideObscureToggle,
|
||||
label,
|
||||
labelClassName,
|
||||
labelPosition = "top",
|
||||
labelRightSlot,
|
||||
inputMode,
|
||||
leftSlot,
|
||||
name,
|
||||
onBlur,
|
||||
onChange,
|
||||
onFocus,
|
||||
onFocusRaw,
|
||||
onKeyDownCapture,
|
||||
onPaste,
|
||||
placeholder,
|
||||
required,
|
||||
rightSlot,
|
||||
size = "md",
|
||||
step,
|
||||
tint,
|
||||
type = "text",
|
||||
validate,
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
// Track a local key for updates. If the default value is changed when the input is not in focus,
|
||||
// regenerate this to force the field to update.
|
||||
const [focusedUpdateKey, regenerateFocusedUpdateKey] = useRandomKey();
|
||||
const forceUpdateKey = `${forceUpdateKeyFromAbove}::${focusedUpdateKey}`;
|
||||
|
||||
const [obscured, setObscured] = useStateWithDeps(type === "password", [type]);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const [hasChanged, setHasChanged] = useStateWithDeps<boolean>(false, [forceUpdateKey]);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useImperativeHandle<{ focus: () => void } | null, { focus: () => void } | null>(
|
||||
ref,
|
||||
() => inputRef.current,
|
||||
);
|
||||
|
||||
const handleFocus = useCallback(
|
||||
(e: FocusEvent<HTMLInputElement>) => {
|
||||
onFocusRaw?.(e);
|
||||
setFocused(true);
|
||||
if (autoSelect) {
|
||||
inputRef.current?.select();
|
||||
textareaRef.current?.select();
|
||||
}
|
||||
onFocus?.();
|
||||
},
|
||||
[autoSelect, onFocus, onFocusRaw],
|
||||
);
|
||||
|
||||
const handleBlur = useCallback(() => {
|
||||
setFocused(false);
|
||||
onBlur?.();
|
||||
}, [onBlur]);
|
||||
|
||||
// Force input to update when receiving change and not in focus
|
||||
useLayoutEffect(() => {
|
||||
const isFocused = document.activeElement === inputRef.current;
|
||||
if (defaultValue != null && !isFocused) {
|
||||
regenerateFocusedUpdateKey();
|
||||
}
|
||||
}, [regenerateFocusedUpdateKey, defaultValue]);
|
||||
|
||||
const id = useRef(`input-${generateId()}`);
|
||||
const commonClassName = classNames(
|
||||
className,
|
||||
"bg-transparent! min-w-0 w-full focus:outline-hidden placeholder:text-placeholder",
|
||||
"px-2 text-xs font-mono cursor-text",
|
||||
);
|
||||
|
||||
const handleChange = useCallback(
|
||||
(value: string) => {
|
||||
onChange?.(value);
|
||||
setHasChanged(true);
|
||||
const isValid = (value: string) => {
|
||||
if (required && !validateRequire(value)) return false;
|
||||
if (typeof validate === "boolean") return validate;
|
||||
if (typeof validate === "function" && !validate(value)) return false;
|
||||
return true;
|
||||
};
|
||||
inputRef.current?.setCustomValidity(isValid(value) ? "" : "Invalid value");
|
||||
},
|
||||
[onChange, required, setHasChanged, validate],
|
||||
);
|
||||
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={wrapperRef}
|
||||
className={classNames(
|
||||
"w-full",
|
||||
"pointer-events-auto", // Just in case we're placing in disabled parent
|
||||
labelPosition === "left" && "flex items-center gap-2",
|
||||
labelPosition === "top" && "flex-row gap-0.5",
|
||||
)}
|
||||
>
|
||||
<Label
|
||||
htmlFor={id.current}
|
||||
className={labelClassName}
|
||||
visuallyHidden={hideLabel}
|
||||
required={required}
|
||||
help={help}
|
||||
rightSlot={labelRightSlot}
|
||||
>
|
||||
{label}
|
||||
</Label>
|
||||
<HStack
|
||||
alignItems="stretch"
|
||||
className={classNames(
|
||||
containerClassName,
|
||||
"x-theme-input",
|
||||
"relative w-full rounded-md text",
|
||||
"border",
|
||||
"overflow-hidden",
|
||||
focused && !disabled ? "border-border-focus" : "border-border-subtle",
|
||||
disabled && "border-dotted",
|
||||
hasChanged && "has-invalid:border-danger", // For built-in HTML validation
|
||||
size === "md" && "min-h-md",
|
||||
size === "sm" && "min-h-sm",
|
||||
size === "xs" && "min-h-xs",
|
||||
size === "2xs" && "min-h-2xs",
|
||||
)}
|
||||
>
|
||||
{tint != null && (
|
||||
<div
|
||||
aria-hidden
|
||||
className={classNames(
|
||||
"absolute inset-0 opacity-5 pointer-events-none",
|
||||
tint === "info" && "bg-info",
|
||||
tint === "warning" && "bg-warning",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{leftSlot}
|
||||
<HStack
|
||||
className={classNames(
|
||||
"w-full min-w-0",
|
||||
leftSlot ? "pl-0.5 -ml-2" : null,
|
||||
rightSlot ? "pr-0.5 -mr-2" : null,
|
||||
)}
|
||||
>
|
||||
<input
|
||||
id={id.current}
|
||||
ref={inputRef}
|
||||
key={forceUpdateKey}
|
||||
type={type === "password" && !obscured ? "text" : type}
|
||||
name={name}
|
||||
// oxlint-disable-next-line jsx-a11y/no-autofocus
|
||||
autoFocus={autoFocus}
|
||||
defaultValue={defaultValue ?? undefined}
|
||||
disabled={disabled}
|
||||
autoComplete="off"
|
||||
autoCapitalize="off"
|
||||
autoCorrect="off"
|
||||
writingsuggestions="false"
|
||||
inputMode={inputMode}
|
||||
onChange={(e) => handleChange(e.target.value)}
|
||||
onPaste={(e) => onPaste?.(e.clipboardData.getData("Text"))}
|
||||
className={classNames(commonClassName, "h-full disabled:opacity-disabled")}
|
||||
onFocus={handleFocus}
|
||||
onBlur={handleBlur}
|
||||
required={required}
|
||||
step={step}
|
||||
placeholder={placeholder}
|
||||
onKeyDownCapture={onKeyDownCapture}
|
||||
/>
|
||||
</HStack>
|
||||
{type === "password" && !hideObscureToggle && (
|
||||
<IconButton
|
||||
title={
|
||||
obscured
|
||||
? `Show ${typeof label === "string" ? label : "field"}`
|
||||
: `Obscure ${typeof label === "string" ? label : "field"}`
|
||||
}
|
||||
size="xs"
|
||||
className="mr-0.5 group/obscure h-auto! my-0.5"
|
||||
iconClassName="group-hover/obscure:text"
|
||||
iconSize="sm"
|
||||
icon={obscured ? "eye" : "eye_closed"}
|
||||
onClick={() => setObscured((o) => !o)}
|
||||
/>
|
||||
)}
|
||||
{rightSlot}
|
||||
</HStack>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
function validateRequire(v: string) {
|
||||
return v.length > 0;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { useMemo } from "react";
|
||||
import type { DropdownItem, DropdownItemSeparator, DropdownProps } from "./Dropdown";
|
||||
import { Dropdown } from "./Dropdown";
|
||||
import { Icon } from "./Icon";
|
||||
|
||||
export type RadioDropdownItem<T = string | null> =
|
||||
| {
|
||||
type?: "default";
|
||||
label: ReactNode;
|
||||
shortLabel?: ReactNode;
|
||||
value: T;
|
||||
rightSlot?: ReactNode;
|
||||
}
|
||||
| DropdownItemSeparator;
|
||||
|
||||
export interface RadioDropdownProps<T = string | null> {
|
||||
value: T;
|
||||
onChange: (value: T) => void;
|
||||
itemsBefore?: DropdownItem[];
|
||||
items: RadioDropdownItem<T>[];
|
||||
itemsAfter?: DropdownItem[];
|
||||
children: DropdownProps["children"];
|
||||
}
|
||||
|
||||
export function RadioDropdown<T = string | null>({
|
||||
value,
|
||||
items,
|
||||
itemsAfter,
|
||||
itemsBefore,
|
||||
onChange,
|
||||
children,
|
||||
}: RadioDropdownProps<T>) {
|
||||
const dropdownItems = useMemo(
|
||||
() => [
|
||||
...((itemsBefore
|
||||
? [
|
||||
...itemsBefore,
|
||||
{
|
||||
type: "separator",
|
||||
hidden: itemsBefore[itemsBefore.length - 1]?.type === "separator",
|
||||
},
|
||||
]
|
||||
: []) as DropdownItem[]),
|
||||
...items.map((item) => {
|
||||
if (item.type === "separator") {
|
||||
return item;
|
||||
}
|
||||
return {
|
||||
key: item.value,
|
||||
label: item.label,
|
||||
rightSlot: item.rightSlot,
|
||||
onSelect: () => onChange(item.value),
|
||||
leftSlot: <Icon icon={value === item.value ? "check" : "empty"} />,
|
||||
} as DropdownItem;
|
||||
}),
|
||||
...((itemsAfter
|
||||
? [{ type: "separator", hidden: itemsAfter[0]?.type === "separator" }, ...itemsAfter]
|
||||
: []) as DropdownItem[]),
|
||||
],
|
||||
[itemsBefore, items, itemsAfter, value, onChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<Dropdown fullWidth items={dropdownItems}>
|
||||
{children}
|
||||
</Dropdown>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
import classNames from "classnames";
|
||||
import type { CSSProperties, MouseEvent as ReactMouseEvent } from "react";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
|
||||
const START_DISTANCE = 7;
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { createHandleDrag } from "./resizeDrag";
|
||||
|
||||
export interface ResizeHandleEvent {
|
||||
x: number;
|
||||
@@ -34,45 +33,47 @@ export function ResizeHandle({
|
||||
}: Props) {
|
||||
const vertical = side === "top";
|
||||
const [isResizing, setIsResizing] = useState<boolean>(false);
|
||||
const moveState = useRef<{
|
||||
move: (e: MouseEvent) => void;
|
||||
up: (e: MouseEvent) => void;
|
||||
calledStart: boolean;
|
||||
xStart: number;
|
||||
yStart: number;
|
||||
} | null>(null);
|
||||
const stopDrag = useRef<(() => void) | null>(null);
|
||||
|
||||
// A handle that goes away mid-drag ends the drag, so its owner is not left resizing
|
||||
useEffect(() => () => stopDrag.current?.(), []);
|
||||
|
||||
const handlePointerDown = useCallback(
|
||||
(e: ReactMouseEvent<HTMLDivElement>) => {
|
||||
function move(e: MouseEvent) {
|
||||
if (moveState.current == null) return;
|
||||
stopDrag.current?.();
|
||||
|
||||
const xDistance = moveState.current.xStart - e.clientX;
|
||||
const yDistance = moveState.current.yStart - e.clientY;
|
||||
const distance = Math.abs(vertical ? yDistance : xDistance);
|
||||
if (moveState.current.calledStart) {
|
||||
onResizeMove?.({
|
||||
x: e.clientX,
|
||||
y: e.clientY,
|
||||
xStart: moveState.current.xStart,
|
||||
yStart: moveState.current.yStart,
|
||||
});
|
||||
} else if (distance > START_DISTANCE) {
|
||||
const drag = createHandleDrag({
|
||||
vertical,
|
||||
xStart: e.clientX,
|
||||
yStart: e.clientY,
|
||||
onResizeStart: () => {
|
||||
onResizeStart?.();
|
||||
moveState.current.calledStart = true;
|
||||
setIsResizing(true);
|
||||
}
|
||||
},
|
||||
onResizeMove,
|
||||
onResizeEnd,
|
||||
});
|
||||
|
||||
function move(e: MouseEvent) {
|
||||
drag.move(e);
|
||||
}
|
||||
|
||||
function removeListeners() {
|
||||
stopDrag.current = null;
|
||||
document.documentElement.removeEventListener("mousemove", move);
|
||||
document.documentElement.removeEventListener("mouseup", up);
|
||||
}
|
||||
|
||||
function up() {
|
||||
removeListeners();
|
||||
setIsResizing(false);
|
||||
moveState.current = null;
|
||||
document.documentElement.removeEventListener("mousemove", move);
|
||||
document.documentElement.removeEventListener("mouseup", up);
|
||||
onResizeEnd?.();
|
||||
drag.up();
|
||||
}
|
||||
|
||||
moveState.current = { calledStart: false, xStart: e.clientX, yStart: e.clientY, move, up };
|
||||
stopDrag.current = () => {
|
||||
removeListeners();
|
||||
drag.abort();
|
||||
};
|
||||
|
||||
document.documentElement.addEventListener("mousemove", move);
|
||||
document.documentElement.addEventListener("mouseup", up);
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { Color } from "@yaakapp-internal/plugins";
|
||||
import type { IconProps } from "./Icon";
|
||||
import { IconButton } from "./IconButton";
|
||||
import classNames from "classnames";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
/**
|
||||
* A single control attached to a labelled separator, rendered between the label
|
||||
* and the rule.
|
||||
*
|
||||
* Declared rather than passed as a node so the separator keeps ownership of the
|
||||
* things that are easy to get wrong by hand: matching the label's colour, and
|
||||
* staying out of the rule's way when the label is long.
|
||||
*/
|
||||
export interface SeparatorAction {
|
||||
icon: IconProps["icon"];
|
||||
/** Tooltip and accessible name. Required — the control is icon-only. */
|
||||
title: string;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
orientation?: "horizontal" | "vertical";
|
||||
dashed?: boolean;
|
||||
className?: string;
|
||||
children?: ReactNode;
|
||||
color?: Color;
|
||||
action?: SeparatorAction;
|
||||
}
|
||||
|
||||
export function Separator({
|
||||
color,
|
||||
className,
|
||||
dashed,
|
||||
orientation = "horizontal",
|
||||
children,
|
||||
action,
|
||||
}: Props) {
|
||||
return (
|
||||
<div role="presentation" className={classNames(className, "flex items-center w-full")}>
|
||||
{children && (
|
||||
<div className="text-sm text-text-subtlest mr-2 whitespace-nowrap">{children}</div>
|
||||
)}
|
||||
{action && (
|
||||
<IconButton
|
||||
size="2xs"
|
||||
iconSize="xs"
|
||||
className="shrink-0 mr-2 -ml-1"
|
||||
// Forced, because the button itself sets `text-text` at full strength.
|
||||
iconClassName="text-text-subtlest!"
|
||||
icon={action.icon}
|
||||
title={action.title}
|
||||
onClick={action.onClick}
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
className={classNames(
|
||||
"opacity-60",
|
||||
// Keep a stub of the line visible no matter how long the label is —
|
||||
// `w-full` alone gets squeezed to nothing by a wide label.
|
||||
orientation === "horizontal" && "min-w-8",
|
||||
color == null && "border-border",
|
||||
color === "primary" && "border-primary",
|
||||
color === "secondary" && "border-secondary",
|
||||
color === "success" && "border-success",
|
||||
color === "notice" && "border-notice",
|
||||
color === "warning" && "border-warning",
|
||||
color === "danger" && "border-danger",
|
||||
color === "info" && "border-info",
|
||||
dashed && "border-dashed",
|
||||
orientation === "horizontal" && "w-full h-0 border-t",
|
||||
orientation === "vertical" && "h-full w-0 border-l",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import classNames from "classnames";
|
||||
import * as m from "motion/react-m";
|
||||
import type { CSSProperties, ReactNode } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useContainerSize } from "../hooks/useContainerSize";
|
||||
import { Overlay } from "./Overlay";
|
||||
import type { ResizeHandleEvent } from "./ResizeHandle";
|
||||
import { ResizeHandle } from "./ResizeHandle";
|
||||
import type { SidebarDrag, SidebarSize } from "./resizeDrag";
|
||||
import { createSidebarDrag, sidebarGridTemplate } from "./resizeDrag";
|
||||
|
||||
const FLOATING_BREAKPOINT = 600;
|
||||
|
||||
@@ -53,44 +55,65 @@ export function SidebarLayout({
|
||||
}, [floating]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const [isResizing, setIsResizing] = useState(false);
|
||||
const startWidth = useRef<number | null>(null);
|
||||
|
||||
const sideWidth = hidden ? 0 : width;
|
||||
// While dragging, the width is written straight to the DOM and only handed to the owner when the
|
||||
// drag ends. Until the owner's props catch up with that (hiding may be saved asynchronously),
|
||||
// keep showing what the drag ended on, so the sidebar does not flash back open.
|
||||
const liveDrag = useRef<SidebarDrag | null>(null);
|
||||
const [committed, setCommitted] = useState<{ from: SidebarSize; to: SidebarSize } | null>(null);
|
||||
|
||||
if (committed != null) {
|
||||
const { from, to } = committed;
|
||||
const settled = (prop: number | boolean, key: keyof SidebarSize) =>
|
||||
prop === to[key] || prop !== from[key];
|
||||
if (settled(hidden, "hidden") && settled(width, "width")) setCommitted(null);
|
||||
}
|
||||
|
||||
const shownWidth = committed?.to.width ?? width;
|
||||
const shownHidden = committed?.to.hidden ?? hidden;
|
||||
const sideWidth = shownHidden ? 0 : shownWidth;
|
||||
|
||||
const styles = useMemo<CSSProperties>(
|
||||
() => ({
|
||||
gridTemplate: `
|
||||
' ${side.gridArea} ${drag.gridArea} ${body.gridArea}' minmax(0,1fr)
|
||||
/ ${sideWidth}px 0 1fr`,
|
||||
}),
|
||||
() => ({ gridTemplate: sidebarGridTemplate(sideWidth) }),
|
||||
[sideWidth],
|
||||
);
|
||||
|
||||
const handleResizeStart = useCallback(() => {
|
||||
startWidth.current = width;
|
||||
setIsResizing(true);
|
||||
}, [width]);
|
||||
|
||||
const handleResizeEnd = useCallback(() => {
|
||||
setIsResizing(false);
|
||||
startWidth.current = null;
|
||||
const applySize = useCallback((size: SidebarSize) => {
|
||||
if (containerRef.current == null) return;
|
||||
containerRef.current.style.gridTemplate = sidebarGridTemplate(size.hidden ? 0 : size.width);
|
||||
}, []);
|
||||
|
||||
const handleResizeMove = useCallback(
|
||||
({ x, xStart }: ResizeHandleEvent) => {
|
||||
if (startWidth.current == null) return;
|
||||
// Something else re-rendering mid-drag may write the saved width back; put the live one back
|
||||
// before it is painted.
|
||||
useLayoutEffect(() => {
|
||||
const size = liveDrag.current?.size;
|
||||
if (size != null) applySize(size);
|
||||
});
|
||||
|
||||
const newWidth = startWidth.current + (x - xStart);
|
||||
if (newWidth < minWidth) {
|
||||
onHiddenChange?.(true);
|
||||
onWidthChange(defaultWidth);
|
||||
} else {
|
||||
if (hidden) onHiddenChange?.(false);
|
||||
onWidthChange(newWidth);
|
||||
}
|
||||
},
|
||||
[minWidth, hidden, onHiddenChange, onWidthChange, defaultWidth],
|
||||
);
|
||||
const handleResizeStart = useCallback(() => {
|
||||
const from = { width: shownWidth, hidden: shownHidden };
|
||||
liveDrag.current = createSidebarDrag({
|
||||
startWidth: shownWidth,
|
||||
minWidth,
|
||||
defaultWidth,
|
||||
apply: applySize,
|
||||
commit: (to) => {
|
||||
setCommitted({ from, to });
|
||||
if (to.hidden !== from.hidden) onHiddenChange?.(to.hidden);
|
||||
onWidthChange(to.width);
|
||||
},
|
||||
});
|
||||
setIsResizing(true);
|
||||
}, [shownWidth, shownHidden, minWidth, defaultWidth, applySize, onHiddenChange, onWidthChange]);
|
||||
|
||||
const handleResizeMove = useCallback((e: ResizeHandleEvent) => liveDrag.current?.move(e), []);
|
||||
|
||||
const handleResizeEnd = useCallback(() => {
|
||||
const d = liveDrag.current;
|
||||
liveDrag.current = null;
|
||||
d?.end();
|
||||
setIsResizing(false);
|
||||
}, []);
|
||||
|
||||
const handleReset = useCallback(() => {
|
||||
onWidthChange(defaultWidth);
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import classNames from "classnames";
|
||||
import type { CSSProperties, ReactNode } from "react";
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
import { useCallback, useLayoutEffect, useMemo, useRef } from "react";
|
||||
import { useLocalStorage } from "react-use";
|
||||
import { useContainerSize } from "../hooks/useContainerSize";
|
||||
import { clamp } from "../lib/clamp";
|
||||
import type { ResizeHandleEvent } from "./ResizeHandle";
|
||||
import { ResizeHandle } from "./ResizeHandle";
|
||||
import type { SplitDrag } from "./resizeDrag";
|
||||
import { clampSplitRatio, createSplitDrag, splitGridTemplate } from "./resizeDrag";
|
||||
|
||||
export type SplitLayoutLayout = "responsive" | "horizontal" | "vertical";
|
||||
|
||||
@@ -63,71 +64,78 @@ export function SplitLayout({
|
||||
const renderedWidth = clampSplitRatio(width, minWidthPx, size.width);
|
||||
const renderedHeight = secondSlot ? clampSplitRatio(height, minHeightPx, size.height) : 0;
|
||||
|
||||
const styles = useMemo<CSSProperties>(() => {
|
||||
return {
|
||||
const styles = useMemo<CSSProperties>(
|
||||
() => ({
|
||||
...style,
|
||||
gridTemplate: vertical
|
||||
? `
|
||||
' ${areaL.gridArea}' minmax(0,${1 - renderedHeight}fr)
|
||||
' ${areaD.gridArea}' 0
|
||||
' ${areaR.gridArea}' minmax(0,${renderedHeight}fr)
|
||||
/ 1fr
|
||||
`
|
||||
: `
|
||||
' ${areaL.gridArea} ${areaD.gridArea} ${areaR.gridArea}' minmax(0,1fr)
|
||||
/ ${1 - renderedWidth}fr 0 ${renderedWidth}fr
|
||||
`,
|
||||
};
|
||||
}, [style, vertical, renderedHeight, renderedWidth]);
|
||||
gridTemplate: splitGridTemplate(vertical, vertical ? renderedHeight : renderedWidth),
|
||||
}),
|
||||
[style, vertical, renderedHeight, renderedWidth],
|
||||
);
|
||||
|
||||
// While dragging, the split is written straight to the DOM and only saved (and rendered) when
|
||||
// the drag ends, so the panes are not re-rendered on every move.
|
||||
const liveDrag = useRef<SplitDrag | null>(null);
|
||||
|
||||
const applySplit = useCallback((vertical: boolean, ratio: number) => {
|
||||
if (containerRef.current == null) return;
|
||||
containerRef.current.style.gridTemplate = splitGridTemplate(vertical, ratio);
|
||||
}, []);
|
||||
|
||||
// Something else re-rendering mid-drag (a response arriving, say) may write the saved split
|
||||
// back; put the live one back before it is painted.
|
||||
useLayoutEffect(() => {
|
||||
const d = liveDrag.current;
|
||||
if (d?.ratio != null) applySplit(d.vertical, d.ratio);
|
||||
});
|
||||
|
||||
const handleReset = useCallback(() => {
|
||||
if (vertical) setHeight(defaultRatio);
|
||||
else setWidth(defaultRatio);
|
||||
}, [vertical, setHeight, defaultRatio, setWidth]);
|
||||
|
||||
const handleResizeMove = useCallback(
|
||||
(e: ResizeHandleEvent) => {
|
||||
if (containerRef.current === null) return;
|
||||
|
||||
const { paddingLeft, paddingRight, paddingTop, paddingBottom } = getComputedStyle(
|
||||
containerRef.current,
|
||||
);
|
||||
const $c = containerRef.current;
|
||||
const containerWidth =
|
||||
$c.clientWidth - Number.parseFloat(paddingLeft) - Number.parseFloat(paddingRight);
|
||||
const containerHeight =
|
||||
$c.clientHeight - Number.parseFloat(paddingTop) - Number.parseFloat(paddingBottom);
|
||||
|
||||
if ((vertical && containerHeight <= 0) || (!vertical && containerWidth <= 0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const mouseStartX = e.xStart;
|
||||
const mouseStartY = e.yStart;
|
||||
const startWidth = containerWidth * renderedWidth;
|
||||
const startHeight = containerHeight * renderedHeight;
|
||||
|
||||
if (vertical) {
|
||||
const minHeight = Math.min(minHeightPx, containerHeight);
|
||||
const maxHeightPx = Math.max(minHeight, containerHeight - minHeightPx);
|
||||
const newHeightPx = clamp(startHeight - (e.y - mouseStartY), minHeight, maxHeightPx);
|
||||
setHeight(newHeightPx / containerHeight);
|
||||
} else {
|
||||
const minWidth = Math.min(minWidthPx, containerWidth);
|
||||
const maxWidthPx = Math.max(minWidth, containerWidth - minWidthPx);
|
||||
const newWidthPx = clamp(startWidth - (e.x - mouseStartX), minWidth, maxWidthPx);
|
||||
setWidth(newWidthPx / containerWidth);
|
||||
}
|
||||
},
|
||||
[
|
||||
renderedWidth,
|
||||
renderedHeight,
|
||||
const handleResizeStart = useCallback(() => {
|
||||
liveDrag.current = createSplitDrag({
|
||||
vertical,
|
||||
minHeightPx,
|
||||
setHeight,
|
||||
minWidthPx,
|
||||
setWidth,
|
||||
],
|
||||
startRatio: vertical ? renderedHeight : renderedWidth,
|
||||
minPx: vertical ? minHeightPx : minWidthPx,
|
||||
measure: () => {
|
||||
const $c = containerRef.current;
|
||||
if ($c == null) return 0;
|
||||
const { paddingLeft, paddingRight, paddingTop, paddingBottom } = getComputedStyle($c);
|
||||
return vertical
|
||||
? $c.clientHeight - Number.parseFloat(paddingTop) - Number.parseFloat(paddingBottom)
|
||||
: $c.clientWidth - Number.parseFloat(paddingLeft) - Number.parseFloat(paddingRight);
|
||||
},
|
||||
apply: (ratio) => applySplit(vertical, ratio),
|
||||
commit: (ratio) => (vertical ? setHeight(ratio) : setWidth(ratio)),
|
||||
});
|
||||
}, [
|
||||
vertical,
|
||||
renderedHeight,
|
||||
renderedWidth,
|
||||
minHeightPx,
|
||||
minWidthPx,
|
||||
applySplit,
|
||||
setHeight,
|
||||
setWidth,
|
||||
]);
|
||||
|
||||
const handleResizeMove = useCallback((e: ResizeHandleEvent) => liveDrag.current?.move(e), []);
|
||||
|
||||
const handleResizeEnd = useCallback(() => {
|
||||
const d = liveDrag.current;
|
||||
liveDrag.current = null;
|
||||
d?.end();
|
||||
}, []);
|
||||
|
||||
// The container's size changes often (another splitter being dragged, the window resizing) and
|
||||
// re-renders this component; reuse the slots then, so the panes are only re-rendered when the
|
||||
// owner re-renders or the orientation flips.
|
||||
const orientation = vertical ? "vertical" : "horizontal";
|
||||
const first = useMemo(() => firstSlot({ style: areaL, orientation }), [firstSlot, orientation]);
|
||||
const second = useMemo(
|
||||
() => secondSlot?.({ style: areaR, orientation }) ?? null,
|
||||
[secondSlot, orientation],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -136,7 +144,7 @@ export function SplitLayout({
|
||||
style={styles}
|
||||
className={classNames(className, "grid w-full h-full overflow-hidden")}
|
||||
>
|
||||
{firstSlot({ style: areaL, orientation: vertical ? "vertical" : "horizontal" })}
|
||||
{first}
|
||||
{secondSlot && (
|
||||
<>
|
||||
<ResizeHandle
|
||||
@@ -145,24 +153,16 @@ export function SplitLayout({
|
||||
resizeHandleClassName,
|
||||
vertical ? "-translate-y-1" : "-translate-x-1",
|
||||
)}
|
||||
onResizeStart={handleResizeStart}
|
||||
onResizeMove={handleResizeMove}
|
||||
onResizeEnd={handleResizeEnd}
|
||||
onReset={handleReset}
|
||||
side={vertical ? "top" : "left"}
|
||||
justify="center"
|
||||
/>
|
||||
{secondSlot({ style: areaR, orientation: vertical ? "vertical" : "horizontal" })}
|
||||
{second}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function clampSplitRatio(ratio: number, minPx: number, containerPx: number): number {
|
||||
if (containerPx <= 0 || minPx <= 0) {
|
||||
return ratio;
|
||||
}
|
||||
|
||||
const minRatio = Math.min(1, minPx / containerPx);
|
||||
const maxRatio = minRatio >= 0.5 ? minRatio : 1 - minRatio;
|
||||
return clamp(ratio, minRatio, maxRatio);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import type { ShowToastRequest } from "@yaakapp-internal/plugins";
|
||||
import classNames from "classnames";
|
||||
import * as m from "motion/react-m";
|
||||
import type { ReactNode } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useKey } from "react-use";
|
||||
import { Icon, type IconProps } from "./Icon";
|
||||
import { IconButton } from "./IconButton";
|
||||
import { VStack } from "./Stacks";
|
||||
|
||||
export interface ToastProps {
|
||||
children: ReactNode;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
className?: string;
|
||||
timeout: number | null;
|
||||
action?: (args: { hide: () => void }) => ReactNode;
|
||||
icon?: ShowToastRequest["icon"] | null;
|
||||
color?: ShowToastRequest["color"];
|
||||
// Grow with the content (up to the viewport) instead of scrolling internally
|
||||
// past the default max height
|
||||
dynamicHeight?: boolean;
|
||||
// Hide the close button, for toasts that render their own dismiss action.
|
||||
// Escape still closes the toast
|
||||
hideDismiss?: boolean;
|
||||
}
|
||||
|
||||
const ICONS: Record<NonNullable<ToastProps["color"] | "custom">, IconProps["icon"] | null> = {
|
||||
custom: null,
|
||||
danger: "alert_triangle",
|
||||
info: "info",
|
||||
notice: "alert_triangle",
|
||||
primary: "info",
|
||||
secondary: "info",
|
||||
success: "check_circle",
|
||||
warning: "alert_triangle",
|
||||
};
|
||||
|
||||
export function Toast({
|
||||
children,
|
||||
open,
|
||||
onClose,
|
||||
timeout,
|
||||
action,
|
||||
icon,
|
||||
color,
|
||||
dynamicHeight,
|
||||
hideDismiss,
|
||||
}: ToastProps) {
|
||||
const onCloseRef = useRef(onClose);
|
||||
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const [autoHideCanceled, setAutoHideCanceled] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
onCloseRef.current = onClose;
|
||||
}, [onClose]);
|
||||
|
||||
const cancelAutoHide = useCallback(() => {
|
||||
if (timeoutRef.current == null) return;
|
||||
clearTimeout(timeoutRef.current);
|
||||
timeoutRef.current = null;
|
||||
setAutoHideCanceled(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || timeout == null || autoHideCanceled) return;
|
||||
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
timeoutRef.current = null;
|
||||
onCloseRef.current();
|
||||
}, timeout);
|
||||
|
||||
return () => {
|
||||
if (timeoutRef.current == null) return;
|
||||
clearTimeout(timeoutRef.current);
|
||||
timeoutRef.current = null;
|
||||
};
|
||||
}, [autoHideCanceled, open, timeout]);
|
||||
|
||||
useKey(
|
||||
"Escape",
|
||||
() => {
|
||||
if (!open) return;
|
||||
onClose();
|
||||
},
|
||||
{},
|
||||
[open],
|
||||
);
|
||||
|
||||
const toastIcon = icon === null ? null : (icon ?? (color && color in ICONS && ICONS[color]));
|
||||
|
||||
return (
|
||||
<m.div
|
||||
initial={{ opacity: 0, right: "-10%" }}
|
||||
animate={{ opacity: 100, right: 0 }}
|
||||
exit={{ opacity: 0, right: "-100%" }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className={classNames("bg-surface m-2 rounded-lg")}
|
||||
>
|
||||
<div
|
||||
className={classNames(
|
||||
`x-theme-toast x-theme-toast--${color}`,
|
||||
"pointer-events-auto overflow-hidden",
|
||||
"relative pointer-events-auto bg-surface text-text rounded-lg",
|
||||
"border border-border shadow-lg w-100",
|
||||
)}
|
||||
onFocusCapture={cancelAutoHide}
|
||||
onKeyDownCapture={cancelAutoHide}
|
||||
onPointerDownCapture={cancelAutoHide}
|
||||
>
|
||||
<div
|
||||
className={classNames(
|
||||
"pl-3 py-3 flex items-start gap-2 w-full overflow-auto",
|
||||
hideDismiss ? "pr-3" : "pr-10",
|
||||
dynamicHeight ? "max-h-[80vh]" : "max-h-44",
|
||||
)}
|
||||
>
|
||||
{toastIcon && <Icon icon={toastIcon} color={color} className="mt-1 shrink-0" />}
|
||||
<VStack space={2} className="w-full min-w-0">
|
||||
<div className="select-auto">{children}</div>
|
||||
{action?.({ hide: onClose })}
|
||||
</VStack>
|
||||
</div>
|
||||
|
||||
{!hideDismiss && (
|
||||
<IconButton
|
||||
color={color}
|
||||
variant="border"
|
||||
className="opacity-60 border-0 absolute! top-2 right-2"
|
||||
title="Dismiss"
|
||||
icon="x"
|
||||
onClick={onClose}
|
||||
/>
|
||||
)}
|
||||
|
||||
{timeout != null && !autoHideCanceled && (
|
||||
<div className="w-full absolute bottom-0 left-0 right-0">
|
||||
<m.div
|
||||
className="bg-surface-highlight h-[3px]"
|
||||
initial={{ width: "100%" }}
|
||||
animate={{ width: "0%", opacity: 0.2 }}
|
||||
transition={{ duration: timeout / 1000, ease: "linear" }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</m.div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useAtomValue, useStore } from "jotai";
|
||||
import { AnimatePresence } from "motion/react";
|
||||
import { hideToast, type ToastInstance, toastsAtom } from "../lib/toast";
|
||||
import { ErrorBoundary } from "./ErrorBoundary";
|
||||
import { Portal } from "./Portal";
|
||||
import { Toast } from "./Toast";
|
||||
|
||||
/** The toasts in the app's jotai store, bottom right */
|
||||
export function Toasts({ onShowError }: { onShowError?: (error: unknown) => void }) {
|
||||
const store = useStore();
|
||||
const toasts = useAtomValue(toastsAtom);
|
||||
return (
|
||||
<Portal name="toasts">
|
||||
<div className="absolute right-0 bottom-0 z-50">
|
||||
<AnimatePresence>
|
||||
{toasts.map((toast: ToastInstance) => {
|
||||
const { message, uniqueKey, ...props } = toast;
|
||||
return (
|
||||
<ErrorBoundary key={uniqueKey} name={`Toast ${uniqueKey}`} onShowError={onShowError}>
|
||||
<Toast
|
||||
open
|
||||
{...props}
|
||||
// We call onClose inside actions.hide instead of passing to toast so that
|
||||
// it gets called from external close calls as well
|
||||
onClose={() => hideToast(store, toast)}
|
||||
>
|
||||
{message}
|
||||
</Toast>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
})}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</Portal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import classNames from "classnames";
|
||||
import type { CSSProperties, KeyboardEvent, ReactNode } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import { generateId } from "@yaakapp-internal/lib/generateId";
|
||||
import { Portal } from "./Portal";
|
||||
|
||||
export interface TooltipProps {
|
||||
children: ReactNode;
|
||||
content: ReactNode;
|
||||
tabIndex?: number;
|
||||
size?: "md" | "lg";
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const hiddenStyles: CSSProperties = {
|
||||
left: -99999,
|
||||
top: -99999,
|
||||
visibility: "hidden",
|
||||
pointerEvents: "none",
|
||||
opacity: 0,
|
||||
};
|
||||
|
||||
type TooltipPosition = "top" | "bottom";
|
||||
|
||||
interface TooltipOpenState {
|
||||
styles: CSSProperties;
|
||||
position: TooltipPosition;
|
||||
}
|
||||
|
||||
export function Tooltip({ children, className, content, tabIndex, size = "md" }: TooltipProps) {
|
||||
const [openState, setOpenState] = useState<TooltipOpenState | null>(null);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const tooltipRef = useRef<HTMLDivElement>(null);
|
||||
const showTimeout = useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||
|
||||
const handleOpenImmediate = () => {
|
||||
if (triggerRef.current == null || tooltipRef.current == null) return;
|
||||
clearTimeout(showTimeout.current);
|
||||
const triggerRect = triggerRef.current.getBoundingClientRect();
|
||||
const tooltipRect = tooltipRef.current.getBoundingClientRect();
|
||||
const viewportHeight = document.documentElement.clientHeight;
|
||||
|
||||
const margin = 8;
|
||||
const spaceAbove = Math.max(0, triggerRect.top - margin);
|
||||
const spaceBelow = Math.max(0, viewportHeight - triggerRect.bottom - margin);
|
||||
const preferBottom = spaceAbove < tooltipRect.height + margin && spaceBelow > spaceAbove;
|
||||
const position: TooltipPosition = preferBottom ? "bottom" : "top";
|
||||
|
||||
const styles: CSSProperties = {
|
||||
left: Math.max(0, triggerRect.left + triggerRect.width / 2 - tooltipRect.width / 2),
|
||||
maxHeight: position === "top" ? spaceAbove : spaceBelow,
|
||||
...(position === "top"
|
||||
? { bottom: viewportHeight - triggerRect.top }
|
||||
: { top: triggerRect.bottom }),
|
||||
};
|
||||
|
||||
setOpenState({ styles, position });
|
||||
};
|
||||
|
||||
const handleOpen = () => {
|
||||
clearTimeout(showTimeout.current);
|
||||
showTimeout.current = setTimeout(handleOpenImmediate, 500);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
clearTimeout(showTimeout.current);
|
||||
setOpenState(null);
|
||||
};
|
||||
|
||||
const handleToggleImmediate = () => {
|
||||
if (openState) handleClose();
|
||||
else handleOpenImmediate();
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent<HTMLButtonElement>) => {
|
||||
if (openState && e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleClose();
|
||||
}
|
||||
};
|
||||
|
||||
const id = useRef(`tooltip-${generateId()}`);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Portal name="tooltip">
|
||||
<div
|
||||
ref={tooltipRef}
|
||||
style={openState?.styles ?? hiddenStyles}
|
||||
id={id.current}
|
||||
role="tooltip"
|
||||
aria-hidden={openState == null}
|
||||
onMouseEnter={handleOpenImmediate}
|
||||
onMouseLeave={handleClose}
|
||||
className="p-2 fixed z-50 text-sm transition-opacity grid grid-rows-[minmax(0,1fr)]"
|
||||
>
|
||||
<div
|
||||
className={classNames(
|
||||
"bg-surface-highlight rounded-md px-3 py-2 z-50 border border-border overflow-auto",
|
||||
size === "md" && "max-w-sm",
|
||||
size === "lg" && "max-w-md",
|
||||
)}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
<Triangle
|
||||
className="text-border"
|
||||
position={openState?.position === "bottom" ? "top" : "bottom"}
|
||||
/>
|
||||
</div>
|
||||
</Portal>
|
||||
{/* oxlint-disable-next-line jsx-a11y/prefer-tag-over-role -- Needs to be usable in other buttons */}
|
||||
<span
|
||||
ref={triggerRef}
|
||||
role="button"
|
||||
aria-describedby={openState ? id.current : undefined}
|
||||
tabIndex={tabIndex ?? -1}
|
||||
className={classNames(className, "grow-0 flex items-center")}
|
||||
onClick={handleToggleImmediate}
|
||||
onMouseEnter={handleOpen}
|
||||
onMouseLeave={handleClose}
|
||||
onFocus={handleOpenImmediate}
|
||||
onBlur={handleClose}
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Triangle({ className, position }: { className?: string; position: "top" | "bottom" }) {
|
||||
const isBottom = position === "bottom";
|
||||
|
||||
return (
|
||||
<svg
|
||||
aria-hidden
|
||||
viewBox="0 0 30 10"
|
||||
preserveAspectRatio="none"
|
||||
shapeRendering="crispEdges"
|
||||
className={classNames(
|
||||
className,
|
||||
"absolute z-50 left-[calc(50%-0.4rem)] h-2 w-[0.8rem]",
|
||||
isBottom
|
||||
? "border-t-2 border-surface-highlight -bottom-[calc(0.5rem-3px)] mb-2"
|
||||
: "border-b-2 border-surface-highlight -top-[calc(0.5rem-3px)] mt-2",
|
||||
)}
|
||||
>
|
||||
<title>Triangle</title>
|
||||
<polygon
|
||||
className="fill-surface-highlight"
|
||||
points={isBottom ? "0,0 30,0 15,10" : "0,10 30,10 15,0"}
|
||||
/>
|
||||
<path
|
||||
d={isBottom ? "M0 0 L15 9 L30 0" : "M0 10 L15 1 L30 10"}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1"
|
||||
strokeLinejoin="miter"
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
@reference "tailwindcss";
|
||||
@reference "../../../../tailwind-config/index.css";
|
||||
|
||||
.cm-wrapper {
|
||||
@apply h-full overflow-hidden;
|
||||
|
||||
.cm-editor {
|
||||
@apply w-full block text-base;
|
||||
|
||||
/* Regular cursor */
|
||||
|
||||
.cm-cursor {
|
||||
@apply border-text!;
|
||||
/* Widen the cursor a bit */
|
||||
@apply border-l-[2px];
|
||||
}
|
||||
|
||||
/* Vim-mode cursor */
|
||||
|
||||
.cm-fat-cursor {
|
||||
@apply outline-0! bg-text!;
|
||||
@apply text-surface!;
|
||||
}
|
||||
|
||||
/* Matching bracket */
|
||||
|
||||
.cm-matchingBracket {
|
||||
@apply bg-transparent border-b border-b-text-subtle;
|
||||
}
|
||||
|
||||
&:not(.cm-focused) {
|
||||
.cm-cursor,
|
||||
.cm-fat-cursor {
|
||||
@apply hidden;
|
||||
}
|
||||
}
|
||||
|
||||
&.cm-focused {
|
||||
outline: none !important;
|
||||
}
|
||||
|
||||
.cm-content {
|
||||
@apply py-0;
|
||||
}
|
||||
|
||||
.cm-line {
|
||||
@apply w-full;
|
||||
/* Important! Ensure it spans the entire width */
|
||||
@apply w-full text-text px-0;
|
||||
|
||||
/* So the search highlight border is not cut off by editor view */
|
||||
@apply pl-[1px];
|
||||
}
|
||||
|
||||
.cm-placeholder {
|
||||
@apply text-placeholder;
|
||||
}
|
||||
|
||||
.cm-scroller {
|
||||
/* Inherit line-height from outside */
|
||||
line-height: inherit;
|
||||
|
||||
* {
|
||||
@apply cursor-text;
|
||||
@apply caret-transparent!;
|
||||
}
|
||||
}
|
||||
|
||||
.cm-selectionBackground {
|
||||
@apply bg-selection!;
|
||||
}
|
||||
|
||||
/* Fix WebKit/WKWebView rendering bug where selection layer leaves a ghost
|
||||
residual line below wrapped lines after deselecting (CodeMirror issue #1600, #1627).
|
||||
The layer div must be hidden when empty to force a repaint. */
|
||||
.cm-selectionLayer:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Style gutters */
|
||||
|
||||
.cm-gutters {
|
||||
@apply border-0 text-text-subtlest bg-surface pr-1.5;
|
||||
/* Not sure why, but there's a tiny gap left of the gutter that you can see text
|
||||
through. Move left slightly to fix that. */
|
||||
@apply -left-[1px];
|
||||
|
||||
.cm-gutterElement {
|
||||
@apply cursor-default;
|
||||
}
|
||||
}
|
||||
|
||||
.cm-gutter-lint {
|
||||
@apply w-auto!;
|
||||
|
||||
.cm-gutterElement {
|
||||
@apply px-0;
|
||||
}
|
||||
|
||||
.cm-lint-marker {
|
||||
@apply cursor-default opacity-80 hover:opacity-100 transition-opacity;
|
||||
@apply rounded-full w-[0.9em] h-[0.9em];
|
||||
|
||||
content: "";
|
||||
|
||||
&.cm-lint-marker-error {
|
||||
@apply bg-danger;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.template-tag {
|
||||
/* Colors */
|
||||
@apply bg-surface text-text-subtle border-border-subtle whitespace-nowrap cursor-default;
|
||||
@apply hover:border-border hover:text-text hover:bg-surface-highlight;
|
||||
|
||||
@apply inline border px-1 mx-[0.5px] rounded-sm dark:shadow;
|
||||
|
||||
-webkit-text-security: none;
|
||||
|
||||
* {
|
||||
@apply cursor-default;
|
||||
}
|
||||
|
||||
/* The chevron on a tag that opens a menu. The tag itself is the button, so this is
|
||||
only the affordance that says so. */
|
||||
.tag-action {
|
||||
@apply inline-flex items-center align-middle ml-1;
|
||||
@apply text-text-subtlest;
|
||||
|
||||
svg {
|
||||
@apply w-[0.9em] h-[0.9em];
|
||||
}
|
||||
}
|
||||
|
||||
/* A preview of the value a tag stands for. Sized before the image loads, so arriving
|
||||
never changes the line's height. */
|
||||
.tag-thumbnail {
|
||||
@apply inline-block align-middle mr-1 rounded-xs;
|
||||
@apply w-[1.1em] h-[1.1em] object-cover bg-surface-highlight;
|
||||
}
|
||||
|
||||
.fn {
|
||||
@apply inline-block;
|
||||
.fn-inner {
|
||||
@apply text-text-subtle max-w-[40em] italic inline-flex items-end whitespace-pre text-[0.9em];
|
||||
}
|
||||
.fn-arg-name {
|
||||
/* Nothing yet */
|
||||
@apply opacity-60;
|
||||
}
|
||||
.fn-arg-value {
|
||||
@apply inline-block truncate;
|
||||
}
|
||||
.fn-bracket {
|
||||
@apply text-text-subtle opacity-30;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.hyperlink-widget {
|
||||
& > * {
|
||||
@apply underline;
|
||||
}
|
||||
|
||||
&:hover > * {
|
||||
@apply text-primary;
|
||||
}
|
||||
|
||||
-webkit-text-security: none;
|
||||
}
|
||||
}
|
||||
|
||||
&.cm-singleline {
|
||||
.cm-editor {
|
||||
@apply w-full h-full;
|
||||
}
|
||||
|
||||
.cm-scroller {
|
||||
@apply font-mono text-xs;
|
||||
|
||||
/* Hide scrollbars */
|
||||
|
||||
&::-webkit-scrollbar-corner,
|
||||
&::-webkit-scrollbar {
|
||||
@apply hidden!;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.cm-multiline {
|
||||
&.cm-full-height {
|
||||
@apply relative;
|
||||
|
||||
.cm-editor {
|
||||
@apply inset-0 absolute;
|
||||
position: absolute !important;
|
||||
}
|
||||
}
|
||||
|
||||
.cm-editor {
|
||||
@apply h-full;
|
||||
}
|
||||
|
||||
.cm-scroller {
|
||||
@apply font-mono text-editor;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Style search matches */
|
||||
.cm-searchMatch {
|
||||
@apply bg-transparent!;
|
||||
@apply rounded-[2px] outline outline-1;
|
||||
|
||||
&.cm-searchMatch-selected {
|
||||
@apply outline-text;
|
||||
@apply bg-text!;
|
||||
|
||||
&,
|
||||
* {
|
||||
@apply text-surface! font-semibold!;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Obscure text for password fields */
|
||||
.cm-wrapper.cm-obscure-text .cm-line {
|
||||
-webkit-text-security: disc;
|
||||
}
|
||||
|
||||
/* Obscure text for password fields */
|
||||
.cm-wrapper.cm-obscure-text .cm-line {
|
||||
-webkit-text-security: disc;
|
||||
|
||||
.cm-placeholder {
|
||||
-webkit-text-security: none;
|
||||
}
|
||||
}
|
||||
|
||||
.cm-editor .cm-gutterElement {
|
||||
@apply flex items-center;
|
||||
transition: color var(--transition-duration);
|
||||
}
|
||||
|
||||
.cm-editor .fold-gutter-icon {
|
||||
@apply pt-[0.25em] pl-[0.4em] px-[0.4em] h-4 rounded-sm;
|
||||
@apply cursor-default!;
|
||||
}
|
||||
|
||||
.cm-editor .fold-gutter-icon::after {
|
||||
@apply block w-1.5 h-1.5 p-0.5 border-transparent border-l border-b border-l-[currentColor] border-b-[currentColor] content-[''];
|
||||
}
|
||||
|
||||
/* Rotate the fold gutter chevron when open */
|
||||
.cm-editor .fold-gutter-icon[data-open]::after {
|
||||
@apply rotate-[-45deg];
|
||||
}
|
||||
|
||||
/* Adjust fold gutter icon position after rotation */
|
||||
.cm-editor .fold-gutter-icon:not([data-open])::after {
|
||||
@apply relative -left-[0.1em] top-[0.1em] rotate-[-135deg];
|
||||
}
|
||||
|
||||
.cm-editor .fold-gutter-icon:hover {
|
||||
@apply text-text bg-surface-highlight;
|
||||
}
|
||||
|
||||
.cm-editor .cm-foldPlaceholder {
|
||||
@apply px-2 border border-border-subtle bg-surface-highlight;
|
||||
@apply hover:text-text hover:border-border-subtle text-text;
|
||||
@apply cursor-default!;
|
||||
}
|
||||
|
||||
.cm-editor .cm-activeLineGutter {
|
||||
@apply bg-transparent text-text-subtle;
|
||||
}
|
||||
|
||||
/* Cursor and mouse cursor for readonly mode */
|
||||
.cm-wrapper.cm-readonly {
|
||||
&.cm-singleline * {
|
||||
@apply cursor-default;
|
||||
}
|
||||
}
|
||||
|
||||
.cm-singleline .cm-editor {
|
||||
.cm-content {
|
||||
@apply h-full flex items-center;
|
||||
|
||||
/* Break characters on line wrapping mode, useful for URL field.
|
||||
* We can make this dynamic if we need it to be configurable later
|
||||
*/
|
||||
|
||||
&.cm-lineWrapping {
|
||||
@apply break-all;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.cm-tooltip-lint {
|
||||
@apply font-mono! text-editor! rounded-sm! overflow-hidden! bg-surface-highlight! border! border-border! shadow!;
|
||||
|
||||
.cm-diagnostic-error {
|
||||
@apply border-l-danger px-4 py-2;
|
||||
}
|
||||
}
|
||||
|
||||
.cm-lintPoint {
|
||||
&.cm-lintPoint-error {
|
||||
&::after {
|
||||
@apply border-b-danger;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.cm-tooltip.cm-tooltip-hover {
|
||||
@apply shadow-lg bg-surface rounded-sm text-text-subtle border border-border-subtle z-50 pointer-events-auto text-sm;
|
||||
@apply p-1.5;
|
||||
|
||||
/* Style the tooltip for popping up "open in browser" and other stuff */
|
||||
|
||||
a,
|
||||
button {
|
||||
@apply text-text hover:bg-surface-highlight w-full h-sm flex items-center px-2 rounded-sm;
|
||||
}
|
||||
|
||||
a {
|
||||
@apply cursor-default!;
|
||||
|
||||
&::after {
|
||||
@apply text-text bg-text h-3 w-3 ml-1;
|
||||
content: "";
|
||||
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100' fill='black' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M8.636 3.5a.5.5 0 0 0-.5-.5H1.5A1.5 1.5 0 0 0 0 4.5v10A1.5 1.5 0 0 0 1.5 16h10a1.5 1.5 0 0 0 1.5-1.5V7.864a.5.5 0 0 0-1 0V14.5a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h6.636a.5.5 0 0 0 .5-.5z'/%3E%3Cpath fill-rule='evenodd' d='M16 .5a.5.5 0 0 0-.5-.5h-5a.5.5 0 0 0 0 1h3.793L6.146 9.146a.5.5 0 1 0 .708.708L15 1.707V5.5a.5.5 0 0 0 1 0v-5z'/%3E%3C/svg%3E");
|
||||
-webkit-mask-size: contain;
|
||||
display: inline-block;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* NOTE: Extra selector required to override default styles */
|
||||
.cm-tooltip.cm-tooltip-autocomplete,
|
||||
.cm-tooltip.cm-completionInfo {
|
||||
@apply shadow-lg bg-surface rounded-sm text-text-subtle border border-border-subtle z-50 pointer-events-auto;
|
||||
|
||||
& * {
|
||||
@apply font-mono! text-editor!;
|
||||
}
|
||||
|
||||
.cm-completionIcon {
|
||||
@apply opacity-80 italic;
|
||||
|
||||
&::after {
|
||||
content: "a" !important; /* Default (eg. for GraphQL) */
|
||||
}
|
||||
|
||||
&.cm-completionIcon-function::after {
|
||||
content: "f" !important;
|
||||
@apply text-info;
|
||||
}
|
||||
|
||||
&.cm-completionIcon-variable::after {
|
||||
content: "x" !important;
|
||||
@apply text-primary;
|
||||
}
|
||||
|
||||
&.cm-completionIcon-namespace::after {
|
||||
content: "n" !important;
|
||||
@apply text-warning;
|
||||
}
|
||||
|
||||
&.cm-completionIcon-constant::after {
|
||||
content: "c" !important;
|
||||
@apply text-notice;
|
||||
}
|
||||
|
||||
&.cm-completionIcon-class::after {
|
||||
content: "o" !important;
|
||||
}
|
||||
|
||||
&.cm-completionIcon-enum::after {
|
||||
content: "e" !important;
|
||||
}
|
||||
|
||||
&.cm-completionIcon-interface::after {
|
||||
content: "i" !important;
|
||||
}
|
||||
|
||||
&.cm-completionIcon-keyword::after {
|
||||
content: "k" !important;
|
||||
}
|
||||
|
||||
&.cm-completionIcon-method::after {
|
||||
content: "m" !important;
|
||||
}
|
||||
|
||||
&.cm-completionIcon-property::after {
|
||||
content: "a" !important;
|
||||
}
|
||||
|
||||
&.cm-completionIcon-text::after {
|
||||
content: "t" !important;
|
||||
}
|
||||
|
||||
&.cm-completionIcon-type::after {
|
||||
content: "t" !important;
|
||||
}
|
||||
}
|
||||
|
||||
&.cm-completionInfo {
|
||||
@apply mx-0.5 -mt-0.5 font-sans;
|
||||
}
|
||||
|
||||
* {
|
||||
@apply transition-none;
|
||||
}
|
||||
|
||||
&.cm-tooltip-autocomplete {
|
||||
@apply font-mono;
|
||||
|
||||
& > ul {
|
||||
@apply p-1 max-h-[40vh];
|
||||
}
|
||||
|
||||
& > ul > li {
|
||||
@apply cursor-default px-2 h-[2em] rounded-sm text-text flex items-center;
|
||||
}
|
||||
|
||||
& > ul > li[aria-selected] {
|
||||
@apply bg-surface-highlight text-text;
|
||||
}
|
||||
|
||||
.cm-completionIcon {
|
||||
@apply text-sm flex items-center pb-0.5 shrink-0;
|
||||
}
|
||||
|
||||
.cm-completionLabel {
|
||||
@apply text-text;
|
||||
}
|
||||
|
||||
.cm-completionDetail {
|
||||
@apply ml-auto pl-6 text-text-subtle;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.cm-editor .cm-panels {
|
||||
@apply bg-surface-highlight backdrop-blur-sm p-1 mb-1 text-text z-20 rounded-md;
|
||||
|
||||
input,
|
||||
button {
|
||||
@apply rounded-sm outline-hidden;
|
||||
}
|
||||
|
||||
button {
|
||||
@apply border-border-subtle bg-surface-highlight text-text hover:border-info;
|
||||
@apply appearance-none bg-none cursor-default;
|
||||
}
|
||||
|
||||
button[name="close"] {
|
||||
@apply text-text-subtle! hocus:text-text! px-2! -mr-1.5!;
|
||||
}
|
||||
|
||||
input {
|
||||
@apply bg-surface border-border-subtle focus:border-border-focus;
|
||||
@apply border outline-hidden;
|
||||
}
|
||||
|
||||
input.cm-textfield {
|
||||
@apply cursor-text;
|
||||
}
|
||||
|
||||
.cm-search label {
|
||||
@apply inline-flex items-center h-6 px-1.5 rounded-sm border border-border-subtle cursor-default text-text-subtle text-xs;
|
||||
|
||||
input[type="checkbox"] {
|
||||
@apply hidden;
|
||||
}
|
||||
|
||||
&:has(:checked) {
|
||||
@apply text-primary border-border;
|
||||
}
|
||||
}
|
||||
|
||||
/* Hide the "All" button */
|
||||
|
||||
button[name="select"] {
|
||||
@apply hidden;
|
||||
}
|
||||
|
||||
/* Replace next/prev button text with chevron icons */
|
||||
|
||||
.cm-search button[name="next"],
|
||||
.cm-search button[name="prev"] {
|
||||
@apply text-[0px] w-7 h-6 inline-flex items-center justify-center border border-border-subtle mr-1;
|
||||
}
|
||||
|
||||
.cm-search button[name="prev"]::after,
|
||||
.cm-search button[name="next"]::after {
|
||||
@apply block w-3.5 h-3.5 bg-text;
|
||||
content: "";
|
||||
}
|
||||
|
||||
.cm-search button[name="prev"]::after {
|
||||
-webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M15 18l-6-6 6-6'/%3E%3C/svg%3E");
|
||||
mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M15 18l-6-6 6-6'/%3E%3C/svg%3E");
|
||||
}
|
||||
|
||||
.cm-search button[name="next"]::after {
|
||||
-webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M9 18l6-6-6-6'/%3E%3C/svg%3E");
|
||||
mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M9 18l6-6-6-6'/%3E%3C/svg%3E");
|
||||
}
|
||||
|
||||
.cm-search-match-count {
|
||||
@apply text-text-subtle text-xs font-mono whitespace-nowrap px-1.5 py-0.5 self-center;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,696 @@
|
||||
import { defaultKeymap, historyField, indentWithTab } from "@codemirror/commands";
|
||||
import { foldState, forceParsing } from "@codemirror/language";
|
||||
import type { EditorStateConfig, Extension } from "@codemirror/state";
|
||||
import { Compartment, EditorState } from "@codemirror/state";
|
||||
import { EditorView, keymap, placeholder as placeholderExt, tooltips } from "@codemirror/view";
|
||||
import { emacs } from "@replit/codemirror-emacs";
|
||||
import { vim } from "@replit/codemirror-vim";
|
||||
|
||||
import { vscodeKeymap } from "@replit/codemirror-vscode-keymap";
|
||||
import { debounce } from "@yaakapp-internal/lib";
|
||||
import type { EditorKeymap } from "@yaakapp-internal/models";
|
||||
import type { EditorLanguage } from "@yaakapp-internal/plugins";
|
||||
import classNames from "classnames";
|
||||
import type { ReactNode, RefObject } from "react";
|
||||
import {
|
||||
Children,
|
||||
cloneElement,
|
||||
isValidElement,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
} from "react";
|
||||
import { docFingerprint } from "../../lib/docFingerprint";
|
||||
import { IconButton } from "../IconButton";
|
||||
import { HStack } from "../Stacks";
|
||||
import "./CodeEditor.css";
|
||||
import {
|
||||
baseExtensions,
|
||||
editableExtensions,
|
||||
getLanguageExtension,
|
||||
multiLineExtensions,
|
||||
readonlyExtensions,
|
||||
} from "./extensions";
|
||||
import { singleLineExtensions } from "./singleLine";
|
||||
|
||||
// VSCode's Tab actions mess with the single-line editor tab actions, so remove it.
|
||||
const vsCodeWithoutTab = vscodeKeymap.filter((k) => k.key !== "Tab");
|
||||
|
||||
const keymapExtensions: Record<EditorKeymap, Extension> = {
|
||||
vim: vim(),
|
||||
emacs: emacs(),
|
||||
vscode: keymap.of(vsCodeWithoutTab),
|
||||
default: [],
|
||||
};
|
||||
|
||||
export interface CodeEditorProps {
|
||||
actions?: ReactNode;
|
||||
autoFocus?: boolean;
|
||||
autoSelect?: boolean;
|
||||
className?: string;
|
||||
defaultValue?: string | null;
|
||||
disableTabIndent?: boolean;
|
||||
disabled?: boolean;
|
||||
/** Added to the editable document's extensions, swapped out with read-only */
|
||||
editableExtensions?: Extension;
|
||||
extensions?: Extension[] | Extension;
|
||||
forceUpdateKey?: string | number;
|
||||
format?: (v: string) => Promise<string>;
|
||||
heightMode?: "auto" | "full";
|
||||
hideGutter?: boolean;
|
||||
id?: string;
|
||||
/** Runs before `onKeyDown`; returning true consumes the key */
|
||||
keyDownHandler?: (e: KeyboardEvent, view: EditorView) => boolean;
|
||||
keymap?: EditorKeymap;
|
||||
language?: EditorLanguage | null;
|
||||
/** Replaces the extension built from `language`, reconfigured whenever it changes */
|
||||
languageExtension?: Extension;
|
||||
lintExtension?: Extension;
|
||||
/** Added to the read-only document's extensions, swapped out with editable */
|
||||
readOnlyExtensions?: Extension;
|
||||
onBlur?: () => void;
|
||||
onChange?: (value: string) => void;
|
||||
onFocus?: () => void;
|
||||
onKeyDown?: (e: KeyboardEvent) => void;
|
||||
onPaste?: (value: string) => void;
|
||||
onPasteOverwrite?: (e: ClipboardEvent, value: string) => void;
|
||||
placeholder?: string;
|
||||
readOnly?: boolean;
|
||||
singleLine?: boolean;
|
||||
containerOnly?: boolean;
|
||||
stateKey: string | null;
|
||||
tooltipContainer?: HTMLElement;
|
||||
type?: "text" | "password";
|
||||
wrapLines?: boolean;
|
||||
setRef?: (view: EditorView | null) => void;
|
||||
}
|
||||
|
||||
const stateFields = { history: historyField, folds: foldState };
|
||||
|
||||
const emptyExtension: Extension = [];
|
||||
|
||||
export function CodeEditor(props: CodeEditorProps) {
|
||||
return <CodeEditorInner key={props.stateKey} {...props} />;
|
||||
}
|
||||
|
||||
function CodeEditorInner({
|
||||
actions,
|
||||
autoFocus,
|
||||
autoSelect,
|
||||
className,
|
||||
defaultValue,
|
||||
disableTabIndent,
|
||||
disabled,
|
||||
editableExtensions: extraEditableExtensions,
|
||||
extensions: extraExtensions,
|
||||
forceUpdateKey,
|
||||
format,
|
||||
heightMode,
|
||||
hideGutter,
|
||||
keyDownHandler,
|
||||
keymap: editorKeymap = "default",
|
||||
language,
|
||||
languageExtension,
|
||||
lintExtension,
|
||||
onBlur,
|
||||
onChange,
|
||||
onFocus,
|
||||
onKeyDown,
|
||||
onPaste,
|
||||
onPasteOverwrite,
|
||||
placeholder,
|
||||
readOnly,
|
||||
readOnlyExtensions: extraReadOnlyExtensions,
|
||||
singleLine,
|
||||
containerOnly,
|
||||
stateKey,
|
||||
type,
|
||||
wrapLines,
|
||||
setRef,
|
||||
}: CodeEditorProps) {
|
||||
if (disabled) {
|
||||
readOnly = true;
|
||||
}
|
||||
|
||||
if (singleLine || language == null || language === "text") {
|
||||
disableTabIndent = true;
|
||||
}
|
||||
|
||||
const cm = useRef<{ view: EditorView; languageCompartment: Compartment } | null>(null);
|
||||
|
||||
// Use ref so we can update the handler without re-initializing the editor
|
||||
const handleChange = useRef<CodeEditorProps["onChange"]>(onChange);
|
||||
useEffect(() => {
|
||||
handleChange.current = onChange;
|
||||
}, [onChange]);
|
||||
|
||||
// Use ref so we can update the handler without re-initializing the editor
|
||||
const handlePaste = useRef<CodeEditorProps["onPaste"]>(onPaste);
|
||||
useEffect(() => {
|
||||
handlePaste.current = onPaste;
|
||||
}, [onPaste]);
|
||||
|
||||
// Use ref so we can update the handler without re-initializing the editor
|
||||
const handlePasteOverwrite = useRef<CodeEditorProps["onPasteOverwrite"]>(onPasteOverwrite);
|
||||
useEffect(() => {
|
||||
handlePasteOverwrite.current = onPasteOverwrite;
|
||||
}, [onPasteOverwrite]);
|
||||
|
||||
// Use ref so we can update the handler without re-initializing the editor
|
||||
const handleFocus = useRef<CodeEditorProps["onFocus"]>(onFocus);
|
||||
useEffect(() => {
|
||||
handleFocus.current = onFocus;
|
||||
}, [onFocus]);
|
||||
|
||||
// Use ref so we can update the handler without re-initializing the editor
|
||||
const handleBlur = useRef<CodeEditorProps["onBlur"]>(onBlur);
|
||||
useEffect(() => {
|
||||
handleBlur.current = onBlur;
|
||||
}, [onBlur]);
|
||||
|
||||
// Use ref so we can update the handler without re-initializing the editor
|
||||
const handleKeyDown = useRef<CodeEditorProps["onKeyDown"]>(onKeyDown);
|
||||
useEffect(() => {
|
||||
handleKeyDown.current = onKeyDown;
|
||||
}, [onKeyDown]);
|
||||
|
||||
// Use ref so we can update the handler without re-initializing the editor
|
||||
const handleKeyDownFirst = useRef<CodeEditorProps["keyDownHandler"]>(keyDownHandler);
|
||||
useEffect(() => {
|
||||
handleKeyDownFirst.current = keyDownHandler;
|
||||
}, [keyDownHandler]);
|
||||
|
||||
// Update placeholder
|
||||
const placeholderCompartment = useRef(new Compartment());
|
||||
useEffect(
|
||||
function configurePlaceholder() {
|
||||
if (cm.current === null) return;
|
||||
const ext = placeholderExt(placeholderElFromText(placeholder));
|
||||
const effects = placeholderCompartment.current.reconfigure(ext);
|
||||
cm.current?.view.dispatch({ effects });
|
||||
},
|
||||
[placeholder],
|
||||
);
|
||||
|
||||
// Update vim
|
||||
const keymapCompartment = useRef(new Compartment());
|
||||
useEffect(
|
||||
function configureKeymap() {
|
||||
if (cm.current === null) return;
|
||||
const current = keymapCompartment.current.get(cm.current.view.state) ?? [];
|
||||
// PERF: This is expensive with hundreds of editors on screen, so only do it when necessary
|
||||
if (editorKeymap === "default" && current === keymapExtensions.default) return; // Nothing to do
|
||||
if (editorKeymap === "vim" && current === keymapExtensions.vim) return; // Nothing to do
|
||||
if (editorKeymap === "vscode" && current === keymapExtensions.vscode) return; // Nothing to do
|
||||
if (editorKeymap === "emacs" && current === keymapExtensions.emacs) return; // Nothing to do
|
||||
|
||||
const ext = keymapExtensions[editorKeymap] ?? keymapExtensions.default;
|
||||
const effects = keymapCompartment.current.reconfigure(ext);
|
||||
cm.current.view.dispatch({ effects });
|
||||
},
|
||||
[editorKeymap],
|
||||
);
|
||||
|
||||
// Update wrap lines
|
||||
const wrapLinesCompartment = useRef(new Compartment());
|
||||
useEffect(
|
||||
function configureWrapLines() {
|
||||
if (cm.current === null) return;
|
||||
const current = wrapLinesCompartment.current.get(cm.current.view.state) ?? emptyExtension;
|
||||
// PERF: This is expensive with hundreds of editors on screen, so only do it when necessary
|
||||
if (wrapLines && current !== emptyExtension) return; // Nothing to do
|
||||
if (!wrapLines && current === emptyExtension) return; // Nothing to do
|
||||
|
||||
const ext = wrapLines ? EditorView.lineWrapping : emptyExtension;
|
||||
const effects = wrapLinesCompartment.current.reconfigure(ext);
|
||||
cm.current?.view.dispatch({ effects });
|
||||
},
|
||||
[wrapLines],
|
||||
);
|
||||
|
||||
// Update tab indent
|
||||
const tabIndentCompartment = useRef(new Compartment());
|
||||
useEffect(
|
||||
function configureTabIndent() {
|
||||
if (cm.current === null) return;
|
||||
const current = tabIndentCompartment.current.get(cm.current.view.state) ?? emptyExtension;
|
||||
// PERF: This is expensive with hundreds of editors on screen, so only do it when necessary
|
||||
if (disableTabIndent && current !== emptyExtension) return; // Nothing to do
|
||||
if (!disableTabIndent && current === emptyExtension) return; // Nothing to do
|
||||
|
||||
const ext = !disableTabIndent ? keymap.of([indentWithTab]) : emptyExtension;
|
||||
const effects = tabIndentCompartment.current.reconfigure(ext);
|
||||
cm.current?.view.dispatch({ effects });
|
||||
},
|
||||
[disableTabIndent],
|
||||
);
|
||||
|
||||
const modeExtensions = useMemo(
|
||||
() => ({
|
||||
readOnly: extraReadOnlyExtensions
|
||||
? [readonlyExtensions, extraReadOnlyExtensions]
|
||||
: readonlyExtensions,
|
||||
editable: extraEditableExtensions
|
||||
? [editableExtensions, extraEditableExtensions]
|
||||
: editableExtensions,
|
||||
}),
|
||||
[extraReadOnlyExtensions, extraEditableExtensions],
|
||||
);
|
||||
|
||||
// Update read-only
|
||||
const readOnlyCompartment = useRef(new Compartment());
|
||||
useEffect(
|
||||
function configureReadOnly() {
|
||||
if (cm.current === null) return;
|
||||
const current = readOnlyCompartment.current.get(cm.current.view.state) ?? emptyExtension;
|
||||
const next = readOnly ? modeExtensions.readOnly : modeExtensions.editable;
|
||||
// PERF: This is expensive with hundreds of editors on screen, so only do it when necessary
|
||||
if (current === next) return;
|
||||
|
||||
const effects = readOnlyCompartment.current.reconfigure(next);
|
||||
cm.current?.view.dispatch({ effects });
|
||||
},
|
||||
[readOnly, modeExtensions],
|
||||
);
|
||||
|
||||
const langExt = useMemo(
|
||||
() => languageExtension ?? getLanguageExtension({ language, lintExtension, hideGutter }),
|
||||
[languageExtension, language, lintExtension, hideGutter],
|
||||
);
|
||||
|
||||
// Update the language extension when the language changes
|
||||
useEffect(() => {
|
||||
if (cm.current === null) return;
|
||||
const { view, languageCompartment } = cm.current;
|
||||
if (languageCompartment.get(view.state) === langExt) return;
|
||||
view.dispatch({ effects: languageCompartment.reconfigure(langExt) });
|
||||
}, [langExt]);
|
||||
|
||||
// Initialize the editor when ref mounts
|
||||
// oxlint-disable-next-line react-hooks/exhaustive-deps -- only reinitialize when necessary
|
||||
const initEditorRef = useCallback(
|
||||
function initEditorRef(container: HTMLDivElement | null) {
|
||||
if (container === null) {
|
||||
flushCachedEditorState(stateKey);
|
||||
cm.current?.view.destroy();
|
||||
cm.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const languageCompartment = new Compartment();
|
||||
const extensions = [
|
||||
languageCompartment.of(langExt),
|
||||
placeholderCompartment.current.of(placeholderExt(placeholderElFromText(placeholder))),
|
||||
wrapLinesCompartment.current.of(wrapLines ? EditorView.lineWrapping : emptyExtension),
|
||||
tabIndentCompartment.current.of(
|
||||
!disableTabIndent ? keymap.of([indentWithTab]) : emptyExtension,
|
||||
),
|
||||
keymapCompartment.current.of(keymapExtensions[editorKeymap] ?? keymapExtensions.default),
|
||||
readOnlyCompartment.current.of(
|
||||
readOnly ? modeExtensions.readOnly : modeExtensions.editable,
|
||||
),
|
||||
...getExtensions({
|
||||
container,
|
||||
singleLine,
|
||||
hideGutter,
|
||||
stateKey,
|
||||
onChange: handleChange,
|
||||
onPaste: handlePaste,
|
||||
onPasteOverwrite: handlePasteOverwrite,
|
||||
onFocus: handleFocus,
|
||||
onBlur: handleBlur,
|
||||
onKeyDown: handleKeyDown,
|
||||
keyDownHandler: handleKeyDownFirst,
|
||||
}),
|
||||
...(Array.isArray(extraExtensions)
|
||||
? extraExtensions
|
||||
: extraExtensions
|
||||
? [extraExtensions]
|
||||
: []),
|
||||
];
|
||||
|
||||
const cachedJsonState = getCachedEditorState(defaultValue ?? "", stateKey, !!readOnly);
|
||||
|
||||
const doc = `${defaultValue ?? ""}`;
|
||||
const config: EditorStateConfig = { extensions, doc };
|
||||
|
||||
const state = cachedJsonState
|
||||
? EditorState.fromJSON(cachedJsonState, config, stateFields)
|
||||
: EditorState.create(config);
|
||||
|
||||
// PERF: Built detached and attached in a microtask, rather than passing `parent` and
|
||||
// letting the constructor attach it first.
|
||||
//
|
||||
// The constructor sets `contenteditable` on the content element and then reads
|
||||
// `document.fonts.ready`. Both force the browser to flush style and layout when the
|
||||
// element is already in the document, and whatever the previous editor attached has
|
||||
// just dirtied it again — so mounting n editors in one commit costs n forced layouts.
|
||||
// The environment editor mounts two per variable row (~60 of them), which is where its
|
||||
// half-second open went.
|
||||
//
|
||||
// Building detached moves that work off the live document, and deferring the attach to
|
||||
// a microtask means every editor in the commit is built before any of them is inserted:
|
||||
// one forced layout for the batch instead of one each. The microtask still runs before
|
||||
// paint, so nothing is visible in the meantime.
|
||||
const view = new EditorView({ state });
|
||||
|
||||
// For large documents, the parser may parse the max number of lines and fail to add
|
||||
// things like fold markers because of it.
|
||||
// This forces it to parse more but keeps the timeout to the default of 100 ms.
|
||||
forceParsing(view, 9e6, 100);
|
||||
|
||||
cm.current = { view, languageCompartment };
|
||||
queueMicrotask(() => {
|
||||
// The editor was torn down (or replaced) before we got here
|
||||
if (cm.current?.view !== view) return;
|
||||
|
||||
// Runs after the surrounding try/catch has returned, so it needs its own
|
||||
try {
|
||||
container.appendChild(view.dom);
|
||||
// Everything the constructor measured, it measured detached
|
||||
view.requestMeasure();
|
||||
|
||||
if (autoFocus) {
|
||||
view.focus();
|
||||
}
|
||||
if (autoSelect) {
|
||||
view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } });
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("Failed to attach Codemirror", e);
|
||||
}
|
||||
});
|
||||
setRef?.(view);
|
||||
} catch (e) {
|
||||
console.log("Failed to initialize Codemirror", e);
|
||||
}
|
||||
},
|
||||
[forceUpdateKey],
|
||||
);
|
||||
|
||||
// For read-only mode, update content when `defaultValue` changes
|
||||
useEffect(
|
||||
function updateReadOnlyEditor() {
|
||||
if (readOnly && cm.current?.view != null) {
|
||||
updateContents(cm.current.view, defaultValue || "");
|
||||
}
|
||||
},
|
||||
[defaultValue, readOnly],
|
||||
);
|
||||
|
||||
// Force input to update when receiving change and not in focus
|
||||
useLayoutEffect(
|
||||
function updateNonFocusedEditor() {
|
||||
const notFocused = !cm.current?.view.hasFocus;
|
||||
if (notFocused && cm.current != null) {
|
||||
updateContents(cm.current.view, defaultValue || "");
|
||||
}
|
||||
},
|
||||
[defaultValue],
|
||||
);
|
||||
|
||||
// Add bg classes to actions, so they appear over the text
|
||||
const decoratedActions = useMemo(() => {
|
||||
const results = [];
|
||||
const actionClassName = classNames(
|
||||
"bg-surface transition-opacity transform-gpu opacity-0 group-hover:opacity-100 hover:opacity-100! shadow",
|
||||
);
|
||||
|
||||
if (format) {
|
||||
results.push(
|
||||
<IconButton
|
||||
showConfirm
|
||||
key="format"
|
||||
size="sm"
|
||||
title="Reformat contents"
|
||||
icon="magic_wand"
|
||||
variant="border"
|
||||
className={classNames(actionClassName)}
|
||||
onClick={async () => {
|
||||
if (cm.current === null) return;
|
||||
const { doc } = cm.current.view.state;
|
||||
const formatted = await format(doc.toString());
|
||||
// Update editor and blur because the cursor will reset anyway
|
||||
cm.current.view.dispatch({
|
||||
changes: { from: 0, to: doc.length, insert: formatted },
|
||||
});
|
||||
cm.current.view.contentDOM.blur();
|
||||
// Fire change event
|
||||
onChange?.(formatted);
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
results.push(
|
||||
Children.map(actions, (existingChild) => {
|
||||
if (!isValidElement<{ className?: string }>(existingChild)) return null;
|
||||
const existingProps = existingChild.props;
|
||||
|
||||
return cloneElement(existingChild, {
|
||||
...existingProps,
|
||||
className: classNames(existingProps.className, actionClassName),
|
||||
});
|
||||
}),
|
||||
);
|
||||
return results;
|
||||
}, [actions, format, onChange]);
|
||||
|
||||
const cmContainer = (
|
||||
<div
|
||||
ref={initEditorRef}
|
||||
className={classNames(
|
||||
className,
|
||||
"cm-wrapper text-base",
|
||||
disabled && "opacity-disabled",
|
||||
type === "password" && "cm-obscure-text",
|
||||
heightMode === "auto" ? "cm-auto-height" : "cm-full-height",
|
||||
singleLine ? "cm-singleline" : "cm-multiline",
|
||||
readOnly && "cm-readonly",
|
||||
)}
|
||||
/>
|
||||
);
|
||||
|
||||
if (singleLine || containerOnly) {
|
||||
return cmContainer;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="group relative h-full w-full x-theme-editor bg-surface">
|
||||
{cmContainer}
|
||||
{decoratedActions && (
|
||||
<HStack
|
||||
space={1}
|
||||
justifyContent="end"
|
||||
className={classNames(
|
||||
"absolute bottom-2 left-0 right-0",
|
||||
"pointer-events-none", // No pointer events, so we don't block the editor
|
||||
)}
|
||||
>
|
||||
{decoratedActions}
|
||||
</HStack>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function getExtensions({
|
||||
stateKey,
|
||||
container,
|
||||
singleLine,
|
||||
hideGutter,
|
||||
onChange,
|
||||
onPaste,
|
||||
onPasteOverwrite,
|
||||
onFocus,
|
||||
onBlur,
|
||||
onKeyDown,
|
||||
keyDownHandler,
|
||||
}: Pick<CodeEditorProps, "singleLine" | "hideGutter"> & {
|
||||
stateKey: CodeEditorProps["stateKey"];
|
||||
container: HTMLDivElement | null;
|
||||
onChange: RefObject<CodeEditorProps["onChange"]>;
|
||||
onPaste: RefObject<CodeEditorProps["onPaste"]>;
|
||||
onPasteOverwrite: RefObject<CodeEditorProps["onPasteOverwrite"]>;
|
||||
onFocus: RefObject<CodeEditorProps["onFocus"]>;
|
||||
onBlur: RefObject<CodeEditorProps["onBlur"]>;
|
||||
onKeyDown: RefObject<CodeEditorProps["onKeyDown"]>;
|
||||
keyDownHandler: RefObject<CodeEditorProps["keyDownHandler"]>;
|
||||
}) {
|
||||
// TODO: Ensure tooltips render inside the dialog if we are in one.
|
||||
const parent =
|
||||
container?.closest<HTMLDivElement>('[role="dialog"]') ??
|
||||
document.querySelector<HTMLDivElement>("#cm-portal") ??
|
||||
undefined;
|
||||
|
||||
return [
|
||||
...baseExtensions, // Must be first
|
||||
EditorView.contentAttributes.of({
|
||||
autocapitalize: "off",
|
||||
autocorrect: "off",
|
||||
// Keeps macOS Writing Tools from offering to write code for us
|
||||
writingsuggestions: "false",
|
||||
}),
|
||||
EditorView.domEventHandlers({
|
||||
focus: () => {
|
||||
onFocus.current?.();
|
||||
},
|
||||
blur: () => {
|
||||
onBlur.current?.();
|
||||
},
|
||||
keydown: (e, view) => {
|
||||
if (keyDownHandler.current?.(e, view)) {
|
||||
return true;
|
||||
}
|
||||
onKeyDown.current?.(e);
|
||||
},
|
||||
paste: (e, v) => {
|
||||
const textData = e.clipboardData?.getData("text/plain") ?? "";
|
||||
onPaste.current?.(textData);
|
||||
if (v.state.selection.main.from === 0 && v.state.selection.main.to === v.state.doc.length) {
|
||||
onPasteOverwrite.current?.(e, textData);
|
||||
}
|
||||
},
|
||||
}),
|
||||
tooltips({ parent }),
|
||||
keymap.of(singleLine ? defaultKeymap.filter((k) => k.key !== "Enter") : defaultKeymap),
|
||||
...(singleLine ? [singleLineExtensions()] : []),
|
||||
...(!singleLine ? multiLineExtensions({ hideGutter }) : []),
|
||||
|
||||
// ------------------------ //
|
||||
// Things that must be last //
|
||||
// ------------------------ //
|
||||
|
||||
EditorView.updateListener.of((update) => {
|
||||
if (update.startState === update.state) return;
|
||||
|
||||
if (onChange && update.docChanged) {
|
||||
onChange.current?.(update.state.doc.toString());
|
||||
}
|
||||
|
||||
saveCachedEditorStateDebounced(stateKey, update.state);
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
const placeholderElFromText = (text: string | undefined) => {
|
||||
const el = document.createElement("div");
|
||||
// Default to <SPACE> because codemirror needs it for sizing. I'm not sure why, but probably something
|
||||
// to do with how Yaak "hacks" it with CSS for single line input.
|
||||
el.innerHTML = text ? text.replaceAll("\n", "<br/>") : " ";
|
||||
return el;
|
||||
};
|
||||
|
||||
// Caching the state is too expensive to do on every update (every keystroke and cursor move),
|
||||
// so debounce it per state key and flush when the editor unmounts.
|
||||
//
|
||||
// The cost scales with the document, and every update pays it in full:
|
||||
// - `state.toJSON` flattens the whole rope into a string, ~0.13 ms per 200 KB
|
||||
// - the fingerprint is an exact md5 for editable documents, ~0.3 ms per 200 KB. `docFingerprint`
|
||||
// only samples read-only ones, so editing a large body still hashes all of it
|
||||
// - `sessionStorage.setItem` is synchronous and blocks the main thread
|
||||
// Typing in a 200 KB body costs ~0.4 ms per keystroke before the storage write, and a 1 MB one
|
||||
// ~2.3 ms. Read-only documents skip most of the hashing but still serialize, which is the larger
|
||||
// half once documents get into the megabytes.
|
||||
const SAVE_STATE_DEBOUNCE_MS = 500;
|
||||
const stateSavers = new Map<string, ReturnType<typeof debounce>>();
|
||||
|
||||
function saveCachedEditorStateDebounced(stateKey: string | null, state: EditorState) {
|
||||
if (!stateKey) return;
|
||||
let saver = stateSavers.get(stateKey);
|
||||
if (saver == null) {
|
||||
saver = debounce(
|
||||
(s: EditorState) => saveCachedEditorState(stateKey, s),
|
||||
SAVE_STATE_DEBOUNCE_MS,
|
||||
);
|
||||
stateSavers.set(stateKey, saver);
|
||||
}
|
||||
saver(state);
|
||||
}
|
||||
|
||||
// NOTE: Only called when an editor unmounts, so the saver is dropped rather than left in the map
|
||||
// for every state key the session has ever shown. A pending saver holds the last EditorState,
|
||||
// which holds the whole document.
|
||||
function flushCachedEditorState(stateKey: string | null) {
|
||||
if (!stateKey) return;
|
||||
const saver = stateSavers.get(stateKey);
|
||||
if (saver == null) return;
|
||||
saver.flush();
|
||||
stateSavers.delete(stateKey);
|
||||
}
|
||||
|
||||
function saveCachedEditorState(stateKey: string | null, state: EditorState | null) {
|
||||
if (!stateKey || state == null) return;
|
||||
const stateObj = state.toJSON(stateFields);
|
||||
|
||||
// Save state in sessionStorage by removing doc and saving a fingerprint of it instead.
|
||||
// This will be checked on restore and put back in if it matches.
|
||||
// Editable documents get the exact hash, so a collision can never restore undo history
|
||||
// belonging to other content
|
||||
stateObj.docHash = docFingerprint(stateObj.doc, { exact: !state.readOnly });
|
||||
stateObj.doc = undefined;
|
||||
|
||||
try {
|
||||
sessionStorage.setItem(computeFullStateKey(stateKey), JSON.stringify(stateObj));
|
||||
} catch (err) {
|
||||
console.log("Failed to save to editor state", stateKey, err);
|
||||
}
|
||||
}
|
||||
|
||||
function getCachedEditorState(doc: string, stateKey: string | null, readOnly: boolean) {
|
||||
if (stateKey == null) return;
|
||||
|
||||
try {
|
||||
const stateStr = sessionStorage.getItem(computeFullStateKey(stateKey));
|
||||
if (stateStr == null) return null;
|
||||
|
||||
const { docHash, ...state } = JSON.parse(stateStr);
|
||||
|
||||
// Ensure the doc matches the one that was used to save the state
|
||||
if (docHash !== docFingerprint(doc, { exact: !readOnly })) {
|
||||
return null;
|
||||
}
|
||||
|
||||
state.doc = doc;
|
||||
return state;
|
||||
} catch (err) {
|
||||
console.log("Failed to restore editor storage", stateKey, err);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function computeFullStateKey(stateKey: string): string {
|
||||
return `editor.${stateKey}`;
|
||||
}
|
||||
|
||||
function updateContents(view: EditorView, text: string) {
|
||||
// Replace codemirror contents
|
||||
const currentDoc = view.state.doc.toString();
|
||||
|
||||
if (currentDoc === text) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (text.startsWith(currentDoc)) {
|
||||
// If we're just appending, append only the changes. This preserves
|
||||
// things like scroll position.
|
||||
view.dispatch({
|
||||
changes: view.state.changes({
|
||||
from: currentDoc.length,
|
||||
insert: text.slice(currentDoc.length),
|
||||
}),
|
||||
});
|
||||
} else {
|
||||
// If we're replacing everything, reset the entire content
|
||||
view.dispatch({
|
||||
changes: view.state.changes({
|
||||
from: 0,
|
||||
to: currentDoc.length,
|
||||
insert: text,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { lazy, Suspense } from "react";
|
||||
import type { CodeEditorProps } from "./CodeEditor";
|
||||
|
||||
const CodeEditor_ = lazy(() => import("./CodeEditor").then((m) => ({ default: m.CodeEditor })));
|
||||
|
||||
export function LazyCodeEditor(props: CodeEditorProps) {
|
||||
return (
|
||||
<Suspense>
|
||||
<CodeEditor_ {...props} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
import {
|
||||
autocompletion,
|
||||
closeBrackets,
|
||||
closeBracketsKeymap,
|
||||
completionKeymap,
|
||||
} from "@codemirror/autocomplete";
|
||||
import { history, historyKeymap } from "@codemirror/commands";
|
||||
import { go } from "@codemirror/lang-go";
|
||||
import { java } from "@codemirror/lang-java";
|
||||
import { javascript } from "@codemirror/lang-javascript";
|
||||
import { markdown } from "@codemirror/lang-markdown";
|
||||
import { php } from "@codemirror/lang-php";
|
||||
import { python } from "@codemirror/lang-python";
|
||||
import { xml } from "@codemirror/lang-xml";
|
||||
import {
|
||||
bracketMatching,
|
||||
codeFolding,
|
||||
foldGutter,
|
||||
foldKeymap,
|
||||
HighlightStyle,
|
||||
indentOnInput,
|
||||
LanguageSupport,
|
||||
StreamLanguage,
|
||||
syntaxHighlighting,
|
||||
} from "@codemirror/language";
|
||||
import { c, csharp, kotlin, objectiveC } from "@codemirror/legacy-modes/mode/clike";
|
||||
import { clojure } from "@codemirror/legacy-modes/mode/clojure";
|
||||
import { http } from "@codemirror/legacy-modes/mode/http";
|
||||
import { oCaml } from "@codemirror/legacy-modes/mode/mllike";
|
||||
import { powerShell } from "@codemirror/legacy-modes/mode/powershell";
|
||||
import { r } from "@codemirror/legacy-modes/mode/r";
|
||||
import { ruby } from "@codemirror/legacy-modes/mode/ruby";
|
||||
import { shell } from "@codemirror/legacy-modes/mode/shell";
|
||||
import { swift } from "@codemirror/legacy-modes/mode/swift";
|
||||
import { linter, lintGutter, lintKeymap } from "@codemirror/lint";
|
||||
import { search, searchKeymap } from "@codemirror/search";
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import {
|
||||
crosshairCursor,
|
||||
drawSelection,
|
||||
dropCursor,
|
||||
EditorView,
|
||||
highlightActiveLineGutter,
|
||||
highlightSpecialChars,
|
||||
keymap,
|
||||
lineNumbers,
|
||||
rectangularSelection,
|
||||
} from "@codemirror/view";
|
||||
import { tags as t } from "@lezer/highlight";
|
||||
import { jsonc, jsoncLanguage } from "@shopify/lang-jsonc";
|
||||
import { pluralizeCount } from "@yaakapp-internal/lib/pluralize";
|
||||
import type { EditorLanguage } from "@yaakapp-internal/plugins";
|
||||
import { jsonParseLinter } from "./json-lint";
|
||||
import { searchMatchCount } from "./searchMatchCount";
|
||||
import { text } from "./text/extension";
|
||||
|
||||
export const syntaxHighlightStyle = HighlightStyle.define([
|
||||
{
|
||||
tag: [t.documentMeta, t.blockComment, t.lineComment, t.docComment, t.comment],
|
||||
color: "var(--textSubtlest)",
|
||||
},
|
||||
{
|
||||
tag: [t.emphasis],
|
||||
textDecoration: "underline",
|
||||
},
|
||||
{
|
||||
tag: [t.angleBracket, t.paren, t.bracket, t.squareBracket, t.brace, t.separator, t.punctuation],
|
||||
color: "var(--textSubtle)",
|
||||
},
|
||||
{
|
||||
tag: [t.link, t.name, t.tagName, t.angleBracket, t.docString, t.number],
|
||||
color: "var(--info)",
|
||||
},
|
||||
{ tag: [t.variableName], color: "var(--success)" },
|
||||
{ tag: [t.bool], color: "var(--warning)" },
|
||||
{ tag: [t.attributeName, t.propertyName], color: "var(--primary)" },
|
||||
{ tag: [t.attributeValue], color: "var(--warning)" },
|
||||
{ tag: [t.string], color: "var(--notice)" },
|
||||
{ tag: [t.atom, t.meta, t.operator, t.bool, t.null, t.keyword], color: "var(--danger)" },
|
||||
]);
|
||||
|
||||
const syntaxTheme = EditorView.theme({}, { dark: true });
|
||||
|
||||
export const closeBracketsExtensions: Extension = [
|
||||
closeBrackets(),
|
||||
keymap.of([...closeBracketsKeymap]),
|
||||
];
|
||||
|
||||
const legacyLang = (mode: Parameters<typeof StreamLanguage.define>[0]) => {
|
||||
return () => new LanguageSupport(StreamLanguage.define(mode));
|
||||
};
|
||||
|
||||
export type LanguageSupports = Record<string, null | (() => LanguageSupport)>;
|
||||
|
||||
export const syntaxExtensions: Record<EditorLanguage, null | (() => LanguageSupport)> = {
|
||||
graphql: null,
|
||||
json: jsonc,
|
||||
javascript: javascript,
|
||||
// HTML as XML because HTML is oddly slow
|
||||
html: xml,
|
||||
xml: xml,
|
||||
text: text,
|
||||
markdown: markdown,
|
||||
c: legacyLang(c),
|
||||
clojure: legacyLang(clojure),
|
||||
csharp: legacyLang(csharp),
|
||||
go: go,
|
||||
http: legacyLang(http),
|
||||
java: java,
|
||||
kotlin: legacyLang(kotlin),
|
||||
objective_c: legacyLang(objectiveC),
|
||||
ocaml: legacyLang(oCaml),
|
||||
php: php,
|
||||
powershell: legacyLang(powerShell),
|
||||
python: python,
|
||||
r: legacyLang(r),
|
||||
ruby: legacyLang(ruby),
|
||||
shell: legacyLang(shell),
|
||||
swift: legacyLang(swift),
|
||||
};
|
||||
|
||||
const closeBracketsFor: string[] = ["json", "javascript", "graphql"];
|
||||
|
||||
export function getLanguageExtension({
|
||||
language = "text",
|
||||
lintExtension,
|
||||
hideGutter,
|
||||
languages = syntaxExtensions,
|
||||
extraExtensions: hostExtensions = [],
|
||||
wrap,
|
||||
}: {
|
||||
language?: string | null;
|
||||
lintExtension?: Extension;
|
||||
hideGutter?: boolean;
|
||||
/** Language supports by name, for a host with languages of its own */
|
||||
languages?: LanguageSupports;
|
||||
extraExtensions?: Extension[];
|
||||
/** Wraps the base language, as a templating language does */
|
||||
wrap?: (base: LanguageSupport, extraExtensions: Extension[]) => Extension;
|
||||
}): Extension {
|
||||
const extraExtensions: Extension[] = [...hostExtensions];
|
||||
|
||||
// Only close brackets on languages that need it
|
||||
if (language && closeBracketsFor.includes(language)) {
|
||||
extraExtensions.push(closeBracketsExtensions);
|
||||
}
|
||||
|
||||
if (language === "json") {
|
||||
extraExtensions.push(lintExtension ?? linter(jsonParseLinter()));
|
||||
extraExtensions.push(
|
||||
jsoncLanguage.data.of({
|
||||
commentTokens: { line: "//", block: { open: "/*", close: "*/" } },
|
||||
}),
|
||||
);
|
||||
if (!hideGutter) {
|
||||
extraExtensions.push(lintGutter());
|
||||
}
|
||||
}
|
||||
|
||||
const maybeBase = language ? languages[language] : null;
|
||||
const base = typeof maybeBase === "function" ? maybeBase() : null;
|
||||
if (base == null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return wrap ? wrap(base, extraExtensions) : [base, extraExtensions];
|
||||
}
|
||||
|
||||
// Filter out autocomplete start triggers from completionKeymap since we handle it via configurable hotkeys.
|
||||
// Keep navigation keys (ArrowUp/Down, Enter, Escape, etc.) but remove startCompletion bindings.
|
||||
const filteredCompletionKeymap = completionKeymap.filter((binding) => {
|
||||
const key = binding.key?.toLowerCase() ?? "";
|
||||
const mac = (binding as { mac?: string }).mac?.toLowerCase() ?? "";
|
||||
// Filter out Ctrl-Space and Mac-specific autocomplete triggers (Alt-`, Alt-i)
|
||||
const isStartTrigger = key.includes("space") || mac.includes("alt-") || mac.includes("`");
|
||||
return !isStartTrigger;
|
||||
});
|
||||
|
||||
export const baseExtensions = [
|
||||
highlightSpecialChars(),
|
||||
history(),
|
||||
dropCursor(),
|
||||
drawSelection(),
|
||||
autocompletion({
|
||||
tooltipClass: () => "x-theme-menu",
|
||||
closeOnBlur: true, // Set to `false` for debugging in devtools without closing it
|
||||
defaultKeymap: false, // We handle the trigger via configurable hotkeys
|
||||
compareCompletions: (a, b) => {
|
||||
// Don't sort completions at all, only on boost
|
||||
return (a.boost ?? 0) - (b.boost ?? 0);
|
||||
},
|
||||
}),
|
||||
syntaxHighlighting(syntaxHighlightStyle),
|
||||
syntaxTheme,
|
||||
keymap.of([...historyKeymap, ...filteredCompletionKeymap]),
|
||||
];
|
||||
|
||||
export const readonlyExtensions = [
|
||||
EditorState.readOnly.of(true),
|
||||
EditorView.contentAttributes.of({ tabindex: "-1" }),
|
||||
];
|
||||
|
||||
export const editableExtensions: Extension[] = [];
|
||||
|
||||
export const multiLineExtensions = ({ hideGutter }: { hideGutter?: boolean }) => [
|
||||
search({ top: true }),
|
||||
searchMatchCount(),
|
||||
hideGutter
|
||||
? []
|
||||
: [
|
||||
lineNumbers(),
|
||||
foldGutter({
|
||||
markerDOM: (open) => {
|
||||
const el = document.createElement("div");
|
||||
el.classList.add("fold-gutter-icon");
|
||||
el.tabIndex = -1;
|
||||
if (open) {
|
||||
el.setAttribute("data-open", "");
|
||||
}
|
||||
return el;
|
||||
},
|
||||
}),
|
||||
],
|
||||
codeFolding({
|
||||
placeholderDOM(_view, onclick, prepared) {
|
||||
const el = document.createElement("span");
|
||||
el.onclick = onclick;
|
||||
el.className = "cm-foldPlaceholder";
|
||||
el.innerText = prepared || "…";
|
||||
el.title = "unfold";
|
||||
el.ariaLabel = "folded code";
|
||||
return el;
|
||||
},
|
||||
/**
|
||||
* Show the number of items when code folded. NOTE: this doesn't get called when restoring
|
||||
* a previous serialized editor state, which is a bummer
|
||||
*/
|
||||
preparePlaceholder(state, range) {
|
||||
let count: number | undefined;
|
||||
let startToken = "{";
|
||||
let endToken = "}";
|
||||
|
||||
const prevLine = state.doc.lineAt(range.from).text;
|
||||
const isArray = prevLine.lastIndexOf("[") > prevLine.lastIndexOf("{");
|
||||
|
||||
if (isArray) {
|
||||
startToken = "[";
|
||||
endToken = "]";
|
||||
}
|
||||
|
||||
const internal = state.sliceDoc(range.from, range.to);
|
||||
const toParse = startToken + internal + endToken;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(toParse);
|
||||
count = Object.keys(parsed).length;
|
||||
} catch {
|
||||
/* empty */
|
||||
}
|
||||
|
||||
if (count !== undefined) {
|
||||
const label = isArray ? "item" : "key";
|
||||
return pluralizeCount(label, count);
|
||||
}
|
||||
},
|
||||
}),
|
||||
indentOnInput(),
|
||||
rectangularSelection(),
|
||||
crosshairCursor(),
|
||||
bracketMatching(),
|
||||
highlightActiveLineGutter(),
|
||||
keymap.of([...searchKeymap, ...foldKeymap, ...lintKeymap]),
|
||||
];
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { Diagnostic } from "@codemirror/lint";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { type ParseError, parse, printParseErrorCode } from "jsonc-parser";
|
||||
|
||||
// jsonc-parser reports error codes, so these are the words the editor shows for them
|
||||
const MESSAGES: Record<string, string> = {
|
||||
InvalidSymbol: "Invalid symbol",
|
||||
InvalidNumberFormat: "Invalid number format",
|
||||
PropertyNameExpected: "Property name expected",
|
||||
ValueExpected: "Value expected",
|
||||
ColonExpected: "Colon expected",
|
||||
CommaExpected: "Comma expected",
|
||||
CloseBraceExpected: "Closing brace expected",
|
||||
CloseBracketExpected: "Closing bracket expected",
|
||||
EndOfFileExpected: "End of file expected",
|
||||
InvalidCommentToken: "Comments are not allowed",
|
||||
UnexpectedEndOfComment: "Unexpected end of comment",
|
||||
UnexpectedEndOfString: "Unexpected end of string",
|
||||
UnexpectedEndOfNumber: "Unexpected end of number",
|
||||
InvalidUnicode: "Invalid unicode sequence",
|
||||
InvalidEscapeCharacter: "Invalid escape character",
|
||||
InvalidCharacter: "Invalid character",
|
||||
};
|
||||
|
||||
export interface JsonLintOptions {
|
||||
allowComments?: boolean;
|
||||
allowTrailingCommas?: boolean;
|
||||
/** Rewrites the document before parsing, keeping every offset where it was */
|
||||
escape?: (doc: string) => string;
|
||||
}
|
||||
|
||||
export function jsonParseLinter(options?: JsonLintOptions) {
|
||||
return (view: EditorView): Diagnostic[] => {
|
||||
const doc = view.state.doc.toString();
|
||||
if (doc.trim() === "") return [];
|
||||
|
||||
const escapedDoc = options?.escape?.(doc) ?? doc;
|
||||
|
||||
const errors: ParseError[] = [];
|
||||
parse(escapedDoc, errors, {
|
||||
allowTrailingComma: options?.allowTrailingCommas ?? false,
|
||||
disallowComments: !(options?.allowComments ?? true),
|
||||
});
|
||||
|
||||
// Later errors are mostly consequences of the first one, so only that one is shown
|
||||
const error = errors[0];
|
||||
if (error == null) return [];
|
||||
|
||||
return [
|
||||
{
|
||||
from: error.offset,
|
||||
to: error.offset + error.length,
|
||||
severity: "error",
|
||||
message: MESSAGES[printParseErrorCode(error.error)] ?? "Invalid JSON",
|
||||
},
|
||||
];
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import type { EditorView, ViewUpdate } from "@codemirror/view";
|
||||
import { ViewPlugin } from "@codemirror/view";
|
||||
import type { JsonPathSegment } from "./jsonPath";
|
||||
import { jsonPathSegmentsAt } from "./jsonPath";
|
||||
|
||||
export interface BreadcrumbUpdate {
|
||||
/** Path to the cursor, or `null` when the document isn't JSON. */
|
||||
segments: JsonPathSegment[] | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports the JSON path under the cursor when the editor is created (it may restore a
|
||||
* cached selection), and whenever the selection, document, or parsed tree changes. The
|
||||
* tree matters because large documents parse in the background, so a path read early
|
||||
* can be wrong until the parser reaches the cursor.
|
||||
*
|
||||
* The callback is not fired on blur: moving focus to the filter box (by clicking
|
||||
* a crumb) must not erase the breadcrumb that was just acted on.
|
||||
*/
|
||||
export function jsonBreadcrumbExtension(onUpdate: (update: BreadcrumbUpdate) => void): Extension {
|
||||
const report = (view: EditorView) => {
|
||||
onUpdate({ segments: jsonPathSegmentsAt(view.state, view.state.selection.main.head) });
|
||||
};
|
||||
|
||||
return ViewPlugin.define((view) => {
|
||||
report(view);
|
||||
return {
|
||||
update(update: ViewUpdate) {
|
||||
if (
|
||||
update.selectionSet ||
|
||||
update.docChanged ||
|
||||
syntaxTree(update.startState) !== syntaxTree(update.state)
|
||||
) {
|
||||
report(update.view);
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { jsonc } from "@shopify/lang-jsonc";
|
||||
import { forceParsing } from "@codemirror/language";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { jsonPathSegmentsAt, jsonPathToSegments, segmentsToJsonPath } from "./jsonPath";
|
||||
|
||||
function stateFor(doc: string): EditorState {
|
||||
const state = EditorState.create({ doc, extensions: [jsonc()] });
|
||||
// Ensure the whole doc is parsed so resolveInner sees a complete tree.
|
||||
forceParsing({ state } as never, doc.length, 5000);
|
||||
return state;
|
||||
}
|
||||
|
||||
/** JSONPath produced when the cursor sits just after the first occurrence of `needle`. */
|
||||
function pathAt(doc: string, needle: string): string {
|
||||
const pos = doc.indexOf(needle) + needle.length;
|
||||
const segs = jsonPathSegmentsAt(stateFor(doc), pos);
|
||||
if (segs == null) throw new Error("no JSON tree");
|
||||
return segmentsToJsonPath(segs);
|
||||
}
|
||||
|
||||
/** JSONPath produced when the cursor sits just before the first occurrence of `needle`. */
|
||||
function pathBefore(doc: string, needle: string): string {
|
||||
const pos = doc.indexOf(needle);
|
||||
const segs = jsonPathSegmentsAt(stateFor(doc), pos);
|
||||
if (segs == null) throw new Error("no JSON tree");
|
||||
return segmentsToJsonPath(segs);
|
||||
}
|
||||
|
||||
describe("jsonPathSegmentsAt", () => {
|
||||
test("nested object keys", () => {
|
||||
const doc = `{ "address": { "geo": { "lat": "-37" } } }`;
|
||||
expect(pathAt(doc, `-37`)).toBe(`$.address.geo.lat`);
|
||||
});
|
||||
|
||||
test("array element index", () => {
|
||||
const doc = `{ "featured": [ { "id": 1 }, { "id": 2 } ] }`;
|
||||
expect(pathAt(doc, `2`)).toBe(`$.featured[1].id`);
|
||||
});
|
||||
|
||||
test("root array element", () => {
|
||||
const doc = `[ { "id": 1 }, { "id": 2 } ]`;
|
||||
expect(pathAt(doc, `"id": 2`)).toBe(`$[1].id`);
|
||||
});
|
||||
|
||||
test("key containing a dot uses bracket-quote notation", () => {
|
||||
const doc = `{ "sort": { "link": { "filter": { "category.id": [ "100" ] } } } }`;
|
||||
expect(pathAt(doc, `"100"`)).toBe(`$.sort.link.filter["category.id"][0]`);
|
||||
});
|
||||
|
||||
test("cursor on a property name resolves that key", () => {
|
||||
const doc = `{ "outer": { "inner": 5 } }`;
|
||||
expect(pathAt(doc, `"inner"`)).toBe(`$.outer.inner`);
|
||||
});
|
||||
|
||||
test("deeply nested arrays and objects", () => {
|
||||
const doc = `{ "a": [ { "b": [ 10, 20, 30 ] } ] }`;
|
||||
expect(pathAt(doc, `30`)).toBe(`$.a[0].b[2]`);
|
||||
});
|
||||
|
||||
test("root scalar yields the root path", () => {
|
||||
expect(pathAt(`"hello"`, `hello`)).toBe(`$`);
|
||||
});
|
||||
|
||||
test("caret just before a key still resolves that key", () => {
|
||||
// The character to the left is the object's whitespace, not the property.
|
||||
const doc = `[\n {\n "userId": 1,\n "body": "x"\n }\n]`;
|
||||
expect(pathBefore(doc, `"body"`)).toBe(`$[0].body`);
|
||||
});
|
||||
|
||||
test("caret in a line's indentation resolves that line's member", () => {
|
||||
// Caret in the blank indentation of the `title` line (structurally the
|
||||
// object's whitespace) reads as being on `title`, not a neighbour.
|
||||
const doc = `[\n {\n "userId": 1,\n "id": 1,\n "title": "x"\n }\n]`;
|
||||
const pos = doc.indexOf(`"title"`) - 2; // two spaces into the title line
|
||||
const segs = jsonPathSegmentsAt(stateFor(doc), pos);
|
||||
expect(segs == null ? null : segmentsToJsonPath(segs)).toBe(`$[0].title`);
|
||||
});
|
||||
|
||||
test("caret at the end of an array element keeps the element index", () => {
|
||||
// The caret sits after `}` where the left token is the object's close brace.
|
||||
const doc = `[\n { "id": 1 },\n { "id": 2 }\n]`;
|
||||
const pos = doc.indexOf(`},`) + 1;
|
||||
const segs = jsonPathSegmentsAt(stateFor(doc), pos);
|
||||
expect(segs == null ? null : segmentsToJsonPath(segs)).toBe(`$[0]`);
|
||||
});
|
||||
|
||||
test("non-JSON documents return null", () => {
|
||||
const state = EditorState.create({ doc: `<xml/>` });
|
||||
expect(jsonPathSegmentsAt(state, 3)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("segmentsToJsonPath", () => {
|
||||
test("empty segment list is the root", () => {
|
||||
expect(segmentsToJsonPath([])).toBe(`$`);
|
||||
});
|
||||
|
||||
test("partial path via count", () => {
|
||||
const segs = [
|
||||
{ kind: "key", key: "a" },
|
||||
{ kind: "index", index: 2 },
|
||||
{ kind: "key", key: "b" },
|
||||
] as const;
|
||||
expect(segmentsToJsonPath([...segs], 2)).toBe(`$.a[2]`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("jsonPathToSegments", () => {
|
||||
// The filter side of these keys is tested in crates/yaak-filter.
|
||||
test.each([
|
||||
"identifier",
|
||||
"a.b",
|
||||
"space key",
|
||||
"",
|
||||
'quote"key',
|
||||
"back\\slash",
|
||||
"combined\"\\]'key",
|
||||
"*",
|
||||
"$",
|
||||
"$foo",
|
||||
"?(true)",
|
||||
"line\nbreak\t\u0000",
|
||||
"emoji 🤔",
|
||||
"__proto__",
|
||||
])("round-trips the caret path to the literal key %j", (key) => {
|
||||
const doc = JSON.stringify({ [key]: "needle-value", decoy: "wrong-value" }, null, 2);
|
||||
const segments = jsonPathSegmentsAt(stateFor(doc), doc.indexOf('"needle-value"') + 4);
|
||||
expect(segments).toEqual([{ kind: "key", key }]);
|
||||
expect(jsonPathToSegments(segmentsToJsonPath(segments ?? []))).toEqual(segments);
|
||||
});
|
||||
|
||||
test("round-trips paths built by segmentsToJsonPath", () => {
|
||||
for (const path of ["$", "$[0]", "$[0].id", '$.data["user.name"][12]', '$["say \\"hi\\""]']) {
|
||||
const segments = jsonPathToSegments(path);
|
||||
expect(segments).not.toBeNull();
|
||||
expect(segmentsToJsonPath(segments ?? [])).toBe(path);
|
||||
}
|
||||
});
|
||||
|
||||
test("returns null for paths that don't name a single location", () => {
|
||||
for (const path of [
|
||||
"$..id",
|
||||
"$[*]",
|
||||
"$.items[?(@.id)]",
|
||||
"$[0:2]",
|
||||
"items[0]",
|
||||
"$.a b",
|
||||
'$["\\q"]',
|
||||
'$["unterminated]',
|
||||
'$["line\nbreak"]',
|
||||
"$[01]",
|
||||
"$[9007199254740993]",
|
||||
"$.$",
|
||||
]) {
|
||||
expect(jsonPathToSegments(path)).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
import type { EditorState } from "@codemirror/state";
|
||||
import type { SyntaxNode } from "@lezer/common";
|
||||
import type { JsonPathSegment } from "@yaakapp-internal/lib/jsonPath";
|
||||
|
||||
export { jsonPathToSegments } from "@yaakapp-internal/lib/jsonPath";
|
||||
export type { JsonPathSegment } from "@yaakapp-internal/lib/jsonPath";
|
||||
|
||||
// Lezer node names from the JSONC grammar (@shopify/lang-jsonc). A JSON value is
|
||||
// exactly one of these; everything else in the tree is punctuation or a comment.
|
||||
const VALUE_NODES = new Set(["Object", "Array", "String", "Number", "True", "False", "Null"]);
|
||||
// The nodes with children that a caret can land "between" — its whitespace and
|
||||
// punctuation belong to the container, not to any value inside it.
|
||||
const CONTAINER_NODES = new Set(["Object", "Array", "JsoncText"]);
|
||||
|
||||
/** Read a `PropertyName` (a quoted JSON string) back to its raw key. */
|
||||
function keyFromPropertyName(node: SyntaxNode, state: EditorState): string {
|
||||
const raw = state.doc.sliceString(node.from, node.to);
|
||||
try {
|
||||
return JSON.parse(raw) as string;
|
||||
} catch {
|
||||
// A half-typed or malformed key still deserves a best-effort label.
|
||||
return raw.replace(/^"|"$/g, "");
|
||||
}
|
||||
}
|
||||
|
||||
/** Index of `child` among the value elements of its parent `Array` node. */
|
||||
function indexInArray(array: SyntaxNode, child: SyntaxNode): number {
|
||||
let idx = 0;
|
||||
for (let c = array.firstChild; c != null; c = c.nextSibling) {
|
||||
if (c.from === child.from && c.to === child.to) return idx;
|
||||
if (VALUE_NODES.has(c.name)) idx++;
|
||||
}
|
||||
return idx;
|
||||
}
|
||||
|
||||
/**
|
||||
* The path from the document root to the member on the caret's line, or `null`
|
||||
* when the document has no JSON tree (a different language, or empty). An empty
|
||||
* array means the caret sits at the root value itself.
|
||||
*
|
||||
* A caret exactly on a token uses that token. A caret in a line's whitespace
|
||||
* resolves to the enclosing object or array, so it's re-anchored to the first
|
||||
* non-whitespace character on that line — in pretty-printed JSON each member
|
||||
* starts its own line, so that's the member's own token. This tracks "the line
|
||||
* I'm on" without guessing between neighbouring keys.
|
||||
*
|
||||
* From the anchor, each ancestor contributes a segment: a `Property` its key, a
|
||||
* value directly inside an `Array` its index. Collected deepest-first, reversed.
|
||||
*/
|
||||
export function jsonPathSegmentsAt(state: EditorState, pos: number): JsonPathSegment[] | null {
|
||||
const tree = syntaxTree(state);
|
||||
if (tree.topNode.name !== "JsoncText") return null;
|
||||
|
||||
let node: SyntaxNode = tree.resolveInner(pos, -1);
|
||||
if (CONTAINER_NODES.has(node.name)) {
|
||||
const line = state.doc.lineAt(pos);
|
||||
const indent = line.text.length - line.text.trimStart().length;
|
||||
if (indent < line.text.length) {
|
||||
node = tree.resolveInner(line.from + indent, 1);
|
||||
}
|
||||
}
|
||||
|
||||
const segments: JsonPathSegment[] = [];
|
||||
let cur: SyntaxNode | null = node;
|
||||
while (cur != null) {
|
||||
const parent: SyntaxNode | null = cur.parent;
|
||||
if (cur.name === "Property") {
|
||||
const nameNode = cur.getChild("PropertyName");
|
||||
if (nameNode != null) {
|
||||
segments.push({ kind: "key", key: keyFromPropertyName(nameNode, state) });
|
||||
}
|
||||
} else if (parent != null && parent.name === "Array" && VALUE_NODES.has(cur.name)) {
|
||||
segments.push({ kind: "index", index: indexInArray(parent, cur) });
|
||||
}
|
||||
cur = parent;
|
||||
}
|
||||
|
||||
segments.reverse();
|
||||
return segments;
|
||||
}
|
||||
|
||||
const BARE_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
||||
|
||||
/** A single segment as JSONPath, choosing dot vs. bracket form for a key. */
|
||||
function segmentToJsonPath(segment: JsonPathSegment): string {
|
||||
if (segment.kind === "index") return `[${segment.index}]`;
|
||||
// jsonpath-plus interprets a bare `$` as its root operator.
|
||||
if (BARE_KEY.test(segment.key) && segment.key !== "$") return `.${segment.key}`;
|
||||
// Anything with a dot, space, quote, etc. must be a quoted bracket accessor.
|
||||
// JSON.stringify gives correct double-quoting and escaping, matching the
|
||||
// convention the JSONPath filter box already displays.
|
||||
return `[${JSON.stringify(segment.key)}]`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a JSONPath expression for the first `count` segments (all of them by
|
||||
* default). `segmentsToJsonPath([])` is the root, `$`.
|
||||
*/
|
||||
export function segmentsToJsonPath(segments: JsonPathSegment[], count = segments.length): string {
|
||||
return "$" + segments.slice(0, count).map(segmentToJsonPath).join("");
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import {
|
||||
currentMatch,
|
||||
literalSearch,
|
||||
MAX_COUNT,
|
||||
MatchCounter,
|
||||
normalizeDoc,
|
||||
normalizeSearch,
|
||||
scanNormalized,
|
||||
scanQuery,
|
||||
} from "./searchMatchCount";
|
||||
|
||||
type QueryConfig = ConstructorParameters<typeof SearchQuery>[0];
|
||||
|
||||
const stateOf = (doc: string) => EditorState.create({ doc });
|
||||
|
||||
/**
|
||||
* The matches the counter finds, having checked them against the search panel's own cursor.
|
||||
*
|
||||
* The cursor decides which ranges the editor highlights and which one `find next` lands on, so
|
||||
* a count that doesn't agree with it is a wrong count, however fast it was to produce.
|
||||
*/
|
||||
function matchesOf(doc: string, config: QueryConfig) {
|
||||
const state = stateOf(doc);
|
||||
const query = new SearchQuery(config);
|
||||
const matches = new MatchCounter().matches(state, query);
|
||||
expect(matches).toEqual(scanQuery(state, query));
|
||||
return matches;
|
||||
}
|
||||
|
||||
const countOf = (doc: string, config: QueryConfig) => matchesOf(doc, config).length;
|
||||
|
||||
describe("counting", () => {
|
||||
test("counts every match, whatever the case", () => {
|
||||
expect(countOf("one Two three two", { search: "two" })).toBe(2);
|
||||
expect(countOf("one Two three two", { search: "two", caseSensitive: true })).toBe(1);
|
||||
});
|
||||
|
||||
test("skips matches overlapping an earlier one", () => {
|
||||
expect(countOf("aaaaa", { search: "aa" })).toBe(2);
|
||||
expect(countOf("ababa", { search: "aba" })).toBe(1);
|
||||
});
|
||||
|
||||
test("treats a query as text, not as a pattern", () => {
|
||||
expect(countOf("a.b axb", { search: "a.b" })).toBe(1);
|
||||
});
|
||||
|
||||
test("unquotes escapes unless the query is literal", () => {
|
||||
expect(countOf("one\ntwo\nthree", { search: "\\n" })).toBe(2);
|
||||
expect(countOf("one\\ntwo", { search: "\\n", literal: true })).toBe(1);
|
||||
});
|
||||
|
||||
test("counts regexp and whole word queries through the cursor", () => {
|
||||
expect(literalSearch(new SearchQuery({ search: "a", regexp: true }))).toBe(null);
|
||||
expect(literalSearch(new SearchQuery({ search: "a", wholeWord: true }))).toBe(null);
|
||||
expect(countOf("a1 b2 c3", { search: "[a-z]\\d", regexp: true })).toBe(3);
|
||||
expect(countOf("cat cats cat", { search: "cat", wholeWord: true })).toBe(2);
|
||||
});
|
||||
|
||||
test("stops counting at the cap", () => {
|
||||
expect(countOf("x".repeat(MAX_COUNT + 100), { search: "x" })).toBe(MAX_COUNT + 1);
|
||||
});
|
||||
|
||||
test("reports where the matches are", () => {
|
||||
expect(matchesOf("ab..ab", { search: "ab" })).toEqual([
|
||||
{ from: 0, to: 2 },
|
||||
{ from: 4, to: 6 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("finds nothing to match with an empty needle", () => {
|
||||
expect(scanNormalized(normalizeDoc("abc", false), "")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalization", () => {
|
||||
test("finds what a character decomposes into", () => {
|
||||
// The é is one character holding an `e`, and the match covers the whole of it
|
||||
expect(matchesOf("café", { search: "e" })).toEqual([{ from: 3, to: 4 }]);
|
||||
expect(matchesOf("file", { search: "fi" })).toEqual([{ from: 0, to: 1 }]);
|
||||
expect(matchesOf("a…b", { search: "..." })).toEqual([{ from: 1, to: 2 }]);
|
||||
expect(countOf("one two", { search: "one two" })).toBe(1);
|
||||
expect(countOf("full width", { search: "full" })).toBe(1);
|
||||
});
|
||||
|
||||
test("matches a decomposed query against composed text, and the reverse", () => {
|
||||
expect(countOf("café", { search: "café" })).toBe(1);
|
||||
expect(countOf("café", { search: "café" })).toBe(1);
|
||||
expect(countOf("café", { search: "café" })).toBe(1);
|
||||
});
|
||||
|
||||
test("keeps offsets straight after an expansion", () => {
|
||||
expect(matchesOf("é.é.end", { search: "end" })).toEqual([{ from: 4, to: 7 }]);
|
||||
expect(matchesOf("fififi stop", { search: "stop" })).toEqual([{ from: 4, to: 8 }]);
|
||||
});
|
||||
|
||||
test("normalizes the query whole, the document by character", () => {
|
||||
expect(normalizeSearch("CAFÉ", false)).toBe("café");
|
||||
expect(normalizeSearch("CAFÉ", true)).toBe("CAFÉ");
|
||||
// Whole-string NFKD would fold this to a final sigma, which the cursor never does
|
||||
expect(normalizeDoc("ΟΔΟΣ", false).text).toBe("οδοσ");
|
||||
});
|
||||
|
||||
test("leaves a document that normalizes to itself untouched", () => {
|
||||
const { text, expansions } = normalizeDoc("plain 日本 🎉 text", false);
|
||||
expect(text).toBe("plain 日本 🎉 text");
|
||||
expect(expansions).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("current match", () => {
|
||||
const matches = [
|
||||
{ from: 0, to: 2 },
|
||||
{ from: 4, to: 6 },
|
||||
{ from: 8, to: 10 },
|
||||
];
|
||||
|
||||
test("counts from one, and reports 0 off a match", () => {
|
||||
expect(currentMatch(matches, { from: 4, to: 6 })).toBe(2);
|
||||
expect(currentMatch(matches, { from: 8, to: 10 })).toBe(3);
|
||||
expect(currentMatch(matches, { from: 5, to: 5 })).toBe(2);
|
||||
expect(currentMatch(matches, { from: 2, to: 3 })).toBe(0);
|
||||
expect(currentMatch(matches, { from: 4, to: 7 })).toBe(0);
|
||||
expect(currentMatch([], { from: 0, to: 0 })).toBe(0);
|
||||
});
|
||||
|
||||
test("moving the selection doesn't scan again", () => {
|
||||
const state = stateOf("a1 b2 c3");
|
||||
const query = new SearchQuery({ search: "\\d", regexp: true });
|
||||
const counter = new MatchCounter();
|
||||
const found = counter.matches(state, query);
|
||||
|
||||
// The document a selection-only transaction leaves behind is the one already scanned
|
||||
const moved = state.update({ selection: { anchor: 4, head: 5 } }).state;
|
||||
expect(counter.matches(moved, query)).toBe(found);
|
||||
expect(currentMatch(found, moved.selection.main)).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The mapping from normalized offsets back to document offsets is the part of this that can go
|
||||
* quietly wrong, and only on input nobody thinks to write a case for. So generate the input.
|
||||
*/
|
||||
describe("against the cursor, on awkward text", () => {
|
||||
const ALPHABET = [
|
||||
..."abcABC .\\\n".split(""),
|
||||
"é",
|
||||
"é",
|
||||
"fi",
|
||||
"…",
|
||||
" ",
|
||||
"İ",
|
||||
"Σ",
|
||||
"ς",
|
||||
"日",
|
||||
"🎉",
|
||||
"Ⅻ",
|
||||
"f",
|
||||
"①",
|
||||
"́",
|
||||
];
|
||||
|
||||
/** Seeded, so a failure is the same failure next run */
|
||||
function random(seed: number) {
|
||||
let state = seed;
|
||||
return () => {
|
||||
state = (state * 1664525 + 1013904223) >>> 0;
|
||||
return state / 2 ** 32;
|
||||
};
|
||||
}
|
||||
|
||||
for (const caseSensitive of [false, true]) {
|
||||
test(`agrees on every generated document (caseSensitive: ${caseSensitive})`, () => {
|
||||
const next = random(caseSensitive ? 20260831 : 7);
|
||||
|
||||
for (let round = 0; round < 400; round++) {
|
||||
const doc = Array.from(
|
||||
{ length: 2 + Math.floor(next() * 60) },
|
||||
() => ALPHABET[Math.floor(next() * ALPHABET.length)]!,
|
||||
).join("");
|
||||
|
||||
// Half the queries are lifted out of the document, so matches are actually found
|
||||
const start = Math.floor(next() * doc.length);
|
||||
const search =
|
||||
next() < 0.5
|
||||
? doc.slice(start, start + 1 + Math.floor(next() * 3))
|
||||
: Array.from(
|
||||
{ length: 1 + Math.floor(next() * 2) },
|
||||
() => ALPHABET[Math.floor(next() * ALPHABET.length)]!,
|
||||
).join("");
|
||||
if (search === "") continue;
|
||||
|
||||
const state = stateOf(doc);
|
||||
const query = new SearchQuery({ search, caseSensitive });
|
||||
const where = `doc=${JSON.stringify(doc)} search=${JSON.stringify(search)}`;
|
||||
expect(new MatchCounter().matches(state, query), where).toEqual(scanQuery(state, query));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,325 @@
|
||||
import { getSearchQuery, type SearchQuery, searchPanelOpen } from "@codemirror/search";
|
||||
import type { EditorState, Extension, Text } from "@codemirror/state";
|
||||
import { type EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
|
||||
/** Matches are counted no further than this, since an exact total stops being useful long before */
|
||||
export const MAX_COUNT = 9999;
|
||||
|
||||
/** What normalizing rewrites: anything outside ASCII, plus the case it folds */
|
||||
const REWRITTEN = /\P{ASCII}|[A-Z]+/gu;
|
||||
const REWRITTEN_CASE_SENSITIVE = /\P{ASCII}/gu;
|
||||
|
||||
export interface Match {
|
||||
from: number;
|
||||
to: number;
|
||||
}
|
||||
|
||||
/** A character whose normalized form is a different length, shifting every offset past it */
|
||||
interface Expansion {
|
||||
normFrom: number;
|
||||
normTo: number;
|
||||
docFrom: number;
|
||||
docTo: number;
|
||||
}
|
||||
|
||||
/** A document as SearchCursor compares it, with what's needed to get back to real offsets */
|
||||
export interface NormalizedDoc {
|
||||
text: string;
|
||||
expansions: Expansion[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrites a document the way SearchCursor does — NFKD, then a case fold unless the search is
|
||||
* case-sensitive — in a single pass rather than one call per code point.
|
||||
*
|
||||
* The cursor spends 90% of its time asking ICU about one character at a time, which is what
|
||||
* makes counting matches in a large response slow. Doing it a character at a time still matters
|
||||
* for the result, since it keeps NFKD from reordering marks across characters, so the
|
||||
* granularity stays and only the repeated work goes: each distinct character is normalized once
|
||||
* and the answer reused, and ASCII runs never reach ICU at all.
|
||||
*/
|
||||
export function normalizeDoc(text: string, caseSensitive: boolean): NormalizedDoc {
|
||||
const rewritten = new Map<string, string>();
|
||||
const expansions: Expansion[] = [];
|
||||
let shift = 0;
|
||||
|
||||
const normalized = text.replace(
|
||||
caseSensitive ? REWRITTEN_CASE_SENSITIVE : REWRITTEN,
|
||||
(chunk: string, at: number) => {
|
||||
// An ASCII run only ever folds case, which can't change its length
|
||||
if (chunk.charCodeAt(0) < 0x80) return chunk.toLowerCase();
|
||||
|
||||
let out = rewritten.get(chunk);
|
||||
if (out === undefined) {
|
||||
out = chunk.normalize("NFKD");
|
||||
if (!caseSensitive) out = out.toLowerCase();
|
||||
rewritten.set(chunk, out);
|
||||
}
|
||||
|
||||
if (out.length !== chunk.length) {
|
||||
expansions.push({
|
||||
normFrom: at + shift,
|
||||
normTo: at + shift + out.length,
|
||||
docFrom: at,
|
||||
docTo: at + chunk.length,
|
||||
});
|
||||
shift += out.length - chunk.length;
|
||||
}
|
||||
|
||||
return out;
|
||||
},
|
||||
);
|
||||
|
||||
return { text: normalized, expansions };
|
||||
}
|
||||
|
||||
/** The query as SearchCursor compares it, which it normalizes whole rather than by character */
|
||||
export function normalizeSearch(search: string, caseSensitive: boolean): string {
|
||||
const normalized = search.normalize("NFKD");
|
||||
return caseSensitive ? normalized : normalized.toLowerCase();
|
||||
}
|
||||
|
||||
/** Every occurrence of `needle`, skipping matches that overlap an earlier one */
|
||||
export function scanNormalized(doc: NormalizedDoc, needle: string): Match[] {
|
||||
const matches: Match[] = [];
|
||||
if (needle === "") return matches;
|
||||
|
||||
const { text } = doc;
|
||||
let pos = text.indexOf(needle);
|
||||
while (pos >= 0) {
|
||||
let end = pos + needle.length;
|
||||
// However the query was cut, a match ends on a whole code point, as the cursor's do
|
||||
if (isLowSurrogate(text.charCodeAt(end))) end++;
|
||||
|
||||
matches.push({ from: docStart(doc, pos), to: docEnd(doc, end) });
|
||||
if (matches.length > MAX_COUNT) break;
|
||||
|
||||
pos = text.indexOf(needle, resumeAfter(doc, end));
|
||||
}
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
/** The same through the query's own cursor, which handles regexps and whole words */
|
||||
export function scanQuery(state: EditorState, query: SearchQuery): Match[] {
|
||||
const matches: Match[] = [];
|
||||
const cursor = query.getCursor(state);
|
||||
|
||||
for (let result = cursor.next(); !result.done; result = cursor.next()) {
|
||||
matches.push({ from: result.value.from, to: result.value.to });
|
||||
if (matches.length > MAX_COUNT) break;
|
||||
}
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
|
||||
|
||||
/** The last character expansion beginning at or before `offset`, if there is one */
|
||||
function expansionAt({ expansions }: NormalizedDoc, offset: number): Expansion | null {
|
||||
let low = 0;
|
||||
let high = expansions.length - 1;
|
||||
let found: Expansion | null = null;
|
||||
|
||||
while (low <= high) {
|
||||
const mid = (low + high) >> 1;
|
||||
if (expansions[mid]!.normFrom <= offset) {
|
||||
found = expansions[mid]!;
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid - 1;
|
||||
}
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
function docStart(doc: NormalizedDoc, offset: number): number {
|
||||
const expansion = expansionAt(doc, offset);
|
||||
if (expansion == null) return offset;
|
||||
// A match starting inside a character's expansion starts at the character
|
||||
return offset < expansion.normTo
|
||||
? expansion.docFrom
|
||||
: offset - (expansion.normTo - expansion.docTo);
|
||||
}
|
||||
|
||||
/**
|
||||
* Where scanning picks up after a match ending at `offset`.
|
||||
*
|
||||
* The cursor moves through the document a character at a time, so once a match ends inside a
|
||||
* character's expansion the rest of that expansion is behind it — "…" holds three dots but only
|
||||
* ever counts as one match of ".".
|
||||
*/
|
||||
function resumeAfter(doc: NormalizedDoc, offset: number): number {
|
||||
const expansion = expansionAt(doc, offset);
|
||||
return expansion != null && offset > expansion.normFrom && offset < expansion.normTo
|
||||
? expansion.normTo
|
||||
: offset;
|
||||
}
|
||||
|
||||
function docEnd(doc: NormalizedDoc, offset: number): number {
|
||||
const expansion = expansionAt(doc, offset);
|
||||
if (expansion == null) return offset;
|
||||
if (offset <= expansion.normFrom) return expansion.docFrom;
|
||||
// A match ending inside a character's expansion covers the whole character
|
||||
return offset < expansion.normTo
|
||||
? expansion.docTo
|
||||
: offset - (expansion.normTo - expansion.docTo);
|
||||
}
|
||||
|
||||
/** Position of the match holding the selection, counting from one, or 0 when it isn't on one */
|
||||
export function currentMatch(matches: Match[], selection: { from: number; to: number }): number {
|
||||
let index = 0;
|
||||
for (const match of matches) {
|
||||
index++;
|
||||
if (match.from <= selection.from && match.to >= selection.to) return index;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** The text a plain query looks for, or null when only the cursor can answer it */
|
||||
export function literalSearch(query: SearchQuery): string | null {
|
||||
if (query.regexp || query.wholeWord || query.test != null) return null;
|
||||
// Mirrors SearchQuery's own unquoting, which the published type doesn't expose
|
||||
return query.literal
|
||||
? query.search
|
||||
: query.search.replace(/\\([nrt\\])/g, (_, ch) =>
|
||||
ch === "n" ? "\n" : ch === "r" ? "\r" : ch === "t" ? "\t" : "\\",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the matches for the search panel, keeping the normalized document and the matches it
|
||||
* last found, so neither moving the selection nor typing another character starts over.
|
||||
*/
|
||||
export class MatchCounter {
|
||||
private doc: { doc: Text; caseSensitive: boolean; normalized: NormalizedDoc } | null = null;
|
||||
private last: { doc: Text; query: SearchQuery; matches: Match[] } | null = null;
|
||||
|
||||
matches(state: EditorState, query: SearchQuery): Match[] {
|
||||
const last = this.last;
|
||||
if (last != null && last.doc === state.doc && last.query.eq(query)) {
|
||||
return last.matches;
|
||||
}
|
||||
|
||||
const matches = this.scan(state, query);
|
||||
this.last = { doc: state.doc, query, matches };
|
||||
return matches;
|
||||
}
|
||||
|
||||
private scan(state: EditorState, query: SearchQuery): Match[] {
|
||||
const search = literalSearch(query);
|
||||
if (search == null) return scanQuery(state, query);
|
||||
|
||||
const doc = this.normalizedDoc(state.doc, query.caseSensitive);
|
||||
return scanNormalized(doc, normalizeSearch(search, query.caseSensitive));
|
||||
}
|
||||
|
||||
private normalizedDoc(doc: Text, caseSensitive: boolean): NormalizedDoc {
|
||||
const cached = this.doc;
|
||||
if (cached != null && cached.doc === doc && cached.caseSensitive === caseSensitive) {
|
||||
return cached.normalized;
|
||||
}
|
||||
|
||||
const normalized = normalizeDoc(doc.toString(), caseSensitive);
|
||||
this.doc = { doc, caseSensitive, normalized };
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A CodeMirror extension that displays the total number of search matches
|
||||
* inside the built-in search panel.
|
||||
*/
|
||||
export function searchMatchCount(): Extension {
|
||||
return ViewPlugin.fromClass(
|
||||
class {
|
||||
private countEl: HTMLElement | null = null;
|
||||
private counter = new MatchCounter();
|
||||
|
||||
constructor(private view: EditorView) {
|
||||
this.updateCount();
|
||||
}
|
||||
|
||||
update(update: ViewUpdate) {
|
||||
// Recompute when doc changes, search state changes, or selection moves
|
||||
const query = getSearchQuery(update.state);
|
||||
const prevQuery = getSearchQuery(update.startState);
|
||||
const open = searchPanelOpen(update.state);
|
||||
const prevOpen = searchPanelOpen(update.startState);
|
||||
|
||||
if (update.docChanged || update.selectionSet || !query.eq(prevQuery) || open !== prevOpen) {
|
||||
this.updateCount();
|
||||
}
|
||||
}
|
||||
|
||||
private updateCount() {
|
||||
const state = this.view.state;
|
||||
const open = searchPanelOpen(state);
|
||||
const query = getSearchQuery(state);
|
||||
|
||||
if (!open) {
|
||||
this.removeCountEl();
|
||||
return;
|
||||
}
|
||||
|
||||
this.ensureCountEl();
|
||||
if (this.countEl == null) return;
|
||||
|
||||
if (!query.search) {
|
||||
this.countEl.textContent = "0/0";
|
||||
return;
|
||||
}
|
||||
|
||||
const matches = this.counter.matches(state, query);
|
||||
if (matches.length > MAX_COUNT) {
|
||||
this.countEl.textContent = `${MAX_COUNT}+`;
|
||||
} else if (matches.length === 0) {
|
||||
this.countEl.textContent = "0/0";
|
||||
} else {
|
||||
const current = currentMatch(matches, state.selection.main);
|
||||
this.countEl.textContent = `${current}/${matches.length}`;
|
||||
}
|
||||
}
|
||||
|
||||
private ensureCountEl() {
|
||||
// Find the search panel in the editor DOM
|
||||
const panel = this.view.dom.querySelector(".cm-search");
|
||||
if (!panel) {
|
||||
this.countEl = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.countEl && this.countEl.parentElement === panel) {
|
||||
return; // Already attached
|
||||
}
|
||||
|
||||
this.countEl = document.createElement("span");
|
||||
this.countEl.className = "cm-search-match-count";
|
||||
|
||||
// Reorder: insert prev button, then next button, then count after the search input
|
||||
const searchInput = panel.querySelector("input");
|
||||
const prevBtn = panel.querySelector('button[name="prev"]');
|
||||
const nextBtn = panel.querySelector('button[name="next"]');
|
||||
if (searchInput && searchInput.parentElement === panel) {
|
||||
searchInput.after(this.countEl);
|
||||
if (prevBtn) this.countEl.after(prevBtn);
|
||||
if (nextBtn && prevBtn) prevBtn.after(nextBtn);
|
||||
} else {
|
||||
panel.prepend(this.countEl);
|
||||
}
|
||||
}
|
||||
|
||||
private removeCountEl() {
|
||||
if (this.countEl) {
|
||||
this.countEl.remove();
|
||||
this.countEl = null;
|
||||
}
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.removeCountEl();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { Extension, TransactionSpec } from "@codemirror/state";
|
||||
import { EditorSelection, EditorState, Transaction } from "@codemirror/state";
|
||||
|
||||
/**
|
||||
* A CodeMirror extension that forces single-line input by stripping
|
||||
* all newline characters from user input, including pasted content.
|
||||
*
|
||||
* This extension uses a transaction filter to intercept user input,
|
||||
* removes any newline characters, and adjusts the selection to the end
|
||||
* of the inserted text.
|
||||
*
|
||||
* IME composition events are ignored to preserve proper input behavior
|
||||
* for non-Latin languages.
|
||||
*
|
||||
* @returns A CodeMirror extension that enforces single-line editing.
|
||||
*/
|
||||
export function singleLineExtensions(): Extension {
|
||||
return EditorState.transactionFilter.of(
|
||||
(tr: Transaction): TransactionSpec | readonly TransactionSpec[] => {
|
||||
if (!tr.isUserEvent("input") || tr.isUserEvent("input.type.compose")) return tr;
|
||||
|
||||
const changes: { from: number; to: number; insert: string }[] = [];
|
||||
|
||||
tr.changes.iterChanges((_fromA, toA, fromB, _toB, inserted) => {
|
||||
let insert = "";
|
||||
for (const line of inserted.iterLines()) {
|
||||
insert += line.replace(/\n/g, "");
|
||||
}
|
||||
|
||||
if (insert !== inserted.toString()) {
|
||||
changes.push({ from: fromB, to: toA, insert });
|
||||
}
|
||||
});
|
||||
|
||||
const lastChange = changes[changes.length - 1];
|
||||
if (lastChange == null) return tr;
|
||||
|
||||
const selection = EditorSelection.cursor(lastChange.from + lastChange.insert.length);
|
||||
|
||||
return {
|
||||
changes,
|
||||
selection,
|
||||
userEvent: tr.annotation(Transaction.userEvent) ?? undefined,
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { LanguageSupport, LRLanguage } from "@codemirror/language";
|
||||
import { parser } from "./text";
|
||||
|
||||
export const textLanguage = LRLanguage.define({
|
||||
name: "text",
|
||||
parser,
|
||||
languageData: {},
|
||||
});
|
||||
|
||||
export function text() {
|
||||
return new LanguageSupport(textLanguage);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
@top Template { Text }
|
||||
|
||||
@tokens {
|
||||
Text { ![]+ }
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
// This file was generated by lezer-generator. You probably shouldn't edit it.
|
||||
export const Template = 1,
|
||||
Text = 2;
|
||||
@@ -0,0 +1,16 @@
|
||||
// This file was generated by lezer-generator. You probably shouldn't edit it.
|
||||
import { LRParser } from "@lezer/lr";
|
||||
export const parser = LRParser.deserialize({
|
||||
version: 14,
|
||||
states: "[OQOPOOQOOOOO",
|
||||
stateData: "V~OQPO~O",
|
||||
goto: "QPP",
|
||||
nodeNames: "⚠ Template Text",
|
||||
maxTerm: 3,
|
||||
skippedNodes: [0],
|
||||
repeatNodeCount: 0,
|
||||
tokenData: "p~RRO;'S[;'S;=`j<%lO[~aRQ~O;'S[;'S;=`j<%lO[~mP;=`<%l[",
|
||||
tokenizers: [0],
|
||||
topRules: { Template: [0, 1] },
|
||||
tokenPrec: 0,
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { type ReactNode, useMemo } from "react";
|
||||
import { useToggle } from "../../hooks/useToggle";
|
||||
import { isProbablyTextContentType } from "../../lib/mimeType";
|
||||
import { Banner } from "../Banner";
|
||||
import { Button } from "../Button";
|
||||
import { InlineCode } from "../InlineCode";
|
||||
import { HStack } from "../Stacks";
|
||||
import { SizeTag } from "../tags/SizeTag";
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
/** Bytes of the body being guarded */
|
||||
contentLength: number | null;
|
||||
contentType: string | null;
|
||||
/** What's being shown, in the notice: "responses" or "content" */
|
||||
noun?: string;
|
||||
/** The reveal button's label */
|
||||
revealLabel?: string;
|
||||
/** Save the body to a file, when the app can */
|
||||
onSave?: () => void;
|
||||
/** Read the body as text for copying, when the app can */
|
||||
getText?: () => Promise<string | null>;
|
||||
/** The copy button, rendered by the app so it reports the copy its own way */
|
||||
renderCopyButton?: (getText: () => Promise<string | null>) => ReactNode;
|
||||
}
|
||||
|
||||
const LARGE_BYTES = 2 * 1000 * 1000;
|
||||
|
||||
/** Holds back a body big enough to slow the window down, until asked to show it */
|
||||
export function ConfirmLargeResponse({
|
||||
children,
|
||||
contentLength,
|
||||
contentType,
|
||||
noun = "responses",
|
||||
revealLabel = "Reveal Response",
|
||||
onSave,
|
||||
getText,
|
||||
renderCopyButton,
|
||||
}: Props) {
|
||||
const [showLargeResponse, toggleShowLargeResponse] = useToggle();
|
||||
const isProbablyText = useMemo(() => isProbablyTextContentType(contentType), [contentType]);
|
||||
|
||||
const isLarge = (contentLength ?? 0) > LARGE_BYTES;
|
||||
if (!showLargeResponse && isLarge) {
|
||||
return (
|
||||
<Banner color="primary" className="flex flex-col gap-3">
|
||||
<p>
|
||||
Showing {noun} over{" "}
|
||||
<InlineCode>
|
||||
<SizeTag contentLength={LARGE_BYTES} />
|
||||
</InlineCode>{" "}
|
||||
may impact performance
|
||||
</p>
|
||||
<HStack wrap space={2}>
|
||||
<Button color="primary" size="xs" onClick={toggleShowLargeResponse}>
|
||||
{revealLabel}
|
||||
</Button>
|
||||
{onSave != null && (
|
||||
<Button color="secondary" variant="border" size="xs" onClick={onSave}>
|
||||
Save to File
|
||||
</Button>
|
||||
)}
|
||||
{isProbablyText && getText != null && renderCopyButton?.(getText)}
|
||||
</HStack>
|
||||
</Banner>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import type { Pair, PairEditorProps } from "../pairs/PairEditor";
|
||||
import { PairEditor } from "../pairs/PairEditor";
|
||||
import type { HttpFormFieldView, HttpRequestBodyView } from "./types";
|
||||
|
||||
type Props = {
|
||||
forceUpdateKey: string;
|
||||
/** The request's id, keeping each request's editor state apart */
|
||||
requestId: string;
|
||||
form: HttpFormFieldView[] | undefined;
|
||||
onChange?: (body: HttpRequestBodyView) => void;
|
||||
/** Show the fields without a way to change them */
|
||||
readOnly?: boolean;
|
||||
};
|
||||
|
||||
export function FormMultipartEditor({
|
||||
requestId,
|
||||
form,
|
||||
forceUpdateKey,
|
||||
onChange,
|
||||
readOnly,
|
||||
}: Props) {
|
||||
const pairs = useMemo<Pair[]>(
|
||||
() =>
|
||||
(Array.isArray(form) ? form : []).map((p) => ({
|
||||
enabled: p.enabled,
|
||||
name: p.name,
|
||||
value: (p.file ?? p.value) as string,
|
||||
contentType: p.contentType,
|
||||
filename: p.filename,
|
||||
isFile: !!p.file,
|
||||
id: p.id,
|
||||
})),
|
||||
[form],
|
||||
);
|
||||
|
||||
const handleChange = useCallback<PairEditorProps["onChange"]>(
|
||||
(pairs) =>
|
||||
onChange?.({
|
||||
form: pairs.map((p) => ({
|
||||
enabled: p.enabled,
|
||||
name: p.name,
|
||||
contentType: p.contentType,
|
||||
filename: p.filename,
|
||||
file: p.isFile ? p.value : undefined,
|
||||
value: p.isFile ? undefined : p.value,
|
||||
id: p.id,
|
||||
})),
|
||||
}),
|
||||
[onChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<PairEditor
|
||||
valueAutocompleteFunctions
|
||||
valueAutocompleteVariables
|
||||
nameAutocompleteVariables
|
||||
nameAutocompleteFunctions
|
||||
allowFileValues
|
||||
allowMultilineValues
|
||||
pairs={pairs}
|
||||
onChange={handleChange}
|
||||
readOnly={readOnly}
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
stateKey={`multipart.${requestId}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import type { Pair, PairEditorProps } from "../pairs/PairEditor";
|
||||
import { PairOrBulkEditor } from "../pairs/PairOrBulkEditor";
|
||||
import type { HttpFormFieldView, HttpRequestBodyView } from "./types";
|
||||
|
||||
type Props = {
|
||||
forceUpdateKey: string;
|
||||
/** The request's id, keeping each request's editor state apart */
|
||||
requestId: string;
|
||||
form: HttpFormFieldView[] | undefined;
|
||||
onChange?: (body: HttpRequestBodyView) => void;
|
||||
/** Show the fields without a way to change them */
|
||||
readOnly?: boolean;
|
||||
};
|
||||
|
||||
export function FormUrlencodedEditor({
|
||||
requestId,
|
||||
form,
|
||||
forceUpdateKey,
|
||||
onChange,
|
||||
readOnly,
|
||||
}: Props) {
|
||||
const pairs = useMemo<Pair[]>(
|
||||
() =>
|
||||
(Array.isArray(form) ? form : []).map((p) => ({
|
||||
enabled: !!p.enabled,
|
||||
name: p.name || "",
|
||||
value: p.value || "",
|
||||
id: p.id,
|
||||
})),
|
||||
[form],
|
||||
);
|
||||
|
||||
const handleChange = useCallback<PairEditorProps["onChange"]>(
|
||||
(pairs) =>
|
||||
onChange?.({
|
||||
form: pairs.map((p) => ({ enabled: p.enabled, name: p.name, value: p.value })),
|
||||
}),
|
||||
[onChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<PairOrBulkEditor
|
||||
allowMultilineValues
|
||||
preferenceName="form_urlencoded"
|
||||
valueAutocompleteFunctions
|
||||
valueAutocompleteVariables
|
||||
nameAutocompleteFunctions
|
||||
nameAutocompleteVariables
|
||||
namePlaceholder="entry_name"
|
||||
valuePlaceholder="Value"
|
||||
pairs={pairs}
|
||||
onChange={handleChange}
|
||||
readOnly={readOnly}
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
stateKey={`urlencoded.${requestId}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import { acceptLanguages } from "../../lib/data/acceptLanguages";
|
||||
import { cacheControlDirectives } from "../../lib/data/cacheControl";
|
||||
import { charsets } from "../../lib/data/charsets";
|
||||
import { connections } from "../../lib/data/connections";
|
||||
import { encodings } from "../../lib/data/encodings";
|
||||
import type { HeaderValuePreset } from "../../lib/data/headerValuePresets";
|
||||
import { headerNames } from "../../lib/data/headerNames";
|
||||
import { mimeTypes } from "../../lib/data/mimetypes";
|
||||
import { userAgents } from "../../lib/data/userAgents";
|
||||
import { validateHttpHeader } from "../../lib/validateHttpHeader";
|
||||
import { CountBadge } from "../CountBadge";
|
||||
import { DetailsBanner } from "../DetailsBanner";
|
||||
import type { GenericCompletion, GenericCompletionConfig, HostInputProps } from "../EditorHost";
|
||||
import { useEditorHost } from "../EditorHost";
|
||||
import type { Pair, PairEditorProps } from "../pairs/PairEditor";
|
||||
import { PairEditorRow } from "../pairs/PairEditor";
|
||||
import { ensurePairId } from "../pairs/PairEditor.util";
|
||||
import { PairOrBulkEditor } from "../pairs/PairOrBulkEditor";
|
||||
import { HStack } from "../Stacks";
|
||||
import type { HttpPairView } from "./types";
|
||||
|
||||
type Props = {
|
||||
forceUpdateKey: string;
|
||||
headers: HttpPairView[];
|
||||
inheritedHeaders?: HttpPairView[];
|
||||
inheritedHeadersLabel?: string;
|
||||
stateKey: string;
|
||||
onChange?: PairEditorProps["onChange"];
|
||||
/** Show the headers without a way to change them */
|
||||
readOnly?: boolean;
|
||||
label?: string;
|
||||
};
|
||||
|
||||
export function HeadersEditor({
|
||||
stateKey,
|
||||
headers,
|
||||
inheritedHeaders,
|
||||
inheritedHeadersLabel = "Inherited",
|
||||
onChange = ignoreChange,
|
||||
readOnly,
|
||||
forceUpdateKey,
|
||||
}: Props) {
|
||||
const { useDetailsBannerStoredValue } = useEditorHost();
|
||||
// Get header names defined at current level (case-insensitive)
|
||||
const currentHeaderNames = new Set(
|
||||
headers.filter((h) => h.name).map((h) => h.name.toLowerCase()),
|
||||
);
|
||||
// Filter inherited headers: must be enabled, have content, and not be overridden by current level
|
||||
const validInheritedHeaders =
|
||||
inheritedHeaders?.filter(
|
||||
(pair) =>
|
||||
pair.enabled &&
|
||||
(pair.name || pair.value) &&
|
||||
!currentHeaderNames.has(pair.name.toLowerCase()),
|
||||
) ?? [];
|
||||
const hasInheritedHeaders = validInheritedHeaders.length > 0;
|
||||
return (
|
||||
<div
|
||||
className={
|
||||
hasInheritedHeaders
|
||||
? "@container w-full h-full grid grid-rows-[auto_minmax(0,1fr)] gap-y-1.5"
|
||||
: "@container w-full h-full"
|
||||
}
|
||||
>
|
||||
{hasInheritedHeaders && (
|
||||
<DetailsBanner
|
||||
useStoredValue={useDetailsBannerStoredValue}
|
||||
color="secondary"
|
||||
className="text-sm"
|
||||
summary={
|
||||
<HStack>
|
||||
{inheritedHeadersLabel} <CountBadge count={validInheritedHeaders.length} />
|
||||
</HStack>
|
||||
}
|
||||
>
|
||||
<div className="pb-2">
|
||||
{validInheritedHeaders?.map((pair, i) => (
|
||||
<PairEditorRow
|
||||
key={`${pair.id}.${i}`}
|
||||
index={i}
|
||||
disabled
|
||||
disableDrag
|
||||
className="py-1"
|
||||
pair={ensurePairId(pair)}
|
||||
stateKey={null}
|
||||
nameAutocompleteFunctions
|
||||
nameAutocompleteVariables
|
||||
valueAutocompleteFunctions
|
||||
valueAutocompleteVariables
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</DetailsBanner>
|
||||
)}
|
||||
<PairOrBulkEditor
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
nameAutocomplete={nameAutocomplete}
|
||||
nameAutocompleteFunctions
|
||||
nameAutocompleteVariables
|
||||
namePlaceholder="Header-Name"
|
||||
nameValidate={validateHttpHeader}
|
||||
onChange={onChange}
|
||||
pairs={headers}
|
||||
readOnly={readOnly}
|
||||
preferenceName="headers"
|
||||
stateKey={stateKey}
|
||||
valueType={valueType}
|
||||
valueAutocomplete={valueAutocomplete}
|
||||
valueAutocompleteFunctions
|
||||
valueAutocompleteVariables
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const MIN_MATCH = 3;
|
||||
|
||||
const headerOptionsMap: Record<string, HeaderValuePreset[]> = {
|
||||
"content-type": mimeTypes,
|
||||
accept: ["*/*", ...mimeTypes],
|
||||
"accept-encoding": encodings,
|
||||
"content-encoding": encodings,
|
||||
connection: connections,
|
||||
"accept-charset": charsets,
|
||||
"accept-language": acceptLanguages,
|
||||
"cache-control": cacheControlDirectives,
|
||||
"user-agent": userAgents,
|
||||
pragma: ["no-cache"],
|
||||
te: ["trailers", "compress", "deflate", "gzip"],
|
||||
dnt: ["1", "0"],
|
||||
"upgrade-insecure-requests": ["1"],
|
||||
"x-requested-with": ["XMLHttpRequest"],
|
||||
};
|
||||
|
||||
function ignoreChange() {}
|
||||
|
||||
const valueType = (pair: Pair): HostInputProps["type"] => {
|
||||
const name = pair.name.toLowerCase().trim();
|
||||
if (
|
||||
name.includes("authorization") ||
|
||||
name.includes("api-key") ||
|
||||
name.includes("access-token") ||
|
||||
name.includes("auth") ||
|
||||
name.includes("secret") ||
|
||||
name.includes("token") ||
|
||||
name === "cookie" ||
|
||||
name === "set-cookie"
|
||||
) {
|
||||
return "password";
|
||||
}
|
||||
return "text";
|
||||
};
|
||||
|
||||
const valueAutocomplete = (headerName: string): GenericCompletionConfig | undefined => {
|
||||
const name = headerName.toLowerCase().trim();
|
||||
const options: GenericCompletion[] =
|
||||
headerOptionsMap[name]?.map((o) =>
|
||||
typeof o === "string"
|
||||
? {
|
||||
label: o,
|
||||
type: "constant",
|
||||
boost: 1, // Put above other completions
|
||||
}
|
||||
: {
|
||||
// Show the short label but insert the full value (e.g. User-Agent)
|
||||
label: o.label,
|
||||
apply: o.value,
|
||||
type: "constant",
|
||||
boost: 1,
|
||||
},
|
||||
) ?? [];
|
||||
return { minMatch: MIN_MATCH, options };
|
||||
};
|
||||
|
||||
const nameAutocomplete: PairEditorProps["nameAutocomplete"] = {
|
||||
minMatch: MIN_MATCH,
|
||||
options: headerNames.map((t) =>
|
||||
typeof t === "string"
|
||||
? {
|
||||
label: t,
|
||||
type: "constant",
|
||||
boost: 1, // Put above other completions
|
||||
}
|
||||
: {
|
||||
...t,
|
||||
boost: 1, // Put above other completions
|
||||
},
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,458 @@
|
||||
import classNames from "classnames";
|
||||
import type { CSSProperties, ReactNode, Ref } from "react";
|
||||
import { useMemo } from "react";
|
||||
import { languageFromContentType } from "../../lib/contentType";
|
||||
import { CountBadge } from "../CountBadge";
|
||||
import { EmptyStateText } from "../EmptyStateText";
|
||||
import type { HostInputProps } from "../EditorHost";
|
||||
import { useEditorHost } from "../EditorHost";
|
||||
import { KeyValueRows } from "../KeyValueRow";
|
||||
import type { HotkeyAction } from "../../hooks/useHotKey";
|
||||
import type { EditablePair, PairEditorHandle, PairEditorProps } from "../pairs/PairEditor";
|
||||
import type { TabItem, TabsRef } from "../tabs/Tabs";
|
||||
import { TabContent, Tabs } from "../tabs/Tabs";
|
||||
import { FormMultipartEditor } from "./FormMultipartEditor";
|
||||
import { FormUrlencodedEditor } from "./FormUrlencodedEditor";
|
||||
import { HeadersEditor } from "./HeadersEditor";
|
||||
import type { ExtraPaneTab } from "./HttpResponsePaneView";
|
||||
import { JsonBodyEditor } from "./JsonBodyEditor";
|
||||
import { RequestBodyViewer } from "./RequestBodyViewer";
|
||||
import { RequestMethodDropdown } from "./RequestMethodDropdown";
|
||||
import { KeyValueRow } from "./ResponseHeaders";
|
||||
import {
|
||||
BODY_TYPE_BINARY,
|
||||
BODY_TYPE_FORM_MULTIPART,
|
||||
BODY_TYPE_FORM_URLENCODED,
|
||||
BODY_TYPE_GRAPHQL,
|
||||
BODY_TYPE_JSON,
|
||||
BODY_TYPE_OTHER,
|
||||
BODY_TYPE_XML,
|
||||
type HttpBodyLoader,
|
||||
type HttpRequestBodyView,
|
||||
type HttpRequestView,
|
||||
} from "./types";
|
||||
import { UrlBar } from "./UrlBar";
|
||||
import { UrlParametersEditor } from "./UrlParametersEditor";
|
||||
|
||||
export const REQUEST_TAB_BODY = "body";
|
||||
export const REQUEST_TAB_PARAMS = "params";
|
||||
export const REQUEST_TAB_HEADERS = "headers";
|
||||
export const REQUEST_TAB_AUTH = "auth";
|
||||
|
||||
export interface HttpRequestPaneViewProps {
|
||||
request: HttpRequestView;
|
||||
/** Lets the request be changed and sent; without it the pane only shows it */
|
||||
editable?: boolean;
|
||||
style?: CSSProperties;
|
||||
className?: string;
|
||||
fullHeight: boolean;
|
||||
/** Where the tab order and the active tab are remembered */
|
||||
tabsStorageKey?: string;
|
||||
tabsRef?: Ref<TabsRef>;
|
||||
/** Re-seeds the editors when the request changes from elsewhere */
|
||||
forceUpdateKey: string;
|
||||
|
||||
/** The URL bar's own reset key, when the app resets it apart from the rest */
|
||||
urlBarKey?: string;
|
||||
/** Re-seeds the URL bar's text without remounting it */
|
||||
urlForceUpdateKey?: string;
|
||||
urlAutocomplete?: HostInputProps["autocomplete"];
|
||||
urlPlaceholder?: string;
|
||||
onUrlChange?: (url: string) => void;
|
||||
onUrlPasteOverwrite?: HostInputProps["onPasteOverwrite"];
|
||||
onSend?: () => void;
|
||||
onCancel?: () => void;
|
||||
isSending?: boolean;
|
||||
/** The action whose keys send the request */
|
||||
sendHotkeyAction?: HotkeyAction;
|
||||
/** The action whose keys select the URL */
|
||||
focusHotkeyAction?: HotkeyAction;
|
||||
/** Colour the method by what it does */
|
||||
methodColored?: boolean;
|
||||
onMethodChange?: (method: string) => void | Promise<void>;
|
||||
/** Replaces the method shown at the start of the URL bar */
|
||||
methodSlot?: ReactNode;
|
||||
|
||||
/** The body tab, when the app offers a menu of body types; otherwise a label names it */
|
||||
bodyTab?: TabItem;
|
||||
/** Renders the body tab's content, given the shared editor for the body type */
|
||||
renderBody?: (sharedEditor: ReactNode) => ReactNode;
|
||||
/** Reads a body that isn't text, like a captured binary or multipart one */
|
||||
bodyLoader?: HttpBodyLoader;
|
||||
onBodyChange?: (body: HttpRequestBodyView) => void;
|
||||
/** A text body changed; JSON writes at once, the rest may debounce */
|
||||
onBodyTextChange?: (text: string, bodyType: string | null) => void;
|
||||
onSendJsonCommentsChange?: (sendJsonComments: boolean) => void;
|
||||
/** Where dismissing the JSON comments notice is remembered */
|
||||
jsonNoticeStorageKey?: string;
|
||||
|
||||
/** Parameters to edit, when the app derives more than the request's own (path placeholders) */
|
||||
urlParameterPairs?: EditablePair[];
|
||||
urlParametersForceUpdateKey?: string;
|
||||
onUrlParametersChange?: PairEditorProps["onChange"];
|
||||
onUrlParametersRef?: (handle: PairEditorHandle) => void;
|
||||
/** Overrides the parameters editor, like the client's one wired to its focus events */
|
||||
renderUrlParameters?: (pairs: EditablePair[]) => ReactNode;
|
||||
|
||||
/** The headers tab, when the app counts inherited headers into it */
|
||||
headersTabs?: TabItem[];
|
||||
inheritedHeaders?: HeadersEditorInherited;
|
||||
headersForceUpdateKey?: string;
|
||||
onHeadersChange?: PairEditorProps["onChange"];
|
||||
|
||||
/** The auth tab and what it shows, when the app edits authentication itself */
|
||||
authTabs?: TabItem[];
|
||||
authContent?: ReactNode;
|
||||
|
||||
/** Tabs only the app has, after the shared ones */
|
||||
extraTabs?: ExtraPaneTab[];
|
||||
}
|
||||
|
||||
type HeadersEditorInherited = { name: string; value: string; enabled?: boolean; id?: string }[];
|
||||
|
||||
/** Yaak's request pane: the URL bar over Body, Params, Headers and Auth tabs */
|
||||
export function HttpRequestPaneView({
|
||||
request,
|
||||
editable = false,
|
||||
style,
|
||||
className,
|
||||
fullHeight,
|
||||
tabsStorageKey = "http_request_tabs",
|
||||
tabsRef,
|
||||
forceUpdateKey,
|
||||
urlBarKey,
|
||||
urlForceUpdateKey,
|
||||
urlAutocomplete,
|
||||
urlPlaceholder = "https://example.com",
|
||||
onUrlChange,
|
||||
onUrlPasteOverwrite,
|
||||
onSend,
|
||||
onCancel,
|
||||
isSending,
|
||||
sendHotkeyAction,
|
||||
focusHotkeyAction,
|
||||
methodColored,
|
||||
onMethodChange,
|
||||
methodSlot,
|
||||
bodyTab,
|
||||
renderBody,
|
||||
bodyLoader,
|
||||
onBodyChange,
|
||||
onBodyTextChange,
|
||||
onSendJsonCommentsChange,
|
||||
jsonNoticeStorageKey,
|
||||
urlParameterPairs,
|
||||
urlParametersForceUpdateKey,
|
||||
onUrlParametersChange,
|
||||
onUrlParametersRef,
|
||||
renderUrlParameters,
|
||||
headersTabs,
|
||||
inheritedHeaders,
|
||||
headersForceUpdateKey,
|
||||
onHeadersChange,
|
||||
authTabs,
|
||||
authContent,
|
||||
extraTabs,
|
||||
}: HttpRequestPaneViewProps) {
|
||||
const { ErrorBoundary } = useEditorHost();
|
||||
const readOnly = !editable;
|
||||
const paramPairs = urlParameterPairs ?? request.urlParameters;
|
||||
|
||||
let numParams = 0;
|
||||
if (
|
||||
request.bodyType === BODY_TYPE_FORM_URLENCODED ||
|
||||
request.bodyType === BODY_TYPE_FORM_MULTIPART
|
||||
) {
|
||||
numParams = Array.isArray(request.body?.form)
|
||||
? request.body.form.filter((p) => p.name).length
|
||||
: 0;
|
||||
}
|
||||
|
||||
const tabs = useMemo<TabItem[]>(
|
||||
() => [
|
||||
bodyTab ?? {
|
||||
value: REQUEST_TAB_BODY,
|
||||
label: bodyTypeLabel(request.bodyType, request.contentType),
|
||||
rightSlot: numParams > 0 ? <CountBadge count={numParams} /> : null,
|
||||
},
|
||||
{
|
||||
value: REQUEST_TAB_PARAMS,
|
||||
rightSlot: <CountBadge count={paramPairs.length} />,
|
||||
label: "Params",
|
||||
},
|
||||
...(headersTabs ?? [
|
||||
{
|
||||
value: REQUEST_TAB_HEADERS,
|
||||
label: "Headers",
|
||||
rightSlot: (
|
||||
<CountBadge
|
||||
count={request.headers.filter((h) => h.name && h.enabled !== false).length}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]),
|
||||
...(authTabs ??
|
||||
(request.auth == null
|
||||
? []
|
||||
: [
|
||||
{
|
||||
value: REQUEST_TAB_AUTH,
|
||||
label: request.auth.label,
|
||||
},
|
||||
])),
|
||||
...(extraTabs?.map((t) => t.tab) ?? []),
|
||||
],
|
||||
[
|
||||
authTabs,
|
||||
bodyTab,
|
||||
extraTabs,
|
||||
headersTabs,
|
||||
numParams,
|
||||
paramPairs.length,
|
||||
request.auth,
|
||||
request.bodyType,
|
||||
request.contentType,
|
||||
request.headers,
|
||||
],
|
||||
);
|
||||
|
||||
const sharedBody = (
|
||||
<RequestBodyEditor
|
||||
request={request}
|
||||
readOnly={readOnly}
|
||||
fullHeight={fullHeight}
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
bodyLoader={bodyLoader}
|
||||
onBodyChange={onBodyChange}
|
||||
onBodyTextChange={onBodyTextChange}
|
||||
onSendJsonCommentsChange={onSendJsonCommentsChange}
|
||||
jsonNoticeStorageKey={jsonNoticeStorageKey ?? request.id}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
style={style}
|
||||
className={classNames(className, "h-full grid grid-rows-[auto_minmax(0,1fr)] grid-cols-1")}
|
||||
>
|
||||
<UrlBar
|
||||
stateKey={`url.${request.id}`}
|
||||
key={urlBarKey}
|
||||
url={request.url}
|
||||
placeholder={urlPlaceholder}
|
||||
onPasteOverwrite={onUrlPasteOverwrite}
|
||||
autocomplete={urlAutocomplete}
|
||||
onSend={onSend}
|
||||
onCancel={onCancel}
|
||||
onUrlChange={onUrlChange}
|
||||
readOnly={readOnly}
|
||||
sendHotkeyAction={readOnly ? undefined : sendHotkeyAction}
|
||||
focusHotkeyAction={readOnly ? undefined : focusHotkeyAction}
|
||||
leftSlot={
|
||||
<div className="py-0.5">
|
||||
{methodSlot ?? (
|
||||
<RequestMethodDropdown
|
||||
method={request.method}
|
||||
colored={methodColored}
|
||||
onChange={onMethodChange}
|
||||
readOnly={readOnly}
|
||||
className="ml-0.5 h-full!"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
forceUpdateKey={urlForceUpdateKey ?? forceUpdateKey}
|
||||
isLoading={isSending}
|
||||
/>
|
||||
<Tabs
|
||||
ref={tabsRef}
|
||||
label="Request"
|
||||
tabs={tabs}
|
||||
tabListClassName="mt-1 -mb-1.5"
|
||||
storageKey={tabsStorageKey}
|
||||
activeTabKey={request.id}
|
||||
>
|
||||
<TabContent value={REQUEST_TAB_AUTH} ErrorBoundary={ErrorBoundary}>
|
||||
{authContent ?? (request.auth != null && <AuthDisplay auth={request.auth} />)}
|
||||
</TabContent>
|
||||
<TabContent value={REQUEST_TAB_HEADERS} ErrorBoundary={ErrorBoundary}>
|
||||
<HeadersEditor
|
||||
inheritedHeaders={inheritedHeaders}
|
||||
forceUpdateKey={headersForceUpdateKey ?? forceUpdateKey}
|
||||
headers={request.headers}
|
||||
stateKey={`headers.${request.id}`}
|
||||
onChange={onHeadersChange}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
</TabContent>
|
||||
<TabContent value={REQUEST_TAB_PARAMS} ErrorBoundary={ErrorBoundary}>
|
||||
{renderUrlParameters?.(paramPairs) ?? (
|
||||
<UrlParametersEditor
|
||||
stateKey={`params.${request.id}`}
|
||||
forceUpdateKey={urlParametersForceUpdateKey ?? forceUpdateKey}
|
||||
pairs={paramPairs}
|
||||
onChange={onUrlParametersChange}
|
||||
setRef={onUrlParametersRef}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
)}
|
||||
</TabContent>
|
||||
<TabContent value={REQUEST_TAB_BODY} ErrorBoundary={ErrorBoundary}>
|
||||
{renderBody ? renderBody(sharedBody) : sharedBody}
|
||||
</TabContent>
|
||||
{extraTabs?.map(({ tab, content }) => (
|
||||
<TabContent key={tab.value} value={tab.value} ErrorBoundary={ErrorBoundary}>
|
||||
{content}
|
||||
</TabContent>
|
||||
))}
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface RequestBodyEditorProps {
|
||||
request: HttpRequestView;
|
||||
readOnly: boolean;
|
||||
fullHeight: boolean;
|
||||
forceUpdateKey: string;
|
||||
bodyLoader?: HttpBodyLoader;
|
||||
onBodyChange?: (body: HttpRequestBodyView) => void;
|
||||
onBodyTextChange?: (text: string, bodyType: string | null) => void;
|
||||
onSendJsonCommentsChange?: (sendJsonComments: boolean) => void;
|
||||
jsonNoticeStorageKey: string;
|
||||
}
|
||||
|
||||
/** The editor for a request body's type: JSON, XML, forms, or any other text */
|
||||
export function RequestBodyEditor({
|
||||
request,
|
||||
readOnly,
|
||||
fullHeight,
|
||||
forceUpdateKey,
|
||||
bodyLoader,
|
||||
onBodyChange,
|
||||
onBodyTextChange,
|
||||
onSendJsonCommentsChange,
|
||||
jsonNoticeStorageKey,
|
||||
}: RequestBodyEditorProps) {
|
||||
const { Editor } = useEditorHost();
|
||||
const { bodyType } = request;
|
||||
const handleTextChange = (text: string) => onBodyTextChange?.(text, bodyType);
|
||||
|
||||
// A captured body that isn't text shows in the viewer for its content type
|
||||
if (
|
||||
bodyLoader != null &&
|
||||
(bodyType === BODY_TYPE_BINARY || bodyType === BODY_TYPE_FORM_MULTIPART) &&
|
||||
readOnly
|
||||
) {
|
||||
return (
|
||||
<RequestBodyViewer id={request.id} contentType={request.contentType} body={bodyLoader} />
|
||||
);
|
||||
}
|
||||
|
||||
if (bodyType === BODY_TYPE_JSON) {
|
||||
return (
|
||||
<JsonBodyEditor
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
heightMode={fullHeight ? "full" : "auto"}
|
||||
requestId={request.id}
|
||||
text={request.body?.text ?? ""}
|
||||
sendJsonComments={request.body?.sendJsonComments === true}
|
||||
onChange={handleTextChange}
|
||||
onChangeSendJsonComments={onSendJsonCommentsChange}
|
||||
noticeStorageKey={jsonNoticeStorageKey}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (bodyType === BODY_TYPE_XML) {
|
||||
return (
|
||||
<Editor
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
autocompleteFunctions
|
||||
autocompleteVariables
|
||||
placeholder="..."
|
||||
heightMode={fullHeight ? "full" : "auto"}
|
||||
defaultValue={`${request.body?.text ?? ""}`}
|
||||
language="xml"
|
||||
onChange={handleTextChange}
|
||||
readOnly={readOnly}
|
||||
stateKey={`xml.${request.id}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (bodyType === BODY_TYPE_FORM_URLENCODED) {
|
||||
return (
|
||||
<FormUrlencodedEditor
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
requestId={request.id}
|
||||
form={request.body.form}
|
||||
onChange={onBodyChange}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (bodyType === BODY_TYPE_FORM_MULTIPART) {
|
||||
return (
|
||||
<FormMultipartEditor
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
requestId={request.id}
|
||||
form={request.body.form}
|
||||
onChange={onBodyChange}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (typeof bodyType === "string" && bodyType !== BODY_TYPE_BINARY) {
|
||||
return (
|
||||
<Editor
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
autocompleteFunctions
|
||||
autocompleteVariables
|
||||
language={languageFromContentType(request.contentType)}
|
||||
placeholder="..."
|
||||
heightMode={fullHeight ? "full" : "auto"}
|
||||
defaultValue={`${request.body?.text ?? ""}`}
|
||||
onChange={handleTextChange}
|
||||
readOnly={readOnly}
|
||||
stateKey={`other.${request.id}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <EmptyStateText>No Body</EmptyStateText>;
|
||||
}
|
||||
|
||||
function AuthDisplay({ auth }: { auth: NonNullable<HttpRequestView["auth"]> }) {
|
||||
return (
|
||||
<KeyValueRows>
|
||||
{auth.values.map((v) => (
|
||||
<KeyValueRow key={v.name} labelColor="primary" label={v.name}>
|
||||
{v.value}
|
||||
</KeyValueRow>
|
||||
))}
|
||||
</KeyValueRows>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the body tab is called when there's no menu of body types to name it */
|
||||
export function bodyTypeLabel(bodyType: string | null, contentType: string | null): string {
|
||||
switch (bodyType) {
|
||||
case BODY_TYPE_JSON:
|
||||
return "JSON";
|
||||
case BODY_TYPE_XML:
|
||||
return "XML";
|
||||
case BODY_TYPE_GRAPHQL:
|
||||
return "GraphQL";
|
||||
case BODY_TYPE_FORM_URLENCODED:
|
||||
return "Url Encoded";
|
||||
case BODY_TYPE_FORM_MULTIPART:
|
||||
return "Multi-Part";
|
||||
case BODY_TYPE_BINARY:
|
||||
return "Binary";
|
||||
case BODY_TYPE_OTHER:
|
||||
return languageFromContentType(contentType) === "markdown" ? "Markdown" : "Other";
|
||||
case null:
|
||||
return "Body";
|
||||
default:
|
||||
return "Body";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
import classNames from "classnames";
|
||||
import type { CSSProperties, ReactElement, ReactNode } from "react";
|
||||
import { Suspense, useMemo } from "react";
|
||||
import { getMimeTypeFromContentType } from "../../lib/mimeType";
|
||||
import { Banner } from "../Banner";
|
||||
import { CountBadge } from "../CountBadge";
|
||||
import type { DropdownItem } from "../Dropdown";
|
||||
import { type EditorHost, useEditorHost } from "../EditorHost";
|
||||
import { Icon } from "../Icon";
|
||||
import { LoadingIcon } from "../LoadingIcon";
|
||||
import { HStack } from "../Stacks";
|
||||
import type { TabItem } from "../tabs/Tabs";
|
||||
import { TabContent, Tabs } from "../tabs/Tabs";
|
||||
import { HttpResponseDurationTagRaw } from "../tags/HttpResponseDurationTag";
|
||||
import { HttpStatusTagRaw } from "../tags/HttpStatusTag";
|
||||
import { SizeTag } from "../tags/SizeTag";
|
||||
import { ConfirmLargeResponse } from "./ConfirmLargeResponse";
|
||||
import { RequestBodyViewer } from "./RequestBodyViewer";
|
||||
import type { ResponseTextViewerExtras, ResponseViewMode } from "./ResponseBodyViewer";
|
||||
import { ResponseBodyViewer } from "./ResponseBodyViewer";
|
||||
import { parseCookieHeaders, ResponseCookies } from "./ResponseCookies";
|
||||
import { ResponseHeaders } from "./ResponseHeaders";
|
||||
import type { HttpBodyLoader, HttpResponseView } from "./types";
|
||||
|
||||
export const RESPONSE_TAB_BODY = "body";
|
||||
export const RESPONSE_TAB_REQUEST = "request";
|
||||
export const RESPONSE_TAB_HEADERS = "headers";
|
||||
export const RESPONSE_TAB_COOKIES = "cookies";
|
||||
|
||||
/** A tab only one app has, like the client's timeline, with what it shows */
|
||||
export interface ExtraPaneTab {
|
||||
tab: TabItem;
|
||||
content: ReactNode;
|
||||
}
|
||||
|
||||
export interface HttpResponsePaneViewProps {
|
||||
response: HttpResponseView | null;
|
||||
/** Reads the response body */
|
||||
body: HttpBodyLoader | null;
|
||||
/** Reads the request body the response answered */
|
||||
requestBody: HttpBodyLoader | null;
|
||||
style?: CSSProperties;
|
||||
className?: string;
|
||||
/** Shown before there's a response */
|
||||
emptyState: ReactNode;
|
||||
viewMode: ResponseViewMode;
|
||||
onViewModeChange: (viewMode: ResponseViewMode) => void;
|
||||
/** Where the tab order and the active tab are remembered */
|
||||
tabsStorageKey?: string;
|
||||
/** Remembers the active tab per request or flow */
|
||||
activeTabKey: string;
|
||||
/** Between the status and the right of the status line, like a warning */
|
||||
statusLineCenter?: ReactNode;
|
||||
/** At the right of the status line, like a menu of earlier responses */
|
||||
statusLineRight?: ReactNode;
|
||||
onSaveBody?: () => void;
|
||||
onCopyBody?: () => void;
|
||||
onCopyAsCurl?: () => void;
|
||||
/** Stop a request that's still being sent */
|
||||
onCancel?: () => void;
|
||||
/** Overrides the cookie counts the tab shows, when the app counts them its own way */
|
||||
cookieCounts?: { sent: number; received: number };
|
||||
/** Tabs only the app has, after the shared ones */
|
||||
extraTabs?: ExtraPaneTab[];
|
||||
textViewer?: ResponseTextViewerExtras;
|
||||
/** Viewers only this app has for a response body, like the client's event stream viewer */
|
||||
renderBodyViewer?: EditorHost["renderBodyViewer"];
|
||||
/** More rows for the Headers tab's Info section */
|
||||
infoRows?: ReactElement[];
|
||||
/** The copy button for a body held back for its size */
|
||||
renderCopyButton?: (getText: () => Promise<string | null>) => ReactNode;
|
||||
}
|
||||
|
||||
/** Yaak's response pane: a status line over Response, Request, Headers and Cookies tabs */
|
||||
export function HttpResponsePaneView({
|
||||
response,
|
||||
body,
|
||||
requestBody,
|
||||
style,
|
||||
className,
|
||||
emptyState,
|
||||
viewMode,
|
||||
onViewModeChange,
|
||||
tabsStorageKey = "http_response_tabs",
|
||||
activeTabKey,
|
||||
statusLineCenter,
|
||||
statusLineRight,
|
||||
onSaveBody,
|
||||
onCopyBody,
|
||||
onCopyAsCurl,
|
||||
onCancel,
|
||||
cookieCounts: cookieCountsOverride,
|
||||
extraTabs,
|
||||
textViewer,
|
||||
renderBodyViewer,
|
||||
infoRows,
|
||||
renderCopyButton,
|
||||
}: HttpResponsePaneViewProps) {
|
||||
const { ErrorBoundary } = useEditorHost();
|
||||
const mimeType =
|
||||
response?.contentType == null ? null : getMimeTypeFromContentType(response.contentType).essence;
|
||||
|
||||
const cookieCounts = useMemo(() => {
|
||||
if (cookieCountsOverride != null) return cookieCountsOverride;
|
||||
if (response == null) return { sent: 0, received: 0 };
|
||||
const { sentCookies, receivedCookies } = parseCookieHeaders(response.cookieHeaders);
|
||||
return { sent: sentCookies.length, received: receivedCookies.length };
|
||||
}, [cookieCountsOverride, response]);
|
||||
|
||||
const tabs = useMemo<TabItem[]>(() => {
|
||||
const bodyActionsDisabled = response?.state !== "closed" && (response?.status ?? 0) >= 100;
|
||||
const bodyActionsHidden = response == null || !!response.error;
|
||||
const itemsAfter: DropdownItem[] = [
|
||||
...(onSaveBody != null
|
||||
? [
|
||||
{
|
||||
label: "Save to File",
|
||||
onSelect: onSaveBody,
|
||||
leftSlot: <Icon icon="save" />,
|
||||
hidden: bodyActionsHidden,
|
||||
disabled: bodyActionsDisabled,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(onCopyBody != null
|
||||
? [
|
||||
{
|
||||
label: "Copy Body",
|
||||
onSelect: onCopyBody,
|
||||
leftSlot: <Icon icon="copy" />,
|
||||
hidden: bodyActionsHidden,
|
||||
disabled: bodyActionsDisabled,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(onCopyAsCurl != null
|
||||
? [{ label: "Copy as cURL", onSelect: onCopyAsCurl, leftSlot: <Icon icon="copy" /> }]
|
||||
: []),
|
||||
];
|
||||
|
||||
return [
|
||||
{
|
||||
value: RESPONSE_TAB_BODY,
|
||||
options: {
|
||||
value: viewMode,
|
||||
onChange: (v) => onViewModeChange(v === "raw" ? "raw" : "pretty"),
|
||||
items: [
|
||||
{ label: "Response", value: "pretty" },
|
||||
...(mimeType?.startsWith("image")
|
||||
? []
|
||||
: [{ label: "Response (Raw)", shortLabel: "Raw", value: "raw" }]),
|
||||
],
|
||||
itemsAfter: itemsAfter.length > 0 ? itemsAfter : undefined,
|
||||
},
|
||||
},
|
||||
{
|
||||
value: RESPONSE_TAB_REQUEST,
|
||||
label: "Request",
|
||||
rightSlot: (response?.requestContentLength ?? 0) > 0 ? <CountBadge count={true} /> : null,
|
||||
},
|
||||
{
|
||||
value: RESPONSE_TAB_HEADERS,
|
||||
label: "Headers",
|
||||
rightSlot: (
|
||||
<CountBadge
|
||||
count={response?.requestHeaders.length ?? 0}
|
||||
count2={response?.headers.length ?? 0}
|
||||
showZero
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
value: RESPONSE_TAB_COOKIES,
|
||||
label: "Cookies",
|
||||
rightSlot:
|
||||
cookieCounts.sent > 0 || cookieCounts.received > 0 ? (
|
||||
<CountBadge count={cookieCounts.sent} count2={cookieCounts.received} showZero />
|
||||
) : null,
|
||||
},
|
||||
...(extraTabs?.map((t) => t.tab) ?? []),
|
||||
];
|
||||
}, [
|
||||
cookieCounts,
|
||||
extraTabs,
|
||||
mimeType,
|
||||
onCopyAsCurl,
|
||||
onCopyBody,
|
||||
onSaveBody,
|
||||
onViewModeChange,
|
||||
response,
|
||||
viewMode,
|
||||
]);
|
||||
|
||||
return (
|
||||
<div
|
||||
style={style}
|
||||
className={classNames(
|
||||
className,
|
||||
"x-theme-responsePane",
|
||||
"max-h-full h-full",
|
||||
"bg-surface rounded-md border border-border-subtle overflow-hidden",
|
||||
"relative",
|
||||
)}
|
||||
>
|
||||
{response == null ? (
|
||||
emptyState
|
||||
) : (
|
||||
<div className="h-full w-full grid grid-rows-[auto_minmax(0,1fr)] grid-cols-1">
|
||||
<HStack
|
||||
className={classNames(
|
||||
"text-text-subtle w-full shrink-0",
|
||||
// Remove a bit of space because the tabs have lots too
|
||||
"-mb-1.5",
|
||||
)}
|
||||
>
|
||||
<ResponseStatusLine
|
||||
response={response}
|
||||
center={statusLineCenter}
|
||||
right={statusLineRight}
|
||||
/>
|
||||
</HStack>
|
||||
|
||||
<div className="overflow-hidden flex flex-col min-h-0">
|
||||
{response.error && (
|
||||
<Banner color="danger" className="mx-3 mt-1 shrink-0">
|
||||
{response.error}
|
||||
</Banner>
|
||||
)}
|
||||
{/* Show tabs if we have any data (headers, body, etc.) even if there's an error */}
|
||||
<Tabs
|
||||
tabs={tabs}
|
||||
label="Response"
|
||||
className="ml-3 mr-3 mb-3 min-h-0 flex-1"
|
||||
tabListClassName="mt-0.5 -mb-1.5"
|
||||
storageKey={tabsStorageKey}
|
||||
activeTabKey={activeTabKey}
|
||||
>
|
||||
<TabContent value={RESPONSE_TAB_BODY} ErrorBoundary={ErrorBoundary}>
|
||||
<ErrorBoundary name="Http Response Viewer">
|
||||
<Suspense>
|
||||
<ConfirmLargeResponse
|
||||
contentLength={response.contentLength}
|
||||
contentType={response.contentType}
|
||||
onSave={onSaveBody}
|
||||
getText={body?.getText}
|
||||
renderCopyButton={renderCopyButton}
|
||||
>
|
||||
{body != null && (
|
||||
<ResponseBodyViewer
|
||||
response={response}
|
||||
body={body}
|
||||
viewMode={viewMode}
|
||||
textViewer={textViewer}
|
||||
onCancel={onCancel}
|
||||
renderBodyViewer={renderBodyViewer}
|
||||
/>
|
||||
)}
|
||||
</ConfirmLargeResponse>
|
||||
</Suspense>
|
||||
</ErrorBoundary>
|
||||
</TabContent>
|
||||
<TabContent value={RESPONSE_TAB_REQUEST} ErrorBoundary={ErrorBoundary}>
|
||||
<ConfirmLargeResponse
|
||||
contentLength={response.requestContentLength}
|
||||
contentType={response.contentType}
|
||||
noun="content"
|
||||
revealLabel="Reveal Request Body"
|
||||
getText={requestBody?.getText}
|
||||
renderCopyButton={renderCopyButton}
|
||||
>
|
||||
{requestBody != null && (
|
||||
<RequestBodyViewer
|
||||
id={response.id}
|
||||
contentType={findHeader(response.requestHeaders, "content-type")}
|
||||
body={requestBody}
|
||||
/>
|
||||
)}
|
||||
</ConfirmLargeResponse>
|
||||
</TabContent>
|
||||
<TabContent value={RESPONSE_TAB_HEADERS} ErrorBoundary={ErrorBoundary}>
|
||||
<ResponseHeaders response={response} infoRows={infoRows} />
|
||||
</TabContent>
|
||||
<TabContent value={RESPONSE_TAB_COOKIES} ErrorBoundary={ErrorBoundary}>
|
||||
<ResponseCookies response={response} />
|
||||
</TabContent>
|
||||
{extraTabs?.map(({ tab, content }) => (
|
||||
<TabContent key={tab.value} value={tab.value} ErrorBoundary={ErrorBoundary}>
|
||||
{content}
|
||||
</TabContent>
|
||||
))}
|
||||
</Tabs>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The status, time and size of a response, with room for the app's own pieces */
|
||||
export function ResponseStatusLine({
|
||||
response,
|
||||
center,
|
||||
right,
|
||||
}: {
|
||||
response: HttpResponseView;
|
||||
center?: ReactNode;
|
||||
right?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
"grid grid-cols-[auto_minmax(4rem,1fr)_auto]",
|
||||
// As tall as an `h-sm` button with `m-0.5` (the client's response history menu), so the
|
||||
// status sits the same distance from the card's edge with or without one on the right
|
||||
"min-h-[calc(var(--height-sm)+0.25rem)]",
|
||||
"cursor-default select-none",
|
||||
"whitespace-nowrap w-full pl-3 overflow-x-auto font-mono text-sm hide-scrollbars",
|
||||
)}
|
||||
>
|
||||
<HStack space={2} className="w-full shrink-0">
|
||||
{response.state !== "closed" && <LoadingIcon size="sm" />}
|
||||
<HttpStatusTagRaw
|
||||
showReason
|
||||
status={response.status}
|
||||
state={response.state}
|
||||
statusReason={response.statusReason}
|
||||
/>
|
||||
<span>•</span>
|
||||
<HttpResponseDurationTagRaw
|
||||
closed={response.state === "closed"}
|
||||
startedAt={response.startedAt}
|
||||
elapsedMs={response.elapsedMs}
|
||||
elapsedHeadersMs={response.elapsedHeadersMs}
|
||||
elapsedDnsMs={response.elapsedDnsMs}
|
||||
/>
|
||||
<span>•</span>
|
||||
<SizeTag
|
||||
contentLength={response.contentLength ?? 0}
|
||||
contentLengthCompressed={response.contentLengthCompressed}
|
||||
/>
|
||||
</HStack>
|
||||
{center ?? <span />}
|
||||
<div className="justify-self-end shrink-0">{right}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function findHeader(headers: { name: string; value: string }[], name: string): string | null {
|
||||
return headers.find((h) => h.name.toLowerCase() === name)?.value ?? null;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { linter } from "@codemirror/lint";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { textLikelyContainsJsonComments } from "../../lib/jsonComments";
|
||||
import { replaceTemplateTags } from "../../lib/templateTags";
|
||||
import { Banner } from "../Banner";
|
||||
import type { DropdownItem } from "../Dropdown";
|
||||
import { Dropdown } from "../Dropdown";
|
||||
import type { HostEditorProps } from "../EditorHost";
|
||||
import { useEditorHost } from "../EditorHost";
|
||||
import { jsonParseLinter } from "../editor/json-lint";
|
||||
import { Icon } from "../Icon";
|
||||
import { IconButton } from "../IconButton";
|
||||
import { IconTooltip } from "../IconTooltip";
|
||||
|
||||
interface Props {
|
||||
forceUpdateKey: string;
|
||||
heightMode: HostEditorProps["heightMode"];
|
||||
/** The request's id, keeping each request's editor state apart */
|
||||
requestId: string;
|
||||
text: string;
|
||||
/** JSON is sent as written, comments and all, instead of cleaned up first */
|
||||
sendJsonComments: boolean;
|
||||
onChange?: (text: string) => void;
|
||||
onChangeSendJsonComments?: (sendJsonComments: boolean) => void;
|
||||
/** Where dismissing the comments notice is remembered, like the workspace it applies to */
|
||||
noticeStorageKey: string;
|
||||
/** Show the body without a way to change it */
|
||||
readOnly?: boolean;
|
||||
}
|
||||
|
||||
export function JsonBodyEditor({
|
||||
forceUpdateKey,
|
||||
heightMode,
|
||||
requestId,
|
||||
text,
|
||||
sendJsonComments,
|
||||
onChange,
|
||||
onChangeSendJsonComments,
|
||||
noticeStorageKey,
|
||||
readOnly,
|
||||
}: Props) {
|
||||
const { Editor, useStoredValue } = useEditorHost();
|
||||
const autoFix = sendJsonComments !== true;
|
||||
|
||||
const lintExtension = useMemo(
|
||||
() =>
|
||||
linter(
|
||||
jsonParseLinter(
|
||||
autoFix || readOnly
|
||||
? { allowComments: true, allowTrailingCommas: true, escape: escapeTemplateTags }
|
||||
: { allowComments: false, allowTrailingCommas: false, escape: escapeTemplateTags },
|
||||
),
|
||||
),
|
||||
[autoFix, readOnly],
|
||||
);
|
||||
|
||||
const hasComments = useMemo(() => textLikelyContainsJsonComments(text), [text]);
|
||||
|
||||
const [bannerDismissed, setBannerDismissed] = useStoredValue<boolean>(
|
||||
["json-fix-3", noticeStorageKey],
|
||||
false,
|
||||
"no_sync",
|
||||
);
|
||||
|
||||
const handleToggleAutoFix = useCallback(
|
||||
() => onChangeSendJsonComments?.(autoFix),
|
||||
[autoFix, onChangeSendJsonComments],
|
||||
);
|
||||
|
||||
const handleDropdownOpen = useCallback(() => {
|
||||
if (!bannerDismissed) {
|
||||
Promise.resolve(setBannerDismissed(true)).catch(console.error);
|
||||
}
|
||||
}, [bannerDismissed, setBannerDismissed]);
|
||||
|
||||
const showBanner = hasComments && autoFix && !bannerDismissed;
|
||||
|
||||
const stripMessage = "Automatically strip comments and trailing commas before sending";
|
||||
const actions = useMemo<HostEditorProps["actions"]>(
|
||||
() =>
|
||||
readOnly
|
||||
? undefined
|
||||
: [
|
||||
showBanner && (
|
||||
<Banner
|
||||
color="notice"
|
||||
className="opacity-100! h-sm py-0! px-2! flex items-center text-xs"
|
||||
>
|
||||
<p className="inline-flex items-center gap-1 min-w-0">
|
||||
<span className="truncate">Auto-fix enabled</span>
|
||||
<Icon icon="arrow_right" size="sm" className="opacity-disabled" />
|
||||
</p>
|
||||
</Banner>
|
||||
),
|
||||
<div key="settings" className="opacity-100! shadow!">
|
||||
<Dropdown
|
||||
onOpen={handleDropdownOpen}
|
||||
items={
|
||||
[
|
||||
{
|
||||
label: "Automatically Fix JSON",
|
||||
keepOpenOnSelect: true,
|
||||
onSelect: handleToggleAutoFix,
|
||||
rightSlot: <IconTooltip content={stripMessage} />,
|
||||
leftSlot: (
|
||||
<Icon icon={autoFix ? "check_square_checked" : "check_square_unchecked"} />
|
||||
),
|
||||
},
|
||||
] satisfies DropdownItem[]
|
||||
}
|
||||
>
|
||||
<IconButton size="sm" variant="border" icon="settings" title="JSON Settings" />
|
||||
</Dropdown>
|
||||
</div>,
|
||||
],
|
||||
[handleDropdownOpen, handleToggleAutoFix, autoFix, readOnly, showBanner],
|
||||
);
|
||||
|
||||
return (
|
||||
<Editor
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
autocompleteFunctions
|
||||
autocompleteVariables
|
||||
placeholder="..."
|
||||
heightMode={heightMode}
|
||||
defaultValue={text}
|
||||
language="json"
|
||||
onChange={onChange}
|
||||
readOnly={readOnly}
|
||||
stateKey={`json.${requestId}`}
|
||||
actions={actions}
|
||||
lintExtension={lintExtension}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// We need lint to not break on stuff like {"foo:" ${[ ... ]}} so we'll replace all template
|
||||
// syntax with repeating `1` characters, so it's valid JSON and the position is still correct.
|
||||
function escapeTemplateTags(doc: string): string {
|
||||
return replaceTemplateTags(doc, (m) => "1".repeat(m.end - m.start));
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { formatSize } from "@yaakapp-internal/lib/formatSize";
|
||||
import { languageFromContentType } from "../../lib/contentType";
|
||||
import { getMimeTypeFromContentType } from "../../lib/mimeType";
|
||||
import { EmptyStateText } from "../EmptyStateText";
|
||||
import { useEditorHost } from "../EditorHost";
|
||||
import { LoadingIcon } from "../LoadingIcon";
|
||||
import { AudioViewer } from "../viewers/AudioViewer";
|
||||
import { CsvViewer } from "../viewers/CsvViewer";
|
||||
import { ImageViewer } from "../viewers/ImageViewer";
|
||||
import { SvgViewer } from "../viewers/SvgViewer";
|
||||
import { VideoViewer } from "../viewers/VideoViewer";
|
||||
import { WebPageViewer } from "../viewers/WebPageViewer";
|
||||
import type { HttpBodyLoader } from "./types";
|
||||
|
||||
interface Props {
|
||||
/** Identifies the body, for viewer state */
|
||||
id: string;
|
||||
/** The Content-Type the request was sent with */
|
||||
contentType: string | null;
|
||||
body: HttpBodyLoader;
|
||||
}
|
||||
|
||||
/** The body a request was sent with, in the viewer its content type calls for */
|
||||
export function RequestBodyViewer({ id, contentType, body }: Props) {
|
||||
return <RequestBodyViewerInner key={id} id={id} contentType={contentType} body={body} />;
|
||||
}
|
||||
|
||||
function RequestBodyViewerInner({ id, contentType, body }: Props) {
|
||||
const { MultipartViewer, TextViewer, renderBodyViewer } = useEditorHost();
|
||||
const text = body.useText();
|
||||
const bytes = body.useBytes();
|
||||
|
||||
if (text.isLoading || bytes.isLoading) {
|
||||
return (
|
||||
<EmptyStateText>
|
||||
<LoadingIcon />
|
||||
</EmptyStateText>
|
||||
);
|
||||
}
|
||||
|
||||
const error = text.error ?? bytes.error;
|
||||
if (error) {
|
||||
return <EmptyStateText>Error loading request body: {error.message}</EmptyStateText>;
|
||||
}
|
||||
|
||||
// Whether there's a body is the bytes' to say: a binary body has no text
|
||||
const bodyBytes = bytes.data;
|
||||
if (bodyBytes == null || bodyBytes.length === 0) {
|
||||
return <EmptyStateText>No request body</EmptyStateText>;
|
||||
}
|
||||
|
||||
const mimeType = contentType ? getMimeTypeFromContentType(contentType).essence : null;
|
||||
|
||||
// Route to appropriate viewer based on content type
|
||||
if (mimeType?.match(/^multipart/i)) {
|
||||
const boundary = contentType?.split("boundary=")[1] ?? "unknown";
|
||||
// Create a copy because parseMultipart may detach the buffer
|
||||
const bodyCopy = new Uint8Array(bodyBytes);
|
||||
return <MultipartViewer data={bodyCopy} boundary={boundary} idPrefix={`request.${id}`} />;
|
||||
}
|
||||
|
||||
if (mimeType?.match(/^image/i) && !mimeType.match(/^image\/svg/i)) {
|
||||
return <ImageViewer data={bodyBytes.buffer as ArrayBuffer} />;
|
||||
}
|
||||
|
||||
if (mimeType?.match(/^audio/i)) {
|
||||
return <AudioViewer data={bodyBytes} />;
|
||||
}
|
||||
|
||||
if (mimeType?.match(/^video/i)) {
|
||||
return <VideoViewer data={bodyBytes} />;
|
||||
}
|
||||
|
||||
const appViewer = mimeType?.match(/pdf/i)
|
||||
? renderBodyViewer?.({ source: "request", mimeType, viewMode: "pretty", body, complete: true })
|
||||
: null;
|
||||
|
||||
// The rest show text, which a body that isn't valid UTF-8 doesn't have
|
||||
const bodyText = text.data;
|
||||
if (bodyText == null || bodyText.length === 0) {
|
||||
return (
|
||||
appViewer ?? <EmptyStateText>Binary body, {formatSize(bodyBytes.length)}</EmptyStateText>
|
||||
);
|
||||
}
|
||||
|
||||
if (mimeType?.match(/^image\/svg/i)) {
|
||||
return <SvgViewer text={bodyText} />;
|
||||
}
|
||||
|
||||
if (mimeType?.match(/csv|tab-separated/i)) {
|
||||
return <CsvViewer text={bodyText} />;
|
||||
}
|
||||
|
||||
if (mimeType?.match(/^text\/html/i)) {
|
||||
return <WebPageViewer html={bodyText} />;
|
||||
}
|
||||
|
||||
if (appViewer != null) return appViewer;
|
||||
|
||||
const language = languageFromContentType(contentType, bodyText);
|
||||
return <TextViewer text={bodyText} language={language} stateKey={`request.body.${id}`} />;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import classNames from "classnames";
|
||||
import { memo, useCallback, useMemo } from "react";
|
||||
import { Button } from "../Button";
|
||||
import type { DropdownItem } from "../Dropdown";
|
||||
import { useEditorHost } from "../EditorHost";
|
||||
import { Icon } from "../Icon";
|
||||
import type { RadioDropdownItem } from "../RadioDropdown";
|
||||
import { RadioDropdown } from "../RadioDropdown";
|
||||
import { HttpMethodTagRaw } from "../tags/HttpMethodTag";
|
||||
|
||||
type Props = {
|
||||
method: string;
|
||||
/** Colour the method by what it does, as the client's setting chooses */
|
||||
colored?: boolean;
|
||||
onChange?: (method: string) => void | Promise<void>;
|
||||
/** Show the method without a menu to change it */
|
||||
readOnly?: boolean;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
const METHODS = ["GET", "PUT", "POST", "PATCH", "DELETE", "OPTIONS", "QUERY", "HEAD"];
|
||||
|
||||
export const RequestMethodDropdown = memo(function RequestMethodDropdown({
|
||||
method,
|
||||
colored,
|
||||
onChange,
|
||||
readOnly,
|
||||
className,
|
||||
}: Props) {
|
||||
const { showPrompt } = useEditorHost();
|
||||
|
||||
const radioItems = useMemo<RadioDropdownItem<string>[]>(
|
||||
() =>
|
||||
METHODS.map((m) => ({ value: m, label: <HttpMethodTagRaw method={m} colored={colored} /> })),
|
||||
[colored],
|
||||
);
|
||||
|
||||
const handleChange = useCallback(
|
||||
async (method: string) => {
|
||||
await onChange?.(method);
|
||||
},
|
||||
[onChange],
|
||||
);
|
||||
|
||||
const itemsAfter = useMemo<DropdownItem[]>(
|
||||
() => [
|
||||
{
|
||||
key: "custom",
|
||||
label: "CUSTOM",
|
||||
leftSlot: <Icon icon="sparkles" />,
|
||||
hidden: showPrompt == null,
|
||||
onSelect: async () => {
|
||||
const newMethod = await showPrompt?.({
|
||||
id: "custom-method",
|
||||
label: "Http Method",
|
||||
title: "Custom Method",
|
||||
confirmText: "Save",
|
||||
description: "Enter a custom method name",
|
||||
placeholder: "CUSTOM",
|
||||
});
|
||||
if (newMethod == null) return;
|
||||
await handleChange(newMethod);
|
||||
},
|
||||
},
|
||||
],
|
||||
[handleChange, showPrompt],
|
||||
);
|
||||
|
||||
const button = (
|
||||
<Button size="xs" className={classNames(className, "text-text-subtle hover:text")}>
|
||||
<HttpMethodTagRaw method={method} colored={colored} />
|
||||
</Button>
|
||||
);
|
||||
|
||||
if (readOnly) return button;
|
||||
|
||||
return (
|
||||
<RadioDropdown
|
||||
value={method}
|
||||
items={radioItems}
|
||||
itemsAfter={itemsAfter}
|
||||
onChange={handleChange}
|
||||
>
|
||||
{button}
|
||||
</RadioDropdown>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
import { formatSize } from "@yaakapp-internal/lib/formatSize";
|
||||
import type { ComponentType } from "react";
|
||||
import { languageFromContentType } from "../../lib/contentType";
|
||||
import { getMimeTypeFromContentType } from "../../lib/mimeType";
|
||||
import { Banner } from "../Banner";
|
||||
import { Button } from "../Button";
|
||||
import { EmptyStateText } from "../EmptyStateText";
|
||||
import { type EditorHost, useEditorHost } from "../EditorHost";
|
||||
import { LoadingIcon } from "../LoadingIcon";
|
||||
import { HStack, VStack } from "../Stacks";
|
||||
import { AudioViewer } from "../viewers/AudioViewer";
|
||||
import { CsvViewer } from "../viewers/CsvViewer";
|
||||
import { ImageViewer } from "../viewers/ImageViewer";
|
||||
import { SvgViewer } from "../viewers/SvgViewer";
|
||||
import type { TextViewerProps } from "../viewers/TextViewer";
|
||||
import { VideoViewer } from "../viewers/VideoViewer";
|
||||
import { WebPageViewer } from "../viewers/WebPageViewer";
|
||||
import type { HttpBodyLoader, HttpResponseView } from "./types";
|
||||
|
||||
export type ResponseViewMode = "pretty" | "raw";
|
||||
|
||||
/** What the text viewer adds for the app, like its filter history and save and copy buttons */
|
||||
export type ResponseTextViewerExtras = Pick<
|
||||
TextViewerProps,
|
||||
"footerActions" | "filterStateKey" | "onFilterApplied" | "filterLeftSlot"
|
||||
>;
|
||||
|
||||
interface Props {
|
||||
response: HttpResponseView;
|
||||
body: HttpBodyLoader;
|
||||
viewMode: ResponseViewMode;
|
||||
textViewer?: ResponseTextViewerExtras;
|
||||
/** Stop a request that's still being sent */
|
||||
onCancel?: () => void;
|
||||
/** Viewers only this pane's app has, tried before the host's and the shared ones */
|
||||
renderBodyViewer?: EditorHost["renderBodyViewer"];
|
||||
}
|
||||
|
||||
/** Picks the viewer for a response body from its content type, as the client's response pane does */
|
||||
export function ResponseBodyViewer({
|
||||
response,
|
||||
body,
|
||||
viewMode,
|
||||
textViewer,
|
||||
onCancel,
|
||||
renderBodyViewer: renderPaneBodyViewer,
|
||||
}: Props) {
|
||||
const { renderBodyViewer: renderHostBodyViewer } = useEditorHost();
|
||||
const mimeType =
|
||||
response.contentType == null ? null : getMimeTypeFromContentType(response.contentType).essence;
|
||||
|
||||
if (response.state === "initialized") {
|
||||
return (
|
||||
<EmptyStateText>
|
||||
<VStack space={3}>
|
||||
<HStack space={3}>
|
||||
<LoadingIcon className="text-text-subtlest" />
|
||||
Sending Request
|
||||
</HStack>
|
||||
{onCancel != null && (
|
||||
<Button size="sm" variant="border" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
</VStack>
|
||||
</EmptyStateText>
|
||||
);
|
||||
}
|
||||
|
||||
if (response.state === "closed" && (response.contentLength ?? 0) === 0) {
|
||||
return <EmptyStateText>Empty</EmptyStateText>;
|
||||
}
|
||||
|
||||
const viewerArgs = {
|
||||
source: "response" as const,
|
||||
mimeType,
|
||||
viewMode,
|
||||
body,
|
||||
complete: response.state === "closed",
|
||||
};
|
||||
const appViewer = renderPaneBodyViewer?.(viewerArgs) ?? renderHostBodyViewer?.(viewerArgs);
|
||||
if (appViewer != null) return appViewer;
|
||||
|
||||
if (mimeType?.match(/^image\/svg/)) {
|
||||
return <BodySvgViewer body={body} />;
|
||||
}
|
||||
if (mimeType?.match(/^image/i)) {
|
||||
return <EnsureCompleteResponse response={response} body={body} Component={ImageViewer} />;
|
||||
}
|
||||
if (mimeType?.match(/^audio/i)) {
|
||||
return <EnsureCompleteResponse response={response} body={body} Component={AudioViewer} />;
|
||||
}
|
||||
if (mimeType?.match(/^video/i)) {
|
||||
return <EnsureCompleteResponse response={response} body={body} Component={VideoViewer} />;
|
||||
}
|
||||
if (mimeType?.match(/^multipart/i) && viewMode === "pretty") {
|
||||
return <BodyMultipartViewer response={response} body={body} />;
|
||||
}
|
||||
if (mimeType?.match(/csv|tab-separated/i) && viewMode === "pretty") {
|
||||
return <BodyCsvViewer className="pb-2" body={body} />;
|
||||
}
|
||||
return (
|
||||
<HTMLOrTextViewer
|
||||
textViewerClassName="-mr-2 bg-surface" // Pull to the right
|
||||
response={response}
|
||||
body={body}
|
||||
pretty={viewMode === "pretty"}
|
||||
textViewer={textViewer}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** A body with no text is either empty or not valid UTF-8, which only its bytes can tell apart */
|
||||
function BinaryOrEmptyBody({ body }: { body: HttpBodyLoader }) {
|
||||
const bytes = body.useBytes();
|
||||
if (bytes.isLoading) return null;
|
||||
const length = bytes.data?.length ?? 0;
|
||||
return (
|
||||
<EmptyStateText>
|
||||
{length > 0 ? `Binary body, ${formatSize(length)}` : "Empty response"}
|
||||
</EmptyStateText>
|
||||
);
|
||||
}
|
||||
|
||||
function EnsureCompleteResponse({
|
||||
response,
|
||||
body,
|
||||
Component,
|
||||
}: {
|
||||
response: HttpResponseView;
|
||||
body: HttpBodyLoader;
|
||||
Component: ComponentType<{ bodyUrl: string }>;
|
||||
}) {
|
||||
// Wait until the response has been fully-downloaded before asking for it
|
||||
const complete = response.state === "closed";
|
||||
const bodyUrl = body.useUrl(complete);
|
||||
|
||||
if (!complete || bodyUrl.isLoading) {
|
||||
return (
|
||||
<EmptyStateText>
|
||||
<LoadingIcon />
|
||||
</EmptyStateText>
|
||||
);
|
||||
}
|
||||
|
||||
if (bodyUrl.error) {
|
||||
return <Banner color="danger">{String(bodyUrl.error)}</Banner>;
|
||||
}
|
||||
|
||||
if (bodyUrl.data == null) {
|
||||
return <div>Empty response body</div>;
|
||||
}
|
||||
|
||||
return <Component bodyUrl={bodyUrl.data} />;
|
||||
}
|
||||
|
||||
function BodySvgViewer({ body }: { body: HttpBodyLoader }) {
|
||||
const text = body.useText();
|
||||
if (!text.data) return null;
|
||||
return <SvgViewer text={text.data} />;
|
||||
}
|
||||
|
||||
function BodyCsvViewer({ body, className }: { body: HttpBodyLoader; className?: string }) {
|
||||
const text = body.useText();
|
||||
return <CsvViewer text={text.data ?? null} className={className} />;
|
||||
}
|
||||
|
||||
function BodyMultipartViewer({
|
||||
response,
|
||||
body,
|
||||
}: {
|
||||
response: HttpResponseView;
|
||||
body: HttpBodyLoader;
|
||||
}) {
|
||||
const { MultipartViewer } = useEditorHost();
|
||||
const bytes = body.useBytes();
|
||||
if (bytes.data == null) return null;
|
||||
|
||||
const boundary = response.contentType?.split("boundary=")[1] ?? "unknown";
|
||||
return <MultipartViewer data={bytes.data} boundary={boundary} idPrefix={response.id} />;
|
||||
}
|
||||
|
||||
interface HTMLOrTextViewerProps {
|
||||
response: HttpResponseView;
|
||||
body: HttpBodyLoader;
|
||||
pretty: boolean;
|
||||
textViewerClassName?: string;
|
||||
textViewer?: ResponseTextViewerExtras;
|
||||
}
|
||||
|
||||
export function HTMLOrTextViewer({
|
||||
response,
|
||||
body,
|
||||
pretty,
|
||||
textViewerClassName,
|
||||
textViewer,
|
||||
}: HTMLOrTextViewerProps) {
|
||||
const { TextViewer } = useEditorHost();
|
||||
const rawTextBody = body.useText();
|
||||
const language = languageFromContentType(response.contentType, rawTextBody.data ?? "");
|
||||
|
||||
if (rawTextBody.isLoading || response.state === "initialized") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (language === "html" && pretty) {
|
||||
return <WebPageViewer html={rawTextBody.data ?? ""} baseUrl={response.url} />;
|
||||
}
|
||||
if (rawTextBody.data == null) {
|
||||
return <BinaryOrEmptyBody body={body} />;
|
||||
}
|
||||
return (
|
||||
<TextViewer
|
||||
text={rawTextBody.data}
|
||||
language={language}
|
||||
stateKey={`response.body.${response.id}`}
|
||||
pretty={pretty}
|
||||
className={textViewerClassName}
|
||||
filterText={body.filterText}
|
||||
filterStateKey={`response.body.${response.ownerId}`}
|
||||
{...textViewer}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import classNames from "classnames";
|
||||
import { useMemo } from "react";
|
||||
import type { JSX } from "react/jsx-runtime";
|
||||
import { CountBadge } from "../CountBadge";
|
||||
import { DetailsBanner } from "../DetailsBanner";
|
||||
import { useEditorHost } from "../EditorHost";
|
||||
import { KeyValueRows } from "../KeyValueRow";
|
||||
import { KeyValueRow } from "./ResponseHeaders";
|
||||
import type { HttpResponseView } from "./types";
|
||||
|
||||
interface Props {
|
||||
response: HttpResponseView;
|
||||
}
|
||||
|
||||
interface ParsedCookie {
|
||||
name: string;
|
||||
value: string;
|
||||
domain?: string;
|
||||
path?: string;
|
||||
expires?: string;
|
||||
maxAge?: string;
|
||||
secure?: boolean;
|
||||
httpOnly?: boolean;
|
||||
sameSite?: string;
|
||||
isDeleted?: boolean;
|
||||
}
|
||||
|
||||
function parseCookieHeader(cookieHeader: string): Array<{ name: string; value: string }> {
|
||||
// Parse "Cookie: name=value; name2=value2" format
|
||||
return cookieHeader.split(";").map((pair) => {
|
||||
const [name = "", ...valueParts] = pair.split("=");
|
||||
return {
|
||||
name: name.trim(),
|
||||
value: valueParts.join("=").trim(),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function parseSetCookieHeader(setCookieHeader: string): ParsedCookie {
|
||||
// Parse "Set-Cookie: name=value; Domain=...; Path=..." format
|
||||
const parts = setCookieHeader.split(";").map((p) => p.trim());
|
||||
const [nameValue = "", ...attributes] = parts;
|
||||
const [name = "", ...valueParts] = nameValue.split("=");
|
||||
|
||||
const cookie: ParsedCookie = {
|
||||
name: name.trim(),
|
||||
value: valueParts.join("=").trim(),
|
||||
};
|
||||
|
||||
for (const attr of attributes) {
|
||||
const [key = "", val] = attr.split("=").map((s) => s.trim());
|
||||
const lowerKey = key.toLowerCase();
|
||||
|
||||
if (lowerKey === "domain") cookie.domain = val;
|
||||
else if (lowerKey === "path") cookie.path = val;
|
||||
else if (lowerKey === "expires") cookie.expires = val;
|
||||
else if (lowerKey === "max-age") cookie.maxAge = val;
|
||||
else if (lowerKey === "secure") cookie.secure = true;
|
||||
else if (lowerKey === "httponly") cookie.httpOnly = true;
|
||||
else if (lowerKey === "samesite") cookie.sameSite = val;
|
||||
}
|
||||
|
||||
// Detect if cookie is being deleted
|
||||
if (cookie.maxAge !== undefined) {
|
||||
const maxAgeNum = Number.parseInt(cookie.maxAge, 10);
|
||||
if (!Number.isNaN(maxAgeNum) && maxAgeNum <= 0) {
|
||||
cookie.isDeleted = true;
|
||||
}
|
||||
} else if (cookie.expires !== undefined) {
|
||||
// Check if expires date is in the past
|
||||
try {
|
||||
const expiresDate = new Date(cookie.expires);
|
||||
if (expiresDate.getTime() < Date.now()) {
|
||||
cookie.isDeleted = true;
|
||||
}
|
||||
} catch {
|
||||
// Invalid date, ignore
|
||||
}
|
||||
}
|
||||
|
||||
return cookie;
|
||||
}
|
||||
|
||||
/** The cookies a response's headers sent and received, the latest value of each name winning */
|
||||
export function parseCookieHeaders({ sent, received }: HttpResponseView["cookieHeaders"]) {
|
||||
const sentMap = new Map<string, { name: string; value: string }>();
|
||||
const receivedMap = new Map<string, ParsedCookie>();
|
||||
|
||||
for (const header of sent) {
|
||||
for (const cookie of parseCookieHeader(header)) {
|
||||
sentMap.set(cookie.name, cookie);
|
||||
}
|
||||
}
|
||||
for (const header of received) {
|
||||
const cookie = parseSetCookieHeader(header);
|
||||
receivedMap.set(cookie.name, cookie);
|
||||
}
|
||||
|
||||
return {
|
||||
sentCookies: Array.from(sentMap.values()),
|
||||
receivedCookies: Array.from(receivedMap.values()),
|
||||
};
|
||||
}
|
||||
|
||||
export function ResponseCookies({ response }: Props) {
|
||||
const { useDetailsBannerStoredValue } = useEditorHost();
|
||||
const { sentCookies, receivedCookies } = useMemo(
|
||||
() => parseCookieHeaders(response.cookieHeaders),
|
||||
[response.cookieHeaders],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="overflow-auto h-full pb-4 gap-y-3 flex flex-col pr-0.5">
|
||||
<DetailsBanner
|
||||
defaultOpen
|
||||
useStoredValue={useDetailsBannerStoredValue}
|
||||
storageKey={`${response.ownerId}.sent_cookies`}
|
||||
summary={
|
||||
<h2 className="flex items-center">
|
||||
Sent Cookies <CountBadge showZero count={sentCookies.length} />
|
||||
</h2>
|
||||
}
|
||||
>
|
||||
{sentCookies.length === 0 ? (
|
||||
<NoCookies />
|
||||
) : (
|
||||
<KeyValueRows>
|
||||
{sentCookies.map((cookie, i) => (
|
||||
// oxlint-disable-next-line react/no-array-index-key
|
||||
<KeyValueRow labelColor="primary" key={i} label={cookie.name}>
|
||||
{cookie.value}
|
||||
</KeyValueRow>
|
||||
))}
|
||||
</KeyValueRows>
|
||||
)}
|
||||
</DetailsBanner>
|
||||
|
||||
<DetailsBanner
|
||||
defaultOpen
|
||||
useStoredValue={useDetailsBannerStoredValue}
|
||||
storageKey={`${response.ownerId}.received_cookies`}
|
||||
summary={
|
||||
<h2 className="flex items-center">
|
||||
Received Cookies <CountBadge showZero count={receivedCookies.length} />
|
||||
</h2>
|
||||
}
|
||||
>
|
||||
{receivedCookies.length === 0 ? (
|
||||
<NoCookies />
|
||||
) : (
|
||||
<div className="flex flex-col gap-4">
|
||||
{receivedCookies.map((cookie, i) => (
|
||||
// oxlint-disable-next-line react/no-array-index-key
|
||||
<div key={i} className="flex flex-col gap-1">
|
||||
<div className="flex items-center gap-2 my-1">
|
||||
<span
|
||||
className={classNames(
|
||||
"font-mono text-editor select-auto cursor-auto",
|
||||
cookie.isDeleted ? "line-through opacity-60 text-text-subtle" : "text-text",
|
||||
)}
|
||||
>
|
||||
{cookie.name}
|
||||
<span className="text-text-subtlest select-auto cursor-auto mx-0.5">=</span>
|
||||
{cookie.value}
|
||||
</span>
|
||||
{cookie.isDeleted && (
|
||||
<span className="text-xs font-sans text-danger bg-danger/10 px-1.5 py-0.5 rounded-sm">
|
||||
Deleted
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<KeyValueRows>
|
||||
{[
|
||||
cookie.domain && (
|
||||
<KeyValueRow labelColor="info" label="Domain" key="domain">
|
||||
{cookie.domain}
|
||||
</KeyValueRow>
|
||||
),
|
||||
cookie.path && (
|
||||
<KeyValueRow labelColor="info" label="Path" key="path">
|
||||
{cookie.path}
|
||||
</KeyValueRow>
|
||||
),
|
||||
cookie.expires && (
|
||||
<KeyValueRow labelColor="info" label="Expires" key="expires">
|
||||
{cookie.expires}
|
||||
</KeyValueRow>
|
||||
),
|
||||
cookie.maxAge && (
|
||||
<KeyValueRow labelColor="info" label="Max-Age" key="maxAge">
|
||||
{cookie.maxAge}
|
||||
</KeyValueRow>
|
||||
),
|
||||
cookie.secure && (
|
||||
<KeyValueRow labelColor="info" label="Secure" key="secure">
|
||||
true
|
||||
</KeyValueRow>
|
||||
),
|
||||
cookie.httpOnly && (
|
||||
<KeyValueRow labelColor="info" label="HttpOnly" key="httpOnly">
|
||||
true
|
||||
</KeyValueRow>
|
||||
),
|
||||
cookie.sameSite && (
|
||||
<KeyValueRow labelColor="info" label="SameSite" key="sameSite">
|
||||
{cookie.sameSite}
|
||||
</KeyValueRow>
|
||||
),
|
||||
].filter((item): item is JSX.Element => Boolean(item))}
|
||||
</KeyValueRows>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</DetailsBanner>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NoCookies() {
|
||||
return <span className="text-text-subtlest text-sm italic">No Cookies</span>;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { format, formatDistanceToNowStrict } from "date-fns";
|
||||
import type { ReactElement } from "react";
|
||||
import { DetailsBanner } from "../DetailsBanner";
|
||||
import { useEditorHost } from "../EditorHost";
|
||||
import { HeadersTable } from "../HeadersTable";
|
||||
import { IconButton } from "../IconButton";
|
||||
import type { KeyValueRowProps } from "../KeyValueRow";
|
||||
import { KeyValueRow as BaseKeyValueRow, KeyValueRows } from "../KeyValueRow";
|
||||
import type { HttpResponseView } from "./types";
|
||||
|
||||
interface Props {
|
||||
response: HttpResponseView;
|
||||
/** More rows for the Info section, after the standard ones, each keyed */
|
||||
infoRows?: ReactElement[];
|
||||
}
|
||||
|
||||
export function ResponseHeaders({ response, infoRows }: Props) {
|
||||
const { openUrl, useDetailsBannerStoredValue } = useEditorHost();
|
||||
return (
|
||||
<div className="overflow-auto h-full pb-4 gap-y-3 flex flex-col pr-0.5">
|
||||
<DetailsBanner
|
||||
storageKey={`${response.ownerId}.general`}
|
||||
summary={<h2>Info</h2>}
|
||||
useStoredValue={useDetailsBannerStoredValue}
|
||||
>
|
||||
<KeyValueRows>
|
||||
{[
|
||||
<KeyValueRow key="sent" labelColor="secondary" label="Sent">
|
||||
<time
|
||||
dateTime={new Date(response.startedAt).toISOString()}
|
||||
title={formatDistanceToNowStrict(response.startedAt, { addSuffix: true })}
|
||||
>
|
||||
{format(response.startedAt, "MMM d, yyyy, h:mm:ss a O")}
|
||||
</time>
|
||||
</KeyValueRow>,
|
||||
<KeyValueRow key="url" labelColor="secondary" label="Request URL">
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="select-text cursor-text">{response.url}</span>
|
||||
{openUrl != null && (
|
||||
<IconButton
|
||||
iconSize="sm"
|
||||
className="inline-block w-auto h-auto! opacity-50 hover:opacity-100"
|
||||
icon="external_link"
|
||||
onClick={() => openUrl(response.url)}
|
||||
title="Open in browser"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</KeyValueRow>,
|
||||
<KeyValueRow key="remote" labelColor="secondary" label="Remote Address">
|
||||
{response.remoteAddr ?? <span className="text-text-subtlest">--</span>}
|
||||
</KeyValueRow>,
|
||||
<KeyValueRow key="version" labelColor="secondary" label="Version">
|
||||
{response.version ?? <span className="text-text-subtlest">--</span>}
|
||||
</KeyValueRow>,
|
||||
...(infoRows ?? []),
|
||||
]}
|
||||
</KeyValueRows>
|
||||
</DetailsBanner>
|
||||
<HeadersTable
|
||||
title="Request Headers"
|
||||
headers={response.requestHeaders}
|
||||
labelColor="primary"
|
||||
storageKey={`${response.ownerId}.request_headers`}
|
||||
useStoredValue={useDetailsBannerStoredValue}
|
||||
/>
|
||||
<HeadersTable
|
||||
defaultOpen
|
||||
title="Response Headers"
|
||||
headers={response.headers}
|
||||
labelColor="info"
|
||||
storageKey={`${response.ownerId}.response_headers`}
|
||||
useStoredValue={useDetailsBannerStoredValue}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A row that copies its value with the host's clipboard */
|
||||
export function KeyValueRow(props: Omit<KeyValueRowProps, "copy">) {
|
||||
const { copy } = useEditorHost();
|
||||
return <BaseKeyValueRow {...props} copy={copy} />;
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import classNames from "classnames";
|
||||
import type { FormEvent, ReactNode } from "react";
|
||||
import { memo, useCallback, useRef, useState } from "react";
|
||||
import type { HotkeyAction } from "../../hooks/useHotKey";
|
||||
import { useFormattedHotkey, useHotKey } from "../../hooks/useHotKey";
|
||||
import type { HostInputProps } from "../EditorHost";
|
||||
import { useEditorHost } from "../EditorHost";
|
||||
import type { IconProps } from "../Icon";
|
||||
import { IconButton } from "../IconButton";
|
||||
import type { InputHandle } from "../Input";
|
||||
import { HStack } from "../Stacks";
|
||||
|
||||
export type UrlBarProps = {
|
||||
url: string;
|
||||
className?: string;
|
||||
placeholder: string;
|
||||
onSend?: () => void;
|
||||
onUrlChange?: (url: string) => void;
|
||||
onPaste?: (v: string) => void;
|
||||
onPasteOverwrite?: HostInputProps["onPasteOverwrite"];
|
||||
onCancel?: () => void;
|
||||
submitIcon?: IconProps["icon"] | null;
|
||||
isLoading?: boolean;
|
||||
forceUpdateKey: string;
|
||||
rightSlot?: ReactNode;
|
||||
leftSlot?: ReactNode;
|
||||
autocomplete?: HostInputProps["autocomplete"];
|
||||
stateKey: HostInputProps["stateKey"];
|
||||
/** Show the URL without a way to change or send it */
|
||||
readOnly?: boolean;
|
||||
/** The action whose keys send, shown on the send button */
|
||||
sendHotkeyAction?: HotkeyAction;
|
||||
/** The action whose keys select the whole URL */
|
||||
focusHotkeyAction?: HotkeyAction;
|
||||
};
|
||||
|
||||
export const UrlBar = memo(function UrlBar({
|
||||
forceUpdateKey,
|
||||
onUrlChange,
|
||||
url,
|
||||
placeholder,
|
||||
className,
|
||||
onSend,
|
||||
onCancel,
|
||||
onPaste,
|
||||
onPasteOverwrite,
|
||||
submitIcon = "send_horizontal",
|
||||
autocomplete,
|
||||
leftSlot,
|
||||
rightSlot,
|
||||
isLoading = false,
|
||||
stateKey,
|
||||
readOnly,
|
||||
sendHotkeyAction,
|
||||
focusHotkeyAction,
|
||||
}: UrlBarProps) {
|
||||
const { Input } = useEditorHost();
|
||||
const inputRef = useRef<InputHandle>(null);
|
||||
const [isFocused, setIsFocused] = useState<boolean>(false);
|
||||
|
||||
const handleInitInputRef = useCallback((h: InputHandle | null) => {
|
||||
inputRef.current = h;
|
||||
}, []);
|
||||
|
||||
useHotKey(focusHotkeyAction ?? null, () => {
|
||||
inputRef.current?.selectAll();
|
||||
});
|
||||
|
||||
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (readOnly) return;
|
||||
if (isLoading) onCancel?.();
|
||||
else onSend?.();
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className={classNames("x-theme-urlBar", className)}>
|
||||
<Input
|
||||
setRef={handleInitInputRef}
|
||||
autocompleteFunctions
|
||||
autocompleteVariables
|
||||
stateKey={stateKey}
|
||||
size="sm"
|
||||
wrapLines={isFocused}
|
||||
hideLabel
|
||||
language="url"
|
||||
className="px-1.5 py-0.5"
|
||||
label="Enter URL"
|
||||
name="url"
|
||||
autocomplete={autocomplete}
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
onFocus={() => setIsFocused(true)}
|
||||
onBlur={() => setIsFocused(false)}
|
||||
onPaste={onPaste}
|
||||
onPasteOverwrite={onPasteOverwrite}
|
||||
onChange={onUrlChange}
|
||||
readOnly={readOnly}
|
||||
defaultValue={url}
|
||||
placeholder={placeholder}
|
||||
leftSlot={leftSlot}
|
||||
rightSlot={
|
||||
<HStack space={0.5}>
|
||||
{rightSlot && <div className="py-0.5 h-full">{rightSlot}</div>}
|
||||
{submitIcon !== null && !readOnly && (
|
||||
<div className="py-0.5 h-full">
|
||||
<SendButton
|
||||
icon={isLoading ? "x" : submitIcon}
|
||||
hotkeyAction={sendHotkeyAction ?? null}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</HStack>
|
||||
}
|
||||
/>
|
||||
</form>
|
||||
);
|
||||
});
|
||||
|
||||
function SendButton({
|
||||
icon,
|
||||
hotkeyAction,
|
||||
}: {
|
||||
icon: IconProps["icon"];
|
||||
hotkeyAction: HotkeyAction | null;
|
||||
}) {
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
const hotkeyTrigger = useFormattedHotkey(hotkeyAction)?.join("");
|
||||
useHotKey(hotkeyAction, () => buttonRef.current?.click());
|
||||
|
||||
return (
|
||||
<IconButton
|
||||
ref={buttonRef}
|
||||
size="xs"
|
||||
iconSize="md"
|
||||
title={hotkeyTrigger ? `Send Request ${hotkeyTrigger}` : "Send Request"}
|
||||
type="submit"
|
||||
className="w-8 mr-0.5 h-full!"
|
||||
iconColor="secondary"
|
||||
icon={icon}
|
||||
onMouseDown={(e) => {
|
||||
// Prevent the button from taking focus
|
||||
e.preventDefault();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { EditablePair, PairEditorHandle, PairEditorProps } from "../pairs/PairEditor";
|
||||
import { PairOrBulkEditor } from "../pairs/PairOrBulkEditor";
|
||||
import { VStack } from "../Stacks";
|
||||
|
||||
type Props = {
|
||||
forceUpdateKey: string;
|
||||
pairs: EditablePair[];
|
||||
stateKey: PairEditorProps["stateKey"];
|
||||
onChange?: PairEditorProps["onChange"];
|
||||
/** Show the parameters without a way to change them */
|
||||
readOnly?: boolean;
|
||||
setRef?: (handle: PairEditorHandle) => void;
|
||||
};
|
||||
|
||||
export function UrlParametersEditor({
|
||||
pairs,
|
||||
forceUpdateKey,
|
||||
onChange = ignoreChange,
|
||||
readOnly,
|
||||
setRef,
|
||||
stateKey,
|
||||
}: Props) {
|
||||
return (
|
||||
<VStack className="h-full">
|
||||
<PairOrBulkEditor
|
||||
setRef={setRef}
|
||||
allowMultilineValues
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
nameAutocompleteFunctions
|
||||
nameAutocompleteVariables
|
||||
namePlaceholder="param_name"
|
||||
onChange={onChange}
|
||||
pairs={pairs}
|
||||
preferenceName="url_parameters"
|
||||
readOnly={readOnly}
|
||||
stateKey={stateKey}
|
||||
valueAutocompleteFunctions
|
||||
valueAutocompleteVariables
|
||||
valuePlaceholder="Value"
|
||||
/>
|
||||
</VStack>
|
||||
);
|
||||
}
|
||||
|
||||
function ignoreChange() {}
|
||||
@@ -0,0 +1,247 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import type { HostEditorProps, HostInputProps, SelectFileProps } from "../EditorHost";
|
||||
import { EditorHostProvider } from "../EditorHost";
|
||||
import { PairEditorRow } from "../pairs/PairEditor";
|
||||
import { bodyTypeLabel } from "./HttpRequestPaneView";
|
||||
import { ResponseStatusLine } from "./HttpResponsePaneView";
|
||||
import { JsonBodyEditor } from "./JsonBodyEditor";
|
||||
import { RequestBodyViewer } from "./RequestBodyViewer";
|
||||
import { HTMLOrTextViewer } from "./ResponseBodyViewer";
|
||||
import { RequestMethodDropdown } from "./RequestMethodDropdown";
|
||||
import { parseCookieHeaders } from "./ResponseCookies";
|
||||
import {
|
||||
BODY_TYPE_FORM_URLENCODED,
|
||||
BODY_TYPE_JSON,
|
||||
BODY_TYPE_OTHER,
|
||||
type HttpBodyLoader,
|
||||
type HttpResponseView,
|
||||
} from "./types";
|
||||
import { UrlBar } from "./UrlBar";
|
||||
|
||||
// Stand-ins for the host's editors that show what they were given
|
||||
function StubInput({ name, defaultValue, readOnly, rightSlot, leftSlot }: HostInputProps) {
|
||||
return (
|
||||
<div data-input={name} data-readonly={String(!!readOnly)}>
|
||||
{leftSlot}
|
||||
{defaultValue}
|
||||
{rightSlot}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StubEditor({ defaultValue, readOnly, actions }: HostEditorProps) {
|
||||
return (
|
||||
<div data-editor data-readonly={String(!!readOnly)}>
|
||||
{defaultValue}
|
||||
{actions}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StubSelectFile({ filePath }: SelectFileProps) {
|
||||
return (
|
||||
<button type="button" data-picker>
|
||||
{filePath}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function render(node: ReactNode) {
|
||||
return renderToStaticMarkup(
|
||||
<EditorHostProvider value={{ Input: StubInput, Editor: StubEditor }}>
|
||||
{node}
|
||||
</EditorHostProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("read-only modes", () => {
|
||||
test("a pair row shows its fields read-only, with no drag handle or row menu", () => {
|
||||
const markup = render(
|
||||
<PairEditorRow
|
||||
readOnly
|
||||
index={0}
|
||||
stateKey="test"
|
||||
pair={{ id: "p1", enabled: true, name: "Accept", value: "*/*" }}
|
||||
/>,
|
||||
);
|
||||
expect(markup).toContain('data-input="name[0]" data-readonly="true"');
|
||||
expect(markup).toContain('data-input="value[0]" data-readonly="true"');
|
||||
expect(markup).not.toContain("More actions");
|
||||
expect(markup).toMatch(/<input[^>]*disabled/);
|
||||
});
|
||||
|
||||
test("a read-only file value shows as text, not a file picker", () => {
|
||||
const pair = {
|
||||
id: "p1",
|
||||
enabled: true,
|
||||
name: "avatar",
|
||||
value: "/Users/me/avatar.png",
|
||||
isFile: true,
|
||||
};
|
||||
const host = { Input: StubInput, Editor: StubEditor, SelectFile: StubSelectFile };
|
||||
const readOnly = renderToStaticMarkup(
|
||||
<EditorHostProvider value={host}>
|
||||
<PairEditorRow readOnly allowFileValues index={0} stateKey="test" pair={pair} />
|
||||
</EditorHostProvider>,
|
||||
);
|
||||
expect(readOnly).not.toContain("data-picker");
|
||||
expect(readOnly).toContain("data-file-value");
|
||||
expect(readOnly).toContain("/Users/me/avatar.png");
|
||||
|
||||
const editable = renderToStaticMarkup(
|
||||
<EditorHostProvider value={host}>
|
||||
<PairEditorRow allowFileValues index={0} stateKey="test" pair={pair} />
|
||||
</EditorHostProvider>,
|
||||
);
|
||||
expect(editable).toContain("data-picker");
|
||||
});
|
||||
|
||||
test("an editable pair row keeps its row menu", () => {
|
||||
const markup = render(
|
||||
<PairEditorRow
|
||||
index={0}
|
||||
stateKey="test"
|
||||
pair={{ id: "p1", enabled: true, name: "Accept", value: "*/*" }}
|
||||
/>,
|
||||
);
|
||||
expect(markup).toContain('data-input="name[0]" data-readonly="false"');
|
||||
expect(markup).toContain("More actions");
|
||||
});
|
||||
|
||||
test("the URL bar has no send button when read-only", () => {
|
||||
const readOnly = render(
|
||||
<UrlBar url="https://yaak.app" placeholder="" forceUpdateKey="" stateKey={null} readOnly />,
|
||||
);
|
||||
expect(readOnly).toContain('data-input="url" data-readonly="true"');
|
||||
expect(readOnly).not.toContain("Send Request");
|
||||
|
||||
const editable = render(
|
||||
<UrlBar url="https://yaak.app" placeholder="" forceUpdateKey="" stateKey={null} />,
|
||||
);
|
||||
expect(editable).toContain("Send Request");
|
||||
});
|
||||
|
||||
test("the method shows without a menu when read-only", () => {
|
||||
const readOnly = render(<RequestMethodDropdown method="POST" readOnly />);
|
||||
const editable = render(<RequestMethodDropdown method="POST" onChange={() => {}} />);
|
||||
expect(readOnly).toContain("POST");
|
||||
expect(readOnly).not.toEqual(editable);
|
||||
});
|
||||
|
||||
test("a read-only JSON body has no settings menu", () => {
|
||||
const props = {
|
||||
forceUpdateKey: "",
|
||||
heightMode: "auto" as const,
|
||||
requestId: "r1",
|
||||
text: '{"a":1}',
|
||||
sendJsonComments: false,
|
||||
noticeStorageKey: "w1",
|
||||
};
|
||||
const readOnly = render(<JsonBodyEditor {...props} readOnly />);
|
||||
expect(readOnly).toContain('data-readonly="true"');
|
||||
expect(readOnly).not.toContain("JSON Settings");
|
||||
|
||||
const editable = render(<JsonBodyEditor {...props} onChange={() => {}} />);
|
||||
expect(editable).toContain("JSON Settings");
|
||||
});
|
||||
});
|
||||
|
||||
describe("RequestBodyViewer", () => {
|
||||
// A captured body that isn't valid UTF-8 has bytes but no text
|
||||
const binary: HttpBodyLoader = {
|
||||
useText: () => ({ data: null, isLoading: false, error: null }),
|
||||
useBytes: () => ({ data: new Uint8Array([0x89, 0x50, 0xff]), isLoading: false, error: null }),
|
||||
useUrl: () => ({ data: null, isLoading: false, error: null }),
|
||||
};
|
||||
|
||||
test("shows a binary body instead of calling it empty", () => {
|
||||
const markup = render(
|
||||
<RequestBodyViewer id="b1" contentType="application/octet-stream" body={binary} />,
|
||||
);
|
||||
expect(markup).not.toContain("No request body");
|
||||
expect(markup).toContain("Binary body, 3");
|
||||
});
|
||||
|
||||
test("hands a binary image to the image viewer", () => {
|
||||
const markup = render(<RequestBodyViewer id="b2" contentType="image/png" body={binary} />);
|
||||
expect(markup).not.toContain("No request body");
|
||||
expect(markup).not.toContain("Binary body");
|
||||
});
|
||||
});
|
||||
|
||||
describe("HTMLOrTextViewer", () => {
|
||||
const response = {
|
||||
id: "rs_1",
|
||||
ownerId: "rq_1",
|
||||
state: "closed",
|
||||
status: 200,
|
||||
statusReason: "OK",
|
||||
url: "https://yaak.app",
|
||||
headers: [],
|
||||
requestHeaders: [],
|
||||
contentType: "application/octet-stream",
|
||||
contentLength: 3,
|
||||
contentLengthCompressed: null,
|
||||
requestContentLength: 0,
|
||||
startedAt: "2026-11-04T22:10:00Z",
|
||||
elapsedMs: 1,
|
||||
elapsedHeadersMs: 1,
|
||||
elapsedDnsMs: 0,
|
||||
error: null,
|
||||
remoteAddr: null,
|
||||
version: null,
|
||||
cookieHeaders: { sent: [], received: [] },
|
||||
} satisfies HttpResponseView;
|
||||
|
||||
function loader(bytes: Uint8Array): HttpBodyLoader {
|
||||
return {
|
||||
useText: () => ({ data: null, isLoading: false, error: null }),
|
||||
useBytes: () => ({ data: bytes, isLoading: false, error: null }),
|
||||
useUrl: () => ({ data: null, isLoading: false, error: null }),
|
||||
};
|
||||
}
|
||||
|
||||
test("tells a binary response from an empty one", () => {
|
||||
const binary = render(
|
||||
<HTMLOrTextViewer response={response} body={loader(new Uint8Array([0xff, 0, 1]))} pretty />,
|
||||
);
|
||||
expect(binary).toContain("Binary body, 3");
|
||||
|
||||
const empty = render(
|
||||
<HTMLOrTextViewer response={response} body={loader(new Uint8Array())} pretty />,
|
||||
);
|
||||
expect(empty).toContain("Empty response");
|
||||
});
|
||||
|
||||
test("the status line keeps its height without the client's history button", () => {
|
||||
// The client's button sets the line's height; without it, the line would hug the card's top
|
||||
const markup = render(<ResponseStatusLine response={response} />);
|
||||
expect(markup).toContain("min-h-[calc(var(--height-sm)+0.25rem)]");
|
||||
});
|
||||
});
|
||||
|
||||
describe("bodyTypeLabel", () => {
|
||||
test("names a body by its type", () => {
|
||||
expect(bodyTypeLabel(BODY_TYPE_JSON, "application/json")).toBe("JSON");
|
||||
expect(bodyTypeLabel(BODY_TYPE_FORM_URLENCODED, null)).toBe("Url Encoded");
|
||||
expect(bodyTypeLabel(BODY_TYPE_OTHER, "text/markdown")).toBe("Markdown");
|
||||
expect(bodyTypeLabel(null, null)).toBe("Body");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseCookieHeaders", () => {
|
||||
test("splits sent cookies and parses received ones, the latest of a name winning", () => {
|
||||
const { sentCookies, receivedCookies } = parseCookieHeaders({
|
||||
sent: ["a=1; b=2", "a=3"],
|
||||
received: ["s=x; Path=/; HttpOnly", "gone=; Max-Age=0"],
|
||||
});
|
||||
expect(sentCookies).toEqual([
|
||||
{ name: "a", value: "3" },
|
||||
{ name: "b", value: "2" },
|
||||
]);
|
||||
expect(receivedCookies[0]).toMatchObject({ name: "s", value: "x", path: "/", httpOnly: true });
|
||||
expect(receivedCookies[1]).toMatchObject({ name: "gone", isDeleted: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* What the shared request and response panes render. Each app maps its own models onto these
|
||||
* (the client its `HttpRequest` and `HttpResponse`, the proxy a captured `Flow`), so the panes
|
||||
* never import either app's model types.
|
||||
*/
|
||||
|
||||
export const BODY_TYPE_NONE = null;
|
||||
export const BODY_TYPE_GRAPHQL = "graphql";
|
||||
export const BODY_TYPE_JSON = "application/json";
|
||||
export const BODY_TYPE_BINARY = "binary";
|
||||
export const BODY_TYPE_OTHER = "other";
|
||||
export const BODY_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded";
|
||||
export const BODY_TYPE_FORM_MULTIPART = "multipart/form-data";
|
||||
export const BODY_TYPE_XML = "text/xml";
|
||||
|
||||
/** A header, URL parameter or form field */
|
||||
export interface HttpPairView {
|
||||
id?: string;
|
||||
name: string;
|
||||
value: string;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
/** A form field. A multipart file field has the file's path in `file` instead of a `value` */
|
||||
export interface HttpFormFieldView {
|
||||
id?: string;
|
||||
name: string;
|
||||
value?: string;
|
||||
enabled?: boolean;
|
||||
file?: string;
|
||||
contentType?: string;
|
||||
filename?: string;
|
||||
}
|
||||
|
||||
/** A request body, in the shape its body type edits it */
|
||||
export interface HttpRequestBodyView {
|
||||
/** Text bodies: JSON, XML, GraphQL's query, anything else typed */
|
||||
text?: string;
|
||||
/** Form bodies, url-encoded or multipart */
|
||||
form?: HttpFormFieldView[];
|
||||
/** A binary body read from a file when sent */
|
||||
filePath?: string;
|
||||
/** JSON sent as written, comments and all, instead of cleaned up first */
|
||||
sendJsonComments?: boolean;
|
||||
}
|
||||
|
||||
/** Authentication, for display only; editing it stays with the app that knows its plugins */
|
||||
export interface HttpAuthView {
|
||||
/** The scheme's name, like `Bearer` or `Basic` */
|
||||
label: string;
|
||||
/** What it sends, like an `Authorization` header */
|
||||
values: HttpPairView[];
|
||||
}
|
||||
|
||||
export interface HttpRequestView {
|
||||
/** Identifies the request across renders, for remembered tabs and editor state */
|
||||
id: string;
|
||||
method: string;
|
||||
url: string;
|
||||
headers: HttpPairView[];
|
||||
urlParameters: HttpPairView[];
|
||||
/** One of the `BODY_TYPE_*` values, or a content type the body was typed as */
|
||||
bodyType: string | null;
|
||||
body: HttpRequestBodyView;
|
||||
/** The request's Content-Type header */
|
||||
contentType: string | null;
|
||||
auth: HttpAuthView | null;
|
||||
}
|
||||
|
||||
export type HttpResponseViewState = "initialized" | "connected" | "closed";
|
||||
|
||||
export interface HttpResponseView {
|
||||
/** Identifies this response, for viewer state */
|
||||
id: string;
|
||||
/** Identifies what it answers (the request or flow), for state kept across responses */
|
||||
ownerId: string;
|
||||
state: HttpResponseViewState;
|
||||
/** 0 before a status arrives or when it never did */
|
||||
status: number;
|
||||
statusReason: string | null;
|
||||
url: string;
|
||||
headers: HttpPairView[];
|
||||
requestHeaders: HttpPairView[];
|
||||
/** The response's Content-Type header */
|
||||
contentType: string | null;
|
||||
/** Decoded body bytes */
|
||||
contentLength: number | null;
|
||||
/** Body bytes on the wire, when it was compressed */
|
||||
contentLengthCompressed: number | null;
|
||||
/** Request body bytes sent */
|
||||
requestContentLength: number | null;
|
||||
/** When the request started, as an ISO 8601 string with its zone */
|
||||
startedAt: string;
|
||||
elapsedMs: number;
|
||||
elapsedHeadersMs: number;
|
||||
elapsedDnsMs: number;
|
||||
error: string | null;
|
||||
remoteAddr: string | null;
|
||||
version: string | null;
|
||||
/** Raw `Cookie` header values sent and `Set-Cookie` values received */
|
||||
cookieHeaders: { sent: string[]; received: string[] };
|
||||
}
|
||||
|
||||
/** What a viewer gets back from loading part of a body */
|
||||
export interface HttpBodyResult<T> {
|
||||
data: T | undefined;
|
||||
isLoading: boolean;
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* How a pane reads a body, which each app stores its own way: the client in files read
|
||||
* through its host, the proxy through the engine's body RPC. Each `use*` is a hook, called
|
||||
* unconditionally by the viewer that needs that form of the body.
|
||||
*/
|
||||
export interface HttpBodyLoader {
|
||||
/** The body as text, null when there's none */
|
||||
useText: () => HttpBodyResult<string | null>;
|
||||
/** The body's bytes, null when there's none */
|
||||
useBytes: () => HttpBodyResult<Uint8Array | null>;
|
||||
/** A URL a media element can load the body from, null when there's none or not `enabled` */
|
||||
useUrl: (enabled: boolean) => HttpBodyResult<string | null>;
|
||||
/** Run a JSONPath or XPath filter over the body */
|
||||
filterText?: (expression: string) => Promise<string | null>;
|
||||
/** The body's text, for copying, without rendering it */
|
||||
getText?: () => Promise<string | null>;
|
||||
}
|
||||
Loaded 100 of 794 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user