Add Markdown import and code block copy to vault notes.

Support bulk .md/.txt import into the current notebook folder and add hover copy buttons on note code blocks in edit and preview modes.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
bincxzandCursor committed 2026-06-23 09:51:32 +08:00
1 parent 6304608114
commit a493fbfea8
12 files changed
+407 -33

No files matched your search

@@ -273,3 +273,34 @@ test("note code block frame is borderless and language picker is compact", () =>
/\.netcatty-mdx-editor--preview\s+\[class\*="_codeMirrorToolbar_"\]\s*\{[^}]*display:\s*none\s*!important;/s,
);
});
test("getCodeMirrorBlockText reads rendered code block lines", () => {
const source = readFileSync(new URL("./InlineMarkdownEditor.tsx", import.meta.url), "utf8");
assert.match(source, /export const getCodeMirrorBlockText/);
assert.match(source, /\.cm-content \.cm-line/);
assert.match(source, /\.join\("\\n"\)/);
});
test("annotateNoteCodeBlockCopyButtons adds a copy action to code blocks", () => {
const source = readFileSync(new URL("./InlineMarkdownEditor.tsx", import.meta.url), "utf8");
assert.match(source, /export const annotateNoteCodeBlockCopyButtons/);
assert.match(source, /data-note-code-copy/);
assert.match(source, /getCodeMirrorBlockText\(wrapper\)/);
assert.match(source, /onCopy\(text\)/);
});
test("note code blocks expose a hover copy action in edit and preview modes", () => {
const source = readFileSync(new URL("./InlineMarkdownEditor.tsx", import.meta.url), "utf8");
const styles = readFileSync(new URL("../../index.css", import.meta.url), "utf8");
assert.match(source, /annotateNoteCodeBlockCopyButtons/);
assert.match(source, /notes\.codeBlock\.copied/);
assert.match(source, /copyToClipboard/);
assert.match(styles, /\.netcatty-note-code-copy/);
assert.match(
styles,
/\.netcatty-mdx-editor\s+\[class\*="_codeMirrorWrapper_"\]:hover\s+\.netcatty-note-code-copy/s,
);
});
+77
View File
@@ -34,8 +34,10 @@ import {
getNearestEditorFromDOMNode,
} from "lexical";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useI18n } from "../../application/i18n/I18nProvider";
import { resolveRenderedMarkdownLinkHref } from "../../domain/notes";
import { buildSshNoteLinkOpenHost } from "../../domain/sshDeepLink";
import { copyToClipboard } from "../keychain/utils";
import { cn } from "../../lib/utils";
import type { Host } from "../../types";
@@ -322,6 +324,64 @@ export const getHostPickerTriggerRange = (textBeforeCursor: string): {
};
};
export const getCodeMirrorBlockText = (wrapper: Element): string => {
const lines = wrapper.querySelectorAll(".cm-content .cm-line");
if (lines.length > 0) {
return Array.from(lines)
.map((line) => line.textContent?.replace(/\u00a0/g, " ") ?? "")
.join("\n");
}
const content = wrapper.querySelector(".cm-content");
return content?.textContent?.replace(/\u00a0/g, " ") ?? "";
};
export const annotateNoteCodeBlockCopyButtons = (
container: HTMLElement,
{
copyLabel,
copiedLabel,
onCopy,
}: {
copyLabel: string;
copiedLabel: string;
onCopy: (text: string) => Promise<boolean>;
},
): void => {
container.querySelectorAll('[class*="_codeMirrorWrapper_"]').forEach((wrapper) => {
if (!(wrapper instanceof HTMLElement)) return;
if (wrapper.querySelector("[data-note-code-copy]")) return;
const button = document.createElement("button");
button.type = "button";
button.dataset.noteCodeCopy = "true";
button.className = "netcatty-note-code-copy";
button.title = copyLabel;
button.setAttribute("aria-label", copyLabel);
button.textContent = copyLabel;
button.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
void (async () => {
const text = getCodeMirrorBlockText(wrapper);
const ok = await onCopy(text);
if (!ok) return;
button.dataset.copied = "true";
button.textContent = copiedLabel;
button.title = copiedLabel;
window.setTimeout(() => {
delete button.dataset.copied;
button.textContent = copyLabel;
button.title = copyLabel;
}, 1500);
})();
});
wrapper.appendChild(button);
});
};
const deleteLexicalTextRange = (range: Range, onUpdate: () => void): boolean => {
const rangeContainer = range.startContainer.nodeType === Node.TEXT_NODE
? range.startContainer.parentElement
@@ -358,6 +418,7 @@ export function InlineMarkdownEditor({
onOpenExternalLink,
previewEmptyLabel,
}: InlineMarkdownEditorProps) {
const { t } = useI18n();
const editorRef = useRef<MDXEditorMethods>(null);
const latestMarkdownRef = useRef(value);
const containerRef = useRef<HTMLDivElement>(null);
@@ -522,6 +583,22 @@ export function InlineMarkdownEditor({
return () => window.cancelAnimationFrame(frame);
}, [annotateHostLinks, value]);
const annotateCodeBlockCopyButtons = useCallback(() => {
const container = containerRef.current;
if (!container) return;
annotateNoteCodeBlockCopyButtons(container, {
copyLabel: t("action.copy"),
copiedLabel: t("notes.codeBlock.copied"),
onCopy: copyToClipboard,
});
}, [t]);
useEffect(() => {
const frame = window.requestAnimationFrame(annotateCodeBlockCopyButtons);
return () => window.cancelAnimationFrame(frame);
}, [annotateCodeBlockCopyButtons, editorMode, value]);
const commitMarkdown = useCallback((markdown: string) => {
if (markdown === latestMarkdownRef.current) return;
latestMarkdownRef.current = markdown;
+10
View File
@@ -212,9 +212,19 @@ test("NotesManager renders empty state", () => {
assert.match(markup, /No notes yet/);
assert.match(markup, /New Note/);
assert.match(markup, /Import Markdown/);
assert.doesNotMatch(markup, /data-notes-drop-zone="root"/);
});
test("NotesManager exposes markdown import controls", () => {
const source = readFileSync(new URL("./NotesManager.tsx", import.meta.url), "utf8");
assert.match(source, /notes\.action\.importMarkdown/);
assert.match(source, /importMarkdownFilesToVaultNotes/);
assert.match(source, /accept="\.md,\.markdown,\.txt,text\/markdown,text\/plain"/);
assert.match(source, /multiple/);
});
test("NotesManager sidebar mode renders list without editor by default", () => {
const markup = renderNotes([note()], "sidebar");
+84 -4
View File
@@ -11,6 +11,7 @@ import {
PencilLine,
Plus,
Search,
Upload,
X,
} from "lucide-react";
import React, { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -25,6 +26,7 @@ import {
isNoteGroupInside,
joinNoteGroupPath,
matchesVaultNoteSearch,
importMarkdownFilesToVaultNotes,
normalizeNoteGroups,
normalizeVaultNotes,
remapExpandedNoteGroupPaths,
@@ -37,6 +39,7 @@ import {
STORAGE_KEY_VAULT_NOTES_TREE_WIDTH,
} from "../../infrastructure/config/storageKeys";
import { cn } from "../../lib/utils";
import { readTextFile } from "../../lib/readTextFile";
import type { Host, VaultNote } from "../../types";
import { Button } from "../ui/button";
import { LazyLoadBoundary } from "../ui/lazy-load-boundary";
@@ -50,6 +53,7 @@ import { Dropdown, DropdownContent, DropdownTrigger } from "../ui/dropdown";
import { Input } from "../ui/input";
import { ScrollArea } from "../ui/scroll-area";
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
import { toast } from "../ui/toast";
import {
VaultTreeGroupRow,
VaultTreeInlineRenameInput,
@@ -353,6 +357,7 @@ export const NotesManager: React.FC<NotesManagerProps> = ({
{ min: NOTES_TREE_MIN_WIDTH, max: NOTES_TREE_MAX_WIDTH },
);
const searchInputRef = useRef<HTMLInputElement>(null);
const importFileInputRef = useRef<HTMLInputElement>(null);
const groups = useMemo(() => normalizeNoteGroups(noteGroups), [noteGroups]);
const groupOrderByPath = useMemo(
@@ -497,6 +502,51 @@ export const NotesManager: React.FC<NotesManagerProps> = ({
addNoteToGroup(getNoteActionTargetGroup(selectedNote, selectedGroup));
};
const handleImportMarkdownFiles = useCallback(async (fileList: FileList | null) => {
if (!fileList || fileList.length === 0) return;
const files = Array.from(fileList);
const targetGroup = getNoteActionTargetGroup(selectedNote, selectedGroup);
try {
const result = await importMarkdownFilesToVaultNotes(
files,
sortedNotes,
targetGroup,
readTextFile,
);
if (result.importedCount === 0) {
toast.error(t("notes.import.toast.noNotes"));
return;
}
onUpdateNotes(result.notes);
if (targetGroup) expandPath(targetGroup);
const lastImported = result.notes[result.notes.length - 1];
const nextSelection = getNoteSelectionState(lastImported, isSidebarMode);
setSelectedNoteId(nextSelection.selectedNoteId);
setSelectedGroup(nextSelection.selectedGroup);
setOverlayNoteId(nextSelection.overlayNoteId);
toast.success(t("notes.import.toast.success", { count: result.importedCount }));
} catch {
toast.error(t("notes.import.toast.failed"));
} finally {
if (importFileInputRef.current) {
importFileInputRef.current.value = "";
}
}
}, [
isSidebarMode,
onUpdateNotes,
selectedGroup,
selectedNote,
sortedNotes,
t,
]);
const duplicateNoteById = (noteId: string) => {
const source = sortedNotes.find((note) => note.id === noteId);
if (!source) return;
@@ -1061,6 +1111,16 @@ export const NotesManager: React.FC<NotesManagerProps> = ({
return (
<div className="relative flex h-full min-h-0 flex-col overflow-hidden">
<input
ref={importFileInputRef}
type="file"
accept=".md,.markdown,.txt,text/markdown,text/plain"
multiple
className="hidden"
onChange={(event) => {
void handleImportMarkdownFiles(event.target.files);
}}
/>
<div className="flex min-h-0 flex-1">
{shouldShowNotesTree && (
<aside
@@ -1114,6 +1174,20 @@ export const NotesManager: React.FC<NotesManagerProps> = ({
<TooltipContent side="bottom">{t("notes.action.newGroup")}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className={toolbarIconButtonClass}
onClick={() => importFileInputRef.current?.click()}
>
<Upload size={14} className="text-muted-foreground" />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">{t("notes.action.importMarkdown")}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
@@ -1276,10 +1350,16 @@ export const NotesManager: React.FC<NotesManagerProps> = ({
</div>
<h3 className="mb-2 text-lg font-semibold text-foreground">{t("notes.empty.title")}</h3>
<p className="mb-4 text-sm">{t("notes.empty.desc")}</p>
<Button onClick={addNote}>
<Plus size={14} className="mr-2" />
{t("notes.action.newNote")}
</Button>
<div className="flex flex-wrap items-center justify-center gap-2">
<Button onClick={addNote}>
<Plus size={14} className="mr-2" />
{t("notes.action.newNote")}
</Button>
<Button variant="outline" onClick={() => importFileInputRef.current?.click()}>
<Upload size={14} className="mr-2" />
{t("notes.action.importMarkdown")}
</Button>
</div>
</div>
</div>
)}