Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat(attachments): 统一文件卡片与类型图标

tianma-iff7d17e1047e2
diff --git a/apps/web/src/components/AssetsPane.tsx b/apps/web/src/components/AssetsPane.tsx
index 8f9ef34f..dd33342e 100644
--- a/apps/web/src/components/AssetsPane.tsx
+++ b/apps/web/src/components/AssetsPane.tsx
@@ -11,18 +11,11 @@ import "yet-another-react-lightbox/plugins/thumbnails.css";
import {
Archive,
HardDrive,
- ImageIcon,
- File as FileIcon,
ExternalLink,
ChevronLeft,
Search,
Grid,
List,
- FileText,
- FileSpreadsheet,
- FileArchive,
- Music,
- Video,
X,
Loader2,
} from "lucide-react";
@@ -35,6 +28,7 @@ import type { EdgeEverRepository } from "@/lib/repository";
import { isPdfAttachment, type ResourceListItem } from "@edgeever/shared";
import { PdfViewer } from "@/components/pdf/PdfViewer";
import { PdfThumbnail } from "@/components/pdf/PdfThumbnail";
+import { AttachmentFileIcon } from "@/components/attachments/AttachmentFileIcon";
export const formatBytes = (bytes: number) => {
if (!Number.isFinite(bytes) || bytes <= 0) {
@@ -65,53 +59,6 @@ const DOCUMENT_MIME_TYPES = new Set([
"text/javascript",
]);
-const getFileIcon = (mimeType: string | null, filename: string | null) => {
- const mime = (mimeType || "").toLowerCase();
- const ext = (filename || "").split(".").pop()?.toLowerCase() || "";
-
- if (mime.startsWith("image/")) return <ImageIcon className="h-8 w-8 text-emerald-500" />;
- if (mime.startsWith("audio/")) return <Music className="h-8 w-8 text-sky-500" />;
- if (mime.startsWith("video/")) return <Video className="h-8 w-8 text-rose-500" />;
-
- if (mime === "application/pdf" || ext === "pdf") {
- return <FileText className="h-8 w-8 text-rose-600" />;
- }
-
- if (
- mime.includes("spreadsheet") ||
- mime.includes("excel") ||
- ext === "xls" ||
- ext === "xlsx" ||
- ext === "csv"
- ) {
- return <FileSpreadsheet className="h-8 w-8 text-green-600" />;
- }
-
- if (
- mime.includes("word") ||
- mime.includes("officedocument.wordprocessingml") ||
- ext === "doc" ||
- ext === "docx"
- ) {
- return <FileText className="h-8 w-8 text-blue-600" />;
- }
-
- if (
- mime.includes("zip") ||
- mime.includes("tar") ||
- mime.includes("rar") ||
- mime.includes("gzip") ||
- ext === "zip" ||
- ext === "rar" ||
- ext === "tar" ||
- ext === "gz"
- ) {
- return <FileArchive className="h-8 w-8 text-amber-500" />;
- }
-
- return <FileIcon className="h-8 w-8 text-slate-400" />;
-};
-
interface AssetsPaneProps {
onClose: () => void;
repository: EdgeEverRepository;
@@ -390,7 +337,7 @@ export const AssetsPane = ({ onClose, repository }: AssetsPaneProps) => {
/>
) : (
<div className="flex flex-col items-center gap-1.5 p-3 text-center">
- {getFileIcon(resource.mimeType, resource.filename)}
+ <AttachmentFileIcon mimeType={resource.mimeType} filename={resource.filename} />
<span className="rounded bg-slate-100 px-1.5 py-0.5 text-[9px] font-bold text-slate-500 uppercase tracking-wider">
{(resource.filename || "").split(".").pop() || "FILE"}
</span>
@@ -470,7 +417,7 @@ export const AssetsPane = ({ onClose, repository }: AssetsPaneProps) => {
className="p-1"
/>
) : (
- getFileIcon(resource.mimeType, resource.filename)
+ <AttachmentFileIcon mimeType={resource.mimeType} filename={resource.filename} />
)}
</div>
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index 0b9a4f1b..a6eb4598 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -224,6 +224,7 @@ import {
} from "./editor/ResizableImage";
import { ImageViewer } from "./editor/ImageViewer";
import { PdfAttachment } from "./editor/PdfAttachment";
+import { FileAttachment } from "./editor/FileAttachment";
import {
createNoteSearchHighlightPlugin,
formatNoteSearchMatchLabel,
@@ -1312,12 +1313,13 @@ const RichEditorPane = ({
return {
type: "paragraph",
content: [{
- type: "text",
- text: t("editor.attachmentLabel", { filename }),
- marks: [{
- type: "link",
- attrs: { href: resource.url, target: "_blank", class: "edgeever-attachment-link" },
- }],
+ type: "edgeeverFileAttachment",
+ attrs: {
+ url: resource.url,
+ label: t("editor.attachmentLabel", { filename }),
+ filename,
+ mimeType: file.type,
+ },
}],
};
});
@@ -1371,6 +1373,7 @@ const RichEditorPane = ({
EdgeEverCodeBlock.configure({ lowlight: codeBlockLowlight, defaultLanguage: "plaintext" }),
MergeDivider,
PdfAttachment,
+ FileAttachment,
...createEdgeEverMathematics(),
ThemeBlock,
ResizableImage.configure({
diff --git a/apps/web/src/components/MobileStandaloneTiptapEditor.tsx b/apps/web/src/components/MobileStandaloneTiptapEditor.tsx
index c2826402..313332be 100644
--- a/apps/web/src/components/MobileStandaloneTiptapEditor.tsx
+++ b/apps/web/src/components/MobileStandaloneTiptapEditor.tsx
@@ -4,12 +4,13 @@ import { useTranslation } from "react-i18next";
import { EditorContent, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import { PdfAttachment } from "@/components/editor/PdfAttachment";
+import { FileAttachment } from "@/components/editor/FileAttachment";
import Image from "@tiptap/extension-image";
import { TaskItem, TaskList } from "@tiptap/extension-list";
import { mergeAttributes } from "@tiptap/core";
import Placeholder from "@tiptap/extension-placeholder";
import { TableKit } from "@tiptap/extension-table";
-import { createExcerpt, docToMarkdown, docToText, emptyDoc, getImageReferrerPolicy, MergeDivider, type MemoDetail, type MemoEditSession, type Notebook, type TagSummary, type TiptapDoc } from "@edgeever/shared";
+import { createExcerpt, docToMarkdown, docToText, emptyDoc, getImageReferrerPolicy, isPdfAttachment, MergeDivider, type MemoDetail, type MemoEditSession, type Notebook, type TagSummary, type TiptapDoc } from "@edgeever/shared";
import { createEdgeEverMathematics } from "@edgeever/shared/mathematics";
import { getMobileEditorInputAttributes, getMobileEditorPlaceholder } from "@edgeever/shared/mobile-editor";
import {
@@ -197,6 +198,7 @@ export const MobileStandaloneTiptapEditor = ({
extensions: [
StarterKit,
PdfAttachment,
+ FileAttachment,
TaskList,
TaskItem.configure({ nested: true }),
MergeDivider,
@@ -633,19 +635,37 @@ export const MobileStandaloneTiptapEditor = ({
title: file.name,
})
.run();
+ } else if (isPdfAttachment(file.type, resource.filename || file.name)) {
+ editor
+ .chain()
+ .focus()
+ .insertContent({
+ type: "paragraph",
+ content: [{
+ type: "edgeeverPdfAttachment",
+ attrs: {
+ url: resource.url,
+ label: `附件:${resource.filename || file.name}`,
+ displayMode: "compact",
+ },
+ }],
+ })
+ .run();
} else {
+ const filename = resource.filename || file.name;
editor
.chain()
.focus()
.insertContent({
type: "paragraph",
content: [{
- type: "text",
- text: `附件:${resource.filename || file.name}`,
- marks: [{
- type: "link",
- attrs: { href: resource.url, target: "_blank", class: "edgeever-attachment-link" },
- }],
+ type: "edgeeverFileAttachment",
+ attrs: {
+ url: resource.url,
+ label: `附件:${filename}`,
+ filename,
+ mimeType: file.type,
+ },
}],
})
.run();
diff --git a/apps/web/src/components/PublicSharePage.tsx b/apps/web/src/components/PublicSharePage.tsx
index ef75a274..ce3ee803 100644
--- a/apps/web/src/components/PublicSharePage.tsx
+++ b/apps/web/src/components/PublicSharePage.tsx
@@ -23,6 +23,7 @@ import {
} from "@edgeever/shared";
import { createEdgeEverMathematics } from "@edgeever/shared/mathematics";
import { PdfAttachment } from "@/components/editor/PdfAttachment";
+import { FileAttachment } from "@/components/editor/FileAttachment";
const SharedImage = Image.extend({
addAttributes() {
@@ -91,6 +92,7 @@ const SharedDocument = ({ share, token }: { share: PublicMemoShare; token: strin
EdgeEverCodeBlock.configure({ lowlight: codeBlockLowlight, defaultLanguage: "plaintext" }),
MergeDivider,
PdfAttachment,
+ FileAttachment,
...createEdgeEverMathematics(),
SharedThemeBlock,
SharedImage.configure({ allowBase64: false, inline: false }),
diff --git a/apps/web/src/components/attachments/AttachmentFileIcon.tsx b/apps/web/src/components/attachments/AttachmentFileIcon.tsx
new file mode 100644
index 00000000..b178aa2e
--- /dev/null
+++ b/apps/web/src/components/attachments/AttachmentFileIcon.tsx
@@ -0,0 +1,40 @@
+import {
+ File,
+ FileArchive,
+ FileCode2,
+ FileSpreadsheet,
+ FileText,
+ ImageIcon,
+ Music,
+ Presentation,
+ Video,
+} from "lucide-react";
+import { resolveAttachmentKind } from "@edgeever/shared";
+import { cn } from "@/lib/utils";
+
+export const AttachmentFileIcon = ({
+ mimeType,
+ filename,
+ className,
+}: {
+ mimeType?: string | null;
+ filename?: string | null;
+ className?: string;
+}) => {
+ const kind = resolveAttachmentKind(mimeType, filename);
+ const commonClassName = cn("h-8 w-8 shrink-0", className);
+
+ switch (kind) {
+ case "image": return <ImageIcon className={cn(commonClassName, "text-emerald-500")} aria-hidden="true" />;
+ case "audio": return <Music className={cn(commonClassName, "text-sky-500")} aria-hidden="true" />;
+ case "video": return <Video className={cn(commonClassName, "text-rose-500")} aria-hidden="true" />;
+ case "pdf": return <FileText className={cn(commonClassName, "text-rose-600")} aria-hidden="true" />;
+ case "spreadsheet": return <FileSpreadsheet className={cn(commonClassName, "text-green-600")} aria-hidden="true" />;
+ case "document": return <FileText className={cn(commonClassName, "text-blue-600")} aria-hidden="true" />;
+ case "presentation": return <Presentation className={cn(commonClassName, "text-orange-500")} aria-hidden="true" />;
+ case "archive": return <FileArchive className={cn(commonClassName, "text-amber-500")} aria-hidden="true" />;
+ case "code": return <FileCode2 className={cn(commonClassName, "text-violet-500")} aria-hidden="true" />;
+ case "text": return <FileText className={cn(commonClassName, "text-slate-500")} aria-hidden="true" />;
+ default: return <File className={cn(commonClassName, "text-slate-400")} aria-hidden="true" />;
+ }
+};
diff --git a/apps/web/src/components/editor/FileAttachment.tsx b/apps/web/src/components/editor/FileAttachment.tsx
new file mode 100644
index 00000000..b0de1ed9
--- /dev/null
+++ b/apps/web/src/components/editor/FileAttachment.tsx
@@ -0,0 +1,53 @@
+import {
+ FileAttachment as BaseFileAttachment,
+ getAttachmentFilenameFromLabel,
+} from "@edgeever/shared";
+import { NodeViewWrapper, ReactNodeViewRenderer, type NodeViewProps } from "@tiptap/react";
+import { Download, ExternalLink } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { AttachmentFileIcon } from "@/components/attachments/AttachmentFileIcon";
+import { ButtonTooltip } from "@/components/ui/button-tooltip";
+import { isDesktopResourceRuntime, toApiResourceUrl } from "@/lib/desktop-resources";
+
+const FileAttachmentNodeView = ({ node }: NodeViewProps) => {
+ const { t } = useTranslation();
+ const url = typeof node.attrs.url === "string" ? node.attrs.url : "";
+ const label = typeof node.attrs.label === "string" ? node.attrs.label : "Attachment";
+ const filename = typeof node.attrs.filename === "string" && node.attrs.filename
+ ? node.attrs.filename
+ : getAttachmentFilenameFromLabel(label);
+ const mimeType = typeof node.attrs.mimeType === "string" ? node.attrs.mimeType : "";
+ const resolvedUrl = isDesktopResourceRuntime() ? url : toApiResourceUrl(url);
+
+ return (
+ <NodeViewWrapper as="span" className="edgeever-file-attachment-node" contentEditable={false}>
+ <span className="edgeever-file-viewer flex min-h-12 w-full items-center gap-2 overflow-hidden rounded-xl border border-slate-200 bg-white px-3 shadow-sm">
+ <a
+ href={resolvedUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="flex min-w-0 flex-1 items-center gap-2 text-left text-sm font-semibold text-slate-800 no-underline"
+ >
+ <AttachmentFileIcon mimeType={mimeType} filename={filename || label} className="h-4 w-4" />
+ <span className="min-w-0 truncate">{label}</span>
+ </a>
+ <ButtonTooltip title={t("pdfViewer.download")}>
+ <a className="pdf-viewer-action" href={resolvedUrl} download={filename || label} aria-label={t("pdfViewer.download")}>
+ <Download aria-hidden="true" />
+ </a>
+ </ButtonTooltip>
+ <ButtonTooltip title={t("pdfViewer.openExternal")}>
+ <a className="pdf-viewer-action" href={resolvedUrl} target="_blank" rel="noreferrer" aria-label={t("pdfViewer.openExternal")}>
+ <ExternalLink aria-hidden="true" />
+ </a>
+ </ButtonTooltip>
+ </span>
+ </NodeViewWrapper>
+ );
+};
+
+export const FileAttachment = BaseFileAttachment.extend({
+ addNodeView() {
+ return ReactNodeViewRenderer(FileAttachmentNodeView);
+ },
+});
diff --git a/apps/web/src/components/pdf/PdfViewer.tsx b/apps/web/src/components/pdf/PdfViewer.tsx
index 1a321844..1e2a2cfa 100644
--- a/apps/web/src/components/pdf/PdfViewer.tsx
+++ b/apps/web/src/components/pdf/PdfViewer.tsx
@@ -6,7 +6,6 @@ import {
ChevronUp,
Download,
ExternalLink,
- FileText,
Loader2,
Maximize2,
Minimize2,
@@ -18,6 +17,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { ButtonTooltip } from "@/components/ui/button-tooltip";
+import { AttachmentFileIcon } from "@/components/attachments/AttachmentFileIcon";
import { isDesktopResourceRuntime, toApiResourceUrl } from "@/lib/desktop-resources";
import { cn } from "@/lib/utils";
import { loadPdfJs } from "./pdfjs-loader";
@@ -270,7 +270,7 @@ export const PdfViewer = ({
disabled={isFullscreen}
onClick={() => setExpanded(!expanded)}
>
- <FileText className="h-4 w-4 shrink-0 text-rose-600" aria-hidden="true" />
+ <AttachmentFileIcon mimeType="application/pdf" filename={label} className="h-4 w-4" />
<span className="min-w-0 truncate">{label}</span>
</button>
{expanded && !failed ? (
diff --git a/apps/web/src/styles/globals.css b/apps/web/src/styles/globals.css
index e823ca40..685b189c 100644
--- a/apps/web/src/styles/globals.css
+++ b/apps/web/src/styles/globals.css
@@ -706,7 +706,8 @@ textarea {
transition: border-color 160ms ease, background 160ms ease, box-shadow 160ms ease;
}
-.edgeever-pdf-attachment-node {
+.edgeever-pdf-attachment-node,
+.edgeever-file-attachment-node {
display: block;
margin: 0.75rem 0 1rem;
}
@@ -765,7 +766,8 @@ textarea {
}
.ProseMirror .edgeever-pdf-viewer a.edgeever-attachment-link,
-.ProseMirror .edgeever-pdf-viewer a[href*="/api/v1/resources/"] {
+.ProseMirror .edgeever-pdf-viewer a[href*="/api/v1/resources/"],
+.ProseMirror .edgeever-file-viewer a[href*="/api/v1/resources/"] {
max-width: none;
padding: 0;
border: 0;
@@ -775,11 +777,13 @@ textarea {
}
.ProseMirror .edgeever-pdf-viewer a.edgeever-attachment-link::before,
-.ProseMirror .edgeever-pdf-viewer a[href*="/api/v1/resources/"]::before {
+.ProseMirror .edgeever-pdf-viewer a[href*="/api/v1/resources/"]::before,
+.ProseMirror .edgeever-file-viewer a[href*="/api/v1/resources/"]::before {
content: none;
}
-.ProseMirror .edgeever-pdf-viewer a.pdf-viewer-action:hover {
+.ProseMirror .edgeever-pdf-viewer a.pdf-viewer-action:hover,
+.ProseMirror .edgeever-file-viewer a.pdf-viewer-action:hover {
background: var(--brand-green-soft);
color: var(--brand-green-text);
}
diff --git a/packages/shared/src/attachment-kind.test.mjs b/packages/shared/src/attachment-kind.test.mjs
new file mode 100644
index 00000000..bd8e2bb0
--- /dev/null
+++ b/packages/shared/src/attachment-kind.test.mjs
@@ -0,0 +1,19 @@
+import { describe, expect, test } from "bun:test";
+import { resolveAttachmentKind } from "./attachment-kind.ts";
+
+describe("attachment kind", () => {
+ test("uses MIME types for media and filenames for common documents", () => {
+ expect(resolveAttachmentKind("audio/mpeg", "recording.bin")).toBe("audio");
+ expect(resolveAttachmentKind(null, "report.PDF")).toBe("pdf");
+ expect(resolveAttachmentKind(null, "budget.xlsx")).toBe("spreadsheet");
+ expect(resolveAttachmentKind(null, "proposal.docx")).toBe("document");
+ expect(resolveAttachmentKind(null, "pitch.pptx")).toBe("presentation");
+ expect(resolveAttachmentKind(null, "source.ts")).toBe("code");
+ expect(resolveAttachmentKind(null, "backup.7z")).toBe("archive");
+ });
+
+ test("falls back predictably for text and unknown files", () => {
+ expect(resolveAttachmentKind("text/plain", "README")).toBe("text");
+ expect(resolveAttachmentKind("application/octet-stream", "payload.bin")).toBe("file");
+ });
+});
diff --git a/packages/shared/src/attachment-kind.ts b/packages/shared/src/attachment-kind.ts
new file mode 100644
index 00000000..31ec3a6c
--- /dev/null
+++ b/packages/shared/src/attachment-kind.ts
@@ -0,0 +1,61 @@
+export const ATTACHMENT_KINDS = [
+ "image",
+ "audio",
+ "video",
+ "pdf",
+ "spreadsheet",
+ "document",
+ "presentation",
+ "archive",
+ "code",
+ "text",
+ "file",
+] as const;
+
+export type AttachmentKind = (typeof ATTACHMENT_KINDS)[number];
+
+const extensionOf = (filename: string | null | undefined) =>
+ filename?.trim().toLowerCase().match(/\.([a-z0-9]+)(?:[?#].*)?$/)?.[1] ?? "";
+
+export const resolveAttachmentKind = (
+ mimeType: string | null | undefined,
+ filename: string | null | undefined,
+): AttachmentKind => {
+ const mime = mimeType?.trim().toLowerCase() ?? "";
+ const extension = extensionOf(filename);
+
+ if (mime.startsWith("image/")) return "image";
+ if (mime.startsWith("audio/")) return "audio";
+ if (mime.startsWith("video/")) return "video";
+ if (mime === "application/pdf" || extension === "pdf") return "pdf";
+
+ if (
+ mime.includes("spreadsheet") || mime.includes("excel") ||
+ ["xls", "xlsx", "xlsm", "ods", "csv"].includes(extension)
+ ) return "spreadsheet";
+
+ if (
+ mime.includes("word") || mime.includes("wordprocessingml") ||
+ ["doc", "docx", "odt", "rtf"].includes(extension)
+ ) return "document";
+
+ if (
+ mime.includes("presentation") || mime.includes("powerpoint") ||
+ ["ppt", "pptx", "odp", "key"].includes(extension)
+ ) return "presentation";
+
+ if (
+ mime.includes("zip") || mime.includes("compressed") || mime.includes("tar") ||
+ mime.includes("rar") || mime.includes("gzip") ||
+ ["zip", "rar", "7z", "tar", "gz", "bz2", "xz"].includes(extension)
+ ) return "archive";
+
+ if (
+ mime.includes("javascript") || mime.includes("typescript") || mime.includes("json") ||
+ mime.includes("xml") || mime.includes("yaml") ||
+ ["js", "jsx", "ts", "tsx", "json", "xml", "yaml", "yml", "html", "css", "sh", "py", "java", "go", "rs"].includes(extension)
+ ) return "code";
+
+ if (mime.startsWith("text/") || ["txt", "md", "log"].includes(extension)) return "text";
+ return "file";
+};
diff --git a/packages/shared/src/content.test.mjs b/packages/shared/src/content.test.mjs
index b02fb5ac..7d88775f 100644
--- a/packages/shared/src/content.test.mjs
+++ b/packages/shared/src/content.test.mjs
@@ -6,6 +6,7 @@ import {
markdownToDoc,
MERGE_DIVIDER_MARKDOWN_MARKER,
MERGE_DIVIDER_NODE_TYPE,
+ FILE_ATTACHMENT_NODE_TYPE,
PDF_ATTACHMENT_NODE_TYPE,
mergeMemoDocs,
resolvePdfDisplayMode,
@@ -96,6 +97,47 @@ describe("PDF attachment Markdown compatibility", () => {
});
});
+describe("file attachment Markdown compatibility", () => {
+ test("parses a stored non-PDF resource link as an attachment card", () => {
+ const markdown = "[Attachment: budget.xlsx](/api/v1/resources/res_sheet/blob)";
+ const doc = markdownToDoc(markdown);
+
+ expect(doc.content[0]).toMatchObject({
+ type: "paragraph",
+ content: [{
+ type: FILE_ATTACHMENT_NODE_TYPE,
+ attrs: {
+ label: "Attachment: budget.xlsx",
+ filename: "budget.xlsx",
+ url: "/api/v1/resources/res_sheet/blob",
+ },
+ }],
+ });
+ expect(docToMarkdown(doc)).toBe(markdown);
+ });
+
+ test("keeps an ordinary standalone web link as text", () => {
+ const doc = markdownToDoc("[EdgeEver](https://edgeever.org)");
+ expect(doc.content[0]?.content?.[0]?.type).toBe("text");
+ });
+
+ test("upgrades a legacy standalone attachment link from rich content", () => {
+ const legacyDoc = {
+ type: "doc",
+ content: [{
+ type: "paragraph",
+ content: [{
+ type: "text",
+ text: "附件:archive.zip",
+ marks: [{ type: "link", attrs: { href: "/api/v1/resources/res_archive/blob" } }],
+ }],
+ }],
+ };
+
+ expect(resolveMemoContentDoc(legacyDoc, "").content[0]?.content?.[0]?.type).toBe(FILE_ATTACHMENT_NODE_TYPE);
+ });
+});
+
describe("memo character count", () => {
test("counts punctuation while excluding whitespace and formatting", () => {
const doc = markdownToDoc("你好, **EdgeEver**!\n\n下一行");
diff --git a/packages/shared/src/content.ts b/packages/shared/src/content.ts
index 89824830..bfe000e7 100644
--- a/packages/shared/src/content.ts
+++ b/packages/shared/src/content.ts
@@ -5,6 +5,7 @@ import { Markdown, MarkdownManager } from "@tiptap/markdown";
import StarterKit from "@tiptap/starter-kit";
import { MergeDivider, MERGE_DIVIDER_NODE_TYPE } from "./merge-divider";
import { PdfAttachment, PDF_ATTACHMENT_NODE_TYPE, upgradeStandalonePdfLinks } from "./pdf-attachment";
+import { FileAttachment, FILE_ATTACHMENT_NODE_TYPE, upgradeStandaloneFileLinks } from "./file-attachment";
import {
BLOCK_MATH_NODE_TYPE,
createEdgeEverMarkdownMathematics,
@@ -34,6 +35,13 @@ export {
} from "./pdf-attachment";
export type { PdfDisplayMode } from "./pdf-attachment";
+export {
+ FileAttachment,
+ FILE_ATTACHMENT_NODE_TYPE,
+ isFileAttachmentLink,
+ upgradeStandaloneFileLinks,
+} from "./file-attachment";
+
export type TiptapTextNode = {
type: "text";
text: string;
@@ -87,6 +95,7 @@ const markdownManager = new MarkdownManager({
TableKit,
Image,
PdfAttachment,
+ FileAttachment,
MergeDivider,
...createEdgeEverMarkdownMathematics(),
Markdown.configure({
@@ -122,7 +131,7 @@ export const resolveMemoContentDoc = (
contentMarkdown: string | null | undefined
): TiptapDoc => {
const currentDoc = contentJson && Array.isArray(contentJson.content)
- ? upgradeStandalonePdfLinks(upgradeLegacyAttachmentLinks(contentJson))
+ ? upgradeStandaloneFileLinks(upgradeStandalonePdfLinks(upgradeLegacyAttachmentLinks(contentJson)))
: emptyDoc();
if (
!contentMarkdown?.trim() ||
@@ -133,6 +142,7 @@ export const resolveMemoContentDoc = (
docContainsNodeType(currentDoc, BLOCK_MATH_NODE_TYPE) ||
docContainsNodeType(currentDoc, INLINE_MATH_NODE_TYPE)
|| docContainsNodeType(currentDoc, PDF_ATTACHMENT_NODE_TYPE)
+ || docContainsNodeType(currentDoc, FILE_ATTACHMENT_NODE_TYPE)
) {
return currentDoc;
}
@@ -218,7 +228,7 @@ export const docToText = (doc: unknown): string => {
}
}
- if (current.type === PDF_ATTACHMENT_NODE_TYPE) {
+ if (current.type === PDF_ATTACHMENT_NODE_TYPE || current.type === FILE_ATTACHMENT_NODE_TYPE) {
const label = getStringAttr(current.attrs, "label");
if (label) pieces.push(label);
}
@@ -274,7 +284,7 @@ export const countMemoCharacters = (doc: unknown): number => {
pieces.push(current.text);
}
- if (current.type === PDF_ATTACHMENT_NODE_TYPE) {
+ if (current.type === PDF_ATTACHMENT_NODE_TYPE || current.type === FILE_ATTACHMENT_NODE_TYPE) {
const label = getStringAttr(current.attrs, "label");
if (label) pieces.push(label);
}
diff --git a/packages/shared/src/file-attachment.ts b/packages/shared/src/file-attachment.ts
new file mode 100644
index 00000000..55ff6a10
--- /dev/null
+++ b/packages/shared/src/file-attachment.ts
@@ -0,0 +1,140 @@
+import { mergeAttributes, Node } from "@tiptap/core";
+import type { TiptapDoc, TiptapMark, TiptapNode, TiptapTextNode } from "./content";
+import { resolveAttachmentKind } from "./attachment-kind";
+import { getAttachmentFilenameFromLabel } from "./resource-links";
+
+export const FILE_ATTACHMENT_NODE_TYPE = "edgeeverFileAttachment" as const;
+
+const MARKDOWN_LINK_PATTERN = /^\[([^\]]+)\]\(([^\s)]+)(?:\s+"[^"]*")?\)/;
+const ATTACHMENT_LABEL_PATTERN = /^\s*(?:附件[::]|Attachment:)\s*/i;
+const RESOURCE_URL_PATTERN = /(?:\/api\/v1\/resources\/|edgeever-(?:resource|staged):\/\/)/i;
+
+const escapeMarkdownLabel = (value: string) =>
+ value.replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]");
+
+export const isFileAttachmentLink = (label: string, url: string) => {
+ const filename = getAttachmentFilenameFromLabel(label) || label || url;
+ if (resolveAttachmentKind(null, filename) === "pdf" || resolveAttachmentKind(null, url) === "pdf") {
+ return false;
+ }
+ return ATTACHMENT_LABEL_PATTERN.test(label) || RESOURCE_URL_PATTERN.test(url) || resolveAttachmentKind(null, filename) !== "file";
+};
+
+export const FileAttachment = Node.create({
+ name: FILE_ATTACHMENT_NODE_TYPE,
+ group: "inline",
+ inline: true,
+ atom: true,
+ selectable: true,
+ draggable: true,
+
+ addAttributes() {
+ return {
+ url: {
+ default: "",
+ parseHTML: (element) => element.getAttribute("data-file-url") || "",
+ renderHTML: (attributes) => ({ "data-file-url": attributes.url || "" }),
+ },
+ label: {
+ default: "Attachment",
+ parseHTML: (element) => element.getAttribute("data-file-label") || "Attachment",
+ renderHTML: (attributes) => ({ "data-file-label": attributes.label || "Attachment" }),
+ },
+ filename: {
+ default: "",
+ parseHTML: (element) => element.getAttribute("data-file-name") || "",
+ renderHTML: (attributes) => ({ "data-file-name": attributes.filename || "" }),
+ },
+ mimeType: {
+ default: "",
+ parseHTML: (element) => element.getAttribute("data-file-mime-type") || "",
+ renderHTML: (attributes) => ({ "data-file-mime-type": attributes.mimeType || "" }),
+ },
+ };
+ },
+
+ parseHTML() {
+ return [{ tag: 'span[data-type="edgeever-file-attachment"]' }];
+ },
+
+ renderHTML({ HTMLAttributes }) {
+ return [
+ "span",
+ mergeAttributes(HTMLAttributes, {
+ "data-type": "edgeever-file-attachment",
+ class: "edgeever-file-attachment",
+ }),
+ ];
+ },
+
+ parseMarkdown: (token) => {
+ const label = token.label || "Attachment";
+ return {
+ type: FILE_ATTACHMENT_NODE_TYPE,
+ attrs: {
+ url: token.url || "",
+ label,
+ filename: getAttachmentFilenameFromLabel(label),
+ mimeType: "",
+ },
+ };
+ },
+
+ renderMarkdown: (node) =>
+ `[${escapeMarkdownLabel(String(node.attrs?.label || "Attachment"))}](${String(node.attrs?.url || "")})`,
+
+ markdownTokenizer: {
+ name: FILE_ATTACHMENT_NODE_TYPE,
+ level: "inline",
+ start(source: string) {
+ return source.indexOf("[");
+ },
+ tokenize(source: string) {
+ const match = MARKDOWN_LINK_PATTERN.exec(source);
+ if (!match || !isFileAttachmentLink(match[1], match[2])) return undefined;
+ return {
+ type: FILE_ATTACHMENT_NODE_TYPE,
+ raw: match[0],
+ label: match[1],
+ url: match[2],
+ };
+ },
+ },
+});
+
+const getLinkMark = (node: TiptapTextNode): TiptapMark | undefined =>
+ node.marks?.find((mark) => mark.type === "link" && typeof mark.attrs?.href === "string");
+
+/** Upgrade legacy standalone attachment links while preserving ordinary web links. */
+export const upgradeStandaloneFileLinks = (doc: TiptapDoc): TiptapDoc => {
+ let changed = false;
+ const visit = (node: TiptapNode): TiptapNode => {
+ if (node.type === "paragraph" && node.content?.length === 1) {
+ const child = node.content[0];
+ if (child.type === "text" && "text" in child) {
+ const link = getLinkMark(child);
+ const href = link?.attrs?.href;
+ if (typeof href === "string" && isFileAttachmentLink(child.text, href)) {
+ changed = true;
+ return {
+ ...node,
+ content: [{
+ type: FILE_ATTACHMENT_NODE_TYPE,
+ attrs: {
+ url: href,
+ label: child.text,
+ filename: getAttachmentFilenameFromLabel(child.text),
+ mimeType: "",
+ },
+ }],
+ };
+ }
+ }
+ }
+ return node.content
+ ? { ...node, content: node.content.map((child) => child.type === "text" ? child : visit(child)) }
+ : node;
+ };
+ const content = doc.content.map(visit);
+ return changed ? { ...doc, content } : doc;
+};
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index ea79287f..d1a064cf 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -4,6 +4,7 @@ export * from "./ai-assistant";
export * from "./ai-prompt-seeds";
export * from "./ai-tag-suggestions";
export * from "./ai-selection";
+export * from "./attachment-kind";
export * from "./backup";
export * from "./github-feedback";
export * from "./image-display";
@@ -21,6 +22,7 @@ export * from "./schemas";
export * from "./sharing";
export * from "./sync";
export * from "./desktop-rpc";
+export * from "./file-attachment";
export * from "./note-image-card";
export * from "./pdf-attachment";
export * from "./types";