ArchivesPage.tsx 93 KB

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