EditArchiveModal.tsx 19 KB

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