ArchivesPage.tsx 192 KB

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