hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits
| 1 | import { createEffect, createSignal, onCleanup } from "solid-js"; |
| 2 | import { getClassesByUserId } from "@/api/classes"; |
| 3 | |
| 4 | /** |
| 5 | * Class labels for people shown in a search result. `/users/search` returns |
| 6 | * only id/username/display name, so "which class is this student in?" — the |
| 7 | * question that tells two students with the same name apart — needs a second |
| 8 | * read per student (`GET /classes/user/{id}`, teacher+). |
| 9 | * |
| 10 | * Only call this for a list that is already bounded (a picker's visible |
| 11 | * results, a palette page), and only for students: a caller below teacher |
| 12 | * gets a 403, which is swallowed here as "no label". |
| 13 | * |
| 14 | * Answers are cached for the lifetime of the tab. Class membership does not |
| 15 | * move during a session, and without the cache every keystroke-driven result |
| 16 | * list would re-ask for people it just looked up. |
| 17 | */ |
| 18 | const cache = new Map<string, string>(); |
| 19 | const inflight = new Map<string, Promise<string>>(); |
| 20 | |
| 21 | const MAX_CLASSES_PER_STUDENT = 3; |
| 22 | |
| 23 | function load(userId: string): Promise<string> { |
| 24 | const cached = cache.get(userId); |
| 25 | if (cached !== undefined) return Promise.resolve(cached); |
| 26 | const running = inflight.get(userId); |
| 27 | if (running) return running; |
| 28 | const request = getClassesByUserId(userId, { limit: MAX_CLASSES_PER_STUDENT }) |
| 29 | .then((page) => page.items.map((group) => group.name).join(", ")) |
| 30 | // A 403/404 (no permission, no such membership) is not an error to show — |
| 31 | // the row simply carries no class. |
| 32 | .catch(() => "") |
| 33 | .then((label) => { |
| 34 | cache.set(userId, label); |
| 35 | inflight.delete(userId); |
| 36 | return label; |
| 37 | }); |
| 38 | inflight.set(userId, request); |
| 39 | return request; |
| 40 | } |
| 41 | |
| 42 | /** Reactive `id -> class name` map that fills in as the lookups land. */ |
| 43 | export function createStudentClassLabels(userIds: () => string[]) { |
| 44 | const [labels, setLabels] = createSignal<Record<string, string>>({}); |
| 45 | createEffect(() => { |
| 46 | let disposed = false; |
| 47 | onCleanup(() => { |
| 48 | disposed = true; |
| 49 | }); |
| 50 | for (const id of userIds()) { |
| 51 | void load(id).then((label) => { |
| 52 | if (disposed || !label) return; |
| 53 | setLabels((prev) => (prev[id] === label ? prev : { ...prev, [id]: label })); |
| 54 | }); |
| 55 | } |
| 56 | }); |
| 57 | return labels; |
| 58 | } |