Skip to content
Merged
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 packages/app/src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6249,6 +6249,26 @@ describe("Markra workspace", () => {
);
});

it("copies a standalone file tab path relative to the folder the file tree shows", async () => {
mockedOpenNativeMarkdownPath.mockResolvedValue({
kind: "file",
file: {
content: "# Alpha\n\nStandalone.",
name: "alpha.md",
path: "/synthetic/docs/alpha.md"
}
});

renderApp();

fireEvent.keyDown(window, { key: "o", metaKey: true });
await expectVisibleMarkdownText("Alpha");

fireEvent.contextMenu(screen.getByRole("tab", { name: /alpha\.md/ }));

expect(screen.getByRole("menuitem", { name: "Copy relative path" })).toBeInTheDocument();
});

it("opens another file from an untouched blank document without asking to discard changes", async () => {
mockedOpenNativeMarkdownPath
.mockResolvedValueOnce({
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4552,6 +4552,7 @@ function WorkspaceApp() {
onRevealTabInFileTree={handleRevealPathInFileTree}
onRenameTab={handleRenameTitlebarTab}
onSelectTab={handleSelectTitlebarTab}
rootPath={fileTree.workspacePath}
/>
) : null;
const appTitlebarActions = useMemo(
Expand Down
63 changes: 63 additions & 0 deletions packages/app/src/components/MarkdownFileTreeDrawer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import { fileTreeRowHeight } from "./file-tree/file-tree-model";
import { getMarkdownOutline } from "@markra/markdown";
import { readNativeClipboardText, showNativeMarkdownFileTreeContextMenu } from "../lib/tauri";
import type { WorkspaceLinkIndex } from "../lib/workspace-links";
import { showAppToast } from "../lib/app-toast";

vi.mock("../lib/app-toast", () => ({ showAppToast: vi.fn() }));

vi.mock("../lib/tauri", () => ({
readNativeClipboardText: vi.fn(),
Expand Down Expand Up @@ -2718,6 +2721,66 @@ describe("MarkdownFileTreeDrawer", () => {
expect(openContainingFolder).toHaveBeenCalledWith("/vault");
});

it("reports a denied clipboard write from file tree context menus", async () => {
const writeText = vi.fn().mockRejectedValue(new DOMException("Denied", "NotAllowedError"));
vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } });

try {
render(
<MarkdownFileTreeDrawer
currentPath="/vault/Untitled.md"
files={markdownFiles}
open
outlineItems={[]}
rootPath="/vault"
rootName="Obsidian Vault"
onOpenFile={() => {}}
onSelectOutlineItem={() => {}}
/>
);

fireEvent.contextMenu(screen.getByRole("button", { name: "Untitled.md" }));
const fileContextHandlers = mockedShowNativeMarkdownFileTreeContextMenu.mock.calls[0]?.[0];
await act(async () => {
await fileContextHandlers?.copyPath?.("Untitled.md");
});

expect(showAppToast).toHaveBeenCalledWith({ message: "Could not copy the path.", status: "error" });
} finally {
vi.unstubAllGlobals();
}
});

it("copies a file path from file tree context menus", async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } });

try {
render(
<MarkdownFileTreeDrawer
currentPath="/vault/Untitled.md"
files={markdownFiles}
open
outlineItems={[]}
rootPath="/vault"
rootName="Obsidian Vault"
onOpenFile={() => {}}
onSelectOutlineItem={() => {}}
/>
);

fireEvent.contextMenu(screen.getByRole("button", { name: "Untitled.md" }));
const fileContextHandlers = mockedShowNativeMarkdownFileTreeContextMenu.mock.calls[0]?.[0];
await act(async () => {
await fileContextHandlers?.copyPath?.("/vault/Untitled.md");
});

expect(writeText).toHaveBeenCalledWith("/vault/Untitled.md");
} finally {
vi.unstubAllGlobals();
}
});

it("shows text editing actions when right-clicking a file name input", async () => {
const createFile = vi.fn();
mockedReadNativeClipboardText.mockResolvedValue("Pasted note");
Expand Down
2 changes: 2 additions & 0 deletions packages/app/src/components/MarkdownFileTreeDrawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ import { markraHighlightRemarkPlugin, type MarkdownOutlineItem } from "@markra/m
import { DocumentLinksPanel } from "./DocumentLinksPanel";
import type { NativeMarkdownFolderFile } from "../lib/tauri";
import { normalizeMovedPath, sameNativePath } from "../lib/path-move";
import { copyPathToClipboard } from "../lib/copy-path";
import { readNativeClipboardText, showNativeMarkdownFileTreeContextMenu } from "../lib/tauri";
import { resolveDesktopPlatform, type DesktopPlatform } from "../lib/platform";
import { anchoredPopoverStyle } from "../lib/anchored-popover";
Expand Down Expand Up @@ -1602,6 +1603,7 @@ export function MarkdownFileTreeDrawer({
name: template.name
}))
: undefined,
copyPath: (path) => copyPathToClipboard(path, language),
createFolder: folderCreationAvailable ? () => startCreatingFolder(createTargetFolderPath) : undefined,
deleteFile: deleteFileTreeTarget,
openContainingFolder: onOpenContainingFolder
Expand Down
77 changes: 77 additions & 0 deletions packages/app/src/components/MarkdownTabsBar.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, vi } from "vitest";
import { MarkdownTabsBar } from "./MarkdownTabsBar";
import { showAppToast } from "../lib/app-toast";

vi.mock("../lib/app-toast", () => ({ showAppToast: vi.fn() }));

describe("MarkdownTabsBar", () => {
afterEach(() => {
Expand Down Expand Up @@ -615,6 +618,80 @@ describe("MarkdownTabsBar", () => {
expect(onCloseTab).toHaveBeenNthCalledWith(2, "tab-d");
});

it("copies the tab file path and its path relative to the open folder", async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } });

try {
render(
<MarkdownTabsBar
activeTabId="tab-a"
items={[{ dirty: false, id: "tab-a", name: "Alpha.md", path: "/synthetic/docs/alpha.md" }]}
onCloseTab={() => {}}
onNewTab={() => {}}
onSelectTab={() => {}}
rootPath="/synthetic"
/>
);

fireEvent.contextMenu(screen.getByRole("tab", { name: /Alpha\.md/ }));
fireEvent.click(screen.getByRole("menuitem", { name: "Copy path" }));
fireEvent.contextMenu(screen.getByRole("tab", { name: /Alpha\.md/ }));
fireEvent.click(screen.getByRole("menuitem", { name: "Copy relative path" }));

await waitFor(() => expect(writeText).toHaveBeenCalledTimes(2));
expect(writeText.mock.calls).toEqual([["/synthetic/docs/alpha.md"], ["docs/alpha.md"]]);
} finally {
vi.unstubAllGlobals();
}
});

it("reports a denied clipboard write from the tab menu", async () => {
const writeText = vi.fn().mockRejectedValue(new DOMException("Denied", "NotAllowedError"));
vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } });

