Skip to content

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

revert: remove automatic note title derivation

tianma-iff00c98c355ee
diff --git a/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift b/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift
index 4855c2b7..ed24111f 100644
--- a/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift
+++ b/apps/ios/EdgeEver/Features/Workspace/MemoEditView.swift
@@ -289,7 +289,6 @@ struct MemoEditView: View {
}
.task {
await loadInitial()
- viewModel.beginTitleDerivationSession()
contentHydrated = true
// editorReady flips true from TipTap onBodyReady (or fallback below).
try? await Task.sleep(nanoseconds: 800_000_000)
@@ -429,10 +428,7 @@ struct MemoEditView: View {
env.preferences.t("无标题笔记", en: "Untitled note"),
text: Binding(
get: { viewModel.title },
- set: {
- viewModel.userEditedTitle($0)
- markDirtyAndScheduleSave()
- }
+ set: { viewModel.title = $0 }
)
)
.font(.system(size: 28, weight: .heavy))
@@ -440,6 +436,7 @@ struct MemoEditView: View {
.textFieldStyle(.plain)
.padding(.top, 14)
.padding(.bottom, 8)
+ .onChange(of: title) { _, _ in markDirtyAndScheduleSave() }
.accessibilityLabel(env.preferences.t("笔记标题", en: "Note title"))
.accessibilityIdentifier(CreateMemoChrome.title)
@@ -819,7 +816,6 @@ struct MemoEditView: View {
private func applyTemplateSeed(_ seed: CreateMemoSeed) {
title = seed.title
- viewModel.beginTitleDerivationSession()
tagsText = seed.tagsText
contentMarkdown = seed.contentMarkdown
// Empty stub JSON forces TipTapContentSource to open from markdown structure.
diff --git a/apps/ios/EdgeEver/Features/Workspace/MemoEditViewModel.swift b/apps/ios/EdgeEver/Features/Workspace/MemoEditViewModel.swift
index 7b4e426e..52546774 100644
--- a/apps/ios/EdgeEver/Features/Workspace/MemoEditViewModel.swift
+++ b/apps/ios/EdgeEver/Features/Workspace/MemoEditViewModel.swift
@@ -25,7 +25,6 @@ final class MemoEditViewModel {
var suppressPersistence = false
var contentHydrated = false
var baselineMarkdown = ""
- private(set) var titleDerivationEligible = false
@ObservationIgnored private var saveTask: Task<Void, Never>?
var tags: [String] {
@@ -44,45 +43,6 @@ final class MemoEditViewModel {
isDirty = true
}
- func beginTitleDerivationSession() {
- titleDerivationEligible = title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
- }
-
- func userEditedTitle(_ nextTitle: String) {
- titleDerivationEligible = false
- title = nextTitle
- }
-
- private func deriveTitleIfEligible(from json: String) {
- guard titleDerivationEligible,
- let data = json.data(using: .utf8),
- let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
- let blocks = root["content"] as? [[String: Any]]
- else { return }
-
- for block in blocks {
- let text = Self.nodeText(block)
- .split(whereSeparator: { $0.isWhitespace })
- .joined(separator: " ")
- if text.isEmpty {
- let type = block["type"] as? String
- if type == "paragraph" || type == "heading" { continue }
- }
- guard block["type"] as? String == "heading",
- let attrs = block["attrs"] as? [String: Any],
- (attrs["level"] as? NSNumber)?.intValue == 1
- else { return }
- title = String(text.prefix(160))
- return
- }
- }
-
- private static func nodeText(_ node: [String: Any]) -> String {
- let own = node["text"] as? String ?? ""
- let children = (node["content"] as? [[String: Any]] ?? []).map(nodeText).joined()
- return own + children
- }
-
func scheduleSave(
delayNanoseconds: UInt64 = 500_000_000,
operation: @escaping @MainActor () async -> Void
@@ -185,7 +145,6 @@ final class MemoEditViewModel {
contentJSON = nextJSON
contentMarkdown = nextMarkdown
- deriveTitleIfEligible(from: nextJSON)
}
func wouldClobberNonEmptyBody(isCreate: Bool) -> Bool {
diff --git a/apps/ios/Tests/EdgeEverTests/MemoEditViewModelTests.swift b/apps/ios/Tests/EdgeEverTests/MemoEditViewModelTests.swift
index 8aa1e97e..2219bc5d 100644
--- a/apps/ios/Tests/EdgeEverTests/MemoEditViewModelTests.swift
+++ b/apps/ios/Tests/EdgeEverTests/MemoEditViewModelTests.swift
@@ -38,52 +38,6 @@ final class MemoEditViewModelTests: XCTestCase {
XCTAssertTrue(EditorContentCodec.jsonContainsResource(model.contentJSON, src: "/api/v1/resources/image/blob"))
}
- func testDerivesTitleWhileTypingFirstH1AndStopsNextSession() {
- let model = MemoEditViewModel()
- model.beginTitleDerivationSession()
- model.applyEditorPayload(
- markdown: "# Product plan\n\nBody",
- json: "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\"},{\"type\":\"heading\",\"attrs\":{\"level\":1},\"content\":[{\"type\":\"text\",\"text\":\"Product plan\"}]}]}"
- )
- XCTAssertEqual(model.title, "Product plan")
-
- model.applyEditorPayload(
- markdown: "# Renamed heading",
- json: "{\"type\":\"doc\",\"content\":[{\"type\":\"heading\",\"attrs\":{\"level\":1},\"content\":[{\"type\":\"text\",\"text\":\"Renamed heading\"}]}]}"
- )
- XCTAssertEqual(model.title, "Renamed heading")
-
- let reopened = MemoEditViewModel()
- reopened.title = model.title
- reopened.beginTitleDerivationSession()
- reopened.applyEditorPayload(
- markdown: "# Later edit",
- json: "{\"type\":\"doc\",\"content\":[{\"type\":\"heading\",\"attrs\":{\"level\":1},\"content\":[{\"type\":\"text\",\"text\":\"Later edit\"}]}]}"
- )
- XCTAssertEqual(reopened.title, "Renamed heading")
- }
-
- func testDoesNotDeriveTitleFromH1AfterBodyContent() {
- let model = MemoEditViewModel()
- model.beginTitleDerivationSession()
- model.applyEditorPayload(
- markdown: "Intro\n\n# Product plan",
- json: "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"Intro\"}]},{\"type\":\"heading\",\"attrs\":{\"level\":1},\"content\":[{\"type\":\"text\",\"text\":\"Product plan\"}]}]}"
- )
- XCTAssertEqual(model.title, "")
- }
-
- func testDoesNotDeriveTitleAfterManualTitleEdit() {
- let model = MemoEditViewModel()
- model.beginTitleDerivationSession()
- model.userEditedTitle("")
- model.applyEditorPayload(
- markdown: "# Product plan",
- json: "{\"type\":\"doc\",\"content\":[{\"type\":\"heading\",\"attrs\":{\"level\":1},\"content\":[{\"type\":\"text\",\"text\":\"Product plan\"}]}]}"
- )
- XCTAssertEqual(model.title, "")
- }
-
func testDebouncedSaveKeepsOnlyLatestOperation() async {
let model = MemoEditViewModel()
model.markDirty()
diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsx
index 0d74ee1d..c02a1889 100644
--- a/apps/mobile/src/screens/WorkspaceScreen.tsx
+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx
@@ -70,7 +70,7 @@ import { Alert, Pressable, Text, TextInput } from "../components/LocalizedText";
import Markdown, { type ASTNode, type RenderRules } from "react-native-markdown-display";
import { SvgXml } from "react-native-svg";
import { ApiRequestError } from "@edgeever/client";
-import { buildGitHubFeedbackUrl, createExcerpt, DEFAULT_MEMO_TITLE, deriveMemoTitleDuringInitialEdit, docToMarkdown, docToText, getNotebookDescendantIds, markdownToDoc, resolveMemoContentDoc, type AuthUser, type MemoDetail, type MemoRevision, type MemoSummary, type Notebook, type TiptapDoc } from "@edgeever/shared";
+import { buildGitHubFeedbackUrl, createExcerpt, DEFAULT_MEMO_TITLE, docToMarkdown, docToText, getNotebookDescendantIds, markdownToDoc, resolveMemoContentDoc, type AuthUser, type MemoDetail, type MemoRevision, type MemoSummary, type Notebook, type TiptapDoc } from "@edgeever/shared";
import { MOBILE_UI_METRICS, getMobileCenteredScrollOffset, getMobileNotebookSearchVisibleIds, toggleMobileMemoFilterMode, toggleMobileMemoSelection } from "@edgeever/shared/mobile-ui";
import { clearMobileMemoDraft, clearMobileNewMemoDraft, readMobileMemoDraft, writeMobileMemoDraft, type MobileMemoDraft } from "../lib/mobile-drafts";
import {
@@ -2136,7 +2136,6 @@ const CreateMemoModal = ({
const targetNotebookId = notebookId || fallbackNotebookId;
const selectedNotebookName = notebooks.find((notebook) => notebook.id === targetNotebookId)?.name ?? "选择笔记本";
const titleRef = useRef(title);
- const titleDerivationEligibleRef = useRef(!initialDraft?.title.trim());
const tagsTextRef = useRef(tagsText);
const targetNotebookIdRef = useRef(targetNotebookId);
const userEditedSinceOpenRef = useRef(false);
@@ -2271,8 +2270,6 @@ const CreateMemoModal = ({
contentMarkdownRef.current = markdown;
contentJsonRef.current = doc;
setTitle(seed.title);
- titleRef.current = seed.title;
- titleDerivationEligibleRef.current = !seed.title.trim();
setTagsText(seed.tagsText);
setContentMarkdown(markdown);
draftVersionRef.current += 1;
@@ -2567,13 +2564,6 @@ const CreateMemoModal = ({
}}
onChange={async (contentJson) => {
contentJsonRef.current = contentJson;
- if (titleDerivationEligibleRef.current) {
- const derivedTitle = deriveMemoTitleDuringInitialEdit(titleRef.current, contentJson, true);
- if (derivedTitle) {
- titleRef.current = derivedTitle;
- setTitle(derivedTitle);
- }
- }
const markdown = docToMarkdown(contentJson);
contentMarkdownRef.current = markdown;
setContentMarkdown(markdown);
@@ -2635,7 +2625,6 @@ const CreateMemoModal = ({
autoCorrect
accessibilityLabel="笔记标题"
onChangeText={(value) => {
- titleDerivationEligibleRef.current = false;
setTitle(value);
markDirty();
}}
@@ -2936,7 +2925,6 @@ const RichEditorModal = ({
const notebookLabel = notebooks.find((notebook) => notebook.id === notebookId)?.name ?? "未分类";
const saveLabel = error ? "保存失败" : saving ? "保存中" : uploading ? "上传中" : dirty ? (draftRestored ? "本地草稿" : "未保存") : ready ? "已保存" : "加载中";
const titleRef = useRef(title);
- const titleDerivationEligibleRef = useRef(!title.trim());
const tagsTextRef = useRef(tagsText);
const notebookIdRef = useRef(notebookId);
titleRef.current = title;
@@ -2974,13 +2962,6 @@ const RichEditorModal = ({
}
contentSnapshotRef.current = contentSnapshot;
contentJsonRef.current = contentJson;
- if (titleDerivationEligibleRef.current) {
- const derivedTitle = deriveMemoTitleDuringInitialEdit(titleRef.current, contentJson, true);
- if (derivedTitle) {
- titleRef.current = derivedTitle;
- setTitle(derivedTitle);
- }
- }
contentMarkdownRef.current = docToMarkdown(contentJson);
dirtyRef.current = true;
setDirty(true);
@@ -3238,7 +3219,6 @@ const RichEditorModal = ({
<View style={styles.richEditorContainer}>
<TextInput
onChangeText={(value) => {
- titleDerivationEligibleRef.current = false;
setTitle(value);
dirtyRef.current = true;
setDirty(true);
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index e0eb4b2f..923e9180 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -126,7 +126,6 @@ import { cn, formatDateTime, parseTagsText } from "@/lib/utils";
import { EDITOR_CONTENT_MAX_WIDTH, EDITOR_CONTENT_MAX_WIDTH_COLLAPSED } from "@/lib/workspace-ui";
import {
countMemoCharacters,
- deriveMemoTitleDuringInitialEdit,
docToMarkdown,
MEMO_CONTENT_STYLE,
markdownToDoc,
@@ -954,9 +953,6 @@ const RichEditorPane = ({
}, [desktopReadingProtection]);
const memoRef = useRef<MemoDetail | null>(memo);
- const titleRef = useRef(title);
- const titleDerivationEligibleRef = useRef(false);
- const titleWasAutoDerivedRef = useRef(false);
const editSessionRef = useRef<MemoEditSession | null>(null);
const editorRef = useRef<Editor | null>(null);
const editorCanvasInteractionVersionRef = useRef(0);
@@ -1001,25 +997,6 @@ const RichEditorPane = ({
"external-link": "",
},
});
- titleRef.current = title;
-
- const maybeDeriveMemoTitle = useCallback((contentJson: TiptapDoc, finalize = false) => {
- if (
- !titleDerivationEligibleRef.current ||
- (titleRef.current.trim() && !titleWasAutoDerivedRef.current)
- ) return titleRef.current;
- const derivedTitle = deriveMemoTitleDuringInitialEdit(
- titleRef.current,
- contentJson,
- titleWasAutoDerivedRef.current,
- );
- if (!derivedTitle) return titleRef.current;
- titleWasAutoDerivedRef.current = true;
- titleRef.current = derivedTitle;
- setTitle(derivedTitle);
- if (finalize) titleDerivationEligibleRef.current = false;
- return derivedTitle;
- }, []);
slashCommandLabelsRef.current = {
menu: t("slashMenu.menu"),
empty: t("slashMenu.empty"),
@@ -2201,12 +2178,7 @@ const RichEditorPane = ({
return;
}
- const refreshToolbar = () => {
- setEditorStateVersion((version) => version + 1);
- if (titleWasAutoDerivedRef.current && !editor.isActive("heading", { level: 1 })) {
- titleDerivationEligibleRef.current = false;
- }
- };
+ const refreshToolbar = () => setEditorStateVersion((version) => version + 1);
editor.on("selectionUpdate", refreshToolbar);
editor.on("transaction", refreshToolbar);
@@ -2554,9 +2526,6 @@ const RichEditorPane = ({
setHydratedEditorMemoId(null);
editingMemoIdRef.current = null;
setHasUnsavedChanges(false);
- titleDerivationEligibleRef.current = false;
- titleWasAutoDerivedRef.current = false;
- titleRef.current = "";
setTitle("");
setTagsText("");
setMobilePlainText("");
@@ -2723,9 +2692,6 @@ const RichEditorPane = ({
setSaveConflictInfo(null);
}
setTitle(nextTitle);
- titleRef.current = nextTitle;
- titleDerivationEligibleRef.current = !nextTitle.trim();
- titleWasAutoDerivedRef.current = false;
setTagsText(nextTagsText);
setMobilePlainText(nextMarkdown);
setMarkdownSource(nextMarkdown);
@@ -2813,12 +2779,7 @@ const RichEditorPane = ({
if (hydratingRef.current || memoRef.current?.isDeleted) {
return;
}
- const contentJson = editor.getJSON() as TiptapDoc;
- const nextTitle = maybeDeriveMemoTitle(
- contentJson,
- titleWasAutoDerivedRef.current && !editor.isActive("heading", { level: 1 }),
- );
- persistCurrentDraft(nextTitle);
+ persistCurrentDraft();
markDirty();
};
@@ -2826,7 +2787,7 @@ const RichEditorPane = ({
return () => {
editor.off("update", persistDraft);
};
- }, [editor, markDirty, maybeDeriveMemoTitle, memo, persistCurrentDraft]);
+ }, [editor, markDirty, memo, persistCurrentDraft]);
useEffect(() => {
const advanceMemoSyncBase = (syncedMemo: MemoDetail | null | undefined) => {
@@ -2940,9 +2901,8 @@ const RichEditorPane = ({
const handleMarkdownSourceChange = useCallback((value: string) => {
setMarkdownSource(value);
- maybeDeriveMemoTitle(markdownToDoc(value));
markDirty();
- }, [markDirty, maybeDeriveMemoTitle]);
+ }, [markDirty]);
const handleCopyToWeChat = useCallback(async () => {
if (!isEditorReady(editor)) {
@@ -3699,7 +3659,6 @@ const RichEditorPane = ({
};
const handleNativeInput = (event: Event) => {
mobileImeDebugRecorderRef.current(event.type, event);
- maybeDeriveMemoTitle(markdownToDoc(getMobilePlainTextElementValue(plainTextElement)));
markMobilePlainTextDirtyRef.current();
};
@@ -3723,7 +3682,7 @@ const RichEditorPane = ({
plainTextElement.removeEventListener("compositionend", recordNativeEvent);
plainTextElement.removeEventListener("input", handleNativeInput);
};
- }, [maybeDeriveMemoTitle, useMobilePlainTextEditor]);
+ }, [useMobilePlainTextEditor]);
useEffect(() => () => clearMobileEditorTimers(), [clearMobileEditorTimers]);
@@ -4000,7 +3959,6 @@ const RichEditorPane = ({
const nextValue = `${currentText}${currentText ? "\n" : ""}${nextText}`;
setMobilePlainText(nextValue);
setMobilePlainTextElementValue(mobileTextAreaRef.current, nextValue);
- maybeDeriveMemoTitle(markdownToDoc(nextValue));
markMobilePlainTextDirty();
recordMobileImeDebugEvent(eventName);
window.requestAnimationFrame(() => focusMobileInputTarget());
@@ -4608,9 +4566,6 @@ const RichEditorPane = ({
value={title}
readOnly={effectiveReadOnly}
onChange={(event) => {
- titleDerivationEligibleRef.current = false;
- titleWasAutoDerivedRef.current = false;
- titleRef.current = event.target.value;
setTitle(event.target.value);
persistCurrentDraft(event.target.value, tagsText, getMobilePlainTextValue());
markDirty();
diff --git a/apps/web/src/components/MobileStandaloneTiptapEditor.tsx b/apps/web/src/components/MobileStandaloneTiptapEditor.tsx
index 60867c2e..11162eac 100644
--- a/apps/web/src/components/MobileStandaloneTiptapEditor.tsx
+++ b/apps/web/src/components/MobileStandaloneTiptapEditor.tsx
@@ -10,7 +10,7 @@ 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, deriveMemoTitleDuringInitialEdit, docToMarkdown, docToText, emptyDoc, getImageReferrerPolicy, isPdfAttachment, 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 {
@@ -93,8 +93,6 @@ export const MobileStandaloneTiptapEditor = ({
const [notebookSheetOpen, setNotebookSheetOpen] = useState(false);
const [title, setTitle] = useState("");
const titleRef = useRef("");
- const titleDerivationEligibleRef = useRef(false);
- const titleWasAutoDerivedRef = useRef(false);
const [tagsText, setTagsText] = useState("");
const tagsTextRef = useRef("");
const contentJsonRef = useRef<TiptapDoc>(emptyDoc());
@@ -113,23 +111,6 @@ export const MobileStandaloneTiptapEditor = ({
const backgroundSavePendingRef = useRef(false);
const imageInputRef = useRef<HTMLInputElement | null>(null);
- const maybeDeriveMemoTitle = useCallback((contentJson: TiptapDoc, finalize = false) => {
- if (
- !titleDerivationEligibleRef.current ||
- (titleRef.current.trim() && !titleWasAutoDerivedRef.current)
- ) return;
- const derivedTitle = deriveMemoTitleDuringInitialEdit(
- titleRef.current,
- contentJson,
- titleWasAutoDerivedRef.current,
- );
- if (!derivedTitle) return;
- titleWasAutoDerivedRef.current = true;
- titleRef.current = derivedTitle;
- setTitle(derivedTitle);
- if (finalize) titleDerivationEligibleRef.current = false;
- }, []);
-
const setSaveStateStable = useCallback((nextState: MobileEditorSaveState) => {
if (saveStateRef.current === nextState) {
return;
@@ -247,10 +228,6 @@ export const MobileStandaloneTiptapEditor = ({
},
onUpdate: ({ editor: activeEditor }) => {
contentJsonRef.current = activeEditor.getJSON() as TiptapDoc;
- maybeDeriveMemoTitle(
- contentJsonRef.current,
- titleWasAutoDerivedRef.current && !activeEditor.isActive("heading", { level: 1 }),
- );
dirtyRef.current = true;
persistLocalDraft();
@@ -275,12 +252,7 @@ export const MobileStandaloneTiptapEditor = ({
return;
}
- const refreshToolbar = () => {
- setToolbarVersion((version) => version + 1);
- if (titleWasAutoDerivedRef.current && !editor.isActive("heading", { level: 1 })) {
- titleDerivationEligibleRef.current = false;
- }
- };
+ const refreshToolbar = () => setToolbarVersion((version) => version + 1);
editor.on("selectionUpdate", refreshToolbar);
editor.on("transaction", refreshToolbar);
@@ -573,8 +545,6 @@ export const MobileStandaloneTiptapEditor = ({
}, [navigateBack, persistLocalDraft, saveNow, setSaveStateStable]);
const handleTitleChange = (nextTitle: string) => {
- titleDerivationEligibleRef.current = false;
- titleWasAutoDerivedRef.current = false;
setTitle(nextTitle);
titleRef.current = nextTitle;
scheduleMetadataSave();
@@ -811,8 +781,6 @@ export const MobileStandaloneTiptapEditor = ({
if (useDraft && draft) {
setTitle(draft.title || "");
titleRef.current = draft.title || "";
- titleDerivationEligibleRef.current = !titleRef.current.trim();
- titleWasAutoDerivedRef.current = false;
setTagsText(draft.tagsText || "");
tagsTextRef.current = draft.tagsText || "";
contentJsonRef.current = draft.contentJson || emptyDoc();
@@ -826,8 +794,6 @@ export const MobileStandaloneTiptapEditor = ({
const queuedTagsText = queuedPayload.tags.join(", ");
setTitle(queuedTitle);
titleRef.current = queuedTitle;
- titleDerivationEligibleRef.current = !queuedTitle.trim();
- titleWasAutoDerivedRef.current = false;
setTagsText(queuedTagsText);
tagsTextRef.current = queuedTagsText;
contentJsonRef.current = queuedPayload.contentJson || emptyDoc();
@@ -843,8 +809,6 @@ export const MobileStandaloneTiptapEditor = ({
} else {
setTitle(nextTitle);
titleRef.current = nextTitle;
- titleDerivationEligibleRef.current = !nextTitle.trim();
- titleWasAutoDerivedRef.current = false;
setTagsText(nextTagsText);
tagsTextRef.current = nextTagsText;
contentJsonRef.current = nextContentJson;
diff --git a/packages/shared/src/content-title.test.mjs b/packages/shared/src/content-title.test.mjs
deleted file mode 100644
index 14f96112..00000000
--- a/packages/shared/src/content-title.test.mjs
+++ /dev/null
@@ -1,43 +0,0 @@
-import { describe, expect, test } from "bun:test";
-import { deriveMemoTitleDuringInitialEdit, deriveMemoTitleFromContent, markdownToDoc } from "./content.ts";
-
-describe("deriveMemoTitleFromContent", () => {
- test("uses the first non-empty H1", () => {
- expect(deriveMemoTitleFromContent(markdownToDoc("\n# Product plan \n\nBody"))).toBe("Product plan");
- });
-
- test("does not use a later H1 when body content comes first", () => {
- expect(deriveMemoTitleFromContent(markdownToDoc("Intro\n\n# Product plan"))).toBeNull();
- });
-
- test("does not use lower-level headings", () => {
- expect(deriveMemoTitleFromContent(markdownToDoc("## Product plan"))).toBeNull();
- });
-
- test("does not skip a meaningful non-text block before the H1", () => {
- expect(deriveMemoTitleFromContent({
- type: "doc",
- content: [
- { type: "image", attrs: { src: "/cover.png" } },
- { type: "heading", attrs: { level: 1 }, content: [{ type: "text", text: "Product plan" }] },
- ],
- })).toBeNull();
- });
-
- test("limits generated titles to the persisted title length", () => {
- expect(deriveMemoTitleFromContent(markdownToDoc(`# ${"a".repeat(200)}`))).toHaveLength(160);
- });
-});
-
-describe("deriveMemoTitleDuringInitialEdit", () => {
- test("keeps filling the title as the initial H1 is typed", () => {
- const first = deriveMemoTitleDuringInitialEdit("", markdownToDoc("# 浏"), false);
- expect(first).toBe("浏");
- expect(deriveMemoTitleDuringInitialEdit(first, markdownToDoc("# 浏览器真实回归"), true))
- .toBe("浏览器真实回归");
- });
-
- test("does not replace a manually entered title", () => {
- expect(deriveMemoTitleDuringInitialEdit("我的标题", markdownToDoc("# 正文标题"), false)).toBeNull();
- });
-});
diff --git a/packages/shared/src/content.ts b/packages/shared/src/content.ts
index 2e17730b..42351f7f 100644
--- a/packages/shared/src/content.ts
+++ b/packages/shared/src/content.ts
@@ -66,51 +66,6 @@ export type TiptapDoc = {
};
export const DEFAULT_MEMO_TITLE = "无标题笔记";
-export const MEMO_TITLE_MAX_LENGTH = 160;
-
-const nodeText = (node: unknown): string => {
- if (!node || typeof node !== "object") return "";
- const current = node as { text?: unknown; content?: unknown };
- const ownText = typeof current.text === "string" ? current.text : "";
- const childText = Array.isArray(current.content) ? current.content.map(nodeText).join("") : "";
- return `${ownText}${childText}`;
-};
-
-/**
- * Derives a note title only when the first meaningful top-level block is an
- * H1. Empty text blocks before it are ignored; body content prevents a later
- * section heading from unexpectedly renaming the note.
- */
-export const deriveMemoTitleFromContent = (doc: unknown): string | null => {
- if (!doc || typeof doc !== "object") return null;
- const content = (doc as { content?: unknown }).content;
- if (!Array.isArray(content)) return null;
-
- for (const value of content) {
- if (!value || typeof value !== "object") continue;
- const node = value as { type?: unknown; attrs?: Record<string, unknown> };
- const text = nodeText(node).replace(/\s+/g, " ").trim();
- if (!text) {
- if (node.type === "paragraph" || node.type === "heading") continue;
- return null;
- }
- if (node.type !== "heading" || node.attrs?.level !== 1) return null;
- return text.slice(0, MEMO_TITLE_MAX_LENGTH);
- }
-
- return null;
-};
-
-/** Keeps an automatically generated title complete while the user is still
- * typing the initial H1, without overriding a title they entered themselves. */
-export const deriveMemoTitleDuringInitialEdit = (
- currentTitle: string,
- doc: unknown,
- wasAutoDerived: boolean,
-): string | null => {
- if (currentTitle.trim() && !wasAutoDerived) return null;
- return deriveMemoTitleFromContent(doc);
-};
export const resolveMergedMemoTitle = (
inputTitle: string | null | undefined,
diff --git a/tests/e2e/new-memo-sync.spec.ts b/tests/e2e/new-memo-sync.spec.ts
index e62c50fd..a3f9a684 100644
--- a/tests/e2e/new-memo-sync.spec.ts
+++ b/tests/e2e/new-memo-sync.spec.ts
@@ -177,71 +177,6 @@ const finishSyncAndVerifyReload = async (
};
test.describe("new memo synchronization", () => {
- test("derives the complete title when the first meaningful block is an H1", async ({ page }) => {
- const derivedTitle = `首个一级标题 ${Date.now()}`;
- const createResponsePromise = page.waitForResponse(
- (response) => response.request().method() === "POST" && new URL(response.url()).pathname === "/api/v1/memos",
- );
-
- await page.goto("/");
- await page.getByRole("button", { name: "新建笔记", exact: true }).click();
- const createResponse = await createResponsePromise;
- const created = await createResponse.json() as { memo: { id: string } };
- const editor = page.locator(".ProseMirror[contenteditable='true']");
-
- try {
- await editor.click();
- await page.keyboard.type("# ");
- await page.keyboard.insertText(derivedTitle);
-
- await expect(page.getByPlaceholder("无标题")).toHaveValue(derivedTitle);
- await expect.poll(async () => {
- const response = await page.request.get(`/api/v1/memos/${created.memo.id}`);
- if (!response.ok()) return null;
- const body = await response.json() as { memo: { title: string | null } };
- return body.memo.title;
- }).toBe(derivedTitle);
- } finally {
- await page.request.delete(`/api/v1/memos/${created.memo.id}`);
- await page.request.delete(`/api/v1/memos/${created.memo.id}?permanent=1`);
- }
- });
-
- test("does not derive the title from an H1 after body paragraphs", async ({ page }) => {
- const sectionHeading = `后置一级标题 ${Date.now()}`;
- const createResponsePromise = page.waitForResponse(
- (response) => response.request().method() === "POST" && new URL(response.url()).pathname === "/api/v1/memos",
- );
-
- await page.goto("/");
- await page.getByRole("button", { name: "新建笔记", exact: true }).click();
- const createResponse = await createResponsePromise;
- const created = await createResponse.json() as { memo: { id: string } };
- const editor = page.locator(".ProseMirror[contenteditable='true']");
- const titleInput = page.getByPlaceholder("无标题");
-
- try {
- await editor.click();
- await page.keyboard.insertText("第一段正文");
- await page.keyboard.press("Enter");
- await page.keyboard.insertText("第二段正文");
- await page.keyboard.press("Enter");
- await page.keyboard.type("# ");
- await page.keyboard.insertText(sectionHeading);
-
- await expect(titleInput).toHaveValue("");
- await expect.poll(async () => {
- const response = await page.request.get(`/api/v1/memos/${created.memo.id}`);
- if (!response.ok()) return null;
- const body = await response.json() as { memo: { title: string | null } };
- return body.memo.title;
- }).toBe("无标题笔记");
- } finally {
- await page.request.delete(`/api/v1/memos/${created.memo.id}`);
- await page.request.delete(`/api/v1/memos/${created.memo.id}?permanent=1`);
- }
- });
-
test("rebases a second autosave after memo creation reaches cloud revision 1", async ({ page }) => {
const marker = `${Date.now()}-draft-only`;
const title = `E2E create race ${marker}`;