diff --git a/components/bookmarks-command-center/index.tsx b/components/bookmarks-command-center/index.tsx index 7982ae681..872ca8d1c 100644 --- a/components/bookmarks-command-center/index.tsx +++ b/components/bookmarks-command-center/index.tsx @@ -24,7 +24,7 @@ import { useAppToast } from "@/lib/toast"; import { COMMAND_CENTER_ITEMS_PER_PAGE } from "@/lib/constants/view-modes"; import type { BookmarkSortBy } from "@/lib/types"; import { LibraryPageShell } from "@/components/evidence-libraries/library-page-shell"; -import { ListLoading } from "@/components/evidence-libraries/list-controls"; +import { ListLoading, STALE_ROWS } from "@/components/evidence-libraries/list-controls"; import { usePersistedStoreReady } from "@/lib/use-persisted-store-ready"; import { useResearchStatus } from "@/lib/research/provider"; import { ResearchAccountChangedError } from "@/lib/research/binding"; @@ -224,7 +224,7 @@ export function BookmarksCommandCenter() { > {/* A page kept from before the filter, sort or search changed is dimmed and takes no clicks until its own arrives. */} -
+
{!ready ? error ? : : ) : read.items.length ? ( - // A full page's height while there are pages, so a short last page keeps the pager where it was. -
    - {read.items.map((submission) => ( - - ))} -
+ // A full page's height while there are pages, so a short last page keeps the pager where it was. Each list enters + // on a wrapper of its own: the list dims while the next is read, and one element never animates and transitions at once. +
+
    + {read.items.map((submission) => ( + + ))} +
+
) : ( {search || show !== "all" ? t("noMatches") : t("noneYet")} diff --git a/components/evidence-libraries/configuration/sections/added-papers-row.tsx b/components/evidence-libraries/configuration/sections/added-papers-row.tsx index c379bc962..b18c1197c 100644 --- a/components/evidence-libraries/configuration/sections/added-papers-row.tsx +++ b/components/evidence-libraries/configuration/sections/added-papers-row.tsx @@ -24,6 +24,7 @@ import { DisclosureButton, DisclosureContent } from "../disclosure-button"; import { SectionCard } from "../section-card"; import { StatusChip } from "../status-chip"; import { SourceCount, SourceRow, SourceSwitch } from "./source-row"; +import { STALE_ROWS } from "@/components/evidence-libraries/list-controls"; /** The running community the Added papers row reads, and the person's role there; null until it runs. */ export function useAddedPapersCommunity(libraryId: Id<"evidenceLibraries">) { @@ -101,7 +102,7 @@ export function AddedPapersRow({ libraryId, adding, onAddingChange }: {
{/* Every page holds five rows' height, so a short last page doesn't move the pager. */} -
    +
      {papers?.papers.map((paper) => (
    • diff --git a/components/evidence-libraries/list-controls.tsx b/components/evidence-libraries/list-controls.tsx index f7281d2cf..a286b476b 100644 --- a/components/evidence-libraries/list-controls.tsx +++ b/components/evidence-libraries/list-controls.tsx @@ -17,6 +17,11 @@ export const LIST_TILE = * Every filter shares the search box's small text. A select's value takes the * free space, so a wide select still reads from the left. */ +/** + * Rows of a list still up while the next page, search or order is read (`isStale` from lib/hooks/use-cursor-page.ts): + * dimmed and out of reach of the pointer, the same in every list. + */ +export const STALE_ROWS = "pointer-events-none opacity-60 transition-opacity"; export const LIST_FILTER = "border-transparent bg-inset text-xs shadow-none md:text-xs *:data-[slot=select-value]:flex-1"; /** diff --git a/components/evidence-libraries/public-communities.tsx b/components/evidence-libraries/public-communities.tsx index f639e1f14..292bded52 100644 --- a/components/evidence-libraries/public-communities.tsx +++ b/components/evidence-libraries/public-communities.tsx @@ -17,7 +17,7 @@ import { PUBLIC_PER_PAGE } from "@/lib/evidence-libraries/directory"; import type { Preloaded } from "convex/react"; import { preloadedQueryResult } from "convex/nextjs"; import { cn } from "@/lib/utils"; -import { LIST_FILTER, ListEmpty, ListLoading } from "./list-controls"; +import { LIST_FILTER, ListEmpty, ListLoading, STALE_ROWS } from "./list-controls"; import { FadeImage } from "@/components/ui/fade-image"; import { ApplyCorner } from "./applications/apply-corner"; import { fromCard, type Standing } from "./applications/apply-dialog"; @@ -79,7 +79,7 @@ export function PublicCommunities({ search, preloaded, heading, signedIn = false
        community._id).join(",")} // One column of the panel's width on a phone: an implicit column would be as wide as a card's whole name. - className={cn("grid grid-cols-1 content-start gap-4 @xl/public:grid-cols-2 @4xl/public:grid-cols-3", read.isStale && "opacity-60")} + className={cn("grid grid-cols-1 content-start gap-4 @xl/public:grid-cols-2 @4xl/public:grid-cols-3", read.isStale && STALE_ROWS)} inert={read.isStale || undefined} > {read.items.map((community) => )} diff --git a/components/evidence-libraries/your-communities.tsx b/components/evidence-libraries/your-communities.tsx index bd2fb15a7..89cab940f 100644 --- a/components/evidence-libraries/your-communities.tsx +++ b/components/evidence-libraries/your-communities.tsx @@ -29,7 +29,7 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigge import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectSeparator, SelectTrigger, SelectValue } from "@/components/ui/select"; import { PageStepper } from "@/components/shared/page-stepper"; import { AdminAreaLink } from "./admin-area-link"; -import { LIST_FILTER } from "./list-controls"; +import { LIST_FILTER, STALE_ROWS } from "./list-controls"; import { LibraryImage } from "./library-image"; import { LibraryStatusIcon, type LibraryOperation } from "./library-status-chip"; @@ -220,7 +220,7 @@ export function YourCommunities({ waiting = false, framed = false, search, perso ) : rows.length ? (
          {rows.map((community) => )} diff --git a/components/extraction/extraction-command-center.tsx b/components/extraction/extraction-command-center.tsx index 6425124ab..0db9ba0a0 100644 --- a/components/extraction/extraction-command-center.tsx +++ b/components/extraction/extraction-command-center.tsx @@ -24,7 +24,7 @@ import { import { CommandCenterFilters } from "@/components/command-center/command-center-toolbar"; import { BAR_ACTION, BAR_LABEL } from "@/components/evidence-libraries/configuration/panel-header"; import { LibraryPageShell } from "@/components/evidence-libraries/library-page-shell"; -import { ListLoading } from "@/components/evidence-libraries/list-controls"; +import { ListLoading, STALE_ROWS } from "@/components/evidence-libraries/list-controls"; import { ViewModeSwitch } from "@/components/view-mode-toggle"; import { JobListItem } from "./job-list-item"; import type { ViewMode } from "@/lib/types"; @@ -101,7 +101,7 @@ export function ExtractionCommandCenter() { > {/* Extractions shared with the person that wait for their answer, above their own. */} -
          +
          {/* The list waits for the invitations above it too, so they never push it down. */} {jobs.isLoading || invitations === undefined ? : | "pdf"; @@ -517,7 +518,7 @@ function List({ rows, empty, stale = false, pages = false, label, children }: { if (!rows) return

          {empty}

          ; return (
          -
          +
          {children}
          diff --git a/components/extraction/smart-pagination.tsx b/components/extraction/smart-pagination.tsx index 528c1f5f1..eae7b0ff9 100644 --- a/components/extraction/smart-pagination.tsx +++ b/components/extraction/smart-pagination.tsx @@ -10,7 +10,7 @@ import { SelectValue, } from "@/components/ui/select"; import { cn } from "@/lib/utils"; -import { LIST_FILTER } from "@/components/evidence-libraries/list-controls"; +import { LIST_FILTER, STALE_ROWS } from "@/components/evidence-libraries/list-controls"; import { useTranslations, useLocale } from "next-intl"; interface SmartPaginationProps { @@ -56,7 +56,7 @@ export function SmartPagination({ const endIdx = offset + displayedCount; return ( -
          +
          {/* Left: Results info */} {/* The sides share the row evenly, so the steps stay put when the count's text changes width. */}

          diff --git a/components/library/library-filter-content.tsx b/components/library/library-filter-content.tsx index 166aab323..81a17c516 100644 --- a/components/library/library-filter-content.tsx +++ b/components/library/library-filter-content.tsx @@ -29,6 +29,7 @@ import { useDebouncedValue } from "@/lib/hooks/use-debounced-value"; import { cn } from "@/lib/utils"; import { AutoHeight } from "@/components/ui/auto-height"; import { inWorkspace, useWorkspace } from "@/lib/workspaces/url"; +import { STALE_ROWS } from "@/components/evidence-libraries/list-controls"; /** * Combined sort options for the library sort dropdown. @@ -375,7 +376,7 @@ function CollectionFilterSection({ {/* Vertical list */}

          diff --git a/components/library/library-page-client.tsx b/components/library/library-page-client.tsx index 03e2b9e41..f63ad9909 100644 --- a/components/library/library-page-client.tsx +++ b/components/library/library-page-client.tsx @@ -62,6 +62,7 @@ import { LibraryEmptyState } from "./library-empty-state"; import { LibraryFilterSidebar } from "./library-filter-sidebar"; import { LibraryItemSkeleton } from "./library-item-skeleton"; import { inWorkspace, useWorkspace } from "@/lib/workspaces/url"; +import { STALE_ROWS } from "@/components/evidence-libraries/list-controls"; const PAGE_SIZE = 20; @@ -617,7 +618,7 @@ export function LibraryPageClient() { {/* The page shown stays, dimmed and still, until the one it steps to arrives. */} {/* Only the cards rate in the open collection. Focus mode keeps the person's own rating, on its stars, its shortcuts and its phone control alike. */} -
          +
          {pageResults.map((paper, index) => { const globalIndex = pageStart + index; return ( diff --git a/components/screening/data.ts b/components/screening/data.ts index 176da543c..b86e31f73 100644 --- a/components/screening/data.ts +++ b/components/screening/data.ts @@ -410,19 +410,6 @@ export const day = (at: number) => { const date = new Date(at); return `${date.getDate()} ${MONTHS[date.getMonth()]}${date.getFullYear() === new Date().getFullYear() ? "" : ` ${date.getFullYear()}`}`; }; -/** A date as a page shows it: how long ago for the last week, the day before that. */ -export function ago(at: number, now = Date.now()) { - const minutes = Math.max(0, Math.round((now - at) / 60_000)); - if (minutes < 1) return "just now"; - if (minutes < 60) return `${minutes} min ago`; - // Days are counted on the calendar: a vote cast late yesterday was cast yesterday, not "18 h ago". - const midnight = (time: number) => new Date(time).setHours(0, 0, 0, 0); - const days = Math.round((midnight(now) - midnight(at)) / DAY); - if (days <= 0) return `${Math.round(minutes / 60)} h ago`; - if (days === 1) return "yesterday"; - if (days < 7) return `${days} days ago`; - return day(at); -} /** An abstract cut into its sentences, the way a model that names a passage counts them (lib/screening/passages.ts). */ export { sentencesOf } from "@/lib/screening/passages"; diff --git a/components/screening/index-page.tsx b/components/screening/index-page.tsx index 1f3a1052d..4c86c7fb4 100644 --- a/components/screening/index-page.tsx +++ b/components/screening/index-page.tsx @@ -12,7 +12,7 @@ import { CommandCenterPagination } from "@/components/command-center/command-cen import { CommandCenterFilters } from "@/components/command-center/command-center-toolbar"; import { BAR_ACTION, BAR_LABEL } from "@/components/evidence-libraries/configuration/panel-header"; import { LibraryPageShell } from "@/components/evidence-libraries/library-page-shell"; -import { ListEmpty, ListRowsSkeleton } from "@/components/evidence-libraries/list-controls"; +import { ListEmpty, ListRowsSkeleton, STALE_ROWS } from "@/components/evidence-libraries/list-controls"; import { SkeletonBar } from "@/components/library/library-item-skeleton"; import { PageWrapper } from "@/components/PageWrapper"; import { Chip } from "./parts"; @@ -98,7 +98,7 @@ export function ScreeningsIndex() { // The screenings the person is invited to, narrowed by the search as the list is. const invited = (invitations ?? []).filter((row) => row.kind === "screening" && nameHas(row.name, searched)); // "Needs you first" is the newest first with what waits for the person above them. - const listed = useCursorPageAt("page", api.screening.view.list, inWorkspace(here, show === "you" ? "skip" : { show, sort: sort === "you" ? ("newest" as const) : sort, ...(runBy.by ? { by: runBy.by } : {}), ...(searched ? { text: searched } : {}) }), PAGE); + const listed = useCursorPageAt("page", api.screening.view.list, inWorkspace(here, show === "you" ? "skip" : { show, sort: sort === "you" ? ("newest" as const) : sort, ...(runBy.by ? { by: runBy.by } : {}), ...(searched ? { text: searched } : {}) }), PAGE, { list: JSON.stringify([show, runBy.by ?? null]) }); const fits = (row: Summary) => nameHas(row.name, searched) && (!runBy.by || row.createdBy.id === runBy.by); const needing = (row: Summary) => row.forYou + row.conflicts + row.asked > 0; @@ -114,10 +114,7 @@ export function ScreeningsIndex() { // Under "Needs you first" the rows sit in their groups, each group in the page's order: one group never splits around another. .sort((a, b) => (sort === "you" ? a.group - b.group : 0)); // Another tab or person asked for (a search typed or another order keeps the rows up, dimmed): until its rows come it shows skeletons, or at once says it is empty where its count is 0. Never the last tab's rows under the new one. Needs you is read with the page, so it has no wait. - const askedList = JSON.stringify([show, runBy.by ?? null]); - const [arrivedList, setArrivedList] = useState(askedList); - if ((show === "you" || (!listed.isLoading && !listed.isStale)) && arrivedList !== askedList) setArrivedList(askedList); - const otherList = arrivedList !== askedList; + const otherList = listed.isOther; const listRows = otherList ? [] : rows; // The rows wait for what is drawn above them too, so a list that has drawn is never pushed down. const loading = mine === undefined || tally === undefined || elsewhere === undefined || invitations === undefined || (show !== "you" && listed.isLoading); @@ -237,7 +234,7 @@ export function ScreeningsIndex() { {(loading && !rows.length) || (otherList && counts?.[show] !== 0) ? ( ) : ( -
            +
              {listRows.map(({ row, group }, i) => { const id = row.id; const me = row.me as string; diff --git a/components/screening/overview.tsx b/components/screening/overview.tsx index c49612fbb..5b30e6ddc 100644 --- a/components/screening/overview.tsx +++ b/components/screening/overview.tsx @@ -45,6 +45,7 @@ import { useWorkspace } from "./workspace"; import { useOpenInAddress } from "./address"; import { useWords } from "./words"; import { ScrollArea } from "@/components/ui/scroll-area"; +import { STALE_ROWS } from "@/components/evidence-libraries/list-controls"; /** What the Overview shows, kept in its address: the order of the reviewers, and every check for new papers or the last few. */ const PLACE = { @@ -706,7 +707,7 @@ function Unread({ open, model }: { open: Open; model: Reviewer }) { return ( <> -
                +
                  {/* Each row holds two lines, the most a title takes here, loaded or not: a long title never moves what is under the list. */} {Array.from({ length: coming }, (_, at) =>
                • )} {papers.items.map((paper) => ( diff --git a/components/screening/papers.tsx b/components/screening/papers.tsx index dc244a2e4..efc48b5ff 100644 --- a/components/screening/papers.tsx +++ b/components/screening/papers.tsx @@ -6,7 +6,7 @@ import dynamic from "next/dynamic"; // The open screening's Papers page: every paper as a row, a column of votes per reviewer, and where // the paper stands. A row opens the paper in a drawer at the window's side, with who voted what and when. -import { ListEmpty, ListRowsSkeleton, ListSearch } from "@/components/evidence-libraries/list-controls"; +import { ListEmpty, ListRowsSkeleton, ListSearch, STALE_ROWS } from "@/components/evidence-libraries/list-controls"; import { useEffect, useLayoutEffect, useRef, useState, type ComponentProps, type ReactNode, type CSSProperties } from "react"; import { AnimatePresence, motion } from "motion/react"; import { SamePageLink as NextLink } from "./same-page-link"; @@ -230,7 +230,9 @@ function Papers({ open, onExport }: { open: Open; onExport: (tab: ExportTab) => // The server gives one reviewer's papers in the order they voted on them, and a search's in the order they best match: no other order is offered then, and the menu says which it is. const fixedOrder = searched ? ("bySearch" as const) : who ? (voted === "none" || voted === "failed" ? ("byPlace" as const) : ("byVote" as const)) : null; const matching = { jobId: id, ...(filter !== "all" ? { result: filter } : {}), ...narrowed, ...(others.length ? { also: others } : {}), ...(searched ? { text: searched } : {}) }; - const listed = useCursorPageAt("page", api.screening.paperViews.list, inWorkspace(workspaceId, { ...matching, ...(sort !== "added" ? { sort } : {}) }), PAGE, { scroll: false }); + // Another tab or filter is another list; words looked for, another order or another page are the same list, whose rows stay up, dimmed. + const { text: _typed, ...narrowing } = matching as typeof matching & { text?: string }; + const listed = useCursorPageAt("page", api.screening.paperViews.list, inWorkspace(workspaceId, { ...matching, ...(sort !== "added" ? { sort } : {}) }), PAGE, { scroll: false, list: JSON.stringify(narrowing) }); const shown = listed.items; // How many papers stand each way is kept for the whole screening. Narrowed to a source, a check, a reason or a reviewer, the server counts them (convex/screening/paperViews.ts `counts`). Words looked for, the papers two reviewers share and the conflicts one person settled are found a page at a time, and their tabs carry no number. const anyNarrow = from !== "all" || Boolean(who) || Boolean(reason) || added !== "all" || Boolean(searched); @@ -241,11 +243,7 @@ function Papers({ open, onExport }: { open: Open; onExport: (tab: ExportTab) => const total = countOf(filter); // Another list asked for (another tab or filter), not another page, search or order of the same: its rows show as skeletons under the table's head until they come, and a tab the counts say is empty says so at once. Never the last list's rows under the new tab. // A search typed or another order keeps the rows up, dimmed, as Screen's search does: only another tab or filter is another list. - const { text: _typed, ...narrowing } = matching as typeof matching & { text?: string }; - const asked = JSON.stringify(narrowing); - const [arrivedList, setArrivedList] = useState(asked); - if (!listed.isLoading && !listed.isStale && arrivedList !== asked) setArrivedList(asked); - const otherList = arrivedList !== asked; + const otherList = listed.isOther; // Empty by the counts, from the first read too. const emptyNow = (otherList || listed.isLoading) && total === 0; const rowsPending = otherList && !emptyNow; @@ -663,7 +661,7 @@ function Papers({ open, onExport }: { open: Open; onExport: (tab: ExportTab) => {/* A full page's height while there are pages, so a short last page doesn't move the pager. The table scrolls sideways only where it can't fit, which would stop its head row sticking. */} {/* While the page is read it keeps the height of the rows it will hold, as many as the filter counts up to a page; what is left over slides. */} - + {listed.isLoading && !emptyNow ? ( <> {/* The table's two head rows, then as many rows as the page will hold. */} diff --git a/components/screening/screen.tsx b/components/screening/screen.tsx index bde758625..0549634c8 100644 --- a/components/screening/screen.tsx +++ b/components/screening/screen.tsx @@ -156,7 +156,7 @@ function Screen({ open }: { open: Open }) { const counted = screening.reviewers.find((one) => one.id === open.me)?.tally; // The queue as the server holds it, a page at a time: found by a paper's title or authors, Done by your vote, and To do in the order asked for. // It is read as it stands, so a paper you have dealt with leaves it and the ones after it move up. The open one is the exception: it keeps its place, with your vote on it, until you move on. - const listed = useCursorPageAt("page", api.screening.paperViews.queue, inWorkspace(workspaceId, { jobId: id, queue, ...(queue === "todo" ? { order } : {}), ...(queue === "done" && voted !== "any" ? { voted } : {}), ...(searched ? { text: searched } : {}) }), QUEUE_PAGE, { scroll: false }); + const listed = useCursorPageAt("page", api.screening.paperViews.queue, inWorkspace(workspaceId, { jobId: id, queue, ...(queue === "todo" ? { order } : {}), ...(queue === "done" && voted !== "any" ? { voted } : {}), ...(searched ? { text: searched } : {}) }), QUEUE_PAGE, { scroll: false, list: `${id}:${queue}` }); const holding = `${id}:${queue}:${order}:${searched.toLowerCase()}:${voted}`; // With no paper named in the address, the page's first is the open one, and stays it while the queue changes under the person: someone else settling a conflict never swaps the paper being read, or written about, for the next one. const [led, setLed] = useState<{ of: string; id: string } | null>(null); @@ -326,13 +326,11 @@ function Screen({ open }: { open: Open }) { const finished = Boolean(screening.finishedAt); // While another queue picked is read, the rows and paper still up are the last queue's: they stay where they are, dimmed and out of reach, until the new queue's arrive. One the counts say is empty says so at once. // Any change to the list asked for counts (another queue, order, vote picked in Done, or search): the paper of the list before is never voted on while the new one is read. - const [arrivedList, setArrivedList] = useState(holding); - if (arrived && arrivedList !== holding) setArrivedList(holding); // A page turned and not read yet counts too. - const switching = (arrivedList !== holding || listed.isStale) && !picked; + const switching = (listed.isStale || listed.isOther) && !picked; // Another queue picked: until its papers arrive its rows and paper show as skeletons in their places, never the last queue's papers under the new tab. // By the list alone, a paper named in the address or not: Back to a queue with its paper named, or a link to a paper in another queue, shows that queue's rows as skeletons too, never the last queue's under its tab. The named paper is read by itself, so it shows. - const otherQueue = arrivedList !== holding && arrivedList.split(":")[1] !== queue; + const otherQueue = listed.isOther; // Where the open paper stands in its queue. Another queue opens at its first paper, which its count already places. const shownAt = otherQueue && !picked ? 1 : listed.offset + at + 1; // Nothing is voted or settled on the last queue's paper while it stands dimmed: not by a press, not by a key. diff --git a/components/screening/screening-form.tsx b/components/screening/screening-form.tsx index 6101c6d9f..0ffb82a8e 100644 --- a/components/screening/screening-form.tsx +++ b/components/screening/screening-form.tsx @@ -16,7 +16,7 @@ import { toast } from "sonner"; import useSWR from "swr"; import { FileText, GitCompare, AiIcon, Ban, Hash, Upload, Check, ChevronDown, ChevronRight, Clock, Coins, Copy, ExternalLink, FileX, Folder, FolderPlus, ListChecks, Lock, Minus, MoreHorizontal, PenLine, Plus, RefreshCw, Trash2, TriangleAlert, Undo2, UserPlus, Users, X, type AppIcon, RotateCcw, Repeat } from "@/components/icons"; import { CommandCenterPagination } from "@/components/command-center/command-center-pagination"; -import { ListEmpty, ListLoading, ListRowsSkeleton, ListSearch } from "@/components/evidence-libraries/list-controls"; +import { ListEmpty, ListLoading, ListRowsSkeleton, ListSearch, STALE_ROWS } from "@/components/evidence-libraries/list-controls"; import { LibraryPageShell } from "@/components/evidence-libraries/library-page-shell"; import { PageWrapper } from "@/components/PageWrapper"; import { LibrarySelect, useLibrarySources, useRowLabel } from "./library-sources"; @@ -1319,7 +1319,7 @@ export function ScreeningForm({ id }: { id?: string }) { ) : null} {/* While a list is read, and while it runs to more than a page, it keeps a page's height, so a short last page moves nothing under it. A list that turns out shorter slides to its own height. */} -
                  +
                  {offered.loading && !offered.rows.length ? : null} {offered.rows.map((offer) => { const search = searchOf.get(offer.ref); const row = { offer, ...searchLook(offer), icon: kindIcon(offer.set.kind), added: taken_(offer.ref) }; return search ? pick(filters.length ? { ...offer, filters } : offer)} /> : pick(offer)} />; })} {!offered.rows.length && !offered.loading ?

                  {typed ? t("papers.noneByName") : kind === "screening" ? (here?.kind === "personal" ? t("papers.noneOwnIncluded") : t("papers.noneIncluded", { workspace: workspace.name })) : kind === "search" ? t("papers.noSearches") : t("papers.nothingHere")}

                  : null} @@ -2043,7 +2043,7 @@ function Merged({ jobId, sourceId, total, open, sources }: { jobId: Id<"screenin
                  {/* The list holds its rows' height from the first frame: how many there are is known before they are read. */} {rows.isLoading ? : ( -
                    +
                      {rows.items.map((row) => { // The source that brought the paper this record is the same as: another one, or this one where it lists the paper more than once. const from = row.paper?.sourceId === sourceId ? t("papers.mergedSame") : row.paper ? t("papers.mergedFrom", { source: sources.find((one) => one.id === row.paper!.sourceId)?.name ?? t("papers.mergedElsewhere") }) : t("papers.mergedGone"); @@ -2098,7 +2098,7 @@ function LeftOut({ jobId, sourceId, total, dois = false, onList }: { jobId: Id<"
                      {/* The list holds its rows' height from the first frame: how many there are is known before they are read. */} {rows.isLoading ? : ( -
                        +
                          {rows.items.map((row) => (
                        • {/* A title is read in full here: this list is where someone finds out what was left out. */} diff --git a/components/screening/sources.tsx b/components/screening/sources.tsx index 898d69e0d..4faeabc36 100644 --- a/components/screening/sources.tsx +++ b/components/screening/sources.tsx @@ -11,7 +11,7 @@ import { useTranslations } from "next-intl"; import { toast } from "sonner"; import { Check, ChevronRight, ChevronsUpDown, Coins, FileSpreadsheet, FileText, FileX, Folder, Hash, Library, Plus, Trash2, TriangleAlert, Upload, UserRound, Users, X, type AppIcon } from "@/components/icons"; import { CommandCenterPagination } from "@/components/command-center/command-center-pagination"; -import { ListRowsSkeleton, ListSearch } from "@/components/evidence-libraries/list-controls"; +import { ListRowsSkeleton, ListSearch, STALE_ROWS } from "@/components/evidence-libraries/list-controls"; import { SkeletonBar } from "@/components/library/library-item-skeleton"; import { ZoteroIcon } from "@/components/icons/zotero-icon"; import { LibrarySources, useLibrarySources, useRowLabel } from "./library-sources"; @@ -397,7 +397,7 @@ export function PdfFiles({ batch, total }: { batch: string; total: number }) { return (
                          {rows.isLoading ? : ( -
                            +
                              {rows.items.map((row) => { const stands = row.state === "read" ? (row.known ? "known" : "file") : row.state; return ( @@ -652,7 +652,7 @@ export function ZoteroTab({ sources, onAdd }: { sources: Source[]; onAdd: (added {/* The list holds a page's height while it fills or pages, the rows still to come drawn in their place, and a change to its height slides. */} {/* Rows of the list before (another library, folder or search) stay dimmed and out of reach until the new ones come: none can be added under the wrong library. */} -
                              +
                              {/* Where the list stands: all of the library, or the collection opened from it with the steps that lead back up. It can be added as it is. A name being looked for is looked for in the whole library. */} {words || gone || resolving ? null : here ? ( add(here)} {...counted(here)} /> diff --git a/components/screening/team.tsx b/components/screening/team.tsx index b398252bd..29f908d59 100644 --- a/components/screening/team.tsx +++ b/components/screening/team.tsx @@ -29,6 +29,7 @@ import { modelKey, type Person } from "./data"; import { paperCredits, pdfsMissed } from "./store"; import { useWords } from "./words"; import type { Pdfs } from "@/lib/pricing/estimate"; +import { STALE_ROWS } from "@/components/evidence-libraries/list-controls"; /** Picks a person: a member of the workspace the page is in, found by name or email, or an email address to invite from outside it. */ export function AddPerson({ exclude, screening, freeing = 0, onPick, children }: { exclude: string[]; /** A saved screening: whoever it is shared with from outside, or invited to, is on it already, and never invited again. */ screening?: string; /** Invitations this form takes back on Save: their places are free for the ones it adds. */ freeing?: number; onPick: (pick: { person: Person } | { email: string }) => void; children?: ReactNode }) { @@ -95,7 +96,7 @@ export function AddPerson({ exclude, screening, freeing = 0, onPick, children }: ) : null} {email || found === undefined ? null : <>{text.trim() ? t("nobodyByName") : t("nobodyElse")}{outsideFull ?? t("inviteHint")}} {left.length ? ( - + {left.map((person) => ( pick({ person: { id: person.id, name: person.name, ...(person.imageUrl ? { imageUrl: person.imageUrl } : {}) } })} className="gap-3"> diff --git a/components/workspaces/shared.tsx b/components/workspaces/shared.tsx index 85960492d..82e2f0a0b 100644 --- a/components/workspaces/shared.tsx +++ b/components/workspaces/shared.tsx @@ -21,7 +21,7 @@ import { Building2, Check, CircleCheck, Coins, FileSearch, Folder, ListFilter, L import { CommandCenterFilters } from "@/components/command-center/command-center-toolbar"; import { Entry, EntryAction, EntryAside, ENTRY_OPEN } from "@/components/command-center/entry"; import { LibraryPageShell } from "@/components/evidence-libraries/library-page-shell"; -import { ListEmpty, ListRowsSkeleton } from "@/components/evidence-libraries/list-controls"; +import { ListEmpty, ListRowsSkeleton, STALE_ROWS } from "@/components/evidence-libraries/list-controls"; import { LIST, Tile } from "@/components/settings/parts"; import { Button } from "@/components/ui/button"; import { PersonTag, RoleLabel } from "@/components/ui/identity"; @@ -146,7 +146,7 @@ export function SharedWithMe({ initial }: { initial?: { counts: Counts; rows: Sh {rows?.length ? ( // Rows of the view before stay, dimmed and still, until the one asked for arrives. -
                              +
                              {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());