try {
render(
<MarkdownTabsBar
activeTabId="tab-a"
items={[{ dirty: false, id: "tab-a", name: "Alpha.md", path: "/synthetic/docs/alpha.md" }]}
onCloseTab={() => {}}
onNewTab={() => {}}
onSelectTab={() => {}}
rootPath="/synthetic/docs"
/>
);

fireEvent.contextMenu(screen.getByRole("tab", { name: /Alpha\.md/ }));
fireEvent.click(screen.getByRole("menuitem", { name: "Copy relative path" }));

await waitFor(() =>
expect(showAppToast).toHaveBeenCalledWith({ message: "Could not copy the path.", status: "error" })
);
expect(writeText).toHaveBeenCalledWith("alpha.md");
} finally {
vi.unstubAllGlobals();
}
});

it("offers no relative path for a tab outside the open folder", () => {
render(
<MarkdownTabsBar
activeTabId="tab-a"
items={[{ dirty: false, id: "tab-a", name: "Alpha.md", path: "/elsewhere/alpha.md" }]}
onCloseTab={() => {}}
onNewTab={() => {}}
onSelectTab={() => {}}
rootPath="/synthetic"
/>
);

fireEvent.contextMenu(screen.getByRole("tab", { name: /Alpha\.md/ }));

expect(screen.getByRole("menuitem", { name: "Copy path" })).toBeInTheDocument();
expect(screen.queryByRole("menuitem", { name: "Copy relative path" })).not.toBeInTheDocument();
});

