forge
Explore
Log in

Don't you dare go Hollow

📌 sticky table headers, list position on Back, scroll-fed appointments

Browse files at this commit

c513a0cfa884079af1e4fdc37304b2caa221db49Burak BoduroğluParent: 33fa92d
  • feat
    • 📌 sticky table headers, list position on Back, scroll-fed appointments
Show full message
feat: 📌 sticky table headers, list position on Back, scroll-fed appointments
- a table that fits keeps its header row pinned under the app top bar
  while the page scrolls (its frame only clips instead of scrolling)
- DataTable remembers how many rows were revealed and the page offset per
  history entry; Back from a detail page redraws them and lands on the
  same row, a fresh visit still starts at the top
- createInfiniteList gains refresh() (re-read loaded rows in place) and
  restoreKey (reload as many rows as before); converted lists use both
- appointments load slots and bookings page by page instead of stopping
  at the first 100; the 30s poll refreshes in place
- selected filled tiles (user menu, theme picker, date picker, unread
  pills) drop the border that matched their fill
src/components/exams/exam-room-ws.tsxmodified+1 -1
@@ -898,7 +898,7 @@ function QuestionAnswerCardWS(props: {
898 setValue(choice.id);898 setValue(choice.id);
899 }}899 }}
900 >900 >
901- <span class={value() === choice.id ? "flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-primary bg-primary text-xs font-semibold text-primary-foreground" : "flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-input bg-background text-xs font-semibold text-foreground"}>901+ <span class={value() === choice.id ? "flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-transparent bg-primary bg-clip-padding text-xs font-semibold text-primary-foreground" : "flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-input bg-background text-xs font-semibold text-foreground"}>
902 {String.fromCharCode(65 + choiceIndex())}902 {String.fromCharCode(65 + choiceIndex())}
903 </span>903 </span>
904 <span class="min-w-0 space-y-2">904 <span class="min-w-0 space-y-2">
src/components/layout/celebi-panel.tsxmodified+1 -1
@@ -557,7 +557,7 @@ export function CelebiPanel(props: { open: boolean; onOpenChange: (open: boolean
557 type="button"557 type="button"
558 class={cn(558 class={cn(
559 "absolute bottom-3 left-1/2 inline-flex h-8 -translate-x-1/2 items-center gap-1.5 rounded-full border px-3 text-xs font-medium shadow-md backdrop-blur transition-colors",559 "absolute bottom-3 left-1/2 inline-flex h-8 -translate-x-1/2 items-center gap-1.5 rounded-full border px-3 text-xs font-medium shadow-md backdrop-blur transition-colors",
560- unread() ? "border-primary bg-primary text-primary-foreground hover:bg-primary/90" : "border-border bg-card/95 text-foreground hover:bg-accent",560+ unread() ? "border-transparent bg-primary bg-clip-padding text-primary-foreground hover:bg-primary/90" : "border-border bg-card/95 text-foreground hover:bg-accent",
561 )}561 )}
562 onClick={scrollToLatest}562 onClick={scrollToLatest}
563 >563 >
src/components/layout/theme-mode-control.tsxmodified+2 -2
@@ -54,11 +54,11 @@ export function ThemeModeControl(props: ThemeModeControlProps) {
54 54
55 return (55 return (
56 <div class="grid grid-cols-2 gap-2" role="group" aria-label={prefs.t("theme.toggle")}>56 <div class="grid grid-cols-2 gap-2" role="group" aria-label={prefs.t("theme.toggle")}>
57- <button type="button" role="menuitemradio" aria-checked={!isDark()} class={cn("flex min-h-16 w-full flex-col items-center justify-center gap-1.5 rounded-md border px-2 py-2.5 text-center text-xs font-medium transition-colors outline-hidden focus-visible:ring-2 focus-visible:ring-ring", !isDark() ? "border-primary bg-primary text-primary-foreground shadow-xs" : "border-border bg-background text-foreground hover:bg-accent hover:text-accent-foreground")} onClick={() => selectTheme("light")}>57+ <button type="button" role="menuitemradio" aria-checked={!isDark()} class={cn("flex min-h-16 w-full flex-col items-center justify-center gap-1.5 rounded-md border px-2 py-2.5 text-center text-xs font-medium transition-colors outline-hidden focus-visible:ring-2 focus-visible:ring-ring", !isDark() ? "border-transparent bg-primary bg-clip-padding text-primary-foreground shadow-xs" : "border-border bg-background text-foreground hover:bg-accent hover:text-accent-foreground")} onClick={() => selectTheme("light")}>
58 <span class="flex h-7 w-7 items-center justify-center"><IconSun class="h-5 w-5" /></span>58 <span class="flex h-7 w-7 items-center justify-center"><IconSun class="h-5 w-5" /></span>
59 <span class="leading-tight">{lightLabel()}</span>59 <span class="leading-tight">{lightLabel()}</span>
60 </button>60 </button>
61- <button type="button" role="menuitemradio" aria-checked={isDark()} class={cn("flex min-h-16 w-full flex-col items-center justify-center gap-1.5 rounded-md border px-2 py-2.5 text-center text-xs font-medium transition-colors outline-hidden focus-visible:ring-2 focus-visible:ring-ring", isDark() ? "border-primary bg-primary text-primary-foreground shadow-xs" : "border-border bg-background text-foreground hover:bg-accent hover:text-accent-foreground")} onClick={() => selectTheme("dark")}>61+ <button type="button" role="menuitemradio" aria-checked={isDark()} class={cn("flex min-h-16 w-full flex-col items-center justify-center gap-1.5 rounded-md border px-2 py-2.5 text-center text-xs font-medium transition-colors outline-hidden focus-visible:ring-2 focus-visible:ring-ring", isDark() ? "border-transparent bg-primary bg-clip-padding text-primary-foreground shadow-xs" : "border-border bg-background text-foreground hover:bg-accent hover:text-accent-foreground")} onClick={() => selectTheme("dark")}>
62 <span class="flex h-7 w-7 items-center justify-center"><IconMoon class="h-5 w-5" /></span>62 <span class="flex h-7 w-7 items-center justify-center"><IconMoon class="h-5 w-5" /></span>
63 <span class="leading-tight">{darkLabel()}</span>63 <span class="leading-tight">{darkLabel()}</span>
64 </button>64 </button>
src/components/layout/user-menu.tsxmodified+1 -1
@@ -50,7 +50,7 @@ function ChoiceButton(props: {
50 "flex min-h-16 w-full flex-col items-center justify-center gap-1.5 rounded-md border px-2 py-2.5 text-center text-xs font-medium transition-colors",50 "flex min-h-16 w-full flex-col items-center justify-center gap-1.5 rounded-md border px-2 py-2.5 text-center text-xs font-medium transition-colors",
51 "outline-hidden focus-visible:ring-2 focus-visible:ring-ring",51 "outline-hidden focus-visible:ring-2 focus-visible:ring-ring",
52 props.active52 props.active
53- ? "border-primary bg-primary text-primary-foreground shadow-xs"53+ ? "border-transparent bg-primary bg-clip-padding text-primary-foreground shadow-xs"
54 : "border-border bg-background text-foreground hover:bg-accent hover:text-accent-foreground",54 : "border-border bg-background text-foreground hover:bg-accent hover:text-accent-foreground",
55 )}55 )}
56 onClick={props.onSelect}56 onClick={props.onSelect}
src/components/rag/rag-study-panel.tsxmodified+1 -1
@@ -527,7 +527,7 @@ export function RagStudyPanel() {
527 class={cn(527 class={cn(
528 "absolute bottom-3 left-1/2 inline-flex h-8 -translate-x-1/2 items-center gap-1.5 rounded-full border px-3 text-xs font-medium shadow-md backdrop-blur transition-colors",528 "absolute bottom-3 left-1/2 inline-flex h-8 -translate-x-1/2 items-center gap-1.5 rounded-full border px-3 text-xs font-medium shadow-md backdrop-blur transition-colors",
529 unread()529 unread()
530- ? "border-primary bg-primary text-primary-foreground hover:bg-primary/90"530+ ? "border-transparent bg-primary bg-clip-padding text-primary-foreground hover:bg-primary/90"
531 : "border-border bg-surface-base/95 text-foreground hover:bg-surface-overlay",531 : "border-border bg-surface-base/95 text-foreground hover:bg-surface-overlay",
532 )}532 )}
533 onClick={scrollToLatest}533 onClick={scrollToLatest}
src/components/ui/data-table.tsxmodified+74 -2
@@ -1,4 +1,4 @@
1-import { For, Show, createEffect, createSignal, on, onCleanup } from "solid-js";1+import { For, Show, createEffect, createSignal, on, onCleanup, onMount } from "solid-js";
2 import type { JSX, ParentProps } from "solid-js";2 import type { JSX, ParentProps } from "solid-js";
3 import {3 import {
4 type Column,4 type Column,
@@ -159,8 +159,39 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData,
159 // Client-side tables drop page numbers for scroll-to-reveal; only a159 // Client-side tables drop page numbers for scroll-to-reveal; only a
160 // server-paged table (`manualPagination`) still pages.160 // server-paged table (`manualPagination`) still pages.
161 const revealing = () => paginationEnabled && !props.manualPagination && !props.infinite;161 const revealing = () => paginationEnabled && !props.manualPagination && !props.infinite;
162- const [revealed, setRevealed] = createSignal(REVEAL_STEP);162+ // How far the reader had revealed, per page and table, for this tab: coming
163+ // back from a detail page renders those rows again, so the router's scroll
164+ // restoration has somewhere to land.
165+ const revealKey = typeof window === "undefined"
166+ ? null
167+ : `reveal:${window.location.pathname}${window.location.search}:${props.storageKey ?? props.title ?? ""}`;
168+ const readRevealed = () => {
169+ try {
170+ const count = Number(revealKey ? sessionStorage.getItem(revealKey) : null);
171+ return Number.isFinite(count) && count > REVEAL_STEP ? Math.floor(count) : REVEAL_STEP;
172+ } catch {
173+ return REVEAL_STEP;
174+ }
175+ };
176+ const [revealed, setRevealed] = createSignal(readRevealed());
177+ createEffect(on(revealed, (count) => {
178+ if (!revealKey || count === Number.MAX_SAFE_INTEGER) return;
179+ try {
180+ sessionStorage.setItem(revealKey, String(count));
181+ } catch {
182+ // storage blocked: the table just starts at the first step
183+ }
184+ }, { defer: true }));
163 const resetReveal = () => setRevealed(REVEAL_STEP);185 const resetReveal = () => setRevealed(REVEAL_STEP);
186+ // The router's own scroll restoration runs before a list's rows arrive, so
187+ // a long list came back at the top. Remember the page offset against this
188+ // history entry and put it back once the rows are drawn — only on a return
189+ // to the same entry (Back), never on a fresh visit.
190+ const scrollKey = revealKey ? `${revealKey}:scroll` : null;
191+ const historyEntry = () => {
192+ const state = history.state as Record<string, unknown> | null;
193+ return String(state?.__TSR_key ?? state?.key ?? "");
194+ };
164 createEffect(on(() => props.pageResetKey, resetReveal, { defer: true }));195 createEffect(on(() => props.pageResetKey, resetReveal, { defer: true }));
165 // The search box's text when the table owns it — the `searchPredicate`196 // The search box's text when the table owns it — the `searchPredicate`
166 // query, or the `filterColumn` filter value.197 // query, or the `filterColumn` filter value.
@@ -370,6 +401,47 @@ export function DataTable<TData, TValue = unknown>(props: DataTableProps<TData,
370 if (busy === false && observing) queueMicrotask(revealMore);401 if (busy === false && observing) queueMicrotask(revealMore);
371 }, { defer: true }));402 }, { defer: true }));
372 if (!observing) setRevealed(Number.MAX_SAFE_INTEGER);403 if (!observing) setRevealed(Number.MAX_SAFE_INTEGER);
404+ if (scrollKey) {
405+ let saveTimer: ReturnType<typeof setTimeout> | undefined;
406+ const saveScroll = () => {
407+ clearTimeout(saveTimer);
408+ saveTimer = setTimeout(() => {
409+ try {
410+ sessionStorage.setItem(scrollKey, JSON.stringify({ y: Math.round(window.scrollY), entry: historyEntry() }));
411+ } catch {
412+ // storage blocked: no restore, nothing else breaks
413+ }
414+ }, 150);
415+ };
416+ onMount(() => {
417+ window.addEventListener("scroll", saveScroll, { passive: true });
418+ onCleanup(() => {
419+ clearTimeout(saveTimer);
420+ window.removeEventListener("scroll", saveScroll);
421+ });
422+ });
423+ let restored = false;
424+ createEffect(() => {
425+ if (restored || visibleRows().length === 0) return;
426+ restored = true;
427+ try {
428+ const saved = JSON.parse(sessionStorage.getItem(scrollKey) ?? "null") as { y?: number; entry?: string } | null;
429+ // The router may already have tried, clamped to a page that was still
430+ // short; correct it once the rows are laid out, and once more after
431+ // late content (avatars, badges) settles.
432+ const target = saved?.y;
433+ if (target && saved.entry === historyEntry()) {
434+ const settle = () => {
435+ if (Math.abs(window.scrollY - target) > 8) window.scrollTo(0, target);
436+ };
437+ requestAnimationFrame(settle);
438+ setTimeout(settle, 300);
439+ }
440+ } catch {
441+ // malformed entry: start at the top
442+ }
443+ });
444+ }
373 const searchFieldValue = () => {445 const searchFieldValue = () => {
374 if (props.onSearchInput || props.searchPredicate || props.filterColumn) return searchValue();446 if (props.onSearchInput || props.searchPredicate || props.filterColumn) return searchValue();
375 return "";447 return "";
src/components/ui/date-picker.tsxmodified+1 -1
@@ -200,7 +200,7 @@ export function DatePicker(props: {
200 class={cn(200 class={cn(
201 "inline-flex h-9 items-center justify-center rounded-md border border-transparent p-0 text-xs font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring",201 "inline-flex h-9 items-center justify-center rounded-md border border-transparent p-0 text-xs font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring",
202 isSameDay(today, day()) && "border-primary/50 text-primary-text",202 isSameDay(today, day()) && "border-primary/50 text-primary-text",
203- sameDay(selected(), day()) && "border-primary bg-primary text-primary-foreground shadow-xs hover:bg-primary/90 hover:text-primary-foreground",203+ sameDay(selected(), day()) && "border-transparent bg-primary bg-clip-padding text-primary-foreground shadow-xs hover:bg-primary/90 hover:text-primary-foreground",
204 )}204 )}
205 onClick={(event) => {205 onClick={(event) => {
206 event.stopPropagation();206 event.stopPropagation();
src/components/ui/draw-canvas.tsxmodified+1 -1
@@ -360,7 +360,7 @@ export function DrawCanvas(props: {
360 cn(360 cn(
361 "flex h-11 w-11 items-center justify-center rounded-lg border transition-colors",361 "flex h-11 w-11 items-center justify-center rounded-lg border transition-colors",
362 active362 active
363- ? "border-primary bg-primary text-primary-foreground shadow-xs"363+ ? "border-transparent bg-primary bg-clip-padding text-primary-foreground shadow-xs"
364 : "border-border bg-background text-muted-foreground hover:bg-accent hover:text-foreground",364 : "border-border bg-background text-muted-foreground hover:bg-accent hover:text-foreground",
365 );365 );
366 366
src/index.cssmodified+20 -0
@@ -260,6 +260,26 @@
260 border-right-color: var(--color-border-hairline);260 border-right-color: var(--color-border-hairline);
261 }261 }
262 262
263+/* The header row stays in view while the page scrolls. `overflow-x: auto`
264+ * makes the frame its own scroller, which pins a sticky thead inside a box
265+ * that never scrolls vertically; a table that fits needs no sideways scroll,
266+ * so its frame only clips (rounded corners) and the thead sticks to the
267+ * page instead. A table wide enough to scroll sideways keeps its scroller
268+ * and a header that scrolls with it. */
269+.data-table-wrap:not([data-scrollable]) {
270+ overflow: clip;
271+}
272+/* In the page (not a side panel) the header clears the app's sticky top
273+ * bar, which only exists from lg up. */
274+#main-content .data-table-wrap:not([data-scrollable]) .data-table thead {
275+ top: 0;
276+}
277+@media (min-width: 64rem) {
278+ #main-content .data-table-wrap:not([data-scrollable]) .data-table thead {
279+ top: calc(49px + env(safe-area-inset-top));
280+ }
281+}
282+
263 /* İşlemler sütunu: sabit 110x45. */283 /* İşlemler sütunu: sabit 110x45. */
264 .data-table td.table-action-cell,284 .data-table td.table-action-cell,
265 .data-table th.table-action-cell {285 .data-table th.table-action-cell {
src/lib/infinite-list.test.tsxmodified+37 -0
@@ -92,4 +92,41 @@ describe("createInfiniteList", () => {
92 dispose();92 dispose();
93 });93 });
94 });94 });
95+
96+ it("refresh refetches the loaded rows in one request and keeps them", async () => {
97+ const fetch = server(120);
98+ await createRoot(async (dispose) => {
99+ const list = createInfiniteList(() => "r", fetch, { pageSize: 50 });
100+ await flush();
101+ list.loadMore();
102+ await flush();
103+ expect(list.items()).toHaveLength(100);
104+ await list.refresh();
105+ expect(fetch).toHaveBeenLastCalledWith("r", { limit: 100, offset: 0 });
106+ expect(list.items()).toHaveLength(100);
107+ expect(list.hasMore()).toBe(true);
108+ dispose();
109+ });
110+ });
111+
112+ it("restores the loaded row count for a query from session storage", async () => {
113+ sessionStorage.clear();
114+ const fetch = server(120);
115+ await createRoot(async (dispose) => {
116+ const list = createInfiniteList(() => "r", fetch, { pageSize: 50, restoreKey: "t" });
117+ await flush();
118+ list.loadMore();
119+ await flush();
120+ dispose();
121+ });
122+ fetch.mockClear();
123+ await createRoot(async (dispose) => {
124+ const list = createInfiniteList(() => "r", fetch, { pageSize: 50, restoreKey: "t" });
125+ await flush();
126+ expect(fetch).toHaveBeenCalledTimes(1);
127+ expect(fetch).toHaveBeenLastCalledWith("r", { limit: 100, offset: 0 });
128+ expect(list.items()).toHaveLength(100);
129+ dispose();
130+ });
131+ });
95 });132 });
src/lib/infinite-list.tsmodified+62 -4
@@ -3,6 +3,8 @@ import type { Page, PageParams } from "@/api/client";
3 3
4 /** Rows fetched per request while the reader scrolls a server-paged list. */4 /** Rows fetched per request while the reader scrolls a server-paged list. */
5 export const INFINITE_PAGE_SIZE = 50;5 export const INFINITE_PAGE_SIZE = 50;
6+/** The most rows one request may ask for when refetching or restoring. */
7+const MAX_BATCH = 500;
6 8
7 export type InfiniteList<T> = {9 export type InfiniteList<T> = {
8 /** Every row fetched so far, in server order. */10 /** Every row fetched so far, in server order. */
@@ -17,8 +19,14 @@ export type InfiniteList<T> = {
17 hasMore: () => boolean;19 hasMore: () => boolean;
18 /** Fetch the next page; a no-op while one is in flight or none is left. */20 /** Fetch the next page; a no-op while one is in flight or none is left. */
19 loadMore: () => void;21 loadMore: () => void;
20- /** Start the current query over from its first page (after a create/delete). */22+ /** Start the current query over from its first page. */
21 reload: () => void;23 reload: () => void;
24+ /**
25+ * Refetch every row loaded so far in one request and swap them in place,
26+ * keeping the reader's place (a poll, or after an edit or delete). Skipped
27+ * while a page is in flight.
28+ */
29+ refresh: () => Promise<void>;
22 /** Patch the loaded rows in place (an edit that needs no refetch). */30 /** Patch the loaded rows in place (an edit that needs no refetch). */
23 mutate: (update: (items: T[]) => T[]) => void;31 mutate: (update: (items: T[]) => T[]) => void;
24 };32 };
@@ -36,7 +44,16 @@ export type InfiniteList<T> = {
36 export function createInfiniteList<T, K>(44 export function createInfiniteList<T, K>(
37 source: () => K | null | undefined | false,45 source: () => K | null | undefined | false,
38 fetchPage: (key: K, params: PageParams) => Promise<Page<T>>,46 fetchPage: (key: K, params: PageParams) => Promise<Page<T>>,
39- options: { pageSize?: number; equals?: (a: K, b: K) => boolean } = {},47+ options: {
48+ pageSize?: number;
49+ equals?: (a: K, b: K) => boolean;
50+ /**
51+ * Remember how many rows were loaded (per query, for this tab) so coming
52+ * back from a detail page loads them again in one request and the
53+ * browser's scroll restoration has the rows to land on.
54+ */
55+ restoreKey?: string;
56+ } = {},
40 ): InfiniteList<T> {57 ): InfiniteList<T> {
41 const pageSize = options.pageSize ?? INFINITE_PAGE_SIZE;58 const pageSize = options.pageSize ?? INFINITE_PAGE_SIZE;
42 const [items, setItems] = createSignal<T[]>([]);59 const [items, setItems] = createSignal<T[]>([]);
@@ -48,23 +65,48 @@ export function createInfiniteList<T, K>(
48 let generation = 0;65 let generation = 0;
49 let key: K | null = null;66 let key: K | null = null;
50 67
68+ const storageKey = () => (options.restoreKey && key !== null ? `infinite:${options.restoreKey}:${JSON.stringify(key)}` : null);
69+ const savedCount = () => {
70+ const name = storageKey();
71+ if (!name) return 0;
72+ try {
73+ const count = Number(sessionStorage.getItem(name));
74+ return Number.isFinite(count) ? Math.min(Math.max(0, Math.floor(count)), MAX_BATCH) : 0;
75+ } catch {
76+ return 0;
77+ }
78+ };
79+ const saveCount = (count: number) => {
80+ const name = storageKey();
81+ if (!name) return;
82+ try {
83+ sessionStorage.setItem(name, String(count));
84+ } catch {
85+ // storage full or blocked: the list still works, it just starts short
86+ }
87+ };
88+
51 const fetchNext = async () => {89 const fetchNext = async () => {
52 if (key === null || loading()) return;90 if (key === null || loading()) return;
53 const run = generation;91 const run = generation;
54 const current = key;92 const current = key;
55 const offset = items().length;93 const offset = items().length;
94+ // The first page of a query restored from session storage asks for as
95+ // many rows as were loaded before, in one request.
96+ const limit = offset === 0 ? Math.max(pageSize, savedCount()) : pageSize;
56 setLoading(true);97 setLoading(true);
57 setError(undefined);98 setError(undefined);
58 try {99 try {
59- const page = await fetchPage(current, { limit: pageSize, offset });100+ const page = await fetchPage(current, { limit, offset });
60 if (run !== generation) return;101 if (run !== generation) return;
61 const rows = Array.isArray(page.items) ? page.items : [];102 const rows = Array.isArray(page.items) ? page.items : [];
62 setItems((prev) => (offset === 0 ? rows : [...prev, ...rows]));103 setItems((prev) => (offset === 0 ? rows : [...prev, ...rows]));
63 const next = offset + rows.length;104 const next = offset + rows.length;
64 // A short page ends the list even if `total` says otherwise, so a stale105 // A short page ends the list even if `total` says otherwise, so a stale
65 // count never keeps asking for pages that are not there.106 // count never keeps asking for pages that are not there.
66- setTotal(rows.length < pageSize ? next : Math.max(typeof page.total === "number" ? page.total : next, next));107+ setTotal(rows.length < limit ? next : Math.max(typeof page.total === "number" ? page.total : next, next));
67 setLoaded(true);108 setLoaded(true);
109+ saveCount(next);
68 } catch (err) {110 } catch (err) {
69 if (run === generation) setError(err);111 if (run === generation) setError(err);
70 } finally {112 } finally {
@@ -107,6 +149,22 @@ export function createInfiniteList<T, K>(
107 if (hasMore()) void fetchNext();149 if (hasMore()) void fetchNext();
108 },150 },
109 reload: start,151 reload: start,
152+ refresh: async () => {
153+ if (key === null || loading() || !loaded()) return;
154+ const run = generation;
155+ const current = key;
156+ const limit = Math.min(Math.max(pageSize, items().length), MAX_BATCH);
157+ try {
158+ const page = await fetchPage(current, { limit, offset: 0 });
159+ if (run !== generation) return;
160+ const rows = Array.isArray(page.items) ? page.items : [];
161+ setItems(rows);
162+ setTotal(rows.length < limit ? rows.length : Math.max(typeof page.total === "number" ? page.total : rows.length, rows.length));
163+ setError(undefined);
164+ } catch (err) {
165+ if (run === generation) setError(err);
166+ }
167+ },
110 mutate: (update) => setItems((prev) => update(prev)),168 mutate: (update) => setItems((prev) => update(prev)),
111 };169 };
112 }170 }
src/pages/appointments-page.test.tsxmodified+3 -2
@@ -58,6 +58,7 @@ test("separates bookings and available times into tabs", async () => {
58 // teacher=me) and their own bookings without a start window: neither read58 // teacher=me) and their own bookings without a start window: neither read
59 // downloads history.59 // downloads history.
60 await waitFor(() => expect(getSlots).toHaveBeenCalled());60 await waitFor(() => expect(getSlots).toHaveBeenCalled());
61- expect(getSlots).toHaveBeenCalledWith({ starts_after: expect.any(Number), limit: 100 });61+ // First scroll page only, not a silent 100-row cap.
62- expect(getAppointments).toHaveBeenCalledWith({ limit: 100 });62+ expect(getSlots).toHaveBeenCalledWith({ starts_after: expect.any(Number), limit: 50, offset: 0 });
63+ expect(getAppointments).toHaveBeenCalledWith({ limit: 50, offset: 0 });
63 });64 });
src/pages/appointments-page.tsxmodified+40 -38
@@ -1,5 +1,5 @@
1 import { Show, createMemo, createSignal } from "solid-js";1 import { Show, createMemo, createSignal } from "solid-js";
2-import { createResource } from "@/lib/create-resource";2+import { createInfiniteList } from "@/lib/infinite-list";
3 import type { ColumnDef } from "@tanstack/solid-table";3 import type { ColumnDef } from "@tanstack/solid-table";
4 import {4 import {
5 deleteSlotById,5 deleteSlotById,
@@ -45,8 +45,6 @@ import { hasMinRole } from "@/lib/roles";
45 import { useAuth } from "@/stores/auth-context";45 import { useAuth } from "@/stores/auth-context";
46 import { usePreferences, useT } from "@/stores/preferences-context";46 import { usePreferences, useT } from "@/stores/preferences-context";
47 47
48-const PAGE_SIZE = 10;
49-const PAGE_LIMIT = 100;
50 const isLive = (status: AppointmentStatus) => status === "pending" || status === "approved";48 const isLive = (status: AppointmentStatus) => status === "pending" || status === "approved";
51 49
52 export default function AppointmentsPage() {50 export default function AppointmentsPage() {
@@ -81,23 +79,31 @@ function AppointmentsContent() {
81 // existed because the endpoint had neither a window nor a teacher filter.79 // existed because the endpoint had neither a window nor a teacher filter.
82 // Non-manager staff get their own published slots (`teacher=me`); managers80 // Non-manager staff get their own published slots (`teacher=me`); managers
83 // supervise every teacher's, requesters everyone's open ones.81 // supervise every teacher's, requesters everyone's open ones.
84- const fetchSlots = async () => {82+ // Both lists load a page at a time as the reader scrolls (they used to stop
85- const params: SlotListParams = { starts_after: Date.now(), limit: PAGE_LIMIT };83+ // silently at the first 100). The query is the role scope only; the slot
86- if (isStaff() && !isManager()) params.teacher = "me";84+ // window's `starts_after` is taken at each fetch so a poll drops slots that
87- return (await getSlots(params)).items;85+ // have started meanwhile.
88- };86+ const scope = () => (auth.user() ? (isStaff() && !isManager() ? "me" : "all") : null);
89- const [slots, { refetch: refetchSlots }] = createResource(fetchSlots);87+ const slotList = createInfiniteList(scope, (teacher, paging) => {
90- // Appointments come back newest-first (`ORDER BY id DESC`), so page one is88+ const params: SlotListParams = { ...paging, starts_after: Date.now() };
91- // right. The requests table shows decided rows too, so no status window;89+ if (teacher === "me") params.teacher = "me";
92- // non-manager staff narrow to their own rows server-side (`teacher=me`).90+ return getSlots(params);
93- const [appts, { refetch: refetchAppts }] = createResource(async () => {91+ });
94- const params: AppointmentListParams = { limit: PAGE_LIMIT };92+ // Appointments come back newest-first (`ORDER BY id DESC`). The requests
95- if (isStaff() && !isManager()) params.teacher = "me";93+ // table shows decided rows too, so no status window; non-manager staff
96- return (await getAppointments(params)).items;94+ // narrow to their own rows server-side (`teacher=me`).
95+ const apptList = createInfiniteList(scope, (teacher, paging) => {
96+ const params: AppointmentListParams = { ...paging };
97+ if (teacher === "me") params.teacher = "me";
98+ return getAppointments(params);
97 });99 });
100+ const slots = () => slotList.items();
101+ const appts = () => apptList.items();
98 102
99- const refetchAll = () => Promise.all([refetchSlots(), refetchAppts()]);103+ // Polls and actions re-read the loaded rows in place, so a status change
100- const loaded = () => slots.latest !== undefined && appts.latest !== undefined;104+ // never throws the reader back to the top of a long list.
105+ const refetchAll = () => Promise.all([slotList.refresh(), apptList.refresh()]);
106+ const loaded = () => !slotList.initialLoading() && !apptList.initialLoading();
101 107
102 // Poll so statuses stay in sync when the other party acts (approve, book,108 // Poll so statuses stay in sync when the other party acts (approve, book,
103 // cancel…). Visibility-aware: pauses on hidden tabs, refetches on tab-back so109 // cancel…). Visibility-aware: pauses on hidden tabs, refetches on tab-back so
@@ -199,8 +205,8 @@ function AppointmentsContent() {
199 205
200 // --- staff: my published slots (the server already narrows to `teacher=me`206 // --- staff: my published slots (the server already narrows to `teacher=me`
201 // for non-manager staff; managers see every teacher's) ---207 // for non-manager staff; managers see every teacher's) ---
202- const mySlots = () => slots.latest ?? [];208+ const mySlots = () => slots();
203- const slotBooking = (slotId: string) => (appts.latest ?? []).find((a) => a.slot === slotId && isLive(a.status));209+ const slotBooking = (slotId: string) => appts().find((a) => a.slot === slotId && isLive(a.status));
204 210
205 const slotColumns = createMemo<ColumnDef<AppointmentSlot>[]>(() => [211 const slotColumns = createMemo<ColumnDef<AppointmentSlot>[]>(() => [
206 ...windowColumns<AppointmentSlot>(),212 ...windowColumns<AppointmentSlot>(),
@@ -247,7 +253,7 @@ function AppointmentsContent() {
247 253
248 // --- staff: booking requests for my slots (server-narrowed via `teacher=me`254 // --- staff: booking requests for my slots (server-narrowed via `teacher=me`
249 // for non-manager staff, as with the slots above) ---255 // for non-manager staff, as with the slots above) ---
250- const requests = () => appts.latest ?? [];256+ const requests = () => appts();
251 257
252 const requestColumns = createMemo<ColumnDef<Appointment>[]>(() => [258 const requestColumns = createMemo<ColumnDef<Appointment>[]>(() => [
253 {259 {
@@ -283,13 +289,13 @@ function AppointmentsContent() {
283 ]);289 ]);
284 290
285 // --- booker: available slots ---291 // --- booker: available slots ---
286- const myLiveSlotIds = () => new Set((appts.latest ?? []).filter((a) => a.requester.id === me()?.id && isLive(a.status)).map((a) => a.slot));292+ const myLiveSlotIds = () => new Set(appts().filter((a) => a.requester.id === me()?.id && isLive(a.status)).map((a) => a.slot));
287 const availableSlots = () => {293 const availableSlots = () => {
288 const taken = myLiveSlotIds();294 const taken = myLiveSlotIds();
289 // `book` refuses a slot whose window has OPENED ("the slot has already295 // `book` refuses a slot whose window has OPENED ("the slot has already
290 // started", no skew grace), not one that has ended — an in-progress slot296 // started", no skew grace), not one that has ended — an in-progress slot
291 // listed here would show a Book button that always 409s.297 // listed here would show a Book button that always 409s.
292- return (slots.latest ?? []).filter((s) => s.starts_at > now() && !taken.has(s.id));298+ return slots().filter((s) => s.starts_at > now() && !taken.has(s.id));
293 };299 };
294 300
295 const availableColumns = createMemo<ColumnDef<AppointmentSlot>[]>(() => [301 const availableColumns = createMemo<ColumnDef<AppointmentSlot>[]>(() => [
@@ -316,7 +322,7 @@ function AppointmentsContent() {
316 ]);322 ]);
317 323
318 // --- booker: my bookings ---324 // --- booker: my bookings ---
319- const myBookings = () => (appts.latest ?? []).filter((a) => a.requester.id === me()?.id);325+ const myBookings = () => appts().filter((a) => a.requester.id === me()?.id);
320 const nextBooking = createMemo(() =>326 const nextBooking = createMemo(() =>
321 myBookings()327 myBookings()
322 .filter((a) => isLive(a.status) && a.starts_at != null && a.starts_at > now())328 .filter((a) => isLive(a.status) && a.starts_at != null && a.starts_at > now())
@@ -440,14 +446,14 @@ function AppointmentsContent() {
440 <IconCalendarDays class="h-4 w-4" />446 <IconCalendarDays class="h-4 w-4" />
441 {isStaff() ? t("appointments.requests") : t("appointments.myBookings")}447 {isStaff() ? t("appointments.requests") : t("appointments.myBookings")}
442 <Badge variant="secondary" class="h-5 min-w-5 justify-center rounded-full px-1.5 py-0 text-[11px] group-data-selected:bg-background group-data-selected:text-foreground">448 <Badge variant="secondary" class="h-5 min-w-5 justify-center rounded-full px-1.5 py-0 text-[11px] group-data-selected:bg-background group-data-selected:text-foreground">
443- {isStaff() ? requests().length : myBookings().length}449+ {apptList.total()}
444 </Badge>450 </Badge>
445 </TabsTrigger>451 </TabsTrigger>
446 <TabsTrigger value="availability" class="min-w-0">452 <TabsTrigger value="availability" class="min-w-0">
447 <IconClock class="h-4 w-4" />453 <IconClock class="h-4 w-4" />
448 {isStaff() ? t("appointments.mySlots") : t("appointments.availableSlots")}454 {isStaff() ? t("appointments.mySlots") : t("appointments.availableSlots")}
449 <Badge variant="secondary" class="h-5 min-w-5 justify-center rounded-full px-1.5 py-0 text-[11px] group-data-selected:bg-background group-data-selected:text-foreground">455 <Badge variant="secondary" class="h-5 min-w-5 justify-center rounded-full px-1.5 py-0 text-[11px] group-data-selected:bg-background group-data-selected:text-foreground">
450- {isStaff() ? mySlots().length : availableSlots().length}456+ {isStaff() ? slotList.total() : availableSlots().length}
451 </Badge>457 </Badge>
452 </TabsTrigger>458 </TabsTrigger>
453 </TabsList>459 </TabsList>
@@ -456,7 +462,7 @@ function AppointmentsContent() {
456 <Show when={isStaff()} fallback={462 <Show when={isStaff()} fallback={
457 <section class="space-y-4 p-0">463 <section class="space-y-4 p-0">
458 <Show when={loaded()} fallback={<DataTableSkeleton columns={4} rows={6} />}>464 <Show when={loaded()} fallback={<DataTableSkeleton columns={4} rows={6} />}>
459- <Show when={appts.error}><Alert variant="destructive">{formatApiError(appts.error)}</Alert></Show>465+ <Show when={apptList.error()}>{(err) => <Alert variant="destructive">{formatApiError(err())}</Alert>}</Show>
460 <Show when={nextBooking()}>466 <Show when={nextBooking()}>
461 {(booking) => (467 {(booking) => (
462 <div class="mb-4 flex flex-wrap items-center gap-3 rounded-xl border border-border-line bg-surface-tint p-4">468 <div class="mb-4 flex flex-wrap items-center gap-3 rounded-xl border border-border-line bg-surface-tint p-4">
@@ -477,8 +483,7 @@ function AppointmentsContent() {
477 columns={bookingColumns()}483 columns={bookingColumns()}
478 data={myBookings()}484 data={myBookings()}
479 tableClass="table-fixed min-w-[46rem]"485 tableClass="table-fixed min-w-[46rem]"
480- enablePagination486+ infinite={{ hasMore: apptList.hasMore(), loading: apptList.loading(), total: apptList.total(), onLoadMore: apptList.loadMore }}
481- pageSize={PAGE_SIZE}
482 storageKey="appointment-bookings"487 storageKey="appointment-bookings"
483 onRowClick={setDetailAppt}488 onRowClick={setDetailAppt}
484 empty={t("appointments.noBookings")}489 empty={t("appointments.noBookings")}
@@ -488,15 +493,14 @@ function AppointmentsContent() {
488 }>493 }>
489 <section class="space-y-4 p-0">494 <section class="space-y-4 p-0">
490 <Show when={loaded()} fallback={<DataTableSkeleton columns={5} rows={6} />}>495 <Show when={loaded()} fallback={<DataTableSkeleton columns={5} rows={6} />}>
491- <Show when={appts.error}><Alert variant="destructive">{formatApiError(appts.error)}</Alert></Show>496+ <Show when={apptList.error()}>{(err) => <Alert variant="destructive">{formatApiError(err())}</Alert>}</Show>
492 <DataTable497 <DataTable
493 title={t("appointments.requests")}498 title={t("appointments.requests")}
494 description={t("appointments.requestsHint")}499 description={t("appointments.requestsHint")}
495 columns={requestColumns()}500 columns={requestColumns()}
496 data={requests()}501 data={requests()}
497 tableClass="table-fixed min-w-[46rem]"502 tableClass="table-fixed min-w-[46rem]"
498- enablePagination503+ infinite={{ hasMore: apptList.hasMore(), loading: apptList.loading(), total: apptList.total(), onLoadMore: apptList.loadMore }}
499- pageSize={PAGE_SIZE}
500 storageKey="appointment-requests"504 storageKey="appointment-requests"
501 onRowClick={setDetailAppt}505 onRowClick={setDetailAppt}
502 empty={t("appointments.noRequests")}506 empty={t("appointments.noRequests")}
@@ -510,15 +514,14 @@ function AppointmentsContent() {
510 <Show when={isStaff()} fallback={514 <Show when={isStaff()} fallback={
511 <section class="space-y-4 p-0">515 <section class="space-y-4 p-0">
512 <Show when={loaded()} fallback={<DataTableSkeleton columns={4} rows={6} />}>516 <Show when={loaded()} fallback={<DataTableSkeleton columns={4} rows={6} />}>
513- <Show when={slots.error}><Alert variant="destructive">{formatApiError(slots.error)}</Alert></Show>517+ <Show when={slotList.error()}>{(err) => <Alert variant="destructive">{formatApiError(err())}</Alert>}</Show>
514 <DataTable518 <DataTable
515 title={t("appointments.availableSlots")}519 title={t("appointments.availableSlots")}
516 description={t("appointments.availableSlotsHint")}520 description={t("appointments.availableSlotsHint")}
517 columns={availableColumns()}521 columns={availableColumns()}
518 data={availableSlots()}522 data={availableSlots()}
519 tableClass="table-fixed min-w-[46rem]"523 tableClass="table-fixed min-w-[46rem]"
520- enablePagination524+ infinite={{ hasMore: slotList.hasMore(), loading: slotList.loading(), total: slotList.total(), onLoadMore: slotList.loadMore }}
521- pageSize={PAGE_SIZE}
522 storageKey="appointment-available-slots"525 storageKey="appointment-available-slots"
523 onRowClick={setDetailSlot}526 onRowClick={setDetailSlot}
524 empty={t("appointments.noSlots")}527 empty={t("appointments.noSlots")}
@@ -528,7 +531,7 @@ function AppointmentsContent() {
528 }>531 }>
529 <section class="space-y-4 p-0">532 <section class="space-y-4 p-0">
530 <Show when={loaded()} fallback={<DataTableSkeleton columns={5} rows={6} />}>533 <Show when={loaded()} fallback={<DataTableSkeleton columns={5} rows={6} />}>
531- <Show when={slots.error}><Alert variant="destructive">{formatApiError(slots.error)}</Alert></Show>534+ <Show when={slotList.error()}>{(err) => <Alert variant="destructive">{formatApiError(err())}</Alert>}</Show>
532 <DataTable535 <DataTable
533 title={t("appointments.mySlots")}536 title={t("appointments.mySlots")}
534 description={t("appointments.mySlotsHint")}537 description={t("appointments.mySlotsHint")}
@@ -541,8 +544,7 @@ function AppointmentsContent() {
541 columns={slotColumns()}544 columns={slotColumns()}
542 data={mySlots()}545 data={mySlots()}
543 tableClass="table-fixed min-w-[46rem]"546 tableClass="table-fixed min-w-[46rem]"
544- enablePagination547+ infinite={{ hasMore: slotList.hasMore(), loading: slotList.loading(), total: slotList.total(), onLoadMore: slotList.loadMore }}
545- pageSize={PAGE_SIZE}
546 storageKey="appointment-my-slots"548 storageKey="appointment-my-slots"
547 onRowClick={setDetailSlot}549 onRowClick={setDetailSlot}
548 empty={t("appointments.noSlots")}550 empty={t("appointments.noSlots")}
src/pages/courses-page.tsxmodified+5 -3
@@ -82,9 +82,11 @@ function CoursesContent() {
82 ...(filters.q ? { q: filters.q } : {}),82 ...(filters.q ? { q: filters.q } : {}),
83 ...(filters.taught != null ? { taught: filters.taught } : {}),83 ...(filters.taught != null ? { taught: filters.taught } : {}),
84 }),84 }),
85- { equals: (a, b) => a.role === b.role && a.kind === b.kind && a.q === b.q && a.taught === b.taught },85+ { equals: (a, b) => a.role === b.role && a.kind === b.kind && a.q === b.q && a.taught === b.taught, restoreKey: "courses" },
86 );86 );
87- const refetch = () => list.reload();87+ // Edits and deletes re-read the loaded rows in place; the retry after an
88+ // error starts over.
89+ const refetch = () => list.refresh();
88 const openCourse = (course: Course) => void navigate({ to: "/courses/$id", params: { id: course.id } });90 const openCourse = (course: Course) => void navigate({ to: "/courses/$id", params: { id: course.id } });
89 // Catalog rights, as on the detail page: the creator or a manager+.91 // Catalog rights, as on the detail page: the creator or a manager+.
90 const canManageCatalog = (course: Course) => {92 const canManageCatalog = (course: Course) => {
@@ -273,7 +275,7 @@ function CoursesContent() {
273 275
274 <TabsContent value={pageKind() ?? "all"} class="mt-4 space-y-4 border-0 bg-transparent p-0 shadow-none">276 <TabsContent value={pageKind() ?? "all"} class="mt-4 space-y-4 border-0 bg-transparent p-0 shadow-none">
275 <Show when={list.error()}>277 <Show when={list.error()}>
276- {(err) => <ErrorAlert message={formatApiError(err())} onRetry={refetch} />}278+ {(err) => <ErrorAlert message={formatApiError(err())} onRetry={list.reload} />}
277 </Show>279 </Show>
278 <Show when={!list.initialLoading()} fallback={<DataTableSkeleton columns={5} rows={8} />}>280 <Show when={!list.initialLoading()} fallback={<DataTableSkeleton columns={5} rows={8} />}>
279 <DataTable281 <DataTable
src/pages/messages-page.tsxmodified+4 -2
@@ -62,9 +62,11 @@ export default function MessagesPage() {
62 const messageList = createInfiniteList(62 const messageList = createInfiniteList(
63 () => ({ f: folder(), q: debouncedQuery().trim() }),63 () => ({ f: folder(), q: debouncedQuery().trim() }),
64 (args, paging) => getMessages(args.f, { ...paging, ...(args.q ? { q: args.q } : {}) }),64 (args, paging) => getMessages(args.f, { ...paging, ...(args.q ? { q: args.q } : {}) }),
65- { equals: (a, b) => a.f === b.f && a.q === b.q },65+ { equals: (a, b) => a.f === b.f && a.q === b.q, restoreKey: "messages" },
66 );66 );
67- const refetch = async () => messageList.reload();67+ // Moves, deletes and the refresh button re-read the loaded rows in place,
68+ // so acting on a message far down the list keeps the reader there.
69+ const refetch = () => messageList.refresh();
68 70
69 const [unreadCount, { refetch: refetchUnread }] = createResource(71 const [unreadCount, { refetch: refetchUnread }] = createResource(
70 async () => (await getMessages("inbox", { read: false, limit: 1 })).total72 async () => (await getMessages("inbox", { read: false, limit: 1 })).total
src/pages/question-bank-page.tsxmodified+3 -2
@@ -75,10 +75,11 @@ function QuestionBankContent() {
75 });75 });
76 return result;76 return result;
77 },77 },
78- { equals: (a, b) => JSON.stringify(a) === JSON.stringify(b) },78+ { equals: (a, b) => JSON.stringify(a) === JSON.stringify(b), restoreKey: "question-bank" },
79 );79 );
80 const total = () => list.total();80 const total = () => list.total();
81- const refetch = () => list.reload();81+ // An edit or delete refreshes the loaded rows in place, keeping the reader's spot.
82+ const refetch = () => list.refresh();
82 83
83 // Only courses the teacher can author in supply subjects for a new template.84 // Only courses the teacher can author in supply subjects for a new template.
84 const [courses] = createResource(async () => (await getCourses({ limit: 100 })).items);85 const [courses] = createResource(async () => (await getCourses({ limit: 100 })).items);
src/pages/questions-page.tsxmodified+2 -1
@@ -52,9 +52,10 @@ function QuestionsContent() {
52 const questions = createInfiniteList(52 const questions = createInfiniteList(
53 () => statusFilter(),53 () => statusFilter(),
54 (status, paging) => getQuestions(status, paging),54 (status, paging) => getQuestions(status, paging),
55+ { restoreKey: "questions" },
55 );56 );
56 const list = () => questions.items();57 const list = () => questions.items();
57- const refetch = () => questions.reload();58+ const refetch = () => questions.refresh();
58 59
59 const [askOpen, setAskOpen] = createSignal(location().searchStr.includes("action=new"));60 const [askOpen, setAskOpen] = createSignal(location().searchStr.includes("action=new"));
60 const [questionToDelete, setQuestionToDelete] = createSignal<any | null>(null);61 const [questionToDelete, setQuestionToDelete] = createSignal<any | null>(null);
src/pages/whiteboards-page.tsxmodified+1 -0
@@ -44,6 +44,7 @@ function WhiteboardsContent() {
44 const boards = createInfiniteList(44 const boards = createInfiniteList(
45 () => debouncedQuery().trim(),45 () => debouncedQuery().trim(),
46 (q, paging) => getBoards({ ...paging, ...(q ? { q } : {}) }),46 (q, paging) => getBoards({ ...paging, ...(q ? { q } : {}) }),
47+ { restoreKey: "whiteboards" },
47 );48 );
48 const [createOpen, setCreateOpen] = createSignal(false);49 const [createOpen, setCreateOpen] = createSignal(false);
49 const visibleBoards = () => boards.items();50 const visibleBoards = () => boards.items();