import { ContentConverter } from "./converter";
import type { NoteEntry, NotesListItem } from "./types";
export interface NoteExtraInfo {
title?: string;
note_content_type?: string;
web_images?: string;
mind_content?: string;
mind_content_plain_text?: string;
}
export function buildNotesListItem(note: NoteEntry, converter: ContentConverter): NotesListItem {
const title = deriveNoteTitle(note, converter);
const snippetMarkdown = converter.xmlToMarkdown(note.snippet ?? "");
return {
id: note.id,
title,
snippet: snippetMarkdown,
modifyDate: note.modifyDate,
folderId: note.folderId,
};
}
export function deriveNoteTitle(note: NoteEntry, converter: ContentConverter): string {
const extraInfo = parseExtraInfo(note.extraInfo);
if (extraInfo?.title && extraInfo.title.trim().length > 0) {
return extraInfo.title.trim();
}
if (note.subject && note.subject.trim().length > 0) {
return note.subject.trim();
}
const firstLine = converter
.xmlToMarkdown(note.snippet ?? "")
.split("\n")
.map((line) => line.trim())
.find((line) => line.length > 0);
return firstLine ?? `笔记 ${note.id}`;
}
export function parseExtraInfo(raw: string | undefined): NoteExtraInfo | undefined {
if (!raw) {
return undefined;
}
try {
const parsed = JSON.parse(raw) as NoteExtraInfo;
return parsed;
} catch (error) {
console.warn(`解析 extraInfo 失败: ${(error as Error).message}`);
return undefined;
}
}
export function buildExtraInfoString(title: string | undefined, existing?: string): string | undefined {
const base = parseExtraInfo(existing);
const info: NoteExtraInfo = {
note_content_type: base?.note_content_type ?? "common",
title: base?.title,
web_images: base?.web_images,
mind_content: base?.mind_content,
mind_content_plain_text: base?.mind_content_plain_text,
};
if (title !== undefined) {
info.title = title;
}
const entries = Object.entries(info).filter(([, value]) => value !== undefined && value !== "");
if (entries.length === 0) {
return undefined;
}
return JSON.stringify(Object.fromEntries(entries));
}
export function extractSnippetFromXml(xml: string): string {
const snippet = xml
.split("\n")
.map((line) => line.trim())
.find((line) => line.length > 0);
return snippet ?? "";
}