it("opens tab actions from right click and closes related tabs", async () => {
const onCloseTab = vi.fn();

Expand Down
50 changes: 48 additions & 2 deletions packages/app/src/components/MarkdownTabsBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ import {
type PointerEvent as ReactPointerEvent,
type WheelEvent as ReactWheelEvent
} from "react";
import { Columns2, FileText, ImageIcon, LocateFixed, Pencil, Plus, X } from "lucide-react";
import { Columns2, Copy, FileText, ImageIcon, LocateFixed, Pencil, Plus, X } from "lucide-react";
import { IconButton, Tooltip } from "@markra/ui";
import { t, type AppLanguage } from "@markra/shared";
import type { MarkdownDocumentTab } from "../hooks/useMarkdownDocument";
import { ContextMenu, type ContextMenuEntry } from "./ContextMenu";
import { copyPathToClipboard } from "../lib/copy-path";
import { isFileSystemPath } from "../runtime/context-menu-items";

export type MarkdownTabsBarDocumentItem = Pick<MarkdownDocumentTab, "deleted" | "dirty" | "id" | "name"> & {
displayKind?: "image" | "markdown";
Expand All @@ -33,6 +35,7 @@ type MarkdownTabsBarProps = {
onNewTab: () => unknown;
onOpenTabToSide?: (tabId: string, primaryTabId?: string) => unknown;
onRevealTabInFileTree?: (path: string) => unknown;
rootPath?: string | null;
onRenameTab?: (tab: MarkdownTabsBarDocumentItem, name: string) => unknown;
onSelectTab: (tabId: string) => unknown;
};
Expand Down Expand Up @@ -67,6 +70,47 @@ export const markdownTabDragDataType = "application/x-markra-document-tab";
const pointerTabDragThresholdPx = 6;
const pointerTabDragPreviewOffsetPx = 12;

function pathRelativeToRoot(path: string, rootPath: string | null | undefined) {
const root = rootPath?.replace(/[\\/]+$/u, "");
if (!root || !path.startsWith(root)) return null;

const separator = path.charAt(root.length);
return separator === "/" || separator === "\\" ? path.slice(root.length + 1) : null;
}

function copyPathEntries(
path: string,
rootPath: string | null | undefined,
language: AppLanguage,
run: (action: () => unknown) => unknown
): ContextMenuEntry[] {
if (!isFileSystemPath(path)) return [];

const copy = (text: string) => run(() => copyPathToClipboard(text, language));
const relativePath = pathRelativeToRoot(path, rootPath);

return [
{
icon: <Copy aria-hidden="true" size={14} />,
id: "markra:tab:copy-path",
kind: "item",
label: t(language, "app.copyPath"),
onSelect: () => copy(path)
},
...(relativePath
? [
{
icon: <Copy aria-hidden="true" size={14} />,
id: "markra:tab:copy-relative-path",
kind: "item" as const,
label: t(language, "app.copyRelativePath"),
onSelect: () => copy(relativePath)
}
]
: [])
];
}

export function MarkdownTabsBar({
activeTabId,
focusedTabId,
Expand All @@ -81,7 +125,8 @@ export function MarkdownTabsBar({
onOpenTabToSide,
onRevealTabInFileTree,
onRenameTab,
onSelectTab
onSelectTab,
rootPath
}: MarkdownTabsBarProps) {
const label = (key: Parameters<typeof t>[1]) => t(language, key);
const [renamingTabId, setRenamingTabId] = useState<string | null>(null);
Expand Down Expand Up @@ -408,6 +453,7 @@ export function MarkdownTabsBar({
}
]
: []),
...(contextMenuTab.path ? copyPathEntries(contextMenuTab.path, rootPath, language, runTabContextMenuAction) : []),
...(onCancelSideBySide && contextMenuTabIsSideBySide
? [
{
Expand Down
10 changes: 10 additions & 0 deletions packages/app/src/hooks/useMarkdownFileTree.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ function FileTreeProbe({
return (
<section>
<p data-testid="root-name">{tree.rootNameForDocument(currentPath)}</p>
<p data-testid="workspace-path">{tree.workspacePath}</p>
<p data-testid="open-state">{tree.open ? "open" : "closed"}</p>
<p data-testid="tree-width">{tree.width}</p>
<p data-testid="tree-resizing">{tree.resizing ? "resizing" : "idle"}</p>
Expand Down Expand Up @@ -490,6 +491,15 @@ describe("useMarkdownFileTree", () => {
expect(firstSignalRef.current?.aborted).toBe(true);
});

it("resolves a standalone file root to the folder the tree shows", () => {
mockedLoadNativeMarkdownFilesForPath.mockResolvedValue([]);
render(<FileTreeProbe />);

fireEvent.click(screen.getByRole("button", { name: "Use file root" }));

expect(screen.getByTestId("workspace-path")).toHaveTextContent(/^\/mock-workspaces\/notes$/u);
});

it("keeps the first selected folder load alive when switching from a file root", async () => {
const fileRootLoad = createDeferredMarkdownFileList();
const folderLoad = createDeferredMarkdownFileList();
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/hooks/useMarkdownFileTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,7 @@ export function useMarkdownFileTree({
refresh,
setRootFromMarkdownFilePath,
sourcePath,
workspacePath: fileTreeWorkspacePath,
openMarkdownFolder,
renameFile,
resize,
Expand Down
7 changes: 7 additions & 0 deletions packages/app/src/lib/copy-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { t, type AppLanguage } from "@markra/shared";
import { showAppToast } from "./app-toast";

export async function copyPathToClipboard(path: string, language: AppLanguage) {
const copied = await navigator.clipboard?.writeText(path).then(() => true, () => false);
if (!copied) showAppToast({ message: t(language, "app.copyPathFailed"), status: "error" });
}
1 change: 1 addition & 0 deletions packages/app/src/lib/tauri/menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type NativeMarkdownFileTreeContextMenuHandlers = {
id: string;
name: string;
}>;
copyPath?: (path: string) => unknown | Promise<unknown>;
createFolder?: () => unknown | Promise<unknown>;
deleteFile?: (file: NativeMarkdownFolderFile) => unknown | Promise<unknown>;
openContainingFolder?: (file?: NativeMarkdownFolderFile) => unknown | Promise<unknown>;
Expand Down
32 changes: 32 additions & 0 deletions packages/app/src/runtime/context-menu-items.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -463,4 +463,36 @@ describe("markdown file tree context menu entries", () => {
expect(menuItemById(entries, "markra:file-tree:open-containing-folder").disabled).toBe(true);
expect(menuItemById(entries, "markra:file-tree:rename").disabled).toBe(true);
});

it("copies the absolute and relative path of a file or folder", () => {
const copyPath = vi.fn();
const file = { name: "guide.md", path: "/mock-project/docs/guide.md", relativePath: "docs/guide.md" };
const folder = { kind: "folder" as const, name: "docs", path: "C:\\mock-project\\docs", relativePath: "docs" };

menuItemById(createMarkdownFileTreeContextMenuEntries({ copyPath }, "en", file), "markra:file-tree:copy-path").onSelect?.();
menuItemById(
createMarkdownFileTreeContextMenuEntries({ copyPath }, "en", file),
"markra:file-tree:copy-relative-path"
).onSelect?.();
menuItemById(createMarkdownFileTreeContextMenuEntries({ copyPath }, "en", folder), "markra:file-tree:copy-path").onSelect?.();

expect(copyPath.mock.calls).toEqual([["/mock-project/docs/guide.md"], ["docs/guide.md"], ["C:\\mock-project\\docs"]]);
});

it("offers only the relative path when the file has no file system path", () => {
const file = { name: "guide.md", path: "web-folder://mock-handle/docs/guide.md", relativePath: "docs/guide.md" };
const ids = createMarkdownFileTreeContextMenuEntries({ copyPath: vi.fn() }, "en", file)
.flatMap((entry) => ("id" in entry ? [entry.id] : []));

expect(ids).toContain("markra:file-tree:copy-relative-path");
expect(ids).not.toContain("markra:file-tree:copy-path");
});

it("disables copying paths for a multi-selection", () => {
const file = { name: "guide.md", path: "/mock-project/docs/guide.md", relativePath: "docs/guide.md" };
const entries = createMarkdownFileTreeContextMenuEntries({ copyPath: vi.fn(), multiSelect: true }, "en", file);

expect(menuItemById(entries, "markra:file-tree:copy-path").disabled).toBe(true);
expect(menuItemById(entries, "markra:file-tree:copy-relative-path").disabled).toBe(true);
});
});
Loading
Loading