+
{rows.map((item) => (
))}
diff --git a/convex/screening/discussion.ts b/convex/screening/discussion.ts
index 72b7e505b..b1f5ba2d5 100644
--- a/convex/screening/discussion.ts
+++ b/convex/screening/discussion.ts
@@ -20,14 +20,26 @@ import { SCREENING_TEXT } from "./validators";
const LINES = 100;
const ANSWERED = 200;
-/** The paper and what the person is to its screening, where they may read what was written about it. */
-async function readable(ctx: Pick, actor: InWorkspace, jobId: Id<"screeningJobs">, paperId: Id<"screeningResults">) {
+/**
+ * What the person is to a screening, worked out once, and a way to ask of any of its papers whether they may read
+ * what was written about it: the paper with their standing, or null. Null for a screening they can't open.
+ */
+async function readerOf(ctx: Pick, actor: InWorkspace, jobId: Id<"screeningJobs">) {
const standing = await standingOn(ctx, actor, jobId);
- const paper = standing?.job.shape === 2 ? await ctx.db.get("screeningResults", paperId) : null;
- if (!standing || paper?.jobId !== jobId) return null;
- const [votes, reviewers] = await Promise.all([votesOf(ctx, paperId), reviewersOf(ctx, jobId)]);
- const kinds = new Map(reviewers.map((one) => [one._id, one.kind]));
- return seesPaper(standing.job, paper.result, votes, (id) => kinds.get(id), standing.reviewer?._id) ? { ...standing, paper } : null;
+ if (!standing || standing.job.shape !== 2) return null;
+ const kinds = new Map((await reviewersOf(ctx, jobId)).map((one) => [one._id, one.kind]));
+ return async (paperId: Id<"screeningResults">) => {
+ const paper = await ctx.db.get("screeningResults", paperId);
+ if (paper?.jobId !== jobId) return null;
+ return seesPaper(standing.job, paper.result, await votesOf(ctx, paperId), (id) => kinds.get(id), standing.reviewer?._id) ? { ...standing, paper } : null;
+ };
+}
+
+/** The people some lines name, each read once. */
+async function peopleIn(ctx: Pick, lines: Array<{ by: Id<"users">; to?: Id<"users"> }>) {
+ const ids = [...new Set(lines.flatMap((line) => [line.by, ...(line.to ? [line.to] : [])]))];
+ const users = await Promise.all(ids.map((id) => ctx.db.get("users", id)));
+ return new Map(ids.map((id, at) => [id, personOf(users[at] ?? null, id)]));
}
const person = v.object({ id: v.id("users"), name: v.string(), imageUrl: v.optional(v.string()) });
@@ -38,14 +50,10 @@ export const threadAction = defineUserQuery({
args: { jobId: v.id("screeningJobs"), paperId: v.id("screeningResults"), paginationOpts: paginationOptsValidator },
returns: paginationResultValidator(v.object({ id: v.id("screeningMessages"), by: person, at: v.number(), text: v.string(), to: v.optional(person), open: v.optional(v.boolean()) })),
run: async (ctx, actor, { jobId, paperId, paginationOpts }) => {
- if (!(await readable(ctx, actor, jobId, paperId))) return { page: [], isDone: true, continueCursor: "" };
+ if (!(await (await readerOf(ctx, actor, jobId))?.(paperId))) return { page: [], isDone: true, continueCursor: "" };
const read = await ctx.db.query("screeningMessages").withIndex("by_result", (q) => q.eq("resultId", paperId)).order("desc").paginate({ ...paginationOpts, numItems: Math.min(paginationOpts.numItems, LINES) });
const lines = read.page;
- const people = new Map, { id: Id<"users">; name: string; imageUrl?: string }>();
- for (const id of new Set(lines.flatMap((line) => [line.by, ...(line.to ? [line.to] : [])]))) {
- const user = await ctx.db.get("users", id);
- people.set(id, personOf(user, id));
- }
+ const people = await peopleIn(ctx, lines);
return { ...read, page: lines.map((line) => ({ id: line._id, by: people.get(line.by)!, at: line._creationTime, text: line.text, ...(line.to ? { to: people.get(line.to)! } : {}), ...(line.open ? { open: true } : {}) })) };
},
});
@@ -58,18 +66,15 @@ export const allAction = defineUserQuery({
args: { jobId: v.id("screeningJobs"), paginationOpts: paginationOptsValidator },
returns: paginationResultValidator(v.object({ id: v.id("screeningMessages"), paperId: v.id("screeningResults"), by: person, at: v.number(), text: v.string(), to: v.optional(person) })),
run: async (ctx, actor, { jobId, paginationOpts }) => {
- const standing = await standingOn(ctx, actor, jobId);
- if (!standing || standing.job.shape !== 2) return { page: [], isDone: true, continueCursor: "" };
+ const readable = await readerOf(ctx, actor, jobId);
+ if (!readable) return { page: [], isDone: true, continueCursor: "" };
const read = await ctx.db.query("screeningMessages").withIndex("by_job_and_to_and_open", (q) => q.eq("jobId", jobId)).paginate({ ...paginationOpts, numItems: Math.min(paginationOpts.numItems, LINES) });
// Each paper the page speaks of is looked at once: whether the person may read what was written about it.
- const seen = new Map, boolean>();
- for (const paperId of new Set(read.page.map((line) => line.resultId))) seen.set(paperId, (await readable(ctx, actor, jobId, paperId)) !== null);
- const lines = read.page.filter((line) => seen.get(line.resultId));
- const people = new Map, { id: Id<"users">; name: string; imageUrl?: string }>();
- for (const id of new Set(lines.flatMap((line) => [line.by, ...(line.to ? [line.to] : [])]))) {
- const user = await ctx.db.get("users", id);
- people.set(id, personOf(user, id));
- }
+ const papers = [...new Set(read.page.map((line) => line.resultId))];
+ const shown = await Promise.all(papers.map(readable));
+ const seen = new Set(papers.filter((_, at) => shown[at] !== null));
+ const lines = read.page.filter((line) => seen.has(line.resultId));
+ const people = await peopleIn(ctx, lines);
return { ...read, page: lines.map((line) => ({ id: line._id, paperId: line.resultId, by: people.get(line.by)!, at: line._creationTime, text: line.text, ...(line.to ? { to: people.get(line.to)! } : {}) })) };
},
});
@@ -85,7 +90,7 @@ export const say = workspaceMutation({
args: { jobId: v.id("screeningJobs"), paperId: v.id("screeningResults"), text: v.string(), to: v.optional(v.id("users")) },
returns: v.null(),
handler: async (ctx, actor, { jobId, paperId, text, to }) => {
- const place = await readable(ctx, actor, jobId, paperId);
+ const place = await (await readerOf(ctx, actor, jobId))?.(paperId);
if (!place) throw createError("NOT_FOUND", "Paper not found");
const { job, reviewer, paper } = place;
if (!reviewer && job.rule?.resolver !== actor.userId) throw createError("FORBIDDEN", "Only this screening's reviewers, and whoever settles its conflicts, write here.");
diff --git a/convex/screening/queries.ts b/convex/screening/queries.ts
index 6997ec87b..5c6a7acb4 100644
--- a/convex/screening/queries.ts
+++ b/convex/screening/queries.ts
@@ -427,7 +427,6 @@ export async function readScreeningResultsPage(ctx: QueryCtx, job: Doc<"screenin
}),
};
}
-export type ScreeningResultRow = Awaited>["page"][number];
/** One page of the results of a job the person may read; an empty page for anyone else. */
export const listScreeningResultsAction = defineUserQuery({
diff --git a/convex/screening/validators.ts b/convex/screening/validators.ts
index f44b9abd0..e5b8f56b4 100644
--- a/convex/screening/validators.ts
+++ b/convex/screening/validators.ts
@@ -94,15 +94,19 @@ export const screeningPaperInputValidator = v.object({
* The papers a job reads (#341), resolved on the server: a saved search by its ID in the
* browser, a collection, every saved paper, or an earlier job's included papers.
*/
-export const paperSetValidator = v.union(
+/** The sets a job reads and a screening's sources both name the same way. */
+const sharedSets = [
v.object({ kind: v.literal("search"), searchId: v.string() }),
v.object({ kind: v.literal("collection"), collectionId: v.id("collections") }),
v.object({ kind: v.literal("saved") }),
v.object({ kind: v.literal("screening"), jobId: v.id("screeningJobs") }),
- // The person's own Zotero library, or one collection of it, or a group's of theirs: read through their connected account.
- v.object({ kind: v.literal("zotero"), collectionKey: v.optional(v.string()), groupId: v.optional(v.string()) }),
// An Evidence Library's records as the person may read them there (plans/evidence-library-sources): its keys are kept when the job starts.
v.object({ kind: v.literal("evidenceLibrary"), libraryId: v.id("evidenceLibraries"), source: librarySourceValidator }),
+] as const;
+export const paperSetValidator = v.union(
+ ...sharedSets,
+ // The person's own Zotero library, or one collection of it, or a group's of theirs: read through their connected account.
+ v.object({ kind: v.literal("zotero"), collectionKey: v.optional(v.string()), groupId: v.optional(v.string()) }),
);
/** Where a job's included papers go: nowhere, a new collection by name, or one the person has. */
@@ -255,11 +259,7 @@ export const voteStatusValidator = v.union(v.literal("waiting"), v.literal("cast
* table kept in storage, PDFs kept in storage, or a pasted list of DOIs kept there too.
*/
export const sourceSetValidator = v.union(
- v.object({ kind: v.literal("search"), searchId: v.string() }),
- v.object({ kind: v.literal("collection"), collectionId: v.id("collections") }),
- v.object({ kind: v.literal("saved") }),
- v.object({ kind: v.literal("screening"), jobId: v.id("screeningJobs") }),
- v.object({ kind: v.literal("evidenceLibrary"), libraryId: v.id("evidenceLibraries"), source: librarySourceValidator }),
+ ...sharedSets,
// `deep`: with the collections under the one it names.
v.object({ kind: v.literal("zotero"), collectionKey: v.optional(v.string()), groupId: v.optional(v.string()), deep: v.optional(v.boolean()) }),
// `columns`: which of a table's columns is the title, the abstract and so on, where its headings didn't say.
diff --git a/lib/hooks/use-cursor-page.ts b/lib/hooks/use-cursor-page.ts
index 83a75b618..965477f52 100644
--- a/lib/hooks/use-cursor-page.ts
+++ b/lib/hooks/use-cursor-page.ts
@@ -14,7 +14,7 @@ type PageArgs = Omit;
type PageItem = Query["_returnType"]["page"][number];
type Read = { cursor: string | null; numItems: number };
type Result = { page: PageItem[]; isDone: boolean; continueCursor: string };
-type Shown = Result & { key: string; number: number; offset: number; from: Result[] };
+type Shown = Result & { key: string; list: string | undefined; number: number; offset: number; from: Result[] };
/** Where a page after the first starts, and how many rows the pages before it held. */
type Start = { cursor: string; offset: number };
/** The first page's place: one array, so a list at its first page is the same place on every draw. */
@@ -47,8 +47,13 @@ const invalidCursor = (error: Error) =>
* A list that ends exactly on a full page finds that out from the empty page after it, and
* stops offering next there until a row is added after it.
*/
-/** `open`: a query anyone may read, signed in or not, which doesn't wait for sign-in. */
-type Options = { open?: boolean };
+/**
+ * `open`: a query anyone may read, signed in or not, which doesn't wait for sign-in.
+ * `list`: what makes it another list rather than another page, search or order of the same one, such as a tab or a
+ * filter. While the rows up are of another list than the one asked for, `isOther` says so: a page shows skeletons
+ * then, never the last list's rows under the new tab, and only dims rows of the same list (`isStale`).
+ */
+type Options = { open?: boolean; list?: string };
/** `scroll: false` for a list that is one part of a long page: its next page opens where the list is, not at the page's top. */
type PlacedOptions = Options & { scroll?: boolean };
@@ -96,7 +101,7 @@ export function useCursorPageAt(name: string, query: Qu
return usePages({ placed, setPlaced: (next) => void setPlaced(next) }, query, args, pageSize, options);
}
-function usePages(place: Place | null, query: Query, args: PageArgs | "skip", pageSize: number, { open = false }: Options) {
+function usePages(place: Place | null, query: Query, args: PageArgs | "skip", pageSize: number, { open = false, list }: Options) {
const { canRunProtectedQueries } = useAuthReadiness();
// A page of another size starts somewhere else, so the size is part of what the pages are of.
const key = JSON.stringify([args, pageSize]);
@@ -180,11 +185,11 @@ function usePages(place: Place | null, query: Query, ar
// person works through it, the rows past its last read never reach it: it is read again from its start, which
// they fill. A sparse filter leaves it as short as it was, and it is then shown as it is.
setState({ ...current, reads: [{ cursor: starts.at(-1)?.cursor ?? null, numItems: pageSize }], id: id + 1, end: undefined, packed: count });
- } else if (shown?.key === key && shown.number === starts.length + 1 && shown.from.length === from.length && shown.from.every((result, i) => result === from[i])) {
+ } else if (shown?.key === key && shown.list === list && shown.number === starts.length + 1 && shown.from.length === from.length && shown.from.every((result, i) => result === from[i])) {
data = shown;
} else {
const offset = starts.at(-1)?.offset ?? 0;
- data = { key, number: starts.length + 1, offset, from, page: from.flatMap((result) => result.page), isDone: last.isDone, continueCursor: last.continueCursor };
+ data = { key, list, number: starts.length + 1, offset, from, page: from.flatMap((result) => result.page), isDone: last.isDone, continueCursor: last.continueCursor };
}
}
@@ -217,7 +222,14 @@ function usePages(place: Place | null, query: Query, ar
if (ended === undefined && peek !== undefined && peekAt === peek && !emptied && !passing && after !== undefined && !(after instanceof Error) && found !== foundBefore) setState({ ...current, found });
const more = ended === undefined ? peek === undefined || after instanceof Error || (after === undefined ? (foundBefore ?? true) : found) : found;
+ // A list not read (`"skip"`) lets go of the rows it showed: asked for again, it is another list's rows until it is read.
+ if (args === "skip" && shown !== undefined) setShown(undefined);
const visible = args === "skip" ? undefined : emptied ? shown : (data ?? shown);
+ // The list whose rows are up, or were last: another list asked for before the first rows arrive, or after a list
+ // not read (which counts as shown), is another's until its own rows come.
+ const [seen, setSeen] = useState(list);
+ const showing = args === "skip" ? list : (visible?.list ?? seen);
+ if (showing !== seen) setSeen(showing);
const page = visible?.number ?? want + 1;
// The same array until the page shown changes, so what's derived from it isn't rebuilt each render.
const items = useMemo(() => (visible?.page ?? []).slice(0, pageSize), [visible, pageSize]);
@@ -227,6 +239,8 @@ function usePages(place: Place | null, query: Query, ar
isLoading: visible === undefined || (page === 1 && peek !== undefined && ended === undefined && after === undefined && foundBefore === undefined),
/** What's shown is an earlier page or earlier arguments, still waiting for the new one. */
isStale: visible !== undefined && visible !== data,
+ /** What's up, or was last, is of another `list` than the one asked for, still waiting for it: its rows aren't this list's. */
+ isOther: showing !== list,
/** The number of the page shown, from 1; it moves when the page it steps to arrives. */
page,
/** How many rows the pages before the one shown held; short pages make it less than (page - 1) × size. */
diff --git a/tests/hooks/use-cursor-page.test.tsx b/tests/hooks/use-cursor-page.test.tsx
index eb0955091..9dc31b8be 100644
--- a/tests/hooks/use-cursor-page.test.tsx
+++ b/tests/hooks/use-cursor-page.test.tsx
@@ -84,6 +84,36 @@ describe("useCursorPage", () => {
expect(readAs({ cursor: null, numItems: 1 })).toBe(true);
});
+ it("says another list's rows are up from the moment another list is asked for, even before any rows arrived", () => {
+ server.pages.delete("|null");
+ server.pages.delete("x|null");
+ const { result, rerender } = renderHook(({ search, list }) => useCursorPage(query, { search }, 2, { list }), { initialProps: { search: undefined as string | undefined, list: "all" } });
+ expect(result.current).toMatchObject({ isLoading: true, isOther: false });
+ // Another tab asked for while the first is still read: whatever is open belongs to the tab before.
+ rerender({ search: "x", list: "mine" });
+ expect(result.current).toMatchObject({ isLoading: true, isOther: true });
+ server.pages.set("x|null", page(["x"], "", true));
+ rerender({ search: "x", list: "mine" });
+ expect(result.current).toMatchObject({ items: ["x"], isOther: false });
+ });
+
+ it("keeps the rows of the same list up, dimmed, for another search, and says they aren't another list's", () => {
+ server.pages.delete("x|null");
+ const { result, rerender } = renderHook(({ search }) => useCursorPage(query, { search }, 2, { list: "all" }), { initialProps: { search: undefined as string | undefined } });
+ rerender({ search: "x" });
+ expect(result.current).toMatchObject({ items: ["a", "b"], isStale: true, isOther: false });
+ });
+
+ it("lets go of its rows when it isn't read, so a list asked for after it is another's until it is read", () => {
+ const { result, rerender } = renderHook(({ skip, list }) => useCursorPage(query, skip ? "skip" : {}, 2, { list }), { initialProps: { skip: false, list: "all" } });
+ expect(result.current).toMatchObject({ items: ["a", "b"], isOther: false });
+ rerender({ skip: true, list: "you" });
+ expect(result.current).toMatchObject({ items: [], isOther: false });
+ server.pages.delete("|null");
+ rerender({ skip: false, list: "all" });
+ expect(result.current).toMatchObject({ items: [], isLoading: true, isOther: true });
+ });
+
it("steps back from a page its rows were all deleted from", () => {
const { result, rerender } = renderHook(() => useCursorPage(query, {}, 2));
act(() => result.current.next());