Skip to content

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

feat(mobile): align revision history and list states

tianma-ifa316121e7ada
diff --git a/apps/mobile/src/lib/mobile-locale.tsx b/apps/mobile/src/lib/mobile-locale.tsx
index b03f9569..e5b54887 100644
--- a/apps/mobile/src/lib/mobile-locale.tsx
+++ b/apps/mobile/src/lib/mobile-locale.tsx
@@ -22,12 +22,17 @@ const mobileOnlyTranslations = new Map<string, string>([
["切换到浅色模式", "Switch to light mode"],
["完成编辑", "Finish editing"],
["完成新建笔记", "Finish creating note"],
+ ["Markdown 源代码编辑", "Edit Markdown source"],
+ ["资源", "Resources"],
["笔记列表操作", "Note list actions"],
["搜索", "Search"],
["搜索标题、正文或标签", "Search titles, content, or tags"],
["输入关键词开始搜索", "Enter a keyword to search"],
["搜索本机同步缓存,结果会即时显示", "Search the local synced cache with instant results"],
["笔记操作", "Note actions"],
+ ["加载失败", "Failed to load"],
+ ["请稍后重试", "Please try again later"],
+ ["重试", "Retry"],
["编辑笔记", "Edit note"],
["所在笔记本", "Notebook"],
["笔记标题", "Note title"],
diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsx
index a238f200..7f5ac7f9 100644
--- a/apps/mobile/src/screens/WorkspaceScreen.tsx
+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx
@@ -78,7 +78,7 @@ import {
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
import { Alert, Pressable, Text, TextInput } from "../components/LocalizedText";
import Markdown from "react-native-markdown-display";
-import { createExcerpt, docToMarkdown, docToText, getNotebookDescendantIds, markdownToDoc, type ApiToken, type AuthUser, type MemoDetail, type MemoRevision, type MemoSummary, type Notebook, type ResourceListItem, type TagSummary, type TiptapDoc } from "@edgeever/shared";
+import { buildRevisionDiffRows, createExcerpt, docToMarkdown, docToText, getNotebookDescendantIds, markdownToDoc, type ApiToken, type AuthUser, type MemoDetail, type MemoRevision, type MemoSummary, type Notebook, type ResourceListItem, type RevisionDiffRow, type TagSummary, type TiptapDoc } from "@edgeever/shared";
import { clearMobileMemoDraft, clearMobileNewMemoDraft, readMobileMemoDraft, readMobileNewMemoDraft, writeMobileMemoDraft, writeMobileNewMemoDraft } from "../lib/mobile-drafts";
import {
readMobileImageCompressionEnabled,
@@ -1573,8 +1573,8 @@ const NotesView = ({
<MemoList
emptyAction={memoView === "notebook" && notebooks.length > 0 ? { label: "新建笔记", onPress: onCreate } : undefined}
- emptyDescription={memoView === "trash" ? "删除的笔记会出现在这里" : notebooks.length > 0 ? "点击下方加号或这里创建第一条笔记" : "请先创建一个笔记本"}
- emptyTitle={memoView === "trash" ? "回收站为空" : "暂无笔记"}
+ emptyDescription={memoView === "trash" ? "删除的笔记会显示在这里。" : memoFilterMode !== "all" ? "试试切换筛选条件,或调整搜索关键词。" : "先创建一条笔记,之后可以在这里快速预览、搜索和批量整理。"}
+ emptyTitle={memoView === "trash" ? "回收站为空" : memoFilterMode !== "all" ? "没有符合筛选的笔记" : "暂无笔记"}
error={error}
isError={isError}
isLoading={isLoading}
@@ -4225,7 +4225,7 @@ const RevisionHistoryModal = ({
});
const requestRestoreRevision = (revision: MemoRevision) => {
- Alert.alert("恢复此版本?", `将把笔记内容恢复到修订 ${revision.revision}。当前内容会作为新的修订保留。`, [
+ Alert.alert("恢复到这个历史版本", "当前内容会被这个历史版本替换,恢复后仍会产生新的历史记录。", [
{ text: "取消", style: "cancel" },
{
text: "恢复",
@@ -4237,101 +4237,104 @@ const RevisionHistoryModal = ({
return (
<Modal animationType="slide" onRequestClose={onClose} presentationStyle="pageSheet" visible={Boolean(memo)}>
<SafeAreaView style={styles.modalSafeArea}>
- <View style={styles.modalHeader}>
- <IconButton onPress={onClose}>
+ <View style={styles.managementHeader}>
+ <View style={styles.managementHeaderText}>
+ <View style={styles.managementTitleRow}>
+ <History color="#059669" size={19} />
+ <Text style={styles.managementTitle}>版本历史</Text>
+ </View>
+ <Text numberOfLines={1} style={styles.managementSubtitle}>{memo?.title?.trim() || DEFAULT_MEMO_TITLE}</Text>
+ </View>
+ <IconButton accessibilityLabel="关闭" onPress={onClose}>
<X color="#0f172a" size={20} />
</IconButton>
- <Text numberOfLines={1} style={styles.modalTitle}>
- 修订历史
- </Text>
- <View style={styles.iconButtonPlaceholder} />
</View>
- {revisionsQuery.isLoading ? (
- <View style={styles.centerState}>
- <ActivityIndicator color="#0f172a" />
- </View>
- ) : revisions.length === 0 ? (
- <View style={styles.centerState}>
- <History color="#94a3b8" size={32} />
- <Text style={styles.emptyTitle}>暂无历史版本</Text>
- <Text style={styles.mutedText}>笔记保存后产生的修订会显示在这里</Text>
+ <ScrollView contentContainerStyle={styles.revisionHistoryContent}>
+ <View style={styles.revisionSummaryRow}>
+ <View style={styles.revisionSummaryText}>
+ <Text style={styles.settingsRowTitle}>{selectedRevision ? `版本 ${selectedRevision.revision} 与当前内容` : "未选择历史版本"}</Text>
+ {selectedRevision ? <Text style={styles.revisionChangeBadge}>{`${changedLines} 行有变化`}</Text> : null}
+ </View>
+ {selectedRevision ? (
+ <ActionButton disabled={restoreRevisionMutation.isPending || Boolean(memo?.isDeleted)} label={restoreRevisionMutation.isPending ? "恢复中" : "恢复该版本"} onPress={() => requestRestoreRevision(selectedRevision)}>
+ <RotateCcw color="#0f172a" size={16} />
+ </ActionButton>
+ ) : null}
</View>
- ) : (
- <ScrollView contentContainerStyle={styles.editorForm}>
- <Text style={styles.detailTitle}>{memo?.title?.trim() || DEFAULT_MEMO_TITLE}</Text>
- <Text style={styles.sectionSubtitle}>{selectedRevision ? `修订 ${selectedRevision.revision} · ${changedLines} 行差异` : "请选择一个修订"}</Text>
- <ScrollView horizontal showsHorizontalScrollIndicator={false}>
+ <Text style={styles.revisionTimelineLabel}>历史记录</Text>
+ {revisionsQuery.isLoading ? (
+ <View style={styles.revisionTimelineState}>
+ <Text style={styles.mutedText}>加载中</Text>
+ </View>
+ ) : revisionsQuery.isError ? (
+ <View style={styles.revisionTimelineState}>
+ <Text style={styles.errorText}>加载失败</Text>
+ <Text style={styles.revisionTimelineError}>
+ {revisionsQuery.error instanceof Error ? revisionsQuery.error.message : "请稍后重试"}
+ </Text>
+ <ActionButton label="重试" onPress={() => void revisionsQuery.refetch()}>
+ <RotateCcw color="#0f172a" size={16} />
+ </ActionButton>
+ </View>
+ ) : revisions.length === 0 ? (
+ <View style={styles.revisionTimelineState}>
+ <Text style={styles.mutedText}>暂无历史版本</Text>
+ </View>
+ ) : (
+ <View style={styles.revisionTimeline}>
{revisions.map((revision) => (
<Pressable
key={revision.id}
onPress={() => setSelectedRevisionId(revision.id)}
style={[styles.revisionPill, selectedRevision?.id === revision.id && styles.revisionPillActive]}
>
- <Text style={[styles.revisionPillTitle, selectedRevision?.id === revision.id && styles.revisionPillTitleActive]}>修订 {revision.revision}</Text>
+ <Text style={[styles.revisionPillTitle, selectedRevision?.id === revision.id && styles.revisionPillTitleActive]}>{`版本 ${revision.revision}`}</Text>
<Text style={[styles.revisionPillMeta, selectedRevision?.id === revision.id && styles.revisionPillTitleActive]}>
{formatDate(revision.createdAt, localePreference)} · {formatRevisionActor(revision.createdBy)}
</Text>
</Pressable>
))}
- </ScrollView>
+ </View>
+ )}
- {selectedRevision ? (
- <>
- <ActionButton disabled={restoreRevisionMutation.isPending || Boolean(memo?.isDeleted)} label={restoreRevisionMutation.isPending ? "恢复中" : "恢复此版本"} onPress={() => requestRestoreRevision(selectedRevision)}>
- <RotateCcw color="#0f172a" size={16} />
- </ActionButton>
- <View style={styles.revisionPreviewBlock}>
- <Text style={styles.label}>历史版本</Text>
- <RevisionDiffPreview rows={diffRows?.leftRows ?? []} tone="history" />
- </View>
- <View style={styles.revisionPreviewBlock}>
- <Text style={styles.label}>当前内容</Text>
- <RevisionDiffPreview rows={diffRows?.rightRows ?? []} tone="current" />
- </View>
- </>
- ) : null}
- {restoreRevisionMutation.error ? (
- <Text style={styles.errorText}>{restoreRevisionMutation.error instanceof Error ? restoreRevisionMutation.error.message : "恢复失败"}</Text>
- ) : null}
- </ScrollView>
- )}
+ {selectedRevision ? <RevisionComparisonTable leftRows={diffRows?.leftRows ?? []} rightRows={diffRows?.rightRows ?? []} /> : null}
+ {restoreRevisionMutation.error ? (
+ <Text style={styles.errorText}>{restoreRevisionMutation.error instanceof Error ? restoreRevisionMutation.error.message : "恢复失败"}</Text>
+ ) : null}
+ </ScrollView>
</SafeAreaView>
</Modal>
);
};
-const RevisionDiffPreview = ({ rows, tone }: { rows: DiffRow[]; tone: "history" | "current" }) => {
- const hasContent = rows.some((row) => row.text);
-
- if (!hasContent) {
- return <Text style={styles.mutedText}>没有正文内容</Text>;
- }
+const RevisionComparisonTable = ({ leftRows, rightRows }: { leftRows: RevisionDiffRow[]; rightRows: RevisionDiffRow[] }) => {
+ const hasContent = leftRows.some((row) => row.text) || rightRows.some((row) => row.text);
return (
- <View style={styles.revisionDiffTable}>
- {rows.map((row) => {
- const changed = row.state === "changed";
-
- return (
- <View
- key={row.lineNumber}
- style={[
- styles.revisionDiffRow,
- changed && tone === "history" && styles.revisionDiffRowHistory,
- changed && tone === "current" && styles.revisionDiffRowCurrent,
- ]}
- >
- <Text style={styles.revisionDiffLineNumber}>{row.lineNumber}</Text>
- <Text style={[styles.revisionDiffText, row.state === "empty" && styles.revisionDiffTextEmpty]}>{row.text || " "}</Text>
- </View>
- );
- })}
+ <View style={styles.revisionComparisonTable}>
+ <View style={styles.revisionComparisonHeader}>
+ <Text style={styles.revisionComparisonHeaderText}>历史版本</Text>
+ <Text style={styles.revisionComparisonHeaderText}>当前内容</Text>
+ </View>
+ {hasContent ? leftRows.map((leftRow, index) => (
+ <View key={`${leftRow.lineNumber ?? "empty"}-${index}`} style={styles.revisionComparisonRow}>
+ <RevisionDiffCell row={leftRow} tone="history" />
+ <RevisionDiffCell row={rightRows[index] ?? { lineNumber: null, text: "", state: "empty" }} tone="current" />
+ </View>
+ )) : <Text style={styles.revisionComparisonEmpty}>空笔记</Text>}
</View>
);
};
+const RevisionDiffCell = ({ row, tone }: { row: RevisionDiffRow; tone: "history" | "current" }) => (
+ <View style={[styles.revisionComparisonCell, tone === "current" && styles.revisionComparisonCellCurrent, row.state === "changed" && (tone === "history" ? styles.revisionDiffRowHistory : styles.revisionDiffRowCurrent)]}>
+ <Text style={styles.revisionComparisonLineNumber}>{row.lineNumber ?? ""}</Text>
+ <Text style={[styles.revisionComparisonText, row.state === "empty" && styles.revisionDiffTextEmpty]}>{row.text || " "}</Text>
+ </View>
+);
+
const MemoDetailModal = ({
isDeleting,
isLoading,
@@ -4399,7 +4402,7 @@ const MemoDetailModal = ({
<ChevronLeft color="#475569" size={21} />
</Pressable>
<Text style={styles.detailSyncStatus}>{isSaving ? "保存中" : "已同步"}</Text>
- {memo?.isDeleted ? (
+ {memo ? (
<Pressable accessibilityLabel="笔记操作" accessibilityRole="button" onPress={() => setActionsOpen(true)} style={styles.detailHeaderButton}>
<MoreHorizontal color="#475569" size={21} />
</Pressable>
@@ -4482,8 +4485,8 @@ const MemoDetailModal = ({
<ActionSheetItem icon={<Code color="#0f172a" size={18} />} label="Markdown 源代码编辑" onPress={() => closeActionsAndRun(() => onEdit(memo))} />
</>
)}
- <ActionSheetItem icon={<Search color="#0f172a" size={18} />} label="查找当前笔记" onPress={() => closeActionsAndRun(() => setSearchOpen((open) => !open))} />
- <ActionSheetItem icon={<History color="#0f172a" size={18} />} label="修订历史" onPress={() => closeActionsAndRun(() => onOpenRevisions(memo))} />
+ <ActionSheetItem icon={<Search color="#0f172a" size={18} />} label="搜索当前笔记" onPress={() => closeActionsAndRun(() => setSearchOpen((open) => !open))} />
+ <ActionSheetItem icon={<History color="#0f172a" size={18} />} label="版本历史" onPress={() => closeActionsAndRun(() => onOpenRevisions(memo))} />
<ActionSheetItem icon={<Archive color="#0f172a" size={18} />} label="资源" onPress={() => closeActionsAndRun(onOpenResources)} />
<ActionSheetItem danger disabled={isDeleting} icon={<Trash2 color="#b91c1c" size={18} />} label={isDeleting ? "删除中" : memo.isDeleted ? "永久删除" : "删除"} onPress={() => closeActionsAndRun(() => onDelete(memo))} />
</Pressable>
@@ -5310,23 +5313,25 @@ const MemoList = ({
}) => {
if (isLoading) {
return (
- <View style={styles.centerState}>
- <ActivityIndicator color="#0f172a" />
+ <View style={styles.memoListStateWrap}>
+ <Text style={styles.memoListLoadingText}>正在拉取最新笔记</Text>
</View>
);
}
- if (isError) {
+ if (isError && memos.length === 0) {
return (
- <View style={styles.centerState}>
- <Text style={styles.errorText}>加载失败</Text>
- <Text style={styles.mutedText}>{error instanceof Error ? error.message : "请稍后再试"}</Text>
+ <View style={styles.memoListStateWrap}>
+ <View style={styles.memoListErrorCard}>
+ <Text style={styles.memoListErrorTitle}>暂时没有拉到笔记</Text>
+ <Text style={styles.memoListErrorDescription}>网络或 PWA 后台恢复可能短暂中断了同步。这里不会把它当作空笔记本。</Text>
{onRetry ? (
- <Pressable accessibilityLabel="重试加载" accessibilityRole="button" onPress={onRetry} style={styles.emptyActionButton}>
- <RotateCcw color="#ffffff" size={17} />
- <Text style={styles.emptyActionButtonText}>重试</Text>
+ <Pressable accessibilityLabel="重试加载" accessibilityRole="button" onPress={onRetry} style={styles.memoListRetryButton}>
+ <RotateCcw color="#92400e" size={17} />
+ <Text style={styles.memoListRetryText}>重试</Text>
</Pressable>
) : null}
+ </View>
</View>
);
}
@@ -5354,8 +5359,7 @@ const MemoList = ({
/>
)}
ListEmptyComponent={
- <View style={styles.centerState}>
- <BookOpen color="#94a3b8" size={32} />
+ <View style={styles.memoListEmptyCard}>
<Text style={styles.emptyTitle}>{emptyTitle}</Text>
<Text style={styles.mutedText}>{emptyDescription}</Text>
{emptyAction ? (
@@ -6674,44 +6678,6 @@ const buildMcpRemoteConfig = (baseUrl: string, token: string) =>
2
);
-type DiffRow = {
- lineNumber: number;
- text: string;
- state: "same" | "changed" | "empty";
-};
-
-const buildRevisionDiffRows = (left: string, right: string) => {
- const leftLines = left.split("\n");
- const rightLines = right.split("\n");
- const maxLines = Math.max(leftLines.length, rightLines.length, 1);
- const leftRows: DiffRow[] = [];
- const rightRows: DiffRow[] = [];
- let changed = 0;
-
- for (let index = 0; index < maxLines; index += 1) {
- const leftText = leftLines[index] ?? "";
- const rightText = rightLines[index] ?? "";
- const isChanged = leftText !== rightText;
-
- if (isChanged) {
- changed += 1;
- }
-
- leftRows.push({
- lineNumber: index + 1,
- text: leftText,
- state: isChanged ? "changed" : leftText ? "same" : "empty",
- });
- rightRows.push({
- lineNumber: index + 1,
- text: rightText,
- state: isChanged ? "changed" : rightText ? "same" : "empty",
- });
- }
-
- return { changed, leftRows, rightRows };
-};
-
const formatRevisionActor = (actor: string) => {
if (actor.startsWith("user:")) {
return "user";
@@ -7450,6 +7416,66 @@ const baseWorkspaceStyles = StyleSheet.create({
flexGrow: 1,
paddingBottom: 22,
},
+ memoListStateWrap: {
+ paddingHorizontal: 12,
+ paddingTop: 16,
+ },
+ memoListLoadingText: {
+ color: "#64748b",
+ fontSize: 14,
+ paddingHorizontal: 8,
+ },
+ memoListErrorCard: {
+ alignItems: "center",
+ backgroundColor: "#fffbeb",
+ borderColor: "#fcd34d",
+ borderRadius: 8,
+ borderStyle: "dashed",
+ borderWidth: 1,
+ paddingHorizontal: 16,
+ paddingVertical: 34,
+ },
+ memoListErrorTitle: {
+ color: "#451a03",
+ fontSize: 14,
+ fontWeight: "800",
+ },
+ memoListErrorDescription: {
+ color: "#92400e",
+ fontSize: 12,
+ lineHeight: 20,
+ marginTop: 8,
+ maxWidth: 300,
+ textAlign: "center",
+ },
+ memoListRetryButton: {
+ alignItems: "center",
+ backgroundColor: "#fef3c7",
+ borderRadius: 8,
+ flexDirection: "row",
+ gap: 7,
+ marginTop: 16,
+ minHeight: 36,
+ paddingHorizontal: 12,
+ },
+ memoListRetryText: {
+ color: "#92400e",
+ fontSize: 13,
+ fontWeight: "800",
+ },
+ memoListEmptyCard: {
+ alignItems: "center",
+ alignSelf: "stretch",
+ backgroundColor: "#ffffff",
+ borderColor: "#cbd5e1",
+ borderRadius: 8,
+ borderStyle: "dashed",
+ borderWidth: 1,
+ marginHorizontal: 12,
+ marginTop: 12,
+ paddingHorizontal: 16,
+ paddingVertical: 34,
+ },
memoCard: {
backgroundColor: "#ffffff",
borderColor: "#f1f5f9",
@@ -8738,20 +8764,74 @@ const baseWorkspaceStyles = StyleSheet.create({
fontSize: 14,
fontWeight: "700",
},
+ revisionHistoryContent: {
+ gap: 12,
+ padding: 16,
+ paddingBottom: 48,
+ },
+ revisionSummaryRow: {
+ alignItems: "center",
+ flexDirection: "row",
+ gap: 10,
+ justifyContent: "space-between",
+ },
+ revisionSummaryText: {
+ flex: 1,
+ gap: 6,
+ minWidth: 0,
+ },
+ revisionChangeBadge: {
+ alignSelf: "flex-start",
+ backgroundColor: "#fffbeb",
+ borderColor: "#fde68a",
+ borderRadius: 999,
+ borderWidth: 1,
+ color: "#92400e",
+ fontSize: 11,
+ fontWeight: "700",
+ overflow: "hidden",
+ paddingHorizontal: 8,
+ paddingVertical: 3,
+ },
+ revisionTimelineLabel: {
+ color: "#94a3b8",
+ fontSize: 11,
+ fontWeight: "700",
+ letterSpacing: 0.6,
+ textTransform: "uppercase",
+ },
+ revisionTimeline: {
+ gap: 7,
+ },
+ revisionTimelineState: {
+ alignItems: "center",
+ backgroundColor: "#ffffff",
+ borderColor: "#cbd5e1",
+ borderRadius: 8,
+ borderStyle: "dashed",
+ borderWidth: 1,
+ gap: 12,
+ paddingHorizontal: 16,
+ paddingVertical: 32,
+ },
+ revisionTimelineError: {
+ color: "#64748b",
+ fontSize: 12,
+ lineHeight: 18,
+ textAlign: "center",
+ },
revisionPill: {
backgroundColor: "#ffffff",
borderColor: "#e2e8f0",
borderRadius: 8,
borderWidth: 1,
- marginRight: 8,
- minHeight: 58,
- minWidth: 132,
+ minHeight: 68,
paddingHorizontal: 12,
paddingVertical: 9,
},
revisionPillActive: {
- backgroundColor: "#0f172a",
- borderColor: "#0f172a",
+ backgroundColor: "#ecfdf5",
+ borderColor: "#a7f3d0",
},
revisionPillTitle: {
color: "#0f172a",
@@ -8759,7 +8839,7 @@ const baseWorkspaceStyles = StyleSheet.create({
fontWeight: "800",
},
revisionPillTitleActive: {
- color: "#ffffff",
+ color: "#047857",
},
revisionPillMeta: {
color: "#64748b",
@@ -8767,55 +8847,78 @@ const baseWorkspaceStyles = StyleSheet.create({
fontWeight: "700",
marginTop: 4,
},
- revisionPreviewBlock: {
+ revisionComparisonTable: {
backgroundColor: "#ffffff",
borderColor: "#e2e8f0",
borderRadius: 8,
borderWidth: 1,
- gap: 8,
- padding: 12,
+ overflow: "hidden",
},
- revisionPreviewText: {
- color: "#334155",
- fontSize: 13,
- lineHeight: 20,
+ revisionComparisonHeader: {
+ backgroundColor: "#f8fafc",
+ flexDirection: "row",
},
- revisionDiffTable: {
- borderColor: "#e2e8f0",
- borderRadius: 8,
- borderWidth: 1,
- overflow: "hidden",
+ revisionComparisonHeaderText: {
+ color: "#475569",
+ flex: 1,
+ fontSize: 11,
+ fontWeight: "800",
+ padding: 10,
},
- revisionDiffRow: {
+ revisionComparisonRow: {
+ alignItems: "stretch",
borderBottomColor: "#f1f5f9",
borderBottomWidth: 1,
flexDirection: "row",
minHeight: 28,
},
- revisionDiffRowHistory: {
- backgroundColor: "#fffbeb",
+ revisionComparisonCell: {
+ flex: 1,
+ flexDirection: "row",
+ minWidth: 0,
},
- revisionDiffRowCurrent: {
- backgroundColor: "#ecfdf5",
+ revisionComparisonCellCurrent: {
+ borderLeftColor: "#e2e8f0",
+ borderLeftWidth: 1,
},
- revisionDiffLineNumber: {
+ revisionComparisonLineNumber: {
+ backgroundColor: "#f8fafc",
borderRightColor: "#e2e8f0",
borderRightWidth: 1,
color: "#94a3b8",
- fontSize: 11,
- minWidth: 42,
- paddingHorizontal: 8,
+ fontSize: 10,
+ minWidth: 28,
+ paddingHorizontal: 4,
paddingTop: 6,
textAlign: "right",
},
- revisionDiffText: {
+ revisionComparisonText: {
color: "#334155",
flex: 1,
- fontSize: 12,
- lineHeight: 18,
- paddingHorizontal: 10,
+ fontFamily: Platform.select({ android: "monospace", ios: "Menlo" }),
+ fontSize: 11,
+ lineHeight: 17,
+ minWidth: 0,
+ paddingHorizontal: 6,
paddingVertical: 5,
},
+ revisionComparisonEmpty: {
+ color: "#94a3b8",
+ fontSize: 13,
+ padding: 24,
+ textAlign: "center",
+ },
+ revisionPreviewText: {
+ color: "#334155",
+ fontSize: 13,
+ lineHeight: 20,
+ },
+ revisionDiffRowHistory: {
+ backgroundColor: "#fff1f2",
+ },
+ revisionDiffRowCurrent: {
+ backgroundColor: "#ecfdf5",
+ },
revisionDiffTextEmpty: {
color: "#94a3b8",
},
diff --git a/apps/web/src/components/dialogs/RevisionHistoryDialog.tsx b/apps/web/src/components/dialogs/RevisionHistoryDialog.tsx
index eb076a5d..1fa945dd 100644
--- a/apps/web/src/components/dialogs/RevisionHistoryDialog.tsx
+++ b/apps/web/src/components/dialogs/RevisionHistoryDialog.tsx
@@ -8,117 +8,7 @@ import { api } from "@/lib/api";
import { cn, formatDateTime } from "@/lib/utils";
import { getMemoTitle } from "@/lib/app-helpers";
import { AppConfirmDialog } from "./ConfirmDialogs";
-import type { MemoDetail } from "@edgeever/shared";
-
-const summarizeMarkdownDiff = (left: string, right: string) => {
- const leftLines = left.split("\n");
- const rightLines = right.split("\n");
- const maxLines = Math.max(leftLines.length, rightLines.length);
- let changed = 0;
-
- for (let index = 0; index < maxLines; index += 1) {
- if ((leftLines[index] ?? "") !== (rightLines[index] ?? "")) {
- changed += 1;
- }
- }
-
- return { changed };
-};
-
-type DiffRow = {
- lineNumber: number | null;
- text: string;
- state: "same" | "changed" | "empty";
-};
-
-const buildRevisionDiffRows = (left: string, right: string) => {
- const leftLines = left.split("\n");
- const rightLines = right.split("\n");
- const m = leftLines.length;
- const n = rightLines.length;
-
- const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
-
- for (let i = 1; i <= m; i++) {
- for (let j = 1; j <= n; j++) {
- if (leftLines[i - 1] === rightLines[j - 1]) {
- dp[i][j] = dp[i - 1][j - 1] + 1;
- } else {
- dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
- }
- }
- }
-
- let i = m;
- let j = n;
- type DiffAction =
- | { type: "same"; left: string; right: string }
- | { type: "removed"; line: string }
- | { type: "added"; line: string };
- const actions: DiffAction[] = [];
-
- while (i > 0 || j > 0) {
- if (i > 0 && j > 0 && leftLines[i - 1] === rightLines[j - 1]) {
- actions.unshift({ type: "same", left: leftLines[i - 1], right: rightLines[j - 1] });
- i--;
- j--;
- } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
- actions.unshift({ type: "added", line: rightLines[j - 1] });
- j--;
- } else {
- actions.unshift({ type: "removed", line: leftLines[i - 1] });
- i--;
- }
- }
-
- const leftRows: DiffRow[] = [];
- const rightRows: DiffRow[] = [];
-
- let leftLineNum = 1;
- let rightLineNum = 1;
-
- let index = 0;
- while (index < actions.length) {
- const action = actions[index];
- if (action.type === "same") {
- leftRows.push({ lineNumber: leftLineNum++, text: action.left, state: "same" });
- rightRows.push({ lineNumber: rightLineNum++, text: action.right, state: "same" });
- index++;
- } else {
- const removedBlock: string[] = [];
- const addedBlock: string[] = [];
-
- while (index < actions.length && actions[index].type !== "same") {
- const act = actions[index];
- if (act.type === "removed") {
- removedBlock.push(act.line);
- } else if (act.type === "added") {
- addedBlock.push(act.line);
- }
- index++;
- }
-
- const maxLen = Math.max(removedBlock.length, addedBlock.length);
- for (let k = 0; k < maxLen; k++) {
- const hasRemoved = k < removedBlock.length;
- const hasAdded = k < addedBlock.length;
-
- if (hasRemoved && hasAdded) {
- leftRows.push({ lineNumber: leftLineNum++, text: removedBlock[k], state: "changed" });
- rightRows.push({ lineNumber: rightLineNum++, text: addedBlock[k], state: "changed" });
- } else if (hasRemoved) {
- leftRows.push({ lineNumber: leftLineNum++, text: removedBlock[k], state: "changed" });
- rightRows.push({ lineNumber: null, text: "", state: "empty" });
- } else if (hasAdded) {
- leftRows.push({ lineNumber: null, text: "", state: "empty" });
- rightRows.push({ lineNumber: rightLineNum++, text: addedBlock[k], state: "changed" });
- }
- }
- }
- }
-
- return { leftRows, rightRows };
-};
+import { buildRevisionDiffRows, type MemoDetail } from "@edgeever/shared";
const formatRevisionActor = (actor: string) => {
if (actor.startsWith("user:")) {
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 08e06779..7947c2ab 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -2,5 +2,6 @@ export * from "./content";
export * from "./backup";
export * from "./memo-safety";
export * from "./notebooks";
+export * from "./revision-diff";
export * from "./schemas";
export * from "./types";
diff --git a/packages/shared/src/revision-diff.test.mjs b/packages/shared/src/revision-diff.test.mjs
new file mode 100644
index 00000000..049b3e5a
--- /dev/null
+++ b/packages/shared/src/revision-diff.test.mjs
@@ -0,0 +1,35 @@
+import { describe, expect, test } from "bun:test";
+import { buildRevisionDiffRows } from "./revision-diff.ts";
+
+describe("buildRevisionDiffRows", () => {
+ test("aligns inserted lines without shifting unchanged content", () => {
+ const result = buildRevisionDiffRows("alpha\nbeta", "alpha\ninserted\nbeta");
+
+ expect(result.changed).toBe(1);
+ expect(result.leftRows).toEqual([
+ { lineNumber: 1, text: "alpha", state: "same" },
+ { lineNumber: null, text: "", state: "empty" },
+ { lineNumber: 2, text: "beta", state: "same" },
+ ]);
+ expect(result.rightRows).toEqual([
+ { lineNumber: 1, text: "alpha", state: "same" },
+ { lineNumber: 2, text: "inserted", state: "changed" },
+ { lineNumber: 3, text: "beta", state: "same" },
+ ]);
+ });
+
+ test("pairs replacement lines as changed rows", () => {
+ const result = buildRevisionDiffRows("before\nkeep", "after\nkeep");
+
+ expect(result.changed).toBe(1);
+ expect(result.leftRows[0]).toEqual({ lineNumber: 1, text: "before", state: "changed" });
+ expect(result.rightRows[0]).toEqual({ lineNumber: 1, text: "after", state: "changed" });
+ });
+
+ test("reports no changes for identical content", () => {
+ const result = buildRevisionDiffRows("same\ncontent", "same\ncontent");
+
+ expect(result.changed).toBe(0);
+ expect(result.leftRows).toEqual(result.rightRows);
+ });
+});
diff --git a/packages/shared/src/revision-diff.ts b/packages/shared/src/revision-diff.ts
new file mode 100644
index 00000000..d91e765f
--- /dev/null
+++ b/packages/shared/src/revision-diff.ts
@@ -0,0 +1,89 @@
+export type RevisionDiffRow = {
+ lineNumber: number | null;
+ text: string;
+ state: "same" | "changed" | "empty";
+};
+
+export const buildRevisionDiffRows = (left: string, right: string) => {
+ const leftLines = left.split("\n");
+ const rightLines = right.split("\n");
+ const leftLength = leftLines.length;
+ const rightLength = rightLines.length;
+ const matrix: number[][] = Array.from({ length: leftLength + 1 }, () => Array(rightLength + 1).fill(0));
+
+ for (let leftIndex = 1; leftIndex <= leftLength; leftIndex += 1) {
+ for (let rightIndex = 1; rightIndex <= rightLength; rightIndex += 1) {
+ matrix[leftIndex][rightIndex] = leftLines[leftIndex - 1] === rightLines[rightIndex - 1]
+ ? matrix[leftIndex - 1][rightIndex - 1] + 1
+ : Math.max(matrix[leftIndex - 1][rightIndex], matrix[leftIndex][rightIndex - 1]);
+ }
+ }
+
+ type DiffAction =
+ | { type: "same"; left: string; right: string }
+ | { type: "removed"; line: string }
+ | { type: "added"; line: string };
+ const actions: DiffAction[] = [];
+ let leftIndex = leftLength;
+ let rightIndex = rightLength;
+
+ while (leftIndex > 0 || rightIndex > 0) {
+ if (leftIndex > 0 && rightIndex > 0 && leftLines[leftIndex - 1] === rightLines[rightIndex - 1]) {
+ actions.push({ type: "same", left: leftLines[leftIndex - 1], right: rightLines[rightIndex - 1] });
+ leftIndex -= 1;
+ rightIndex -= 1;
+ } else if (rightIndex > 0 && (leftIndex === 0 || matrix[leftIndex][rightIndex - 1] >= matrix[leftIndex - 1][rightIndex])) {
+ actions.push({ type: "added", line: rightLines[rightIndex - 1] });
+ rightIndex -= 1;
+ } else {
+ actions.push({ type: "removed", line: leftLines[leftIndex - 1] });
+ leftIndex -= 1;
+ }
+ }
+ actions.reverse();
+
+ const leftRows: RevisionDiffRow[] = [];
+ const rightRows: RevisionDiffRow[] = [];
+ let leftLineNumber = 1;
+ let rightLineNumber = 1;
+ let actionIndex = 0;
+
+ while (actionIndex < actions.length) {
+ const action = actions[actionIndex];
+ if (action.type === "same") {
+ leftRows.push({ lineNumber: leftLineNumber++, text: action.left, state: "same" });
+ rightRows.push({ lineNumber: rightLineNumber++, text: action.right, state: "same" });
+ actionIndex += 1;
+ continue;
+ }
+
+ const removedLines: string[] = [];
+ const addedLines: string[] = [];
+ while (actionIndex < actions.length && actions[actionIndex].type !== "same") {
+ const changedAction = actions[actionIndex];
+ if (changedAction.type === "removed") {
+ removedLines.push(changedAction.line);
+ } else if (changedAction.type === "added") {
+ addedLines.push(changedAction.line);
+ }
+ actionIndex += 1;
+ }
+
+ const changedBlockLength = Math.max(removedLines.length, addedLines.length);
+ for (let index = 0; index < changedBlockLength; index += 1) {
+ leftRows.push(index < removedLines.length
+ ? { lineNumber: leftLineNumber++, text: removedLines[index], state: "changed" }
+ : { lineNumber: null, text: "", state: "empty" });
+ rightRows.push(index < addedLines.length
+ ? { lineNumber: rightLineNumber++, text: addedLines[index], state: "changed" }
+ : { lineNumber: null, text: "", state: "empty" });
+ }
+ }
+
+ const changed = leftRows.reduce(
+ (total, row, index) => total + (row.state !== "same" || rightRows[index]?.state !== "same" ? 1 : 0),
+ 0
+ );
+
+ return { changed, leftRows, rightRows };
+};