Skip to content

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

Add infinite memo list pagination

yoma1271a850bf62
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 06bd2daa..c13ff229 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -91,6 +91,19 @@ type MemoSummaryRow = {
revision: number;
};
+type MemoListSortMode = "updated-desc" | "created-desc" | "title-asc";
+type MemoListFilterMode = "all" | "tagged" | "untagged" | "pinned";
+
+type MemoListCursor = {
+ sort: MemoListSortMode;
+ id: string;
+ pinned?: number;
+ updatedAt?: string;
+ createdAt?: string;
+ deletedAt?: string | null;
+ title?: string;
+};
+
type MemoDetailRow = MemoSummaryRow & {
content_json: string;
content_markdown: string;
@@ -188,6 +201,9 @@ type ResourceStatsRow = {
type AppContext = Context<{ Bindings: Bindings; Variables: { auth: AuthContext } }>;
const SESSION_COOKIE = "edgeever_session";
+const DEFAULT_MEMO_LIST_LIMIT = 100;
+const MAX_MEMO_LIST_LIMIT = 200;
+const UNTITLED_MEMO_TITLE = "无标题笔记";
const PASSWORD_HASH_ALGORITHM = "pbkdf2-sha256";
const PASSWORD_HASH_ITERATIONS = 100_000;
const PASSWORD_HASH_BYTES = 32;
@@ -696,14 +712,73 @@ app.get("/api/v1/memos", async (c) => {
const notebookId = c.req.query("notebookId");
const q = c.req.query("q")?.trim();
const includeTrash = c.req.query("trash") === "1";
- const limit = clampNumber(Number(c.req.query("limit") ?? 5000), 1, 5000);
+ const sort = normalizeMemoListSort(c.req.query("sort"));
+ const filter = normalizeMemoListFilter(c.req.query("filter"));
+ const limit = clampNumber(Number(c.req.query("limit") ?? DEFAULT_MEMO_LIST_LIMIT), 1, MAX_MEMO_LIST_LIMIT);
+ const cursor = decodeMemoListCursor(c.req.query("cursor"), sort);
const deletedClause = includeTrash ? "m.is_deleted = 1" : "m.is_deleted = 0";
+ const titleSortExpression = `LOWER(COALESCE(NULLIF(m.title, ''), '${UNTITLED_MEMO_TITLE}'))`;
+ const baseConditions = [deletedClause];
+ const baseBinds: unknown[] = [];
+
+ if (notebookId) {
+ baseConditions.push("m.notebook_id = ?");
+ baseBinds.push(notebookId);
+ }
+
+ if (filter === "tagged") {
+ baseConditions.push("m.tags_json <> '[]'");
+ } else if (filter === "untagged") {
+ baseConditions.push("m.tags_json = '[]'");
+ } else if (filter === "pinned") {
+ baseConditions.push("m.is_pinned = 1");
+ }
+
+ const getOrderBy = () => {
+ if (includeTrash) {
+ return "m.deleted_at DESC, m.id DESC";
+ }
+
+ if (sort === "created-desc") {
+ return "m.is_pinned DESC, m.created_at DESC, m.id DESC";
+ }
+
+ if (sort === "title-asc") {
+ return `m.is_pinned DESC, ${titleSortExpression} ASC, m.updated_at DESC, m.id DESC`;
+ }
+
+ return "m.is_pinned DESC, m.updated_at DESC, m.id DESC";
+ };
+
+ const cursorConditions = [...baseConditions];
+ const cursorBinds = [...baseBinds];
+
+ if (cursor) {
+ if (includeTrash) {
+ cursorConditions.push("(m.deleted_at < ? OR (m.deleted_at = ? AND m.id < ?))");
+ cursorBinds.push(cursor.deletedAt ?? "", cursor.deletedAt ?? "", cursor.id);
+ } else if (sort === "created-desc") {
+ cursorConditions.push("(m.is_pinned < ? OR (m.is_pinned = ? AND (m.created_at < ? OR (m.created_at = ? AND m.id < ?))))");
+ cursorBinds.push(cursor.pinned ?? 0, cursor.pinned ?? 0, cursor.createdAt ?? "", cursor.createdAt ?? "", cursor.id);
+ } else if (sort === "title-asc") {
+ cursorConditions.push(
+ `(m.is_pinned < ? OR (m.is_pinned = ? AND (${titleSortExpression} > ? OR (${titleSortExpression} = ? AND (m.updated_at < ? OR (m.updated_at = ? AND m.id < ?))))))`
+ );
+ cursorBinds.push(cursor.pinned ?? 0, cursor.pinned ?? 0, cursor.title ?? "", cursor.title ?? "", cursor.updatedAt ?? "", cursor.updatedAt ?? "", cursor.id);
+ } else {
+ cursorConditions.push("(m.is_pinned < ? OR (m.is_pinned = ? AND (m.updated_at < ? OR (m.updated_at = ? AND m.id < ?))))");
+ cursorBinds.push(cursor.pinned ?? 0, cursor.pinned ?? 0, cursor.updatedAt ?? "", cursor.updatedAt ?? "", cursor.id);
+ }
+ }
+
+ const pageLimit = limit + 1;
if (q) {
const ftsQuery = toFtsQuery(q);
const likeQuery = `%${escapeLike(q)}%`;
if (ftsQuery) {
+ const searchPrefix = [ftsQuery, likeQuery, likeQuery, likeQuery];
const [rows, totalRow] = await Promise.all([
c.env.DB.prepare(
`WITH raw_matches(memo_id, rank) AS (
@@ -726,16 +801,15 @@ app.get("/api/v1/memos", async (c) => {
GROUP BY memo_id
)
SELECT m.id, m.notebook_id, m.title, m.excerpt, m.tags_json, m.is_pinned,
- m.is_archived, m.is_deleted, m.created_at, m.updated_at, m.deleted_at, c.revision
+ m.is_archived, m.is_deleted, m.created_at, m.updated_at, m.deleted_at, mc.revision
FROM search_matches s
INNER JOIN memos m ON m.id = s.memo_id
- INNER JOIN memo_contents c ON c.memo_id = m.id
- WHERE ${deletedClause}
- AND (? IS NULL OR m.notebook_id = ?)
- ORDER BY s.rank ASC, m.is_pinned DESC, m.updated_at DESC
+ INNER JOIN memo_contents mc ON mc.memo_id = m.id
+ WHERE ${cursorConditions.join(" AND ")}
+ ORDER BY ${getOrderBy()}
LIMIT ?`
)
- .bind(ftsQuery, likeQuery, likeQuery, likeQuery, notebookId ?? null, notebookId ?? null, limit)
+ .bind(...searchPrefix, ...cursorBinds, pageLimit)
.all<MemoSummaryRow>(),
c.env.DB.prepare(
`WITH raw_matches(memo_id) AS (
@@ -760,41 +834,75 @@ app.get("/api/v1/memos", async (c) => {
SELECT COUNT(*) AS count
FROM search_matches s
INNER JOIN memos m ON m.id = s.memo_id
- WHERE ${deletedClause}
- AND (? IS NULL OR m.notebook_id = ?)`
+ WHERE ${baseConditions.join(" AND ")}`
)
- .bind(ftsQuery, likeQuery, likeQuery, likeQuery, notebookId ?? null, notebookId ?? null)
+ .bind(...searchPrefix, ...baseBinds)
.first<{ count: number }>(),
]);
- return c.json({ memos: rows.results.map(mapMemoSummary), totalCount: totalRow?.count ?? rows.results.length });
+ const page = rows.results.slice(0, limit);
+ const nextCursor = rows.results.length > limit ? encodeMemoListCursor(page[page.length - 1], sort, includeTrash) : null;
+
+ return c.json({ memos: page.map(mapMemoSummary), totalCount: totalRow?.count ?? page.length, nextCursor });
}
+
+ const searchConditions = [...baseConditions, "(m.title LIKE ? ESCAPE '\\' OR mc.content_text LIKE ? ESCAPE '\\' OR m.tags_json LIKE ? ESCAPE '\\')"];
+ const searchBinds = [...baseBinds, likeQuery, likeQuery, likeQuery];
+ const searchCursorConditions = [...cursorConditions, "(m.title LIKE ? ESCAPE '\\' OR mc.content_text LIKE ? ESCAPE '\\' OR m.tags_json LIKE ? ESCAPE '\\')"];
+ const searchCursorBinds = [...cursorBinds, likeQuery, likeQuery, likeQuery];
+ const [rows, totalRow] = await Promise.all([
+ c.env.DB.prepare(
+ `SELECT m.id, m.notebook_id, m.title, m.excerpt, m.tags_json, m.is_pinned,
+ m.is_archived, m.is_deleted, m.created_at, m.updated_at, m.deleted_at, mc.revision
+ FROM memos m
+ INNER JOIN memo_contents mc ON mc.memo_id = m.id
+ WHERE ${searchCursorConditions.join(" AND ")}
+ ORDER BY ${getOrderBy()}
+ LIMIT ?`
+ )
+ .bind(...searchCursorBinds, pageLimit)
+ .all<MemoSummaryRow>(),
+ c.env.DB.prepare(
+ `SELECT COUNT(*) AS count
+ FROM memos m
+ INNER JOIN memo_contents mc ON mc.memo_id = m.id
+ WHERE ${searchConditions.join(" AND ")}`
+ )
+ .bind(...searchBinds)
+ .first<{ count: number }>(),
+ ]);
+
+ const page = rows.results.slice(0, limit);
+ const nextCursor = rows.results.length > limit ? encodeMemoListCursor(page[page.length - 1], sort, includeTrash) : null;
+
+ return c.json({ memos: page.map(mapMemoSummary), totalCount: totalRow?.count ?? page.length, nextCursor });
}
const [rows, totalRow] = await Promise.all([
c.env.DB.prepare(
`SELECT m.id, m.notebook_id, m.title, m.excerpt, m.tags_json, m.is_pinned,
- m.is_archived, m.is_deleted, m.created_at, m.updated_at, m.deleted_at, c.revision
+ m.is_archived, m.is_deleted, m.created_at, m.updated_at, m.deleted_at, mc.revision
FROM memos m
- INNER JOIN memo_contents c ON c.memo_id = m.id
- WHERE ${deletedClause}
- AND (? IS NULL OR m.notebook_id = ?)
- ORDER BY ${includeTrash ? "m.deleted_at DESC," : "m.is_pinned DESC,"} m.updated_at DESC
+ INNER JOIN memo_contents mc ON mc.memo_id = m.id
+ WHERE ${cursorConditions.join(" AND ")}
+ ORDER BY ${getOrderBy()}
LIMIT ?`
)
- .bind(notebookId ?? null, notebookId ?? null, limit)
+ .bind(...cursorBinds, pageLimit)
.all<MemoSummaryRow>(),
c.env.DB.prepare(
`SELECT COUNT(*) AS count
FROM memos m
- WHERE ${deletedClause}
- AND (? IS NULL OR m.notebook_id = ?)`
+ WHERE ${baseConditions.join(" AND ")}`
)
- .bind(notebookId ?? null, notebookId ?? null)
+ .bind(...baseBinds)
.first<{ count: number }>(),
]);
- return c.json({ memos: rows.results.map(mapMemoSummary), totalCount: totalRow?.count ?? rows.results.length });
+ const page = rows.results.slice(0, limit);
+ const nextCursor = rows.results.length > limit ? encodeMemoListCursor(page[page.length - 1], sort, includeTrash) : null;
+
+ return c.json({ memos: page.map(mapMemoSummary), totalCount: totalRow?.count ?? page.length, nextCursor });
});
app.post("/api/v1/memos", zValidator("json", MemoCreateSchema), async (c) => {
@@ -3934,6 +4042,12 @@ const normalizeMemoTitle = (value: string | null | undefined) => {
return title || DEFAULT_MEMO_TITLE;
};
+const normalizeMemoListSort = (value: string | undefined): MemoListSortMode =>
+ value === "created-desc" || value === "title-asc" ? value : "updated-desc";
+
+const normalizeMemoListFilter = (value: string | undefined): MemoListFilterMode =>
+ value === "tagged" || value === "untagged" || value === "pinned" ? value : "all";
+
const clampNumber = (value: number, min: number, max: number) => {
if (Number.isNaN(value)) {
return min;
@@ -3942,6 +4056,59 @@ const clampNumber = (value: number, min: number, max: number) => {
return Math.min(Math.max(value, min), max);
};
+const encodeMemoListCursor = (memo: MemoSummaryRow, sort: MemoListSortMode, includeTrash: boolean) => {
+ const cursor: MemoListCursor = {
+ sort,
+ id: memo.id,
+ };
+
+ if (includeTrash) {
+ cursor.deletedAt = memo.deleted_at;
+ } else {
+ cursor.pinned = memo.is_pinned;
+ }
+
+ if (sort === "created-desc") {
+ cursor.createdAt = memo.created_at;
+ } else if (sort === "title-asc") {
+ cursor.title = normalizeMemoTitle(memo.title).toLocaleLowerCase();
+ cursor.updatedAt = memo.updated_at;
+ } else {
+ cursor.updatedAt = memo.updated_at;
+ }
+
+ const bytes = new TextEncoder().encode(JSON.stringify(cursor));
+ let binary = "";
+
+ for (const byte of bytes) {
+ binary += String.fromCharCode(byte);
+ }
+
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
+};
+
+const decodeMemoListCursor = (value: string | undefined, sort: MemoListSortMode): MemoListCursor | null => {
+ if (!value) {
+ return null;
+ }
+
+ try {
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
+ const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
+ const binary = atob(padded);
+ const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
+ const cursor = JSON.parse(new TextDecoder().decode(bytes)) as Partial<MemoListCursor>;
+
+ if (cursor.sort !== sort || typeof cursor.id !== "string") {
+ return null;
+ }
+
+ return cursor as MemoListCursor;
+ } catch {
+ return null;
+ }
+};
+
const toFtsQuery = (value: string) => {
const tokens = value.match(/[\p{L}\p{N}_]+/gu) ?? [];
return tokens
diff --git a/apps/web/src/components/MemoListPane.tsx b/apps/web/src/components/MemoListPane.tsx
index 5c66b447..cece830e 100644
--- a/apps/web/src/components/MemoListPane.tsx
+++ b/apps/web/src/components/MemoListPane.tsx
@@ -61,8 +61,6 @@ import type { SyncQueueSummary } from "@/lib/sync-queue";
import {
MEMO_FILTER_OPTIONS,
MEMO_SORT_OPTIONS,
- filterMemos,
- sortMemos,
getNotebookMoveOptions,
readMemoListDensityPreference,
writeMemoListDensityPreference,
@@ -305,6 +303,8 @@ export const MemoListPane = ({
notebook,
memos,
totalMemoCount,
+ hasMoreMemos,
+ isLoadingMoreMemos,
selectedMemoId,
selectedMemoIds,
selectionMode,
@@ -318,6 +318,11 @@ export const MemoListPane = ({
search,
searchFocusToken,
mobileSearchActive,
+ filterMode,
+ sortMode,
+ onFilterModeChange,
+ onSortModeChange,
+ onLoadMoreMemos,
onOpenMemo,
onDeleteMemo,
onRestoreMemo,
@@ -366,6 +371,8 @@ export const MemoListPane = ({
notebook: Notebook | null;
memos: MemoSummary[];
totalMemoCount: number;
+ hasMoreMemos: boolean;
+ isLoadingMoreMemos: boolean;
selectedMemoId: string | null;
selectedMemoIds: Set<string>;
selectionMode: boolean;
@@ -379,6 +386,11 @@ export const MemoListPane = ({
search: string;
searchFocusToken: number;
mobileSearchActive: boolean;
+ filterMode: MemoFilterMode;
+ sortMode: MemoSortMode;
+ onFilterModeChange: (filterMode: MemoFilterMode) => void;
+ onSortModeChange: (sortMode: MemoSortMode) => void;
+ onLoadMoreMemos: () => void;
onOpenMemo: (memoId: string) => void;
onDeleteMemo: (memoId: string) => void;
onRestoreMemo: (memoId: string) => void;
@@ -417,17 +429,13 @@ export const MemoListPane = ({
}) => {
const [memoContextMenu, setMemoContextMenu] = useState<MemoContextMenuState | null>(null);
const [contextMoveOpen, setContextMoveOpen] = useState(false);
- const [filterMode, setFilterMode] = useState<MemoFilterMode>("all");
- const [sortMode, setSortMode] = useState<MemoSortMode>("updated-desc");
const [listDensity, setListDensity] = useState<MemoListDensity>(() => readMemoListDensityPreference());
const [lastSelectedMemoId, setLastSelectedMemoId] = useState<string | null>(null);
const [moveTargetNotebookId, setMoveTargetNotebookId] = useState("");
const filterOptions = MEMO_FILTER_OPTIONS;
const mobileFilterOptions = useMemo(() => filterOptions.filter((option: any) => option.value !== "all"), [filterOptions]);
- const filteredMemos = useMemo(() => filterMemos(memos, filterMode), [filterMode, memos]);
- const sortedMemos = useMemo(() => sortMemos(filteredMemos, sortMode, view !== "trash"), [filteredMemos, sortMode, view]);
- const visibleMemoIds = useMemo(() => sortedMemos.map((memo) => memo.id), [sortedMemos]);
+ const visibleMemoIds = useMemo(() => memos.map((memo) => memo.id), [memos]);
const moveNotebookOptions = useMemo(() => getNotebookMoveOptions(notebooks), [notebooks]);
const selectedMemosInList = useMemo(() => memos.filter((memo) => selectedMemoIds.has(memo.id)), [memos, selectedMemoIds]);
@@ -447,7 +455,7 @@ export const MemoListPane = ({
const listTitle = view === "trash" ? "回收站" : notebook?.name ?? "全部笔记";
const listContextLabel = view === "trash" ? "已删除笔记" : notebook ? "当前笔记本" : "所有笔记本";
- const listCountLabel = `${filteredMemos.length}${filterMode !== "all" || filteredMemos.length !== totalMemoCount ? ` / ${totalMemoCount}` : ""} ${
+ const listCountLabel = `${memos.length}${memos.length !== totalMemoCount ? ` / ${totalMemoCount}` : ""} ${
view === "trash" ? "条已删除" : "条笔记"
}`;
const selectionCountLabel = getSelectionCountLabel(selectedMemoIds.size);
@@ -510,9 +518,32 @@ export const MemoListPane = ({
useEffect(() => {
if (!filterOptions.some((option) => option.value === filterMode)) {
- setFilterMode("all");
+ onFilterModeChange("all");
}
- }, [filterMode, filterOptions]);
+ }, [filterMode, filterOptions, onFilterModeChange]);
+
+ useEffect(() => {
+ if (!hasMoreMemos || isLoadingMoreMemos) {
+ return;
+ }
+
+ const scrollContainer = listScrollRef.current;
+ if (!scrollContainer) {
+ return;
+ }
+
+ const handleScroll = () => {
+ const remaining = scrollContainer.scrollHeight - scrollContainer.scrollTop - scrollContainer.clientHeight;
+
+ if (remaining < 480) {
+ onLoadMoreMemos();
+ }
+ };
+
+ handleScroll();
+ scrollContainer.addEventListener("scroll", handleScroll, { passive: true });
+ return () => scrollContainer.removeEventListener("scroll", handleScroll);
+ }, [hasMoreMemos, isLoadingMoreMemos, onLoadMoreMemos]);
useEffect(() => {
const scrollContainer = listScrollRef.current;
@@ -746,14 +777,14 @@ export const MemoListPane = ({
const handleResetListConstraints = () => {
onClearSelection();
- setFilterMode("all");
+ onFilterModeChange("all");
onSearch("");
focusSearchInput();
};
const handleFilterModeChange = (value: MemoFilterMode) => {
onClearSelection();
- setFilterMode(value);
+ onFilterModeChange(value);
};
const handleListDensityChange = (value: MemoListDensity) => {
@@ -1016,7 +1047,7 @@ export const MemoListPane = ({
"flex h-9 w-full items-center gap-2 px-3 text-left text-sm cursor-pointer outline-none",
sortMode === option.value ? "bg-slate-100 text-slate-900" : "text-slate-700 hover:bg-slate-50"
)}
- onClick={() => setSortMode(option.value)}
+ onClick={() => onSortModeChange(option.value)}
>
<span className="min-w-0 flex-1 truncate">{option.label}</span>
</DropdownMenuItem>
@@ -1171,7 +1202,7 @@ export const MemoListPane = ({
{hasListConstraint && (
<div className="mt-3 flex min-h-8 items-center gap-2 rounded-md border border-slate-200 bg-white px-3 py-1.5 text-xs text-slate-500">
<span className="min-w-0 flex-1 truncate">
- {search.trim() ? `搜索「${search.trim()}」` : `筛选:${activeFilterLabel}`} · {filteredMemos.length} 条
+ {search.trim() ? `搜索「${search.trim()}」` : `筛选:${activeFilterLabel}`} · {totalMemoCount} 条
</span>
<button
className="shrink-0 font-semibold text-slate-600 transition hover:text-slate-950"
@@ -1201,7 +1232,7 @@ export const MemoListPane = ({
重新拉取
</Button>
</div>
- ) : filteredMemos.length === 0 ? (
+ ) : memos.length === 0 ? (
<div className="rounded-md border border-dashed border-slate-300 bg-white px-4 py-9 text-center">
<div className="text-sm font-semibold text-slate-800">
{memos.length === 0 ? (view === "trash" ? "回收站为空" : "暂无笔记") : "没有符合筛选的笔记"}
@@ -1223,7 +1254,7 @@ export const MemoListPane = ({
) : (
<div className="space-y-4 lg:space-y-0 lg:overflow-hidden lg:rounded-sm lg:border-y lg:border-slate-200 lg:bg-white">
<div className="space-y-3 lg:space-y-0">
- {sortedMemos.map((memo) => (
+ {memos.map((memo) => (
<MemoCard
key={memo.id}
memo={memo}
@@ -1245,6 +1276,11 @@ export const MemoListPane = ({
/>
))}
</div>
+ {isLoadingMoreMemos && (
+ <div className="border-t border-slate-100 px-4 py-3 text-center text-xs font-medium text-slate-500">
+ 正在加载更多笔记
+ </div>
+ )}
</div>
)}
</div>
@@ -1425,7 +1461,7 @@ export const MemoListPane = ({
handleListDensityChange(value);
}}
onSortModeChange={(value) => {
- setSortMode(value);
+ onSortModeChange(value);
}}
/>
</Suspense>
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index fab29a9d..196f62e6 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -12,7 +12,7 @@ import {
type KeyboardEvent as ReactKeyboardEvent,
type PointerEvent as ReactPointerEvent,
} from "react";
-import { useQuery, useMutation, useQueryClient, type QueryClient } from "@tanstack/react-query";
+import { useInfiniteQuery, useQuery, useMutation, useQueryClient, type QueryClient } from "@tanstack/react-query";
import { Home, Search, UserRound, Plus, ChevronDown, ChevronRight, RefreshCw, X } from "lucide-react";
import { useLocation, useNavigate } from "react-router";
import { Button } from "@/components/ui/button";
@@ -40,6 +40,8 @@ import type {
NotebookMoveOption,
MemoTemplate,
ShortcutSettings,
+ MemoFilterMode,
+ MemoSortMode,
} from "@/lib/app-helpers";
import {
DEFAULT_MEMO_TITLE,
@@ -140,15 +142,6 @@ const cacheMemoDetail = (queryClient: QueryClient, memo: MemoDetail, view: MemoV
queryClient.setQueryData(memoDetailQueryKey(memo.id, view), { memo });
};
-const prependMemoSummaryToList = (queryClient: QueryClient, queryKey: readonly unknown[], memo: MemoDetail) => {
- const summary = memoToSummary(memo);
-
- queryClient.setQueryData<{ memos: MemoSummary[]; totalCount?: number }>(queryKey, (current) => ({
- memos: [summary, ...(current?.memos ?? []).filter((item) => item.id !== memo.id)],
- totalCount: (current?.totalCount ?? current?.memos.length ?? 0) + 1,
- }));
-};
-
const MobileBottomNavButton = ({
active = false,
icon,
@@ -524,6 +517,8 @@ export const WorkspaceApp = ({
const [noteReplaceFocusToken, setNoteReplaceFocusToken] = useState(0);
const [memoListWidth, setMemoListWidth] = useState(readMemoListWidthPreference);
const [search, setSearch] = useState("");
+ const [memoFilterMode, setMemoFilterMode] = useState<MemoFilterMode>("all");
+ const [memoSortMode, setMemoSortMode] = useState<MemoSortMode>("updated-desc");
const [syncSummary, setSyncSummary] = useState<SyncQueueSummary>(emptySyncQueueSummary);
const [isOnline, setIsOnline] = useState(() => (typeof navigator === "undefined" ? true : navigator.onLine));
const [isDesktop, setIsDesktop] = useState(isDesktopViewport);
@@ -908,18 +903,40 @@ export const WorkspaceApp = ({
return () => window.clearInterval(timer);
}, [runQueuedSync, syncSummary.total]);
- const memosQuery = useQuery({
- queryKey: ["memos", memoView, selectedNotebookId, search],
- queryFn: () =>
+ const memosQuery = useInfiniteQuery({
+ queryKey: ["memos", memoView, selectedNotebookId, search, memoFilterMode, memoSortMode],
+ queryFn: ({ pageParam }) =>
api.listMemos({
notebookId: memoView === "notebook" ? selectedNotebookId : null,
q: search,
trash: memoView === "trash",
+ filter: memoFilterMode,
+ sort: memoSortMode,
+ cursor: pageParam,
}),
+ initialPageParam: null as string | null,
+ getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
});
- const memos = memosQuery.data?.memos ?? [];
- const totalMemoCount = memosQuery.data?.totalCount ?? memos.length;
+ const memos = useMemo(() => {
+ const memoMap = new Map<string, MemoSummary>();
+
+ for (const page of memosQuery.data?.pages ?? []) {
+ for (const memo of page.memos) {
+ memoMap.set(memo.id, memo);
+ }
+ }
+
+ return Array.from(memoMap.values());
+ }, [memosQuery.data?.pages]);
+ const totalMemoCount = memosQuery.data?.pages[0]?.totalCount ?? memos.length;
+ const handleLoadMoreMemos = useCallback(() => {
+ if (!memosQuery.hasNextPage || memosQuery.isFetchingNextPage) {
+ return;
+ }
+
+ void memosQuery.fetchNextPage();
+ }, [memosQuery]);
const selectedMemoIndex = selectedMemoId ? memos.findIndex((memo) => memo.id === selectedMemoId) : -1;
const previousMemoId = selectedMemoIndex > 0 ? memos[selectedMemoIndex - 1]?.id : null;
const nextMemoId =
@@ -988,10 +1005,6 @@ export const WorkspaceApp = ({
setSelectedNotebookId(targetNotebookId);
}
cacheMemoDetail(queryClient, data.memo, "notebook");
- prependMemoSummaryToList(queryClient, ["memos", "notebook", targetNotebookId, ""], data.memo);
- if (targetNotebookId !== null) {
- prependMemoSummaryToList(queryClient, ["memos", "notebook", null, ""], data.memo);
- }
void Promise.all([
queryClient.invalidateQueries({ queryKey: ["memos"] }),
queryClient.invalidateQueries({ queryKey: ["notebooks"] }),
@@ -1042,17 +1055,8 @@ export const WorkspaceApp = ({
]);
const memoIdSet = new Set(memoIds);
- const previousMemoQueries = queryClient.getQueriesData<{ memos: MemoSummary[]; totalCount?: number }>({ queryKey: ["memos"] });
const previousMemoDetailQueries = queryClient.getQueriesData<{ memo: MemoDetail }>({ queryKey: ["memo"] });
- queryClient.setQueriesData<{ memos: MemoSummary[]; totalCount?: number }>({ queryKey: ["memos"] }, (current) =>
- current
- ? {
- ...current,
- memos: current.memos.map((memo) => (memoIdSet.has(memo.id) ? { ...memo, isPinned } : memo)),
- }
- : current
- );
queryClient.setQueriesData<{ memo: MemoDetail }>({ queryKey: ["memo"] }, (current) =>
current && memoIdSet.has(current.memo.id)
? {
@@ -1061,12 +1065,9 @@ export const WorkspaceApp = ({
: current
);
- return { previousMemoQueries, previousMemoDetailQueries };
+ return { previousMemoDetailQueries };
},
onError: (_error, _variables, context) => {
- context?.previousMemoQueries.forEach(([queryKey, data]) => {
- queryClient.setQueryData(queryKey, data);
- });
context?.previousMemoDetailQueries.forEach(([queryKey, data]) => {
queryClient.setQueryData(queryKey, data);
});
@@ -1998,12 +1999,19 @@ export const WorkspaceApp = ({
view={memoView}
memos={memos}
totalMemoCount={totalMemoCount}
+ hasMoreMemos={Boolean(memosQuery.hasNextPage)}
+ isLoadingMoreMemos={memosQuery.isFetchingNextPage}
selectedMemoId={selectedMemoId}
selectedMemoIds={selectedMemoIds}
selectionMode={memoSelectionModeActive}
search={search}
+ filterMode={memoFilterMode}
+ sortMode={memoSortMode}
mobileSearchActive={mobileSearchActive}
searchFocusToken={mobileSearchFocusToken}
+ onFilterModeChange={setMemoFilterMode}
+ onSortModeChange={setMemoSortMode}
+ onLoadMoreMemos={handleLoadMoreMemos}
canCreateMemo={canCreateMemo}
isLoading={memosQuery.isLoading}
isRefreshing={memosQuery.isFetching}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 4f4853fa..a7140a39 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -12,6 +12,7 @@ import type {
TagSummary,
TiptapDoc,
} from "@edgeever/shared";
+import type { MemoFilterMode, MemoSortMode } from "./app-helpers";
type ListNotebooksResponse = {
notebooks: Notebook[];
@@ -20,6 +21,7 @@ type ListNotebooksResponse = {
type ListMemosResponse = {
memos: MemoSummary[];
totalCount: number;
+ nextCursor: string | null;
};
type ListMemoRevisionsResponse = {
@@ -155,7 +157,15 @@ export const api = {
method: "DELETE",
}),
- listMemos: (params: { notebookId?: string | null; q?: string; trash?: boolean }) => {
+ listMemos: (params: {
+ notebookId?: string | null;
+ q?: string;
+ trash?: boolean;
+ sort?: MemoSortMode;
+ filter?: MemoFilterMode;
+ cursor?: string | null;
+ limit?: number;
+ }) => {
const search = new URLSearchParams();
if (params.notebookId) {
@@ -170,6 +180,22 @@ export const api = {
search.set("trash", "1");
}
+ if (params.sort) {
+ search.set("sort", params.sort);
+ }
+
+ if (params.filter && params.filter !== "all") {
+ search.set("filter", params.filter);
+ }
+
+ if (params.cursor) {
+ search.set("cursor", params.cursor);
+ }
+
+ if (params.limit) {
+ search.set("limit", String(params.limit));
+ }
+
return request<ListMemosResponse>(`/api/v1/memos?${search.toString()}`);
},
diff --git a/docs/openapi.json b/docs/openapi.json
index d83f9224..ddded01e 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -377,8 +377,33 @@
"schema": {
"type": "integer",
"minimum": 1,
- "maximum": 5000,
- "default": 5000
+ "maximum": 200,
+ "default": 100
+ }
+ },
+ {
+ "name": "cursor",
+ "in": "query",
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "sort",
+ "in": "query",
+ "schema": {
+ "type": "string",
+ "enum": ["updated-desc", "created-desc", "title-asc"],
+ "default": "updated-desc"
+ }
+ },
+ {
+ "name": "filter",
+ "in": "query",
+ "schema": {
+ "type": "string",
+ "enum": ["all", "tagged", "untagged", "pinned"],
+ "default": "all"
}
}
],
@@ -399,9 +424,12 @@
"totalCount": {
"type": "integer",
"minimum": 0
+ },
+ "nextCursor": {
+ "type": ["string", "null"]
}
},
- "required": ["memos", "totalCount"]
+ "required": ["memos", "totalCount", "nextCursor"]
}
}
}