forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

instance-settings-panel.tsx240 lines, 10.2 KiBHistoryRawDownload
1import { Show, createEffect, createSignal } from "solid-js";
2import {
3 deleteInstanceExamWeightByKind,
4 deleteInstanceExamWeights,
5 deleteInstanceSubjectById,
6 deleteInstanceSubjects,
7 patchInstanceById,
8 patchInstanceExamWeight,
9 postInstanceReset,
10 postInstanceSubject,
11} from "@/api/instances";
12import { formatApiError, type ExamWeightEntry, type Instance, type InstanceOverrideField, type Subject } from "@/api/client";
13import { ExamWeightsEditor } from "@/components/instances/exam-weights-editor";
14import { OverrideBadge } from "@/components/instances/override-badge";
15import { SubjectSetEditor } from "@/components/instances/subject-set-editor";
16import { Alert } from "@/components/ui/alert";
17import { Button } from "@/components/ui/button";
18import { ConfirmDialog } from "@/components/ui/confirm-dialog";
19import { DataSection } from "@/components/ui/data-section";
20import { IconEdit, IconPlus, IconRotateCcw } from "@/components/ui/icons";
21import { Input } from "@/components/ui/input";
22import { Label } from "@/components/ui/label";
23import { SidePanel } from "@/components/ui/side-panel";
24import { Textarea } from "@/components/ui/textarea";
25import { useT } from "@/stores/preferences-context";
26
27type ResetTarget = { fields: InstanceOverrideField[]; label: string; run?: () => Promise<void> };
28
29/**
30 * What a section overrides of its grade template: title/description, hours
31 * and the karne flag, the topic set and the exam weights. Every value is the
32 * resolved one; a badge tells an own override from an inherited value, and
33 * "reset" hands a field back to the template.
34 */
35export function InstanceSettingsPanel(props: {
36 instance: Instance;
37 canManage: boolean;
38 /** The catalog course's subjects — what a section's own set may hold. */
39 courseSubjects: Subject[];
40 /** settings.exam_kinds names. */
41 examKinds: string[];
42 maxTitleLen?: number;
43 maxDescriptionLen?: number;
44 onChanged: () => unknown;
45}) {
46 const t = useT();
47 const [error, setError] = createSignal("");
48 const [editingContent, setEditingContent] = createSignal(false);
49 const [title, setTitle] = createSignal("");
50 const [description, setDescription] = createSignal("");
51 const [contentError, setContentError] = createSignal("");
52 const [pending, setPending] = createSignal(false);
53 const [reset, setReset] = createSignal<ResetTarget | null>(null);
54 const [weightEditing, setWeightEditing] = createSignal<ExamWeightEntry | "new" | null>(null);
55
56 createEffect(() => {
57 if (!editingContent()) return;
58 setTitle(props.instance.title);
59 setDescription(props.instance.description);
60 setContentError("");
61 });
62
63 const act = async (action: () => Promise<unknown>) => {
64 setError("");
65 try {
66 await action();
67 await props.onChanged();
68 } catch (err) {
69 setError(formatApiError(err));
70 throw err;
71 }
72 };
73
74 // For editors that show their own error: write, then reload the instance.
75 const mutate = async (action: () => Promise<unknown>) => {
76 await action();
77 await props.onChanged();
78 };
79
80 const saveContent = async (event: SubmitEvent) => {
81 event.preventDefault();
82 const nextTitle = title().trim();
83 if (!nextTitle) {
84 setContentError(t("form.fieldRequired"));
85 return;
86 }
87 // PATCH only what changed: sending an unchanged inherited value would
88 // silently freeze it as the section's own override.
89 const body: { title?: string; description?: string } = {};
90 if (nextTitle !== props.instance.title) body.title = nextTitle;
91 if (description().trim() !== props.instance.description) body.description = description().trim();
92 if (!body.title && body.description === undefined) {
93 setEditingContent(false);
94 return;
95 }
96 setPending(true);
97 try {
98 await patchInstanceById(props.instance.id, body);
99 await props.onChanged();
100 setEditingContent(false);
101 } catch (err) {
102 setContentError(formatApiError(err));
103 } finally {
104 setPending(false);
105 }
106 };
107
108 const resetButton = (target: ResetTarget) => (
109 <Button type="button" size="sm" variant="outline" class="rounded-lg" onClick={() => setReset(target)}>
110 <IconRotateCcw class="h-4 w-4" />
111 {t("override.reset")}
112 </Button>
113 );
114
115 const row = (label: string, value: string, own: boolean, field: InstanceOverrideField) => (
116 <div class="flex flex-wrap items-center justify-between gap-3 border-b border-border-hairline py-2.5 last:border-b-0">
117 <div class="min-w-0 flex-1">
118 <p class="text-xs font-medium text-text-subtle">{label}</p>
119 <p class="truncate text-sm text-text-default" title={value}>{value || "—"}</p>
120 </div>
121 <div class="flex shrink-0 items-center gap-2">
122 <OverrideBadge own={own} />
123 <Show when={props.canManage && own}>
124 {resetButton({ fields: [field], label })}
125 </Show>
126 </div>
127 </div>
128 );
129
130 return (
131 <div class="space-y-4">
132 <p class="text-sm text-muted-foreground">{t("instances.settingsHelp")}</p>
133 <Show when={error()}><Alert variant="destructive">{error()}</Alert></Show>
134
135 <DataSection
136 title={t("instances.contentTitle")}
137 description={t("instances.contentHelp")}
138 actions={
139 <Show when={props.canManage}>
140 <Button type="button" size="sm" variant="outline" onClick={() => setEditingContent(true)}>
141 <IconEdit class="h-4 w-4" />
142 {t("instances.editContent")}
143 </Button>
144 </Show>
145 }
146 >
147 <div>
148 {row(t("form.title"), props.instance.title, props.instance.title_overridden, "title")}
149 {row(t("form.description"), props.instance.description, props.instance.description_overridden, "description")}
150 </div>
151 </DataSection>
152
153 <DataSection title={t("instances.policyTitle")}>
154 <div>
155 {row(t("instances.dersSaati"), String(props.instance.ders_saati), props.instance.ders_saati_overridden, "ders_saati")}
156 {row(t("instances.countsTowardKarne"), props.instance.counts_toward_karne ? t("common.yes") : t("common.no"), props.instance.counts_toward_karne_overridden, "counts_toward_karne")}
157 </div>
158 </DataSection>
159
160 <DataSection
161 title={t("instances.subjectsTitle")}
162 description={`${t("instances.subjectsHelp")} ${props.instance.subjects_inherited ? t("instances.subjectsInheritedHint") : t("instances.subjectsOwnHint")}`}
163 actions={
164 <Show when={props.canManage && !props.instance.subjects_inherited}>
165 {resetButton({ fields: ["subjects"], label: t("instances.subjectsTitle"), run: () => deleteInstanceSubjects(props.instance.id) })}
166 </Show>
167 }
168 >
169 <OverrideBadge own={!props.instance.subjects_inherited} />
170 <SubjectSetEditor
171 selected={props.instance.subjects}
172 available={props.courseSubjects}
173 canEdit={props.canManage}
174 onAdd={(subjectId) => mutate(() => postInstanceSubject(props.instance.id, subjectId))}
175 onRemove={(subject) => mutate(() => deleteInstanceSubjectById(props.instance.id, subject.id))}
176 />
177 </DataSection>
178
179 <DataSection
180 title={t("instances.examWeightsTitle")}
181 description={`${t("instances.examWeightsHelp")} ${props.instance.exam_weights_inherited ? t("instances.examWeightsInheritedHint") : t("instances.examWeightsOwnHint")}`}
182 >
183 <OverrideBadge own={!props.instance.exam_weights_inherited} />
184 <ExamWeightsEditor
185 weights={props.instance.exam_weights}
186 kinds={props.examKinds}
187 canEdit={props.canManage}
188 editing={weightEditing()}
189 onEditingChange={setWeightEditing}
190 onSet={(entry) => mutate(() => patchInstanceExamWeight(props.instance.id, entry))}
191 onRemove={props.instance.exam_weights_inherited ? undefined : (kind) => mutate(() => deleteInstanceExamWeightByKind(props.instance.id, kind))}
192 actions={
193 <Show when={props.canManage}>
194 <Show when={!props.instance.exam_weights_inherited}>
195 {resetButton({ fields: ["exam_weights"], label: t("instances.examWeightsTitle"), run: () => deleteInstanceExamWeights(props.instance.id) })}
196 </Show>
197 <Button type="button" size="sm" onClick={() => setWeightEditing("new")}>
198 <IconPlus class="h-4 w-4" />
199 {t("instances.addWeight")}
200 </Button>
201 </Show>
202 }
203 />
204 </DataSection>
205
206 <SidePanel guardUnsaved open={editingContent()} onOpenChange={setEditingContent} title={t("instances.editContent")} description={t("instances.contentHelp")}>
207 <form class="space-y-4" noValidate onSubmit={saveContent}>
208 <div class="space-y-1.5">
209 <Label for="instance-title">{t("form.title")}</Label>
210 <Input id="instance-title" maxlength={props.maxTitleLen} value={title()} error={contentError() && !title().trim() ? contentError() : undefined} onInput={(e) => setTitle(e.currentTarget.value)} />
211 </div>
212 <div class="space-y-1.5">
213 <Label for="instance-description">{t("form.description")}</Label>
214 <Textarea id="instance-description" rows={4} maxlength={props.maxDescriptionLen} value={description()} onInput={(e) => setDescription(e.currentTarget.value)} />
215 </div>
216 <Show when={contentError() && title().trim()}><Alert variant="destructive">{contentError()}</Alert></Show>
217 <div class="flex gap-2 border-t border-border-hairline pt-4">
218 <Button type="submit" disabled={pending()}>{t("common.save")}</Button>
219 <Button type="button" variant="outline" onClick={() => setEditingContent(false)}>{t("common.cancel")}</Button>
220 </div>
221 </form>
222 </SidePanel>
223
224 <ConfirmDialog
225 open={reset() !== null}
226 onOpenChange={(open) => !open && setReset(null)}
227 title={t("override.resetConfirmTitle")}
228 description={t("override.resetConfirmHint")}
229 summary={reset()?.label ?? ""}
230 confirmLabel={t("override.reset")}
231 onConfirm={async () => {
232 const target = reset();
233 if (!target) return;
234 await act(() => (target.run ? target.run() : postInstanceReset(props.instance.id, target.fields))).catch(() => undefined);
235 setReset(null);
236 }}
237 />
238 </div>
239 );
240}