hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits
| 1 | import { createEffect, createSignal, onCleanup } from "solid-js"; |
| 2 | import { getClassById, getClassInstances, getClasses, getMyClasses } from "@/api/classes"; |
| 3 | import { getInstanceById } from "@/api/instances"; |
| 4 | import type { ClassCourse, ClassGroup, Role } from "@/api/client"; |
| 5 | import { FAN_OUT_LIMIT, mapConcurrent } from "@/lib/map-concurrent"; |
| 6 | import { hasMinRole } from "@/lib/roles"; |
| 7 | |
| 8 | /** |
| 9 | * "<ders> — <şube>" for a şube×ders instance. |
| 10 | * |
| 11 | * Exams and homework name an instance (`class_course`), never a course. The |
| 12 | * same ders taught in two şubeler therefore produces rows with the same title, |
| 13 | * and only the şube tells them apart — so every surface listing them labels a |
| 14 | * row through here instead of showing the catalog title alone. |
| 15 | * |
| 16 | * Reads, all cached for the tab (a section never changes its course or class): |
| 17 | * - `GET /instances/{id}`: ids plus the resolved display `title` (override, |
| 18 | * else offering, else catalog), so no per-course read is needed; |
| 19 | * - the class name: one `GET /classes` list for teacher+, `GET /classes/me` |
| 20 | * once for anyone else; a class missing from the list falls back to |
| 21 | * `GET /classes/{id}`. |
| 22 | * A read the caller may not make just leaves that part out of the label. |
| 23 | */ |
| 24 | export type InstanceLabel = { |
| 25 | course: string; |
| 26 | class: string; |
| 27 | courseTitle: string | null; |
| 28 | className: string | null; |
| 29 | label: string; |
| 30 | }; |
| 31 | |
| 32 | const instanceCache = new Map<string, Promise<InstanceLabel | null>>(); |
| 33 | const classCache = new Map<string, Promise<string | null>>(); |
| 34 | let myClassesCache: Promise<Map<string, string>> | null = null; |
| 35 | let allClassesCache: Promise<Map<string, string>> | null = null; |
| 36 | let classListCache: Promise<ClassGroup[]> | null = null; |
| 37 | const sectionCache = new Map<string, Promise<ClassCourse[]>>(); |
| 38 | let schoolIndexCache: Promise<boolean> | null = null; |
| 39 | const FRESH_MS = 5 * 60 * 1000; |
| 40 | let freshUntil = Date.now() + FRESH_MS; |
| 41 | |
| 42 | function ensureFresh(): void { |
| 43 | if (Date.now() >= freshUntil) invalidateSchoolWalk(); |
| 44 | } |
| 45 | |
| 46 | export function invalidateSchoolWalk(): void { |
| 47 | resetInstanceLabelCache(); |
| 48 | freshUntil = Date.now() + FRESH_MS; |
| 49 | } |
| 50 | |
| 51 | /** Teacher+: the school's class list, read once per tab. */ |
| 52 | export function classList(): Promise<ClassGroup[]> { |
| 53 | ensureFresh(); |
| 54 | if (!classListCache) { |
| 55 | classListCache = getClasses({ limit: 200 }).then( |
| 56 | (page) => page.items, |
| 57 | () => { |
| 58 | classListCache = null; |
| 59 | return []; |
| 60 | }, |
| 61 | ); |
| 62 | } |
| 63 | return classListCache; |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * Teacher+: every section of the school, class by class (there is no |
| 68 | * school-wide section route), read once per tab and shared by the label |
| 69 | * cache and the section pickers. A class that cannot be read comes back empty. |
| 70 | */ |
| 71 | export function classSections(classId: string): Promise<ClassCourse[]> { |
| 72 | ensureFresh(); |
| 73 | let hit = sectionCache.get(classId); |
| 74 | if (!hit) { |
| 75 | const read = getClassInstances(classId, { limit: 200 }).then((page) => page.items); |
| 76 | const pending = read.catch((error) => { |
| 77 | if (sectionCache.get(classId) === pending) sectionCache.delete(classId); |
| 78 | throw error; |
| 79 | }); |
| 80 | hit = pending; |
| 81 | sectionCache.set(classId, hit); |
| 82 | } |
| 83 | return hit; |
| 84 | } |
| 85 | |
| 86 | export async function loadSchoolSections(): Promise<{ klass: ClassGroup; sections: ClassCourse[] }[]> { |
| 87 | const classes = await classList(); |
| 88 | return mapConcurrent(classes, FAN_OUT_LIMIT, async (klass) => ({ |
| 89 | klass, sections: await classSections(klass.id).catch(() => [] as ClassCourse[]), |
| 90 | })); |
| 91 | } |
| 92 | |
| 93 | /** |
| 94 | * Teacher+ only: read every section of the school through the class list — |
| 95 | * one request per class — and seed the label cache with all of them. Used |
| 96 | * when a page needs more labels than there are classes (a dashboard or a |
| 97 | * calendar full of homework), where it replaces one read per section. |
| 98 | */ |
| 99 | function seedSchoolIndex(role: Role | undefined): Promise<boolean> { |
| 100 | if (!schoolIndexCache) { |
| 101 | schoolIndexCache = loadSchoolSections().then((pages) => { |
| 102 | if (pages.length === 0) return false; |
| 103 | for (const entry of pages) { |
| 104 | for (const instance of entry.sections) { |
| 105 | const title = instance.title?.trim() || null; |
| 106 | const label = formatInstanceLabel(title, entry.klass.name); |
| 107 | if (!label) continue; |
| 108 | instanceCache.set(`${role ?? ""}:${instance.id}`, Promise.resolve({ |
| 109 | course: instance.course, |
| 110 | class: instance.class, |
| 111 | courseTitle: title, |
| 112 | className: entry.klass.name, |
| 113 | label, |
| 114 | })); |
| 115 | } |
| 116 | } |
| 117 | return true; |
| 118 | }).catch(() => { |
| 119 | schoolIndexCache = null; |
| 120 | return false; |
| 121 | }); |
| 122 | } |
| 123 | return schoolIndexCache; |
| 124 | } |
| 125 | |
| 126 | function className(id: string, role: Role | undefined): Promise<string | null> { |
| 127 | if (hasMinRole(role, "teacher")) { |
| 128 | if (!allClassesCache) { |
| 129 | allClassesCache = classList().then((classes) => new Map(classes.map((klass) => [klass.id, klass.name]))); |
| 130 | } |
| 131 | return allClassesCache.then((names) => names.get(id) ?? classById(id)); |
| 132 | } |
| 133 | if (!myClassesCache) { |
| 134 | myClassesCache = getMyClasses().then( |
| 135 | (page) => new Map(page.items.map((klass) => [klass.id, klass.name])), |
| 136 | () => new Map<string, string>(), |
| 137 | ); |
| 138 | } |
| 139 | return myClassesCache.then((names) => names.get(id) ?? null); |
| 140 | } |
| 141 | |
| 142 | function classById(id: string): Promise<string | null> { |
| 143 | { |
| 144 | let hit = classCache.get(id); |
| 145 | if (!hit) { |
| 146 | hit = getClassById(id).then( |
| 147 | (klass) => klass.name, |
| 148 | () => { |
| 149 | classCache.delete(id); |
| 150 | return null; |
| 151 | }, |
| 152 | ); |
| 153 | classCache.set(id, hit); |
| 154 | } |
| 155 | return hit; |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | /** Joins a course title and a class name; either may be missing. */ |
| 160 | export function formatInstanceLabel(courseTitle: string | null, className: string | null): string { |
| 161 | if (courseTitle && className) return `${courseTitle} — ${className}`; |
| 162 | return courseTitle ?? className ?? ""; |
| 163 | } |
| 164 | |
| 165 | export function loadInstanceLabel(id: string, role: Role | undefined): Promise<InstanceLabel | null> { |
| 166 | ensureFresh(); |
| 167 | const key = `${role ?? ""}:${id}`; |
| 168 | let hit = instanceCache.get(key); |
| 169 | if (!hit) { |
| 170 | hit = Promise.resolve() |
| 171 | .then(() => getInstanceById(id)) |
| 172 | .then(async (instance) => { |
| 173 | const title = instance.title?.trim() || null; |
| 174 | const klass = await className(instance.class, role); |
| 175 | // A part that failed to load (a rate limit, a blip) is not kept, so |
| 176 | // the next list asks again instead of showing a half label all session. |
| 177 | if (title == null || klass == null) instanceCache.delete(key); |
| 178 | const label = formatInstanceLabel(title, klass); |
| 179 | return label ? { course: instance.course, class: instance.class, courseTitle: title, className: klass, label } : null; |
| 180 | }) |
| 181 | .catch(() => { |
| 182 | // A failed read is not remembered, so a later list can try again. |
| 183 | instanceCache.delete(key); |
| 184 | return null; |
| 185 | }); |
| 186 | instanceCache.set(key, hit); |
| 187 | } |
| 188 | return hit; |
| 189 | } |
| 190 | |
| 191 | /** Labels for a bounded set of instance ids, fetched a few at a time. */ |
| 192 | export async function loadInstanceLabels(ids: readonly string[], role: Role | undefined): Promise<Map<string, InstanceLabel>> { |
| 193 | ensureFresh(); |
| 194 | const unique = [...new Set(ids)]; |
| 195 | // Many labels at once: reading the school's sections class by class is |
| 196 | // cheaper than one read per section, once they outnumber the classes. |
| 197 | if (hasMinRole(role, "teacher")) { |
| 198 | const uncached = unique.filter((id) => !instanceCache.has(`${role ?? ""}:${id}`)); |
| 199 | if (uncached.length > 0) { |
| 200 | const classes = await classList(); |
| 201 | if (classes.length > 0 && uncached.length > classes.length) await seedSchoolIndex(role); |
| 202 | } |
| 203 | } |
| 204 | const labels = await mapConcurrent(unique, FAN_OUT_LIMIT, (id) => loadInstanceLabel(id, role)); |
| 205 | const out = new Map<string, InstanceLabel>(); |
| 206 | unique.forEach((id, index) => { |
| 207 | const label = labels[index]; |
| 208 | if (label) out.set(id, label); |
| 209 | }); |
| 210 | return out; |
| 211 | } |
| 212 | |
| 213 | /** Reactive `instance id -> label` record that fills in as the reads land. */ |
| 214 | export function createInstanceLabels(ids: () => readonly string[], role: () => Role | undefined) { |
| 215 | const [labels, setLabels] = createSignal<Record<string, InstanceLabel>>({}); |
| 216 | createEffect(() => { |
| 217 | const wanted = [...new Set(ids())]; |
| 218 | const currentRole = role(); |
| 219 | let disposed = false; |
| 220 | onCleanup(() => { |
| 221 | disposed = true; |
| 222 | }); |
| 223 | if (!currentRole || wanted.length === 0) return; |
| 224 | void loadInstanceLabels(wanted, currentRole).catch(() => new Map<string, InstanceLabel>()).then((found) => { |
| 225 | if (disposed || found.size === 0) return; |
| 226 | setLabels((prev) => { |
| 227 | let changed = false; |
| 228 | const next = { ...prev }; |
| 229 | for (const [id, entry] of found) { |
| 230 | if (next[id]?.label !== entry.label) { |
| 231 | next[id] = entry; |
| 232 | changed = true; |
| 233 | } |
| 234 | } |
| 235 | return changed ? next : prev; |
| 236 | }); |
| 237 | }); |
| 238 | }); |
| 239 | return labels; |
| 240 | } |
| 241 | |
| 242 | /** Test hook: forget every cached read. */ |
| 243 | export function resetInstanceLabelCache(): void { |
| 244 | instanceCache.clear(); |
| 245 | classCache.clear(); |
| 246 | myClassesCache = null; |
| 247 | allClassesCache = null; |
| 248 | classListCache = null; |
| 249 | sectionCache.clear(); |
| 250 | schoolIndexCache = null; |
| 251 | freshUntil = Date.now() + FRESH_MS; |
| 252 | } |