mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-08-14 15:42:02 +02:00
Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e2db7799b | ||
|
|
c596e25e5e | ||
|
|
74d1b5d6ce | ||
|
|
b9d4f76193 | ||
|
|
d4a963e216 | ||
|
|
be765d7bcc | ||
|
|
d43de3d95a | ||
|
|
bc0494fe0e | ||
|
|
c57a64d455 | ||
|
|
5bebd74b09 | ||
|
|
a6dd058a3d | ||
|
|
1fe8261fbd | ||
|
|
0e4c355e8b | ||
|
|
f6d926f4b9 | ||
|
|
a6be9dbaee | ||
|
|
67a628d67a | ||
|
|
0bf7eaed81 | ||
|
|
784a3d3a32 | ||
|
|
077bfa87b8 | ||
|
|
733f2e5929 | ||
|
|
0f994f89ac | ||
|
|
24f76398f9 | ||
|
|
14475915df | ||
|
|
a50e04f565 | ||
|
|
32fbd66912 | ||
|
|
3503a9da8e | ||
|
|
cef6abf5d0 | ||
|
|
3f098f95fe | ||
|
|
195f89337f | ||
|
|
57fffe5a41 | ||
|
|
0c24d6562a | ||
|
|
b1ea3e3560 | ||
|
|
d72b7d7d30 | ||
|
|
b40e2cdc1b | ||
|
|
19cc6ee6d4 | ||
|
|
e59ecce886 | ||
|
|
c30f5b767b | ||
|
|
42b22d4c07 | ||
|
|
e05feba708 | ||
|
|
6b9b3660de |
@@ -630,6 +630,22 @@ async function checkPullRequest({
|
||||
const pr = response.data;
|
||||
const issueNumber = pr.number;
|
||||
|
||||
if (pr.user.type === "Bot") {
|
||||
core.notice(
|
||||
`Skipping contribution policy for bot PR #${pr.number} from @${pr.user.login}.`,
|
||||
);
|
||||
return {
|
||||
blocked: false,
|
||||
number: pr.number,
|
||||
summary: summarizeResult({
|
||||
pr,
|
||||
skipped: true,
|
||||
skipReason: `bot @${pr.user.login}`,
|
||||
}),
|
||||
skipped: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
minimumAutomaticPullNumber != null &&
|
||||
pr.number < minimumAutomaticPullNumber
|
||||
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
node-version: "24"
|
||||
|
||||
- name: Install source generators
|
||||
run: |
|
||||
|
||||
@@ -58,3 +58,4 @@ flatpak/node-sources.json
|
||||
|
||||
# Claude Code local settings
|
||||
.claude/settings.local.json
|
||||
.claude/worktrees/
|
||||
|
||||
Generated
+68
-11
@@ -862,6 +862,15 @@ dependencies = [
|
||||
"alloc-stdlib",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bs58"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"
|
||||
dependencies = [
|
||||
"tinyvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bstr"
|
||||
version = "1.12.1"
|
||||
@@ -1752,8 +1761,18 @@ version = "0.20.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"darling_macro",
|
||||
"darling_core 0.20.11",
|
||||
"darling_macro 0.20.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.23.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"
|
||||
dependencies = [
|
||||
"darling_core 0.23.0",
|
||||
"darling_macro 0.23.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1763,6 +1782,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"
|
||||
dependencies = [
|
||||
"fnv",
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.101",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_core"
|
||||
version = "0.23.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0"
|
||||
dependencies = [
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -1776,7 +1807,18 @@ version = "0.20.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
|
||||
dependencies = [
|
||||
"darling_core",
|
||||
"darling_core 0.20.11",
|
||||
"quote",
|
||||
"syn 2.0.101",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.23.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"
|
||||
dependencies = [
|
||||
"darling_core 0.23.0",
|
||||
"quote",
|
||||
"syn 2.0.101",
|
||||
]
|
||||
@@ -7316,6 +7358,18 @@ dependencies = [
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schemars"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f"
|
||||
dependencies = [
|
||||
"dyn-clone",
|
||||
"ref-cast",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schemars"
|
||||
version = "1.2.1"
|
||||
@@ -7384,7 +7438,7 @@ version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bae0cbad6ab996955664982739354128c58d16e126114fe88c2a493642502aab"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"darling 0.20.11",
|
||||
"heck 0.4.1",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -7653,17 +7707,19 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "serde_with"
|
||||
version = "3.12.0"
|
||||
version = "3.21.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6b6f7f2fcb69f747921f79f3926bd1e203fce4fef62c268dd3abfb6d86029aa"
|
||||
checksum = "76a5c54c7310e7b8b9577c286d7e399ddd876c3e12b3ed917a8aabc4b96e9e8c"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bs58",
|
||||
"chrono",
|
||||
"hex",
|
||||
"indexmap 1.9.3",
|
||||
"indexmap 2.14.0",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"schemars 0.9.0",
|
||||
"schemars 1.2.1",
|
||||
"serde_core",
|
||||
"serde_json",
|
||||
"serde_with_macros",
|
||||
"time",
|
||||
@@ -7671,11 +7727,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "serde_with_macros"
|
||||
version = "3.12.0"
|
||||
version = "3.21.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d00caa5193a3c8362ac2b73be6b9e768aa5a4b2f721d8f4b339600c3cb51f8e"
|
||||
checksum = "84d57bc0c8b9a17920c178daa6bb924850d54a9c97ab45194bb8c17ad66bb660"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"darling 0.23.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.101",
|
||||
@@ -10926,6 +10982,7 @@ dependencies = [
|
||||
name = "yaak-app-client"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"charset",
|
||||
"chrono",
|
||||
"cookie",
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
<!-- sponsors-premium --><a href="https://github.com/MVST-Solutions"><img src="https://github.com/MVST-Solutions.png" width="80px" alt="User avatar: MVST-Solutions" /></a> <a href="https://github.com/dharsanb"><img src="https://github.com/dharsanb.png" width="80px" alt="User avatar: dharsanb" /></a> <a href="https://github.com/railwayapp"><img src="https://github.com/railwayapp.png" width="80px" alt="User avatar: railwayapp" /></a> <a href="https://github.com/caseyamcl"><img src="https://github.com/caseyamcl.png" width="80px" alt="User avatar: caseyamcl" /></a> <a href="https://github.com/bytebase"><img src="https://github.com/bytebase.png" width="80px" alt="User avatar: bytebase" /></a> <a href="https://github.com/"><img src="https://raw.githubusercontent.com/JamesIves/github-sponsors-readme-action/dev/.github/assets/placeholder.png" width="80px" alt="User avatar: " /></a> <!-- sponsors-premium -->
|
||||
</p>
|
||||
<p align="center">
|
||||
<!-- sponsors-base --><a href="https://github.com/seanwash"><img src="https://github.com/seanwash.png" width="50px" alt="User avatar: seanwash" /></a> <a href="https://github.com/jerath"><img src="https://github.com/jerath.png" width="50px" alt="User avatar: jerath" /></a> <a href="https://github.com/itsa-sh"><img src="https://github.com/itsa-sh.png" width="50px" alt="User avatar: itsa-sh" /></a> <a href="https://github.com/dmmulroy"><img src="https://github.com/dmmulroy.png" width="50px" alt="User avatar: dmmulroy" /></a> <a href="https://github.com/timcole"><img src="https://github.com/timcole.png" width="50px" alt="User avatar: timcole" /></a> <a href="https://github.com/VLZH"><img src="https://github.com/VLZH.png" width="50px" alt="User avatar: VLZH" /></a> <a href="https://github.com/terasaka2k"><img src="https://github.com/terasaka2k.png" width="50px" alt="User avatar: terasaka2k" /></a> <a href="https://github.com/andriyor"><img src="https://github.com/andriyor.png" width="50px" alt="User avatar: andriyor" /></a> <a href="https://github.com/majudhu"><img src="https://github.com/majudhu.png" width="50px" alt="User avatar: majudhu" /></a> <a href="https://github.com/axelrindle"><img src="https://github.com/axelrindle.png" width="50px" alt="User avatar: axelrindle" /></a> <a href="https://github.com/jirizverina"><img src="https://github.com/jirizverina.png" width="50px" alt="User avatar: jirizverina" /></a> <a href="https://github.com/chip-well"><img src="https://github.com/chip-well.png" width="50px" alt="User avatar: chip-well" /></a> <a href="https://github.com/GRAYAH"><img src="https://github.com/GRAYAH.png" width="50px" alt="User avatar: GRAYAH" /></a> <a href="https://github.com/flashblaze"><img src="https://github.com/flashblaze.png" width="50px" alt="User avatar: flashblaze" /></a> <a href="https://github.com/Frostist"><img src="https://github.com/Frostist.png" width="50px" alt="User avatar: Frostist" /></a> <!-- sponsors-base -->
|
||||
<!-- sponsors-base --><a href="https://github.com/seanwash"><img src="https://github.com/seanwash.png" width="50px" alt="User avatar: seanwash" /></a> <a href="https://github.com/jerath"><img src="https://github.com/jerath.png" width="50px" alt="User avatar: jerath" /></a> <a href="https://github.com/itsa-sh"><img src="https://github.com/itsa-sh.png" width="50px" alt="User avatar: itsa-sh" /></a> <a href="https://github.com/dmmulroy"><img src="https://github.com/dmmulroy.png" width="50px" alt="User avatar: dmmulroy" /></a> <a href="https://github.com/timcole"><img src="https://github.com/timcole.png" width="50px" alt="User avatar: timcole" /></a> <a href="https://github.com/VLZH"><img src="https://github.com/VLZH.png" width="50px" alt="User avatar: VLZH" /></a> <a href="https://github.com/terasaka2k"><img src="https://github.com/terasaka2k.png" width="50px" alt="User avatar: terasaka2k" /></a> <a href="https://github.com/andriyor"><img src="https://github.com/andriyor.png" width="50px" alt="User avatar: andriyor" /></a> <a href="https://github.com/majudhu"><img src="https://github.com/majudhu.png" width="50px" alt="User avatar: majudhu" /></a> <a href="https://github.com/axelrindle"><img src="https://github.com/axelrindle.png" width="50px" alt="User avatar: axelrindle" /></a> <a href="https://github.com/jirizverina"><img src="https://github.com/jirizverina.png" width="50px" alt="User avatar: jirizverina" /></a> <a href="https://github.com/chip-well"><img src="https://github.com/chip-well.png" width="50px" alt="User avatar: chip-well" /></a> <a href="https://github.com/GRAYAH"><img src="https://github.com/GRAYAH.png" width="50px" alt="User avatar: GRAYAH" /></a> <a href="https://github.com/flashblaze"><img src="https://github.com/flashblaze.png" width="50px" alt="User avatar: flashblaze" /></a> <a href="https://github.com/Frostist"><img src="https://github.com/Frostist.png" width="50px" alt="User avatar: Frostist" /></a> <a href="https://github.com/PurplProto"><img src="https://github.com/PurplProto.png" width="50px" alt="User avatar: PurplProto" /></a> <!-- sponsors-base -->
|
||||
</p>
|
||||
|
||||

|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useAtomValue } from "jotai";
|
||||
import { contextMenusAtom, hideContextMenu } from "../lib/contextMenu";
|
||||
import { ContextMenu } from "./core/Dropdown";
|
||||
import { ErrorBoundary } from "./ErrorBoundary";
|
||||
|
||||
/** Renders menus opened by {@link showContextMenu}, the way {@link Dialogs} renders dialogs. */
|
||||
export function ContextMenus() {
|
||||
const menus = useAtomValue(contextMenusAtom);
|
||||
return (
|
||||
<>
|
||||
{menus.map(({ id, items, triggerPosition, triggerRect, triggerEl }) => (
|
||||
<ErrorBoundary key={id} name={`ContextMenu ${id}`}>
|
||||
<ContextMenu
|
||||
items={items}
|
||||
triggerPosition={triggerPosition}
|
||||
triggerRect={triggerRect}
|
||||
// The trigger isn't a React component here, so it arrives as an element and gets
|
||||
// wrapped to look like the ref the menu expects
|
||||
triggerRef={{ current: triggerEl ?? null }}
|
||||
onClose={() => hideContextMenu(id)}
|
||||
/>
|
||||
</ErrorBoundary>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
import { type GrpcRequest, type HttpRequestHeader, patchModel } from "@yaakapp-internal/models";
|
||||
import {
|
||||
type GrpcRequest,
|
||||
type HttpRequestHeader,
|
||||
patchModel,
|
||||
patchModelDebounced,
|
||||
} from "@yaakapp-internal/models";
|
||||
import { HStack, Icon, useContainerSize, VStack } from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import type { CSSProperties } from "react";
|
||||
@@ -75,11 +80,13 @@ export function GrpcRequestPane({
|
||||
const { width: paneWidth } = useContainerSize(urlContainerEl);
|
||||
|
||||
const handleChangeUrl = useCallback(
|
||||
(url: string) => patchModel(activeRequest, { url }),
|
||||
(url: string) => patchModelDebounced(activeRequest, { url }),
|
||||
[activeRequest],
|
||||
);
|
||||
|
||||
const handleChangeMessage = useCallback(
|
||||
// Not debounced: handleSend reads message from the store, so a pending
|
||||
// debounced patch would send stale text
|
||||
(message: string) => patchModel(activeRequest, { message }),
|
||||
[activeRequest],
|
||||
);
|
||||
@@ -146,12 +153,12 @@ export function GrpcRequestPane({
|
||||
);
|
||||
|
||||
const handleMetadataChange = useCallback(
|
||||
(metadata: HttpRequestHeader[]) => patchModel(activeRequest, { metadata }),
|
||||
(metadata: HttpRequestHeader[]) => patchModelDebounced(activeRequest, { metadata }),
|
||||
[activeRequest],
|
||||
);
|
||||
|
||||
const handleDescriptionChange = useCallback(
|
||||
(description: string) => patchModel(activeRequest, { description }),
|
||||
(description: string) => patchModelDebounced(activeRequest, { description }),
|
||||
[activeRequest],
|
||||
);
|
||||
|
||||
@@ -299,7 +306,7 @@ export function GrpcRequestPane({
|
||||
className="font-sans text-xl! px-0!"
|
||||
containerClassName="border-0"
|
||||
placeholder={resolvedModelName(activeRequest)}
|
||||
onChange={(name) => patchModel(activeRequest, { name })}
|
||||
onChange={(name) => patchModelDebounced(activeRequest, { name })}
|
||||
/>
|
||||
<MarkdownEditor
|
||||
name="request-description"
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import type { HttpRequestHeader } from "@yaakapp-internal/models";
|
||||
import type { GenericCompletionOption } from "@yaakapp-internal/plugins";
|
||||
import { HStack } from "@yaakapp-internal/ui";
|
||||
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 { CountBadge } from "./core/CountBadge";
|
||||
import { DetailsBanner } from "./core/DetailsBanner";
|
||||
import type { GenericCompletionConfig } from "./core/Editor/genericCompletion";
|
||||
import type { GenericCompletion, GenericCompletionConfig } from "./core/Editor/genericCompletion";
|
||||
import type { InputProps } from "./core/Input";
|
||||
import type { Pair, PairEditorProps } from "./core/PairEditor";
|
||||
import { PairEditorRow } from "./core/PairEditor";
|
||||
@@ -105,12 +108,21 @@ export function HeadersEditor({
|
||||
|
||||
const MIN_MATCH = 3;
|
||||
|
||||
const headerOptionsMap: Record<string, string[]> = {
|
||||
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"],
|
||||
};
|
||||
|
||||
const valueType = (pair: Pair): InputProps["type"] => {
|
||||
@@ -132,12 +144,22 @@ const valueType = (pair: Pair): InputProps["type"] => {
|
||||
|
||||
const valueAutocomplete = (headerName: string): GenericCompletionConfig | undefined => {
|
||||
const name = headerName.toLowerCase().trim();
|
||||
const options: GenericCompletionOption[] =
|
||||
headerOptionsMap[name]?.map((o) => ({
|
||||
label: o,
|
||||
type: "constant",
|
||||
boost: 1, // Put above other completions
|
||||
})) ?? [];
|
||||
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 };
|
||||
};
|
||||
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import type { HttpRequest } from "@yaakapp-internal/models";
|
||||
import { patchModel } from "@yaakapp-internal/models";
|
||||
import { getModel, patchModel, patchModelDebounced } from "@yaakapp-internal/models";
|
||||
import type { GenericCompletionOption } from "@yaakapp-internal/plugins";
|
||||
import classNames from "classnames";
|
||||
import { atom, useAtomValue } from "jotai";
|
||||
import type { CSSProperties } from "react";
|
||||
import { lazy, Suspense, useCallback, useMemo, useRef, useState } from "react";
|
||||
import { activeRequestIdAtom } from "../hooks/useActiveRequestId";
|
||||
import { allRequestsAtom } from "../hooks/useAllRequests";
|
||||
import { allRequestUrlsAtom } from "../hooks/useAllRequests";
|
||||
import { useAuthTab } from "../hooks/useAuthTab";
|
||||
import { useCancelHttpResponse } from "../hooks/useCancelHttpResponse";
|
||||
import { useHeadersTab } from "../hooks/useHeadersTab";
|
||||
@@ -16,10 +15,9 @@ import { usePinnedHttpResponse } from "../hooks/usePinnedHttpResponse";
|
||||
import { useRequestEditor, useRequestEditorEvent } from "../hooks/useRequestEditor";
|
||||
import { useRequestUpdateKey } from "../hooks/useRequestUpdateKey";
|
||||
import { useSendAnyHttpRequest } from "../hooks/useSendAnyHttpRequest";
|
||||
import { deepEqualAtom } from "../lib/atoms";
|
||||
import { languageFromContentType } from "../lib/contentType";
|
||||
import { generateId } from "../lib/generateId";
|
||||
import { extractPathPlaceholders } from "../lib/pathPlaceholders";
|
||||
import { derivePathPlaceholderPairs, renamePathPlaceholder } from "../lib/pathPlaceholders";
|
||||
import { convertRequestBody } from "../lib/requestBodyConversion";
|
||||
import {
|
||||
BODY_TYPE_BINARY,
|
||||
@@ -39,9 +37,9 @@ import { BinaryFileEditor } from "./BinaryFileEditor";
|
||||
import { ConfirmLargeRequestBody } from "./ConfirmLargeRequestBody";
|
||||
import { CountBadge } from "./core/CountBadge";
|
||||
import type { GenericCompletionConfig } from "./core/Editor/genericCompletion";
|
||||
import { getUrlCompletionConfig } from "./core/Editor/url/completion";
|
||||
import { Editor } from "./core/Editor/LazyEditor";
|
||||
import { InlineCode } from "@yaakapp-internal/ui";
|
||||
import type { Pair } from "./core/PairEditor";
|
||||
import { PlainInput } from "./core/PlainInput";
|
||||
import type { TabItem, TabsRef } from "./core/Tabs/Tabs";
|
||||
import { setActiveTab, TabContent, Tabs } from "./core/Tabs/Tabs";
|
||||
@@ -76,15 +74,12 @@ const TAB_SETTINGS = "settings";
|
||||
const TAB_DESCRIPTION = "description";
|
||||
const TABS_STORAGE_KEY = "http_request_tabs";
|
||||
|
||||
const nonActiveRequestUrlsAtom = atom((get) => {
|
||||
const activeRequestId = get(activeRequestIdAtom);
|
||||
const requests = get(allRequestsAtom);
|
||||
return requests
|
||||
.filter((r) => r.id !== activeRequestId)
|
||||
.map((r): GenericCompletionOption => ({ type: "constant", label: r.url }));
|
||||
});
|
||||
|
||||
const memoNotActiveRequestUrlsAtom = deepEqualAtom(nonActiveRequestUrlsAtom);
|
||||
// Derived from the identity-stable URL list so this only recomputes when a URL
|
||||
// actually changes. The active request's own URL is included, but exact matches
|
||||
// are filtered out at completion time by genericCompletion.
|
||||
const requestUrlOptionsAtom = atom((get): GenericCompletionOption[] =>
|
||||
get(allRequestUrlsAtom).map((url) => ({ type: "constant", label: url })),
|
||||
);
|
||||
|
||||
export function HttpRequestPane({ style, fullHeight, className, activeRequest }: Props) {
|
||||
const activeRequestId = activeRequest.id;
|
||||
@@ -132,20 +127,33 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
||||
[activeRequest],
|
||||
);
|
||||
|
||||
const { urlParameterPairs, urlParametersKey } = useMemo(() => {
|
||||
const placeholderNames = extractPathPlaceholders(activeRequest.url);
|
||||
const nonEmptyParameters = activeRequest.urlParameters.filter((p) => p.name || p.value);
|
||||
const items: Pair[] = [...nonEmptyParameters];
|
||||
for (const name of placeholderNames) {
|
||||
const item = items.find((p) => p.name === name);
|
||||
if (item) {
|
||||
item.readOnlyName = true;
|
||||
} else {
|
||||
items.push({ name, value: "", enabled: true, readOnlyName: true, id: generateId() });
|
||||
}
|
||||
}
|
||||
return { urlParameterPairs: items, urlParametersKey: placeholderNames.join(",") };
|
||||
}, [activeRequest.url, activeRequest.urlParameters]);
|
||||
// Renaming a path placeholder has to rewrite the URL and rename the parameter together, or the
|
||||
// value detaches from the placeholder.
|
||||
// NOTE: Reads the request fresh rather than closing over `activeRequest`. The row that calls this
|
||||
// holds onto it until the URL's placeholders change, so a captured request would go stale and
|
||||
// patch its parameter list back over newer edits.
|
||||
const handleRenamePathPlaceholder = useCallback(
|
||||
(oldName: string, newName: string) => {
|
||||
const request = getModel("http_request", activeRequestId);
|
||||
if (request == null) return false;
|
||||
|
||||
const patch = renamePathPlaceholder(request, oldName, newName);
|
||||
if (patch == null) return false; // Unusable name, so the editor reverts the field
|
||||
void patchModel(request, patch);
|
||||
return true;
|
||||
},
|
||||
[activeRequestId],
|
||||
);
|
||||
|
||||
const { urlParameterPairs, urlParametersKey } = useMemo(
|
||||
() =>
|
||||
derivePathPlaceholderPairs(
|
||||
activeRequest.url,
|
||||
activeRequest.urlParameters,
|
||||
handleRenamePathPlaceholder,
|
||||
),
|
||||
[activeRequest.url, activeRequest.urlParameters, handleRenamePathPlaceholder],
|
||||
);
|
||||
|
||||
let numParams = 0;
|
||||
if (
|
||||
@@ -273,28 +281,19 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
||||
const { mutate: importCurl } = useImportCurl();
|
||||
|
||||
const handleBodyChange = useCallback(
|
||||
(body: HttpRequest["body"]) => patchModel(activeRequest, { body }),
|
||||
(body: HttpRequest["body"]) => patchModelDebounced(activeRequest, { body }),
|
||||
[activeRequest],
|
||||
);
|
||||
|
||||
const handleBodyTextChange = useCallback(
|
||||
(text: string) => patchModel(activeRequest, { body: { ...activeRequest.body, text } }),
|
||||
(text: string) => patchModelDebounced(activeRequest, { body: { ...activeRequest.body, text } }),
|
||||
[activeRequest],
|
||||
);
|
||||
|
||||
const autocompleteUrls = useAtomValue(memoNotActiveRequestUrlsAtom);
|
||||
const autocompleteUrls = useAtomValue(requestUrlOptionsAtom);
|
||||
|
||||
const autocomplete: GenericCompletionConfig = useMemo(
|
||||
() => ({
|
||||
minMatch: 3,
|
||||
options:
|
||||
autocompleteUrls.length > 0
|
||||
? autocompleteUrls
|
||||
: [
|
||||
{ label: "http://", type: "constant" },
|
||||
{ label: "https://", type: "constant" },
|
||||
],
|
||||
}),
|
||||
() => getUrlCompletionConfig(autocompleteUrls),
|
||||
[autocompleteUrls],
|
||||
);
|
||||
|
||||
@@ -331,7 +330,7 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
||||
);
|
||||
|
||||
const handleUrlChange = useCallback(
|
||||
(url: string) => patchModel(activeRequest, { url }),
|
||||
(url: string) => patchModelDebounced(activeRequest, { url }),
|
||||
[activeRequest],
|
||||
);
|
||||
|
||||
@@ -377,7 +376,7 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
||||
forceUpdateKey={`${forceUpdateHeaderEditorKey}::${forceUpdateKey}`}
|
||||
headers={activeRequest.headers}
|
||||
stateKey={`headers.${activeRequest.id}`}
|
||||
onChange={(headers) => patchModel(activeRequest, { headers })}
|
||||
onChange={(headers) => patchModelDebounced(activeRequest, { headers })}
|
||||
/>
|
||||
</TabContent>
|
||||
<TabContent value={TAB_PARAMS}>
|
||||
@@ -385,7 +384,7 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
||||
stateKey={`params.${activeRequest.id}`}
|
||||
forceUpdateKey={forceUpdateKey + urlParametersKey}
|
||||
pairs={urlParameterPairs}
|
||||
onChange={(urlParameters) => patchModel(activeRequest, { urlParameters })}
|
||||
onChange={(urlParameters) => patchModelDebounced(activeRequest, { urlParameters })}
|
||||
/>
|
||||
</TabContent>
|
||||
<TabContent value={TAB_SETTINGS}>
|
||||
@@ -437,7 +436,7 @@ export function HttpRequestPane({ style, fullHeight, className, activeRequest }:
|
||||
requestId={activeRequest.id}
|
||||
contentType={contentType}
|
||||
body={activeRequest.body}
|
||||
onChange={(body) => patchModel(activeRequest, { body })}
|
||||
onChange={(body) => patchModelDebounced(activeRequest, { body })}
|
||||
onChangeContentType={handleContentTypeChange}
|
||||
/>
|
||||
) : typeof activeRequest.bodyType === "string" ? (
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
import { formatSize } from "@yaakapp-internal/lib/formatSize";
|
||||
import { Banner, Button, HStack, LoadingIcon } from "@yaakapp-internal/ui";
|
||||
import type { ReactNode } from "react";
|
||||
import { lazy, Suspense, useEffect, useMemo, useState } from "react";
|
||||
import type { SniffedValue } from "./core/Editor/sniffValue";
|
||||
import { showDialog } from "../lib/dialog";
|
||||
import { decodeValue, largeValueActions } from "../lib/largeValue";
|
||||
import { Dropdown } from "./core/Dropdown";
|
||||
import { AudioViewer } from "./responseViewers/AudioViewer";
|
||||
import { ImageViewer } from "./responseViewers/ImageViewer";
|
||||
import { SvgViewer } from "./responseViewers/SvgViewer";
|
||||
import { VideoViewer } from "./responseViewers/VideoViewer";
|
||||
|
||||
const PdfViewer = lazy(() =>
|
||||
import("./responseViewers/PdfViewer").then((m) => ({ default: m.PdfViewer })),
|
||||
);
|
||||
|
||||
interface Props {
|
||||
/** The whole value, exactly as it reads in the document */
|
||||
text: string;
|
||||
sniffed: SniffedValue | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a value the editor collapsed, in whatever viewer its type calls for.
|
||||
*
|
||||
* The editor only ever read the value's head, so this is where it is decoded in full — on an
|
||||
* explicit click, behind a spinner, rather than during layout.
|
||||
*/
|
||||
export function LargeValueDialog({ text, sniffed }: Props) {
|
||||
const viewer = sniffed == null ? null : viewerFor(sniffed.mime);
|
||||
const decoded = useDecoded(text, viewer == null ? null : sniffed);
|
||||
|
||||
// Nothing recognised it, so there is nothing to decode it into
|
||||
if (sniffed == null || viewer == null) {
|
||||
return (
|
||||
<PagedText text={text}>
|
||||
{sniffed != null && (
|
||||
<Banner color="info" className="mb-3">
|
||||
{sniffed.label} content cannot be previewed, so it is shown as it appears in the
|
||||
response.
|
||||
</Banner>
|
||||
)}
|
||||
</PagedText>
|
||||
);
|
||||
}
|
||||
|
||||
if (decoded == null) {
|
||||
return (
|
||||
<HStack className="h-full" alignItems="center" justifyContent="center">
|
||||
<LoadingIcon />
|
||||
</HStack>
|
||||
);
|
||||
}
|
||||
|
||||
if ("error" in decoded) {
|
||||
return (
|
||||
<PagedText text={text}>
|
||||
<Banner color="danger" className="mb-3">
|
||||
Failed to decode this {sniffed.label} value: {decoded.error}
|
||||
</Banner>
|
||||
</PagedText>
|
||||
);
|
||||
}
|
||||
|
||||
const { bytes } = decoded;
|
||||
|
||||
switch (viewer) {
|
||||
case "svg":
|
||||
return <DecodedSvg bytes={bytes} />;
|
||||
case "image":
|
||||
return (
|
||||
<div className="h-full overflow-auto flex items-center justify-center">
|
||||
<ImageViewer data={toArrayBuffer(bytes)} mimeType={sniffed.mime} />
|
||||
</div>
|
||||
);
|
||||
case "audio":
|
||||
return <AudioViewer data={bytes} mimeType={sniffed.mime} />;
|
||||
case "video":
|
||||
return <VideoViewer data={bytes} mimeType={sniffed.mime} />;
|
||||
case "pdf":
|
||||
return (
|
||||
<Suspense fallback={<LoadingIcon />}>
|
||||
<PdfViewer data={bytes} />
|
||||
</Suspense>
|
||||
);
|
||||
case "text":
|
||||
return <DecodedText bytes={bytes} />;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decoding megabytes is worth doing once, not on every render — and the viewers below key their
|
||||
* blob URLs off the string, so a fresh one each time would rebuild them for nothing.
|
||||
*/
|
||||
function DecodedSvg({ bytes }: { bytes: Uint8Array }) {
|
||||
const text = useMemo(() => new TextDecoder().decode(bytes), [bytes]);
|
||||
return <SvgViewer text={text} />;
|
||||
}
|
||||
|
||||
function DecodedText({ bytes }: { bytes: Uint8Array }) {
|
||||
const text = useMemo(() => new TextDecoder().decode(bytes), [bytes]);
|
||||
return <PagedText text={text} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* The same menu the tag in the editor carries, minus the one entry that would only reopen this.
|
||||
*
|
||||
* It lives in the dialog's title rather than above the content, which would cost a band of
|
||||
* whitespace the width of the dialog to hold one small button.
|
||||
*/
|
||||
function LargeValueActions({ text, sniffed }: Props) {
|
||||
const items = useMemo(
|
||||
() =>
|
||||
largeValueActions({
|
||||
value: () => text,
|
||||
sniffed,
|
||||
// The tag copies only what it hides; in here, what you see is the whole value
|
||||
copyText: () => text,
|
||||
}),
|
||||
[text, sniffed],
|
||||
);
|
||||
|
||||
return (
|
||||
<Dropdown items={items}>
|
||||
<Button size="xs" variant="border" forDropdown>
|
||||
Actions
|
||||
</Button>
|
||||
</Dropdown>
|
||||
);
|
||||
}
|
||||
|
||||
type Viewer = "image" | "svg" | "audio" | "video" | "pdf" | "text";
|
||||
|
||||
/** Which viewer a media type calls for, or null if none of them can show it. */
|
||||
function viewerFor(mime: string): Viewer | null {
|
||||
if (mime.startsWith("image/svg")) return "svg";
|
||||
if (mime.startsWith("image/")) return "image";
|
||||
if (mime.startsWith("audio/")) return "audio";
|
||||
if (mime.startsWith("video/")) return "video";
|
||||
if (mime === "application/pdf") return "pdf";
|
||||
if (mime.startsWith("text/") || /\b(json|xml|javascript|csv)\b/.test(mime)) return "text";
|
||||
return null;
|
||||
}
|
||||
|
||||
type Decoded = { bytes: Uint8Array } | { error: string };
|
||||
|
||||
/**
|
||||
* The value's bytes, once they exist.
|
||||
*
|
||||
* Decoding a few megabytes takes long enough to be seen, so it happens in an effect rather than
|
||||
* during render — the dialog paints with a spinner first, instead of opening late.
|
||||
*/
|
||||
function useDecoded(text: string, sniffed: SniffedValue | null): Decoded | null {
|
||||
const [decoded, setDecoded] = useState<Decoded | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (sniffed == null) return;
|
||||
|
||||
setDecoded(null);
|
||||
let cancelled = false;
|
||||
const timer = setTimeout(() => {
|
||||
let result: Decoded;
|
||||
try {
|
||||
result = { bytes: decodeValue(text, sniffed) };
|
||||
} catch (err) {
|
||||
result = { error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
if (!cancelled) setDecoded(result);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [text, sniffed]);
|
||||
|
||||
return decoded;
|
||||
}
|
||||
|
||||
/** A copy, since a `Uint8Array` may be a view onto a larger buffer */
|
||||
function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
|
||||
return bytes.slice().buffer;
|
||||
}
|
||||
|
||||
/** Characters shown at once. A page this size lays out instantly once its lines are short. */
|
||||
const PAGE_CHARS = 50_000;
|
||||
|
||||
/** Where a line is broken. The long-line cost this whole feature avoids is per line. */
|
||||
const WRAP_CHARS = 120;
|
||||
|
||||
/**
|
||||
* The raw text, in pages of short lines.
|
||||
*
|
||||
* What is left when nothing can render the value. Handing it to an editor whole would walk
|
||||
* straight back into the layout stall that collapsed it in the first place, so it is paged and
|
||||
* hard-wrapped instead: no line is ever long, and no page is ever big.
|
||||
*/
|
||||
function PagedText({ text, children }: { text: string; children?: ReactNode }) {
|
||||
const [page, setPage] = useState(0);
|
||||
const pages = Math.max(1, Math.ceil(text.length / PAGE_CHARS));
|
||||
const from = page * PAGE_CHARS;
|
||||
const to = Math.min(from + PAGE_CHARS, text.length);
|
||||
const body = useMemo(() => wrap(text.slice(from, to)), [text, from, to]);
|
||||
|
||||
return (
|
||||
<div className="h-full grid grid-rows-[auto_minmax(0,1fr)_auto] gap-3">
|
||||
<div>{children}</div>
|
||||
<pre className="overflow-auto font-mono text-sm text-text-subtle select-text">{body}</pre>
|
||||
<HStack space={2} alignItems="center" className="text-sm text-text-subtle">
|
||||
<span>
|
||||
{(to - from).toLocaleString()} of {text.length.toLocaleString()} characters
|
||||
</span>
|
||||
{pages > 1 && (
|
||||
<HStack space={2} alignItems="center" className="ml-auto">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="border"
|
||||
disabled={page === 0}
|
||||
onClick={() => setPage((p) => p - 1)}
|
||||
>
|
||||
Previous
|
||||
</Button>
|
||||
<span>
|
||||
Page {page + 1} of {pages.toLocaleString()}
|
||||
</span>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="border"
|
||||
disabled={page >= pages - 1}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
</HStack>
|
||||
)}
|
||||
</HStack>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Breaks every line at {@link WRAP_CHARS}, leaving the ones already shorter alone. */
|
||||
function wrap(text: string): string {
|
||||
const lines: string[] = [];
|
||||
for (const line of text.split("\n")) {
|
||||
if (line.length <= WRAP_CHARS) {
|
||||
lines.push(line);
|
||||
continue;
|
||||
}
|
||||
for (let i = 0; i < line.length; i += WRAP_CHARS) {
|
||||
lines.push(line.slice(i, i + WRAP_CHARS));
|
||||
}
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function showLargeValueDialog({ text, sniffed }: Props) {
|
||||
showDialog({
|
||||
id: "large-value",
|
||||
size: "lg",
|
||||
className: "h-[calc(100vh-10rem)]",
|
||||
// Everything in one line: the same words the tag uses, and the same menu it carries. A
|
||||
// separate description and a row of its own for the button cost three bands to say this.
|
||||
title: (
|
||||
<HStack space={3} alignItems="center">
|
||||
<span>
|
||||
{sniffed == null ? "Hidden Value" : sniffed.label} · {formatSize(text.length)}
|
||||
</span>
|
||||
<LargeValueActions text={text} sniffed={sniffed} />
|
||||
</HStack>
|
||||
),
|
||||
render: () => <LargeValueDialog text={text} sniffed={sniffed} />,
|
||||
});
|
||||
}
|
||||
@@ -112,6 +112,7 @@ function Sidebar({ className }: { className?: string }) {
|
||||
const treeId = `tree.${activeWorkspaceId ?? "unknown"}`;
|
||||
const filterText = useAtomValue(sidebarFilterAtom);
|
||||
const [tree, allFields, emptyFilterSuggestions] = useAtomValue(sidebarTreeAtom) ?? [];
|
||||
|
||||
const wrapperRef = useRef<HTMLElement>(null);
|
||||
const treeRef = useRef<TreeHandle>(null);
|
||||
const filterRef = useRef<InputHandle>(null);
|
||||
@@ -724,7 +725,11 @@ function Sidebar({ className }: { className?: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
export default Sidebar;
|
||||
// Memoized so route navigations (which re-render the workspace layout) don't
|
||||
// re-render the sidebar subtree. In large workspaces a sidebar re-render is
|
||||
// very expensive: it re-renders DndContext, whose context churn re-renders
|
||||
// every visible TreeItem regardless of their memo comparators.
|
||||
export default memo(Sidebar);
|
||||
|
||||
function getGitContextMenuItems({
|
||||
items,
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import type { HttpRequest } from "@yaakapp-internal/models";
|
||||
import { VStack } from "@yaakapp-internal/ui";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { useRequestEditor, useRequestEditorEvent } from "../hooks/useRequestEditor";
|
||||
import type { PairEditorHandle, PairEditorProps } from "./core/PairEditor";
|
||||
import type { EditablePair, PairEditorHandle, PairEditorProps } from "./core/PairEditor";
|
||||
import { PairOrBulkEditor } from "./core/PairOrBulkEditor";
|
||||
|
||||
type Props = {
|
||||
forceUpdateKey: string;
|
||||
pairs: HttpRequest["headers"];
|
||||
pairs: EditablePair[];
|
||||
stateKey: PairEditorProps["stateKey"];
|
||||
onChange: (headers: HttpRequest["urlParameters"]) => void;
|
||||
onChange: PairEditorProps["onChange"];
|
||||
};
|
||||
|
||||
export function UrlParametersEditor({ pairs, forceUpdateKey, onChange, stateKey }: Props) {
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import type { WebsocketRequest } from "@yaakapp-internal/models";
|
||||
import { patchModel } from "@yaakapp-internal/models";
|
||||
import {
|
||||
flushAllModelWrites,
|
||||
getModel,
|
||||
patchModel,
|
||||
patchModelDebounced,
|
||||
} from "@yaakapp-internal/models";
|
||||
import type { GenericCompletionOption } from "@yaakapp-internal/plugins";
|
||||
import { closeWebsocket, connectWebsocket, sendWebsocket } from "@yaakapp-internal/ws";
|
||||
import classNames from "classnames";
|
||||
@@ -8,8 +13,7 @@ import type { CSSProperties } from "react";
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
import { getActiveCookieJar } from "../hooks/useActiveCookieJar";
|
||||
import { getActiveEnvironment } from "../hooks/useActiveEnvironment";
|
||||
import { activeRequestIdAtom } from "../hooks/useActiveRequestId";
|
||||
import { allRequestsAtom } from "../hooks/useAllRequests";
|
||||
import { allRequestUrlsAtom } from "../hooks/useAllRequests";
|
||||
import { useAuthTab } from "../hooks/useAuthTab";
|
||||
import { useCancelHttpResponse } from "../hooks/useCancelHttpResponse";
|
||||
import { useHeadersTab } from "../hooks/useHeadersTab";
|
||||
@@ -18,17 +22,15 @@ import { usePinnedHttpResponse } from "../hooks/usePinnedHttpResponse";
|
||||
import { activeWebsocketConnectionAtom } from "../hooks/usePinnedWebsocketConnection";
|
||||
import { useRequestEditor, useRequestEditorEvent } from "../hooks/useRequestEditor";
|
||||
import { useRequestUpdateKey } from "../hooks/useRequestUpdateKey";
|
||||
import { deepEqualAtom } from "../lib/atoms";
|
||||
import { languageFromContentType } from "../lib/contentType";
|
||||
import { generateId } from "../lib/generateId";
|
||||
import { extractPathPlaceholders } from "../lib/pathPlaceholders";
|
||||
import { derivePathPlaceholderPairs, renamePathPlaceholder } from "../lib/pathPlaceholders";
|
||||
import { prepareImportQuerystring } from "../lib/prepareImportQuerystring";
|
||||
import { resolvedModelName } from "../lib/resolvedModelName";
|
||||
import { CountBadge } from "./core/CountBadge";
|
||||
import type { GenericCompletionConfig } from "./core/Editor/genericCompletion";
|
||||
import { getUrlCompletionConfig } from "./core/Editor/url/completion";
|
||||
import { Editor } from "./core/Editor/LazyEditor";
|
||||
import { IconButton } from "./core/IconButton";
|
||||
import type { Pair } from "./core/PairEditor";
|
||||
import { PlainInput } from "./core/PlainInput";
|
||||
import type { TabItem, TabsRef } from "./core/Tabs/Tabs";
|
||||
import { setActiveTab, TabContent, Tabs } from "./core/Tabs/Tabs";
|
||||
@@ -54,15 +56,12 @@ const TAB_SETTINGS = "settings";
|
||||
const TAB_DESCRIPTION = "description";
|
||||
const TABS_STORAGE_KEY = "websocket_request_tabs";
|
||||
|
||||
const nonActiveRequestUrlsAtom = atom((get) => {
|
||||
const activeRequestId = get(activeRequestIdAtom);
|
||||
const requests = get(allRequestsAtom);
|
||||
return requests
|
||||
.filter((r) => r.id !== activeRequestId)
|
||||
.map((r): GenericCompletionOption => ({ type: "constant", label: r.url }));
|
||||
});
|
||||
|
||||
const memoNotActiveRequestUrlsAtom = deepEqualAtom(nonActiveRequestUrlsAtom);
|
||||
// Derived from the identity-stable URL list so this only recomputes when a URL
|
||||
// actually changes. The active request's own URL is included, but exact matches
|
||||
// are filtered out at completion time by genericCompletion.
|
||||
const requestUrlOptionsAtom = atom((get): GenericCompletionOption[] =>
|
||||
get(allRequestUrlsAtom).map((url) => ({ type: "constant", label: url })),
|
||||
);
|
||||
|
||||
export function WebsocketRequestPane({ style, fullHeight, className, activeRequest }: Props) {
|
||||
const activeRequestId = activeRequest.id;
|
||||
@@ -83,20 +82,33 @@ export function WebsocketRequestPane({ style, fullHeight, className, activeReque
|
||||
[],
|
||||
);
|
||||
|
||||
const { urlParameterPairs, urlParametersKey } = useMemo(() => {
|
||||
const placeholderNames = extractPathPlaceholders(activeRequest.url);
|
||||
const nonEmptyParameters = activeRequest.urlParameters.filter((p) => p.name || p.value);
|
||||
const items: Pair[] = [...nonEmptyParameters];
|
||||
for (const name of placeholderNames) {
|
||||
const item = items.find((p) => p.name === name);
|
||||
if (item) {
|
||||
item.readOnlyName = true;
|
||||
} else {
|
||||
items.push({ name, value: "", enabled: true, readOnlyName: true, id: generateId() });
|
||||
}
|
||||
}
|
||||
return { urlParameterPairs: items, urlParametersKey: placeholderNames.join(",") };
|
||||
}, [activeRequest.url, activeRequest.urlParameters]);
|
||||
// Renaming a path placeholder has to rewrite the URL and rename the parameter together, or the
|
||||
// value detaches from the placeholder.
|
||||
// NOTE: Reads the request fresh rather than closing over `activeRequest`. The row that calls this
|
||||
// holds onto it until the URL's placeholders change, so a captured request would go stale and
|
||||
// patch its parameter list back over newer edits.
|
||||
const handleRenamePathPlaceholder = useCallback(
|
||||
(oldName: string, newName: string) => {
|
||||
const request = getModel("websocket_request", activeRequestId);
|
||||
if (request == null) return false;
|
||||
|
||||
const patch = renamePathPlaceholder(request, oldName, newName);
|
||||
if (patch == null) return false; // Unusable name, so the editor reverts the field
|
||||
void patchModel(request, patch);
|
||||
return true;
|
||||
},
|
||||
[activeRequestId],
|
||||
);
|
||||
|
||||
const { urlParameterPairs, urlParametersKey } = useMemo(
|
||||
() =>
|
||||
derivePathPlaceholderPairs(
|
||||
activeRequest.url,
|
||||
activeRequest.urlParameters,
|
||||
handleRenamePathPlaceholder,
|
||||
),
|
||||
[activeRequest.url, activeRequest.urlParameters, handleRenamePathPlaceholder],
|
||||
);
|
||||
|
||||
const tabs = useMemo<TabItem[]>(() => {
|
||||
return [
|
||||
@@ -127,23 +139,15 @@ export function WebsocketRequestPane({ style, fullHeight, className, activeReque
|
||||
const { mutate: cancelResponse } = useCancelHttpResponse(activeResponse?.id ?? null);
|
||||
const connection = useAtomValue(activeWebsocketConnectionAtom);
|
||||
|
||||
const autocompleteUrls = useAtomValue(memoNotActiveRequestUrlsAtom);
|
||||
const autocompleteUrls = useAtomValue(requestUrlOptionsAtom);
|
||||
|
||||
const autocomplete: GenericCompletionConfig = useMemo(
|
||||
() => ({
|
||||
minMatch: 3,
|
||||
options:
|
||||
autocompleteUrls.length > 0
|
||||
? autocompleteUrls
|
||||
: [
|
||||
{ label: "http://", type: "constant" },
|
||||
{ label: "https://", type: "constant" },
|
||||
],
|
||||
}),
|
||||
() => getUrlCompletionConfig(autocompleteUrls),
|
||||
[autocompleteUrls],
|
||||
);
|
||||
|
||||
const handleConnect = useCallback(async () => {
|
||||
await flushAllModelWrites(); // The backend reads the request from the DB
|
||||
await connectWebsocket({
|
||||
requestId: activeRequest.id,
|
||||
environmentId: getActiveEnvironment()?.id ?? null,
|
||||
@@ -153,6 +157,7 @@ export function WebsocketRequestPane({ style, fullHeight, className, activeReque
|
||||
|
||||
const handleSend = useCallback(async () => {
|
||||
if (connection == null) return;
|
||||
await flushAllModelWrites(); // The backend reads the message from the DB
|
||||
await sendWebsocket({
|
||||
connectionId: connection?.id,
|
||||
environmentId: getActiveEnvironment()?.id ?? null,
|
||||
@@ -165,7 +170,7 @@ export function WebsocketRequestPane({ style, fullHeight, className, activeReque
|
||||
}, [connection]);
|
||||
|
||||
const handleUrlChange = useCallback(
|
||||
(url: string) => patchModel(activeRequest, { url }),
|
||||
(url: string) => patchModelDebounced(activeRequest, { url }),
|
||||
[activeRequest],
|
||||
);
|
||||
|
||||
@@ -249,7 +254,7 @@ export function WebsocketRequestPane({ style, fullHeight, className, activeReque
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
headers={activeRequest.headers}
|
||||
stateKey={`headers.${activeRequest.id}`}
|
||||
onChange={(headers) => patchModel(activeRequest, { headers })}
|
||||
onChange={(headers) => patchModelDebounced(activeRequest, { headers })}
|
||||
/>
|
||||
</TabContent>
|
||||
<TabContent value={TAB_PARAMS}>
|
||||
@@ -257,7 +262,7 @@ export function WebsocketRequestPane({ style, fullHeight, className, activeReque
|
||||
stateKey={`params.${activeRequest.id}`}
|
||||
forceUpdateKey={forceUpdateKey + urlParametersKey}
|
||||
pairs={urlParameterPairs}
|
||||
onChange={(urlParameters) => patchModel(activeRequest, { urlParameters })}
|
||||
onChange={(urlParameters) => patchModelDebounced(activeRequest, { urlParameters })}
|
||||
/>
|
||||
</TabContent>
|
||||
<TabContent value={TAB_MESSAGE}>
|
||||
@@ -269,7 +274,7 @@ export function WebsocketRequestPane({ style, fullHeight, className, activeReque
|
||||
heightMode={fullHeight ? "full" : "auto"}
|
||||
defaultValue={activeRequest.message}
|
||||
language={messageLanguage}
|
||||
onChange={(message) => patchModel(activeRequest, { message })}
|
||||
onChange={(message) => patchModelDebounced(activeRequest, { message })}
|
||||
stateKey={`json.${activeRequest.id}`}
|
||||
/>
|
||||
</TabContent>
|
||||
@@ -286,7 +291,7 @@ export function WebsocketRequestPane({ style, fullHeight, className, activeReque
|
||||
className="font-sans text-xl! px-0!"
|
||||
containerClassName="border-0"
|
||||
placeholder={resolvedModelName(activeRequest)}
|
||||
onChange={(name) => patchModel(activeRequest, { name })}
|
||||
onChange={(name) => patchModelDebounced(activeRequest, { name })}
|
||||
/>
|
||||
<MarkdownEditor
|
||||
name="request-description"
|
||||
@@ -294,7 +299,7 @@ export function WebsocketRequestPane({ style, fullHeight, className, activeReque
|
||||
defaultValue={activeRequest.description}
|
||||
stateKey={`description.${activeRequest.id}`}
|
||||
forceUpdateKey={forceUpdateKey}
|
||||
onChange={(description) => patchModel(activeRequest, { description })}
|
||||
onChange={(description) => patchModelDebounced(activeRequest, { description })}
|
||||
/>
|
||||
</div>
|
||||
</TabContent>
|
||||
|
||||
@@ -233,23 +233,40 @@ export const Dropdown = forwardRef<DropdownRef, DropdownProps>(function Dropdown
|
||||
|
||||
export interface ContextMenuProps {
|
||||
triggerPosition: { x: number; y: number } | null;
|
||||
/**
|
||||
* The box the menu belongs to, when the trigger has one.
|
||||
*
|
||||
* Placement aligns to the trigger's left or right edge depending on the room beside it, so a
|
||||
* menu opened from an element wants its real rect. Without one the position is treated as a
|
||||
* zero-width point, which is right for a menu opened at the cursor and wrong for one opened
|
||||
* from a button.
|
||||
*/
|
||||
triggerRect?: Pick<DOMRect, "top" | "bottom" | "left" | "right">;
|
||||
/**
|
||||
* The element the menu belongs to, so a click on it doesn't count as a click outside.
|
||||
*
|
||||
* Without this the trigger gets both: the outside-click handler closes the menu on mousedown,
|
||||
* then the trigger's own click opens it again, and pressing it looks like it does nothing.
|
||||
*/
|
||||
triggerRef?: RefObject<HTMLElement | null>;
|
||||
className?: string;
|
||||
items: DropdownProps["items"];
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export const ContextMenu = forwardRef<DropdownRef, ContextMenuProps>(function ContextMenu(
|
||||
{ triggerPosition, className, items, onClose },
|
||||
{ triggerPosition, triggerRect, triggerRef, className, items, onClose },
|
||||
ref,
|
||||
) {
|
||||
const triggerShape = useMemo(
|
||||
() => ({
|
||||
top: triggerPosition?.y ?? 0,
|
||||
bottom: triggerPosition?.y ?? 0,
|
||||
left: triggerPosition?.x ?? 0,
|
||||
right: triggerPosition?.x ?? 0,
|
||||
}),
|
||||
[triggerPosition],
|
||||
() =>
|
||||
triggerRect ?? {
|
||||
top: triggerPosition?.y ?? 0,
|
||||
bottom: triggerPosition?.y ?? 0,
|
||||
left: triggerPosition?.x ?? 0,
|
||||
right: triggerPosition?.x ?? 0,
|
||||
},
|
||||
[triggerPosition, triggerRect],
|
||||
);
|
||||
|
||||
if (triggerPosition == null) return null;
|
||||
@@ -259,9 +276,13 @@ export const ContextMenu = forwardRef<DropdownRef, ContextMenuProps>(function Co
|
||||
isOpen={true} // Always open because we return null if not
|
||||
className={className}
|
||||
defaultSelectedIndex={null}
|
||||
// A menu opened from an element points back at it. One opened at the cursor has nothing
|
||||
// to point at, so it goes without.
|
||||
showTriangle={triggerRect != null}
|
||||
ref={ref}
|
||||
items={items}
|
||||
onClose={onClose}
|
||||
triggerRef={triggerRef}
|
||||
triggerShape={triggerShape}
|
||||
/>
|
||||
);
|
||||
@@ -277,7 +298,9 @@ interface MenuProps {
|
||||
fullWidth?: boolean;
|
||||
isOpen: boolean;
|
||||
items: DropdownItem[];
|
||||
triggerRef?: RefObject<HTMLButtonElement | null>;
|
||||
// Any element, not just a button: a menu can be opened from anything, and this is only ever
|
||||
// used to ask whether a click landed on the trigger
|
||||
triggerRef?: RefObject<HTMLElement | null>;
|
||||
isSubmenu?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -121,6 +121,24 @@
|
||||
@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 {
|
||||
|
||||
@@ -8,6 +8,7 @@ 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 { settingsAtom } from "@yaakapp-internal/models";
|
||||
import type { EditorLanguage, TemplateFunction } from "@yaakapp-internal/plugins";
|
||||
@@ -15,7 +16,6 @@ import { HStack } from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import type { GraphQLSchema } from "graphql";
|
||||
import { useAtomValue } from "jotai";
|
||||
import { md5 } from "js-md5";
|
||||
import type { ReactNode, RefObject } from "react";
|
||||
import {
|
||||
Children,
|
||||
@@ -33,6 +33,7 @@ import { useEnvironmentVariables } from "../../../hooks/useEnvironmentVariables"
|
||||
import { eventMatchesHotkey } from "../../../hooks/useHotKey";
|
||||
import { useRequestEditor } from "../../../hooks/useRequestEditor";
|
||||
import { useTemplateFunctionCompletionOptions } from "../../../hooks/useTemplateFunctions";
|
||||
import { docFingerprint } from "../../../lib/docFingerprint";
|
||||
import { editEnvironment } from "../../../lib/editEnvironment";
|
||||
import { tryFormatJson, tryFormatXml } from "../../../lib/formatters";
|
||||
import { jotaiStore } from "../../../lib/jotai";
|
||||
@@ -42,6 +43,7 @@ import { IconButton } from "../IconButton";
|
||||
import "./Editor.css";
|
||||
import {
|
||||
baseExtensions,
|
||||
editableExtensions,
|
||||
getLanguageExtension,
|
||||
multiLineExtensions,
|
||||
readonlyExtensions,
|
||||
@@ -288,7 +290,7 @@ function EditorInner({
|
||||
function configureReadOnly() {
|
||||
if (cm.current === null) return;
|
||||
const current = readOnlyCompartment.current.get(cm.current.view.state) ?? emptyExtension;
|
||||
const next = readOnly ? readonlyExtensions : emptyExtension;
|
||||
const next = readOnly ? readonlyExtensions : editableExtensions;
|
||||
// PERF: This is expensive with hundreds of editors on screen, so only do it when necessary
|
||||
if (current === next) return;
|
||||
|
||||
@@ -381,6 +383,7 @@ function EditorInner({
|
||||
const initEditorRef = useCallback(
|
||||
function initEditorRef(container: HTMLDivElement | null) {
|
||||
if (container === null) {
|
||||
flushCachedEditorState(stateKey);
|
||||
cm.current?.view.destroy();
|
||||
cm.current = null;
|
||||
return;
|
||||
@@ -410,7 +413,7 @@ function EditorInner({
|
||||
keymapCompartment.current.of(
|
||||
keymapExtensions[settings.editorKeymap] ?? keymapExtensions.default,
|
||||
),
|
||||
readOnlyCompartment.current.of(readOnly ? readonlyExtensions : emptyExtension),
|
||||
readOnlyCompartment.current.of(readOnly ? readonlyExtensions : editableExtensions),
|
||||
...getExtensions({
|
||||
container,
|
||||
singleLine,
|
||||
@@ -430,7 +433,7 @@ function EditorInner({
|
||||
: []),
|
||||
];
|
||||
|
||||
const cachedJsonState = getCachedEditorState(defaultValue ?? "", stateKey);
|
||||
const cachedJsonState = getCachedEditorState(defaultValue ?? "", stateKey, !!readOnly);
|
||||
|
||||
const doc = `${defaultValue ?? ""}`;
|
||||
const config: EditorStateConfig = { extensions, doc };
|
||||
@@ -639,7 +642,7 @@ function getExtensions({
|
||||
onChange.current?.(update.state.doc.toString());
|
||||
}
|
||||
|
||||
saveCachedEditorState(stateKey, update.state);
|
||||
saveCachedEditorStateDebounced(stateKey, update.state);
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -652,13 +655,53 @@ const placeholderElFromText = (text: string | undefined) => {
|
||||
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 the hash of it instead.
|
||||
// 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.
|
||||
stateObj.docHash = md5(stateObj.doc);
|
||||
// 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 {
|
||||
@@ -668,7 +711,7 @@ function saveCachedEditorState(stateKey: string | null, state: EditorState | nul
|
||||
}
|
||||
}
|
||||
|
||||
function getCachedEditorState(doc: string, stateKey: string | null) {
|
||||
function getCachedEditorState(doc: string, stateKey: string | null, readOnly: boolean) {
|
||||
if (stateKey == null) return;
|
||||
|
||||
try {
|
||||
@@ -678,7 +721,7 @@ function getCachedEditorState(doc: string, stateKey: string | null) {
|
||||
const { docHash, ...state } = JSON.parse(stateStr);
|
||||
|
||||
// Ensure the doc matches the one that was used to save the state
|
||||
if (docHash !== md5(doc)) {
|
||||
if (docHash !== docFingerprint(doc, { exact: !readOnly })) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -59,6 +59,7 @@ import { pluralizeCount } from "../../../lib/pluralize";
|
||||
import { showGraphQLDocExplorerAtom } from "../../graphql/graphqlAtoms";
|
||||
import type { EditorProps } from "./Editor";
|
||||
import { jsonParseLinter } from "./json-lint";
|
||||
import { largeValues, mediaValues } from "./largeValues";
|
||||
import { pairs } from "./pairs/extension";
|
||||
import { searchMatchCount } from "./searchMatchCount";
|
||||
import { text } from "./text/extension";
|
||||
@@ -258,8 +259,19 @@ export const baseExtensions = [
|
||||
export const readonlyExtensions = [
|
||||
EditorState.readOnly.of(true),
|
||||
EditorView.contentAttributes.of({ tabindex: "-1" }),
|
||||
// Nobody is editing this, so every rule applies
|
||||
largeValues,
|
||||
];
|
||||
|
||||
/**
|
||||
* The counterpart for a document being edited.
|
||||
*
|
||||
* Only encoded media collapses here: it is pasted rather than typed, and replaced rather than
|
||||
* edited, so a tag stands in for it without hiding anything anyone meant to read. The rules that
|
||||
* hide text by length alone stay out. See {@link mediaValues}.
|
||||
*/
|
||||
export const editableExtensions = [mediaValues];
|
||||
|
||||
export const multiLineExtensions = ({ hideGutter }: { hideGutter?: boolean }) => [
|
||||
search({ top: true }),
|
||||
searchMatchCount(),
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import type { CompletionContext } from "@codemirror/autocomplete";
|
||||
import type { Completion, CompletionContext } from "@codemirror/autocomplete";
|
||||
import type { GenericCompletionOption } from "@yaakapp-internal/plugins";
|
||||
import { defaultBoost } from "./twig/completion";
|
||||
|
||||
export type GenericCompletion = GenericCompletionOption & {
|
||||
apply?: Completion["apply"];
|
||||
};
|
||||
|
||||
export interface GenericCompletionConfig {
|
||||
minMatch?: number;
|
||||
options: GenericCompletionOption[];
|
||||
options: GenericCompletion[];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { jsonc } from "@shopify/lang-jsonc";
|
||||
import { text } from "./text/extension";
|
||||
import { twig } from "./twig/extension";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import {
|
||||
COLLAPSE_MEDIA_CHARS,
|
||||
COLLAPSE_TOKEN_CHARS,
|
||||
collapseDecorations,
|
||||
largeValues,
|
||||
MAX_VISIBLE_LINE_CHARS,
|
||||
} from "./largeValues";
|
||||
import type { SniffedValue } from "./sniffValue";
|
||||
|
||||
const BIG = "A".repeat(1_000_000);
|
||||
|
||||
/** With a grammar, so tokens can be collapsed individually */
|
||||
const jsonState = (doc: string) => EditorState.create({ doc, extensions: [jsonc(), largeValues] });
|
||||
|
||||
/** Without a grammar, so only the column rule applies */
|
||||
const plainState = (doc: string) => EditorState.create({ doc, extensions: largeValues });
|
||||
|
||||
/**
|
||||
* The decorations as if the whole document were on screen.
|
||||
*
|
||||
* In the editor the plugin passes the viewport instead, which is the same call with narrower
|
||||
* ranges — the rules themselves don't know the difference.
|
||||
*/
|
||||
function decorationsFor(state: EditorState) {
|
||||
return collapseDecorations(state, [{ from: 0, to: state.doc.length }]);
|
||||
}
|
||||
|
||||
function collapsedRanges(state: EditorState) {
|
||||
const ranges: { from: number; to: number }[] = [];
|
||||
const iter = decorationsFor(state).iter();
|
||||
while (iter.value != null) {
|
||||
ranges.push({ from: iter.from, to: iter.to });
|
||||
iter.next();
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
|
||||
/** How much of each line is still rendered */
|
||||
function visibleLineLengths(state: EditorState) {
|
||||
const hidden = collapsedRanges(state);
|
||||
const lengths: number[] = [];
|
||||
for (let n = 1; n <= state.doc.lines; n++) {
|
||||
const line = state.doc.line(n);
|
||||
const covered = hidden
|
||||
.filter((h) => h.from >= line.from && h.to <= line.to)
|
||||
.reduce((sum, h) => sum + (h.to - h.from), 0);
|
||||
lengths.push(line.length - covered);
|
||||
}
|
||||
return lengths;
|
||||
}
|
||||
|
||||
describe("collapsing", () => {
|
||||
test("leaves an ordinary body alone", () => {
|
||||
expect(collapsedRanges(jsonState('{"hello":"world"}'))).toEqual([]);
|
||||
});
|
||||
|
||||
test("leaves a large body of short lines alone", () => {
|
||||
const doc = Array.from({ length: 20_000 }, (_, i) => ` { "id": ${i} },`).join("\n");
|
||||
expect(doc.length).toBeGreaterThan(MAX_VISIBLE_LINE_CHARS);
|
||||
expect(collapsedRanges(jsonState(doc))).toEqual([]);
|
||||
});
|
||||
|
||||
test("leaves a line just under the column limit alone", () => {
|
||||
expect(collapsedRanges(plainState("x".repeat(MAX_VISIBLE_LINE_CHARS)))).toEqual([]);
|
||||
});
|
||||
|
||||
test("never renders more than the column limit per line", () => {
|
||||
for (const state of [jsonState(`{"image":"${BIG}"}`), plainState(BIG)]) {
|
||||
for (const length of visibleLineLengths(state)) {
|
||||
expect(length).toBeLessThanOrEqual(MAX_VISIBLE_LINE_CHARS);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps the document text intact", () => {
|
||||
const doc = `{"image":"${BIG}"}`;
|
||||
expect(jsonState(doc).sliceDoc()).toBe(doc);
|
||||
expect(jsonState(doc).doc.length).toBe(doc.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("token collapsing, with a grammar", () => {
|
||||
test("hides the whole value, leaving its quotes visible", () => {
|
||||
const doc = `{"name":"a.png","image":"${BIG}","size":12}`;
|
||||
const state = jsonState(doc);
|
||||
const ranges = collapsedRanges(state);
|
||||
|
||||
expect(ranges).toHaveLength(1);
|
||||
// Exactly the text between the quotes, so the line reads as `"image":"<tag>"`
|
||||
expect(state.sliceDoc(ranges[0]!.from, ranges[0]!.to)).toBe(BIG);
|
||||
expect(doc[ranges[0]!.from - 1]).toBe('"');
|
||||
expect(doc[ranges[0]!.to]).toBe('"');
|
||||
|
||||
// Everything after the value is still rendered, unlike a plain column cut
|
||||
expect(doc.slice(ranges[0]!.to)).toContain('"size":12}');
|
||||
});
|
||||
|
||||
// Small enough that the parse always finishes inside PARSE_TIMEOUT_MS, even on a slow
|
||||
// machine. With a bigger body this falls back to the column cut, which is by design but
|
||||
// makes the assertion depend on how fast the runner is.
|
||||
test("keeps every key visible in a minified body with several large values", () => {
|
||||
const chunk = "B".repeat(20_000);
|
||||
const doc = `{${["a", "b", "c", "d", "e"].map((k) => `"${k}":"${chunk}"`).join(",")}}`;
|
||||
const state = jsonState(doc);
|
||||
const ranges = collapsedRanges(state);
|
||||
|
||||
expect(ranges).toHaveLength(5);
|
||||
for (const key of ["a", "b", "c", "d", "e"]) {
|
||||
// No collapse swallows the key
|
||||
const at = doc.indexOf(`"${key}":`);
|
||||
expect(ranges.some((r) => r.from <= at && r.to > at)).toBe(false);
|
||||
}
|
||||
expect(visibleLineLengths(state)[0]).toBeLessThanOrEqual(MAX_VISIBLE_LINE_CHARS);
|
||||
});
|
||||
|
||||
test("collapses a value on a pretty-printed line", () => {
|
||||
const doc = `{\n "name": "a.png",\n "image": "${BIG}"\n}`;
|
||||
const state = jsonState(doc);
|
||||
const ranges = collapsedRanges(state);
|
||||
|
||||
expect(ranges).toHaveLength(1);
|
||||
expect(state.sliceDoc(ranges[0]!.from, ranges[0]!.to)).toBe(BIG);
|
||||
// Only the long line is touched, and all that is left of it is ` "image": ""`
|
||||
expect(visibleLineLengths(state)).toEqual([1, 18, 13, 1]);
|
||||
expect(state.doc.line(2).text).toBe(' "name": "a.png",');
|
||||
});
|
||||
|
||||
test("ignores tokens under the collapse threshold", () => {
|
||||
// Under the threshold once the surrounding quotes are counted
|
||||
const short = "C".repeat(COLLAPSE_TOKEN_CHARS - 10);
|
||||
const doc = `{${Array.from({ length: 4 }, (_, i) => `"k${i}":"${short}"`).join(",")}}`;
|
||||
expect(doc.length).toBeGreaterThan(MAX_VISIBLE_LINE_CHARS);
|
||||
|
||||
// Nothing is big enough to collapse on its own, so the column rule takes over
|
||||
const ranges = collapsedRanges(jsonState(doc));
|
||||
expect(ranges).toHaveLength(1);
|
||||
expect(ranges[0]!.to).toBe(doc.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("column collapsing, without a grammar", () => {
|
||||
test("collapses everything past the limit", () => {
|
||||
const ranges = collapsedRanges(plainState(BIG));
|
||||
expect(ranges).toHaveLength(1);
|
||||
expect(ranges[0]!.from).toBe(MAX_VISIBLE_LINE_CHARS);
|
||||
expect(ranges[0]!.to).toBe(BIG.length);
|
||||
});
|
||||
|
||||
test("handles a long line of many short tokens", () => {
|
||||
// A single-line CSV row: no token is long enough to collapse on its own
|
||||
const row = Array.from({ length: 40_000 }, (_, i) => `value ${i}`).join(", ");
|
||||
const ranges = collapsedRanges(plainState(row));
|
||||
expect(ranges).toHaveLength(1);
|
||||
expect(ranges[0]!.from).toBe(MAX_VISIBLE_LINE_CHARS);
|
||||
});
|
||||
|
||||
test("collapses each long line independently", () => {
|
||||
const doc = `${BIG}\nshort\n${BIG}`;
|
||||
const ranges = collapsedRanges(plainState(doc));
|
||||
expect(ranges).toHaveLength(2);
|
||||
for (const length of visibleLineLengths(plainState(doc))) {
|
||||
expect(length).toBeLessThanOrEqual(MAX_VISIBLE_LINE_CHARS);
|
||||
}
|
||||
});
|
||||
|
||||
test("never hides a line break", () => {
|
||||
const doc = `${BIG}\nshort`;
|
||||
const state = plainState(doc);
|
||||
for (const { from, to } of collapsedRanges(state)) {
|
||||
expect(state.sliceDoc(from, to)).not.toContain("\n");
|
||||
}
|
||||
expect(state.doc.lines).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("undelimited tokens", () => {
|
||||
// The text grammar parses a whole line as one token. Collapsing it whole would leave the
|
||||
// line with nothing on it but a tag, so the column cut handles it instead.
|
||||
const textState = (doc: string) => EditorState.create({ doc, extensions: [text(), largeValues] });
|
||||
|
||||
test("falls back to the column cut for a long line of plain text", () => {
|
||||
const doc = Array.from({ length: 90_000 }, (_, i) => `word${i}`).join(" ");
|
||||
const ranges = collapsedRanges(textState(doc));
|
||||
|
||||
expect(ranges).toHaveLength(1);
|
||||
expect(ranges[0]!.from).toBe(MAX_VISIBLE_LINE_CHARS);
|
||||
expect(ranges[0]!.to).toBe(doc.length);
|
||||
});
|
||||
|
||||
test("leaves the start of the line readable", () => {
|
||||
const doc = `IMPORTANT-PREFIX ${"z".repeat(500_000)}`;
|
||||
const state = textState(doc);
|
||||
const ranges = collapsedRanges(state);
|
||||
|
||||
expect(ranges[0]!.from).toBe(MAX_VISIBLE_LINE_CHARS);
|
||||
expect(state.sliceDoc(0, 16)).toBe("IMPORTANT-PREFIX");
|
||||
});
|
||||
});
|
||||
|
||||
describe("sniffing the collapsed value", () => {
|
||||
/** The widget standing in for each collapse, in document order */
|
||||
function widgets(state: EditorState) {
|
||||
const found: { valueFrom: number; sniffed: SniffedValue | null }[] = [];
|
||||
const iter = decorationsFor(state).iter();
|
||||
while (iter.value != null) {
|
||||
found.push(iter.value.spec.widget);
|
||||
iter.next();
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** A base64 value that starts with a PNG signature and runs on well past the limits */
|
||||
function pngBase64(length = 1_000_000) {
|
||||
const bytes = new Uint8Array(length);
|
||||
bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
let binary = "";
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte);
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
test("names the format of a base64 value inside JSON", () => {
|
||||
const state = jsonState(`{"image":"${pngBase64()}"}`);
|
||||
expect(widgets(state)[0]?.sniffed).toMatchObject({ mime: "image/png", label: "PNG" });
|
||||
});
|
||||
|
||||
test("names the format of a data URI", () => {
|
||||
const doc = `{"image":"data:image/jpeg;base64,${BIG}"}`;
|
||||
expect(widgets(jsonState(doc))[0]?.sniffed).toMatchObject({ label: "JPEG" });
|
||||
});
|
||||
|
||||
test("names nothing when the value is just text", () => {
|
||||
expect(widgets(jsonState(`{"image":"${BIG}"}`))[0]?.sniffed).toBeNull();
|
||||
expect(widgets(plainState(BIG))[0]?.sniffed).toBeNull();
|
||||
});
|
||||
|
||||
test("reads a column cut from the start of its line, not from the cut", () => {
|
||||
// A body that is nothing but one base64 blob: the tail is hidden, but the value it
|
||||
// belongs to begins at the start of the line, which is where the signature is
|
||||
const state = plainState(pngBase64());
|
||||
const [widget] = widgets(state);
|
||||
|
||||
expect(widget?.valueFrom).toBe(0);
|
||||
expect(widget?.sniffed).toMatchObject({ label: "PNG" });
|
||||
});
|
||||
|
||||
test("reads a token collapse from the value itself", () => {
|
||||
const doc = `{"image":"${pngBase64()}"}`;
|
||||
const [widget] = widgets(jsonState(doc));
|
||||
|
||||
// Just past the opening quote, so the signature is the first thing it sees
|
||||
expect(widget?.valueFrom).toBe(doc.indexOf('"', doc.indexOf("image") + 6) + 1);
|
||||
expect(widget?.sniffed).toMatchObject({ label: "PNG" });
|
||||
});
|
||||
|
||||
test("finds a run that starts partway through a line, and names it", () => {
|
||||
// No grammar here, and the value is not the whole line. The run is found by its alphabet,
|
||||
// so the prefix stays on screen and the blob is still named.
|
||||
const prefix = "some prefix text ";
|
||||
const state = plainState(`${prefix}${pngBase64()}`);
|
||||
const [widget] = widgets(state);
|
||||
|
||||
expect(widget?.valueFrom).toBe(prefix.length);
|
||||
expect(widget?.sniffed).toMatchObject({ label: "PNG" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("recomputing", () => {
|
||||
test("updates when the document changes", () => {
|
||||
const state = plainState('{"image":"short"}');
|
||||
expect(collapsedRanges(state)).toEqual([]);
|
||||
|
||||
const next = state.update({
|
||||
changes: { from: 0, to: state.doc.length, insert: BIG },
|
||||
}).state;
|
||||
expect(collapsedRanges(next)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("media collapsing, below the length rules", () => {
|
||||
/** A real PNG signature, at a size that no length rule would touch */
|
||||
function png(bytes: number) {
|
||||
const b = new Uint8Array(bytes);
|
||||
b.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
let binary = "";
|
||||
for (const byte of b) binary += String.fromCharCode(byte);
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
/** Well under every length threshold, so only the media rule can collapse it */
|
||||
const SMALL = png(3_000);
|
||||
|
||||
test("collapses a small image on a short line", () => {
|
||||
expect(SMALL.length).toBeLessThan(MAX_VISIBLE_LINE_CHARS);
|
||||
expect(SMALL.length).toBeLessThan(COLLAPSE_TOKEN_CHARS);
|
||||
|
||||
const state = jsonState(`{\n "avatar": "${SMALL}"\n}`);
|
||||
const ranges = collapsedRanges(state);
|
||||
|
||||
expect(ranges).toHaveLength(1);
|
||||
expect(state.sliceDoc(ranges[0]!.from, ranges[0]!.to)).toBe(SMALL);
|
||||
});
|
||||
|
||||
test("names it, so the tag can say what it is", () => {
|
||||
const state = jsonState(`{"avatar":"${SMALL}"}`);
|
||||
const iter = decorationsFor(state).iter();
|
||||
expect(iter.value?.spec.widget.sniffed).toMatchObject({ mime: "image/png", label: "PNG" });
|
||||
});
|
||||
|
||||
test("leaves a value of the same size alone when nothing recognises it", () => {
|
||||
// The only difference from the case above is what the bytes turn out to be
|
||||
const prose = "x".repeat(SMALL.length);
|
||||
expect(collapsedRanges(jsonState(`{"note":"${prose}"}`))).toEqual([]);
|
||||
});
|
||||
|
||||
test("leaves anything under the media threshold alone, recognised or not", () => {
|
||||
const tiny = png(400);
|
||||
expect(tiny.length).toBeLessThan(COLLAPSE_MEDIA_CHARS);
|
||||
expect(collapsedRanges(jsonState(`{"icon":"${tiny}"}`))).toEqual([]);
|
||||
});
|
||||
|
||||
test("leaves text alone even when its first bytes match a signature", () => {
|
||||
// `Qk0` decodes to `BM`, the whole of the BMP signature. Two bytes come up by chance often
|
||||
// enough that the sniff alone must not be allowed to hide something.
|
||||
const prose = `Qk0 ${"the quick brown fox jumps over the lazy dog. ".repeat(40)}`;
|
||||
expect(prose.length).toBeGreaterThan(COLLAPSE_MEDIA_CHARS);
|
||||
expect(collapsedRanges(jsonState(`{"note":"${prose}"}`))).toEqual([]);
|
||||
});
|
||||
|
||||
test("still collapses it once it is long enough to be a rendering problem", () => {
|
||||
// Past the length rule the sniff no longer decides anything, so this is hidden for its size
|
||||
const prose = "Qk0 " + "words and more words ".repeat(COLLAPSE_TOKEN_CHARS);
|
||||
expect(collapsedRanges(jsonState(`{"note":"${prose}"}`))).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("collapses a data URI on a short line", () => {
|
||||
const state = jsonState(`{"avatar":"data:image/jpeg;base64,${SMALL}"}`);
|
||||
expect(collapsedRanges(state)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("still leaves an ordinary document completely untouched", () => {
|
||||
const doc = Array.from({ length: 5_000 }, (_, i) => ` { "id": ${i}, "name": "item" },`).join(
|
||||
"\n",
|
||||
);
|
||||
expect(collapsedRanges(jsonState(doc))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("media rule only, for a document being edited", () => {
|
||||
/** What an editable editor gets: rule 2 alone */
|
||||
function editableRanges(state: EditorState) {
|
||||
const ranges: { from: number; to: number }[] = [];
|
||||
const iter = collapseDecorations(state, [{ from: 0, to: state.doc.length }], "media").iter();
|
||||
while (iter.value != null) {
|
||||
ranges.push({ from: iter.from, to: iter.to });
|
||||
iter.next();
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
|
||||
function png(bytes: number) {
|
||||
const b = new Uint8Array(bytes);
|
||||
b.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
let binary = "";
|
||||
for (const byte of b) binary += String.fromCharCode(byte);
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
test("collapses a pasted image, the one thing it is for", () => {
|
||||
const value = png(3_000);
|
||||
const state = jsonState(`{\n "avatar": "${value}"\n}`);
|
||||
|
||||
expect(editableRanges(state)).toHaveLength(1);
|
||||
expect(state.sliceDoc(editableRanges(state)[0]!.from, editableRanges(state)[0]!.to)).toBe(
|
||||
value,
|
||||
);
|
||||
});
|
||||
|
||||
test("leaves a long value alone when nothing can name it", () => {
|
||||
// Rule 1 would take this on a stalling line. Editing it is plausible, so it stays.
|
||||
const doc = `{"blob":"${"Z".repeat(COLLAPSE_TOKEN_CHARS * 3)}"}`;
|
||||
expect(doc.length).toBeGreaterThan(MAX_VISIBLE_LINE_CHARS);
|
||||
expect(editableRanges(jsonState(doc))).toEqual([]);
|
||||
});
|
||||
|
||||
test("never cuts at the column limit, which would strand text out of reach", () => {
|
||||
// Rule 3 territory: a minified body with no value big enough to collapse on its own
|
||||
const doc = `[${Array.from({ length: 4_000 }, (_, i) => `"word-${i}"`).join(",")}]`;
|
||||
expect(doc.length).toBeGreaterThan(MAX_VISIBLE_LINE_CHARS);
|
||||
expect(editableRanges(jsonState(doc))).toEqual([]);
|
||||
// The read-only rules still cut it
|
||||
expect(collapsedRanges(jsonState(doc))).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("never swallows a template tag, collapsing only the run beside it", () => {
|
||||
// A brace is not in the base64 alphabet, so the run starts after the tag and the tag stays
|
||||
// on screen where it can still be read and edited
|
||||
const tag = "{{ image }}";
|
||||
const doc = `{"avatar":"${tag}${png(3_000)}"}`;
|
||||
const ranges = editableRanges(jsonState(doc));
|
||||
|
||||
expect(ranges).toHaveLength(1);
|
||||
expect(ranges[0]!.from).toBe(doc.indexOf(tag) + tag.length);
|
||||
expect(doc.slice(ranges[0]!.from, ranges[0]!.to)).not.toContain("{");
|
||||
});
|
||||
|
||||
test("finds a data URI whole, header and all", () => {
|
||||
const value = `data:image/jpeg;base64,${png(3_000)}`;
|
||||
const doc = `{"avatar":"${value}"}`;
|
||||
const ranges = editableRanges(jsonState(doc));
|
||||
|
||||
expect(ranges).toHaveLength(1);
|
||||
expect(doc.slice(ranges[0]!.from, ranges[0]!.to)).toBe(value);
|
||||
});
|
||||
|
||||
test("hides no line break, so the plugin may provide it from the viewport", () => {
|
||||
const state = jsonState(`{\n "a": "${png(3_000)}",\n "b": 1\n}`);
|
||||
for (const { from, to } of editableRanges(state)) {
|
||||
expect(state.sliceDoc(from, to)).not.toContain("\n");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("templated fields, where the grammar is an overlay", () => {
|
||||
// Every editable field mixes its language with twig, which mounts the base language as an
|
||||
// overlay. Overlays are not traversed by `Tree.iterate`, so a rule that walks the tree sees
|
||||
// one enormous Text node and finds nothing. Rule 2 reads the text instead, and this is the
|
||||
// case that has to keep working: an image pasted into a JSON request body.
|
||||
const twigState = (doc: string) =>
|
||||
EditorState.create({
|
||||
doc,
|
||||
extensions: [
|
||||
twig({
|
||||
base: jsonc(),
|
||||
environmentVariables: [],
|
||||
completionOptions: [],
|
||||
onClickVariable: () => {},
|
||||
onClickMissingVariable: () => {},
|
||||
onClickPathParameter: () => {},
|
||||
extraExtensions: [],
|
||||
}),
|
||||
largeValues,
|
||||
],
|
||||
});
|
||||
|
||||
function png(bytes: number) {
|
||||
const b = new Uint8Array(bytes);
|
||||
b.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
let binary = "";
|
||||
for (const byte of b) binary += String.fromCharCode(byte);
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
test("collapses a pasted image in a templated body", () => {
|
||||
const value = png(3_000);
|
||||
const state = twigState(`{\n "avatar": "${value}"\n}`);
|
||||
const ranges: { from: number; to: number }[] = [];
|
||||
const iter = collapseDecorations(state, [{ from: 0, to: state.doc.length }], "media").iter();
|
||||
while (iter.value != null) {
|
||||
ranges.push({ from: iter.from, to: iter.to });
|
||||
iter.next();
|
||||
}
|
||||
|
||||
expect(ranges).toHaveLength(1);
|
||||
expect(state.sliceDoc(ranges[0]!.from, ranges[0]!.to)).toBe(value);
|
||||
});
|
||||
});
|
||||
|
||||
describe("viewport scoping", () => {
|
||||
const doc = () => {
|
||||
const value = "A".repeat(COLLAPSE_TOKEN_CHARS * 2);
|
||||
return `{\n${["a", "b", "c"].map((k) => ` "${k}": "${value}"`).join(",\n")}\n}`;
|
||||
};
|
||||
|
||||
test("decorates only the ranges it is given", () => {
|
||||
const state = jsonState(doc());
|
||||
const secondLine = state.doc.line(3);
|
||||
|
||||
const all = collapseDecorations(state, [{ from: 0, to: state.doc.length }]);
|
||||
const one = collapseDecorations(state, [{ from: secondLine.from, to: secondLine.to }]);
|
||||
|
||||
expect(all.size).toBe(3);
|
||||
expect(one.size).toBe(1);
|
||||
});
|
||||
|
||||
test("covers a line the range only partly overlaps", () => {
|
||||
// The viewport can start mid-line; the collapse still has to span the whole value
|
||||
const state = jsonState(doc());
|
||||
const line = state.doc.line(2);
|
||||
const partial = collapseDecorations(state, [{ from: line.from + 5, to: line.from + 6 }]);
|
||||
|
||||
expect(partial.size).toBe(1);
|
||||
const iter = partial.iter();
|
||||
expect(iter.to).toBeGreaterThan(line.from + 6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,584 @@
|
||||
import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
|
||||
import { formatSize } from "@yaakapp-internal/lib/formatSize";
|
||||
import type { EditorState, Extension, Range } from "@codemirror/state";
|
||||
import type { Tree as SyntaxTree } from "@lezer/common";
|
||||
import type { DecorationSet, ViewUpdate } from "@codemirror/view";
|
||||
import { Decoration, EditorView, ViewPlugin, WidgetType } from "@codemirror/view";
|
||||
import { fireAndForget } from "../../../lib/fireAndForget";
|
||||
import type { SniffedValue } from "./sniffValue";
|
||||
import { isEncodedRun, SNIFF_HEAD_CHARS, sniffValue } from "./sniffValue";
|
||||
|
||||
/**
|
||||
* How much of a line may be rendered before the rest is collapsed.
|
||||
*
|
||||
* VS Code draws nothing past column 10,000 (`editor.stopRenderingLineAfter`) for the same
|
||||
* reason. It can afford to be blunt about it because it doesn't soft wrap by default; we
|
||||
* collapse to a placeholder that can be opened instead.
|
||||
*/
|
||||
export const MAX_VISIBLE_LINE_CHARS = 10_000;
|
||||
|
||||
/**
|
||||
* A quoted value longer than this is collapsed whole, whatever it turns out to hold. Long
|
||||
* enough that nothing a person might actually read is ever hidden on length alone.
|
||||
*/
|
||||
export const COLLAPSE_TOKEN_CHARS = 5_000;
|
||||
|
||||
/**
|
||||
* A quoted value longer than this is collapsed too, but only when {@link sniffValue} can say
|
||||
* what it is. Encoded media is never worth reading, so once we can name it and offer a viewer,
|
||||
* a tag beats a wall of base64 well below the length that would make it a rendering problem —
|
||||
* this covers the avatars and icons that make up most base64 in real payloads. Anything we
|
||||
* can't identify stays visible until it's big enough to be a problem on its own.
|
||||
*/
|
||||
export const COLLAPSE_MEDIA_CHARS = 1_000;
|
||||
|
||||
/**
|
||||
* Collapses what can't be read: over-long lines, which stall layout, and encoded media, which
|
||||
* is only noise on screen.
|
||||
*
|
||||
* Layout cost tracks the length of the longest line, not the size of the document. A 1 MB
|
||||
* response of ordinary multi-line JSON renders fine, while the same 1 MB on a single line stalls
|
||||
* the UI, because soft wrap has to measure the whole line end to end to find its break points.
|
||||
* Measured in WKWebView, the engine macOS ships: 221 ms per render pass at 1 MB and 968 ms at
|
||||
* 3 MB, against 51 ms and 138 ms once collapsed, with soft wrap left on.
|
||||
*
|
||||
* Three rules:
|
||||
*
|
||||
* 1. Collapse quoted values over {@link COLLAPSE_TOKEN_CHARS} whole, so a base64 string reads
|
||||
* as `"image": "PNG · 999.8 KB"` with its key intact. A minified body with several large
|
||||
* values keeps every one of its keys. Needs a grammar to find the value.
|
||||
* 2. Collapse quoted values over {@link COLLAPSE_MEDIA_CHARS} that sniff as a known format,
|
||||
* which is what catches an ordinary embedded image long before it is a rendering problem.
|
||||
* 3. On a line still over {@link MAX_VISIBLE_LINE_CHARS}, collapse whatever is left past the
|
||||
* column limit. This needs no grammar, so it covers plain text, undelimited tokens, and any
|
||||
* line that is simply long.
|
||||
*
|
||||
* Only what the viewport covers is examined, and only lines long enough to hold a collapse are
|
||||
* looked at, so a document of ordinary short lines costs a length check per visible line and
|
||||
* nothing else — no grammar is consulted and no tree is walked.
|
||||
*
|
||||
* Nothing leaves the document. Copy, filter and save all still see the full text, and the tag
|
||||
* itself is a button, opening a menu that views, copies or saves exactly what it stands for.
|
||||
*
|
||||
* The value's own head says what it is — a `data:` URI names its media type, and raw base64
|
||||
* gives its format up in the first dozen bytes — so the tag can name the format and open the
|
||||
* value in the matching viewer without any of it being read. See {@link sniffValue}.
|
||||
*
|
||||
* An editable document gets rule 2 alone, as {@link mediaValues}. Encoded media is never typed
|
||||
* by hand: it arrives pasted, and the only edit anyone makes to it is replacing it wholesale,
|
||||
* which the tag already supports — {@link EditorView.atomicRanges} makes it delete as one unit.
|
||||
* So collapsing it hides nothing anyone was going to read. The other two rules stay out, since
|
||||
* they hide text by length alone, without being able to say what it is: under rule 3 a minified
|
||||
* body would become uneditable past the column limit, which really would be editing text you
|
||||
* can't see.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Which of the three rules to apply.
|
||||
*
|
||||
* `media` is the subset safe for a document being edited: collapse only what we can name.
|
||||
*/
|
||||
export type CollapseRules = "all" | "media";
|
||||
|
||||
/**
|
||||
* A hidden range, the value it belongs to, and what that value turned out to be.
|
||||
*
|
||||
* The hidden range and the value differ under the column rule, where the value starts at the
|
||||
* beginning of the line but only what runs past the limit is hidden. The tag stands in for
|
||||
* [from, to) and copies exactly that; the viewer needs the whole value, [valueFrom, to).
|
||||
*/
|
||||
interface Collapse {
|
||||
from: number;
|
||||
to: number;
|
||||
valueFrom: number;
|
||||
sniffed: SniffedValue | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lucide's `chevron-down`, inlined because the widget builds its DOM synchronously and
|
||||
* rendering React here would leave it empty while CodeMirror measures line heights.
|
||||
*/
|
||||
const CHEVRON_DOWN =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" ' +
|
||||
'stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ' +
|
||||
'aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>';
|
||||
|
||||
/**
|
||||
* Marks the tag as the thing that opens the menu.
|
||||
*
|
||||
* The whole tag is the target rather than the chevron alone: there is only one action, and a
|
||||
* label you can't click next to a hit area a few pixels wide is a worse button than the tag
|
||||
* itself. The chevron stays as the affordance that says so.
|
||||
*
|
||||
* A span with a role rather than a real button, because a button's box model makes the line
|
||||
* taller — the one thing this extension exists to keep from happening.
|
||||
*/
|
||||
function makeTagButton(el: HTMLElement, title: string, onOpen: () => void) {
|
||||
el.role = "button";
|
||||
el.ariaHasPopup = "menu";
|
||||
el.tabIndex = 0;
|
||||
el.title = title;
|
||||
el.ariaLabel = title;
|
||||
|
||||
// Keep the editor from moving the cursor when the tag is pressed
|
||||
el.addEventListener("mousedown", (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
});
|
||||
el.addEventListener("click", (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onOpen();
|
||||
});
|
||||
el.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Enter" && e.key !== " ") return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onOpen();
|
||||
});
|
||||
}
|
||||
|
||||
class LargeValueWidget extends WidgetType {
|
||||
constructor(
|
||||
private readonly from: number,
|
||||
private readonly to: number,
|
||||
private readonly valueFrom: number,
|
||||
private readonly sniffed: SniffedValue | null,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
eq(other: LargeValueWidget) {
|
||||
return (
|
||||
other.from === this.from &&
|
||||
other.to === this.to &&
|
||||
other.valueFrom === this.valueFrom &&
|
||||
other.sniffed?.mime === this.sniffed?.mime
|
||||
);
|
||||
}
|
||||
|
||||
toDOM(view: EditorView) {
|
||||
const length = this.to - this.from;
|
||||
|
||||
const el = document.createElement("span");
|
||||
// The same neutral tag styling a path parameter uses. The theme scope matters: these
|
||||
// tokens resolve against the tag palette, not the editor's ambient one, where a
|
||||
// tag-sized border is meant to be near invisible.
|
||||
el.className = "x-theme-templateTag x-theme-templateTag--secondary template-tag";
|
||||
|
||||
const thumbnail = buildThumbnail(view, this.valueFrom, this.to, this.sniffed);
|
||||
if (thumbnail != null) {
|
||||
el.appendChild(thumbnail);
|
||||
}
|
||||
|
||||
const label = document.createElement("span");
|
||||
// A named type reads as a stand-in for the value, so it only needs to say what and how big.
|
||||
// Without a name there is nothing to show but the fact that something is missing.
|
||||
label.textContent =
|
||||
this.sniffed == null
|
||||
? `${formatSize(length)} hidden…`
|
||||
: `${this.sniffed.label} · ${formatSize(length)}`;
|
||||
el.appendChild(label);
|
||||
|
||||
const chevron = document.createElement("span");
|
||||
chevron.className = "tag-action";
|
||||
chevron.ariaHidden = "true";
|
||||
chevron.innerHTML = CHEVRON_DOWN;
|
||||
el.appendChild(chevron);
|
||||
|
||||
makeTagButton(
|
||||
el,
|
||||
this.sniffed == null ? "Value actions" : `${this.sniffed.label} actions`,
|
||||
() => fireAndForget(this.openMenu(view, el)),
|
||||
);
|
||||
|
||||
return el;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy, view and save, in a menu opened against the button.
|
||||
*
|
||||
* Everything the menu needs is pulled in on click. The editor loads on every response, and
|
||||
* neither the React menu nor the viewers behind the dialog are worth carrying until someone
|
||||
* asks for them.
|
||||
*/
|
||||
private async openMenu(view: EditorView, tag: HTMLElement) {
|
||||
const [{ toggleContextMenu }, { showLargeValueDialog }, { encodingLabel, largeValueActions }] =
|
||||
await Promise.all([
|
||||
import("../../../lib/contextMenu"),
|
||||
import("../../LargeValueDialog"),
|
||||
import("../../../lib/largeValue"),
|
||||
]);
|
||||
|
||||
const { sniffed } = this;
|
||||
// Sliced when an action runs rather than now, so opening the menu never touches the value
|
||||
const value = () => view.state.sliceDoc(this.valueFrom, this.to);
|
||||
const head = view.state.sliceDoc(
|
||||
this.valueFrom,
|
||||
Math.min(this.valueFrom + SNIFF_HEAD_CHARS, this.to),
|
||||
);
|
||||
|
||||
// The whole tag, so the menu can align to whichever edge has room beside it
|
||||
const rect = tag.getBoundingClientRect();
|
||||
toggleContextMenu({
|
||||
id: "large-value",
|
||||
triggerPosition: { x: rect.left, y: rect.bottom },
|
||||
triggerRect: rect,
|
||||
triggerEl: tag,
|
||||
items: [
|
||||
{ type: "separator", label: encodingLabel(head, sniffed, this.to - this.from) },
|
||||
...largeValueActions({
|
||||
value,
|
||||
sniffed,
|
||||
// Exactly what the tag stands in for, which under the column rule is only the tail
|
||||
copyText: () => view.state.sliceDoc(this.from, this.to),
|
||||
onView: () => showLargeValueDialog({ text: value(), sniffed }),
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
ignoreEvent() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How much encoded image a tag will preview. Roughly 3 MB of file, base64 being 4 bytes to 3.
|
||||
*
|
||||
* The decode runs on WebKit's image thread, but the bitmap it produces is sized by the image's
|
||||
* own dimensions, not by the box we draw it in — a 4000×3000 photo costs 48 MB however small the
|
||||
* thumbnail. So there has to be a limit, even though encoded size is only a proxy for the one
|
||||
* that matters: a well-compressed photo can decode larger than a lossless screenshot twice its
|
||||
* file size. This is set high enough to cover ordinary screenshots and wallpapers, since a tag
|
||||
* that previews some images and not others is worse than one that previews none. Only widgets in
|
||||
* the viewport are ever built, so a screenful is the most that decode at once.
|
||||
*/
|
||||
const THUMBNAIL_MAX_CHARS = 4_000_000;
|
||||
|
||||
/**
|
||||
* A preview of the value, at a size fixed before it loads.
|
||||
*
|
||||
* The box is a fixed square from the moment it's inserted, so the image arriving never changes
|
||||
* the line's height or the tag's width. A growing line box is the layout cost this whole
|
||||
* extension exists to avoid, and an image of unknown dimensions is the classic way to cause one.
|
||||
*
|
||||
* The src is the value's own text handed straight to the decoder as a data URI. Decoding the
|
||||
* base64 ourselves first would mean walking megabytes on the main thread, which is the one
|
||||
* thing that must not happen here.
|
||||
*/
|
||||
function buildThumbnail(
|
||||
view: EditorView,
|
||||
valueFrom: number,
|
||||
to: number,
|
||||
sniffed: SniffedValue | null,
|
||||
): HTMLElement | null {
|
||||
if (sniffed == null || !sniffed.mime.startsWith("image/")) return null;
|
||||
if (sniffed.encoding !== "base64") return null;
|
||||
if (to - valueFrom > THUMBNAIL_MAX_CHARS) return null;
|
||||
|
||||
const img = document.createElement("img");
|
||||
img.className = "tag-thumbnail";
|
||||
img.alt = "";
|
||||
img.ariaHidden = "true";
|
||||
img.decoding = "async";
|
||||
// A magic number can be wrong, and a data URI can lie. Drop the box rather than leave a
|
||||
// broken-image glyph sitting in the tag.
|
||||
img.addEventListener("error", () => img.remove());
|
||||
// Read the document and build the data URI after the widget is measured and on screen
|
||||
requestAnimationFrame(() => {
|
||||
if (!img.isConnected) return;
|
||||
const payload = view.state.sliceDoc(valueFrom + sniffed.offset, to);
|
||||
img.src = `data:${sniffed.mime};base64,${payload}`;
|
||||
});
|
||||
return img;
|
||||
}
|
||||
|
||||
interface Line {
|
||||
from: number;
|
||||
to: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The lines the given ranges touch, in document order and each listed once.
|
||||
*
|
||||
* Only lines long enough to hold a collapse are returned. That check is what keeps this free on
|
||||
* ordinary documents: no grammar is consulted and no tree is walked for a screen of short lines.
|
||||
*/
|
||||
function collapsibleLines(state: EditorState, ranges: readonly { from: number; to: number }[]) {
|
||||
const lines: Line[] = [];
|
||||
let lastFrom = -1;
|
||||
|
||||
for (const range of ranges) {
|
||||
let pos = range.from;
|
||||
for (;;) {
|
||||
const line = state.doc.lineAt(pos);
|
||||
if (line.from > lastFrom) {
|
||||
lastFrom = line.from;
|
||||
if (line.to - line.from >= COLLAPSE_MEDIA_CHARS) {
|
||||
lines.push({ from: line.from, to: line.to });
|
||||
}
|
||||
}
|
||||
if (line.to >= range.to) break;
|
||||
pos = line.to + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long to spend parsing before falling back to the column rule.
|
||||
*
|
||||
* The initial parse is budgeted by time, so it stops partway through a document with several
|
||||
* large values, and we'd only find the first one. Parsing the rest of a 1 MB body costs about
|
||||
* 12 ms, against the 171 ms of layout it saves.
|
||||
*/
|
||||
const PARSE_TIMEOUT_MS = 100;
|
||||
|
||||
/**
|
||||
* The parsed tree covering these lines.
|
||||
*
|
||||
* Parsing is only ever forced for a line long enough to stall layout, where finding the values
|
||||
* inside it is what saves the frame. For everything else we take whatever the background parse
|
||||
* has reached and decorate again when it advances — a forced parse runs from the top of the
|
||||
* document, so making one happen on every scroll would cost far more than the tags are worth.
|
||||
*/
|
||||
function treeForLines(state: EditorState, lines: Line[]): SyntaxTree {
|
||||
const last = lines[lines.length - 1];
|
||||
const stalls = lines.some((l) => l.to - l.from > MAX_VISIBLE_LINE_CHARS);
|
||||
if (last == null || !stalls) {
|
||||
return syntaxTree(state);
|
||||
}
|
||||
return ensureSyntaxTree(state, last.to, PARSE_TIMEOUT_MS) ?? syntaxTree(state);
|
||||
}
|
||||
|
||||
const QUOTES = ['"', "'", "`"];
|
||||
|
||||
/** A run of base64, long enough to be worth looking at. Nothing else can be encoded media. */
|
||||
const ENCODED_RUN = new RegExp(`[A-Za-z0-9+/=_-]{${COLLAPSE_MEDIA_CHARS},}`, "g");
|
||||
|
||||
/** The header that turns a bare run into a data URI, when one sits right before it. */
|
||||
const DATA_URI_HEAD = /data:[^,;\s"']*(?:;[^,;\s"']*)*;base64,$/;
|
||||
|
||||
/**
|
||||
* Encoded media on this line, found by reading the text rather than the grammar.
|
||||
*
|
||||
* Deliberately grammar-free. Every editable field in the app mixes its language with the twig
|
||||
* parser, which mounts the base language as an *overlay*, and overlays are not traversed by
|
||||
* `Tree.iterate` — so a rule that walks the tree finds one enormous `Text` node and nothing
|
||||
* inside it. Rule 2 has to work in those fields above all, since that is where images get
|
||||
* pasted, and a run of base64 is a text pattern anyway: no grammar can describe it better than
|
||||
* the alphabet does.
|
||||
*
|
||||
* A `data:` header is picked up by looking backwards from the run, so the whole URI collapses
|
||||
* as one thing and its declared type is what names it.
|
||||
*/
|
||||
function findMediaRuns(state: EditorState, line: Line): Collapse[] {
|
||||
const text = state.sliceDoc(line.from, line.to);
|
||||
const collapses: Collapse[] = [];
|
||||
|
||||
ENCODED_RUN.lastIndex = 0;
|
||||
for (let m = ENCODED_RUN.exec(text); m != null; m = ENCODED_RUN.exec(text)) {
|
||||
let start = m.index;
|
||||
// A data URI's own header breaks the alphabet, so the run starts after it
|
||||
const header = DATA_URI_HEAD.exec(text.slice(0, start));
|
||||
if (header != null) {
|
||||
start = header.index;
|
||||
}
|
||||
|
||||
const valueFrom = line.from + start;
|
||||
const valueTo = line.from + m.index + m[0].length;
|
||||
const head = state.sliceDoc(valueFrom, Math.min(valueFrom + SNIFF_HEAD_CHARS, valueTo));
|
||||
const sniffed = sniffValue(head);
|
||||
|
||||
// Only hide what we can name. A short magic number matches by chance now and then, so the
|
||||
// run itself has to look encoded too.
|
||||
if (sniffed != null && sniffed.encoding === "base64" && isEncodedRun(head, sniffed.offset)) {
|
||||
collapses.push({ from: valueFrom, to: valueTo, valueFrom, sniffed });
|
||||
}
|
||||
}
|
||||
|
||||
return collapses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Quoted values big enough to be a rendering problem on their own, whatever they hold.
|
||||
*
|
||||
* Needs the grammar, to find where the value starts and ends, and so only runs for a document
|
||||
* nobody is editing — which is also the only place this rule applies.
|
||||
*/
|
||||
function findLargeTokens(state: EditorState, tree: SyntaxTree, line: Line): Collapse[] {
|
||||
const collapses: Collapse[] = [];
|
||||
|
||||
tree.iterate({
|
||||
from: line.from,
|
||||
to: line.to,
|
||||
enter: (node) => {
|
||||
// A node this small can't contain anything worth collapsing, and neither can its children
|
||||
if (node.to - node.from < COLLAPSE_TOKEN_CHARS) return false;
|
||||
// Only leaves, so we collapse the string itself rather than the object holding it
|
||||
if (node.node.firstChild != null) return true;
|
||||
|
||||
const from = Math.max(node.from, line.from);
|
||||
const to = Math.min(node.to, line.to);
|
||||
const open = state.sliceDoc(from, from + 1);
|
||||
const quoted = to - from >= 2 && QUOTES.includes(open) && state.sliceDoc(to - 1, to) === open;
|
||||
if (!quoted) return false;
|
||||
|
||||
// Everything inside the quotes. The whole value is hidden, so it is its own value range
|
||||
const valueFrom = from + 1;
|
||||
const valueTo = to - 1;
|
||||
if (valueTo - valueFrom < COLLAPSE_TOKEN_CHARS) return false;
|
||||
|
||||
const head = state.sliceDoc(valueFrom, Math.min(valueFrom + SNIFF_HEAD_CHARS, valueTo));
|
||||
collapses.push({ from: valueFrom, to: valueTo, valueFrom, sniffed: sniffValue(head) });
|
||||
return false;
|
||||
},
|
||||
});
|
||||
|
||||
return collapses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Both rules' findings as one list, in document order, with nothing overlapping.
|
||||
*
|
||||
* A big quoted base64 value satisfies both rules, and two decorations over the same text is an
|
||||
* error. The token wins where they collide, because its range stops at the quotes and so leaves
|
||||
* the structure around it readable.
|
||||
*/
|
||||
function mergeCollapses(tokens: Collapse[], runs: Collapse[]): Collapse[] {
|
||||
const merged = [...tokens];
|
||||
for (const run of runs) {
|
||||
if (!tokens.some((t) => run.from < t.to && t.from < run.to)) {
|
||||
merged.push(run);
|
||||
}
|
||||
}
|
||||
return merged.sort((a, b) => a.from - b.from);
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the line runs past the column limit, counting only what is still visible after the
|
||||
* token collapses, or -1 if it fits.
|
||||
*/
|
||||
function findColumnCut(line: Line, tokens: Collapse[]): number {
|
||||
let visible = 0;
|
||||
let pos = line.from;
|
||||
|
||||
for (const token of [...tokens, null]) {
|
||||
const segmentEnd = token == null ? line.to : token.from;
|
||||
if (segmentEnd > pos) {
|
||||
if (visible + (segmentEnd - pos) > MAX_VISIBLE_LINE_CHARS) {
|
||||
return pos + (MAX_VISIBLE_LINE_CHARS - visible);
|
||||
}
|
||||
visible += segmentEnd - pos;
|
||||
}
|
||||
if (token != null) {
|
||||
pos = token.to;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
function collapsesForLine(
|
||||
state: EditorState,
|
||||
tree: SyntaxTree,
|
||||
line: Line,
|
||||
rules: CollapseRules,
|
||||
): Collapse[] {
|
||||
const runs = findMediaRuns(state, line);
|
||||
// Length alone only hides things on a line that would stall without it, and never in a
|
||||
// document being edited, where hiding text by size would put it out of reach
|
||||
const stalls = rules === "all" && line.to - line.from > MAX_VISIBLE_LINE_CHARS;
|
||||
const tokens = mergeCollapses(stalls ? findLargeTokens(state, tree, line) : [], runs);
|
||||
|
||||
// Short enough to render, so there is nothing left to cut
|
||||
if (!stalls) {
|
||||
return tokens;
|
||||
}
|
||||
|
||||
const cut = findColumnCut(line, tokens);
|
||||
if (cut < 0) {
|
||||
return tokens;
|
||||
}
|
||||
|
||||
// The cut always lands in a visible stretch, so it never splits a token collapse
|
||||
const kept = tokens.filter((t) => t.to <= cut);
|
||||
// Only the tail is hidden, but the value it belongs to runs from the start of the line — a
|
||||
// body that is nothing but one base64 blob is still recognisable from there
|
||||
const head = state.sliceDoc(line.from, Math.min(line.from + SNIFF_HEAD_CHARS, line.to));
|
||||
kept.push({ from: cut, to: line.to, valueFrom: line.from, sniffed: sniffValue(head) });
|
||||
return kept;
|
||||
}
|
||||
|
||||
/**
|
||||
* The collapses covering the given document ranges.
|
||||
*
|
||||
* Kept separate from the plugin so the rules can be exercised against a state directly, with no
|
||||
* view and no DOM.
|
||||
*/
|
||||
export function collapseDecorations(
|
||||
state: EditorState,
|
||||
ranges: readonly { from: number; to: number }[],
|
||||
rules: CollapseRules = "all",
|
||||
): DecorationSet {
|
||||
const lines = collapsibleLines(state, ranges);
|
||||
if (lines.length === 0) {
|
||||
return Decoration.none;
|
||||
}
|
||||
|
||||
const tree = treeForLines(state, lines);
|
||||
const decorations: Range<Decoration>[] = [];
|
||||
for (const line of lines) {
|
||||
for (const { from, to, valueFrom, sniffed } of collapsesForLine(state, tree, line, rules)) {
|
||||
const widget = new LargeValueWidget(from, to, valueFrom, sniffed);
|
||||
decorations.push(Decoration.replace({ widget }).range(from, to));
|
||||
}
|
||||
}
|
||||
return Decoration.set(decorations);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scoped to the viewport, so the cost is a screenful however big the document is.
|
||||
*
|
||||
* Recomputed when the document changes, when the viewport moves, and when background parsing
|
||||
* advances — a value can only be found once the grammar has reached it.
|
||||
*/
|
||||
function collapsePlugin(rules: CollapseRules) {
|
||||
return ViewPlugin.fromClass(
|
||||
class {
|
||||
decorations: DecorationSet;
|
||||
|
||||
constructor(view: EditorView) {
|
||||
this.decorations = collapseDecorations(view.state, view.visibleRanges, rules);
|
||||
}
|
||||
|
||||
update(update: ViewUpdate) {
|
||||
if (
|
||||
update.docChanged ||
|
||||
update.viewportChanged ||
|
||||
syntaxTree(update.startState) !== syntaxTree(update.state)
|
||||
) {
|
||||
this.decorations = collapseDecorations(
|
||||
update.view.state,
|
||||
update.view.visibleRanges,
|
||||
rules,
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
decorations: (v) => v.decorations,
|
||||
// Step the cursor over a placeholder instead of stranding it inside, and delete it whole
|
||||
provide: (plugin) =>
|
||||
EditorView.atomicRanges.of((view) => view.plugin(plugin)?.decorations ?? Decoration.none),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** All three rules. For a document nobody is editing. */
|
||||
export const largeValues: Extension = [collapsePlugin("all")];
|
||||
|
||||
/** Only what we can name, which is the part that is safe to hide while someone is editing. */
|
||||
export const mediaValues: Extension = [collapsePlugin("media")];
|
||||
@@ -0,0 +1,170 @@
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { decodeBase64Prefix, labelForMime, SNIFF_HEAD_CHARS, sniffValue } from "./sniffValue";
|
||||
|
||||
/** A base64 value that starts with `magic` and runs on for a while, as a real one would */
|
||||
function base64Of(magic: number[], length = 2_000): string {
|
||||
const bytes = new Uint8Array(length);
|
||||
bytes.set(magic);
|
||||
for (let i = magic.length; i < length; i++) {
|
||||
bytes[i] = i % 251;
|
||||
}
|
||||
let binary = "";
|
||||
for (const byte of bytes) {
|
||||
binary += String.fromCharCode(byte);
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
/** One character, one byte. These are all ASCII signatures. */
|
||||
function ascii(s: string): number[] {
|
||||
const bytes: number[] = [];
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
bytes.push(s.charCodeAt(i));
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/** Four bytes no signature looks at: a RIFF chunk length, or an ISO-BMFF box size */
|
||||
const IGNORED = [0x00, 0x00, 0x00, 0x20];
|
||||
|
||||
const PNG = [0x89, ...ascii("PNG"), 0x0d, 0x0a, 0x1a, 0x0a];
|
||||
const JPEG = [0xff, 0xd8, 0xff, 0xe0];
|
||||
const PDF = ascii("%PDF-1.7");
|
||||
|
||||
describe("magic numbers", () => {
|
||||
const cases: [string, number[], string, string][] = [
|
||||
["PNG", PNG, "image/png", "PNG"],
|
||||
["JPEG", JPEG, "image/jpeg", "JPEG"],
|
||||
["GIF", ascii("GIF89a"), "image/gif", "GIF"],
|
||||
["PDF", PDF, "application/pdf", "PDF"],
|
||||
["WEBP", [...ascii("RIFF"), ...IGNORED, ...ascii("WEBP")], "image/webp", "WEBP"],
|
||||
["WAV", [...ascii("RIFF"), ...IGNORED, ...ascii("WAVE")], "audio/wav", "WAV"],
|
||||
["ZIP", [...ascii("PK"), 0x03, 0x04], "application/zip", "ZIP"],
|
||||
["GZIP", [0x1f, 0x8b, 0x08], "application/gzip", "GZIP"],
|
||||
["MP3", [...ascii("ID3"), 0x04], "audio/mpeg", "MP3"],
|
||||
["OGG", ascii("OggS"), "audio/ogg", "OGG"],
|
||||
["FLAC", ascii("fLaC"), "audio/flac", "FLAC"],
|
||||
["WEBM", [0x1a, 0x45, 0xdf, 0xa3], "video/webm", "WEBM"],
|
||||
["MP4", [...IGNORED, ...ascii("ftypisom")], "video/mp4", "MP4"],
|
||||
["AVIF", [...IGNORED, ...ascii("ftypavif")], "image/avif", "AVIF"],
|
||||
["HEIC", [...IGNORED, ...ascii("ftypheic")], "image/heic", "HEIC"],
|
||||
["M4A", [...IGNORED, ...ascii("ftypM4A ")], "audio/mp4", "M4A"],
|
||||
["MOV", [...IGNORED, ...ascii("ftypqt ")], "video/quicktime", "MOV"],
|
||||
["BMP", ascii("BMxx"), "image/bmp", "BMP"],
|
||||
["TIFF", [...ascii("II"), 0x2a, 0x00], "image/tiff", "TIFF"],
|
||||
];
|
||||
|
||||
for (const [name, magic, mime, label] of cases) {
|
||||
test(`recognises ${name}`, () => {
|
||||
expect(sniffValue(base64Of(magic))).toEqual({ mime, label, offset: 0, encoding: "base64" });
|
||||
});
|
||||
}
|
||||
|
||||
test("recognises nothing in arbitrary base64", () => {
|
||||
expect(sniffValue(btoa("just some text that happens to be encoded"))).toBeNull();
|
||||
});
|
||||
|
||||
test("recognises nothing in text that isn't base64", () => {
|
||||
expect(sniffValue("the quick brown fox jumps over the lazy dog".repeat(10))).toBeNull();
|
||||
});
|
||||
|
||||
test("recognises nothing in a JWT-shaped value", () => {
|
||||
expect(sniffValue(`${btoa('{"alg":"HS256"}')}.${btoa('{"sub":"1"}')}.c2ln`)).toBeNull();
|
||||
});
|
||||
|
||||
test("reads the url-safe alphabet", () => {
|
||||
const urlSafe = base64Of(PNG).replaceAll("+", "-").replaceAll("/", "_");
|
||||
expect(sniffValue(urlSafe)?.label).toBe("PNG");
|
||||
});
|
||||
|
||||
test("ignores leading whitespace, and counts it in the offset", () => {
|
||||
expect(sniffValue(` ${base64Of(PNG)}`)).toMatchObject({ label: "PNG", offset: 3 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("data URIs", () => {
|
||||
test("takes the declared type over the bytes", () => {
|
||||
const uri = `data:image/svg+xml;base64,${btoa("<svg/>")}`;
|
||||
expect(sniffValue(uri)).toEqual({
|
||||
mime: "image/svg+xml",
|
||||
label: "SVG",
|
||||
offset: "data:image/svg+xml;base64,".length,
|
||||
encoding: "base64",
|
||||
});
|
||||
});
|
||||
|
||||
test("points past the header, so the payload can be decoded from there", () => {
|
||||
const payload = base64Of(PNG);
|
||||
const uri = `data:image/png;base64,${payload}`;
|
||||
const sniffed = sniffValue(uri)!;
|
||||
expect(uri.slice(sniffed.offset, sniffed.offset + 8)).toBe(payload.slice(0, 8));
|
||||
});
|
||||
|
||||
test("falls back to the bytes when the declared type says nothing", () => {
|
||||
const uri = `data:application/octet-stream;base64,${base64Of(PDF)}`;
|
||||
expect(sniffValue(uri)).toMatchObject({ mime: "application/pdf", label: "PDF" });
|
||||
});
|
||||
|
||||
test("handles a header with no type at all", () => {
|
||||
expect(sniffValue(`data:;base64,${base64Of(JPEG)}`)).toMatchObject({ mime: "image/jpeg" });
|
||||
});
|
||||
|
||||
test("handles extra parameters", () => {
|
||||
const uri = `data:text/plain;charset=utf-8;base64,${btoa("hello")}`;
|
||||
expect(sniffValue(uri)).toMatchObject({ mime: "text/plain", encoding: "base64" });
|
||||
});
|
||||
|
||||
test("handles a percent-encoded payload", () => {
|
||||
expect(sniffValue("data:text/html,%3Ch1%3Ehi%3C/h1%3E")).toEqual({
|
||||
mime: "text/html",
|
||||
label: "HTML",
|
||||
offset: "data:text/html,".length,
|
||||
encoding: "percent",
|
||||
});
|
||||
});
|
||||
|
||||
test("defaults a bare percent-encoded payload to text", () => {
|
||||
expect(sniffValue("data:,hello%20there")).toMatchObject({
|
||||
mime: "text/plain",
|
||||
encoding: "percent",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("decoding only the head", () => {
|
||||
test("reads no more of the value than the bytes asked for", () => {
|
||||
const big = base64Of(PNG, 3_000_000);
|
||||
// Truncating to the head must not change what is found, which is the whole point:
|
||||
// callers only ever hand it a slice
|
||||
expect(sniffValue(big.slice(0, SNIFF_HEAD_CHARS))).toEqual(sniffValue(big));
|
||||
});
|
||||
|
||||
test("decodes whole 4-character groups only", () => {
|
||||
// 12 bytes needs 16 characters; a 15-character slice yields the 12 bytes of 3 whole groups
|
||||
expect(decodeBase64Prefix(base64Of(PNG), 0, 12)).toHaveLength(12);
|
||||
expect(decodeBase64Prefix(base64Of(PNG).slice(0, 15), 0, 12)).toHaveLength(9);
|
||||
});
|
||||
|
||||
test("declines a value too short to hold a group", () => {
|
||||
expect(decodeBase64Prefix("abc", 0, 12)).toBeNull();
|
||||
});
|
||||
|
||||
test("declines text outside the alphabet", () => {
|
||||
expect(decodeBase64Prefix("hello world, not base64!", 0, 12)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("labels", () => {
|
||||
test.each([
|
||||
["image/png", "PNG"],
|
||||
["image/svg+xml", "SVG"],
|
||||
["text/plain", "TEXT"],
|
||||
["application/vnd.ms-excel", "MS-EXCEL"],
|
||||
["image/x-icon", "ICON"],
|
||||
["application/octet-stream", "APPLICATION"],
|
||||
["font/woff2", "WOFF2"],
|
||||
["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "DOCUMENT"],
|
||||
])("%s reads as %s", (mime, label) => {
|
||||
expect(labelForMime(mime)).toBe(label);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* What a collapsed value turns out to be.
|
||||
*
|
||||
* Sniffing reads the head of the value only. A `data:` URI states its own media type, and raw
|
||||
* base64 gives up its type in the first few bytes, so neither needs the rest — which is the
|
||||
* point, since the whole reason these values are collapsed is that touching all of one costs
|
||||
* enough to stall the UI.
|
||||
*/
|
||||
export interface SniffedValue {
|
||||
/** Full media type, e.g. `image/png`. What the dialog routes on. */
|
||||
mime: string;
|
||||
/** A word for the tag, e.g. `PNG`. */
|
||||
label: string;
|
||||
/** Where the encoded payload starts in the value, past any `data:` header. */
|
||||
offset: number;
|
||||
encoding: "base64" | "percent";
|
||||
}
|
||||
|
||||
/**
|
||||
* How much of a value {@link sniffValue} needs. Enough for a `data:` header of realistic
|
||||
* length, and far more than the 24 base64 characters the magic numbers are read from.
|
||||
*/
|
||||
export const SNIFF_HEAD_CHARS = 256;
|
||||
|
||||
/** Bytes the longest signature needs: `RIFF????WEBP`, and an ISO-BMFF brand at offset 8. */
|
||||
const SNIFF_BYTES = 12;
|
||||
|
||||
/** `data:[<mime>][;<param>…],` — the payload follows the comma. */
|
||||
const DATA_URI = /^data:([^,;]*)((?:;[^,;]*)*),/;
|
||||
|
||||
/** Media types that name no format, so the bytes are worth a look even when one is declared. */
|
||||
const UNINFORMATIVE = ["", "application/octet-stream", "binary/octet-stream"];
|
||||
|
||||
interface Signature {
|
||||
label: string;
|
||||
mime: string;
|
||||
offset?: number;
|
||||
/** Byte values, where `null` matches anything */
|
||||
magic: readonly (number | null)[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A magic number written as the ASCII it reads as, with `?` for a byte that varies.
|
||||
*
|
||||
* Indexed rather than iterated, because a signature is a sequence of bytes: one character here
|
||||
* is one byte, and splitting into code points would be the wrong unit for that.
|
||||
*/
|
||||
function ascii(pattern: string): (number | null)[] {
|
||||
const bytes: (number | null)[] = [];
|
||||
for (let i = 0; i < pattern.length; i++) {
|
||||
bytes.push(pattern[i] === "?" ? null : pattern.charCodeAt(i));
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
const SIGNATURES: readonly Signature[] = [
|
||||
{ label: "PNG", mime: "image/png", magic: [0x89, ...ascii("PNG"), 0x0d, 0x0a, 0x1a, 0x0a] },
|
||||
{ label: "JPEG", mime: "image/jpeg", magic: [0xff, 0xd8, 0xff] },
|
||||
{ label: "GIF", mime: "image/gif", magic: ascii("GIF8") },
|
||||
{ label: "BMP", mime: "image/bmp", magic: ascii("BM") },
|
||||
{ label: "WEBP", mime: "image/webp", magic: ascii("RIFF????WEBP") },
|
||||
{ label: "TIFF", mime: "image/tiff", magic: [...ascii("II"), 0x2a, 0x00] },
|
||||
{ label: "TIFF", mime: "image/tiff", magic: [...ascii("MM"), 0x00, 0x2a] },
|
||||
{ label: "ICO", mime: "image/x-icon", magic: [0x00, 0x00, 0x01, 0x00] },
|
||||
{ label: "PDF", mime: "application/pdf", magic: ascii("%PDF-") },
|
||||
{ label: "WAV", mime: "audio/wav", magic: ascii("RIFF????WAVE") },
|
||||
{ label: "AVI", mime: "video/x-msvideo", magic: ascii("RIFF????AVI ") },
|
||||
{ label: "MP3", mime: "audio/mpeg", magic: ascii("ID3") },
|
||||
// A bare MPEG frame header: 11 sync bits, then a layer III / II / I version pair
|
||||
{ label: "MP3", mime: "audio/mpeg", magic: [0xff, 0xfb] },
|
||||
{ label: "MP3", mime: "audio/mpeg", magic: [0xff, 0xf3] },
|
||||
{ label: "MP3", mime: "audio/mpeg", magic: [0xff, 0xf2] },
|
||||
{ label: "OGG", mime: "audio/ogg", magic: ascii("OggS") },
|
||||
{ label: "FLAC", mime: "audio/flac", magic: ascii("fLaC") },
|
||||
{ label: "WEBM", mime: "video/webm", magic: [0x1a, 0x45, 0xdf, 0xa3] },
|
||||
{ label: "ZIP", mime: "application/zip", magic: [...ascii("PK"), 0x03, 0x04] },
|
||||
{ label: "GZIP", mime: "application/gzip", magic: [0x1f, 0x8b] },
|
||||
{ label: "7Z", mime: "application/x-7z-compressed", magic: [...ascii("7z"), 0xbc, 0xaf, 0x27] },
|
||||
{ label: "RAR", mime: "application/vnd.rar", magic: ascii("Rar!") },
|
||||
{ label: "GLTF", mime: "model/gltf-binary", magic: ascii("glTF") },
|
||||
];
|
||||
|
||||
/**
|
||||
* ISO base media files all start `????ftyp`, so the format is in the brand that follows rather
|
||||
* than in the signature itself. Anything unlisted is some flavour of MP4.
|
||||
*/
|
||||
const ISO_BRANDS: Record<string, { mime: string; label: string }> = {
|
||||
avif: { mime: "image/avif", label: "AVIF" },
|
||||
avis: { mime: "image/avif", label: "AVIF" },
|
||||
heic: { mime: "image/heic", label: "HEIC" },
|
||||
heix: { mime: "image/heic", label: "HEIC" },
|
||||
hevc: { mime: "image/heic", label: "HEIC" },
|
||||
mif1: { mime: "image/heif", label: "HEIF" },
|
||||
msf1: { mime: "image/heif", label: "HEIF" },
|
||||
"M4A ": { mime: "audio/mp4", label: "M4A" },
|
||||
"qt ": { mime: "video/quicktime", label: "MOV" },
|
||||
};
|
||||
|
||||
function matches(bytes: Uint8Array, { magic, offset = 0 }: Signature): boolean {
|
||||
if (bytes.length < offset + magic.length) return false;
|
||||
return magic.every((b, i) => b == null || bytes[offset + i] === b);
|
||||
}
|
||||
|
||||
function readAscii(bytes: Uint8Array, from: number, length: number): string {
|
||||
return String.fromCharCode(...bytes.subarray(from, from + length));
|
||||
}
|
||||
|
||||
/** The format the first bytes of a file identify it as, or null if they identify nothing. */
|
||||
export function sniffBytes(bytes: Uint8Array): { mime: string; label: string } | null {
|
||||
if (readAscii(bytes, 4, 4) === "ftyp") {
|
||||
return ISO_BRANDS[readAscii(bytes, 8, 4)] ?? { mime: "video/mp4", label: "MP4" };
|
||||
}
|
||||
const sig = SIGNATURES.find((s) => matches(bytes, s));
|
||||
return sig == null ? null : { mime: sig.mime, label: sig.label };
|
||||
}
|
||||
|
||||
/**
|
||||
* The first `bytes` bytes of a base64 payload, or null if it isn't base64 after all.
|
||||
*
|
||||
* Only the characters those bytes need are decoded. The trailing partial group is dropped
|
||||
* rather than padded, since `atob` rejects a group of one or two characters outright and we
|
||||
* have no use for the byte a three-character group would add.
|
||||
*/
|
||||
export function decodeBase64Prefix(text: string, offset: number, bytes: number): Uint8Array | null {
|
||||
const wanted = Math.ceil(bytes / 3) * 4;
|
||||
let b64 = text.slice(offset, offset + wanted);
|
||||
b64 = b64.slice(0, b64.length - (b64.length % 4));
|
||||
if (b64.length === 0) return null;
|
||||
|
||||
// The URL-safe alphabet stands for the same bytes
|
||||
b64 = b64.replaceAll("-", "+").replaceAll("_", "/");
|
||||
if (!/^[A-Za-z0-9+/]+$/.test(b64)) return null;
|
||||
|
||||
try {
|
||||
const binary = atob(b64);
|
||||
const out = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
out[i] = binary.charCodeAt(i);
|
||||
}
|
||||
return out;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a value is, from its head alone, or null if nothing recognises it.
|
||||
*
|
||||
* `head` need only be the first {@link SNIFF_HEAD_CHARS} characters — pass more and the rest is
|
||||
* ignored. The offsets in the result are relative to the start of the whole value.
|
||||
*/
|
||||
export function sniffValue(head: string): SniffedValue | null {
|
||||
const lead = head.length - head.trimStart().length;
|
||||
const value = head.slice(lead);
|
||||
|
||||
const dataUri = DATA_URI.exec(value);
|
||||
if (dataUri != null) {
|
||||
const declared = dataUri[1]!.toLowerCase();
|
||||
const offset = lead + dataUri[0].length;
|
||||
if (!dataUri[2]!.split(";").includes("base64")) {
|
||||
// A percent-encoded payload states its own type or is text by definition
|
||||
const mime = declared === "" ? "text/plain" : declared;
|
||||
return { mime, label: labelForMime(mime), offset, encoding: "percent" };
|
||||
}
|
||||
if (!UNINFORMATIVE.includes(declared)) {
|
||||
return { mime: declared, label: labelForMime(declared), offset, encoding: "base64" };
|
||||
}
|
||||
return sniffBase64At(head, offset);
|
||||
}
|
||||
|
||||
return sniffBase64At(head, lead);
|
||||
}
|
||||
|
||||
function sniffBase64At(head: string, offset: number): SniffedValue | null {
|
||||
const bytes = decodeBase64Prefix(head, offset, SNIFF_BYTES);
|
||||
const sniffed = bytes == null ? null : sniffBytes(bytes);
|
||||
return sniffed == null ? null : { ...sniffed, offset, encoding: "base64" };
|
||||
}
|
||||
|
||||
/** The shortest run of base64 that {@link isEncodedRun} will accept as convincing */
|
||||
const ENCODED_RUN_CHARS = 64;
|
||||
|
||||
/**
|
||||
* Whether a value is one unbroken run of base64, rather than text that merely opens like it.
|
||||
*
|
||||
* A magic number is only a few bytes, so short ones match by chance — `BM` is two, which comes
|
||||
* up about once in every 65,000 values. That was harmless while a value had to be long enough
|
||||
* to hurt rendering before anything was hidden, and the sniff only chose the label. It is not
|
||||
* harmless when the sniff itself decides to hide something, so that rule asks for this as well:
|
||||
* prose leaves the alphabet within a few characters, and an encoded blob never does.
|
||||
*/
|
||||
export function isEncodedRun(head: string, offset: number): boolean {
|
||||
const run = head.slice(offset);
|
||||
return run.length >= ENCODED_RUN_CHARS && /^[A-Za-z0-9+/\-_]+={0,2}$/.test(run);
|
||||
}
|
||||
|
||||
/** Subtypes whose own name makes a poor label */
|
||||
const LABEL_OVERRIDES: Record<string, string> = {
|
||||
"text/plain": "TEXT",
|
||||
};
|
||||
|
||||
/**
|
||||
* A word short enough for a tag. The distinguishing part of a subtype is its last dotted
|
||||
* segment before any `+suffix`, so `image/svg+xml` reads as SVG and `application/vnd.ms-excel`
|
||||
* as MS-EXCEL. Anything still too long falls back to the top-level type.
|
||||
*/
|
||||
export function labelForMime(mime: string): string {
|
||||
const override = LABEL_OVERRIDES[mime];
|
||||
if (override != null) {
|
||||
return override;
|
||||
}
|
||||
|
||||
const [type, subtype] = mime.split("/");
|
||||
const word = (subtype ?? "").split("+")[0]!.split(".").pop()!.replace(/^x-/, "");
|
||||
if (word.length > 0 && word.length <= 10 && word !== "octet-stream") {
|
||||
return word.toUpperCase();
|
||||
}
|
||||
return (type ?? mime).toUpperCase();
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { Completion } from "@codemirror/autocomplete";
|
||||
import { EditorState, type TransactionSpec } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { applyUrlCompletion, getUrlCompletionConfig } from "./completion";
|
||||
|
||||
describe("applyUrlCompletion", () => {
|
||||
test("consumes an existing protocol suffix and preserves the rest of the URL", () => {
|
||||
expect(applyCompletion("http://rickandmortyapi.com/api/character", "http://", 4)).toBe(
|
||||
"http://rickandmortyapi.com/api/character",
|
||||
);
|
||||
});
|
||||
|
||||
test("inserts a protocol when there is no existing suffix", () => {
|
||||
expect(applyCompletion("htt", "http://", 3)).toBe("http://");
|
||||
});
|
||||
|
||||
test("replaces the full URL when accepting a saved URL", () => {
|
||||
expect(applyCompletion("htt://old.example/path", "https://new.example/api", 3)).toBe(
|
||||
"https://new.example/api",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getUrlCompletionConfig", () => {
|
||||
test("always includes protocols alongside saved URL options", () => {
|
||||
const config = getUrlCompletionConfig([{ label: "https://example.com" }]);
|
||||
|
||||
expect(config.options.map((option) => option.label)).toEqual([
|
||||
"http://",
|
||||
"https://",
|
||||
"https://example.com",
|
||||
]);
|
||||
expect(config.options.every((option) => option.apply === applyUrlCompletion)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
function applyCompletion(document: string, label: string, cursor: number) {
|
||||
let state = EditorState.create({ doc: document, selection: { anchor: cursor } });
|
||||
const view = {
|
||||
state,
|
||||
dispatch: (spec: TransactionSpec) => {
|
||||
state = state.update(spec).state;
|
||||
},
|
||||
} as unknown as EditorView;
|
||||
|
||||
applyUrlCompletion(view, { label } satisfies Completion, 0, cursor);
|
||||
return state.doc.toString();
|
||||
}
|
||||
@@ -1,9 +1,51 @@
|
||||
import { genericCompletion } from "../genericCompletion";
|
||||
import { insertCompletionText, pickedCompletion, type Completion } from "@codemirror/autocomplete";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import type { GenericCompletionOption } from "@yaakapp-internal/plugins";
|
||||
import {
|
||||
genericCompletion,
|
||||
type GenericCompletion,
|
||||
type GenericCompletionConfig,
|
||||
} from "../genericCompletion";
|
||||
|
||||
export const completions = genericCompletion({
|
||||
options: [
|
||||
{ label: "http://", type: "constant" },
|
||||
{ label: "https://", type: "constant" },
|
||||
],
|
||||
minMatch: 1,
|
||||
});
|
||||
const protocolOptions: GenericCompletionOption[] = [
|
||||
{ label: "http://", type: "constant" },
|
||||
{ label: "https://", type: "constant" },
|
||||
];
|
||||
|
||||
export function getUrlCompletionConfig(
|
||||
options: GenericCompletionOption[],
|
||||
minMatch = 3,
|
||||
): GenericCompletionConfig {
|
||||
const urlOptions = [
|
||||
...protocolOptions,
|
||||
...options.filter(
|
||||
(option) => !protocolOptions.some((protocol) => protocol.label === option.label),
|
||||
),
|
||||
];
|
||||
return {
|
||||
minMatch,
|
||||
options: urlOptions.map<GenericCompletion>((option) => ({
|
||||
...option,
|
||||
apply: applyUrlCompletion,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function applyUrlCompletion(
|
||||
view: EditorView,
|
||||
completion: Completion,
|
||||
from: number,
|
||||
to: number,
|
||||
) {
|
||||
const isProtocol = /^https?:\/\/$/.test(completion.label);
|
||||
const replaceTo = isProtocol
|
||||
? to + (view.state.sliceDoc(to, to + 3) === "://" ? 3 : 0)
|
||||
: view.state.doc.length;
|
||||
|
||||
view.dispatch({
|
||||
...insertCompletionText(view.state, completion.label, from, replaceTo),
|
||||
annotations: pickedCompletion.of(completion),
|
||||
});
|
||||
}
|
||||
|
||||
export const completions = genericCompletion(getUrlCompletionConfig([], 1));
|
||||
|
||||
@@ -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>',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -18,7 +18,10 @@ export const HotkeyList = ({ hotkeys, bottomSlot, className }: Props) => {
|
||||
{hotkeys.map((hotkey) => (
|
||||
<Fragment key={hotkey}>
|
||||
<HotkeyLabel className="truncate" action={hotkey} />
|
||||
<Hotkey className="ml-4" 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}
|
||||
|
||||
@@ -22,6 +22,7 @@ import { Button } from "./Button";
|
||||
import type { DropdownItem } from "./Dropdown";
|
||||
import { Dropdown } from "./Dropdown";
|
||||
import type { EditorProps } from "./Editor/Editor";
|
||||
import type { GenericCompletion } from "./Editor/genericCompletion";
|
||||
import { Editor } from "./Editor/LazyEditor";
|
||||
import { IconButton } from "./IconButton";
|
||||
import { IconTooltip } from "./IconTooltip";
|
||||
@@ -63,6 +64,13 @@ export type InputProps = Pick<
|
||||
placeholder?: string;
|
||||
required?: boolean;
|
||||
rightSlot?: ReactNode;
|
||||
/**
|
||||
* Show a chevron that opens the `autocomplete` options as a menu, so a value can be picked
|
||||
* without knowing what to type. Opt-in, because plenty of inputs pass `autocomplete` without
|
||||
* wanting the affordance (the URL bar completes from history, and a chevron there would be
|
||||
* noise). Renders nothing when there are no options to show.
|
||||
*/
|
||||
showOptionsPicker?: boolean;
|
||||
size?: "2xs" | "xs" | "sm" | "md" | "auto";
|
||||
stateKey: EditorProps["stateKey"];
|
||||
extraExtensions?: EditorProps["extraExtensions"];
|
||||
@@ -115,6 +123,7 @@ function BaseInput({
|
||||
readOnly,
|
||||
required,
|
||||
rightSlot,
|
||||
showOptionsPicker,
|
||||
size = "md",
|
||||
stateKey,
|
||||
tint,
|
||||
@@ -156,6 +165,17 @@ function BaseInput({
|
||||
[],
|
||||
);
|
||||
|
||||
// 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 pickerOptions = showOptionsPicker && !disabled ? (props.autocomplete?.options ?? []) : [];
|
||||
|
||||
const setEditorRef = useCallback(
|
||||
(h: EditorView | null) => {
|
||||
editorRef.current = h;
|
||||
@@ -350,12 +370,55 @@ function BaseInput({
|
||||
onClick={() => setObscured((o) => !o)}
|
||||
/>
|
||||
)}
|
||||
{pickerOptions.length > 0 && (
|
||||
<OptionsPickerDropdown options={pickerOptions} onSelect={insertOption} />
|
||||
)}
|
||||
{rightSlot}
|
||||
</HStack>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Chevron that opens the input's autocomplete options as a menu, for browsing values rather than
|
||||
* typing them. Shows `label` but inserts `apply` when set, so a long value can be listed under a
|
||||
* short name (e.g. a User-Agent).
|
||||
*
|
||||
* Skipped in the tab order: once focus is in the input, inline autocomplete offers the same
|
||||
* options, so this would only add a stop between fields. Hidden when the nearest container is
|
||||
* narrow and the input needs the width more — written as a `max` query so it stays visible for
|
||||
* inputs that have no container ancestor at all.
|
||||
*/
|
||||
function OptionsPickerDropdown({
|
||||
options,
|
||||
onSelect,
|
||||
}: {
|
||||
options: GenericCompletion[];
|
||||
onSelect: (value: string) => void;
|
||||
}) {
|
||||
const items = useMemo<DropdownItem[]>(
|
||||
() =>
|
||||
options.map((o) => ({
|
||||
label: o.label,
|
||||
onSelect: () => onSelect(typeof o.apply === "string" ? o.apply : o.label),
|
||||
})),
|
||||
[options, onSelect],
|
||||
);
|
||||
|
||||
return (
|
||||
<Dropdown items={items}>
|
||||
<IconButton
|
||||
tabIndex={-1}
|
||||
iconSize="sm"
|
||||
size="xs"
|
||||
icon="chevron_down"
|
||||
title="Show suggestions"
|
||||
className="mr-0.5 h-auto! my-0.5 text-text-subtlest @max-[24rem]:hidden"
|
||||
/>
|
||||
</Dropdown>
|
||||
);
|
||||
}
|
||||
|
||||
function validateRequire(v: string) {
|
||||
return v.length > 0;
|
||||
}
|
||||
|
||||
@@ -36,10 +36,19 @@ import type { RadioDropdownItem } from "./RadioDropdown";
|
||||
import { RadioDropdown } from "./RadioDropdown";
|
||||
|
||||
export interface PairEditorHandle {
|
||||
/**
|
||||
* Focus a row's name field once it's able to take focus. Focus can't land immediately when the
|
||||
* row isn't mounted yet or the editor is hidden — eg. sitting in a tab that's still becoming
|
||||
* active — so this retries for up to ~1s. A newer focus request cancels a pending one.
|
||||
*/
|
||||
focusName(id: string): void;
|
||||
/** Focus a row's value field. See {@link PairEditorHandle.focusName} for timing. */
|
||||
focusValue(id: string): void;
|
||||
}
|
||||
|
||||
/** ~1s at 60fps, plenty for a tab switch to land without spinning forever if it never does */
|
||||
const MAX_FOCUS_ATTEMPTS = 60;
|
||||
|
||||
export type PairEditorProps = {
|
||||
allowFileValues?: boolean;
|
||||
allowMultilineValues?: boolean;
|
||||
@@ -53,7 +62,7 @@ export type PairEditorProps = {
|
||||
nameValidate?: InputProps["validate"];
|
||||
noScroll?: boolean;
|
||||
onChange: (pairs: PairWithId[]) => void;
|
||||
pairs: Pair[];
|
||||
pairs: EditablePair[];
|
||||
stateKey: InputProps["stateKey"];
|
||||
setRef?: (n: PairEditorHandle) => void;
|
||||
valueAutocomplete?: (name: string) => GenericCompletionConfig | undefined;
|
||||
@@ -72,13 +81,35 @@ export type Pair = {
|
||||
contentType?: string;
|
||||
filename?: string;
|
||||
isFile?: boolean;
|
||||
readOnlyName?: boolean;
|
||||
};
|
||||
|
||||
export type PairWithId = Pair & {
|
||||
id: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A pair as handed to the editor. Adds behaviour that only the editor cares about, so the plain
|
||||
* `Pair` stays the shape that gets written to models.
|
||||
*/
|
||||
export type EditablePair = Pair & {
|
||||
/**
|
||||
* When set, name edits are held until the field blurs and then committed through this, instead
|
||||
* of calling `onChange` on every keystroke. Return false to reject the new name, which reverts
|
||||
* the field. For names that can't be written directly, like a URL path placeholder that lives
|
||||
* in the URL itself.
|
||||
*/
|
||||
commitName?: (name: string) => boolean;
|
||||
};
|
||||
|
||||
type EditablePairWithId = EditablePair & {
|
||||
id: string;
|
||||
};
|
||||
|
||||
/** Strip the editor-only fields, so they can never reach a model write */
|
||||
function toPairData({ commitName: _commitName, ...pair }: EditablePairWithId): PairWithId {
|
||||
return pair;
|
||||
}
|
||||
|
||||
/** Max number of pairs to show before prompting the user to reveal the rest */
|
||||
const MAX_INITIAL_PAIRS = 30;
|
||||
|
||||
@@ -106,8 +137,8 @@ export function PairEditor({
|
||||
setRef,
|
||||
}: PairEditorProps) {
|
||||
const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
|
||||
const [isDragging, setIsDragging] = useState<PairWithId | null>(null);
|
||||
const [pairs, setPairs] = useState<PairWithId[]>([]);
|
||||
const [isDragging, setIsDragging] = useState<EditablePairWithId | null>(null);
|
||||
const [pairs, setPairs] = useState<EditablePairWithId[]>([]);
|
||||
const [showAll, toggleShowAll] = useToggle(false);
|
||||
// NOTE: Use local force update key because we trigger an effect on forceUpdateKey change. If
|
||||
// we simply pass forceUpdateKey to the editor, the data set by useEffect will be stale.
|
||||
@@ -115,16 +146,38 @@ export function PairEditor({
|
||||
|
||||
const rowsRef = useRef<Record<string, RowHandle | null>>({});
|
||||
|
||||
const pendingFocusFrame = useRef<number | null>(null);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (pendingFocusFrame.current != null) cancelAnimationFrame(pendingFocusFrame.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const focusWhenReady = useCallback((id: string, field: "name" | "value") => {
|
||||
if (pendingFocusFrame.current != null) cancelAnimationFrame(pendingFocusFrame.current);
|
||||
|
||||
let attemptsLeft = MAX_FOCUS_ATTEMPTS;
|
||||
const attempt = () => {
|
||||
pendingFocusFrame.current = null;
|
||||
const row = rowsRef.current[id];
|
||||
const landed = field === "name" ? row?.focusName() : row?.focusValue();
|
||||
if (landed || --attemptsLeft <= 0) return;
|
||||
pendingFocusFrame.current = requestAnimationFrame(attempt);
|
||||
};
|
||||
attempt();
|
||||
}, []);
|
||||
|
||||
const handle = useMemo<PairEditorHandle>(
|
||||
() => ({
|
||||
focusName(id: string) {
|
||||
rowsRef.current[id]?.focusName();
|
||||
focusWhenReady(id, "name");
|
||||
},
|
||||
focusValue(id: string) {
|
||||
rowsRef.current[id]?.focusValue();
|
||||
focusWhenReady(id, "value");
|
||||
},
|
||||
}),
|
||||
[],
|
||||
[focusWhenReady],
|
||||
);
|
||||
|
||||
const initPairEditorRow = useCallback(
|
||||
@@ -147,7 +200,7 @@ export function PairEditor({
|
||||
// oxlint-disable-next-line react-hooks/exhaustive-deps -- Only care about forceUpdateKey
|
||||
useEffect(() => {
|
||||
// Remove empty headers on initial render and ensure they all have valid ids (pairs didn't use to have IDs)
|
||||
const newPairs: PairWithId[] = [];
|
||||
const newPairs: EditablePairWithId[] = [];
|
||||
for (let i = 0; i < originalPairs.length; i++) {
|
||||
const p = originalPairs[i];
|
||||
if (!p) continue; // Make TS happy
|
||||
@@ -155,6 +208,21 @@ export function PairEditor({
|
||||
newPairs.push(ensurePairId(p));
|
||||
}
|
||||
|
||||
// When the reset holds the exact same rows (eg. renaming a URL path placeholder, which keeps
|
||||
// every row id), swap the data in without rebuilding the row editors. Unfocused inputs re-seed
|
||||
// themselves when `defaultValue` changes, and a rebuild would drop the user's focus and
|
||||
// selection — like tabbing from a placeholder's name into its value.
|
||||
const trailingPair = pairs[pairs.length - 1];
|
||||
const sameRows =
|
||||
trailingPair != null &&
|
||||
isPairEmpty(trailingPair) &&
|
||||
pairs.length === newPairs.length + 1 &&
|
||||
newPairs.every((p, i) => p.id === pairs[i]?.id);
|
||||
if (sameRows) {
|
||||
setPairs([...newPairs, trailingPair]);
|
||||
return;
|
||||
}
|
||||
|
||||
// Add empty last pair if there is none
|
||||
const lastPair = newPairs[newPairs.length - 1];
|
||||
if (lastPair == null || !isPairEmpty(lastPair)) {
|
||||
@@ -166,10 +234,10 @@ export function PairEditor({
|
||||
}, [forceUpdateKey]);
|
||||
|
||||
const setPairsAndSave = useCallback(
|
||||
(fn: (pairs: PairWithId[]) => PairWithId[]) => {
|
||||
(fn: (pairs: EditablePairWithId[]) => EditablePairWithId[]) => {
|
||||
setPairs((oldPairs) => {
|
||||
const pairs = fn(oldPairs);
|
||||
onChange(pairs);
|
||||
onChange(pairs.map(toPairData));
|
||||
return pairs;
|
||||
});
|
||||
},
|
||||
@@ -177,7 +245,7 @@ export function PairEditor({
|
||||
);
|
||||
|
||||
const handleChange = useCallback(
|
||||
(pair: PairWithId) =>
|
||||
(pair: EditablePairWithId) =>
|
||||
setPairsAndSave((pairs) => pairs.map((p) => (pair.id !== p.id ? p : pair))),
|
||||
[setPairsAndSave],
|
||||
);
|
||||
@@ -362,14 +430,14 @@ export function PairEditor({
|
||||
|
||||
type PairEditorRowProps = {
|
||||
className?: string;
|
||||
pair: PairWithId;
|
||||
pair: EditablePairWithId;
|
||||
forceFocusNamePairId?: string | null;
|
||||
forceFocusValuePairId?: string | null;
|
||||
onChange?: (pair: PairWithId) => void;
|
||||
onDelete?: (pair: PairWithId, focusPrevious: boolean) => void;
|
||||
onFocusName?: (pair: PairWithId) => void;
|
||||
onFocusValue?: (pair: PairWithId) => void;
|
||||
onSubmit?: (pair: PairWithId) => void;
|
||||
onChange?: (pair: EditablePairWithId) => void;
|
||||
onDelete?: (pair: EditablePairWithId, focusPrevious: boolean) => void;
|
||||
onFocusName?: (pair: EditablePairWithId) => void;
|
||||
onFocusValue?: (pair: EditablePairWithId) => void;
|
||||
onSubmit?: (pair: EditablePairWithId) => void;
|
||||
isLast?: boolean;
|
||||
disabled?: boolean;
|
||||
disableDrag?: boolean;
|
||||
@@ -397,8 +465,8 @@ type PairEditorRowProps = {
|
||||
>;
|
||||
|
||||
interface RowHandle {
|
||||
focusName(): void;
|
||||
focusValue(): void;
|
||||
focusName(): boolean;
|
||||
focusValue(): boolean;
|
||||
}
|
||||
|
||||
export function PairEditorRow({
|
||||
@@ -436,9 +504,11 @@ export function PairEditorRow({
|
||||
const handle = useRef<RowHandle>({
|
||||
focusName() {
|
||||
nameInputRef.current?.focus();
|
||||
return nameInputRef.current?.isFocused() ?? false;
|
||||
},
|
||||
focusValue() {
|
||||
valueInputRef.current?.focus();
|
||||
return valueInputRef.current?.isFocused() ?? false;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -471,11 +541,37 @@ export function PairEditorRow({
|
||||
[onChange, pair],
|
||||
);
|
||||
|
||||
// The name being typed into a deferred-commit field, before it's committed or reverted
|
||||
const pendingName = useRef<string | null>(null);
|
||||
|
||||
const handleChangeName = useMemo(
|
||||
() => (name: string) => onChange?.({ ...pair, name }),
|
||||
() => (name: string) => {
|
||||
// Keep the edit local until commit. Writing on every keystroke would reset the editor from
|
||||
// beneath the cursor, since the pairs are derived from the name being edited.
|
||||
if (pair.commitName != null) pendingName.current = name;
|
||||
else onChange?.({ ...pair, name });
|
||||
},
|
||||
[onChange, pair],
|
||||
);
|
||||
|
||||
const revertName = useCallback(() => {
|
||||
const nameInput = nameInputRef.current;
|
||||
if (nameInput != null) {
|
||||
const changes = { from: 0, to: nameInput.value().length, insert: pair.name };
|
||||
nameInput.dispatch({ changes });
|
||||
}
|
||||
pendingName.current = null;
|
||||
}, [pair.name]);
|
||||
|
||||
const handleBlurName = useCallback(() => {
|
||||
if (pair.commitName == null) return;
|
||||
|
||||
const name = pendingName.current;
|
||||
pendingName.current = null;
|
||||
if (name == null || name === pair.name) return;
|
||||
if (!pair.commitName(name)) revertName();
|
||||
}, [pair, revertName]);
|
||||
|
||||
const handleChangeValueText = useMemo(
|
||||
() => (value: string) => onChange?.({ ...pair, value, isFile: false }),
|
||||
[onChange, pair],
|
||||
@@ -551,6 +647,10 @@ export function PairEditorRow({
|
||||
[setDraggableRef, setDroppableRef],
|
||||
);
|
||||
|
||||
// Skip the trailing placeholder row. It exists to start a new pair, so a picker there would
|
||||
// imply it's already a real row. `Input` handles the rest, including having no options to show.
|
||||
const showOptionsPicker = !isLast;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={handleSetRef}
|
||||
@@ -596,7 +696,7 @@ export function PairEditorRow({
|
||||
stateKey={`name.${pair.id}.${stateKey}`}
|
||||
disabled={disabled}
|
||||
wrapLines={false}
|
||||
readOnly={pair.readOnlyName || isDraggingGlobal}
|
||||
readOnly={isDraggingGlobal}
|
||||
size="sm"
|
||||
required={!isLast && !!pair.enabled && !!pair.value}
|
||||
validate={nameValidate}
|
||||
@@ -606,12 +706,14 @@ export function PairEditorRow({
|
||||
defaultValue={pair.name}
|
||||
label="Name"
|
||||
name={`name[${index}]`}
|
||||
onBlur={handleBlurName}
|
||||
onChange={handleChangeName}
|
||||
onFocus={handleFocusName}
|
||||
placeholder={namePlaceholder ?? "name"}
|
||||
autocomplete={nameAutocomplete}
|
||||
autocompleteVariables={nameAutocompleteVariables}
|
||||
autocompleteFunctions={nameAutocompleteFunctions}
|
||||
showOptionsPicker={showOptionsPicker}
|
||||
/>
|
||||
<div className="w-full grid grid-cols-[minmax(0,1fr)_auto] gap-1 items-center">
|
||||
{pair.isFile ? (
|
||||
@@ -656,6 +758,7 @@ export function PairEditorRow({
|
||||
autocomplete={valueAutocomplete?.(pair.name)}
|
||||
autocompleteFunctions={valueAutocompleteFunctions}
|
||||
autocompleteVariables={valueAutocompleteVariablesFiltered}
|
||||
showOptionsPicker={showOptionsPicker}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -675,8 +778,10 @@ export function PairEditorRow({
|
||||
<IconButton
|
||||
iconSize="sm"
|
||||
size="xs"
|
||||
icon={isLast || disabled ? "empty" : "chevron_down"}
|
||||
title="Select form data type"
|
||||
// Ellipsis rather than a chevron: the name and value fields now carry chevrons for
|
||||
// picking a suggestion, and this menu acts on the row instead of filling in a field.
|
||||
icon={isLast || disabled ? "empty" : "ellipsis_vertical"}
|
||||
title="More actions"
|
||||
className="text-text-subtlest"
|
||||
/>
|
||||
</Dropdown>
|
||||
@@ -800,7 +905,8 @@ function FileActionsDropdown({
|
||||
<IconButton
|
||||
iconSize="sm"
|
||||
size="xs"
|
||||
icon="chevron_down"
|
||||
// Matches the plain row menu, so the actions column reads the same for file and text rows
|
||||
icon="ellipsis_vertical"
|
||||
title="Select form data type"
|
||||
className="text-text-subtlest"
|
||||
/>
|
||||
@@ -808,7 +914,7 @@ function FileActionsDropdown({
|
||||
);
|
||||
}
|
||||
|
||||
function emptyPair(): PairWithId {
|
||||
function emptyPair(): EditablePairWithId {
|
||||
return ensurePairId({ enabled: true, name: "", value: "" });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { generateId } from "../../lib/generateId";
|
||||
import type { Pair, PairWithId } from "./PairEditor";
|
||||
|
||||
export function ensurePairId(p: Pair): PairWithId {
|
||||
// NOTE: Generic so callers keep whatever they passed in (eg. an EditablePair stays editable)
|
||||
export function ensurePairId<T extends Pair>(p: T): T & PairWithId {
|
||||
if (typeof p.id === "string") {
|
||||
return p as PairWithId;
|
||||
return p as T & PairWithId;
|
||||
}
|
||||
return { ...p, id: p.id ?? generateId() };
|
||||
}
|
||||
|
||||
@@ -4,23 +4,26 @@ import { useEffect, useState } from "react";
|
||||
interface Props {
|
||||
bodyPath?: string;
|
||||
data?: Uint8Array;
|
||||
mimeType?: string;
|
||||
}
|
||||
|
||||
export function AudioViewer({ bodyPath, data }: Props) {
|
||||
export function AudioViewer({ bodyPath, data, mimeType }: Props) {
|
||||
const [src, setSrc] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
if (bodyPath) {
|
||||
setSrc(convertFileSrc(bodyPath));
|
||||
} else if (data) {
|
||||
const blob = new Blob([new Uint8Array(data)], { type: "audio/mpeg" });
|
||||
// The type matters here in a way it doesn't for an image: a media element goes by what
|
||||
// the blob declares rather than sniffing it, so an Ogg labelled as MP3 won't play
|
||||
const blob = new Blob([new Uint8Array(data)], { type: mimeType ?? "audio/mpeg" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
setSrc(url);
|
||||
return () => URL.revokeObjectURL(url);
|
||||
} else {
|
||||
setSrc(undefined);
|
||||
}
|
||||
}, [bodyPath, data]);
|
||||
}, [bodyPath, data, mimeType]);
|
||||
|
||||
// oxlint-disable-next-line jsx-a11y/media-has-caption
|
||||
return <audio className="w-full" controls src={src} />;
|
||||
|
||||
@@ -219,7 +219,7 @@ function ActualEventStreamViewer({ response }: Props) {
|
||||
<SseSummaryFooter
|
||||
style={style}
|
||||
error={summary.error ? String(summary.error) : null}
|
||||
isLoading={summary.isLoading}
|
||||
isLoading={summary.isLoading && summary.data == null}
|
||||
onRenderMarkdownChange={renderMarkdownSetting.set}
|
||||
renderMarkdown={renderMarkdown}
|
||||
resultKeyPath={summarySettings.resultKeyPath ?? ""}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import classNames from "classnames";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
type Props = { className?: string } & (
|
||||
type Props = { className?: string; mimeType?: string } & (
|
||||
| {
|
||||
bodyPath: string;
|
||||
}
|
||||
@@ -11,7 +11,7 @@ type Props = { className?: string } & (
|
||||
}
|
||||
);
|
||||
|
||||
export function ImageViewer({ className, ...props }: Props) {
|
||||
export function ImageViewer({ className, mimeType, ...props }: Props) {
|
||||
const [src, setSrc] = useState<string>();
|
||||
const bodyPath = "bodyPath" in props ? props.bodyPath : null;
|
||||
const data = "data" in props ? props.data : null;
|
||||
@@ -20,14 +20,14 @@ export function ImageViewer({ className, ...props }: Props) {
|
||||
if (bodyPath != null) {
|
||||
setSrc(convertFileSrc(bodyPath));
|
||||
} else if (data != null) {
|
||||
const blob = new Blob([data], { type: "image/png" });
|
||||
const blob = new Blob([data], { type: mimeType ?? "image/png" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
setSrc(url);
|
||||
return () => URL.revokeObjectURL(url);
|
||||
} else {
|
||||
setSrc(undefined);
|
||||
}
|
||||
}, [bodyPath, data]);
|
||||
}, [bodyPath, data, mimeType]);
|
||||
|
||||
return (
|
||||
<img
|
||||
|
||||
@@ -3,7 +3,7 @@ import "react-pdf/dist/Page/AnnotationLayer.css";
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import "./PdfViewer.css";
|
||||
import type { PDFDocumentProxy } from "pdfjs-dist";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { Document, Page } from "react-pdf";
|
||||
import { useContainerSize } from "@yaakapp-internal/ui";
|
||||
import { fireAndForget } from "../../lib/fireAndForget";
|
||||
@@ -30,26 +30,32 @@ const options = {
|
||||
export function PdfViewer({ bodyPath, data }: Props) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [numPages, setNumPages] = useState<number>();
|
||||
const [src, setSrc] = useState<string | { data: Uint8Array }>();
|
||||
|
||||
const { width: containerWidth } = useContainerSize(containerRef);
|
||||
|
||||
useEffect(() => {
|
||||
// During render, not in an effect: an effect leaves the first paint with no file, and
|
||||
// `Document` renders its "Failed to load PDF file" state for that frame before recovering
|
||||
const src = useMemo(() => {
|
||||
if (bodyPath) {
|
||||
setSrc(convertFileSrc(bodyPath));
|
||||
} else if (data) {
|
||||
return convertFileSrc(bodyPath);
|
||||
}
|
||||
if (data) {
|
||||
// Create a copy to avoid "Buffer is already detached" errors
|
||||
// This happens when the ArrayBuffer is transferred/detached elsewhere
|
||||
const dataCopy = new Uint8Array(data);
|
||||
setSrc({ data: dataCopy });
|
||||
} else {
|
||||
setSrc(undefined);
|
||||
return { data: new Uint8Array(data) };
|
||||
}
|
||||
return undefined;
|
||||
}, [bodyPath, data]);
|
||||
|
||||
const onDocumentLoadSuccess = ({ numPages: nextNumPages }: PDFDocumentProxy): void => {
|
||||
setNumPages(nextNumPages);
|
||||
};
|
||||
|
||||
// Nothing to show yet, rather than the failure state `Document` renders for an empty file
|
||||
if (src == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="w-full h-full overflow-y-auto">
|
||||
<Document
|
||||
|
||||
@@ -4,23 +4,25 @@ import { useEffect, useState } from "react";
|
||||
interface Props {
|
||||
bodyPath?: string;
|
||||
data?: Uint8Array;
|
||||
mimeType?: string;
|
||||
}
|
||||
|
||||
export function VideoViewer({ bodyPath, data }: Props) {
|
||||
export function VideoViewer({ bodyPath, data, mimeType }: Props) {
|
||||
const [src, setSrc] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
if (bodyPath) {
|
||||
setSrc(convertFileSrc(bodyPath));
|
||||
} else if (data) {
|
||||
const blob = new Blob([new Uint8Array(data)], { type: "video/mp4" });
|
||||
// As in AudioViewer: a media element trusts the declared type instead of sniffing
|
||||
const blob = new Blob([new Uint8Array(data)], { type: mimeType ?? "video/mp4" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
setSrc(url);
|
||||
return () => URL.revokeObjectURL(url);
|
||||
} else {
|
||||
setSrc(undefined);
|
||||
}
|
||||
}, [bodyPath, data]);
|
||||
}, [bodyPath, data, mimeType]);
|
||||
|
||||
// oxlint-disable-next-line jsx-a11y/media-has-caption
|
||||
return <video className="w-full" controls src={src} />;
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
websocketRequestsAtom,
|
||||
} from "@yaakapp-internal/models";
|
||||
import { atom, useAtomValue } from "jotai";
|
||||
import { selectAtom } from "jotai/utils";
|
||||
|
||||
export const allRequestsAtom = atom((get) => [
|
||||
...get(httpRequestsAtom),
|
||||
@@ -14,3 +15,26 @@ export const allRequestsAtom = atom((get) => [
|
||||
export function useAllRequests() {
|
||||
return useAtomValue(allRequestsAtom);
|
||||
}
|
||||
|
||||
const stringArrayEqual = (a: string[], b: string[]) =>
|
||||
a.length === b.length && a.every((v, i) => v === b[i]);
|
||||
|
||||
// Identity-stable derivations so subscribers don't recompute or re-render when
|
||||
// unrelated request fields change (eg. every debounced edit of a request)
|
||||
export const allRequestIdsAtom = selectAtom(
|
||||
allRequestsAtom,
|
||||
(requests) => requests.map((r) => r.id),
|
||||
stringArrayEqual,
|
||||
);
|
||||
|
||||
export const allRequestUrlsAtom = selectAtom(
|
||||
allRequestsAtom,
|
||||
(requests) => {
|
||||
const urls = new Set<string>();
|
||||
for (const r of requests) {
|
||||
if (r.url) urls.add(r.url);
|
||||
}
|
||||
return Array.from(urls);
|
||||
},
|
||||
stringArrayEqual,
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { emit } from "@tauri-apps/api/event";
|
||||
import type { GrpcConnection, GrpcRequest } from "@yaakapp-internal/models";
|
||||
import { flushAllModelWrites } from "@yaakapp-internal/models";
|
||||
import { jotaiStore } from "../lib/jotai";
|
||||
import { minPromiseMillis } from "../lib/minPromiseMillis";
|
||||
import { invokeCmd } from "../lib/tauri";
|
||||
@@ -22,8 +23,14 @@ export function useGrpc(
|
||||
|
||||
const go = useMutation<void, string>({
|
||||
mutationKey: ["grpc_go", conn?.id],
|
||||
mutationFn: () =>
|
||||
invokeCmd<void>("cmd_grpc_go", { requestId, environmentId: environment?.id, protoFiles }),
|
||||
mutationFn: async () => {
|
||||
await flushAllModelWrites(); // The backend reads the request from the DB
|
||||
return invokeCmd<void>("cmd_grpc_go", {
|
||||
requestId,
|
||||
environmentId: environment?.id,
|
||||
protoFiles,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const send = useMutation({
|
||||
|
||||
@@ -6,21 +6,19 @@ import { useMemo } from "react";
|
||||
export function useParentFolders(m: Folder | HttpRequest | GrpcRequest | WebsocketRequest | null) {
|
||||
const folders = useAtomValue(foldersAtom);
|
||||
|
||||
return useMemo(() => getParentFolders(folders, m), [folders, m]);
|
||||
// Key on folderId, not the model itself, so edits to the model (eg. every URL
|
||||
// keystroke replacing the active request) don't produce a new array identity
|
||||
const folderId = m?.folderId ?? null;
|
||||
return useMemo(() => getParentFolders(folders, folderId), [folders, folderId]);
|
||||
}
|
||||
|
||||
function getParentFolders(
|
||||
folders: Folder[],
|
||||
currentModel: Folder | HttpRequest | GrpcRequest | WebsocketRequest | null,
|
||||
): Folder[] {
|
||||
if (currentModel == null) return [];
|
||||
function getParentFolders(folders: Folder[], folderId: string | null): Folder[] {
|
||||
if (folderId == null) return [];
|
||||
|
||||
const parentFolder = currentModel.folderId
|
||||
? folders.find((f) => f.id === currentModel.folderId)
|
||||
: null;
|
||||
const parentFolder = folders.find((f) => f.id === folderId);
|
||||
if (parentFolder == null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [parentFolder, ...getParentFolders(folders, parentFolder)];
|
||||
return [parentFolder, ...getParentFolders(folders, parentFolder.folderId ?? null)];
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { getResponseBodySseSummary } from "../lib/responseBody";
|
||||
export function useResponseBodySseSummary(response: HttpResponse, resultKeyPath: string | null) {
|
||||
return useQuery<SseSummary>({
|
||||
enabled: resultKeyPath != null,
|
||||
placeholderData: (prev) => prev, // Keep previous data on refetch
|
||||
queryKey: [
|
||||
"response-body-sse-summary",
|
||||
response.id,
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { atom } from "jotai";
|
||||
import type { DropdownItem } from "../components/core/Dropdown";
|
||||
import { jotaiStore } from "./jotai";
|
||||
|
||||
/**
|
||||
* A menu opened from somewhere that can't render React.
|
||||
*
|
||||
* Most menus in the app are a `Dropdown` wrapped around their own trigger. This is for the
|
||||
* cases where the trigger isn't a React component at all — a CodeMirror widget builds its DOM
|
||||
* synchronously, so it can only hand over a position and a list of items. Same shape as
|
||||
* {@link showDialog}.
|
||||
*/
|
||||
export interface ContextMenuInstance {
|
||||
id: string;
|
||||
/** Where to open, in viewport coordinates */
|
||||
triggerPosition: { x: number; y: number };
|
||||
/** The trigger's box, when it has one, so placement can align to its edges */
|
||||
triggerRect?: Pick<DOMRect, "top" | "bottom" | "left" | "right">;
|
||||
/** The element it belongs to, so clicking that doesn't read as a click outside */
|
||||
triggerEl?: HTMLElement | null;
|
||||
items: DropdownItem[];
|
||||
}
|
||||
|
||||
export const contextMenusAtom = atom<ContextMenuInstance[]>([]);
|
||||
|
||||
export function showContextMenu({ id, ...props }: ContextMenuInstance) {
|
||||
jotaiStore.set(contextMenusAtom, (m) => [...m.filter((c) => c.id !== id), { id, ...props }]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the menu, or closes it if this one is already open.
|
||||
*
|
||||
* What a trigger wants: pressing it a second time should put the menu away. Same shape as
|
||||
* {@link toggleDialog}.
|
||||
*/
|
||||
export function toggleContextMenu({ id, ...props }: ContextMenuInstance) {
|
||||
if (jotaiStore.get(contextMenusAtom).some((c) => c.id === id)) {
|
||||
hideContextMenu(id);
|
||||
} else {
|
||||
showContextMenu({ id, ...props });
|
||||
}
|
||||
}
|
||||
|
||||
export function hideContextMenu(id: string) {
|
||||
jotaiStore.set(contextMenusAtom, (m) => m.filter((c) => c.id !== id));
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Common Accept-Language values.
|
||||
export const acceptLanguages = [
|
||||
"*",
|
||||
"en",
|
||||
"en-US",
|
||||
"en-US,en;q=0.9",
|
||||
"en-GB,en;q=0.9",
|
||||
"de-DE,de;q=0.9,en;q=0.8",
|
||||
"fr-FR,fr;q=0.9,en;q=0.8",
|
||||
"es-ES,es;q=0.9,en;q=0.8",
|
||||
"ru-RU,ru;q=0.9,en;q=0.8",
|
||||
"uk-UA,uk;q=0.9,en;q=0.8",
|
||||
"zh-CN,zh;q=0.9,en;q=0.8",
|
||||
"ja-JP,ja;q=0.9,en;q=0.8",
|
||||
];
|
||||
@@ -0,0 +1,16 @@
|
||||
// Common Cache-Control directives (request and response).
|
||||
export const cacheControlDirectives = [
|
||||
"no-cache",
|
||||
"no-store",
|
||||
"no-transform",
|
||||
"max-age=0",
|
||||
"max-age=3600",
|
||||
"max-age=86400",
|
||||
"s-maxage=3600",
|
||||
"must-revalidate",
|
||||
"proxy-revalidate",
|
||||
"stale-while-revalidate=60",
|
||||
"public",
|
||||
"private",
|
||||
"immutable",
|
||||
];
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* A suggested value for a header. A plain string is used when the displayed
|
||||
* label and the inserted value are the same (e.g. mime types). The object form
|
||||
* lets us show a short, readable `label` (e.g. "Chrome (Windows)") while
|
||||
* inserting a longer `value` (the full User-Agent string).
|
||||
*/
|
||||
export type HeaderValuePreset = string | { label: string; value: string };
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { HeaderValuePreset } from "./headerValuePresets";
|
||||
|
||||
// Common, real-world User-Agent strings. The short `label` is shown in the
|
||||
// dropdown/autocomplete, while the full UA string is what gets inserted.
|
||||
//
|
||||
// Browsers freeze parts of their UA: Chrome reports its minor version as 0.0.0
|
||||
// and Safari reports macOS as 10_15_7, regardless of the actual version.
|
||||
export const userAgents: HeaderValuePreset[] = [
|
||||
{
|
||||
label: "Chrome 151 · Windows 10/11 · x64",
|
||||
value:
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36",
|
||||
},
|
||||
{
|
||||
label: "Edge 151 · Windows 10/11 · x64",
|
||||
value:
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36 Edg/151.0.0.0",
|
||||
},
|
||||
{
|
||||
label: "Firefox 153 · Windows 10/11 · x64",
|
||||
value: "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:153.0) Gecko/20100101 Firefox/153.0",
|
||||
},
|
||||
{
|
||||
label: "Chrome 151 · macOS",
|
||||
value:
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36",
|
||||
},
|
||||
{
|
||||
label: "Safari 27 · macOS",
|
||||
value:
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.0 Safari/605.1.15",
|
||||
},
|
||||
{
|
||||
label: "Chrome 151 · Linux · x64",
|
||||
value:
|
||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36",
|
||||
},
|
||||
{
|
||||
label: "Safari 27 · iOS 27 · iPhone",
|
||||
value:
|
||||
"Mozilla/5.0 (iPhone; CPU iPhone OS 27_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.0 Mobile/15E148 Safari/604.1",
|
||||
},
|
||||
{
|
||||
label: "Chrome 151 · Android 16 · Pixel 10",
|
||||
value:
|
||||
"Mozilla/5.0 (Linux; Android 16; Pixel 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Mobile Safari/537.36",
|
||||
},
|
||||
{ label: "curl 8.21.0 · CLI", value: "curl/8.21.0" },
|
||||
{ label: "Postman 7.56 · API client", value: "PostmanRuntime/7.56.1" },
|
||||
{ label: "Insomnia 13.1 · API client", value: "insomnia/13.1.0" },
|
||||
];
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { docFingerprint } from "./docFingerprint";
|
||||
|
||||
const sampled = (text: string) => docFingerprint(text, { exact: false });
|
||||
const exact = (text: string) => docFingerprint(text, { exact: true });
|
||||
|
||||
/** Same length as `text`, with one character changed at `at` */
|
||||
const changeAt = (text: string, at: number) =>
|
||||
`${text.slice(0, at)}${text[at] === "b" ? "c" : "b"}${text.slice(at + 1)}`;
|
||||
|
||||
describe("docFingerprint", () => {
|
||||
test("is stable for the same text", () => {
|
||||
expect(sampled("hello")).toBe(sampled("hello"));
|
||||
expect(exact("hello")).toBe(exact("hello"));
|
||||
});
|
||||
|
||||
test("differs on different short text", () => {
|
||||
expect(sampled("hello")).not.toBe(sampled("world"));
|
||||
});
|
||||
|
||||
test("differs on length alone", () => {
|
||||
expect(sampled("a".repeat(1_000_000))).not.toBe(sampled("a".repeat(1_000_001)));
|
||||
});
|
||||
|
||||
test("hashes small documents in full, so any change is caught", () => {
|
||||
const doc = "a".repeat(100);
|
||||
for (let i = 0; i < doc.length; i++) {
|
||||
expect(sampled(doc)).not.toBe(sampled(changeAt(doc, i)));
|
||||
}
|
||||
});
|
||||
|
||||
describe("sampled", () => {
|
||||
const doc = "a".repeat(1_000_000);
|
||||
|
||||
test("notices a change at the start", () => {
|
||||
expect(sampled(doc)).not.toBe(sampled(changeAt(doc, 0)));
|
||||
});
|
||||
|
||||
test("notices a change at the end", () => {
|
||||
expect(sampled(doc)).not.toBe(sampled(changeAt(doc, doc.length - 1)));
|
||||
});
|
||||
|
||||
test("notices a change in the middle", () => {
|
||||
expect(sampled(doc)).not.toBe(sampled(changeAt(doc, doc.length / 2)));
|
||||
});
|
||||
|
||||
test("misses a same-length change between the samples", () => {
|
||||
// The documented cost of sampling. Read-only editors accept it because the worst a
|
||||
// collision can do there is restore a fold or the cursor to the wrong place.
|
||||
expect(sampled(doc)).toBe(sampled(changeAt(doc, 250_000)));
|
||||
});
|
||||
});
|
||||
|
||||
describe("exact", () => {
|
||||
const doc = "a".repeat(1_000_000);
|
||||
|
||||
test("catches a same-length change anywhere, which is why editable docs use it", () => {
|
||||
for (const at of [0, 250_000, doc.length / 2, 750_000, doc.length - 1]) {
|
||||
expect(exact(doc)).not.toBe(exact(changeAt(doc, at)));
|
||||
}
|
||||
});
|
||||
|
||||
test("does not collide with the sampled fingerprint of the same text", () => {
|
||||
expect(exact(doc)).not.toBe(sampled(doc));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { md5 } from "js-md5";
|
||||
|
||||
/** How much of each end and the middle to hash */
|
||||
const SAMPLE_CHARS = 512;
|
||||
|
||||
/**
|
||||
* Identifies a document, so a cached editor state is never restored onto different content.
|
||||
*
|
||||
* Hashing the whole document costs about 4 ms per megabyte and is paid on every editor update
|
||||
* as well as on restore, which is a lot of work for a document nobody can edit.
|
||||
*
|
||||
* `exact` decides how much certainty that buys. Editable documents get a full hash, because a
|
||||
* collision there would restore undo history belonging to other content and let an undo write
|
||||
* nonsense into the body. Read-only documents get a sampled one: they hold the megabyte-sized
|
||||
* responses this exists for, their history can never be applied, and the worst a collision can
|
||||
* do is put a fold or the cursor in the wrong place.
|
||||
*
|
||||
* Sampling still pins the exact length plus three windows, so a colliding pair has to agree on
|
||||
* all four and differ only in between. Documents small enough to hash outright still are.
|
||||
*/
|
||||
export function docFingerprint(text: string, { exact }: { exact: boolean }): string {
|
||||
if (exact || text.length <= SAMPLE_CHARS * 3) {
|
||||
return `${text.length}:${md5(text)}`;
|
||||
}
|
||||
|
||||
const middle = Math.floor((text.length - SAMPLE_CHARS) / 2);
|
||||
return [
|
||||
text.length,
|
||||
md5(text.slice(0, SAMPLE_CHARS)),
|
||||
md5(text.slice(middle, middle + SAMPLE_CHARS)),
|
||||
md5(text.slice(-SAMPLE_CHARS)),
|
||||
].join(":");
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import { save } from "@tauri-apps/plugin-dialog";
|
||||
import { Icon } from "@yaakapp-internal/ui";
|
||||
import mime from "mime";
|
||||
import { createElement } from "react";
|
||||
import type { DropdownItem } from "../components/core/Dropdown";
|
||||
import type { SniffedValue } from "../components/core/Editor/sniffValue";
|
||||
import { isEncodedRun } from "../components/core/Editor/sniffValue";
|
||||
import { copyToClipboard } from "./copy";
|
||||
import { fireAndForget } from "./fireAndForget";
|
||||
import { invokeCmd } from "./tauri";
|
||||
import { showToast } from "./toast";
|
||||
|
||||
/**
|
||||
* How the value is written, which is the thing worth knowing about it — that it is base64
|
||||
* explains why it reads as gibberish far better than its length does.
|
||||
*
|
||||
* A value we couldn't identify may still be plainly encoded, so it is checked here too: an
|
||||
* unrecognised format and an unrecognised encoding are different things to be told.
|
||||
*
|
||||
* `head` need only be the first {@link SNIFF_HEAD_CHARS} characters of the value.
|
||||
*/
|
||||
export function encodingLabel(head: string, sniffed: SniffedValue | null, chars: number): string {
|
||||
const size = `${chars.toLocaleString()} chars`;
|
||||
if (sniffed?.encoding === "percent") {
|
||||
return `Percent-encoded · ${size}`;
|
||||
}
|
||||
const encoded = sniffed?.encoding === "base64" || isEncodedRun(head, sniffed?.offset ?? 0);
|
||||
return encoded ? `Base64 · ${size}` : size;
|
||||
}
|
||||
|
||||
interface ActionOptions {
|
||||
/** The whole value. A function, so opening a menu never copies megabytes to build it. */
|
||||
value: () => string;
|
||||
sniffed: SniffedValue | null;
|
||||
/** What to copy. The tag copies only what it hides; the viewer copies what it shows. */
|
||||
copyText: () => string;
|
||||
/** Left out inside the viewer itself, where there is nothing further to open */
|
||||
onView?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The things you can do with a collapsed value, as menu items.
|
||||
*
|
||||
* Shared so the tag in the editor and the dialog it opens offer the same list, rather than
|
||||
* drifting apart.
|
||||
*/
|
||||
export function largeValueActions({
|
||||
value,
|
||||
sniffed,
|
||||
copyText,
|
||||
onView,
|
||||
}: ActionOptions): DropdownItem[] {
|
||||
const items: DropdownItem[] = [];
|
||||
|
||||
if (onView != null) {
|
||||
items.push({
|
||||
label: sniffed == null ? "View" : `View ${sniffed.label}`,
|
||||
leftSlot: createElement(Icon, { icon: "eye" }),
|
||||
onSelect: onView,
|
||||
});
|
||||
}
|
||||
|
||||
// Two ways to copy a picture, because either can be the one you wanted: the image to paste
|
||||
// somewhere that takes one, or the text to paste back into a request
|
||||
const image = isCopyableImage(sniffed);
|
||||
if (image) {
|
||||
items.push({
|
||||
label: "Copy Image",
|
||||
leftSlot: createElement(Icon, { icon: "copy" }),
|
||||
onSelect: () => copyImage(value(), sniffed, copyText()),
|
||||
});
|
||||
}
|
||||
|
||||
items.push({
|
||||
label: sniffed?.encoding === "base64" ? "Copy Base64" : "Copy",
|
||||
// Second of a pair reads as one thing with two options, so it keeps the indent without
|
||||
// repeating the icon above it
|
||||
leftSlot: createElement(Icon, { icon: image ? "empty" : "copy" }),
|
||||
onSelect: () => copyToClipboard(copyText()),
|
||||
});
|
||||
|
||||
items.push({
|
||||
label: "Save to File",
|
||||
leftSlot: createElement(Icon, { icon: "download" }),
|
||||
onSelect: () =>
|
||||
fireAndForget(saveValue(value(), sniffed, sniffed?.label.toLowerCase() ?? "value")),
|
||||
});
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
/** The payload, with the `data:` header taken off. */
|
||||
function payloadOf(text: string, sniffed: SniffedValue): string {
|
||||
return text.slice(sniffed.offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* A payload every strict base64 decoder will accept.
|
||||
*
|
||||
* The url-safe alphabet stands for the same bytes, and a ragged final group is dropped rather
|
||||
* than padded — it can only ever be worth a single byte, and both `atob` and the Rust decoder
|
||||
* behind the save command reject one outright.
|
||||
*/
|
||||
function normalizeBase64(payload: string): string {
|
||||
const clean = payload.replace(/\s+/g, "").replaceAll("-", "+").replaceAll("_", "/");
|
||||
return clean.slice(0, clean.length - (clean.length % 4));
|
||||
}
|
||||
|
||||
/**
|
||||
* The bytes a collapsed value stands for.
|
||||
*
|
||||
* `atob` rather than `Uint8Array.fromBase64`, which is too new to rely on across the webviews we
|
||||
* ship on. Only ever called for something the user asked to see, never during layout.
|
||||
*/
|
||||
export function decodeValue(text: string, sniffed: SniffedValue): Uint8Array<ArrayBuffer> {
|
||||
const payload = payloadOf(text, sniffed);
|
||||
if (sniffed.encoding === "percent") {
|
||||
return new TextEncoder().encode(decodeURIComponent(payload));
|
||||
}
|
||||
|
||||
const binary = atob(normalizeBase64(payload));
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
bytes[i] = binary.charCodeAt(i);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the clipboard can take this as a picture rather than as text.
|
||||
*
|
||||
* SVG is left out on purpose: it is markup, so it pastes usefully as text, and rasterising it
|
||||
* would throw away the thing that makes it worth having.
|
||||
*/
|
||||
function isCopyableImage(sniffed: SniffedValue | null): sniffed is SniffedValue {
|
||||
return (
|
||||
sniffed != null && sniffed.mime.startsWith("image/") && !sniffed.mime.startsWith("image/svg")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The value as a PNG.
|
||||
*
|
||||
* Not a preference: PNG is the only image format the Clipboard API requires a browser to accept
|
||||
* on write — `text/plain`, `text/html` and `image/png` are the spec's mandatory data types — and
|
||||
* engines reject `image/jpeg` outright. So anything else is rasterised through a canvas, which
|
||||
* costs a decode and an encode but means a JPEG or a WEBP pastes just as readily as a PNG.
|
||||
*
|
||||
* `ClipboardItem.supports()` exists to ask whether a format could be written as it stands, and
|
||||
* skipping the conversion would be worth real time on a large photo. It was tried: WebKit says
|
||||
* no to `image/jpeg`, so the check only ever chose PNG and was removed again.
|
||||
*
|
||||
* The re-encode is lossless, so nothing is degraded, but a photograph lands on the clipboard far
|
||||
* larger than its JPEG. That matters less than it looks: the system pasteboard holds images
|
||||
* uncompressed regardless of what we hand it.
|
||||
*/
|
||||
async function toPngBlob(text: string, sniffed: SniffedValue): Promise<Blob> {
|
||||
const blob = new Blob([decodeValue(text, sniffed)], { type: sniffed.mime });
|
||||
if (sniffed.mime === "image/png") {
|
||||
return blob;
|
||||
}
|
||||
|
||||
const bitmap = await createImageBitmap(blob);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = bitmap.width;
|
||||
canvas.height = bitmap.height;
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (ctx == null) {
|
||||
throw new Error("Could not get a canvas to convert the image");
|
||||
}
|
||||
ctx.drawImage(bitmap, 0, 0);
|
||||
bitmap.close();
|
||||
|
||||
return await new Promise((resolve, reject) => {
|
||||
canvas.toBlob(
|
||||
(png) => (png == null ? reject(new Error("Could not encode the image")) : resolve(png)),
|
||||
"image/png",
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the picture on the clipboard, so it can be pasted anywhere that takes an image.
|
||||
*
|
||||
* Not awaited, and deliberately so. The webview only allows a clipboard write that starts inside
|
||||
* the click that asked for it, and decoding a few megabytes takes longer than that lasts — so
|
||||
* the item is handed the still-pending promise rather than a finished blob.
|
||||
*/
|
||||
export function copyImage(text: string, sniffed: SniffedValue, fallback: string) {
|
||||
if (typeof ClipboardItem === "undefined") {
|
||||
copyToClipboard(fallback);
|
||||
return;
|
||||
}
|
||||
|
||||
const png = toPngBlob(text, sniffed);
|
||||
navigator.clipboard
|
||||
.write([new ClipboardItem({ "image/png": png })])
|
||||
.then(() =>
|
||||
showToast({
|
||||
id: "copied",
|
||||
color: "success",
|
||||
icon: "copy",
|
||||
// Says PNG because that is what lands on the clipboard, whatever the value held
|
||||
message: "Copied as PNG",
|
||||
}),
|
||||
)
|
||||
.catch((err: unknown) => {
|
||||
// Anything from a webview that won't take an image to a file we couldn't decode. The
|
||||
// encoded text is always there to fall back on.
|
||||
console.error("Failed to copy image, copying text instead", err);
|
||||
copyToClipboard(fallback);
|
||||
});
|
||||
}
|
||||
|
||||
/** Base64 of a byte array, in chunks so a few megabytes don't blow the argument limit. */
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a collapsed value to a file the user picks.
|
||||
*
|
||||
* A value that is already base64 goes straight to the backend as-is — decoding it here only to
|
||||
* encode it again would walk megabytes twice for nothing.
|
||||
*/
|
||||
export async function saveValue(text: string, sniffed: SniffedValue | null, name: string) {
|
||||
const ext = sniffed == null ? "txt" : (mime.getExtension(sniffed.mime) ?? "bin");
|
||||
const filepath = await save({ defaultPath: `${name}.${ext}`, title: "Save Value" });
|
||||
if (filepath == null) {
|
||||
return; // Cancelled
|
||||
}
|
||||
|
||||
const data =
|
||||
sniffed == null
|
||||
? toBase64(new TextEncoder().encode(text))
|
||||
: sniffed.encoding === "base64"
|
||||
? normalizeBase64(payloadOf(text, sniffed))
|
||||
: toBase64(decodeValue(text, sniffed));
|
||||
|
||||
await invokeCmd("cmd_save_base64_to_binary", { filepath, data });
|
||||
showToast({ message: `Saved to ${filepath}` });
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { extractPathPlaceholders } from "./pathPlaceholders";
|
||||
import {
|
||||
derivePathPlaceholderPairs,
|
||||
extractPathPlaceholders,
|
||||
renamePathPlaceholder,
|
||||
} from "./pathPlaceholders";
|
||||
|
||||
describe("extractPathPlaceholders", () => {
|
||||
test("extracts a single placeholder", () => {
|
||||
@@ -26,3 +30,185 @@ describe("extractPathPlaceholders", () => {
|
||||
expect(extractPathPlaceholders("https://example.com/foo/bar?q=1#hash")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("derivePathPlaceholderPairs", () => {
|
||||
const neverRename = () => false;
|
||||
|
||||
test("adds a row for a placeholder with no parameter", () => {
|
||||
const { urlParameterPairs } = derivePathPlaceholderPairs("/users/:id", [], neverRename);
|
||||
expect(urlParameterPairs).toMatchObject([{ name: ":id", value: "", enabled: true }]);
|
||||
expect(urlParameterPairs[0]?.commitName).toBeTypeOf("function");
|
||||
});
|
||||
|
||||
test("gives the existing parameter for a placeholder a commitName, without mutating it", () => {
|
||||
const parameter = { name: ":id", value: "123", enabled: true, id: "p1" };
|
||||
const { urlParameterPairs } = derivePathPlaceholderPairs(
|
||||
"/users/:id",
|
||||
[parameter],
|
||||
neverRename,
|
||||
);
|
||||
expect(urlParameterPairs[0]).toMatchObject({ name: ":id", value: "123", id: "p1" });
|
||||
expect(urlParameterPairs[0]?.commitName).toBeTypeOf("function");
|
||||
expect(parameter).toEqual({ name: ":id", value: "123", enabled: true, id: "p1" });
|
||||
});
|
||||
|
||||
test("leaves query parameters alone", () => {
|
||||
const { urlParameterPairs } = derivePathPlaceholderPairs(
|
||||
"/users/:id",
|
||||
[{ name: "q", value: "hi", enabled: true, id: "p1" }],
|
||||
neverRename,
|
||||
);
|
||||
expect(urlParameterPairs[0]).toEqual({ name: "q", value: "hi", enabled: true, id: "p1" });
|
||||
expect(urlParameterPairs[1]?.commitName).toBeTypeOf("function");
|
||||
});
|
||||
|
||||
test("commitName renames this row's placeholder", () => {
|
||||
const renames: [string, string][] = [];
|
||||
const { urlParameterPairs } = derivePathPlaceholderPairs(
|
||||
"/a/:x/b/:y",
|
||||
[],
|
||||
(oldName, newName) => {
|
||||
renames.push([oldName, newName]);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
urlParameterPairs[1]?.commitName?.(":z");
|
||||
expect(renames).toEqual([[":y", ":z"]]);
|
||||
});
|
||||
|
||||
test("drops empty parameters", () => {
|
||||
const { urlParameterPairs } = derivePathPlaceholderPairs(
|
||||
"/users",
|
||||
[
|
||||
{ name: "", value: "", enabled: true, id: "p1" },
|
||||
{ name: "q", value: "", enabled: true, id: "p2" },
|
||||
],
|
||||
neverRename,
|
||||
);
|
||||
expect(urlParameterPairs).toMatchObject([{ name: "q", id: "p2" }]);
|
||||
});
|
||||
|
||||
test("collapses a placeholder that appears twice into one row", () => {
|
||||
const { urlParameterPairs } = derivePathPlaceholderPairs("/a/:id/b/:id", [], neverRename);
|
||||
expect(urlParameterPairs).toMatchObject([{ name: ":id" }]);
|
||||
});
|
||||
|
||||
test("gives a derived row the same id every time, so re-deriving is stable", () => {
|
||||
const first = derivePathPlaceholderPairs("/users/:id", [], neverRename);
|
||||
const second = derivePathPlaceholderPairs("/users/:id", [], neverRename);
|
||||
expect(first.urlParameterPairs[0]?.id).toEqual(second.urlParameterPairs[0]?.id);
|
||||
});
|
||||
|
||||
test("derived row ids avoid colliding with a persisted derived id", () => {
|
||||
// A derived id sticks to the parameter once the user gives the row a value. If its placeholder
|
||||
// is then renamed away in the URL bar, the parameter survives as a stray still holding the id,
|
||||
// and the replacement placeholder's row must not collide with it.
|
||||
const stray = { name: ":old", value: "42", enabled: true, id: "path-placeholder:0" };
|
||||
const { urlParameterPairs } = derivePathPlaceholderPairs("/pets/:new", [stray], neverRename);
|
||||
const ids = urlParameterPairs.map((p) => p.id);
|
||||
expect(new Set(ids).size).toEqual(ids.length);
|
||||
});
|
||||
|
||||
test("keeps a derived row's id stable across a rename", () => {
|
||||
const before = derivePathPlaceholderPairs("/a/:x/b/:y", [], neverRename);
|
||||
const after = derivePathPlaceholderPairs("/a/:x2/b/:y", [], neverRename);
|
||||
expect(after.urlParameterPairs.map((p) => p.id)).toEqual(
|
||||
before.urlParameterPairs.map((p) => p.id),
|
||||
);
|
||||
});
|
||||
|
||||
test("keys off the placeholder names", () => {
|
||||
expect(derivePathPlaceholderPairs("/a/:x/b/:y", [], neverRename).urlParametersKey).toEqual(
|
||||
":x,:y",
|
||||
);
|
||||
expect(derivePathPlaceholderPairs("/a/b", [], neverRename).urlParametersKey).toEqual("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("renamePathPlaceholder", () => {
|
||||
const model = (url: string, urlParameters: { name: string; value: string }[] = []) => ({
|
||||
url,
|
||||
urlParameters,
|
||||
});
|
||||
|
||||
test("renames the placeholder in the URL", () => {
|
||||
expect(
|
||||
renamePathPlaceholder(model("https://x.com/pets/:petId/info"), ":petId", ":animalId"),
|
||||
).toEqual({ url: "https://x.com/pets/:animalId/info", urlParameters: [] });
|
||||
});
|
||||
|
||||
test("carries the parameter value over to the new name", () => {
|
||||
const patch = renamePathPlaceholder(
|
||||
model("/pets/:petId", [
|
||||
{ name: "q", value: "1" },
|
||||
{ name: ":petId", value: "42" },
|
||||
]),
|
||||
":petId",
|
||||
":animalId",
|
||||
);
|
||||
expect(patch).toEqual({
|
||||
url: "/pets/:animalId",
|
||||
urlParameters: [
|
||||
{ name: "q", value: "1" },
|
||||
{ name: ":animalId", value: "42" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("renames every occurrence of a repeated placeholder", () => {
|
||||
expect(renamePathPlaceholder(model("/a/:id/b/:id"), ":id", ":key")?.url).toEqual(
|
||||
"/a/:key/b/:key",
|
||||
);
|
||||
});
|
||||
|
||||
test("adds a missing leading colon", () => {
|
||||
expect(renamePathPlaceholder(model("/pets/:petId"), ":petId", "animalId")?.url).toEqual(
|
||||
"/pets/:animalId",
|
||||
);
|
||||
});
|
||||
|
||||
test("renames a placeholder followed by a literal colon", () => {
|
||||
expect(renamePathPlaceholder(model("/tasks/:id:cancel"), ":id", ":taskId")?.url).toEqual(
|
||||
"/tasks/:taskId:cancel",
|
||||
);
|
||||
});
|
||||
|
||||
test("does not rename a placeholder the new name is a prefix of", () => {
|
||||
expect(renamePathPlaceholder(model("/a/:id/b/:idx"), ":id", ":key")?.url).toEqual(
|
||||
"/a/:key/b/:idx",
|
||||
);
|
||||
});
|
||||
|
||||
test("does not touch a same-named segment that isn't a placeholder", () => {
|
||||
expect(renamePathPlaceholder(model("/id/:id?x=:id"), ":id", ":key")?.url).toEqual(
|
||||
"/id/:key?x=:id",
|
||||
);
|
||||
});
|
||||
|
||||
test("treats regex characters in the old name literally", () => {
|
||||
expect(renamePathPlaceholder(model("/a/:i.d/b/:iXd"), ":i.d", ":key")?.url).toEqual(
|
||||
"/a/:key/b/:iXd",
|
||||
);
|
||||
});
|
||||
|
||||
test.each([[""], [":"], [":a/b"], [":a?b"], [":a#b"], [":a:b"], [":a b"], [":a\tb"]])(
|
||||
"rejects the unusable name %j",
|
||||
(name) => {
|
||||
expect(renamePathPlaceholder(model("/pets/:petId"), ":petId", name)).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
test("rejects a name already used by another placeholder", () => {
|
||||
expect(renamePathPlaceholder(model("/pets/:petId/:ownerId"), ":petId", ":ownerId")).toBeNull();
|
||||
});
|
||||
|
||||
test("allows renaming a placeholder to itself", () => {
|
||||
expect(renamePathPlaceholder(model("/pets/:petId"), ":petId", ":petId")?.url).toEqual(
|
||||
"/pets/:petId",
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects renaming a placeholder that isn't in the URL", () => {
|
||||
expect(renamePathPlaceholder(model("/pets/:petId"), ":other", ":animalId")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import type { HttpUrlParameter } from "@yaakapp-internal/models";
|
||||
import type { EditablePair } from "../components/core/PairEditor";
|
||||
|
||||
/**
|
||||
* Extract `:name`-style path placeholders from a URL string.
|
||||
*
|
||||
@@ -12,3 +15,88 @@
|
||||
export function extractPathPlaceholders(url: string): string[] {
|
||||
return Array.from(url.matchAll(/\/(:[^/?#:]+)/g)).map((m) => m[1] ?? "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the rows for the Params tab: the request's URL parameters, plus a row for each path
|
||||
* placeholder in the URL that doesn't have one yet. A placeholder that appears more than once
|
||||
* in the URL still gets a single row.
|
||||
*
|
||||
* Only placeholder rows get a `commitName`, which makes the editor hold name edits until blur and
|
||||
* hand them to `renamePlaceholder` instead of writing on every keystroke — renaming has to rewrite
|
||||
* the URL too. `renamePlaceholder` returns false to reject the new name, which reverts the field.
|
||||
*
|
||||
* `urlParametersKey` changes whenever the URL's placeholders do, and is used to reset the pair
|
||||
* editor so derived rows appear and disappear along with the URL.
|
||||
*/
|
||||
export function derivePathPlaceholderPairs(
|
||||
url: string,
|
||||
urlParameters: HttpUrlParameter[],
|
||||
renamePlaceholder: (oldName: string, newName: string) => boolean,
|
||||
): { urlParameterPairs: EditablePair[]; urlParametersKey: string } {
|
||||
const placeholderNames = extractPathPlaceholders(url);
|
||||
const commitNameFor = (oldName: string) => (newName: string) =>
|
||||
renamePlaceholder(oldName, newName);
|
||||
|
||||
// NOTE: Copy each parameter because `commitName` is UI-only. Adding it in place would mutate the
|
||||
// persisted model.
|
||||
const urlParameterPairs: EditablePair[] = urlParameters
|
||||
.filter((p) => p.name || p.value)
|
||||
.map((p) =>
|
||||
placeholderNames.includes(p.name) ? { ...p, commitName: commitNameFor(p.name) } : { ...p },
|
||||
);
|
||||
|
||||
// NOTE: Ids are derived from the placeholder's position instead of generated, so neither
|
||||
// re-deriving nor renaming hands a row a new identity. The pair editor keys rows by id, so a
|
||||
// changed id remounts the row and drops the user's focus.
|
||||
//
|
||||
// A derived id sticks to the parameter once the user gives the row a value, so a parameter that
|
||||
// outlives its placeholder (renamed away in the URL bar) still holds one. Skip past taken ids
|
||||
// so a new placeholder at that position can't collide with it.
|
||||
const takenIds = new Set(urlParameterPairs.map((p) => p.id));
|
||||
const uniquePlaceholderNames = [...new Set(placeholderNames)];
|
||||
for (const [index, name] of uniquePlaceholderNames.entries()) {
|
||||
if (urlParameterPairs.some((p) => p.name === name)) continue;
|
||||
|
||||
let id = `path-placeholder:${index}`;
|
||||
for (let bump = index + 1; takenIds.has(id); bump++) id = `path-placeholder:${bump}`;
|
||||
takenIds.add(id);
|
||||
|
||||
urlParameterPairs.push({ name, value: "", enabled: true, commitName: commitNameFor(name), id });
|
||||
}
|
||||
|
||||
return { urlParameterPairs, urlParametersKey: placeholderNames.join(",") };
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the patch for renaming a path placeholder: every occurrence replaced in the URL, and
|
||||
* the matching URL parameter renamed so the user's value follows along. Both have to be applied
|
||||
* together, or the value detaches from the placeholder.
|
||||
*
|
||||
* Returns `null` when the rename can't be applied, meaning the caller should leave the model
|
||||
* alone. That's the case when the new name wouldn't parse as a placeholder anymore (empty, or
|
||||
* containing `/`, `?`, `#`, `:`, or whitespace) or when it's already used by another placeholder
|
||||
* in the URL. A missing leading `:` is added rather than rejected, since focusing the name field
|
||||
* selects all of its text and typing over it is the natural way to rename.
|
||||
*/
|
||||
export function renamePathPlaceholder(
|
||||
model: { url: string; urlParameters: HttpUrlParameter[] },
|
||||
oldName: string,
|
||||
newName: string,
|
||||
): { url: string; urlParameters: HttpUrlParameter[] } | null {
|
||||
const name = newName.startsWith(":") ? newName : `:${newName}`;
|
||||
if (!/^:[^/?#:\s]+$/.test(name)) return null;
|
||||
|
||||
const placeholderNames = extractPathPlaceholders(model.url);
|
||||
if (!placeholderNames.includes(oldName)) return null;
|
||||
if (name !== oldName && placeholderNames.includes(name)) return null;
|
||||
|
||||
const pattern = new RegExp(`(/)${escapeRegExp(oldName)}(?=[/?#:]|$)`, "g");
|
||||
return {
|
||||
url: model.url.replace(pattern, (_match, slash: string) => `${slash}${name}`),
|
||||
urlParameters: model.urlParameters.map((p) => (p.name === oldName ? { ...p, name } : p)),
|
||||
};
|
||||
}
|
||||
|
||||
function escapeRegExp(text: string): string {
|
||||
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ type TauriCmd =
|
||||
| "cmd_plugin_init_errors"
|
||||
| "cmd_reload_plugins"
|
||||
| "cmd_render_template"
|
||||
| "cmd_save_base64_to_binary"
|
||||
| "cmd_save_response"
|
||||
| "cmd_secure_template"
|
||||
| "cmd_send_ephemeral_request"
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
"@shopify/lang-jsonc": "^1.0.1",
|
||||
"@tanstack/react-query": "^5.90.5",
|
||||
"@tanstack/react-router": "^1.133.13",
|
||||
"@tanstack/react-virtual": "^3.13.12",
|
||||
"@tanstack/react-virtual": "^3.14.9",
|
||||
"@tauri-apps/api": "^2.11.0",
|
||||
"@tauri-apps/plugin-clipboard-manager": "^2.3.2",
|
||||
"@tauri-apps/plugin-dialog": "^2.7.1",
|
||||
@@ -57,7 +57,7 @@
|
||||
"lucide-react": "^0.525.0",
|
||||
"mime": "^4.0.4",
|
||||
"motion": "^12.4.7",
|
||||
"nanoid": "^5.0.9",
|
||||
"nanoid": "^5.1.16",
|
||||
"papaparse": "^5.4.1",
|
||||
"parse-color": "^1.0.0",
|
||||
"react": "^19.2.0",
|
||||
|
||||
@@ -12,6 +12,9 @@ import { queryClient } from "../lib/queryClient";
|
||||
|
||||
const Toasts = lazy(() => import("../components/Toasts").then((m) => ({ default: m.Toasts })));
|
||||
const Dialogs = lazy(() => import("../components/Dialogs").then((m) => ({ default: m.Dialogs })));
|
||||
const ContextMenus = lazy(() =>
|
||||
import("../components/ContextMenus").then((m) => ({ default: m.ContextMenus })),
|
||||
);
|
||||
|
||||
export const Route = createRootRoute({
|
||||
component: RouteComponent,
|
||||
@@ -29,6 +32,7 @@ function RouteComponent() {
|
||||
<Suspense>
|
||||
<Toasts />
|
||||
<Dialogs />
|
||||
<ContextMenus />
|
||||
</Suspense>
|
||||
<Layout />
|
||||
<GlobalHooks />
|
||||
|
||||
@@ -16,6 +16,7 @@ use tokio::net::{TcpListener, TcpStream};
|
||||
const OAUTH_CLIENT_ID: &str = "a1fe44800c2d7e803cad1b4bf07a291c";
|
||||
const KEYRING_USER: &str = "yaak";
|
||||
const AUTH_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
const CALLBACK_READ_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const MAX_REQUEST_BYTES: usize = 16 * 1024;
|
||||
|
||||
type CommandResult<T = ()> = std::result::Result<T, String>;
|
||||
@@ -209,35 +210,71 @@ async fn receive_oauth_code(
|
||||
expected_state: &str,
|
||||
app_base_url: &str,
|
||||
) -> CommandResult<String> {
|
||||
// Browsers speculatively open extra connections that may never carry a
|
||||
// request. Handle each connection concurrently so an idle socket can't
|
||||
// block the one carrying the real callback.
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel::<CommandResult<String>>(1);
|
||||
|
||||
loop {
|
||||
let (mut stream, _) = listener
|
||||
.accept()
|
||||
.await
|
||||
.map_err(|e| format!("OAuth callback server accept error: {e}"))?;
|
||||
|
||||
match parse_callback_request(&mut stream).await {
|
||||
Ok((state, code)) => {
|
||||
if state != expected_state {
|
||||
let _ = write_bad_request(&mut stream, "Invalid OAuth state").await;
|
||||
continue;
|
||||
}
|
||||
|
||||
let success_redirect = format!("{app_base_url}/login/oauth/success");
|
||||
write_redirect(&mut stream, &success_redirect)
|
||||
.await
|
||||
.map_err(|e| format!("Failed responding to OAuth callback: {e}"))?;
|
||||
return Ok(code);
|
||||
tokio::select! {
|
||||
accepted = listener.accept() => {
|
||||
let (stream, _) = accepted
|
||||
.map_err(|e| format!("OAuth callback server accept error: {e}"))?;
|
||||
tokio::spawn(handle_callback_connection(
|
||||
stream,
|
||||
expected_state.to_string(),
|
||||
app_base_url.to_string(),
|
||||
tx.clone(),
|
||||
));
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = write_bad_request(&mut stream, &error).await;
|
||||
if error.starts_with("OAuth provider returned error:") {
|
||||
return Err(error);
|
||||
result = rx.recv() => {
|
||||
if let Some(result) = result {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_callback_connection(
|
||||
mut stream: TcpStream,
|
||||
expected_state: String,
|
||||
app_base_url: String,
|
||||
tx: tokio::sync::mpsc::Sender<CommandResult<String>>,
|
||||
) {
|
||||
let parsed = match tokio::time::timeout(
|
||||
CALLBACK_READ_TIMEOUT,
|
||||
parse_callback_request(&mut stream),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(parsed) => parsed,
|
||||
Err(_) => return, // Idle speculative connection; drop it
|
||||
};
|
||||
|
||||
match parsed {
|
||||
Ok((state, code)) => {
|
||||
if state != expected_state {
|
||||
let _ = write_bad_request(&mut stream, "Invalid OAuth state").await;
|
||||
return;
|
||||
}
|
||||
|
||||
let success_redirect = format!("{app_base_url}/login/oauth/success");
|
||||
let result = match write_redirect(&mut stream, &success_redirect).await {
|
||||
Ok(()) => Ok(code),
|
||||
Err(e) => Err(format!("Failed responding to OAuth callback: {e}")),
|
||||
};
|
||||
let _ = tx.send(result).await;
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = write_bad_request(&mut stream, &error).await;
|
||||
if error.starts_with("OAuth provider returned error:") {
|
||||
let _ = tx.send(Err(error)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn parse_callback_request(stream: &mut TcpStream) -> CommandResult<(String, String)> {
|
||||
let target = read_http_target(stream).await?;
|
||||
if !target.starts_with("/oauth/callback") {
|
||||
@@ -488,6 +525,37 @@ mod tests {
|
||||
assert!(err.contains("User denied"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn receive_oauth_code_ignores_idle_speculative_connections() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
|
||||
let addr = listener.local_addr().expect("local addr");
|
||||
|
||||
let server = tokio::spawn(async move {
|
||||
receive_oauth_code(listener, "expected-state", "http://localhost:9444").await
|
||||
});
|
||||
|
||||
// Browsers preconnect sockets that never carry a request; these must
|
||||
// not block the connection carrying the real callback.
|
||||
let _idle1 = TcpStream::connect(addr).await.expect("connect idle 1");
|
||||
let _idle2 = TcpStream::connect(addr).await.expect("connect idle 2");
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
|
||||
let mut client = TcpStream::connect(addr).await.expect("connect");
|
||||
client
|
||||
.write_all(
|
||||
b"GET /oauth/callback?code=abc123&state=expected-state HTTP/1.1\r\nHost: localhost\r\n\r\n",
|
||||
)
|
||||
.await
|
||||
.expect("write");
|
||||
|
||||
let code = tokio::time::timeout(std::time::Duration::from_secs(2), server)
|
||||
.await
|
||||
.expect("idle connections must not block the real callback")
|
||||
.expect("join")
|
||||
.expect("should return code");
|
||||
assert_eq!(code, "abc123");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn receive_oauth_code_fails_fast_on_provider_error() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
|
||||
|
||||
@@ -28,6 +28,7 @@ openssl-sys = { version = "0.9.105", features = ["vendored"] } # For Ubuntu inst
|
||||
rlimit = "0.11" # Raise the launchd 256 open-file soft limit at startup
|
||||
|
||||
[dependencies]
|
||||
base64 = "0.22.1" # For writing values the editor only ever held encoded
|
||||
charset = "0.1.5"
|
||||
chrono = { workspace = true, features = ["serde"] }
|
||||
cookie = "0.18.1"
|
||||
|
||||
@@ -1434,6 +1434,30 @@ async fn cmd_export_data<R: Runtime>(
|
||||
})?)
|
||||
}
|
||||
|
||||
/// Decodes base64 and writes the bytes to a file the user picked.
|
||||
///
|
||||
/// The webview can't do this itself: its `fs` permissions are read-only and scoped to the app
|
||||
/// data directory, and widening them so it could write anywhere would be a poor trade in an app
|
||||
/// whose whole job is rendering responses from servers it doesn't control.
|
||||
///
|
||||
/// Base64 in rather than bytes for two reasons. A `Vec<u8>` crosses the IPC boundary as a JSON
|
||||
/// array of numbers, several times the size of the thing being saved. And the callers that need
|
||||
/// this — values the editor collapsed — are holding base64 already, so passing it through
|
||||
/// untouched means the save never decodes megabytes on the main thread.
|
||||
#[tauri::command]
|
||||
async fn cmd_save_base64_to_binary<R: Runtime>(
|
||||
_app_handle: AppHandle<R>,
|
||||
filepath: &str,
|
||||
data: &str,
|
||||
) -> YaakResult<()> {
|
||||
use base64::Engine;
|
||||
let bytes = base64::engine::general_purpose::STANDARD
|
||||
.decode(data)
|
||||
.map_err(|e| GenericError(format!("Data is not valid base64: {e}")))?;
|
||||
fs::write(filepath, bytes).map_err(|e| GenericError(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn cmd_save_response<R: Runtime>(
|
||||
app_handle: AppHandle<R>,
|
||||
@@ -1863,6 +1887,7 @@ pub fn run() {
|
||||
cmd_reload_plugins,
|
||||
cmd_render_template,
|
||||
cmd_restart,
|
||||
cmd_save_base64_to_binary,
|
||||
cmd_save_response,
|
||||
cmd_send_ephemeral_request,
|
||||
cmd_send_http_request,
|
||||
|
||||
@@ -194,20 +194,31 @@ pub(crate) fn models_delete<R: Runtime>(
|
||||
#[tauri::command]
|
||||
pub(crate) fn models_duplicate<R: Runtime>(
|
||||
window: WebviewWindow<R>,
|
||||
model: AnyModel,
|
||||
model_type: String,
|
||||
model_id: String,
|
||||
) -> Result<String> {
|
||||
use yaak_models::error::Error::GenericError;
|
||||
|
||||
// Use transaction for duplications because it might recurse
|
||||
window.with_tx(|tx| {
|
||||
let source = &UpdateSource::from_window_label(window.label());
|
||||
let id = match model {
|
||||
AnyModel::Environment(m) => tx.duplicate_environment(&m, source)?.id,
|
||||
AnyModel::Folder(m) => tx.duplicate_folder(&m, source)?.id,
|
||||
AnyModel::GrpcRequest(m) => tx.duplicate_grpc_request(&m, source)?.id,
|
||||
AnyModel::HttpRequest(m) => tx.duplicate_http_request(&m, source)?.id,
|
||||
AnyModel::WebsocketRequest(m) => tx.duplicate_websocket_request(&m, source)?.id,
|
||||
a => return Err(GenericError(format!("Cannot duplicate AnyModel {a:?})"))),
|
||||
// Fetch the model fresh from the DB so the duplicate doesn't come from
|
||||
// a stale frontend snapshot
|
||||
let id = match model_type.as_str() {
|
||||
"environment" => {
|
||||
tx.duplicate_environment(&tx.get_environment(&model_id)?, source)?.id
|
||||
}
|
||||
"folder" => tx.duplicate_folder(&tx.get_folder(&model_id)?, source)?.id,
|
||||
"grpc_request" => {
|
||||
tx.duplicate_grpc_request(&tx.get_grpc_request(&model_id)?, source)?.id
|
||||
}
|
||||
"http_request" => {
|
||||
tx.duplicate_http_request(&tx.get_http_request(&model_id)?, source)?.id
|
||||
}
|
||||
"websocket_request" => {
|
||||
tx.duplicate_websocket_request(&tx.get_websocket_request(&model_id)?, source)?.id
|
||||
}
|
||||
t => return Err(GenericError(format!("Cannot duplicate model type {t}"))),
|
||||
};
|
||||
|
||||
Ok(id)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { resolvedModelName } from "@yaakapp/yaak-client/lib/resolvedModelName";
|
||||
import { debounce } from "@yaakapp-internal/lib";
|
||||
import { AnyModel, ModelPayload } from "../bindings/gen_models";
|
||||
import { modelStoreDataAtom } from "./atoms";
|
||||
import { ExtractModel, JotaiStore, ModelStoreData } from "./types";
|
||||
@@ -13,6 +13,9 @@ const pendingModelWrites = new Set<Promise<unknown>>();
|
||||
export function initModelStore(store: JotaiStore) {
|
||||
_store = store;
|
||||
|
||||
// Don't lose debounced patches if the window closes while one is pending
|
||||
window.addEventListener("beforeunload", flushAllPendingPatches);
|
||||
|
||||
getCurrentWebviewWindow()
|
||||
.listen<ModelPayload>("model_write", ({ payload }) => {
|
||||
if (shouldIgnoreModel(payload)) return;
|
||||
@@ -54,6 +57,7 @@ function trackModelWrite<T>(write: Promise<T>): Promise<T> {
|
||||
}
|
||||
|
||||
export async function flushAllModelWrites(): Promise<void> {
|
||||
flushAllPendingPatches();
|
||||
const results = await Promise.allSettled(pendingModelWrites);
|
||||
const rejected = results.find((result) => result.status === "rejected");
|
||||
if (rejected?.status === "rejected") {
|
||||
@@ -61,6 +65,85 @@ export async function flushAllModelWrites(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
const PATCH_DEBOUNCE_MS = 400;
|
||||
|
||||
interface PendingPatch {
|
||||
model: AnyModel["model"];
|
||||
id: string;
|
||||
patch: Record<string, unknown>;
|
||||
write: ReturnType<typeof debounce>;
|
||||
}
|
||||
|
||||
const pendingPatches = new Map<string, PendingPatch>();
|
||||
|
||||
/**
|
||||
* Like patchModel, but coalesces rapid patches to the same model (eg. one per
|
||||
* keystroke) into a single write. Later fields overwrite earlier ones, so it's
|
||||
* only safe for whole-value fields like url, body, or headers. Pending patches
|
||||
* flush after a short delay, and flushAllModelWrites() (called before sends and
|
||||
* duplicates) flushes them immediately.
|
||||
*/
|
||||
export function patchModelDebounced<
|
||||
M extends AnyModel["model"],
|
||||
T extends ExtractModel<AnyModel, M>,
|
||||
>(base: Pick<T, "id" | "model">, patch: Partial<T>): void {
|
||||
const key = `${base.model}.${base.id}`;
|
||||
let pending = pendingPatches.get(key);
|
||||
if (pending == null) {
|
||||
pending = {
|
||||
model: base.model,
|
||||
id: base.id,
|
||||
patch: {},
|
||||
write: debounce(() => writePendingPatch(key), PATCH_DEBOUNCE_MS),
|
||||
};
|
||||
pendingPatches.set(key, pending);
|
||||
}
|
||||
pending.patch = { ...pending.patch, ...patch };
|
||||
pending.write();
|
||||
}
|
||||
|
||||
function writePendingPatch(key: string) {
|
||||
const pending = pendingPatches.get(key);
|
||||
if (pending == null) return;
|
||||
pendingPatches.delete(key);
|
||||
try {
|
||||
void patchModelById(pending.model, pending.id, pending.patch);
|
||||
} catch (err) {
|
||||
// Model may have been deleted while the patch was pending
|
||||
console.warn("Failed to flush pending patch", key, err);
|
||||
}
|
||||
}
|
||||
|
||||
export function flushAllPendingPatches() {
|
||||
for (const pending of Array.from(pendingPatches.values())) {
|
||||
pending.write.flush();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a model's pending patch, if it has one that hasn't been written yet.
|
||||
*
|
||||
* The store only moves forward when the backend echoes a write back, so between a keystroke and
|
||||
* its debounced write the stored copy is behind what the user typed. Reading through the pending
|
||||
* patch keeps that window invisible to the imperative readers below, which are the ones that go
|
||||
* on to write the model back.
|
||||
*/
|
||||
function withPendingPatch<T>(model: T | null): T | null {
|
||||
if (model == null || pendingPatches.size === 0) return model;
|
||||
const { model: modelType, id } = model as { model?: string; id?: string };
|
||||
const pending = pendingPatches.get(`${modelType}.${id}`);
|
||||
return pending == null ? model : ({ ...model, ...pending.patch } as T);
|
||||
}
|
||||
|
||||
/** Drop a model's pending patch and cancel its scheduled write */
|
||||
function consumePendingPatch(model: AnyModel["model"], id: string) {
|
||||
const key = `${model}.${id}`;
|
||||
const pending = pendingPatches.get(key);
|
||||
if (pending == null) return;
|
||||
pending.write.cancel();
|
||||
pendingPatches.delete(key);
|
||||
}
|
||||
|
||||
let _activeWorkspaceId: string | null = null;
|
||||
|
||||
export async function changeModelStoreWorkspace(workspaceId: string | null) {
|
||||
@@ -97,7 +180,7 @@ export function getModel<M extends AnyModel["model"], T extends ExtractModel<Any
|
||||
const types: ReadonlyArray<M> = Array.isArray(modelType) ? modelType : [modelType];
|
||||
for (const t of types) {
|
||||
let v = data[t][id];
|
||||
if (v?.model === t) return v as T;
|
||||
if (v?.model === t) return withPendingPatch(v as T);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -107,7 +190,7 @@ export function getAnyModel(id: string): AnyModel | null {
|
||||
for (const t of Object.keys(data)) {
|
||||
// oxlint-disable-next-line no-explicit-any -- dynamic key access
|
||||
let v = (data as any)[t]?.[id];
|
||||
if (v?.model === t) return v;
|
||||
if (v?.model === t) return withPendingPatch(v);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -117,11 +200,17 @@ export function patchModelById<M extends AnyModel["model"], T extends ExtractMod
|
||||
id: string,
|
||||
patch: Partial<T> | ((prev: T) => T),
|
||||
): Promise<string> {
|
||||
// Reads through any pending debounced patch, so the merge below can't put a stale value back
|
||||
// over something the user has already typed
|
||||
let prev = getModel<M, T>(model, id);
|
||||
if (prev == null) {
|
||||
throw new Error(`Failed to get model to patch id=${id} model=${model}`);
|
||||
}
|
||||
|
||||
// `prev` already carries the pending patch, so this write supersedes it. Leaving it queued
|
||||
// would let it land afterwards and undo whatever this write decided.
|
||||
consumePendingPatch(model, id);
|
||||
|
||||
const newModel = typeof patch === "function" ? patch(prev) : { ...prev, ...patch };
|
||||
return updateModel(newModel);
|
||||
}
|
||||
@@ -156,44 +245,22 @@ export async function deleteModel<M extends AnyModel["model"], T extends Extract
|
||||
await trackModelWrite(invoke<string>("models_delete", { model }));
|
||||
}
|
||||
|
||||
export function duplicateModel<M extends AnyModel["model"], T extends ExtractModel<AnyModel, M>>(
|
||||
model: T | null,
|
||||
) {
|
||||
export async function duplicateModel<
|
||||
M extends AnyModel["model"],
|
||||
T extends ExtractModel<AnyModel, M>,
|
||||
>(model: T | null): Promise<string> {
|
||||
if (model == null) {
|
||||
throw new Error("Failed to duplicate null model");
|
||||
}
|
||||
|
||||
// If the model has an explicit (non-empty) name, try to duplicate it with a name that doesn't conflict.
|
||||
// When the name is empty, keep it empty so the display falls back to the URL.
|
||||
let name = "name" in model ? model.name : undefined;
|
||||
if (name) {
|
||||
const existingModels = listModels(model.model);
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const hasConflict = existingModels.some((m) => {
|
||||
if ("folderId" in m && "folderId" in model && model.folderId !== m.folderId) {
|
||||
return false;
|
||||
} else if (resolvedModelName(m) !== name) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (!hasConflict) {
|
||||
break;
|
||||
}
|
||||
// Flush pending writes first, since the backend duplicates from the DB (the passed-in
|
||||
// model may be a stale snapshot, eg. from the memoized sidebar tree). Conflict-free
|
||||
// naming ("Foo Copy 2") is also handled by the backend.
|
||||
await flushAllModelWrites();
|
||||
|
||||
// Name conflict. Try another one
|
||||
const m: RegExpMatchArray | null = name.match(/ Copy( (?<n>\d+))?$/);
|
||||
if (m != null && m.groups?.n == null) {
|
||||
name = name.substring(0, m.index) + " Copy 2";
|
||||
} else if (m != null && m.groups?.n != null) {
|
||||
name = name.substring(0, m.index) + ` Copy ${parseInt(m.groups.n) + 1}`;
|
||||
} else {
|
||||
name = `${name} Copy`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return trackModelWrite(invoke<string>("models_duplicate", { model: { ...model, name } }));
|
||||
return trackModelWrite(
|
||||
invoke<string>("models_duplicate", { modelType: model.model, modelId: model.id }),
|
||||
);
|
||||
}
|
||||
|
||||
export async function createGlobalModel<T extends Exclude<AnyModel, { workspaceId: string }>>(
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/// Compute a name for a duplicated model that doesn't conflict with any sibling
|
||||
/// name, following the " Copy N" convention. Empty names are kept empty so the
|
||||
/// display falls back to the URL.
|
||||
pub(crate) fn conflict_free_name(name: &str, sibling_names: &[String]) -> String {
|
||||
if name.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let mut name = name.to_string();
|
||||
for _ in 0..100 {
|
||||
if !sibling_names.contains(&name) {
|
||||
break;
|
||||
}
|
||||
name = next_copy_name(&name);
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
fn next_copy_name(name: &str) -> String {
|
||||
if let Some(base) = name.strip_suffix(" Copy") {
|
||||
return format!("{base} Copy 2");
|
||||
}
|
||||
|
||||
if let Some(idx) = name.rfind(" Copy ") {
|
||||
let n = &name[idx + " Copy ".len()..];
|
||||
if !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()) {
|
||||
if let Ok(n) = n.parse::<u64>() {
|
||||
return format!("{} Copy {}", &name[..idx], n + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
format!("{name} Copy")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_next_copy_name() {
|
||||
assert_eq!(next_copy_name("Foo"), "Foo Copy");
|
||||
assert_eq!(next_copy_name("Foo Copy"), "Foo Copy 2");
|
||||
assert_eq!(next_copy_name("Foo Copy 2"), "Foo Copy 3");
|
||||
assert_eq!(next_copy_name("Foo Copy 99"), "Foo Copy 100");
|
||||
assert_eq!(next_copy_name("Copy"), "Copy Copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_conflict_free_name() {
|
||||
let siblings = vec!["Foo".to_string(), "Foo Copy".to_string(), "".to_string()];
|
||||
assert_eq!(conflict_free_name("Foo", &siblings), "Foo Copy 2");
|
||||
assert_eq!(conflict_free_name("Bar", &siblings), "Bar");
|
||||
assert_eq!(conflict_free_name("", &siblings), "");
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::conflict_free_name;
|
||||
use crate::client_db::ClientDb;
|
||||
use crate::error::Error::{MissingBaseEnvironment, MultipleBaseEnvironments};
|
||||
use crate::error::Result;
|
||||
@@ -88,6 +89,12 @@ impl<'a> ClientDb<'a> {
|
||||
) -> Result<Environment> {
|
||||
let mut environment = environment.clone();
|
||||
environment.id = "".to_string();
|
||||
let sibling_names = self
|
||||
.list_environments_dangerous(&environment.workspace_id)?
|
||||
.into_iter()
|
||||
.map(|e| e.name)
|
||||
.collect::<Vec<_>>();
|
||||
environment.name = conflict_free_name(&environment.name, &sibling_names);
|
||||
self.upsert_environment(&environment, source)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::conflict_free_name;
|
||||
use crate::client_db::ClientDb;
|
||||
use crate::connection_or_tx::ConnectionOrTx;
|
||||
use crate::error::Result;
|
||||
@@ -62,14 +63,19 @@ impl<'a> ClientDb<'a> {
|
||||
pub fn duplicate_folder(&self, src_folder: &Folder, source: &UpdateSource) -> Result<Folder> {
|
||||
let fid = &src_folder.id;
|
||||
|
||||
let new_folder = self.upsert_folder(
|
||||
&Folder {
|
||||
id: "".into(),
|
||||
sort_priority: src_folder.sort_priority + 0.001,
|
||||
..src_folder.clone()
|
||||
},
|
||||
source,
|
||||
)?;
|
||||
let mut folder = Folder {
|
||||
id: "".into(),
|
||||
sort_priority: src_folder.sort_priority + 0.001,
|
||||
..src_folder.clone()
|
||||
};
|
||||
let sibling_names = self
|
||||
.list_folders(&folder.workspace_id)?
|
||||
.into_iter()
|
||||
.filter(|f| f.folder_id == folder.folder_id)
|
||||
.map(|f| f.name)
|
||||
.collect::<Vec<_>>();
|
||||
folder.name = conflict_free_name(&folder.name, &sibling_names);
|
||||
let new_folder = self.upsert_folder(&folder, source)?;
|
||||
|
||||
for m in self.find_many::<HttpRequest>(HttpRequestIden::FolderId, fid, None)? {
|
||||
self.upsert_http_request(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::dedupe_headers;
|
||||
use super::{conflict_free_name, dedupe_headers};
|
||||
use crate::client_db::ClientDb;
|
||||
use crate::error::Result;
|
||||
use crate::models::{
|
||||
@@ -58,6 +58,13 @@ impl<'a> ClientDb<'a> {
|
||||
let mut request = grpc_request.clone();
|
||||
request.id = "".to_string();
|
||||
request.sort_priority = request.sort_priority + 0.001;
|
||||
let sibling_names = self
|
||||
.list_grpc_requests(&request.workspace_id)?
|
||||
.into_iter()
|
||||
.filter(|m| m.folder_id == request.folder_id)
|
||||
.map(|m| m.name)
|
||||
.collect::<Vec<_>>();
|
||||
request.name = conflict_free_name(&request.name, &sibling_names);
|
||||
self.upsert(&request, source)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::dedupe_headers;
|
||||
use super::{conflict_free_name, dedupe_headers};
|
||||
use crate::client_db::ClientDb;
|
||||
use crate::error::Result;
|
||||
use crate::models::{
|
||||
@@ -44,6 +44,13 @@ impl<'a> ClientDb<'a> {
|
||||
let mut http_request = http_request.clone();
|
||||
http_request.id = "".to_string();
|
||||
http_request.sort_priority = http_request.sort_priority + 0.001;
|
||||
let sibling_names = self
|
||||
.list_http_requests(&http_request.workspace_id)?
|
||||
.into_iter()
|
||||
.filter(|m| m.folder_id == http_request.folder_id)
|
||||
.map(|m| m.name)
|
||||
.collect::<Vec<_>>();
|
||||
http_request.name = conflict_free_name(&http_request.name, &sibling_names);
|
||||
self.upsert(&http_request, source)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod any_request;
|
||||
mod batch;
|
||||
mod cookie_jars;
|
||||
mod duplicate_name;
|
||||
mod environments;
|
||||
mod folders;
|
||||
mod graphql_introspections;
|
||||
@@ -22,6 +23,7 @@ mod websocket_requests;
|
||||
mod workspace_metas;
|
||||
pub mod workspaces;
|
||||
pub use model_changes::PersistedModelChange;
|
||||
pub(crate) use duplicate_name::conflict_free_name;
|
||||
|
||||
const MAX_HISTORY_ITEMS: usize = 20;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::dedupe_headers;
|
||||
use super::{conflict_free_name, dedupe_headers};
|
||||
use crate::client_db::ClientDb;
|
||||
use crate::error::Result;
|
||||
use crate::models::{
|
||||
@@ -60,6 +60,13 @@ impl<'a> ClientDb<'a> {
|
||||
let mut websocket_request = websocket_request.clone();
|
||||
websocket_request.id = "".to_string();
|
||||
websocket_request.sort_priority = websocket_request.sort_priority + 0.001;
|
||||
let sibling_names = self
|
||||
.list_websocket_requests(&websocket_request.workspace_id)?
|
||||
.into_iter()
|
||||
.filter(|m| m.folder_id == websocket_request.folder_id)
|
||||
.map(|m| m.name)
|
||||
.collect::<Vec<_>>();
|
||||
websocket_request.name = conflict_free_name(&websocket_request.name, &sibling_names);
|
||||
self.upsert(&websocket_request, source)
|
||||
}
|
||||
|
||||
|
||||
@@ -247,7 +247,8 @@ impl PluginManager {
|
||||
pub async fn list_bundled_plugin_dirs(&self) -> Result<Vec<String>> {
|
||||
let plugins_dir = self.get_plugins_dir();
|
||||
info!("Loading bundled plugins from {plugins_dir:?}");
|
||||
read_plugins_dir(&plugins_dir).await
|
||||
let dirs = read_plugins_dir(&plugins_dir).await?;
|
||||
Ok(dirs.into_iter().filter(|dir| !is_removed_bundled_plugin_dir(dir)).collect())
|
||||
}
|
||||
|
||||
pub async fn resolve_plugins_for_runtime_from_db(&self, plugins: Vec<Plugin>) -> Vec<Plugin> {
|
||||
@@ -1098,7 +1099,7 @@ impl PluginManager {
|
||||
&InternalEventPayload::ImportRequest(ImportRequest {
|
||||
content: content.to_string(),
|
||||
}),
|
||||
Duration::from_secs(5),
|
||||
Duration::from_secs(60),
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -1173,6 +1174,23 @@ fn prefer_plugin(candidate: &Plugin, existing: &Plugin) -> bool {
|
||||
candidate.created_at > existing.created_at
|
||||
}
|
||||
|
||||
/// Bundled plugin directories that shipped in past versions and no longer exist. Updates
|
||||
/// can leave these behind on disk, where they'd be discovered as bundled plugins and load
|
||||
/// alongside the plugin that replaced them, producing duplicate actions in menus.
|
||||
///
|
||||
/// Ignoring them here also drops any plugin rows users already have, because bundled rows
|
||||
/// whose directory isn't in this list are filtered out by `resolve_plugins_for_runtime`.
|
||||
///
|
||||
/// `exporter-curl` was renamed to `action-copy-curl` in 19ffcd18, which is why affected
|
||||
/// installs show "Copy as cURL" twice.
|
||||
const REMOVED_BUNDLED_PLUGIN_DIRS: &[&str] = &["exporter-curl"];
|
||||
|
||||
/// Whether a plugin directory path is one of the known-removed bundled plugins.
|
||||
fn is_removed_bundled_plugin_dir(dir: &str) -> bool {
|
||||
let name = dir.trim_end_matches(['/', '\\']).rsplit(['/', '\\']).next().unwrap_or_default();
|
||||
REMOVED_BUNDLED_PLUGIN_DIRS.contains(&name)
|
||||
}
|
||||
|
||||
async fn read_plugins_dir(dir: &PathBuf) -> Result<Vec<String>> {
|
||||
let mut result = read_dir(dir).await?;
|
||||
let mut dirs: Vec<String> = vec![];
|
||||
@@ -1198,3 +1216,30 @@ fn fix_windows_paths(p: &PathBuf) -> String {
|
||||
// 2. Convert backslashes to forward slashes for Node.js compatibility
|
||||
PathBuf::from(safe_path).to_slash_lossy().to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::is_removed_bundled_plugin_dir;
|
||||
|
||||
#[test]
|
||||
fn ignores_removed_bundled_plugins() {
|
||||
assert!(is_removed_bundled_plugin_dir(
|
||||
"/Applications/Yaak.app/vendored/plugins/exporter-curl"
|
||||
));
|
||||
// Windows paths are slash-normalized before reaching here, but handle both
|
||||
assert!(is_removed_bundled_plugin_dir(
|
||||
r"C:\Users\me\AppData\Local\Yaak\vendored\plugins\exporter-curl"
|
||||
));
|
||||
assert!(is_removed_bundled_plugin_dir("vendored/plugins/exporter-curl/"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_current_bundled_plugins() {
|
||||
assert!(!is_removed_bundled_plugin_dir(
|
||||
"/Applications/Yaak.app/vendored/plugins/action-copy-curl"
|
||||
));
|
||||
assert!(!is_removed_bundled_plugin_dir("vendored/plugins/importer-curl"));
|
||||
// Must match the whole directory name, not a substring
|
||||
assert!(!is_removed_bundled_plugin_dir("vendored/plugins/my-exporter-curl"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const { execSync } = require("node:child_process");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
|
||||
if (process.env.SKIP_WASM_BUILD === "1") {
|
||||
@@ -7,7 +8,18 @@ if (process.env.SKIP_WASM_BUILD === "1") {
|
||||
return;
|
||||
}
|
||||
|
||||
execSync("wasm-pack build --target bundler", { stdio: "inherit" });
|
||||
// Remap machine-specific paths that rustc embeds into the binary (panic
|
||||
// location strings), so builds are reproducible across machines
|
||||
const sysroot = execSync("rustc --print sysroot").toString().trim();
|
||||
const cargoHome = process.env.CARGO_HOME ?? path.join(os.homedir(), ".cargo");
|
||||
|
||||
execSync("wasm-pack build --target bundler", {
|
||||
stdio: "inherit",
|
||||
env: {
|
||||
...process.env,
|
||||
RUSTFLAGS: `--remap-path-prefix=${cargoHome}=/cargo --remap-path-prefix=${sysroot}=/rustc`,
|
||||
},
|
||||
});
|
||||
|
||||
// Rewrite the generated entry to use Vite's ?init import style instead of
|
||||
// the ES Module Integration style that wasm-pack generates, which Vite/rolldown
|
||||
|
||||
+4
-1
@@ -1,5 +1,8 @@
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export function unescape_template(template: string): any;
|
||||
|
||||
export function escape_template(template: string): any;
|
||||
|
||||
export function parse_template(template: string): any;
|
||||
|
||||
export function unescape_template(template: string): any;
|
||||
|
||||
+118
-128
@@ -1,9 +1,82 @@
|
||||
let wasm;
|
||||
export function __wbg_set_wasm(val) {
|
||||
wasm = val;
|
||||
/**
|
||||
* @param {string} template
|
||||
* @returns {any}
|
||||
*/
|
||||
export function escape_template(template) {
|
||||
const ptr0 = passStringToWasm0(template, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
||||
const len0 = WASM_VECTOR_LEN;
|
||||
const ret = wasm.escape_template(ptr0, len0);
|
||||
if (ret[2]) {
|
||||
throw takeFromExternrefTable0(ret[1]);
|
||||
}
|
||||
return takeFromExternrefTable0(ret[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} template
|
||||
* @returns {any}
|
||||
*/
|
||||
export function parse_template(template) {
|
||||
const ptr0 = passStringToWasm0(template, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
||||
const len0 = WASM_VECTOR_LEN;
|
||||
const ret = wasm.parse_template(ptr0, len0);
|
||||
if (ret[2]) {
|
||||
throw takeFromExternrefTable0(ret[1]);
|
||||
}
|
||||
return takeFromExternrefTable0(ret[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} template
|
||||
* @returns {any}
|
||||
*/
|
||||
export function unescape_template(template) {
|
||||
const ptr0 = passStringToWasm0(template, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
||||
const len0 = WASM_VECTOR_LEN;
|
||||
const ret = wasm.unescape_template(ptr0, len0);
|
||||
if (ret[2]) {
|
||||
throw takeFromExternrefTable0(ret[1]);
|
||||
}
|
||||
return takeFromExternrefTable0(ret[0]);
|
||||
}
|
||||
export function __wbg___wbindgen_debug_string_edece8177ad01481(arg0, arg1) {
|
||||
const ret = debugString(arg1);
|
||||
const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
||||
const len1 = WASM_VECTOR_LEN;
|
||||
getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
|
||||
getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
|
||||
}
|
||||
export function __wbg___wbindgen_throw_9c31b086c2b26051(arg0, arg1) {
|
||||
throw new Error(getStringFromWasm0(arg0, arg1));
|
||||
}
|
||||
export function __wbg_new_02d162bc6cf02f60() {
|
||||
const ret = new Object();
|
||||
return ret;
|
||||
}
|
||||
export function __wbg_new_310879b66b6e95e1() {
|
||||
const ret = new Array();
|
||||
return ret;
|
||||
}
|
||||
export function __wbg_set_6be42768c690e380(arg0, arg1, arg2) {
|
||||
arg0[arg1] = arg2;
|
||||
}
|
||||
export function __wbg_set_78ea6a19f4818587(arg0, arg1, arg2) {
|
||||
arg0[arg1 >>> 0] = arg2;
|
||||
}
|
||||
export function __wbindgen_cast_0000000000000001(arg0, arg1) {
|
||||
// Cast intrinsic for `Ref(String) -> Externref`.
|
||||
const ret = getStringFromWasm0(arg0, arg1);
|
||||
return ret;
|
||||
}
|
||||
export function __wbindgen_init_externref_table() {
|
||||
const table = wasm.__wbindgen_externrefs;
|
||||
const offset = table.grow(4);
|
||||
table.set(0, undefined);
|
||||
table.set(offset + 0, undefined);
|
||||
table.set(offset + 1, null);
|
||||
table.set(offset + 2, true);
|
||||
table.set(offset + 3, false);
|
||||
}
|
||||
function debugString(val) {
|
||||
// primitive types
|
||||
const type = typeof val;
|
||||
@@ -69,10 +142,19 @@ function debugString(val) {
|
||||
return className;
|
||||
}
|
||||
|
||||
let WASM_VECTOR_LEN = 0;
|
||||
let cachedDataViewMemory0 = null;
|
||||
function getDataViewMemory0() {
|
||||
if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
|
||||
cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
|
||||
}
|
||||
return cachedDataViewMemory0;
|
||||
}
|
||||
|
||||
function getStringFromWasm0(ptr, len) {
|
||||
return decodeText(ptr >>> 0, len);
|
||||
}
|
||||
|
||||
let cachedUint8ArrayMemory0 = null;
|
||||
|
||||
function getUint8ArrayMemory0() {
|
||||
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
|
||||
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
|
||||
@@ -80,25 +162,7 @@ function getUint8ArrayMemory0() {
|
||||
return cachedUint8ArrayMemory0;
|
||||
}
|
||||
|
||||
const lTextEncoder = typeof TextEncoder === 'undefined' ? (0, module.require)('util').TextEncoder : TextEncoder;
|
||||
|
||||
let cachedTextEncoder = new lTextEncoder('utf-8');
|
||||
|
||||
const encodeString = (typeof cachedTextEncoder.encodeInto === 'function'
|
||||
? function (arg, view) {
|
||||
return cachedTextEncoder.encodeInto(arg, view);
|
||||
}
|
||||
: function (arg, view) {
|
||||
const buf = cachedTextEncoder.encode(arg);
|
||||
view.set(buf);
|
||||
return {
|
||||
read: arg.length,
|
||||
written: buf.length
|
||||
};
|
||||
});
|
||||
|
||||
function passStringToWasm0(arg, malloc, realloc) {
|
||||
|
||||
if (realloc === undefined) {
|
||||
const buf = cachedTextEncoder.encode(arg);
|
||||
const ptr = malloc(buf.length, 1) >>> 0;
|
||||
@@ -119,14 +183,13 @@ function passStringToWasm0(arg, malloc, realloc) {
|
||||
if (code > 0x7F) break;
|
||||
mem[ptr + offset] = code;
|
||||
}
|
||||
|
||||
if (offset !== len) {
|
||||
if (offset !== 0) {
|
||||
arg = arg.slice(offset);
|
||||
}
|
||||
ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
|
||||
const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
|
||||
const ret = encodeString(arg, view);
|
||||
const ret = cachedTextEncoder.encodeInto(arg, view);
|
||||
|
||||
offset += ret.written;
|
||||
ptr = realloc(ptr, len, offset, 1) >>> 0;
|
||||
@@ -136,116 +199,43 @@ function passStringToWasm0(arg, malloc, realloc) {
|
||||
return ptr;
|
||||
}
|
||||
|
||||
let cachedDataViewMemory0 = null;
|
||||
|
||||
function getDataViewMemory0() {
|
||||
if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
|
||||
cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
|
||||
}
|
||||
return cachedDataViewMemory0;
|
||||
}
|
||||
|
||||
const lTextDecoder = typeof TextDecoder === 'undefined' ? (0, module.require)('util').TextDecoder : TextDecoder;
|
||||
|
||||
let cachedTextDecoder = new lTextDecoder('utf-8', { ignoreBOM: true, fatal: true });
|
||||
|
||||
cachedTextDecoder.decode();
|
||||
|
||||
function getStringFromWasm0(ptr, len) {
|
||||
ptr = ptr >>> 0;
|
||||
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
|
||||
}
|
||||
|
||||
function takeFromExternrefTable0(idx) {
|
||||
const value = wasm.__wbindgen_export_2.get(idx);
|
||||
const value = wasm.__wbindgen_externrefs.get(idx);
|
||||
wasm.__externref_table_dealloc(idx);
|
||||
return value;
|
||||
}
|
||||
/**
|
||||
* @param {string} template
|
||||
* @returns {any}
|
||||
*/
|
||||
export function unescape_template(template) {
|
||||
const ptr0 = passStringToWasm0(template, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
||||
const len0 = WASM_VECTOR_LEN;
|
||||
const ret = wasm.unescape_template(ptr0, len0);
|
||||
if (ret[2]) {
|
||||
throw takeFromExternrefTable0(ret[1]);
|
||||
|
||||
let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
|
||||
cachedTextDecoder.decode();
|
||||
const MAX_SAFARI_DECODE_BYTES = 2146435072;
|
||||
let numBytesDecoded = 0;
|
||||
function decodeText(ptr, len) {
|
||||
numBytesDecoded += len;
|
||||
if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
|
||||
cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
|
||||
cachedTextDecoder.decode();
|
||||
numBytesDecoded = len;
|
||||
}
|
||||
return takeFromExternrefTable0(ret[0]);
|
||||
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} template
|
||||
* @returns {any}
|
||||
*/
|
||||
export function escape_template(template) {
|
||||
const ptr0 = passStringToWasm0(template, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
||||
const len0 = WASM_VECTOR_LEN;
|
||||
const ret = wasm.escape_template(ptr0, len0);
|
||||
if (ret[2]) {
|
||||
throw takeFromExternrefTable0(ret[1]);
|
||||
}
|
||||
return takeFromExternrefTable0(ret[0]);
|
||||
const cachedTextEncoder = new TextEncoder();
|
||||
|
||||
if (!('encodeInto' in cachedTextEncoder)) {
|
||||
cachedTextEncoder.encodeInto = function (arg, view) {
|
||||
const buf = cachedTextEncoder.encode(arg);
|
||||
view.set(buf);
|
||||
return {
|
||||
read: arg.length,
|
||||
written: buf.length
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} template
|
||||
* @returns {any}
|
||||
*/
|
||||
export function parse_template(template) {
|
||||
const ptr0 = passStringToWasm0(template, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
||||
const len0 = WASM_VECTOR_LEN;
|
||||
const ret = wasm.parse_template(ptr0, len0);
|
||||
if (ret[2]) {
|
||||
throw takeFromExternrefTable0(ret[1]);
|
||||
}
|
||||
return takeFromExternrefTable0(ret[0]);
|
||||
let WASM_VECTOR_LEN = 0;
|
||||
|
||||
|
||||
let wasm;
|
||||
export function __wbg_set_wasm(val) {
|
||||
wasm = val;
|
||||
}
|
||||
|
||||
export function __wbg_new_405e22f390576ce2() {
|
||||
const ret = new Object();
|
||||
return ret;
|
||||
};
|
||||
|
||||
export function __wbg_new_78feb108b6472713() {
|
||||
const ret = new Array();
|
||||
return ret;
|
||||
};
|
||||
|
||||
export function __wbg_set_37837023f3d740e8(arg0, arg1, arg2) {
|
||||
arg0[arg1 >>> 0] = arg2;
|
||||
};
|
||||
|
||||
export function __wbg_set_3f1d0b984ed272ed(arg0, arg1, arg2) {
|
||||
arg0[arg1] = arg2;
|
||||
};
|
||||
|
||||
export function __wbindgen_debug_string(arg0, arg1) {
|
||||
const ret = debugString(arg1);
|
||||
const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
||||
const len1 = WASM_VECTOR_LEN;
|
||||
getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
|
||||
getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
|
||||
};
|
||||
|
||||
export function __wbindgen_init_externref_table() {
|
||||
const table = wasm.__wbindgen_export_2;
|
||||
const offset = table.grow(4);
|
||||
table.set(0, undefined);
|
||||
table.set(offset + 0, undefined);
|
||||
table.set(offset + 1, null);
|
||||
table.set(offset + 2, true);
|
||||
table.set(offset + 3, false);
|
||||
;
|
||||
};
|
||||
|
||||
export function __wbindgen_string_new(arg0, arg1) {
|
||||
const ret = getStringFromWasm0(arg0, arg1);
|
||||
return ret;
|
||||
};
|
||||
|
||||
export function __wbindgen_throw(arg0, arg1) {
|
||||
throw new Error(getStringFromWasm0(arg0, arg1));
|
||||
};
|
||||
|
||||
|
||||
BIN
Binary file not shown.
+1
-1
@@ -6,6 +6,6 @@ export const parse_template: (a: number, b: number) => [number, number, number];
|
||||
export const unescape_template: (a: number, b: number) => [number, number, number];
|
||||
export const __wbindgen_malloc: (a: number, b: number) => number;
|
||||
export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
|
||||
export const __wbindgen_export_2: WebAssembly.Table;
|
||||
export const __wbindgen_externrefs: WebAssembly.Table;
|
||||
export const __externref_table_dealloc: (a: number) => void;
|
||||
export const __wbindgen_start: () => void;
|
||||
|
||||
@@ -135,6 +135,10 @@ async fn render_value<T: TemplateCallback>(
|
||||
opt: &RenderOptions,
|
||||
depth: usize,
|
||||
) -> Result<String> {
|
||||
if depth > MAX_DEPTH {
|
||||
return opt.error_behavior.handle(Err(RenderStackExceededError));
|
||||
}
|
||||
|
||||
let v = match val {
|
||||
Val::Str { text } => {
|
||||
let r = Box::pin(parse_and_render_at_depth(&text, vars, cb, opt, depth)).await?;
|
||||
@@ -154,7 +158,7 @@ async fn render_value<T: TemplateCallback>(
|
||||
Val::Bool { value } => serde_json::Value::Bool(value),
|
||||
Val::Null => serde_json::Value::Null,
|
||||
_ => serde_json::Value::String(
|
||||
Box::pin(render_value(a.value, vars, cb, opt, depth)).await?,
|
||||
Box::pin(render_value(a.value, vars, cb, opt, depth + 1)).await?,
|
||||
),
|
||||
};
|
||||
resolved_args.insert(a.name, v);
|
||||
@@ -498,6 +502,50 @@ mod parse_and_render_tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_nested_function_args_beyond_max_depth() -> Result<()> {
|
||||
struct CB {}
|
||||
impl TemplateCallback for CB {
|
||||
async fn run(
|
||||
&self,
|
||||
_fn_name: &str,
|
||||
args: HashMap<String, serde_json::Value>,
|
||||
) -> Result<String> {
|
||||
Ok(args["value"].as_str().unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
fn transform_arg(
|
||||
&self,
|
||||
_fn_name: &str,
|
||||
_arg_name: &str,
|
||||
arg_value: &str,
|
||||
) -> Result<String> {
|
||||
Ok(arg_value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
let nested_beyond_limit = (0..=super::MAX_DEPTH)
|
||||
.fold("'ok'".to_string(), |value, _| format!("identity(value={value})"));
|
||||
let template_beyond_limit = format!("${{[ {nested_beyond_limit} ]}}");
|
||||
let vars = HashMap::new();
|
||||
|
||||
assert_eq!(
|
||||
parse_and_render(&template_beyond_limit, &vars, &CB {}, &RenderOptions::throw()).await,
|
||||
Err(RenderStackExceededError)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_and_render(
|
||||
&template_beyond_limit,
|
||||
&vars,
|
||||
&CB {},
|
||||
&RenderOptions::return_empty(),
|
||||
)
|
||||
.await,
|
||||
Ok(String::new())
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn render_fn_err() -> Result<()> {
|
||||
let vars = HashMap::new();
|
||||
|
||||
+71
-19
@@ -511,7 +511,10 @@ pub async fn send_http_request<T: TemplateCallback>(
|
||||
.map_err(SendHttpRequestError::PrepareSendableRequest)?;
|
||||
}
|
||||
|
||||
let request_content_length = sendable_body_length(sendable_request.body.as_ref());
|
||||
let request_content_length = match sendable_request.body.as_ref() {
|
||||
Some(SendableBody::Bytes(_)) => sendable_body_length(sendable_request.body.as_ref()),
|
||||
Some(SendableBody::Stream { .. }) | None => None,
|
||||
};
|
||||
let mut response = params.existing_response.unwrap_or_default();
|
||||
response.request_id = params.request.id.clone();
|
||||
response.workspace_id = params.request.workspace_id.clone();
|
||||
@@ -811,16 +814,6 @@ pub async fn send_http_request<T: TemplateCallback>(
|
||||
})?;
|
||||
drop(body_stream);
|
||||
|
||||
if let Some(task) = request_body_capture_task.take() {
|
||||
match task.await {
|
||||
Ok(Ok(total)) => {
|
||||
response.request_content_length = Some(usize_to_i32(total));
|
||||
}
|
||||
Ok(Err(err)) => request_body_capture_error = Some(err),
|
||||
Err(err) => request_body_capture_error = Some(err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(err) = request_body_capture_error.take() {
|
||||
response.error = Some(append_error_message(
|
||||
response.error.take(),
|
||||
@@ -828,10 +821,6 @@ pub async fn send_http_request<T: TemplateCallback>(
|
||||
));
|
||||
}
|
||||
|
||||
if let Err(join_err) = event_handle.await {
|
||||
warn!("Failed to join response event task: {}", join_err);
|
||||
}
|
||||
|
||||
if let Some(err) = body_read_error {
|
||||
if persist_response {
|
||||
let _ = persist_response_error(
|
||||
@@ -849,6 +838,16 @@ pub async fn send_http_request<T: TemplateCallback>(
|
||||
cookie_jar.as_mut(),
|
||||
cookie_behavior.store.as_ref(),
|
||||
)?;
|
||||
if let Some(task) = request_body_capture_task.take() {
|
||||
match task.await {
|
||||
Ok(Ok(_)) => {}
|
||||
Ok(Err(err)) => warn!("Failed to store request body after response error: {err}"),
|
||||
Err(err) => warn!("Failed to join request body capture task: {err}"),
|
||||
}
|
||||
}
|
||||
if let Err(join_err) = event_handle.await {
|
||||
warn!("Failed to join response event task: {}", join_err);
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
@@ -875,6 +874,49 @@ pub async fn send_http_request<T: TemplateCallback>(
|
||||
|
||||
persist_cookie_jar(params.query_manager, cookie_jar.as_mut(), cookie_behavior.store.as_ref())?;
|
||||
|
||||
// Request-body history can be much larger than the response. It should not keep the
|
||||
// response in a loading state after the network/response-body work has completed.
|
||||
if let Some(task) = request_body_capture_task.take() {
|
||||
let mut update_response = false;
|
||||
match task.await {
|
||||
Ok(Ok(total)) => {
|
||||
let total = Some(usize_to_i32(total));
|
||||
if response.request_content_length != total {
|
||||
response.request_content_length = total;
|
||||
update_response = true;
|
||||
}
|
||||
}
|
||||
Ok(Err(err)) => {
|
||||
response.error = Some(append_error_message(
|
||||
response.error.take(),
|
||||
format!("Request succeeded but failed to store request body: {err}"),
|
||||
));
|
||||
update_response = true;
|
||||
}
|
||||
Err(err) => {
|
||||
response.error = Some(append_error_message(
|
||||
response.error.take(),
|
||||
format!("Request succeeded but failed to store request body: {err}"),
|
||||
));
|
||||
update_response = true;
|
||||
}
|
||||
}
|
||||
|
||||
if update_response && persist_response {
|
||||
response = params
|
||||
.query_manager
|
||||
.connect()
|
||||
.upsert_http_response(&response, ¶ms.update_source, params.blob_manager)
|
||||
.map_err(SendHttpRequestError::PersistResponse)?;
|
||||
}
|
||||
}
|
||||
|
||||
// Timeline events are useful history, but they should not keep the response in a loading state
|
||||
// after the network/response-body work has completed.
|
||||
if let Err(join_err) = event_handle.await {
|
||||
warn!("Failed to join response event task: {}", join_err);
|
||||
}
|
||||
|
||||
Ok(SendHttpRequestResult { rendered_request, response, response_body })
|
||||
}
|
||||
|
||||
@@ -907,14 +949,24 @@ async fn persist_request_body_stream(
|
||||
) -> std::result::Result<usize, String> {
|
||||
let mut chunk_index: i32 = 0;
|
||||
let mut total_bytes = 0usize;
|
||||
|
||||
// Stream reads arrive in small (eg. 8-16 KiB) pieces, so accumulate them into
|
||||
// full-size chunks to avoid thousands of tiny inserts for large bodies
|
||||
let mut buf: Vec<u8> = Vec::with_capacity(REQUEST_BODY_CHUNK_SIZE);
|
||||
while let Some(data) = rx.recv().await {
|
||||
total_bytes += data.len();
|
||||
if data.is_empty() {
|
||||
continue;
|
||||
buf.extend_from_slice(&data);
|
||||
while buf.len() >= REQUEST_BODY_CHUNK_SIZE {
|
||||
let data = buf.drain(..REQUEST_BODY_CHUNK_SIZE).collect();
|
||||
let chunk = BodyChunk::new(&body_id, chunk_index, data);
|
||||
blob_manager.connect().insert_chunk(&chunk).map_err(|e| e.to_string())?;
|
||||
chunk_index += 1;
|
||||
}
|
||||
let chunk = BodyChunk::new(&body_id, chunk_index, data);
|
||||
}
|
||||
|
||||
if !buf.is_empty() {
|
||||
let chunk = BodyChunk::new(&body_id, chunk_index, buf);
|
||||
blob_manager.connect().insert_chunk(&chunk).map_err(|e| e.to_string())?;
|
||||
chunk_index += 1;
|
||||
}
|
||||
|
||||
Ok(total_bytes)
|
||||
|
||||
Generated
+102
-57
@@ -83,12 +83,12 @@
|
||||
"@tauri-apps/cli": "npm:@tauri-apps/cli-cef@3.0.0-alpha.6",
|
||||
"@types/babel__core": "^7.20.5",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"@yaakapp/cli": "latest",
|
||||
"@yaakapp/cli": "*",
|
||||
"babel-plugin-react-compiler": "^1.0.0",
|
||||
"dotenv-cli": "^11.0.0",
|
||||
"nodejs-file-downloader": "^4.13.0",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"postcss": "^8.5.16",
|
||||
"postcss": "^8.5.25",
|
||||
"tailwindcss": "^4.3.2",
|
||||
"typescript": "^5.8.3",
|
||||
"vite": "npm:@voidzero-dev/vite-plus-core@^0.2.1",
|
||||
@@ -121,7 +121,7 @@
|
||||
"@shopify/lang-jsonc": "^1.0.1",
|
||||
"@tanstack/react-query": "^5.90.5",
|
||||
"@tanstack/react-router": "^1.133.13",
|
||||
"@tanstack/react-virtual": "^3.13.12",
|
||||
"@tanstack/react-virtual": "^3.14.9",
|
||||
"@tauri-apps/api": "^2.11.0",
|
||||
"@tauri-apps/plugin-clipboard-manager": "^2.3.2",
|
||||
"@tauri-apps/plugin-dialog": "^2.7.1",
|
||||
@@ -148,7 +148,7 @@
|
||||
"lucide-react": "^0.525.0",
|
||||
"mime": "^4.0.4",
|
||||
"motion": "^12.4.7",
|
||||
"nanoid": "^5.0.9",
|
||||
"nanoid": "^5.1.16",
|
||||
"papaparse": "^5.4.1",
|
||||
"parse-color": "^1.0.0",
|
||||
"react": "^19.2.0",
|
||||
@@ -205,7 +205,9 @@
|
||||
}
|
||||
},
|
||||
"apps/yaak-client/node_modules/nanoid": {
|
||||
"version": "5.1.6",
|
||||
"version": "5.1.16",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz",
|
||||
"integrity": "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -1484,9 +1486,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@hono/node-server": {
|
||||
"version": "1.19.14",
|
||||
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",
|
||||
"integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==",
|
||||
"version": "1.19.17",
|
||||
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.17.tgz",
|
||||
"integrity": "sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.14.1"
|
||||
@@ -4340,12 +4342,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/react-virtual": {
|
||||
"version": "3.13.18",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.13.18.tgz",
|
||||
"integrity": "sha512-dZkhyfahpvlaV0rIKnvQiVoWPyURppl6w4m9IwMDpuIjcJ1sD9YGWrt0wISvgU7ewACXx2Ct46WPgI6qAD4v6A==",
|
||||
"version": "3.14.9",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.14.9.tgz",
|
||||
"integrity": "sha512-qZyr0FZDP8rDC4WBhsryIZmAd9bveJvFGUJJtskWaew6/0dTRS6wZxnR6VQ5bY2KwL3LjerrHqQLk3a0GKcPXQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@tanstack/virtual-core": "3.13.18"
|
||||
"@tanstack/virtual-core": "3.17.7"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
@@ -4490,9 +4492,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/virtual-core": {
|
||||
"version": "3.13.18",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.13.18.tgz",
|
||||
"integrity": "sha512-Mx86Hqu1k39icq2Zusq+Ey2J6dDWTjDvEv43PJtRCoEYTLyfaPnxIQ6iy7YAOK0NV/qOEmZQ/uCufrppZxTgcg==",
|
||||
"version": "3.17.7",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.17.7.tgz",
|
||||
"integrity": "sha512-bp+v10y65sp2H7WpWfIMyxTNfl8ZVfxFTLRjPIFRryi6FV/J33z4IS53WO4pTk36KlvJ4iLiQz+oaydDC1xbcA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
@@ -6331,20 +6333,20 @@
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser": {
|
||||
"version": "2.2.2",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz",
|
||||
"integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==",
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
|
||||
"integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bytes": "^3.1.2",
|
||||
"content-type": "^1.0.5",
|
||||
"content-type": "^2.0.0",
|
||||
"debug": "^4.4.3",
|
||||
"http-errors": "^2.0.0",
|
||||
"iconv-lite": "^0.7.0",
|
||||
"http-errors": "^2.0.1",
|
||||
"iconv-lite": "^0.7.2",
|
||||
"on-finished": "^2.4.1",
|
||||
"qs": "^6.14.1",
|
||||
"raw-body": "^3.0.1",
|
||||
"type-is": "^2.0.1"
|
||||
"qs": "^6.15.2",
|
||||
"raw-body": "^3.0.2",
|
||||
"type-is": "^2.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
@@ -6354,6 +6356,19 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser/node_modules/content-type": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",
|
||||
"integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "1.1.12",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
|
||||
@@ -8298,12 +8313,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/express-rate-limit": {
|
||||
"version": "8.2.1",
|
||||
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.2.1.tgz",
|
||||
"integrity": "sha512-PCZEIEIxqwhzw4KF0n7QF4QqruVTcF73O5kFKUnGOyjbCCgizBBiFaYpd/fnBLUMPw/BWw9OsiN7GgrNYr7j6g==",
|
||||
"version": "8.6.2",
|
||||
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.6.2.tgz",
|
||||
"integrity": "sha512-YH4ru+eOJxQABscKFfRCy9R7x9QFGdezclVMwwgFFndzS2Xnm0uo6B0ABZsLhcpeptGv2qvuJVWlQr9gQZoC3A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ip-address": "10.0.1"
|
||||
"debug": "^4.4.3",
|
||||
"ip-address": "^10.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
@@ -8386,9 +8402,9 @@
|
||||
"integrity": "sha512-HPtaa38cPgWvaCFmRNhlc6NG7pv6NUHqjPgVAkWGoB9mQMwYB27/K0CvOM5Czy+qpT3e8XJ6Q4aPAnzpNpzNaw=="
|
||||
},
|
||||
"node_modules/fast-uri": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",
|
||||
"integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",
|
||||
"version": "3.1.5",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz",
|
||||
"integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -9249,9 +9265,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/hono": {
|
||||
"version": "4.12.25",
|
||||
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.25.tgz",
|
||||
"integrity": "sha512-2NFaIyNVgJmBs/ecmtGzlmluTFs5cHEWGTdu0t1HBwYzoGXOL5nUQBRMXsXWla5i4KkG//QMzVP88m1+I3fdAQ==",
|
||||
"version": "4.12.34",
|
||||
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.34.tgz",
|
||||
"integrity": "sha512-GqXJqY/xJkJmuloTrnV1ZEXG3fqte+VjkUqoRNZXcrUidiUOP4fMSIHHY4tsqZBK++kVyWmt/AAfSUuy57/eSA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16.9.0"
|
||||
@@ -9509,9 +9525,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/ip-address": {
|
||||
"version": "10.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.0.1.tgz",
|
||||
"integrity": "sha512-NWv9YLW4PoW2B7xtzaS3NCot75m6nK7Icdv0o3lfMceJVRfSoQwqD4wEH5rLwoKJwUiZ/rfpiVBhnaF0FK4HoA==",
|
||||
"version": "10.4.0",
|
||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.4.0.tgz",
|
||||
"integrity": "sha512-oSK96Grm3aP6OrS263xVxbNDGVL7rzBtYdpGqlDG8iQdoenDoTs/nkki+DflYbAEE8Xl6o5YxhxlrKvI3nqKXQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 12"
|
||||
@@ -12107,9 +12123,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.15",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.15.tgz",
|
||||
"integrity": "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA==",
|
||||
"version": "3.3.16",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz",
|
||||
"integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -13483,9 +13499,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.16",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.16.tgz",
|
||||
"integrity": "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg==",
|
||||
"version": "8.5.25",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz",
|
||||
"integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -13503,7 +13519,7 @@
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.12",
|
||||
"nanoid": "^3.3.16",
|
||||
"picocolors": "^1.1.1",
|
||||
"source-map-js": "^1.2.1"
|
||||
},
|
||||
@@ -14616,9 +14632,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/seroval": {
|
||||
"version": "1.4.2",
|
||||
"resolved": "https://registry.npmjs.org/seroval/-/seroval-1.4.2.tgz",
|
||||
"integrity": "sha512-N3HEHRCZYn3cQbsC4B5ldj9j+tHdf4JZoYPlcI4rRYu0Xy4qN8MQf1Z08EibzB0WpgRG5BGK08FTrmM66eSzKQ==",
|
||||
"version": "1.5.6",
|
||||
"resolved": "https://registry.npmjs.org/seroval/-/seroval-1.5.6.tgz",
|
||||
"integrity": "sha512-rVQVWjjSvlINzaQPZH5JFqsqEsIWdTxY3iJZCnTL/5gQbXIRooVZKI60tVCkOVfzcRPejboxO2t0P89dg5mQaA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
@@ -14739,9 +14755,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/shell-quote": {
|
||||
"version": "1.8.4",
|
||||
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.4.tgz",
|
||||
"integrity": "sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ==",
|
||||
"version": "1.10.0",
|
||||
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.10.0.tgz",
|
||||
"integrity": "sha512-w1aiOKwKuRgtwAReIIj89puqg+I7GvX4IbLrvmhXbzQsj1+Zwi4VO3+fa6ZF91TWSjIxoEkKnMeHcLEODK5ZXA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -15916,17 +15932,34 @@
|
||||
}
|
||||
},
|
||||
"node_modules/type-is": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz",
|
||||
"integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==",
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
|
||||
"integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"content-type": "^1.0.5",
|
||||
"content-type": "^2.0.0",
|
||||
"media-typer": "^1.1.0",
|
||||
"mime-types": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
"node": ">= 18"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/type-is/node_modules/content-type": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz",
|
||||
"integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/type-is/node_modules/mime-db": {
|
||||
@@ -17266,9 +17299,9 @@
|
||||
"version": "0.2.1",
|
||||
"dependencies": {
|
||||
"@hono/mcp": "^0.2.3",
|
||||
"@hono/node-server": "^1.19.13",
|
||||
"@hono/node-server": "^2.0.10",
|
||||
"@modelcontextprotocol/sdk": "^1.26.0",
|
||||
"hono": "^4.12.25",
|
||||
"hono": "^4.12.34",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -17276,6 +17309,18 @@
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
},
|
||||
"plugins-external/mcp-server/node_modules/@hono/node-server": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.0.tgz",
|
||||
"integrity": "sha512-XovyyCCnBzW+zKu+z/zq8hwNs4KOR5rEMAOxo2f40Q5xoOI37IMm6MIg2COOUtUApo0i6850MTBKH2u4QLGIqg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"hono": "^4"
|
||||
}
|
||||
},
|
||||
"plugins/action-copy-curl": {
|
||||
"name": "@yaak/action-copy-curl",
|
||||
"version": "0.1.0"
|
||||
|
||||
+1
-1
@@ -121,7 +121,7 @@
|
||||
"dotenv-cli": "^11.0.0",
|
||||
"nodejs-file-downloader": "^4.13.0",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"postcss": "^8.5.16",
|
||||
"postcss": "^8.5.25",
|
||||
"tailwindcss": "^4.3.2",
|
||||
"typescript": "^5.8.3",
|
||||
"vite": "npm:@voidzero-dev/vite-plus-core@^0.2.1",
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { debounce } from "./debounce";
|
||||
|
||||
describe("debounce", () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("calls once with the latest args after the delay", () => {
|
||||
const fn = vi.fn();
|
||||
const d = debounce(fn, 100);
|
||||
|
||||
d("a");
|
||||
d("b");
|
||||
d("c");
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(100);
|
||||
expect(fn).toHaveBeenCalledExactlyOnceWith("c");
|
||||
});
|
||||
|
||||
it("flush invokes a pending call immediately", () => {
|
||||
const fn = vi.fn();
|
||||
const d = debounce(fn, 100);
|
||||
|
||||
d("a");
|
||||
d("b");
|
||||
d.flush();
|
||||
expect(fn).toHaveBeenCalledExactlyOnceWith("b");
|
||||
|
||||
// The scheduled call was cancelled, so waiting out the delay adds nothing
|
||||
vi.advanceTimersByTime(100);
|
||||
expect(fn).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("flush is a no-op with nothing pending", () => {
|
||||
const fn = vi.fn();
|
||||
const d = debounce(fn, 100);
|
||||
|
||||
d.flush();
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
|
||||
d("a");
|
||||
vi.advanceTimersByTime(100);
|
||||
d.flush();
|
||||
expect(fn).toHaveBeenCalledExactlyOnceWith("a");
|
||||
});
|
||||
|
||||
it("cancel drops the pending call and its args", () => {
|
||||
const fn = vi.fn();
|
||||
const d = debounce(fn, 100);
|
||||
|
||||
d("a");
|
||||
d.cancel();
|
||||
vi.advanceTimersByTime(100);
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
|
||||
// A cancelled call must not leak its args into the next one
|
||||
d.flush();
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("starts a fresh delay after firing", () => {
|
||||
const fn = vi.fn();
|
||||
const d = debounce(fn, 100);
|
||||
|
||||
d("a");
|
||||
vi.advanceTimersByTime(100);
|
||||
d("b");
|
||||
vi.advanceTimersByTime(99);
|
||||
expect(fn).toHaveBeenCalledOnce();
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(fn).toHaveBeenCalledTimes(2);
|
||||
expect(fn).toHaveBeenLastCalledWith("b");
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,32 @@
|
||||
// oxlint-disable-next-line no-explicit-any
|
||||
export function debounce(fn: (...args: any[]) => void, delay = 500) {
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
// oxlint-disable-next-line no-explicit-any
|
||||
let lastArgs: any[] | null = null;
|
||||
// oxlint-disable-next-line no-explicit-any
|
||||
const result = (...args: any[]) => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => fn(...args), delay);
|
||||
lastArgs = args;
|
||||
if (timer != null) clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
timer = null;
|
||||
const argsToUse = lastArgs ?? [];
|
||||
lastArgs = null;
|
||||
fn(...argsToUse);
|
||||
}, delay);
|
||||
};
|
||||
result.cancel = () => {
|
||||
if (timer != null) clearTimeout(timer);
|
||||
timer = null;
|
||||
lastArgs = null;
|
||||
};
|
||||
// Invoke a pending call immediately instead of waiting out the delay
|
||||
result.flush = () => {
|
||||
if (timer == null) return;
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
const argsToUse = lastArgs ?? [];
|
||||
lastArgs = null;
|
||||
fn(...argsToUse);
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -147,8 +147,13 @@ function normalizeColorVariables(theme: Theme, vars: CSSVariables): CSSVariables
|
||||
|
||||
function templateTagColorVariables(theme: Theme, color: YaakColor): CSSVariables {
|
||||
return completeFullColorVariables(theme, {
|
||||
text: color.liftMax().lower(0.05).css(),
|
||||
textSubtle: color.liftMax().lower(0.08).css(),
|
||||
// Lift toward the foreground, but not all the way. liftMax() pushes lightness to an
|
||||
// extreme, and the two extremes don't behave alike: lightening past the sRGB gamut clips
|
||||
// to a still-tinted color, while darkening to zero lightness collapses every hue to black.
|
||||
// That's why tags kept their color in dark mode and turned black in light. Stopping short
|
||||
// keeps the hue in both, and still clears 6:1 against the tag's own surface.
|
||||
text: color.lift(0.6).css(),
|
||||
textSubtle: color.lift(0.5).css(),
|
||||
textSubtlest: color.css(),
|
||||
surface: color.lower(0.2).translucify(0.8).css(),
|
||||
border: color.translucify(0.6).css(),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { DragEndEvent, DragMoveEvent, DragStartEvent } from "@dnd-kit/core";
|
||||
import type { Virtualizer } from "@tanstack/react-virtual";
|
||||
import {
|
||||
DndContext,
|
||||
MeasuringStrategy,
|
||||
@@ -23,10 +24,10 @@ import {
|
||||
} from "react";
|
||||
import { useKey, useKeyPressEvent } from "react-use";
|
||||
import { computeSideForDragMove } from "../../lib/dnd";
|
||||
import { useStore } from "jotai";
|
||||
import { useAtomValue, useStore } from "jotai";
|
||||
import { draggingIdsFamily, focusIdsFamily, hoveredParentFamily, selectedIdsFamily } from "./atoms";
|
||||
import { type CollapsedAtom, CollapsedAtomContext } from "./context";
|
||||
import type { ContextMenuRenderer, JotaiStore, SelectableTreeNode, TreeNode } from "./common";
|
||||
import type { ContextMenuRenderer, TreeNode } from "./common";
|
||||
import { closestVisibleNode, equalSubtree, getSelectedItems, hasAncestor } from "./common";
|
||||
import { TreeDragOverlay } from "./TreeDragOverlay";
|
||||
import type { TreeItemClickEvent, TreeItemHandle, TreeItemProps } from "./TreeItem";
|
||||
@@ -87,7 +88,39 @@ function TreeInner<T extends { id: string }>(
|
||||
) {
|
||||
const store = useStore();
|
||||
const treeRef = useRef<HTMLDivElement>(null);
|
||||
const virtualizerRef = useRef<Virtualizer<HTMLElement, Element> | null>(null);
|
||||
|
||||
// The scroll container is tracked in state as well as a ref, so the virtualizer re-resolves it
|
||||
// once it exists. React attaches refs and runs layout effects child-first, so TreeItemList's
|
||||
// effects run before this ancestor's ref is set: on a fresh mount a ref-only getScrollElement
|
||||
// returns null, and the virtualizer renders nothing until some later render happens to wake it
|
||||
// up. Usually one does, which is why this only showed when the tree remounted into settled data
|
||||
// (filtering down to no results and back).
|
||||
const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null);
|
||||
const setTreeRef = useCallback((el: HTMLDivElement | null) => {
|
||||
treeRef.current = el;
|
||||
setScrollEl(el);
|
||||
}, []);
|
||||
const getScrollElement = useCallback(() => scrollEl, [scrollEl]);
|
||||
const handleVirtualizerReady = useCallback((v: Virtualizer<HTMLElement, Element>) => {
|
||||
virtualizerRef.current = v;
|
||||
}, []);
|
||||
const selectableItems = useSelectableItems(root);
|
||||
|
||||
// Only render nodes that are actually visible (not filtered out, and not
|
||||
// inside a collapsed folder). Mounting every node regardless of visibility
|
||||
// makes large workspaces unusable: thousands of hidden TreeItems each run
|
||||
// their dnd/context hooks on every tree commit just to return null.
|
||||
const collapsedMap = useAtomValue(collapsedAtom);
|
||||
const visibleItems = useMemo(() => {
|
||||
return selectableItems.filter((i) => {
|
||||
if (i.node.hidden) return false;
|
||||
for (let p = i.node.parent; p != null; p = p.parent) {
|
||||
if (collapsedMap[p.item.id]) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}, [selectableItems, collapsedMap]);
|
||||
const [showContextMenu, setShowContextMenu] = useState<{
|
||||
items: unknown[];
|
||||
x: number;
|
||||
@@ -97,6 +130,28 @@ function TreeInner<T extends { id: string }>(
|
||||
const handleAddTreeItemRef = useCallback((item: T, r: TreeItemHandle | null) => {
|
||||
if (r == null) {
|
||||
delete treeItemRefs.current[item.id];
|
||||
|
||||
// Keep keyboard focus inside the tree when the focused row is virtualized away.
|
||||
//
|
||||
// Scrolling the focused row out of the window destroys the button holding focus, and the
|
||||
// browser drops focus to the body rather than moving it anywhere. Everything keyboard-driven
|
||||
// is gated on the tree containing document.activeElement (arrow navigation here, rename,
|
||||
// delete, duplicate and the context menu in the consumer), so the entire keyboard interface
|
||||
// would go dead until the user clicked a row again. They all act on the selected id rather
|
||||
// than the focused element, so parking focus on the container is enough to keep them live.
|
||||
//
|
||||
// NOTE: This has to hang off the unmount rather than a render or a focusout. Scrolling
|
||||
// re-renders the list, not this component, and removing a focused element doesn't reliably
|
||||
// fire focusout.
|
||||
requestAnimationFrame(() => {
|
||||
const el = treeRef.current;
|
||||
if (el == null) return;
|
||||
const active = document.activeElement;
|
||||
const focusWasDropped = active == null || active === document.body || !active.isConnected;
|
||||
if (focusWasDropped) {
|
||||
el.focus({ preventScroll: true });
|
||||
}
|
||||
});
|
||||
} else {
|
||||
treeItemRefs.current[item.id] = r;
|
||||
}
|
||||
@@ -125,16 +180,28 @@ function TreeInner<T extends { id: string }>(
|
||||
}, []);
|
||||
|
||||
const tryFocus = useCallback(() => {
|
||||
const $el = treeRef.current?.querySelector<HTMLButtonElement>(
|
||||
'.tree-item button[tabindex="0"]',
|
||||
);
|
||||
if ($el == null) {
|
||||
const find = () =>
|
||||
treeRef.current?.querySelector<HTMLButtonElement>('.tree-item button[tabindex="0"]');
|
||||
const $el = find();
|
||||
if ($el != null) {
|
||||
// preventScroll so scrolling stays single-sourced (focus() implicitly
|
||||
// scrolls, which fights the virtualizer's scrollToIndex)
|
||||
$el.focus({ preventScroll: true });
|
||||
$el.scrollIntoView({ block: "nearest" });
|
||||
return true;
|
||||
}
|
||||
|
||||
// The focused row may be virtualized out of range. Scroll it into range,
|
||||
// then focus it once it has mounted.
|
||||
const lastFocusedId = store.get(focusIdsFamily(treeId)).lastId;
|
||||
const index = visibleItems.findIndex((i) => i.node.item.id === lastFocusedId);
|
||||
if (index < 0) {
|
||||
return false;
|
||||
}
|
||||
$el.focus();
|
||||
$el.scrollIntoView({ block: "nearest" });
|
||||
virtualizerRef.current?.scrollToIndex(index, { align: "auto" });
|
||||
requestAnimationFrame(() => find()?.focus({ preventScroll: true }));
|
||||
return true;
|
||||
}, []);
|
||||
}, [store, treeId, visibleItems]);
|
||||
|
||||
const ensureTabbableItem = useCallback(() => {
|
||||
const lastSelectedId = store.get(focusIdsFamily(treeId)).lastId;
|
||||
@@ -187,13 +254,42 @@ function TreeInner<T extends { id: string }>(
|
||||
[treeId, tryFocus],
|
||||
);
|
||||
|
||||
/**
|
||||
* Run something against a row's handle, scrolling the row into view first when it isn't
|
||||
* mounted.
|
||||
*
|
||||
* Virtualized rows only have a handle while they're in the window, but the row these act on is
|
||||
* the selected one, which the user is free to scroll away from before hitting a hotkey. Without
|
||||
* this, renaming an off-screen row silently does nothing and the context menu has no rect to
|
||||
* open against.
|
||||
*/
|
||||
const withTreeItem = useCallback(
|
||||
(id: string, action: (handle: TreeItemHandle) => void) => {
|
||||
const mounted = treeItemRefs.current[id];
|
||||
if (mounted != null) {
|
||||
action(mounted);
|
||||
return;
|
||||
}
|
||||
|
||||
const index = visibleItems.findIndex((i) => i.node.item.id === id);
|
||||
if (index < 0) return;
|
||||
|
||||
virtualizerRef.current?.scrollToIndex(index, { align: "auto" });
|
||||
requestAnimationFrame(() => {
|
||||
const handle = treeItemRefs.current[id];
|
||||
if (handle != null) action(handle);
|
||||
});
|
||||
},
|
||||
[visibleItems],
|
||||
);
|
||||
|
||||
const treeHandle = useMemo<TreeHandle>(
|
||||
() => ({
|
||||
treeId,
|
||||
focus: tryFocus,
|
||||
hasFocus: hasFocus,
|
||||
getSelectedItems: () => getSelectedItems(store, treeId, selectableItems),
|
||||
renameItem: (id) => treeItemRefs.current[id]?.rename(),
|
||||
renameItem: (id) => withTreeItem(id, (handle) => handle.rename()),
|
||||
selectItem: (id, focus) => {
|
||||
if (store.get(selectedIdsFamily(treeId)).includes(id)) {
|
||||
// Already selected
|
||||
@@ -207,12 +303,14 @@ function TreeInner<T extends { id: string }>(
|
||||
const items = getSelectedItems(store, treeId, selectableItems);
|
||||
const menuItems = await getContextMenu(items);
|
||||
const lastSelectedId = store.get(focusIdsFamily(treeId)).lastId;
|
||||
const rect = lastSelectedId ? treeItemRefs.current[lastSelectedId]?.rect() : null;
|
||||
if (rect == null) return;
|
||||
setShowContextMenu({ items: menuItems, x: rect.x, y: rect.y });
|
||||
if (lastSelectedId == null) return;
|
||||
withTreeItem(lastSelectedId, (handle) => {
|
||||
const rect = handle.rect();
|
||||
setShowContextMenu({ items: menuItems, x: rect.x, y: rect.y });
|
||||
});
|
||||
},
|
||||
}),
|
||||
[getContextMenu, hasFocus, selectableItems, setSelected, treeId, tryFocus],
|
||||
[getContextMenu, hasFocus, selectableItems, setSelected, treeId, tryFocus, withTreeItem],
|
||||
);
|
||||
|
||||
useImperativeHandle(ref, (): TreeHandle => treeHandle, [treeHandle]);
|
||||
@@ -244,11 +342,8 @@ function TreeInner<T extends { id: string }>(
|
||||
store.set(focusIdsFamily(treeId), (prev) => ({ ...prev, lastId: item.id }));
|
||||
|
||||
if (shiftKey) {
|
||||
const validSelectableItems = getValidSelectableItems(store, collapsedAtom, selectableItems);
|
||||
const anchorIndex = validSelectableItems.findIndex(
|
||||
(i) => i.node.item.id === anchorSelectedId,
|
||||
);
|
||||
const currIndex = validSelectableItems.findIndex((v) => v.node.item.id === item.id);
|
||||
const anchorIndex = visibleItems.findIndex((i) => i.node.item.id === anchorSelectedId);
|
||||
const currIndex = visibleItems.findIndex((v) => v.node.item.id === item.id);
|
||||
|
||||
// Nothing was selected yet, so just select this item
|
||||
if (selectedIds.length === 0 || anchorIndex === -1 || currIndex === -1) {
|
||||
@@ -259,14 +354,14 @@ function TreeInner<T extends { id: string }>(
|
||||
|
||||
if (currIndex > anchorIndex) {
|
||||
// Selecting down
|
||||
const itemsToSelect = validSelectableItems.slice(anchorIndex, currIndex + 1);
|
||||
const itemsToSelect = visibleItems.slice(anchorIndex, currIndex + 1);
|
||||
setSelected(
|
||||
itemsToSelect.map((v) => v.node.item.id),
|
||||
true,
|
||||
);
|
||||
} else if (currIndex < anchorIndex) {
|
||||
// Selecting up
|
||||
const itemsToSelect = validSelectableItems.slice(currIndex, anchorIndex + 1);
|
||||
const itemsToSelect = visibleItems.slice(currIndex, anchorIndex + 1);
|
||||
setSelected(
|
||||
itemsToSelect.map((v) => v.node.item.id),
|
||||
true,
|
||||
@@ -289,7 +384,7 @@ function TreeInner<T extends { id: string }>(
|
||||
store.set(focusIdsFamily(treeId), (prev) => ({ ...prev, anchorId: item.id }));
|
||||
}
|
||||
},
|
||||
[selectableItems, setSelected, treeId],
|
||||
[setSelected, treeId, visibleItems],
|
||||
);
|
||||
|
||||
const handleClick = useCallback<NonNullable<TreeItemProps<T>["onClick"]>>(
|
||||
@@ -307,27 +402,25 @@ function TreeInner<T extends { id: string }>(
|
||||
const selectPrevItem = useCallback(
|
||||
(e: TreeItemClickEvent) => {
|
||||
const lastSelectedId = store.get(focusIdsFamily(treeId)).lastId;
|
||||
const validSelectableItems = getValidSelectableItems(store, collapsedAtom, selectableItems);
|
||||
const index = validSelectableItems.findIndex((i) => i.node.item.id === lastSelectedId);
|
||||
const item = validSelectableItems[index - 1];
|
||||
const index = visibleItems.findIndex((i) => i.node.item.id === lastSelectedId);
|
||||
const item = visibleItems[index - 1];
|
||||
if (item != null) {
|
||||
handleSelect(item.node.item, e);
|
||||
}
|
||||
},
|
||||
[handleSelect, selectableItems, treeId],
|
||||
[handleSelect, treeId, visibleItems],
|
||||
);
|
||||
|
||||
const selectNextItem = useCallback(
|
||||
(e: TreeItemClickEvent) => {
|
||||
const lastSelectedId = store.get(focusIdsFamily(treeId)).lastId;
|
||||
const validSelectableItems = getValidSelectableItems(store, collapsedAtom, selectableItems);
|
||||
const index = validSelectableItems.findIndex((i) => i.node.item.id === lastSelectedId);
|
||||
const item = validSelectableItems[index + 1];
|
||||
const index = visibleItems.findIndex((i) => i.node.item.id === lastSelectedId);
|
||||
const item = visibleItems[index + 1];
|
||||
if (item != null) {
|
||||
handleSelect(item.node.item, e);
|
||||
}
|
||||
},
|
||||
[handleSelect, selectableItems, treeId],
|
||||
[handleSelect, treeId, visibleItems],
|
||||
);
|
||||
|
||||
const selectParentItem = useCallback(
|
||||
@@ -448,8 +541,8 @@ function TreeInner<T extends { id: string }>(
|
||||
store.set(hoveredParentFamily(treeId), {
|
||||
parentId: root.item.id,
|
||||
parentDepth: root.depth,
|
||||
index: selectableItems.length,
|
||||
childIndex: selectableItems.length,
|
||||
index: visibleItems.length,
|
||||
childIndex: visibleItems.length,
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -477,8 +570,8 @@ function TreeInner<T extends { id: string }>(
|
||||
|
||||
const item = node.item;
|
||||
let hoveredParent = node.parent;
|
||||
const dragIndex = selectableItems.findIndex((n) => n.node.item.id === item.id) ?? -1;
|
||||
const hovered = selectableItems[dragIndex]?.node ?? null;
|
||||
const dragIndex = visibleItems.findIndex((n) => n.node.item.id === item.id) ?? -1;
|
||||
const hovered = visibleItems[dragIndex]?.node ?? null;
|
||||
const hoveredIndex = dragIndex + (side === "before" ? 0 : 1);
|
||||
let hoveredChildIndex = overSelectableItem.index + (side === "before" ? 0 : 1);
|
||||
|
||||
@@ -509,7 +602,7 @@ function TreeInner<T extends { id: string }>(
|
||||
});
|
||||
}
|
||||
},
|
||||
[root.depth, root.item.id, selectableItems, treeId],
|
||||
[root.depth, root.item.id, selectableItems, treeId, visibleItems],
|
||||
);
|
||||
|
||||
const handleDragStart = useCallback(
|
||||
@@ -659,7 +752,10 @@ function TreeInner<T extends { id: string }>(
|
||||
autoScroll
|
||||
>
|
||||
<div
|
||||
ref={treeRef}
|
||||
ref={setTreeRef}
|
||||
// Focusable so the container can hold focus when the focused row unmounts. Not reachable
|
||||
// by tabbing, since the rows themselves are what's tabbable.
|
||||
tabIndex={-1}
|
||||
className={classNames(
|
||||
className,
|
||||
"outline-hidden h-full",
|
||||
@@ -680,12 +776,18 @@ function TreeInner<T extends { id: string }>(
|
||||
"[&_.tree-item.selected+.drop-marker+.tree-item.selected]:rounded-t-none",
|
||||
"[&_.tree-item.selected:has(+.tree-item.selected)]:rounded-b-none",
|
||||
"[&_.tree-item.selected:has(+.drop-marker+.tree-item.selected)]:rounded-b-none",
|
||||
// Virtualized rows are wrapped in .tree-row divs, so the sibling
|
||||
// relationships above need wrapper-aware equivalents
|
||||
"[&_.tree-row:has(.tree-item.selected)+.tree-row_.tree-item.selected]:rounded-t-none",
|
||||
"[&_.tree-row:has(.tree-item.selected):has(+.tree-row_.tree-item.selected)_.tree-item.selected]:rounded-b-none",
|
||||
)}
|
||||
>
|
||||
<TreeItemList
|
||||
addTreeItemRef={handleAddTreeItemRef}
|
||||
nodes={selectableItems}
|
||||
nodes={visibleItems}
|
||||
treeId={treeId}
|
||||
getScrollElement={getScrollElement}
|
||||
onVirtualizerReady={handleVirtualizerReady}
|
||||
{...treeItemListProps}
|
||||
/>
|
||||
</div>
|
||||
@@ -731,20 +833,3 @@ function DropRegionAfterList({
|
||||
// biome-ignore lint/a11y/noStaticElementInteractions: Meh
|
||||
return <div ref={setNodeRef} onContextMenu={onContextMenu} />;
|
||||
}
|
||||
|
||||
function getValidSelectableItems<T extends { id: string }>(
|
||||
store: JotaiStore,
|
||||
collapsedAtom: CollapsedAtom,
|
||||
selectableItems: SelectableTreeNode<T>[],
|
||||
) {
|
||||
const collapsed = store.get(collapsedAtom);
|
||||
return selectableItems.filter((i) => {
|
||||
if (i.node.hidden) return false;
|
||||
let p = i.node.parent;
|
||||
while (p) {
|
||||
if (collapsed[p.item.id]) return false;
|
||||
p = p.parent;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from "./context";
|
||||
import type { TreeNode } from "./common";
|
||||
import { getNodeKey } from "./common";
|
||||
import { isImeCompositionEvent } from "./keyboard";
|
||||
import type { TreeProps } from "./Tree";
|
||||
import { TreeIndentGuide } from "./TreeIndentGuide";
|
||||
|
||||
@@ -106,8 +107,14 @@ function TreeItem_<T extends { id: string }>({
|
||||
[editing, getEditOptions],
|
||||
);
|
||||
|
||||
// NOTE: Unregisters on unmount, or the tree keeps a handle to a component that no longer exists.
|
||||
// Harmless while every row stayed mounted, but virtualized rows unmount whenever they leave the
|
||||
// window, and acting on a dead handle does nothing at best (rename) and reports a zeroed rect at
|
||||
// worst (the context menu opening in the corner of the screen).
|
||||
useEffect(() => {
|
||||
setRef?.(node.item, handle);
|
||||
const item = node.item;
|
||||
setRef?.(item, handle);
|
||||
return () => setRef?.(item, null);
|
||||
}, [setRef, handle, node.item]);
|
||||
|
||||
const ancestorIds = useMemo(() => {
|
||||
@@ -170,6 +177,8 @@ function TreeItem_<T extends { id: string }>({
|
||||
const handleEditKeyDown = useCallback(
|
||||
async (e: ReactKeyboardEvent<HTMLInputElement>) => {
|
||||
e.stopPropagation(); // Don't trigger other tree keys (like arrows)
|
||||
if (isImeCompositionEvent(e.nativeEvent)) return;
|
||||
|
||||
switch (e.key) {
|
||||
case "Enter":
|
||||
if (editing) {
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { Virtualizer } from "@tanstack/react-virtual";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { useAtomValue } from "jotai";
|
||||
import type { CSSProperties } from "react";
|
||||
import { Fragment } from "react";
|
||||
import { Fragment, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { draggingIdsFamily } from "./atoms";
|
||||
import type { SelectableTreeNode } from "./common";
|
||||
import type { TreeProps } from "./Tree";
|
||||
import { TreeDropMarker } from "./TreeDropMarker";
|
||||
@@ -22,9 +26,22 @@ export type TreeItemListProps<T extends { id: string }> = Pick<
|
||||
className?: string;
|
||||
forceDepth?: number;
|
||||
addTreeItemRef?: (item: T, n: TreeItemHandle | null) => void;
|
||||
/**
|
||||
* Enable virtualization by providing the scroll container. Rows are then
|
||||
* windowed with @tanstack/react-virtual and only visible rows mount.
|
||||
*/
|
||||
getScrollElement?: () => HTMLElement | null;
|
||||
onVirtualizerReady?: (v: Virtualizer<HTMLElement, Element>) => void;
|
||||
};
|
||||
|
||||
export function TreeItemList<T extends { id: string }>({
|
||||
export function TreeItemList<T extends { id: string }>(props: TreeItemListProps<T>) {
|
||||
if (props.getScrollElement != null) {
|
||||
return <VirtualTreeItemList {...props} getScrollElement={props.getScrollElement} />;
|
||||
}
|
||||
return <StaticTreeItemList {...props} />;
|
||||
}
|
||||
|
||||
function StaticTreeItemList<T extends { id: string }>({
|
||||
className,
|
||||
getItemKey,
|
||||
nodes,
|
||||
@@ -32,6 +49,8 @@ export function TreeItemList<T extends { id: string }>({
|
||||
treeId,
|
||||
forceDepth,
|
||||
addTreeItemRef,
|
||||
getScrollElement: _getScrollElement,
|
||||
onVirtualizerReady: _onVirtualizerReady,
|
||||
...props
|
||||
}: TreeItemListProps<T>) {
|
||||
return (
|
||||
@@ -53,3 +72,120 @@ export function TreeItemList<T extends { id: string }>({
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
// Rows are --height-sm (2rem). Derive the pixel estimate from the actual root
|
||||
// font size so scroll math stays accurate under interface scaling.
|
||||
function estimateRowHeightPx() {
|
||||
const rem = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
|
||||
return 2 * rem;
|
||||
}
|
||||
|
||||
function VirtualTreeItemList<T extends { id: string }>({
|
||||
className,
|
||||
getItemKey,
|
||||
nodes,
|
||||
style,
|
||||
treeId,
|
||||
forceDepth,
|
||||
addTreeItemRef,
|
||||
getScrollElement,
|
||||
onVirtualizerReady,
|
||||
...props
|
||||
}: TreeItemListProps<T> & { getScrollElement: () => HTMLElement | null }) {
|
||||
const listRef = useRef<HTMLUListElement>(null);
|
||||
|
||||
// Offset of the list within the scroll container (eg. container padding),
|
||||
// so windowing and scrollToIndex targets aren't shifted by it
|
||||
const [scrollMargin, setScrollMargin] = useState(0);
|
||||
useLayoutEffect(() => {
|
||||
const list = listRef.current;
|
||||
const scroller = getScrollElement();
|
||||
if (list == null || scroller == null) return;
|
||||
const offset =
|
||||
list.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop;
|
||||
setScrollMargin(offset);
|
||||
}, [getScrollElement]);
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: nodes.length,
|
||||
getScrollElement,
|
||||
estimateSize: estimateRowHeightPx,
|
||||
overscan: 10,
|
||||
scrollMargin,
|
||||
});
|
||||
|
||||
useLayoutEffect(() => {
|
||||
onVirtualizerReady?.(virtualizer);
|
||||
}, [virtualizer, onVirtualizerReady]);
|
||||
|
||||
const virtualItems = virtualizer.getVirtualItems();
|
||||
|
||||
// Rows being dragged stay mounted even after they scroll out of the window.
|
||||
//
|
||||
// dnd-kit keeps a live reference to the node being dragged and re-measures it whenever that
|
||||
// node is replaced. Its scroll adjustment is a delta against a baseline captured when that rect
|
||||
// was last measured, and re-measuring resets the baseline to wherever the list happens to be
|
||||
// scrolled right then, discarding the scroll accumulated so far. Letting the dragged row unmount
|
||||
// mid-drag therefore corrupts every coordinate dnd-kit derives, by a bit more each time it
|
||||
// happens, which is why the drop indicator drifts further the longer a drag autoscrolls.
|
||||
const draggingIds = useAtomValue(draggingIdsFamily(treeId));
|
||||
const pinnedIndexes = useMemo(() => {
|
||||
if (draggingIds.length === 0) return [];
|
||||
const rendered = new Set(virtualItems.map((v) => v.index));
|
||||
const out: number[] = [];
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const node = nodes[i];
|
||||
if (node == null || rendered.has(i)) continue;
|
||||
if (draggingIds.includes(node.node.item.id)) out.push(i);
|
||||
}
|
||||
return out;
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: keyed off the rendered range
|
||||
}, [draggingIds, nodes, virtualItems]);
|
||||
|
||||
const renderRow = (index: number, start: number, measure: boolean) => {
|
||||
const child = nodes[index];
|
||||
if (child == null) return null;
|
||||
return (
|
||||
<div
|
||||
// Key by item so window shifts don't remount rows unnecessarily
|
||||
key={getItemKey(child.node.item)}
|
||||
ref={measure ? virtualizer.measureElement : undefined}
|
||||
data-index={index}
|
||||
className="tree-row"
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
transform: `translateY(${start - scrollMargin}px)`,
|
||||
}}
|
||||
>
|
||||
<TreeItem
|
||||
treeId={treeId}
|
||||
setRef={addTreeItemRef}
|
||||
node={child.node}
|
||||
getItemKey={getItemKey}
|
||||
depth={forceDepth == null ? child.depth : forceDepth}
|
||||
{...props}
|
||||
/>
|
||||
<TreeDropMarker node={child.node} treeId={treeId} index={index + 1} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<ul
|
||||
ref={listRef}
|
||||
style={{ ...style, height: `${virtualizer.getTotalSize()}px`, position: "relative" }}
|
||||
className={className}
|
||||
>
|
||||
<TreeDropMarker node={null} treeId={treeId} index={0} />
|
||||
{virtualItems.map((virtualItem) => renderRow(virtualItem.index, virtualItem.start, true))}
|
||||
{/* NOTE: Not measured. Measuring an out-of-window row would write its size into the
|
||||
virtualizer's cache under an index the window isn't tracking. */}
|
||||
{pinnedIndexes.map((index) =>
|
||||
renderRow(index, virtualizer.measurementsCache[index]?.start ?? 0, false),
|
||||
)}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { isImeCompositionEvent } from "./keyboard";
|
||||
|
||||
describe("isImeCompositionEvent", () => {
|
||||
test("detects an active standards-based composition", () => {
|
||||
expect(isImeCompositionEvent({ isComposing: true, keyCode: 13 })).toBe(true);
|
||||
});
|
||||
|
||||
test("detects the Safari/WebKit key code fallback", () => {
|
||||
expect(isImeCompositionEvent({ isComposing: false, keyCode: 229 })).toBe(true);
|
||||
});
|
||||
|
||||
test("does not classify an ordinary Enter keydown as composition", () => {
|
||||
expect(isImeCompositionEvent({ isComposing: false, keyCode: 13 })).toBe(false);
|
||||
});
|
||||
|
||||
test("does not classify an ordinary Escape keydown as composition", () => {
|
||||
expect(isImeCompositionEvent({ isComposing: false, keyCode: 27 })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
export type ImeKeyboardEvent = Pick<KeyboardEvent, "isComposing" | "keyCode">;
|
||||
|
||||
export function isImeCompositionEvent(event: ImeKeyboardEvent): boolean {
|
||||
// Safari can clear `isComposing` on the keydown that finishes composition.
|
||||
// `229` is retained as the compatibility signal that an IME is processing it.
|
||||
return event.isComposing || event.keyCode === 229;
|
||||
}
|
||||
@@ -15,9 +15,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@hono/mcp": "^0.2.3",
|
||||
"@hono/node-server": "^1.19.13",
|
||||
"@hono/node-server": "^2.0.10",
|
||||
"@modelcontextprotocol/sdk": "^1.26.0",
|
||||
"hono": "^4.12.25",
|
||||
"hono": "^4.12.34",
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -13,6 +13,7 @@ export async function getOrRefreshAccessToken(
|
||||
credentialsInBody,
|
||||
clientId,
|
||||
clientSecret,
|
||||
tokenName,
|
||||
forceRefresh,
|
||||
}: {
|
||||
scope: string | null;
|
||||
@@ -20,6 +21,7 @@ export async function getOrRefreshAccessToken(
|
||||
credentialsInBody: boolean;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
tokenName?: "access_token" | "id_token";
|
||||
forceRefresh?: boolean;
|
||||
},
|
||||
): Promise<AccessToken | null> {
|
||||
@@ -28,7 +30,7 @@ export async function getOrRefreshAccessToken(
|
||||
return null;
|
||||
}
|
||||
|
||||
const isExpired = isTokenExpired(token);
|
||||
const isExpired = isTokenExpired(token, tokenName);
|
||||
|
||||
// Return the current access token if it's still valid
|
||||
if (!isExpired && !forceRefresh) {
|
||||
@@ -111,5 +113,5 @@ export async function getOrRefreshAccessToken(
|
||||
refresh_token: response.refresh_token ?? token.response.refresh_token,
|
||||
};
|
||||
|
||||
return storeToken(ctx, tokenArgs, newResponse);
|
||||
return storeToken(ctx, tokenArgs, newResponse, tokenName);
|
||||
}
|
||||
|
||||
@@ -67,6 +67,7 @@ export async function getAuthorizationCode(
|
||||
clientId,
|
||||
clientSecret,
|
||||
credentialsInBody,
|
||||
tokenName,
|
||||
});
|
||||
if (token != null) {
|
||||
return token;
|
||||
|
||||
@@ -37,7 +37,7 @@ export async function getImplicit(
|
||||
authorizationUrl: authorizationUrlRaw,
|
||||
};
|
||||
const token = await getToken(ctx, tokenArgs);
|
||||
if (token != null && !isTokenExpired(token)) {
|
||||
if (token != null && !isTokenExpired(token, tokenName)) {
|
||||
return token;
|
||||
}
|
||||
|
||||
@@ -137,7 +137,7 @@ async function getTokenViaEmbeddedBrowser(
|
||||
|
||||
const response = Object.fromEntries(params) as unknown as AccessTokenRawResponse;
|
||||
try {
|
||||
resolve(storeToken(ctx, tokenArgs, response));
|
||||
resolve(storeToken(ctx, tokenArgs, response, tokenName));
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
@@ -195,5 +195,5 @@ async function extractImplicitToken(
|
||||
response.id_token = idToken;
|
||||
}
|
||||
|
||||
return storeToken(ctx, tokenArgs, response);
|
||||
return storeToken(ctx, tokenArgs, response, tokenName);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import type { Context } from "@yaakapp/api";
|
||||
import { jwtExpiresAt } from "./util";
|
||||
|
||||
export async function storeToken(
|
||||
ctx: Context,
|
||||
@@ -11,7 +12,10 @@ export async function storeToken(
|
||||
throw new Error(`${tokenName} not found in response ${Object.keys(response).join(", ")}`);
|
||||
}
|
||||
|
||||
const expiresAt = response.expires_in ? Date.now() + response.expires_in * 1000 : null;
|
||||
// Prefer expires_in from the response, falling back to the JWT's own exp claim
|
||||
const expiresAt = response.expires_in
|
||||
? Date.now() + response.expires_in * 1000
|
||||
: jwtExpiresAt(response[tokenName]);
|
||||
const token: AccessToken = {
|
||||
response,
|
||||
expiresAt,
|
||||
|
||||
@@ -1,7 +1,34 @@
|
||||
import jwt from "jsonwebtoken";
|
||||
import type { AccessToken } from "./store";
|
||||
|
||||
export function isTokenExpired(token: AccessToken) {
|
||||
return token.expiresAt && Date.now() > token.expiresAt;
|
||||
export function isTokenExpired(
|
||||
token: AccessToken,
|
||||
tokenName: "access_token" | "id_token" = "access_token",
|
||||
) {
|
||||
// Fall back to the JWT's own exp claim for tokens stored without an expiry
|
||||
// (eg. from a token response that had no expires_in). Decode the same token
|
||||
// that gets sent as the credential.
|
||||
const expiresAt = token.expiresAt ?? jwtExpiresAt(token.response[tokenName]);
|
||||
return expiresAt != null && Date.now() > expiresAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the expiry timestamp (ms) from a JWT's `exp` claim, or null if the token
|
||||
* is not a JWT or has no `exp`.
|
||||
*/
|
||||
export function jwtExpiresAt(token: string | undefined): number | null {
|
||||
if (!token) return null;
|
||||
|
||||
try {
|
||||
const payload = jwt.decode(token);
|
||||
if (payload != null && typeof payload === "object" && typeof payload.exp === "number") {
|
||||
return payload.exp * 1000;
|
||||
}
|
||||
} catch {
|
||||
// Opaque (non-JWT) token
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function extractCode(urlStr: string, redirectUri: string | null): string | null {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import jwt from "jsonwebtoken";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { extractCode } from "../src/util";
|
||||
import { extractCode, isTokenExpired, jwtExpiresAt } from "../src/util";
|
||||
|
||||
describe("extractCode", () => {
|
||||
test("extracts code from query when same origin + path", () => {
|
||||
@@ -107,3 +108,55 @@ describe("extractCode", () => {
|
||||
expect(extractCode(url, redirect)).toBe("abc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isTokenExpired", () => {
|
||||
const jwtWithExp = (expSecondsFromNow: number) =>
|
||||
jwt.sign({ exp: Math.floor(Date.now() / 1000) + expSecondsFromNow }, "test-secret");
|
||||
|
||||
test("uses stored expiresAt when present", () => {
|
||||
expect(isTokenExpired({ response: { access_token: "x" }, expiresAt: Date.now() - 1000 })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(isTokenExpired({ response: { access_token: "x" }, expiresAt: Date.now() + 10000 })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("falls back to JWT exp claim when expiresAt is null", () => {
|
||||
expect(
|
||||
isTokenExpired({ response: { access_token: jwtWithExp(-60) }, expiresAt: null }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isTokenExpired({ response: { access_token: jwtWithExp(60) }, expiresAt: null }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("treats opaque tokens without expiresAt as non-expiring", () => {
|
||||
expect(isTokenExpired({ response: { access_token: "opaque-token" }, expiresAt: null })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("checks the token that is used as the credential", () => {
|
||||
// Expired id_token credential is not masked by an opaque access_token
|
||||
const token = {
|
||||
response: { access_token: "opaque-token", id_token: jwtWithExp(-60) },
|
||||
expiresAt: null,
|
||||
};
|
||||
expect(isTokenExpired(token, "id_token")).toBe(true);
|
||||
expect(isTokenExpired(token, "access_token")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("jwtExpiresAt", () => {
|
||||
test("extracts exp claim in milliseconds", () => {
|
||||
const exp = Math.floor(Date.now() / 1000) + 300;
|
||||
expect(jwtExpiresAt(jwt.sign({ exp }, "test-secret"))).toBe(exp * 1000);
|
||||
});
|
||||
|
||||
test("returns null for non-JWT or missing tokens", () => {
|
||||
expect(jwtExpiresAt("not-a-jwt")).toBeNull();
|
||||
expect(jwtExpiresAt(undefined)).toBeNull();
|
||||
expect(jwtExpiresAt(jwt.sign({ foo: "bar" }, "test-secret"))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/* oxlint-disable no-explicit-any */
|
||||
|
||||
export function isJSObject(obj: unknown) {
|
||||
return Object.prototype.toString.call(obj) === "[object Object]";
|
||||
}
|
||||
@@ -13,6 +15,91 @@ export function convertId(id: string): string {
|
||||
return `GENERATE_ID::${id}`;
|
||||
}
|
||||
|
||||
export function importHttpBodyAndHeaders(obj: any) {
|
||||
const { headers } = importHeaders(obj);
|
||||
const { body, bodyType } = importHttpBody(obj.body);
|
||||
const mimeType = typeof obj.body?.mimeType === "string" ? obj.body.mimeType.trim() : "";
|
||||
|
||||
if (
|
||||
bodyType != null &&
|
||||
mimeType !== "" &&
|
||||
!headers.some((header: { name: string }) => header.name.toLowerCase() === "content-type")
|
||||
) {
|
||||
headers.push({ enabled: true, name: "Content-Type", value: mimeType });
|
||||
}
|
||||
|
||||
return { body, bodyType, headers };
|
||||
}
|
||||
|
||||
export function importHeaders(obj: any) {
|
||||
const headers = (obj.headers ?? [])
|
||||
.map((header: any) => ({
|
||||
enabled: !header.disabled,
|
||||
name: header.name ?? "",
|
||||
value: header.value ?? "",
|
||||
}))
|
||||
.filter(({ name, value }: any) => name !== "" || value !== "");
|
||||
return { headers } as const;
|
||||
}
|
||||
|
||||
function importHttpBody(rawBody: any) {
|
||||
const mimeType = typeof rawBody?.mimeType === "string" ? rawBody.mimeType.trim() : "";
|
||||
const normalizedMimeType = mimeType.split(";", 1)[0]?.toLowerCase() ?? "";
|
||||
|
||||
if (normalizedMimeType === "application/octet-stream") {
|
||||
return { bodyType: "binary", body: { filePath: rawBody.fileName ?? "" } };
|
||||
}
|
||||
|
||||
if (normalizedMimeType === "application/x-www-form-urlencoded") {
|
||||
return {
|
||||
bodyType: "application/x-www-form-urlencoded",
|
||||
body: {
|
||||
form: (rawBody.params ?? []).map((parameter: any) => ({
|
||||
enabled: !parameter.disabled,
|
||||
name: parameter.name ?? "",
|
||||
value: parameter.value ?? "",
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (normalizedMimeType === "multipart/form-data") {
|
||||
return {
|
||||
bodyType: "multipart/form-data",
|
||||
body: {
|
||||
form: (rawBody.params ?? []).map((parameter: any) => ({
|
||||
enabled: !parameter.disabled,
|
||||
name: parameter.name ?? "",
|
||||
value: parameter.value ?? "",
|
||||
file: parameter.fileName ?? null,
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (normalizedMimeType === "application/graphql") {
|
||||
return { bodyType: "graphql", body: { text: rawBody.text ?? "" } };
|
||||
}
|
||||
|
||||
if (normalizedMimeType === "application/json" || normalizedMimeType.endsWith("+json")) {
|
||||
return { bodyType: "application/json", body: { text: rawBody.text ?? "" } };
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedMimeType === "text/xml" ||
|
||||
normalizedMimeType === "application/xml" ||
|
||||
normalizedMimeType.endsWith("+xml")
|
||||
) {
|
||||
return { bodyType: "text/xml", body: { text: rawBody.text ?? "" } };
|
||||
}
|
||||
|
||||
if (typeof rawBody?.text === "string") {
|
||||
return { bodyType: "other", body: { text: rawBody.text } };
|
||||
}
|
||||
|
||||
return { bodyType: null, body: {} };
|
||||
}
|
||||
|
||||
export function deleteUndefinedAttrs<T>(obj: T): T {
|
||||
if (Array.isArray(obj) && obj != null) {
|
||||
return obj.map(deleteUndefinedAttrs) as T;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/* oxlint-disable no-explicit-any */
|
||||
import type { PartialImportResources } from "@yaakapp/api";
|
||||
import { convertId, convertTemplateSyntax, isJSObject } from "./common";
|
||||
import { convertId, convertTemplateSyntax, importHttpBodyAndHeaders, isJSObject } from "./common";
|
||||
|
||||
export function convertInsomniaV4(parsed: any) {
|
||||
if (!Array.isArray(parsed.resources)) return null;
|
||||
@@ -64,38 +64,6 @@ export function convertInsomniaV4(parsed: any) {
|
||||
}
|
||||
|
||||
function importHttpRequest(r: any, workspaceId: string): PartialImportResources["httpRequests"][0] {
|
||||
let bodyType: string | null = null;
|
||||
let body = {};
|
||||
if (r.body.mimeType === "application/octet-stream") {
|
||||
bodyType = "binary";
|
||||
body = { filePath: r.body.fileName ?? "" };
|
||||
} else if (r.body?.mimeType === "application/x-www-form-urlencoded") {
|
||||
bodyType = "application/x-www-form-urlencoded";
|
||||
body = {
|
||||
form: (r.body.params ?? []).map((p: any) => ({
|
||||
enabled: !p.disabled,
|
||||
name: p.name ?? "",
|
||||
value: p.value ?? "",
|
||||
})),
|
||||
};
|
||||
} else if (r.body?.mimeType === "multipart/form-data") {
|
||||
bodyType = "multipart/form-data";
|
||||
body = {
|
||||
form: (r.body.params ?? []).map((p: any) => ({
|
||||
enabled: !p.disabled,
|
||||
name: p.name ?? "",
|
||||
value: p.value ?? "",
|
||||
file: p.fileName ?? null,
|
||||
})),
|
||||
};
|
||||
} else if (r.body?.mimeType === "application/graphql") {
|
||||
bodyType = "graphql";
|
||||
body = { text: r.body.text ?? "" };
|
||||
} else if (r.body?.mimeType === "application/json") {
|
||||
bodyType = "application/json";
|
||||
body = { text: r.body.text ?? "" };
|
||||
}
|
||||
|
||||
let authenticationType: string | null = null;
|
||||
let authentication = {};
|
||||
if (r.authentication.type === "bearer") {
|
||||
@@ -127,18 +95,10 @@ function importHttpRequest(r: any, workspaceId: string): PartialImportResources[
|
||||
name: p.name ?? "",
|
||||
value: p.value ?? "",
|
||||
})),
|
||||
body,
|
||||
bodyType,
|
||||
...importHttpBodyAndHeaders(r),
|
||||
authentication,
|
||||
authenticationType,
|
||||
method: r.method,
|
||||
headers: (r.headers ?? [])
|
||||
.map((h: any) => ({
|
||||
enabled: !h.disabled,
|
||||
name: h.name ?? "",
|
||||
value: h.value ?? "",
|
||||
}))
|
||||
.filter(({ name, value }: any) => name !== "" || value !== ""),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
/* oxlint-disable no-explicit-any */
|
||||
import type { PartialImportResources } from "@yaakapp/api";
|
||||
import { convertId, convertTemplateSyntax, isJSObject } from "./common";
|
||||
import {
|
||||
convertId,
|
||||
convertTemplateSyntax,
|
||||
importHeaders,
|
||||
importHttpBodyAndHeaders,
|
||||
isJSObject,
|
||||
} from "./common";
|
||||
|
||||
export function convertInsomniaV5(parsed: any) {
|
||||
// Assert parsed is object
|
||||
@@ -82,38 +88,6 @@ function importHttpRequest(
|
||||
const updated = r.meta?.modified ?? r.updated;
|
||||
const sortKey = r.meta?.sortKey ?? r.sortKey;
|
||||
|
||||
let bodyType: string | null = null;
|
||||
let body = {};
|
||||
if (r.body?.mimeType === "application/octet-stream") {
|
||||
bodyType = "binary";
|
||||
body = { filePath: r.body.fileName ?? "" };
|
||||
} else if (r.body?.mimeType === "application/x-www-form-urlencoded") {
|
||||
bodyType = "application/x-www-form-urlencoded";
|
||||
body = {
|
||||
form: (r.body.params ?? []).map((p: any) => ({
|
||||
enabled: !p.disabled,
|
||||
name: p.name ?? "",
|
||||
value: p.value ?? "",
|
||||
})),
|
||||
};
|
||||
} else if (r.body?.mimeType === "multipart/form-data") {
|
||||
bodyType = "multipart/form-data";
|
||||
body = {
|
||||
form: (r.body.params ?? []).map((p: any) => ({
|
||||
enabled: !p.disabled,
|
||||
name: p.name ?? "",
|
||||
value: p.value ?? "",
|
||||
file: p.fileName ?? null,
|
||||
})),
|
||||
};
|
||||
} else if (r.body?.mimeType === "application/graphql") {
|
||||
bodyType = "graphql";
|
||||
body = { text: r.body.text ?? "" };
|
||||
} else if (r.body?.mimeType === "application/json") {
|
||||
bodyType = "application/json";
|
||||
body = { text: r.body.text ?? "" };
|
||||
}
|
||||
|
||||
return {
|
||||
id: convertId(id),
|
||||
workspaceId: convertId(workspaceId),
|
||||
@@ -130,10 +104,8 @@ function importHttpRequest(
|
||||
name: p.name ?? "",
|
||||
value: p.value ?? "",
|
||||
})),
|
||||
body,
|
||||
bodyType,
|
||||
...importHttpBodyAndHeaders(r),
|
||||
method: r.method,
|
||||
...importHeaders(r),
|
||||
...importAuthentication(r),
|
||||
};
|
||||
}
|
||||
@@ -203,17 +175,6 @@ function importWebsocketRequest(
|
||||
};
|
||||
}
|
||||
|
||||
function importHeaders(obj: any) {
|
||||
const headers = (obj.headers ?? [])
|
||||
.map((h: any) => ({
|
||||
enabled: !h.disabled,
|
||||
name: h.name ?? "",
|
||||
value: h.value ?? "",
|
||||
}))
|
||||
.filter(({ name, value }: any) => name !== "" || value !== "");
|
||||
return { headers } as const;
|
||||
}
|
||||
|
||||
function importAuthentication(obj: any) {
|
||||
let authenticationType: string | null = null;
|
||||
let authentication = {};
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { importHttpBodyAndHeaders } from "../src/common";
|
||||
|
||||
describe("importHttpBodyAndHeaders", () => {
|
||||
test("imports XML text using the native XML body type", () => {
|
||||
const result = importHttpBodyAndHeaders({
|
||||
body: {
|
||||
mimeType: "application/soap+xml; charset=utf-8",
|
||||
text: "<soap:Envelope />",
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
bodyType: "text/xml",
|
||||
body: { text: "<soap:Envelope />" },
|
||||
headers: [
|
||||
{
|
||||
enabled: true,
|
||||
name: "Content-Type",
|
||||
value: "application/soap+xml; charset=utf-8",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("imports vendor JSON using the native JSON body type", () => {
|
||||
const result = importHttpBodyAndHeaders({
|
||||
body: {
|
||||
mimeType: "application/problem+json",
|
||||
text: '{"message":"Nope"}',
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.bodyType).toBe("application/json");
|
||||
expect(result.body).toEqual({ text: '{"message":"Nope"}' });
|
||||
});
|
||||
|
||||
test("imports unknown text using the other body type", () => {
|
||||
const result = importHttpBodyAndHeaders({
|
||||
body: {
|
||||
mimeType: "application/yaml",
|
||||
text: "message: hello",
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
bodyType: "other",
|
||||
body: { text: "message: hello" },
|
||||
headers: [
|
||||
{
|
||||
enabled: true,
|
||||
name: "Content-Type",
|
||||
value: "application/yaml",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves an explicit content type instead of adding a duplicate", () => {
|
||||
const result = importHttpBodyAndHeaders({
|
||||
body: {
|
||||
mimeType: "application/yaml",
|
||||
text: "message: hello",
|
||||
},
|
||||
headers: [
|
||||
{
|
||||
name: "content-type",
|
||||
value: "application/x-yaml",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.headers).toEqual([
|
||||
{
|
||||
enabled: true,
|
||||
name: "content-type",
|
||||
value: "application/x-yaml",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("imports text without inventing a content type", () => {
|
||||
const result = importHttpBodyAndHeaders({ body: { text: "hello" } });
|
||||
|
||||
expect(result).toEqual({
|
||||
bodyType: "other",
|
||||
body: { text: "hello" },
|
||||
headers: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -42,12 +42,27 @@ const expressionArg: TemplateFunctionArg = {
|
||||
const formatArg: TemplateFunctionArg = {
|
||||
name: "format",
|
||||
label: "Format String",
|
||||
description: "Format string to describe the output (eg. 'yyyy-MM-dd at HH:mm:ss')",
|
||||
description:
|
||||
"date-fns format string to describe the output (eg. \"yyyy-MM-dd 'at' HH:mm:ss\"). " +
|
||||
"Wrap literal text in single quotes to escape it",
|
||||
optional: true,
|
||||
placeholder: "yyyy-MM-dd HH:mm:ss",
|
||||
type: "text",
|
||||
};
|
||||
|
||||
const formatDocsBanner: TemplateFunctionArg = {
|
||||
type: "banner",
|
||||
color: "info",
|
||||
inputs: [
|
||||
{
|
||||
type: "markdown",
|
||||
content:
|
||||
"Uses [date-fns format tokens](https://date-fns.org/docs/format), " +
|
||||
"not dayjs or Moment. Wrap literal text in single quotes to escape it.",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const plugin: PluginDefinition = {
|
||||
templateFunctions: [
|
||||
{
|
||||
@@ -79,8 +94,8 @@ export const plugin: PluginDefinition = {
|
||||
},
|
||||
{
|
||||
name: "timestamp.format",
|
||||
description: "Format a date using a dayjs-compatible format string",
|
||||
args: [dateArg, formatArg],
|
||||
description: "Format a date using a date-fns format string",
|
||||
args: [formatDocsBanner, dateArg, formatArg],
|
||||
previewArgs: [formatArg.name],
|
||||
onRender: async (_ctx, args) => formatDatetime(args.values),
|
||||
},
|
||||
|
||||
@@ -39,6 +39,7 @@ const appConfigs = {
|
||||
defaultPort: "1420",
|
||||
tauriConfig: "tauri.conf.json",
|
||||
tauriDevConfig: "tauri.development.conf.json",
|
||||
tauriWorktreeConfig: "tauri.worktree.conf.json",
|
||||
},
|
||||
proxy: {
|
||||
appDir: "crates-tauri/yaak-app-proxy",
|
||||
@@ -47,6 +48,7 @@ const appConfigs = {
|
||||
defaultPort: "2420",
|
||||
tauriConfig: "tauri.conf.json",
|
||||
tauriDevConfig: "tauri.development.conf.json",
|
||||
tauriWorktreeConfig: "tauri.worktree.conf.json",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -86,6 +88,14 @@ for (let i = 0; i < additionalArgs.length; i++) {
|
||||
normalizedAdditionalArgs.push(arg);
|
||||
}
|
||||
|
||||
// Tauri only auto-merges platform-specific config names, so the per-worktree config
|
||||
// written by the post-checkout hook has to be passed explicitly. It's gitignored, so
|
||||
// it's normally absent in the main checkout.
|
||||
const worktreeConfigArgs = [];
|
||||
if (fs.existsSync(path.join(rootDir, appConfig.appDir, appConfig.tauriWorktreeConfig))) {
|
||||
worktreeConfigArgs.push("--config", appConfig.tauriWorktreeConfig);
|
||||
}
|
||||
|
||||
const args = [
|
||||
"dev",
|
||||
"--no-watch",
|
||||
@@ -93,6 +103,7 @@ const args = [
|
||||
appConfig.tauriConfig,
|
||||
"--config",
|
||||
appConfig.tauriDevConfig,
|
||||
...worktreeConfigArgs,
|
||||
"--config",
|
||||
config,
|
||||
...normalizedAdditionalArgs,
|
||||
|
||||
+2
-1
@@ -14,6 +14,7 @@ export default defineConfig({
|
||||
},
|
||||
},
|
||||
test: {
|
||||
exclude: ["**/node_modules/**", "**/flatpak/**"],
|
||||
// Nested git worktrees live under .claude, and their tests are not this checkout's
|
||||
exclude: ["**/node_modules/**", "**/flatpak/**", "**/.claude/**"],
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user