ArchivesPage.tsx 135 KB

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