aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/client/components/EditNoteModal.tsx
blob: 5bd864dd404f9fff4802ebbc7bca1a324e89e4d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import { faSpinner } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { type FormEvent, useCallback, useEffect, useState } from "react";
import { ApiClientError, apiClient } from "../api";

interface NoteField {
	id: string;
	name: string;
	order: number;
}

interface NoteType {
	id: string;
	name: string;
	frontTemplate: string;
	backTemplate: string;
	isReversible: boolean;
	fields: NoteField[];
}

interface NoteFieldValue {
	id: string;
	noteId: string;
	noteFieldTypeId: string;
	value: string;
}

interface NoteWithFieldValues {
	id: string;
	deckId: string;
	noteTypeId: string;
	fieldValues: NoteFieldValue[];
}

interface EditNoteModalProps {
	isOpen: boolean;
	deckId: string;
	noteId: string | null;
	onClose: () => void;
	onNoteUpdated: () => void;
}

export function EditNoteModal({
	isOpen,
	deckId,
	noteId,
	onClose,
	onNoteUpdated,
}: EditNoteModalProps) {
	const [note, setNote] = useState<NoteWithFieldValues | null>(null);
	const [noteType, setNoteType] = useState<NoteType | null>(null);
	const [fieldValues, setFieldValues] = useState<Record<string, string>>({});
	const [error, setError] = useState<string | null>(null);
	const [isLoadingNote, setIsLoadingNote] = useState(false);
	const [isLoadingNoteType, setIsLoadingNoteType] = useState(false);
	const [isSubmitting, setIsSubmitting] = useState(false);

	const fetchNoteTypeDetails = useCallback(async (noteTypeId: string) => {
		setIsLoadingNoteType(true);
		setError(null);

		try {
			const authHeader = apiClient.getAuthHeader();
			if (!authHeader) {
				throw new ApiClientError("Not authenticated", 401);
			}

			const res = await fetch(`/api/note-types/${noteTypeId}`, {
				headers: authHeader,
			});

			if (!res.ok) {
				const errorBody = await res.json().catch(() => ({}));
				throw new ApiClientError(
					(errorBody as { error?: string }).error ||
						`Request failed with status ${res.status}`,
					res.status,
				);
			}

			const data = await res.json();
			setNoteType(data.noteType);
		} catch (err) {
			if (err instanceof ApiClientError) {
				setError(err.message);
			} else {
				setError("Failed to load note type details. Please try again.");
			}
		} finally {
			setIsLoadingNoteType(false);
		}
	}, []);

	const fetchNote = useCallback(async () => {
		if (!noteId) return;

		setIsLoadingNote(true);
		setError(null);

		try {
			const authHeader = apiClient.getAuthHeader();
			if (!authHeader) {
				throw new ApiClientError("Not authenticated", 401);
			}

			const res = await fetch(`/api/decks/${deckId}/notes/${noteId}`, {
				headers: authHeader,
			});

			if (!res.ok) {
				const errorBody = await res.json().catch(() => ({}));
				throw new ApiClientError(
					(errorBody as { error?: string }).error ||
						`Request failed with status ${res.status}`,
					res.status,
				);
			}

			const data = await res.json();
			setNote(data.note);

			// Initialize field values from note
			const initialValues: Record<string, string> = {};
			for (const fv of data.note.fieldValues) {
				initialValues[fv.noteFieldTypeId] = fv.value;
			}
			setFieldValues(initialValues);

			// Fetch note type details
			await fetchNoteTypeDetails(data.note.noteTypeId);
		} catch (err) {
			if (err instanceof ApiClientError) {
				setError(err.message);
			} else {
				setError("Failed to load note. Please try again.");
			}
		} finally {
			setIsLoadingNote(false);
		}
	}, [noteId, deckId, fetchNoteTypeDetails]);

	useEffect(() => {
		if (isOpen && noteId) {
			fetchNote();
		}
	}, [isOpen, noteId, fetchNote]);

	const resetForm = () => {
		setNote(null);
		setNoteType(null);
		setFieldValues({});
		setError(null);
	};

	const handleClose = () => {
		resetForm();
		onClose();
	};

	const handleFieldChange = (fieldId: string, value: string) => {
		setFieldValues((prev) => ({
			...prev,
			[fieldId]: value,
		}));
	};

	const handleSubmit = async (e: FormEvent) => {
		e.preventDefault();
		setError(null);

		if (!note) {
			setError("Note data is not loaded.");
			return;
		}

		setIsSubmitting(true);

		try {
			const authHeader = apiClient.getAuthHeader();
			if (!authHeader) {
				throw new ApiClientError("Not authenticated", 401);
			}

			// Trim all field values
			const trimmedFields: Record<string, string> = {};
			for (const [fieldId, value] of Object.entries(fieldValues)) {
				trimmedFields[fieldId] = value.trim();
			}

			const res = await fetch(`/api/decks/${deckId}/notes/${note.id}`, {
				method: "PUT",
				headers: {
					"Content-Type": "application/json",
					...authHeader,
				},
				body: JSON.stringify({
					fields: trimmedFields,
				}),
			});

			if (!res.ok) {
				const errorBody = await res.json().catch(() => ({}));
				throw new ApiClientError(
					(errorBody as { error?: string }).error ||
						`Request failed with status ${res.status}`,
					res.status,
				);
			}

			onNoteUpdated();
			handleClose();
		} catch (err) {
			if (err instanceof ApiClientError) {
				setError(err.message);
			} else {
				setError("Failed to update note. Please try again.");
			}
		} finally {
			setIsSubmitting(false);
		}
	};

	if (!isOpen || !noteId) {
		return null;
	}

	// Check if all required fields have values
	const isFormValid =
		noteType &&
		noteType.fields.length > 0 &&
		noteType.fields.every((field) => fieldValues[field.id]?.trim());

	const isLoading = isLoadingNote || isLoadingNoteType;

	return (
		<div
			role="dialog"
			aria-modal="true"
			aria-labelledby="edit-note-title"
			className="fixed inset-0 bg-ink/40 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in"
			onClick={(e) => {
				if (e.target === e.currentTarget) {
					handleClose();
				}
			}}
			onKeyDown={(e) => {
				if (e.key === "Escape") {
					handleClose();
				}
			}}
		>
			<div className="bg-white rounded-2xl shadow-xl w-full max-w-lg animate-scale-in">
				<div className="p-6">
					<h2
						id="edit-note-title"
						className="font-display text-xl font-medium text-ink mb-6"
					>
						Edit Note
					</h2>

					<form onSubmit={handleSubmit} className="space-y-4">
						{error && (
							<div
								role="alert"
								className="bg-error/5 text-error text-sm px-4 py-3 rounded-lg border border-error/20"
							>
								{error}
							</div>
						)}

						{/* Loading indicator */}
						{isLoading && (
							<div className="flex items-center gap-2 text-muted text-sm py-4">
								<FontAwesomeIcon
									icon={faSpinner}
									className="h-4 w-4 animate-spin"
									aria-hidden="true"
								/>
								Loading note...
							</div>
						)}

						{/* Note Type Display (read-only) */}
						{noteType && !isLoading && (
							<div>
								<span className="block text-sm font-medium text-slate mb-1.5">
									Note Type
								</span>
								<div className="px-4 py-2.5 bg-ivory border border-border rounded-lg text-muted">
									{noteType.name}
									{noteType.isReversible ? " (reversed)" : ""}
								</div>
							</div>
						)}

						{/* Dynamic Field Inputs */}
						{noteType &&
							!isLoading &&
							(noteType.fields.length === 0 ? (
								<div className="text-muted text-sm py-2">
									This note type has no fields.
								</div>
							) : (
								noteType.fields
									.sort((a, b) => a.order - b.order)
									.map((field) => (
										<div key={field.id}>
											<label
												htmlFor={`field-${field.id}`}
												className="block text-sm font-medium text-slate mb-1.5"
											>
												{field.name}
											</label>
											<textarea
												id={`field-${field.id}`}
												value={fieldValues[field.id] || ""}
												onChange={(e) =>
													handleFieldChange(field.id, e.target.value)
												}
												required
												disabled={isSubmitting}
												rows={3}
												placeholder={`Enter ${field.name.toLowerCase()}`}
												className="w-full px-4 py-2.5 bg-ivory border border-border rounded-lg text-slate placeholder-muted transition-all duration-200 hover:border-muted focus:border-primary focus:ring-2 focus:ring-primary/10 disabled:opacity-50 disabled:cursor-not-allowed resize-none"
											/>
										</div>
									))
							))}

						<div className="flex gap-3 justify-end pt-2">
							<button
								type="button"
								onClick={handleClose}
								disabled={isSubmitting}
								className="px-4 py-2 text-slate hover:bg-ivory rounded-lg transition-colors disabled:opacity-50"
							>
								Cancel
							</button>
							<button
								type="submit"
								disabled={isSubmitting || !isFormValid || isLoading}
								className="px-4 py-2 bg-primary hover:bg-primary-dark text-white font-medium rounded-lg transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
							>
								{isSubmitting ? "Saving..." : "Save Changes"}
							</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	);
}