Files
zhimingge/lib/history/storage.ts
T
2026-06-13 09:39:38 +08:00

67 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
HISTORY_MAX_ITEMS,
HISTORY_STORAGE_KEY,
type CalcHistoryEntry,
} from "@/lib/history/types";
export function loadHistory(): CalcHistoryEntry[] {
if (typeof window === "undefined") {
return [];
}
try {
const raw = localStorage.getItem(HISTORY_STORAGE_KEY);
if (!raw) {
return [];
}
const parsed = JSON.parse(raw) as CalcHistoryEntry[];
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
export function saveHistoryEntry(
entry: Omit<CalcHistoryEntry, "id" | "createdAt">,
): CalcHistoryEntry {
const full: CalcHistoryEntry = {
...entry,
id: crypto.randomUUID(),
createdAt: new Date().toISOString(),
};
const list = [full, ...loadHistory()].slice(0, HISTORY_MAX_ITEMS);
localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(list));
return full;
}
export function deleteHistoryEntry(id: string): void {
const list = loadHistory().filter((e) => e.id !== id);
localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(list));
}
export function downloadMarkdown(content: string, filename: string) {
const blob = new Blob([content], { type: "text/markdown;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename.endsWith(".md") ? filename : `${filename}.md`;
a.click();
URL.revokeObjectURL(url);
}
export function buildHistoryMarkdown(entry: CalcHistoryEntry): string {
const lines = [
`# ${entry.title}`,
"",
`- 类型:${entry.mode}`,
`- 时间:${new Date(entry.createdAt).toLocaleString("zh-CN")}`,
`- 问事:${entry.question}`,
"",
...Object.entries(entry.meta).map(([k, v]) => `- ${k}${v}`),
"",
"---",
"",
entry.completion,
];
return lines.join("\n");
}