ArchivesPage.tsx 192 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661
  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. const { data: users } = useQuery({
  2817. queryKey: ['users'],
  2818. queryFn: api.getUsers,
  2819. enabled: viewMode === 'log',
  2820. });
  2821. const { data: printLogData, isLoading: isLogLoading } = useQuery({
  2822. queryKey: ['print-log', filterPrinter, logFilterUser, logFilterStatus, logFilterDateFrom, logFilterDateTo, search, logOffset, logPageSize, logSort.column, logSort.direction],
  2823. queryFn: () => api.getPrintLog({
  2824. search: search || undefined,
  2825. printerId: filterPrinter || undefined,
  2826. username: logFilterUser || undefined,
  2827. status: logFilterStatus || undefined,
  2828. dateFrom: logFilterDateFrom || undefined,
  2829. dateTo: logFilterDateTo || undefined,
  2830. limit: logPageSize,
  2831. offset: logOffset,
  2832. sortBy: logSort.column,
  2833. sortDir: logSort.direction,
  2834. }),
  2835. enabled: viewMode === 'log',
  2836. });
  2837. const timeFormat: TimeFormat = settings?.time_format || 'system';
  2838. // Desktop "Open in Slicer" target — falls back to preferred_slicer when the
  2839. // user hasn't explicitly chosen a different desktop slicer (#1329). This is
  2840. // ONLY the URI-handoff target; the in-app SliceModal still uses
  2841. // preferred_slicer for the sidecar.
  2842. const preferredSlicer: SlicerType = resolveDesktopSlicer(settings?.open_in_slicer, settings?.preferred_slicer);
  2843. const useSlicerApi = settings?.use_slicer_api ?? false;
  2844. const currency = getCurrencySymbol(settings?.currency || 'USD');
  2845. // Print Log columns, with labels translated at render time (#2636).
  2846. const logColumnConfig: ColumnConfig[] = useMemo(
  2847. () =>
  2848. logColumns.map((c) => ({
  2849. ...c,
  2850. label: t(LOG_COLUMN_LABEL_KEYS[c.id] ?? c.id),
  2851. })),
  2852. [logColumns, t],
  2853. );
  2854. const defaultLogColumnConfig: ColumnConfig[] = useMemo(
  2855. () =>
  2856. DEFAULT_LOG_COLUMNS.map((c) => ({
  2857. ...c,
  2858. label: t(LOG_COLUMN_LABEL_KEYS[c.id] ?? c.id),
  2859. })),
  2860. [t],
  2861. );
  2862. // Click a header to sort by it; click again to flip. Dates, durations and
  2863. // amounts open on descending — "newest / biggest first" is what someone
  2864. // reaching for those wants — while text opens A-Z.
  2865. const handleLogSort = useCallback((colId: string) => {
  2866. if (!SORTABLE_LOG_COLUMNS.has(colId)) return;
  2867. setLogSort((prev) => {
  2868. const numericFirstDesc = ['date', 'completed_at', 'duration', 'filament_used', 'cost', 'energy', 'energy_cost'];
  2869. const next: LogSortState =
  2870. prev.column === colId
  2871. ? { column: colId, direction: prev.direction === 'asc' ? 'desc' : 'asc' }
  2872. : { column: colId, direction: numericFirstDesc.includes(colId) ? 'desc' : 'asc' };
  2873. saveLogSort(next);
  2874. return next;
  2875. });
  2876. // Page 1 of the new order, not whatever offset the old one was on —
  2877. // otherwise sorting by cost from page 3 lands you in the middle of the
  2878. // re-sorted list with no indication why.
  2879. setLogOffset(0);
  2880. }, []);
  2881. const handleLogColumnSave = useCallback((config: ColumnConfig[]) => {
  2882. const stripped = config.map((c) => ({ id: c.id, visible: c.visible }));
  2883. setLogColumns(stripped);
  2884. saveLogColumnConfig(stripped);
  2885. }, []);
  2886. // Columns that hold a number and read better right-aligned. Kept as data so
  2887. // the header and the body can't drift apart.
  2888. const LOG_NUMERIC_COLUMNS = useMemo(
  2889. () => new Set(['duration', 'filament_used', 'cost', 'energy', 'energy_cost']),
  2890. [],
  2891. );
  2892. const renderLogCell = useCallback(
  2893. (colId: string, entry: PrintLogEntry) => {
  2894. switch (colId) {
  2895. case 'date':
  2896. return (
  2897. <span className="text-white whitespace-nowrap">
  2898. {formatDateTime(entry.started_at || entry.created_at, timeFormat)}
  2899. </span>
  2900. );
  2901. case 'completed_at':
  2902. return (
  2903. <span className="text-bambu-gray-light whitespace-nowrap">
  2904. {entry.completed_at ? formatDateTime(entry.completed_at, timeFormat) : '—'}
  2905. </span>
  2906. );
  2907. case 'print_name':
  2908. return (
  2909. <div className="flex items-center gap-2">
  2910. {entry.thumbnail_path && (
  2911. <img
  2912. src={api.getPrintLogThumbnail(entry.id)}
  2913. alt=""
  2914. className="w-8 h-8 rounded object-cover flex-shrink-0"
  2915. onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }}
  2916. />
  2917. )}
  2918. <span className="text-white break-words" title={entry.print_name || ''}>
  2919. {entry.print_name || '—'}
  2920. </span>
  2921. </div>
  2922. );
  2923. case 'printer':
  2924. return <span className="text-bambu-gray-light">{entry.printer_name || '—'}</span>;
  2925. case 'user':
  2926. return <span className="text-bambu-gray-light">{entry.created_by_username || '—'}</span>;
  2927. case 'status':
  2928. return (
  2929. <>
  2930. <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
  2931. entry.status === 'completed' ? 'bg-green-100 dark:bg-green-500/20 text-green-700 dark:text-green-400' :
  2932. entry.status === 'failed' ? 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400' :
  2933. entry.status === 'stopped' ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400' :
  2934. entry.status === 'cancelled' ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400' :
  2935. entry.status === 'skipped' ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400' :
  2936. 'bg-gray-500/20 text-gray-400'
  2937. }`}>
  2938. {entry.status}
  2939. </span>
  2940. {entry.failure_reason && (
  2941. <span className="block text-[10px] text-bambu-gray mt-0.5">
  2942. {t(`editArchive.failureReasons.${entry.failure_reason}`, { defaultValue: entry.failure_reason })}
  2943. </span>
  2944. )}
  2945. </>
  2946. );
  2947. case 'duration':
  2948. return (
  2949. <span className="text-bambu-gray-light whitespace-nowrap">
  2950. {entry.duration_seconds ? formatDuration(entry.duration_seconds) : '—'}
  2951. </span>
  2952. );
  2953. case 'filament':
  2954. return (
  2955. <div className="flex items-center gap-1.5">
  2956. {entry.filament_color && (
  2957. <div className="flex items-center gap-0.5 flex-wrap">
  2958. {entry.filament_color.split(',').map((color, i) => {
  2959. const trimmed = color.trim();
  2960. return (
  2961. <span
  2962. key={i}
  2963. className="w-3 h-3 rounded-full border border-black/20 flex-shrink-0"
  2964. style={{ backgroundColor: trimmed.startsWith('#') ? trimmed : undefined }}
  2965. title={trimmed}
  2966. />
  2967. );
  2968. })}
  2969. </div>
  2970. )}
  2971. <span className="text-bambu-gray-light text-xs">
  2972. {entry.filament_type || '—'}
  2973. </span>
  2974. </div>
  2975. );
  2976. case 'filament_used':
  2977. // Per-run actual, not the archive's estimate: partial prints are
  2978. // scaled to progress and multi-plate archives are scoped to the
  2979. // plate that printed. One decimal matches the per-archive log table.
  2980. return (
  2981. <span className="text-bambu-gray-light whitespace-nowrap tabular-nums">
  2982. {entry.filament_used_grams != null ? `${entry.filament_used_grams.toFixed(1)} g` : '—'}
  2983. </span>
  2984. );
  2985. case 'cost':
  2986. return (
  2987. <span className="text-bambu-gray-light whitespace-nowrap tabular-nums">
  2988. {entry.cost != null ? `${currency}${entry.cost.toFixed(2)}` : '—'}
  2989. </span>
  2990. );
  2991. case 'energy':
  2992. // Written by the energy background task after the row itself, so a
  2993. // just-finished print shows "—" for a moment. That is accurate: the
  2994. // measurement genuinely isn't in yet.
  2995. return (
  2996. <span className="text-bambu-gray-light whitespace-nowrap tabular-nums">
  2997. {entry.energy_kwh != null ? `${entry.energy_kwh.toFixed(2)} kWh` : '—'}
  2998. </span>
  2999. );
  3000. case 'energy_cost':
  3001. return (
  3002. <span className="text-bambu-gray-light whitespace-nowrap tabular-nums">
  3003. {entry.energy_cost != null ? `${currency}${entry.energy_cost.toFixed(2)}` : '—'}
  3004. </span>
  3005. );
  3006. default:
  3007. return null;
  3008. }
  3009. },
  3010. [currency, t, timeFormat],
  3011. );
  3012. const bulkDeleteMutation = useMutation({
  3013. mutationFn: async (ids: number[]) => {
  3014. await Promise.all(ids.map((id) => api.deleteArchive(id)));
  3015. return ids.length;
  3016. },
  3017. onSuccess: (count) => {
  3018. invalidateArchiveAndProjectViews(queryClient);
  3019. setSelectedIds(new Set());
  3020. showToast(`${count} archive${count !== 1 ? 's' : ''} deleted`);
  3021. },
  3022. onError: () => {
  3023. showToast(t('archives.toast.failedDeleteArchives'), 'error');
  3024. },
  3025. });
  3026. const clearLogMutation = useMutation({
  3027. mutationFn: () => api.clearPrintLog(),
  3028. onSuccess: (data) => {
  3029. queryClient.invalidateQueries({ queryKey: ['print-log'] });
  3030. setLogOffset(0);
  3031. showToast(t('archives.log.cleared', { count: data.deleted }));
  3032. },
  3033. onError: () => {
  3034. showToast(t('archives.log.clearFailed'), 'error');
  3035. },
  3036. });
  3037. const deleteLogEntryMutation = useMutation({
  3038. mutationFn: (id: number) => api.deletePrintLogEntry(id),
  3039. onSuccess: () => {
  3040. queryClient.invalidateQueries({ queryKey: ['print-log'] });
  3041. queryClient.invalidateQueries({ queryKey: ['archives-stats'] });
  3042. showToast(t('archives.log.entryDeleted'));
  3043. },
  3044. onError: () => {
  3045. showToast(t('archives.log.entryDeleteFailed'), 'error');
  3046. },
  3047. });
  3048. const updateLogEntryMutation = useMutation({
  3049. mutationFn: ({ id, body }: { id: number; body: { failure_reason?: string | null; status?: string } }) =>
  3050. api.updatePrintLogEntry(id, body),
  3051. onSuccess: () => {
  3052. queryClient.invalidateQueries({ queryKey: ['print-log'] });
  3053. // Also invalidate /archives/stats — the Failure Analysis widget there
  3054. // groups by PrintLogEntry.failure_reason, so a re-classification needs
  3055. // to flow through (#1687 part 4).
  3056. queryClient.invalidateQueries({ queryKey: ['archives-stats'] });
  3057. setEditingLogEntry(null);
  3058. showToast(t('archives.log.entryUpdated'));
  3059. },
  3060. onError: () => {
  3061. showToast(t('archives.log.entryUpdateFailed'), 'error');
  3062. },
  3063. });
  3064. // Persist all filters to localStorage
  3065. useEffect(() => {
  3066. if (filterPrinter !== null) {
  3067. localStorage.setItem('archiveFilterPrinter', filterPrinter.toString());
  3068. } else {
  3069. localStorage.removeItem('archiveFilterPrinter');
  3070. }
  3071. }, [filterPrinter]);
  3072. useEffect(() => {
  3073. if (filterMaterial) {
  3074. localStorage.setItem('archiveFilterMaterial', filterMaterial);
  3075. } else {
  3076. localStorage.removeItem('archiveFilterMaterial');
  3077. }
  3078. }, [filterMaterial]);
  3079. useEffect(() => {
  3080. localStorage.setItem('archiveFilterColors', JSON.stringify([...filterColors]));
  3081. }, [filterColors]);
  3082. useEffect(() => {
  3083. localStorage.setItem('archiveColorFilterMode', colorFilterMode);
  3084. }, [colorFilterMode]);
  3085. useEffect(() => {
  3086. localStorage.setItem('archiveFilterFavorites', filterFavorites.toString());
  3087. }, [filterFavorites]);
  3088. useEffect(() => {
  3089. localStorage.setItem('archiveHideFailed', hideFailed.toString());
  3090. }, [hideFailed]);
  3091. useEffect(() => {
  3092. localStorage.setItem('archiveHideDuplicates', hideDuplicates.toString());
  3093. }, [hideDuplicates]);
  3094. useEffect(() => {
  3095. if (filterTag) {
  3096. localStorage.setItem('archiveFilterTag', filterTag);
  3097. } else {
  3098. localStorage.removeItem('archiveFilterTag');
  3099. }
  3100. }, [filterTag]);
  3101. useEffect(() => {
  3102. localStorage.setItem('archiveFilterFileType', filterFileType);
  3103. }, [filterFileType]);
  3104. // Reset page when filters/search/sort/collection change
  3105. useEffect(() => {
  3106. setPageIndex(0);
  3107. }, [search, filterPrinter, filterMaterial, filterColors, colorFilterMode, filterFavorites, hideFailed, hideDuplicates, filterTag, filterFileType, sortBy, collection]);
  3108. useEffect(() => {
  3109. try { localStorage.setItem('archivePageSize', String(pageSize)); } catch { /* ignore */ }
  3110. }, [pageSize]);
  3111. useEffect(() => {
  3112. localStorage.setItem('archiveViewMode', viewMode);
  3113. }, [viewMode]);
  3114. useEffect(() => {
  3115. localStorage.setItem('archiveSortBy', sortBy);
  3116. }, [sortBy]);
  3117. useEffect(() => {
  3118. localStorage.setItem('archiveCollection', collection);
  3119. }, [collection]);
  3120. // Persist log view filters
  3121. useEffect(() => {
  3122. if (logFilterUser) {
  3123. localStorage.setItem('logFilterUser', logFilterUser);
  3124. } else {
  3125. localStorage.removeItem('logFilterUser');
  3126. }
  3127. }, [logFilterUser]);
  3128. useEffect(() => {
  3129. if (logFilterStatus) {
  3130. localStorage.setItem('logFilterStatus', logFilterStatus);
  3131. } else {
  3132. localStorage.removeItem('logFilterStatus');
  3133. }
  3134. }, [logFilterStatus]);
  3135. useEffect(() => {
  3136. if (logFilterDateFrom) {
  3137. localStorage.setItem('logFilterDateFrom', logFilterDateFrom);
  3138. } else {
  3139. localStorage.removeItem('logFilterDateFrom');
  3140. }
  3141. }, [logFilterDateFrom]);
  3142. useEffect(() => {
  3143. if (logFilterDateTo) {
  3144. localStorage.setItem('logFilterDateTo', logFilterDateTo);
  3145. } else {
  3146. localStorage.removeItem('logFilterDateTo');
  3147. }
  3148. }, [logFilterDateTo]);
  3149. useEffect(() => {
  3150. localStorage.setItem('logOffset', logOffset.toString());
  3151. }, [logOffset]);
  3152. useEffect(() => {
  3153. localStorage.setItem('logPageSize', logPageSize.toString());
  3154. }, [logPageSize]);
  3155. // Memoised: it's handed to every ArchiveCard as a prop, and a fresh Map each
  3156. // render would re-run their lookups for no reason.
  3157. const printerMap = useMemo(
  3158. () => new Map<number, string>(printers?.map((p) => [p.id, p.name]) || []),
  3159. [printers],
  3160. );
  3161. // Extract unique materials and colors from archives
  3162. const uniqueMaterials = [...new Set(
  3163. archives?.flatMap(a => a.filament_type?.split(', ') || []).filter(Boolean) || []
  3164. )].sort();
  3165. const uniqueColors = [...new Set(
  3166. archives?.flatMap(a => a.filament_color?.split(',') || []).filter(Boolean) || []
  3167. )];
  3168. const uniqueTags = [...new Set(
  3169. archives?.flatMap(a => a.tags?.split(',').map(t => t.trim()) || []).filter(Boolean) || []
  3170. )].sort();
  3171. const filteredArchives = archives
  3172. ?.filter((a) => {
  3173. // Collection filter
  3174. const now = new Date();
  3175. const archiveDate = parseUTCDate(a.created_at) || new Date(0);
  3176. let matchesCollection = true;
  3177. switch (collection) {
  3178. case 'recent':
  3179. matchesCollection = (now.getTime() - archiveDate.getTime()) < 24 * 60 * 60 * 1000;
  3180. break;
  3181. case 'this-week':
  3182. matchesCollection = (now.getTime() - archiveDate.getTime()) < 7 * 24 * 60 * 60 * 1000;
  3183. break;
  3184. case 'this-month':
  3185. matchesCollection = archiveDate.getMonth() === now.getMonth() && archiveDate.getFullYear() === now.getFullYear();
  3186. break;
  3187. case 'favorites':
  3188. matchesCollection = a.is_favorite === true;
  3189. break;
  3190. case 'not-printed':
  3191. matchesCollection = a.status === 'archived';
  3192. break;
  3193. case 'printed':
  3194. matchesCollection = (PRINTED_STATUSES as readonly string[]).includes(a.status);
  3195. break;
  3196. case 'failed':
  3197. matchesCollection = a.status === 'failed' || a.status === 'aborted';
  3198. break;
  3199. case 'duplicates':
  3200. matchesCollection = a.duplicate_count > 0;
  3201. break;
  3202. }
  3203. // Search filter
  3204. const matchesSearch = (a.print_name || a.filename).toLowerCase().includes(search.toLowerCase());
  3205. // Material filter
  3206. const matchesMaterial = !filterMaterial ||
  3207. (a.filament_type?.split(', ').includes(filterMaterial));
  3208. // Color filter (AND: must have all selected colors, OR: must have any selected color)
  3209. const archiveColors = a.filament_color?.split(',') || [];
  3210. const matchesColor = filterColors.size === 0 ||
  3211. (colorFilterMode === 'or'
  3212. ? archiveColors.some(c => filterColors.has(c))
  3213. : [...filterColors].every(c => archiveColors.includes(c)));
  3214. // Favorites filter (only apply if not using favorites collection)
  3215. const matchesFavorites = collection === 'favorites' || !filterFavorites || a.is_favorite;
  3216. // Hide failed filter (don't apply when viewing failed collection)
  3217. const matchesHideFailed = collection === 'failed' || !hideFailed || (a.status !== 'failed' && a.status !== 'aborted');
  3218. // Hide duplicates filter (don't apply when viewing duplicates collection)
  3219. const matchesHideDuplicates =
  3220. collection === 'duplicates' || !hideDuplicates || a.duplicate_count === 0 || a.duplicate_sequence === 0;
  3221. // Tag filter
  3222. const archiveTags = a.tags?.split(',').map(t => t.trim()) || [];
  3223. const matchesTag = !filterTag || archiveTags.includes(filterTag);
  3224. // File type filter (gcode = sliced, source = project file only)
  3225. const isGcodeFile = isSlicedFile(a);
  3226. const matchesFileType = filterFileType === 'all' ||
  3227. (filterFileType === 'gcode' && isGcodeFile) ||
  3228. (filterFileType === 'source' && !isGcodeFile);
  3229. return matchesCollection && matchesSearch && matchesMaterial && matchesColor && matchesFavorites && matchesHideFailed && matchesHideDuplicates && matchesTag && matchesFileType;
  3230. })
  3231. .sort((a, b) => {
  3232. switch (sortBy) {
  3233. case 'date-desc':
  3234. return (parseUTCDate(b.created_at)?.getTime() || 0) - (parseUTCDate(a.created_at)?.getTime() || 0);
  3235. case 'date-asc':
  3236. return (parseUTCDate(a.created_at)?.getTime() || 0) - (parseUTCDate(b.created_at)?.getTime() || 0);
  3237. case 'name-asc':
  3238. return (a.print_name || a.filename).localeCompare(b.print_name || b.filename);
  3239. case 'name-desc':
  3240. return (b.print_name || b.filename).localeCompare(a.print_name || a.filename);
  3241. case 'size-desc':
  3242. return b.file_size - a.file_size;
  3243. case 'size-asc':
  3244. return a.file_size - b.file_size;
  3245. default:
  3246. return 0;
  3247. }
  3248. });
  3249. // Pagination
  3250. const totalFiltered = filteredArchives?.length || 0;
  3251. const showAll = pageSize === -1;
  3252. const effectivePageSize = showAll ? totalFiltered || 1 : pageSize;
  3253. const totalPages = Math.max(1, Math.ceil(totalFiltered / effectivePageSize));
  3254. const paginatedArchives = showAll
  3255. ? filteredArchives
  3256. : filteredArchives?.slice(pageIndex * effectivePageSize, (pageIndex + 1) * effectivePageSize);
  3257. // Jump to the page containing the highlighted archive
  3258. useEffect(() => {
  3259. if (highlightedArchiveId && filteredArchives && !showAll) {
  3260. const idx = filteredArchives.findIndex(a => a.id === highlightedArchiveId);
  3261. if (idx >= 0) {
  3262. const targetPage = Math.floor(idx / effectivePageSize);
  3263. if (targetPage !== pageIndex) setPageIndex(targetPage);
  3264. }
  3265. }
  3266. // eslint-disable-next-line react-hooks/exhaustive-deps
  3267. }, [highlightedArchiveId]);
  3268. const selectionMode = isSelectionMode || selectedIds.size > 0;
  3269. const toggleSelect = (id: number) => {
  3270. setSelectedIds((prev) => {
  3271. const next = new Set(prev);
  3272. if (next.has(id)) {
  3273. next.delete(id);
  3274. } else {
  3275. next.add(id);
  3276. }
  3277. return next;
  3278. });
  3279. };
  3280. const selectAll = () => {
  3281. if (filteredArchives) {
  3282. setSelectedIds(new Set(filteredArchives.map((a) => a.id)));
  3283. }
  3284. };
  3285. const clearSelection = () => {
  3286. setSelectedIds(new Set());
  3287. setIsSelectionMode(false);
  3288. };
  3289. const toggleColor = (color: string) => {
  3290. setFilterColors((prev) => {
  3291. const next = new Set(prev);
  3292. if (next.has(color)) {
  3293. next.delete(color);
  3294. } else {
  3295. next.add(color);
  3296. }
  3297. return next;
  3298. });
  3299. };
  3300. const clearColorFilter = () => {
  3301. setFilterColors(new Set());
  3302. };
  3303. const clearTopFilters = () => {
  3304. setSearch('');
  3305. setFilterPrinter(null);
  3306. setFilterMaterial(null);
  3307. setFilterFavorites(false);
  3308. setHideFailed(false);
  3309. setHideDuplicates(false);
  3310. setFilterTag(null);
  3311. setFilterFileType('all');
  3312. };
  3313. const hasTopFilters = search || filterPrinter || filterMaterial || filterFavorites || hideFailed || hideDuplicates || filterTag || filterFileType !== 'all';
  3314. // Page-wide drag-and-drop upload (#1510). The hook covers the three cancel
  3315. // paths the previous inline implementation missed (drag-out-of-window, Escape,
  3316. // dragend outside any drop target). Disabled while the upload modal is open
  3317. // so drags into the modal's own drop zone don't bubble up and flash the page
  3318. // overlay behind it.
  3319. const { isDraggingOver, dragHandlers } = usePageFileDrop({
  3320. disabled: showUpload,
  3321. extensions: ['.3mf'],
  3322. onFiles: (files) => {
  3323. setUploadFiles(files);
  3324. setShowUpload(true);
  3325. },
  3326. onRejected: () => showToast(t('archives.page.only3mfSupported'), 'warning'),
  3327. });
  3328. // Keyboard shortcuts
  3329. const handleKeyDown = useCallback((e: KeyboardEvent) => {
  3330. const target = e.target as HTMLElement;
  3331. // Ignore if typing in an input/textarea
  3332. if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
  3333. if (e.key === 'Escape') {
  3334. target.blur();
  3335. }
  3336. return;
  3337. }
  3338. switch (e.key) {
  3339. case '/':
  3340. e.preventDefault();
  3341. searchInputRef.current?.focus();
  3342. break;
  3343. case 'u':
  3344. case 'U':
  3345. if (!e.metaKey && !e.ctrlKey) {
  3346. e.preventDefault();
  3347. setShowUpload(true);
  3348. }
  3349. break;
  3350. case 'Escape':
  3351. if (selectionMode) {
  3352. clearSelection();
  3353. }
  3354. break;
  3355. }
  3356. }, [selectionMode]);
  3357. useEffect(() => {
  3358. document.addEventListener('keydown', handleKeyDown);
  3359. return () => document.removeEventListener('keydown', handleKeyDown);
  3360. }, [handleKeyDown]);
  3361. return (
  3362. <div
  3363. className="p-4 md:p-8 relative"
  3364. {...dragHandlers}
  3365. >
  3366. {/* Drag & Drop Overlay */}
  3367. {isDraggingOver && (
  3368. <div className="fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none">
  3369. <div className="border-4 border-dashed border-bambu-green rounded-xl p-12 text-center">
  3370. <Upload className="w-16 h-16 mx-auto mb-4 text-bambu-green" />
  3371. <p className="text-2xl font-semibold text-white mb-2">{t('archives.page.dropFilesHere')}</p>
  3372. <p className="text-bambu-gray">{t('archives.releaseToUpload')}</p>
  3373. </div>
  3374. </div>
  3375. )}
  3376. {/* Selection Toolbar */}
  3377. {selectionMode && (
  3378. <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">
  3379. <Button variant="secondary" size="sm" onClick={clearSelection}>
  3380. <X className="w-4 h-4" />
  3381. Close
  3382. </Button>
  3383. <div className="w-px h-6 bg-bambu-dark-tertiary" />
  3384. <span className="text-white font-medium">
  3385. {selectedIds.size} selected
  3386. </span>
  3387. <div className="w-px h-6 bg-bambu-dark-tertiary" />
  3388. <Button variant="secondary" size="sm" onClick={selectAll}>
  3389. Select All
  3390. </Button>
  3391. <div className="w-px h-6 bg-bambu-dark-tertiary" />
  3392. <Button
  3393. variant="secondary"
  3394. size="sm"
  3395. onClick={() => setShowBatchTag(true)}
  3396. disabled={!hasAnyPermission('archives:update_own', 'archives:update_all')}
  3397. title={!hasAnyPermission('archives:update_own', 'archives:update_all') ? t('archives.permission.noUpdateArchives') : undefined}
  3398. >
  3399. <Tag className="w-4 h-4" />
  3400. Tags
  3401. </Button>
  3402. <Button
  3403. variant="secondary"
  3404. size="sm"
  3405. onClick={() => setShowBatchProject(true)}
  3406. disabled={!hasAnyPermission('archives:update_own', 'archives:update_all')}
  3407. title={!hasAnyPermission('archives:update_own', 'archives:update_all') ? t('archives.permission.noUpdateArchives') : undefined}
  3408. >
  3409. <FolderKanban className="w-4 h-4" />
  3410. Project
  3411. </Button>
  3412. <Button
  3413. variant="secondary"
  3414. size="sm"
  3415. disabled={!hasAnyPermission('archives:update_own', 'archives:update_all')}
  3416. title={!hasAnyPermission('archives:update_own', 'archives:update_all') ? t('archives.permission.noUpdateArchives') : undefined}
  3417. onClick={() => {
  3418. const ids = Array.from(selectedIds);
  3419. Promise.all(ids.map(id => api.toggleFavorite(id)))
  3420. .then(() => {
  3421. queryClient.invalidateQueries({ queryKey: ['archives'] });
  3422. showToast(`Toggled favorites for ${ids.length} archive${ids.length !== 1 ? 's' : ''}`);
  3423. })
  3424. .catch(() => {
  3425. showToast(t('archives.toast.failedUpdateFavorites'), 'error');
  3426. });
  3427. }}
  3428. >
  3429. <Star className="w-4 h-4" />
  3430. Favorite
  3431. </Button>
  3432. <Button
  3433. size="sm"
  3434. className="bg-red-500 hover:bg-red-600"
  3435. onClick={() => setShowBulkDeleteConfirm(true)}
  3436. disabled={!hasAnyPermission('archives:delete_own', 'archives:delete_all')}
  3437. title={!hasAnyPermission('archives:delete_own', 'archives:delete_all') ? t('archives.permission.noDelete') : undefined}
  3438. >
  3439. <Trash2 className="w-4 h-4" />
  3440. Delete
  3441. </Button>
  3442. </div>
  3443. )}
  3444. {no3MFWarning?.has_fallback && !no3MFWarningDismissed && (
  3445. <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">
  3446. <AlertCircle className="w-5 h-5 text-amber-600 dark:text-amber-400 flex-shrink-0 mt-0.5" />
  3447. <div className="flex-1 min-w-0">
  3448. <div className="text-sm font-medium text-amber-900 dark:text-amber-200">
  3449. {t('archives.no3mfBanner.title')}
  3450. </div>
  3451. <div className="text-xs text-amber-800/90 dark:text-amber-200/80 mt-1">
  3452. {t('archives.no3mfBanner.body')}{' '}
  3453. <a
  3454. href="https://wiki.bambuddy.cool/getting-started/#step-4-enable-store-sent-files-on-external-storage"
  3455. target="_blank"
  3456. rel="noreferrer"
  3457. className="underline hover:text-amber-900 dark:hover:text-amber-100 inline-flex items-center gap-1"
  3458. >
  3459. {t('archives.no3mfBanner.docsLink')}
  3460. <ExternalLink className="w-3 h-3" />
  3461. </a>
  3462. </div>
  3463. </div>
  3464. <button
  3465. onClick={dismissNo3MFWarning}
  3466. 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"
  3467. title={t('archives.no3mfBanner.dismissLabel')}
  3468. aria-label={t('archives.no3mfBanner.dismissLabel')}
  3469. >
  3470. <X className="w-4 h-4" />
  3471. </button>
  3472. </div>
  3473. )}
  3474. <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8">
  3475. <div>
  3476. <div className="flex items-start gap-3">
  3477. <div>
  3478. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  3479. <ArchiveIcon className="w-7 h-7 text-bambu-green" />
  3480. Archives
  3481. </h1>
  3482. <p className="text-bambu-gray mt-1">
  3483. {filteredArchives?.length || 0} of {archives?.length || 0} prints
  3484. </p>
  3485. </div>
  3486. <select
  3487. 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"
  3488. value={collection}
  3489. onChange={(e) => setCollection(e.target.value as Collection)}
  3490. >
  3491. {collections.map((c) => (
  3492. <option key={c.id} value={c.id}>
  3493. {c.label}
  3494. </option>
  3495. ))}
  3496. </select>
  3497. </div>
  3498. </div>
  3499. <div className="flex items-center gap-2 sm:gap-3 flex-wrap">
  3500. {/* Export dropdown */}
  3501. <div className="relative">
  3502. <Button
  3503. variant="secondary"
  3504. onClick={() => setShowExportMenu(!showExportMenu)}
  3505. disabled={isExporting}
  3506. >
  3507. {isExporting ? (
  3508. <Loader2 className="w-4 h-4 animate-spin" />
  3509. ) : (
  3510. <FileSpreadsheet className="w-4 h-4" />
  3511. )}
  3512. Export
  3513. </Button>
  3514. {showExportMenu && (
  3515. <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">
  3516. <button
  3517. 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"
  3518. onClick={async () => {
  3519. setShowExportMenu(false);
  3520. setIsExporting(true);
  3521. try {
  3522. const { blob, filename } = await api.exportArchives({
  3523. format: 'csv',
  3524. printerId: filterPrinter || undefined,
  3525. status: collection === 'failed' ? 'failed' : undefined,
  3526. search: search || undefined,
  3527. });
  3528. const url = URL.createObjectURL(blob);
  3529. const a = document.createElement('a');
  3530. a.href = url;
  3531. a.download = filename;
  3532. a.click();
  3533. URL.revokeObjectURL(url);
  3534. showToast(t('archives.toast.exportDownloaded'));
  3535. } catch {
  3536. showToast(t('archives.toast.exportFailed'), 'error');
  3537. } finally {
  3538. setIsExporting(false);
  3539. }
  3540. }}
  3541. >
  3542. <FileText className="w-4 h-4" />
  3543. Export as CSV
  3544. </button>
  3545. <button
  3546. 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"
  3547. onClick={async () => {
  3548. setShowExportMenu(false);
  3549. setIsExporting(true);
  3550. try {
  3551. const { blob, filename } = await api.exportArchives({
  3552. format: 'xlsx',
  3553. printerId: filterPrinter || undefined,
  3554. status: collection === 'failed' ? 'failed' : undefined,
  3555. search: search || undefined,
  3556. });
  3557. const url = URL.createObjectURL(blob);
  3558. const a = document.createElement('a');
  3559. a.href = url;
  3560. a.download = filename;
  3561. a.click();
  3562. URL.revokeObjectURL(url);
  3563. showToast(t('archives.toast.exportDownloaded'));
  3564. } catch {
  3565. showToast(t('archives.toast.exportFailed'), 'error');
  3566. } finally {
  3567. setIsExporting(false);
  3568. }
  3569. }}
  3570. >
  3571. <FileSpreadsheet className="w-4 h-4" />
  3572. Export as Excel
  3573. </button>
  3574. </div>
  3575. )}
  3576. </div>
  3577. {/* Compare button (only when 2-5 items selected) */}
  3578. {selectedIds.size >= 2 && selectedIds.size <= 5 && (
  3579. <Button
  3580. variant="secondary"
  3581. onClick={() => setShowCompareModal(true)}
  3582. >
  3583. <GitCompare className="w-4 h-4" />
  3584. Compare ({selectedIds.size})
  3585. </Button>
  3586. )}
  3587. {!selectionMode && (
  3588. <Button variant="secondary" onClick={() => setIsSelectionMode(true)}>
  3589. <CheckSquare className="w-4 h-4" />
  3590. Select
  3591. </Button>
  3592. )}
  3593. <Button
  3594. onClick={() => setShowUpload(true)}
  3595. disabled={!hasPermission('archives:create')}
  3596. title={!hasPermission('archives:create') ? t('archives.permission.noCreate') : undefined}
  3597. >
  3598. <Upload className="w-4 h-4" />
  3599. Upload 3MF
  3600. </Button>
  3601. {hasPermission('archives:purge') && (
  3602. <Button
  3603. variant="secondary"
  3604. onClick={() => setShowPurgeModal(true)}
  3605. title={t('archivePurge.headerTooltip')}
  3606. >
  3607. <Trash2 className="w-4 h-4 mr-2" />
  3608. {t('archivePurge.headerButton')}
  3609. </Button>
  3610. )}
  3611. </div>
  3612. </div>
  3613. {/* View mode toggle — always visible */}
  3614. <div className="flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden flex-shrink-0 w-fit mb-4">
  3615. <button
  3616. className={`p-2 ${viewMode === 'grid' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  3617. onClick={() => setViewMode('grid')}
  3618. title={t('archives.gridView')}
  3619. >
  3620. <LayoutGrid className="w-4 h-4" />
  3621. </button>
  3622. <button
  3623. className={`p-2 ${viewMode === 'list' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  3624. onClick={() => setViewMode('list')}
  3625. title={t('archives.listView')}
  3626. >
  3627. <List className="w-4 h-4" />
  3628. </button>
  3629. <button
  3630. className={`p-2 ${viewMode === 'calendar' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  3631. onClick={() => setViewMode('calendar')}
  3632. title={t('archives.calendarView')}
  3633. >
  3634. <CalendarDays className="w-4 h-4" />
  3635. </button>
  3636. <button
  3637. className={`p-2 ${viewMode === 'log' ? 'bg-bambu-green text-white' : 'bg-bambu-dark text-bambu-gray hover:text-white'}`}
  3638. onClick={() => setViewMode('log')}
  3639. title={t('archives.logView')}
  3640. >
  3641. <ClipboardList className="w-4 h-4" />
  3642. </button>
  3643. </div>
  3644. {/* Filters (hidden in log view which has its own filters) */}
  3645. {viewMode !== 'log' && <Card className="mb-6">
  3646. <CardContent className="py-4">
  3647. <div className="flex flex-col md:flex-row gap-3 md:gap-4 md:items-center md:flex-wrap">
  3648. {/* Search - full width on mobile */}
  3649. <div className="w-full md:flex-1 relative md:min-w-[200px]">
  3650. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  3651. <input
  3652. ref={searchInputRef}
  3653. type="text"
  3654. placeholder={t('archives.searchPlaceholder')}
  3655. 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"
  3656. value={search}
  3657. onChange={(e) => setSearch(e.target.value)}
  3658. />
  3659. </div>
  3660. {/* Filters - horizontal scroll on mobile */}
  3661. <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">
  3662. <div className="flex items-center gap-2 flex-shrink-0">
  3663. <Filter className="w-4 h-4 text-bambu-gray hidden md:block" />
  3664. <select
  3665. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3666. value={filterPrinter || ''}
  3667. onChange={(e) =>
  3668. setFilterPrinter(e.target.value ? Number(e.target.value) : null)
  3669. }
  3670. >
  3671. <option value="">All Printers</option>
  3672. {printers?.map((p) => (
  3673. <option key={p.id} value={p.id}>
  3674. {p.name}
  3675. </option>
  3676. ))}
  3677. </select>
  3678. </div>
  3679. <div className="flex items-center gap-2 flex-shrink-0">
  3680. <Package className="w-4 h-4 text-bambu-gray hidden md:block" />
  3681. <select
  3682. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3683. value={filterMaterial || ''}
  3684. onChange={(e) =>
  3685. setFilterMaterial(e.target.value || null)
  3686. }
  3687. >
  3688. <option value="">All Materials</option>
  3689. {uniqueMaterials.map((m) => (
  3690. <option key={m} value={m}>
  3691. {m}
  3692. </option>
  3693. ))}
  3694. </select>
  3695. </div>
  3696. <div className="flex items-center gap-2 flex-shrink-0">
  3697. <FileCode className="w-4 h-4 text-bambu-gray hidden md:block" />
  3698. <select
  3699. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3700. value={filterFileType}
  3701. onChange={(e) => setFilterFileType(e.target.value as 'all' | 'gcode' | 'source')}
  3702. >
  3703. <option value="all">All Files</option>
  3704. <option value="gcode">Sliced (GCODE)</option>
  3705. <option value="source">Source Only</option>
  3706. </select>
  3707. </div>
  3708. <button
  3709. onClick={() => setFilterFavorites(!filterFavorites)}
  3710. className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${
  3711. filterFavorites
  3712. ? 'bg-yellow-100 dark:bg-yellow-500/20 border-yellow-500 text-yellow-700 dark:text-yellow-400'
  3713. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  3714. }`}
  3715. title={filterFavorites ? t('archives.showAll') : t('archives.showFavoritesOnly')}
  3716. >
  3717. <Star className={`w-4 h-4 ${filterFavorites ? 'fill-yellow-400' : ''}`} />
  3718. <span className="text-sm hidden md:inline">Favorites</span>
  3719. </button>
  3720. <button
  3721. onClick={() => setHideFailed(!hideFailed)}
  3722. className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${
  3723. hideFailed
  3724. ? 'bg-red-100 dark:bg-red-500/20 border-red-500 text-red-700 dark:text-red-400'
  3725. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  3726. }`}
  3727. title={hideFailed ? t('archives.showFailedPrints') : t('archives.hideFailedPrints')}
  3728. >
  3729. <AlertCircle className={`w-4 h-4 ${hideFailed ? '' : ''}`} />
  3730. <span className="text-sm hidden md:inline">Hide Failed</span>
  3731. </button>
  3732. <button
  3733. onClick={() => setHideDuplicates(!hideDuplicates)}
  3734. className={`flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors flex-shrink-0 ${
  3735. hideDuplicates
  3736. ? 'bg-purple-100 dark:bg-purple-500/20 border-purple-500 text-purple-700 dark:text-purple-400'
  3737. : 'bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  3738. }`}
  3739. title={t('archives.hideDuplicates')}
  3740. >
  3741. <Copy className="w-4 h-4" />
  3742. <span className="text-sm hidden md:inline">{t('archives.hideDuplicates')}</span>
  3743. </button>
  3744. {uniqueTags.length > 0 && (
  3745. <div className="flex items-center gap-2 flex-shrink-0">
  3746. <Tag className="w-4 h-4 text-bambu-gray hidden md:block" />
  3747. <select
  3748. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3749. value={filterTag || ''}
  3750. onChange={(e) => setFilterTag(e.target.value || null)}
  3751. >
  3752. <option value="">All Tags</option>
  3753. {uniqueTags.map((t) => (
  3754. <option key={t} value={t}>
  3755. {t}
  3756. </option>
  3757. ))}
  3758. </select>
  3759. <button
  3760. onClick={() => setShowTagManagement(true)}
  3761. 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"
  3762. title={t('archives.manageTags')}
  3763. >
  3764. <Settings className="w-4 h-4" />
  3765. </button>
  3766. </div>
  3767. )}
  3768. <div className="flex items-center gap-2 flex-shrink-0">
  3769. <ArrowUpDown className="w-4 h-4 text-bambu-gray hidden md:block" />
  3770. <select
  3771. className="px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  3772. value={sortBy}
  3773. onChange={(e) => setSortBy(e.target.value as SortOption)}
  3774. >
  3775. <option value="date-desc">{t('archives.sortNewest')}</option>
  3776. <option value="date-asc">{t('archives.sortOldest')}</option>
  3777. <option value="name-asc">{t('archives.sortName')} A-Z</option>
  3778. <option value="name-desc">{t('archives.sortName')} Z-A</option>
  3779. <option value="size-desc">{t('archives.sortLargest')}</option>
  3780. <option value="size-asc">{t('archives.sortSmallest')}</option>
  3781. </select>
  3782. </div>
  3783. </div>
  3784. {hasTopFilters && (
  3785. <Button
  3786. variant="ghost"
  3787. size="sm"
  3788. onClick={clearTopFilters}
  3789. className="text-bambu-gray hover:text-white"
  3790. >
  3791. <X className="w-4 h-4" />
  3792. Reset
  3793. </Button>
  3794. )}
  3795. </div>
  3796. {/* Color Filter */}
  3797. {uniqueColors.length > 0 && (
  3798. <div className="flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary">
  3799. <span className="text-xs text-bambu-gray">Colors:</span>
  3800. {filterColors.size > 1 && (
  3801. <button
  3802. onClick={() => setColorFilterMode(m => m === 'or' ? 'and' : 'or')}
  3803. className={`px-2 py-0.5 text-xs rounded transition-colors ${
  3804. colorFilterMode === 'and'
  3805. ? 'bg-bambu-green text-white'
  3806. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white'
  3807. }`}
  3808. title={colorFilterMode === 'or' ? 'Match ANY selected color' : 'Match ALL selected colors'}
  3809. >
  3810. {colorFilterMode.toUpperCase()}
  3811. </button>
  3812. )}
  3813. <div className="flex items-center gap-1.5 flex-wrap">
  3814. {uniqueColors.map((color) => (
  3815. <button
  3816. key={color}
  3817. onClick={() => toggleColor(color)}
  3818. className={`w-6 h-6 rounded-full border-2 transition-all ${
  3819. filterColors.has(color)
  3820. ? 'border-bambu-green scale-110'
  3821. : 'border-white/20 hover:border-white/40'
  3822. }`}
  3823. style={{ backgroundColor: color }}
  3824. title={color}
  3825. />
  3826. ))}
  3827. </div>
  3828. {filterColors.size > 0 && (
  3829. <button
  3830. onClick={clearColorFilter}
  3831. className="text-xs text-bambu-gray hover:text-white flex items-center gap-1"
  3832. >
  3833. <X className="w-3 h-3" />
  3834. Clear
  3835. </button>
  3836. )}
  3837. </div>
  3838. )}
  3839. </CardContent>
  3840. </Card>}
  3841. {/* Pending Uploads Panel (visible when in queue mode with pending files) */}
  3842. <PendingUploadsPanel />
  3843. {/* Archives */}
  3844. {isLoading ? (
  3845. <div className="text-center py-12 text-bambu-gray">{t('archives.loadingArchives')}</div>
  3846. ) : filteredArchives?.length === 0 && viewMode !== 'log' ? (
  3847. // The log view is exempt: `print_log_entries` is an independent table
  3848. // that outlives the archives it refers to (deleting an archive only
  3849. // NULLs the FK), so "no archives" says nothing about whether there is
  3850. // a log to show. Without the guard, purging archives made the whole
  3851. // Print Log unreachable — the view has its own empty state below.
  3852. <Card>
  3853. <CardContent className="text-center py-12">
  3854. <p className="text-bambu-gray">
  3855. {search ? t('archives.noArchivesSearch') : t('archives.noArchivesYet')}
  3856. </p>
  3857. <p className="text-sm text-bambu-gray mt-2">
  3858. Archives are created automatically when prints complete
  3859. </p>
  3860. </CardContent>
  3861. </Card>
  3862. ) : viewMode === 'calendar' ? (
  3863. <Card className="p-6">
  3864. <CalendarView
  3865. archives={filteredArchives || []}
  3866. onArchiveClick={(archive) => {
  3867. // Switch to grid view and highlight the archive
  3868. setSearch(''); // Clear search to show all archives
  3869. setViewMode('grid');
  3870. setHighlightedArchiveId(archive.id);
  3871. }}
  3872. highlightedArchiveId={highlightedArchiveId}
  3873. />
  3874. </Card>
  3875. ) : viewMode === 'grid' ? (
  3876. <>
  3877. <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
  3878. {paginatedArchives?.map((archive) => (
  3879. <ArchiveCard
  3880. key={archive.id}
  3881. archive={archive}
  3882. printerName={archive.printer_id ? printerMap.get(archive.printer_id) || 'Unknown' : (archive.sliced_for_model || 'No Printer')}
  3883. printerMap={printerMap}
  3884. isSelected={selectedIds.has(archive.id)}
  3885. onSelect={toggleSelect}
  3886. selectionMode={selectionMode}
  3887. projects={projects}
  3888. isHighlighted={archive.id === highlightedArchiveId}
  3889. timeFormat={timeFormat}
  3890. preferredSlicer={preferredSlicer}
  3891. useSlicerApi={useSlicerApi}
  3892. currency={currency}
  3893. t={t}
  3894. onNavigateToArchive={handleNavigateToArchive}
  3895. />
  3896. ))}
  3897. </div>
  3898. <ArchivePaginationBar
  3899. pageIndex={pageIndex}
  3900. pageSize={pageSize}
  3901. totalRows={totalFiltered}
  3902. totalPages={totalPages}
  3903. onPageChange={setPageIndex}
  3904. onPageSizeChange={(size) => { setPageSize(size); setPageIndex(0); }}
  3905. t={t}
  3906. />
  3907. </>
  3908. ) : viewMode === 'list' ? (
  3909. <>
  3910. <Card>
  3911. <div className="divide-y divide-bambu-dark-tertiary">
  3912. {/* List Header */}
  3913. <div className="grid grid-cols-12 gap-4 px-4 py-3 text-xs text-bambu-gray font-medium">
  3914. <div className="col-span-1"></div>
  3915. <div className="col-span-4">Name</div>
  3916. <div className="col-span-2">Printer</div>
  3917. <div className="col-span-2">Date</div>
  3918. <div className="col-span-1">Size</div>
  3919. <div className="col-span-2 text-right">Actions</div>
  3920. </div>
  3921. {/* List Items */}
  3922. {paginatedArchives?.map((archive) => (
  3923. <ArchiveListRow
  3924. key={archive.id}
  3925. archive={archive}
  3926. printerName={archive.printer_id ? printerMap.get(archive.printer_id) || 'Unknown' : (archive.sliced_for_model || 'No Printer')}
  3927. isSelected={selectedIds.has(archive.id)}
  3928. onSelect={toggleSelect}
  3929. selectionMode={selectionMode}
  3930. projects={projects}
  3931. isHighlighted={archive.id === highlightedArchiveId}
  3932. preferredSlicer={preferredSlicer}
  3933. useSlicerApi={useSlicerApi}
  3934. t={t}
  3935. onNavigateToArchive={handleNavigateToArchive}
  3936. />
  3937. ))}
  3938. </div>
  3939. </Card>
  3940. <ArchivePaginationBar
  3941. pageIndex={pageIndex}
  3942. pageSize={pageSize}
  3943. totalRows={totalFiltered}
  3944. totalPages={totalPages}
  3945. onPageChange={setPageIndex}
  3946. onPageSizeChange={(size) => { setPageSize(size); setPageIndex(0); }}
  3947. t={t}
  3948. />
  3949. </>
  3950. ) : viewMode === 'log' ? (
  3951. <div className="space-y-4">
  3952. {/* Log filters */}
  3953. <Card>
  3954. <CardContent className="py-3">
  3955. <div className="flex flex-col md:flex-row gap-3 md:items-center md:flex-wrap">
  3956. {/* Search */}
  3957. <div className="flex-1 relative md:min-w-[200px]">
  3958. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  3959. <input
  3960. type="text"
  3961. placeholder={t('archives.searchPlaceholder')}
  3962. 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"
  3963. value={search}
  3964. onChange={(e) => { setSearch(e.target.value); setLogOffset(0); }}
  3965. />
  3966. </div>
  3967. {/* Printer filter */}
  3968. <select
  3969. 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"
  3970. value={filterPrinter || ''}
  3971. onChange={(e) => { setFilterPrinter(e.target.value ? Number(e.target.value) : null); setLogOffset(0); }}
  3972. >
  3973. <option value="">{t('archives.log.allPrinters')}</option>
  3974. {printers?.map((p) => (
  3975. <option key={p.id} value={p.id}>{p.name}</option>
  3976. ))}
  3977. </select>
  3978. {/* User filter */}
  3979. <select
  3980. 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"
  3981. value={logFilterUser || ''}
  3982. onChange={(e) => { setLogFilterUser(e.target.value || null); setLogOffset(0); }}
  3983. >
  3984. <option value="">{t('archives.log.allUsers')}</option>
  3985. {users?.map((u) => (
  3986. <option key={u.id} value={u.username}>{u.username}</option>
  3987. ))}
  3988. </select>
  3989. {/* Status filter */}
  3990. <select
  3991. 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"
  3992. value={logFilterStatus || ''}
  3993. onChange={(e) => { setLogFilterStatus(e.target.value || null); setLogOffset(0); }}
  3994. >
  3995. <option value="">{t('archives.log.allStatuses')}</option>
  3996. <option value="completed">{t('archives.status.completed')}</option>
  3997. <option value="failed">{t('archives.status.failed')}</option>
  3998. <option value="stopped">{t('archives.status.stopped')}</option>
  3999. <option value="cancelled">{t('archives.log.cancelled')}</option>
  4000. <option value="skipped">{t('archives.log.skipped')}</option>
  4001. </select>
  4002. {/* Date range */}
  4003. <div className="flex items-center gap-2">
  4004. <label className="text-sm text-bambu-gray">{t('archives.log.dateFrom')}</label>
  4005. <input
  4006. type="date"
  4007. 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"
  4008. value={logFilterDateFrom}
  4009. onChange={(e) => { setLogFilterDateFrom(e.target.value); setLogOffset(0); }}
  4010. />
  4011. </div>
  4012. <div className="flex items-center gap-2">
  4013. <label className="text-sm text-bambu-gray">{t('archives.log.dateTo')}</label>
  4014. <input
  4015. type="date"
  4016. 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"
  4017. value={logFilterDateTo}
  4018. onChange={(e) => { setLogFilterDateTo(e.target.value); setLogOffset(0); }}
  4019. />
  4020. </div>
  4021. {/* Columns + clear log */}
  4022. <div className="ml-auto flex items-center gap-2">
  4023. {/* #2636: the log carries more per-run data than fits on one
  4024. screen, so which columns show is the user's choice. */}
  4025. <button
  4026. type="button"
  4027. onClick={() => setShowLogColumnModal(true)}
  4028. 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"
  4029. title={t('inventory.configureColumns')}
  4030. >
  4031. <Columns className="w-4 h-4" />
  4032. <span className="hidden sm:inline">{t('archives.log.columns')}</span>
  4033. </button>
  4034. <Button
  4035. variant="danger"
  4036. size="sm"
  4037. onClick={() => setShowClearLogConfirm(true)}
  4038. disabled={!hasPermission('archives:delete_all') || clearLogMutation.isPending}
  4039. >
  4040. <Trash2 className="w-4 h-4" />
  4041. {t('archives.log.clearLog')}
  4042. </Button>
  4043. </div>
  4044. </div>
  4045. </CardContent>
  4046. </Card>
  4047. {/* Log table */}
  4048. <Card>
  4049. {isLogLoading ? (
  4050. <div className="flex items-center justify-center py-12">
  4051. <Loader2 className="w-6 h-6 animate-spin text-bambu-green" />
  4052. </div>
  4053. ) : !printLogData?.items.length ? (
  4054. <div className="text-center py-12 text-bambu-gray">
  4055. {t('archives.log.noEntries')}
  4056. </div>
  4057. ) : (
  4058. <>
  4059. <div className="overflow-x-auto">
  4060. <table className="w-full text-sm">
  4061. <thead>
  4062. <tr className="border-b border-bambu-dark-tertiary text-bambu-gray text-left">
  4063. {visibleLogColumns.map((colId) => {
  4064. const sortable = SORTABLE_LOG_COLUMNS.has(colId);
  4065. const isActive = logSort.column === colId;
  4066. const label = t(LOG_COLUMN_LABEL_KEYS[colId] ?? colId);
  4067. return (
  4068. <th
  4069. key={colId}
  4070. scope="col"
  4071. aria-sort={
  4072. isActive ? (logSort.direction === 'asc' ? 'ascending' : 'descending') : 'none'
  4073. }
  4074. className={`px-4 py-3 font-medium ${LOG_NUMERIC_COLUMNS.has(colId) ? 'text-right' : ''}`}
  4075. >
  4076. {sortable ? (
  4077. <button
  4078. type="button"
  4079. onClick={() => handleLogSort(colId)}
  4080. className={`inline-flex items-center gap-1 font-medium transition-colors hover:text-bambu-green ${
  4081. isActive ? 'text-bambu-green' : ''
  4082. }`}
  4083. title={t('archives.log.sortBy', { column: label })}
  4084. >
  4085. {label}
  4086. {isActive ? (
  4087. logSort.direction === 'asc' ? (
  4088. <ChevronUp className="w-3.5 h-3.5" />
  4089. ) : (
  4090. <ChevronDown className="w-3.5 h-3.5" />
  4091. )
  4092. ) : (
  4093. // Held at low opacity rather than omitted, so
  4094. // the header doesn't shift sideways when it
  4095. // becomes the active sort.
  4096. <ArrowUpDown className="w-3.5 h-3.5 opacity-30" />
  4097. )}
  4098. </button>
  4099. ) : (
  4100. label
  4101. )}
  4102. </th>
  4103. );
  4104. })}
  4105. <th className="px-4 py-3 font-medium w-10" aria-label={t('common.actions')} />
  4106. </tr>
  4107. </thead>
  4108. <tbody className="divide-y divide-bambu-dark-tertiary">
  4109. {printLogData.items.map((entry) => (
  4110. <tr key={entry.id} className="hover:bg-bambu-dark-secondary/50">
  4111. {visibleLogColumns.map((colId) => (
  4112. <td
  4113. key={colId}
  4114. className={`px-4 py-3 ${LOG_NUMERIC_COLUMNS.has(colId) ? 'text-right' : ''}`}
  4115. >
  4116. {renderLogCell(colId, entry)}
  4117. </td>
  4118. ))}
  4119. <td className="px-4 py-3 text-right">
  4120. <div className="inline-flex items-center gap-2">
  4121. <button
  4122. type="button"
  4123. onClick={() => {
  4124. setEditingLogEntry(entry);
  4125. setEditingLogFailureReason(entry.failure_reason || '');
  4126. setEditingLogStatus(entry.status);
  4127. }}
  4128. disabled={
  4129. updateLogEntryMutation.isPending ||
  4130. !(hasPermission('archives:update_all') || hasPermission('archives:update_own'))
  4131. }
  4132. title={
  4133. hasPermission('archives:update_all') || hasPermission('archives:update_own')
  4134. ? t('archives.log.editEntryTitle')
  4135. : t('archives.permission.noEdit')
  4136. }
  4137. className="text-bambu-gray hover:text-bambu-blue disabled:opacity-40 disabled:hover:text-bambu-gray transition-colors"
  4138. >
  4139. <Pencil className="w-4 h-4" />
  4140. </button>
  4141. <button
  4142. type="button"
  4143. onClick={() => setPendingDeleteEntryId(entry.id)}
  4144. disabled={
  4145. deleteLogEntryMutation.isPending ||
  4146. !(hasPermission('archives:delete_all') || hasPermission('archives:delete_own'))
  4147. }
  4148. title={
  4149. hasPermission('archives:delete_all') || hasPermission('archives:delete_own')
  4150. ? t('archives.log.deleteEntryTitle')
  4151. : t('archives.permission.noDelete')
  4152. }
  4153. className="text-bambu-gray hover:text-red-600 dark:hover:text-red-400 disabled:opacity-40 disabled:hover:text-bambu-gray transition-colors"
  4154. >
  4155. <Trash2 className="w-4 h-4" />
  4156. </button>
  4157. </div>
  4158. </td>
  4159. </tr>
  4160. ))}
  4161. </tbody>
  4162. </table>
  4163. </div>
  4164. {/* Pagination */}
  4165. <div className="flex items-center justify-between px-4 py-3 border-t border-bambu-dark-tertiary flex-wrap gap-2">
  4166. <div className="flex items-center gap-3">
  4167. <span className="text-sm text-bambu-gray">
  4168. {t('archives.log.showing', { count: Math.min(logOffset + logPageSize, printLogData.total), total: printLogData.total })}
  4169. </span>
  4170. <div className="flex items-center gap-1.5">
  4171. <label className="text-xs text-bambu-gray">{t('archives.log.rowsPerPage')}</label>
  4172. <select
  4173. 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"
  4174. value={logPageSize}
  4175. onChange={(e) => { setLogPageSize(Number(e.target.value)); setLogOffset(0); }}
  4176. >
  4177. <option value={10}>10</option>
  4178. <option value={25}>25</option>
  4179. <option value={50}>50</option>
  4180. <option value={100}>100</option>
  4181. </select>
  4182. </div>
  4183. </div>
  4184. <div className="flex items-center gap-2">
  4185. <span className="text-sm text-bambu-gray">
  4186. {t('archives.log.page')} {Math.floor(logOffset / logPageSize) + 1} / {Math.max(1, Math.ceil(printLogData.total / logPageSize))}
  4187. </span>
  4188. <Button variant="secondary" size="sm" onClick={() => setLogOffset(Math.max(0, logOffset - logPageSize))} disabled={logOffset === 0}>
  4189. <ChevronLeft className="w-4 h-4" />
  4190. </Button>
  4191. <Button variant="secondary" size="sm" onClick={() => setLogOffset(logOffset + logPageSize)} disabled={logOffset + logPageSize >= printLogData.total}>
  4192. <ChevronRight className="w-4 h-4" />
  4193. </Button>
  4194. </div>
  4195. </div>
  4196. </>
  4197. )}
  4198. </Card>
  4199. </div>
  4200. ) : null}
  4201. {/* Upload Modal */}
  4202. {showUpload && (
  4203. <UploadModal
  4204. onClose={() => {
  4205. setShowUpload(false);
  4206. setUploadFiles([]);
  4207. }}
  4208. initialFiles={uploadFiles}
  4209. />
  4210. )}
  4211. {/* Archive bulk-purge modal (#1008 follow-up) */}
  4212. {showPurgeModal && (
  4213. <PurgeArchivesModal onClose={() => setShowPurgeModal(false)} />
  4214. )}
  4215. {/* Bulk Delete Confirmation */}
  4216. {showBulkDeleteConfirm && (
  4217. <ConfirmModal
  4218. title={t('archives.modal.deleteArchives')}
  4219. message={t('archives.modal.deleteArchivesConfirm', { count: selectedIds.size })}
  4220. confirmText={t('archives.modal.deleteCount', { count: selectedIds.size })}
  4221. variant="danger"
  4222. onConfirm={() => {
  4223. bulkDeleteMutation.mutate(Array.from(selectedIds));
  4224. setShowBulkDeleteConfirm(false);
  4225. }}
  4226. onCancel={() => setShowBulkDeleteConfirm(false)}
  4227. />
  4228. )}
  4229. {/* Batch Tag Modal */}
  4230. {showBatchTag && (
  4231. <BatchTagModal
  4232. selectedIds={Array.from(selectedIds)}
  4233. existingTags={uniqueTags}
  4234. onClose={() => setShowBatchTag(false)}
  4235. />
  4236. )}
  4237. {/* Batch Project Modal */}
  4238. {showBatchProject && (
  4239. <BatchProjectModal
  4240. selectedIds={Array.from(selectedIds)}
  4241. onClose={() => setShowBatchProject(false)}
  4242. />
  4243. )}
  4244. {/* Compare Archives Modal */}
  4245. {showCompareModal && selectedIds.size >= 2 && selectedIds.size <= 5 && (
  4246. <CompareArchivesModal
  4247. archiveIds={Array.from(selectedIds)}
  4248. onClose={() => {
  4249. setShowCompareModal(false);
  4250. setSelectedIds(new Set());
  4251. setIsSelectionMode(false);
  4252. }}
  4253. />
  4254. )}
  4255. {/* Tag Management Modal */}
  4256. {showTagManagement && (
  4257. <TagManagementModal onClose={() => setShowTagManagement(false)} />
  4258. )}
  4259. {/* Print Log column picker (#2636) */}
  4260. <ColumnConfigModal
  4261. isOpen={showLogColumnModal}
  4262. onClose={() => setShowLogColumnModal(false)}
  4263. columns={logColumnConfig}
  4264. defaultColumns={defaultLogColumnConfig}
  4265. onSave={handleLogColumnSave}
  4266. />
  4267. {/* Clear Log Confirmation */}
  4268. {showClearLogConfirm && (
  4269. <ConfirmModal
  4270. title={t('archives.log.clearLogTitle')}
  4271. message={t('archives.log.clearLogConfirm')}
  4272. confirmText={t('archives.log.clearLogButton')}
  4273. variant="danger"
  4274. onConfirm={() => {
  4275. clearLogMutation.mutate();
  4276. setShowClearLogConfirm(false);
  4277. }}
  4278. onCancel={() => setShowClearLogConfirm(false)}
  4279. />
  4280. )}
  4281. {/* Per-row Print Log entry delete confirmation (#1687) */}
  4282. {pendingDeleteEntryId !== null && (
  4283. <ConfirmModal
  4284. title={t('archives.log.deleteEntryTitle')}
  4285. message={t('archives.log.deleteEntryConfirm')}
  4286. confirmText={t('common.delete')}
  4287. variant="danger"
  4288. onConfirm={() => {
  4289. deleteLogEntryMutation.mutate(pendingDeleteEntryId);
  4290. setPendingDeleteEntryId(null);
  4291. }}
  4292. onCancel={() => setPendingDeleteEntryId(null)}
  4293. />
  4294. )}
  4295. {/* Per-row Print Log classification editor (#1687 part 4).
  4296. Reuses editArchive.failureReasons.* and archives.log.statuses.*
  4297. vocabularies so the dropdown stays in lockstep with the
  4298. Archive Edit modal — backend validates against the same list. */}
  4299. {editingLogEntry !== null && (
  4300. <div
  4301. className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
  4302. onClick={() => setEditingLogEntry(null)}
  4303. >
  4304. <div
  4305. className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg w-full max-w-md mx-4 p-6"
  4306. onClick={(e) => e.stopPropagation()}
  4307. >
  4308. <h3 className="text-lg font-semibold text-white mb-4">
  4309. {t('archives.log.editEntryTitle')}
  4310. </h3>
  4311. <p className="text-xs text-bambu-gray mb-4">
  4312. {t('archives.log.editEntryDescription')}
  4313. </p>
  4314. <div className="space-y-4">
  4315. <div>
  4316. <label className="block text-sm text-bambu-gray mb-1">
  4317. {t('editArchive.status')}
  4318. </label>
  4319. <select
  4320. value={editingLogStatus}
  4321. onChange={(e) => setEditingLogStatus(e.target.value)}
  4322. 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"
  4323. >
  4324. <option value="completed">{t('archives.log.statuses.completed', { defaultValue: 'completed' })}</option>
  4325. <option value="failed">{t('archives.log.statuses.failed', { defaultValue: 'failed' })}</option>
  4326. <option value="stopped">{t('archives.log.statuses.stopped', { defaultValue: 'stopped' })}</option>
  4327. <option value="cancelled">{t('archives.log.statuses.cancelled', { defaultValue: 'cancelled' })}</option>
  4328. <option value="skipped">{t('archives.log.statuses.skipped', { defaultValue: 'skipped' })}</option>
  4329. </select>
  4330. </div>
  4331. <div>
  4332. <label className="block text-sm text-bambu-gray mb-1">
  4333. {t('editArchive.failureReason')}
  4334. </label>
  4335. <select
  4336. value={editingLogFailureReason}
  4337. onChange={(e) => setEditingLogFailureReason(e.target.value)}
  4338. 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"
  4339. >
  4340. <option value="">{t('editArchive.selectReason')}</option>
  4341. {FAILURE_REASON_KEYS.map((key) => (
  4342. <option key={key} value={key}>
  4343. {t(`editArchive.failureReasons.${key}`)}
  4344. </option>
  4345. ))}
  4346. </select>
  4347. </div>
  4348. </div>
  4349. <div className="flex justify-end gap-2 mt-6">
  4350. <Button
  4351. variant="secondary"
  4352. onClick={() => setEditingLogEntry(null)}
  4353. >
  4354. {t('common.cancel')}
  4355. </Button>
  4356. <Button
  4357. variant="primary"
  4358. onClick={() => {
  4359. const body: { failure_reason?: string | null; status?: string } = {};
  4360. // Send failure_reason only if it changed — empty string
  4361. // clears the classification (backend stores it as NULL).
  4362. if (editingLogFailureReason !== (editingLogEntry.failure_reason || '')) {
  4363. body.failure_reason = editingLogFailureReason || null;
  4364. }
  4365. if (editingLogStatus !== editingLogEntry.status) {
  4366. body.status = editingLogStatus;
  4367. }
  4368. if (Object.keys(body).length === 0) {
  4369. setEditingLogEntry(null);
  4370. return;
  4371. }
  4372. updateLogEntryMutation.mutate({ id: editingLogEntry.id, body });
  4373. }}
  4374. disabled={updateLogEntryMutation.isPending}
  4375. >
  4376. {updateLogEntryMutation.isPending ? t('editArchive.saving') : t('common.save')}
  4377. </Button>
  4378. </div>
  4379. </div>
  4380. </div>
  4381. )}
  4382. </div>
  4383. );
  4384. }
  4385. /* Pagination bar for archives grid/list views */
  4386. function ArchivePaginationBar({
  4387. pageIndex, pageSize, totalRows, totalPages, onPageChange, onPageSizeChange, t,
  4388. }: {
  4389. pageIndex: number;
  4390. pageSize: number;
  4391. totalRows: number;
  4392. totalPages: number;
  4393. onPageChange: (page: number) => void;
  4394. onPageSizeChange: (size: number) => void;
  4395. t: (key: string) => string;
  4396. }) {
  4397. const isShowAll = pageSize === -1;
  4398. if (totalPages <= 1 && !isShowAll) return null;
  4399. const effectiveSize = isShowAll ? totalRows || 1 : pageSize;
  4400. return (
  4401. <div className="flex items-center justify-between pt-2 text-sm">
  4402. <span className="text-bambu-gray">
  4403. {isShowAll
  4404. ? `${totalRows} ${t('archives.prints')}`
  4405. : <>{t('archives.pagination.showing')} {pageIndex * effectiveSize + 1} {t('archives.pagination.to')}{' '}
  4406. {Math.min((pageIndex + 1) * effectiveSize, totalRows)}{' '}
  4407. {t('archives.pagination.of')} {totalRows} {t('archives.prints')}</>
  4408. }
  4409. </span>
  4410. <div className="flex items-center gap-2">
  4411. <span className="text-bambu-gray">{t('archives.pagination.show')}</span>
  4412. <select
  4413. value={pageSize}
  4414. onChange={(e) => onPageSizeChange(Number(e.target.value))}
  4415. 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"
  4416. >
  4417. {[25, 50, 100, 200].map((n) => (
  4418. <option key={n} value={n}>{n}</option>
  4419. ))}
  4420. <option value={-1}>{t('archives.pagination.all')}</option>
  4421. </select>
  4422. {!isShowAll && (
  4423. <>
  4424. <button
  4425. onClick={() => onPageChange(0)}
  4426. disabled={pageIndex === 0}
  4427. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  4428. >
  4429. <ChevronsLeft className="w-4 h-4" />
  4430. </button>
  4431. <button
  4432. onClick={() => onPageChange(Math.max(0, pageIndex - 1))}
  4433. disabled={pageIndex === 0}
  4434. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  4435. >
  4436. <ChevronLeft className="w-4 h-4" />
  4437. </button>
  4438. <span className="text-bambu-gray px-2 whitespace-nowrap">
  4439. {t('archives.pagination.page')} {pageIndex + 1} {t('archives.pagination.of')} {totalPages}
  4440. </span>
  4441. <button
  4442. onClick={() => onPageChange(Math.min(totalPages - 1, pageIndex + 1))}
  4443. disabled={pageIndex >= totalPages - 1}
  4444. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  4445. >
  4446. <ChevronRight className="w-4 h-4" />
  4447. </button>
  4448. <button
  4449. onClick={() => onPageChange(totalPages - 1)}
  4450. disabled={pageIndex >= totalPages - 1}
  4451. className="p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
  4452. >
  4453. <ChevronsRight className="w-4 h-4" />
  4454. </button>
  4455. </>
  4456. )}
  4457. </div>
  4458. </div>
  4459. );
  4460. }