ArchivesPage.tsx 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885
  1. import { useState, useRef, useEffect, useCallback } from 'react';
  2. import { Link } from 'react-router-dom';
  3. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  4. import {
  5. Download,
  6. Trash2,
  7. Clock,
  8. Package,
  9. Layers,
  10. Search,
  11. Filter,
  12. Image,
  13. Box,
  14. Printer,
  15. Upload,
  16. ExternalLink,
  17. CheckSquare,
  18. Square,
  19. X,
  20. Globe,
  21. Pencil,
  22. LayoutGrid,
  23. List,
  24. CalendarDays,
  25. ArrowUpDown,
  26. Star,
  27. Tag,
  28. StickyNote,
  29. FolderOpen,
  30. Calendar,
  31. AlertCircle,
  32. Copy,
  33. Film,
  34. ScanSearch,
  35. QrCode,
  36. Camera,
  37. FileText,
  38. FileCode,
  39. MoreVertical,
  40. FileSpreadsheet,
  41. GitCompare,
  42. Loader2,
  43. FolderKanban,
  44. ChevronLeft,
  45. ChevronRight,
  46. Settings,
  47. } from 'lucide-react';
  48. import { api } from '../api/client';
  49. import { openInSlicer } from '../utils/slicer';
  50. import { formatDateTime, formatDateOnly, parseUTCDate, type TimeFormat } from '../utils/date';
  51. import { useIsMobile } from '../hooks/useIsMobile';
  52. import type { Archive, ProjectListItem } from '../api/client';
  53. import { Card, CardContent } from '../components/Card';
  54. import { Button } from '../components/Button';
  55. import { ModelViewerModal } from '../components/ModelViewerModal';
  56. import { PrintModal } from '../components/PrintModal';
  57. import { UploadModal } from '../components/UploadModal';
  58. import { ConfirmModal } from '../components/ConfirmModal';
  59. import { EditArchiveModal } from '../components/EditArchiveModal';
  60. import { ContextMenu, type ContextMenuItem } from '../components/ContextMenu';
  61. import { BatchTagModal } from '../components/BatchTagModal';
  62. import { BatchProjectModal } from '../components/BatchProjectModal';
  63. import { CalendarView } from '../components/CalendarView';
  64. import { QRCodeModal } from '../components/QRCodeModal';
  65. import { PhotoGalleryModal } from '../components/PhotoGalleryModal';
  66. import { ProjectPageModal } from '../components/ProjectPageModal';
  67. import { TimelapseViewer } from '../components/TimelapseViewer';
  68. import { CompareArchivesModal } from '../components/CompareArchivesModal';
  69. import { PendingUploadsPanel } from '../components/PendingUploadsPanel';
  70. import { TagManagementModal } from '../components/TagManagementModal';
  71. import { useToast } from '../contexts/ToastContext';
  72. function formatFileSize(bytes: number): string {
  73. if (bytes < 1024) return `${bytes} B`;
  74. if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  75. return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  76. }
  77. function formatDuration(seconds: number): string {
  78. const hours = Math.floor(seconds / 3600);
  79. const minutes = Math.floor((seconds % 3600) / 60);
  80. if (hours > 0) return `${hours}h ${minutes}m`;
  81. return `${minutes}m`;
  82. }
  83. /**
  84. * Check if an archive filename represents a sliced/printable file.
  85. * Matches: .gcode, .gcode.3mf, .gcode.anything
  86. */
  87. function isSlicedFile(filename: string | null | undefined): boolean {
  88. if (!filename) return false;
  89. const lower = filename.toLowerCase();
  90. // Match .gcode at end OR .gcode. followed by anything (like .gcode.3mf)
  91. return lower.endsWith('.gcode') || lower.includes('.gcode.');
  92. }
  93. // formatDate imported from '../utils/date' - handles UTC conversion
  94. function ArchiveCard({
  95. archive,
  96. printerName,
  97. isSelected,
  98. onSelect,
  99. selectionMode,
  100. projects,
  101. isHighlighted,
  102. timeFormat = 'system',
  103. }: {
  104. archive: Archive;
  105. printerName: string;
  106. isSelected: boolean;
  107. onSelect: (id: number) => void;
  108. selectionMode: boolean;
  109. projects: ProjectListItem[] | undefined;
  110. isHighlighted?: boolean;
  111. timeFormat?: TimeFormat;
  112. }) {
  113. // Debug: log when card is highlighted
  114. if (isHighlighted) {
  115. console.log('ArchiveCard isHighlighted=true for archive:', archive.id);
  116. }
  117. const queryClient = useQueryClient();
  118. const { showToast } = useToast();
  119. const isMobile = useIsMobile();
  120. const [showViewer, setShowViewer] = useState(false);
  121. const [showReprint, setShowReprint] = useState(false);
  122. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  123. const [showEdit, setShowEdit] = useState(false);
  124. const [showTimelapse, setShowTimelapse] = useState(false);
  125. const [showTimelapseSelect, setShowTimelapseSelect] = useState(false);
  126. const [availableTimelapses, setAvailableTimelapses] = useState<Array<{ name: string; path: string; size: number; mtime: string | null }>>([]);
  127. const [showQRCode, setShowQRCode] = useState(false);
  128. const [showPhotos, setShowPhotos] = useState(false);
  129. const [showProjectPage, setShowProjectPage] = useState(false);
  130. const [showSchedule, setShowSchedule] = useState(false);
  131. const [showDeleteSource3mfConfirm, setShowDeleteSource3mfConfirm] = useState(false);
  132. const [showDeleteF3dConfirm, setShowDeleteF3dConfirm] = useState(false);
  133. const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
  134. const [currentPlateIndex, setCurrentPlateIndex] = useState<number | null>(null);
  135. const [showPlateNav, setShowPlateNav] = useState(false);
  136. const source3mfInputRef = useRef<HTMLInputElement>(null);
  137. const f3dInputRef = useRef<HTMLInputElement>(null);
  138. // Fetch plates data for multi-plate browsing (lazy - only when hovering)
  139. const { data: platesData } = useQuery({
  140. queryKey: ['archive-plates', archive.id],
  141. queryFn: () => api.getArchivePlates(archive.id),
  142. enabled: showPlateNav, // Only fetch when user hovers to see navigation
  143. staleTime: 5 * 60 * 1000, // Cache for 5 minutes
  144. });
  145. const plates = platesData?.plates ?? [];
  146. const isMultiPlate = platesData?.is_multi_plate ?? false;
  147. const displayPlateIndex = currentPlateIndex ?? 0;
  148. const source3mfUploadMutation = useMutation({
  149. mutationFn: (file: File) => api.uploadSource3mf(archive.id, file),
  150. onSuccess: (data) => {
  151. queryClient.invalidateQueries({ queryKey: ['archives'] });
  152. showToast(`Source 3MF attached: ${data.filename}`);
  153. },
  154. onError: (error: Error) => {
  155. showToast(error.message || 'Failed to upload source 3MF', 'error');
  156. },
  157. });
  158. const source3mfDeleteMutation = useMutation({
  159. mutationFn: () => api.deleteSource3mf(archive.id),
  160. onSuccess: () => {
  161. queryClient.invalidateQueries({ queryKey: ['archives'] });
  162. showToast('Source 3MF removed');
  163. },
  164. onError: (error: Error) => {
  165. showToast(error.message || 'Failed to remove source 3MF', 'error');
  166. },
  167. });
  168. const f3dUploadMutation = useMutation({
  169. mutationFn: (file: File) => api.uploadF3d(archive.id, file),
  170. onSuccess: (data) => {
  171. queryClient.invalidateQueries({ queryKey: ['archives'] });
  172. showToast(`F3D attached: ${data.filename}`);
  173. },
  174. onError: (error: Error) => {
  175. showToast(error.message || 'Failed to upload F3D', 'error');
  176. },
  177. });
  178. const f3dDeleteMutation = useMutation({
  179. mutationFn: () => api.deleteF3d(archive.id),
  180. onSuccess: () => {
  181. queryClient.invalidateQueries({ queryKey: ['archives'] });
  182. showToast('F3D removed');
  183. },
  184. onError: (error: Error) => {
  185. showToast(error.message || 'Failed to remove F3D', 'error');
  186. },
  187. });
  188. const timelapseScanMutation = useMutation({
  189. mutationFn: () => api.scanArchiveTimelapse(archive.id),
  190. onSuccess: (data) => {
  191. if (data.status === 'attached') {
  192. queryClient.invalidateQueries({ queryKey: ['archives'] });
  193. showToast(`Timelapse attached: ${data.filename}`);
  194. } else if (data.status === 'exists') {
  195. showToast('Timelapse already attached');
  196. } else if (data.status === 'not_found' && data.available_files && data.available_files.length > 0) {
  197. // Show selection dialog
  198. setAvailableTimelapses(data.available_files);
  199. setShowTimelapseSelect(true);
  200. } else {
  201. showToast(data.message || 'No matching timelapse found', 'warning');
  202. }
  203. },
  204. onError: (error: Error) => {
  205. showToast(error.message || 'Failed to scan for timelapse', 'error');
  206. },
  207. });
  208. const timelapseSelectMutation = useMutation({
  209. mutationFn: (filename: string) => api.selectArchiveTimelapse(archive.id, filename),
  210. onSuccess: (data) => {
  211. queryClient.invalidateQueries({ queryKey: ['archives'] });
  212. showToast(`Timelapse attached: ${data.filename}`);
  213. setShowTimelapseSelect(false);
  214. setAvailableTimelapses([]);
  215. },
  216. onError: (error: Error) => {
  217. showToast(error.message || 'Failed to attach timelapse', 'error');
  218. },
  219. });
  220. const deleteMutation = useMutation({
  221. mutationFn: () => api.deleteArchive(archive.id),
  222. onSuccess: () => {
  223. queryClient.invalidateQueries({ queryKey: ['archives'] });
  224. showToast('Archive deleted');
  225. },
  226. onError: () => {
  227. showToast('Failed to delete archive', 'error');
  228. },
  229. });
  230. const favoriteMutation = useMutation({
  231. mutationFn: () => api.toggleFavorite(archive.id),
  232. onSuccess: (data) => {
  233. queryClient.invalidateQueries({ queryKey: ['archives'] });
  234. showToast(data.is_favorite ? 'Added to favorites' : 'Removed from favorites');
  235. },
  236. });
  237. // Query for linked folders
  238. const { data: linkedFolders } = useQuery({
  239. queryKey: ['archive-folders', archive.id],
  240. queryFn: () => api.getLibraryFoldersByArchive(archive.id),
  241. });
  242. const assignProjectMutation = useMutation({
  243. mutationFn: (projectId: number | null) => api.updateArchive(archive.id, { project_id: projectId }),
  244. onSuccess: () => {
  245. queryClient.invalidateQueries({ queryKey: ['archives'] });
  246. queryClient.invalidateQueries({ queryKey: ['projects'] });
  247. showToast('Project updated');
  248. },
  249. onError: () => {
  250. showToast('Failed to update project', 'error');
  251. },
  252. });
  253. const handleContextMenu = (e: React.MouseEvent) => {
  254. e.preventDefault();
  255. setContextMenu({ x: e.clientX, y: e.clientY });
  256. };
  257. const isGcodeFile = isSlicedFile(archive.filename);
  258. const contextMenuItems: ContextMenuItem[] = [
  259. // For gcode files: show Print option
  260. // For source files: show Slice as the primary action
  261. ...(isGcodeFile ? [
  262. {
  263. label: 'Print',
  264. icon: <Printer className="w-4 h-4" />,
  265. onClick: () => setShowReprint(true),
  266. },
  267. {
  268. label: 'Schedule',
  269. icon: <Calendar className="w-4 h-4" />,
  270. onClick: () => setShowSchedule(true),
  271. },
  272. {
  273. label: 'Open in Bambu Studio',
  274. icon: <ExternalLink className="w-4 h-4" />,
  275. onClick: () => {
  276. const filename = archive.print_name || archive.filename || 'model';
  277. const downloadUrl = `${window.location.origin}${api.getArchiveForSlicer(archive.id, filename)}`;
  278. openInSlicer(downloadUrl);
  279. },
  280. },
  281. ] : [
  282. {
  283. label: 'Slice',
  284. icon: <ExternalLink className="w-4 h-4" />,
  285. onClick: () => {
  286. const filename = archive.print_name || archive.filename || 'model';
  287. const downloadUrl = `${window.location.origin}${api.getArchiveForSlicer(archive.id, filename)}`;
  288. openInSlicer(downloadUrl);
  289. },
  290. },
  291. ]),
  292. {
  293. label: archive.external_url ? 'External Link' : 'View on MakerWorld',
  294. icon: <Globe className="w-4 h-4" />,
  295. onClick: () => {
  296. const url = archive.external_url || archive.makerworld_url;
  297. if (url) window.open(url, '_blank');
  298. },
  299. disabled: !archive.external_url && !archive.makerworld_url,
  300. },
  301. { label: '', divider: true, onClick: () => {} },
  302. {
  303. label: '3D Preview',
  304. icon: <Box className="w-4 h-4" />,
  305. onClick: () => setShowViewer(true),
  306. },
  307. {
  308. label: 'View Timelapse',
  309. icon: <Film className="w-4 h-4" />,
  310. onClick: () => setShowTimelapse(true),
  311. disabled: !archive.timelapse_path,
  312. },
  313. {
  314. label: 'Scan for Timelapse',
  315. icon: <ScanSearch className="w-4 h-4" />,
  316. onClick: () => timelapseScanMutation.mutate(),
  317. disabled: !archive.printer_id || !!archive.timelapse_path || timelapseScanMutation.isPending,
  318. },
  319. { label: '', divider: true, onClick: () => {} },
  320. {
  321. label: archive.source_3mf_path ? 'Download Source 3MF' : 'Upload Source 3MF',
  322. icon: <FileCode className="w-4 h-4" />,
  323. onClick: () => {
  324. if (archive.source_3mf_path) {
  325. const link = document.createElement('a');
  326. link.href = api.getSource3mfDownloadUrl(archive.id);
  327. link.download = `${archive.print_name || archive.filename}_source.3mf`;
  328. link.click();
  329. } else {
  330. source3mfInputRef.current?.click();
  331. }
  332. },
  333. },
  334. ...(archive.source_3mf_path ? [{
  335. label: 'Replace Source 3MF',
  336. icon: <Upload className="w-4 h-4" />,
  337. onClick: () => source3mfInputRef.current?.click(),
  338. },
  339. {
  340. label: 'Remove Source 3MF',
  341. icon: <Trash2 className="w-4 h-4" />,
  342. onClick: () => setShowDeleteSource3mfConfirm(true),
  343. danger: true,
  344. }] : []),
  345. {
  346. label: archive.f3d_path ? 'Replace F3D' : 'Upload F3D',
  347. icon: <Box className="w-4 h-4" />,
  348. onClick: () => f3dInputRef.current?.click(),
  349. },
  350. ...(archive.f3d_path ? [{
  351. label: 'Download F3D',
  352. icon: <Download className="w-4 h-4" />,
  353. onClick: () => {
  354. const link = document.createElement('a');
  355. link.href = api.getF3dDownloadUrl(archive.id);
  356. link.download = `${archive.print_name || archive.filename}.f3d`;
  357. link.click();
  358. },
  359. },
  360. {
  361. label: 'Remove F3D',
  362. icon: <Trash2 className="w-4 h-4" />,
  363. onClick: () => setShowDeleteF3dConfirm(true),
  364. danger: true,
  365. }] : []),
  366. { label: '', divider: true, onClick: () => {} },
  367. {
  368. label: 'Download',
  369. icon: <Download className="w-4 h-4" />,
  370. onClick: () => {
  371. const link = document.createElement('a');
  372. link.href = api.getArchiveDownload(archive.id);
  373. link.download = `${archive.print_name || archive.filename}.3mf`;
  374. link.click();
  375. },
  376. },
  377. {
  378. label: 'Copy Download Link',
  379. icon: <Copy className="w-4 h-4" />,
  380. onClick: () => {
  381. const url = `${window.location.origin}${api.getArchiveDownload(archive.id)}`;
  382. navigator.clipboard.writeText(url).then(() => {
  383. showToast('Link copied to clipboard');
  384. }).catch(() => {
  385. showToast('Failed to copy link', 'error');
  386. });
  387. },
  388. },
  389. {
  390. label: 'QR Code',
  391. icon: <QrCode className="w-4 h-4" />,
  392. onClick: () => setShowQRCode(true),
  393. },
  394. {
  395. label: `View Photos${archive.photos?.length ? ` (${archive.photos.length})` : ''}`,
  396. icon: <Camera className="w-4 h-4" />,
  397. onClick: () => setShowPhotos(true),
  398. disabled: !archive.photos?.length,
  399. },
  400. {
  401. label: 'Project Page',
  402. icon: <FileText className="w-4 h-4" />,
  403. onClick: () => setShowProjectPage(true),
  404. },
  405. { label: '', divider: true, onClick: () => {} },
  406. {
  407. label: archive.is_favorite ? 'Remove from Favorites' : 'Add to Favorites',
  408. icon: <Star className={`w-4 h-4 ${archive.is_favorite ? 'fill-yellow-400 text-yellow-400' : ''}`} />,
  409. onClick: () => favoriteMutation.mutate(),
  410. },
  411. {
  412. label: 'Edit',
  413. icon: <Pencil className="w-4 h-4" />,
  414. onClick: () => setShowEdit(true),
  415. },
  416. ...(archive.project_id && archive.project_name ? [{
  417. label: `Go to Project: ${archive.project_name}`,
  418. icon: <FolderKanban className="w-4 h-4 text-bambu-green" />,
  419. onClick: () => window.location.href = '/projects',
  420. }] : []),
  421. {
  422. label: 'Add to Project',
  423. icon: <FolderKanban className="w-4 h-4" />,
  424. onClick: () => {},
  425. submenu: (() => {
  426. const items: ContextMenuItem[] = [];
  427. // Add "Remove from Project" if archive is in a project
  428. if (archive.project_id) {
  429. items.push({
  430. label: 'Remove from Project',
  431. icon: <X className="w-4 h-4" />,
  432. onClick: () => assignProjectMutation.mutate(null),
  433. });
  434. }
  435. // Add project options
  436. if (!projects) {
  437. items.push({
  438. label: 'Loading...',
  439. icon: <Loader2 className="w-4 h-4 animate-spin" />,
  440. onClick: () => {},
  441. disabled: true,
  442. });
  443. } else {
  444. const activeProjects = projects.filter(p => p.status === 'active');
  445. if (activeProjects.length === 0) {
  446. items.push({
  447. label: 'No projects available',
  448. icon: <FolderKanban className="w-4 h-4 opacity-50" />,
  449. onClick: () => {},
  450. disabled: true,
  451. });
  452. } else {
  453. activeProjects.forEach(p => {
  454. items.push({
  455. label: p.name,
  456. icon: <div className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: p.color || '#888' }} />,
  457. onClick: () => assignProjectMutation.mutate(p.id),
  458. disabled: archive.project_id === p.id,
  459. });
  460. });
  461. }
  462. }
  463. return items;
  464. })(),
  465. },
  466. {
  467. label: isSelected ? 'Deselect' : 'Select',
  468. icon: isSelected ? <CheckSquare className="w-4 h-4" /> : <Square className="w-4 h-4" />,
  469. onClick: () => onSelect(archive.id),
  470. },
  471. { label: '', divider: true, onClick: () => {} },
  472. {
  473. label: 'Delete',
  474. icon: <Trash2 className="w-4 h-4" />,
  475. onClick: () => setShowDeleteConfirm(true),
  476. danger: true,
  477. },
  478. ];
  479. return (
  480. <Card
  481. data-archive-id={archive.id}
  482. className={`relative flex flex-col group ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode ? 'cursor-pointer' : ''}`}
  483. style={isHighlighted ? { outline: '4px solid #facc15', outlineOffset: '2px' } : undefined}
  484. onContextMenu={handleContextMenu}
  485. onClick={selectionMode ? () => onSelect(archive.id) : undefined}
  486. >
  487. {/* Selection checkbox */}
  488. {selectionMode && (
  489. <button
  490. className="absolute top-2 left-2 z-10 p-1 rounded bg-black/50 hover:bg-black/70 transition-colors"
  491. onClick={(e) => { e.stopPropagation(); onSelect(archive.id); }}
  492. >
  493. {isSelected ? (
  494. <CheckSquare className="w-5 h-5 text-bambu-green" />
  495. ) : (
  496. <Square className="w-5 h-5 text-white" />
  497. )}
  498. </button>
  499. )}
  500. {/* Thumbnail with plate navigation */}
  501. <div
  502. className="aspect-video bg-bambu-dark relative flex-shrink-0 overflow-hidden rounded-t-xl"
  503. onMouseEnter={() => setShowPlateNav(true)}
  504. onMouseLeave={() => setShowPlateNav(false)}
  505. >
  506. {archive.thumbnail_path ? (
  507. <img
  508. src={
  509. currentPlateIndex !== null && plates.length > 0
  510. ? api.getArchivePlateThumbnail(archive.id, plates[displayPlateIndex]?.index ?? 0)
  511. : api.getArchiveThumbnail(archive.id)
  512. }
  513. alt={archive.print_name || archive.filename}
  514. className="w-full h-full object-cover"
  515. />
  516. ) : (
  517. <div className="w-full h-full flex items-center justify-center">
  518. <Image className="w-12 h-12 text-bambu-dark-tertiary" />
  519. </div>
  520. )}
  521. {/* Plate navigation - only show for multi-plate archives */}
  522. {isMultiPlate && plates.length > 1 && (
  523. <>
  524. {/* Left arrow */}
  525. <button
  526. className={`absolute left-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${
  527. isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
  528. }`}
  529. onClick={(e) => {
  530. e.stopPropagation();
  531. setCurrentPlateIndex((prev) => {
  532. const current = prev ?? 0;
  533. return current > 0 ? current - 1 : plates.length - 1;
  534. });
  535. }}
  536. title="Previous plate"
  537. >
  538. <ChevronLeft className="w-4 h-4 text-white" />
  539. </button>
  540. {/* Right arrow */}
  541. <button
  542. className={`absolute right-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${
  543. isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
  544. }`}
  545. onClick={(e) => {
  546. e.stopPropagation();
  547. setCurrentPlateIndex((prev) => {
  548. const current = prev ?? 0;
  549. return current < plates.length - 1 ? current + 1 : 0;
  550. });
  551. }}
  552. title="Next plate"
  553. >
  554. <ChevronRight className="w-4 h-4 text-white" />
  555. </button>
  556. {/* Dots indicator */}
  557. <div
  558. className={`absolute bottom-1 left-1/2 -translate-x-1/2 flex gap-1 px-2 py-1 rounded-full bg-black/50 transition-all ${
  559. isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
  560. }`}
  561. >
  562. {plates.map((plate, idx) => (
  563. <button
  564. key={plate.index}
  565. className={`w-2 h-2 rounded-full transition-colors ${
  566. idx === displayPlateIndex ? 'bg-bambu-green' : 'bg-white/50 hover:bg-white/80'
  567. }`}
  568. onClick={(e) => {
  569. e.stopPropagation();
  570. setCurrentPlateIndex(idx);
  571. }}
  572. title={plate.name || `Plate ${plate.index}`}
  573. />
  574. ))}
  575. </div>
  576. </>
  577. )}
  578. {/* Context menu button - visible on mobile, shows on hover for desktop */}
  579. <button
  580. className={`absolute top-2 left-2 p-1.5 rounded bg-black/50 hover:bg-black/70 transition-all ${
  581. isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
  582. } ${selectionMode ? 'left-10' : ''}`}
  583. onClick={(e) => {
  584. e.stopPropagation();
  585. const rect = e.currentTarget.getBoundingClientRect();
  586. setContextMenu({ x: rect.left, y: rect.bottom + 4 });
  587. }}
  588. title="Right-click for more options"
  589. >
  590. <MoreVertical className="w-5 h-5 text-white" />
  591. </button>
  592. {/* Favorite star */}
  593. <button
  594. className="absolute top-2 right-2 p-1 rounded bg-black/50 hover:bg-black/70 transition-colors"
  595. onClick={(e) => {
  596. e.stopPropagation();
  597. favoriteMutation.mutate();
  598. }}
  599. title={archive.is_favorite ? 'Remove from favorites' : 'Add to favorites'}
  600. >
  601. <Star
  602. className={`w-5 h-5 ${archive.is_favorite ? 'text-yellow-400 fill-yellow-400' : 'text-white'}`}
  603. />
  604. </button>
  605. {(archive.status === 'failed' || archive.status === 'aborted') && (
  606. <div className="absolute top-2 left-12 px-2 py-1 rounded text-xs bg-status-error/80 text-white">
  607. {archive.status === 'aborted' ? 'cancelled' : 'failed'}
  608. </div>
  609. )}
  610. {/* Duplicate badge */}
  611. {archive.duplicate_count > 0 && (
  612. <div
  613. className="absolute top-2 right-2 px-2 py-1 rounded text-xs bg-purple-500/80 text-white flex items-center gap-1"
  614. title="This model has been printed before"
  615. >
  616. <Copy className="w-3 h-3" />
  617. duplicate
  618. </div>
  619. )}
  620. {/* Source 3MF badge */}
  621. {archive.source_3mf_path && (
  622. <button
  623. className="absolute bottom-2 left-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors"
  624. onClick={(e) => {
  625. e.stopPropagation();
  626. // Open source 3MF in Bambu Studio - use filename in URL for slicer compatibility
  627. const sourceName = (archive.print_name || archive.filename || 'source').replace(/\.gcode\.3mf$/i, '') + '_source';
  628. const downloadUrl = `${window.location.origin}${api.getSource3mfForSlicer(archive.id, sourceName)}`;
  629. openInSlicer(downloadUrl);
  630. }}
  631. title="Open source 3MF in Bambu Studio (right-click for more options)"
  632. >
  633. <FileCode className="w-4 h-4 text-orange-400" />
  634. </button>
  635. )}
  636. {/* F3D badge */}
  637. {archive.f3d_path && (
  638. <button
  639. className={`absolute bottom-2 ${archive.source_3mf_path ? 'left-12' : 'left-2'} p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors`}
  640. onClick={(e) => {
  641. e.stopPropagation();
  642. // Download F3D file
  643. window.location.href = api.getF3dDownloadUrl(archive.id);
  644. }}
  645. title="Download Fusion 360 design file"
  646. >
  647. <Box className="w-4 h-4 text-cyan-400" />
  648. </button>
  649. )}
  650. {/* Timelapse badge */}
  651. {archive.timelapse_path && (
  652. <button
  653. className="absolute bottom-2 right-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors"
  654. onClick={(e) => {
  655. e.stopPropagation();
  656. setShowTimelapse(true);
  657. }}
  658. title="View timelapse"
  659. >
  660. <Film className="w-4 h-4 text-bambu-green" />
  661. </button>
  662. )}
  663. {/* Photos badge */}
  664. {archive.photos && archive.photos.length > 0 && (
  665. <button
  666. className={`absolute bottom-2 ${archive.timelapse_path ? 'right-12' : 'right-2'} p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors`}
  667. onClick={(e) => {
  668. e.stopPropagation();
  669. setShowPhotos(true);
  670. }}
  671. title={`View ${archive.photos.length} photo${archive.photos.length > 1 ? 's' : ''}`}
  672. >
  673. <Camera className="w-4 h-4 text-blue-400" />
  674. {archive.photos.length > 1 && (
  675. <span className="absolute -top-1 -right-1 w-4 h-4 bg-blue-500 rounded-full text-[10px] text-white flex items-center justify-center">
  676. {archive.photos.length}
  677. </span>
  678. )}
  679. </button>
  680. )}
  681. {/* Linked folder badge */}
  682. {linkedFolders && linkedFolders.length > 0 && (
  683. <Link
  684. to={`/files?folder=${linkedFolders[0].id}`}
  685. className="absolute bottom-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors"
  686. onClick={(e) => e.stopPropagation()}
  687. title={`Open folder: ${linkedFolders[0].name}`}
  688. style={{ left: archive.source_3mf_path ? (archive.f3d_path ? '5.5rem' : '3rem') : (archive.f3d_path ? '3rem' : '0.5rem') }}
  689. >
  690. <FolderOpen className="w-4 h-4 text-yellow-400" />
  691. </Link>
  692. )}
  693. </div>
  694. <CardContent className="p-4 flex-1 flex flex-col">
  695. {/* Title */}
  696. <h3 className="font-medium text-white mb-1 truncate">
  697. {archive.print_name || archive.filename}
  698. </h3>
  699. <div className="flex items-center gap-2 mb-3 flex-wrap">
  700. <p className="text-xs text-bambu-gray">{printerName}</p>
  701. {/* File type badge */}
  702. <span
  703. className={`text-[10px] px-1.5 py-0.5 rounded font-medium ${
  704. isSlicedFile(archive.filename)
  705. ? 'bg-bambu-green/20 text-bambu-green'
  706. : 'bg-orange-500/20 text-orange-400'
  707. }`}
  708. title={
  709. isSlicedFile(archive.filename)
  710. ? 'Sliced file - ready to print'
  711. : 'Source file only - no AMS mapping available'
  712. }
  713. >
  714. {isSlicedFile(archive.filename) ? 'GCODE' : 'SOURCE'}
  715. </span>
  716. {archive.project_name && (
  717. <span
  718. className="text-xs px-1.5 py-0.5 rounded-full truncate max-w-[120px]"
  719. style={{
  720. backgroundColor: `${projects?.find(p => p.id === archive.project_id)?.color || '#6b7280'}20`,
  721. color: projects?.find(p => p.id === archive.project_id)?.color || '#6b7280'
  722. }}
  723. title={`Project: ${archive.project_name}`}
  724. >
  725. {archive.project_name}
  726. </span>
  727. )}
  728. </div>
  729. {/* Stats */}
  730. <div className="grid grid-cols-2 gap-2 text-xs mb-4 min-h-[48px]">
  731. {(archive.print_time_seconds || archive.actual_time_seconds) && (
  732. <div className="flex items-center gap-1.5 text-bambu-gray" title={
  733. archive.time_accuracy
  734. ? `Estimated: ${formatDuration(archive.print_time_seconds || 0)}\nActual: ${formatDuration(archive.actual_time_seconds || 0)}\nAccuracy: ${archive.time_accuracy.toFixed(0)}%`
  735. : archive.actual_time_seconds
  736. ? `Actual: ${formatDuration(archive.actual_time_seconds)}`
  737. : `Estimated: ${formatDuration(archive.print_time_seconds || 0)}`
  738. }>
  739. <Clock className="w-3 h-3" />
  740. {formatDuration(archive.actual_time_seconds || archive.print_time_seconds || 0)}
  741. {archive.time_accuracy && (
  742. <span className={`text-[10px] px-1 rounded ${
  743. archive.time_accuracy >= 95 && archive.time_accuracy <= 105
  744. ? 'bg-bambu-green/20 text-bambu-green'
  745. : archive.time_accuracy > 105
  746. ? 'bg-blue-500/20 text-blue-400'
  747. : 'bg-orange-500/20 text-orange-400'
  748. }`}>
  749. {archive.time_accuracy > 100 ? '+' : ''}{(archive.time_accuracy - 100).toFixed(0)}%
  750. </span>
  751. )}
  752. </div>
  753. )}
  754. {archive.filament_used_grams && (
  755. <div className="flex items-center gap-1.5 text-bambu-gray">
  756. <Package className="w-3 h-3" />
  757. {archive.filament_used_grams.toFixed(1)}g
  758. </div>
  759. )}
  760. {(archive.layer_height || archive.total_layers) && (
  761. <div className="flex items-center gap-1.5 text-bambu-gray">
  762. <Layers className="w-3 h-3" />
  763. {archive.total_layers && <span>{archive.total_layers} layers</span>}
  764. {archive.total_layers && archive.layer_height && <span className="text-bambu-gray/50">·</span>}
  765. {archive.layer_height && <span>{archive.layer_height}mm</span>}
  766. </div>
  767. )}
  768. {archive.object_count != null && archive.object_count > 0 && (
  769. <div className="flex items-center gap-1.5 text-bambu-gray" title={`${archive.object_count} object${archive.object_count > 1 ? 's' : ''}`}>
  770. <Box className="w-3 h-3" />
  771. {archive.object_count} object{archive.object_count > 1 ? 's' : ''}
  772. </div>
  773. )}
  774. {archive.sliced_for_model && (
  775. <div className="flex items-center gap-1.5 text-bambu-gray" title={`Sliced for ${archive.sliced_for_model}`}>
  776. <Printer className="w-3 h-3" />
  777. {archive.sliced_for_model}
  778. </div>
  779. )}
  780. {archive.filament_type && (
  781. <div className="flex items-center gap-1.5 col-span-2">
  782. <span className="text-bambu-gray text-xs">{archive.filament_type}</span>
  783. {archive.filament_color && (
  784. <div className="flex items-center gap-0.5 flex-wrap">
  785. {archive.filament_color.split(',').map((color, i) => (
  786. <div
  787. key={i}
  788. className="w-3 h-3 rounded-full border border-white/20"
  789. style={{ backgroundColor: color }}
  790. title={color}
  791. />
  792. ))}
  793. </div>
  794. )}
  795. </div>
  796. )}
  797. </div>
  798. {/* Tags & Notes */}
  799. {(archive.tags || archive.notes) && (
  800. <div className="flex flex-wrap items-center gap-1.5 mb-3">
  801. {archive.notes && (
  802. <div
  803. className="flex items-center gap-1 px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded text-xs"
  804. title={archive.notes}
  805. >
  806. <StickyNote className="w-3 h-3" />
  807. </div>
  808. )}
  809. {archive.tags?.split(',').map((tag, i) => (
  810. <span
  811. key={i}
  812. className="px-1.5 py-0.5 bg-bambu-dark-tertiary text-bambu-gray-light rounded text-xs"
  813. >
  814. {tag.trim()}
  815. </span>
  816. ))}
  817. </div>
  818. )}
  819. {/* Spacer to push content to bottom */}
  820. <div className="flex-1" />
  821. {/* Date & Size */}
  822. <div className="flex items-center justify-between text-xs text-bambu-gray border-t border-bambu-dark-tertiary pt-3">
  823. <span>{formatDateTime(archive.created_at, timeFormat)}</span>
  824. <span>{formatFileSize(archive.file_size)}</span>
  825. </div>
  826. {/* Actions */}
  827. <div className="flex gap-1 mt-3">
  828. {isSlicedFile(archive.filename) ? (
  829. // Sliced file - can print directly
  830. <>
  831. <Button
  832. variant="primary"
  833. size="sm"
  834. className="flex-1 min-w-0"
  835. onClick={() => setShowReprint(true)}
  836. >
  837. <Printer className="w-3 h-3 flex-shrink-0" />
  838. <span className="hidden sm:inline">Reprint</span>
  839. </Button>
  840. <Button
  841. variant="secondary"
  842. size="sm"
  843. className="min-w-0 p-1 sm:p-1.5"
  844. onClick={() => {
  845. const filename = archive.print_name || archive.filename || 'model';
  846. const downloadUrl = `${window.location.origin}${api.getArchiveForSlicer(archive.id, filename)}`;
  847. openInSlicer(downloadUrl);
  848. }}
  849. title="Open in Bambu Studio"
  850. >
  851. <ExternalLink className="w-3 h-3 sm:w-4 sm:h-4" />
  852. </Button>
  853. </>
  854. ) : (
  855. // Source file only - must open in slicer first
  856. <Button
  857. variant="primary"
  858. size="sm"
  859. className="flex-1 min-w-0"
  860. onClick={() => {
  861. const filename = archive.print_name || archive.filename || 'model';
  862. const downloadUrl = `${window.location.origin}${api.getArchiveForSlicer(archive.id, filename)}`;
  863. openInSlicer(downloadUrl);
  864. }}
  865. title="Open in Bambu Studio to slice"
  866. >
  867. <ExternalLink className="w-3 h-3 flex-shrink-0" />
  868. <span className="hidden sm:inline">Slice</span>
  869. </Button>
  870. )}
  871. <Button
  872. variant="secondary"
  873. size="sm"
  874. className="min-w-0 p-1 sm:p-1.5"
  875. onClick={() => {
  876. const url = archive.external_url || archive.makerworld_url;
  877. if (url) window.open(url, '_blank');
  878. }}
  879. disabled={!archive.external_url && !archive.makerworld_url}
  880. title={
  881. archive.external_url
  882. ? 'External Link'
  883. : archive.makerworld_url
  884. ? `MakerWorld: ${archive.designer || 'View project'}`
  885. : 'No external link'
  886. }
  887. >
  888. <Globe className={`w-3 h-3 sm:w-4 sm:h-4 ${!archive.external_url && !archive.makerworld_url ? 'opacity-20' : ''}`} />
  889. </Button>
  890. <Button
  891. variant="secondary"
  892. size="sm"
  893. className="min-w-0 p-1 sm:p-1.5"
  894. onClick={() => setShowViewer(true)}
  895. title="3D Preview"
  896. >
  897. <Box className="w-3 h-3 sm:w-4 sm:h-4" />
  898. </Button>
  899. <Button
  900. variant="secondary"
  901. size="sm"
  902. className="min-w-0 p-1 sm:p-1.5"
  903. onClick={() => {
  904. const link = document.createElement('a');
  905. link.href = api.getArchiveDownload(archive.id);
  906. link.download = `${archive.print_name || archive.filename}.3mf`;
  907. link.click();
  908. }}
  909. title="Download"
  910. >
  911. <Download className="w-3 h-3 sm:w-4 sm:h-4" />
  912. </Button>
  913. <Button
  914. variant="ghost"
  915. size="sm"
  916. className="min-w-0 p-1 sm:p-1.5"
  917. onClick={() => setShowEdit(true)}
  918. title="Edit"
  919. >
  920. <Pencil className="w-3 h-3 sm:w-4 sm:h-4" />
  921. </Button>
  922. <Button
  923. variant="ghost"
  924. size="sm"
  925. className="min-w-0 p-1 sm:p-1.5"
  926. onClick={() => setShowDeleteConfirm(true)}
  927. title="Delete"
  928. >
  929. <Trash2 className="w-3 h-3 sm:w-4 sm:h-4 text-red-400" />
  930. </Button>
  931. </div>
  932. </CardContent>
  933. {/* Edit Modal */}
  934. {showEdit && (
  935. <EditArchiveModal
  936. archive={archive}
  937. onClose={() => setShowEdit(false)}
  938. />
  939. )}
  940. {/* 3D Viewer Modal */}
  941. {showViewer && (
  942. <ModelViewerModal
  943. archiveId={archive.id}
  944. title={archive.print_name || archive.filename}
  945. onClose={() => setShowViewer(false)}
  946. />
  947. )}
  948. {/* Reprint Modal */}
  949. {showReprint && (
  950. <PrintModal
  951. mode="reprint"
  952. archiveId={archive.id}
  953. archiveName={archive.print_name || archive.filename}
  954. onClose={() => setShowReprint(false)}
  955. />
  956. )}
  957. {/* Delete Confirmation */}
  958. {showDeleteConfirm && (
  959. <ConfirmModal
  960. title="Delete Archive"
  961. message={`Are you sure you want to delete "${archive.print_name || archive.filename}"? This action cannot be undone.`}
  962. confirmText="Delete"
  963. variant="danger"
  964. onConfirm={() => {
  965. deleteMutation.mutate();
  966. setShowDeleteConfirm(false);
  967. }}
  968. onCancel={() => setShowDeleteConfirm(false)}
  969. />
  970. )}
  971. {/* Delete Source 3MF Confirmation */}
  972. {showDeleteSource3mfConfirm && (
  973. <ConfirmModal
  974. title="Remove Source 3MF"
  975. message={`Are you sure you want to remove the source 3MF file from "${archive.print_name || archive.filename}"? This will delete the original slicer project file.`}
  976. confirmText="Remove"
  977. variant="danger"
  978. onConfirm={() => {
  979. source3mfDeleteMutation.mutate();
  980. setShowDeleteSource3mfConfirm(false);
  981. }}
  982. onCancel={() => setShowDeleteSource3mfConfirm(false)}
  983. />
  984. )}
  985. {/* Delete F3D Confirmation */}
  986. {showDeleteF3dConfirm && (
  987. <ConfirmModal
  988. title="Remove F3D"
  989. message={`Are you sure you want to remove the Fusion 360 design file from "${archive.print_name || archive.filename}"?`}
  990. confirmText="Remove"
  991. variant="danger"
  992. onConfirm={() => {
  993. f3dDeleteMutation.mutate();
  994. setShowDeleteF3dConfirm(false);
  995. }}
  996. onCancel={() => setShowDeleteF3dConfirm(false)}
  997. />
  998. )}
  999. {/* Context Menu */}
  1000. {contextMenu && (
  1001. <ContextMenu
  1002. x={contextMenu.x}
  1003. y={contextMenu.y}
  1004. items={contextMenuItems}
  1005. onClose={() => setContextMenu(null)}
  1006. />
  1007. )}
  1008. {/* Timelapse Viewer Modal */}
  1009. {showTimelapse && archive.timelapse_path && (
  1010. <TimelapseViewer
  1011. src={api.getArchiveTimelapse(archive.id)}
  1012. title={`${archive.print_name || archive.filename} - Timelapse`}
  1013. downloadFilename={`${archive.print_name || archive.filename}_timelapse.mp4`}
  1014. archiveId={archive.id}
  1015. onClose={() => setShowTimelapse(false)}
  1016. onEdit={() => {
  1017. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1018. setShowTimelapse(false); // Close viewer to reload fresh video
  1019. }}
  1020. />
  1021. )}
  1022. {/* Timelapse Selection Modal */}
  1023. {showTimelapseSelect && availableTimelapses.length > 0 && (
  1024. <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4">
  1025. <div className="bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col">
  1026. <div className="flex items-center justify-between p-4 border-b border-gray-700">
  1027. <div>
  1028. <h3 className="text-lg font-semibold text-white">Select Timelapse</h3>
  1029. <p className="text-sm text-gray-400 mt-1">
  1030. No auto-match found. Select the timelapse for this print:
  1031. </p>
  1032. </div>
  1033. <button
  1034. onClick={() => {
  1035. setShowTimelapseSelect(false);
  1036. setAvailableTimelapses([]);
  1037. }}
  1038. className="text-gray-400 hover:text-white p-1"
  1039. >
  1040. <X className="w-5 h-5" />
  1041. </button>
  1042. </div>
  1043. <div className="overflow-y-auto flex-1 p-2">
  1044. {availableTimelapses.map((file) => (
  1045. <button
  1046. key={file.name}
  1047. onClick={() => timelapseSelectMutation.mutate(file.name)}
  1048. disabled={timelapseSelectMutation.isPending}
  1049. className="w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors flex items-center gap-3 disabled:opacity-50"
  1050. >
  1051. <Film className="w-8 h-8 text-bambu-green flex-shrink-0" />
  1052. <div className="flex-1 min-w-0">
  1053. <p className="text-white font-medium truncate">{file.name}</p>
  1054. <p className="text-sm text-gray-400">
  1055. {formatFileSize(file.size)}
  1056. {file.mtime && ` • ${formatDateTime(file.mtime, timeFormat)}`}
  1057. </p>
  1058. </div>
  1059. </button>
  1060. ))}
  1061. </div>
  1062. <div className="p-4 border-t border-gray-700">
  1063. <Button
  1064. variant="secondary"
  1065. onClick={() => {
  1066. setShowTimelapseSelect(false);
  1067. setAvailableTimelapses([]);
  1068. }}
  1069. className="w-full"
  1070. >
  1071. Cancel
  1072. </Button>
  1073. </div>
  1074. </div>
  1075. </div>
  1076. )}
  1077. {/* QR Code Modal */}
  1078. {showQRCode && (
  1079. <QRCodeModal
  1080. archiveId={archive.id}
  1081. archiveName={archive.print_name || archive.filename}
  1082. onClose={() => setShowQRCode(false)}
  1083. />
  1084. )}
  1085. {/* Photo Gallery Modal */}
  1086. {showPhotos && archive.photos && archive.photos.length > 0 && (
  1087. <PhotoGalleryModal
  1088. archiveId={archive.id}
  1089. archiveName={archive.print_name || archive.filename}
  1090. photos={archive.photos}
  1091. onClose={() => setShowPhotos(false)}
  1092. onDelete={async (filename) => {
  1093. try {
  1094. await api.deleteArchivePhoto(archive.id, filename);
  1095. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1096. showToast('Photo deleted');
  1097. } catch {
  1098. showToast('Failed to delete photo', 'error');
  1099. }
  1100. }}
  1101. />
  1102. )}
  1103. {/* Project Page Modal */}
  1104. {showProjectPage && (
  1105. <ProjectPageModal
  1106. archiveId={archive.id}
  1107. archiveName={archive.print_name || archive.filename}
  1108. onClose={() => setShowProjectPage(false)}
  1109. />
  1110. )}
  1111. {showSchedule && (
  1112. <PrintModal
  1113. mode="add-to-queue"
  1114. archiveId={archive.id}
  1115. archiveName={archive.print_name || archive.filename}
  1116. onClose={() => setShowSchedule(false)}
  1117. />
  1118. )}
  1119. {/* Hidden file input for source 3MF upload */}
  1120. <input
  1121. ref={source3mfInputRef}
  1122. type="file"
  1123. accept=".3mf"
  1124. className="hidden"
  1125. onChange={(e) => {
  1126. const file = e.target.files?.[0];
  1127. if (file) {
  1128. source3mfUploadMutation.mutate(file);
  1129. }
  1130. e.target.value = '';
  1131. }}
  1132. />
  1133. {/* Hidden file input for F3D upload */}
  1134. <input
  1135. ref={f3dInputRef}
  1136. type="file"
  1137. accept=".f3d"
  1138. className="hidden"
  1139. onChange={(e) => {
  1140. const file = e.target.files?.[0];
  1141. if (file) {
  1142. f3dUploadMutation.mutate(file);
  1143. }
  1144. e.target.value = '';
  1145. }}
  1146. />
  1147. </Card>
  1148. );
  1149. }
  1150. function ArchiveListRow({
  1151. archive,
  1152. printerName,
  1153. isSelected,
  1154. onSelect,
  1155. selectionMode,
  1156. projects,
  1157. isHighlighted,
  1158. }: {
  1159. archive: Archive;
  1160. printerName: string;
  1161. isSelected: boolean;
  1162. onSelect: (id: number) => void;
  1163. selectionMode: boolean;
  1164. projects: ProjectListItem[] | undefined;
  1165. isHighlighted?: boolean;
  1166. }) {
  1167. const queryClient = useQueryClient();
  1168. const { showToast } = useToast();
  1169. const [showEdit, setShowEdit] = useState(false);
  1170. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1171. const [showReprint, setShowReprint] = useState(false);
  1172. const [showSchedule, setShowSchedule] = useState(false);
  1173. const [showViewer, setShowViewer] = useState(false);
  1174. const [showTimelapse, setShowTimelapse] = useState(false);
  1175. const [showTimelapseSelect, setShowTimelapseSelect] = useState(false);
  1176. const [availableTimelapses, setAvailableTimelapses] = useState<Array<{ name: string; path: string; size: number; mtime: string | null }>>([]);
  1177. const [showQRCode, setShowQRCode] = useState(false);
  1178. const [showPhotos, setShowPhotos] = useState(false);
  1179. const [showProjectPage, setShowProjectPage] = useState(false);
  1180. const [showDeleteSource3mfConfirm, setShowDeleteSource3mfConfirm] = useState(false);
  1181. const [showDeleteF3dConfirm, setShowDeleteF3dConfirm] = useState(false);
  1182. const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
  1183. const source3mfInputRef = useRef<HTMLInputElement>(null);
  1184. const f3dInputRef = useRef<HTMLInputElement>(null);
  1185. const source3mfUploadMutation = useMutation({
  1186. mutationFn: (file: File) => api.uploadSource3mf(archive.id, file),
  1187. onSuccess: (data) => {
  1188. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1189. showToast(`Source 3MF attached: ${data.filename}`);
  1190. },
  1191. onError: (error: Error) => {
  1192. showToast(error.message || 'Failed to upload source 3MF', 'error');
  1193. },
  1194. });
  1195. const source3mfDeleteMutation = useMutation({
  1196. mutationFn: () => api.deleteSource3mf(archive.id),
  1197. onSuccess: () => {
  1198. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1199. showToast('Source 3MF removed');
  1200. },
  1201. onError: (error: Error) => {
  1202. showToast(error.message || 'Failed to remove source 3MF', 'error');
  1203. },
  1204. });
  1205. const f3dUploadMutation = useMutation({
  1206. mutationFn: (file: File) => api.uploadF3d(archive.id, file),
  1207. onSuccess: (data) => {
  1208. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1209. showToast(`F3D attached: ${data.filename}`);
  1210. },
  1211. onError: (error: Error) => {
  1212. showToast(error.message || 'Failed to upload F3D', 'error');
  1213. },
  1214. });
  1215. const f3dDeleteMutation = useMutation({
  1216. mutationFn: () => api.deleteF3d(archive.id),
  1217. onSuccess: () => {
  1218. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1219. showToast('F3D removed');
  1220. },
  1221. onError: (error: Error) => {
  1222. showToast(error.message || 'Failed to remove F3D', 'error');
  1223. },
  1224. });
  1225. const timelapseScanMutation = useMutation({
  1226. mutationFn: () => api.scanArchiveTimelapse(archive.id),
  1227. onSuccess: (data) => {
  1228. if (data.status === 'attached') {
  1229. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1230. showToast(`Timelapse attached: ${data.filename}`);
  1231. } else if (data.status === 'exists') {
  1232. showToast('Timelapse already attached');
  1233. } else if (data.status === 'not_found' && data.available_files && data.available_files.length > 0) {
  1234. setAvailableTimelapses(data.available_files);
  1235. setShowTimelapseSelect(true);
  1236. } else {
  1237. showToast(data.message || 'No matching timelapse found', 'warning');
  1238. }
  1239. },
  1240. onError: (error: Error) => {
  1241. showToast(error.message || 'Failed to scan for timelapse', 'error');
  1242. },
  1243. });
  1244. const timelapseSelectMutation = useMutation({
  1245. mutationFn: (filename: string) => api.selectArchiveTimelapse(archive.id, filename),
  1246. onSuccess: (data) => {
  1247. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1248. showToast(`Timelapse attached: ${data.filename}`);
  1249. setShowTimelapseSelect(false);
  1250. setAvailableTimelapses([]);
  1251. },
  1252. onError: (error: Error) => {
  1253. showToast(error.message || 'Failed to attach timelapse', 'error');
  1254. },
  1255. });
  1256. const deleteMutation = useMutation({
  1257. mutationFn: () => api.deleteArchive(archive.id),
  1258. onSuccess: () => {
  1259. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1260. showToast('Archive deleted');
  1261. },
  1262. onError: () => {
  1263. showToast('Failed to delete archive', 'error');
  1264. },
  1265. });
  1266. const favoriteMutation = useMutation({
  1267. mutationFn: () => api.toggleFavorite(archive.id),
  1268. onSuccess: (data) => {
  1269. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1270. showToast(data.is_favorite ? 'Added to favorites' : 'Removed from favorites');
  1271. },
  1272. });
  1273. // Query for linked folders
  1274. const { data: linkedFolders } = useQuery({
  1275. queryKey: ['archive-folders', archive.id],
  1276. queryFn: () => api.getLibraryFoldersByArchive(archive.id),
  1277. });
  1278. const assignProjectMutation = useMutation({
  1279. mutationFn: (projectId: number | null) => api.updateArchive(archive.id, { project_id: projectId }),
  1280. onSuccess: () => {
  1281. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1282. queryClient.invalidateQueries({ queryKey: ['projects'] });
  1283. showToast('Project updated');
  1284. },
  1285. onError: () => {
  1286. showToast('Failed to update project', 'error');
  1287. },
  1288. });
  1289. const handleContextMenu = (e: React.MouseEvent) => {
  1290. e.preventDefault();
  1291. setContextMenu({ x: e.clientX, y: e.clientY });
  1292. };
  1293. const isGcodeFile = isSlicedFile(archive.filename);
  1294. const contextMenuItems: ContextMenuItem[] = [
  1295. ...(isGcodeFile ? [
  1296. {
  1297. label: 'Print',
  1298. icon: <Printer className="w-4 h-4" />,
  1299. onClick: () => setShowReprint(true),
  1300. },
  1301. {
  1302. label: 'Schedule',
  1303. icon: <Calendar className="w-4 h-4" />,
  1304. onClick: () => setShowSchedule(true),
  1305. },
  1306. {
  1307. label: 'Open in Bambu Studio',
  1308. icon: <ExternalLink className="w-4 h-4" />,
  1309. onClick: () => {
  1310. const filename = archive.print_name || archive.filename || 'model';
  1311. const downloadUrl = `${window.location.origin}${api.getArchiveForSlicer(archive.id, filename)}`;
  1312. openInSlicer(downloadUrl);
  1313. },
  1314. },
  1315. ] : [
  1316. {
  1317. label: 'Slice',
  1318. icon: <ExternalLink className="w-4 h-4" />,
  1319. onClick: () => {
  1320. const filename = archive.print_name || archive.filename || 'model';
  1321. const downloadUrl = `${window.location.origin}${api.getArchiveForSlicer(archive.id, filename)}`;
  1322. openInSlicer(downloadUrl);
  1323. },
  1324. },
  1325. ]),
  1326. {
  1327. label: archive.external_url ? 'External Link' : 'View on MakerWorld',
  1328. icon: <Globe className="w-4 h-4" />,
  1329. onClick: () => {
  1330. const url = archive.external_url || archive.makerworld_url;
  1331. if (url) window.open(url, '_blank');
  1332. },
  1333. disabled: !archive.external_url && !archive.makerworld_url,
  1334. },
  1335. { label: '', divider: true, onClick: () => {} },
  1336. {
  1337. label: '3D Preview',
  1338. icon: <Box className="w-4 h-4" />,
  1339. onClick: () => setShowViewer(true),
  1340. },
  1341. {
  1342. label: 'View Timelapse',
  1343. icon: <Film className="w-4 h-4" />,
  1344. onClick: () => setShowTimelapse(true),
  1345. disabled: !archive.timelapse_path,
  1346. },
  1347. {
  1348. label: 'Scan for Timelapse',
  1349. icon: <ScanSearch className="w-4 h-4" />,
  1350. onClick: () => timelapseScanMutation.mutate(),
  1351. disabled: !archive.printer_id || !!archive.timelapse_path || timelapseScanMutation.isPending,
  1352. },
  1353. { label: '', divider: true, onClick: () => {} },
  1354. {
  1355. label: archive.source_3mf_path ? 'Download Source 3MF' : 'Upload Source 3MF',
  1356. icon: <FileCode className="w-4 h-4" />,
  1357. onClick: () => {
  1358. if (archive.source_3mf_path) {
  1359. const link = document.createElement('a');
  1360. link.href = api.getSource3mfDownloadUrl(archive.id);
  1361. link.download = `${archive.print_name || archive.filename}_source.3mf`;
  1362. link.click();
  1363. } else {
  1364. source3mfInputRef.current?.click();
  1365. }
  1366. },
  1367. },
  1368. ...(archive.source_3mf_path ? [{
  1369. label: 'Replace Source 3MF',
  1370. icon: <Upload className="w-4 h-4" />,
  1371. onClick: () => source3mfInputRef.current?.click(),
  1372. },
  1373. {
  1374. label: 'Remove Source 3MF',
  1375. icon: <Trash2 className="w-4 h-4" />,
  1376. onClick: () => setShowDeleteSource3mfConfirm(true),
  1377. danger: true,
  1378. }] : []),
  1379. {
  1380. label: archive.f3d_path ? 'Replace F3D' : 'Upload F3D',
  1381. icon: <Box className="w-4 h-4" />,
  1382. onClick: () => f3dInputRef.current?.click(),
  1383. },
  1384. ...(archive.f3d_path ? [{
  1385. label: 'Download F3D',
  1386. icon: <Download className="w-4 h-4" />,
  1387. onClick: () => {
  1388. const link = document.createElement('a');
  1389. link.href = api.getF3dDownloadUrl(archive.id);
  1390. link.download = `${archive.print_name || archive.filename}.f3d`;
  1391. link.click();
  1392. },
  1393. },
  1394. {
  1395. label: 'Remove F3D',
  1396. icon: <Trash2 className="w-4 h-4" />,
  1397. onClick: () => setShowDeleteF3dConfirm(true),
  1398. danger: true,
  1399. }] : []),
  1400. { label: '', divider: true, onClick: () => {} },
  1401. {
  1402. label: 'Download',
  1403. icon: <Download className="w-4 h-4" />,
  1404. onClick: () => {
  1405. const link = document.createElement('a');
  1406. link.href = api.getArchiveDownload(archive.id);
  1407. link.download = `${archive.print_name || archive.filename}.3mf`;
  1408. link.click();
  1409. },
  1410. },
  1411. {
  1412. label: 'Copy Download Link',
  1413. icon: <Copy className="w-4 h-4" />,
  1414. onClick: () => {
  1415. const url = `${window.location.origin}${api.getArchiveDownload(archive.id)}`;
  1416. navigator.clipboard.writeText(url).then(() => {
  1417. showToast('Link copied to clipboard');
  1418. }).catch(() => {
  1419. showToast('Failed to copy link', 'error');
  1420. });
  1421. },
  1422. },
  1423. {
  1424. label: 'QR Code',
  1425. icon: <QrCode className="w-4 h-4" />,
  1426. onClick: () => setShowQRCode(true),
  1427. },
  1428. {
  1429. label: `View Photos${archive.photos?.length ? ` (${archive.photos.length})` : ''}`,
  1430. icon: <Camera className="w-4 h-4" />,
  1431. onClick: () => setShowPhotos(true),
  1432. disabled: !archive.photos?.length,
  1433. },
  1434. {
  1435. label: 'Project Page',
  1436. icon: <FileText className="w-4 h-4" />,
  1437. onClick: () => setShowProjectPage(true),
  1438. },
  1439. { label: '', divider: true, onClick: () => {} },
  1440. {
  1441. label: archive.is_favorite ? 'Remove from Favorites' : 'Add to Favorites',
  1442. icon: <Star className={`w-4 h-4 ${archive.is_favorite ? 'fill-yellow-400 text-yellow-400' : ''}`} />,
  1443. onClick: () => favoriteMutation.mutate(),
  1444. },
  1445. {
  1446. label: 'Edit',
  1447. icon: <Pencil className="w-4 h-4" />,
  1448. onClick: () => setShowEdit(true),
  1449. },
  1450. ...(archive.project_id && archive.project_name ? [{
  1451. label: `Go to Project: ${archive.project_name}`,
  1452. icon: <FolderKanban className="w-4 h-4 text-bambu-green" />,
  1453. onClick: () => window.location.href = '/projects',
  1454. }] : []),
  1455. {
  1456. label: 'Add to Project',
  1457. icon: <FolderKanban className="w-4 h-4" />,
  1458. onClick: () => {},
  1459. submenu: (() => {
  1460. const items: ContextMenuItem[] = [];
  1461. if (archive.project_id) {
  1462. items.push({
  1463. label: 'Remove from Project',
  1464. icon: <X className="w-4 h-4" />,
  1465. onClick: () => assignProjectMutation.mutate(null),
  1466. });
  1467. }
  1468. if (!projects) {
  1469. items.push({
  1470. label: 'Loading...',
  1471. icon: <Loader2 className="w-4 h-4 animate-spin" />,
  1472. onClick: () => {},
  1473. disabled: true,
  1474. });
  1475. } else {
  1476. const activeProjects = projects.filter(p => p.status === 'active');
  1477. if (activeProjects.length === 0) {
  1478. items.push({
  1479. label: 'No projects available',
  1480. icon: <FolderKanban className="w-4 h-4 opacity-50" />,
  1481. onClick: () => {},
  1482. disabled: true,
  1483. });
  1484. } else {
  1485. activeProjects.forEach(p => {
  1486. items.push({
  1487. label: p.name,
  1488. icon: <div className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: p.color || '#888' }} />,
  1489. onClick: () => assignProjectMutation.mutate(p.id),
  1490. disabled: archive.project_id === p.id,
  1491. });
  1492. });
  1493. }
  1494. }
  1495. return items;
  1496. })(),
  1497. },
  1498. {
  1499. label: isSelected ? 'Deselect' : 'Select',
  1500. icon: isSelected ? <CheckSquare className="w-4 h-4" /> : <Square className="w-4 h-4" />,
  1501. onClick: () => onSelect(archive.id),
  1502. },
  1503. { label: '', divider: true, onClick: () => {} },
  1504. {
  1505. label: 'Delete',
  1506. icon: <Trash2 className="w-4 h-4" />,
  1507. onClick: () => setShowDeleteConfirm(true),
  1508. danger: true,
  1509. },
  1510. ];
  1511. return (
  1512. <>
  1513. <div
  1514. data-archive-id={archive.id}
  1515. className={`grid grid-cols-12 gap-4 px-4 py-3 items-center hover:bg-bambu-dark-tertiary/30 ${
  1516. isSelected ? 'bg-bambu-green/10' : ''
  1517. }`}
  1518. style={isHighlighted ? { outline: '4px solid #facc15', outlineOffset: '-4px' } : undefined}
  1519. onContextMenu={handleContextMenu}
  1520. >
  1521. <div className="col-span-1 flex items-center gap-2">
  1522. {selectionMode && (
  1523. <button onClick={() => onSelect(archive.id)}>
  1524. {isSelected ? (
  1525. <CheckSquare className="w-4 h-4 text-bambu-green" />
  1526. ) : (
  1527. <Square className="w-4 h-4 text-bambu-gray" />
  1528. )}
  1529. </button>
  1530. )}
  1531. {archive.thumbnail_path ? (
  1532. <img
  1533. src={api.getArchiveThumbnail(archive.id)}
  1534. alt=""
  1535. className="w-10 h-10 object-cover rounded"
  1536. />
  1537. ) : (
  1538. <div className="w-10 h-10 bg-bambu-dark rounded flex items-center justify-center">
  1539. <Image className="w-5 h-5 text-bambu-dark-tertiary" />
  1540. </div>
  1541. )}
  1542. </div>
  1543. <div className="col-span-4">
  1544. <div className="flex items-center gap-2">
  1545. <p className="text-white text-sm truncate">{archive.print_name || archive.filename}</p>
  1546. {archive.timelapse_path && (
  1547. <span title="Has timelapse">
  1548. <Film className="w-3.5 h-3.5 text-bambu-green flex-shrink-0" />
  1549. </span>
  1550. )}
  1551. {linkedFolders && linkedFolders.length > 0 && (
  1552. <Link
  1553. to={`/files?folder=${linkedFolders[0].id}`}
  1554. className="flex-shrink-0"
  1555. title={`Open folder: ${linkedFolders[0].name}`}
  1556. onClick={(e) => e.stopPropagation()}
  1557. >
  1558. <FolderOpen className="w-3.5 h-3.5 text-yellow-400" />
  1559. </Link>
  1560. )}
  1561. </div>
  1562. {(archive.filament_type || archive.sliced_for_model) && (
  1563. <div className="flex items-center gap-1.5 mt-0.5">
  1564. {archive.sliced_for_model && (
  1565. <span className="text-xs text-bambu-gray flex items-center gap-1" title={`Sliced for ${archive.sliced_for_model}`}>
  1566. <Printer className="w-2.5 h-2.5" />
  1567. {archive.sliced_for_model}
  1568. </span>
  1569. )}
  1570. {archive.sliced_for_model && archive.filament_type && (
  1571. <span className="text-bambu-gray/50">·</span>
  1572. )}
  1573. {archive.filament_type && (
  1574. <span className="text-xs text-bambu-gray">{archive.filament_type}</span>
  1575. )}
  1576. {archive.filament_color && (
  1577. <div className="flex items-center gap-0.5 flex-wrap">
  1578. {archive.filament_color.split(',').map((color, i) => (
  1579. <div
  1580. key={i}
  1581. className="w-2.5 h-2.5 rounded-full border border-white/20"
  1582. style={{ backgroundColor: color }}
  1583. title={color}
  1584. />
  1585. ))}
  1586. </div>
  1587. )}
  1588. </div>
  1589. )}
  1590. </div>
  1591. <div className="col-span-2 text-sm text-bambu-gray truncate">
  1592. {printerName}
  1593. </div>
  1594. <div className="col-span-2 text-sm text-bambu-gray">
  1595. {formatDateOnly(archive.created_at)}
  1596. </div>
  1597. <div className="col-span-1 text-sm text-bambu-gray">
  1598. {formatFileSize(archive.file_size)}
  1599. </div>
  1600. <div className="col-span-2 flex justify-end gap-1">
  1601. <Button
  1602. variant="ghost"
  1603. size="sm"
  1604. onClick={() => {
  1605. const filename = archive.print_name || archive.filename || 'model';
  1606. const downloadUrl = `${window.location.origin}${api.getArchiveForSlicer(archive.id, filename)}`;
  1607. openInSlicer(downloadUrl);
  1608. }}
  1609. title="Open in Bambu Studio"
  1610. >
  1611. <ExternalLink className="w-4 h-4" />
  1612. </Button>
  1613. {(archive.external_url || archive.makerworld_url) && (
  1614. <Button
  1615. variant="ghost"
  1616. size="sm"
  1617. onClick={() => window.open((archive.external_url || archive.makerworld_url)!, '_blank')}
  1618. title={archive.external_url ? 'External Link' : 'MakerWorld'}
  1619. >
  1620. <Globe className="w-4 h-4" />
  1621. </Button>
  1622. )}
  1623. <Button
  1624. variant="ghost"
  1625. size="sm"
  1626. onClick={() => {
  1627. const link = document.createElement('a');
  1628. link.href = api.getArchiveDownload(archive.id);
  1629. link.download = `${archive.print_name || archive.filename}.3mf`;
  1630. link.click();
  1631. }}
  1632. title="Download"
  1633. >
  1634. <Download className="w-4 h-4" />
  1635. </Button>
  1636. <Button
  1637. variant="ghost"
  1638. size="sm"
  1639. onClick={() => setShowEdit(true)}
  1640. title="Edit"
  1641. >
  1642. <Pencil className="w-4 h-4" />
  1643. </Button>
  1644. <Button
  1645. variant="ghost"
  1646. size="sm"
  1647. onClick={() => setShowDeleteConfirm(true)}
  1648. title="Delete"
  1649. >
  1650. <Trash2 className="w-4 h-4 text-red-400" />
  1651. </Button>
  1652. <Button
  1653. variant="ghost"
  1654. size="sm"
  1655. onClick={(e) => {
  1656. const rect = e.currentTarget.getBoundingClientRect();
  1657. setContextMenu({ x: rect.left, y: rect.bottom + 4 });
  1658. }}
  1659. title="More options"
  1660. >
  1661. <MoreVertical className="w-4 h-4" />
  1662. </Button>
  1663. </div>
  1664. </div>
  1665. {/* Edit Modal */}
  1666. {showEdit && (
  1667. <EditArchiveModal
  1668. archive={archive}
  1669. onClose={() => setShowEdit(false)}
  1670. />
  1671. )}
  1672. {/* 3D Viewer Modal */}
  1673. {showViewer && (
  1674. <ModelViewerModal
  1675. archiveId={archive.id}
  1676. title={archive.print_name || archive.filename}
  1677. onClose={() => setShowViewer(false)}
  1678. />
  1679. )}
  1680. {/* Reprint Modal */}
  1681. {showReprint && (
  1682. <PrintModal
  1683. mode="reprint"
  1684. archiveId={archive.id}
  1685. archiveName={archive.print_name || archive.filename}
  1686. onClose={() => setShowReprint(false)}
  1687. />
  1688. )}
  1689. {/* Delete Confirmation */}
  1690. {showDeleteConfirm && (
  1691. <ConfirmModal
  1692. title="Delete Archive"
  1693. message={`Are you sure you want to delete "${archive.print_name || archive.filename}"? This action cannot be undone.`}
  1694. confirmText="Delete"
  1695. variant="danger"
  1696. onConfirm={() => {
  1697. deleteMutation.mutate();
  1698. setShowDeleteConfirm(false);
  1699. }}
  1700. onCancel={() => setShowDeleteConfirm(false)}
  1701. />
  1702. )}
  1703. {/* Delete Source 3MF Confirmation */}
  1704. {showDeleteSource3mfConfirm && (
  1705. <ConfirmModal
  1706. title="Remove Source 3MF"
  1707. message={`Are you sure you want to remove the source 3MF file from "${archive.print_name || archive.filename}"?`}
  1708. confirmText="Remove"
  1709. variant="danger"
  1710. onConfirm={() => {
  1711. source3mfDeleteMutation.mutate();
  1712. setShowDeleteSource3mfConfirm(false);
  1713. }}
  1714. onCancel={() => setShowDeleteSource3mfConfirm(false)}
  1715. />
  1716. )}
  1717. {/* Delete F3D Confirmation */}
  1718. {showDeleteF3dConfirm && (
  1719. <ConfirmModal
  1720. title="Remove F3D"
  1721. message={`Are you sure you want to remove the Fusion 360 design file from "${archive.print_name || archive.filename}"?`}
  1722. confirmText="Remove"
  1723. variant="danger"
  1724. onConfirm={() => {
  1725. f3dDeleteMutation.mutate();
  1726. setShowDeleteF3dConfirm(false);
  1727. }}
  1728. onCancel={() => setShowDeleteF3dConfirm(false)}
  1729. />
  1730. )}
  1731. {/* Context Menu */}
  1732. {contextMenu && (
  1733. <ContextMenu
  1734. x={contextMenu.x}
  1735. y={contextMenu.y}
  1736. items={contextMenuItems}
  1737. onClose={() => setContextMenu(null)}
  1738. />
  1739. )}
  1740. {/* Timelapse Viewer Modal */}
  1741. {showTimelapse && archive.timelapse_path && (
  1742. <TimelapseViewer
  1743. src={api.getArchiveTimelapse(archive.id)}
  1744. title={`${archive.print_name || archive.filename} - Timelapse`}
  1745. downloadFilename={`${archive.print_name || archive.filename}_timelapse.mp4`}
  1746. archiveId={archive.id}
  1747. onClose={() => setShowTimelapse(false)}
  1748. onEdit={() => {
  1749. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1750. setShowTimelapse(false);
  1751. }}
  1752. />
  1753. )}
  1754. {/* Timelapse Selection Modal */}
  1755. {showTimelapseSelect && availableTimelapses.length > 0 && (
  1756. <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4">
  1757. <div className="bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col">
  1758. <div className="flex items-center justify-between p-4 border-b border-gray-700">
  1759. <div>
  1760. <h3 className="text-lg font-semibold text-white">Select Timelapse</h3>
  1761. <p className="text-sm text-gray-400 mt-1">
  1762. No auto-match found. Select the timelapse for this print:
  1763. </p>
  1764. </div>
  1765. <button
  1766. onClick={() => {
  1767. setShowTimelapseSelect(false);
  1768. setAvailableTimelapses([]);
  1769. }}
  1770. className="text-gray-400 hover:text-white p-1"
  1771. >
  1772. <X className="w-5 h-5" />
  1773. </button>
  1774. </div>
  1775. <div className="overflow-y-auto flex-1 p-2">
  1776. {availableTimelapses.map((file) => (
  1777. <button
  1778. key={file.name}
  1779. onClick={() => timelapseSelectMutation.mutate(file.name)}
  1780. disabled={timelapseSelectMutation.isPending}
  1781. className="w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors mb-1"
  1782. >
  1783. <div className="font-medium text-white">{file.name}</div>
  1784. <div className="text-sm text-gray-400 flex gap-3">
  1785. <span>{formatFileSize(file.size)}</span>
  1786. {file.mtime && (
  1787. <span>{formatDateOnly(file.mtime)}</span>
  1788. )}
  1789. </div>
  1790. </button>
  1791. ))}
  1792. </div>
  1793. </div>
  1794. </div>
  1795. )}
  1796. {/* QR Code Modal */}
  1797. {showQRCode && (
  1798. <QRCodeModal
  1799. archiveId={archive.id}
  1800. archiveName={archive.print_name || archive.filename}
  1801. onClose={() => setShowQRCode(false)}
  1802. />
  1803. )}
  1804. {/* Photo Gallery Modal */}
  1805. {showPhotos && archive.photos && (
  1806. <PhotoGalleryModal
  1807. archiveId={archive.id}
  1808. archiveName={archive.print_name || archive.filename}
  1809. photos={archive.photos}
  1810. onClose={() => setShowPhotos(false)}
  1811. onDelete={async (filename) => {
  1812. try {
  1813. await api.deleteArchivePhoto(archive.id, filename);
  1814. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1815. showToast('Photo deleted');
  1816. } catch {
  1817. showToast('Failed to delete photo', 'error');
  1818. }
  1819. }}
  1820. />
  1821. )}
  1822. {/* Project Page Modal */}
  1823. {showProjectPage && (
  1824. <ProjectPageModal
  1825. archiveId={archive.id}
  1826. archiveName={archive.print_name || archive.filename}
  1827. onClose={() => setShowProjectPage(false)}
  1828. />
  1829. )}
  1830. {/* Schedule Modal */}
  1831. {showSchedule && (
  1832. <PrintModal
  1833. mode="add-to-queue"
  1834. archiveId={archive.id}
  1835. archiveName={archive.print_name || archive.filename}
  1836. onClose={() => setShowSchedule(false)}
  1837. />
  1838. )}
  1839. {/* Hidden file input for source 3MF upload */}
  1840. <input
  1841. ref={source3mfInputRef}
  1842. type="file"
  1843. accept=".3mf"
  1844. className="hidden"
  1845. onChange={(e) => {
  1846. const file = e.target.files?.[0];
  1847. if (file) {
  1848. source3mfUploadMutation.mutate(file);
  1849. }
  1850. e.target.value = '';
  1851. }}
  1852. />
  1853. {/* Hidden file input for F3D upload */}
  1854. <input
  1855. ref={f3dInputRef}
  1856. type="file"
  1857. accept=".f3d"
  1858. className="hidden"
  1859. onChange={(e) => {
  1860. const file = e.target.files?.[0];
  1861. if (file) {
  1862. f3dUploadMutation.mutate(file);
  1863. }
  1864. e.target.value = '';
  1865. }}
  1866. />
  1867. </>
  1868. );
  1869. }
  1870. type SortOption = 'date-desc' | 'date-asc' | 'name-asc' | 'name-desc' | 'size-desc' | 'size-asc';
  1871. type ViewMode = 'grid' | 'list' | 'calendar';
  1872. type Collection = 'all' | 'recent' | 'this-week' | 'this-month' | 'favorites' | 'failed' | 'duplicates';
  1873. const collections: { id: Collection; label: string; icon: React.ReactNode }[] = [
  1874. { id: 'all', label: 'All Archives', icon: <FolderOpen className="w-4 h-4" /> },
  1875. { id: 'recent', label: 'Last 24 Hours', icon: <Clock className="w-4 h-4" /> },
  1876. { id: 'this-week', label: 'This Week', icon: <Calendar className="w-4 h-4" /> },
  1877. { id: 'this-month', label: 'This Month', icon: <Calendar className="w-4 h-4" /> },
  1878. { id: 'favorites', label: 'Favorites', icon: <Star className="w-4 h-4" /> },
  1879. { id: 'failed', label: 'Failed Prints', icon: <AlertCircle className="w-4 h-4" /> },
  1880. { id: 'duplicates', label: 'Duplicates', icon: <Copy className="w-4 h-4" /> },
  1881. ];
  1882. export function ArchivesPage() {
  1883. const queryClient = useQueryClient();
  1884. const { showToast } = useToast();
  1885. const searchInputRef = useRef<HTMLInputElement>(null);
  1886. const [search, setSearch] = useState('');
  1887. const [filterPrinter, setFilterPrinter] = useState<number | null>(() => {
  1888. const saved = localStorage.getItem('archiveFilterPrinter');
  1889. return saved ? Number(saved) : null;
  1890. });
  1891. const [filterMaterial, setFilterMaterial] = useState<string | null>(() =>
  1892. localStorage.getItem('archiveFilterMaterial')
  1893. );
  1894. const [filterColors, setFilterColors] = useState<Set<string>>(() => {
  1895. const saved = localStorage.getItem('archiveFilterColors');
  1896. return saved ? new Set(JSON.parse(saved)) : new Set();
  1897. });
  1898. const [colorFilterMode, setColorFilterMode] = useState<'or' | 'and'>(() =>
  1899. (localStorage.getItem('archiveColorFilterMode') as 'or' | 'and') || 'or'
  1900. );
  1901. const [filterFavorites, setFilterFavorites] = useState(() =>
  1902. localStorage.getItem('archiveFilterFavorites') === 'true'
  1903. );
  1904. const [hideFailed, setHideFailed] = useState(() =>
  1905. localStorage.getItem('archiveHideFailed') === 'true'
  1906. );
  1907. const [filterTag, setFilterTag] = useState<string | null>(() =>
  1908. localStorage.getItem('archiveFilterTag')
  1909. );
  1910. const [filterFileType, setFilterFileType] = useState<'all' | 'gcode' | 'source'>(() =>
  1911. (localStorage.getItem('archiveFilterFileType') as 'all' | 'gcode' | 'source') || 'all'
  1912. );
  1913. const [showUpload, setShowUpload] = useState(false);
  1914. const [uploadFiles, setUploadFiles] = useState<File[]>([]);
  1915. const [isDraggingOver, setIsDraggingOver] = useState(false);
  1916. const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
  1917. const [isSelectionMode, setIsSelectionMode] = useState(false);
  1918. const [showBulkDeleteConfirm, setShowBulkDeleteConfirm] = useState(false);
  1919. const [showBatchTag, setShowBatchTag] = useState(false);
  1920. const [showBatchProject, setShowBatchProject] = useState(false);
  1921. const [viewMode, setViewMode] = useState<ViewMode>(() =>
  1922. (localStorage.getItem('archiveViewMode') as ViewMode) || 'grid'
  1923. );
  1924. const [sortBy, setSortBy] = useState<SortOption>(() =>
  1925. (localStorage.getItem('archiveSortBy') as SortOption) || 'date-desc'
  1926. );
  1927. const [collection, setCollection] = useState<Collection>(() =>
  1928. (localStorage.getItem('archiveCollection') as Collection) || 'all'
  1929. );
  1930. const [showExportMenu, setShowExportMenu] = useState(false);
  1931. const [isExporting, setIsExporting] = useState(false);
  1932. const [showCompareModal, setShowCompareModal] = useState(false);
  1933. const [showTagManagement, setShowTagManagement] = useState(false);
  1934. const [highlightedArchiveId, setHighlightedArchiveId] = useState<number | null>(null);
  1935. // Clear highlight after 5 seconds and scroll to highlighted element
  1936. useEffect(() => {
  1937. if (highlightedArchiveId) {
  1938. // Scroll to highlighted element after a short delay (to let the view render)
  1939. const scrollTimer = setTimeout(() => {
  1940. const element = document.querySelector(`[data-archive-id="${highlightedArchiveId}"]`);
  1941. if (element) {
  1942. element.scrollIntoView({ behavior: 'smooth', block: 'center' });
  1943. }
  1944. }, 100);
  1945. // Clear highlight after 5 seconds
  1946. const clearTimer = setTimeout(() => setHighlightedArchiveId(null), 5000);
  1947. return () => {
  1948. clearTimeout(scrollTimer);
  1949. clearTimeout(clearTimer);
  1950. };
  1951. }
  1952. }, [highlightedArchiveId]);
  1953. const { data: archives, isLoading } = useQuery({
  1954. queryKey: ['archives', filterPrinter],
  1955. queryFn: () => api.getArchives(filterPrinter || undefined),
  1956. });
  1957. const { data: printers } = useQuery({
  1958. queryKey: ['printers'],
  1959. queryFn: api.getPrinters,
  1960. });
  1961. const { data: projects } = useQuery({
  1962. queryKey: ['projects'],
  1963. queryFn: () => api.getProjects(),
  1964. });
  1965. const { data: settings } = useQuery({
  1966. queryKey: ['settings'],
  1967. queryFn: api.getSettings,
  1968. });
  1969. const timeFormat: TimeFormat = settings?.time_format || 'system';
  1970. const bulkDeleteMutation = useMutation({
  1971. mutationFn: async (ids: number[]) => {
  1972. await Promise.all(ids.map((id) => api.deleteArchive(id)));
  1973. return ids.length;
  1974. },
  1975. onSuccess: (count) => {
  1976. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1977. setSelectedIds(new Set());
  1978. showToast(`${count} archive${count !== 1 ? 's' : ''} deleted`);
  1979. },
  1980. onError: () => {
  1981. showToast('Failed to delete archives', 'error');
  1982. },
  1983. });
  1984. // Persist all filters to localStorage
  1985. useEffect(() => {
  1986. if (filterPrinter !== null) {
  1987. localStorage.setItem('archiveFilterPrinter', filterPrinter.toString());
  1988. } else {
  1989. localStorage.removeItem('archiveFilterPrinter');
  1990. }
  1991. }, [filterPrinter]);
  1992. useEffect(() => {
  1993. if (filterMaterial) {
  1994. localStorage.setItem('archiveFilterMaterial', filterMaterial);
  1995. } else {
  1996. localStorage.removeItem('archiveFilterMaterial');
  1997. }
  1998. }, [filterMaterial]);
  1999. useEffect(() => {
  2000. localStorage.setItem('archiveFilterColors', JSON.stringify([...filterColors]));
  2001. }, [filterColors]);
  2002. useEffect(() => {
  2003. localStorage.setItem('archiveColorFilterMode', colorFilterMode);
  2004. }, [colorFilterMode]);
  2005. useEffect(() => {
  2006. localStorage.setItem('archiveFilterFavorites', filterFavorites.toString());
  2007. }, [filterFavorites]);
  2008. useEffect(() => {
  2009. localStorage.setItem('archiveHideFailed', hideFailed.toString());
  2010. }, [hideFailed]);
  2011. useEffect(() => {
  2012. if (filterTag) {
  2013. localStorage.setItem('archiveFilterTag', filterTag);
  2014. } else {
  2015. localStorage.removeItem('archiveFilterTag');
  2016. }
  2017. }, [filterTag]);
  2018. useEffect(() => {
  2019. localStorage.setItem('archiveFilterFileType', filterFileType);
  2020. }, [filterFileType]);
  2021. useEffect(() => {
  2022. localStorage.setItem('archiveViewMode', viewMode);
  2023. }, [viewMode]);
  2024. useEffect(() => {
  2025. localStorage.setItem('archiveSortBy', sortBy);
  2026. }, [sortBy]);
  2027. useEffect(() => {
  2028. localStorage.setItem('archiveCollection', collection);
  2029. }, [collection]);
  2030. const printerMap = new Map(printers?.map((p) => [p.id, p.name]) || []);
  2031. // Extract unique materials and colors from archives
  2032. const uniqueMaterials = [...new Set(
  2033. archives?.flatMap(a => a.filament_type?.split(', ') || []).filter(Boolean) || []
  2034. )].sort();
  2035. const uniqueColors = [...new Set(
  2036. archives?.flatMap(a => a.filament_color?.split(',') || []).filter(Boolean) || []
  2037. )];
  2038. const uniqueTags = [...new Set(
  2039. archives?.flatMap(a => a.tags?.split(',').map(t => t.trim()) || []).filter(Boolean) || []
  2040. )].sort();
  2041. const filteredArchives = archives
  2042. ?.filter((a) => {
  2043. // Collection filter
  2044. const now = new Date();
  2045. const archiveDate = parseUTCDate(a.created_at) || new Date(0);
  2046. let matchesCollection = true;
  2047. switch (collection) {
  2048. case 'recent':
  2049. matchesCollection = (now.getTime() - archiveDate.getTime()) < 24 * 60 * 60 * 1000;
  2050. break;
  2051. case 'this-week':
  2052. matchesCollection = (now.getTime() - archiveDate.getTime()) < 7 * 24 * 60 * 60 * 1000;
  2053. break;
  2054. case 'this-month':
  2055. matchesCollection = archiveDate.getMonth() === now.getMonth() && archiveDate.getFullYear() === now.getFullYear();
  2056. break;
  2057. case 'favorites':
  2058. matchesCollection = a.is_favorite === true;
  2059. break;
  2060. case 'failed':
  2061. matchesCollection = a.status === 'failed' || a.status === 'aborted';
  2062. break;
  2063. case 'duplicates':
  2064. matchesCollection = a.duplicate_count > 0;
  2065. break;
  2066. }
  2067. // Search filter
  2068. const matchesSearch = (a.print_name || a.filename).toLowerCase().includes(search.toLowerCase());
  2069. // Material filter
  2070. const matchesMaterial = !filterMaterial ||
  2071. (a.filament_type?.split(', ').includes(filterMaterial));
  2072. // Color filter (AND: must have all selected colors, OR: must have any selected color)
  2073. const archiveColors = a.filament_color?.split(',') || [];
  2074. const matchesColor = filterColors.size === 0 ||
  2075. (colorFilterMode === 'or'
  2076. ? archiveColors.some(c => filterColors.has(c))
  2077. : [...filterColors].every(c => archiveColors.includes(c)));
  2078. // Favorites filter (only apply if not using favorites collection)
  2079. const matchesFavorites = collection === 'favorites' || !filterFavorites || a.is_favorite;
  2080. // Hide failed filter (don't apply when viewing failed collection)
  2081. const matchesHideFailed = collection === 'failed' || !hideFailed || (a.status !== 'failed' && a.status !== 'aborted');
  2082. // Tag filter
  2083. const archiveTags = a.tags?.split(',').map(t => t.trim()) || [];
  2084. const matchesTag = !filterTag || archiveTags.includes(filterTag);
  2085. // File type filter (gcode = sliced, source = project file only)
  2086. const isGcodeFile = isSlicedFile(a.filename);
  2087. const matchesFileType = filterFileType === 'all' ||
  2088. (filterFileType === 'gcode' && isGcodeFile) ||
  2089. (filterFileType === 'source' && !isGcodeFile);
  2090. return matchesCollection && matchesSearch && matchesMaterial && matchesColor && matchesFavorites && matchesHideFailed && matchesTag && matchesFileType;
  2091. })
  2092. .sort((a, b) => {
  2093. switch (sortBy) {
  2094. case 'date-desc':
  2095. return (parseUTCDate(b.created_at)?.getTime() || 0) - (parseUTCDate(a.created_at)?.getTime() || 0);
  2096. case 'date-asc':
  2097. return (parseUTCDate(a.created_at)?.getTime() || 0) - (parseUTCDate(b.created_at)?.getTime() || 0);
  2098. case 'name-asc':
  2099. return (a.print_name || a.filename).localeCompare(b.print_name || b.filename);
  2100. case 'name-desc':
  2101. return (b.print_name || b.filename).localeCompare(a.print_name || a.filename);
  2102. case 'size-desc':
  2103. return b.file_size - a.file_size;
  2104. case 'size-asc':
  2105. return a.file_size - b.file_size;
  2106. default:
  2107. return 0;
  2108. }
  2109. });
  2110. const selectionMode = isSelectionMode || selectedIds.size > 0;
  2111. const toggleSelect = (id: number) => {
  2112. setSelectedIds((prev) => {
  2113. const next = new Set(prev);
  2114. if (next.has(id)) {
  2115. next.delete(id);
  2116. } else {
  2117. next.add(id);
  2118. }
  2119. return next;
  2120. });
  2121. };
  2122. const selectAll = () => {
  2123. if (filteredArchives) {
  2124. setSelectedIds(new Set(filteredArchives.map((a) => a.id)));
  2125. }
  2126. };
  2127. const clearSelection = () => {
  2128. setSelectedIds(new Set());
  2129. setIsSelectionMode(false);
  2130. };
  2131. const toggleColor = (color: string) => {
  2132. setFilterColors((prev) => {
  2133. const next = new Set(prev);
  2134. if (next.has(color)) {
  2135. next.delete(color);
  2136. } else {
  2137. next.add(color);
  2138. }
  2139. return next;
  2140. });
  2141. };
  2142. const clearColorFilter = () => {
  2143. setFilterColors(new Set());
  2144. };
  2145. const clearTopFilters = () => {
  2146. setSearch('');
  2147. setFilterPrinter(null);
  2148. setFilterMaterial(null);
  2149. setFilterFavorites(false);
  2150. setHideFailed(false);
  2151. setFilterTag(null);
  2152. setFilterFileType('all');
  2153. };
  2154. const hasTopFilters = search || filterPrinter || filterMaterial || filterFavorites || hideFailed || filterTag || filterFileType !== 'all';
  2155. // Drag & drop handlers for page-wide upload
  2156. const handleDragOver = useCallback((e: React.DragEvent) => {
  2157. e.preventDefault();
  2158. if (e.dataTransfer.types.includes('Files')) {
  2159. setIsDraggingOver(true);
  2160. }
  2161. }, []);
  2162. const handleDragLeave = useCallback((e: React.DragEvent) => {
  2163. e.preventDefault();
  2164. // Only hide if leaving the page (not entering a child)
  2165. if (e.currentTarget === e.target) {
  2166. setIsDraggingOver(false);
  2167. }
  2168. }, []);
  2169. const handleDrop = useCallback((e: React.DragEvent) => {
  2170. e.preventDefault();
  2171. setIsDraggingOver(false);
  2172. const droppedFiles = Array.from(e.dataTransfer.files).filter(f => f.name.endsWith('.3mf'));
  2173. if (droppedFiles.length > 0) {
  2174. setUploadFiles(droppedFiles);
  2175. setShowUpload(true);
  2176. } else if (e.dataTransfer.files.length > 0) {
  2177. showToast('Only .3mf files are supported', 'warning');
  2178. }
  2179. }, [showToast]);
  2180. // Keyboard shortcuts
  2181. const handleKeyDown = useCallback((e: KeyboardEvent) => {
  2182. const target = e.target as HTMLElement;
  2183. // Ignore if typing in an input/textarea
  2184. if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
  2185. if (e.key === 'Escape') {
  2186. target.blur();
  2187. }
  2188. return;
  2189. }
  2190. switch (e.key) {
  2191. case '/':
  2192. e.preventDefault();
  2193. searchInputRef.current?.focus();
  2194. break;
  2195. case 'u':
  2196. case 'U':
  2197. if (!e.metaKey && !e.ctrlKey) {
  2198. e.preventDefault();
  2199. setShowUpload(true);
  2200. }
  2201. break;
  2202. case 'Escape':
  2203. if (selectionMode) {
  2204. clearSelection();
  2205. }
  2206. break;
  2207. }
  2208. }, [selectionMode]);
  2209. useEffect(() => {
  2210. document.addEventListener('keydown', handleKeyDown);
  2211. return () => document.removeEventListener('keydown', handleKeyDown);
  2212. }, [handleKeyDown]);
  2213. return (
  2214. <div
  2215. className="p-4 md:p-8 relative min-h-full"
  2216. onDragOver={handleDragOver}
  2217. onDragLeave={handleDragLeave}
  2218. onDrop={handleDrop}
  2219. >
  2220. {/* Drag & Drop Overlay */}
  2221. {isDraggingOver && (
  2222. <div className="fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none">
  2223. <div className="border-4 border-dashed border-bambu-green rounded-xl p-12 text-center">
  2224. <Upload className="w-16 h-16 mx-auto mb-4 text-bambu-green" />
  2225. <p className="text-2xl font-semibold text-white mb-2">Drop .3mf files here</p>
  2226. <p className="text-bambu-gray">Release to upload</p>
  2227. </div>
  2228. </div>
  2229. )}
  2230. {/* Selection Toolbar */}
  2231. {selectionMode && (
  2232. <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-40 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl px-4 py-3 flex items-center gap-4">
  2233. <Button variant="secondary" size="sm" onClick={clearSelection}>
  2234. <X className="w-4 h-4" />
  2235. Close
  2236. </Button>
  2237. <div className="w-px h-6 bg-bambu-dark-tertiary" />
  2238. <span className="text-white font-medium">
  2239. {selectedIds.size} selected
  2240. </span>
  2241. <div className="w-px h-6 bg-bambu-dark-tertiary" />
  2242. <Button variant="secondary" size="sm" onClick={selectAll}>
  2243. Select All
  2244. </Button>
  2245. <div className="w-px h-6 bg-bambu-dark-tertiary" />
  2246. <Button
  2247. variant="secondary"
  2248. size="sm"
  2249. onClick={() => setShowBatchTag(true)}
  2250. >
  2251. <Tag className="w-4 h-4" />
  2252. Tags
  2253. </Button>
  2254. <Button
  2255. variant="secondary"
  2256. size="sm"
  2257. onClick={() => setShowBatchProject(true)}
  2258. >
  2259. <FolderKanban className="w-4 h-4" />
  2260. Project
  2261. </Button>
  2262. <Button
  2263. variant="secondary"
  2264. size="sm"
  2265. onClick={() => {
  2266. const ids = Array.from(selectedIds);
  2267. Promise.all(ids.map(id => api.toggleFavorite(id)))
  2268. .then(() => {
  2269. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2270. showToast(`Toggled favorites for ${ids.length} archive${ids.length !== 1 ? 's' : ''}`);
  2271. })
  2272. .catch(() => {
  2273. showToast('Failed to update favorites', 'error');
  2274. });
  2275. }}
  2276. >
  2277. <Star className="w-4 h-4" />
  2278. Favorite
  2279. </Button>
  2280. <Button
  2281. size="sm"
  2282. className="bg-red-500 hover:bg-red-600"
  2283. onClick={() => setShowBulkDeleteConfirm(true)}
  2284. >
  2285. <Trash2 className="w-4 h-4" />
  2286. Delete
  2287. </Button>
  2288. </div>
  2289. )}
  2290. <div className="flex items-center justify-between mb-8">
  2291. <div>
  2292. <div className="flex items-center gap-3">
  2293. <h1 className="text-2xl font-bold text-white">Archives</h1>
  2294. <select
  2295. className="px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray-light text-sm focus:border-bambu-green focus:outline-none"
  2296. value={collection}
  2297. onChange={(e) => setCollection(e.target.value as Collection)}
  2298. >
  2299. {collections.map((c) => (
  2300. <option key={c.id} value={c.id}>
  2301. {c.label}
  2302. </option>
  2303. ))}
  2304. </select>
  2305. </div>
  2306. <p className="text-bambu-gray">
  2307. {filteredArchives?.length || 0} of {archives?.length || 0} prints
  2308. </p>
  2309. </div>
  2310. <div className="flex items-center gap-3">
  2311. {/* Export dropdown */}
  2312. <div className="relative">
  2313. <Button
  2314. variant="secondary"
  2315. onClick={() => setShowExportMenu(!showExportMenu)}
  2316. disabled={isExporting}
  2317. >
  2318. {isExporting ? (
  2319. <Loader2 className="w-4 h-4 animate-spin" />
  2320. ) : (
  2321. <FileSpreadsheet className="w-4 h-4" />
  2322. )}
  2323. Export
  2324. </Button>
  2325. {showExportMenu && (
  2326. <div className="absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20">
  2327. <button
  2328. className="w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg"
  2329. onClick={async () => {
  2330. setShowExportMenu(false);
  2331. setIsExporting(true);
  2332. try {
  2333. const { blob, filename } = await api.exportArchives({
  2334. format: 'csv',
  2335. printerId: filterPrinter || undefined,
  2336. status: collection === 'failed' ? 'failed' : undefined,
  2337. search: search || undefined,
  2338. });
  2339. const url = URL.createObjectURL(blob);
  2340. const a = document.createElement('a');
  2341. a.href = url;
  2342. a.download = filename;
  2343. a.click();
  2344. URL.revokeObjectURL(url);
  2345. showToast('Export downloaded');
  2346. } catch {
  2347. showToast('Export failed', 'error');
  2348. } finally {
  2349. setIsExporting(false);
  2350. }
  2351. }}
  2352. >
  2353. <FileText className="w-4 h-4" />
  2354. Export as CSV
  2355. </button>
  2356. <button
  2357. className="w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg"
  2358. onClick={async () => {
  2359. setShowExportMenu(false);
  2360. setIsExporting(true);
  2361. try {
  2362. const { blob, filename } = await api.exportArchives({
  2363. format: 'xlsx',
  2364. printerId: filterPrinter || undefined,
  2365. status: collection === 'failed' ? 'failed' : undefined,
  2366. search: search || undefined,
  2367. });
  2368. const url = URL.createObjectURL(blob);
  2369. const a = document.createElement('a');
  2370. a.href = url;
  2371. a.download = filename;
  2372. a.click();
  2373. URL.revokeObjectURL(url);
  2374. showToast('Export downloaded');
  2375. } catch {
  2376. showToast('Export failed', 'error');
  2377. } finally {
  2378. setIsExporting(false);
  2379. }
  2380. }}
  2381. >
  2382. <FileSpreadsheet className="w-4 h-4" />
  2383. Export as Excel
  2384. </button>
  2385. </div>
  2386. )}
  2387. </div>
  2388. {/* Compare button (only when 2-5 items selected) */}
  2389. {selectedIds.size >= 2 && selectedIds.size <= 5 && (
  2390. <Button
  2391. variant="secondary"
  2392. onClick={() => setShowCompareModal(true)}
  2393. >
  2394. <GitCompare className="w-4 h-4" />
  2395. Compare ({selectedIds.size})
  2396. </Button>
  2397. )}
  2398. {!selectionMode && (
  2399. <Button variant="secondary" onClick={() => setIsSelectionMode(true)}>
  2400. <CheckSquare className="w-4 h-4" />
  2401. Select
  2402. </Button>
  2403. )}
  2404. <Button onClick={() => setShowUpload(true)}>
  2405. <Upload className="w-4 h-4" />
  2406. Upload 3MF
  2407. </Button>
  2408. </div>
  2409. </div>
  2410. {/* Filters */}
  2411. <Card className="mb-6">
  2412. <CardContent className="py-4">
  2413. <div className="flex flex-col md:flex-row gap-3 md:gap-4 md:items-center md:flex-wrap">
  2414. {/* Search - full width on mobile */}
  2415. <div className="w-full md:flex-1 relative md:min-w-[200px]">
  2416. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  2417. <input
  2418. ref={searchInputRef}
  2419. type="text"
  2420. placeholder="Search archives..."
  2421. className="w-full pl-10 pr-4 py-3 md:py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  2422. value={search}
  2423. onChange={(e) => setSearch(e.target.value)}
  2424. />
  2425. </div>
  2426. {/* Filters - horizontal scroll on mobile */}
  2427. <div className="flex gap-2 md:gap-4 overflow-x-auto pb-1 md:pb-0 -mx-4 px-4 md:mx-0 md:px-0 md:flex-wrap scrollbar-hide">
  2428. <div className="flex items-center gap-2 flex-shrink-0">
  2429. <Filter className="w-4 h-4 text-bambu-gray hidden md:block" />
  2430. <select
  2431. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  2432. value={filterPrinter || ''}
  2433. onChange={(e) =>
  2434. setFilterPrinter(e.target.value ? Number(e.target.value) : null)
  2435. }
  2436. >
  2437. <option value="">All Printers</option>
  2438. {printers?.map((p) => (
  2439. <option key={p.id} value={p.id}>
  2440. {p.name}
  2441. </option>
  2442. ))}
  2443. </select>
  2444. </div>
  2445. <div className="flex items-center gap-2 flex-shrink-0">
  2446. <Package className="w-4 h-4 text-bambu-gray hidden md:block" />
  2447. <select
  2448. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  2449. value={filterMaterial || ''}
  2450. onChange={(e) =>
  2451. setFilterMaterial(e.target.value || null)
  2452. }
  2453. >
  2454. <option value="">All Materials</option>
  2455. {uniqueMaterials.map((m) => (
  2456. <option key={m} value={m}>
  2457. {m}
  2458. </option>
  2459. ))}
  2460. </select>
  2461. </div>
  2462. <div className="flex items-center gap-2 flex-shrink-0">
  2463. <FileCode className="w-4 h-4 text-bambu-gray hidden md:block" />
  2464. <select
  2465. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  2466. value={filterFileType}
  2467. onChange={(e) => setFilterFileType(e.target.value as 'all' | 'gcode' | 'source')}
  2468. >
  2469. <option value="all">All Files</option>
  2470. <option value="gcode">Sliced (GCODE)</option>
  2471. <option value="source">Source Only</option>
  2472. </select>
  2473. </div>
  2474. <button
  2475. onClick={() => setFilterFavorites(!filterFavorites)}
  2476. className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${
  2477. filterFavorites
  2478. ? 'bg-yellow-500/20 border-yellow-500 text-yellow-400'
  2479. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  2480. }`}
  2481. title={filterFavorites ? 'Show all' : 'Show favorites only'}
  2482. >
  2483. <Star className={`w-4 h-4 ${filterFavorites ? 'fill-yellow-400' : ''}`} />
  2484. <span className="text-sm hidden md:inline">Favorites</span>
  2485. </button>
  2486. <button
  2487. onClick={() => setHideFailed(!hideFailed)}
  2488. className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${
  2489. hideFailed
  2490. ? 'bg-red-500/20 border-red-500 text-red-400'
  2491. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  2492. }`}
  2493. title={hideFailed ? 'Show failed prints' : 'Hide failed prints'}
  2494. >
  2495. <AlertCircle className={`w-4 h-4 ${hideFailed ? '' : ''}`} />
  2496. <span className="text-sm hidden md:inline">Hide Failed</span>
  2497. </button>
  2498. {uniqueTags.length > 0 && (
  2499. <div className="flex items-center gap-2 flex-shrink-0">
  2500. <Tag className="w-4 h-4 text-bambu-gray hidden md:block" />
  2501. <select
  2502. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  2503. value={filterTag || ''}
  2504. onChange={(e) => setFilterTag(e.target.value || null)}
  2505. >
  2506. <option value="">All Tags</option>
  2507. {uniqueTags.map((t) => (
  2508. <option key={t} value={t}>
  2509. {t}
  2510. </option>
  2511. ))}
  2512. </select>
  2513. <button
  2514. onClick={() => setShowTagManagement(true)}
  2515. className="p-2 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-green transition-colors"
  2516. title="Manage Tags"
  2517. >
  2518. <Settings className="w-4 h-4" />
  2519. </button>
  2520. </div>
  2521. )}
  2522. <div className="flex items-center gap-2 flex-shrink-0">
  2523. <ArrowUpDown className="w-4 h-4 text-bambu-gray hidden md:block" />
  2524. <select
  2525. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  2526. value={sortBy}
  2527. onChange={(e) => setSortBy(e.target.value as SortOption)}
  2528. >
  2529. <option value="date-desc">Newest first</option>
  2530. <option value="date-asc">Oldest first</option>
  2531. <option value="name-asc">Name A-Z</option>
  2532. <option value="name-desc">Name Z-A</option>
  2533. <option value="size-desc">Largest first</option>
  2534. <option value="size-asc">Smallest first</option>
  2535. </select>
  2536. </div>
  2537. <div className="flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden flex-shrink-0">
  2538. <button
  2539. className={`p-2 ${viewMode === 'grid' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  2540. onClick={() => setViewMode('grid')}
  2541. title="Grid view"
  2542. >
  2543. <LayoutGrid className="w-4 h-4" />
  2544. </button>
  2545. <button
  2546. className={`p-2 ${viewMode === 'list' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  2547. onClick={() => setViewMode('list')}
  2548. title="List view"
  2549. >
  2550. <List className="w-4 h-4" />
  2551. </button>
  2552. <button
  2553. className={`p-2 ${viewMode === 'calendar' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  2554. onClick={() => setViewMode('calendar')}
  2555. title="Calendar view"
  2556. >
  2557. <CalendarDays className="w-4 h-4" />
  2558. </button>
  2559. </div>
  2560. </div>
  2561. {hasTopFilters && (
  2562. <Button
  2563. variant="ghost"
  2564. size="sm"
  2565. onClick={clearTopFilters}
  2566. className="text-bambu-gray hover:text-white"
  2567. >
  2568. <X className="w-4 h-4" />
  2569. Reset
  2570. </Button>
  2571. )}
  2572. </div>
  2573. {/* Color Filter */}
  2574. {uniqueColors.length > 0 && (
  2575. <div className="flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary">
  2576. <span className="text-xs text-bambu-gray">Colors:</span>
  2577. {filterColors.size > 1 && (
  2578. <button
  2579. onClick={() => setColorFilterMode(m => m === 'or' ? 'and' : 'or')}
  2580. className={`px-2 py-0.5 text-xs rounded transition-colors ${
  2581. colorFilterMode === 'and'
  2582. ? 'bg-bambu-green text-white'
  2583. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white'
  2584. }`}
  2585. title={colorFilterMode === 'or' ? 'Match ANY selected color' : 'Match ALL selected colors'}
  2586. >
  2587. {colorFilterMode.toUpperCase()}
  2588. </button>
  2589. )}
  2590. <div className="flex items-center gap-1.5 flex-wrap">
  2591. {uniqueColors.map((color) => (
  2592. <button
  2593. key={color}
  2594. onClick={() => toggleColor(color)}
  2595. className={`w-6 h-6 rounded-full border-2 transition-all ${
  2596. filterColors.has(color)
  2597. ? 'border-bambu-green scale-110'
  2598. : 'border-white/20 hover:border-white/40'
  2599. }`}
  2600. style={{ backgroundColor: color }}
  2601. title={color}
  2602. />
  2603. ))}
  2604. </div>
  2605. {filterColors.size > 0 && (
  2606. <button
  2607. onClick={clearColorFilter}
  2608. className="text-xs text-bambu-gray hover:text-white flex items-center gap-1"
  2609. >
  2610. <X className="w-3 h-3" />
  2611. Clear
  2612. </button>
  2613. )}
  2614. </div>
  2615. )}
  2616. </CardContent>
  2617. </Card>
  2618. {/* Pending Uploads Panel (visible when in queue mode with pending files) */}
  2619. <PendingUploadsPanel />
  2620. {/* Archives */}
  2621. {isLoading ? (
  2622. <div className="text-center py-12 text-bambu-gray">Loading archives...</div>
  2623. ) : filteredArchives?.length === 0 ? (
  2624. <Card>
  2625. <CardContent className="text-center py-12">
  2626. <p className="text-bambu-gray">
  2627. {search ? 'No archives match your search' : 'No archives yet'}
  2628. </p>
  2629. <p className="text-sm text-bambu-gray mt-2">
  2630. Archives are created automatically when prints complete
  2631. </p>
  2632. </CardContent>
  2633. </Card>
  2634. ) : viewMode === 'calendar' ? (
  2635. <Card className="p-6">
  2636. <CalendarView
  2637. archives={filteredArchives || []}
  2638. onArchiveClick={(archive) => {
  2639. // Switch to grid view and highlight the archive
  2640. setSearch(''); // Clear search to show all archives
  2641. setViewMode('grid');
  2642. setHighlightedArchiveId(archive.id);
  2643. }}
  2644. highlightedArchiveId={highlightedArchiveId}
  2645. />
  2646. </Card>
  2647. ) : viewMode === 'grid' ? (
  2648. <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
  2649. {filteredArchives?.map((archive) => (
  2650. <ArchiveCard
  2651. key={archive.id}
  2652. archive={archive}
  2653. printerName={archive.printer_id ? printerMap.get(archive.printer_id) || 'Unknown' : (archive.sliced_for_model ? `Sliced for ${archive.sliced_for_model}` : 'No Printer')}
  2654. isSelected={selectedIds.has(archive.id)}
  2655. onSelect={toggleSelect}
  2656. selectionMode={selectionMode}
  2657. projects={projects}
  2658. isHighlighted={archive.id === highlightedArchiveId}
  2659. timeFormat={timeFormat}
  2660. />
  2661. ))}
  2662. </div>
  2663. ) : viewMode === 'list' ? (
  2664. <Card>
  2665. <div className="divide-y divide-bambu-dark-tertiary">
  2666. {/* List Header */}
  2667. <div className="grid grid-cols-12 gap-4 px-4 py-3 text-xs text-bambu-gray font-medium">
  2668. <div className="col-span-1"></div>
  2669. <div className="col-span-4">Name</div>
  2670. <div className="col-span-2">Printer</div>
  2671. <div className="col-span-2">Date</div>
  2672. <div className="col-span-1">Size</div>
  2673. <div className="col-span-2 text-right">Actions</div>
  2674. </div>
  2675. {/* List Items */}
  2676. {filteredArchives?.map((archive) => (
  2677. <ArchiveListRow
  2678. key={archive.id}
  2679. archive={archive}
  2680. printerName={archive.printer_id ? printerMap.get(archive.printer_id) || 'Unknown' : (archive.sliced_for_model ? `Sliced for ${archive.sliced_for_model}` : 'No Printer')}
  2681. isSelected={selectedIds.has(archive.id)}
  2682. onSelect={toggleSelect}
  2683. selectionMode={selectionMode}
  2684. projects={projects}
  2685. isHighlighted={archive.id === highlightedArchiveId}
  2686. />
  2687. ))}
  2688. </div>
  2689. </Card>
  2690. ) : null}
  2691. {/* Upload Modal */}
  2692. {showUpload && (
  2693. <UploadModal
  2694. onClose={() => {
  2695. setShowUpload(false);
  2696. setUploadFiles([]);
  2697. }}
  2698. initialFiles={uploadFiles}
  2699. />
  2700. )}
  2701. {/* Bulk Delete Confirmation */}
  2702. {showBulkDeleteConfirm && (
  2703. <ConfirmModal
  2704. title="Delete Archives"
  2705. message={`Are you sure you want to delete ${selectedIds.size} archive${selectedIds.size > 1 ? 's' : ''}? This action cannot be undone.`}
  2706. confirmText={`Delete ${selectedIds.size}`}
  2707. variant="danger"
  2708. onConfirm={() => {
  2709. bulkDeleteMutation.mutate(Array.from(selectedIds));
  2710. setShowBulkDeleteConfirm(false);
  2711. }}
  2712. onCancel={() => setShowBulkDeleteConfirm(false)}
  2713. />
  2714. )}
  2715. {/* Batch Tag Modal */}
  2716. {showBatchTag && (
  2717. <BatchTagModal
  2718. selectedIds={Array.from(selectedIds)}
  2719. existingTags={uniqueTags}
  2720. onClose={() => setShowBatchTag(false)}
  2721. />
  2722. )}
  2723. {/* Batch Project Modal */}
  2724. {showBatchProject && (
  2725. <BatchProjectModal
  2726. selectedIds={Array.from(selectedIds)}
  2727. onClose={() => setShowBatchProject(false)}
  2728. />
  2729. )}
  2730. {/* Compare Archives Modal */}
  2731. {showCompareModal && selectedIds.size >= 2 && selectedIds.size <= 5 && (
  2732. <CompareArchivesModal
  2733. archiveIds={Array.from(selectedIds)}
  2734. onClose={() => {
  2735. setShowCompareModal(false);
  2736. setSelectedIds(new Set());
  2737. setIsSelectionMode(false);
  2738. }}
  2739. />
  2740. )}
  2741. {/* Tag Management Modal */}
  2742. {showTagManagement && (
  2743. <TagManagementModal onClose={() => setShowTagManagement(false)} />
  2744. )}
  2745. </div>
  2746. );
  2747. }