Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions app/components/CopySelectedNode.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useHotkeys } from "react-hotkeys-hook";
import { useSelectedInfo } from "../hooks/useSelectedInfo";
import { useJsonColumnViewState } from "../hooks/useJsonColumnView";
import { formatPath } from "../utilities/pathFormatter";

export function CopySelectedNodeShortcut() {
const selectedInfo = useSelectedInfo();
Expand All @@ -18,3 +20,21 @@ export function CopySelectedNodeShortcut() {

return <></>;
}

export function CopySelectedNodePathShortcut() {
const { selectedNodeId } = useJsonColumnViewState();

useHotkeys(
'shift+p,shift+P',
(e) => {
if (!selectedNodeId) {
return;
}
e.preventDefault();
navigator.clipboard.writeText(formatPath(selectedNodeId, "jsonpath"));
},
[selectedNodeId]
);

return <></>;
}
3 changes: 2 additions & 1 deletion app/components/JsonColumnView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
} from "../hooks/useJsonColumnView";
import { useHotkeys } from "react-hotkeys-hook";
import { Columns } from "./Columns";
import { CopySelectedNodeShortcut } from "./CopySelectedNode";
import { CopySelectedNodeShortcut, CopySelectedNodePathShortcut } from "./CopySelectedNode";

export function JsonColumnView() {
const { getColumnViewProps, columns } = useJsonColumnViewState();
Expand Down Expand Up @@ -70,5 +70,6 @@ function KeyboardShortcuts() {

return <>
<CopySelectedNodeShortcut />
<CopySelectedNodePathShortcut />
</>;
}
3 changes: 2 additions & 1 deletion app/components/JsonTreeView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
import { useJsonDoc } from "~/hooks/useJsonDoc";
import { JsonTreeViewNode, useJsonTreeViewContext } from "~/hooks/useJsonTree";
import { VirtualNode } from "~/hooks/useVirtualTree";
import { CopySelectedNodeShortcut } from "./CopySelectedNode";
import { CopySelectedNodeShortcut, CopySelectedNodePathShortcut } from "./CopySelectedNode";
import { Body } from "./Primitives/Body";
import { Mono } from "./Primitives/Mono";

Expand Down Expand Up @@ -84,6 +84,7 @@ export function JsonTreeView() {
return (
<>
<CopySelectedNodeShortcut />
<CopySelectedNodePathShortcut />
<div
className="text-white w-full"
ref={parentRef}
Expand Down
58 changes: 57 additions & 1 deletion app/components/PathBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
ArrowRightIcon,
PencilAltIcon,
CheckIcon,
ClipboardCopyIcon,
} from "@heroicons/react/outline";
import { ColumnViewNode } from "~/useColumnView";
import { Body } from "./Primitives/Body";
Expand All @@ -12,9 +13,16 @@ import {
useJsonColumnViewState,
} from "../hooks/useJsonColumnView";
import { useHotkeys } from "react-hotkeys-hook";
import { memo, useEffect, useRef, useState } from "react";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { useJson } from '~/hooks/useJson';
import { JSONHeroPath } from '@jsonhero/path';
import { formatPath, PathFormat } from "../utilities/pathFormatter";
import {
Popover,
PopoverArrow,
PopoverContent,
PopoverTrigger,
} from "./UI/Popover";

export function PathBar() {
const [isEditable, setIsEditable] = useState(false);
Expand Down Expand Up @@ -125,6 +133,7 @@ export function PathBarLink({
/>
);
})}
<CopyPathButton selectedPath={selectedNodes.at(-1)?.id} />
<button
className="flex ml-auto justify-center items-center w-[26px] h-[26px] hover:bg-slate-300 dark:text-slate-400 dark:hover:bg-white dark:hover:bg-opacity-[10%]"
onClick={enableEdit}>
Expand All @@ -134,6 +143,53 @@ export function PathBarLink({
);
}

export function CopyPathButton({ selectedPath }: { selectedPath?: string }) {
const [copied, setCopied] = useState<PathFormat | null>(null);

const copyAs = useCallback(
(format: PathFormat) => {
if (!selectedPath) {
return;
}
navigator.clipboard.writeText(formatPath(selectedPath, format));
setCopied(format);
setTimeout(() => setCopied(null), 1500);
},
[selectedPath]
);

if (!selectedPath) {
return null;
}

return (
<Popover>
<PopoverTrigger>
<button
title="Copy path"
className="flex justify-center items-center w-[26px] h-[26px] hover:bg-slate-300 dark:text-slate-400 dark:hover:bg-white dark:hover:bg-opacity-[10%]">
<ClipboardCopyIcon className='h-5' />
</button>
</PopoverTrigger>
<PopoverContent side="bottom" sideOffset={8} align="end">
<div className="flex flex-col bg-slate-700 rounded-sm overflow-hidden shadow-lg">
<button
className="flex items-center px-3 py-2 text-left text-sm text-slate-200 hover:bg-slate-600 transition whitespace-nowrap"
onClick={() => copyAs("jsonpath")}>
{copied === "jsonpath" ? "Copied!" : "Copy as JSONPath"}
</button>
<button
className="flex items-center px-3 py-2 text-left text-sm text-slate-200 hover:bg-slate-600 transition whitespace-nowrap"
onClick={() => copyAs("js")}>
{copied === "js" ? "Copied!" : "Copy as JavaScript"}
</button>
</div>
<PopoverArrow className="fill-current text-slate-700" />
</PopoverContent>
</Popover>
);
}

export function PathHistoryControls() {
const { canGoBack, canGoForward } = useJsonColumnViewState();
const { goBack, goForward } = useJsonColumnViewAPI();
Expand Down
56 changes: 56 additions & 0 deletions app/utilities/pathFormatter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { JSONHeroPath, PathComponent } from "@jsonhero/path";

export type PathFormat = "jsonpath" | "js";

// The public PathComponent interface doesn't expose `keyName`, but every
// concrete component (SimpleKeyPathComponent, StartPathComponent, ...) does.
function keyNameOf(component: PathComponent): string {
return (component as PathComponent & { keyName: string }).keyName;
}

const SAFE_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;

function quoteKey(key: string): string {
const escaped = key.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
return `["${escaped}"]`;
}

/**
* Formats a JSONHeroPath string (e.g. `$.data.0.user-name`) as either a
* JSONPath expression or a JavaScript accessor.
*
* - jsonpath: `$.data[0]["user-name"]` (root -> `$`)
* - js: `data[0]["user-name"]` (root -> ``)
*/
export function formatPath(path: string, format: PathFormat): string {
const heroPath = new JSONHeroPath(path);

// Drop the leading StartPathComponent (`$`).
const components = heroPath.components.slice(1);

let result = format === "jsonpath" ? "$" : "";

components.forEach((component, index) => {
const key = keyNameOf(component);

if (component.isArray) {
result += `[${key}]`;
return;
}

if (!SAFE_IDENTIFIER.test(key)) {
result += quoteKey(key);
return;
}

// A safe identifier: use dot notation, except for the very first
// component of a JS accessor, which has no leading dot.
if (format === "js" && index === 0) {
result += key;
} else {
result += `.${key}`;
}
});

return result;
}
56 changes: 56 additions & 0 deletions tests/pathFormatter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { formatPath } from "../app/utilities/pathFormatter";

describe("formatPath", () => {
describe("jsonpath", () => {
it("returns $ for the root path", () => {
expect(formatPath("$", "jsonpath")).toBe("$");
});

it("formats a single simple key with a dot", () => {
expect(formatPath("$.name", "jsonpath")).toBe("$.name");
});

it("formats array indices with bracket notation", () => {
expect(formatPath("$.data.0.name", "jsonpath")).toBe("$.data[0].name");
});

it("brackets and quotes keys that are not safe identifiers", () => {
expect(formatPath("$.user-name", "jsonpath")).toBe('$["user-name"]');
});

it("handles consecutive array indices", () => {
expect(formatPath("$.a.b.0.1", "jsonpath")).toBe("$.a.b[0][1]");
});

it("escapes embedded quotes and backslashes in bracketed keys", () => {
// a key literally containing a double-quote
expect(formatPath('$.a."b', "jsonpath")).toBe('$.a["\\"b"]');
});
});

describe("js accessor", () => {
it("returns an empty string for the root path", () => {
expect(formatPath("$", "js")).toBe("");
});

it("drops the leading $ and uses no leading dot for the first key", () => {
expect(formatPath("$.name", "js")).toBe("name");
});

it("formats nested keys and array indices", () => {
expect(formatPath("$.data.0.name", "js")).toBe("data[0].name");
});

it("uses bracket notation for unsafe keys, even when first", () => {
expect(formatPath("$.user-name", "js")).toBe('["user-name"]');
});

it("uses bracket notation for an unsafe key after a simple key", () => {
expect(formatPath("$.data.user-name", "js")).toBe('data["user-name"]');
});

it("treats a leading array index as bracket notation", () => {
expect(formatPath("$.0.name", "js")).toBe("[0].name");
});
});
});