ArchivesPage.tsx 141 KB

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