ArchivesPage.tsx 192 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659
  1. import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
  2. import { Link, useNavigate } 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. Cog,
  57. Archive as ArchiveIcon,
  58. History,
  59. CheckCircle2,
  60. Columns,
  61. ChevronUp,
  62. ChevronDown,
  63. } from 'lucide-react';
  64. import { api } from '../api/client';
  65. import { SliceModal } from '../components/SliceModal';
  66. import { RunWithPipelineModal } from '../components/RunWithPipelineModal';
  67. import { openInSlicer, type SlicerType } from '../utils/slicer';
  68. import { formatDateTime, formatDateOnly, parseUTCDate, type TimeFormat, formatDuration } from '../utils/date';
  69. import { getCurrencySymbol } from '../utils/currency';
  70. import { getBedTypeInfo } from '../utils/bedType';
  71. import { invalidateArchiveAndProjectViews } from '../utils/projectQueries';
  72. import { useIsMobile } from '../hooks/useIsMobile';
  73. import { usePageFileDrop } from '../hooks/usePageFileDrop';
  74. import type { Archive, PrintLogEntry, ProjectListItem } from '../api/client';
  75. import { Card, CardContent } from '../components/Card';
  76. import { Button } from '../components/Button';
  77. import { PrintModal } from '../components/PrintModal';
  78. import { UploadModal } from '../components/UploadModal';
  79. import { PurgeArchivesModal } from '../components/PurgeArchivesModal';
  80. import { ConfirmModal } from '../components/ConfirmModal';
  81. import { EditArchiveModal, FAILURE_REASON_KEYS } from '../components/EditArchiveModal';
  82. import { PrintLogModal } from '../components/PrintLogModal';
  83. import { ColumnConfigModal, type ColumnConfig } from '../components/ColumnConfigModal';
  84. import { ContextMenu, type ContextMenuItem } from '../components/ContextMenu';
  85. import { BatchTagModal } from '../components/BatchTagModal';
  86. import { BatchProjectModal } from '../components/BatchProjectModal';
  87. import { CalendarView } from '../components/CalendarView';
  88. import { QRCodeModal } from '../components/QRCodeModal';
  89. import { PhotoGalleryModal } from '../components/PhotoGalleryModal';
  90. import { ProjectPageModal } from '../components/ProjectPageModal';
  91. import { TimelapseViewer } from '../components/TimelapseViewer';
  92. import { CompareArchivesModal } from '../components/CompareArchivesModal';
  93. import { PendingUploadsPanel } from '../components/PendingUploadsPanel';
  94. import { TagManagementModal } from '../components/TagManagementModal';
  95. import { PlatePickerModal } from '../components/PlatePickerModal';
  96. import type { PlateMetadata } from '../types/plates';
  97. import { useToast } from '../contexts/ToastContext';
  98. import { useAuth } from '../contexts/AuthContext';
  99. import { formatFileSize } from '../utils/file';
  100. type TFunction = (key: string, options?: Record<string, unknown>) => string;
  101. // ---------------------------------------------------------------------------
  102. // Print Log column configuration (#2636, reporter @ajbastien)
  103. //
  104. // The log view used to hardcode seven columns, which left four populated
  105. // columns of `print_log_entries` — filament used, cost, energy, energy cost —
  106. // unreachable in the UI even though the API has always returned them. They are
  107. // per-run actuals (partial prints scaled to progress, multi-plate archives
  108. // scoped to the printed plate), so they are exactly what a log is for.
  109. //
  110. // Persisted per browser like the Inventory table's config, under its own key.
  111. // Labels are NOT read back from storage: they are re-derived from `t()` on
  112. // every render so a stored config from before a language switch doesn't pin
  113. // the column picker to the old language.
  114. // ---------------------------------------------------------------------------
  115. const LOG_COLUMN_CONFIG_KEY = 'bambuddy-printlog-columns';
  116. /** Column id -> i18n key. Also the authoritative list of valid ids. */
  117. const LOG_COLUMN_LABEL_KEYS: Record<string, string> = {
  118. date: 'archives.log.date',
  119. print_name: 'archives.log.printName',
  120. printer: 'archives.log.printer',
  121. user: 'archives.log.user',
  122. status: 'archives.log.status',
  123. duration: 'archives.log.duration',
  124. completed_at: 'archives.log.completedAt',
  125. filament: 'archives.log.filament',
  126. filament_used: 'archives.log.filamentUsed',
  127. cost: 'archives.log.cost',
  128. energy: 'archives.log.energy',
  129. energy_cost: 'archives.log.energyCost',
  130. };
  131. // Defaults reproduce the previous seven columns in the same order, plus the
  132. // filament amount the issue actually asked for. The rest ship hidden: they are
  133. // available to anyone who wants them without widening the table for everyone
  134. // who doesn't.
  135. const DEFAULT_LOG_COLUMNS: Array<{ id: string; visible: boolean }> = [
  136. { id: 'date', visible: true },
  137. { id: 'print_name', visible: true },
  138. { id: 'printer', visible: true },
  139. { id: 'user', visible: true },
  140. { id: 'status', visible: true },
  141. { id: 'duration', visible: true },
  142. { id: 'filament', visible: true },
  143. { id: 'filament_used', visible: true },
  144. { id: 'completed_at', visible: false },
  145. { id: 'cost', visible: false },
  146. { id: 'energy', visible: false },
  147. { id: 'energy_cost', visible: false },
  148. ];
  149. /** Stored config merged with the defaults: unknown ids (removed columns) are
  150. * dropped and ids added by a later Bambuddy version are appended with their
  151. * default visibility, so an upgrade never silently hides a new column or
  152. * crashes on one that no longer exists. */
  153. function loadLogColumnConfig(): Array<{ id: string; visible: boolean }> {
  154. try {
  155. const stored = localStorage.getItem(LOG_COLUMN_CONFIG_KEY);
  156. if (stored) {
  157. const parsed = JSON.parse(stored) as Array<{ id: string; visible: boolean }>;
  158. const known = new Set(Object.keys(LOG_COLUMN_LABEL_KEYS));
  159. const storedIds = new Set(parsed.map((c) => c.id));
  160. const valid = parsed
  161. .filter((c) => known.has(c.id))
  162. .map((c) => ({ id: c.id, visible: !!c.visible }));
  163. const added = DEFAULT_LOG_COLUMNS.filter((c) => !storedIds.has(c.id));
  164. if (valid.length > 0) return [...valid, ...added];
  165. }
  166. } catch {
  167. // Corrupt or unavailable storage falls back to defaults.
  168. }
  169. return DEFAULT_LOG_COLUMNS.map((c) => ({ ...c }));
  170. }
  171. const LOG_SORT_KEY = 'bambuddy-printlog-sort';
  172. type LogSortState = { column: string; direction: 'asc' | 'desc' };
  173. /** Column ids the backend will order by. Kept in step with
  174. * ``_SORTABLE_COLUMNS`` in ``routes/print_log.py`` — an id missing there
  175. * comes back as a 400, so a header is only made clickable if it is listed
  176. * in both. */
  177. const SORTABLE_LOG_COLUMNS = new Set(Object.keys(LOG_COLUMN_LABEL_KEYS));
  178. const DEFAULT_LOG_SORT: LogSortState = { column: 'date', direction: 'desc' };
  179. function loadLogSort(): LogSortState {
  180. try {
  181. const stored = localStorage.getItem(LOG_SORT_KEY);
  182. if (stored) {
  183. const parsed = JSON.parse(stored) as LogSortState;
  184. if (SORTABLE_LOG_COLUMNS.has(parsed?.column) && (parsed.direction === 'asc' || parsed.direction === 'desc')) {
  185. return parsed;
  186. }
  187. }
  188. } catch {
  189. // Fall through to the default.
  190. }
  191. return { ...DEFAULT_LOG_SORT };
  192. }
  193. function saveLogSort(state: LogSortState) {
  194. try {
  195. localStorage.setItem(LOG_SORT_KEY, JSON.stringify(state));
  196. } catch {
  197. // Private-mode / quota failures shouldn't break the page.
  198. }
  199. }
  200. function saveLogColumnConfig(config: Array<{ id: string; visible: boolean }>) {
  201. try {
  202. localStorage.setItem(
  203. LOG_COLUMN_CONFIG_KEY,
  204. JSON.stringify(config.map((c) => ({ id: c.id, visible: c.visible }))),
  205. );
  206. } catch {
  207. // Private-mode / quota failures shouldn't break the page.
  208. }
  209. }
  210. /**
  211. * Check if an archive represents a sliced/printable file.
  212. * Uses filename (.gcode, .gcode.3mf) as primary check, then falls back to
  213. * metadata — a .3mf with total_layers or print_time is sliced (contains gcode),
  214. * while a raw source .3mf (CAD export) has neither.
  215. */
  216. function isSlicedFile(archive: { filename?: string | null; total_layers?: number | null; print_time_seconds?: number | null }): boolean {
  217. const filename = archive.filename;
  218. if (filename) {
  219. const lower = filename.toLowerCase();
  220. if (lower.endsWith('.gcode') || lower.includes('.gcode.')) return true;
  221. }
  222. // .3mf can be either sliced or source — check for gcode metadata
  223. if (archive.total_layers || archive.print_time_seconds) return true;
  224. return false;
  225. }
  226. // formatDate imported from '../utils/date' - handles UTC conversion
  227. /**
  228. * Open an archive file in the slicer.
  229. * Fetches a short-lived download token, then builds a token-authenticated URL
  230. * that bypasses auth middleware (slicer protocol handlers can't send auth headers).
  231. */
  232. async function openInSlicerWithToken(
  233. archiveId: number,
  234. filename: string,
  235. resourceType: 'file' | 'source',
  236. slicer: SlicerType,
  237. ): Promise<void> {
  238. try {
  239. if (resourceType === 'source') {
  240. const { token } = await api.createSourceSlicerToken(archiveId);
  241. const path = api.getSourceSlicerDownloadUrl(archiveId, token, filename);
  242. openInSlicer(`${window.location.origin}${path}`, slicer);
  243. } else {
  244. const { token } = await api.createArchiveSlicerToken(archiveId);
  245. const path = api.getArchiveSlicerDownloadUrl(archiveId, token, filename);
  246. openInSlicer(`${window.location.origin}${path}`, slicer);
  247. }
  248. } catch {
  249. // Fallback to direct URL (works when auth is disabled)
  250. const path = resourceType === 'source'
  251. ? api.getSource3mfForSlicer(archiveId, filename)
  252. : api.getArchiveForSlicer(archiveId, filename);
  253. openInSlicer(`${window.location.origin}${path}`, slicer);
  254. }
  255. }
  256. function ArchiveCard({
  257. archive,
  258. printerName,
  259. printerMap,
  260. isSelected,
  261. onSelect,
  262. selectionMode,
  263. projects,
  264. isHighlighted,
  265. timeFormat = 'system',
  266. preferredSlicer = 'bambu_studio',
  267. useSlicerApi = false,
  268. currency,
  269. t,
  270. onNavigateToArchive,
  271. }: {
  272. archive: Archive;
  273. printerName: string;
  274. isSelected: boolean;
  275. onSelect: (id: number) => void;
  276. selectionMode: boolean;
  277. projects: ProjectListItem[] | undefined;
  278. isHighlighted?: boolean;
  279. timeFormat?: TimeFormat;
  280. preferredSlicer?: SlicerType;
  281. useSlicerApi?: boolean;
  282. currency: string;
  283. t: TFunction;
  284. onNavigateToArchive?: (archiveId: number) => void;
  285. /** Printer id -> name, for naming the printer a saved slicer AMS mapping
  286. * belongs to. The card can't know which printer a reprint will target, so
  287. * the badge names the one the mapping is actually good for. */
  288. printerMap: Map<number, string>;
  289. }) {
  290. // Debug: log when card is highlighted
  291. if (isHighlighted) {
  292. console.log('ArchiveCard isHighlighted=true for archive:', archive.id);
  293. }
  294. const queryClient = useQueryClient();
  295. const { showToast } = useToast();
  296. const { hasPermission, canModify } = useAuth();
  297. const isMobile = useIsMobile();
  298. const navigate = useNavigate();
  299. // Name of the printer this archive's saved slicer AMS mapping was resolved
  300. // against, or undefined when there is none. Undefined also when the printer
  301. // has since been deleted — a mapping whose printer is gone can never be
  302. // reused, so the badge stays off rather than naming a ghost.
  303. const savedSlicerAmsMappingPrinter = useMemo(() => {
  304. const saved = (archive.extra_data as Record<string, unknown> | null)?.slicer_ams_mapping as
  305. | { mapping?: unknown; printer_id?: number }
  306. | undefined;
  307. if (!saved || !Array.isArray(saved.mapping) || saved.printer_id == null) return undefined;
  308. return printerMap.get(saved.printer_id);
  309. }, [archive.extra_data, printerMap]);
  310. const [showReprint, setShowReprint] = useState(false);
  311. const [showSliceModal, setShowSliceModal] = useState(false);
  312. const [showRunPipeline, setShowRunPipeline] = useState(false);
  313. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  314. // #1343: when true, the delete also drops the row from Quick Stats. Default
  315. // off — soft delete preserves the archive's filament/time/cost contribution.
  316. const [deletePurgeStats, setDeletePurgeStats] = useState(false);
  317. // #1734: pre-flight count of related queue items so the confirm modal can
  318. // tell the user how many will be removed and disable the button if any are
  319. // currently printing (the server 409s in that case).
  320. const deleteImpactQuery = useQuery({
  321. queryKey: ['archive', archive.id, 'delete-impact'],
  322. queryFn: () => api.getArchiveDeleteImpact(archive.id),
  323. enabled: showDeleteConfirm,
  324. staleTime: 0,
  325. });
  326. const [showEdit, setShowEdit] = useState(false);
  327. const [showPrintLog, setShowPrintLog] = useState(false);
  328. const [showTimelapse, setShowTimelapse] = useState(false);
  329. const [showTimelapseSelect, setShowTimelapseSelect] = useState(false);
  330. const [availableTimelapses, setAvailableTimelapses] = useState<Array<{ name: string; path: string; size: number; mtime: string | null }>>([]);
  331. const [showQRCode, setShowQRCode] = useState(false);
  332. const [showPhotos, setShowPhotos] = useState(false);
  333. const [showProjectPage, setShowProjectPage] = useState(false);
  334. const [showDeleteSource3mfConfirm, setShowDeleteSource3mfConfirm] = useState(false);
  335. const [showDeleteF3dConfirm, setShowDeleteF3dConfirm] = useState(false);
  336. const [showDeleteTimelapseConfirm, setShowDeleteTimelapseConfirm] = useState(false);
  337. const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
  338. const [currentPlateIndex, setCurrentPlateIndex] = useState<number | null>(null);
  339. const [showPlateNav, setShowPlateNav] = useState(false);
  340. const [platePickerPlates, setPlatePickerPlates] = useState<PlateMetadata[] | null>(null);
  341. const source3mfInputRef = useRef<HTMLInputElement>(null);
  342. const f3dInputRef = useRef<HTMLInputElement>(null);
  343. const timelapseInputRef = useRef<HTMLInputElement>(null);
  344. // Fetch plates data for multi-plate browsing (lazy - only when hovering)
  345. const { data: platesData } = useQuery({
  346. queryKey: ['archive-plates', archive.id],
  347. queryFn: () => api.getArchivePlates(archive.id),
  348. enabled: showPlateNav, // Only fetch when user hovers to see navigation
  349. staleTime: 5 * 60 * 1000, // Cache for 5 minutes
  350. });
  351. // Use pre-computed duplicate sequence and original archive ID from list response
  352. const duplicateSequence = archive.duplicate_sequence ?? 0;
  353. const originalArchiveId = archive.original_archive_id ?? null;
  354. const plates = platesData?.plates ?? [];
  355. const isMultiPlate = platesData?.is_multi_plate ?? false;
  356. const displayPlateIndex = currentPlateIndex ?? 0;
  357. // 3D Preview click handler. Multi-plate archives show the plate picker
  358. // first; single-plate archives navigate straight into the viewer. Source-
  359. // only archives (no sliced gcode, e.g. pure project 3MFs from BambuStudio
  360. // that carry only plate PNG/JSON metadata) get a toast — there's nothing
  361. // the gcode viewer can render for them.
  362. const openGcodeViewer = async () => {
  363. try {
  364. const resp = await api.getArchivePlates(archive.id);
  365. if (resp.has_gcode === false) {
  366. showToast(t('archives.platePicker.noGcode'), 'info');
  367. return;
  368. }
  369. if (resp.is_multi_plate && resp.plates.length > 1) {
  370. setPlatePickerPlates(resp.plates);
  371. return;
  372. }
  373. } catch {
  374. // Swallow — fall through to the no-plate navigate below so the viewer
  375. // still opens on the first plate (the backend's default).
  376. }
  377. navigate(`/gcode-viewer?archive=${archive.id}`);
  378. };
  379. const timelapseDeleteMutation = useMutation({
  380. mutationFn: () => api.deleteArchiveTimelapse(archive.id),
  381. onSuccess: () => {
  382. queryClient.invalidateQueries({ queryKey: ['archives'] });
  383. showToast(t('archives.toast.timelapseRemoved'));
  384. },
  385. onError: (error: Error) => {
  386. showToast(error.message || t('archives.toast.failedRemoveTimelapse'), 'error');
  387. },
  388. });
  389. const timelapseUploadMutation = useMutation({
  390. mutationFn: (file: File) => api.uploadArchiveTimelapse(archive.id, file),
  391. onSuccess: (data) => {
  392. queryClient.invalidateQueries({ queryKey: ['archives'] });
  393. showToast(t('archives.toast.timelapseUploaded', { filename: data.filename }));
  394. },
  395. onError: (error: Error) => {
  396. showToast(error.message || t('archives.toast.failedUploadTimelapse'), 'error');
  397. },
  398. });
  399. const source3mfUploadMutation = useMutation({
  400. mutationFn: (file: File) => api.uploadSource3mf(archive.id, file),
  401. onSuccess: (data) => {
  402. queryClient.invalidateQueries({ queryKey: ['archives'] });
  403. showToast(t('archives.toast.source3mfAttached', { filename: data.filename }));
  404. },
  405. onError: (error: Error) => {
  406. showToast(error.message || t('archives.toast.failedUploadSource3mf'), 'error');
  407. },
  408. });
  409. const source3mfDeleteMutation = useMutation({
  410. mutationFn: () => api.deleteSource3mf(archive.id),
  411. onSuccess: () => {
  412. queryClient.invalidateQueries({ queryKey: ['archives'] });
  413. showToast(t('archives.toast.source3mfRemoved'));
  414. },
  415. onError: (error: Error) => {
  416. showToast(error.message || t('archives.toast.failedRemoveSource3mf'), 'error');
  417. },
  418. });
  419. const f3dUploadMutation = useMutation({
  420. mutationFn: (file: File) => api.uploadF3d(archive.id, file),
  421. onSuccess: (data) => {
  422. queryClient.invalidateQueries({ queryKey: ['archives'] });
  423. showToast(t('archives.toast.f3dAttached', { filename: data.filename }));
  424. },
  425. onError: (error: Error) => {
  426. showToast(error.message || t('archives.toast.failedUploadF3d'), 'error');
  427. },
  428. });
  429. const f3dDeleteMutation = useMutation({
  430. mutationFn: () => api.deleteF3d(archive.id),
  431. onSuccess: () => {
  432. queryClient.invalidateQueries({ queryKey: ['archives'] });
  433. showToast(t('archives.toast.f3dRemoved'));
  434. },
  435. onError: (error: Error) => {
  436. showToast(error.message || t('archives.toast.failedRemoveF3d'), 'error');
  437. },
  438. });
  439. const timelapseScanMutation = useMutation({
  440. mutationFn: () => api.scanArchiveTimelapse(archive.id),
  441. onSuccess: (data) => {
  442. if (data.status === 'attached') {
  443. queryClient.invalidateQueries({ queryKey: ['archives'] });
  444. showToast(t('archives.toast.timelapseAttached', { filename: data.filename }));
  445. } else if (data.status === 'exists') {
  446. showToast(t('archives.toast.timelapseAlreadyAttached'));
  447. } else if (data.status === 'not_found' && data.available_files && data.available_files.length > 0) {
  448. // Show selection dialog
  449. setAvailableTimelapses(data.available_files);
  450. setShowTimelapseSelect(true);
  451. } else {
  452. showToast(data.message || t('archives.toast.noMatchingTimelapse'), 'warning');
  453. }
  454. },
  455. onError: (error: Error) => {
  456. showToast(error.message || t('archives.toast.failedScanTimelapse'), 'error');
  457. },
  458. });
  459. const timelapseSelectMutation = useMutation({
  460. mutationFn: (filename: string) => api.selectArchiveTimelapse(archive.id, filename),
  461. onSuccess: (data) => {
  462. queryClient.invalidateQueries({ queryKey: ['archives'] });
  463. showToast(t('archives.toast.timelapseAttached', { filename: data.filename }));
  464. setShowTimelapseSelect(false);
  465. setAvailableTimelapses([]);
  466. },
  467. onError: (error: Error) => {
  468. showToast(error.message || t('archives.toast.failedAttachTimelapse'), 'error');
  469. },
  470. });
  471. const deleteMutation = useMutation({
  472. mutationFn: (purgeStats: boolean) => api.deleteArchive(archive.id, purgeStats),
  473. onSuccess: () => {
  474. // A deleted archive leaves its project too, so the project views have to
  475. // be refreshed alongside the archive list (#2731).
  476. invalidateArchiveAndProjectViews(queryClient);
  477. showToast(t('archives.toast.archiveDeleted'));
  478. },
  479. onError: () => {
  480. showToast(t('archives.toast.failedDeleteArchive'), 'error');
  481. },
  482. });
  483. const favoriteMutation = useMutation({
  484. mutationFn: () => api.toggleFavorite(archive.id),
  485. onSuccess: (data) => {
  486. queryClient.invalidateQueries({ queryKey: ['archives'] });
  487. showToast(data.is_favorite ? t('archives.toast.addedToFavorites') : t('archives.toast.removedFromFavorites'));
  488. },
  489. });
  490. // Query for linked folders
  491. const { data: linkedFolders } = useQuery({
  492. queryKey: ['archive-folders', archive.id],
  493. queryFn: () => api.getLibraryFoldersByArchive(archive.id),
  494. });
  495. const assignProjectMutation = useMutation({
  496. mutationFn: (projectId: number | null) => api.updateArchive(archive.id, { project_id: projectId }),
  497. onSuccess: () => {
  498. invalidateArchiveAndProjectViews(queryClient);
  499. showToast(t('archives.toast.projectUpdated'));
  500. },
  501. onError: () => {
  502. showToast(t('archives.toast.failedUpdateProject'), 'error');
  503. },
  504. });
  505. const handleContextMenu = (e: React.MouseEvent) => {
  506. e.preventDefault();
  507. setContextMenu({ x: e.clientX, y: e.clientY });
  508. };
  509. const isGcodeFile = isSlicedFile(archive);
  510. const contextMenuItems: ContextMenuItem[] = [
  511. // For gcode files: show Print option
  512. // For source files: show Slice as the primary action
  513. ...(isGcodeFile ? [
  514. {
  515. label: t('common.print'),
  516. icon: <Printer className="w-4 h-4" />,
  517. onClick: () => setShowReprint(true),
  518. disabled: !archive.file_path || !hasPermission('queue:create') || !canModify('archives', 'reprint', archive.created_by_id),
  519. title: !archive.file_path
  520. ? t('archives.card.noFileForReprint')
  521. : !hasPermission('queue:create')
  522. ? t('archives.permission.noAddToQueue')
  523. : !canModify('archives', 'reprint', archive.created_by_id)
  524. ? t('archives.permission.noReprint')
  525. : undefined,
  526. },
  527. {
  528. label: t('archives.menu.openInBambuStudio'),
  529. icon: <ExternalLink className="w-4 h-4" />,
  530. onClick: () => {
  531. const filename = archive.print_name || archive.filename || 'model';
  532. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  533. },
  534. disabled: !archive.file_path,
  535. title: !archive.file_path ? t('archives.card.noFileForReprint') : undefined,
  536. },
  537. ] : [
  538. {
  539. label: t('archives.menu.slice'),
  540. icon: useSlicerApi ? <Cog className="w-4 h-4" /> : <ExternalLink className="w-4 h-4" />,
  541. onClick: () => {
  542. if (useSlicerApi) {
  543. setShowSliceModal(true);
  544. } else {
  545. const filename = archive.print_name || archive.filename || 'model';
  546. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  547. }
  548. },
  549. },
  550. // Run-with-pipeline (#1425 PR B follow-up). Sources from archive's
  551. // source 3MF (or file_path fallback). Only when slicer-api is on.
  552. ...(useSlicerApi
  553. ? [{
  554. label: t('library.runWithPipeline.actionLabel'),
  555. icon: <Play className="w-4 h-4" />,
  556. onClick: () => setShowRunPipeline(true),
  557. disabled: !hasPermission('pipelines:run'),
  558. title: !hasPermission('pipelines:run')
  559. ? t('library.runWithPipeline.noPermission')
  560. : undefined,
  561. }]
  562. : []),
  563. ]),
  564. {
  565. label: archive.external_url ? t('archives.menu.externalLink') : t('archives.menu.viewOnMakerWorld'),
  566. icon: <Globe className="w-4 h-4" />,
  567. onClick: () => {
  568. const url = archive.external_url || archive.makerworld_url;
  569. if (url) window.open(url, '_blank');
  570. },
  571. disabled: !archive.external_url && !archive.makerworld_url,
  572. },
  573. { label: '', divider: true, onClick: () => {} },
  574. {
  575. label: t('archives.menu.preview3d'),
  576. icon: <Box className="w-4 h-4" />,
  577. onClick: () => { openGcodeViewer(); },
  578. },
  579. {
  580. label: t('archives.menu.viewTimelapse'),
  581. icon: <Film className="w-4 h-4" />,
  582. onClick: () => setShowTimelapse(true),
  583. disabled: !archive.timelapse_path,
  584. },
  585. {
  586. label: t('archives.menu.scanForTimelapse'),
  587. icon: <ScanSearch className="w-4 h-4" />,
  588. onClick: () => timelapseScanMutation.mutate(),
  589. disabled: !archive.printer_id || !!archive.timelapse_path || timelapseScanMutation.isPending || !canModify('archives', 'update', archive.created_by_id),
  590. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  591. },
  592. {
  593. label: t('archives.menu.uploadTimelapse'),
  594. icon: <Upload className="w-4 h-4" />,
  595. onClick: () => timelapseInputRef.current?.click(),
  596. disabled: !!archive.timelapse_path || !canModify('archives', 'update', archive.created_by_id),
  597. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  598. },
  599. ...(archive.timelapse_path ? [{
  600. label: t('archives.menu.removeTimelapse'),
  601. icon: <Trash2 className="w-4 h-4" />,
  602. onClick: () => setShowDeleteTimelapseConfirm(true),
  603. danger: true,
  604. disabled: !canModify('archives', 'update', archive.created_by_id),
  605. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  606. }] : []),
  607. { label: '', divider: true, onClick: () => {} },
  608. {
  609. label: archive.source_3mf_path ? t('archives.menu.downloadSource3mf') : t('archives.menu.uploadSource3mf'),
  610. icon: <FileCode className="w-4 h-4" />,
  611. onClick: () => {
  612. if (archive.source_3mf_path) {
  613. api.downloadSource3mf(archive.id).catch((err) => {
  614. console.error('Source 3MF download failed:', err);
  615. });
  616. } else {
  617. source3mfInputRef.current?.click();
  618. }
  619. },
  620. disabled: !archive.source_3mf_path && !canModify('archives', 'update', archive.created_by_id),
  621. title: !archive.source_3mf_path && !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUploadFiles') : undefined,
  622. },
  623. ...(archive.source_3mf_path ? [{
  624. label: t('archives.menu.replaceSource3mf'),
  625. icon: <Upload className="w-4 h-4" />,
  626. onClick: () => source3mfInputRef.current?.click(),
  627. disabled: !canModify('archives', 'update', archive.created_by_id),
  628. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  629. },
  630. {
  631. label: t('archives.menu.removeSource3mf'),
  632. icon: <Trash2 className="w-4 h-4" />,
  633. onClick: () => setShowDeleteSource3mfConfirm(true),
  634. danger: true,
  635. disabled: !canModify('archives', 'update', archive.created_by_id),
  636. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  637. }] : []),
  638. {
  639. label: archive.f3d_path ? t('archives.menu.replaceF3d') : t('archives.menu.uploadF3d'),
  640. icon: <Box className="w-4 h-4" />,
  641. onClick: () => f3dInputRef.current?.click(),
  642. disabled: !canModify('archives', 'update', archive.created_by_id),
  643. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  644. },
  645. ...(archive.f3d_path ? [{
  646. label: t('archives.menu.downloadF3d'),
  647. icon: <Download className="w-4 h-4" />,
  648. onClick: () => {
  649. api.downloadF3d(archive.id).catch((err) => {
  650. console.error('F3D download failed:', err);
  651. });
  652. },
  653. },
  654. {
  655. label: t('archives.menu.removeF3d'),
  656. icon: <Trash2 className="w-4 h-4" />,
  657. onClick: () => setShowDeleteF3dConfirm(true),
  658. danger: true,
  659. disabled: !canModify('archives', 'update', archive.created_by_id),
  660. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  661. }] : []),
  662. { label: '', divider: true, onClick: () => {} },
  663. {
  664. label: t('archives.menu.download'),
  665. icon: <Download className="w-4 h-4" />,
  666. onClick: () => {
  667. api.downloadArchive(archive.id, `${archive.print_name || archive.filename}.3mf`).catch((err) => {
  668. console.error('Archive download failed:', err);
  669. });
  670. },
  671. disabled: !hasPermission('archives:read'),
  672. title: !hasPermission('archives:read') ? t('archives.permission.noDownload') : undefined,
  673. },
  674. {
  675. label: t('archives.menu.copyDownloadLink'),
  676. icon: <Copy className="w-4 h-4" />,
  677. onClick: () => {
  678. const url = `${window.location.origin}${api.getArchiveDownload(archive.id)}`;
  679. navigator.clipboard.writeText(url).then(() => {
  680. showToast(t('archives.toast.linkCopied'));
  681. }).catch(() => {
  682. showToast(t('archives.toast.failedCopyLink'), 'error');
  683. });
  684. },
  685. disabled: !hasPermission('archives:read'),
  686. title: !hasPermission('archives:read') ? t('archives.permission.noCopyLink') : undefined,
  687. },
  688. {
  689. label: t('archives.menu.qrCode'),
  690. icon: <QrCode className="w-4 h-4" />,
  691. onClick: () => setShowQRCode(true),
  692. },
  693. {
  694. label: archive.photos?.length ? t('archives.menu.viewPhotosCount', { count: archive.photos.length }) : t('archives.menu.viewPhotos'),
  695. icon: <Camera className="w-4 h-4" />,
  696. onClick: () => setShowPhotos(true),
  697. disabled: !archive.photos?.length,
  698. },
  699. {
  700. label: t('archives.menu.projectPage'),
  701. icon: <FileText className="w-4 h-4" />,
  702. onClick: () => setShowProjectPage(true),
  703. },
  704. { label: '', divider: true, onClick: () => {} },
  705. {
  706. label: archive.is_favorite ? t('archives.menu.removeFromFavorites') : t('archives.menu.addToFavorites'),
  707. icon: <Star className={`w-4 h-4 ${archive.is_favorite ? 'fill-yellow-400 text-yellow-400' : ''}`} />,
  708. onClick: () => favoriteMutation.mutate(),
  709. disabled: !canModify('archives', 'update', archive.created_by_id),
  710. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  711. },
  712. {
  713. label: t('archives.menu.edit'),
  714. icon: <Pencil className="w-4 h-4" />,
  715. onClick: () => setShowEdit(true),
  716. disabled: !canModify('archives', 'update', archive.created_by_id),
  717. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  718. },
  719. {
  720. label: t('archives.menu.printLog'),
  721. icon: <History className="w-4 h-4" />,
  722. onClick: () => setShowPrintLog(true),
  723. },
  724. ...(archive.project_id && archive.project_name ? [{
  725. label: t('archives.menu.goToProject', { name: archive.project_name }),
  726. icon: <FolderKanban className="w-4 h-4 text-bambu-green" />,
  727. onClick: () => window.location.href = '/projects',
  728. }] : []),
  729. {
  730. label: t('archives.menu.addToProject'),
  731. icon: <FolderKanban className="w-4 h-4" />,
  732. onClick: () => {},
  733. disabled: !canModify('archives', 'update', archive.created_by_id),
  734. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  735. submenuSearchPlaceholder: (projects?.filter(p => p.status === 'active').length ?? 0) > 5
  736. ? t('archives.menu.searchProjects')
  737. : undefined,
  738. submenu: (() => {
  739. const items: ContextMenuItem[] = [];
  740. // Add "Remove from Project" if archive is in a project
  741. if (archive.project_id) {
  742. items.push({
  743. label: t('archives.menu.removeFromProject'),
  744. icon: <X className="w-4 h-4" />,
  745. onClick: () => assignProjectMutation.mutate(null),
  746. disabled: !canModify('archives', 'update', archive.created_by_id),
  747. });
  748. }
  749. // Add project options
  750. if (!projects) {
  751. items.push({
  752. label: t('archives.menu.loading'),
  753. icon: <Loader2 className="w-4 h-4 animate-spin" />,
  754. onClick: () => {},
  755. disabled: true,
  756. });
  757. } else {
  758. const activeProjects = projects
  759. .filter(p => p.status === 'active')
  760. .sort((a, b) => a.name.localeCompare(b.name));
  761. if (activeProjects.length === 0) {
  762. items.push({
  763. label: t('archives.menu.noProjectsAvailable'),
  764. icon: <FolderKanban className="w-4 h-4 opacity-50" />,
  765. onClick: () => {},
  766. disabled: true,
  767. });
  768. } else {
  769. activeProjects.forEach(p => {
  770. items.push({
  771. label: p.name,
  772. icon: <div className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: p.color || '#888' }} />,
  773. onClick: () => assignProjectMutation.mutate(p.id),
  774. disabled: archive.project_id === p.id || !canModify('archives', 'update', archive.created_by_id),
  775. });
  776. });
  777. }
  778. }
  779. return items;
  780. })(),
  781. },
  782. {
  783. label: isSelected ? t('archives.menu.deselect') : t('archives.menu.select'),
  784. icon: isSelected ? <CheckSquare className="w-4 h-4" /> : <Square className="w-4 h-4" />,
  785. onClick: () => onSelect(archive.id),
  786. },
  787. { label: '', divider: true, onClick: () => {} },
  788. {
  789. label: t('archives.menu.delete'),
  790. icon: <Trash2 className="w-4 h-4" />,
  791. onClick: () => setShowDeleteConfirm(true),
  792. danger: true,
  793. disabled: !canModify('archives', 'delete', archive.created_by_id),
  794. title: !canModify('archives', 'delete', archive.created_by_id) ? t('archives.permission.noDelete') : undefined,
  795. },
  796. ];
  797. return (
  798. <Card
  799. data-archive-id={archive.id}
  800. className={`relative flex flex-col group ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode ? 'cursor-pointer' : ''}`}
  801. style={isHighlighted ? { outline: '4px solid #facc15', outlineOffset: '2px' } : undefined}
  802. onContextMenu={handleContextMenu}
  803. onClick={selectionMode ? () => onSelect(archive.id) : undefined}
  804. >
  805. {/* Selection checkbox */}
  806. {selectionMode && (
  807. <button
  808. className="absolute top-2 left-2 z-10 p-1 rounded bg-black/50 hover:bg-black/70 transition-colors"
  809. onClick={(e) => { e.stopPropagation(); onSelect(archive.id); }}
  810. >
  811. {isSelected ? (
  812. <CheckSquare className="w-5 h-5 text-bambu-green" />
  813. ) : (
  814. <Square className="w-5 h-5 text-white" />
  815. )}
  816. </button>
  817. )}
  818. {/* Thumbnail with plate navigation */}
  819. <div
  820. className="aspect-video bg-bambu-dark relative flex-shrink-0 overflow-hidden rounded-t-xl"
  821. onMouseEnter={() => setShowPlateNav(true)}
  822. onMouseLeave={() => setShowPlateNav(false)}
  823. >
  824. {archive.thumbnail_path ? (
  825. <img
  826. src={
  827. currentPlateIndex !== null && plates.length > 0
  828. ? api.getArchivePlateThumbnail(archive.id, plates[displayPlateIndex]?.index ?? 0)
  829. : api.getArchiveThumbnail(archive.id)
  830. }
  831. alt={archive.print_name || archive.filename}
  832. className="w-full h-full object-cover"
  833. />
  834. ) : (
  835. <div className="w-full h-full flex items-center justify-center">
  836. <Image className="w-12 h-12 text-bambu-dark-tertiary" />
  837. </div>
  838. )}
  839. {/* Plate navigation - only show for multi-plate archives */}
  840. {isMultiPlate && plates.length > 1 && (
  841. <>
  842. {/* Left arrow */}
  843. <button
  844. className={`absolute left-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${
  845. isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
  846. }`}
  847. onClick={(e) => {
  848. e.stopPropagation();
  849. setCurrentPlateIndex((prev) => {
  850. const current = prev ?? 0;
  851. return current > 0 ? current - 1 : plates.length - 1;
  852. });
  853. }}
  854. title={t('archives.card.previousPlate')}
  855. >
  856. <ChevronLeft className="w-4 h-4 text-white" />
  857. </button>
  858. {/* Right arrow */}
  859. <button
  860. className={`absolute right-1 top-1/2 -translate-y-1/2 p-1 rounded-full bg-black/60 hover:bg-black/80 transition-all ${
  861. isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
  862. }`}
  863. onClick={(e) => {
  864. e.stopPropagation();
  865. setCurrentPlateIndex((prev) => {
  866. const current = prev ?? 0;
  867. return current < plates.length - 1 ? current + 1 : 0;
  868. });
  869. }}
  870. title={t('archives.card.nextPlate')}
  871. >
  872. <ChevronRight className="w-4 h-4 text-white" />
  873. </button>
  874. {/* Dots indicator */}
  875. <div
  876. 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 ${
  877. isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
  878. }`}
  879. >
  880. {plates.map((plate, idx) => (
  881. <button
  882. key={plate.index}
  883. className={`w-2 h-2 rounded-full transition-colors ${
  884. idx === displayPlateIndex ? 'bg-bambu-green' : 'bg-white/50 hover:bg-white/80'
  885. }`}
  886. onClick={(e) => {
  887. e.stopPropagation();
  888. setCurrentPlateIndex(idx);
  889. }}
  890. title={plate.name || t('archives.card.plateNumber', { index: plate.index })}
  891. />
  892. ))}
  893. </div>
  894. </>
  895. )}
  896. {/* Context menu button - visible on mobile, shows on hover for desktop */}
  897. <button
  898. className={`absolute top-2 left-2 p-1.5 rounded bg-black/50 hover:bg-black/70 transition-all ${
  899. isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
  900. } ${selectionMode ? 'left-10' : ''}`}
  901. onClick={(e) => {
  902. e.stopPropagation();
  903. const rect = e.currentTarget.getBoundingClientRect();
  904. setContextMenu({ x: rect.left, y: rect.bottom + 4 });
  905. }}
  906. title={t('archives.card.moreOptions')}
  907. >
  908. <MoreVertical className="w-5 h-5 text-white" />
  909. </button>
  910. {/* Favorite star */}
  911. <button
  912. className={`absolute top-2 right-2 p-1 rounded transition-colors ${
  913. canModify('archives', 'update', archive.created_by_id)
  914. ? 'bg-black/50 hover:bg-black/70'
  915. : 'bg-black/30 cursor-not-allowed'
  916. }`}
  917. onClick={(e) => {
  918. e.stopPropagation();
  919. if (canModify('archives', 'update', archive.created_by_id)) {
  920. favoriteMutation.mutate();
  921. }
  922. }}
  923. disabled={!canModify('archives', 'update', archive.created_by_id)}
  924. title={!canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : (archive.is_favorite ? t('archives.card.removeFromFavorites') : t('archives.card.addToFavorites'))}
  925. >
  926. <Star
  927. 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' : ''}`}
  928. />
  929. </button>
  930. {(archive.status === 'failed' || archive.status === 'aborted') && (
  931. <div className="absolute top-2 left-12 px-2 py-1 rounded text-xs bg-status-error/80 text-white">
  932. {archive.status === 'aborted' ? t('archives.card.cancelled') : t('archives.card.failed')}
  933. </div>
  934. )}
  935. {/* Duplicate badge */}
  936. {archive.duplicate_count > 0 && duplicateSequence > 0 && originalArchiveId && (
  937. <button
  938. onClick={(e) => {
  939. e.stopPropagation();
  940. onNavigateToArchive?.(originalArchiveId);
  941. }}
  942. 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"
  943. title={t('archives.viewOriginalPrint', { id: originalArchiveId })}
  944. >
  945. <Copy className="w-3 h-3" />
  946. #{duplicateSequence}
  947. </button>
  948. )}
  949. {archive.duplicate_count > 0 && duplicateSequence === 0 && (
  950. <span
  951. className="absolute top-2 right-12 px-2 py-1 rounded text-xs bg-purple-500/80 text-white flex items-center gap-1"
  952. title={`${archive.duplicate_count} reprint${archive.duplicate_count === 1 ? '' : 's'}`}
  953. >
  954. <GitBranch className="w-3 h-3" />
  955. +{archive.duplicate_count}
  956. </span>
  957. )}
  958. {/* Source 3MF badge */}
  959. {archive.source_3mf_path && (
  960. <button
  961. className="absolute bottom-2 left-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors"
  962. onClick={(e) => {
  963. e.stopPropagation();
  964. // Open source 3MF in Bambu Studio - use filename in URL for slicer compatibility
  965. const sourceName = (archive.print_name || archive.filename || 'source').replace(/\.gcode\.3mf$/i, '') + '_source';
  966. openInSlicerWithToken(archive.id, sourceName, 'source', preferredSlicer);
  967. }}
  968. title={t('archives.card.openSource3mf')}
  969. >
  970. <FileCode className="w-4 h-4 text-orange-400" />
  971. </button>
  972. )}
  973. {/* F3D badge */}
  974. {archive.f3d_path && (
  975. <button
  976. 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`}
  977. onClick={(e) => {
  978. e.stopPropagation();
  979. // Download F3D file
  980. api.downloadF3d(archive.id).catch((err) => {
  981. console.error('F3D download failed:', err);
  982. });
  983. }}
  984. title={t('archives.card.downloadF3d')}
  985. >
  986. <Box className="w-4 h-4 text-cyan-400" />
  987. </button>
  988. )}
  989. {/* 3D preview badge */}
  990. <button
  991. className="absolute bottom-2 right-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors"
  992. onClick={(e) => {
  993. e.stopPropagation();
  994. openGcodeViewer();
  995. }}
  996. title={t('archives.card.preview3d')}
  997. >
  998. <Layers className="w-4 h-4 text-white" />
  999. </button>
  1000. {/* Timelapse badge */}
  1001. {archive.timelapse_path && (
  1002. <button
  1003. className="absolute bottom-2 right-12 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors"
  1004. onClick={(e) => {
  1005. e.stopPropagation();
  1006. setShowTimelapse(true);
  1007. }}
  1008. title={t('archives.card.viewTimelapse')}
  1009. >
  1010. <Film className="w-4 h-4 text-bambu-green" />
  1011. </button>
  1012. )}
  1013. {/* Photos badge */}
  1014. {archive.photos && archive.photos.length > 0 && (
  1015. <button
  1016. 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`}
  1017. onClick={(e) => {
  1018. e.stopPropagation();
  1019. setShowPhotos(true);
  1020. }}
  1021. title={archive.photos.length === 1 ? t('archives.card.viewPhoto') : t('archives.card.viewPhotos', { count: archive.photos.length })}
  1022. >
  1023. <Camera className="w-4 h-4 text-blue-400" />
  1024. {archive.photos.length > 1 && (
  1025. <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">
  1026. {archive.photos.length}
  1027. </span>
  1028. )}
  1029. </button>
  1030. )}
  1031. {/* Linked folder badge */}
  1032. {linkedFolders && linkedFolders.length > 0 && (
  1033. <Link
  1034. to={`/files?folder=${linkedFolders[0].id}`}
  1035. className="absolute bottom-2 p-1.5 rounded bg-black/60 hover:bg-black/80 transition-colors"
  1036. onClick={(e) => e.stopPropagation()}
  1037. title={t('archives.card.openFolder', { name: linkedFolders[0].name })}
  1038. style={{ left: archive.source_3mf_path ? (archive.f3d_path ? '5.5rem' : '3rem') : (archive.f3d_path ? '3rem' : '0.5rem') }}
  1039. >
  1040. <FolderOpen className="w-4 h-4 text-yellow-400" />
  1041. </Link>
  1042. )}
  1043. </div>
  1044. <CardContent className="p-4 flex-1 flex flex-col">
  1045. {/* Archive ID */}
  1046. <p className="text-[10px] text-bambu-gray/70 mb-1">#{archive.id}</p>
  1047. {/* Title */}
  1048. <div className="flex items-center justify-between gap-2 mb-1">
  1049. <h3 className="min-w-0 font-medium text-white truncate">
  1050. {archive.print_name || archive.filename}
  1051. {archive.plate_id != null && ` — ${t('printers.plateNumber', { number: archive.plate_id })}`}
  1052. </h3>
  1053. <Button
  1054. variant="ghost"
  1055. size="sm"
  1056. className="p-1 sm:p-1.5 shrink-0"
  1057. onClick={() => setShowEdit(true)}
  1058. disabled={!canModify('archives', 'update', archive.created_by_id)}
  1059. title={!canModify('archives', 'update', archive.created_by_id) ? t('archives.card.noPermissionEdit') : t('archives.card.edit')}
  1060. >
  1061. <Pencil className="w-3 h-3 sm:w-4 sm:h-4" />
  1062. </Button>
  1063. </div>
  1064. <div className="flex items-center gap-2 mb-3 flex-wrap">
  1065. <p className="text-xs text-bambu-gray">{printerName}</p>
  1066. {(() => {
  1067. const bed = getBedTypeInfo(archive.bed_type);
  1068. return bed ? (
  1069. <img src={bed.icon} alt={bed.label} title={bed.label} className="w-4 h-4 flex-shrink-0" />
  1070. ) : null;
  1071. })()}
  1072. {/* File type badge */}
  1073. <span
  1074. className={`text-[10px] px-1.5 py-0.5 rounded font-medium ${
  1075. isSlicedFile(archive)
  1076. ? 'bg-bambu-green/20 text-bambu-green'
  1077. : 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  1078. }`}
  1079. title={
  1080. isSlicedFile(archive)
  1081. ? t('archives.card.slicedFile')
  1082. : t('archives.card.sourceFile')
  1083. }
  1084. >
  1085. {isSlicedFile(archive) ? t('archives.card.gcode') : t('archives.card.source')}
  1086. </span>
  1087. {/* File hash badge */}
  1088. {archive.content_hash && (
  1089. <span
  1090. 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"
  1091. title={`SHA256: ${archive.content_hash}`}
  1092. >
  1093. {archive.content_hash.slice(0, 8).toUpperCase()}
  1094. </span>
  1095. )}
  1096. {archive.project_name && (
  1097. <span
  1098. className="text-xs px-1.5 py-0.5 rounded-full truncate max-w-[120px]"
  1099. style={{
  1100. backgroundColor: `${projects?.find(p => p.id === archive.project_id)?.color || '#6b7280'}20`,
  1101. color: projects?.find(p => p.id === archive.project_id)?.color || '#6b7280'
  1102. }}
  1103. title={t('archives.card.project', { name: archive.project_name })}
  1104. >
  1105. {archive.project_name}
  1106. </span>
  1107. )}
  1108. {archive.run_count > 1 && (
  1109. <button
  1110. className="text-[10px] px-1.5 py-0.5 rounded font-medium bg-bambu-orange/20 text-bambu-orange hover:bg-bambu-orange/30 transition-colors cursor-pointer"
  1111. onClick={(e) => {
  1112. e.stopPropagation();
  1113. setShowPrintLog(true);
  1114. }}
  1115. title={t('archives.card.runsBadgeTitle', {
  1116. count: archive.run_count,
  1117. successful: archive.successful_run_count,
  1118. failed: archive.failed_run_count,
  1119. })}
  1120. >
  1121. {t('archives.card.runsBadge', { count: archive.run_count })}
  1122. </button>
  1123. )}
  1124. </div>
  1125. {/* Stats */}
  1126. <div className="grid grid-cols-2 gap-2 text-xs mb-4 min-h-[48px]">
  1127. {(archive.print_time_seconds || archive.actual_time_seconds) && (
  1128. <div className="flex items-center gap-1.5 text-bambu-gray" title={
  1129. archive.time_accuracy
  1130. ? `Estimated: ${formatDuration(archive.print_time_seconds || 0)}\nActual: ${formatDuration(archive.actual_time_seconds || 0)}\nAccuracy: ${archive.time_accuracy.toFixed(0)}%`
  1131. : archive.actual_time_seconds
  1132. ? `Actual: ${formatDuration(archive.actual_time_seconds)}`
  1133. : `Estimated: ${formatDuration(archive.print_time_seconds || 0)}`
  1134. }>
  1135. <Clock className="w-3 h-3" />
  1136. {formatDuration(archive.actual_time_seconds || archive.print_time_seconds || 0)}
  1137. {archive.time_accuracy && (
  1138. <span className={`text-[10px] px-1 rounded ${
  1139. archive.time_accuracy >= 95 && archive.time_accuracy <= 105
  1140. ? 'bg-bambu-green/20 text-bambu-green'
  1141. : archive.time_accuracy > 105
  1142. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400'
  1143. : 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  1144. }`}>
  1145. {archive.time_accuracy > 100 ? '+' : ''}{(archive.time_accuracy - 100).toFixed(0)}%
  1146. </span>
  1147. )}
  1148. </div>
  1149. )}
  1150. {archive.filament_used_grams && (
  1151. <div className="flex items-center gap-1.5 text-bambu-gray">
  1152. <Package className="w-3 h-3" />
  1153. {archive.filament_used_grams.toFixed(1)}g
  1154. </div>
  1155. )}
  1156. {(archive.cost != null || archive.energy_cost != null) && (
  1157. <div className="flex items-center gap-3 text-bambu-gray">
  1158. {archive.cost != null && (
  1159. <div className="flex items-center gap-1.5">
  1160. <Coins className="w-3 h-3" />
  1161. {currency}{archive.cost.toFixed(2)}
  1162. </div>
  1163. )}
  1164. {archive.energy_cost != null && (
  1165. <div className="flex items-center gap-1.5" title={`${t('stats.energyUsed')}: ${archive.energy_kwh?.toFixed(3) || 'N/A'} kWh`}>
  1166. <Zap className="w-3 h-3" />
  1167. {currency}{archive.energy_cost.toFixed(2)}
  1168. </div>
  1169. )}
  1170. </div>
  1171. )}
  1172. {(archive.layer_height || archive.total_layers) && (
  1173. <div className="flex items-center gap-1.5 text-bambu-gray">
  1174. <Layers className="w-3 h-3" />
  1175. {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>}
  1176. {archive.total_layers && archive.layer_height && <span className="text-bambu-gray/50">·</span>}
  1177. {archive.layer_height && <span>{archive.layer_height}mm</span>}
  1178. </div>
  1179. )}
  1180. {archive.object_count != null && archive.object_count > 0 && (
  1181. <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 })}>
  1182. <Box className="w-3 h-3" />
  1183. {archive.object_count === 1 ? t('archives.card.object', { count: archive.object_count }) : t('archives.card.objects', { count: archive.object_count })}
  1184. </div>
  1185. )}
  1186. {archive.sliced_for_model && (
  1187. <div className="flex items-center gap-1.5 text-bambu-gray" title={t('archives.card.slicedFor', { model: archive.sliced_for_model })}>
  1188. <Printer className="w-3 h-3" />
  1189. {archive.sliced_for_model}
  1190. </div>
  1191. )}
  1192. {archive.filament_type && (
  1193. <div className="flex items-center gap-1.5 col-span-2">
  1194. <span className="text-bambu-gray text-xs">{archive.filament_type}</span>
  1195. {archive.filament_color && (
  1196. <div className="flex items-center gap-0.5 flex-wrap">
  1197. {archive.filament_color.split(',').map((color, i) => (
  1198. <div
  1199. key={i}
  1200. className="w-3 h-3 rounded-full border border-black/20"
  1201. style={{ backgroundColor: color }}
  1202. title={color}
  1203. />
  1204. ))}
  1205. </div>
  1206. )}
  1207. </div>
  1208. )}
  1209. </div>
  1210. {/* Slicer's own saved AMS-slot pick (see "Save AMS mapping" VP setting).
  1211. Named with the printer it was resolved against: global tray IDs mean
  1212. nothing on any other printer, so a reprint only reuses these exact
  1213. spools when it targets that same printer. */}
  1214. {savedSlicerAmsMappingPrinter && (
  1215. <div
  1216. className="flex items-center gap-1.5 text-bambu-green text-xs mb-3"
  1217. title={t('archives.card.slicerAmsMappingTooltip', { printer: savedSlicerAmsMappingPrinter })}
  1218. >
  1219. <CheckCircle2 className="w-3.5 h-3.5" />
  1220. {t('archives.card.slicerAmsMapping', { printer: savedSlicerAmsMappingPrinter })}
  1221. </div>
  1222. )}
  1223. {/* Tags & Notes */}
  1224. {(archive.tags || archive.notes) && (
  1225. <div className="flex flex-wrap items-center gap-1.5 mb-3">
  1226. {archive.notes && (
  1227. <div
  1228. className="flex items-center gap-1 px-1.5 py-0.5 bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 rounded text-xs"
  1229. title={archive.notes}
  1230. >
  1231. <StickyNote className="w-3 h-3" />
  1232. </div>
  1233. )}
  1234. {archive.tags?.split(',').map((tag, i) => (
  1235. <span
  1236. key={i}
  1237. className="px-1.5 py-0.5 bg-bambu-dark-tertiary text-bambu-gray-light rounded text-xs"
  1238. >
  1239. {tag.trim()}
  1240. </span>
  1241. ))}
  1242. </div>
  1243. )}
  1244. {/* Spacer to push content to bottom */}
  1245. <div className="flex-1" />
  1246. {/* Date, Size & Creator */}
  1247. <div className="flex items-center justify-between text-xs text-bambu-gray border-t border-bambu-dark-tertiary pt-3">
  1248. <span>{formatDateTime(archive.created_at, timeFormat)}</span>
  1249. <div className="flex items-center gap-2">
  1250. {archive.created_by_username && (
  1251. <span className="flex items-center gap-1" title={t('archives.card.uploadedBy', { name: archive.created_by_username })}>
  1252. <User className="w-3 h-3" />
  1253. {archive.created_by_username}
  1254. </span>
  1255. )}
  1256. <span>{formatFileSize(archive.file_size)}</span>
  1257. </div>
  1258. </div>
  1259. {/* Actions */}
  1260. <div className="flex gap-1 mt-3">
  1261. {isSlicedFile(archive) ? (
  1262. // Sliced file - can print directly
  1263. <>
  1264. <Button
  1265. variant="primary"
  1266. size="sm"
  1267. className="flex-1 min-w-0 overflow-hidden"
  1268. onClick={() => setShowReprint(true)}
  1269. disabled={!archive.file_path || !hasPermission('queue:create') || !canModify('archives', 'reprint', archive.created_by_id)}
  1270. title={!archive.file_path ? t('archives.card.noFileForReprint') : !hasPermission('queue:create') ? t('archives.permission.noAddToQueue') : !canModify('archives', 'reprint', archive.created_by_id) ? t('archives.card.noPermissionReprint') : undefined}
  1271. >
  1272. <Printer className="w-3 h-3 flex-shrink-0" />
  1273. <span className="hidden xl:inline truncate">{t('common.print')}</span>
  1274. </Button>
  1275. <Button
  1276. variant="secondary"
  1277. size="sm"
  1278. className="min-w-0 p-1 sm:p-1.5"
  1279. onClick={() => {
  1280. const filename = archive.print_name || archive.filename || 'model';
  1281. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  1282. }}
  1283. title={t('archives.card.openInBambuStudio')}
  1284. >
  1285. <ExternalLink className="w-3 h-3 sm:w-4 sm:h-4" />
  1286. </Button>
  1287. </>
  1288. ) : (
  1289. // Source file only - "Slice" action
  1290. <Button
  1291. variant="primary"
  1292. size="sm"
  1293. className="flex-1 min-w-0 overflow-hidden"
  1294. onClick={() => {
  1295. if (useSlicerApi) {
  1296. setShowSliceModal(true);
  1297. } else {
  1298. const filename = archive.print_name || archive.filename || 'model';
  1299. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  1300. }
  1301. }}
  1302. title={useSlicerApi ? t('slice.title') : t('archives.card.openInBambuStudioToSlice')}
  1303. >
  1304. {useSlicerApi ? (
  1305. <Cog className="w-3 h-3 flex-shrink-0" />
  1306. ) : (
  1307. <ExternalLink className="w-3 h-3 flex-shrink-0" />
  1308. )}
  1309. <span className="hidden xl:inline truncate">{t('archives.card.slice')}</span>
  1310. </Button>
  1311. )}
  1312. <Button
  1313. variant="secondary"
  1314. size="sm"
  1315. className="min-w-0 p-1 sm:p-1.5"
  1316. onClick={() => {
  1317. const url = archive.external_url || archive.makerworld_url;
  1318. if (url) window.open(url, '_blank');
  1319. }}
  1320. disabled={!archive.external_url && !archive.makerworld_url}
  1321. title={
  1322. archive.external_url
  1323. ? t('archives.card.externalLink')
  1324. : archive.makerworld_url
  1325. ? t('archives.card.makerWorld', { designer: archive.designer || t('archives.card.viewProject') })
  1326. : t('archives.card.noExternalLink')
  1327. }
  1328. >
  1329. <Globe className={`w-3 h-3 sm:w-4 sm:h-4 ${!archive.external_url && !archive.makerworld_url ? 'opacity-20' : ''}`} />
  1330. </Button>
  1331. <Button
  1332. variant="secondary"
  1333. size="sm"
  1334. className="min-w-0 p-1 sm:p-1.5"
  1335. onClick={() => {
  1336. api.downloadArchive(archive.id, `${archive.print_name || archive.filename}.3mf`).catch((err) => {
  1337. console.error('Archive download failed:', err);
  1338. });
  1339. }}
  1340. title={t('archives.card.download')}
  1341. >
  1342. <Download className="w-3 h-3 sm:w-4 sm:h-4" />
  1343. </Button>
  1344. <Button
  1345. variant="ghost"
  1346. size="sm"
  1347. className="min-w-0 p-1 sm:p-1.5"
  1348. onClick={() => setShowDeleteConfirm(true)}
  1349. disabled={!canModify('archives', 'delete', archive.created_by_id)}
  1350. title={!canModify('archives', 'delete', archive.created_by_id) ? t('archives.card.noPermissionDelete') : t('archives.card.delete')}
  1351. >
  1352. <Trash2 className="w-3 h-3 sm:w-4 sm:h-4 text-red-600 dark:text-red-400" />
  1353. </Button>
  1354. </div>
  1355. </CardContent>
  1356. {/* Edit Modal */}
  1357. {showEdit && (
  1358. <EditArchiveModal
  1359. archive={archive}
  1360. onClose={() => setShowEdit(false)}
  1361. />
  1362. )}
  1363. {/* Print Log Modal — opened from the "N prints" badge or context menu (#1378) */}
  1364. {showPrintLog && (
  1365. <PrintLogModal
  1366. archiveId={archive.id}
  1367. archiveName={archive.print_name || archive.filename}
  1368. onClose={() => setShowPrintLog(false)}
  1369. />
  1370. )}
  1371. {/* Plate picker — shown only for multi-plate archives on 3D Preview click */}
  1372. {platePickerPlates && (
  1373. <PlatePickerModal
  1374. plates={platePickerPlates}
  1375. onSelect={(plateIndex) => {
  1376. setPlatePickerPlates(null);
  1377. navigate(`/gcode-viewer?archive=${archive.id}&plate=${plateIndex}`);
  1378. }}
  1379. onClose={() => setPlatePickerPlates(null)}
  1380. />
  1381. )}
  1382. {/* Reprint Modal */}
  1383. {showReprint && (
  1384. <PrintModal
  1385. mode="create"
  1386. archiveId={archive.id}
  1387. archiveName={archive.print_name || archive.filename}
  1388. onClose={() => setShowReprint(false)}
  1389. />
  1390. )}
  1391. {/* Slice Modal */}
  1392. {showSliceModal && (
  1393. <SliceModal
  1394. source={{ kind: 'archive', id: archive.id, filename: archive.print_name || archive.filename || 'model' }}
  1395. onClose={() => setShowSliceModal(false)}
  1396. />
  1397. )}
  1398. {/* Run-with-Pipeline Modal (#1425 PR B). Sources from archive — backend
  1399. reads source_3mf_path, falls back to file_path. */}
  1400. {showRunPipeline && (
  1401. <RunWithPipelineModal
  1402. source={{ kind: 'archive', id: archive.id, filename: archive.print_name || archive.filename || 'model' }}
  1403. onClose={() => setShowRunPipeline(false)}
  1404. />
  1405. )}
  1406. {/* Delete Confirmation */}
  1407. {showDeleteConfirm && (
  1408. <ConfirmModal
  1409. title={t('archives.modal.deleteArchive')}
  1410. message={t('archives.modal.deleteConfirm', { name: archive.print_name || archive.filename })}
  1411. confirmText={t('archives.modal.deleteButton')}
  1412. variant="danger"
  1413. confirmDisabled={(deleteImpactQuery.data?.currently_printing ?? 0) > 0}
  1414. onConfirm={() => {
  1415. deleteMutation.mutate(deletePurgeStats);
  1416. setShowDeleteConfirm(false);
  1417. setDeletePurgeStats(false);
  1418. }}
  1419. onCancel={() => {
  1420. setShowDeleteConfirm(false);
  1421. setDeletePurgeStats(false);
  1422. }}
  1423. >
  1424. {/* #1734: warn the user when related queue items will also be removed,
  1425. and block the action entirely if any are currently printing. */}
  1426. {(deleteImpactQuery.data?.related_queue_items ?? 0) > 0 && (
  1427. <div
  1428. className={
  1429. (deleteImpactQuery.data?.currently_printing ?? 0) > 0
  1430. ? 'text-sm text-red-600 dark:text-red-400 mb-2'
  1431. : 'text-sm text-amber-600 dark:text-amber-400 mb-2'
  1432. }
  1433. >
  1434. {(deleteImpactQuery.data?.currently_printing ?? 0) > 0
  1435. ? t('archives.modal.deleteBlockedByPrinting', {
  1436. count: deleteImpactQuery.data!.currently_printing,
  1437. })
  1438. : t('archives.modal.deleteQueueItemsWarning', {
  1439. count: deleteImpactQuery.data!.related_queue_items,
  1440. })}
  1441. </div>
  1442. )}
  1443. {/* #1343: opt-in checkbox — by default the archive is soft-deleted,
  1444. so its filament / time / cost contribution stays in Quick Stats. */}
  1445. <label className="flex items-start gap-2 cursor-pointer text-sm text-bambu-gray">
  1446. <input
  1447. type="checkbox"
  1448. className="mt-0.5 accent-red-500"
  1449. checked={deletePurgeStats}
  1450. onChange={(e) => setDeletePurgeStats(e.target.checked)}
  1451. />
  1452. <span>{t('archives.modal.deletePurgeStats')}</span>
  1453. </label>
  1454. </ConfirmModal>
  1455. )}
  1456. {/* Delete Source 3MF Confirmation */}
  1457. {showDeleteSource3mfConfirm && (
  1458. <ConfirmModal
  1459. title={t('archives.modal.removeSource3mf')}
  1460. message={t('archives.modal.removeSource3mfConfirm', { name: archive.print_name || archive.filename })}
  1461. confirmText={t('archives.modal.removeButton')}
  1462. variant="danger"
  1463. onConfirm={() => {
  1464. source3mfDeleteMutation.mutate();
  1465. setShowDeleteSource3mfConfirm(false);
  1466. }}
  1467. onCancel={() => setShowDeleteSource3mfConfirm(false)}
  1468. />
  1469. )}
  1470. {/* Delete F3D Confirmation */}
  1471. {showDeleteF3dConfirm && (
  1472. <ConfirmModal
  1473. title={t('archives.modal.removeF3d')}
  1474. message={t('archives.modal.removeF3dConfirm', { name: archive.print_name || archive.filename })}
  1475. confirmText={t('archives.modal.removeButton')}
  1476. variant="danger"
  1477. onConfirm={() => {
  1478. f3dDeleteMutation.mutate();
  1479. setShowDeleteF3dConfirm(false);
  1480. }}
  1481. onCancel={() => setShowDeleteF3dConfirm(false)}
  1482. />
  1483. )}
  1484. {/* Delete Timelapse Confirmation */}
  1485. {showDeleteTimelapseConfirm && (
  1486. <ConfirmModal
  1487. title={t('archives.modal.removeTimelapse')}
  1488. message={t('archives.modal.removeTimelapseConfirm', { name: archive.print_name || archive.filename })}
  1489. confirmText={t('archives.modal.removeButton')}
  1490. variant="danger"
  1491. onConfirm={() => {
  1492. timelapseDeleteMutation.mutate();
  1493. setShowDeleteTimelapseConfirm(false);
  1494. }}
  1495. onCancel={() => setShowDeleteTimelapseConfirm(false)}
  1496. />
  1497. )}
  1498. {/* Context Menu */}
  1499. {contextMenu && (
  1500. <ContextMenu
  1501. x={contextMenu.x}
  1502. y={contextMenu.y}
  1503. items={contextMenuItems}
  1504. onClose={() => setContextMenu(null)}
  1505. />
  1506. )}
  1507. {/* Timelapse Viewer Modal */}
  1508. {showTimelapse && archive.timelapse_path && (
  1509. <TimelapseViewer
  1510. src={api.getArchiveTimelapse(archive.id)}
  1511. title={t('archives.modal.timelapse', { name: archive.print_name || archive.filename })}
  1512. downloadFilename={`${archive.print_name || archive.filename}_timelapse.mp4`}
  1513. archiveId={archive.id}
  1514. onClose={() => setShowTimelapse(false)}
  1515. onEdit={() => {
  1516. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1517. setShowTimelapse(false); // Close viewer to reload fresh video
  1518. }}
  1519. />
  1520. )}
  1521. {/* Timelapse Selection Modal */}
  1522. {showTimelapseSelect && availableTimelapses.length > 0 && (
  1523. <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4">
  1524. <div className="bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col">
  1525. <div className="flex items-center justify-between p-4 border-b border-gray-700">
  1526. <div>
  1527. <h3 className="text-lg font-semibold text-white">{t('archives.modal.selectTimelapse')}</h3>
  1528. <p className="text-sm text-gray-400 mt-1">
  1529. {t('archives.modal.selectTimelapseDesc')}
  1530. </p>
  1531. </div>
  1532. <button
  1533. onClick={() => {
  1534. setShowTimelapseSelect(false);
  1535. setAvailableTimelapses([]);
  1536. }}
  1537. className="text-gray-400 hover:text-white p-1"
  1538. >
  1539. <X className="w-5 h-5" />
  1540. </button>
  1541. </div>
  1542. <div className="overflow-y-auto flex-1 p-2">
  1543. {availableTimelapses.map((file) => (
  1544. <button
  1545. key={file.name}
  1546. onClick={() => timelapseSelectMutation.mutate(file.name)}
  1547. disabled={timelapseSelectMutation.isPending}
  1548. className="w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors flex items-center gap-3 disabled:opacity-50"
  1549. >
  1550. <Film className="w-8 h-8 text-bambu-green flex-shrink-0" />
  1551. <div className="flex-1 min-w-0">
  1552. <p className="text-white font-medium truncate">{file.name}</p>
  1553. <p className="text-sm text-gray-400">
  1554. {formatFileSize(file.size)}
  1555. {file.mtime && ` • ${formatDateTime(file.mtime, timeFormat)}`}
  1556. </p>
  1557. </div>
  1558. </button>
  1559. ))}
  1560. </div>
  1561. <div className="p-4 border-t border-gray-700">
  1562. <Button
  1563. variant="secondary"
  1564. onClick={() => {
  1565. setShowTimelapseSelect(false);
  1566. setAvailableTimelapses([]);
  1567. }}
  1568. className="w-full"
  1569. >
  1570. Cancel
  1571. </Button>
  1572. </div>
  1573. </div>
  1574. </div>
  1575. )}
  1576. {/* QR Code Modal */}
  1577. {showQRCode && (
  1578. <QRCodeModal
  1579. archiveId={archive.id}
  1580. archiveName={archive.print_name || archive.filename}
  1581. onClose={() => setShowQRCode(false)}
  1582. />
  1583. )}
  1584. {/* Photo Gallery Modal */}
  1585. {showPhotos && archive.photos && archive.photos.length > 0 && (
  1586. <PhotoGalleryModal
  1587. archiveId={archive.id}
  1588. archiveName={archive.print_name || archive.filename}
  1589. photos={archive.photos}
  1590. onClose={() => setShowPhotos(false)}
  1591. onDelete={async (filename) => {
  1592. try {
  1593. await api.deleteArchivePhoto(archive.id, filename);
  1594. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1595. showToast(t('archives.toast.photoDeleted'));
  1596. } catch {
  1597. showToast(t('archives.toast.failedDeletePhoto'), 'error');
  1598. }
  1599. }}
  1600. />
  1601. )}
  1602. {/* Project Page Modal */}
  1603. {showProjectPage && (
  1604. <ProjectPageModal
  1605. archiveId={archive.id}
  1606. archiveName={archive.print_name || archive.filename}
  1607. onClose={() => setShowProjectPage(false)}
  1608. />
  1609. )}
  1610. {/* Hidden file input for source 3MF upload */}
  1611. <input
  1612. ref={source3mfInputRef}
  1613. type="file"
  1614. accept=".3mf"
  1615. className="hidden"
  1616. onChange={(e) => {
  1617. const file = e.target.files?.[0];
  1618. if (file) {
  1619. source3mfUploadMutation.mutate(file);
  1620. }
  1621. e.target.value = '';
  1622. }}
  1623. />
  1624. {/* Hidden file input for F3D upload */}
  1625. <input
  1626. ref={f3dInputRef}
  1627. type="file"
  1628. accept=".f3d"
  1629. className="hidden"
  1630. onChange={(e) => {
  1631. const file = e.target.files?.[0];
  1632. if (file) {
  1633. f3dUploadMutation.mutate(file);
  1634. }
  1635. e.target.value = '';
  1636. }}
  1637. />
  1638. {/* Hidden file input for timelapse upload */}
  1639. <input
  1640. ref={timelapseInputRef}
  1641. type="file"
  1642. accept=".mp4,.avi,.mkv"
  1643. className="hidden"
  1644. onChange={(e) => {
  1645. const file = e.target.files?.[0];
  1646. if (file) {
  1647. timelapseUploadMutation.mutate(file);
  1648. }
  1649. e.target.value = '';
  1650. }}
  1651. />
  1652. </Card>
  1653. );
  1654. }
  1655. function ArchiveListRow({
  1656. archive,
  1657. printerName,
  1658. isSelected,
  1659. onSelect,
  1660. selectionMode,
  1661. projects,
  1662. isHighlighted,
  1663. preferredSlicer = 'bambu_studio',
  1664. useSlicerApi = false,
  1665. t,
  1666. onNavigateToArchive,
  1667. }: {
  1668. archive: Archive;
  1669. printerName: string;
  1670. isSelected: boolean;
  1671. onSelect: (id: number) => void;
  1672. selectionMode: boolean;
  1673. projects: ProjectListItem[] | undefined;
  1674. isHighlighted?: boolean;
  1675. preferredSlicer?: SlicerType;
  1676. useSlicerApi?: boolean;
  1677. t: TFunction;
  1678. onNavigateToArchive?: (archiveId: number) => void;
  1679. }) {
  1680. const queryClient = useQueryClient();
  1681. const { showToast } = useToast();
  1682. const { hasPermission, canModify } = useAuth();
  1683. const [showEdit, setShowEdit] = useState(false);
  1684. const [showPrintLog, setShowPrintLog] = useState(false);
  1685. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1686. // #1343: opt-in "Also remove from statistics" checkbox state. Default off
  1687. // — soft delete keeps the archive's contribution to Quick Stats.
  1688. const [deletePurgeStats, setDeletePurgeStats] = useState(false);
  1689. // #1734: pre-flight count of related queue items for the delete modal.
  1690. // Same shape as the card-view sibling above.
  1691. const deleteImpactQuery = useQuery({
  1692. queryKey: ['archive', archive.id, 'delete-impact'],
  1693. queryFn: () => api.getArchiveDeleteImpact(archive.id),
  1694. enabled: showDeleteConfirm,
  1695. staleTime: 0,
  1696. });
  1697. const navigate = useNavigate();
  1698. const [showReprint, setShowReprint] = useState(false);
  1699. const [showSliceModal, setShowSliceModal] = useState(false);
  1700. const [showRunPipeline, setShowRunPipeline] = useState(false);
  1701. const [showTimelapse, setShowTimelapse] = useState(false);
  1702. const [showTimelapseSelect, setShowTimelapseSelect] = useState(false);
  1703. const [availableTimelapses, setAvailableTimelapses] = useState<Array<{ name: string; path: string; size: number; mtime: string | null }>>([]);
  1704. const [showQRCode, setShowQRCode] = useState(false);
  1705. const [showPhotos, setShowPhotos] = useState(false);
  1706. const [showProjectPage, setShowProjectPage] = useState(false);
  1707. const [showDeleteSource3mfConfirm, setShowDeleteSource3mfConfirm] = useState(false);
  1708. const [showDeleteF3dConfirm, setShowDeleteF3dConfirm] = useState(false);
  1709. const [showDeleteTimelapseConfirm, setShowDeleteTimelapseConfirm] = useState(false);
  1710. const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
  1711. const source3mfInputRef = useRef<HTMLInputElement>(null);
  1712. const f3dInputRef = useRef<HTMLInputElement>(null);
  1713. const timelapseInputRef = useRef<HTMLInputElement>(null);
  1714. const [platePickerPlates, setPlatePickerPlates] = useState<PlateMetadata[] | null>(null);
  1715. // Use pre-computed duplicate sequence and original archive ID from list response
  1716. const duplicateSequence = archive.duplicate_sequence ?? 0;
  1717. const originalArchiveId = archive.original_archive_id ?? null;
  1718. // 3D Preview click handler. Multi-plate archives show the plate picker
  1719. // first; single-plate archives navigate straight into the viewer.
  1720. const openGcodeViewer = async () => {
  1721. try {
  1722. const resp = await api.getArchivePlates(archive.id);
  1723. if (resp.is_multi_plate && resp.plates.length > 1) {
  1724. setPlatePickerPlates(resp.plates);
  1725. return;
  1726. }
  1727. } catch {
  1728. // Swallow — fall through to navigate on the first-plate default.
  1729. }
  1730. navigate(`/gcode-viewer?archive=${archive.id}`);
  1731. };
  1732. const timelapseDeleteMutation = useMutation({
  1733. mutationFn: () => api.deleteArchiveTimelapse(archive.id),
  1734. onSuccess: () => {
  1735. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1736. showToast(t('archives.toast.timelapseRemoved'));
  1737. },
  1738. onError: (error: Error) => {
  1739. showToast(error.message || t('archives.toast.failedRemoveTimelapse'), 'error');
  1740. },
  1741. });
  1742. const timelapseUploadMutation = useMutation({
  1743. mutationFn: (file: File) => api.uploadArchiveTimelapse(archive.id, file),
  1744. onSuccess: (data) => {
  1745. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1746. showToast(t('archives.toast.timelapseUploaded', { filename: data.filename }));
  1747. },
  1748. onError: (error: Error) => {
  1749. showToast(error.message || t('archives.toast.failedUploadTimelapse'), 'error');
  1750. },
  1751. });
  1752. const source3mfUploadMutation = useMutation({
  1753. mutationFn: (file: File) => api.uploadSource3mf(archive.id, file),
  1754. onSuccess: (data) => {
  1755. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1756. showToast(t('archives.toast.source3mfAttached', { filename: data.filename }));
  1757. },
  1758. onError: (error: Error) => {
  1759. showToast(error.message || t('archives.toast.failedUploadSource3mf'), 'error');
  1760. },
  1761. });
  1762. const source3mfDeleteMutation = useMutation({
  1763. mutationFn: () => api.deleteSource3mf(archive.id),
  1764. onSuccess: () => {
  1765. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1766. showToast(t('archives.toast.source3mfRemoved'));
  1767. },
  1768. onError: (error: Error) => {
  1769. showToast(error.message || t('archives.toast.failedRemoveSource3mf'), 'error');
  1770. },
  1771. });
  1772. const f3dUploadMutation = useMutation({
  1773. mutationFn: (file: File) => api.uploadF3d(archive.id, file),
  1774. onSuccess: (data) => {
  1775. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1776. showToast(t('archives.toast.f3dAttached', { filename: data.filename }));
  1777. },
  1778. onError: (error: Error) => {
  1779. showToast(error.message || t('archives.toast.failedUploadF3d'), 'error');
  1780. },
  1781. });
  1782. const f3dDeleteMutation = useMutation({
  1783. mutationFn: () => api.deleteF3d(archive.id),
  1784. onSuccess: () => {
  1785. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1786. showToast(t('archives.toast.f3dRemoved'));
  1787. },
  1788. onError: (error: Error) => {
  1789. showToast(error.message || t('archives.toast.failedRemoveF3d'), 'error');
  1790. },
  1791. });
  1792. const timelapseScanMutation = useMutation({
  1793. mutationFn: () => api.scanArchiveTimelapse(archive.id),
  1794. onSuccess: (data) => {
  1795. if (data.status === 'attached') {
  1796. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1797. showToast(t('archives.toast.timelapseAttached', { filename: data.filename }));
  1798. } else if (data.status === 'exists') {
  1799. showToast(t('archives.toast.timelapseAlreadyAttached'));
  1800. } else if (data.status === 'not_found' && data.available_files && data.available_files.length > 0) {
  1801. setAvailableTimelapses(data.available_files);
  1802. setShowTimelapseSelect(true);
  1803. } else {
  1804. showToast(data.message || t('archives.toast.noMatchingTimelapse'), 'warning');
  1805. }
  1806. },
  1807. onError: (error: Error) => {
  1808. showToast(error.message || t('archives.toast.failedScanTimelapse'), 'error');
  1809. },
  1810. });
  1811. const timelapseSelectMutation = useMutation({
  1812. mutationFn: (filename: string) => api.selectArchiveTimelapse(archive.id, filename),
  1813. onSuccess: (data) => {
  1814. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1815. showToast(t('archives.toast.timelapseAttached', { filename: data.filename }));
  1816. setShowTimelapseSelect(false);
  1817. setAvailableTimelapses([]);
  1818. },
  1819. onError: (error: Error) => {
  1820. showToast(error.message || t('archives.toast.failedAttachTimelapse'), 'error');
  1821. },
  1822. });
  1823. const deleteMutation = useMutation({
  1824. mutationFn: (purgeStats: boolean) => api.deleteArchive(archive.id, purgeStats),
  1825. onSuccess: () => {
  1826. // A deleted archive leaves its project too, so the project views have to
  1827. // be refreshed alongside the archive list (#2731).
  1828. invalidateArchiveAndProjectViews(queryClient);
  1829. showToast(t('archives.toast.archiveDeleted'));
  1830. },
  1831. onError: () => {
  1832. showToast(t('archives.toast.failedDeleteArchive'), 'error');
  1833. },
  1834. });
  1835. const favoriteMutation = useMutation({
  1836. mutationFn: () => api.toggleFavorite(archive.id),
  1837. onSuccess: (data) => {
  1838. queryClient.invalidateQueries({ queryKey: ['archives'] });
  1839. showToast(data.is_favorite ? t('archives.toast.addedToFavorites') : t('archives.toast.removedFromFavorites'));
  1840. },
  1841. });
  1842. // Query for linked folders
  1843. const { data: linkedFolders } = useQuery({
  1844. queryKey: ['archive-folders', archive.id],
  1845. queryFn: () => api.getLibraryFoldersByArchive(archive.id),
  1846. });
  1847. const assignProjectMutation = useMutation({
  1848. mutationFn: (projectId: number | null) => api.updateArchive(archive.id, { project_id: projectId }),
  1849. onSuccess: () => {
  1850. invalidateArchiveAndProjectViews(queryClient);
  1851. showToast(t('archives.toast.projectUpdated'));
  1852. },
  1853. onError: () => {
  1854. showToast(t('archives.toast.failedUpdateProject'), 'error');
  1855. },
  1856. });
  1857. const handleContextMenu = (e: React.MouseEvent) => {
  1858. e.preventDefault();
  1859. setContextMenu({ x: e.clientX, y: e.clientY });
  1860. };
  1861. const isGcodeFile = isSlicedFile(archive);
  1862. const contextMenuItems: ContextMenuItem[] = [
  1863. ...(isGcodeFile ? [
  1864. {
  1865. label: t('common.print'),
  1866. icon: <Printer className="w-4 h-4" />,
  1867. onClick: () => setShowReprint(true),
  1868. disabled: !archive.file_path || !hasPermission('queue:create') || !canModify('archives', 'reprint', archive.created_by_id),
  1869. title: !archive.file_path
  1870. ? t('archives.card.noFileForReprint')
  1871. : !hasPermission('queue:create')
  1872. ? t('archives.permission.noAddToQueue')
  1873. : !canModify('archives', 'reprint', archive.created_by_id)
  1874. ? t('archives.permission.noReprint')
  1875. : undefined,
  1876. },
  1877. {
  1878. label: t('archives.menu.openInBambuStudio'),
  1879. icon: <ExternalLink className="w-4 h-4" />,
  1880. onClick: () => {
  1881. const filename = archive.print_name || archive.filename || 'model';
  1882. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  1883. },
  1884. disabled: !archive.file_path,
  1885. title: !archive.file_path ? t('archives.card.noFileForReprint') : undefined,
  1886. },
  1887. ] : [
  1888. {
  1889. label: t('archives.menu.slice'),
  1890. icon: useSlicerApi ? <Cog className="w-4 h-4" /> : <ExternalLink className="w-4 h-4" />,
  1891. onClick: () => {
  1892. if (useSlicerApi) {
  1893. setShowSliceModal(true);
  1894. } else {
  1895. const filename = archive.print_name || archive.filename || 'model';
  1896. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  1897. }
  1898. },
  1899. },
  1900. // Run-with-pipeline (#1425 PR B follow-up). Sources from archive's
  1901. // source 3MF (or file_path fallback). Only when slicer-api is on.
  1902. ...(useSlicerApi
  1903. ? [{
  1904. label: t('library.runWithPipeline.actionLabel'),
  1905. icon: <Play className="w-4 h-4" />,
  1906. onClick: () => setShowRunPipeline(true),
  1907. disabled: !hasPermission('pipelines:run'),
  1908. title: !hasPermission('pipelines:run')
  1909. ? t('library.runWithPipeline.noPermission')
  1910. : undefined,
  1911. }]
  1912. : []),
  1913. ]),
  1914. {
  1915. label: archive.external_url ? t('archives.menu.externalLink') : t('archives.menu.viewOnMakerWorld'),
  1916. icon: <Globe className="w-4 h-4" />,
  1917. onClick: () => {
  1918. const url = archive.external_url || archive.makerworld_url;
  1919. if (url) window.open(url, '_blank');
  1920. },
  1921. disabled: !archive.external_url && !archive.makerworld_url,
  1922. },
  1923. { label: '', divider: true, onClick: () => {} },
  1924. {
  1925. label: t('archives.menu.preview3d'),
  1926. icon: <Box className="w-4 h-4" />,
  1927. onClick: () => { openGcodeViewer(); },
  1928. },
  1929. {
  1930. label: t('archives.menu.viewTimelapse'),
  1931. icon: <Film className="w-4 h-4" />,
  1932. onClick: () => setShowTimelapse(true),
  1933. disabled: !archive.timelapse_path,
  1934. },
  1935. {
  1936. label: t('archives.menu.scanForTimelapse'),
  1937. icon: <ScanSearch className="w-4 h-4" />,
  1938. onClick: () => timelapseScanMutation.mutate(),
  1939. disabled: !archive.printer_id || !!archive.timelapse_path || timelapseScanMutation.isPending || !canModify('archives', 'update', archive.created_by_id),
  1940. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1941. },
  1942. {
  1943. label: t('archives.menu.uploadTimelapse'),
  1944. icon: <Upload className="w-4 h-4" />,
  1945. onClick: () => timelapseInputRef.current?.click(),
  1946. disabled: !!archive.timelapse_path || !canModify('archives', 'update', archive.created_by_id),
  1947. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1948. },
  1949. ...(archive.timelapse_path ? [{
  1950. label: t('archives.menu.removeTimelapse'),
  1951. icon: <Trash2 className="w-4 h-4" />,
  1952. onClick: () => setShowDeleteTimelapseConfirm(true),
  1953. danger: true,
  1954. disabled: !canModify('archives', 'update', archive.created_by_id),
  1955. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1956. }] : []),
  1957. { label: '', divider: true, onClick: () => {} },
  1958. {
  1959. label: archive.source_3mf_path ? t('archives.menu.downloadSource3mf') : t('archives.menu.uploadSource3mf'),
  1960. icon: <FileCode className="w-4 h-4" />,
  1961. onClick: () => {
  1962. if (archive.source_3mf_path) {
  1963. api.downloadSource3mf(archive.id).catch((err) => {
  1964. console.error('Source 3MF download failed:', err);
  1965. });
  1966. } else {
  1967. source3mfInputRef.current?.click();
  1968. }
  1969. },
  1970. disabled: !archive.source_3mf_path && !canModify('archives', 'update', archive.created_by_id),
  1971. title: !archive.source_3mf_path && !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUploadFiles') : undefined,
  1972. },
  1973. ...(archive.source_3mf_path ? [{
  1974. label: t('archives.menu.replaceSource3mf'),
  1975. icon: <Upload className="w-4 h-4" />,
  1976. onClick: () => source3mfInputRef.current?.click(),
  1977. disabled: !canModify('archives', 'update', archive.created_by_id),
  1978. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1979. },
  1980. {
  1981. label: t('archives.menu.removeSource3mf'),
  1982. icon: <Trash2 className="w-4 h-4" />,
  1983. onClick: () => setShowDeleteSource3mfConfirm(true),
  1984. danger: true,
  1985. disabled: !canModify('archives', 'update', archive.created_by_id),
  1986. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1987. }] : []),
  1988. {
  1989. label: archive.f3d_path ? t('archives.menu.replaceF3d') : t('archives.menu.uploadF3d'),
  1990. icon: <Box className="w-4 h-4" />,
  1991. onClick: () => f3dInputRef.current?.click(),
  1992. disabled: !canModify('archives', 'update', archive.created_by_id),
  1993. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  1994. },
  1995. ...(archive.f3d_path ? [{
  1996. label: t('archives.menu.downloadF3d'),
  1997. icon: <Download className="w-4 h-4" />,
  1998. onClick: () => {
  1999. api.downloadF3d(archive.id).catch((err) => {
  2000. console.error('F3D download failed:', err);
  2001. });
  2002. },
  2003. },
  2004. {
  2005. label: t('archives.menu.removeF3d'),
  2006. icon: <Trash2 className="w-4 h-4" />,
  2007. onClick: () => setShowDeleteF3dConfirm(true),
  2008. danger: true,
  2009. disabled: !canModify('archives', 'update', archive.created_by_id),
  2010. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  2011. }] : []),
  2012. { label: '', divider: true, onClick: () => {} },
  2013. {
  2014. label: t('archives.menu.download'),
  2015. icon: <Download className="w-4 h-4" />,
  2016. onClick: () => {
  2017. api.downloadArchive(archive.id, `${archive.print_name || archive.filename}.3mf`).catch((err) => {
  2018. console.error('Archive download failed:', err);
  2019. });
  2020. },
  2021. disabled: !hasPermission('archives:read'),
  2022. title: !hasPermission('archives:read') ? t('archives.permission.noDownload') : undefined,
  2023. },
  2024. {
  2025. label: t('archives.menu.copyDownloadLink'),
  2026. icon: <Copy className="w-4 h-4" />,
  2027. onClick: () => {
  2028. const url = `${window.location.origin}${api.getArchiveDownload(archive.id)}`;
  2029. navigator.clipboard.writeText(url).then(() => {
  2030. showToast(t('archives.toast.linkCopied'));
  2031. }).catch(() => {
  2032. showToast(t('archives.toast.failedCopyLink'), 'error');
  2033. });
  2034. },
  2035. disabled: !hasPermission('archives:read'),
  2036. title: !hasPermission('archives:read') ? t('archives.permission.noCopyLink') : undefined,
  2037. },
  2038. {
  2039. label: t('archives.menu.qrCode'),
  2040. icon: <QrCode className="w-4 h-4" />,
  2041. onClick: () => setShowQRCode(true),
  2042. },
  2043. {
  2044. label: archive.photos?.length ? t('archives.menu.viewPhotosCount', { count: archive.photos.length }) : t('archives.menu.viewPhotos'),
  2045. icon: <Camera className="w-4 h-4" />,
  2046. onClick: () => setShowPhotos(true),
  2047. disabled: !archive.photos?.length,
  2048. },
  2049. {
  2050. label: t('archives.menu.projectPage'),
  2051. icon: <FileText className="w-4 h-4" />,
  2052. onClick: () => setShowProjectPage(true),
  2053. },
  2054. { label: '', divider: true, onClick: () => {} },
  2055. {
  2056. label: archive.is_favorite ? t('archives.menu.removeFromFavorites') : t('archives.menu.addToFavorites'),
  2057. icon: <Star className={`w-4 h-4 ${archive.is_favorite ? 'fill-yellow-400 text-yellow-400' : ''}`} />,
  2058. onClick: () => favoriteMutation.mutate(),
  2059. disabled: !canModify('archives', 'update', archive.created_by_id),
  2060. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  2061. },
  2062. {
  2063. label: t('archives.menu.edit'),
  2064. icon: <Pencil className="w-4 h-4" />,
  2065. onClick: () => setShowEdit(true),
  2066. disabled: !canModify('archives', 'update', archive.created_by_id),
  2067. title: !canModify('archives', 'update', archive.created_by_id) ? t('archives.permission.noUpdateArchives') : undefined,
  2068. },
  2069. {
  2070. label: t('archives.menu.printLog'),
  2071. icon: <History className="w-4 h-4" />,
  2072. onClick: () => setShowPrintLog(true),
  2073. },
  2074. ...(archive.project_id && archive.project_name ? [{
  2075. label: t('archives.menu.goToProject', { name: archive.project_name }),
  2076. icon: <FolderKanban className="w-4 h-4 text-bambu-green" />,
  2077. onClick: () => window.location.href = '/projects',
  2078. }] : []),
  2079. {
  2080. label: t('archives.menu.addToProject'),
  2081. icon: <FolderKanban className="w-4 h-4" />,
  2082. onClick: () => {},
  2083. submenuSearchPlaceholder: (projects?.filter(p => p.status === 'active').length ?? 0) > 5
  2084. ? t('archives.menu.searchProjects')
  2085. : undefined,
  2086. submenu: (() => {
  2087. const items: ContextMenuItem[] = [];
  2088. if (archive.project_id) {
  2089. items.push({
  2090. label: t('archives.menu.removeFromProject'),
  2091. icon: <X className="w-4 h-4" />,
  2092. onClick: () => assignProjectMutation.mutate(null),
  2093. });
  2094. }
  2095. if (!projects) {
  2096. items.push({
  2097. label: t('archives.menu.loading'),
  2098. icon: <Loader2 className="w-4 h-4 animate-spin" />,
  2099. onClick: () => {},
  2100. disabled: true,
  2101. });
  2102. } else {
  2103. const activeProjects = projects
  2104. .filter(p => p.status === 'active')
  2105. .sort((a, b) => a.name.localeCompare(b.name));
  2106. if (activeProjects.length === 0) {
  2107. items.push({
  2108. label: t('archives.menu.noProjectsAvailable'),
  2109. icon: <FolderKanban className="w-4 h-4 opacity-50" />,
  2110. onClick: () => {},
  2111. disabled: true,
  2112. });
  2113. } else {
  2114. activeProjects.forEach(p => {
  2115. items.push({
  2116. label: p.name,
  2117. icon: <div className="w-3 h-3 rounded-full flex-shrink-0" style={{ backgroundColor: p.color || '#888' }} />,
  2118. onClick: () => assignProjectMutation.mutate(p.id),
  2119. disabled: archive.project_id === p.id,
  2120. });
  2121. });
  2122. }
  2123. }
  2124. return items;
  2125. })(),
  2126. },
  2127. {
  2128. label: isSelected ? t('archives.menu.deselect') : t('archives.menu.select'),
  2129. icon: isSelected ? <CheckSquare className="w-4 h-4" /> : <Square className="w-4 h-4" />,
  2130. onClick: () => onSelect(archive.id),
  2131. },
  2132. { label: '', divider: true, onClick: () => {} },
  2133. {
  2134. label: t('archives.menu.delete'),
  2135. icon: <Trash2 className="w-4 h-4" />,
  2136. onClick: () => setShowDeleteConfirm(true),
  2137. danger: true,
  2138. disabled: !canModify('archives', 'delete', archive.created_by_id),
  2139. title: !canModify('archives', 'delete', archive.created_by_id) ? t('archives.permission.noDelete') : undefined,
  2140. },
  2141. ];
  2142. return (
  2143. <>
  2144. <div
  2145. data-archive-id={archive.id}
  2146. className={`grid grid-cols-12 gap-4 px-4 py-3 items-center hover:bg-bambu-dark-tertiary/30 ${
  2147. isSelected ? 'bg-bambu-green/10' : ''
  2148. }`}
  2149. style={isHighlighted ? { outline: '4px solid #facc15', outlineOffset: '-4px' } : undefined}
  2150. onContextMenu={handleContextMenu}
  2151. >
  2152. <div className="col-span-1 flex items-center gap-2">
  2153. {selectionMode && (
  2154. <button onClick={() => onSelect(archive.id)}>
  2155. {isSelected ? (
  2156. <CheckSquare className="w-4 h-4 text-bambu-green" />
  2157. ) : (
  2158. <Square className="w-4 h-4 text-bambu-gray" />
  2159. )}
  2160. </button>
  2161. )}
  2162. {archive.thumbnail_path ? (
  2163. <img
  2164. src={api.getArchiveThumbnail(archive.id)}
  2165. alt=""
  2166. className="w-10 h-10 object-cover rounded"
  2167. />
  2168. ) : (
  2169. <div className="w-10 h-10 bg-bambu-dark rounded flex items-center justify-center">
  2170. <Image className="w-5 h-5 text-bambu-dark-tertiary" />
  2171. </div>
  2172. )}
  2173. </div>
  2174. <div className="col-span-4">
  2175. <div className="flex items-center gap-2">
  2176. <p className="text-white text-sm truncate">{archive.print_name || archive.filename}</p>
  2177. {(archive.status === 'failed' || archive.status === 'aborted') && (
  2178. <span className="px-1.5 py-0.5 rounded text-[10px] leading-tight bg-status-error/80 text-white flex-shrink-0">
  2179. {archive.status === 'aborted' ? t('archives.card.cancelled') : t('archives.card.failed')}
  2180. </span>
  2181. )}
  2182. {archive.duplicate_count > 0 && duplicateSequence > 0 && originalArchiveId && (
  2183. <button
  2184. onClick={(e) => {
  2185. e.stopPropagation();
  2186. onNavigateToArchive?.(originalArchiveId);
  2187. }}
  2188. 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"
  2189. title={t('archives.viewOriginalPrint', { id: originalArchiveId })}
  2190. >
  2191. <Copy className="w-3 h-3" />
  2192. #{duplicateSequence}
  2193. </button>
  2194. )}
  2195. {archive.duplicate_count > 0 && duplicateSequence === 0 && (
  2196. <span
  2197. 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"
  2198. title={`${archive.duplicate_count} reprint${archive.duplicate_count === 1 ? '' : 's'}`}
  2199. >
  2200. <GitBranch className="w-3 h-3" />
  2201. +{archive.duplicate_count}
  2202. </span>
  2203. )}
  2204. {archive.timelapse_path && (
  2205. <span title={t('archives.list.hasTimelapse')}>
  2206. <Film className="w-3.5 h-3.5 text-bambu-green flex-shrink-0" />
  2207. </span>
  2208. )}
  2209. {linkedFolders && linkedFolders.length > 0 && (
  2210. <Link
  2211. to={`/files?folder=${linkedFolders[0].id}`}
  2212. className="flex-shrink-0"
  2213. title={t('archives.card.openFolder', { name: linkedFolders[0].name })}
  2214. onClick={(e) => e.stopPropagation()}
  2215. >
  2216. <FolderOpen className="w-3.5 h-3.5 text-yellow-600 dark:text-yellow-400" />
  2217. </Link>
  2218. )}
  2219. </div>
  2220. {(archive.filament_type || archive.sliced_for_model) && (
  2221. <div className="flex items-center gap-1.5 mt-0.5">
  2222. {archive.sliced_for_model && (
  2223. <span className="text-xs text-bambu-gray flex items-center gap-1" title={t('archives.card.slicedFor', { model: archive.sliced_for_model })}>
  2224. <Printer className="w-2.5 h-2.5" />
  2225. {archive.sliced_for_model}
  2226. </span>
  2227. )}
  2228. {(() => {
  2229. const bed = getBedTypeInfo(archive.bed_type);
  2230. return bed ? (
  2231. <img src={bed.icon} alt={bed.label} title={bed.label} className="w-3.5 h-3.5 flex-shrink-0" />
  2232. ) : null;
  2233. })()}
  2234. {archive.sliced_for_model && archive.filament_type && (
  2235. <span className="text-bambu-gray/50">·</span>
  2236. )}
  2237. {archive.filament_type && (
  2238. <span className="text-xs text-bambu-gray">{archive.filament_type}</span>
  2239. )}
  2240. {archive.filament_color && (
  2241. <div className="flex items-center gap-0.5 flex-wrap">
  2242. {archive.filament_color.split(',').map((color, i) => (
  2243. <div
  2244. key={i}
  2245. className="w-2.5 h-2.5 rounded-full border border-black/20"
  2246. style={{ backgroundColor: color }}
  2247. title={color}
  2248. />
  2249. ))}
  2250. </div>
  2251. )}
  2252. </div>
  2253. )}
  2254. </div>
  2255. <div className="col-span-2 text-sm text-bambu-gray truncate">
  2256. {printerName}
  2257. </div>
  2258. <div className="col-span-2 text-sm text-bambu-gray">
  2259. <div>{formatDateOnly(archive.created_at)}</div>
  2260. {archive.created_by_username && (
  2261. <div className="flex items-center gap-1 text-xs opacity-75" title={t('archives.card.uploadedBy', { name: archive.created_by_username })}>
  2262. <User className="w-3 h-3" />
  2263. {archive.created_by_username}
  2264. </div>
  2265. )}
  2266. </div>
  2267. <div className="col-span-1 text-sm text-bambu-gray">
  2268. {formatFileSize(archive.file_size)}
  2269. </div>
  2270. <div className="col-span-2 flex justify-end gap-1">
  2271. {isSlicedFile(archive) && (
  2272. <Button
  2273. variant="ghost"
  2274. size="sm"
  2275. onClick={() => setShowReprint(true)}
  2276. disabled={!archive.file_path || !hasPermission('queue:create') || !canModify('archives', 'reprint', archive.created_by_id)}
  2277. title={!archive.file_path ? t('archives.card.noFileForReprint') : !hasPermission('queue:create') ? t('archives.permission.noAddToQueue') : !canModify('archives', 'reprint', archive.created_by_id) ? t('archives.card.noPermissionReprint') : t('common.print')}
  2278. className="text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10"
  2279. >
  2280. <Play className="w-4 h-4" />
  2281. </Button>
  2282. )}
  2283. <Button
  2284. variant="ghost"
  2285. size="sm"
  2286. onClick={() => {
  2287. const filename = archive.print_name || archive.filename || 'model';
  2288. openInSlicerWithToken(archive.id, filename, 'file', preferredSlicer);
  2289. }}
  2290. title={t('archives.card.openInBambuStudio')}
  2291. >
  2292. <ExternalLink className="w-4 h-4" />
  2293. </Button>
  2294. {(archive.external_url || archive.makerworld_url) && (
  2295. <Button
  2296. variant="ghost"
  2297. size="sm"
  2298. onClick={() => window.open((archive.external_url || archive.makerworld_url)!, '_blank')}
  2299. title={archive.external_url ? t('archives.card.externalLink') : 'MakerWorld'}
  2300. >
  2301. <Globe className="w-4 h-4" />
  2302. </Button>
  2303. )}
  2304. <Button
  2305. variant="ghost"
  2306. size="sm"
  2307. onClick={() => {
  2308. api.downloadArchive(archive.id, `${archive.print_name || archive.filename}.3mf`).catch((err) => {
  2309. console.error('Archive download failed:', err);
  2310. });
  2311. }}
  2312. title={t('archives.card.download')}
  2313. >
  2314. <Download className="w-4 h-4" />
  2315. </Button>
  2316. <Button
  2317. variant="ghost"
  2318. size="sm"
  2319. onClick={() => setShowEdit(true)}
  2320. disabled={!canModify('archives', 'update', archive.created_by_id)}
  2321. title={!canModify('archives', 'update', archive.created_by_id) ? t('archives.card.noPermissionEdit') : t('archives.card.edit')}
  2322. >
  2323. <Pencil className="w-4 h-4" />
  2324. </Button>
  2325. <Button
  2326. variant="ghost"
  2327. size="sm"
  2328. onClick={() => setShowDeleteConfirm(true)}
  2329. disabled={!canModify('archives', 'delete', archive.created_by_id)}
  2330. title={!canModify('archives', 'delete', archive.created_by_id) ? t('archives.card.noPermissionDelete') : t('archives.card.delete')}
  2331. >
  2332. <Trash2 className="w-4 h-4 text-red-600 dark:text-red-400" />
  2333. </Button>
  2334. <Button
  2335. variant="ghost"
  2336. size="sm"
  2337. onClick={(e) => {
  2338. const rect = e.currentTarget.getBoundingClientRect();
  2339. setContextMenu({ x: rect.left, y: rect.bottom + 4 });
  2340. }}
  2341. title={t('archives.card.moreOptions')}
  2342. >
  2343. <MoreVertical className="w-4 h-4" />
  2344. </Button>
  2345. </div>
  2346. </div>
  2347. {/* Edit Modal */}
  2348. {showEdit && (
  2349. <EditArchiveModal
  2350. archive={archive}
  2351. onClose={() => setShowEdit(false)}
  2352. />
  2353. )}
  2354. {/* Print Log Modal — opened from the "N prints" badge or context menu (#1378) */}
  2355. {showPrintLog && (
  2356. <PrintLogModal
  2357. archiveId={archive.id}
  2358. archiveName={archive.print_name || archive.filename}
  2359. onClose={() => setShowPrintLog(false)}
  2360. />
  2361. )}
  2362. {/* Plate picker — shown only for multi-plate archives on 3D Preview click */}
  2363. {platePickerPlates && (
  2364. <PlatePickerModal
  2365. plates={platePickerPlates}
  2366. onSelect={(plateIndex) => {
  2367. setPlatePickerPlates(null);
  2368. navigate(`/gcode-viewer?archive=${archive.id}&plate=${plateIndex}`);
  2369. }}
  2370. onClose={() => setPlatePickerPlates(null)}
  2371. />
  2372. )}
  2373. {/* Reprint Modal */}
  2374. {showReprint && (
  2375. <PrintModal
  2376. mode="create"
  2377. archiveId={archive.id}
  2378. archiveName={archive.print_name || archive.filename}
  2379. onClose={() => setShowReprint(false)}
  2380. />
  2381. )}
  2382. {/* Slice Modal */}
  2383. {showSliceModal && (
  2384. <SliceModal
  2385. source={{ kind: 'archive', id: archive.id, filename: archive.print_name || archive.filename || 'model' }}
  2386. onClose={() => setShowSliceModal(false)}
  2387. />
  2388. )}
  2389. {/* Run-with-Pipeline Modal (#1425 PR B). Sources from archive — backend
  2390. reads source_3mf_path, falls back to file_path. */}
  2391. {showRunPipeline && (
  2392. <RunWithPipelineModal
  2393. source={{ kind: 'archive', id: archive.id, filename: archive.print_name || archive.filename || 'model' }}
  2394. onClose={() => setShowRunPipeline(false)}
  2395. />
  2396. )}
  2397. {/* Delete Confirmation */}
  2398. {showDeleteConfirm && (
  2399. <ConfirmModal
  2400. title={t('archives.modal.deleteArchive')}
  2401. message={t('archives.modal.deleteConfirm', { name: archive.print_name || archive.filename })}
  2402. confirmText={t('archives.modal.deleteButton')}
  2403. variant="danger"
  2404. confirmDisabled={(deleteImpactQuery.data?.currently_printing ?? 0) > 0}
  2405. onConfirm={() => {
  2406. deleteMutation.mutate(deletePurgeStats);
  2407. setShowDeleteConfirm(false);
  2408. setDeletePurgeStats(false);
  2409. }}
  2410. onCancel={() => {
  2411. setShowDeleteConfirm(false);
  2412. setDeletePurgeStats(false);
  2413. }}
  2414. >
  2415. {/* #1734: warn the user when related queue items will also be removed,
  2416. and block the action entirely if any are currently printing. */}
  2417. {(deleteImpactQuery.data?.related_queue_items ?? 0) > 0 && (
  2418. <div
  2419. className={
  2420. (deleteImpactQuery.data?.currently_printing ?? 0) > 0
  2421. ? 'text-sm text-red-600 dark:text-red-400 mb-2'
  2422. : 'text-sm text-amber-600 dark:text-amber-400 mb-2'
  2423. }
  2424. >
  2425. {(deleteImpactQuery.data?.currently_printing ?? 0) > 0
  2426. ? t('archives.modal.deleteBlockedByPrinting', {
  2427. count: deleteImpactQuery.data!.currently_printing,
  2428. })
  2429. : t('archives.modal.deleteQueueItemsWarning', {
  2430. count: deleteImpactQuery.data!.related_queue_items,
  2431. })}
  2432. </div>
  2433. )}
  2434. {/* #1343: opt-in checkbox — by default the archive is soft-deleted,
  2435. so its filament / time / cost contribution stays in Quick Stats. */}
  2436. <label className="flex items-start gap-2 cursor-pointer text-sm text-bambu-gray">
  2437. <input
  2438. type="checkbox"
  2439. className="mt-0.5 accent-red-500"
  2440. checked={deletePurgeStats}
  2441. onChange={(e) => setDeletePurgeStats(e.target.checked)}
  2442. />
  2443. <span>{t('archives.modal.deletePurgeStats')}</span>
  2444. </label>
  2445. </ConfirmModal>
  2446. )}
  2447. {/* Delete Source 3MF Confirmation */}
  2448. {showDeleteSource3mfConfirm && (
  2449. <ConfirmModal
  2450. title={t('archives.modal.removeSource3mf')}
  2451. message={t('archives.modal.removeSource3mfConfirm', { name: archive.print_name || archive.filename })}
  2452. confirmText={t('archives.modal.removeButton')}
  2453. variant="danger"
  2454. onConfirm={() => {
  2455. source3mfDeleteMutation.mutate();
  2456. setShowDeleteSource3mfConfirm(false);
  2457. }}
  2458. onCancel={() => setShowDeleteSource3mfConfirm(false)}
  2459. />
  2460. )}
  2461. {/* Delete F3D Confirmation */}
  2462. {showDeleteF3dConfirm && (
  2463. <ConfirmModal
  2464. title={t('archives.modal.removeF3d')}
  2465. message={t('archives.modal.removeF3dConfirm', { name: archive.print_name || archive.filename })}
  2466. confirmText={t('archives.modal.removeButton')}
  2467. variant="danger"
  2468. onConfirm={() => {
  2469. f3dDeleteMutation.mutate();
  2470. setShowDeleteF3dConfirm(false);
  2471. }}
  2472. onCancel={() => setShowDeleteF3dConfirm(false)}
  2473. />
  2474. )}
  2475. {/* Delete Timelapse Confirmation */}
  2476. {showDeleteTimelapseConfirm && (
  2477. <ConfirmModal
  2478. title={t('archives.modal.removeTimelapse')}
  2479. message={t('archives.modal.removeTimelapseConfirm', { name: archive.print_name || archive.filename })}
  2480. confirmText={t('archives.modal.removeButton')}
  2481. variant="danger"
  2482. onConfirm={() => {
  2483. timelapseDeleteMutation.mutate();
  2484. setShowDeleteTimelapseConfirm(false);
  2485. }}
  2486. onCancel={() => setShowDeleteTimelapseConfirm(false)}
  2487. />
  2488. )}
  2489. {/* Context Menu */}
  2490. {contextMenu && (
  2491. <ContextMenu
  2492. x={contextMenu.x}
  2493. y={contextMenu.y}
  2494. items={contextMenuItems}
  2495. onClose={() => setContextMenu(null)}
  2496. />
  2497. )}
  2498. {/* Timelapse Viewer Modal */}
  2499. {showTimelapse && archive.timelapse_path && (
  2500. <TimelapseViewer
  2501. src={api.getArchiveTimelapse(archive.id)}
  2502. title={t('archives.modal.timelapse', { name: archive.print_name || archive.filename })}
  2503. downloadFilename={`${archive.print_name || archive.filename}_timelapse.mp4`}
  2504. archiveId={archive.id}
  2505. onClose={() => setShowTimelapse(false)}
  2506. onEdit={() => {
  2507. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2508. setShowTimelapse(false);
  2509. }}
  2510. />
  2511. )}
  2512. {/* Timelapse Selection Modal */}
  2513. {showTimelapseSelect && availableTimelapses.length > 0 && (
  2514. <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4">
  2515. <div className="bg-card-dark rounded-lg max-w-lg w-full max-h-[80vh] flex flex-col">
  2516. <div className="flex items-center justify-between p-4 border-b border-gray-700">
  2517. <div>
  2518. <h3 className="text-lg font-semibold text-white">{t('archives.modal.selectTimelapse')}</h3>
  2519. <p className="text-sm text-gray-400 mt-1">
  2520. {t('archives.modal.selectTimelapseDesc')}
  2521. </p>
  2522. </div>
  2523. <button
  2524. onClick={() => {
  2525. setShowTimelapseSelect(false);
  2526. setAvailableTimelapses([]);
  2527. }}
  2528. className="text-gray-400 hover:text-white p-1"
  2529. >
  2530. <X className="w-5 h-5" />
  2531. </button>
  2532. </div>
  2533. <div className="overflow-y-auto flex-1 p-2">
  2534. {availableTimelapses.map((file) => (
  2535. <button
  2536. key={file.name}
  2537. onClick={() => timelapseSelectMutation.mutate(file.name)}
  2538. disabled={timelapseSelectMutation.isPending}
  2539. className="w-full text-left p-3 rounded-lg hover:bg-gray-700 transition-colors mb-1"
  2540. >
  2541. <div className="font-medium text-white">{file.name}</div>
  2542. <div className="text-sm text-gray-400 flex gap-3">
  2543. <span>{formatFileSize(file.size)}</span>
  2544. {file.mtime && (
  2545. <span>{formatDateOnly(file.mtime)}</span>
  2546. )}
  2547. </div>
  2548. </button>
  2549. ))}
  2550. </div>
  2551. </div>
  2552. </div>
  2553. )}
  2554. {/* QR Code Modal */}
  2555. {showQRCode && (
  2556. <QRCodeModal
  2557. archiveId={archive.id}
  2558. archiveName={archive.print_name || archive.filename}
  2559. onClose={() => setShowQRCode(false)}
  2560. />
  2561. )}
  2562. {/* Photo Gallery Modal */}
  2563. {showPhotos && archive.photos && (
  2564. <PhotoGalleryModal
  2565. archiveId={archive.id}
  2566. archiveName={archive.print_name || archive.filename}
  2567. photos={archive.photos}
  2568. onClose={() => setShowPhotos(false)}
  2569. onDelete={async (filename) => {
  2570. try {
  2571. await api.deleteArchivePhoto(archive.id, filename);
  2572. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2573. showToast(t('archives.toast.photoDeleted'));
  2574. } catch {
  2575. showToast(t('archives.toast.failedDeletePhoto'), 'error');
  2576. }
  2577. }}
  2578. />
  2579. )}
  2580. {/* Project Page Modal */}
  2581. {showProjectPage && (
  2582. <ProjectPageModal
  2583. archiveId={archive.id}
  2584. archiveName={archive.print_name || archive.filename}
  2585. onClose={() => setShowProjectPage(false)}
  2586. />
  2587. )}
  2588. {/* Hidden file input for source 3MF upload */}
  2589. <input
  2590. ref={source3mfInputRef}
  2591. type="file"
  2592. accept=".3mf"
  2593. className="hidden"
  2594. onChange={(e) => {
  2595. const file = e.target.files?.[0];
  2596. if (file) {
  2597. source3mfUploadMutation.mutate(file);
  2598. }
  2599. e.target.value = '';
  2600. }}
  2601. />
  2602. {/* Hidden file input for F3D upload */}
  2603. <input
  2604. ref={f3dInputRef}
  2605. type="file"
  2606. accept=".f3d"
  2607. className="hidden"
  2608. onChange={(e) => {
  2609. const file = e.target.files?.[0];
  2610. if (file) {
  2611. f3dUploadMutation.mutate(file);
  2612. }
  2613. e.target.value = '';
  2614. }}
  2615. />
  2616. {/* Hidden file input for timelapse upload */}
  2617. <input
  2618. ref={timelapseInputRef}
  2619. type="file"
  2620. accept=".mp4,.avi,.mkv"
  2621. className="hidden"
  2622. onChange={(e) => {
  2623. const file = e.target.files?.[0];
  2624. if (file) {
  2625. timelapseUploadMutation.mutate(file);
  2626. }
  2627. e.target.value = '';
  2628. }}
  2629. />
  2630. </>
  2631. );
  2632. }
  2633. type SortOption = 'date-desc' | 'date-asc' | 'name-asc' | 'name-desc' | 'size-desc' | 'size-asc';
  2634. type ViewMode = 'grid' | 'list' | 'calendar' | 'log';
  2635. type Collection = 'all' | 'recent' | 'this-week' | 'this-month' | 'favorites' | 'not-printed' | 'printed' | 'failed' | 'duplicates';
  2636. // status values that indicate a print attempt has finished (regardless of outcome).
  2637. // `archived` is the only status that means "uploaded but never sent to a printer."
  2638. const PRINTED_STATUSES = ['completed', 'failed', 'aborted', 'cancelled', 'stopped'] as const;
  2639. const collections: { id: Collection; label: string; icon: React.ReactNode }[] = [
  2640. { id: 'all', label: 'All Archives', icon: <FolderOpen className="w-4 h-4" /> },
  2641. { id: 'recent', label: 'Last 24 Hours', icon: <Clock className="w-4 h-4" /> },
  2642. { id: 'this-week', label: 'This Week', icon: <Calendar className="w-4 h-4" /> },
  2643. { id: 'this-month', label: 'This Month', icon: <Calendar className="w-4 h-4" /> },
  2644. { id: 'favorites', label: 'Favorites', icon: <Star className="w-4 h-4" /> },
  2645. { id: 'not-printed', label: 'Not Printed', icon: <Upload className="w-4 h-4" /> },
  2646. { id: 'printed', label: 'Printed', icon: <Printer className="w-4 h-4" /> },
  2647. { id: 'failed', label: 'Failed Prints', icon: <AlertCircle className="w-4 h-4" /> },
  2648. { id: 'duplicates', label: 'Duplicates', icon: <Copy className="w-4 h-4" /> },
  2649. ];
  2650. export function ArchivesPage() {
  2651. const { t } = useTranslation();
  2652. const queryClient = useQueryClient();
  2653. const { showToast } = useToast();
  2654. const { hasPermission, hasAnyPermission } = useAuth();
  2655. const searchInputRef = useRef<HTMLInputElement>(null);
  2656. const [search, setSearch] = useState('');
  2657. const [filterPrinter, setFilterPrinter] = useState<number | null>(() => {
  2658. const saved = localStorage.getItem('archiveFilterPrinter');
  2659. return saved ? Number(saved) : null;
  2660. });
  2661. const [filterMaterial, setFilterMaterial] = useState<string | null>(() =>
  2662. localStorage.getItem('archiveFilterMaterial')
  2663. );
  2664. const [filterColors, setFilterColors] = useState<Set<string>>(() => {
  2665. const saved = localStorage.getItem('archiveFilterColors');
  2666. return saved ? new Set(JSON.parse(saved)) : new Set();
  2667. });
  2668. const [colorFilterMode, setColorFilterMode] = useState<'or' | 'and'>(() =>
  2669. (localStorage.getItem('archiveColorFilterMode') as 'or' | 'and') || 'or'
  2670. );
  2671. const [filterFavorites, setFilterFavorites] = useState(() =>
  2672. localStorage.getItem('archiveFilterFavorites') === 'true'
  2673. );
  2674. const [hideFailed, setHideFailed] = useState(() =>
  2675. localStorage.getItem('archiveHideFailed') === 'true'
  2676. );
  2677. const [hideDuplicates, setHideDuplicates] = useState(() =>
  2678. localStorage.getItem('archiveHideDuplicates') === 'true'
  2679. );
  2680. const [filterTag, setFilterTag] = useState<string | null>(() =>
  2681. localStorage.getItem('archiveFilterTag')
  2682. );
  2683. const [filterFileType, setFilterFileType] = useState<'all' | 'gcode' | 'source'>(() =>
  2684. (localStorage.getItem('archiveFilterFileType') as 'all' | 'gcode' | 'source') || 'all'
  2685. );
  2686. const [showUpload, setShowUpload] = useState(false);
  2687. const [uploadFiles, setUploadFiles] = useState<File[]>([]);
  2688. const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
  2689. // Install-step-4 nudge — covers the slicer-side variant of "Store sent files
  2690. // on external storage" that the connection diagnostic can't detect (printer
  2691. // never hears about it). Symptom: archive created via no-3MF fallback. Once
  2692. // dismissed, never shown again — fixing step 4 stops new fallbacks anyway.
  2693. const [no3MFWarningDismissed, setNo3MFWarningDismissed] = useState(
  2694. () => localStorage.getItem('archiveNo3MFWarningDismissed') === 'true',
  2695. );
  2696. const { data: no3MFWarning } = useQuery({
  2697. queryKey: ['archives', 'no-3mf-warning'],
  2698. queryFn: api.getNo3MFWarning,
  2699. staleTime: 5 * 60 * 1000,
  2700. enabled: !no3MFWarningDismissed,
  2701. });
  2702. const dismissNo3MFWarning = () => {
  2703. localStorage.setItem('archiveNo3MFWarningDismissed', 'true');
  2704. setNo3MFWarningDismissed(true);
  2705. };
  2706. const [isSelectionMode, setIsSelectionMode] = useState(false);
  2707. const [showBulkDeleteConfirm, setShowBulkDeleteConfirm] = useState(false);
  2708. const [showBatchTag, setShowBatchTag] = useState(false);
  2709. const [showBatchProject, setShowBatchProject] = useState(false);
  2710. const [viewMode, setViewMode] = useState<ViewMode>(() =>
  2711. (localStorage.getItem('archiveViewMode') as ViewMode) || 'grid'
  2712. );
  2713. const [sortBy, setSortBy] = useState<SortOption>(() =>
  2714. (localStorage.getItem('archiveSortBy') as SortOption) || 'date-desc'
  2715. );
  2716. const [collection, setCollection] = useState<Collection>(() =>
  2717. (localStorage.getItem('archiveCollection') as Collection) || 'all'
  2718. );
  2719. // Pagination state
  2720. const [pageIndex, setPageIndex] = useState(0);
  2721. const [pageSize, setPageSize] = useState<number>(() => {
  2722. try {
  2723. const stored = localStorage.getItem('archivePageSize');
  2724. return stored ? Number(stored) : 50;
  2725. } catch { return 50; }
  2726. });
  2727. const [showExportMenu, setShowExportMenu] = useState(false);
  2728. const [isExporting, setIsExporting] = useState(false);
  2729. const [showCompareModal, setShowCompareModal] = useState(false);
  2730. const [showTagManagement, setShowTagManagement] = useState(false);
  2731. const [showPurgeModal, setShowPurgeModal] = useState(false);
  2732. const [highlightedArchiveId, setHighlightedArchiveId] = useState<number | null>(null);
  2733. const [pendingNavigationArchiveId, setPendingNavigationArchiveId] = useState<number | null>(null);
  2734. // Log view state
  2735. const [logFilterUser, setLogFilterUser] = useState<string | null>(() =>
  2736. localStorage.getItem('logFilterUser') || null
  2737. );
  2738. const [logFilterStatus, setLogFilterStatus] = useState<string | null>(() =>
  2739. localStorage.getItem('logFilterStatus')
  2740. );
  2741. const [logFilterDateFrom, setLogFilterDateFrom] = useState(() =>
  2742. localStorage.getItem('logFilterDateFrom') || ''
  2743. );
  2744. const [logFilterDateTo, setLogFilterDateTo] = useState(() =>
  2745. localStorage.getItem('logFilterDateTo') || ''
  2746. );
  2747. const [logOffset, setLogOffset] = useState(() => {
  2748. const saved = localStorage.getItem('logOffset');
  2749. return saved ? Number(saved) : 0;
  2750. });
  2751. const [showClearLogConfirm, setShowClearLogConfirm] = useState(false);
  2752. const [pendingDeleteEntryId, setPendingDeleteEntryId] = useState<number | null>(null);
  2753. // Per-row classification editor for Print Log entries (#1687 part 4).
  2754. // Holds the entry being edited; null = modal closed.
  2755. const [editingLogEntry, setEditingLogEntry] = useState<PrintLogEntry | null>(null);
  2756. const [editingLogFailureReason, setEditingLogFailureReason] = useState('');
  2757. const [editingLogStatus, setEditingLogStatus] = useState('');
  2758. const [logPageSize, setLogPageSize] = useState(() => {
  2759. const saved = localStorage.getItem('logPageSize');
  2760. return saved ? Number(saved) : 25;
  2761. });
  2762. // Print Log column configuration (#2636). Stored without labels; the picker
  2763. // gets freshly translated ones below.
  2764. const [logColumns, setLogColumns] = useState(loadLogColumnConfig);
  2765. const [showLogColumnModal, setShowLogColumnModal] = useState(false);
  2766. const [logSort, setLogSort] = useState<LogSortState>(loadLogSort);
  2767. const visibleLogColumns = useMemo(
  2768. () => logColumns.filter((c) => c.visible).map((c) => c.id),
  2769. [logColumns],
  2770. );
  2771. const handleNavigateToArchive = useCallback((archiveId: number) => {
  2772. setPendingNavigationArchiveId(archiveId);
  2773. setHighlightedArchiveId(archiveId);
  2774. }, []);
  2775. // Clear highlight after 5 seconds and scroll to highlighted element
  2776. useEffect(() => {
  2777. if (highlightedArchiveId) {
  2778. // Scroll to highlighted element after a short delay (to let the view render)
  2779. const scrollTimer = setTimeout(() => {
  2780. const element = document.querySelector(`[data-archive-id="${highlightedArchiveId}"]`);
  2781. if (element) {
  2782. element.scrollIntoView({ behavior: 'smooth', block: 'center' });
  2783. } else if (pendingNavigationArchiveId === highlightedArchiveId) {
  2784. showToast(t('archives.originalPrintNotVisible'), 'warning');
  2785. }
  2786. if (pendingNavigationArchiveId === highlightedArchiveId) {
  2787. setPendingNavigationArchiveId(null);
  2788. }
  2789. }, 100);
  2790. // Clear highlight after 5 seconds
  2791. const clearTimer = setTimeout(() => setHighlightedArchiveId(null), 5000);
  2792. return () => {
  2793. clearTimeout(scrollTimer);
  2794. clearTimeout(clearTimer);
  2795. };
  2796. }
  2797. }, [highlightedArchiveId, pendingNavigationArchiveId, showToast, t]);
  2798. const { data: archives, isLoading } = useQuery({
  2799. queryKey: ['archives', filterPrinter],
  2800. queryFn: () => api.getArchives(filterPrinter || undefined),
  2801. });
  2802. const { data: printers } = useQuery({
  2803. queryKey: ['printers'],
  2804. queryFn: api.getPrinters,
  2805. });
  2806. const { data: projects } = useQuery({
  2807. queryKey: ['projects'],
  2808. queryFn: () => api.getProjects(),
  2809. });
  2810. const { data: settings } = useQuery({
  2811. queryKey: ['settings'],
  2812. queryFn: api.getSettings,
  2813. });
  2814. const { data: users } = useQuery({
  2815. queryKey: ['users'],
  2816. queryFn: api.getUsers,
  2817. enabled: viewMode === 'log',
  2818. });
  2819. const { data: printLogData, isLoading: isLogLoading } = useQuery({
  2820. queryKey: ['print-log', filterPrinter, logFilterUser, logFilterStatus, logFilterDateFrom, logFilterDateTo, search, logOffset, logPageSize, logSort.column, logSort.direction],
  2821. queryFn: () => api.getPrintLog({
  2822. search: search || undefined,
  2823. printerId: filterPrinter || undefined,
  2824. username: logFilterUser || undefined,
  2825. status: logFilterStatus || undefined,
  2826. dateFrom: logFilterDateFrom || undefined,
  2827. dateTo: logFilterDateTo || undefined,
  2828. limit: logPageSize,
  2829. offset: logOffset,
  2830. sortBy: logSort.column,
  2831. sortDir: logSort.direction,
  2832. }),
  2833. enabled: viewMode === 'log',
  2834. });
  2835. const timeFormat: TimeFormat = settings?.time_format || 'system';
  2836. // Desktop "Open in Slicer" target — falls back to preferred_slicer when the
  2837. // user hasn't explicitly chosen a different desktop slicer (#1329). This is
  2838. // ONLY the URI-handoff target; the in-app SliceModal still uses
  2839. // preferred_slicer for the sidecar.
  2840. const preferredSlicer: SlicerType = settings?.open_in_slicer || settings?.preferred_slicer || 'bambu_studio';
  2841. const useSlicerApi = settings?.use_slicer_api ?? false;
  2842. const currency = getCurrencySymbol(settings?.currency || 'USD');
  2843. // Print Log columns, with labels translated at render time (#2636).
  2844. const logColumnConfig: ColumnConfig[] = useMemo(
  2845. () =>
  2846. logColumns.map((c) => ({
  2847. ...c,
  2848. label: t(LOG_COLUMN_LABEL_KEYS[c.id] ?? c.id),
  2849. })),
  2850. [logColumns, t],
  2851. );
  2852. const defaultLogColumnConfig: ColumnConfig[] = useMemo(
  2853. () =>
  2854. DEFAULT_LOG_COLUMNS.map((c) => ({
  2855. ...c,
  2856. label: t(LOG_COLUMN_LABEL_KEYS[c.id] ?? c.id),
  2857. })),
  2858. [t],
  2859. );
  2860. // Click a header to sort by it; click again to flip. Dates, durations and
  2861. // amounts open on descending — "newest / biggest first" is what someone
  2862. // reaching for those wants — while text opens A-Z.
  2863. const handleLogSort = useCallback((colId: string) => {
  2864. if (!SORTABLE_LOG_COLUMNS.has(colId)) return;
  2865. setLogSort((prev) => {
  2866. const numericFirstDesc = ['date', 'completed_at', 'duration', 'filament_used', 'cost', 'energy', 'energy_cost'];
  2867. const next: LogSortState =
  2868. prev.column === colId
  2869. ? { column: colId, direction: prev.direction === 'asc' ? 'desc' : 'asc' }
  2870. : { column: colId, direction: numericFirstDesc.includes(colId) ? 'desc' : 'asc' };
  2871. saveLogSort(next);
  2872. return next;
  2873. });
  2874. // Page 1 of the new order, not whatever offset the old one was on —
  2875. // otherwise sorting by cost from page 3 lands you in the middle of the
  2876. // re-sorted list with no indication why.
  2877. setLogOffset(0);
  2878. }, []);
  2879. const handleLogColumnSave = useCallback((config: ColumnConfig[]) => {
  2880. const stripped = config.map((c) => ({ id: c.id, visible: c.visible }));
  2881. setLogColumns(stripped);
  2882. saveLogColumnConfig(stripped);
  2883. }, []);
  2884. // Columns that hold a number and read better right-aligned. Kept as data so
  2885. // the header and the body can't drift apart.
  2886. const LOG_NUMERIC_COLUMNS = useMemo(
  2887. () => new Set(['duration', 'filament_used', 'cost', 'energy', 'energy_cost']),
  2888. [],
  2889. );
  2890. const renderLogCell = useCallback(
  2891. (colId: string, entry: PrintLogEntry) => {
  2892. switch (colId) {
  2893. case 'date':
  2894. return (
  2895. <span className="text-white whitespace-nowrap">
  2896. {formatDateTime(entry.started_at || entry.created_at, timeFormat)}
  2897. </span>
  2898. );
  2899. case 'completed_at':
  2900. return (
  2901. <span className="text-bambu-gray-light whitespace-nowrap">
  2902. {entry.completed_at ? formatDateTime(entry.completed_at, timeFormat) : '—'}
  2903. </span>
  2904. );
  2905. case 'print_name':
  2906. return (
  2907. <div className="flex items-center gap-2">
  2908. {entry.thumbnail_path && (
  2909. <img
  2910. src={api.getPrintLogThumbnail(entry.id)}
  2911. alt=""
  2912. className="w-8 h-8 rounded object-cover flex-shrink-0"
  2913. onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }}
  2914. />
  2915. )}
  2916. <span className="text-white break-words" title={entry.print_name || ''}>
  2917. {entry.print_name || '—'}
  2918. </span>
  2919. </div>
  2920. );
  2921. case 'printer':
  2922. return <span className="text-bambu-gray-light">{entry.printer_name || '—'}</span>;
  2923. case 'user':
  2924. return <span className="text-bambu-gray-light">{entry.created_by_username || '—'}</span>;
  2925. case 'status':
  2926. return (
  2927. <>
  2928. <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
  2929. entry.status === 'completed' ? 'bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-400' :
  2930. entry.status === 'failed' ? 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400' :
  2931. entry.status === 'stopped' ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400' :
  2932. entry.status === 'cancelled' ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400' :
  2933. entry.status === 'skipped' ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400' :
  2934. 'bg-gray-500/20 text-gray-400'
  2935. }`}>
  2936. {entry.status}
  2937. </span>
  2938. {entry.failure_reason && (
  2939. <span className="block text-[10px] text-bambu-gray mt-0.5">
  2940. {t(`editArchive.failureReasons.${entry.failure_reason}`, { defaultValue: entry.failure_reason })}
  2941. </span>
  2942. )}
  2943. </>
  2944. );
  2945. case 'duration':
  2946. return (
  2947. <span className="text-bambu-gray-light whitespace-nowrap">
  2948. {entry.duration_seconds ? formatDuration(entry.duration_seconds) : '—'}
  2949. </span>
  2950. );
  2951. case 'filament':
  2952. return (
  2953. <div className="flex items-center gap-1.5">
  2954. {entry.filament_color && (
  2955. <div className="flex items-center gap-0.5 flex-wrap">
  2956. {entry.filament_color.split(',').map((color, i) => {
  2957. const trimmed = color.trim();
  2958. return (
  2959. <span
  2960. key={i}
  2961. className="w-3 h-3 rounded-full border border-black/20 flex-shrink-0"
  2962. style={{ backgroundColor: trimmed.startsWith('#') ? trimmed : undefined }}
  2963. title={trimmed}
  2964. />
  2965. );
  2966. })}
  2967. </div>
  2968. )}
  2969. <span className="text-bambu-gray-light text-xs">
  2970. {entry.filament_type || '—'}
  2971. </span>
  2972. </div>
  2973. );
  2974. case 'filament_used':
  2975. // Per-run actual, not the archive's estimate: partial prints are
  2976. // scaled to progress and multi-plate archives are scoped to the
  2977. // plate that printed. One decimal matches the per-archive log table.
  2978. return (
  2979. <span className="text-bambu-gray-light whitespace-nowrap tabular-nums">
  2980. {entry.filament_used_grams != null ? `${entry.filament_used_grams.toFixed(1)} g` : '—'}
  2981. </span>
  2982. );
  2983. case 'cost':
  2984. return (
  2985. <span className="text-bambu-gray-light whitespace-nowrap tabular-nums">
  2986. {entry.cost != null ? `${currency}${entry.cost.toFixed(2)}` : '—'}
  2987. </span>
  2988. );
  2989. case 'energy':
  2990. // Written by the energy background task after the row itself, so a
  2991. // just-finished print shows "—" for a moment. That is accurate: the
  2992. // measurement genuinely isn't in yet.
  2993. return (
  2994. <span className="text-bambu-gray-light whitespace-nowrap tabular-nums">
  2995. {entry.energy_kwh != null ? `${entry.energy_kwh.toFixed(2)} kWh` : '—'}
  2996. </span>
  2997. );
  2998. case 'energy_cost':
  2999. return (
  3000. <span className="text-bambu-gray-light whitespace-nowrap tabular-nums">
  3001. {entry.energy_cost != null ? `${currency}${entry.energy_cost.toFixed(2)}` : '—'}
  3002. </span>
  3003. );
  3004. default:
  3005. return null;
  3006. }
  3007. },
  3008. [currency, t, timeFormat],
  3009. );
  3010. const bulkDeleteMutation = useMutation({
  3011. mutationFn: async (ids: number[]) => {
  3012. await Promise.all(ids.map((id) => api.deleteArchive(id)));
  3013. return ids.length;
  3014. },
  3015. onSuccess: (count) => {
  3016. invalidateArchiveAndProjectViews(queryClient);
  3017. setSelectedIds(new Set());
  3018. showToast(`${count} archive${count !== 1 ? 's' : ''} deleted`);
  3019. },
  3020. onError: () => {
  3021. showToast(t('archives.toast.failedDeleteArchives'), 'error');
  3022. },
  3023. });
  3024. const clearLogMutation = useMutation({
  3025. mutationFn: () => api.clearPrintLog(),
  3026. onSuccess: (data) => {
  3027. queryClient.invalidateQueries({ queryKey: ['print-log'] });
  3028. setLogOffset(0);
  3029. showToast(t('archives.log.cleared', { count: data.deleted }));
  3030. },
  3031. onError: () => {
  3032. showToast(t('archives.log.clearFailed'), 'error');
  3033. },
  3034. });
  3035. const deleteLogEntryMutation = useMutation({
  3036. mutationFn: (id: number) => api.deletePrintLogEntry(id),
  3037. onSuccess: () => {
  3038. queryClient.invalidateQueries({ queryKey: ['print-log'] });
  3039. queryClient.invalidateQueries({ queryKey: ['archives-stats'] });
  3040. showToast(t('archives.log.entryDeleted'));
  3041. },
  3042. onError: () => {
  3043. showToast(t('archives.log.entryDeleteFailed'), 'error');
  3044. },
  3045. });
  3046. const updateLogEntryMutation = useMutation({
  3047. mutationFn: ({ id, body }: { id: number; body: { failure_reason?: string | null; status?: string } }) =>
  3048. api.updatePrintLogEntry(id, body),
  3049. onSuccess: () => {
  3050. queryClient.invalidateQueries({ queryKey: ['print-log'] });
  3051. // Also invalidate /archives/stats — the Failure Analysis widget there
  3052. // groups by PrintLogEntry.failure_reason, so a re-classification needs
  3053. // to flow through (#1687 part 4).
  3054. queryClient.invalidateQueries({ queryKey: ['archives-stats'] });
  3055. setEditingLogEntry(null);
  3056. showToast(t('archives.log.entryUpdated'));
  3057. },
  3058. onError: () => {
  3059. showToast(t('archives.log.entryUpdateFailed'), 'error');
  3060. },
  3061. });
  3062. // Persist all filters to localStorage
  3063. useEffect(() => {
  3064. if (filterPrinter !== null) {
  3065. localStorage.setItem('archiveFilterPrinter', filterPrinter.toString());
  3066. } else {
  3067. localStorage.removeItem('archiveFilterPrinter');
  3068. }
  3069. }, [filterPrinter]);
  3070. useEffect(() => {
  3071. if (filterMaterial) {
  3072. localStorage.setItem('archiveFilterMaterial', filterMaterial);
  3073. } else {
  3074. localStorage.removeItem('archiveFilterMaterial');
  3075. }
  3076. }, [filterMaterial]);
  3077. useEffect(() => {
  3078. localStorage.setItem('archiveFilterColors', JSON.stringify([...filterColors]));
  3079. }, [filterColors]);
  3080. useEffect(() => {
  3081. localStorage.setItem('archiveColorFilterMode', colorFilterMode);
  3082. }, [colorFilterMode]);
  3083. useEffect(() => {
  3084. localStorage.setItem('archiveFilterFavorites', filterFavorites.toString());
  3085. }, [filterFavorites]);
  3086. useEffect(() => {
  3087. localStorage.setItem('archiveHideFailed', hideFailed.toString());
  3088. }, [hideFailed]);
  3089. useEffect(() => {
  3090. localStorage.setItem('archiveHideDuplicates', hideDuplicates.toString());
  3091. }, [hideDuplicates]);
  3092. useEffect(() => {
  3093. if (filterTag) {
  3094. localStorage.setItem('archiveFilterTag', filterTag);
  3095. } else {
  3096. localStorage.removeItem('archiveFilterTag');
  3097. }
  3098. }, [filterTag]);
  3099. useEffect(() => {
  3100. localStorage.setItem('archiveFilterFileType', filterFileType);
  3101. }, [filterFileType]);
  3102. // Reset page when filters/search/sort/collection change
  3103. useEffect(() => {
  3104. setPageIndex(0);
  3105. }, [search, filterPrinter, filterMaterial, filterColors, colorFilterMode, filterFavorites, hideFailed, hideDuplicates, filterTag, filterFileType, sortBy, collection]);
  3106. useEffect(() => {
  3107. try { localStorage.setItem('archivePageSize', String(pageSize)); } catch { /* ignore */ }
  3108. }, [pageSize]);
  3109. useEffect(() => {
  3110. localStorage.setItem('archiveViewMode', viewMode);
  3111. }, [viewMode]);
  3112. useEffect(() => {
  3113. localStorage.setItem('archiveSortBy', sortBy);
  3114. }, [sortBy]);
  3115. useEffect(() => {
  3116. localStorage.setItem('archiveCollection', collection);
  3117. }, [collection]);
  3118. // Persist log view filters
  3119. useEffect(() => {
  3120. if (logFilterUser) {
  3121. localStorage.setItem('logFilterUser', logFilterUser);
  3122. } else {
  3123. localStorage.removeItem('logFilterUser');
  3124. }
  3125. }, [logFilterUser]);
  3126. useEffect(() => {
  3127. if (logFilterStatus) {
  3128. localStorage.setItem('logFilterStatus', logFilterStatus);
  3129. } else {
  3130. localStorage.removeItem('logFilterStatus');
  3131. }
  3132. }, [logFilterStatus]);
  3133. useEffect(() => {
  3134. if (logFilterDateFrom) {
  3135. localStorage.setItem('logFilterDateFrom', logFilterDateFrom);
  3136. } else {
  3137. localStorage.removeItem('logFilterDateFrom');
  3138. }
  3139. }, [logFilterDateFrom]);
  3140. useEffect(() => {
  3141. if (logFilterDateTo) {
  3142. localStorage.setItem('logFilterDateTo', logFilterDateTo);
  3143. } else {
  3144. localStorage.removeItem('logFilterDateTo');
  3145. }
  3146. }, [logFilterDateTo]);
  3147. useEffect(() => {
  3148. localStorage.setItem('logOffset', logOffset.toString());
  3149. }, [logOffset]);
  3150. useEffect(() => {
  3151. localStorage.setItem('logPageSize', logPageSize.toString());
  3152. }, [logPageSize]);
  3153. // Memoised: it's handed to every ArchiveCard as a prop, and a fresh Map each
  3154. // render would re-run their lookups for no reason.
  3155. const printerMap = useMemo(
  3156. () => new Map<number, string>(printers?.map((p) => [p.id, p.name]) || []),
  3157. [printers],
  3158. );
  3159. // Extract unique materials and colors from archives
  3160. const uniqueMaterials = [...new Set(
  3161. archives?.flatMap(a => a.filament_type?.split(', ') || []).filter(Boolean) || []
  3162. )].sort();
  3163. const uniqueColors = [...new Set(
  3164. archives?.flatMap(a => a.filament_color?.split(',') || []).filter(Boolean) || []
  3165. )];
  3166. const uniqueTags = [...new Set(
  3167. archives?.flatMap(a => a.tags?.split(',').map(t => t.trim()) || []).filter(Boolean) || []
  3168. )].sort();
  3169. const filteredArchives = archives
  3170. ?.filter((a) => {
  3171. // Collection filter
  3172. const now = new Date();
  3173. const archiveDate = parseUTCDate(a.created_at) || new Date(0);
  3174. let matchesCollection = true;
  3175. switch (collection) {
  3176. case 'recent':
  3177. matchesCollection = (now.getTime() - archiveDate.getTime()) < 24 * 60 * 60 * 1000;
  3178. break;
  3179. case 'this-week':
  3180. matchesCollection = (now.getTime() - archiveDate.getTime()) < 7 * 24 * 60 * 60 * 1000;
  3181. break;
  3182. case 'this-month':
  3183. matchesCollection = archiveDate.getMonth() === now.getMonth() && archiveDate.getFullYear() === now.getFullYear();
  3184. break;
  3185. case 'favorites':
  3186. matchesCollection = a.is_favorite === true;
  3187. break;
  3188. case 'not-printed':
  3189. matchesCollection = a.status === 'archived';
  3190. break;
  3191. case 'printed':
  3192. matchesCollection = (PRINTED_STATUSES as readonly string[]).includes(a.status);
  3193. break;
  3194. case 'failed':
  3195. matchesCollection = a.status === 'failed' || a.status === 'aborted';
  3196. break;
  3197. case 'duplicates':
  3198. matchesCollection = a.duplicate_count > 0;
  3199. break;
  3200. }
  3201. // Search filter
  3202. const matchesSearch = (a.print_name || a.filename).toLowerCase().includes(search.toLowerCase());
  3203. // Material filter
  3204. const matchesMaterial = !filterMaterial ||
  3205. (a.filament_type?.split(', ').includes(filterMaterial));
  3206. // Color filter (AND: must have all selected colors, OR: must have any selected color)
  3207. const archiveColors = a.filament_color?.split(',') || [];
  3208. const matchesColor = filterColors.size === 0 ||
  3209. (colorFilterMode === 'or'
  3210. ? archiveColors.some(c => filterColors.has(c))
  3211. : [...filterColors].every(c => archiveColors.includes(c)));
  3212. // Favorites filter (only apply if not using favorites collection)
  3213. const matchesFavorites = collection === 'favorites' || !filterFavorites || a.is_favorite;
  3214. // Hide failed filter (don't apply when viewing failed collection)
  3215. const matchesHideFailed = collection === 'failed' || !hideFailed || (a.status !== 'failed' && a.status !== 'aborted');
  3216. // Hide duplicates filter (don't apply when viewing duplicates collection)
  3217. const matchesHideDuplicates =
  3218. collection === 'duplicates' || !hideDuplicates || a.duplicate_count === 0 || a.duplicate_sequence === 0;
  3219. // Tag filter
  3220. const archiveTags = a.tags?.split(',').map(t => t.trim()) || [];
  3221. const matchesTag = !filterTag || archiveTags.includes(filterTag);
  3222. // File type filter (gcode = sliced, source = project file only)
  3223. const isGcodeFile = isSlicedFile(a);
  3224. const matchesFileType = filterFileType === 'all' ||
  3225. (filterFileType === 'gcode' && isGcodeFile) ||
  3226. (filterFileType === 'source' && !isGcodeFile);
  3227. return matchesCollection && matchesSearch && matchesMaterial && matchesColor && matchesFavorites && matchesHideFailed && matchesHideDuplicates && matchesTag && matchesFileType;
  3228. })
  3229. .sort((a, b) => {
  3230. switch (sortBy) {
  3231. case 'date-desc':
  3232. return (parseUTCDate(b.created_at)?.getTime() || 0) - (parseUTCDate(a.created_at)?.getTime() || 0);
  3233. case 'date-asc':
  3234. return (parseUTCDate(a.created_at)?.getTime() || 0) - (parseUTCDate(b.created_at)?.getTime() || 0);
  3235. case 'name-asc':
  3236. return (a.print_name || a.filename).localeCompare(b.print_name || b.filename);
  3237. case 'name-desc':
  3238. return (b.print_name || b.filename).localeCompare(a.print_name || a.filename);
  3239. case 'size-desc':
  3240. return b.file_size - a.file_size;
  3241. case 'size-asc':
  3242. return a.file_size - b.file_size;
  3243. default:
  3244. return 0;
  3245. }
  3246. });
  3247. // Pagination
  3248. const totalFiltered = filteredArchives?.length || 0;
  3249. const showAll = pageSize === -1;
  3250. const effectivePageSize = showAll ? totalFiltered || 1 : pageSize;
  3251. const totalPages = Math.max(1, Math.ceil(totalFiltered / effectivePageSize));
  3252. const paginatedArchives = showAll
  3253. ? filteredArchives
  3254. : filteredArchives?.slice(pageIndex * effectivePageSize, (pageIndex + 1) * effectivePageSize);
  3255. // Jump to the page containing the highlighted archive
  3256. useEffect(() => {
  3257. if (highlightedArchiveId && filteredArchives && !showAll) {
  3258. const idx = filteredArchives.findIndex(a => a.id === highlightedArchiveId);
  3259. if (idx >= 0) {
  3260. const targetPage = Math.floor(idx / effectivePageSize);
  3261. if (targetPage !== pageIndex) setPageIndex(targetPage);
  3262. }
  3263. }
  3264. // eslint-disable-next-line react-hooks/exhaustive-deps
  3265. }, [highlightedArchiveId]);
  3266. const selectionMode = isSelectionMode || selectedIds.size > 0;
  3267. const toggleSelect = (id: number) => {
  3268. setSelectedIds((prev) => {
  3269. const next = new Set(prev);
  3270. if (next.has(id)) {
  3271. next.delete(id);
  3272. } else {
  3273. next.add(id);
  3274. }
  3275. return next;
  3276. });
  3277. };
  3278. const selectAll = () => {
  3279. if (filteredArchives) {
  3280. setSelectedIds(new Set(filteredArchives.map((a) => a.id)));
  3281. }
  3282. };
  3283. const clearSelection = () => {
  3284. setSelectedIds(new Set());
  3285. setIsSelectionMode(false);
  3286. };
  3287. const toggleColor = (color: string) => {
  3288. setFilterColors((prev) => {
  3289. const next = new Set(prev);
  3290. if (next.has(color)) {
  3291. next.delete(color);
  3292. } else {
  3293. next.add(color);
  3294. }
  3295. return next;
  3296. });
  3297. };
  3298. const clearColorFilter = () => {
  3299. setFilterColors(new Set());
  3300. };
  3301. const clearTopFilters = () => {
  3302. setSearch('');
  3303. setFilterPrinter(null);
  3304. setFilterMaterial(null);
  3305. setFilterFavorites(false);
  3306. setHideFailed(false);
  3307. setHideDuplicates(false);
  3308. setFilterTag(null);
  3309. setFilterFileType('all');
  3310. };
  3311. const hasTopFilters = search || filterPrinter || filterMaterial || filterFavorites || hideFailed || hideDuplicates || filterTag || filterFileType !== 'all';
  3312. // Page-wide drag-and-drop upload (#1510). The hook covers the three cancel
  3313. // paths the previous inline implementation missed (drag-out-of-window, Escape,
  3314. // dragend outside any drop target). Disabled while the upload modal is open
  3315. // so drags into the modal's own drop zone don't bubble up and flash the page
  3316. // overlay behind it.
  3317. const { isDraggingOver, dragHandlers } = usePageFileDrop({
  3318. disabled: showUpload,
  3319. extensions: ['.3mf'],
  3320. onFiles: (files) => {
  3321. setUploadFiles(files);
  3322. setShowUpload(true);
  3323. },
  3324. onRejected: () => showToast(t('archives.page.only3mfSupported'), 'warning'),
  3325. });
  3326. // Keyboard shortcuts
  3327. const handleKeyDown = useCallback((e: KeyboardEvent) => {
  3328. const target = e.target as HTMLElement;
  3329. // Ignore if typing in an input/textarea
  3330. if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
  3331. if (e.key === 'Escape') {
  3332. target.blur();
  3333. }
  3334. return;
  3335. }
  3336. switch (e.key) {
  3337. case '/':
  3338. e.preventDefault();
  3339. searchInputRef.current?.focus();
  3340. break;
  3341. case 'u':
  3342. case 'U':
  3343. if (!e.metaKey && !e.ctrlKey) {
  3344. e.preventDefault();
  3345. setShowUpload(true);
  3346. }
  3347. break;
  3348. case 'Escape':
  3349. if (selectionMode) {
  3350. clearSelection();
  3351. }
  3352. break;
  3353. }
  3354. }, [selectionMode]);
  3355. useEffect(() => {
  3356. document.addEventListener('keydown', handleKeyDown);
  3357. return () => document.removeEventListener('keydown', handleKeyDown);
  3358. }, [handleKeyDown]);
  3359. return (
  3360. <div
  3361. className="p-4 md:p-8 relative"
  3362. {...dragHandlers}
  3363. >
  3364. {/* Drag & Drop Overlay */}
  3365. {isDraggingOver && (
  3366. <div className="fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none">
  3367. <div className="border-4 border-dashed border-bambu-green rounded-xl p-12 text-center">
  3368. <Upload className="w-16 h-16 mx-auto mb-4 text-bambu-green" />
  3369. <p className="text-2xl font-semibold text-white mb-2">{t('archives.page.dropFilesHere')}</p>
  3370. <p className="text-bambu-gray">{t('archives.releaseToUpload')}</p>
  3371. </div>
  3372. </div>
  3373. )}
  3374. {/* Selection Toolbar */}
  3375. {selectionMode && (
  3376. <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">
  3377. <Button variant="secondary" size="sm" onClick={clearSelection}>
  3378. <X className="w-4 h-4" />
  3379. Close
  3380. </Button>
  3381. <div className="w-px h-6 bg-bambu-dark-tertiary" />
  3382. <span className="text-white font-medium">
  3383. {selectedIds.size} selected
  3384. </span>
  3385. <div className="w-px h-6 bg-bambu-dark-tertiary" />
  3386. <Button variant="secondary" size="sm" onClick={selectAll}>
  3387. Select All
  3388. </Button>
  3389. <div className="w-px h-6 bg-bambu-dark-tertiary" />
  3390. <Button
  3391. variant="secondary"
  3392. size="sm"
  3393. onClick={() => setShowBatchTag(true)}
  3394. disabled={!hasAnyPermission('archives:update_own', 'archives:update_all')}
  3395. title={!hasAnyPermission('archives:update_own', 'archives:update_all') ? t('archives.permission.noUpdateArchives') : undefined}
  3396. >
  3397. <Tag className="w-4 h-4" />
  3398. Tags
  3399. </Button>
  3400. <Button
  3401. variant="secondary"
  3402. size="sm"
  3403. onClick={() => setShowBatchProject(true)}
  3404. disabled={!hasAnyPermission('archives:update_own', 'archives:update_all')}
  3405. title={!hasAnyPermission('archives:update_own', 'archives:update_all') ? t('archives.permission.noUpdateArchives') : undefined}
  3406. >
  3407. <FolderKanban className="w-4 h-4" />
  3408. Project
  3409. </Button>
  3410. <Button
  3411. variant="secondary"
  3412. size="sm"
  3413. disabled={!hasAnyPermission('archives:update_own', 'archives:update_all')}
  3414. title={!hasAnyPermission('archives:update_own', 'archives:update_all') ? t('archives.permission.noUpdateArchives') : undefined}
  3415. onClick={() => {
  3416. const ids = Array.from(selectedIds);
  3417. Promise.all(ids.map(id => api.toggleFavorite(id)))
  3418. .then(() => {
  3419. queryClient.invalidateQueries({ queryKey: ['archives'] });
  3420. showToast(`Toggled favorites for ${ids.length} archive${ids.length !== 1 ? 's' : ''}`);
  3421. })
  3422. .catch(() => {
  3423. showToast(t('archives.toast.failedUpdateFavorites'), 'error');
  3424. });
  3425. }}
  3426. >
  3427. <Star className="w-4 h-4" />
  3428. Favorite
  3429. </Button>
  3430. <Button
  3431. size="sm"
  3432. className="bg-red-500 hover:bg-red-600"
  3433. onClick={() => setShowBulkDeleteConfirm(true)}
  3434. disabled={!hasAnyPermission('archives:delete_own', 'archives:delete_all')}
  3435. title={!hasAnyPermission('archives:delete_own', 'archives:delete_all') ? t('archives.permission.noDelete') : undefined}
  3436. >
  3437. <Trash2 className="w-4 h-4" />
  3438. Delete
  3439. </Button>
  3440. </div>
  3441. )}
  3442. {no3MFWarning?.has_fallback && !no3MFWarningDismissed && (
  3443. <div className="mb-6 rounded-lg border border-amber-300 dark:border-amber-500/30 bg-amber-50 dark:bg-amber-500/10 px-4 py-3 flex items-start gap-3">
  3444. <AlertCircle className="w-5 h-5 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5" />
  3445. <div className="flex-1 min-w-0">
  3446. <div className="text-sm font-medium text-amber-900 dark:text-amber-200">
  3447. {t('archives.no3mfBanner.title')}
  3448. </div>
  3449. <div className="text-xs text-amber-800/90 dark:text-amber-200/80 mt-1">
  3450. {t('archives.no3mfBanner.body')}{' '}
  3451. <a
  3452. href="https://wiki.bambuddy.cool/getting-started/#step-4-enable-store-sent-files-on-external-storage"
  3453. target="_blank"
  3454. rel="noreferrer"
  3455. className="underline hover:text-amber-900 dark:hover:text-amber-100 inline-flex items-center gap-1"
  3456. >
  3457. {t('archives.no3mfBanner.docsLink')}
  3458. <ExternalLink className="w-3 h-3" />
  3459. </a>
  3460. </div>
  3461. </div>
  3462. <button
  3463. onClick={dismissNo3MFWarning}
  3464. className="text-amber-800/70 dark:text-amber-200/60 hover:text-amber-900 dark:hover:text-amber-200 flex-shrink-0 p-1 -m-1"
  3465. title={t('archives.no3mfBanner.dismissLabel')}
  3466. aria-label={t('archives.no3mfBanner.dismissLabel')}
  3467. >
  3468. <X className="w-4 h-4" />
  3469. </button>
  3470. </div>
  3471. )}
  3472. <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8">
  3473. <div>
  3474. <div className="flex items-start gap-3">
  3475. <div>
  3476. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  3477. <ArchiveIcon className="w-7 h-7 text-bambu-green" />
  3478. Archives
  3479. </h1>
  3480. <p className="text-bambu-gray mt-1">
  3481. {filteredArchives?.length || 0} of {archives?.length || 0} prints
  3482. </p>
  3483. </div>
  3484. <select
  3485. className="mt-0.5 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"
  3486. value={collection}
  3487. onChange={(e) => setCollection(e.target.value as Collection)}
  3488. >
  3489. {collections.map((c) => (
  3490. <option key={c.id} value={c.id}>
  3491. {c.label}
  3492. </option>
  3493. ))}
  3494. </select>
  3495. </div>
  3496. </div>
  3497. <div className="flex items-center gap-2 sm:gap-3 flex-wrap">
  3498. {/* Export dropdown */}
  3499. <div className="relative">
  3500. <Button
  3501. variant="secondary"
  3502. onClick={() => setShowExportMenu(!showExportMenu)}
  3503. disabled={isExporting}
  3504. >
  3505. {isExporting ? (
  3506. <Loader2 className="w-4 h-4 animate-spin" />
  3507. ) : (
  3508. <FileSpreadsheet className="w-4 h-4" />
  3509. )}
  3510. Export
  3511. </Button>
  3512. {showExportMenu && (
  3513. <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">
  3514. <button
  3515. 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"
  3516. onClick={async () => {
  3517. setShowExportMenu(false);
  3518. setIsExporting(true);
  3519. try {
  3520. const { blob, filename } = await api.exportArchives({
  3521. format: 'csv',
  3522. printerId: filterPrinter || undefined,
  3523. status: collection === 'failed' ? 'failed' : undefined,
  3524. search: search || undefined,
  3525. });
  3526. const url = URL.createObjectURL(blob);
  3527. const a = document.createElement('a');
  3528. a.href = url;
  3529. a.download = filename;
  3530. a.click();
  3531. URL.revokeObjectURL(url);
  3532. showToast(t('archives.toast.exportDownloaded'));
  3533. } catch {
  3534. showToast(t('archives.toast.exportFailed'), 'error');
  3535. } finally {
  3536. setIsExporting(false);
  3537. }
  3538. }}
  3539. >
  3540. <FileText className="w-4 h-4" />
  3541. Export as CSV
  3542. </button>
  3543. <button
  3544. 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"
  3545. onClick={async () => {
  3546. setShowExportMenu(false);
  3547. setIsExporting(true);
  3548. try {
  3549. const { blob, filename } = await api.exportArchives({
  3550. format: 'xlsx',
  3551. printerId: filterPrinter || undefined,
  3552. status: collection === 'failed' ? 'failed' : undefined,
  3553. search: search || undefined,
  3554. });
  3555. const url = URL.createObjectURL(blob);
  3556. const a = document.createElement('a');
  3557. a.href = url;
  3558. a.download = filename;
  3559. a.click();
  3560. URL.revokeObjectURL(url);
  3561. showToast(t('archives.toast.exportDownloaded'));
  3562. } catch {
  3563. showToast(t('archives.toast.exportFailed'), 'error');
  3564. } finally {
  3565. setIsExporting(false);
  3566. }
  3567. }}
  3568. >
  3569. <FileSpreadsheet className="w-4 h-4" />
  3570. Export as Excel
  3571. </button>
  3572. </div>
  3573. )}
  3574. </div>
  3575. {/* Compare button (only when 2-5 items selected) */}
  3576. {selectedIds.size >= 2 && selectedIds.size <= 5 && (
  3577. <Button
  3578. variant="secondary"
  3579. onClick={() => setShowCompareModal(true)}
  3580. >
  3581. <GitCompare className="w-4 h-4" />
  3582. Compare ({selectedIds.size})
  3583. </Button>
  3584. )}
  3585. {!selectionMode && (
  3586. <Button variant="secondary" onClick={() => setIsSelectionMode(true)}>
  3587. <CheckSquare className="w-4 h-4" />
  3588. Select
  3589. </Button>
  3590. )}
  3591. <Button
  3592. onClick={() => setShowUpload(true)}
  3593. disabled={!hasPermission('archives:create')}
  3594. title={!hasPermission('archives:create') ? t('archives.permission.noCreate') : undefined}
  3595. >
  3596. <Upload className="w-4 h-4" />
  3597. Upload 3MF
  3598. </Button>
  3599. {hasPermission('archives:purge') && (
  3600. <Button
  3601. variant="secondary"
  3602. onClick={() => setShowPurgeModal(true)}
  3603. title={t('archivePurge.headerTooltip')}
  3604. >
  3605. <Trash2 className="w-4 h-4 mr-2" />
  3606. {t('archivePurge.headerButton')}
  3607. </Button>
  3608. )}
  3609. </div>
  3610. </div>
  3611. {/* View mode toggle — always visible */}
  3612. <div className="flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden flex-shrink-0 w-fit mb-4">
  3613. <button
  3614. className={`p-2 ${viewMode === 'grid' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  3615. onClick={() => setViewMode('grid')}
  3616. title={t('archives.gridView')}
  3617. >
  3618. <LayoutGrid className="w-4 h-4" />
  3619. </button>
  3620. <button
  3621. className={`p-2 ${viewMode === 'list' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  3622. onClick={() => setViewMode('list')}
  3623. title={t('archives.listView')}
  3624. >
  3625. <List className="w-4 h-4" />
  3626. </button>
  3627. <button
  3628. className={`p-2 ${viewMode === 'calendar' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  3629. onClick={() => setViewMode('calendar')}
  3630. title={t('archives.calendarView')}
  3631. >
  3632. <CalendarDays className="w-4 h-4" />
  3633. </button>
  3634. <button
  3635. className={`p-2 ${viewMode === 'log' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  3636. onClick={() => setViewMode('log')}
  3637. title={t('archives.logView')}
  3638. >
  3639. <ClipboardList className="w-4 h-4" />
  3640. </button>
  3641. </div>
  3642. {/* Filters (hidden in log view which has its own filters) */}
  3643. {viewMode !== 'log' && <Card className="mb-6">
  3644. <CardContent className="py-4">
  3645. <div className="flex flex-col md:flex-row gap-3 md:gap-4 md:items-center md:flex-wrap">
  3646. {/* Search - full width on mobile */}
  3647. <div className="w-full md:flex-1 relative md:min-w-[200px]">
  3648. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  3649. <input
  3650. ref={searchInputRef}
  3651. type="text"
  3652. placeholder={t('archives.searchPlaceholder')}
  3653. 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"
  3654. value={search}
  3655. onChange={(e) => setSearch(e.target.value)}
  3656. />
  3657. </div>
  3658. {/* Filters - horizontal scroll on mobile */}
  3659. <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">
  3660. <div className="flex items-center gap-2 flex-shrink-0">
  3661. <Filter className="w-4 h-4 text-bambu-gray hidden md:block" />
  3662. <select
  3663. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3664. value={filterPrinter || ''}
  3665. onChange={(e) =>
  3666. setFilterPrinter(e.target.value ? Number(e.target.value) : null)
  3667. }
  3668. >
  3669. <option value="">All Printers</option>
  3670. {printers?.map((p) => (
  3671. <option key={p.id} value={p.id}>
  3672. {p.name}
  3673. </option>
  3674. ))}
  3675. </select>
  3676. </div>
  3677. <div className="flex items-center gap-2 flex-shrink-0">
  3678. <Package className="w-4 h-4 text-bambu-gray hidden md:block" />
  3679. <select
  3680. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3681. value={filterMaterial || ''}
  3682. onChange={(e) =>
  3683. setFilterMaterial(e.target.value || null)
  3684. }
  3685. >
  3686. <option value="">All Materials</option>
  3687. {uniqueMaterials.map((m) => (
  3688. <option key={m} value={m}>
  3689. {m}
  3690. </option>
  3691. ))}
  3692. </select>
  3693. </div>
  3694. <div className="flex items-center gap-2 flex-shrink-0">
  3695. <FileCode className="w-4 h-4 text-bambu-gray hidden md:block" />
  3696. <select
  3697. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3698. value={filterFileType}
  3699. onChange={(e) => setFilterFileType(e.target.value as 'all' | 'gcode' | 'source')}
  3700. >
  3701. <option value="all">All Files</option>
  3702. <option value="gcode">Sliced (GCODE)</option>
  3703. <option value="source">Source Only</option>
  3704. </select>
  3705. </div>
  3706. <button
  3707. onClick={() => setFilterFavorites(!filterFavorites)}
  3708. className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${
  3709. filterFavorites
  3710. ? 'bg-yellow-100 dark:bg-yellow-500/20 border-yellow-500 text-yellow-700 dark:text-yellow-400'
  3711. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  3712. }`}
  3713. title={filterFavorites ? t('archives.showAll') : t('archives.showFavoritesOnly')}
  3714. >
  3715. <Star className={`w-4 h-4 ${filterFavorites ? 'fill-yellow-400' : ''}`} />
  3716. <span className="text-sm hidden md:inline">Favorites</span>
  3717. </button>
  3718. <button
  3719. onClick={() => setHideFailed(!hideFailed)}
  3720. className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${
  3721. hideFailed
  3722. ? 'bg-red-100 dark:bg-red-500/20 border-red-500 text-red-700 dark:text-red-400'
  3723. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  3724. }`}
  3725. title={hideFailed ? t('archives.showFailedPrints') : t('archives.hideFailedPrints')}
  3726. >
  3727. <AlertCircle className={`w-4 h-4 ${hideFailed ? '' : ''}`} />
  3728. <span className="text-sm hidden md:inline">Hide Failed</span>
  3729. </button>
  3730. <button
  3731. onClick={() => setHideDuplicates(!hideDuplicates)}
  3732. className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${
  3733. hideDuplicates
  3734. ? 'bg-purple-100 dark:bg-purple-500/20 border-purple-500 text-purple-700 dark:text-purple-400'
  3735. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  3736. }`}
  3737. title={t('archives.hideDuplicates')}
  3738. >
  3739. <Copy className="w-4 h-4" />
  3740. <span className="text-sm hidden md:inline">{t('archives.hideDuplicates')}</span>
  3741. </button>
  3742. {uniqueTags.length > 0 && (
  3743. <div className="flex items-center gap-2 flex-shrink-0">
  3744. <Tag className="w-4 h-4 text-bambu-gray hidden md:block" />
  3745. <select
  3746. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3747. value={filterTag || ''}
  3748. onChange={(e) => setFilterTag(e.target.value || null)}
  3749. >
  3750. <option value="">All Tags</option>
  3751. {uniqueTags.map((t) => (
  3752. <option key={t} value={t}>
  3753. {t}
  3754. </option>
  3755. ))}
  3756. </select>
  3757. <button
  3758. onClick={() => setShowTagManagement(true)}
  3759. 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"
  3760. title={t('archives.manageTags')}
  3761. >
  3762. <Settings className="w-4 h-4" />
  3763. </button>
  3764. </div>
  3765. )}
  3766. <div className="flex items-center gap-2 flex-shrink-0">
  3767. <ArrowUpDown className="w-4 h-4 text-bambu-gray hidden md:block" />
  3768. <select
  3769. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3770. value={sortBy}
  3771. onChange={(e) => setSortBy(e.target.value as SortOption)}
  3772. >
  3773. <option value="date-desc">{t('archives.sortNewest')}</option>
  3774. <option value="date-asc">{t('archives.sortOldest')}</option>
  3775. <option value="name-asc">{t('archives.sortName')} A-Z</option>
  3776. <option value="name-desc">{t('archives.sortName')} Z-A</option>
  3777. <option value="size-desc">{t('archives.sortLargest')}</option>
  3778. <option value="size-asc">{t('archives.sortSmallest')}</option>
  3779. </select>
  3780. </div>
  3781. </div>
  3782. {hasTopFilters && (
  3783. <Button
  3784. variant="ghost"
  3785. size="sm"
  3786. onClick={clearTopFilters}
  3787. className="text-bambu-gray hover:text-white"
  3788. >
  3789. <X className="w-4 h-4" />
  3790. Reset
  3791. </Button>
  3792. )}
  3793. </div>
  3794. {/* Color Filter */}
  3795. {uniqueColors.length > 0 && (
  3796. <div className="flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary">
  3797. <span className="text-xs text-bambu-gray">Colors:</span>
  3798. {filterColors.size > 1 && (
  3799. <button
  3800. onClick={() => setColorFilterMode(m => m === 'or' ? 'and' : 'or')}
  3801. className={`px-2 py-0.5 text-xs rounded transition-colors ${
  3802. colorFilterMode === 'and'
  3803. ? 'bg-bambu-green text-white'
  3804. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white'
  3805. }`}
  3806. title={colorFilterMode === 'or' ? 'Match ANY selected color' : 'Match ALL selected colors'}
  3807. >
  3808. {colorFilterMode.toUpperCase()}
  3809. </button>
  3810. )}
  3811. <div className="flex items-center gap-1.5 flex-wrap">
  3812. {uniqueColors.map((color) => (
  3813. <button
  3814. key={color}
  3815. onClick={() => toggleColor(color)}
  3816. className={`w-6 h-6 rounded-full border-2 transition-all ${
  3817. filterColors.has(color)
  3818. ? 'border-bambu-green scale-110'
  3819. : 'border-white/20 hover:border-white/40'
  3820. }`}
  3821. style={{ backgroundColor: color }}
  3822. title={color}
  3823. />
  3824. ))}
  3825. </div>
  3826. {filterColors.size > 0 && (
  3827. <button
  3828. onClick={clearColorFilter}
  3829. className="text-xs text-bambu-gray hover:text-white flex items-center gap-1"
  3830. >
  3831. <X className="w-3 h-3" />
  3832. Clear
  3833. </button>
  3834. )}
  3835. </div>
  3836. )}
  3837. </CardContent>
  3838. </Card>}
  3839. {/* Pending Uploads Panel (visible when in queue mode with pending files) */}
  3840. <PendingUploadsPanel />
  3841. {/* Archives */}
  3842. {isLoading ? (
  3843. <div className="text-center py-12 text-bambu-gray">{t('archives.loadingArchives')}</div>
  3844. ) : filteredArchives?.length === 0 && viewMode !== 'log' ? (
  3845. // The log view is exempt: `print_log_entries` is an independent table
  3846. // that outlives the archives it refers to (deleting an archive only
  3847. // NULLs the FK), so "no archives" says nothing about whether there is
  3848. // a log to show. Without the guard, purging archives made the whole
  3849. // Print Log unreachable — the view has its own empty state below.
  3850. <Card>
  3851. <CardContent className="text-center py-12">
  3852. <p className="text-bambu-gray">
  3853. {search ? t('archives.noArchivesSearch') : t('archives.noArchivesYet')}
  3854. </p>
  3855. <p className="text-sm text-bambu-gray mt-2">
  3856. Archives are created automatically when prints complete
  3857. </p>
  3858. </CardContent>
  3859. </Card>
  3860. ) : viewMode === 'calendar' ? (
  3861. <Card className="p-6">
  3862. <CalendarView
  3863. archives={filteredArchives || []}
  3864. onArchiveClick={(archive) => {
  3865. // Switch to grid view and highlight the archive
  3866. setSearch(''); // Clear search to show all archives
  3867. setViewMode('grid');
  3868. setHighlightedArchiveId(archive.id);
  3869. }}
  3870. highlightedArchiveId={highlightedArchiveId}
  3871. />
  3872. </Card>
  3873. ) : viewMode === 'grid' ? (
  3874. <>
  3875. <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
  3876. {paginatedArchives?.map((archive) => (
  3877. <ArchiveCard
  3878. key={archive.id}
  3879. archive={archive}
  3880. printerName={archive.printer_id ? printerMap.get(archive.printer_id) || 'Unknown' : (archive.sliced_for_model || 'No Printer')}
  3881. printerMap={printerMap}
  3882. isSelected={selectedIds.has(archive.id)}
  3883. onSelect={toggleSelect}
  3884. selectionMode={selectionMode}
  3885. projects={projects}
  3886. isHighlighted={archive.id === highlightedArchiveId}
  3887. timeFormat={timeFormat}
  3888. preferredSlicer={preferredSlicer}
  3889. useSlicerApi={useSlicerApi}
  3890. currency={currency}
  3891. t={t}
  3892. onNavigateToArchive={handleNavigateToArchive}
  3893. />
  3894. ))}
  3895. </div>
  3896. <ArchivePaginationBar
  3897. pageIndex={pageIndex}
  3898. pageSize={pageSize}
  3899. totalRows={totalFiltered}
  3900. totalPages={totalPages}
  3901. onPageChange={setPageIndex}
  3902. onPageSizeChange={(size) => { setPageSize(size); setPageIndex(0); }}
  3903. t={t}
  3904. />
  3905. </>
  3906. ) : viewMode === 'list' ? (
  3907. <>
  3908. <Card>
  3909. <div className="divide-y divide-bambu-dark-tertiary">
  3910. {/* List Header */}
  3911. <div className="grid grid-cols-12 gap-4 px-4 py-3 text-xs text-bambu-gray font-medium">
  3912. <div className="col-span-1"></div>
  3913. <div className="col-span-4">Name</div>
  3914. <div className="col-span-2">Printer</div>
  3915. <div className="col-span-2">Date</div>
  3916. <div className="col-span-1">Size</div>
  3917. <div className="col-span-2 text-right">Actions</div>
  3918. </div>
  3919. {/* List Items */}
  3920. {paginatedArchives?.map((archive) => (
  3921. <ArchiveListRow
  3922. key={archive.id}
  3923. archive={archive}
  3924. printerName={archive.printer_id ? printerMap.get(archive.printer_id) || 'Unknown' : (archive.sliced_for_model || 'No Printer')}
  3925. isSelected={selectedIds.has(archive.id)}
  3926. onSelect={toggleSelect}
  3927. selectionMode={selectionMode}
  3928. projects={projects}
  3929. isHighlighted={archive.id === highlightedArchiveId}
  3930. preferredSlicer={preferredSlicer}
  3931. useSlicerApi={useSlicerApi}
  3932. t={t}
  3933. onNavigateToArchive={handleNavigateToArchive}
  3934. />
  3935. ))}
  3936. </div>
  3937. </Card>
  3938. <ArchivePaginationBar
  3939. pageIndex={pageIndex}
  3940. pageSize={pageSize}
  3941. totalRows={totalFiltered}
  3942. totalPages={totalPages}
  3943. onPageChange={setPageIndex}
  3944. onPageSizeChange={(size) => { setPageSize(size); setPageIndex(0); }}
  3945. t={t}
  3946. />
  3947. </>
  3948. ) : viewMode === 'log' ? (
  3949. <div className="space-y-4">
  3950. {/* Log filters */}
  3951. <Card>
  3952. <CardContent className="py-3">
  3953. <div className="flex flex-col md:flex-row gap-3 md:items-center md:flex-wrap">
  3954. {/* Search */}
  3955. <div className="flex-1 relative md:min-w-[200px]">
  3956. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  3957. <input
  3958. type="text"
  3959. placeholder={t('archives.searchPlaceholder')}
  3960. 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"
  3961. value={search}
  3962. onChange={(e) => { setSearch(e.target.value); setLogOffset(0); }}
  3963. />
  3964. </div>
  3965. {/* Printer filter */}
  3966. <select
  3967. 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"
  3968. value={filterPrinter || ''}
  3969. onChange={(e) => { setFilterPrinter(e.target.value ? Number(e.target.value) : null); setLogOffset(0); }}
  3970. >
  3971. <option value="">{t('archives.log.allPrinters')}</option>
  3972. {printers?.map((p) => (
  3973. <option key={p.id} value={p.id}>{p.name}</option>
  3974. ))}
  3975. </select>
  3976. {/* User filter */}
  3977. <select
  3978. 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"
  3979. value={logFilterUser || ''}
  3980. onChange={(e) => { setLogFilterUser(e.target.value || null); setLogOffset(0); }}
  3981. >
  3982. <option value="">{t('archives.log.allUsers')}</option>
  3983. {users?.map((u) => (
  3984. <option key={u.id} value={u.username}>{u.username}</option>
  3985. ))}
  3986. </select>
  3987. {/* Status filter */}
  3988. <select
  3989. 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"
  3990. value={logFilterStatus || ''}
  3991. onChange={(e) => { setLogFilterStatus(e.target.value || null); setLogOffset(0); }}
  3992. >
  3993. <option value="">{t('archives.log.allStatuses')}</option>
  3994. <option value="completed">{t('archives.status.completed')}</option>
  3995. <option value="failed">{t('archives.status.failed')}</option>
  3996. <option value="stopped">{t('archives.status.stopped')}</option>
  3997. <option value="cancelled">{t('archives.log.cancelled')}</option>
  3998. <option value="skipped">{t('archives.log.skipped')}</option>
  3999. </select>
  4000. {/* Date range */}
  4001. <div className="flex items-center gap-2">
  4002. <label className="text-sm text-bambu-gray">{t('archives.log.dateFrom')}</label>
  4003. <input
  4004. type="date"
  4005. 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"
  4006. value={logFilterDateFrom}
  4007. onChange={(e) => { setLogFilterDateFrom(e.target.value); setLogOffset(0); }}
  4008. />
  4009. </div>
  4010. <div className="flex items-center gap-2">
  4011. <label className="text-sm text-bambu-gray">{t('archives.log.dateTo')}</label>
  4012. <input
  4013. type="date"
  4014. 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"
  4015. value={logFilterDateTo}
  4016. onChange={(e) => { setLogFilterDateTo(e.target.value); setLogOffset(0); }}
  4017. />
  4018. </div>
  4019. {/* Columns + clear log */}
  4020. <div className="ml-auto flex items-center gap-2">
  4021. {/* #2636: the log carries more per-run data than fits on one
  4022. screen, so which columns show is the user's choice. */}
  4023. <button
  4024. type="button"
  4025. onClick={() => setShowLogColumnModal(true)}
  4026. className="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-bambu-gray border border-bambu-dark-tertiary rounded-lg hover:bg-bambu-dark-tertiary transition-colors"
  4027. title={t('inventory.configureColumns')}
  4028. >
  4029. <Columns className="w-4 h-4" />
  4030. <span className="hidden sm:inline">{t('archives.log.columns')}</span>
  4031. </button>
  4032. <Button
  4033. variant="danger"
  4034. size="sm"
  4035. onClick={() => setShowClearLogConfirm(true)}
  4036. disabled={!hasPermission('archives:delete_all') || clearLogMutation.isPending}
  4037. >
  4038. <Trash2 className="w-4 h-4" />
  4039. {t('archives.log.clearLog')}
  4040. </Button>
  4041. </div>
  4042. </div>
  4043. </CardContent>
  4044. </Card>
  4045. {/* Log table */}
  4046. <Card>
  4047. {isLogLoading ? (
  4048. <div className="flex items-center justify-center py-12">
  4049. <Loader2 className="w-6 h-6 animate-spin text-bambu-green" />
  4050. </div>
  4051. ) : !printLogData?.items.length ? (
  4052. <div className="text-center py-12 text-bambu-gray">
  4053. {t('archives.log.noEntries')}
  4054. </div>
  4055. ) : (
  4056. <>
  4057. <div className="overflow-x-auto">
  4058. <table className="w-full text-sm">
  4059. <thead>
  4060. <tr className="border-b border-bambu-dark-tertiary text-bambu-gray text-left">
  4061. {visibleLogColumns.map((colId) => {
  4062. const sortable = SORTABLE_LOG_COLUMNS.has(colId);
  4063. const isActive = logSort.column === colId;
  4064. const label = t(LOG_COLUMN_LABEL_KEYS[colId] ?? colId);
  4065. return (
  4066. <th
  4067. key={colId}
  4068. scope="col"
  4069. aria-sort={
  4070. isActive ? (logSort.direction === 'asc' ? 'ascending' : 'descending') : 'none'
  4071. }
  4072. className={`px-4 py-3 font-medium ${LOG_NUMERIC_COLUMNS.has(colId) ? 'text-right' : ''}`}
  4073. >
  4074. {sortable ? (
  4075. <button
  4076. type="button"
  4077. onClick={() => handleLogSort(colId)}
  4078. className={`inline-flex items-center gap-1 font-medium transition-colors hover:text-bambu-green ${
  4079. isActive ? 'text-bambu-green' : ''
  4080. }`}
  4081. title={t('archives.log.sortBy', { column: label })}
  4082. >
  4083. {label}
  4084. {isActive ? (
  4085. logSort.direction === 'asc' ? (
  4086. <ChevronUp className="w-3.5 h-3.5" />
  4087. ) : (
  4088. <ChevronDown className="w-3.5 h-3.5" />
  4089. )
  4090. ) : (
  4091. // Held at low opacity rather than omitted, so
  4092. // the header doesn't shift sideways when it
  4093. // becomes the active sort.
  4094. <ArrowUpDown className="w-3.5 h-3.5 opacity-30" />
  4095. )}
  4096. </button>
  4097. ) : (
  4098. label
  4099. )}
  4100. </th>
  4101. );
  4102. })}
  4103. <th className="px-4 py-3 font-medium w-10" aria-label={t('common.actions')} />
  4104. </tr>
  4105. </thead>
  4106. <tbody className="divide-y divide-bambu-dark-tertiary">
  4107. {printLogData.items.map((entry) => (
  4108. <tr key={entry.id} className="hover:bg-bambu-dark-secondary/50">
  4109. {visibleLogColumns.map((colId) => (
  4110. <td
  4111. key={colId}
  4112. className={`px-4 py-3 ${LOG_NUMERIC_COLUMNS.has(colId) ? 'text-right' : ''}`}
  4113. >
  4114. {renderLogCell(colId, entry)}
  4115. </td>
  4116. ))}
  4117. <td className="px-4 py-3 text-right">
  4118. <div className="inline-flex items-center gap-2">
  4119. <button
  4120. type="button"
  4121. onClick={() => {
  4122. setEditingLogEntry(entry);
  4123. setEditingLogFailureReason(entry.failure_reason || '');
  4124. setEditingLogStatus(entry.status);
  4125. }}
  4126. disabled={
  4127. updateLogEntryMutation.isPending ||
  4128. !(hasPermission('archives:update_all') || hasPermission('archives:update_own'))
  4129. }
  4130. title={
  4131. hasPermission('archives:update_all') || hasPermission('archives:update_own')
  4132. ? t('archives.log.editEntryTitle')
  4133. : t('archives.permission.noEdit')
  4134. }
  4135. className="text-bambu-gray hover:text-bambu-blue disabled:opacity-40 disabled:hover:text-bambu-gray transition-colors"
  4136. >
  4137. <Pencil className="w-4 h-4" />
  4138. </button>
  4139. <button
  4140. type="button"
  4141. onClick={() => setPendingDeleteEntryId(entry.id)}
  4142. disabled={
  4143. deleteLogEntryMutation.isPending ||
  4144. !(hasPermission('archives:delete_all') || hasPermission('archives:delete_own'))
  4145. }
  4146. title={
  4147. hasPermission('archives:delete_all') || hasPermission('archives:delete_own')
  4148. ? t('archives.log.deleteEntryTitle')
  4149. : t('archives.permission.noDelete')
  4150. }
  4151. className="text-bambu-gray hover:text-red-600 dark:hover:text-red-400 disabled:opacity-40 disabled:hover:text-bambu-gray transition-colors"
  4152. >
  4153. <Trash2 className="w-4 h-4" />
  4154. </button>
  4155. </div>
  4156. </td>
  4157. </tr>
  4158. ))}
  4159. </tbody>
  4160. </table>
  4161. </div>
  4162. {/* Pagination */}
  4163. <div className="flex items-center justify-between px-4 py-3 border-t border-bambu-dark-tertiary flex-wrap gap-2">
  4164. <div className="flex items-center gap-3">
  4165. <span className="text-sm text-bambu-gray">
  4166. {t('archives.log.showing', { count: Math.min(logOffset + logPageSize, printLogData.total), total: printLogData.total })}
  4167. </span>
  4168. <div className="flex items-center gap-1.5">
  4169. <label className="text-xs text-bambu-gray">{t('archives.log.rowsPerPage')}</label>
  4170. <select
  4171. 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"
  4172. value={logPageSize}
  4173. onChange={(e) => { setLogPageSize(Number(e.target.value)); setLogOffset(0); }}
  4174. >
  4175. <option value={10}>10</option>
  4176. <option value={25}>25</option>
  4177. <option value={50}>50</option>
  4178. <option value={100}>100</option>
  4179. </select>
  4180. </div>
  4181. </div>
  4182. <div className="flex items-center gap-2">
  4183. <span className="text-sm text-bambu-gray">
  4184. {t('archives.log.page')} {Math.floor(logOffset / logPageSize) + 1} / {Math.max(1, Math.ceil(printLogData.total / logPageSize))}
  4185. </span>
  4186. <Button variant="secondary" size="sm" onClick={() => setLogOffset(Math.max(0, logOffset - logPageSize))} disabled={logOffset === 0}>
  4187. <ChevronLeft className="w-4 h-4" />
  4188. </Button>
  4189. <Button variant="secondary" size="sm" onClick={() => setLogOffset(logOffset + logPageSize)} disabled={logOffset + logPageSize >= printLogData.total}>
  4190. <ChevronRight className="w-4 h-4" />
  4191. </Button>
  4192. </div>
  4193. </div>
  4194. </>
  4195. )}
  4196. </Card>
  4197. </div>
  4198. ) : null}
  4199. {/* Upload Modal */}
  4200. {showUpload && (
  4201. <UploadModal
  4202. onClose={() => {
  4203. setShowUpload(false);
  4204. setUploadFiles([]);
  4205. }}
  4206. initialFiles={uploadFiles}
  4207. />
  4208. )}
  4209. {/* Archive bulk-purge modal (#1008 follow-up) */}
  4210. {showPurgeModal && (
  4211. <PurgeArchivesModal onClose={() => setShowPurgeModal(false)} />
  4212. )}
  4213. {/* Bulk Delete Confirmation */}
  4214. {showBulkDeleteConfirm && (
  4215. <ConfirmModal
  4216. title={t('archives.modal.deleteArchives')}
  4217. message={t('archives.modal.deleteArchivesConfirm', { count: selectedIds.size })}
  4218. confirmText={t('archives.modal.deleteCount', { count: selectedIds.size })}
  4219. variant="danger"
  4220. onConfirm={() => {
  4221. bulkDeleteMutation.mutate(Array.from(selectedIds));
  4222. setShowBulkDeleteConfirm(false);
  4223. }}
  4224. onCancel={() => setShowBulkDeleteConfirm(false)}
  4225. />
  4226. )}
  4227. {/* Batch Tag Modal */}
  4228. {showBatchTag && (
  4229. <BatchTagModal
  4230. selectedIds={Array.from(selectedIds)}
  4231. existingTags={uniqueTags}
  4232. onClose={() => setShowBatchTag(false)}
  4233. />
  4234. )}
  4235. {/* Batch Project Modal */}
  4236. {showBatchProject && (
  4237. <BatchProjectModal
  4238. selectedIds={Array.from(selectedIds)}
  4239. onClose={() => setShowBatchProject(false)}
  4240. />
  4241. )}
  4242. {/* Compare Archives Modal */}
  4243. {showCompareModal && selectedIds.size >= 2 && selectedIds.size <= 5 && (
  4244. <CompareArchivesModal
  4245. archiveIds={Array.from(selectedIds)}
  4246. onClose={() => {
  4247. setShowCompareModal(false);
  4248. setSelectedIds(new Set());
  4249. setIsSelectionMode(false);
  4250. }}
  4251. />
  4252. )}
  4253. {/* Tag Management Modal */}
  4254. {showTagManagement && (
  4255. <TagManagementModal onClose={() => setShowTagManagement(false)} />
  4256. )}
  4257. {/* Print Log column picker (#2636) */}
  4258. <ColumnConfigModal
  4259. isOpen={showLogColumnModal}
  4260. onClose={() => setShowLogColumnModal(false)}
  4261. columns={logColumnConfig}
  4262. defaultColumns={defaultLogColumnConfig}
  4263. onSave={handleLogColumnSave}
  4264. />
  4265. {/* Clear Log Confirmation */}
  4266. {showClearLogConfirm && (
  4267. <ConfirmModal
  4268. title={t('archives.log.clearLogTitle')}
  4269. message={t('archives.log.clearLogConfirm')}
  4270. confirmText={t('archives.log.clearLogButton')}
  4271. variant="danger"
  4272. onConfirm={() => {
  4273. clearLogMutation.mutate();
  4274. setShowClearLogConfirm(false);
  4275. }}
  4276. onCancel={() => setShowClearLogConfirm(false)}
  4277. />
  4278. )}
  4279. {/* Per-row Print Log entry delete confirmation (#1687) */}
  4280. {pendingDeleteEntryId !== null && (
  4281. <ConfirmModal
  4282. title={t('archives.log.deleteEntryTitle')}
  4283. message={t('archives.log.deleteEntryConfirm')}
  4284. confirmText={t('common.delete')}
  4285. variant="danger"
  4286. onConfirm={() => {
  4287. deleteLogEntryMutation.mutate(pendingDeleteEntryId);
  4288. setPendingDeleteEntryId(null);
  4289. }}
  4290. onCancel={() => setPendingDeleteEntryId(null)}
  4291. />
  4292. )}
  4293. {/* Per-row Print Log classification editor (#1687 part 4).
  4294. Reuses editArchive.failureReasons.* and archives.log.statuses.*
  4295. vocabularies so the dropdown stays in lockstep with the
  4296. Archive Edit modal — backend validates against the same list. */}
  4297. {editingLogEntry !== null && (
  4298. <div
  4299. className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
  4300. onClick={() => setEditingLogEntry(null)}
  4301. >
  4302. <div
  4303. className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg w-full max-w-md mx-4 p-6"
  4304. onClick={(e) => e.stopPropagation()}
  4305. >
  4306. <h3 className="text-lg font-semibold text-white mb-4">
  4307. {t('archives.log.editEntryTitle')}
  4308. </h3>
  4309. <p className="text-xs text-bambu-gray mb-4">
  4310. {t('archives.log.editEntryDescription')}
  4311. </p>
  4312. <div className="space-y-4">
  4313. <div>
  4314. <label className="block text-sm text-bambu-gray mb-1">
  4315. {t('editArchive.status')}
  4316. </label>
  4317. <select
  4318. value={editingLogStatus}
  4319. onChange={(e) => setEditingLogStatus(e.target.value)}
  4320. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"
  4321. >
  4322. <option value="completed">{t('archives.log.statuses.completed', { defaultValue: 'completed' })}</option>
  4323. <option value="failed">{t('archives.log.statuses.failed', { defaultValue: 'failed' })}</option>
  4324. <option value="stopped">{t('archives.log.statuses.stopped', { defaultValue: 'stopped' })}</option>
  4325. <option value="cancelled">{t('archives.log.statuses.cancelled', { defaultValue: 'cancelled' })}</option>
  4326. <option value="skipped">{t('archives.log.statuses.skipped', { defaultValue: 'skipped' })}</option>
  4327. </select>
  4328. </div>
  4329. <div>
  4330. <label className="block text-sm text-bambu-gray mb-1">
  4331. {t('editArchive.failureReason')}
  4332. </label>
  4333. <select
  4334. value={editingLogFailureReason}
  4335. onChange={(e) => setEditingLogFailureReason(e.target.value)}
  4336. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"
  4337. >
  4338. <option value="">{t('editArchive.selectReason')}</option>
  4339. {FAILURE_REASON_KEYS.map((key) => (
  4340. <option key={key} value={key}>
  4341. {t(`editArchive.failureReasons.${key}`)}
  4342. </option>
  4343. ))}
  4344. </select>
  4345. </div>
  4346. </div>
  4347. <div className="flex justify-end gap-2 mt-6">
  4348. <Button
  4349. variant="secondary"
  4350. onClick={() => setEditingLogEntry(null)}
  4351. >
  4352. {t('common.cancel')}
  4353. </Button>
  4354. <Button
  4355. variant="primary"
  4356. onClick={() => {
  4357. const body: { failure_reason?: string | null; status?: string } = {};
  4358. // Send failure_reason only if it changed — empty string
  4359. // clears the classification (backend stores it as NULL).
  4360. if (editingLogFailureReason !== (editingLogEntry.failure_reason || '')) {
  4361. body.failure_reason = editingLogFailureReason || null;
  4362. }
  4363. if (editingLogStatus !== editingLogEntry.status) {
  4364. body.status = editingLogStatus;
  4365. }
  4366. if (Object.keys(body).length === 0) {
  4367. setEditingLogEntry(null);
  4368. return;
  4369. }
  4370. updateLogEntryMutation.mutate({ id: editingLogEntry.id, body });
  4371. }}
  4372. disabled={updateLogEntryMutation.isPending}
  4373. >
  4374. {updateLogEntryMutation.isPending ? t('editArchive.saving') : t('common.save')}
  4375. </Button>
  4376. </div>
  4377. </div>
  4378. </div>
  4379. )}
  4380. </div>
  4381. );
  4382. }
  4383. /* Pagination bar for archives grid/list views */
  4384. function ArchivePaginationBar({
  4385. pageIndex, pageSize, totalRows, totalPages, onPageChange, onPageSizeChange, t,
  4386. }: {
  4387. pageIndex: number;
  4388. pageSize: number;
  4389. totalRows: number;
  4390. totalPages: number;
  4391. onPageChange: (page: number) => void;
  4392. onPageSizeChange: (size: number) => void;
  4393. t: (key: string) => string;
  4394. }) {
  4395. const isShowAll = pageSize === -1;
  4396. if (totalPages <= 1 && !isShowAll) return null;
  4397. const effectiveSize = isShowAll ? totalRows || 1 : pageSize;
  4398. return (
  4399. <div className="flex items-center justify-between pt-2 text-sm">
  4400. <span className="text-bambu-gray">
  4401. {isShowAll
  4402. ? `${totalRows} ${t('archives.prints')}`
  4403. : <>{t('archives.pagination.showing')} {pageIndex * effectiveSize + 1} {t('archives.pagination.to')}{' '}
  4404. {Math.min((pageIndex + 1) * effectiveSize, totalRows)}{' '}
  4405. {t('archives.pagination.of')} {totalRows} {t('archives.prints')}</>
  4406. }
  4407. </span>
  4408. <div className="flex items-center gap-2">
  4409. <span className="text-bambu-gray">{t('archives.pagination.show')}</span>
  4410. <select
  4411. value={pageSize}
  4412. onChange={(e) => onPageSizeChange(Number(e.target.value))}
  4413. 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"
  4414. >
  4415. {[25, 50, 100, 200].map((n) => (
  4416. <option key={n} value={n}>{n}</option>
  4417. ))}
  4418. <option value={-1}>{t('archives.pagination.all')}</option>
  4419. </select>
  4420. {!isShowAll && (
  4421. <>
  4422. <button
  4423. onClick={() => onPageChange(0)}
  4424. disabled={pageIndex === 0}
  4425. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  4426. >
  4427. <ChevronsLeft className="w-4 h-4" />
  4428. </button>
  4429. <button
  4430. onClick={() => onPageChange(Math.max(0, pageIndex - 1))}
  4431. disabled={pageIndex === 0}
  4432. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  4433. >
  4434. <ChevronLeft className="w-4 h-4" />
  4435. </button>
  4436. <span className="text-bambu-gray px-2 whitespace-nowrap">
  4437. {t('archives.pagination.page')} {pageIndex + 1} {t('archives.pagination.of')} {totalPages}
  4438. </span>
  4439. <button
  4440. onClick={() => onPageChange(Math.min(totalPages - 1, pageIndex + 1))}
  4441. disabled={pageIndex >= totalPages - 1}
  4442. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  4443. >
  4444. <ChevronRight className="w-4 h-4" />
  4445. </button>
  4446. <button
  4447. onClick={() => onPageChange(totalPages - 1)}
  4448. disabled={pageIndex >= totalPages - 1}
  4449. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  4450. >
  4451. <ChevronsRight className="w-4 h-4" />
  4452. </button>
  4453. </>
  4454. )}
  4455. </div>
  4456. </div>
  4457. );
  4458. }