Skip to content

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

feat(markdown): preserve front matter on import and export

tianma-ifccc73ab6af62
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index a59b1dd8..af948bfe 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -130,6 +130,11 @@ import { EDITOR_CONTENT_MAX_WIDTH, EDITOR_OUTLINE_WIDTH } from "@/lib/workspace-
import {
countMemoCharacters,
createEdgeEverDocumentExtensions,
+ getFrontMatterSource,
+ getMappedNoteProperties,
+ parseNoteProperties,
+ splitMarkdownFrontMatter,
+ updateNoteProperty,
docToMarkdown,
MEMO_CONTENT_STYLE,
noteProseCssVariables,
@@ -1406,6 +1411,39 @@ const RichEditorPane = ({
});
const useMarkdownSourceEditor = !useMobilePlainTextEditor && isMarkdownMode;
+ const applyPropertyFields = useCallback((source: string | null) => {
+ if (source === null || hydratingRef.current) return;
+ const fields = memoFieldsRef.current;
+ if (fields.memoId !== memoRef.current?.id) return;
+ const properties = parseNoteProperties(source);
+ if (!properties.values) return;
+ const mapped = getMappedNoteProperties(properties.values);
+ const next = { ...fields, ...(mapped.title !== undefined ? { title: mapped.title } : {}),
+ ...(mapped.tags !== undefined ? { tagsText: mapped.tags.join(", ") } : {}) };
+ if (next.title === fields.title && next.tagsText === fields.tagsText) return;
+ memoFieldsRef.current = next;
+ setMemoFields(next);
+ }, []);
+
+ const updatePropertyField = (name: string, value: unknown) => {
+ if (!isEditorReady(editor)) return;
+ const source = useMarkdownSourceEditor ? splitMarkdownFrontMatter(getMarkdownSource())?.source ?? null
+ : getFrontMatterSource(editor.getJSON() as TiptapDoc);
+ if (source === null) return;
+ const properties = parseNoteProperties(source);
+ if (!properties.values || !Object.hasOwn(properties.values, name)) return;
+ const next = updateNoteProperty(source, name, value);
+ if (useMarkdownSourceEditor) {
+ const split = splitMarkdownFrontMatter(getMarkdownSource())!;
+ const markdown = `---\n${next}\n---\n${split.body}`;
+ setMarkdownSource(markdown);
+ markdownSourceEditorRef.current?.replaceDocument(markdown);
+ } else {
+ const node = editor.state.doc.firstChild!;
+ editor.view.dispatch(editor.state.tr.insertText(next, 1, node.nodeSize - 1));
+ }
+ };
+
const uploadMarkdownPasteFiles = useCallback(async (files: File[]) => {
const targetMemoId = memoRef.current?.id;
if (!targetMemoId || effectiveReadOnly) return "";
@@ -2622,7 +2660,11 @@ const RichEditorPane = ({
return;
}
+ let previousProperties = getFrontMatterSource(editor.getJSON() as TiptapDoc);
const persistDraft = () => {
+ const source = getFrontMatterSource(editor.getJSON() as TiptapDoc);
+ if (source !== previousProperties) applyPropertyFields(source);
+ previousProperties = source;
if (hydratingRef.current || memoRef.current?.isDeleted) {
return;
}
@@ -2634,7 +2676,7 @@ const RichEditorPane = ({
return () => {
editor.off("update", persistDraft);
};
- }, [editor, markDirty, memo, persistCurrentDraft]);
+ }, [applyPropertyFields, editor, markDirty, memo, persistCurrentDraft]);
useEffect(() => {
const advanceMemoSyncBase = (syncedMemo: MemoDetail | null | undefined) => {
@@ -2723,6 +2765,7 @@ const RichEditorPane = ({
const handleMarkdownSourceChange = useCallback((value: string) => {
if (revertingUnsafeMarkdownRef.current) return;
+ const previousProperties = splitMarkdownFrontMatter(getMarkdownSource())?.source ?? null;
if (!setMarkdownSource(value)) {
revertingUnsafeMarkdownRef.current = true;
try {
@@ -2732,8 +2775,10 @@ const RichEditorPane = ({
}
return;
}
+ const properties = splitMarkdownFrontMatter(value)?.source ?? null;
+ if (properties !== previousProperties) applyPropertyFields(properties);
markDirty();
- }, [getMarkdownSource, markDirty, setMarkdownSource]);
+ }, [applyPropertyFields, getMarkdownSource, markDirty, setMarkdownSource]);
const {
handleCopyToWeChat,
@@ -3868,9 +3913,11 @@ const RichEditorPane = ({
value={title}
readOnly={effectiveReadOnly}
onValueChange={(nextTitle) => {
+ if (memoFieldsRef.current.memoId === memo.id) memoFieldsRef.current = { ...memoFieldsRef.current, title: nextTitle };
setMemoFields((fields) => fields.memoId === memo.id
? { ...fields, title: nextTitle }
: fields);
+ updatePropertyField("title", nextTitle);
persistCurrentDraft(nextTitle, tagsText, getMobilePlainTextValue());
markDirty();
}}
@@ -3892,9 +3939,11 @@ const RichEditorPane = ({
onMobileNotebookPickerOpenChange={setMobileNotebookSheetOpen}
onNotebookChange={handleNotebookChange}
onTagsChange={(nextTagsText) => {
+ if (memoFieldsRef.current.memoId === memo.id) memoFieldsRef.current = { ...memoFieldsRef.current, tagsText: nextTagsText };
setMemoFields((fields) => fields.memoId === memo.id
? { ...fields, tagsText: nextTagsText }
: fields);
+ updatePropertyField("tags", parseTagsText(nextTagsText));
persistCurrentDraft(title, nextTagsText, getMobilePlainTextValue());
markDirty();
}}
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index dddd6443..fcf0f284 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -1931,7 +1931,7 @@ export const WorkspaceApp = ({
notebookId: targetNotebookId,
title: payload.title,
contentMarkdown: payload.contentMarkdown,
- tags: [],
+ tags: payload.tags ?? [],
});
} catch {
setAppNoticeDialog({
diff --git a/apps/web/src/components/editor/NoteProperties.tsx b/apps/web/src/components/editor/NoteProperties.tsx
new file mode 100644
index 00000000..ea31c093
--- /dev/null
+++ b/apps/web/src/components/editor/NoteProperties.tsx
@@ -0,0 +1,108 @@
+import { useEffect, useState } from "react";
+import { NodeViewContent, NodeViewWrapper, type NodeViewProps } from "@tiptap/react";
+import { useTranslation } from "react-i18next";
+import { ChevronDown, Code2, Plus, Trash2 } from "lucide-react";
+import { parseNoteProperties, updateNoteProperty } from "@edgeever/shared";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+
+const systemProperties = new Set(["created", "updated", "edgeever_id", "notebook", "pinned"]);
+type PropertyType = "text" | "list" | "number" | "checkbox" | "date" | "datetime" | "nested";
+const propertyType = (name: string, value: unknown): PropertyType => {
+ if (Array.isArray(value)) return value.every((item) => typeof item === "string") ? "list" : "nested";
+ if (value !== null && typeof value === "object") return "nested";
+ if (typeof value === "boolean") return "checkbox";
+ if (typeof value === "number") return "number";
+ if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(value)) return "datetime";
+ if ((typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value)) || name === "published") return "date";
+ return "text";
+};
+
+const PropertyRow = ({ name, value, readOnly, onChange, onRemove }: {
+ name: string; value: unknown; readOnly: boolean;
+ onChange: (value: unknown) => void; onRemove: () => void;
+}) => {
+ const { t } = useTranslation();
+ const type = propertyType(name, value);
+ const display = type === "list" ? (value as string[]).join("\n") : type === "nested" ? JSON.stringify(value) : String(value ?? "");
+ const [draft, setDraft] = useState(display);
+ const [invalid, setInvalid] = useState(false);
+ useEffect(() => { setDraft(display); setInvalid(false); }, [display]);
+ const commit = () => {
+ if (draft === display) return;
+ if (type === "number" && (!draft.trim() || !Number.isFinite(Number(draft)))) { setInvalid(true); return; }
+ onChange(type === "number" ? Number(draft) : type === "list" ? draft.split("\n").map((item) => item.trim()).filter(Boolean) : draft);
+ setInvalid(false);
+ };
+ const locked = readOnly || systemProperties.has(name);
+ return <div className="grid grid-cols-[minmax(80px,1fr)_minmax(0,2fr)_32px] items-start gap-2 py-1.5">
+ <span className="break-words pt-2 text-sm text-muted-foreground">{name}</span>
+ {type === "checkbox" ? <input className="mt-3 h-4 w-4 accent-[#16A06E]" type="checkbox" aria-label={name} checked={Boolean(value)} disabled={locked} onChange={(event) => onChange(event.target.checked)} />
+ : type === "nested" ? <span className="break-all py-2 text-xs text-muted-foreground">{display}</span>
+ : type === "list" || display.includes("\n") ? <textarea className="min-h-10 w-full rounded-md border bg-card px-3 py-2 text-sm" aria-label={name} placeholder={type === "list" ? t("noteProperties.listHint") : undefined} value={draft} readOnly={locked} onChange={(event) => setDraft(event.target.value)} onBlur={commit} />
+ : <Input className="h-9" aria-label={name} aria-invalid={invalid} type={type === "number" ? "text" : type === "date" ? "date" : "text"} value={draft} readOnly={locked}
+ maxLength={name === "title" ? 160 : undefined} onChange={(event) => setDraft(event.target.value)} onBlur={commit} onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); if (event.key === "Escape") { setDraft(display); setInvalid(false); } }} />}
+ {!locked && <Tooltip><TooltipTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8" aria-label={t("noteProperties.remove", { name })} onClick={onRemove}><Trash2 className="h-3.5 w-3.5" /></Button></TooltipTrigger><TooltipContent>{t("noteProperties.remove", { name })}</TooltipContent></Tooltip>}
+ {invalid && <p className="col-span-3 text-xs text-destructive" role="alert">{t("noteProperties.invalidNumber")}</p>}
+ </div>;
+};
+
+export const NoteProperties = ({ editor, node, getPos }: NodeViewProps) => {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(true);
+ const [sourceVisible, setSourceVisible] = useState(false);
+ const [editable, setEditable] = useState(editor.isEditable);
+ const [name, setName] = useState("");
+ const [type, setType] = useState("text");
+ const [error, setError] = useState("");
+ const source = node.textContent;
+ const parsed = parseNoteProperties(source);
+ useEffect(() => {
+ const refresh = () => setEditable(editor.isEditable);
+ refresh();
+ editor.on("update", refresh);
+ return () => {
+ editor.off("update", refresh);
+ };
+ }, [editor]);
+ const replace = (next: string) => {
+ const position = getPos();
+ if (!editor.isEditable || position === undefined) return;
+ editor.view.dispatch(editor.state.tr.insertText(next, position + 1, position + node.nodeSize - 1));
+ };
+ const change = (key: string, value: unknown, remove = false) => {
+ try { replace(updateNoteProperty(source, key, value, remove)); setError(""); }
+ catch (caught) { setError(caught instanceof Error ? caught.message : String(caught)); }
+ };
+ const add = () => {
+ const key = name.trim();
+ if (!key || Object.hasOwn(parsed.values ?? {}, key) || systemProperties.has(key)) { setError(t("noteProperties.invalidName")); return; }
+ const today = new Date();
+ const date = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
+ change(key, type === "checkbox" ? false : type === "number" ? 0 : type === "list" ? [] : type === "date" ? date : "");
+ setName("");
+ };
+ return <NodeViewWrapper className="not-prose my-4 rounded-xl border border-[var(--workspace-divider)] bg-card px-4 py-2" data-note-properties="true">
+ <TooltipProvider><Collapsible open={open} onOpenChange={setOpen}>
+ <div className="flex items-center justify-between gap-2" contentEditable={false}>
+ <CollapsibleTrigger asChild><Button variant="ghost" className="gap-2 px-0 text-sm font-medium"><ChevronDown className={`h-4 w-4 transition-transform ${open ? "" : "-rotate-90"}`} />{t("noteProperties.heading")}</Button></CollapsibleTrigger>
+ <Tooltip><TooltipTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8" aria-label={t("noteProperties.source")} aria-pressed={sourceVisible} onClick={() => { setOpen(true); setSourceVisible((current) => !current); }}><Code2 className="h-4 w-4" /></Button></TooltipTrigger><TooltipContent>{t("noteProperties.source")}</TooltipContent></Tooltip>
+ </div>
+ <CollapsibleContent>
+ {(parsed.error || error) && <p className="py-2 text-sm text-destructive" role="alert" contentEditable={false}>{t("noteProperties.invalidYaml")} {parsed.error || error}</p>}
+ {!sourceVisible && !parsed.error && <div contentEditable={false}>
+ {Object.entries(parsed.values ?? {}).map(([key, value]) => <PropertyRow key={key} name={key} value={value} readOnly={!editable} onChange={(next) => change(key, next)} onRemove={() => change(key, null, true)} />)}
+ {editable && <div className="mt-2 flex flex-wrap items-center gap-2 border-t pt-3">
+ <Input className="h-9 min-w-24 flex-1" aria-label={t("noteProperties.name")} placeholder={t("noteProperties.name")} value={name} onChange={(event) => setName(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter") add(); }} />
+ <Select value={type} onValueChange={setType}><SelectTrigger className="w-28" aria-label={t("noteProperties.type")}><SelectValue /></SelectTrigger><SelectContent>{["text", "list", "number", "checkbox", "date"].map((kind) => <SelectItem key={kind} value={kind}>{t(`noteProperties.${kind}`)}</SelectItem>)}</SelectContent></Select>
+ <Button variant="ghost" className="h-9 gap-1" onClick={add}><Plus className="h-4 w-4" />{t("noteProperties.add")}</Button>
+ </div>}
+ </div>}
+ </CollapsibleContent>
+ </Collapsible></TooltipProvider>
+ <div hidden={!open || (!sourceVisible && !parsed.error)} className="my-2 overflow-auto whitespace-pre-wrap rounded-md bg-muted p-3 font-mono text-sm"><NodeViewContent /></div>
+ </NodeViewWrapper>;
+};
diff --git a/apps/web/src/components/editor/useEditorDocumentActions.ts b/apps/web/src/components/editor/useEditorDocumentActions.ts
index db87234f..50a93186 100644
--- a/apps/web/src/components/editor/useEditorDocumentActions.ts
+++ b/apps/web/src/components/editor/useEditorDocumentActions.ts
@@ -3,7 +3,7 @@ import { useTranslation } from "react-i18next";
import type { Editor } from "@tiptap/react";
import { docToMarkdown, markdownToDoc, type MemoDetail, type TiptapDoc } from "@edgeever/shared";
import type { MemoDocumentActionRequest } from "@/lib/app-helpers";
-import { downloadMarkdownFile } from "@/lib/note-markdown-export";
+import { buildSingleNoteMarkdown, downloadMarkdownFile } from "@/lib/note-markdown-export";
import { downloadNoteHtmlFile, getHtmlImageEmbedNoticeKind } from "@/lib/note-html-export";
import { NOTE_HTML_FULL_STYLES } from "@/lib/note-html-export-assets";
import { openNotePrintPreview, serializeNoteDocumentForPrint } from "@/lib/note-print";
@@ -142,8 +142,8 @@ export const useEditorDocumentActions = ({
return;
}
- downloadMarkdownFile(content.markdown, title, t("common.untitledMemo"));
- }, [memo, resolveExportContent, t, title]);
+ downloadMarkdownFile(buildSingleNoteMarkdown(content.markdown, title, parseTagsText(tagsText)), title, t("common.untitledMemo"));
+ }, [memo, notebookName, resolveExportContent, t, tagsText, title]);
const handleExportHtml = useCallback(async () => {
const content = resolveExportContent();
diff --git a/apps/web/src/lib/code-block.ts b/apps/web/src/lib/code-block.ts
index 816af1ff..de295e77 100644
--- a/apps/web/src/lib/code-block.ts
+++ b/apps/web/src/lib/code-block.ts
@@ -3,6 +3,9 @@ import CodeBlockLowlight from "@tiptap/extension-code-block-lowlight";
import type { Editor } from "@tiptap/core";
import { ReactNodeViewRenderer } from "@tiptap/react";
import { MermaidCodeBlock } from "@/components/MermaidCodeBlock";
+import { NoteProperties } from "@/components/editor/NoteProperties";
+import { FRONT_MATTER_LANGUAGE } from "@edgeever/shared";
+import { createElement } from "react";
export const codeBlockLowlight = createLowlight(common);
@@ -30,7 +33,9 @@ export const EdgeEverCodeBlock = CodeBlockLowlight.extend({
},
addNodeView() {
- return ReactNodeViewRenderer(MermaidCodeBlock);
+ return ReactNodeViewRenderer((props) => createElement(
+ props.node.attrs.language === FRONT_MATTER_LANGUAGE ? NoteProperties : MermaidCodeBlock, props,
+ ));
},
});
diff --git a/apps/web/src/lib/json-backup.ts b/apps/web/src/lib/json-backup.ts
index 8455a771..e41d49e2 100644
--- a/apps/web/src/lib/json-backup.ts
+++ b/apps/web/src/lib/json-backup.ts
@@ -24,7 +24,7 @@ import {
ZipPassThrough,
} from "fflate";
import {
- buildMarkdownFrontMatter,
+ buildNoteMarkdown,
buildNotebookExportPaths,
getExportResourceExtension,
replaceExportResourceUrl,
@@ -259,7 +259,7 @@ export const createEdgeEverZipStream = async (
addJsonFile(zip!, `memos/${memo.id}.json`, { memo, revisions, resources: backupResources });
const markdownFile = new ZipDeflate(`${markdownDirectory}/${memoStem}.md`, { level: 6 });
zip!.add(markdownFile);
- markdownFile.push(strToU8(`${buildMarkdownFrontMatter(memo, notebookPath)}${markdown}`), true);
+ markdownFile.push(strToU8(buildNoteMarkdown(markdown, memo, notebookPath)), true);
revisionCount += revisions.length;
completed += 1;
onProgress?.({ completed, total });
diff --git a/apps/web/src/lib/markdown-export.ts b/apps/web/src/lib/markdown-export.ts
index cf014994..369ea207 100644
--- a/apps/web/src/lib/markdown-export.ts
+++ b/apps/web/src/lib/markdown-export.ts
@@ -1,4 +1,5 @@
import type { MemoDetail, Notebook, Resource } from "@edgeever/shared";
+import { mergeMarkdownFrontMatter } from "@edgeever/shared";
import { strToU8, Zip, ZipDeflate, ZipPassThrough } from "fflate";
export type MarkdownExportProgress = {
@@ -101,21 +102,19 @@ export const buildNotebookExportPaths = (notebooks: Notebook[]) => {
return pathById;
};
-const yamlString = (value: string) => JSON.stringify(value);
-
-export const buildMarkdownFrontMatter = (memo: MemoDetail, notebookPath: string) => [
- "---",
- `title: ${yamlString(memo.title?.trim() || "Untitled note")}`,
- `tags: ${JSON.stringify(memo.tags)}`,
- `notebook: ${yamlString(notebookPath)}`,
- `created: ${yamlString(memo.createdAt)}`,
- `updated: ${yamlString(memo.updatedAt)}`,
- `pinned: ${memo.isPinned}`,
- `edgeever_id: ${yamlString(memo.id)}`,
- "---",
- "",
- "",
-].join("\n");
+export const buildNoteMarkdown = (markdown: string, memo: MemoDetail, notebookPath: string) =>
+ mergeMarkdownFrontMatter(markdown, {
+ title: memo.title?.trim() || "Untitled note",
+ tags: memo.tags,
+ notebook: notebookPath,
+ created: memo.createdAt,
+ updated: memo.updatedAt,
+ pinned: memo.isPinned,
+ edgeever_id: memo.id,
+ });
+
+export const buildMarkdownFrontMatter = (memo: MemoDetail, notebookPath: string) =>
+ buildNoteMarkdown("", memo, notebookPath);
export const getExportResourceExtension = (resource: Resource) => {
const filenameExtension = resource.filename?.match(/\.([a-z0-9]{1,12})$/i)?.[1];
@@ -221,7 +220,7 @@ export const createMarkdownExport = async (
const markdownFile = new ZipDeflate(`${notebookPath}/${memoStem}.md`, { level: 6 });
zip.add(markdownFile);
- markdownFile.push(strToU8(`${buildMarkdownFrontMatter(memo, notebookPath)}${markdown}`), true);
+ markdownFile.push(strToU8(buildNoteMarkdown(markdown, memo, notebookPath)), true);
completed += 1;
onProgress?.({ completed, total: page.totalCount });
}
diff --git a/apps/web/src/lib/markdown-file-import.test.mjs b/apps/web/src/lib/markdown-file-import.test.mjs
index af4d0cee..3fd9e1f0 100644
--- a/apps/web/src/lib/markdown-file-import.test.mjs
+++ b/apps/web/src/lib/markdown-file-import.test.mjs
@@ -6,6 +6,12 @@ import {
} from "./markdown-file-import.ts";
describe("Markdown file import", () => {
+ test("imports title and tags from properties while keeping unknown fields in the document", async () => {
+ const markdown = "---\ntitle: Imported title\ntags: [archive, '#research']\nauthor: [Alice]\n---\n\nBody";
+ expect(await readMarkdownFile({ name: "file.md", text: async () => markdown })).toEqual({
+ title: "Imported title", tags: ["archive", "research"], contentMarkdown: markdown,
+ });
+ });
test("accepts Markdown extensions case-insensitively", () => {
expect(isMarkdownFile({ name: "notes.md" })).toBe(true);
expect(isMarkdownFile({ name: "notes.MARKDOWN" })).toBe(true);
diff --git a/apps/web/src/lib/markdown-file-import.ts b/apps/web/src/lib/markdown-file-import.ts
index 1ac50b67..73de3b09 100644
--- a/apps/web/src/lib/markdown-file-import.ts
+++ b/apps/web/src/lib/markdown-file-import.ts
@@ -1,3 +1,5 @@
+import { getMappedNoteProperties, splitMarkdownFrontMatter } from "@edgeever/shared";
+
const MARKDOWN_FILE_EXTENSION_PATTERN = /\.(?:md|markdown)$/i;
const MAX_MEMO_TITLE_LENGTH = 160;
@@ -9,7 +11,9 @@ export const getMarkdownFileTitle = (fileName: string) => {
return title.slice(0, MAX_MEMO_TITLE_LENGTH);
};
-export const readMarkdownFile = async (file: Pick<File, "name" | "text">) => ({
- title: getMarkdownFileTitle(file.name),
- contentMarkdown: (await file.text()).replace(/^\uFEFF/, ""),
-});
+export const readMarkdownFile = async (file: Pick<File, "name" | "text">) => {
+ const contentMarkdown = (await file.text()).replace(/^\uFEFF/, "");
+ const properties = splitMarkdownFrontMatter(contentMarkdown);
+ const mapped = properties?.values ? getMappedNoteProperties(properties.values) : {};
+ return { title: getMarkdownFileTitle(file.name), ...mapped, contentMarkdown };
+};
diff --git a/apps/web/src/lib/note-markdown-export.ts b/apps/web/src/lib/note-markdown-export.ts
index 42f72344..c2ba40b4 100644
--- a/apps/web/src/lib/note-markdown-export.ts
+++ b/apps/web/src/lib/note-markdown-export.ts
@@ -1,3 +1,15 @@
+import { mergeMarkdownFrontMatter, splitMarkdownFrontMatter } from "@edgeever/shared";
+
+/** Single-note exports retain existing properties without adding application metadata. */
+export const buildSingleNoteMarkdown = (markdown: string, title: string, tags: string[]) => {
+ const properties = splitMarkdownFrontMatter(markdown);
+ if (!properties?.values) return markdown;
+ const metadata: Record<string, unknown> = {};
+ if (Object.hasOwn(properties.values, "title")) metadata.title = title;
+ if (Object.hasOwn(properties.values, "tags")) metadata.tags = tags;
+ return Object.keys(metadata).length ? mergeMarkdownFrontMatter(markdown, metadata) : markdown;
+};
+
const WINDOWS_RESERVED_NAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;
export const buildMarkdownFilename = (title: string, fallback: string) => {
diff --git a/bun.lock b/bun.lock
index 713f22d5..2fbd23fd 100644
--- a/bun.lock
+++ b/bun.lock
@@ -298,6 +298,7 @@
"@tiptap/starter-kit": "3.31.0",
"js-base64": "3.9.3",
"katex": "0.16.22",
+ "yaml": "2.8.3",
"zod": "4.4.3",
},
},
diff --git a/docs/markdown-properties.md b/docs/markdown-properties.md
new file mode 100644
index 00000000..bce3353e
--- /dev/null
+++ b/docs/markdown-properties.md
@@ -0,0 +1,32 @@
+# Markdown note properties
+
+Text notes support a leading YAML Front Matter header. In Web and desktop rich-text view, it appears as a collapsible **Note properties** panel. The panel appears only in documents that already contain a header; ordinary notes have no additional properties entry point. A header can be added directly in Markdown source. The panel supports text, string lists (one value per line), numbers, checkboxes and dates. Nested values remain readable and can be edited in YAML source. The source button and Markdown editor both edit the same document data.
+
+```markdown
+---
+title: Research note
+tags: [archive, research]
+source: https://example.com/article
+author: [Alice, Bob]
+published: 2026-10-10
+description: A short summary
+custom:
+ reviewed: true
+---
+
+The note body starts here.
+```
+
+Importing a `.md` or `.markdown` file reads `title` and `tags` from the header. When no valid title is provided, the filename is used. Other properties, comments and nested values are retained in the document. Property edits to `title` and `tags` update the existing note fields; edits to those fields also update matching properties when present. Removing a property removes it from the document, without deleting the corresponding application field.
+
+Single-note exports (including the card context menu) export only the body for ordinary notes, without adding a header. Existing headers retain their properties and update title and tags only when those keys already exist; no additional system fields are added. Selected-note and full ZIP exports produce one header containing custom properties and current note metadata. The application's title, tags, notebook, creation/update timestamps, pinned state and ID take precedence over imported copies. These system properties (except title and tags) are read-only in the panel; editing their YAML copies does not change application state. `published` is an independent date and is editable. Importing an `edgeever_id` does not overwrite an existing note.
+
+Invalid YAML, duplicate keys, unknown YAML tags, oversized headers (over 64 KiB) and excessive alias expansion show an error with the original YAML available for correction. An invalid header is exported unchanged rather than losing its source. No replacement metadata is added until the header is valid. Plain Markdown separators, ordinary YAML code examples and unclosed headers are not interpreted as properties. Properties are excluded from body excerpts and character counts.
+
+## Compatibility and rollback
+
+Properties use the existing `codeBlock` document node with the `edgeever-frontmatter` language. No database migration is required. Older clients display the YAML as a code block; older codecs may serialize it as a fenced code block, which the new codec recognizes and exports as Front Matter again. Removing the panel or rolling back the client retains that readable representation.
+
+The codec has been checked against the actual `v1.105.0` source with new → old edit → new round trips. This does not replace packaged macOS, Windows, Linux, Android USB-device or iOS cross-version tests. Complete application-level cross-version validation remains required before release. Native Android/iOS editors currently display the property code block rather than the Web property panel.
+
+This feature does not implement Obsidian vault synchronization, property-specific search, a vault-wide property type registry or full support for Obsidian-specific Markdown extensions.
diff --git a/docs/markdown-properties.zh-CN.md b/docs/markdown-properties.zh-CN.md
new file mode 100644
index 00000000..c4ea3f3f
--- /dev/null
+++ b/docs/markdown-properties.zh-CN.md
@@ -0,0 +1,32 @@
+# Markdown 笔记属性
+
+文本笔记支持文件开头的 YAML Front Matter 属性头。在 Web 与桌面端富文本视图中,它显示为可折叠的「笔记属性」面板。仅已有属性头的文档显示该面板;普通笔记不增加属性入口。需要添加属性时,可在 Markdown 源码中编写属性头。面板支持文本、字符串列表(每行一个值)、数字、复选框和日期。嵌套属性保留可读展示,可通过 YAML 源码编辑。面板源码按钮与 Markdown 编辑器操作同一份文档数据。
+
+```markdown
+---
+title: 研究笔记
+tags: [archive, research]
+source: https://example.com/article
+author: [Alice, Bob]
+published: 2026-10-10
+description: 简短摘要
+custom:
+ reviewed: true
+---
+
+这里开始是笔记正文。
+```
+
+导入 `.md` 或 `.markdown` 文件时,会读取属性头的 `title` 和 `tags`。未提供有效标题时使用文件名。其他属性、注释与嵌套值保留在文档中。修改属性中的 `title` 和 `tags` 会同步现有笔记字段;修改原有字段时,也会同步已经存在的对应属性。删除属性仅将它从文档中移除,不会删除对应的应用字段。
+
+单篇导出(包括卡片右键导出)对普通笔记仅导出正文,不新增属性头。文档已有属性头时保留原有属性,并更新已存在的标题和标签,不额外添加系统字段。选中笔记与完整 ZIP 导出生成一个属性头,包含自定义属性和当前笔记元数据。应用中的标题、标签、笔记本、创建与更新时间、置顶状态和 ID 优先于导入的副本。这些系统属性(标题和标签除外)在面板中只读;修改 YAML 中的副本不会改变应用状态。`published` 为独立、可编辑的发布日期。导入 `edgeever_id` 不会覆盖已有笔记。
+
+非法 YAML、重复键、未知 YAML 类型标签、超过 64 KiB 的属性头或过度的别名展开,会显示错误并保留原文供修正。无效属性头导出时保持原样,避免丢失源码;修正为有效属性头后才合并应用元数据。普通 Markdown 分隔线、常规 YAML 代码示例和未闭合的属性头不会被识别为属性。属性不计入正文摘要和字数。
+
+## 兼容与回滚
+
+属性使用现有 `codeBlock` 文档节点及 `edgeever-frontmatter` 语言标记,无需数据库迁移。旧客户端会显示 YAML 代码块;旧编解码器可能将它序列化为围栏代码块,新编解码器能再次识别并导出为 Front Matter。撤回面板或回滚客户端后,这种可读形式仍保留。
+
+已使用真实 `v1.105.0` 源码检查「新版 → 旧版编辑 → 新版」编解码往返。这不能替代打包后的 macOS、Windows、Linux、Android USB 真机或 iOS 跨版本测试;发布前仍需完成应用级跨版本验证。Android/iOS 原生编辑器目前显示属性代码块,尚未提供 Web 属性面板。
+
+本功能不包含 Obsidian Vault 文件同步、属性专用检索、整个知识库统一的属性类型注册表或完整的 Obsidian 专属 Markdown 扩展支持。
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 95fefe64..9cd6c2d8 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -35,6 +35,7 @@
"@tiptap/starter-kit": "3.31.0",
"js-base64": "3.9.3",
"katex": "0.16.22",
+ "yaml": "2.8.3",
"zod": "4.4.3"
}
}
diff --git a/packages/shared/src/content.ts b/packages/shared/src/content.ts
index 7ed4586c..7a33b8b6 100644
--- a/packages/shared/src/content.ts
+++ b/packages/shared/src/content.ts
@@ -16,6 +16,7 @@ import { PluginEmbed, PLUGIN_EMBED_NODE_TYPE } from "./plugin-embed";
import { NEW_IMAGE_WIDTH_PERCENT, parseImageWidth } from "./image-display";
import { ImageGallery, IMAGE_GALLERY_NODE_TYPE, groupConsecutiveImagesIntoGalleries, normalizeImageGalleries } from "./image-gallery";
import { EMPTY_EXTERNAL_LINK_NODE_TYPE } from "./empty-external-link";
+import { FRONT_MATTER_LANGUAGE, createFrontMatterNode, getFrontMatterSource, splitMarkdownFrontMatter } from "./front-matter";
export { PluginEmbed, PLUGIN_EMBED_NODE_TYPE, pluginEmbedToMarkdown, normalizePluginEmbedAttributes } from "./plugin-embed";
export type { PluginEmbedAttributes } from "./plugin-embed";
@@ -142,10 +143,13 @@ export const markdownToDoc = (markdown: string): TiptapDoc => {
return emptyDoc();
}
- const parsed = markdownManager.parse(expandExtraBlankLinesForParse(normalized)) as TiptapDoc;
+ const header = splitMarkdownFrontMatter(normalized);
+ const parsed = markdownManager.parse(expandExtraBlankLinesForParse(header?.body ?? normalized)) as TiptapDoc;
return {
...parsed,
- content: groupConsecutiveImagesIntoGalleries(parsed.content.map(withDefaultImageWidths)),
+ content: [...(header ? [createFrontMatterNode(header.source)] : []),
+ ...groupConsecutiveImagesIntoGalleries(parsed.content.map(withDefaultImageWidths)),
+ ...(header && !parsed.content.length ? [{ type: "paragraph" }] : [])],
};
};
@@ -188,6 +192,7 @@ export const resolveMemoContentDoc = (
upgradeStandaloneFileLinks(upgradeStandalonePdfLinks(upgradeLegacyAttachmentLinks(contentJson))),
))
: emptyDoc();
+ if (getFrontMatterSource(currentDoc) !== null) return currentDoc;
if (
!contentMarkdown?.trim() ||
docContainsNodeType(currentDoc, "table") ||
@@ -207,6 +212,10 @@ export const resolveMemoContentDoc = (
}
const markdownDoc = markdownToDoc(contentMarkdown);
+ const properties = getFrontMatterSource(markdownDoc);
+ if (properties !== null) {
+ return !docToText(currentDoc) ? markdownDoc : { ...currentDoc, content: [createFrontMatterNode(properties), ...currentDoc.content] };
+ }
// Some older saves left an empty JSON document behind while retaining the
// real body in Markdown. Treat that as a compatibility case too; otherwise
// the editor can show the Markdown body while list excerpts see an empty
@@ -274,6 +283,8 @@ export const docToText = (doc: unknown): string => {
const current = node as { type?: unknown; text?: unknown; attrs?: Record<string, unknown>; content?: unknown };
+ if (current.type === "codeBlock" && current.attrs?.language === FRONT_MATTER_LANGUAGE) return;
+
if (typeof current.text === "string") {
pieces.push(current.text);
}
@@ -341,6 +352,8 @@ export const countMemoCharacters = (doc: unknown): number => {
const current = node as { type?: unknown; text?: unknown; attrs?: Record<string, unknown>; content?: unknown };
+ if (current.type === "codeBlock" && current.attrs?.language === FRONT_MATTER_LANGUAGE) return;
+
if (typeof current.text === "string") {
pieces.push(current.text);
}
@@ -376,12 +389,15 @@ export const docToMarkdown = (doc: unknown): string => {
return "";
}
+ const properties = getFrontMatterSource(doc as TiptapDoc);
+ const body = properties === null ? doc : { ...doc, content: root.content.slice(1) };
const serializableDoc = protectLiteralDollarPairs(projectNativeUnknownContentForMarkdown(
- stripEditorOnlyNodes(doc) as TiptapDoc
+ stripEditorOnlyNodes(body) as TiptapDoc
));
- return markdownManager
+ const markdown = markdownManager
.serialize(serializableDoc as Parameters<typeof markdownManager.serialize>[0])
.replaceAll(LITERAL_DOLLAR_PLACEHOLDER, "\\$");
+ return properties === null ? markdown : `---\n${properties}\n---\n\n${markdown}`;
};
const LITERAL_DOLLAR_PLACEHOLDER = "\uE000edgeever-dollar\uE001";
diff --git a/packages/shared/src/front-matter.test.mjs b/packages/shared/src/front-matter.test.mjs
new file mode 100644
index 00000000..04af9ecb
--- /dev/null
+++ b/packages/shared/src/front-matter.test.mjs
@@ -0,0 +1,86 @@
+import { describe, expect, test } from "bun:test";
+import { countMemoCharacters, docToText, docToMarkdown, markdownToDoc, resolveMemoContentDoc } from "./content.ts";
+import { createFrontMatterNode, getFrontMatterSource, getMappedNoteProperties, mergeMarkdownFrontMatter, parseNoteProperties, splitMarkdownFrontMatter, updateNoteProperty } from "./front-matter.ts";
+
+describe("note properties", () => {
+ const header = '# retained comment\ntitle: "Imported note"\ntags: [archive, research]\nauthor: [Alice, Bob]\nsource: https://example.com\npublished: 2026-10-10\ndescription: |\n First line\n Second line\nnested:\n custom: true';
+ const markdown = `---\n${header}\n---\n\n# Body\n\nText **and** a [link](https://example.com).`;
+
+ test("preserves raw YAML, unknown properties, lists, dates and comments across mode switches", () => {
+ const doc = markdownToDoc(markdown);
+ expect(getFrontMatterSource(doc)).toBe(header);
+ expect(doc.content[1].type).toBe("heading");
+ expect(getFrontMatterSource(markdownToDoc(docToMarkdown(doc)))).toBe(header);
+ expect(parseNoteProperties(header).values.nested).toEqual({ custom: true });
+ });
+
+ test("edits individual properties without destroying comments or unknown nested data", () => {
+ const next = updateNoteProperty(header, "source", "https://new.example.com");
+ expect(next).toContain("# retained comment");
+ expect(parseNoteProperties(next).values).toMatchObject({ author: ["Alice", "Bob"], nested: { custom: true }, source: "https://new.example.com" });
+ });
+
+ test("maps title and tags without accepting IDs or arbitrary system metadata", () => {
+ expect(getMappedNoteProperties({ title: " Note ", tags: "#one, two one", edgeever_id: "foreign" })).toEqual({ title: "Note", tags: ["one", "two"] });
+ expect(getMappedNoteProperties({ title: 12, tags: ["valid", 4] })).toEqual({});
+ });
+
+ test("merges export metadata into one header while preserving the body and custom fields", () => {
+ const exported = mergeMarkdownFrontMatter(markdown, { title: "Current note", tags: ["new"], edgeever_id: "current" });
+ const split = splitMarkdownFrontMatter(exported);
+ expect(split.values).toMatchObject({ title: "Current note", tags: ["new"], author: ["Alice", "Bob"], nested: { custom: true }, edgeever_id: "current" });
+ expect(split.body).toBe(splitMarkdownFrontMatter(markdown).body);
+ expect(exported.match(/^---$/gm)).toHaveLength(2);
+ });
+
+ test("does not mistake ordinary Markdown rules or unclosed headers for properties", () => {
+ for (const source of ["---\nHeading\n---\nBody", "---\ntitle: unfinished", "Body\n---\ntitle: body\n---", "```yaml\ntitle: example\n```", "---\n- list item\n---"]) {
+ expect(splitMarkdownFrontMatter(source)).toBeNull();
+ }
+ });
+
+ test("supports BOM, CRLF, empty headers and YAML closing markers", () => {
+ expect(splitMarkdownFrontMatter("\uFEFF---\r\ntitle: Example\r\n...\r\nBody").values.title).toBe("Example");
+ expect(parseNoteProperties("").values).toEqual({});
+ expect(getFrontMatterSource(markdownToDoc("---\n\n---\nBody"))).toBe("");
+ expect(getFrontMatterSource(markdownToDoc("---\n---\nBody"))).toBe("");
+ });
+
+ test("keeps malformed and duplicate-key YAML recoverable instead of silently flattening it", () => {
+ for (const source of ["title: [unclosed", "title: One\ntitle: Two", "nested: !unknown value"]) {
+ const original = `---\n${source}\n---\n\nBody`;
+ expect(splitMarkdownFrontMatter(original).error).toBeTruthy();
+ expect(getFrontMatterSource(markdownToDoc(original))).toBe(source);
+ expect(docToMarkdown(markdownToDoc(original))).toStartWith(`---\n${source}\n---`);
+ expect(mergeMarkdownFrontMatter(original, { title: "New" })).toBe(original);
+ }
+ });
+
+ test("limits oversized headers and alias expansion without losing raw source", () => {
+ expect(parseNoteProperties(`key: ${"a".repeat(65536)}`).error).toBeTruthy();
+ expect(parseNoteProperties("recursive: &self [*self]").error).toBeTruthy();
+ expect(parseNoteProperties("a: &a [1, 2]\nb: &b [*a, *a, *a, *a]\nc: [*b, *b, *b, *b, *b, *b, *b, *b, *b, *b]").error).toBeTruthy();
+ });
+
+ test("recovers properties saved by an old codec as a regular code fence", () => {
+ const oldMarkdown = `\`\`\`edgeever-frontmatter\n${header}\n\`\`\`\n\nBody`;
+ const doc = markdownToDoc(oldMarkdown);
+ expect(getFrontMatterSource(doc)).toBe(header);
+ expect(docToMarkdown(doc)).toStartWith(`---\n${header}\n---`);
+ expect(resolveMemoContentDoc(doc, oldMarkdown)).toEqual(doc);
+ const exported = mergeMarkdownFrontMatter(oldMarkdown, { title: "Current title" });
+ expect(splitMarkdownFrontMatter(exported).values.author).toEqual(["Alice", "Bob"]);
+ expect(exported).not.toContain("```edgeever-frontmatter");
+ });
+
+ test("keeps richer JSON body attributes when properties are present", () => {
+ const doc = { type: "doc", content: [createFrontMatterNode(header), { type: "image", attrs: { src: "https://example.com/image.png", width: "80%" } }] };
+ expect(resolveMemoContentDoc(doc, docToMarkdown(doc))).toEqual(doc);
+ });
+
+ test("keeps metadata out of body excerpts and character counts", () => {
+ const doc = markdownToDoc(`---\n${header}\n---\n\nHello world`);
+ expect(docToText(doc)).toBe("Hello world");
+ expect(countMemoCharacters(doc)).toBe(10);
+ });
+});
diff --git a/packages/shared/src/front-matter.ts b/packages/shared/src/front-matter.ts
new file mode 100644
index 00000000..bbfaf701
--- /dev/null
+++ b/packages/shared/src/front-matter.ts
@@ -0,0 +1,79 @@
+import { isMap, parseDocument } from "yaml";
+import type { TiptapDoc, TiptapNode } from "./content";
+
+// An existing schema node keeps properties readable in older clients.
+export const FRONT_MATTER_LANGUAGE = "edgeever-frontmatter";
+const MAX_PROPERTY_SOURCE_LENGTH = 64 * 1024;
+
+export const parseNoteProperties = (source: string) => {
+ try {
+ if (source.length > MAX_PROPERTY_SOURCE_LENGTH) throw new Error("Properties exceed 64 KiB.");
+ const document = parseDocument(source, { stringKeys: true, prettyErrors: false });
+ if (document.errors.length || document.warnings.length) {
+ throw new Error([...document.errors, ...document.warnings].map((error) => error.message).join("\n"));
+ }
+ if (document.contents !== null && !isMap(document.contents)) throw new Error("Properties must be a YAML mapping.");
+ const values = document.toJS({ maxAliasCount: 50 }) as Record<string, unknown> | null;
+ // Recursive YAML aliases cannot be displayed or persisted as JSON values.
+ JSON.stringify(values);
+ return { document, values: values ?? {}, error: null };
+ } catch (error) {
+ return { document: null, values: null, error: error instanceof Error ? error.message : String(error) };
+ }
+};
+
+/** Only a leading, closed property header is special; ordinary rules stay Markdown. */
+export const splitMarkdownFrontMatter = (markdown: string) => {
+ const legacy = /^(`{3,}|~{3,})edgeever-frontmatter[ \t]*\r?\n([\s\S]*?)^\1[ \t]*(?:\r?\n|$)/m.exec(markdown);
+ if (legacy?.index === 0) {
+ const source = legacy[2]!.replace(/\r?\n$/, "").replace(/\r\n?/g, "\n");
+ return { source, body: markdown.slice(legacy[0].length), ...parseNoteProperties(source) };
+ }
+ const match = /^(?:\uFEFF)?---[ \t]*\r?\n([\s\S]*?)^(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/m.exec(markdown);
+ if (!match || match.index !== 0) return null;
+ const source = match[1]!.replace(/\r?\n$/, "").replace(/\r\n?/g, "\n");
+ const parsed = parseNoteProperties(source);
+ // Don't turn `---\nA paragraph\n---` into a properties panel.
+ if (parsed.error && !source.includes(":")) return null;
+ return { source, body: markdown.slice(match[0].length), ...parsed };
+};
+
+export const isFrontMatterNode = (node: TiptapNode | undefined) =>
+ node?.type === "codeBlock" && node.attrs?.language === FRONT_MATTER_LANGUAGE;
+
+export const getFrontMatterSource = (doc: TiptapDoc) => isFrontMatterNode(doc.content[0])
+ ? doc.content[0]!.content?.map((node) => "text" in node && typeof node.text === "string" ? node.text : "").join("") ?? ""
+ : null;
+
+export const createFrontMatterNode = (source: string): TiptapNode => ({
+ type: "codeBlock", attrs: { language: FRONT_MATTER_LANGUAGE },
+ ...(source ? { content: [{ type: "text", text: source }] } : {}),
+});
+
+/** Modify the YAML AST so untouched comments, unknown keys and nested values survive. */
+export const updateNoteProperty = (source: string, name: string, value: unknown, remove = false) => {
+ const { document, error } = parseNoteProperties(source);
+ if (!document) throw new Error(error ?? "Invalid properties.");
+ if (remove) document.delete(name);
+ else document.set(name, value);
+ return document.toString({ lineWidth: 0 }).trimEnd();
+};
+
+export const getMappedNoteProperties = (values: Record<string, unknown>) => {
+ const title = typeof values.title === "string" && values.title.trim().length <= 160 ? values.title.trim() : undefined;
+ const rawTags = typeof values.tags === "string" ? values.tags.split(/[\s,]+/) : values.tags;
+ const tags = Array.isArray(rawTags) && rawTags.every((tag) => typeof tag === "string")
+ ? [...new Set(rawTags.map((tag: string) => tag.trim().replace(/^#/, "")).filter(Boolean))]
+ : undefined;
+ return { ...(title !== undefined ? { title } : {}), ...(tags !== undefined ? { tags } : {}) };
+};
+
+/** Export one header, with live application metadata taking precedence over imported copies. */
+export const mergeMarkdownFrontMatter = (markdown: string, metadata: Record<string, unknown>) => {
+ const split = splitMarkdownFrontMatter(markdown);
+ // An invalid header must remain recoverable verbatim.
+ if (split?.error) return markdown;
+ let source = split?.source ?? "";
+ for (const [key, value] of Object.entries(metadata)) source = updateNoteProperty(source, key, value);
+ return `---\n${source}\n---\n\n${(split?.body ?? markdown).replace(/^\r?\n/, "")}`;
+};
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 8da3980f..c88f491e 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -2,6 +2,7 @@ import { memoTemplateSeedTranslations } from "../memo-template-seeds";
// Shared by the PWA and native mobile clients.
export const enUS = {
+ noteProperties: {"heading": "Note properties", "source": "Show YAML source", "name": "Property name", "type": "Property type", "add": "Add property", "remove": "Remove {{name}}", "invalidName": "Use a unique name that is not a system property.", "invalidYaml": "Properties need attention:", "invalidNumber": "Enter a valid number.", "listHint": "One value per line", "text": "Text", "list": "List", "number": "Number", "checkbox": "Checkbox", "date": "Date"},
infographic: {
name: "Infographic", autoLayout: "Auto layout", describe: "Describe and generate", chooseTemplate: "Choose a template and fill content",
prompt: "Describe the information, structure, and key points", generate: "Generate infographic", generating: "Generating…",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index 479211f2..925a249a 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -2,6 +2,7 @@ import { memoTemplateSeedTranslations } from "../memo-template-seeds";
// Shared by the PWA and native mobile clients.
export const ja = {
+ noteProperties: {"heading": "ノートのプロパティ", "source": "YAML ソースを表示", "name": "プロパティ名", "type": "プロパティの種類", "add": "プロパティを追加", "remove": "{{name}} を削除", "invalidName": "重複しない、システム予約名以外の名前を入力してください。", "invalidYaml": "プロパティを確認してください:", "invalidNumber": "有効な数値を入力してください。", "listHint": "1 行に 1 つの値", "text": "テキスト", "list": "リスト", "number": "数値", "checkbox": "チェックボックス", "date": "日付"},
infographic: {
name: "インフォグラフィック", autoLayout: "自動配置", describe: "説明して生成", chooseTemplate: "テンプレートを選んで入力",
prompt: "表示したい情報、構成、要点を説明してください", generate: "インフォグラフィックを生成", generating: "生成中…",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index e8528307..8949e3ec 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -2,6 +2,7 @@ import { memoTemplateSeedTranslations } from "../memo-template-seeds";
// Shared by the PWA and native mobile clients.
export const pl = {
+ noteProperties: {"heading": "Właściwości notatki", "source": "Pokaż źródło YAML", "name": "Nazwa właściwości", "type": "Typ właściwości", "add": "Dodaj właściwość", "remove": "Usuń {{name}}", "invalidName": "Użyj unikalnej nazwy, która nie jest właściwością systemową.", "invalidYaml": "Sprawdź właściwości:", "invalidNumber": "Wprowadź poprawną liczbę.", "listHint": "Jedna wartość w wierszu", "text": "Tekst", "list": "Lista", "number": "Liczba", "checkbox": "Pole wyboru", "date": "Data"},
infographic: {
name: "Infografika", autoLayout: "Układ automatyczny", describe: "Opisz i wygeneruj", chooseTemplate: "Wybierz szablon i uzupełnij treść",
prompt: "Opisz informacje, strukturę i kluczowe punkty", generate: "Wygeneruj infografikę", generating: "Generowanie…",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index f593a235..20fd0145 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -2,6 +2,7 @@ import { memoTemplateSeedTranslations } from "../memo-template-seeds";
// Shared by the PWA and native mobile clients.
export const zhCN = {
+ noteProperties: {"heading": "笔记属性", "source": "显示 YAML 源码", "name": "属性名称", "type": "属性类型", "add": "添加属性", "remove": "删除 {{name}}", "invalidName": "请输入不重复且非系统保留的属性名称。", "invalidYaml": "请检查笔记属性:", "invalidNumber": "请输入有效数字。", "listHint": "每行一个值", "text": "文本", "list": "列表", "number": "数字", "checkbox": "复选框", "date": "日期"},
infographic: {
name: "信息图", autoLayout: "自动排版", describe: "描述内容并生成", chooseTemplate: "选择模板手动填内容",
prompt: "描述你想呈现的信息、结构与重点", generate: "生成信息图", generating: "正在生成…",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 2d4abbf6..bce25992 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -60,3 +60,4 @@ export {
} from "./diagram-reader";
export { attachDiagramScroll } from "./diagram-scroll";
+export * from "./front-matter";
diff --git a/tests/json-backup.test.ts b/tests/json-backup.test.ts
index 869cca27..36090ed4 100644
--- a/tests/json-backup.test.ts
+++ b/tests/json-backup.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from "bun:test";
import type { AiPromptTemplate, JsonBackupMemo, JsonBackupNotebook, MemoDetail, Notebook, Resource } from "@edgeever/shared";
+import { splitMarkdownFrontMatter } from "@edgeever/shared";
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
import {
createEdgeEverZip,
@@ -161,7 +162,7 @@ describe("EdgeEver ZIP", () => {
const files = unzipSync(new Uint8Array(await blob.arrayBuffer()));
expect(Array.from(files[backup.memos[0].resources[0].archivePath])).toEqual([1, 2, 3]);
const markdown = strFromU8(files["notes/Root/Child/Backup note.md"]);
- expect(markdown).toContain("edgeever_id: \"memo_backup\"");
+ expect(splitMarkdownFrontMatter(markdown)?.values?.edgeever_id).toBe("memo_backup");
expect(markdown).toContain("![asset](Backup%20note.assets/asset.png)");
expect(backup.memos[0].resources[0].archivePath).toBe("notes/Root/Child/Backup note.assets/asset.png");
});
diff --git a/tests/note-markdown-export.test.ts b/tests/note-markdown-export.test.ts
index 364d6cd6..98f6fabc 100644
--- a/tests/note-markdown-export.test.ts
+++ b/tests/note-markdown-export.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, test } from "bun:test";
+import { splitMarkdownFrontMatter } from "@edgeever/shared";
import {
buildMarkdownFilename,
+ buildSingleNoteMarkdown,
createMarkdownFile,
} from "../apps/web/src/lib/note-markdown-export";
@@ -20,3 +22,35 @@ describe("single-note Markdown export", () => {
expect(buildMarkdownFilename("README.md", "Untitled note")).toBe("README.md");
});
});
+
+describe("single-note Markdown properties", () => {
+ test("ordinary notes export only their body", async () => {
+ const body = "# Article\n\nBody with **formatting**.\n";
+ const markdown = buildSingleNoteMarkdown(body, "Article", ["work"]);
+ expect(markdown).toBe(body);
+ expect(await createMarkdownFile(markdown, "Article", "Untitled").blob.text()).toBe(body);
+ });
+
+ test("retains comments and custom properties while updating existing title and tags", () => {
+ const markdown = buildSingleNoteMarkdown("---\n# Preserve this comment\ntitle: Old\ntags: [old]\nauthor: Alice\ncustom:\n reviewed: true\n---\n\nBody", "New", ["new"]);
+ const header = splitMarkdownFrontMatter(markdown)!;
+ expect(header.values).toEqual({ title: "New", tags: ["new"], author: "Alice", custom: { reviewed: true } });
+ expect(header.source).toContain("# Preserve this comment");
+ expect(header.body.trim()).toBe("Body");
+ });
+
+ test("does not add title, tags or system fields to a custom-only header", () => {
+ const markdown = "---\nsource: https://example.com\n---\n\nBody";
+ expect(buildSingleNoteMarkdown(markdown, "Article", ["work"])).toBe(markdown);
+ });
+
+ test("retains original system fields without replacing or supplementing them", () => {
+ const markdown = buildSingleNoteMarkdown("---\ntitle: Old\ncreated: 2020-01-01\nedgeever_id: original\n---\n\nBody", "New", ["work"]);
+ expect(splitMarkdownFrontMatter(markdown)!.values).toEqual({ title: "New", created: "2020-01-01", edgeever_id: "original" });
+ });
+
+ test("invalid properties remain recoverable verbatim", () => {
+ const markdown = "---\ntitle: [broken\n---\n\nBody";
+ expect(buildSingleNoteMarkdown(markdown, "Article", [])).toBe(markdown);
+ });
+});