EditArchiveModal.tsx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. import { useState, useEffect, useMemo, useRef } from 'react';
  2. import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { X, Save, Tag, Camera, Trash2, Loader2, Plus, FolderKanban, Hash, Link, Weight } from 'lucide-react';
  5. import { api } from '../api/client';
  6. import type { Archive } from '../api/client';
  7. import { Button } from './Button';
  8. import { PrintLogTable } from './PrintLogTable';
  9. import { invalidateArchiveAndProjectViews } from '../utils/projectQueries';
  10. import { assignableProjects } from '../utils/projectTree';
  11. import { verdictSourceKey } from '../utils/verdictSource';
  12. // Keys for failure reasons - translated at render time.
  13. // Exported so the Print Log per-row classification editor (#1687 part 4)
  14. // can share the same vocabulary as the Archive Edit modal — the backend
  15. // PATCH /print-log/{id} validator gates writes against this exact list.
  16. export const FAILURE_REASON_KEYS = [
  17. 'adhesionFailure',
  18. 'spaghettiDetached',
  19. 'layerShift',
  20. 'cloggedNozzle',
  21. 'filamentRunout',
  22. 'warping',
  23. 'stringing',
  24. 'underExtrusion',
  25. 'powerFailure',
  26. 'userCancelled',
  27. 'noStatusUpdate',
  28. 'other',
  29. ] as const;
  30. // Keys for archive statuses - translated at render time
  31. const ARCHIVE_STATUS_KEYS = ['completed', 'failed', 'aborted', 'printing'] as const;
  32. // Mirrors the API's own bound on filament_used_grams. Clamped here as well so
  33. // the field cannot produce a request the backend would reject with a 422 —
  34. // this modal has no error surface, so a refused save looks like nothing
  35. // happened at all (#1820).
  36. const MAX_FILAMENT_GRAMS = 100000;
  37. interface EditArchiveModalProps {
  38. archive: Archive;
  39. onClose: () => void;
  40. existingTags?: string[];
  41. }
  42. export function EditArchiveModal({ archive, onClose, existingTags = [] }: EditArchiveModalProps) {
  43. const { t } = useTranslation();
  44. // Close on Escape key
  45. useEffect(() => {
  46. const handleKeyDown = (e: KeyboardEvent) => {
  47. if (e.key === 'Escape') onClose();
  48. };
  49. window.addEventListener('keydown', handleKeyDown);
  50. return () => window.removeEventListener('keydown', handleKeyDown);
  51. }, [onClose]);
  52. const queryClient = useQueryClient();
  53. const [printName, setPrintName] = useState(archive.print_name || '');
  54. const [printerId, setPrinterId] = useState<number | null>(archive.printer_id);
  55. const [projectId, setProjectId] = useState<number | null>(archive.project_id ?? null);
  56. const [notes, setNotes] = useState(archive.notes || '');
  57. const [tags, setTags] = useState(archive.tags || '');
  58. // Failure reason is stored as a camelCase key (`filamentRunout`). Three older
  59. // writers stored other spellings -- English display labels from the backend,
  60. // this modal's own translated labels, and two prose sentences from the stale
  61. // archive paths -- and a startup migration folds all of them onto keys
  62. // (issue #2974). This reverse lookup is the belt to that migration's braces,
  63. // for a frontend running against a backend that has not restarted yet.
  64. //
  65. // A value it cannot resolve is kept rather than dropped. It used to fall back
  66. // to '', which did not merely look wrong: the empty selection was then saved
  67. // over the stored text, so opening the editor on an archive whose reason was
  68. // free text and pressing Save silently destroyed the classification. Anything
  69. // unrecognised now shows up as its own option (see `unmappedReason` below).
  70. const [failureReason, setFailureReason] = useState(() => {
  71. const raw = archive.failure_reason || '';
  72. if (!raw) return '';
  73. if ((FAILURE_REASON_KEYS as readonly string[]).includes(raw)) return raw;
  74. const match = FAILURE_REASON_KEYS.find(
  75. (k) => t(`editArchive.failureReasons.${k}`) === raw,
  76. );
  77. return match || raw;
  78. });
  79. // The stored value when it is not part of the vocabulary, so the dropdown can
  80. // offer it verbatim instead of appearing empty over a reason that exists.
  81. const unmappedReason =
  82. failureReason && !(FAILURE_REASON_KEYS as readonly string[]).includes(failureReason)
  83. ? failureReason
  84. : null;
  85. const [status, setStatus] = useState(archive.status);
  86. // Post-print quality verdict (#1898): '' = none, 'good' / 'reject'
  87. const [userVerdict, setUserVerdict] = useState<string>(archive.user_verdict ?? '');
  88. const verdictSourceHintKey = verdictSourceKey(archive.user_verdict_source);
  89. const [quantity, setQuantity] = useState(archive.quantity ?? 1);
  90. // Kept as a string so the field can be genuinely empty: a print archived
  91. // without its 3MF has no figure at all, and "" has to stay distinguishable
  92. // from 0 both on the way in and on the way out (#1820).
  93. const [filamentGrams, setFilamentGrams] = useState(
  94. archive.filament_used_grams != null ? String(archive.filament_used_grams) : ''
  95. );
  96. const [photos, setPhotos] = useState<string[]>(archive.photos || []);
  97. const [externalUrl, setExternalUrl] = useState(archive.external_url || '');
  98. const [uploadingPhoto, setUploadingPhoto] = useState(false);
  99. const [showTagSuggestions, setShowTagSuggestions] = useState(false);
  100. const tagInputRef = useRef<HTMLInputElement>(null);
  101. const photoInputRef = useRef<HTMLInputElement>(null);
  102. const blurTimeoutRef = useRef<number | null>(null);
  103. const { data: printers } = useQuery({
  104. queryKey: ['printers'],
  105. queryFn: api.getPrinters,
  106. });
  107. const { data: projects } = useQuery({
  108. queryKey: ['projects'],
  109. queryFn: () => api.getProjects(),
  110. select: (rows) => [...rows].sort((a, b) => a.name.localeCompare(b.name)),
  111. });
  112. // Archived projects drop off the list, except the one this archive is
  113. // already filed under. That one has to stay: a select holding a value with
  114. // no matching option resets to the first one, so the field would read
  115. // "No project" for an archive that is in one (#2888).
  116. const projectOptions = useMemo(
  117. () => assignableProjects(projects ?? [], archive.project_id),
  118. [projects, archive.project_id],
  119. );
  120. // Fetch all tags using the dedicated API
  121. const { data: tagsData } = useQuery({
  122. queryKey: ['tags'],
  123. queryFn: api.getTags,
  124. enabled: existingTags.length === 0,
  125. });
  126. // Use existing tags prop if provided, otherwise use fetched tags
  127. const allTags = existingTags.length > 0
  128. ? existingTags
  129. : (tagsData?.map(t => t.name) || []);
  130. // Get current tags as array
  131. const currentTags = tags.split(',').map(t => t.trim()).filter(Boolean);
  132. // Get the text being typed after the last comma (for autocomplete filtering)
  133. const currentInput = tags.includes(',')
  134. ? tags.substring(tags.lastIndexOf(',') + 1).trim().toLowerCase()
  135. : tags.trim().toLowerCase();
  136. // Filter suggestions: not already added AND matches current input (if any)
  137. const tagSuggestions = allTags.filter(t =>
  138. !currentTags.includes(t) &&
  139. (currentInput === '' || t.toLowerCase().includes(currentInput))
  140. );
  141. // Add a tag (replaces any partial input with the selected tag)
  142. const addTag = (tag: string) => {
  143. // If there's partial input being typed, replace it with the selected tag
  144. // Otherwise, just append the tag
  145. let baseTags: string[];
  146. if (currentInput && !allTags.includes(currentInput)) {
  147. // User is typing a partial tag - replace it with the selected one
  148. baseTags = tags.includes(',')
  149. ? tags.substring(0, tags.lastIndexOf(',')).split(',').map(t => t.trim()).filter(Boolean)
  150. : [];
  151. } else {
  152. // No partial input or input is already a complete tag - append
  153. baseTags = currentTags;
  154. }
  155. if (!baseTags.includes(tag)) {
  156. const newTags = [...baseTags, tag].join(', ');
  157. setTags(newTags);
  158. }
  159. // Clear any pending blur timeout to prevent hiding suggestions
  160. if (blurTimeoutRef.current !== null) {
  161. clearTimeout(blurTimeoutRef.current);
  162. }
  163. tagInputRef.current?.focus();
  164. };
  165. // Remove a tag
  166. const removeTag = (tagToRemove: string) => {
  167. const newTags = currentTags.filter(t => t !== tagToRemove).join(', ');
  168. setTags(newTags);
  169. };
  170. const updateMutation = useMutation({
  171. mutationFn: (data: Parameters<typeof api.updateArchive>[1]) =>
  172. api.updateArchive(archive.id, data),
  173. onSuccess: () => {
  174. // This form can change the archive's project, so the project detail
  175. // views need refreshing too — not just the overview cards (#2731).
  176. invalidateArchiveAndProjectViews(queryClient);
  177. // Some of what this form writes is mirrored onto the archive's most
  178. // recent run — status and failure reason since #1444, filament grams
  179. // since #1820 — and the Print Log this modal renders at its top reads
  180. // the runs through their own query. Without this it serves the cached
  181. // pre-edit row, so the correction looks like it did not take.
  182. queryClient.invalidateQueries({ queryKey: ['archive-runs', archive.id] });
  183. onClose();
  184. },
  185. });
  186. const handlePhotoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  187. const file = e.target.files?.[0];
  188. if (!file) return;
  189. setUploadingPhoto(true);
  190. try {
  191. const result = await api.uploadArchivePhoto(archive.id, file);
  192. setPhotos(result.photos);
  193. queryClient.invalidateQueries({ queryKey: ['archives'] });
  194. } catch (error) {
  195. console.error('Failed to upload photo:', error);
  196. } finally {
  197. setUploadingPhoto(false);
  198. if (photoInputRef.current) {
  199. photoInputRef.current.value = '';
  200. }
  201. }
  202. };
  203. const handlePhotoDelete = async (filename: string) => {
  204. try {
  205. const result = await api.deleteArchivePhoto(archive.id, filename);
  206. setPhotos(result.photos || []);
  207. queryClient.invalidateQueries({ queryKey: ['archives'] });
  208. } catch (error) {
  209. console.error('Failed to delete photo:', error);
  210. }
  211. };
  212. const handleSubmit = (e: React.FormEvent) => {
  213. e.preventDefault();
  214. // Build update data
  215. const updateData: Parameters<typeof api.updateArchive>[1] = {
  216. print_name: printName || undefined,
  217. printer_id: printerId,
  218. project_id: projectId,
  219. notes: notes || undefined,
  220. tags: tags || undefined,
  221. quantity: quantity,
  222. external_url: externalUrl || null,
  223. };
  224. // Only include status if changed
  225. if (status !== archive.status) {
  226. updateData.status = status;
  227. }
  228. // Verdict only when touched, same reasoning as status; '' clears it.
  229. if (userVerdict !== (archive.user_verdict ?? '')) {
  230. updateData.user_verdict = userVerdict === '' ? null : (userVerdict as 'good' | 'reject');
  231. updateData.user_verdict_source = 'dialog';
  232. }
  233. // Sent only when the user actually touched it, so an ordinary save of an
  234. // archive that has its 3MF cannot overwrite the sliced figure with a
  235. // rounded one from the input.
  236. const trimmedGrams = filamentGrams.trim();
  237. const typedGrams = trimmedGrams === '' ? null : Number(trimmedGrams);
  238. // An empty field means "no figure" and clears the stored one; a field that
  239. // holds something unparseable (a lone decimal point, mid-typing) means the
  240. // user is not finished, and must not read as a clear. Clamped here as well
  241. // as on blur because Enter submits without the field losing focus.
  242. const gramsUnparseable = typedGrams !== null && !Number.isFinite(typedGrams);
  243. const parsedGrams = typedGrams === null ? null : Math.min(Math.max(typedGrams, 0), MAX_FILAMENT_GRAMS);
  244. const originalGrams = archive.filament_used_grams ?? null;
  245. if (!gramsUnparseable && parsedGrams !== originalGrams) {
  246. updateData.filament_used_grams = parsedGrams;
  247. }
  248. // Handle failure_reason based on status. A completed-but-rejected print
  249. // (#1898) uses the same field as its reject reason.
  250. if (status === 'failed' || status === 'aborted') {
  251. updateData.failure_reason = failureReason || undefined;
  252. } else if (status === 'completed' && userVerdict === 'reject') {
  253. updateData.failure_reason = failureReason || undefined;
  254. } else if (archive.status === 'failed' || archive.status === 'aborted' || archive.user_verdict === 'reject') {
  255. // Clear failure_reason when neither a failure nor a reject carries one.
  256. // Gated on the archive having held a reject verdict rather than on the
  257. // field merely being populated: a 'cancelled' or 'stopped' archive is
  258. // neither failed nor aborted, its reason is written by the machine
  259. // ("Stopped by user (printer was offline)"), and the status dropdown has
  260. // no option that would let the user put it back.
  261. updateData.failure_reason = null;
  262. }
  263. updateMutation.mutate(updateData);
  264. };
  265. return (
  266. <div
  267. className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4"
  268. onClick={onClose}
  269. >
  270. <div
  271. className="bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col"
  272. onClick={(e) => e.stopPropagation()}
  273. >
  274. {/* Header */}
  275. <div className="flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary">
  276. <h2 className="text-lg font-semibold text-white">{t('editArchive.title')}</h2>
  277. <button
  278. onClick={onClose}
  279. className="text-bambu-gray hover:text-white transition-colors"
  280. >
  281. <X className="w-5 h-5" />
  282. </button>
  283. </div>
  284. {/* Form */}
  285. <form onSubmit={handleSubmit} className="p-6 space-y-4 overflow-y-auto flex-1">
  286. {/* Print Log — per-run history pulled from PrintLogEntry (#1378). Shown
  287. first so users can see which runs contributed to the aggregate stats. */}
  288. <div>
  289. <label className="block text-sm text-bambu-gray mb-1">{t('archives.runLog.title')}</label>
  290. <PrintLogTable archiveId={archive.id} />
  291. </div>
  292. {/* Print Name */}
  293. <div>
  294. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.name')}</label>
  295. <input
  296. type="text"
  297. value={printName}
  298. onChange={(e) => setPrintName(e.target.value)}
  299. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  300. placeholder={t('editArchive.namePlaceholder')}
  301. />
  302. </div>
  303. {/* Printer */}
  304. <div>
  305. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.printer')}</label>
  306. <select
  307. value={printerId ?? ''}
  308. onChange={(e) => setPrinterId(e.target.value ? Number(e.target.value) : null)}
  309. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  310. >
  311. <option value="">{t('editArchive.noPrinter')}</option>
  312. {printers?.map((p) => (
  313. <option key={p.id} value={p.id}>
  314. {p.name}
  315. </option>
  316. ))}
  317. </select>
  318. </div>
  319. {/* Project */}
  320. <div>
  321. <label className="block text-sm text-bambu-gray mb-1">
  322. <FolderKanban className="w-4 h-4 inline mr-1" />
  323. {t('editArchive.project')}
  324. </label>
  325. <select
  326. value={projectId ?? ''}
  327. onChange={(e) => setProjectId(e.target.value ? Number(e.target.value) : null)}
  328. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  329. >
  330. <option value="">{t('editArchive.noProject')}</option>
  331. {projectOptions.map((p) => (
  332. <option key={p.id} value={p.id}>
  333. {p.name}
  334. </option>
  335. ))}
  336. </select>
  337. </div>
  338. {/* Quantity - number of items printed */}
  339. <div>
  340. <label className="block text-sm text-bambu-gray mb-1" htmlFor="archive-items-printed">
  341. <Hash className="w-4 h-4 inline mr-1" />
  342. {t('editArchive.itemsPrinted')}
  343. </label>
  344. <input
  345. id="archive-items-printed"
  346. type="number"
  347. min={0}
  348. value={quantity}
  349. // 0 is a real answer, not an empty field: a plate that jammed and
  350. // came off ruined produced nothing, and the project's completed
  351. // count has to be able to say so (#3051).
  352. onChange={(e) => setQuantity(Math.max(0, parseInt(e.target.value) || 0))}
  353. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  354. placeholder="1"
  355. />
  356. <p className="text-xs text-bambu-gray mt-1">
  357. {t('editArchive.itemsPrintedHelp')}
  358. </p>
  359. </div>
  360. {/* Filament used - the only way to supply a figure for a print that
  361. archived without its 3MF, which no rescan can repair (#1820). */}
  362. <div>
  363. <label className="block text-sm text-bambu-gray mb-1" htmlFor="archive-filament-grams">
  364. <Weight className="w-4 h-4 inline mr-1" />
  365. {t('editArchive.filamentUsed')}
  366. </label>
  367. <input
  368. id="archive-filament-grams"
  369. type="text"
  370. inputMode="decimal"
  371. value={filamentGrams}
  372. // Text rather than number, and filtered on the way in. A number
  373. // input reports an empty string for anything the browser judges
  374. // malformed — including a decimal comma in a locale it doesn't
  375. // expect — which would read here as "the user cleared it" and
  376. // wipe a good figure. Filtering keeps what is displayed and what
  377. // would be sent the same thing, and keeps the value inside the
  378. // range the API accepts: this modal shows nothing at all when a
  379. // save is refused, so it must not be able to send a refusable one.
  380. onChange={(e) => {
  381. const next = e.target.value.replace(',', '.');
  382. if (next === '' || /^\d*\.?\d*$/.test(next)) setFilamentGrams(next);
  383. }}
  384. onBlur={() => setFilamentGrams((current) => {
  385. const parsed = Number(current);
  386. if (current === '' || !Number.isFinite(parsed)) return '';
  387. return String(Math.min(parsed, MAX_FILAMENT_GRAMS));
  388. })}
  389. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  390. placeholder={t('editArchive.filamentUsedPlaceholder')}
  391. />
  392. <p className="text-xs text-bambu-gray mt-1">
  393. {t('editArchive.filamentUsedHelp')}
  394. </p>
  395. </div>
  396. {/* Notes */}
  397. <div>
  398. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.notes')}</label>
  399. <textarea
  400. value={notes}
  401. onChange={(e) => setNotes(e.target.value)}
  402. rows={3}
  403. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none"
  404. placeholder={t('editArchive.notesPlaceholder')}
  405. />
  406. </div>
  407. {/* External Link */}
  408. <div>
  409. <label className="block text-sm text-bambu-gray mb-1">
  410. <Link className="w-4 h-4 inline mr-1" />
  411. {t('editArchive.externalLink')}
  412. </label>
  413. <input
  414. type="url"
  415. value={externalUrl}
  416. onChange={(e) => setExternalUrl(e.target.value)}
  417. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  418. placeholder="https://printables.com/model/..."
  419. />
  420. <p className="text-xs text-bambu-gray mt-1">
  421. {t('editArchive.externalLinkHelp')}
  422. </p>
  423. </div>
  424. {/* Tags */}
  425. <div>
  426. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.tags')}</label>
  427. {/* Current tags as chips */}
  428. {currentTags.length > 0 && (
  429. <div className="flex flex-wrap gap-1.5 mb-2">
  430. {currentTags.map((tag) => (
  431. <span
  432. key={tag}
  433. className="inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white"
  434. >
  435. <Tag className="w-3 h-3" />
  436. {tag}
  437. <button
  438. type="button"
  439. onClick={() => removeTag(tag)}
  440. className="ml-0.5 text-bambu-gray hover:text-white"
  441. >
  442. <X className="w-3 h-3" />
  443. </button>
  444. </span>
  445. ))}
  446. </div>
  447. )}
  448. {/* Tag input with suggestions */}
  449. <div className="relative">
  450. <input
  451. ref={tagInputRef}
  452. type="text"
  453. value={tags}
  454. onChange={(e) => setTags(e.target.value)}
  455. onFocus={() => {
  456. if (blurTimeoutRef.current !== null) {
  457. clearTimeout(blurTimeoutRef.current);
  458. }
  459. setShowTagSuggestions(true);
  460. }}
  461. onBlur={() => {
  462. blurTimeoutRef.current = window.setTimeout(() => setShowTagSuggestions(false), 200);
  463. }}
  464. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  465. placeholder={currentTags.length > 0 ? t('editArchive.addMoreTags') : t('editArchive.tagsPlaceholder')}
  466. />
  467. {/* Suggestions dropdown */}
  468. {showTagSuggestions && tagSuggestions.length > 0 && (
  469. <div className="absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto">
  470. <div className="p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary">
  471. {currentInput ? t('editArchive.matchingTags', { query: currentInput }) : t('editArchive.existingTags')} {t('editArchive.clickToAdd')}
  472. </div>
  473. <div className="p-2 flex flex-wrap gap-1.5">
  474. {tagSuggestions.map((tag) => (
  475. <button
  476. key={tag}
  477. type="button"
  478. onClick={() => addTag(tag)}
  479. className="px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors"
  480. >
  481. {tag}
  482. </button>
  483. ))}
  484. </div>
  485. </div>
  486. )}
  487. </div>
  488. </div>
  489. {/* Status */}
  490. <div>
  491. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.status')}</label>
  492. <select
  493. value={status}
  494. onChange={(e) => {
  495. setStatus(e.target.value);
  496. // Clear failure reason when changing to completed
  497. if (e.target.value === 'completed') {
  498. setFailureReason('');
  499. }
  500. }}
  501. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  502. >
  503. {ARCHIVE_STATUS_KEYS.map((statusKey) => (
  504. <option key={statusKey} value={statusKey}>
  505. {t(`editArchive.statuses.${statusKey}`)}
  506. </option>
  507. ))}
  508. </select>
  509. </div>
  510. {/* Outcome verdict (#1898) - only meaningful on completed prints */}
  511. {status === 'completed' && (
  512. <div>
  513. <label htmlFor="user-verdict-select" className="block text-sm text-bambu-gray mb-1">
  514. {t('editArchive.userVerdict')}
  515. </label>
  516. <select
  517. id="user-verdict-select"
  518. value={userVerdict}
  519. onChange={(e) => setUserVerdict(e.target.value)}
  520. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  521. >
  522. <option value="">{t('editArchive.verdicts.none')}</option>
  523. <option value="good">{t('editArchive.verdicts.good')}</option>
  524. <option value="reject">{t('editArchive.verdicts.reject')}</option>
  525. </select>
  526. {/* How the stored verdict got here (#1898) — hidden once the
  527. select no longer shows that verdict, since the hint would
  528. then describe an answer the user is replacing. */}
  529. {verdictSourceHintKey && userVerdict === (archive.user_verdict ?? '') && (
  530. <p className="text-xs text-bambu-gray/70 mt-1" data-testid="verdict-source-hint">
  531. {t(verdictSourceHintKey)}
  532. </p>
  533. )}
  534. </div>
  535. )}
  536. {/* Failure Reason - shown for failed/aborted prints and for
  537. completed-but-rejected ones (#1898: the reject reason reuses
  538. this field and vocabulary) */}
  539. {(status === 'failed' || status === 'aborted' || (status === 'completed' && userVerdict === 'reject')) && (
  540. <div>
  541. <label htmlFor="failure-reason-select" className="block text-sm text-bambu-gray mb-1">{t('editArchive.failureReason')}</label>
  542. <select
  543. id="failure-reason-select"
  544. value={failureReason}
  545. onChange={(e) => setFailureReason(e.target.value)}
  546. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  547. >
  548. <option value="">{t('editArchive.selectReason')}</option>
  549. {FAILURE_REASON_KEYS.map((reasonKey) => (
  550. <option key={reasonKey} value={reasonKey}>
  551. {t(`editArchive.failureReasons.${reasonKey}`)}
  552. </option>
  553. ))}
  554. {/* A stored reason outside the vocabulary keeps its own option
  555. so it stays visible and survives a save (issue #2974). */}
  556. {unmappedReason && (
  557. <option value={unmappedReason}>{unmappedReason}</option>
  558. )}
  559. </select>
  560. </div>
  561. )}
  562. {/* Photos */}
  563. <div>
  564. <label className="block text-sm text-bambu-gray mb-1">
  565. <Camera className="w-4 h-4 inline mr-1" />
  566. {t('editArchive.photos')}
  567. </label>
  568. {/* Photo grid */}
  569. <div className="flex flex-wrap gap-2 mb-2">
  570. {photos.map((filename) => (
  571. <div key={filename} className="relative group">
  572. <img
  573. src={api.getArchivePhotoUrl(archive.id, filename)}
  574. alt={t('editArchive.printResult')}
  575. className="w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"
  576. />
  577. <button
  578. type="button"
  579. onClick={() => handlePhotoDelete(filename)}
  580. className="absolute -top-1 -right-1 p-1 bg-red-500 rounded-full can-hover:opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity"
  581. >
  582. <Trash2 className="w-3 h-3 text-white" />
  583. </button>
  584. </div>
  585. ))}
  586. {/* Upload button */}
  587. <label className="w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors">
  588. <input
  589. ref={photoInputRef}
  590. type="file"
  591. accept="image/jpeg,image/png,image/webp"
  592. onChange={handlePhotoUpload}
  593. className="hidden"
  594. disabled={uploadingPhoto}
  595. />
  596. {uploadingPhoto ? (
  597. <Loader2 className="w-6 h-6 text-bambu-gray animate-spin" />
  598. ) : (
  599. <Plus className="w-6 h-6 text-bambu-gray" />
  600. )}
  601. </label>
  602. </div>
  603. <p className="text-xs text-bambu-gray">{t('editArchive.photosHelp')}</p>
  604. </div>
  605. {/* Actions */}
  606. <div className="flex gap-3 pt-2">
  607. <Button
  608. type="button"
  609. variant="secondary"
  610. onClick={onClose}
  611. className="flex-1"
  612. >
  613. {t('common.cancel')}
  614. </Button>
  615. <Button
  616. type="submit"
  617. disabled={updateMutation.isPending}
  618. className="flex-1"
  619. >
  620. <Save className="w-4 h-4" />
  621. {updateMutation.isPending ? t('common.saving') : t('common.save')}
  622. </Button>
  623. </div>
  624. </form>
  625. </div>
  626. </div>
  627. );
  628. }