ArchivesPage.tsx 147 KB

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