ArchivesPage.tsx 153 KB

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