ArchivesPage.tsx 119 KB

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