EditArchiveModal.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. import { useState, useEffect, 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 } 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. // Keys for failure reasons - translated at render time
  10. const FAILURE_REASON_KEYS = [
  11. 'adhesionFailure',
  12. 'spaghettiDetached',
  13. 'layerShift',
  14. 'cloggedNozzle',
  15. 'filamentRunout',
  16. 'warping',
  17. 'stringing',
  18. 'underExtrusion',
  19. 'powerFailure',
  20. 'userCancelled',
  21. 'other',
  22. ] as const;
  23. // Keys for archive statuses - translated at render time
  24. const ARCHIVE_STATUS_KEYS = ['completed', 'failed', 'aborted', 'printing'] as const;
  25. interface EditArchiveModalProps {
  26. archive: Archive;
  27. onClose: () => void;
  28. existingTags?: string[];
  29. }
  30. export function EditArchiveModal({ archive, onClose, existingTags = [] }: EditArchiveModalProps) {
  31. const { t } = useTranslation();
  32. // Close on Escape key
  33. useEffect(() => {
  34. const handleKeyDown = (e: KeyboardEvent) => {
  35. if (e.key === 'Escape') onClose();
  36. };
  37. window.addEventListener('keydown', handleKeyDown);
  38. return () => window.removeEventListener('keydown', handleKeyDown);
  39. }, [onClose]);
  40. const queryClient = useQueryClient();
  41. const [printName, setPrintName] = useState(archive.print_name || '');
  42. const [printerId, setPrinterId] = useState<number | null>(archive.printer_id);
  43. const [projectId, setProjectId] = useState<number | null>(archive.project_id ?? null);
  44. const [notes, setNotes] = useState(archive.notes || '');
  45. const [tags, setTags] = useState(archive.tags || '');
  46. const [failureReason, setFailureReason] = useState(archive.failure_reason || '');
  47. const [status, setStatus] = useState(archive.status);
  48. const [quantity, setQuantity] = useState(archive.quantity ?? 1);
  49. const [photos, setPhotos] = useState<string[]>(archive.photos || []);
  50. const [externalUrl, setExternalUrl] = useState(archive.external_url || '');
  51. const [uploadingPhoto, setUploadingPhoto] = useState(false);
  52. const [showTagSuggestions, setShowTagSuggestions] = useState(false);
  53. const tagInputRef = useRef<HTMLInputElement>(null);
  54. const photoInputRef = useRef<HTMLInputElement>(null);
  55. const blurTimeoutRef = useRef<number | null>(null);
  56. const { data: printers } = useQuery({
  57. queryKey: ['printers'],
  58. queryFn: api.getPrinters,
  59. });
  60. const { data: projects } = useQuery({
  61. queryKey: ['projects'],
  62. queryFn: () => api.getProjects(),
  63. select: (rows) => [...rows].sort((a, b) => a.name.localeCompare(b.name)),
  64. });
  65. // Fetch all tags using the dedicated API
  66. const { data: tagsData } = useQuery({
  67. queryKey: ['tags'],
  68. queryFn: api.getTags,
  69. enabled: existingTags.length === 0,
  70. });
  71. // Use existing tags prop if provided, otherwise use fetched tags
  72. const allTags = existingTags.length > 0
  73. ? existingTags
  74. : (tagsData?.map(t => t.name) || []);
  75. // Get current tags as array
  76. const currentTags = tags.split(',').map(t => t.trim()).filter(Boolean);
  77. // Get the text being typed after the last comma (for autocomplete filtering)
  78. const currentInput = tags.includes(',')
  79. ? tags.substring(tags.lastIndexOf(',') + 1).trim().toLowerCase()
  80. : tags.trim().toLowerCase();
  81. // Filter suggestions: not already added AND matches current input (if any)
  82. const tagSuggestions = allTags.filter(t =>
  83. !currentTags.includes(t) &&
  84. (currentInput === '' || t.toLowerCase().includes(currentInput))
  85. );
  86. // Add a tag (replaces any partial input with the selected tag)
  87. const addTag = (tag: string) => {
  88. // If there's partial input being typed, replace it with the selected tag
  89. // Otherwise, just append the tag
  90. let baseTags: string[];
  91. if (currentInput && !allTags.includes(currentInput)) {
  92. // User is typing a partial tag - replace it with the selected one
  93. baseTags = tags.includes(',')
  94. ? tags.substring(0, tags.lastIndexOf(',')).split(',').map(t => t.trim()).filter(Boolean)
  95. : [];
  96. } else {
  97. // No partial input or input is already a complete tag - append
  98. baseTags = currentTags;
  99. }
  100. if (!baseTags.includes(tag)) {
  101. const newTags = [...baseTags, tag].join(', ');
  102. setTags(newTags);
  103. }
  104. // Clear any pending blur timeout to prevent hiding suggestions
  105. if (blurTimeoutRef.current !== null) {
  106. clearTimeout(blurTimeoutRef.current);
  107. }
  108. tagInputRef.current?.focus();
  109. };
  110. // Remove a tag
  111. const removeTag = (tagToRemove: string) => {
  112. const newTags = currentTags.filter(t => t !== tagToRemove).join(', ');
  113. setTags(newTags);
  114. };
  115. const updateMutation = useMutation({
  116. mutationFn: (data: Parameters<typeof api.updateArchive>[1]) =>
  117. api.updateArchive(archive.id, data),
  118. onSuccess: () => {
  119. queryClient.invalidateQueries({ queryKey: ['archives'] });
  120. queryClient.invalidateQueries({ queryKey: ['projects'] });
  121. onClose();
  122. },
  123. });
  124. const handlePhotoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  125. const file = e.target.files?.[0];
  126. if (!file) return;
  127. setUploadingPhoto(true);
  128. try {
  129. const result = await api.uploadArchivePhoto(archive.id, file);
  130. setPhotos(result.photos);
  131. queryClient.invalidateQueries({ queryKey: ['archives'] });
  132. } catch (error) {
  133. console.error('Failed to upload photo:', error);
  134. } finally {
  135. setUploadingPhoto(false);
  136. if (photoInputRef.current) {
  137. photoInputRef.current.value = '';
  138. }
  139. }
  140. };
  141. const handlePhotoDelete = async (filename: string) => {
  142. try {
  143. const result = await api.deleteArchivePhoto(archive.id, filename);
  144. setPhotos(result.photos || []);
  145. queryClient.invalidateQueries({ queryKey: ['archives'] });
  146. } catch (error) {
  147. console.error('Failed to delete photo:', error);
  148. }
  149. };
  150. const handleSubmit = (e: React.FormEvent) => {
  151. e.preventDefault();
  152. // Build update data
  153. const updateData: Parameters<typeof api.updateArchive>[1] = {
  154. print_name: printName || undefined,
  155. printer_id: printerId,
  156. project_id: projectId,
  157. notes: notes || undefined,
  158. tags: tags || undefined,
  159. quantity: quantity,
  160. external_url: externalUrl || null,
  161. };
  162. // Only include status if changed
  163. if (status !== archive.status) {
  164. updateData.status = status;
  165. }
  166. // Handle failure_reason based on status
  167. if (status === 'failed' || status === 'aborted') {
  168. updateData.failure_reason = failureReason || undefined;
  169. } else if (archive.status === 'failed' || archive.status === 'aborted') {
  170. // Clear failure_reason when changing from failed/aborted to another status
  171. updateData.failure_reason = null;
  172. }
  173. updateMutation.mutate(updateData);
  174. };
  175. return (
  176. <div
  177. className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4"
  178. onClick={onClose}
  179. >
  180. <div
  181. className="bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col"
  182. onClick={(e) => e.stopPropagation()}
  183. >
  184. {/* Header */}
  185. <div className="flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary">
  186. <h2 className="text-lg font-semibold text-white">{t('editArchive.title')}</h2>
  187. <button
  188. onClick={onClose}
  189. className="text-bambu-gray hover:text-white transition-colors"
  190. >
  191. <X className="w-5 h-5" />
  192. </button>
  193. </div>
  194. {/* Form */}
  195. <form onSubmit={handleSubmit} className="p-6 space-y-4 overflow-y-auto flex-1">
  196. {/* Print Log — per-run history pulled from PrintLogEntry (#1378). Shown
  197. first so users can see which runs contributed to the aggregate stats. */}
  198. <div>
  199. <label className="block text-sm text-bambu-gray mb-1">{t('archives.runLog.title')}</label>
  200. <PrintLogTable archiveId={archive.id} />
  201. </div>
  202. {/* Print Name */}
  203. <div>
  204. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.name')}</label>
  205. <input
  206. type="text"
  207. value={printName}
  208. onChange={(e) => setPrintName(e.target.value)}
  209. 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"
  210. placeholder={t('editArchive.namePlaceholder')}
  211. />
  212. </div>
  213. {/* Printer */}
  214. <div>
  215. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.printer')}</label>
  216. <select
  217. value={printerId ?? ''}
  218. onChange={(e) => setPrinterId(e.target.value ? Number(e.target.value) : null)}
  219. 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"
  220. >
  221. <option value="">{t('editArchive.noPrinter')}</option>
  222. {printers?.map((p) => (
  223. <option key={p.id} value={p.id}>
  224. {p.name}
  225. </option>
  226. ))}
  227. </select>
  228. </div>
  229. {/* Project */}
  230. <div>
  231. <label className="block text-sm text-bambu-gray mb-1">
  232. <FolderKanban className="w-4 h-4 inline mr-1" />
  233. {t('editArchive.project')}
  234. </label>
  235. <select
  236. value={projectId ?? ''}
  237. onChange={(e) => setProjectId(e.target.value ? Number(e.target.value) : null)}
  238. 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"
  239. >
  240. <option value="">{t('editArchive.noProject')}</option>
  241. {projects?.map((p) => (
  242. <option key={p.id} value={p.id}>
  243. {p.name}
  244. </option>
  245. ))}
  246. </select>
  247. </div>
  248. {/* Quantity - number of items printed */}
  249. <div>
  250. <label className="block text-sm text-bambu-gray mb-1">
  251. <Hash className="w-4 h-4 inline mr-1" />
  252. {t('editArchive.itemsPrinted')}
  253. </label>
  254. <input
  255. type="number"
  256. min={1}
  257. value={quantity}
  258. onChange={(e) => setQuantity(Math.max(1, parseInt(e.target.value) || 1))}
  259. 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"
  260. placeholder="1"
  261. />
  262. <p className="text-xs text-bambu-gray mt-1">
  263. {t('editArchive.itemsPrintedHelp')}
  264. </p>
  265. </div>
  266. {/* Notes */}
  267. <div>
  268. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.notes')}</label>
  269. <textarea
  270. value={notes}
  271. onChange={(e) => setNotes(e.target.value)}
  272. rows={3}
  273. 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"
  274. placeholder={t('editArchive.notesPlaceholder')}
  275. />
  276. </div>
  277. {/* External Link */}
  278. <div>
  279. <label className="block text-sm text-bambu-gray mb-1">
  280. <Link className="w-4 h-4 inline mr-1" />
  281. {t('editArchive.externalLink')}
  282. </label>
  283. <input
  284. type="url"
  285. value={externalUrl}
  286. onChange={(e) => setExternalUrl(e.target.value)}
  287. 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"
  288. placeholder="https://printables.com/model/..."
  289. />
  290. <p className="text-xs text-bambu-gray mt-1">
  291. {t('editArchive.externalLinkHelp')}
  292. </p>
  293. </div>
  294. {/* Tags */}
  295. <div>
  296. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.tags')}</label>
  297. {/* Current tags as chips */}
  298. {currentTags.length > 0 && (
  299. <div className="flex flex-wrap gap-1.5 mb-2">
  300. {currentTags.map((tag) => (
  301. <span
  302. key={tag}
  303. className="inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white"
  304. >
  305. <Tag className="w-3 h-3" />
  306. {tag}
  307. <button
  308. type="button"
  309. onClick={() => removeTag(tag)}
  310. className="ml-0.5 text-bambu-gray hover:text-white"
  311. >
  312. <X className="w-3 h-3" />
  313. </button>
  314. </span>
  315. ))}
  316. </div>
  317. )}
  318. {/* Tag input with suggestions */}
  319. <div className="relative">
  320. <input
  321. ref={tagInputRef}
  322. type="text"
  323. value={tags}
  324. onChange={(e) => setTags(e.target.value)}
  325. onFocus={() => {
  326. if (blurTimeoutRef.current !== null) {
  327. clearTimeout(blurTimeoutRef.current);
  328. }
  329. setShowTagSuggestions(true);
  330. }}
  331. onBlur={() => {
  332. blurTimeoutRef.current = window.setTimeout(() => setShowTagSuggestions(false), 200);
  333. }}
  334. 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"
  335. placeholder={currentTags.length > 0 ? t('editArchive.addMoreTags') : t('editArchive.tagsPlaceholder')}
  336. />
  337. {/* Suggestions dropdown */}
  338. {showTagSuggestions && tagSuggestions.length > 0 && (
  339. <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">
  340. <div className="p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary">
  341. {currentInput ? t('editArchive.matchingTags', { query: currentInput }) : t('editArchive.existingTags')} {t('editArchive.clickToAdd')}
  342. </div>
  343. <div className="p-2 flex flex-wrap gap-1.5">
  344. {tagSuggestions.map((tag) => (
  345. <button
  346. key={tag}
  347. type="button"
  348. onClick={() => addTag(tag)}
  349. 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"
  350. >
  351. {tag}
  352. </button>
  353. ))}
  354. </div>
  355. </div>
  356. )}
  357. </div>
  358. </div>
  359. {/* Status */}
  360. <div>
  361. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.status')}</label>
  362. <select
  363. value={status}
  364. onChange={(e) => {
  365. setStatus(e.target.value);
  366. // Clear failure reason when changing to completed
  367. if (e.target.value === 'completed') {
  368. setFailureReason('');
  369. }
  370. }}
  371. 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"
  372. >
  373. {ARCHIVE_STATUS_KEYS.map((statusKey) => (
  374. <option key={statusKey} value={statusKey}>
  375. {t(`editArchive.statuses.${statusKey}`)}
  376. </option>
  377. ))}
  378. </select>
  379. </div>
  380. {/* Failure Reason - only show for failed/aborted prints */}
  381. {(status === 'failed' || status === 'aborted') && (
  382. <div>
  383. <label className="block text-sm text-bambu-gray mb-1">{t('editArchive.failureReason')}</label>
  384. <select
  385. value={failureReason}
  386. onChange={(e) => setFailureReason(e.target.value)}
  387. 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"
  388. >
  389. <option value="">{t('editArchive.selectReason')}</option>
  390. {FAILURE_REASON_KEYS.map((reasonKey) => (
  391. <option key={reasonKey} value={t(`editArchive.failureReasons.${reasonKey}`)}>
  392. {t(`editArchive.failureReasons.${reasonKey}`)}
  393. </option>
  394. ))}
  395. </select>
  396. </div>
  397. )}
  398. {/* Photos */}
  399. <div>
  400. <label className="block text-sm text-bambu-gray mb-1">
  401. <Camera className="w-4 h-4 inline mr-1" />
  402. {t('editArchive.photos')}
  403. </label>
  404. {/* Photo grid */}
  405. <div className="flex flex-wrap gap-2 mb-2">
  406. {photos.map((filename) => (
  407. <div key={filename} className="relative group">
  408. <img
  409. src={api.getArchivePhotoUrl(archive.id, filename)}
  410. alt={t('editArchive.printResult')}
  411. className="w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"
  412. />
  413. <button
  414. type="button"
  415. onClick={() => handlePhotoDelete(filename)}
  416. className="absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
  417. >
  418. <Trash2 className="w-3 h-3 text-white" />
  419. </button>
  420. </div>
  421. ))}
  422. {/* Upload button */}
  423. <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">
  424. <input
  425. ref={photoInputRef}
  426. type="file"
  427. accept="image/jpeg,image/png,image/webp"
  428. onChange={handlePhotoUpload}
  429. className="hidden"
  430. disabled={uploadingPhoto}
  431. />
  432. {uploadingPhoto ? (
  433. <Loader2 className="w-6 h-6 text-bambu-gray animate-spin" />
  434. ) : (
  435. <Plus className="w-6 h-6 text-bambu-gray" />
  436. )}
  437. </label>
  438. </div>
  439. <p className="text-xs text-bambu-gray">{t('editArchive.photosHelp')}</p>
  440. </div>
  441. {/* Actions */}
  442. <div className="flex gap-3 pt-2">
  443. <Button
  444. type="button"
  445. variant="secondary"
  446. onClick={onClose}
  447. className="flex-1"
  448. >
  449. {t('common.cancel')}
  450. </Button>
  451. <Button
  452. type="submit"
  453. disabled={updateMutation.isPending}
  454. className="flex-1"
  455. >
  456. <Save className="w-4 h-4" />
  457. {updateMutation.isPending ? t('common.saving') : t('common.save')}
  458. </Button>
  459. </div>
  460. </form>
  461. </div>
  462. </div>
  463. );
  464. }